@lemonriver/core 0.2.0 → 0.3.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 (120) hide show
  1. package/dist/{build-Df_xwIpg.js → build-Bqo69DWP.js} +1 -1
  2. package/dist/cli/bin.js +4 -4
  3. package/dist/{config-BjWCLoMQ.js → config-DJ5rkMMg.js} +1594 -974
  4. package/dist/{config-rMGCkz6i.d.ts → config-teo3kWz7.d.ts} +1 -1
  5. package/dist/{dev-Ctsx9IeO.js → dev-B2FJD5bJ.js} +2 -2
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.js +1 -1
  8. package/dist/locale/index.d.ts +1 -1
  9. package/dist/locale/index.js +1 -1
  10. package/dist/{preview-CJgcqsPk.js → preview-C93BOZL1.js} +1 -1
  11. package/dist/{types-8VUyA2bu.d.ts → types-DFK02XVv.d.ts} +0 -35
  12. package/dist/{update-BKOA3Z6o.js → update-DsxZBtwv.js} +2 -70
  13. package/dist/vite/index.d.ts +1 -1
  14. package/dist/vite/index.js +1 -1
  15. package/dist/{zh-tw-CeLrYwRE.js → zh-tw-DwTAZKa6.js} +6 -172
  16. package/package.json +1 -1
  17. package/src/app/app.tsx +5 -18
  18. package/src/app/components/agent/agent-panel.tsx +3 -0
  19. package/src/app/components/agent/agent-presence.tsx +2 -2
  20. package/src/app/components/agent/history-view.tsx +3 -2
  21. package/src/app/components/agent/transcript.tsx +15 -4
  22. package/src/app/components/asset-view.tsx +6 -6
  23. package/src/app/components/command/command-menu.tsx +2 -1
  24. package/src/app/components/inspector/asset-picker-dialog.tsx +7 -5
  25. package/src/app/components/inspector/comment-layer.tsx +2 -1
  26. package/src/app/components/inspector/inspector-panel.tsx +2 -2
  27. package/src/app/components/sidebar/sidebar-footer.tsx +1 -1
  28. package/src/app/components/sidebar/sidebar.tsx +3 -2
  29. package/src/app/components/themes/theme-detail.tsx +4 -2
  30. package/src/app/components/thumbnail-rail.tsx +1 -28
  31. package/src/app/index.html +2 -2
  32. package/src/app/lemonriver/agent/lemon.tsx +64 -0
  33. package/src/app/{components → lemonriver}/board/board-canvas.tsx +17 -17
  34. package/src/app/{routes/board.tsx → lemonriver/board/board-page.tsx} +16 -15
  35. package/src/app/{components → lemonriver}/board/layout.ts +1 -1
  36. package/src/app/lemonriver/board/model/cards.test.ts +239 -0
  37. package/src/app/lemonriver/board/model/cards.ts +234 -0
  38. package/src/app/lemonriver/board/model/structure.test.ts +101 -0
  39. package/src/app/lemonriver/board/model/structure.ts +82 -0
  40. package/src/app/{components → lemonriver}/board/page-node.tsx +34 -31
  41. package/src/app/{components → lemonriver}/board/use-board-cards.ts +6 -6
  42. package/src/app/{components → lemonriver}/board/use-board-columns.ts +7 -7
  43. package/src/app/{components → lemonriver}/board/use-page-order.ts +10 -6
  44. package/src/app/lemonriver/brand/app-icon.svg +44 -0
  45. package/src/app/lemonriver/brand/apple-touch-icon.png +0 -0
  46. package/src/app/lemonriver/brand/favicon-32.png +0 -0
  47. package/src/app/lemonriver/brand/mascot.tsx +59 -0
  48. package/src/app/lemonriver/brand/mascots/lemon-done.png +0 -0
  49. package/src/app/lemonriver/brand/mascots/lemon-idle.png +0 -0
  50. package/src/app/lemonriver/brand/mascots/lemon-needs-you.png +0 -0
  51. package/src/app/lemonriver/brand/mascots/lemon-thinking.png +0 -0
  52. package/src/app/lemonriver/brand/mascots/lemon-working.png +0 -0
  53. package/src/app/lemonriver/chrome/app-chrome.tsx +99 -0
  54. package/src/app/lemonriver/chrome/nav-row.tsx +34 -0
  55. package/src/app/lemonriver/chrome/not-found.tsx +34 -0
  56. package/src/app/lemonriver/chrome/sidebar-extras.tsx +57 -0
  57. package/src/app/lemonriver/chrome/use-slot.ts +23 -0
  58. package/src/app/lemonriver/features.test.ts +29 -0
  59. package/src/app/lemonriver/features.ts +26 -0
  60. package/src/app/lemonriver/feedback/export.ts +7 -0
  61. package/src/app/lemonriver/feedback/lemon-empty.tsx +54 -0
  62. package/src/app/lemonriver/feedback/offline-banner.tsx +41 -0
  63. package/src/app/lemonriver/feedback/pending-toast.test.ts +44 -0
  64. package/src/app/lemonriver/feedback/pending-toast.ts +39 -0
  65. package/src/app/lemonriver/feedback/toaster.tsx +34 -0
  66. package/src/app/lemonriver/feedback/upload.test.ts +26 -0
  67. package/src/app/lemonriver/feedback/upload.ts +19 -0
  68. package/src/app/lemonriver/home/brief-card.tsx +63 -0
  69. package/src/app/lemonriver/home/brief.test.ts +38 -0
  70. package/src/app/lemonriver/home/brief.ts +34 -0
  71. package/src/app/lemonriver/home/controls.tsx +93 -0
  72. package/src/app/lemonriver/home/deck-card.tsx +183 -0
  73. package/src/app/lemonriver/home/dialogs.tsx +292 -0
  74. package/src/app/lemonriver/home/home-page.tsx +335 -0
  75. package/src/app/lemonriver/home/sorting.test.ts +24 -0
  76. package/src/app/lemonriver/home/sorting.ts +59 -0
  77. package/src/app/lemonriver/home/time.test.ts +33 -0
  78. package/src/app/lemonriver/home/time.ts +33 -0
  79. package/src/app/lemonriver/home/use-deck-times.ts +27 -0
  80. package/src/app/lemonriver/home/use-delayed.ts +15 -0
  81. package/src/app/lemonriver/routes.test.tsx +37 -0
  82. package/src/app/lemonriver/routes.tsx +38 -0
  83. package/src/app/lemonriver/settings/settings-page.tsx +103 -0
  84. package/src/app/lemonriver/slide-extensions.tsx +73 -0
  85. package/src/app/lemonriver/text/all.ts +19 -0
  86. package/src/app/lemonriver/text/en.ts +106 -0
  87. package/src/app/lemonriver/text/es.ts +108 -0
  88. package/src/app/lemonriver/text/index.ts +9 -0
  89. package/src/app/lemonriver/text/ja.ts +106 -0
  90. package/src/app/lemonriver/text/text.test.ts +57 -0
  91. package/src/app/lemonriver/text/types.ts +111 -0
  92. package/src/app/lemonriver/text/zh-cn.ts +101 -0
  93. package/src/app/lemonriver/text/zh-tw.ts +101 -0
  94. package/src/app/lemonriver/theme/app.css +288 -0
  95. package/src/app/lemonriver/theme/controls.css +463 -0
  96. package/src/app/lemonriver/theme/index.css +3 -0
  97. package/src/app/lemonriver/theme/motion.ts +52 -0
  98. package/src/app/lemonriver/theme/pages.test.ts +66 -0
  99. package/src/app/lemonriver/theme/pages.ts +56 -0
  100. package/src/app/lemonriver/theme/theme-menu.tsx +64 -0
  101. package/src/app/lemonriver/theme/themes.test.ts +18 -0
  102. package/src/app/lemonriver/theme/themes.ts +16 -0
  103. package/src/app/lemonriver/theme/tokens.css +226 -0
  104. package/src/app/lemonriver/theme/use-theme.tsx +49 -0
  105. package/src/app/lemonriver/trash/api.test.ts +19 -0
  106. package/src/app/lemonriver/trash/api.ts +77 -0
  107. package/src/app/lemonriver/trash/trash-page.tsx +131 -0
  108. package/src/app/lib/pptx/raster.ts +1 -1
  109. package/src/app/main.tsx +8 -1
  110. package/src/app/routes/home-shell.tsx +4 -2
  111. package/src/app/routes/slide.tsx +12 -16
  112. package/src/app/styles.css +1 -0
  113. package/src/locale/en.ts +0 -35
  114. package/src/locale/es.ts +0 -34
  115. package/src/locale/ja.ts +0 -34
  116. package/src/locale/types.ts +0 -36
  117. package/src/locale/zh-cn.ts +3 -37
  118. package/src/locale/zh-tw.ts +3 -37
  119. /package/src/app/{components → lemonriver}/board/board.css +0 -0
  120. /package/src/app/{components → lemonriver}/board/layout.test.ts +0 -0
@@ -1,5 +1,5 @@
1
1
  import { n as defaultDesign } from "./design-Cpqx7SJs.js";
2
- import { A as renameSlideDir, B as validateMutationRequest, C as duplicatePageInDefaultExportInSource, D as readMetaTitleInSource, E as insertNotesElementInSource, F as slugifyTitle, H as CONFIG_FILES, I as updateMetaTitleInSource, L as validateSlideName, M as reorderNotesArrayInSource, N as resolveSlideEntry, O as removeNotesElementInSource, P as rmSlideDir, R as declaredFrameworkSpecifier, S as duplicateNotesElementInSource, T as insertBlankPageInDefaultExportInSource, W as isFrameworkSpecifier, _ as writeManifest, a as json, b as SLIDE_ID_RE, c as readSlideSource, d as foldersManifestPath, f as newFolderId, g as validateReorder, h as validateName, i as BodyTooLargeError, j as reorderDefaultExportPagesInSource, k as removePageFromDefaultExportInSource, l as resolveSlideEntryPath, m as validateIcon, n as registerUpdateRoutes, o as makeContext, p as readManifest, r as runCommand, s as readBody, t as detectPackageManager, u as FOLDER_ID_RE, v as shortId, w as duplicateSlideDir, x as createBlankSlideDir, z as isLoopbackRequest } from "./update-BKOA3Z6o.js";
2
+ import { A as reorderNotesArrayInSource, B as CONFIG_FILES, C as duplicatePageInDefaultExportInSource, D as removePageFromDefaultExportInSource, E as removeNotesElementInSource, F as validateSlideName, H as isFrameworkSpecifier, I as declaredFrameworkSpecifier, L as isLoopbackRequest, M as rmSlideDir, N as slugifyTitle, O as renameSlideDir, P as updateMetaTitleInSource, R as validateMutationRequest, S as duplicateNotesElementInSource, T as readMetaTitleInSource, _ as writeManifest, a as json, b as SLIDE_ID_RE, c as readSlideSource, d as foldersManifestPath, f as newFolderId, g as validateReorder, h as validateName, i as BodyTooLargeError, j as resolveSlideEntry, k as reorderDefaultExportPagesInSource, l as resolveSlideEntryPath, m as validateIcon, n as registerUpdateRoutes, o as makeContext, p as readManifest, r as runCommand, s as readBody, t as detectPackageManager, u as FOLDER_ID_RE, v as shortId, w as duplicateSlideDir, x as createBlankSlideDir } from "./update-DsxZBtwv.js";
3
3
  import { createRequire } from "node:module";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -10,392 +10,1527 @@ import { parse } from "@babel/parser";
10
10
  import { randomBytes, randomUUID } from "node:crypto";
11
11
  import tailwindcss from "@tailwindcss/vite";
12
12
  import react from "@vitejs/plugin-react";
13
- import os from "node:os";
14
13
  import fg from "fast-glob";
15
14
  import { loadConfigFromFile, normalizePath } from "vite";
15
+ import os from "node:os";
16
16
  import * as t from "@babel/types";
17
17
  import { isJSXElement, isJSXFragment } from "@babel/types";
18
- //#region src/editing/placeholder-id.ts
19
- const UNTITLED_SLIDE_ID_RE = /^untitled(-\d+)?$/;
18
+ //#region src/app/lemonriver/theme/pages.ts
19
+ /**
20
+ * BRAND_PAGES as a path pattern, for the pre-paint script, which runs before
21
+ * any module loads. pages.test.ts keeps the two in step.
22
+ */
23
+ const BRAND_PATH_SOURCE = "^/(themes(/.*)?|assets|settings|trash)?/*$";
24
+ /** Agent screenshots and thumbnails render through this route; nothing may cover it. */
25
+ const PREVIEW_PATH_SOURCE = "^/s/[^/]+/preview/*$";
26
+ const REDUCE_MOTION_KEY = "lemonriver:reduce-motion";
27
+ const SPLASH_ID = "lr-splash";
20
28
  //#endregion
21
- //#region src/agent/provider.ts
22
- var ProviderUnavailableError = class extends Error {
23
- constructor(provider) {
24
- super(`${provider.name} is not connected: install ${provider.sdkPackage} in this workspace to use it from the agent panel.`);
25
- this.name = "ProviderUnavailableError";
26
- }
27
- };
28
- const DETAIL_MAX = 400;
29
- function clipDetail(value) {
30
- if (value === void 0 || value === null) return null;
31
- const text = typeof value === "string" ? value : safeJson(value);
32
- if (!text) return null;
33
- const oneLine = text.replace(/\s+/g, " ").trim();
34
- return oneLine.length > DETAIL_MAX ? `${oneLine.slice(0, 399)}…` : oneLine;
35
- }
36
- function safeJson(value) {
37
- try {
38
- return JSON.stringify(value);
39
- } catch {
40
- return String(value);
41
- }
29
+ //#region src/lemonriver/vite-plugin.ts
30
+ /**
31
+ * Runs before the bundle: marks <html> for our styles, picks the lime look on
32
+ * the pages that wear it, and shows the splash until the app mounts. The
33
+ * preview route renders agent screenshots, so it gets no splash. The official
34
+ * script above it has already toggled `dark`.
35
+ */
36
+ function prePaintScript(base) {
37
+ return [
38
+ "(function(){",
39
+ "var d=document.documentElement;d.setAttribute('data-lr-app','');",
40
+ `var b=${JSON.stringify(base.replace(/\/+$/, ""))},p=location.pathname;if(b&&p.indexOf(b)===0)p=p.slice(b.length)||'/';`,
41
+ `var brand=new RegExp(${JSON.stringify(BRAND_PATH_SOURCE)}).test(p);`,
42
+ `var preview=new RegExp(${JSON.stringify(PREVIEW_PATH_SOURCE)}).test(p);`,
43
+ "var theme=null;try{theme=localStorage.getItem('theme');",
44
+ `if(localStorage.getItem(${JSON.stringify(REDUCE_MOTION_KEY)})==='1')d.setAttribute('data-lr-reduce-motion','');}catch(e){}`,
45
+ "if(theme==='lime'){d.classList.remove('dark');d.classList.add('lime');d.style.colorScheme='light';}",
46
+ "if(brand)d.setAttribute('data-lr-brand','');",
47
+ "if(!preview)d.setAttribute('data-lr-splash','');",
48
+ "})();"
49
+ ].join("");
50
+ }
51
+ const SPLASH_STYLE = `
52
+ #${SPLASH_ID}{display:none}
53
+ html[data-lr-splash] #${SPLASH_ID}{position:fixed;inset:0;z-index:2147483000;display:grid;place-items:center;pointer-events:none;
54
+ background:linear-gradient(160deg,#eef56a 0%,#c9e23f 40%,#9bc929 100%);color:#12300f;
55
+ font:700 28px/1.2 -apple-system,BlinkMacSystemFont,"SF Pro Display","Inter","PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;
56
+ opacity:0;animation:lr-splash-in 240ms cubic-bezier(.2,.8,.2,1) 200ms forwards;transition:opacity 240ms cubic-bezier(.2,.8,.2,1)}
57
+ #${SPLASH_ID} div{display:flex;align-items:center;gap:14px}
58
+ #${SPLASH_ID} img{width:56px;height:56px}
59
+ #${SPLASH_ID}[data-leaving]{opacity:0!important;animation:none}
60
+ @keyframes lr-splash-in{to{opacity:1}}
61
+ @media (prefers-reduced-motion: reduce){html[data-lr-splash] #${SPLASH_ID}{animation:none;opacity:1;transition:none}}
62
+ html[data-lr-reduce-motion] #${SPLASH_ID}{animation:none;opacity:1;transition:none}
63
+ `;
64
+ function lemonRiverAppPlugin() {
65
+ let base = "/";
66
+ return {
67
+ name: "lemonriver:app",
68
+ configResolved(config) {
69
+ base = config.base;
70
+ },
71
+ transformIndexHtml: {
72
+ order: "pre",
73
+ handler(html) {
74
+ return {
75
+ html,
76
+ tags: [
77
+ {
78
+ tag: "link",
79
+ attrs: {
80
+ rel: "apple-touch-icon",
81
+ href: "./lemonriver/brand/apple-touch-icon.png"
82
+ },
83
+ injectTo: "head"
84
+ },
85
+ {
86
+ tag: "style",
87
+ children: SPLASH_STYLE,
88
+ injectTo: "head"
89
+ },
90
+ {
91
+ tag: "script",
92
+ children: prePaintScript(base),
93
+ injectTo: "head"
94
+ },
95
+ {
96
+ tag: "div",
97
+ attrs: {
98
+ id: SPLASH_ID,
99
+ "aria-hidden": "true"
100
+ },
101
+ children: [{
102
+ tag: "div",
103
+ children: [{
104
+ tag: "img",
105
+ attrs: {
106
+ src: "./lemonriver/brand/app-icon.svg",
107
+ alt: ""
108
+ }
109
+ }, {
110
+ tag: "span",
111
+ children: "LemonRiver"
112
+ }]
113
+ }],
114
+ injectTo: "body-prepend"
115
+ }
116
+ ]
117
+ };
118
+ }
119
+ }
120
+ };
42
121
  }
43
- function isInsideRoots(cwd, file, roots) {
44
- if (typeof file !== "string" || !file) return false;
45
- const resolved = path.resolve(cwd, file);
46
- return roots.some((root) => {
47
- const rel = path.relative(root, resolved);
48
- return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
49
- });
122
+ //#endregion
123
+ //#region src/app/lemonriver/board/model/cards.ts
124
+ const CARD_STATUSES = [
125
+ "todo",
126
+ "doing",
127
+ "review",
128
+ "done"
129
+ ];
130
+ const TITLE_MAX$1 = 80;
131
+ const MEMO_MAX = 2e3;
132
+ function isCardStatus(value) {
133
+ return typeof value === "string" && CARD_STATUSES.includes(value);
50
134
  }
51
- function relativeToCwd(cwd, file) {
52
- if (typeof file !== "string" || !file) return null;
53
- const normalizedCwd = cwd.replace(/[\\/]+$/, "");
54
- if (file.startsWith(normalizedCwd)) return file.slice(normalizedCwd.length).replace(/^[\\/]+/, "") || ".";
55
- return file;
135
+ function cleanCard(raw) {
136
+ if (!raw || typeof raw !== "object") return null;
137
+ const { title, status, memo } = raw;
138
+ const card = {};
139
+ if (typeof title === "string" && title.trim()) card.title = title.trim().slice(0, TITLE_MAX$1);
140
+ if (isCardStatus(status)) card.status = status;
141
+ if (typeof memo === "string" && memo.trim()) card.memo = memo.trim().slice(0, MEMO_MAX);
142
+ return Object.keys(card).length > 0 ? card : null;
56
143
  }
57
- function parseQuestions(input) {
58
- const raw = Array.isArray(input.questions) ? input.questions : [];
59
- const questions = [];
60
- for (const q of raw) {
61
- if (!q || typeof q !== "object") continue;
62
- const r = q;
63
- const options = Array.isArray(r.options) ? r.options.map((o) => {
64
- if (!o || typeof o !== "object") return null;
65
- const opt = o;
66
- if (typeof opt.label !== "string") return null;
67
- return {
68
- label: opt.label,
69
- description: typeof opt.description === "string" ? opt.description : void 0
70
- };
71
- }).filter((o) => o !== null) : [];
72
- if (typeof r.question !== "string") continue;
73
- questions.push({
74
- header: typeof r.header === "string" ? r.header : "",
75
- question: r.question,
76
- options,
77
- multiSelect: r.multiSelect === true
78
- });
144
+ function sanitizeCards(raw) {
145
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
146
+ const cards = {};
147
+ for (const [key, value] of Object.entries(raw)) {
148
+ const card = cleanCard(value);
149
+ if (key && card) cards[key] = card;
79
150
  }
80
- return questions;
151
+ return cards;
81
152
  }
82
- //#endregion
83
- //#region src/agent/prompt.ts
84
- const PAGE_BY_PAGE = "Write a new deck page by page so the user can follow along on the canvas: first replace the file with the imports, meta (keeping its existing createdAt), design and the cover page only, then add each remaining page with its own separate edit, keeping the file compiling after every write.";
85
- const DECK_SLUG = "This deck's folder still has a placeholder name. Never rename or move the folder yourself: once the deck has content, end your final reply with a slug for it on a line of its own as <deck-slug>short-kebab-case-english-slug</deck-slug>, and LemonRiver renames the folder from it.";
86
- function systemPromptAppend(askInstruction) {
87
- return [
88
- "You are running inside the LemonRiver dev server, driven from its in-app agent panel in the browser rather than a terminal.",
89
- "The workspace is a LemonRiver project: decks live under slides/<id>/index.tsx and the dev server hot-reloads every edit, so the user sees changes immediately.",
90
- "Use the project skills: create-slide to draft a new deck, apply-comments to resolve @slide-comment markers left by the inspector, create-theme for themes, and slide-authoring as the technical reference before writing a page.",
91
- PAGE_BY_PAGE,
92
- "Keep replies short and concrete: the panel is narrow. Prefer doing the work over describing it, and finish with a one-line summary of what changed.",
93
- askInstruction
94
- ].join(" ");
153
+ const sameLink = (link, a, b) => link.a === a && link.b === b || link.a === b && link.b === a;
154
+ function linkCards(links, a, b) {
155
+ if (!a || !b || a === b || links.some((link) => sameLink(link, a, b))) return links;
156
+ return [...links, {
157
+ a,
158
+ b
159
+ }];
95
160
  }
96
- function buildTurnPrompt(text, context) {
97
- const lines = contextLines(context);
98
- if (lines.length === 0) return text;
99
- return `${text}\n\n<open-slide-context>\n${lines.join("\n")}\n</open-slide-context>`;
161
+ function sanitizeLinks(raw) {
162
+ if (!Array.isArray(raw)) return [];
163
+ return raw.reduce((links, item) => {
164
+ const { a, b } = item ?? {};
165
+ return typeof a === "string" && typeof b === "string" ? linkCards(links, a, b) : links;
166
+ }, []);
100
167
  }
101
- const escapeTag = (s) => s.replace(/</g, "&lt;");
102
- function contextLines(context) {
103
- if (!context?.slideId) return [];
104
- const file = `slides/${context.slideId}/index.tsx`;
105
- const lines = [];
106
- if (context.newDeck) {
107
- lines.push(`${file} is a blank deck created for this request. Draft the deck the user describes into it with the create-slide skill: replace the placeholder page, keep the slide id, and do not create another folder.`, "Ask the create-slide scoping questions in a single round, only for what the request leaves unclear; skip any it already answers.", PAGE_BY_PAGE, DECK_SLUG);
108
- return lines;
168
+ //#endregion
169
+ //#region src/app/lemonriver/board/model/structure.ts
170
+ function sanitizeStructure(parsed) {
171
+ if (!parsed || typeof parsed !== "object") return null;
172
+ const columns = parsed.columns;
173
+ if (!Array.isArray(columns)) return null;
174
+ const cleaned = columns.flatMap((column) => {
175
+ if (!column || typeof column !== "object") return [];
176
+ const { title, size } = column;
177
+ if (typeof size !== "number" || !Number.isInteger(size) || size < 0) return [];
178
+ return [{
179
+ title: typeof title === "string" ? title : "",
180
+ size
181
+ }];
182
+ });
183
+ return cleaned.length > 0 ? { columns: cleaned } : null;
184
+ }
185
+ /**
186
+ * Keeps a stored structure usable after the deck changed behind the board's
187
+ * back: pages added outside the board join the last column, and pages deleted
188
+ * outside it come off the end.
189
+ */
190
+ function reconcileColumns(columns, pageCount) {
191
+ if (pageCount <= 0) return [];
192
+ const kept = columns.map((column) => ({ ...column }));
193
+ if (kept.length === 0) return [{
194
+ title: "",
195
+ size: pageCount
196
+ }];
197
+ let total = kept.reduce((sum, column) => sum + column.size, 0);
198
+ if (total === pageCount) return kept;
199
+ if (total < pageCount) {
200
+ kept[kept.length - 1].size += pageCount - total;
201
+ return kept;
109
202
  }
110
- lines.push(`The user is viewing slide "${context.slideId}": ${file}.`);
111
- if (UNTITLED_SLIDE_ID_RE.test(context.slideId)) lines.push(DECK_SLUG);
112
- if (context.slideTitle) lines.push(`<slide-title>${escapeTag(context.slideTitle)}</slide-title>`);
113
- if (context.pageNumber && context.totalPages) lines.push(`They are on page ${context.pageNumber} of ${context.totalPages} (0-based index ${context.pageNumber - 1} in the default export array).`);
114
- if (context.selection) {
115
- const { line, column, tagName, text } = context.selection;
116
- lines.push(`They have selected a <${escapeTag(tagName)}> element at ${file}:${line}:${column}.${text ? " Its text is in <selected-text>." : ""} "This element" refers to it.`);
117
- if (text) lines.push(`<selected-text>${escapeTag(text)}</selected-text>`);
203
+ for (let i = kept.length - 1; i >= 0 && total > pageCount; i--) {
204
+ const drop = Math.min(kept[i].size, total - pageCount);
205
+ kept[i].size -= drop;
206
+ total -= drop;
118
207
  }
119
- if (context.pendingComments) lines.push(`There are ${context.pendingComments} pending @slide-comment markers in this slide's source.`);
120
- return lines;
121
- }
122
- const DECK_SLUG_RE = /\s*<deck-slug>\s*([^<]*?)\s*<\/deck-slug>\s*/gi;
123
- function extractDeckSlug(text) {
124
- let slug = null;
125
- for (const match of text.matchAll(DECK_SLUG_RE)) slug = match[1] || slug;
126
- return slug;
127
- }
128
- function stripDeckSlug(text) {
129
- return text.replace(DECK_SLUG_RE, "\n").replace(/\s*<deck-slug>[^<]*$/i, "").trimEnd();
208
+ while (kept.length > 1 && kept[kept.length - 1].size === 0) kept.pop();
209
+ return kept;
130
210
  }
131
- const QUESTIONS_RE = /<open-slide-questions>([\s\S]*?)<\/open-slide-questions>/i;
132
- const TEXT_QUESTIONS_INSTRUCTION = "You cannot ask the user anything interactively here, and nothing you print in the middle of a turn can be answered. When you need answers before continuing, stop working and end your turn with a final message holding only an <open-slide-questions> block: a JSON array of at most 4 questions shaped like [{\"header\":\"Pages\",\"question\":\"How many pages?\",\"multiSelect\":false,\"options\":[{\"label\":\"6-10 (Recommended)\",\"description\":\"Standard length\"}]}], each with 2 to 4 options, written in the user's language. The panel shows them as a form and sends the answers back as your next message. Write nothing after the block and do not continue the task in the same turn.";
133
- function extractQuestionBlock(text) {
134
- const match = QUESTIONS_RE.exec(text);
135
- if (!match) return null;
136
- const body = match[1].trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
137
- let raw;
211
+ //#endregion
212
+ //#region src/lemonriver/board/page-entries.ts
213
+ /**
214
+ * The deck's page array as written, one entry per page, with whitespace
215
+ * collapsed so reformatting the file keeps every entry the same. `null` when
216
+ * the array cannot be read one entry per page: a spread stands for any number
217
+ * of pages, and a default export that is not an array literal hides them.
218
+ */
219
+ function defaultExportEntriesInSource(source) {
220
+ let body;
138
221
  try {
139
- raw = JSON.parse(body);
222
+ body = parse(source, {
223
+ sourceType: "module",
224
+ plugins: ["typescript", "jsx"],
225
+ errorRecovery: true
226
+ }).program.body;
140
227
  } catch {
141
228
  return null;
142
229
  }
143
- const questions = parseQuestions({ questions: Array.isArray(raw) ? raw : raw?.questions });
144
- if (questions.length === 0) return null;
145
- return {
146
- text: text.replace(QUESTIONS_RE, "").trim(),
147
- questions
148
- };
149
- }
150
- function answersPrompt(questions, answers) {
151
- if (!answers) return "I skipped your questions. Continue the task with your best judgement and sensible defaults.";
152
- return `My answers:\n${questions.map((q) => `- ${q.question} ${answers[q.question] || "(no answer)"}`).join("\n")}\n\nContinue the task with these answers.`;
153
- }
154
- function editedPrompt(original, text) {
155
- return `I went back and edited an earlier message of mine. Treat everything after it in this conversation, including your replies, as discarded, and respond to the edited version instead. Files keep whatever changes were already made.\n\n<original-message>\n${escapeTag(original)}\n</original-message>\n\n${text}`;
156
- }
157
- function rewoundPrompt(text) {
158
- return `${text}\n\n<open-slide-note>I went back and edited this message. Files keep the changes made after it in the discarded part of this conversation, so read the current files before editing them.</open-slide-note>`;
159
- }
160
- //#endregion
161
- //#region src/agent/detect.ts
162
- const IS_WINDOWS = process.platform === "win32";
163
- const VERSION_TIMEOUT_MS = 5e3;
164
- function findOnPath(command, env = process.env) {
165
- const dirs = (env.PATH ?? env.Path ?? "").split(path.delimiter).filter(Boolean);
166
- const exts = IS_WINDOWS ? (env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";") : [""];
167
- for (const dir of dirs) for (const ext of exts) {
168
- const candidate = path.join(dir, command + ext.toLowerCase());
169
- try {
170
- if (statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate;
171
- } catch {}
230
+ for (const node of body) {
231
+ if (node.type !== "ExportDefaultDeclaration") continue;
232
+ let inner = node.declaration;
233
+ while (inner.type === "TSAsExpression" || inner.type === "TSSatisfiesExpression") inner = inner.expression;
234
+ if (inner.type !== "ArrayExpression") return null;
235
+ const entries = [];
236
+ for (const element of inner.elements) {
237
+ if (!element || element.type === "SpreadElement") return null;
238
+ if (element.start == null || element.end == null) return null;
239
+ entries.push(source.slice(element.start, element.end).replace(/\s+/g, " "));
240
+ }
241
+ return entries;
172
242
  }
173
243
  return null;
174
244
  }
175
- function findSpawnableCli(command, env = process.env) {
176
- const found = findOnPath(command, env);
177
- if (!found || !IS_WINDOWS) return found;
178
- return found.toLowerCase().endsWith(".exe") ? found : null;
179
- }
180
- const versionCache = /* @__PURE__ */ new Map();
181
- function commandVersion(file) {
182
- let cached = versionCache.get(file);
183
- if (!cached) {
184
- cached = readVersion(file);
185
- versionCache.set(file, cached);
186
- }
187
- return cached;
188
- }
189
- function readVersion(file) {
190
- return new Promise((resolve) => {
191
- let out = "";
192
- let child;
193
- try {
194
- child = spawn(file, ["--version"], {
195
- stdio: [
196
- "ignore",
197
- "pipe",
198
- "pipe"
199
- ],
200
- shell: IS_WINDOWS,
201
- windowsHide: true
202
- });
203
- } catch {
204
- resolve(null);
205
- return;
206
- }
207
- const timer = setTimeout(() => {
208
- child.kill();
209
- resolve(null);
210
- }, VERSION_TIMEOUT_MS);
211
- child.stdout?.on("data", (c) => {
212
- out += c.toString("utf8");
213
- });
214
- child.stderr?.on("data", (c) => {
215
- out += c.toString("utf8");
216
- });
217
- child.on("error", () => {
218
- clearTimeout(timer);
219
- resolve(null);
220
- });
221
- child.on("close", () => {
222
- clearTimeout(timer);
223
- resolve(parseVersion(out));
245
+ //#endregion
246
+ //#region src/lemonriver/board/page-insert.ts
247
+ function findDefaultExportArray(source) {
248
+ let ast;
249
+ try {
250
+ ast = parse(source, {
251
+ sourceType: "module",
252
+ plugins: ["typescript", "jsx"],
253
+ errorRecovery: true
224
254
  });
225
- });
226
- }
227
- function parseVersion(output) {
228
- const m = /(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/.exec(output);
229
- return m ? m[1] : null;
230
- }
231
- function entryFromPackageJson(pkg) {
232
- const root = pickExport(pkg.exports);
233
- if (root) return root;
234
- return pkg.module ?? pkg.main ?? null;
235
- }
236
- function pickExport(exportsField) {
237
- if (!exportsField) return null;
238
- if (typeof exportsField === "string") return exportsField;
239
- if (typeof exportsField !== "object") return null;
240
- const record = exportsField;
241
- return pickCondition(Object.keys(record).some((k) => k.startsWith(".")) ? record["."] : exportsField);
242
- }
243
- function pickCondition(target) {
244
- if (!target) return null;
245
- if (typeof target === "string") return target;
246
- if (Array.isArray(target)) {
247
- for (const t of target) {
248
- const hit = pickCondition(t);
249
- if (hit) return hit;
250
- }
255
+ } catch {
251
256
  return null;
252
257
  }
253
- if (typeof target !== "object") return null;
254
- const record = target;
255
- for (const key of [
256
- "import",
257
- "node",
258
- "default",
259
- "require"
260
- ]) if (key in record) {
261
- const hit = pickCondition(record[key]);
262
- if (hit) return hit;
258
+ const body = ast.program?.body ?? [];
259
+ for (const node of body) {
260
+ if (node.type !== "ExportDefaultDeclaration") continue;
261
+ let inner = node.declaration;
262
+ while (inner && (inner.type === "TSAsExpression" || inner.type === "TSSatisfiesExpression")) inner = inner.expression;
263
+ if (inner?.type !== "ArrayExpression") return null;
264
+ const arrayStart = inner.start;
265
+ const arrayEnd = inner.end;
266
+ const rawElements = inner.elements ?? [];
267
+ const elements = [];
268
+ for (const el of rawElements) {
269
+ if (!el || typeof el.start !== "number" || typeof el.end !== "number") return null;
270
+ elements.push({
271
+ start: el.start,
272
+ end: el.end
273
+ });
274
+ }
275
+ return {
276
+ elements,
277
+ arrayStart,
278
+ arrayEnd,
279
+ statementStart: node.start
280
+ };
263
281
  }
264
282
  return null;
265
283
  }
266
- function resolveWorkspacePackage(userCwd, name) {
267
- let dir = path.resolve(userCwd);
268
- while (true) {
269
- const pkgJsonPath = path.join(dir, "node_modules", name, "package.json");
270
- if (existsSync(pkgJsonPath)) {
271
- let pkg;
272
- try {
273
- pkg = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
274
- } catch {
275
- return null;
284
+ function findNotesArray(source) {
285
+ let ast;
286
+ try {
287
+ ast = parse(source, {
288
+ sourceType: "module",
289
+ plugins: ["typescript", "jsx"],
290
+ errorRecovery: true
291
+ });
292
+ } catch {
293
+ return "invalid";
294
+ }
295
+ const body = ast.program?.body ?? [];
296
+ for (const stmt of body) {
297
+ if (stmt.type !== "ExportNamedDeclaration") continue;
298
+ const decl = stmt.declaration;
299
+ if (decl?.type !== "VariableDeclaration") continue;
300
+ const declarations = decl.declarations ?? [];
301
+ for (const d of declarations) {
302
+ const id = d.id;
303
+ if (id?.type !== "Identifier" || id.name !== "notes") continue;
304
+ const init = d.init;
305
+ if (init?.type !== "ArrayExpression") return "invalid";
306
+ const arrayStart = init.start;
307
+ const arrayEnd = init.end;
308
+ if (typeof arrayStart !== "number" || typeof arrayEnd !== "number") return "invalid";
309
+ const rawElements = init.elements ?? [];
310
+ const elementTexts = [];
311
+ for (const el of rawElements) {
312
+ if (el === null) {
313
+ elementTexts.push("undefined");
314
+ continue;
315
+ }
316
+ if (el.type === "SpreadElement") return "invalid";
317
+ const start = el.start;
318
+ const end = el.end;
319
+ if (typeof start !== "number" || typeof end !== "number") return "invalid";
320
+ elementTexts.push(source.slice(start, end));
276
321
  }
277
- const entry = entryFromPackageJson(pkg);
278
- if (!entry) return null;
279
- const pkgDir = path.dirname(pkgJsonPath);
280
322
  return {
281
- dir: pkgDir,
282
- version: pkg.version ?? "0.0.0",
283
- entry: path.resolve(pkgDir, entry)
323
+ arrayStart,
324
+ arrayEnd,
325
+ elementTexts
284
326
  };
285
327
  }
286
- const parent = path.dirname(dir);
287
- if (parent === dir) return null;
288
- dir = parent;
289
328
  }
329
+ return null;
290
330
  }
291
- async function importWorkspacePackage(userCwd, name) {
292
- const resolved = resolveWorkspacePackage(userCwd, name);
293
- if (!resolved) return null;
294
- return await import(pathToFileURL(resolved.entry).href);
331
+ function rebuildNotesArray(source, arrayStart, arrayEnd, elements) {
332
+ const trimmed = elements.slice();
333
+ while (trimmed.length > 0 && trimmed[trimmed.length - 1] === "undefined") trimmed.pop();
334
+ const replacement = trimmed.length === 0 ? "[]" : `[\n${trimmed.map((s) => ` ${s},`).join("\n")}\n]`;
335
+ if (replacement === source.slice(arrayStart, arrayEnd)) return source;
336
+ return source.slice(0, arrayStart) + replacement + source.slice(arrayEnd);
337
+ }
338
+ function chooseInsertSeparator(prefix, existingSeparators) {
339
+ const sample = existingSeparators.find((s) => s.includes(","));
340
+ if (sample) return sample;
341
+ if (prefix.includes("\n")) {
342
+ const m = prefix.match(/\n([ \t]*)$/);
343
+ return `,\n${m ? m[1] : " "}`;
344
+ }
345
+ return ", ";
295
346
  }
296
- //#endregion
297
- //#region src/agent/providers/claude.ts
298
- const CLAUDE_SDK_PACKAGE = "@anthropic-ai/claude-agent-sdk";
299
- const CLAUDE_EFFORTS = [
300
- "low",
301
- "medium",
302
- "high",
303
- "xhigh",
304
- "max"
305
- ];
306
- const CLAUDE_MODELS = [
307
- {
308
- id: "opus",
309
- label: "Opus",
310
- efforts: CLAUDE_EFFORTS
311
- },
312
- {
313
- id: "sonnet",
314
- label: "Sonnet",
315
- efforts: CLAUDE_EFFORTS
316
- },
317
- {
318
- id: "haiku",
319
- label: "Haiku",
320
- efforts: []
347
+ /** Separator slots for an array that gained an element at `index`. */
348
+ function separatorsAroundInsert(separators, index, count, insertSep) {
349
+ const out = [];
350
+ for (let i = 0; i < count - 1; i++) if (i === index) out.push(insertSep);
351
+ else if (i === index - 1) out.push(separators[index - 1] ?? insertSep);
352
+ else out.push(separators[i > index ? i - 1 : i] ?? insertSep);
353
+ return out;
354
+ }
355
+ /** Rebuild `[...]` with `text` sitting at `index`, reusing the author's separators. */
356
+ function insertIntoDefaultExportArray(source, found, index, text) {
357
+ const { elements, arrayStart, arrayEnd } = found;
358
+ const n = elements.length;
359
+ const prefix = source.slice(arrayStart, elements[0].start);
360
+ const suffix = source.slice(elements[n - 1].end, arrayEnd);
361
+ const separators = [];
362
+ for (let i = 0; i < n - 1; i++) separators.push(source.slice(elements[i].end, elements[i + 1].start));
363
+ const texts = elements.map((el) => source.slice(el.start, el.end));
364
+ texts.splice(index, 0, text);
365
+ const insertSep = chooseInsertSeparator(prefix, separators);
366
+ const seps = separatorsAroundInsert(separators, index, texts.length, insertSep);
367
+ let rebuilt = prefix + texts[0];
368
+ for (let i = 1; i < texts.length; i++) rebuilt += seps[i - 1] + texts[i];
369
+ rebuilt += suffix;
370
+ return source.slice(0, arrayStart) + rebuilt + source.slice(arrayEnd);
371
+ }
372
+ function chooseBlankPageName(source) {
373
+ const used = new Set(source.match(/[A-Za-z_$][\w$]*/g) ?? []);
374
+ for (let i = 1;; i++) {
375
+ const name = `NewPage${i}`;
376
+ if (!used.has(name)) return name;
321
377
  }
322
- ];
323
- const EDIT_TOOLS = /* @__PURE__ */ new Set([
324
- "Edit",
325
- "MultiEdit",
326
- "Write",
327
- "NotebookEdit"
328
- ]);
329
- function claudeEffort(effort) {
330
- return effort && effort !== "minimal" ? effort : void 0;
331
378
  }
332
- function describeClaudeTool(name, input, cwd) {
333
- const file = relativeToCwd(cwd, input.file_path ?? input.path ?? input.notebook_path);
334
- switch (name) {
335
- case "Read": return {
336
- title: "Read",
337
- detail: file
338
- };
339
- case "Edit":
340
- case "MultiEdit":
341
- case "Write":
342
- case "NotebookEdit": return {
343
- title: name === "Write" ? "Write" : "Edit",
344
- detail: file
345
- };
346
- case "Bash": return {
347
- title: "Run command",
348
- detail: clipDetail(input.command)
349
- };
350
- case "Glob":
351
- case "Grep": return {
352
- title: "Search",
353
- detail: clipDetail(input.pattern)
354
- };
355
- case "WebFetch": return {
356
- title: "Fetch",
357
- detail: clipDetail(input.url)
358
- };
359
- case "WebSearch": return {
360
- title: "Web search",
361
- detail: clipDetail(input.query)
362
- };
363
- case "Skill": return {
364
- title: "Skill",
365
- detail: clipDetail(input.skill ?? input.name)
366
- };
367
- case "Task": return {
368
- title: "Subagent",
369
- detail: clipDetail(input.description)
370
- };
371
- case "AskUserQuestion": return {
372
- title: "Question",
373
- detail: null
374
- };
375
- case "TodoWrite": return {
376
- title: "Plan",
377
- detail: null
378
- };
379
- default: return {
380
- title: name,
381
- detail: clipDetail(input)
382
- };
379
+ /**
380
+ * Insert a brand-new blank page at `index`, declaring its component above the
381
+ * default export and adding it to the array. Unlike duplication, nothing is
382
+ * copied: the page is an empty full-bleed surface for the author to build on.
383
+ *
384
+ * Returns `null` when the default export isn't an array literal or `index` is
385
+ * past the end of the deck.
386
+ */
387
+ function insertBlankPageInDefaultExportInSource(source, index) {
388
+ const found = findDefaultExportArray(source);
389
+ if (!found) return null;
390
+ const n = found.elements.length;
391
+ if (!Number.isInteger(index) || index < 0 || index > n) return null;
392
+ const name = chooseBlankPageName(source);
393
+ const withArray = insertIntoDefaultExportArray(source, found, index, name);
394
+ const before = withArray.slice(0, found.statementStart);
395
+ const gap = before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n";
396
+ return before + `const ${name} = () => (\n <div style={{ width: '100%', height: '100%', background: '#ffffff' }} />\n);\n` + gap + withArray.slice(found.statementStart);
397
+ }
398
+ /**
399
+ * Insert an empty note slot at `index` so `notes` stays aligned with the pages
400
+ * after a page is inserted. Trailing empty slots are dropped again by
401
+ * {@link rebuildNotesArray}, which is correct: an absent note is `undefined`.
402
+ */
403
+ function insertNotesElementInSource(source, index) {
404
+ if (!Number.isInteger(index) || index < 0) return null;
405
+ const found = findNotesArray(source);
406
+ if (found === "invalid") return null;
407
+ if (found === null) return source;
408
+ const { arrayStart, arrayEnd, elementTexts } = found;
409
+ if (index > elementTexts.length) return source;
410
+ const next = elementTexts.slice();
411
+ next.splice(index, 0, "undefined");
412
+ return rebuildNotesArray(source, arrayStart, arrayEnd, next);
413
+ }
414
+ //#endregion
415
+ //#region src/lemonriver/board/store.ts
416
+ function boardStructurePath(userCwd, slideId) {
417
+ return path.join(userCwd, ".open-slide", "board", `${slideId}.json`);
418
+ }
419
+ /** The whole board file. Columns, cards and links each own one field of it. */
420
+ async function readBoardFile(file) {
421
+ try {
422
+ const parsed = JSON.parse(await fs.readFile(file, "utf8"));
423
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
424
+ } catch {
425
+ return {};
383
426
  }
384
427
  }
385
- function createClaudeMapper(emit, cwd) {
386
- let counter = 0;
387
- const nextId = () => `t-${Date.now().toString(36)}-${(counter++).toString(36)}`;
388
- const textByIndex = /* @__PURE__ */ new Map();
389
- const openTextIds = [];
390
- let resultSeen = false;
391
- const handleBlocks = (blocks) => {
392
- for (const block of blocks) if (block.type === "text") {
393
- const { text } = block;
394
- const id = openTextIds.shift();
395
- if (id) emit({
396
- type: "text-end",
397
- id,
398
- text
428
+ async function readBoardStructure(file) {
429
+ return sanitizeStructure(await readBoardFile(file));
430
+ }
431
+ const pending = /* @__PURE__ */ new Map();
432
+ /**
433
+ * Rewrites the fields `fields` names and keeps every other one. Updates to the
434
+ * same file run one after another: the columns and the cards are saved by
435
+ * separate requests, and two read-modify-writes racing would drop one of them.
436
+ */
437
+ function updateBoardFile(file, fields) {
438
+ const run = (pending.get(file) ?? Promise.resolve()).catch(() => void 0).then(async () => {
439
+ const current = await readBoardFile(file);
440
+ await fs.mkdir(path.dirname(file), { recursive: true });
441
+ await fs.writeFile(file, `${JSON.stringify({
442
+ ...current,
443
+ ...fields
444
+ }, null, 2)}\n`, "utf8");
445
+ });
446
+ pending.set(file, run);
447
+ run.finally(() => {
448
+ if (pending.get(file) === run) pending.delete(file);
449
+ }).catch(() => void 0);
450
+ return run;
451
+ }
452
+ async function writeBoardStructure(file, structure) {
453
+ await updateBoardFile(file, { columns: structure.columns });
454
+ }
455
+ //#endregion
456
+ //#region src/lemonriver/board/routes.ts
457
+ function registerBoardRoutes(server, ctx) {
458
+ server.middlewares.use("/__board", async (req, res, next) => {
459
+ const url = new URL(req.url ?? "/", "http://local");
460
+ const method = req.method ?? "GET";
461
+ try {
462
+ if (method === "GET" && url.pathname === "/") {
463
+ const slideId = url.searchParams.get("slideId") ?? "";
464
+ if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
465
+ const stored = await readBoardStructure(boardStructurePath(ctx.userCwd, slideId));
466
+ if (!stored) return json(res, 200, { columns: null });
467
+ const pages = Number(url.searchParams.get("pages") ?? "0");
468
+ const columns = pages > 0 ? reconcileColumns(stored.columns, pages) : stored.columns;
469
+ return json(res, 200, { columns });
470
+ }
471
+ if (method === "PUT" && url.pathname === "/") {
472
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
473
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
474
+ const body = await readBody(req);
475
+ const slideId = body.slideId ?? "";
476
+ if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
477
+ if (!Array.isArray(body.columns)) return json(res, 400, { error: "missing columns" });
478
+ const structure = { columns: body.columns.flatMap((column) => {
479
+ const { title, size } = column ?? {};
480
+ if (typeof size !== "number" || !Number.isInteger(size) || size < 0) return [];
481
+ return [{
482
+ title: typeof title === "string" ? title : "",
483
+ size
484
+ }];
485
+ }) };
486
+ if (structure.columns.length === 0) return json(res, 400, { error: "no usable columns" });
487
+ await writeBoardStructure(boardStructurePath(ctx.userCwd, slideId), structure);
488
+ return json(res, 200, { ok: true });
489
+ }
490
+ if (method === "GET" && url.pathname === "/cards") {
491
+ const slideId = url.searchParams.get("slideId") ?? "";
492
+ if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
493
+ const stored = await readBoardFile(boardStructurePath(ctx.userCwd, slideId));
494
+ return json(res, 200, {
495
+ cards: sanitizeCards(stored.cards),
496
+ links: sanitizeLinks(stored.links)
497
+ });
498
+ }
499
+ if (method === "PUT" && url.pathname === "/cards") {
500
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
501
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
502
+ const body = await readBody(req);
503
+ const slideId = body.slideId ?? "";
504
+ if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
505
+ await updateBoardFile(boardStructurePath(ctx.userCwd, slideId), {
506
+ cards: sanitizeCards(body.cards),
507
+ links: sanitizeLinks(body.links)
508
+ });
509
+ return json(res, 200, { ok: true });
510
+ }
511
+ if (method === "POST" && url.pathname === "/pages/insert") {
512
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
513
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
514
+ const body = await readBody(req);
515
+ const slideId = typeof body?.slideId === "string" ? body.slideId : "";
516
+ const index = typeof body?.index === "number" ? body.index : NaN;
517
+ if (!Number.isInteger(index) || index < 0) return json(res, 400, { error: "invalid index" });
518
+ const entry = resolveSlideEntry(ctx.slidesRoot, slideId);
519
+ if (!entry) return json(res, 400, { error: "invalid slideId" });
520
+ let source;
521
+ try {
522
+ source = await fs.readFile(entry, "utf8");
523
+ } catch {
524
+ return json(res, 404, { error: "slide not found" });
525
+ }
526
+ const withPage = insertBlankPageInDefaultExportInSource(source, index);
527
+ if (withPage === null) return json(res, 422, { error: "could not insert a page — index out of range or default export is not an array" });
528
+ const withNotes = insertNotesElementInSource(withPage, index);
529
+ if (withNotes === null) return json(res, 422, { error: "could not insert a page — `notes` export has an unexpected shape" });
530
+ if (withNotes !== source) await fs.writeFile(entry, withNotes, "utf8");
531
+ return json(res, 200, {
532
+ ok: true,
533
+ slideId,
534
+ index
535
+ });
536
+ }
537
+ if (method === "GET" && url.pathname === "/entries") {
538
+ const slideId = url.searchParams.get("slideId") ?? "";
539
+ const entry = resolveSlideEntryPath(ctx, slideId);
540
+ if (!entry) return json(res, 400, { error: "invalid slideId" });
541
+ const source = await readSlideSource(entry);
542
+ return json(res, 200, { entries: source ? defaultExportEntriesInSource(source) : null });
543
+ }
544
+ next();
545
+ } catch (err) {
546
+ json(res, 500, { error: String(err.message ?? err) });
547
+ }
548
+ });
549
+ }
550
+ //#endregion
551
+ //#region src/lemonriver/decks/routes.ts
552
+ const ENTRY_NAMES$1 = [
553
+ "index.tsx",
554
+ "index.jsx",
555
+ "index.ts",
556
+ "index.js"
557
+ ];
558
+ async function readDeckTimes(slidesRoot) {
559
+ let names;
560
+ try {
561
+ names = await fs.readdir(slidesRoot);
562
+ } catch {
563
+ return {};
564
+ }
565
+ const decks = {};
566
+ for (const name of names) {
567
+ if (!SLIDE_ID_RE.test(name)) continue;
568
+ for (const entry of ENTRY_NAMES$1) try {
569
+ const stat = await fs.stat(path.join(slidesRoot, name, entry));
570
+ decks[name] = { modifiedAt: Math.round(stat.mtimeMs) };
571
+ break;
572
+ } catch {}
573
+ }
574
+ return decks;
575
+ }
576
+ function registerDeckRoutes(server, ctx) {
577
+ server.middlewares.use("/__lr/decks", async (req, res, next) => {
578
+ const url = new URL(req.url ?? "/", "http://local");
579
+ if ((req.method ?? "GET") !== "GET" || url.pathname !== "/") return next();
580
+ try {
581
+ json(res, 200, { decks: await readDeckTimes(ctx.slidesRoot) });
582
+ } catch (err) {
583
+ json(res, 500, { error: String(err.message ?? err) });
584
+ }
585
+ });
586
+ }
587
+ //#endregion
588
+ //#region src/vite/recent-writes.ts
589
+ const recentWrites = /* @__PURE__ */ new Map();
590
+ /** Record that `file` was just written by us. */
591
+ function recordWrite(file, now = Date.now()) {
592
+ recentWrites.set(file, now);
593
+ }
594
+ /**
595
+ * True if `file` was recorded within the recent-write window. Expired entries
596
+ * are pruned so a stale path can no longer suppress a later genuine edit.
597
+ */
598
+ function hasRecentWrite(file, now = Date.now()) {
599
+ const ts = recentWrites.get(file);
600
+ if (ts == null) return false;
601
+ if (now - ts < 1500) return true;
602
+ recentWrites.delete(file);
603
+ return false;
604
+ }
605
+ //#endregion
606
+ //#region src/vite/open-slide-plugin.ts
607
+ const SLIDES_VMOD = "virtual:open-slide/slides";
608
+ const CONFIG_VMOD = "virtual:open-slide/config";
609
+ const FOLDERS_VMOD = "virtual:open-slide/folders";
610
+ function resolved$1(id) {
611
+ return `\0${id}`;
612
+ }
613
+ async function findSlides(userCwd, slidesDir) {
614
+ const abs = path.resolve(userCwd, slidesDir);
615
+ if (!existsSync(abs)) return [];
616
+ return (await fg("*/index.{tsx,jsx,ts,js}", {
617
+ cwd: abs,
618
+ absolute: true,
619
+ onlyFiles: true
620
+ })).sort();
621
+ }
622
+ function toId(absFile, slidesRoot) {
623
+ return path.relative(slidesRoot, absFile).split(path.sep)[0];
624
+ }
625
+ const META_THEME_RE = /(?:^|[\s,{])theme\s*:\s*['"]([^'"]+)['"]/;
626
+ const META_CREATED_AT_RE = /(?:^|[\s,{])createdAt\s*:\s*['"]([^'"]+)['"]/;
627
+ function extractMeta(src) {
628
+ const empty = {
629
+ theme: null,
630
+ createdAt: null
631
+ };
632
+ const metaStart = src.search(/export\s+const\s+meta\b/);
633
+ if (metaStart === -1) return empty;
634
+ const eqIdx = src.indexOf("=", metaStart);
635
+ if (eqIdx === -1) return empty;
636
+ const openBrace = src.indexOf("{", eqIdx);
637
+ if (openBrace === -1) return empty;
638
+ let depth = 0;
639
+ let closeBrace = -1;
640
+ for (let i = openBrace; i < src.length; i++) {
641
+ const ch = src[i];
642
+ if (ch === "{") depth++;
643
+ else if (ch === "}") {
644
+ depth--;
645
+ if (depth === 0) {
646
+ closeBrace = i;
647
+ break;
648
+ }
649
+ }
650
+ }
651
+ if (closeBrace === -1) return empty;
652
+ const body = src.slice(openBrace + 1, closeBrace);
653
+ const themeMatch = body.match(META_THEME_RE);
654
+ const createdAtMatch = body.match(META_CREATED_AT_RE);
655
+ return {
656
+ theme: themeMatch ? themeMatch[1] : null,
657
+ createdAt: createdAtMatch ? createdAtMatch[1] : null
658
+ };
659
+ }
660
+ async function readSlideMeta(abs) {
661
+ try {
662
+ return extractMeta(await fs.readFile(abs, "utf8"));
663
+ } catch {
664
+ return {
665
+ theme: null,
666
+ createdAt: null
667
+ };
668
+ }
669
+ }
670
+ function parseCreatedAtMs(iso) {
671
+ if (!iso) return null;
672
+ const ms = Date.parse(iso);
673
+ return Number.isFinite(ms) ? ms : null;
674
+ }
675
+ const warnedInvalidSlideIds = /* @__PURE__ */ new Set();
676
+ async function generateSlidesModule(files, slidesRoot, isDev) {
677
+ const scanned = await Promise.all(files.map(async (abs) => {
678
+ const id = toId(abs, slidesRoot);
679
+ const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
680
+ const meta = await readSlideMeta(abs);
681
+ return {
682
+ id,
683
+ importPath,
684
+ theme: meta.theme,
685
+ createdAt: parseCreatedAtMs(meta.createdAt)
686
+ };
687
+ }));
688
+ const entries = scanned.filter((e) => SLIDE_ID_RE.test(e.id));
689
+ const ignored = scanned.filter((e) => !SLIDE_ID_RE.test(e.id)).map((e) => e.id);
690
+ const ids = JSON.stringify(entries.map((e) => e.id).sort());
691
+ const themesMap = {};
692
+ const createdAtMap = {};
693
+ for (const e of entries) {
694
+ if (e.theme) themesMap[e.id] = e.theme;
695
+ if (e.createdAt !== null) createdAtMap[e.id] = e.createdAt;
696
+ }
697
+ const themesJson = JSON.stringify(themesMap);
698
+ const createdAtJson = JSON.stringify(createdAtMap);
699
+ const importTokens = JSON.stringify(Object.fromEntries(entries.map((e) => [e.id, 0])));
700
+ return {
701
+ code: `// virtual:open-slide/slides — generated
702
+ export const slideIds = ${ids};
703
+ export const slideThemes = ${themesJson};
704
+ export const slideCreatedAt = ${createdAtJson};
705
+ ${isDev ? `
706
+ const slideImportTokens = ${importTokens};
707
+ if (import.meta.hot) {
708
+ import.meta.hot.on('open-slide:slide-changed', (data) => {
709
+ const ids = Array.isArray(data?.slideIds) ? data.slideIds : [];
710
+ const token = Date.now();
711
+ for (const id of ids) {
712
+ if (Object.prototype.hasOwnProperty.call(slideImportTokens, id)) slideImportTokens[id] = token;
713
+ }
714
+ });
715
+ }
716
+ ` : ""}
717
+
718
+ export async function loadSlide(id) {
719
+ switch (id) {
720
+ ${entries.map((e) => {
721
+ const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(`${e.importPath}?t=`)} + slideImportTokens[${JSON.stringify(e.id)}])` : `import(${JSON.stringify(e.importPath)})`;
722
+ return ` case ${JSON.stringify(e.id)}: return ${importExpr};`;
723
+ }).join("\n")}
724
+ default: throw new Error('Slide not found: ' + id);
725
+ }
726
+ }
727
+ `,
728
+ ignored
729
+ };
730
+ }
731
+ function lemonRiverPlugin(opts) {
732
+ const { userCwd, config, coreVersion } = opts;
733
+ const slidesDir = config.slidesDir ?? "slides";
734
+ const slidesRoot = path.resolve(userCwd, slidesDir);
735
+ const manifestPath = foldersManifestPath(slidesRoot);
736
+ let isDev = false;
737
+ const slideIdForEntry = (p) => {
738
+ const rel = path.relative(slidesRoot, p);
739
+ if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
740
+ const parts = rel.split(path.sep);
741
+ if (parts.length !== 2) return null;
742
+ if (!/^index\.(tsx|jsx|ts|js)$/.test(parts[1])) return null;
743
+ return parts[0];
744
+ };
745
+ let slideChangeTimer = null;
746
+ const pendingSlideChanges = /* @__PURE__ */ new Set();
747
+ const queueSlideChanged = (server, id) => {
748
+ pendingSlideChanges.add(id);
749
+ if (slideChangeTimer) clearTimeout(slideChangeTimer);
750
+ slideChangeTimer = setTimeout(() => {
751
+ slideChangeTimer = null;
752
+ const mod = server.moduleGraph.getModuleById(resolved$1(SLIDES_VMOD));
753
+ if (mod) server.moduleGraph.invalidateModule(mod);
754
+ const slideIds = Array.from(pendingSlideChanges);
755
+ pendingSlideChanges.clear();
756
+ server.ws.send({
757
+ type: "custom",
758
+ event: "open-slide:slide-changed",
759
+ data: { slideIds }
760
+ });
761
+ }, 100);
762
+ };
763
+ return {
764
+ name: "lemonriver",
765
+ config(_c, env) {
766
+ isDev = env.command === "serve";
767
+ },
768
+ resolveId(id) {
769
+ if (id === SLIDES_VMOD) return resolved$1(SLIDES_VMOD);
770
+ if (id === CONFIG_VMOD) return resolved$1(CONFIG_VMOD);
771
+ if (id === FOLDERS_VMOD) return resolved$1(FOLDERS_VMOD);
772
+ return null;
773
+ },
774
+ async load(id) {
775
+ if (id === resolved$1(SLIDES_VMOD)) {
776
+ const { code, ignored } = await generateSlidesModule(await findSlides(userCwd, slidesDir), slidesRoot, isDev);
777
+ for (const slideId of ignored) {
778
+ if (warnedInvalidSlideIds.has(slideId)) continue;
779
+ warnedInvalidSlideIds.add(slideId);
780
+ this.warn(`Ignoring slide folder "${slideId}": slide ids must match ${SLIDE_ID_RE} (lowercase/uppercase letters, digits, "-", "_"). Rename the folder under "${slidesDir}/" to a kebab-case id so it appears in the browser and can be moved into folders.`);
781
+ }
782
+ return code;
783
+ }
784
+ if (id === resolved$1(CONFIG_VMOD)) {
785
+ const userBuild = config.build ?? {};
786
+ const buildResolved = isDev ? {
787
+ showSlideBrowser: true,
788
+ showSlideUi: true,
789
+ allowHtmlDownload: true
790
+ } : {
791
+ showSlideBrowser: userBuild.showSlideBrowser ?? true,
792
+ showSlideUi: userBuild.showSlideUi ?? true,
793
+ allowHtmlDownload: userBuild.allowHtmlDownload ?? true
794
+ };
795
+ const resolvedConfig = {
796
+ ...config,
797
+ build: buildResolved,
798
+ version: coreVersion
799
+ };
800
+ return `export default ${JSON.stringify(resolvedConfig)};\n`;
801
+ }
802
+ if (id === resolved$1(FOLDERS_VMOD)) {
803
+ const manifest = await readManifest(manifestPath);
804
+ return `export default ${JSON.stringify(manifest)};\n`;
805
+ }
806
+ return null;
807
+ },
808
+ handleHotUpdate(ctx) {
809
+ const slideId = slideIdForEntry(ctx.file);
810
+ if (!slideId) return;
811
+ if (hasRecentWrite(ctx.file)) return [];
812
+ queueSlideChanged(ctx.server, slideId);
813
+ return [];
814
+ },
815
+ configureServer(server) {
816
+ const isSlideEntry = (p) => slideIdForEntry(p) !== null;
817
+ let reloadTimer = null;
818
+ const reload = () => {
819
+ if (reloadTimer) clearTimeout(reloadTimer);
820
+ reloadTimer = setTimeout(() => {
821
+ reloadTimer = null;
822
+ const mod = server.moduleGraph.getModuleById(resolved$1(SLIDES_VMOD));
823
+ if (mod) server.moduleGraph.invalidateModule(mod);
824
+ server.ws.send({ type: "full-reload" });
825
+ }, 150);
826
+ };
827
+ if (existsSync(slidesRoot)) server.watcher.add(slidesRoot);
828
+ server.watcher.on("add", (p) => {
829
+ if (isSlideEntry(p) && !hasRecentWrite(p)) reload();
830
+ });
831
+ server.watcher.on("unlink", (p) => {
832
+ if (isSlideEntry(p) && !hasRecentWrite(p)) reload();
833
+ });
834
+ let foldersTimer = null;
835
+ const invalidateFolders = () => {
836
+ if (foldersTimer) clearTimeout(foldersTimer);
837
+ foldersTimer = setTimeout(() => {
838
+ foldersTimer = null;
839
+ const mod = server.moduleGraph.getModuleById(resolved$1(FOLDERS_VMOD));
840
+ if (mod) server.moduleGraph.invalidateModule(mod);
841
+ }, 100);
842
+ };
843
+ server.watcher.add(manifestPath);
844
+ server.watcher.on("change", (p) => {
845
+ if (p === manifestPath) invalidateFolders();
846
+ });
847
+ server.watcher.on("add", (p) => {
848
+ if (p === manifestPath) invalidateFolders();
849
+ });
850
+ server.watcher.on("unlink", (p) => {
851
+ if (p === manifestPath) invalidateFolders();
852
+ });
853
+ }
854
+ };
855
+ }
856
+ function invalidateSlidesModule(server) {
857
+ const mod = server.moduleGraph.getModuleById(resolved$1(SLIDES_VMOD));
858
+ if (mod) server.moduleGraph.invalidateModule(mod);
859
+ }
860
+ async function loadUserConfig(userCwd) {
861
+ const file = CONFIG_FILES.map((name) => path.join(userCwd, name)).find((p) => existsSync(p));
862
+ if (!file) return {};
863
+ return (await loadConfigFromFile({
864
+ command: "serve",
865
+ mode: "development"
866
+ }, file, userCwd, "silent"))?.config ?? {};
867
+ }
868
+ //#endregion
869
+ //#region src/lemonriver/trash/store.ts
870
+ const TRASH_RETENTION_MS = 2592e6;
871
+ /** `<slideId>.<deletedAt>` — unique per deletion, and safe as a single path segment. */
872
+ const ENTRY_ID_RE = /^[a-z0-9_-]+\.\d{1,16}$/i;
873
+ const ENTRY_FILE = "entry.json";
874
+ const SLIDE_DIR = "slide";
875
+ function trashRootFor(userCwd) {
876
+ return path.join(userCwd, "node_modules", ".open-slide", "trash");
877
+ }
878
+ function isTrashEntryId(id) {
879
+ return ENTRY_ID_RE.test(id);
880
+ }
881
+ function inside(root, id) {
882
+ const dir = path.resolve(root, id);
883
+ return dir.startsWith(path.resolve(root) + path.sep) ? dir : null;
884
+ }
885
+ async function exists(p) {
886
+ try {
887
+ await fs.access(p);
888
+ return true;
889
+ } catch {
890
+ return false;
891
+ }
892
+ }
893
+ async function moveDir(from, to) {
894
+ try {
895
+ await fs.rename(from, to);
896
+ } catch (err) {
897
+ if (err.code !== "EXDEV") throw err;
898
+ await fs.cp(from, to, {
899
+ recursive: true,
900
+ errorOnExist: true,
901
+ force: false
902
+ });
903
+ await fs.rm(from, {
904
+ recursive: true,
905
+ force: true
906
+ });
907
+ }
908
+ }
909
+ async function readTitle(slideDir, fallback) {
910
+ try {
911
+ const read = readMetaTitleInSource(await fs.readFile(path.join(slideDir, "index.tsx"), "utf8"));
912
+ return read.kind === "found" && read.title.trim() ? read.title : fallback;
913
+ } catch {
914
+ return fallback;
915
+ }
916
+ }
917
+ function toEntry(id, raw) {
918
+ if (!raw || typeof raw !== "object") return null;
919
+ const r = raw;
920
+ if (typeof r.slideId !== "string" || !SLIDE_ID_RE.test(r.slideId)) return null;
921
+ if (typeof r.deletedAt !== "number" || !Number.isFinite(r.deletedAt)) return null;
922
+ return {
923
+ id,
924
+ slideId: r.slideId,
925
+ title: typeof r.title === "string" && r.title ? r.title : r.slideId,
926
+ folderId: typeof r.folderId === "string" ? r.folderId : null,
927
+ deletedAt: r.deletedAt,
928
+ expiresAt: r.deletedAt + TRASH_RETENTION_MS
929
+ };
930
+ }
931
+ async function readEntry(trashRoot, id) {
932
+ if (!isTrashEntryId(id)) return null;
933
+ const dir = inside(trashRoot, id);
934
+ if (!dir) return null;
935
+ try {
936
+ const entry = toEntry(id, JSON.parse(await fs.readFile(path.join(dir, ENTRY_FILE), "utf8")));
937
+ return entry && await exists(path.join(dir, SLIDE_DIR)) ? entry : null;
938
+ } catch {
939
+ return null;
940
+ }
941
+ }
942
+ async function idTaken(slidesRoot, slideId) {
943
+ try {
944
+ const want = slideId.toLowerCase();
945
+ return (await fs.readdir(slidesRoot)).some((name) => name.toLowerCase() === want);
946
+ } catch {
947
+ return false;
948
+ }
949
+ }
950
+ async function freeSlideId(slidesRoot, slideId) {
951
+ if (!await idTaken(slidesRoot, slideId)) return slideId;
952
+ for (let n = 1;; n++) {
953
+ const candidate = n === 1 ? `${slideId}-restored` : `${slideId}-restored-${n}`;
954
+ if (!await idTaken(slidesRoot, candidate)) return candidate;
955
+ }
956
+ }
957
+ async function listTrash(paths, now = Date.now()) {
958
+ let names;
959
+ try {
960
+ names = await fs.readdir(paths.trashRoot);
961
+ } catch {
962
+ return [];
963
+ }
964
+ const entries = [];
965
+ for (const name of names) {
966
+ const entry = await readEntry(paths.trashRoot, name);
967
+ if (!entry) continue;
968
+ if (now >= entry.expiresAt) {
969
+ await purgeTrashEntry(paths, entry.id);
970
+ continue;
971
+ }
972
+ entries.push(entry);
973
+ }
974
+ return entries.sort((a, b) => b.deletedAt - a.deletedAt);
975
+ }
976
+ async function moveSlideToTrash(paths, slideId, now = Date.now()) {
977
+ if (!SLIDE_ID_RE.test(slideId)) return {
978
+ ok: false,
979
+ status: 400,
980
+ error: "invalid slideId"
981
+ };
982
+ const slideDir = inside(paths.slidesRoot, slideId);
983
+ if (!slideDir || !await exists(slideDir)) return {
984
+ ok: false,
985
+ status: 404,
986
+ error: "slide not found"
987
+ };
988
+ let deletedAt = now;
989
+ while (await exists(path.join(paths.trashRoot, `${slideId}.${deletedAt}`))) deletedAt++;
990
+ const id = `${slideId}.${deletedAt}`;
991
+ const entryDir = path.join(paths.trashRoot, id);
992
+ const manifest = await readManifest(paths.manifestPath);
993
+ const folderId = manifest.assignments[slideId] ?? null;
994
+ const title = await readTitle(slideDir, slideId);
995
+ await fs.mkdir(entryDir, { recursive: true });
996
+ await fs.writeFile(path.join(entryDir, ENTRY_FILE), `${JSON.stringify({
997
+ slideId,
998
+ title,
999
+ folderId,
1000
+ deletedAt
1001
+ }, null, 2)}\n`, "utf8");
1002
+ try {
1003
+ await moveDir(slideDir, path.join(entryDir, SLIDE_DIR));
1004
+ } catch (err) {
1005
+ await fs.rm(entryDir, {
1006
+ recursive: true,
1007
+ force: true
1008
+ });
1009
+ throw err;
1010
+ }
1011
+ if (folderId !== null) {
1012
+ delete manifest.assignments[slideId];
1013
+ await writeManifest(paths.manifestPath, manifest);
1014
+ }
1015
+ return {
1016
+ ok: true,
1017
+ entry: {
1018
+ id,
1019
+ slideId,
1020
+ title,
1021
+ folderId,
1022
+ deletedAt,
1023
+ expiresAt: deletedAt + TRASH_RETENTION_MS
1024
+ }
1025
+ };
1026
+ }
1027
+ async function restoreTrashEntry(paths, id, beforeMove = () => {}) {
1028
+ const entry = await readEntry(paths.trashRoot, id);
1029
+ if (!entry) return {
1030
+ ok: false,
1031
+ status: 404,
1032
+ error: "trash entry not found"
1033
+ };
1034
+ const entryDir = path.join(paths.trashRoot, id);
1035
+ const slideId = await freeSlideId(paths.slidesRoot, entry.slideId);
1036
+ const slideDir = inside(paths.slidesRoot, slideId);
1037
+ if (!slideDir) return {
1038
+ ok: false,
1039
+ status: 400,
1040
+ error: "invalid slideId"
1041
+ };
1042
+ await fs.mkdir(paths.slidesRoot, { recursive: true });
1043
+ beforeMove(slideId);
1044
+ await moveDir(path.join(entryDir, SLIDE_DIR), slideDir);
1045
+ await fs.rm(entryDir, {
1046
+ recursive: true,
1047
+ force: true
1048
+ });
1049
+ if (entry.folderId !== null) {
1050
+ const manifest = await readManifest(paths.manifestPath);
1051
+ if (manifest.folders.some((f) => f.id === entry.folderId)) {
1052
+ manifest.assignments[slideId] = entry.folderId;
1053
+ await writeManifest(paths.manifestPath, manifest);
1054
+ }
1055
+ }
1056
+ return {
1057
+ ok: true,
1058
+ slideId
1059
+ };
1060
+ }
1061
+ async function purgeTrashEntry(paths, id) {
1062
+ if (!isTrashEntryId(id)) return false;
1063
+ const dir = inside(paths.trashRoot, id);
1064
+ if (!dir || !await exists(dir)) return false;
1065
+ await fs.rm(dir, {
1066
+ recursive: true,
1067
+ force: true
1068
+ });
1069
+ return true;
1070
+ }
1071
+ //#endregion
1072
+ //#region src/lemonriver/trash/routes.ts
1073
+ const ENTRY_NAMES = [
1074
+ "index.tsx",
1075
+ "index.jsx",
1076
+ "index.ts",
1077
+ "index.js"
1078
+ ];
1079
+ const DECKS_CHANGED_EVENT = "lemonriver:decks-changed";
1080
+ function registerTrashRoutes(server, ctx) {
1081
+ const paths = {
1082
+ slidesRoot: ctx.slidesRoot,
1083
+ manifestPath: ctx.manifestPath,
1084
+ trashRoot: trashRootFor(ctx.userCwd)
1085
+ };
1086
+ const quietWatcher = (slideId) => {
1087
+ for (const name of ENTRY_NAMES) recordWrite(path.join(ctx.slidesRoot, slideId, name));
1088
+ };
1089
+ const reloadClients = () => {
1090
+ invalidateSlidesModule(server);
1091
+ server.ws.send({
1092
+ type: "custom",
1093
+ event: DECKS_CHANGED_EVENT
1094
+ });
1095
+ };
1096
+ server.middlewares.use("/__lr/trash", async (req, res, next) => {
1097
+ const url = new URL(req.url ?? "/", "http://local");
1098
+ const method = req.method ?? "GET";
1099
+ try {
1100
+ if (method === "GET" && url.pathname === "/") return json(res, 200, { entries: await listTrash(paths) });
1101
+ if (method === "POST" && url.pathname === "/") {
1102
+ const check = validateMutationRequest(req, { requireJsonBody: true });
1103
+ if (!check.ok) return json(res, check.status, { error: check.error });
1104
+ const body = await readBody(req);
1105
+ const slideId = typeof body?.slideId === "string" ? body.slideId : "";
1106
+ if (!SLIDE_ID_RE.test(slideId)) return json(res, 400, { error: "invalid slideId" });
1107
+ quietWatcher(slideId);
1108
+ const moved = await moveSlideToTrash(paths, slideId);
1109
+ if (!moved.ok) return json(res, moved.status, { error: moved.error });
1110
+ json(res, 200, {
1111
+ ok: true,
1112
+ entry: moved.entry
1113
+ });
1114
+ return reloadClients();
1115
+ }
1116
+ const restoreMatch = url.pathname.match(/^\/([^/]+)\/restore$/);
1117
+ if (method === "POST" && restoreMatch) {
1118
+ const check = validateMutationRequest(req);
1119
+ if (!check.ok) return json(res, check.status, { error: check.error });
1120
+ const id = decodeURIComponent(restoreMatch[1]);
1121
+ if (!isTrashEntryId(id)) return json(res, 400, { error: "invalid trash id" });
1122
+ const restored = await restoreTrashEntry(paths, id, quietWatcher);
1123
+ if (!restored.ok) return json(res, restored.status, { error: restored.error });
1124
+ json(res, 200, {
1125
+ ok: true,
1126
+ slideId: restored.slideId
1127
+ });
1128
+ return reloadClients();
1129
+ }
1130
+ const entryMatch = url.pathname.match(/^\/([^/]+)$/);
1131
+ if (method === "DELETE" && entryMatch) {
1132
+ const check = validateMutationRequest(req);
1133
+ if (!check.ok) return json(res, check.status, { error: check.error });
1134
+ const id = decodeURIComponent(entryMatch[1]);
1135
+ if (!isTrashEntryId(id)) return json(res, 400, { error: "invalid trash id" });
1136
+ if (!await purgeTrashEntry(paths, id)) return json(res, 404, { error: "trash entry not found" });
1137
+ return json(res, 200, { ok: true });
1138
+ }
1139
+ next();
1140
+ } catch (err) {
1141
+ json(res, 500, { error: String(err.message ?? err) });
1142
+ }
1143
+ });
1144
+ }
1145
+ //#endregion
1146
+ //#region src/lemonriver/routes.ts
1147
+ function registerLemonRiverRoutes(server, ctx) {
1148
+ registerBoardRoutes(server, ctx);
1149
+ registerTrashRoutes(server, ctx);
1150
+ registerDeckRoutes(server, ctx);
1151
+ }
1152
+ //#endregion
1153
+ //#region src/editing/placeholder-id.ts
1154
+ const UNTITLED_SLIDE_ID_RE = /^untitled(-\d+)?$/;
1155
+ //#endregion
1156
+ //#region src/agent/provider.ts
1157
+ var ProviderUnavailableError = class extends Error {
1158
+ constructor(provider) {
1159
+ super(`${provider.name} is not connected: install ${provider.sdkPackage} in this workspace to use it from the agent panel.`);
1160
+ this.name = "ProviderUnavailableError";
1161
+ }
1162
+ };
1163
+ const DETAIL_MAX = 400;
1164
+ function clipDetail(value) {
1165
+ if (value === void 0 || value === null) return null;
1166
+ const text = typeof value === "string" ? value : safeJson(value);
1167
+ if (!text) return null;
1168
+ const oneLine = text.replace(/\s+/g, " ").trim();
1169
+ return oneLine.length > DETAIL_MAX ? `${oneLine.slice(0, 399)}…` : oneLine;
1170
+ }
1171
+ function safeJson(value) {
1172
+ try {
1173
+ return JSON.stringify(value);
1174
+ } catch {
1175
+ return String(value);
1176
+ }
1177
+ }
1178
+ function isInsideRoots(cwd, file, roots) {
1179
+ if (typeof file !== "string" || !file) return false;
1180
+ const resolved = path.resolve(cwd, file);
1181
+ return roots.some((root) => {
1182
+ const rel = path.relative(root, resolved);
1183
+ return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
1184
+ });
1185
+ }
1186
+ function relativeToCwd(cwd, file) {
1187
+ if (typeof file !== "string" || !file) return null;
1188
+ const normalizedCwd = cwd.replace(/[\\/]+$/, "");
1189
+ if (file.startsWith(normalizedCwd)) return file.slice(normalizedCwd.length).replace(/^[\\/]+/, "") || ".";
1190
+ return file;
1191
+ }
1192
+ function parseQuestions(input) {
1193
+ const raw = Array.isArray(input.questions) ? input.questions : [];
1194
+ const questions = [];
1195
+ for (const q of raw) {
1196
+ if (!q || typeof q !== "object") continue;
1197
+ const r = q;
1198
+ const options = Array.isArray(r.options) ? r.options.map((o) => {
1199
+ if (!o || typeof o !== "object") return null;
1200
+ const opt = o;
1201
+ if (typeof opt.label !== "string") return null;
1202
+ return {
1203
+ label: opt.label,
1204
+ description: typeof opt.description === "string" ? opt.description : void 0
1205
+ };
1206
+ }).filter((o) => o !== null) : [];
1207
+ if (typeof r.question !== "string") continue;
1208
+ questions.push({
1209
+ header: typeof r.header === "string" ? r.header : "",
1210
+ question: r.question,
1211
+ options,
1212
+ multiSelect: r.multiSelect === true
1213
+ });
1214
+ }
1215
+ return questions;
1216
+ }
1217
+ //#endregion
1218
+ //#region src/agent/prompt.ts
1219
+ const PAGE_BY_PAGE = "Write a new deck page by page so the user can follow along on the canvas: first replace the file with the imports, meta (keeping its existing createdAt), design and the cover page only, then add each remaining page with its own separate edit, keeping the file compiling after every write.";
1220
+ const DECK_SLUG = "This deck's folder still has a placeholder name. Never rename or move the folder yourself: once the deck has content, end your final reply with a slug for it on a line of its own as <deck-slug>short-kebab-case-english-slug</deck-slug>, and LemonRiver renames the folder from it.";
1221
+ function systemPromptAppend(askInstruction) {
1222
+ return [
1223
+ "You are running inside the LemonRiver dev server, driven from its in-app agent panel in the browser rather than a terminal.",
1224
+ "The workspace is a LemonRiver project: decks live under slides/<id>/index.tsx and the dev server hot-reloads every edit, so the user sees changes immediately.",
1225
+ "Use the project skills: create-slide to draft a new deck, apply-comments to resolve @slide-comment markers left by the inspector, create-theme for themes, and slide-authoring as the technical reference before writing a page.",
1226
+ PAGE_BY_PAGE,
1227
+ "Keep replies short and concrete: the panel is narrow. Prefer doing the work over describing it, and finish with a one-line summary of what changed.",
1228
+ askInstruction
1229
+ ].join(" ");
1230
+ }
1231
+ function buildTurnPrompt(text, context) {
1232
+ const lines = contextLines(context);
1233
+ if (lines.length === 0) return text;
1234
+ return `${text}\n\n<open-slide-context>\n${lines.join("\n")}\n</open-slide-context>`;
1235
+ }
1236
+ const escapeTag = (s) => s.replace(/</g, "&lt;");
1237
+ function contextLines(context) {
1238
+ if (!context?.slideId) return [];
1239
+ const file = `slides/${context.slideId}/index.tsx`;
1240
+ const lines = [];
1241
+ if (context.newDeck) {
1242
+ lines.push(`${file} is a blank deck created for this request. Draft the deck the user describes into it with the create-slide skill: replace the placeholder page, keep the slide id, and do not create another folder.`, "Ask the create-slide scoping questions in a single round, only for what the request leaves unclear; skip any it already answers.", PAGE_BY_PAGE, DECK_SLUG);
1243
+ return lines;
1244
+ }
1245
+ lines.push(`The user is viewing slide "${context.slideId}": ${file}.`);
1246
+ if (UNTITLED_SLIDE_ID_RE.test(context.slideId)) lines.push(DECK_SLUG);
1247
+ if (context.slideTitle) lines.push(`<slide-title>${escapeTag(context.slideTitle)}</slide-title>`);
1248
+ if (context.pageNumber && context.totalPages) lines.push(`They are on page ${context.pageNumber} of ${context.totalPages} (0-based index ${context.pageNumber - 1} in the default export array).`);
1249
+ if (context.selection) {
1250
+ const { line, column, tagName, text } = context.selection;
1251
+ lines.push(`They have selected a <${escapeTag(tagName)}> element at ${file}:${line}:${column}.${text ? " Its text is in <selected-text>." : ""} "This element" refers to it.`);
1252
+ if (text) lines.push(`<selected-text>${escapeTag(text)}</selected-text>`);
1253
+ }
1254
+ if (context.pendingComments) lines.push(`There are ${context.pendingComments} pending @slide-comment markers in this slide's source.`);
1255
+ return lines;
1256
+ }
1257
+ const DECK_SLUG_RE = /\s*<deck-slug>\s*([^<]*?)\s*<\/deck-slug>\s*/gi;
1258
+ function extractDeckSlug(text) {
1259
+ let slug = null;
1260
+ for (const match of text.matchAll(DECK_SLUG_RE)) slug = match[1] || slug;
1261
+ return slug;
1262
+ }
1263
+ function stripDeckSlug(text) {
1264
+ return text.replace(DECK_SLUG_RE, "\n").replace(/\s*<deck-slug>[^<]*$/i, "").trimEnd();
1265
+ }
1266
+ const QUESTIONS_RE = /<open-slide-questions>([\s\S]*?)<\/open-slide-questions>/i;
1267
+ const TEXT_QUESTIONS_INSTRUCTION = "You cannot ask the user anything interactively here, and nothing you print in the middle of a turn can be answered. When you need answers before continuing, stop working and end your turn with a final message holding only an <open-slide-questions> block: a JSON array of at most 4 questions shaped like [{\"header\":\"Pages\",\"question\":\"How many pages?\",\"multiSelect\":false,\"options\":[{\"label\":\"6-10 (Recommended)\",\"description\":\"Standard length\"}]}], each with 2 to 4 options, written in the user's language. The panel shows them as a form and sends the answers back as your next message. Write nothing after the block and do not continue the task in the same turn.";
1268
+ function extractQuestionBlock(text) {
1269
+ const match = QUESTIONS_RE.exec(text);
1270
+ if (!match) return null;
1271
+ const body = match[1].trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
1272
+ let raw;
1273
+ try {
1274
+ raw = JSON.parse(body);
1275
+ } catch {
1276
+ return null;
1277
+ }
1278
+ const questions = parseQuestions({ questions: Array.isArray(raw) ? raw : raw?.questions });
1279
+ if (questions.length === 0) return null;
1280
+ return {
1281
+ text: text.replace(QUESTIONS_RE, "").trim(),
1282
+ questions
1283
+ };
1284
+ }
1285
+ function answersPrompt(questions, answers) {
1286
+ if (!answers) return "I skipped your questions. Continue the task with your best judgement and sensible defaults.";
1287
+ return `My answers:\n${questions.map((q) => `- ${q.question} ${answers[q.question] || "(no answer)"}`).join("\n")}\n\nContinue the task with these answers.`;
1288
+ }
1289
+ function editedPrompt(original, text) {
1290
+ return `I went back and edited an earlier message of mine. Treat everything after it in this conversation, including your replies, as discarded, and respond to the edited version instead. Files keep whatever changes were already made.\n\n<original-message>\n${escapeTag(original)}\n</original-message>\n\n${text}`;
1291
+ }
1292
+ function rewoundPrompt(text) {
1293
+ return `${text}\n\n<open-slide-note>I went back and edited this message. Files keep the changes made after it in the discarded part of this conversation, so read the current files before editing them.</open-slide-note>`;
1294
+ }
1295
+ //#endregion
1296
+ //#region src/agent/detect.ts
1297
+ const IS_WINDOWS = process.platform === "win32";
1298
+ const VERSION_TIMEOUT_MS = 5e3;
1299
+ function findOnPath(command, env = process.env) {
1300
+ const dirs = (env.PATH ?? env.Path ?? "").split(path.delimiter).filter(Boolean);
1301
+ const exts = IS_WINDOWS ? (env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";") : [""];
1302
+ for (const dir of dirs) for (const ext of exts) {
1303
+ const candidate = path.join(dir, command + ext.toLowerCase());
1304
+ try {
1305
+ if (statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate;
1306
+ } catch {}
1307
+ }
1308
+ return null;
1309
+ }
1310
+ function findSpawnableCli(command, env = process.env) {
1311
+ const found = findOnPath(command, env);
1312
+ if (!found || !IS_WINDOWS) return found;
1313
+ return found.toLowerCase().endsWith(".exe") ? found : null;
1314
+ }
1315
+ const versionCache = /* @__PURE__ */ new Map();
1316
+ function commandVersion(file) {
1317
+ let cached = versionCache.get(file);
1318
+ if (!cached) {
1319
+ cached = readVersion(file);
1320
+ versionCache.set(file, cached);
1321
+ }
1322
+ return cached;
1323
+ }
1324
+ function readVersion(file) {
1325
+ return new Promise((resolve) => {
1326
+ let out = "";
1327
+ let child;
1328
+ try {
1329
+ child = spawn(file, ["--version"], {
1330
+ stdio: [
1331
+ "ignore",
1332
+ "pipe",
1333
+ "pipe"
1334
+ ],
1335
+ shell: IS_WINDOWS,
1336
+ windowsHide: true
1337
+ });
1338
+ } catch {
1339
+ resolve(null);
1340
+ return;
1341
+ }
1342
+ const timer = setTimeout(() => {
1343
+ child.kill();
1344
+ resolve(null);
1345
+ }, VERSION_TIMEOUT_MS);
1346
+ child.stdout?.on("data", (c) => {
1347
+ out += c.toString("utf8");
1348
+ });
1349
+ child.stderr?.on("data", (c) => {
1350
+ out += c.toString("utf8");
1351
+ });
1352
+ child.on("error", () => {
1353
+ clearTimeout(timer);
1354
+ resolve(null);
1355
+ });
1356
+ child.on("close", () => {
1357
+ clearTimeout(timer);
1358
+ resolve(parseVersion(out));
1359
+ });
1360
+ });
1361
+ }
1362
+ function parseVersion(output) {
1363
+ const m = /(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/.exec(output);
1364
+ return m ? m[1] : null;
1365
+ }
1366
+ function entryFromPackageJson(pkg) {
1367
+ const root = pickExport(pkg.exports);
1368
+ if (root) return root;
1369
+ return pkg.module ?? pkg.main ?? null;
1370
+ }
1371
+ function pickExport(exportsField) {
1372
+ if (!exportsField) return null;
1373
+ if (typeof exportsField === "string") return exportsField;
1374
+ if (typeof exportsField !== "object") return null;
1375
+ const record = exportsField;
1376
+ return pickCondition(Object.keys(record).some((k) => k.startsWith(".")) ? record["."] : exportsField);
1377
+ }
1378
+ function pickCondition(target) {
1379
+ if (!target) return null;
1380
+ if (typeof target === "string") return target;
1381
+ if (Array.isArray(target)) {
1382
+ for (const t of target) {
1383
+ const hit = pickCondition(t);
1384
+ if (hit) return hit;
1385
+ }
1386
+ return null;
1387
+ }
1388
+ if (typeof target !== "object") return null;
1389
+ const record = target;
1390
+ for (const key of [
1391
+ "import",
1392
+ "node",
1393
+ "default",
1394
+ "require"
1395
+ ]) if (key in record) {
1396
+ const hit = pickCondition(record[key]);
1397
+ if (hit) return hit;
1398
+ }
1399
+ return null;
1400
+ }
1401
+ function resolveWorkspacePackage(userCwd, name) {
1402
+ let dir = path.resolve(userCwd);
1403
+ while (true) {
1404
+ const pkgJsonPath = path.join(dir, "node_modules", name, "package.json");
1405
+ if (existsSync(pkgJsonPath)) {
1406
+ let pkg;
1407
+ try {
1408
+ pkg = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
1409
+ } catch {
1410
+ return null;
1411
+ }
1412
+ const entry = entryFromPackageJson(pkg);
1413
+ if (!entry) return null;
1414
+ const pkgDir = path.dirname(pkgJsonPath);
1415
+ return {
1416
+ dir: pkgDir,
1417
+ version: pkg.version ?? "0.0.0",
1418
+ entry: path.resolve(pkgDir, entry)
1419
+ };
1420
+ }
1421
+ const parent = path.dirname(dir);
1422
+ if (parent === dir) return null;
1423
+ dir = parent;
1424
+ }
1425
+ }
1426
+ async function importWorkspacePackage(userCwd, name) {
1427
+ const resolved = resolveWorkspacePackage(userCwd, name);
1428
+ if (!resolved) return null;
1429
+ return await import(pathToFileURL(resolved.entry).href);
1430
+ }
1431
+ //#endregion
1432
+ //#region src/agent/providers/claude.ts
1433
+ const CLAUDE_SDK_PACKAGE = "@anthropic-ai/claude-agent-sdk";
1434
+ const CLAUDE_EFFORTS = [
1435
+ "low",
1436
+ "medium",
1437
+ "high",
1438
+ "xhigh",
1439
+ "max"
1440
+ ];
1441
+ const CLAUDE_MODELS = [
1442
+ {
1443
+ id: "opus",
1444
+ label: "Opus",
1445
+ efforts: CLAUDE_EFFORTS
1446
+ },
1447
+ {
1448
+ id: "sonnet",
1449
+ label: "Sonnet",
1450
+ efforts: CLAUDE_EFFORTS
1451
+ },
1452
+ {
1453
+ id: "haiku",
1454
+ label: "Haiku",
1455
+ efforts: []
1456
+ }
1457
+ ];
1458
+ const EDIT_TOOLS = /* @__PURE__ */ new Set([
1459
+ "Edit",
1460
+ "MultiEdit",
1461
+ "Write",
1462
+ "NotebookEdit"
1463
+ ]);
1464
+ function claudeEffort(effort) {
1465
+ return effort && effort !== "minimal" ? effort : void 0;
1466
+ }
1467
+ function describeClaudeTool(name, input, cwd) {
1468
+ const file = relativeToCwd(cwd, input.file_path ?? input.path ?? input.notebook_path);
1469
+ switch (name) {
1470
+ case "Read": return {
1471
+ title: "Read",
1472
+ detail: file
1473
+ };
1474
+ case "Edit":
1475
+ case "MultiEdit":
1476
+ case "Write":
1477
+ case "NotebookEdit": return {
1478
+ title: name === "Write" ? "Write" : "Edit",
1479
+ detail: file
1480
+ };
1481
+ case "Bash": return {
1482
+ title: "Run command",
1483
+ detail: clipDetail(input.command)
1484
+ };
1485
+ case "Glob":
1486
+ case "Grep": return {
1487
+ title: "Search",
1488
+ detail: clipDetail(input.pattern)
1489
+ };
1490
+ case "WebFetch": return {
1491
+ title: "Fetch",
1492
+ detail: clipDetail(input.url)
1493
+ };
1494
+ case "WebSearch": return {
1495
+ title: "Web search",
1496
+ detail: clipDetail(input.query)
1497
+ };
1498
+ case "Skill": return {
1499
+ title: "Skill",
1500
+ detail: clipDetail(input.skill ?? input.name)
1501
+ };
1502
+ case "Task": return {
1503
+ title: "Subagent",
1504
+ detail: clipDetail(input.description)
1505
+ };
1506
+ case "AskUserQuestion": return {
1507
+ title: "Question",
1508
+ detail: null
1509
+ };
1510
+ case "TodoWrite": return {
1511
+ title: "Plan",
1512
+ detail: null
1513
+ };
1514
+ default: return {
1515
+ title: name,
1516
+ detail: clipDetail(input)
1517
+ };
1518
+ }
1519
+ }
1520
+ function createClaudeMapper(emit, cwd) {
1521
+ let counter = 0;
1522
+ const nextId = () => `t-${Date.now().toString(36)}-${(counter++).toString(36)}`;
1523
+ const textByIndex = /* @__PURE__ */ new Map();
1524
+ const openTextIds = [];
1525
+ let resultSeen = false;
1526
+ const handleBlocks = (blocks) => {
1527
+ for (const block of blocks) if (block.type === "text") {
1528
+ const { text } = block;
1529
+ const id = openTextIds.shift();
1530
+ if (id) emit({
1531
+ type: "text-end",
1532
+ id,
1533
+ text
399
1534
  });
400
1535
  else if (text.trim()) {
401
1536
  const fresh = nextId();
@@ -854,14 +1989,14 @@ function createProviders() {
854
1989
  const MAX_SESSIONS = 30;
855
1990
  const MAX_ITEMS_PER_SESSION = 400;
856
1991
  const SAVE_DEBOUNCE_MS = 150;
857
- const TITLE_MAX$1 = 60;
1992
+ const TITLE_MAX = 60;
858
1993
  function newId(prefix) {
859
1994
  return `${prefix}-${randomBytes(6).toString("hex")}`;
860
1995
  }
861
1996
  function titleFromPrompt(text) {
862
1997
  const line = text.split("\n").map((l) => l.trim()).find((l) => l.length > 0);
863
1998
  if (!line) return "Untitled";
864
- return line.length > TITLE_MAX$1 ? `${line.slice(0, 59)}…` : line;
1999
+ return line.length > TITLE_MAX ? `${line.slice(0, 59)}…` : line;
865
2000
  }
866
2001
  function readPersisted(file) {
867
2002
  if (!existsSync(file)) return [];
@@ -931,7 +2066,7 @@ function createSessionStore(opts) {
931
2066
  });
932
2067
  await fs.rename(tmp, file);
933
2068
  } catch (err) {
934
- console.error("[lemonriver] failed to save agent sessions:", err);
2069
+ console.error("[open-slide] failed to save agent sessions:", err);
935
2070
  await fs.rm(tmp, { force: true }).catch(() => {});
936
2071
  }
937
2072
  };
@@ -1306,7 +2441,7 @@ function createAgentRunner(opts) {
1306
2441
  sessionId,
1307
2442
  userItemId
1308
2443
  })).catch((err) => {
1309
- console.error("[lemonriver] agent turn-end handler failed:", err);
2444
+ console.error("[open-slide] agent turn-end handler failed:", err);
1310
2445
  });
1311
2446
  };
1312
2447
  const prompt = buildTurnPrompt(promptText, context);
@@ -1352,397 +2487,116 @@ function createAgentRunner(opts) {
1352
2487
  }
1353
2488
  if (prompt.kind === "question" && "answers" in payload) {
1354
2489
  prompt.resolve(payload.answers);
1355
- return true;
1356
- }
1357
- if (prompt.kind === "permission" && "allow" in payload) {
1358
- prompt.resolve(payload.allow);
1359
- return true;
1360
- }
1361
- return false;
1362
- }
1363
- function answerInNextTurn(sessionId, itemId, payload, next) {
1364
- const item = store.get(sessionId)?.items.find((i) => i.id === itemId);
1365
- if (item?.kind !== "question" || item.status !== "pending" || running.has(sessionId)) return false;
1366
- if (!("answers" in payload) && !("cancel" in payload)) return false;
1367
- const answers = "answers" in payload ? payload.answers : null;
1368
- store.updateItem(sessionId, itemId, "question", {
1369
- answers,
1370
- status: answers ? "answered" : "cancelled"
1371
- });
1372
- const previous = {
1373
- ...lastOptions.get(sessionId),
1374
- ...next
1375
- };
1376
- const context = previous.context ? {
1377
- ...previous.context,
1378
- newDeck: void 0
1379
- } : void 0;
1380
- send(sessionId, {
1381
- ...previous,
1382
- context,
1383
- text: answersPrompt(item.questions, answers),
1384
- answering: itemId
1385
- }).catch((err) => {
1386
- console.error("[lemonriver] agent turn failed:", err);
1387
- });
1388
- return true;
1389
- }
1390
- function stopAll() {
1391
- for (const id of Array.from(running.keys())) stop(id);
1392
- }
1393
- return {
1394
- send,
1395
- stop,
1396
- respond,
1397
- isRunning,
1398
- stopAll
1399
- };
1400
- }
1401
- //#endregion
1402
- //#region src/agent/status.ts
1403
- const INSTALL_TIMEOUT_MS = 6e5;
1404
- async function providerStatus(userCwd, provider) {
1405
- const sdk = resolveWorkspacePackage(userCwd, provider.sdkPackage);
1406
- const cliPath = findOnPath(provider.cliCommand);
1407
- const [cliVersion, models] = await Promise.all([cliPath ? commandVersion(cliPath) : null, provider.models()]);
1408
- return {
1409
- id: provider.id,
1410
- name: provider.name,
1411
- sdkPackage: provider.sdkPackage,
1412
- sdkVersion: sdk?.version ?? null,
1413
- cliCommand: provider.cliCommand,
1414
- cliFound: cliPath !== null,
1415
- cliVersion,
1416
- ready: sdk !== null,
1417
- models
1418
- };
1419
- }
1420
- async function agentStatus(userCwd, providers, packageManager) {
1421
- return {
1422
- enabled: true,
1423
- packageManager,
1424
- providers: await Promise.all(Object.values(providers).map((provider) => providerStatus(userCwd, provider)))
1425
- };
1426
- }
1427
- function installCommandFor(packageManager, pkg) {
1428
- switch (packageManager) {
1429
- case "pnpm": return {
1430
- cmd: "pnpm",
1431
- args: [
1432
- "add",
1433
- "-D",
1434
- pkg
1435
- ]
1436
- };
1437
- case "yarn": return {
1438
- cmd: "yarn",
1439
- args: [
1440
- "add",
1441
- "-D",
1442
- pkg
1443
- ]
1444
- };
1445
- case "bun": return {
1446
- cmd: "bun",
1447
- args: [
1448
- "add",
1449
- "-d",
1450
- pkg
1451
- ]
1452
- };
1453
- case "npm": return {
1454
- cmd: "npm",
1455
- args: [
1456
- "install",
1457
- "-D",
1458
- pkg
1459
- ]
1460
- };
1461
- }
1462
- }
1463
- function installSdk(packageManager, pkg, cwd) {
1464
- return runCommand(installCommandFor(packageManager, pkg), cwd, INSTALL_TIMEOUT_MS);
1465
- }
1466
- //#endregion
1467
- //#region src/vite/recent-writes.ts
1468
- const recentWrites = /* @__PURE__ */ new Map();
1469
- /** Record that `file` was just written by us. */
1470
- function recordWrite(file, now = Date.now()) {
1471
- recentWrites.set(file, now);
1472
- }
1473
- /**
1474
- * True if `file` was recorded within the recent-write window. Expired entries
1475
- * are pruned so a stale path can no longer suppress a later genuine edit.
1476
- */
1477
- function hasRecentWrite(file, now = Date.now()) {
1478
- const ts = recentWrites.get(file);
1479
- if (ts == null) return false;
1480
- if (now - ts < 1500) return true;
1481
- recentWrites.delete(file);
1482
- return false;
1483
- }
1484
- //#endregion
1485
- //#region src/vite/open-slide-plugin.ts
1486
- const SLIDES_VMOD = "virtual:open-slide/slides";
1487
- const CONFIG_VMOD = "virtual:open-slide/config";
1488
- const FOLDERS_VMOD = "virtual:open-slide/folders";
1489
- function resolved$1(id) {
1490
- return `\0${id}`;
1491
- }
1492
- async function findSlides(userCwd, slidesDir) {
1493
- const abs = path.resolve(userCwd, slidesDir);
1494
- if (!existsSync(abs)) return [];
1495
- return (await fg("*/index.{tsx,jsx,ts,js}", {
1496
- cwd: abs,
1497
- absolute: true,
1498
- onlyFiles: true
1499
- })).sort();
1500
- }
1501
- function toId(absFile, slidesRoot) {
1502
- return path.relative(slidesRoot, absFile).split(path.sep)[0];
1503
- }
1504
- const META_THEME_RE = /(?:^|[\s,{])theme\s*:\s*['"]([^'"]+)['"]/;
1505
- const META_CREATED_AT_RE = /(?:^|[\s,{])createdAt\s*:\s*['"]([^'"]+)['"]/;
1506
- function extractMeta(src) {
1507
- const empty = {
1508
- theme: null,
1509
- createdAt: null
1510
- };
1511
- const metaStart = src.search(/export\s+const\s+meta\b/);
1512
- if (metaStart === -1) return empty;
1513
- const eqIdx = src.indexOf("=", metaStart);
1514
- if (eqIdx === -1) return empty;
1515
- const openBrace = src.indexOf("{", eqIdx);
1516
- if (openBrace === -1) return empty;
1517
- let depth = 0;
1518
- let closeBrace = -1;
1519
- for (let i = openBrace; i < src.length; i++) {
1520
- const ch = src[i];
1521
- if (ch === "{") depth++;
1522
- else if (ch === "}") {
1523
- depth--;
1524
- if (depth === 0) {
1525
- closeBrace = i;
1526
- break;
1527
- }
1528
- }
1529
- }
1530
- if (closeBrace === -1) return empty;
1531
- const body = src.slice(openBrace + 1, closeBrace);
1532
- const themeMatch = body.match(META_THEME_RE);
1533
- const createdAtMatch = body.match(META_CREATED_AT_RE);
1534
- return {
1535
- theme: themeMatch ? themeMatch[1] : null,
1536
- createdAt: createdAtMatch ? createdAtMatch[1] : null
1537
- };
1538
- }
1539
- async function readSlideMeta(abs) {
1540
- try {
1541
- return extractMeta(await fs.readFile(abs, "utf8"));
1542
- } catch {
1543
- return {
1544
- theme: null,
1545
- createdAt: null
1546
- };
2490
+ return true;
2491
+ }
2492
+ if (prompt.kind === "permission" && "allow" in payload) {
2493
+ prompt.resolve(payload.allow);
2494
+ return true;
2495
+ }
2496
+ return false;
1547
2497
  }
1548
- }
1549
- function parseCreatedAtMs(iso) {
1550
- if (!iso) return null;
1551
- const ms = Date.parse(iso);
1552
- return Number.isFinite(ms) ? ms : null;
1553
- }
1554
- const warnedInvalidSlideIds = /* @__PURE__ */ new Set();
1555
- async function generateSlidesModule(files, slidesRoot, isDev) {
1556
- const scanned = await Promise.all(files.map(async (abs) => {
1557
- const id = toId(abs, slidesRoot);
1558
- const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
1559
- const meta = await readSlideMeta(abs);
1560
- return {
1561
- id,
1562
- importPath,
1563
- theme: meta.theme,
1564
- createdAt: parseCreatedAtMs(meta.createdAt)
2498
+ function answerInNextTurn(sessionId, itemId, payload, next) {
2499
+ const item = store.get(sessionId)?.items.find((i) => i.id === itemId);
2500
+ if (item?.kind !== "question" || item.status !== "pending" || running.has(sessionId)) return false;
2501
+ if (!("answers" in payload) && !("cancel" in payload)) return false;
2502
+ const answers = "answers" in payload ? payload.answers : null;
2503
+ store.updateItem(sessionId, itemId, "question", {
2504
+ answers,
2505
+ status: answers ? "answered" : "cancelled"
2506
+ });
2507
+ const previous = {
2508
+ ...lastOptions.get(sessionId),
2509
+ ...next
1565
2510
  };
1566
- }));
1567
- const entries = scanned.filter((e) => SLIDE_ID_RE.test(e.id));
1568
- const ignored = scanned.filter((e) => !SLIDE_ID_RE.test(e.id)).map((e) => e.id);
1569
- const ids = JSON.stringify(entries.map((e) => e.id).sort());
1570
- const themesMap = {};
1571
- const createdAtMap = {};
1572
- for (const e of entries) {
1573
- if (e.theme) themesMap[e.id] = e.theme;
1574
- if (e.createdAt !== null) createdAtMap[e.id] = e.createdAt;
2511
+ const context = previous.context ? {
2512
+ ...previous.context,
2513
+ newDeck: void 0
2514
+ } : void 0;
2515
+ send(sessionId, {
2516
+ ...previous,
2517
+ context,
2518
+ text: answersPrompt(item.questions, answers),
2519
+ answering: itemId
2520
+ }).catch((err) => {
2521
+ console.error("[open-slide] agent turn failed:", err);
2522
+ });
2523
+ return true;
2524
+ }
2525
+ function stopAll() {
2526
+ for (const id of Array.from(running.keys())) stop(id);
1575
2527
  }
1576
- const themesJson = JSON.stringify(themesMap);
1577
- const createdAtJson = JSON.stringify(createdAtMap);
1578
- const importTokens = JSON.stringify(Object.fromEntries(entries.map((e) => [e.id, 0])));
1579
2528
  return {
1580
- code: `// virtual:open-slide/slides — generated
1581
- export const slideIds = ${ids};
1582
- export const slideThemes = ${themesJson};
1583
- export const slideCreatedAt = ${createdAtJson};
1584
- ${isDev ? `
1585
- const slideImportTokens = ${importTokens};
1586
- if (import.meta.hot) {
1587
- import.meta.hot.on('open-slide:slide-changed', (data) => {
1588
- const ids = Array.isArray(data?.slideIds) ? data.slideIds : [];
1589
- const token = Date.now();
1590
- for (const id of ids) {
1591
- if (Object.prototype.hasOwnProperty.call(slideImportTokens, id)) slideImportTokens[id] = token;
1592
- }
1593
- });
1594
- }
1595
- ` : ""}
1596
-
1597
- export async function loadSlide(id) {
1598
- switch (id) {
1599
- ${entries.map((e) => {
1600
- const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(`${e.importPath}?t=`)} + slideImportTokens[${JSON.stringify(e.id)}])` : `import(${JSON.stringify(e.importPath)})`;
1601
- return ` case ${JSON.stringify(e.id)}: return ${importExpr};`;
1602
- }).join("\n")}
1603
- default: throw new Error('Slide not found: ' + id);
1604
- }
1605
- }
1606
- `,
1607
- ignored
2529
+ send,
2530
+ stop,
2531
+ respond,
2532
+ isRunning,
2533
+ stopAll
1608
2534
  };
1609
2535
  }
1610
- function lemonRiverPlugin(opts) {
1611
- const { userCwd, config, coreVersion } = opts;
1612
- const slidesDir = config.slidesDir ?? "slides";
1613
- const slidesRoot = path.resolve(userCwd, slidesDir);
1614
- const manifestPath = foldersManifestPath(slidesRoot);
1615
- let isDev = false;
1616
- const slideIdForEntry = (p) => {
1617
- const rel = path.relative(slidesRoot, p);
1618
- if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
1619
- const parts = rel.split(path.sep);
1620
- if (parts.length !== 2) return null;
1621
- if (!/^index\.(tsx|jsx|ts|js)$/.test(parts[1])) return null;
1622
- return parts[0];
1623
- };
1624
- let slideChangeTimer = null;
1625
- const pendingSlideChanges = /* @__PURE__ */ new Set();
1626
- const queueSlideChanged = (server, id) => {
1627
- pendingSlideChanges.add(id);
1628
- if (slideChangeTimer) clearTimeout(slideChangeTimer);
1629
- slideChangeTimer = setTimeout(() => {
1630
- slideChangeTimer = null;
1631
- const mod = server.moduleGraph.getModuleById(resolved$1(SLIDES_VMOD));
1632
- if (mod) server.moduleGraph.invalidateModule(mod);
1633
- const slideIds = Array.from(pendingSlideChanges);
1634
- pendingSlideChanges.clear();
1635
- server.ws.send({
1636
- type: "custom",
1637
- event: "open-slide:slide-changed",
1638
- data: { slideIds }
1639
- });
1640
- }, 100);
2536
+ //#endregion
2537
+ //#region src/agent/status.ts
2538
+ const INSTALL_TIMEOUT_MS = 6e5;
2539
+ async function providerStatus(userCwd, provider) {
2540
+ const sdk = resolveWorkspacePackage(userCwd, provider.sdkPackage);
2541
+ const cliPath = findOnPath(provider.cliCommand);
2542
+ const [cliVersion, models] = await Promise.all([cliPath ? commandVersion(cliPath) : null, provider.models()]);
2543
+ return {
2544
+ id: provider.id,
2545
+ name: provider.name,
2546
+ sdkPackage: provider.sdkPackage,
2547
+ sdkVersion: sdk?.version ?? null,
2548
+ cliCommand: provider.cliCommand,
2549
+ cliFound: cliPath !== null,
2550
+ cliVersion,
2551
+ ready: sdk !== null,
2552
+ models
1641
2553
  };
2554
+ }
2555
+ async function agentStatus(userCwd, providers, packageManager) {
1642
2556
  return {
1643
- name: "lemonriver",
1644
- config(_c, env) {
1645
- isDev = env.command === "serve";
1646
- },
1647
- resolveId(id) {
1648
- if (id === SLIDES_VMOD) return resolved$1(SLIDES_VMOD);
1649
- if (id === CONFIG_VMOD) return resolved$1(CONFIG_VMOD);
1650
- if (id === FOLDERS_VMOD) return resolved$1(FOLDERS_VMOD);
1651
- return null;
1652
- },
1653
- async load(id) {
1654
- if (id === resolved$1(SLIDES_VMOD)) {
1655
- const { code, ignored } = await generateSlidesModule(await findSlides(userCwd, slidesDir), slidesRoot, isDev);
1656
- for (const slideId of ignored) {
1657
- if (warnedInvalidSlideIds.has(slideId)) continue;
1658
- warnedInvalidSlideIds.add(slideId);
1659
- this.warn(`Ignoring slide folder "${slideId}": slide ids must match ${SLIDE_ID_RE} (lowercase/uppercase letters, digits, "-", "_"). Rename the folder under "${slidesDir}/" to a kebab-case id so it appears in the browser and can be moved into folders.`);
1660
- }
1661
- return code;
1662
- }
1663
- if (id === resolved$1(CONFIG_VMOD)) {
1664
- const userBuild = config.build ?? {};
1665
- const buildResolved = isDev ? {
1666
- showSlideBrowser: true,
1667
- showSlideUi: true,
1668
- allowHtmlDownload: true
1669
- } : {
1670
- showSlideBrowser: userBuild.showSlideBrowser ?? true,
1671
- showSlideUi: userBuild.showSlideUi ?? true,
1672
- allowHtmlDownload: userBuild.allowHtmlDownload ?? true
1673
- };
1674
- const resolvedConfig = {
1675
- ...config,
1676
- build: buildResolved,
1677
- version: coreVersion
1678
- };
1679
- return `export default ${JSON.stringify(resolvedConfig)};\n`;
1680
- }
1681
- if (id === resolved$1(FOLDERS_VMOD)) {
1682
- const manifest = await readManifest(manifestPath);
1683
- return `export default ${JSON.stringify(manifest)};\n`;
1684
- }
1685
- return null;
1686
- },
1687
- handleHotUpdate(ctx) {
1688
- const slideId = slideIdForEntry(ctx.file);
1689
- if (!slideId) return;
1690
- if (hasRecentWrite(ctx.file)) return [];
1691
- queueSlideChanged(ctx.server, slideId);
1692
- return [];
1693
- },
1694
- configureServer(server) {
1695
- const isSlideEntry = (p) => slideIdForEntry(p) !== null;
1696
- let reloadTimer = null;
1697
- const reload = () => {
1698
- if (reloadTimer) clearTimeout(reloadTimer);
1699
- reloadTimer = setTimeout(() => {
1700
- reloadTimer = null;
1701
- const mod = server.moduleGraph.getModuleById(resolved$1(SLIDES_VMOD));
1702
- if (mod) server.moduleGraph.invalidateModule(mod);
1703
- server.ws.send({ type: "full-reload" });
1704
- }, 150);
1705
- };
1706
- if (existsSync(slidesRoot)) server.watcher.add(slidesRoot);
1707
- server.watcher.on("add", (p) => {
1708
- if (isSlideEntry(p) && !hasRecentWrite(p)) reload();
1709
- });
1710
- server.watcher.on("unlink", (p) => {
1711
- if (isSlideEntry(p) && !hasRecentWrite(p)) reload();
1712
- });
1713
- let foldersTimer = null;
1714
- const invalidateFolders = () => {
1715
- if (foldersTimer) clearTimeout(foldersTimer);
1716
- foldersTimer = setTimeout(() => {
1717
- foldersTimer = null;
1718
- const mod = server.moduleGraph.getModuleById(resolved$1(FOLDERS_VMOD));
1719
- if (mod) server.moduleGraph.invalidateModule(mod);
1720
- }, 100);
1721
- };
1722
- server.watcher.add(manifestPath);
1723
- server.watcher.on("change", (p) => {
1724
- if (p === manifestPath) invalidateFolders();
1725
- });
1726
- server.watcher.on("add", (p) => {
1727
- if (p === manifestPath) invalidateFolders();
1728
- });
1729
- server.watcher.on("unlink", (p) => {
1730
- if (p === manifestPath) invalidateFolders();
1731
- });
1732
- }
2557
+ enabled: true,
2558
+ packageManager,
2559
+ providers: await Promise.all(Object.values(providers).map((provider) => providerStatus(userCwd, provider)))
1733
2560
  };
1734
2561
  }
1735
- function invalidateSlidesModule(server) {
1736
- const mod = server.moduleGraph.getModuleById(resolved$1(SLIDES_VMOD));
1737
- if (mod) server.moduleGraph.invalidateModule(mod);
2562
+ function installCommandFor(packageManager, pkg) {
2563
+ switch (packageManager) {
2564
+ case "pnpm": return {
2565
+ cmd: "pnpm",
2566
+ args: [
2567
+ "add",
2568
+ "-D",
2569
+ pkg
2570
+ ]
2571
+ };
2572
+ case "yarn": return {
2573
+ cmd: "yarn",
2574
+ args: [
2575
+ "add",
2576
+ "-D",
2577
+ pkg
2578
+ ]
2579
+ };
2580
+ case "bun": return {
2581
+ cmd: "bun",
2582
+ args: [
2583
+ "add",
2584
+ "-d",
2585
+ pkg
2586
+ ]
2587
+ };
2588
+ case "npm": return {
2589
+ cmd: "npm",
2590
+ args: [
2591
+ "install",
2592
+ "-D",
2593
+ pkg
2594
+ ]
2595
+ };
2596
+ }
1738
2597
  }
1739
- async function loadUserConfig(userCwd) {
1740
- const file = CONFIG_FILES.map((name) => path.join(userCwd, name)).find((p) => existsSync(p));
1741
- if (!file) return {};
1742
- return (await loadConfigFromFile({
1743
- command: "serve",
1744
- mode: "development"
1745
- }, file, userCwd, "silent"))?.config ?? {};
2598
+ function installSdk(packageManager, pkg, cwd) {
2599
+ return runCommand(installCommandFor(packageManager, pkg), cwd, INSTALL_TIMEOUT_MS);
1746
2600
  }
1747
2601
  //#endregion
1748
2602
  //#region src/vite/routes/agent.ts
@@ -3456,239 +4310,6 @@ function registerAssetRoutes(server, ctx) {
3456
4310
  });
3457
4311
  }
3458
4312
  //#endregion
3459
- //#region src/editing/page-entries.ts
3460
- /**
3461
- * The deck's page array as written, one entry per page, with whitespace
3462
- * collapsed so reformatting the file keeps every entry the same. `null` when
3463
- * the array cannot be read one entry per page: a spread stands for any number
3464
- * of pages, and a default export that is not an array literal hides them.
3465
- */
3466
- function defaultExportEntriesInSource(source) {
3467
- let body;
3468
- try {
3469
- body = parse(source, {
3470
- sourceType: "module",
3471
- plugins: ["typescript", "jsx"],
3472
- errorRecovery: true
3473
- }).program.body;
3474
- } catch {
3475
- return null;
3476
- }
3477
- for (const node of body) {
3478
- if (node.type !== "ExportDefaultDeclaration") continue;
3479
- let inner = node.declaration;
3480
- while (inner.type === "TSAsExpression" || inner.type === "TSSatisfiesExpression") inner = inner.expression;
3481
- if (inner.type !== "ArrayExpression") return null;
3482
- const entries = [];
3483
- for (const element of inner.elements) {
3484
- if (!element || element.type === "SpreadElement") return null;
3485
- if (element.start == null || element.end == null) return null;
3486
- entries.push(source.slice(element.start, element.end).replace(/\s+/g, " "));
3487
- }
3488
- return entries;
3489
- }
3490
- return null;
3491
- }
3492
- //#endregion
3493
- //#region src/files/board-structure.ts
3494
- function sanitizeStructure(parsed) {
3495
- if (!parsed || typeof parsed !== "object") return null;
3496
- const columns = parsed.columns;
3497
- if (!Array.isArray(columns)) return null;
3498
- const cleaned = columns.flatMap((column) => {
3499
- if (!column || typeof column !== "object") return [];
3500
- const { title, size } = column;
3501
- if (typeof size !== "number" || !Number.isInteger(size) || size < 0) return [];
3502
- return [{
3503
- title: typeof title === "string" ? title : "",
3504
- size
3505
- }];
3506
- });
3507
- return cleaned.length > 0 ? { columns: cleaned } : null;
3508
- }
3509
- /**
3510
- * Keeps a stored structure usable after the deck changed behind the board's
3511
- * back: pages added outside the board join the last column, and pages deleted
3512
- * outside it come off the end.
3513
- */
3514
- function reconcileColumns(columns, pageCount) {
3515
- if (pageCount <= 0) return [];
3516
- const kept = columns.map((column) => ({ ...column }));
3517
- if (kept.length === 0) return [{
3518
- title: "",
3519
- size: pageCount
3520
- }];
3521
- let total = kept.reduce((sum, column) => sum + column.size, 0);
3522
- if (total === pageCount) return kept;
3523
- if (total < pageCount) {
3524
- kept[kept.length - 1].size += pageCount - total;
3525
- return kept;
3526
- }
3527
- for (let i = kept.length - 1; i >= 0 && total > pageCount; i--) {
3528
- const drop = Math.min(kept[i].size, total - pageCount);
3529
- kept[i].size -= drop;
3530
- total -= drop;
3531
- }
3532
- while (kept.length > 1 && kept[kept.length - 1].size === 0) kept.pop();
3533
- return kept;
3534
- }
3535
- //#endregion
3536
- //#region src/files/board.ts
3537
- function boardStructurePath(userCwd, slideId) {
3538
- return path.join(userCwd, ".open-slide", "board", `${slideId}.json`);
3539
- }
3540
- /** The whole board file. Columns, cards and links each own one field of it. */
3541
- async function readBoardFile(file) {
3542
- try {
3543
- const parsed = JSON.parse(await fs.readFile(file, "utf8"));
3544
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
3545
- } catch {
3546
- return {};
3547
- }
3548
- }
3549
- async function readBoardStructure(file) {
3550
- return sanitizeStructure(await readBoardFile(file));
3551
- }
3552
- const pending = /* @__PURE__ */ new Map();
3553
- /**
3554
- * Rewrites the fields `fields` names and keeps every other one. Updates to the
3555
- * same file run one after another: the columns and the cards are saved by
3556
- * separate requests, and two read-modify-writes racing would drop one of them.
3557
- */
3558
- function updateBoardFile(file, fields) {
3559
- const run = (pending.get(file) ?? Promise.resolve()).catch(() => void 0).then(async () => {
3560
- const current = await readBoardFile(file);
3561
- await fs.mkdir(path.dirname(file), { recursive: true });
3562
- await fs.writeFile(file, `${JSON.stringify({
3563
- ...current,
3564
- ...fields
3565
- }, null, 2)}\n`, "utf8");
3566
- });
3567
- pending.set(file, run);
3568
- run.finally(() => {
3569
- if (pending.get(file) === run) pending.delete(file);
3570
- }).catch(() => void 0);
3571
- return run;
3572
- }
3573
- async function writeBoardStructure(file, structure) {
3574
- await updateBoardFile(file, { columns: structure.columns });
3575
- }
3576
- //#endregion
3577
- //#region src/files/board-cards.ts
3578
- const CARD_STATUSES = [
3579
- "todo",
3580
- "doing",
3581
- "review",
3582
- "done"
3583
- ];
3584
- const TITLE_MAX = 80;
3585
- const MEMO_MAX = 2e3;
3586
- function isCardStatus(value) {
3587
- return typeof value === "string" && CARD_STATUSES.includes(value);
3588
- }
3589
- function cleanCard(raw) {
3590
- if (!raw || typeof raw !== "object") return null;
3591
- const { title, status, memo } = raw;
3592
- const card = {};
3593
- if (typeof title === "string" && title.trim()) card.title = title.trim().slice(0, TITLE_MAX);
3594
- if (isCardStatus(status)) card.status = status;
3595
- if (typeof memo === "string" && memo.trim()) card.memo = memo.trim().slice(0, MEMO_MAX);
3596
- return Object.keys(card).length > 0 ? card : null;
3597
- }
3598
- function sanitizeCards(raw) {
3599
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
3600
- const cards = {};
3601
- for (const [key, value] of Object.entries(raw)) {
3602
- const card = cleanCard(value);
3603
- if (key && card) cards[key] = card;
3604
- }
3605
- return cards;
3606
- }
3607
- const sameLink = (link, a, b) => link.a === a && link.b === b || link.a === b && link.b === a;
3608
- function linkCards(links, a, b) {
3609
- if (!a || !b || a === b || links.some((link) => sameLink(link, a, b))) return links;
3610
- return [...links, {
3611
- a,
3612
- b
3613
- }];
3614
- }
3615
- function sanitizeLinks(raw) {
3616
- if (!Array.isArray(raw)) return [];
3617
- return raw.reduce((links, item) => {
3618
- const { a, b } = item ?? {};
3619
- return typeof a === "string" && typeof b === "string" ? linkCards(links, a, b) : links;
3620
- }, []);
3621
- }
3622
- //#endregion
3623
- //#region src/vite/routes/board.ts
3624
- function registerBoardRoutes(server, ctx) {
3625
- server.middlewares.use("/__board", async (req, res, next) => {
3626
- const url = new URL(req.url ?? "/", "http://local");
3627
- const method = req.method ?? "GET";
3628
- try {
3629
- if (method === "GET" && url.pathname === "/") {
3630
- const slideId = url.searchParams.get("slideId") ?? "";
3631
- if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
3632
- const stored = await readBoardStructure(boardStructurePath(ctx.userCwd, slideId));
3633
- if (!stored) return json(res, 200, { columns: null });
3634
- const pages = Number(url.searchParams.get("pages") ?? "0");
3635
- const columns = pages > 0 ? reconcileColumns(stored.columns, pages) : stored.columns;
3636
- return json(res, 200, { columns });
3637
- }
3638
- if (method === "PUT" && url.pathname === "/") {
3639
- const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
3640
- if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
3641
- const body = await readBody(req);
3642
- const slideId = body.slideId ?? "";
3643
- if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
3644
- if (!Array.isArray(body.columns)) return json(res, 400, { error: "missing columns" });
3645
- const structure = { columns: body.columns.flatMap((column) => {
3646
- const { title, size } = column ?? {};
3647
- if (typeof size !== "number" || !Number.isInteger(size) || size < 0) return [];
3648
- return [{
3649
- title: typeof title === "string" ? title : "",
3650
- size
3651
- }];
3652
- }) };
3653
- if (structure.columns.length === 0) return json(res, 400, { error: "no usable columns" });
3654
- await writeBoardStructure(boardStructurePath(ctx.userCwd, slideId), structure);
3655
- return json(res, 200, { ok: true });
3656
- }
3657
- if (method === "GET" && url.pathname === "/cards") {
3658
- const slideId = url.searchParams.get("slideId") ?? "";
3659
- if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
3660
- const stored = await readBoardFile(boardStructurePath(ctx.userCwd, slideId));
3661
- return json(res, 200, {
3662
- cards: sanitizeCards(stored.cards),
3663
- links: sanitizeLinks(stored.links)
3664
- });
3665
- }
3666
- if (method === "PUT" && url.pathname === "/cards") {
3667
- const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
3668
- if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
3669
- const body = await readBody(req);
3670
- const slideId = body.slideId ?? "";
3671
- if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
3672
- await updateBoardFile(boardStructurePath(ctx.userCwd, slideId), {
3673
- cards: sanitizeCards(body.cards),
3674
- links: sanitizeLinks(body.links)
3675
- });
3676
- return json(res, 200, { ok: true });
3677
- }
3678
- if (method === "GET" && url.pathname === "/entries") {
3679
- const slideId = url.searchParams.get("slideId") ?? "";
3680
- const entry = resolveSlideEntryPath(ctx, slideId);
3681
- if (!entry) return json(res, 400, { error: "invalid slideId" });
3682
- const source = await readSlideSource(entry);
3683
- return json(res, 200, { entries: source ? defaultExportEntriesInSource(source) : null });
3684
- }
3685
- next();
3686
- } catch (err) {
3687
- json(res, 500, { error: String(err.message ?? err) });
3688
- }
3689
- });
3690
- }
3691
- //#endregion
3692
4313
  //#region src/editing/comments.ts
3693
4314
  const MARKER_RE = /\{\/\*\s*@slide-comment\s+id="(c-[a-f0-9]+)"\s+ts="([^"]+)"\s+text="([A-Za-z0-9_-]+={0,2})"\s*\*\/\}/;
3694
4315
  function b64urlEncode(s) {
@@ -4375,9 +4996,7 @@ function registerSlideRoutes(server, ctx) {
4375
4996
  if (!SLIDE_ID_RE.test(slideId)) return json(res, 400, { error: "invalid slideId" });
4376
4997
  if (!Number.isInteger(pageIndex) || pageIndex < 0) return json(res, 400, { error: "invalid page index" });
4377
4998
  const isDelete = method === "DELETE" && !op;
4378
- const isDuplicate = method === "POST" && op === "duplicate";
4379
- const isInsert = method === "POST" && op === "insert";
4380
- if (!isDelete && !isDuplicate && !isInsert) return next();
4999
+ if (!isDelete && !(method === "POST" && op === "duplicate")) return next();
4381
5000
  const requestCheck = validateMutationRequest(req);
4382
5001
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
4383
5002
  const entry = resolveSlideEntry(ctx.slidesRoot, slideId);
@@ -4388,10 +5007,10 @@ function registerSlideRoutes(server, ctx) {
4388
5007
  } catch {
4389
5008
  return json(res, 404, { error: "slide not found" });
4390
5009
  }
4391
- const updated = isDelete ? removePageFromDefaultExportInSource(source, pageIndex) : isInsert ? insertBlankPageInDefaultExportInSource(source, pageIndex) : duplicatePageInDefaultExportInSource(source, pageIndex);
4392
- if (updated === null) return json(res, 422, { error: isDelete ? "could not delete page — index out of range or default export is not an array" : isInsert ? "could not insert a page — index out of range or default export is not an array" : "could not duplicate page — index out of range or default export is not an array" });
4393
- const withNotes = isDelete ? removeNotesElementInSource(updated, pageIndex) : isInsert ? insertNotesElementInSource(updated, pageIndex) : duplicateNotesElementInSource(updated, pageIndex);
4394
- if (withNotes === null) return json(res, 422, { error: isDelete ? "could not delete page — `notes` export has an unexpected shape" : isInsert ? "could not insert a page — `notes` export has an unexpected shape" : "could not duplicate page — `notes` export has an unexpected shape" });
5010
+ const updated = isDelete ? removePageFromDefaultExportInSource(source, pageIndex) : duplicatePageInDefaultExportInSource(source, pageIndex);
5011
+ if (updated === null) return json(res, 422, { error: isDelete ? "could not delete page — index out of range or default export is not an array" : "could not duplicate page — index out of range or default export is not an array" });
5012
+ const withNotes = isDelete ? removeNotesElementInSource(updated, pageIndex) : duplicateNotesElementInSource(updated, pageIndex);
5013
+ if (withNotes === null) return json(res, 422, { error: isDelete ? "could not delete page — `notes` export has an unexpected shape" : "could not duplicate page — `notes` export has an unexpected shape" });
4395
5014
  if (withNotes !== source) await fs.writeFile(entry, withNotes, "utf8");
4396
5015
  return json(res, 200, {
4397
5016
  ok: true,
@@ -4552,7 +5171,7 @@ function apiPlugin(opts) {
4552
5171
  registerEditRoutes(server, ctx);
4553
5172
  registerCommentRoutes(server, ctx);
4554
5173
  registerSlideRoutes(server, ctx);
4555
- registerBoardRoutes(server, ctx);
5174
+ registerLemonRiverRoutes(server, ctx);
4556
5175
  registerAssetRoutes(server, ctx);
4557
5176
  registerSvglRoutes(server);
4558
5177
  registerGfontsRoutes(server);
@@ -5471,7 +6090,8 @@ async function createViteConfig(opts) {
5471
6090
  userCwd,
5472
6091
  slidesDir
5473
6092
  }),
5474
- serverInfoPlugin({ userCwd })
6093
+ serverInfoPlugin({ userCwd }),
6094
+ lemonRiverAppPlugin()
5475
6095
  ],
5476
6096
  resolve: {
5477
6097
  alias: {