@lemonriver/core 0.5.0 → 0.7.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 (83) hide show
  1. package/dist/{build-CS1goZxt.js → build-CKwrex8y.js} +1 -1
  2. package/dist/cli/bin.js +3 -3
  3. package/dist/{config-BpbcCbUv.js → config-B1_gk0sy.js} +2983 -266
  4. package/dist/{dev-BpYnfgLL.js → dev-DZ2Yzl2p.js} +1 -1
  5. package/dist/{preview-HSzPPkSs.js → preview-hMDcuHfP.js} +1 -1
  6. package/dist/vite/index.js +1 -1
  7. package/package.json +1 -1
  8. package/src/app/lemonriver/board/blocks/classify.test.ts +5 -0
  9. package/src/app/lemonriver/board/blocks/classify.ts +29 -2
  10. package/src/app/lemonriver/board/blocks/snapshot.ts +34 -4
  11. package/src/app/lemonriver/board/board-page.tsx +15 -0
  12. package/src/app/lemonriver/board/model/agent-tasks.ts +33 -1
  13. package/src/app/lemonriver/board/model/self-check.test.ts +329 -0
  14. package/src/app/lemonriver/board/model/self-check.ts +489 -0
  15. package/src/app/lemonriver/board/page-node.tsx +23 -1
  16. package/src/app/lemonriver/board/self-check-jump.ts +23 -0
  17. package/src/app/lemonriver/board/self-check-panel.tsx +272 -0
  18. package/src/app/lemonriver/board/self-check-runner.tsx +150 -0
  19. package/src/app/lemonriver/board/use-self-check.ts +117 -0
  20. package/src/app/lemonriver/chrome/app-chrome.tsx +12 -1
  21. package/src/app/lemonriver/chrome/filter-pill.tsx +30 -0
  22. package/src/app/lemonriver/chrome/sidebar-extras.tsx +12 -1
  23. package/src/app/lemonriver/features.test.ts +10 -0
  24. package/src/app/lemonriver/features.ts +3 -1
  25. package/src/app/lemonriver/feedback/pending-toast.ts +7 -2
  26. package/src/app/lemonriver/home/deck-card.tsx +20 -1
  27. package/src/app/lemonriver/home/home-page.tsx +107 -7
  28. package/src/app/lemonriver/home/use-deck-times.ts +4 -1
  29. package/src/app/lemonriver/outline/build-team.tsx +42 -0
  30. package/src/app/lemonriver/outline/describe-page.tsx +128 -27
  31. package/src/app/lemonriver/outline/draft.ts +38 -0
  32. package/src/app/lemonriver/outline/model.test.ts +79 -0
  33. package/src/app/lemonriver/outline/model.ts +80 -7
  34. package/src/app/lemonriver/outline/outline-page.tsx +56 -6
  35. package/src/app/lemonriver/outline/pick-style.tsx +282 -0
  36. package/src/app/lemonriver/routes.test.tsx +17 -5
  37. package/src/app/lemonriver/routes.tsx +28 -0
  38. package/src/app/lemonriver/share/capture.ts +76 -0
  39. package/src/app/lemonriver/share/client.ts +162 -0
  40. package/src/app/lemonriver/share/codes.test.ts +49 -0
  41. package/src/app/lemonriver/share/codes.ts +30 -0
  42. package/src/app/lemonriver/share/compare.test.ts +199 -0
  43. package/src/app/lemonriver/share/compare.ts +367 -0
  44. package/src/app/lemonriver/share/drop.ts +84 -0
  45. package/src/app/lemonriver/share/folder.test.ts +42 -0
  46. package/src/app/lemonriver/share/folder.ts +29 -0
  47. package/src/app/lemonriver/share/freeze.ts +51 -0
  48. package/src/app/lemonriver/share/guide.test.ts +78 -0
  49. package/src/app/lemonriver/share/guide.ts +222 -0
  50. package/src/app/lemonriver/share/import-dialog.tsx +391 -0
  51. package/src/app/lemonriver/share/import-entry.tsx +106 -0
  52. package/src/app/lemonriver/share/model.ts +150 -0
  53. package/src/app/lemonriver/share/naming.test.ts +59 -0
  54. package/src/app/lemonriver/share/naming.ts +71 -0
  55. package/src/app/lemonriver/share/paths.test.ts +75 -0
  56. package/src/app/lemonriver/share/paths.ts +181 -0
  57. package/src/app/lemonriver/share/pdf.test.ts +79 -0
  58. package/src/app/lemonriver/share/pdf.ts +169 -0
  59. package/src/app/lemonriver/share/share-dialog.tsx +286 -0
  60. package/src/app/lemonriver/share/summary.ts +47 -0
  61. package/src/app/lemonriver/slide-extensions.tsx +69 -23
  62. package/src/app/lemonriver/templates/client.ts +60 -0
  63. package/src/app/lemonriver/templates/demo-page.tsx +79 -0
  64. package/src/app/lemonriver/templates/knobs.test.ts +62 -0
  65. package/src/app/lemonriver/templates/knobs.ts +62 -0
  66. package/src/app/lemonriver/templates/library-page.tsx +295 -0
  67. package/src/app/lemonriver/templates/model.test.ts +175 -0
  68. package/src/app/lemonriver/templates/model.ts +339 -0
  69. package/src/app/lemonriver/templates/preview-content.test.ts +117 -0
  70. package/src/app/lemonriver/templates/preview-content.ts +149 -0
  71. package/src/app/lemonriver/templates/recommend.test.ts +71 -0
  72. package/src/app/lemonriver/templates/recommend.ts +72 -0
  73. package/src/app/lemonriver/templates/use-library.ts +58 -0
  74. package/src/app/lemonriver/templates/virtual.d.ts +28 -0
  75. package/src/app/lemonriver/text/en.ts +124 -0
  76. package/src/app/lemonriver/text/es.ts +124 -0
  77. package/src/app/lemonriver/text/ja.ts +124 -0
  78. package/src/app/lemonriver/text/types.ts +151 -0
  79. package/src/app/lemonriver/text/zh-cn.ts +119 -0
  80. package/src/app/lemonriver/text/zh-tw.ts +119 -0
  81. package/src/app/lemonriver/theme/pages.test.ts +4 -0
  82. package/src/app/lemonriver/theme/pages.ts +6 -1
  83. package/src/app/lemonriver/update/prompt.ts +1 -1
@@ -3,25 +3,688 @@ import { A as reorderNotesArrayInSource, B as CONFIG_FILES, C as duplicatePageIn
3
3
  import { createRequire } from "node:module";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
- import { existsSync, readFileSync, rmSync, statSync } from "node:fs";
6
+ import { existsSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
7
7
  import { execFile, spawn } from "node:child_process";
8
8
  import fs from "node:fs/promises";
9
9
  import { parse } from "@babel/parser";
10
- import { randomBytes, randomUUID } from "node:crypto";
10
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
11
11
  import { promisify } from "node:util";
12
12
  import tailwindcss from "@tailwindcss/vite";
13
13
  import react from "@vitejs/plugin-react";
14
+ import { loadConfigFromFile, normalizePath } from "vite";
14
15
  import os from "node:os";
15
16
  import * as t from "@babel/types";
16
17
  import { isJSXElement, isJSXFragment } from "@babel/types";
17
18
  import fg from "fast-glob";
18
- import { loadConfigFromFile, normalizePath } from "vite";
19
+ import { strToU8, unzipSync, zipSync } from "fflate";
20
+ //#region src/app/lemonriver/templates/knobs.ts
21
+ const KNOB_KEYS$1 = [
22
+ "formal",
23
+ "bright",
24
+ "motion"
25
+ ];
26
+ /**
27
+ * Values under a third lean left, over two thirds lean right; the middle keeps
28
+ * the template's own design. Discrete ends keep a deck's colours reproducible.
29
+ */
30
+ const LEFT_UNTIL = .34;
31
+ const RIGHT_FROM = .66;
32
+ function knobEnd(knob, value) {
33
+ if (!knob || value === void 0) return null;
34
+ if (value <= LEFT_UNTIL) return knob.left;
35
+ if (value >= RIGHT_FROM) return knob.right;
36
+ return null;
37
+ }
38
+ function mergeOverrides(design, overrides) {
39
+ return {
40
+ palette: {
41
+ ...design.palette,
42
+ ...overrides.palette
43
+ },
44
+ fonts: {
45
+ ...design.fonts,
46
+ ...overrides.fonts
47
+ },
48
+ typeScale: {
49
+ ...design.typeScale,
50
+ ...overrides.typeScale
51
+ },
52
+ radius: overrides.radius ?? design.radius
53
+ };
54
+ }
55
+ /** A template that does not define a group keeps its own design for that group. */
56
+ function applyKnobs(design, knobs, values = {}) {
57
+ let out = design;
58
+ for (const key of KNOB_KEYS$1) {
59
+ const end = knobEnd(knobs[key], values[key]);
60
+ if (end?.design) out = mergeOverrides(out, end.design);
61
+ }
62
+ return out;
63
+ }
64
+ function knobFlags(knobs, values = {}) {
65
+ const flags = {};
66
+ for (const key of KNOB_KEYS$1) {
67
+ const end = knobEnd(knobs[key], values[key]);
68
+ if (end?.flags) Object.assign(flags, end.flags);
69
+ }
70
+ return flags;
71
+ }
72
+ //#endregion
73
+ //#region src/app/lemonriver/templates/model.ts
74
+ const OCCASIONS = [
75
+ {
76
+ id: "pitch",
77
+ name: "融资路演"
78
+ },
79
+ {
80
+ id: "report",
81
+ name: "经营汇报"
82
+ },
83
+ {
84
+ id: "launch",
85
+ name: "产品发布"
86
+ },
87
+ {
88
+ id: "review",
89
+ name: "专业评审"
90
+ },
91
+ {
92
+ id: "event",
93
+ name: "活动招商与品牌"
94
+ },
95
+ {
96
+ id: "training",
97
+ name: "培训课程"
98
+ },
99
+ {
100
+ id: "retro",
101
+ name: "复盘分享"
102
+ }
103
+ ];
104
+ const OCCASION_IDS = new Set(OCCASIONS.map((occasion) => occasion.id));
105
+ const SKELETONS = [
106
+ {
107
+ id: "cover",
108
+ name: "封面",
109
+ component: "CoverSkeleton"
110
+ },
111
+ {
112
+ id: "overview",
113
+ name: "一页总览",
114
+ component: "OverviewSkeleton"
115
+ },
116
+ {
117
+ id: "bignum",
118
+ name: "超大单数字",
119
+ component: "BignumSkeleton"
120
+ },
121
+ {
122
+ id: "figure",
123
+ name: "主图加右栏",
124
+ component: "FigureSkeleton"
125
+ },
126
+ {
127
+ id: "compare",
128
+ name: "前后对比",
129
+ component: "CompareSkeleton"
130
+ },
131
+ {
132
+ id: "cards",
133
+ name: "三卡或四卡并列",
134
+ component: "CardsSkeleton"
135
+ },
136
+ {
137
+ id: "process",
138
+ name: "原理或流程",
139
+ component: "ProcessSkeleton"
140
+ },
141
+ {
142
+ id: "timeline",
143
+ name: "时间线",
144
+ component: "TimelineSkeleton"
145
+ },
146
+ {
147
+ id: "risk",
148
+ name: "风险",
149
+ component: "RiskSkeleton"
150
+ },
151
+ {
152
+ id: "ask",
153
+ name: "请求",
154
+ component: "AskSkeleton"
155
+ },
156
+ {
157
+ id: "section",
158
+ name: "章节页",
159
+ component: "SectionSkeleton"
160
+ },
161
+ {
162
+ id: "quote",
163
+ name: "引用",
164
+ component: "QuoteSkeleton"
165
+ },
166
+ {
167
+ id: "end",
168
+ name: "结尾",
169
+ component: "EndSkeleton"
170
+ }
171
+ ];
172
+ const SKELETON_IDS$1 = new Set(SKELETONS.map((skeleton) => skeleton.id));
173
+ /** A template may lower the small-type floor, never lift it. */
174
+ const MIN_TYPE_FLOOR = {
175
+ min: 16,
176
+ max: 20
177
+ };
178
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
179
+ const text$2 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : null;
180
+ const KNOB_KEYS = [
181
+ "formal",
182
+ "bright",
183
+ "motion"
184
+ ];
185
+ function readDesign(raw) {
186
+ if (!isRecord$1(raw)) return null;
187
+ const palette = raw.palette;
188
+ const fonts = raw.fonts;
189
+ const typeScale = raw.typeScale;
190
+ if (!isRecord$1(palette) || !isRecord$1(fonts) || !isRecord$1(typeScale)) return null;
191
+ const bg = text$2(palette.bg);
192
+ const ink = text$2(palette.text);
193
+ const accent = text$2(palette.accent);
194
+ const display = text$2(fonts.display);
195
+ const body = text$2(fonts.body);
196
+ const hero = typeScale.hero;
197
+ const bodySize = typeScale.body;
198
+ const radius = raw.radius;
199
+ if (!bg || !ink || !accent || !display || !body) return null;
200
+ if (typeof hero !== "number" || !Number.isFinite(hero) || hero <= 0) return null;
201
+ if (typeof bodySize !== "number" || !Number.isFinite(bodySize) || bodySize <= 0) return null;
202
+ if (typeof radius !== "number" || !Number.isFinite(radius) || radius < 0) return null;
203
+ return {
204
+ palette: {
205
+ bg,
206
+ text: ink,
207
+ accent
208
+ },
209
+ fonts: {
210
+ display,
211
+ body
212
+ },
213
+ typeScale: {
214
+ hero,
215
+ body: bodySize
216
+ },
217
+ radius
218
+ };
219
+ }
220
+ function readOverrides(raw) {
221
+ if (!isRecord$1(raw)) return void 0;
222
+ const out = {};
223
+ if (isRecord$1(raw.palette)) {
224
+ const palette = {};
225
+ for (const key of [
226
+ "bg",
227
+ "text",
228
+ "accent"
229
+ ]) {
230
+ const value = text$2(raw.palette[key]);
231
+ if (value) palette[key] = value;
232
+ }
233
+ if (Object.keys(palette).length > 0) out.palette = palette;
234
+ }
235
+ if (isRecord$1(raw.fonts)) {
236
+ const fonts = {};
237
+ for (const key of ["display", "body"]) {
238
+ const value = text$2(raw.fonts[key]);
239
+ if (value) fonts[key] = value;
240
+ }
241
+ if (Object.keys(fonts).length > 0) out.fonts = fonts;
242
+ }
243
+ if (isRecord$1(raw.typeScale)) {
244
+ const typeScale = {};
245
+ for (const key of ["hero", "body"]) {
246
+ const value = raw.typeScale[key];
247
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) typeScale[key] = value;
248
+ }
249
+ if (Object.keys(typeScale).length > 0) out.typeScale = typeScale;
250
+ }
251
+ const radius = raw.radius;
252
+ if (typeof radius === "number" && Number.isFinite(radius) && radius >= 0) out.radius = radius;
253
+ return Object.keys(out).length > 0 ? out : void 0;
254
+ }
255
+ function readKnobEnd(raw) {
256
+ if (!isRecord$1(raw)) return null;
257
+ const label = text$2(raw.label);
258
+ if (!label) return null;
259
+ const design = readOverrides(raw.design);
260
+ const flags = {};
261
+ if (isRecord$1(raw.flags)) {
262
+ for (const [key, value] of Object.entries(raw.flags)) if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") flags[key] = value;
263
+ }
264
+ const end = { label };
265
+ if (design) end.design = design;
266
+ if (Object.keys(flags).length > 0) end.flags = flags;
267
+ return end;
268
+ }
269
+ function readKnobs(raw) {
270
+ if (!isRecord$1(raw)) return null;
271
+ const knobs = {};
272
+ for (const key of KNOB_KEYS) {
273
+ const knob = raw[key];
274
+ if (!isRecord$1(knob)) return null;
275
+ const left = readKnobEnd(knob.left);
276
+ const right = readKnobEnd(knob.right);
277
+ if (!left || !right) return null;
278
+ knobs[key] = {
279
+ left,
280
+ right
281
+ };
282
+ }
283
+ return knobs;
284
+ }
285
+ function readFonts(raw) {
286
+ if (!Array.isArray(raw)) return null;
287
+ const fonts = [];
288
+ for (const entry of raw) {
289
+ if (!isRecord$1(entry)) return null;
290
+ const file = text$2(entry.file);
291
+ const license = text$2(entry.license);
292
+ if (!file || !license) return null;
293
+ fonts.push({
294
+ file,
295
+ license
296
+ });
297
+ }
298
+ return fonts;
299
+ }
300
+ /**
301
+ * Turns a `template.json` into a template, or names the first thing that is
302
+ * wrong with it. A template the library cannot trust is dropped whole rather
303
+ * than half-read.
304
+ */
305
+ function sanitizeTemplate(raw, expectedId) {
306
+ if (!isRecord$1(raw)) return {
307
+ ok: false,
308
+ reason: "not a JSON object"
309
+ };
310
+ const id = text$2(raw.id);
311
+ if (!id || !/^[a-z0-9][a-z0-9-]*$/.test(id)) return {
312
+ ok: false,
313
+ reason: "id must be lowercase letters, digits and dashes"
314
+ };
315
+ if (expectedId !== void 0 && id !== expectedId) return {
316
+ ok: false,
317
+ reason: `id "${id}" does not match the folder "${expectedId}"`
318
+ };
319
+ const name = text$2(raw.name);
320
+ if (!name) return {
321
+ ok: false,
322
+ reason: "missing name"
323
+ };
324
+ const audience = text$2(raw.audience);
325
+ if (!audience) return {
326
+ ok: false,
327
+ reason: "missing audience"
328
+ };
329
+ const object = text$2(raw.object);
330
+ if (!object) return {
331
+ ok: false,
332
+ reason: "missing object"
333
+ };
334
+ const reason = text$2(raw.reason);
335
+ if (!reason) return {
336
+ ok: false,
337
+ reason: "missing reason"
338
+ };
339
+ const accent = text$2(raw.accent);
340
+ if (!accent) return {
341
+ ok: false,
342
+ reason: "missing accent"
343
+ };
344
+ const occasionsRaw = raw.occasions;
345
+ if (!Array.isArray(occasionsRaw) || occasionsRaw.length === 0) return {
346
+ ok: false,
347
+ reason: "missing occasions"
348
+ };
349
+ const occasions = [];
350
+ for (const entry of occasionsRaw) {
351
+ if (typeof entry !== "string" || !OCCASION_IDS.has(entry)) return {
352
+ ok: false,
353
+ reason: `unknown occasion "${String(entry)}"`
354
+ };
355
+ if (!occasions.includes(entry)) occasions.push(entry);
356
+ }
357
+ const design = readDesign(raw.design);
358
+ if (!design) return {
359
+ ok: false,
360
+ reason: "missing or malformed design"
361
+ };
362
+ const knobs = readKnobs(raw.knobs);
363
+ if (!knobs) return {
364
+ ok: false,
365
+ reason: "missing or malformed knobs"
366
+ };
367
+ const skeletonsRaw = raw.skeletons;
368
+ if (!Array.isArray(skeletonsRaw) || skeletonsRaw.length === 0) return {
369
+ ok: false,
370
+ reason: "missing skeletons"
371
+ };
372
+ const skeletons = [];
373
+ for (const entry of skeletonsRaw) {
374
+ if (typeof entry !== "string" || !SKELETON_IDS$1.has(entry)) return {
375
+ ok: false,
376
+ reason: `unknown skeleton "${String(entry)}"`
377
+ };
378
+ if (!skeletons.includes(entry)) skeletons.push(entry);
379
+ }
380
+ const fonts = readFonts(raw.fonts);
381
+ if (!fonts) return {
382
+ ok: false,
383
+ reason: "missing or malformed fonts"
384
+ };
385
+ const source = raw.source;
386
+ if (source !== null && source !== void 0 && typeof source !== "string") return {
387
+ ok: false,
388
+ reason: "source must be a string or null"
389
+ };
390
+ const minTypeRaw = raw.minType;
391
+ if (minTypeRaw !== void 0 && minTypeRaw !== null) {
392
+ if (typeof minTypeRaw !== "number" || !Number.isInteger(minTypeRaw) || minTypeRaw < MIN_TYPE_FLOOR.min || minTypeRaw > MIN_TYPE_FLOOR.max) return {
393
+ ok: false,
394
+ reason: `minType must be an integer from ${MIN_TYPE_FLOOR.min} to ${MIN_TYPE_FLOOR.max}`
395
+ };
396
+ }
397
+ const previewPages = Array.isArray(raw.previewPages) ? raw.previewPages.filter((n) => typeof n === "number" && Number.isInteger(n) && n >= 1).slice(0, 8) : [];
398
+ return {
399
+ ok: true,
400
+ template: {
401
+ id,
402
+ name,
403
+ occasions,
404
+ audience,
405
+ object,
406
+ reason,
407
+ accent,
408
+ design,
409
+ knobs,
410
+ skeletons,
411
+ previewPages: previewPages.length > 0 ? previewPages : null,
412
+ minType: typeof minTypeRaw === "number" ? minTypeRaw : void 0,
413
+ fonts,
414
+ source: typeof source === "string" && source.trim() !== "" ? source.trim() : null
415
+ }
416
+ };
417
+ }
418
+ /** The board record written when a template is applied; anything else is ignored. */
419
+ function sanitizeAppliedTemplate(raw) {
420
+ if (!isRecord$1(raw)) return null;
421
+ const id = text$2(raw.id);
422
+ const appliedAt = raw.appliedAt;
423
+ if (!id || typeof appliedAt !== "number" || !Number.isFinite(appliedAt)) return null;
424
+ return {
425
+ id,
426
+ knobs: sanitizeKnobValues(raw.knobs),
427
+ appliedAt
428
+ };
429
+ }
430
+ function sanitizeKnobValues(raw) {
431
+ if (!isRecord$1(raw)) return {};
432
+ const values = {};
433
+ for (const key of KNOB_KEYS) {
434
+ const value = raw[key];
435
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1) values[key] = value;
436
+ }
437
+ return values;
438
+ }
439
+ function designSnippet(design) {
440
+ return `export const design: DesignSystem = ${JSON.stringify(design, null, 2)};`;
441
+ }
442
+ //#endregion
443
+ //#region src/lemonriver/templates/library.ts
444
+ const TEMPLATES_ENV = "LEMONRIVER_TEMPLATES_DIR";
445
+ const SKIP_DIR = /^(?:[._]|node_modules$)/;
446
+ function corePackageRoot(from = import.meta.url) {
447
+ let dir = path.dirname(fileURLToPath(from));
448
+ while (dir !== path.dirname(dir)) {
449
+ if (existsSync(path.join(dir, "package.json"))) return dir;
450
+ dir = path.dirname(dir);
451
+ }
452
+ return path.dirname(fileURLToPath(from));
453
+ }
454
+ /**
455
+ * A folder is the template library when it carries `_shared/` or at least one
456
+ * `<id>/template.json`. That keeps an unrelated `templates/` folder in a user's
457
+ * project from being mistaken for one.
458
+ */
459
+ function looksLikeLibrary(dir) {
460
+ try {
461
+ if (statSync(path.join(dir, "_shared")).isDirectory()) return true;
462
+ } catch {}
463
+ try {
464
+ return readdirSync(dir, { withFileTypes: true }).some((entry) => entry.isDirectory() && !SKIP_DIR.test(entry.name) && existsSync(path.join(dir, entry.name, "template.json")));
465
+ } catch {
466
+ return false;
467
+ }
468
+ }
469
+ /**
470
+ * `LEMONRIVER_TEMPLATES_DIR` wins when it is set — a set-but-missing folder
471
+ * means "no library", not "fall back". With it unset, walk up from core's own
472
+ * package until a library folder appears; only a dev checkout has one, because
473
+ * the library never ships in the package.
474
+ */
475
+ function resolveTemplatesRoot(opts) {
476
+ const fromEnv = (opts.env ?? process.env)[TEMPLATES_ENV];
477
+ if (fromEnv !== void 0) {
478
+ const trimmed = fromEnv.trim();
479
+ if (!trimmed) return null;
480
+ const abs = path.resolve(opts.cwd ?? process.cwd(), trimmed);
481
+ return looksLikeLibrary(abs) ? abs : null;
482
+ }
483
+ let dir = path.resolve(opts.coreRoot);
484
+ while (true) {
485
+ const candidate = path.join(dir, "templates");
486
+ if (looksLikeLibrary(candidate)) return candidate;
487
+ const parent = path.dirname(dir);
488
+ if (parent === dir) return null;
489
+ dir = parent;
490
+ }
491
+ }
492
+ const TEMPLATE_ID_RE$1 = /^[a-z0-9][a-z0-9-]*$/;
493
+ /** The sample deck's page count, read from its default export without running it. */
494
+ async function demoPageCount(dir) {
495
+ try {
496
+ const source = await fs.readFile(path.join(dir, "demo", "index.tsx"), "utf8");
497
+ let decl = (parse(source, {
498
+ sourceType: "module",
499
+ plugins: ["typescript", "jsx"]
500
+ }).program?.body ?? []).find((item) => item.type === "ExportDefaultDeclaration")?.declaration;
501
+ while (decl && (decl.type === "TSAsExpression" || decl.type === "TSSatisfiesExpression")) decl = decl.expression;
502
+ if (decl?.type !== "ArrayExpression") return 0;
503
+ return (decl.elements ?? []).length;
504
+ } catch {
505
+ return 0;
506
+ }
507
+ }
508
+ async function loadTemplates(root, log = (line) => console.warn(line)) {
509
+ if (!root) return [];
510
+ let dirents;
511
+ try {
512
+ dirents = await fs.readdir(root, { withFileTypes: true });
513
+ } catch {
514
+ return [];
515
+ }
516
+ const entries = [];
517
+ for (const dirent of dirents.sort((a, b) => a.name.localeCompare(b.name))) {
518
+ if (!dirent.isDirectory() || SKIP_DIR.test(dirent.name)) continue;
519
+ const id = dirent.name;
520
+ if (!TEMPLATE_ID_RE$1.test(id)) {
521
+ log(`template ${id}: folder name must be lowercase letters, digits and dashes`);
522
+ continue;
523
+ }
524
+ let raw;
525
+ try {
526
+ raw = JSON.parse(await fs.readFile(path.join(root, id, "template.json"), "utf8"));
527
+ } catch (err) {
528
+ log(`template ${id}: ${err.message}`);
529
+ continue;
530
+ }
531
+ const read = sanitizeTemplate(raw, id);
532
+ if (!read.ok) {
533
+ log(`template ${id}: ${read.reason}`);
534
+ continue;
535
+ }
536
+ const dir = path.join(root, id);
537
+ const hasDemo = existsSync(path.join(dir, "demo", "index.tsx"));
538
+ entries.push({
539
+ template: read.template,
540
+ dir,
541
+ hasDemo,
542
+ pages: hasDemo ? await demoPageCount(dir) : 0
543
+ });
544
+ }
545
+ return entries;
546
+ }
547
+ function summarize(entry) {
548
+ const { id, name, occasions, audience, object, reason, accent, design, knobs, skeletons, previewPages } = entry.template;
549
+ return {
550
+ id,
551
+ name,
552
+ occasions,
553
+ audience,
554
+ object,
555
+ reason,
556
+ accent,
557
+ design,
558
+ knobs,
559
+ skeletons,
560
+ previewPages,
561
+ minType: entry.template.minType,
562
+ hasDemo: entry.hasDemo,
563
+ pages: entry.pages
564
+ };
565
+ }
566
+ async function readTemplateListing(root) {
567
+ const entries = await loadTemplates(root);
568
+ return {
569
+ available: root !== null,
570
+ occasions: OCCASIONS,
571
+ templates: entries.map(summarize)
572
+ };
573
+ }
574
+ /** Only an id the library already accepted can name a file; nothing is joined blindly. */
575
+ async function readTemplateGuide(root, id) {
576
+ if (!root || !TEMPLATE_ID_RE$1.test(id)) return null;
577
+ if (!(await loadTemplates(root, () => {})).some((entry) => entry.template.id === id)) return null;
578
+ try {
579
+ return await fs.readFile(path.join(root, id, "GUIDE.md"), "utf8");
580
+ } catch {
581
+ return null;
582
+ }
583
+ }
584
+ //#endregion
585
+ //#region src/lemonriver/templates/vite-plugin.ts
586
+ const TEMPLATES_VMOD = "virtual:open-slide/templates";
587
+ function resolved$2(id) {
588
+ return `\0${id}`;
589
+ }
590
+ function generateModule(templates) {
591
+ const meta = templates.map(summarize);
592
+ const casesFor = (file, ok) => templates.flatMap((entry) => {
593
+ if (!ok(entry)) return [];
594
+ const abs = path.join(entry.dir, file);
595
+ const importPath = `@fs/${normalizePath(abs).replace(/^\/+/, "")}`;
596
+ return [` case ${JSON.stringify(entry.template.id)}: return import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(importPath)});`];
597
+ }).join("\n");
598
+ const demoCases = casesFor(path.join("demo", "index.tsx"), (entry) => entry.hasDemo);
599
+ const previewCases = casesFor(path.join("kit", "preview.tsx"), (entry) => existsSync(path.join(entry.dir, "kit", "preview.tsx")));
600
+ return `// virtual:open-slide/templates — generated
601
+ export const templates = ${JSON.stringify(meta)};
602
+
603
+ export async function loadTemplateDemo(id) {
604
+ switch (id) {
605
+ ${demoCases}
606
+ default: throw new Error('Template demo not found: ' + id);
607
+ }
608
+ }
609
+
610
+ export async function loadTemplatePreview(id) {
611
+ switch (id) {
612
+ ${previewCases}
613
+ default: throw new Error('Template preview not found: ' + id);
614
+ }
615
+ }
616
+ `;
617
+ }
618
+ const EMPTY_MODULE = `// virtual:open-slide/templates — the library is dev-only
619
+ export const templates = [];
620
+
621
+ export async function loadTemplateDemo(id) {
622
+ throw new Error('Template demos are only available in dev: ' + id);
623
+ }
624
+
625
+ export async function loadTemplatePreview(id) {
626
+ throw new Error('Template previews are only available in dev: ' + id);
627
+ }
628
+ `;
629
+ function templatesPlugin(opts) {
630
+ let isDev = false;
631
+ const currentRoot = () => resolveTemplatesRoot({
632
+ coreRoot: opts.coreRoot,
633
+ cwd: opts.userCwd
634
+ });
635
+ return {
636
+ name: "lemonriver:templates",
637
+ config(_config, env) {
638
+ isDev = env.command === "serve";
639
+ },
640
+ configResolved(config) {
641
+ const root = currentRoot();
642
+ if (root) config.server.fs.allow.push(root);
643
+ },
644
+ resolveId(id) {
645
+ if (id === TEMPLATES_VMOD) return resolved$2(TEMPLATES_VMOD);
646
+ return null;
647
+ },
648
+ async load(id) {
649
+ if (id !== resolved$2(TEMPLATES_VMOD)) return null;
650
+ if (!isDev) return EMPTY_MODULE;
651
+ return generateModule(await loadTemplates(currentRoot()));
652
+ },
653
+ configureServer(server) {
654
+ const root = currentRoot();
655
+ if (!root) return;
656
+ const under = (file) => {
657
+ const rel = path.relative(root, file);
658
+ return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
659
+ };
660
+ let reloadTimer = null;
661
+ const reload = () => {
662
+ if (reloadTimer) clearTimeout(reloadTimer);
663
+ reloadTimer = setTimeout(() => {
664
+ reloadTimer = null;
665
+ const mod = server.moduleGraph.getModuleById(resolved$2(TEMPLATES_VMOD));
666
+ if (mod) server.moduleGraph.invalidateModule(mod);
667
+ server.ws.send({ type: "full-reload" });
668
+ }, 150);
669
+ };
670
+ if (existsSync(root)) server.watcher.add(root);
671
+ for (const event of [
672
+ "add",
673
+ "change",
674
+ "unlink"
675
+ ]) server.watcher.on(event, (file) => {
676
+ if (under(file)) reload();
677
+ });
678
+ }
679
+ };
680
+ }
681
+ //#endregion
19
682
  //#region src/app/lemonriver/theme/pages.ts
20
683
  /**
21
684
  * BRAND_PAGES as a path pattern, for the pre-paint script, which runs before
22
685
  * any module loads. pages.test.ts keeps the two in step.
23
686
  */
24
- const BRAND_PATH_SOURCE = "^/(themes(/.*)?|assets|settings|trash|new)?/*$";
687
+ const BRAND_PATH_SOURCE = "^/(themes(/.*)?|assets|settings|trash|new|templates)?/*$";
25
688
  /** Agent screenshots and thumbnails render through this route; nothing may cover it. */
26
689
  const PREVIEW_PATH_SOURCE = "^/s/[^/]+/preview/*$";
27
690
  const REDUCE_MOTION_KEY = "lemonriver:reduce-motion";
@@ -1370,6 +2033,17 @@ const OUTLINE_PAGE_SIZES = [
1370
2033
  12
1371
2034
  ];
1372
2035
  const MAX_BRIEF = 2e3;
2036
+ const MAX_TEMPLATE_PROMPT = 8e3;
2037
+ const SKELETON_IDS = new Set(SKELETONS.map((skeleton) => skeleton.id));
2038
+ function sanitizeSkeletons(raw) {
2039
+ if (!Array.isArray(raw)) return [];
2040
+ const out = [];
2041
+ for (const entry of raw) {
2042
+ if (typeof entry !== "string" || !SKELETON_IDS.has(entry)) continue;
2043
+ if (!out.includes(entry)) out.push(entry);
2044
+ }
2045
+ return out;
2046
+ }
1373
2047
  const ID_RE = /^[a-z0-9-]{1,40}$/;
1374
2048
  const BLOCK_RE = /<lemonriver-outline>([\s\S]*?)<\/lemonriver-outline>/gi;
1375
2049
  let idSeq = 0;
@@ -1383,6 +2057,12 @@ function isPageKind(value) {
1383
2057
  function isOutlineState(value) {
1384
2058
  return typeof value === "string" && OUTLINE_STATES.includes(value);
1385
2059
  }
2060
+ function isOccasionId(value) {
2061
+ return typeof value === "string" && OCCASIONS.some((occasion) => occasion.id === value);
2062
+ }
2063
+ function cleanAudience(value) {
2064
+ return typeof value === "string" ? value.trim().slice(0, 40) : "";
2065
+ }
1386
2066
  function cleanTitle(value) {
1387
2067
  return typeof value === "string" ? value.trim().slice(0, 120) : "";
1388
2068
  }
@@ -1487,7 +2167,12 @@ function sanitizeOutline(raw) {
1487
2167
  dispatched: cleanStep(r.dispatched, items.length),
1488
2168
  lastTurn: cleanTurn(r.lastTurn, items.length),
1489
2169
  prefs: sanitizePrefs(r.prefs),
1490
- decisions: sanitizeDecisions(r.decisions)
2170
+ decisions: sanitizeDecisions(r.decisions),
2171
+ occasion: isOccasionId(r.occasion) ? r.occasion : null,
2172
+ audience: cleanAudience(r.audience),
2173
+ templatePrompt: typeof r.templatePrompt === "string" ? r.templatePrompt.slice(0, MAX_TEMPLATE_PROMPT) : "",
2174
+ templateSkeletons: sanitizeSkeletons(r.templateSkeletons),
2175
+ templateId: typeof r.templateId === "string" && /^[a-z0-9][a-z0-9-]*$/.test(r.templateId) ? r.templateId : null
1491
2176
  };
1492
2177
  }
1493
2178
  /** The last outline block wins: a retried answer may carry an earlier draft. */
@@ -1515,22 +2200,47 @@ const KIND_GUIDE = {
1515
2200
  page: "body — a normal content page",
1516
2201
  end: "closing — the last page and what should happen next"
1517
2202
  };
2203
+ const TEMPLATE_PAGE_LINE = "Keep using the template in ./kit/ — follow kit/docs/GUIDE.md and pick one skeleton per page.";
2204
+ const TEMPLATE_REVIEW_LINE = "Before you finish, take a screenshot of every page (see the slide-authoring skill's preview section) and go through kit/docs/质量清单.md item by item; fix what fails. Reply with the items you could not satisfy, if any.";
2205
+ const FRAMEWORK_REVIEW_LINE = "Before you finish, take a screenshot of every page (see the slide-authoring skill's preview section) and go through the pre-delivery checklist at the end of the slide-authoring skill item by item; fix what fails. Reply with the items you could not satisfy, if any.";
2206
+ const SKELETON_FOR_KIND = {
2207
+ cover: ["cover"],
2208
+ kpi: ["overview", "bignum"],
2209
+ chart: ["figure"],
2210
+ list: ["cards"],
2211
+ page: ["compare", "process"],
2212
+ end: ["end"]
2213
+ };
2214
+ /** The skeleton the template offers for a page of this kind, if it has one. */
2215
+ function skeletonFor(kind, available) {
2216
+ return SKELETON_FOR_KIND[kind].find((id) => available.includes(id)) ?? null;
2217
+ }
1518
2218
  function pagePrompt(outline, slideId, k) {
1519
2219
  const file = `slides/${slideId}/index.tsx`;
1520
2220
  const page = outline.items[k - 1];
1521
2221
  if (k >= 2 && page) {
1522
2222
  const title = page.title || "(untitled)";
1523
- return [`Page ${k} of ${outline.items.length}: [${page.kind}] ${title}. Write only this page; leave the others as they are.`, ...prefsLines(outline.prefs, "page")].join("\n");
1524
- }
1525
- const list = outline.items.map((item, i) => `${i + 1}. [${item.kind}] ${item.title || "(untitled)"}`).join("\n");
1526
- return [
2223
+ const skeleton = skeletonFor(page.kind, outline.templateSkeletons);
2224
+ const lines = [`Page ${k} of ${outline.items.length}: [${page.kind}] ${title}${skeleton ? ` → ${skeleton}` : ""}. Write only this page; leave the others as they are.`];
2225
+ if (outline.templatePrompt) lines.push(TEMPLATE_PAGE_LINE);
2226
+ lines.push(...prefsLines(outline.prefs, "page"));
2227
+ return lines.join("\n");
2228
+ }
2229
+ const list = outline.items.map((item, i) => {
2230
+ const base = `${i + 1}. [${item.kind}] ${item.title || "(untitled)"}`;
2231
+ const skeleton = skeletonFor(item.kind, outline.templateSkeletons);
2232
+ return skeleton ? `${base} → ${skeleton}` : base;
2233
+ }).join("\n");
2234
+ const lines = [
1527
2235
  `Build ${file} from this outline, one page per turn. This turn: write page 1 only, replacing the placeholder page, and set meta.title to the deck title. Pages:`,
1528
2236
  list,
1529
2237
  "Page kinds and how to write them:",
1530
2238
  ...PAGE_KINDS.map((kind) => `- ${KIND_GUIDE[kind]}`),
1531
2239
  "Numbers from the reference files stay exactly as written there.",
1532
2240
  ...prefsLines(outline.prefs, "page")
1533
- ].join("\n");
2241
+ ];
2242
+ if (outline.templatePrompt) return `${outline.templatePrompt}\n\n${lines.join("\n")}`;
2243
+ return lines.join("\n");
1534
2244
  }
1535
2245
  function reviewPrompt(outline, slideId) {
1536
2246
  const lines = [
@@ -1538,6 +2248,7 @@ function reviewPrompt(outline, slideId) {
1538
2248
  `Check each page of slides/${slideId}/index.tsx against the outline and the reference files in slides/${slideId}/assets/:`,
1539
2249
  "fix typos and any number that differs from the files."
1540
2250
  ];
2251
+ lines.push(outline.templatePrompt ? TEMPLATE_REVIEW_LINE : FRAMEWORK_REVIEW_LINE);
1541
2252
  if (outline.prefs.askOnMismatch) lines.push("If two files give different numbers for the same thing, ask the user which to use before changing it.");
1542
2253
  lines.push("Do not add or remove pages.", ...prefsLines(outline.prefs, "review"));
1543
2254
  return lines.join(" ");
@@ -1608,10 +2319,83 @@ function lastErrorText(items, userItemId) {
1608
2319
  return null;
1609
2320
  }
1610
2321
  //#endregion
1611
- //#region src/app/lemonriver/board/model/agent-tasks.ts
1612
- const PAGE_ACTIONS = [
1613
- "rewrite",
1614
- "chart",
2322
+ //#region src/app/lemonriver/board/model/self-check.ts
2323
+ const FINDING_KINDS = [
2324
+ "tiny",
2325
+ "small-body",
2326
+ "overflow",
2327
+ "overlap",
2328
+ "no-notes",
2329
+ "long-title",
2330
+ "accent"
2331
+ ];
2332
+ const BOX_KEYS = [
2333
+ "x",
2334
+ "y",
2335
+ "w",
2336
+ "h"
2337
+ ];
2338
+ function readBox(raw) {
2339
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
2340
+ const record = raw;
2341
+ const box = {};
2342
+ for (const key of BOX_KEYS) {
2343
+ const value = record[key];
2344
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
2345
+ box[key] = value;
2346
+ }
2347
+ return box;
2348
+ }
2349
+ function readCount(raw) {
2350
+ return typeof raw === "number" && Number.isFinite(raw) ? Math.round(raw) : void 0;
2351
+ }
2352
+ function sanitizeFindings(raw) {
2353
+ if (!Array.isArray(raw)) return [];
2354
+ return raw.flatMap((entry) => {
2355
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [];
2356
+ const record = entry;
2357
+ const page = record.page;
2358
+ const kind = record.kind;
2359
+ if (typeof page !== "number" || !Number.isInteger(page) || page < 1 || page > 999) return [];
2360
+ if (typeof kind !== "string" || !FINDING_KINDS.includes(kind)) return [];
2361
+ const boxes = Array.isArray(record.boxes) ? record.boxes.flatMap((box) => readBox(box) ?? []) : (() => {
2362
+ const box = readBox(record.box);
2363
+ return box ? [box] : [];
2364
+ })();
2365
+ const finding = {
2366
+ page,
2367
+ kind,
2368
+ detail: typeof record.detail === "string" ? record.detail.slice(0, 160) : "",
2369
+ boxes,
2370
+ count: Math.max(1, readCount(record.count) ?? boxes.length ?? 1)
2371
+ };
2372
+ const size = readCount(record.size);
2373
+ if (size !== void 0) finding.size = size;
2374
+ const measure = readCount(record.measure);
2375
+ if (measure !== void 0) finding.measure = measure;
2376
+ return [finding];
2377
+ });
2378
+ }
2379
+ function readPages(raw) {
2380
+ if (!Array.isArray(raw)) return [];
2381
+ return raw.flatMap((value) => typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 999 ? [value] : []);
2382
+ }
2383
+ function sanitizeSelfCheck(raw) {
2384
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
2385
+ const record = raw;
2386
+ const at = record.at;
2387
+ if (typeof at !== "number" || !Number.isFinite(at)) return null;
2388
+ return {
2389
+ at,
2390
+ findings: sanitizeFindings(record.findings),
2391
+ unread: readPages(record.unread)
2392
+ };
2393
+ }
2394
+ //#endregion
2395
+ //#region src/app/lemonriver/board/model/agent-tasks.ts
2396
+ const PAGE_ACTIONS = [
2397
+ "rewrite",
2398
+ "chart",
1615
2399
  "memo",
1616
2400
  "expand"
1617
2401
  ];
@@ -1656,6 +2440,13 @@ function sanitizeTask(raw) {
1656
2440
  title: typeof task.title === "string" ? task.title.slice(0, 120) : ""
1657
2441
  };
1658
2442
  }
2443
+ case "self-check": {
2444
+ const findings = sanitizeFindings(task.findings).slice(0, 40);
2445
+ return findings.length > 0 ? {
2446
+ kind: "self-check",
2447
+ findings
2448
+ } : null;
2449
+ }
1659
2450
  default: return null;
1660
2451
  }
1661
2452
  }
@@ -1667,6 +2458,22 @@ const ACTION_LINE = {
1667
2458
  chart: "Turn the main numbers on this page into a chart. Keep the title and the point it makes.",
1668
2459
  expand: "Expand this page into two pages: keep this one, and add one more right after it that goes deeper. Add a speaker note for the new page."
1669
2460
  };
2461
+ /** The problems a finished deck's self-check found, one line each. */
2462
+ function selfCheckPrompt({ slideId, findings, lang }) {
2463
+ const lines = findings.map((finding) => {
2464
+ const box = finding.boxes[0];
2465
+ const at = box ? ` at (${Math.round(box.x)}, ${Math.round(box.y)})` : "";
2466
+ const times = finding.count > 1 ? ` (${finding.count} places)` : "";
2467
+ return `- page ${finding.page}: ${finding.detail}${times}${at}`;
2468
+ });
2469
+ return [
2470
+ `A finished deck at slides/${slideId}/index.tsx was checked automatically and these problems were found:`,
2471
+ ...lines,
2472
+ "Fix only what is listed above, and only on those pages. Change nothing else, and do not add or remove pages.",
2473
+ LANGUAGE(lang),
2474
+ DONE
2475
+ ].join("\n");
2476
+ }
1670
2477
  /** The message for one page. A note action without a note has nothing to say. */
1671
2478
  function pageTaskPrompt({ slideId, page, action, lang }) {
1672
2479
  const memo = page.memo?.trim() ?? "";
@@ -2292,7 +3099,7 @@ async function moveBoardRecord(userCwd, fromId, toId) {
2292
3099
  }
2293
3100
  //#endregion
2294
3101
  //#region src/lemonriver/board/apply.ts
2295
- async function readDeck(ctx, slideId) {
3102
+ async function readDeck$1(ctx, slideId) {
2296
3103
  const entry = resolveSlideEntry(ctx.slidesRoot, slideId);
2297
3104
  const source = entry ? await readSlideSource(entry) : null;
2298
3105
  if (source === null) return null;
@@ -2358,7 +3165,7 @@ async function startApply(ctx, slideId, task = { kind: "changes" }, lang = "en")
2358
3165
  status: 409,
2359
3166
  error: "an apply is already running"
2360
3167
  };
2361
- const deck = await readDeck(ctx, slideId);
3168
+ const deck = await readDeck$1(ctx, slideId);
2362
3169
  if (!deck) return {
2363
3170
  ok: false,
2364
3171
  status: 422,
@@ -2472,6 +3279,26 @@ async function startApply(ctx, slideId, task = { kind: "changes" }, lang = "en")
2472
3279
  prompt
2473
3280
  };
2474
3281
  }
3282
+ if (task.kind === "self-check") {
3283
+ if (task.findings.length === 0) return {
3284
+ ok: false,
3285
+ status: 409,
3286
+ error: "nothing to fix"
3287
+ };
3288
+ const prompt = selfCheckPrompt({
3289
+ slideId,
3290
+ findings: task.findings,
3291
+ lang
3292
+ });
3293
+ await updateBoardFile(file, {
3294
+ ...applying({}),
3295
+ chapterPlan: void 0
3296
+ });
3297
+ return {
3298
+ ok: true,
3299
+ prompt
3300
+ };
3301
+ }
2475
3302
  const changes = sanitizeChanges(stored.changes);
2476
3303
  const restructures = sanitizeRestructures(stored.restructures);
2477
3304
  if (changes.length === 0 && restructures.length === 0) return {
@@ -2587,7 +3414,7 @@ async function collectApply(ctx, store, sessionId, userItemId) {
2587
3414
  return;
2588
3415
  }
2589
3416
  const beforeColumns = Array.isArray(stored.applyColumns) ? stored.applyColumns : [];
2590
- const deck = await readDeck(ctx, slideId);
3417
+ const deck = await readDeck$1(ctx, slideId);
2591
3418
  const newKeys = deck ? deck.keys : beforeColumns.flatMap((column) => column.keys);
2592
3419
  const beforeKeys = new Set(beforeColumns.flatMap((column) => column.keys));
2593
3420
  const created = newKeys.filter((key) => !beforeKeys.has(key));
@@ -2605,6 +3432,7 @@ async function collectApply(ctx, store, sessionId, userItemId) {
2605
3432
  fields.changes = [];
2606
3433
  fields.restructures = [];
2607
3434
  } else if (task.kind === "page") pages = [.../* @__PURE__ */ new Set([task.page, ...created])].filter((key) => newKeys.includes(key));
3435
+ else if (task.kind === "self-check") pages = [...new Set(task.findings.map((finding) => finding.page))].map((n) => newKeys[n - 1]).filter((key) => typeof key === "string");
2608
3436
  else {
2609
3437
  pages = created;
2610
3438
  const plan = sanitizeChapterPlan(stored.chapterPlan);
@@ -2671,7 +3499,7 @@ const SKIP_KEYS = /* @__PURE__ */ new Set([
2671
3499
  "trailingComments",
2672
3500
  "innerComments"
2673
3501
  ]);
2674
- function walk(ast, visit, accept) {
3502
+ function walk$1(ast, visit, accept) {
2675
3503
  let stopped = false;
2676
3504
  const recurse = (node) => {
2677
3505
  if (stopped || !node || typeof node !== "object") return;
@@ -2695,10 +3523,10 @@ function walk(ast, visit, accept) {
2695
3523
  const isJsx = (n) => isJSXElement(n) || isJSXFragment(n);
2696
3524
  const acceptAll = () => true;
2697
3525
  function walkJsx(ast, visit) {
2698
- walk(ast, visit, isJsx);
3526
+ walk$1(ast, visit, isJsx);
2699
3527
  }
2700
3528
  function walkAll(ast, visit) {
2701
- walk(ast, visit, acceptAll);
3529
+ walk$1(ast, visit, acceptAll);
2702
3530
  }
2703
3531
  /** Parse with error recovery; recoverable syntax errors are kept in `errors`. */
2704
3532
  function tryParse(source) {
@@ -3009,7 +3837,8 @@ function registerBoardRoutes(server, ctx) {
3009
3837
  applying: sanitizeApplying(raw.applying),
3010
3838
  lastApply: sanitizeLastApply(raw.lastApply),
3011
3839
  chapterPlan: sanitizeChapterPlan(raw.chapterPlan),
3012
- targetMinutes: sanitizeTargetMinutes(raw.targetMinutes)
3840
+ targetMinutes: sanitizeTargetMinutes(raw.targetMinutes),
3841
+ template: sanitizeAppliedTemplate(raw.template)
3013
3842
  });
3014
3843
  }
3015
3844
  if (method === "PUT" && url.pathname === "/") {
@@ -3041,6 +3870,26 @@ function registerBoardRoutes(server, ctx) {
3041
3870
  await updateBoardFile(boardStructurePath(ctx.userCwd, slideId), { targetMinutes: sanitizeTargetMinutes(body?.targetMinutes) });
3042
3871
  return json(res, 200, { ok: true });
3043
3872
  }
3873
+ if (method === "GET" && url.pathname === "/self-check") {
3874
+ const slideId = url.searchParams.get("slideId") ?? "";
3875
+ if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
3876
+ const stored = await readBoardFile(boardStructurePath(ctx.userCwd, slideId));
3877
+ return json(res, 200, { selfCheck: sanitizeSelfCheck(stored.selfCheck) });
3878
+ }
3879
+ if (method === "PUT" && url.pathname === "/self-check") {
3880
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
3881
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
3882
+ const body = await readBody(req);
3883
+ const slideId = typeof body?.slideId === "string" ? body.slideId : "";
3884
+ if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
3885
+ const selfCheck = sanitizeSelfCheck(body?.selfCheck);
3886
+ if (!selfCheck) return json(res, 400, { error: "invalid selfCheck" });
3887
+ await updateBoardFile(boardStructurePath(ctx.userCwd, slideId), { selfCheck });
3888
+ return json(res, 200, {
3889
+ ok: true,
3890
+ selfCheck
3891
+ });
3892
+ }
3044
3893
  if (method === "GET" && url.pathname === "/cards") {
3045
3894
  const slideId = url.searchParams.get("slideId") ?? "";
3046
3895
  if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
@@ -3228,7 +4077,7 @@ function registerBoardRoutes(server, ctx) {
3228
4077
  }
3229
4078
  //#endregion
3230
4079
  //#region src/lemonriver/decks/routes.ts
3231
- const ENTRY_NAMES$1 = [
4080
+ const ENTRY_NAMES$4 = [
3232
4081
  "index.tsx",
3233
4082
  "index.jsx",
3234
4083
  "index.ts",
@@ -3244,7 +4093,7 @@ async function readDeckTimes(slidesRoot) {
3244
4093
  const decks = {};
3245
4094
  for (const name of names) {
3246
4095
  if (!SLIDE_ID_RE.test(name)) continue;
3247
- for (const entry of ENTRY_NAMES$1) try {
4096
+ for (const entry of ENTRY_NAMES$4) try {
3248
4097
  const stat = await fs.stat(path.join(slidesRoot, name, entry));
3249
4098
  decks[name] = { modifiedAt: Math.round(stat.mtimeMs) };
3250
4099
  break;
@@ -3252,19 +4101,212 @@ async function readDeckTimes(slidesRoot) {
3252
4101
  }
3253
4102
  return decks;
3254
4103
  }
4104
+ async function deckFacts(ctx, slideId) {
4105
+ const stored = await readBoardFile(boardStructurePath(ctx.userCwd, slideId));
4106
+ const applied = sanitizeAppliedTemplate(stored.template);
4107
+ const template = applied?.id ?? null;
4108
+ const outline = sanitizeOutline(stored.outline);
4109
+ if (outline?.occasion) return {
4110
+ occasion: outline.occasion,
4111
+ template
4112
+ };
4113
+ if (!applied) return {
4114
+ occasion: null,
4115
+ template
4116
+ };
4117
+ const root = resolveTemplatesRoot({
4118
+ coreRoot: corePackageRoot(),
4119
+ cwd: ctx.userCwd
4120
+ });
4121
+ if (!root) return {
4122
+ occasion: null,
4123
+ template
4124
+ };
4125
+ try {
4126
+ const read = sanitizeTemplate(JSON.parse(await fs.readFile(path.join(root, applied.id, "template.json"), "utf8")), applied.id);
4127
+ return {
4128
+ occasion: read.ok ? read.template.occasions[0] ?? null : null,
4129
+ template
4130
+ };
4131
+ } catch {
4132
+ return {
4133
+ occasion: null,
4134
+ template
4135
+ };
4136
+ }
4137
+ }
3255
4138
  function registerDeckRoutes(server, ctx) {
3256
4139
  server.middlewares.use("/__lr/decks", async (req, res, next) => {
3257
4140
  const url = new URL(req.url ?? "/", "http://local");
3258
4141
  if ((req.method ?? "GET") !== "GET" || url.pathname !== "/") return next();
3259
4142
  try {
3260
- json(res, 200, { decks: await readDeckTimes(ctx.slidesRoot) });
4143
+ const times = await readDeckTimes(ctx.slidesRoot);
4144
+ const decks = {};
4145
+ for (const [id, info] of Object.entries(times)) decks[id] = {
4146
+ modifiedAt: info.modifiedAt,
4147
+ ...await deckFacts(ctx, id)
4148
+ };
4149
+ json(res, 200, { decks });
3261
4150
  } catch (err) {
3262
4151
  json(res, 500, { error: String(err.message ?? err) });
3263
4152
  }
3264
4153
  });
3265
4154
  }
3266
4155
  //#endregion
4156
+ //#region src/lemonriver/templates/apply.ts
4157
+ const SHARED_DOCS = [
4158
+ "讲法.md",
4159
+ "中文排版.md",
4160
+ "质量清单.md",
4161
+ "插图画法.md"
4162
+ ];
4163
+ /** A kit's tests describe the template; the deck that copies it has no one to run them. */
4164
+ const isTestFile = (file) => /\.test\.tsx?$/.test(file);
4165
+ const docList = (slideId) => [`GUIDE.md`, ...SHARED_DOCS].map((doc) => `- slides/${slideId}/kit/docs/${doc}`).join("\n");
4166
+ function promptFor(input) {
4167
+ const { slideId, template, design, flags, knobs } = input;
4168
+ const skeletons = template.skeletons.map((id) => SKELETONS.find((skeleton) => skeleton.id === id)).filter((skeleton) => skeleton !== void 0).map((skeleton) => `- ${skeleton.id} (${skeleton.name}): ${skeleton.component}`).join("\n");
4169
+ const knobLine = `formal=${knobs.formal ?? .5}, bright=${knobs.bright ?? .5}, motion=${knobs.motion ?? .5}`;
4170
+ const flagEntries = Object.entries(flags);
4171
+ const flagLine = flagEntries.length > 0 ? `\nThe knobs also switch: ${flagEntries.map(([key, value]) => `${key}=${value}`).join(", ")}.` : "";
4172
+ return `This deck uses the "${template.name}" template (${template.id}). Everything below is relative to slides/${slideId}/index.tsx.
4173
+
4174
+ Before writing any page, read:
4175
+ ${docList(slideId)}
4176
+
4177
+ The shell, the fixed parts and the skeleton components live in slides/${slideId}/kit/. Import them from './kit/...' and do not reach outside this deck folder. The template describes the borrowed object as: ${template.object}. The accent colour stands for: ${template.accent}.
4178
+
4179
+ Replace any existing \`design\` export with this constant. It is the template's design with the knobs (${knobLine}) already applied; do not hand-edit its colours:
4180
+ ${designSnippet(design)}${flagLine}
4181
+
4182
+ Pick one skeleton per page from slides/${slideId}/kit/skeletons.tsx:
4183
+ ${skeletons}
4184
+
4185
+ When you are done, reply with one short sentence saying which skeletons you used.`;
4186
+ }
4187
+ /**
4188
+ * Copies a template into one deck's own folder. Everything the deck needs to
4189
+ * keep its style later — kit, fonts, guides — travels with it, so a later
4190
+ * template update never rewrites a finished deck.
4191
+ */
4192
+ async function applyTemplateToDeck(ctx, slideId, templateId, knobs) {
4193
+ const entry = resolveSlideEntry(ctx.slidesRoot, slideId);
4194
+ if (!entry) return {
4195
+ ok: false,
4196
+ status: 400,
4197
+ error: "invalid slideId"
4198
+ };
4199
+ try {
4200
+ await fs.access(entry);
4201
+ } catch {
4202
+ return {
4203
+ ok: false,
4204
+ status: 404,
4205
+ error: "slide not found"
4206
+ };
4207
+ }
4208
+ const root = resolveTemplatesRoot({
4209
+ coreRoot: corePackageRoot(),
4210
+ cwd: ctx.userCwd
4211
+ });
4212
+ if (!root) return {
4213
+ ok: false,
4214
+ status: 404,
4215
+ error: "no template library"
4216
+ };
4217
+ const found = (await loadTemplates(root, () => {})).find((candidate) => candidate.template.id === templateId);
4218
+ if (!found) return {
4219
+ ok: false,
4220
+ status: 404,
4221
+ error: "template not found"
4222
+ };
4223
+ const missing = [];
4224
+ for (const doc of SHARED_DOCS) try {
4225
+ await fs.access(path.join(root, "_shared", doc));
4226
+ } catch {
4227
+ missing.push(`_shared/${doc}`);
4228
+ }
4229
+ try {
4230
+ await fs.access(path.join(found.dir, "GUIDE.md"));
4231
+ } catch {
4232
+ missing.push(`${templateId}/GUIDE.md`);
4233
+ }
4234
+ try {
4235
+ await fs.access(path.join(found.dir, "kit"));
4236
+ } catch {
4237
+ missing.push(`${templateId}/kit`);
4238
+ }
4239
+ if (missing.length > 0) return {
4240
+ ok: false,
4241
+ status: 500,
4242
+ error: `template library is incomplete: ${missing.join(", ")}`
4243
+ };
4244
+ const deckDir = path.join(ctx.slidesRoot, slideId);
4245
+ const destKit = path.join(deckDir, "kit");
4246
+ await fs.rm(destKit, {
4247
+ recursive: true,
4248
+ force: true
4249
+ });
4250
+ await fs.cp(path.join(found.dir, "kit"), destKit, {
4251
+ recursive: true,
4252
+ filter: (src) => !isTestFile(src)
4253
+ });
4254
+ const docsDir = path.join(destKit, "docs");
4255
+ await fs.mkdir(docsDir, { recursive: true });
4256
+ await fs.copyFile(path.join(found.dir, "GUIDE.md"), path.join(docsDir, "GUIDE.md"));
4257
+ for (const doc of SHARED_DOCS) await fs.copyFile(path.join(root, "_shared", doc), path.join(docsDir, doc));
4258
+ const values = sanitizeKnobValues(knobs);
4259
+ await updateBoardFile(boardStructurePath(ctx.userCwd, slideId), { template: {
4260
+ id: found.template.id,
4261
+ knobs: values,
4262
+ appliedAt: Date.now()
4263
+ } });
4264
+ return {
4265
+ ok: true,
4266
+ prompt: promptFor({
4267
+ slideId,
4268
+ template: found.template,
4269
+ design: applyKnobs(found.template.design, found.template.knobs, values),
4270
+ flags: knobFlags(found.template.knobs, values),
4271
+ knobs: values
4272
+ }),
4273
+ skeletons: found.template.skeletons
4274
+ };
4275
+ }
4276
+ //#endregion
4277
+ //#region src/lemonriver/outline/occasion.ts
4278
+ const text$1 = (value) => typeof value === "string" ? value.trim() : "";
4279
+ /**
4280
+ * The two lines an outline prompt gains when the user named an occasion: who
4281
+ * it is for, and the page order that occasion usually wants.
4282
+ */
4283
+ async function occasionLines(root, occasion, audience) {
4284
+ const id = text$1(occasion);
4285
+ if (!root || !id) return [];
4286
+ let parsed;
4287
+ try {
4288
+ parsed = JSON.parse(await fs.readFile(path.join(root, "_shared", "场合.json"), "utf8"));
4289
+ } catch {
4290
+ return [];
4291
+ }
4292
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return [];
4293
+ const entry = parsed[id];
4294
+ if (!entry || typeof entry !== "object") return [];
4295
+ const name = text$1(entry.name);
4296
+ if (!name) return [];
4297
+ const lines = [];
4298
+ const who = text$1(audience) || text$1(entry.audience);
4299
+ if (who) lines.push(`The deck is for: ${who}.`);
4300
+ const order = Array.isArray(entry.order) ? entry.order.filter((kind) => typeof kind === "string") : [];
4301
+ if (order.length > 0) lines.push(`For a ${name} deck, this page order is recommended: ${order.join(" → ")}.`);
4302
+ return lines;
4303
+ }
4304
+ //#endregion
3267
4305
  //#region src/lemonriver/outline/routes.ts
4306
+ const TEMPLATE_ID_RE = /^[a-z0-9][a-z0-9-]*$/;
4307
+ function isTemplateId(value) {
4308
+ return typeof value === "string" && TEMPLATE_ID_RE.test(value);
4309
+ }
3268
4310
  function startOutline(input, now) {
3269
4311
  const brief = typeof input.brief === "string" ? input.brief.trim().slice(0, MAX_BRIEF) : "";
3270
4312
  const files = Array.isArray(input.files) ? input.files.filter((file) => typeof file === "string" && file.trim() !== "") : [];
@@ -3281,7 +4323,12 @@ function startOutline(input, now) {
3281
4323
  dispatched: null,
3282
4324
  lastTurn: null,
3283
4325
  prefs: sanitizePrefs(input.prefs),
3284
- decisions: []
4326
+ decisions: [],
4327
+ occasion: isOccasionId(input.occasion) ? input.occasion : null,
4328
+ audience: typeof input.audience === "string" ? input.audience.trim().slice(0, 40) : "",
4329
+ templatePrompt: "",
4330
+ templateSkeletons: [],
4331
+ templateId: isTemplateId(input.template) ? input.template : null
3285
4332
  };
3286
4333
  }
3287
4334
  /** Only a ready outline may be edited: while drafting the agent owns the list. */
@@ -3335,7 +4382,20 @@ function undoBuild(outline, now) {
3335
4382
  stage: "pages",
3336
4383
  dispatched: null,
3337
4384
  lastTurn: null,
3338
- updatedAt: now
4385
+ updatedAt: now,
4386
+ templatePrompt: "",
4387
+ templateSkeletons: []
4388
+ };
4389
+ }
4390
+ /** Only an id shaped like a template folder is passed on; the library re-checks it. */
4391
+ function readTemplateChoice(raw) {
4392
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
4393
+ const record = raw;
4394
+ const id = record.id;
4395
+ if (!isTemplateId(id)) return null;
4396
+ return {
4397
+ id,
4398
+ knobs: record.knobs
3339
4399
  };
3340
4400
  }
3341
4401
  async function readOutline(ctx, slideId) {
@@ -3372,8 +4432,16 @@ function registerOutlineRoutes(server, ctx) {
3372
4432
  const body = await readBody(req);
3373
4433
  const slideId = typeof body.slideId === "string" ? body.slideId : "";
3374
4434
  if (!resolveSlideEntryPath(ctx, slideId)) return json(res, 400, { error: "invalid slideId" });
3375
- await updateBoardFile(boardStructurePath(ctx.userCwd, slideId), { outline: startOutline(body, Date.now()) });
3376
- return json(res, 200, { ok: true });
4435
+ const outline = startOutline(body, Date.now());
4436
+ await updateBoardFile(boardStructurePath(ctx.userCwd, slideId), { outline });
4437
+ const lines = await occasionLines(resolveTemplatesRoot({
4438
+ coreRoot: corePackageRoot(),
4439
+ cwd: ctx.userCwd
4440
+ }), outline.occasion, outline.audience);
4441
+ return json(res, 200, {
4442
+ ok: true,
4443
+ prompt: lines.join("\n")
4444
+ });
3377
4445
  }
3378
4446
  if (method === "POST" && url.pathname === "/build") {
3379
4447
  const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
@@ -3390,8 +4458,21 @@ function registerOutlineRoutes(server, ctx) {
3390
4458
  prefs: sanitizePrefs(body.prefs)
3391
4459
  };
3392
4460
  const buildBackup = await readSlideSource(entry) ?? "";
4461
+ const choice = readTemplateChoice(body.template);
4462
+ let templatePrompt = "";
4463
+ let templateSkeletons = [];
4464
+ if (choice) {
4465
+ const applied = await applyTemplateToDeck(ctx, slideId, choice.id, choice.knobs);
4466
+ if (!applied.ok) return json(res, applied.status, { error: applied.error });
4467
+ templatePrompt = applied.prompt;
4468
+ templateSkeletons = applied.skeletons;
4469
+ }
3393
4470
  await updateBoardFile(file, {
3394
- outline: beginBuild(withPrefs, Date.now()),
4471
+ outline: {
4472
+ ...beginBuild(withPrefs, Date.now()),
4473
+ templatePrompt,
4474
+ templateSkeletons
4475
+ },
3395
4476
  buildBackup
3396
4477
  });
3397
4478
  return json(res, 200, { ok: true });
@@ -3409,8 +4490,17 @@ function registerOutlineRoutes(server, ctx) {
3409
4490
  now: Date.now()
3410
4491
  });
3411
4492
  if (!claimed) return json(res, 409, { error: "no step to send" });
3412
- await updateBoardFile(boardStructurePath(ctx.userCwd, slideId), { outline: claimed.outline });
3413
- const prompt = claimed.step.kind === "review" ? reviewPrompt(outline, slideId) : pagePrompt(outline, slideId, claimed.step.n);
4493
+ let next = claimed.outline;
4494
+ if (claimed.step.kind === "page" && claimed.step.n === 1 && next.templateId && !next.templatePrompt) {
4495
+ const applied = await applyTemplateToDeck(ctx, slideId, next.templateId, {});
4496
+ if (applied.ok) next = {
4497
+ ...next,
4498
+ templatePrompt: applied.prompt,
4499
+ templateSkeletons: applied.skeletons
4500
+ };
4501
+ }
4502
+ await updateBoardFile(boardStructurePath(ctx.userCwd, slideId), { outline: next });
4503
+ const prompt = claimed.step.kind === "review" ? reviewPrompt(next, slideId) : pagePrompt(next, slideId, claimed.step.n);
3414
4504
  return json(res, 200, {
3415
4505
  prompt,
3416
4506
  step: claimed.step
@@ -3446,9 +4536,14 @@ function registerOutlineRoutes(server, ctx) {
3446
4536
  const next = undoBuild(outline, Date.now());
3447
4537
  if (!next) return json(res, 409, { error: "nothing to undo" });
3448
4538
  await fs.writeFile(entry, backup, "utf8");
4539
+ if (sanitizeAppliedTemplate(stored.template)) await fs.rm(path.join(ctx.slidesRoot, slideId, "kit"), {
4540
+ recursive: true,
4541
+ force: true
4542
+ });
3449
4543
  await updateBoardFile(file, {
3450
4544
  outline: next,
3451
- buildBackup: void 0
4545
+ buildBackup: void 0,
4546
+ template: void 0
3452
4547
  });
3453
4548
  return json(res, 200, { ok: true });
3454
4549
  }
@@ -3459,104 +4554,609 @@ function registerOutlineRoutes(server, ctx) {
3459
4554
  });
3460
4555
  }
3461
4556
  //#endregion
3462
- //#region src/vite/recent-writes.ts
3463
- const recentWrites = /* @__PURE__ */ new Map();
3464
- /** Record that `file` was just written by us. */
3465
- function recordWrite(file, now = Date.now()) {
3466
- recentWrites.set(file, now);
4557
+ //#region src/app/lemonriver/share/compare.ts
4558
+ const ENTRY_NAMES$3 = [
4559
+ "index.tsx",
4560
+ "index.jsx",
4561
+ "index.ts",
4562
+ "index.js"
4563
+ ];
4564
+ const ASSETS = "assets/";
4565
+ function toMap(files) {
4566
+ return files instanceof Map ? files : new Map(Object.entries(files));
3467
4567
  }
3468
4568
  /**
3469
- * True if `file` was recorded within the recent-write window. Expired entries
3470
- * are pruned so a stale path can no longer suppress a later genuine edit.
4569
+ * Packing rewrites `@assets/x` to a path relative to each file; comparing raw
4570
+ * text would then report every page that uses an asset as changed.
3471
4571
  */
3472
- function hasRecentWrite(file, now = Date.now()) {
3473
- const ts = recentWrites.get(file);
3474
- if (ts == null) return false;
3475
- if (now - ts < 1500) return true;
3476
- recentWrites.delete(file);
3477
- return false;
4572
+ function normalizeAssets(source) {
4573
+ return source.replace(/(?:\.{1,2}\/)+assets\//g, "@assets/");
3478
4574
  }
3479
- //#endregion
3480
- //#region src/vite/open-slide-plugin.ts
3481
- const SLIDES_VMOD = "virtual:open-slide/slides";
3482
- const CONFIG_VMOD = "virtual:open-slide/config";
3483
- const FOLDERS_VMOD = "virtual:open-slide/folders";
3484
- function resolved$1(id) {
3485
- return `\0${id}`;
4575
+ function compress(source) {
4576
+ return normalizeAssets(source).replace(/\s+/g, "");
3486
4577
  }
3487
- async function findSlides(userCwd, slidesDir) {
3488
- const abs = path.resolve(userCwd, slidesDir);
3489
- if (!existsSync(abs)) return [];
3490
- return (await fg("*/index.{tsx,jsx,ts,js}", {
3491
- cwd: abs,
3492
- absolute: true,
3493
- onlyFiles: true
3494
- })).sort();
4578
+ function slice(source, node) {
4579
+ if (node.start == null || node.end == null) return "";
4580
+ return source.slice(node.start, node.end);
3495
4581
  }
3496
- function toId(absFile, slidesRoot) {
3497
- return path.relative(slidesRoot, absFile).split(path.sep)[0];
4582
+ function unwrapExport(node) {
4583
+ return node.type === "ExportNamedDeclaration" && node.declaration ? node.declaration : node;
3498
4584
  }
3499
- const META_THEME_RE = /(?:^|[\s,{])theme\s*:\s*['"]([^'"]+)['"]/;
3500
- const META_CREATED_AT_RE = /(?:^|[\s,{])createdAt\s*:\s*['"]([^'"]+)['"]/;
3501
- function extractMeta(src) {
3502
- const empty = {
3503
- theme: null,
3504
- createdAt: null
3505
- };
3506
- const metaStart = src.search(/export\s+const\s+meta\b/);
3507
- if (metaStart === -1) return empty;
3508
- const eqIdx = src.indexOf("=", metaStart);
3509
- if (eqIdx === -1) return empty;
3510
- const openBrace = src.indexOf("{", eqIdx);
3511
- if (openBrace === -1) return empty;
3512
- let depth = 0;
3513
- let closeBrace = -1;
3514
- for (let i = openBrace; i < src.length; i++) {
3515
- const ch = src[i];
3516
- if (ch === "{") depth++;
3517
- else if (ch === "}") {
3518
- depth--;
3519
- if (depth === 0) {
3520
- closeBrace = i;
3521
- break;
3522
- }
3523
- }
3524
- }
3525
- if (closeBrace === -1) return empty;
3526
- const body = src.slice(openBrace + 1, closeBrace);
3527
- const themeMatch = body.match(META_THEME_RE);
3528
- const createdAtMatch = body.match(META_CREATED_AT_RE);
3529
- return {
3530
- theme: themeMatch ? themeMatch[1] : null,
3531
- createdAt: createdAtMatch ? createdAtMatch[1] : null
3532
- };
4585
+ /** Pages are compared one by one, and `notes`/`meta` ride with the deck rather than its layout. */
4586
+ function excludedFromShared(name, pages) {
4587
+ return name === "notes" || name === "meta" || name !== null && pages.has(name);
3533
4588
  }
3534
- async function readSlideMeta(abs) {
4589
+ function parseDeck(source) {
4590
+ let body;
3535
4591
  try {
3536
- return extractMeta(await fs.readFile(abs, "utf8"));
4592
+ body = parse(source, {
4593
+ sourceType: "module",
4594
+ plugins: ["typescript", "jsx"],
4595
+ errorRecovery: true
4596
+ }).program.body;
3537
4597
  } catch {
3538
4598
  return {
3539
- theme: null,
3540
- createdAt: null
4599
+ ok: false,
4600
+ pages: [],
4601
+ notes: null,
4602
+ shared: ""
3541
4603
  };
3542
4604
  }
3543
- }
3544
- function parseCreatedAtMs(iso) {
3545
- if (!iso) return null;
3546
- const ms = Date.parse(iso);
3547
- return Number.isFinite(ms) ? ms : null;
3548
- }
3549
- const warnedInvalidSlideIds = /* @__PURE__ */ new Set();
3550
- async function generateSlidesModule(files, slidesRoot, isDev) {
3551
- const scanned = await Promise.all(files.map(async (abs) => {
3552
- const id = toId(abs, slidesRoot);
3553
- const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
3554
- const meta = await readSlideMeta(abs);
3555
- return {
3556
- id,
3557
- importPath,
3558
- theme: meta.theme,
3559
- createdAt: parseCreatedAtMs(meta.createdAt)
4605
+ const declarations = /* @__PURE__ */ new Map();
4606
+ for (const raw of body) {
4607
+ const node = unwrapExport(raw);
4608
+ if (node.type === "VariableDeclaration") {
4609
+ for (const item of node.declarations) if (item.id.type === "Identifier" && item.init) declarations.set(item.id.name, compress(slice(source, item)));
4610
+ } else if (node.type === "FunctionDeclaration" && node.id) declarations.set(node.id.name, compress(slice(source, node)));
4611
+ }
4612
+ let array = null;
4613
+ let notes = null;
4614
+ const named = /* @__PURE__ */ new Set();
4615
+ for (const node of body) {
4616
+ if (node.type === "ExportDefaultDeclaration") {
4617
+ let inner = node.declaration;
4618
+ while (inner.type === "TSAsExpression" || inner.type === "TSSatisfiesExpression") inner = inner.expression;
4619
+ array = inner.type === "ArrayExpression" ? inner : null;
4620
+ continue;
4621
+ }
4622
+ const declaration = node.type === "ExportNamedDeclaration" || node.type === "VariableDeclaration" ? node.type === "ExportNamedDeclaration" ? node.declaration : node : null;
4623
+ if (declaration?.type !== "VariableDeclaration") continue;
4624
+ for (const item of declaration.declarations) {
4625
+ if (item.id.type !== "Identifier" || item.id.name !== "notes") continue;
4626
+ if (item.init?.type === "ArrayExpression") notes = item.init.elements.map((element) => element && element.type !== "SpreadElement" ? compress(slice(source, element)) : "");
4627
+ }
4628
+ }
4629
+ if (array?.type !== "ArrayExpression") return {
4630
+ ok: false,
4631
+ pages: [],
4632
+ notes,
4633
+ shared: ""
4634
+ };
4635
+ const pages = [];
4636
+ let inlineIndex = 0;
4637
+ for (let index = 0; index < array.elements.length; index++) {
4638
+ const element = array.elements[index];
4639
+ if (!element || element.type === "SpreadElement") return {
4640
+ ok: false,
4641
+ pages: [],
4642
+ notes,
4643
+ shared: ""
4644
+ };
4645
+ if (element.type === "Identifier") {
4646
+ named.add(element.name);
4647
+ pages.push({
4648
+ name: element.name,
4649
+ index,
4650
+ inlineIndex: -1,
4651
+ source: declarations.get(element.name) ?? compress(slice(source, element))
4652
+ });
4653
+ continue;
4654
+ }
4655
+ pages.push({
4656
+ name: null,
4657
+ index,
4658
+ inlineIndex: inlineIndex++,
4659
+ source: compress(slice(source, element))
4660
+ });
4661
+ }
4662
+ const shared = [];
4663
+ for (const raw of body) {
4664
+ if (raw.type === "ExportDefaultDeclaration") continue;
4665
+ const node = unwrapExport(raw);
4666
+ if (node.type === "VariableDeclaration") {
4667
+ for (const item of node.declarations) {
4668
+ if (excludedFromShared(item.id.type === "Identifier" ? item.id.name : null, named)) continue;
4669
+ shared.push(compress(slice(source, item)));
4670
+ }
4671
+ continue;
4672
+ }
4673
+ if ((node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") && node.id && excludedFromShared(node.id.name, named)) continue;
4674
+ shared.push(compress(slice(source, node)));
4675
+ }
4676
+ return {
4677
+ ok: true,
4678
+ pages,
4679
+ notes,
4680
+ shared: shared.join("\0")
4681
+ };
4682
+ }
4683
+ function entryKey(files) {
4684
+ for (const name of ENTRY_NAMES$3) if (files.has(name)) return name;
4685
+ return null;
4686
+ }
4687
+ function assetName(path) {
4688
+ return path.startsWith(ASSETS) && path.length > 7 ? path.slice(7) : null;
4689
+ }
4690
+ function sameBytes(a, b) {
4691
+ if (!a || !b) return a === b;
4692
+ if (a.length !== b.length) return false;
4693
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
4694
+ return true;
4695
+ }
4696
+ function compareAssets(local, packaged) {
4697
+ const added = [];
4698
+ const changed = [];
4699
+ const removed = [];
4700
+ const names = /* @__PURE__ */ new Set();
4701
+ for (const path of local.keys()) {
4702
+ const name = assetName(path);
4703
+ if (name) names.add(name);
4704
+ }
4705
+ for (const path of packaged.keys()) {
4706
+ const name = assetName(path);
4707
+ if (name) names.add(name);
4708
+ }
4709
+ for (const name of [...names].sort()) {
4710
+ const a = local.get(`${ASSETS}${name}`);
4711
+ const b = packaged.get(`${ASSETS}${name}`);
4712
+ if (a && !b) removed.push(name);
4713
+ else if (!a && b) added.push(name);
4714
+ else if (!sameBytes(a, b)) changed.push(name);
4715
+ }
4716
+ return {
4717
+ added,
4718
+ changed,
4719
+ removed
4720
+ };
4721
+ }
4722
+ function compareOtherFiles(local, packaged, entry) {
4723
+ const paths = /* @__PURE__ */ new Set();
4724
+ for (const path of local.keys()) paths.add(path);
4725
+ for (const path of packaged.keys()) paths.add(path);
4726
+ for (const path of paths) {
4727
+ if (path === entry || assetName(path) !== null) continue;
4728
+ if (!sameBytes(local.get(path), packaged.get(path))) return true;
4729
+ }
4730
+ return false;
4731
+ }
4732
+ function statusFor(local, packaged) {
4733
+ const moved = local.index !== packaged.index;
4734
+ if (local.source !== packaged.source) return {
4735
+ status: "changed",
4736
+ notes: false
4737
+ };
4738
+ return {
4739
+ status: moved ? "moved" : "same",
4740
+ notes: false
4741
+ };
4742
+ }
4743
+ function notesChanged(local, localIndex, packaged, packagedIndex) {
4744
+ return (local?.[localIndex] ?? "") !== (packaged?.[packagedIndex] ?? "");
4745
+ }
4746
+ function comparePages(local, packaged) {
4747
+ const out = [];
4748
+ const named = /* @__PURE__ */ new Map();
4749
+ const localInline = [];
4750
+ const packagedInline = [];
4751
+ for (const page of local.pages) {
4752
+ if (page.name === null) {
4753
+ localInline.push(page);
4754
+ continue;
4755
+ }
4756
+ const entry = named.get(page.name) ?? {
4757
+ local: [],
4758
+ packaged: []
4759
+ };
4760
+ entry.local.push(page);
4761
+ named.set(page.name, entry);
4762
+ }
4763
+ for (const page of packaged.pages) {
4764
+ if (page.name === null) {
4765
+ packagedInline.push(page);
4766
+ continue;
4767
+ }
4768
+ const entry = named.get(page.name) ?? {
4769
+ local: [],
4770
+ packaged: []
4771
+ };
4772
+ entry.packaged.push(page);
4773
+ named.set(page.name, entry);
4774
+ }
4775
+ for (const [name, entry] of named) {
4776
+ const count = Math.max(entry.local.length, entry.packaged.length);
4777
+ for (let k = 0; k < count; k++) {
4778
+ const a = entry.local[k];
4779
+ const b = entry.packaged[k];
4780
+ if (a && b) {
4781
+ const { status } = statusFor(a, b);
4782
+ const notes = notesChanged(local.notes, a.index, packaged.notes, b.index);
4783
+ out.push({
4784
+ n: b.index + 1,
4785
+ status: status === "same" && notes ? "changed" : status,
4786
+ name,
4787
+ notes,
4788
+ notesOnly: a.source === b.source && notes
4789
+ });
4790
+ continue;
4791
+ }
4792
+ if (b) out.push({
4793
+ n: b.index + 1,
4794
+ status: "added",
4795
+ name,
4796
+ notes: false,
4797
+ notesOnly: false
4798
+ });
4799
+ else if (a) out.push({
4800
+ n: a.index + 1,
4801
+ status: "removed",
4802
+ name,
4803
+ notes: false,
4804
+ notesOnly: false
4805
+ });
4806
+ }
4807
+ }
4808
+ const inlineCount = Math.max(localInline.length, packagedInline.length);
4809
+ for (let k = 0; k < inlineCount; k++) {
4810
+ const a = localInline[k];
4811
+ const b = packagedInline[k];
4812
+ if (a && b) {
4813
+ const { status } = statusFor(a, b);
4814
+ const notes = notesChanged(local.notes, a.index, packaged.notes, b.index);
4815
+ out.push({
4816
+ n: b.index + 1,
4817
+ status: status === "same" && notes ? "changed" : status,
4818
+ name: null,
4819
+ notes,
4820
+ notesOnly: a.source === b.source && notes
4821
+ });
4822
+ continue;
4823
+ }
4824
+ if (b) out.push({
4825
+ n: b.index + 1,
4826
+ status: "added",
4827
+ name: null,
4828
+ notes: false,
4829
+ notesOnly: false
4830
+ });
4831
+ else if (a) out.push({
4832
+ n: a.index + 1,
4833
+ status: "removed",
4834
+ name: null,
4835
+ notes: false,
4836
+ notesOnly: false
4837
+ });
4838
+ }
4839
+ return out.sort((a, b) => a.n - b.n);
4840
+ }
4841
+ function compareDeck(localFiles, packagedFiles) {
4842
+ const local = toMap(localFiles);
4843
+ const packaged = toMap(packagedFiles);
4844
+ const entry = entryKey(local) ?? entryKey(packaged);
4845
+ const assets = compareAssets(local, packaged);
4846
+ if (entry === null) return {
4847
+ pages: [],
4848
+ shared: compareOtherFiles(local, packaged, entry),
4849
+ assets,
4850
+ readable: false
4851
+ };
4852
+ const decoder = new TextDecoder();
4853
+ const localDeck = parseDeck(decoder.decode(local.get(entry) ?? /* @__PURE__ */ new Uint8Array()));
4854
+ const packagedDeck = parseDeck(decoder.decode(packaged.get(entry) ?? /* @__PURE__ */ new Uint8Array()));
4855
+ const otherFilesChanged = compareOtherFiles(local, packaged, entry);
4856
+ if (!localDeck.ok || !packagedDeck.ok) {
4857
+ const entryChanged = !sameBytes(local.get(entry), packaged.get(entry));
4858
+ return {
4859
+ pages: [],
4860
+ shared: otherFilesChanged || entryChanged,
4861
+ assets,
4862
+ readable: false
4863
+ };
4864
+ }
4865
+ return {
4866
+ pages: comparePages(localDeck, packagedDeck),
4867
+ shared: localDeck.shared !== packagedDeck.shared || otherFilesChanged,
4868
+ assets,
4869
+ readable: true
4870
+ };
4871
+ }
4872
+ //#endregion
4873
+ //#region src/app/lemonriver/share/paths.ts
4874
+ /** Slide ids are the same shape the editor uses for a deck folder. */
4875
+ const SHARE_SLIDE_ID_RE = /^[a-z0-9_-]+$/i;
4876
+ const SLIDE_EXTENSIONS = /* @__PURE__ */ new Set([
4877
+ "tsx",
4878
+ "ts",
4879
+ "jsx",
4880
+ "js",
4881
+ "mjs",
4882
+ "json",
4883
+ "css",
4884
+ "md",
4885
+ "txt",
4886
+ "csv",
4887
+ "png",
4888
+ "jpg",
4889
+ "jpeg",
4890
+ "gif",
4891
+ "webp",
4892
+ "svg",
4893
+ "avif",
4894
+ "ico",
4895
+ "bmp",
4896
+ "mp4",
4897
+ "webm",
4898
+ "mov",
4899
+ "mp3",
4900
+ "wav",
4901
+ "m4a",
4902
+ "ogg",
4903
+ "woff",
4904
+ "woff2",
4905
+ "ttf",
4906
+ "otf",
4907
+ "pdf",
4908
+ "xlsx",
4909
+ "xls",
4910
+ "docx",
4911
+ "doc",
4912
+ "pptx",
4913
+ "key",
4914
+ "numbers",
4915
+ "pages"
4916
+ ]);
4917
+ const BLOCKED_SLIDE_FILES = /^(?:package\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb|\.npmrc|vite\.config\..+|lemonriver\.config\..+|open-slide\.config\..+)$/i;
4918
+ function extensionOf(name) {
4919
+ const dot = name.lastIndexOf(".");
4920
+ return dot > 0 ? name.slice(dot + 1).toLowerCase() : "";
4921
+ }
4922
+ /** `LICENSE`, `OFL.txt` and friends: no extension we would accept otherwise. */
4923
+ function looksLikeLicence(name) {
4924
+ return /^(?:LICENSE|OFL)/i.test(name) || name === name.toUpperCase() && /^[A-Z0-9][A-Z0-9._-]*$/.test(name);
4925
+ }
4926
+ function structuralProblem(rel) {
4927
+ if (rel === "") return {
4928
+ code: "bad-path",
4929
+ detail: "empty path"
4930
+ };
4931
+ if (rel.includes("\0")) return {
4932
+ code: "bad-path",
4933
+ detail: "path holds a null byte"
4934
+ };
4935
+ if (rel.includes("\\")) return {
4936
+ code: "bad-path",
4937
+ detail: "backslash in path"
4938
+ };
4939
+ if (rel.startsWith("/") || /^[a-z]:/i.test(rel)) return {
4940
+ code: "bad-path",
4941
+ detail: "absolute path"
4942
+ };
4943
+ for (const segment of rel.split("/")) {
4944
+ if (segment === "") return {
4945
+ code: "bad-path",
4946
+ detail: "empty path segment"
4947
+ };
4948
+ if (segment === "." || segment === "..") return {
4949
+ code: "bad-path",
4950
+ detail: "path climbs out"
4951
+ };
4952
+ if (segment.startsWith(".") && segment !== "..") return {
4953
+ code: "bad-path",
4954
+ detail: `hidden segment "${segment}"`
4955
+ };
4956
+ if (segment.toLowerCase() === "node_modules") return {
4957
+ code: "blocked-file",
4958
+ detail: "node_modules is not shipped"
4959
+ };
4960
+ }
4961
+ return null;
4962
+ }
4963
+ function slideFileProblem(rest) {
4964
+ const name = rest.slice(rest.lastIndexOf("/") + 1);
4965
+ if (BLOCKED_SLIDE_FILES.test(name)) return {
4966
+ code: "blocked-file",
4967
+ detail: `${name} would configure the other machine`
4968
+ };
4969
+ if (looksLikeLicence(name)) return null;
4970
+ const extension = extensionOf(name);
4971
+ if (extension === "" || !SLIDE_EXTENSIONS.has(extension)) return {
4972
+ code: "blocked-file",
4973
+ detail: `"${name}" is not a file a deck may carry`
4974
+ };
4975
+ return null;
4976
+ }
4977
+ /**
4978
+ * One rule for both ends: what may sit under `LemonRiver-files/`. Anything the
4979
+ * packer would refuse is also refused on the way in.
4980
+ */
4981
+ function packagePathProblem(rel) {
4982
+ const structural = structuralProblem(rel);
4983
+ if (structural) return structural;
4984
+ const segments = rel.split("/");
4985
+ const [head, ...rest] = segments;
4986
+ if (head === "manifest.json") return segments.length === 1 ? null : {
4987
+ code: "bad-path",
4988
+ detail: "manifest.json is a file"
4989
+ };
4990
+ if (head === "board") {
4991
+ if (rest.length !== 1 || !rest[0].endsWith(".json")) return {
4992
+ code: "bad-path",
4993
+ detail: "board holds <slideId>.json only"
4994
+ };
4995
+ const id = rest[0].slice(0, -5);
4996
+ if (!SHARE_SLIDE_ID_RE.test(id)) return {
4997
+ code: "bad-path",
4998
+ detail: `bad slide id "${id}"`
4999
+ };
5000
+ return null;
5001
+ }
5002
+ if (head === "themes") {
5003
+ if (rest.length !== 1) return {
5004
+ code: "bad-path",
5005
+ detail: "themes holds files only"
5006
+ };
5007
+ const name = rest[0];
5008
+ if (name.endsWith(".demo.tsx")) {
5009
+ const id = name.slice(0, -9);
5010
+ if (!SHARE_SLIDE_ID_RE.test(id)) return {
5011
+ code: "bad-path",
5012
+ detail: `bad theme id "${id}"`
5013
+ };
5014
+ return null;
5015
+ }
5016
+ if (name.endsWith(".md")) {
5017
+ const id = name.slice(0, -3);
5018
+ if (!SHARE_SLIDE_ID_RE.test(id)) return {
5019
+ code: "bad-path",
5020
+ detail: `bad theme id "${id}"`
5021
+ };
5022
+ return null;
5023
+ }
5024
+ return {
5025
+ code: "bad-path",
5026
+ detail: "a theme is <id>.md or <id>.demo.tsx"
5027
+ };
5028
+ }
5029
+ if (head === "thumbs") {
5030
+ if (rest.length !== 2 || !/^\d{2,}\.jpg$/.test(rest[1])) return {
5031
+ code: "bad-path",
5032
+ detail: "a thumbnail is <slideId>/NN.jpg"
5033
+ };
5034
+ if (!SHARE_SLIDE_ID_RE.test(rest[0])) return {
5035
+ code: "bad-path",
5036
+ detail: `bad slide id "${rest[0]}"`
5037
+ };
5038
+ return null;
5039
+ }
5040
+ if (head === "slides") {
5041
+ if (rest.length < 2) return {
5042
+ code: "bad-path",
5043
+ detail: "a slide holds at least one file"
5044
+ };
5045
+ if (!SHARE_SLIDE_ID_RE.test(rest[0])) return {
5046
+ code: "bad-path",
5047
+ detail: `bad slide id "${rest[0]}"`
5048
+ };
5049
+ return slideFileProblem(rest.slice(1).join("/"));
5050
+ }
5051
+ return {
5052
+ code: "bad-path",
5053
+ detail: `"${head}" is not part of a package`
5054
+ };
5055
+ }
5056
+ /** Ignored on the way in: what a Mac leaves behind when it zips a folder. */
5057
+ function isJunkPath(rel) {
5058
+ if (rel.startsWith("__MACOSX/") || rel === "__MACOSX") return true;
5059
+ return rel.split("/").some((segment) => segment === ".DS_Store");
5060
+ }
5061
+ //#endregion
5062
+ //#region src/vite/recent-writes.ts
5063
+ const recentWrites = /* @__PURE__ */ new Map();
5064
+ /** Record that `file` was just written by us. */
5065
+ function recordWrite(file, now = Date.now()) {
5066
+ recentWrites.set(file, now);
5067
+ }
5068
+ /**
5069
+ * True if `file` was recorded within the recent-write window. Expired entries
5070
+ * are pruned so a stale path can no longer suppress a later genuine edit.
5071
+ */
5072
+ function hasRecentWrite(file, now = Date.now()) {
5073
+ const ts = recentWrites.get(file);
5074
+ if (ts == null) return false;
5075
+ if (now - ts < 1500) return true;
5076
+ recentWrites.delete(file);
5077
+ return false;
5078
+ }
5079
+ //#endregion
5080
+ //#region src/vite/open-slide-plugin.ts
5081
+ const SLIDES_VMOD = "virtual:open-slide/slides";
5082
+ const CONFIG_VMOD = "virtual:open-slide/config";
5083
+ const FOLDERS_VMOD = "virtual:open-slide/folders";
5084
+ function resolved$1(id) {
5085
+ return `\0${id}`;
5086
+ }
5087
+ async function findSlides(userCwd, slidesDir) {
5088
+ const abs = path.resolve(userCwd, slidesDir);
5089
+ if (!existsSync(abs)) return [];
5090
+ return (await fg("*/index.{tsx,jsx,ts,js}", {
5091
+ cwd: abs,
5092
+ absolute: true,
5093
+ onlyFiles: true
5094
+ })).sort();
5095
+ }
5096
+ function toId(absFile, slidesRoot) {
5097
+ return path.relative(slidesRoot, absFile).split(path.sep)[0];
5098
+ }
5099
+ const META_THEME_RE = /(?:^|[\s,{])theme\s*:\s*['"]([^'"]+)['"]/;
5100
+ const META_CREATED_AT_RE = /(?:^|[\s,{])createdAt\s*:\s*['"]([^'"]+)['"]/;
5101
+ function extractMeta(src) {
5102
+ const empty = {
5103
+ theme: null,
5104
+ createdAt: null
5105
+ };
5106
+ const metaStart = src.search(/export\s+const\s+meta\b/);
5107
+ if (metaStart === -1) return empty;
5108
+ const eqIdx = src.indexOf("=", metaStart);
5109
+ if (eqIdx === -1) return empty;
5110
+ const openBrace = src.indexOf("{", eqIdx);
5111
+ if (openBrace === -1) return empty;
5112
+ let depth = 0;
5113
+ let closeBrace = -1;
5114
+ for (let i = openBrace; i < src.length; i++) {
5115
+ const ch = src[i];
5116
+ if (ch === "{") depth++;
5117
+ else if (ch === "}") {
5118
+ depth--;
5119
+ if (depth === 0) {
5120
+ closeBrace = i;
5121
+ break;
5122
+ }
5123
+ }
5124
+ }
5125
+ if (closeBrace === -1) return empty;
5126
+ const body = src.slice(openBrace + 1, closeBrace);
5127
+ const themeMatch = body.match(META_THEME_RE);
5128
+ const createdAtMatch = body.match(META_CREATED_AT_RE);
5129
+ return {
5130
+ theme: themeMatch ? themeMatch[1] : null,
5131
+ createdAt: createdAtMatch ? createdAtMatch[1] : null
5132
+ };
5133
+ }
5134
+ async function readSlideMeta(abs) {
5135
+ try {
5136
+ return extractMeta(await fs.readFile(abs, "utf8"));
5137
+ } catch {
5138
+ return {
5139
+ theme: null,
5140
+ createdAt: null
5141
+ };
5142
+ }
5143
+ }
5144
+ function parseCreatedAtMs(iso) {
5145
+ if (!iso) return null;
5146
+ const ms = Date.parse(iso);
5147
+ return Number.isFinite(ms) ? ms : null;
5148
+ }
5149
+ const warnedInvalidSlideIds = /* @__PURE__ */ new Set();
5150
+ async function generateSlidesModule(files, slidesRoot, isDev) {
5151
+ const scanned = await Promise.all(files.map(async (abs) => {
5152
+ const id = toId(abs, slidesRoot);
5153
+ const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
5154
+ const meta = await readSlideMeta(abs);
5155
+ return {
5156
+ id,
5157
+ importPath,
5158
+ theme: meta.theme,
5159
+ createdAt: parseCreatedAtMs(meta.createdAt)
3560
5160
  };
3561
5161
  }));
3562
5162
  const entries = scanned.filter((e) => SLIDE_ID_RE.test(e.id));
@@ -3756,7 +5356,7 @@ function inside(root, id) {
3756
5356
  const dir = path.resolve(root, id);
3757
5357
  return dir.startsWith(path.resolve(root) + path.sep) ? dir : null;
3758
5358
  }
3759
- async function exists(p) {
5359
+ async function exists$1(p) {
3760
5360
  try {
3761
5361
  await fs.access(p);
3762
5362
  return true;
@@ -3802,164 +5402,1129 @@ function toEntry(id, raw) {
3802
5402
  expiresAt: r.deletedAt + TRASH_RETENTION_MS
3803
5403
  };
3804
5404
  }
3805
- async function readEntry(trashRoot, id) {
3806
- if (!isTrashEntryId(id)) return null;
3807
- const dir = inside(trashRoot, id);
3808
- if (!dir) return null;
5405
+ async function readEntry(trashRoot, id) {
5406
+ if (!isTrashEntryId(id)) return null;
5407
+ const dir = inside(trashRoot, id);
5408
+ if (!dir) return null;
5409
+ try {
5410
+ const entry = toEntry(id, JSON.parse(await fs.readFile(path.join(dir, ENTRY_FILE), "utf8")));
5411
+ return entry && await exists$1(path.join(dir, SLIDE_DIR)) ? entry : null;
5412
+ } catch {
5413
+ return null;
5414
+ }
5415
+ }
5416
+ async function idTaken(slidesRoot, slideId) {
5417
+ try {
5418
+ const want = slideId.toLowerCase();
5419
+ return (await fs.readdir(slidesRoot)).some((name) => name.toLowerCase() === want);
5420
+ } catch {
5421
+ return false;
5422
+ }
5423
+ }
5424
+ async function freeSlideId(slidesRoot, slideId) {
5425
+ if (!await idTaken(slidesRoot, slideId)) return slideId;
5426
+ for (let n = 1;; n++) {
5427
+ const candidate = n === 1 ? `${slideId}-restored` : `${slideId}-restored-${n}`;
5428
+ if (!await idTaken(slidesRoot, candidate)) return candidate;
5429
+ }
5430
+ }
5431
+ async function listTrash(paths, now = Date.now()) {
5432
+ let names;
5433
+ try {
5434
+ names = await fs.readdir(paths.trashRoot);
5435
+ } catch {
5436
+ return [];
5437
+ }
5438
+ const entries = [];
5439
+ for (const name of names) {
5440
+ const entry = await readEntry(paths.trashRoot, name);
5441
+ if (!entry) continue;
5442
+ if (now >= entry.expiresAt) {
5443
+ await purgeTrashEntry(paths, entry.id);
5444
+ continue;
5445
+ }
5446
+ entries.push(entry);
5447
+ }
5448
+ return entries.sort((a, b) => b.deletedAt - a.deletedAt);
5449
+ }
5450
+ async function moveSlideToTrash(paths, slideId, now = Date.now()) {
5451
+ if (!SLIDE_ID_RE.test(slideId)) return {
5452
+ ok: false,
5453
+ status: 400,
5454
+ error: "invalid slideId"
5455
+ };
5456
+ const slideDir = inside(paths.slidesRoot, slideId);
5457
+ if (!slideDir || !await exists$1(slideDir)) return {
5458
+ ok: false,
5459
+ status: 404,
5460
+ error: "slide not found"
5461
+ };
5462
+ let deletedAt = now;
5463
+ while (await exists$1(path.join(paths.trashRoot, `${slideId}.${deletedAt}`))) deletedAt++;
5464
+ const id = `${slideId}.${deletedAt}`;
5465
+ const entryDir = path.join(paths.trashRoot, id);
5466
+ const manifest = await readManifest(paths.manifestPath);
5467
+ const folderId = manifest.assignments[slideId] ?? null;
5468
+ const title = await readTitle(slideDir, slideId);
5469
+ await fs.mkdir(entryDir, { recursive: true });
5470
+ await fs.writeFile(path.join(entryDir, ENTRY_FILE), `${JSON.stringify({
5471
+ slideId,
5472
+ title,
5473
+ folderId,
5474
+ deletedAt
5475
+ }, null, 2)}\n`, "utf8");
5476
+ try {
5477
+ await moveDir(slideDir, path.join(entryDir, SLIDE_DIR));
5478
+ } catch (err) {
5479
+ await fs.rm(entryDir, {
5480
+ recursive: true,
5481
+ force: true
5482
+ });
5483
+ throw err;
5484
+ }
5485
+ if (folderId !== null) {
5486
+ delete manifest.assignments[slideId];
5487
+ await writeManifest(paths.manifestPath, manifest);
5488
+ }
5489
+ return {
5490
+ ok: true,
5491
+ entry: {
5492
+ id,
5493
+ slideId,
5494
+ title,
5495
+ folderId,
5496
+ deletedAt,
5497
+ expiresAt: deletedAt + TRASH_RETENTION_MS
5498
+ }
5499
+ };
5500
+ }
5501
+ async function restoreTrashEntry(paths, id, beforeMove = () => {}) {
5502
+ const entry = await readEntry(paths.trashRoot, id);
5503
+ if (!entry) return {
5504
+ ok: false,
5505
+ status: 404,
5506
+ error: "trash entry not found"
5507
+ };
5508
+ const entryDir = path.join(paths.trashRoot, id);
5509
+ const slideId = await freeSlideId(paths.slidesRoot, entry.slideId);
5510
+ const slideDir = inside(paths.slidesRoot, slideId);
5511
+ if (!slideDir) return {
5512
+ ok: false,
5513
+ status: 400,
5514
+ error: "invalid slideId"
5515
+ };
5516
+ await fs.mkdir(paths.slidesRoot, { recursive: true });
5517
+ beforeMove(slideId);
5518
+ await moveDir(path.join(entryDir, SLIDE_DIR), slideDir);
5519
+ await fs.rm(entryDir, {
5520
+ recursive: true,
5521
+ force: true
5522
+ });
5523
+ if (entry.folderId !== null) {
5524
+ const manifest = await readManifest(paths.manifestPath);
5525
+ if (manifest.folders.some((f) => f.id === entry.folderId)) {
5526
+ manifest.assignments[slideId] = entry.folderId;
5527
+ await writeManifest(paths.manifestPath, manifest);
5528
+ }
5529
+ }
5530
+ return {
5531
+ ok: true,
5532
+ slideId
5533
+ };
5534
+ }
5535
+ async function purgeTrashEntry(paths, id) {
5536
+ if (!isTrashEntryId(id)) return false;
5537
+ const dir = inside(paths.trashRoot, id);
5538
+ if (!dir || !await exists$1(dir)) return false;
5539
+ await fs.rm(dir, {
5540
+ recursive: true,
5541
+ force: true
5542
+ });
5543
+ return true;
5544
+ }
5545
+ //#endregion
5546
+ //#region src/lemonriver/trash/routes.ts
5547
+ const ENTRY_NAMES$2 = [
5548
+ "index.tsx",
5549
+ "index.jsx",
5550
+ "index.ts",
5551
+ "index.js"
5552
+ ];
5553
+ const DECKS_CHANGED_EVENT = "lemonriver:decks-changed";
5554
+ function registerTrashRoutes(server, ctx) {
5555
+ const paths = {
5556
+ slidesRoot: ctx.slidesRoot,
5557
+ manifestPath: ctx.manifestPath,
5558
+ trashRoot: trashRootFor(ctx.userCwd)
5559
+ };
5560
+ const quietWatcher = (slideId) => {
5561
+ for (const name of ENTRY_NAMES$2) recordWrite(path.join(ctx.slidesRoot, slideId, name));
5562
+ };
5563
+ const reloadClients = () => {
5564
+ invalidateSlidesModule(server);
5565
+ server.ws.send({
5566
+ type: "custom",
5567
+ event: DECKS_CHANGED_EVENT
5568
+ });
5569
+ };
5570
+ server.middlewares.use("/__lr/trash", async (req, res, next) => {
5571
+ const url = new URL(req.url ?? "/", "http://local");
5572
+ const method = req.method ?? "GET";
5573
+ try {
5574
+ if (method === "GET" && url.pathname === "/") return json(res, 200, { entries: await listTrash(paths) });
5575
+ if (method === "POST" && url.pathname === "/") {
5576
+ const check = validateMutationRequest(req, { requireJsonBody: true });
5577
+ if (!check.ok) return json(res, check.status, { error: check.error });
5578
+ const body = await readBody(req);
5579
+ const slideId = typeof body?.slideId === "string" ? body.slideId : "";
5580
+ if (!SLIDE_ID_RE.test(slideId)) return json(res, 400, { error: "invalid slideId" });
5581
+ quietWatcher(slideId);
5582
+ const moved = await moveSlideToTrash(paths, slideId);
5583
+ if (!moved.ok) return json(res, moved.status, { error: moved.error });
5584
+ json(res, 200, {
5585
+ ok: true,
5586
+ entry: moved.entry
5587
+ });
5588
+ return reloadClients();
5589
+ }
5590
+ const restoreMatch = url.pathname.match(/^\/([^/]+)\/restore$/);
5591
+ if (method === "POST" && restoreMatch) {
5592
+ const check = validateMutationRequest(req);
5593
+ if (!check.ok) return json(res, check.status, { error: check.error });
5594
+ const id = decodeURIComponent(restoreMatch[1]);
5595
+ if (!isTrashEntryId(id)) return json(res, 400, { error: "invalid trash id" });
5596
+ const restored = await restoreTrashEntry(paths, id, quietWatcher);
5597
+ if (!restored.ok) return json(res, restored.status, { error: restored.error });
5598
+ json(res, 200, {
5599
+ ok: true,
5600
+ slideId: restored.slideId
5601
+ });
5602
+ return reloadClients();
5603
+ }
5604
+ const entryMatch = url.pathname.match(/^\/([^/]+)$/);
5605
+ if (method === "DELETE" && entryMatch) {
5606
+ const check = validateMutationRequest(req);
5607
+ if (!check.ok) return json(res, check.status, { error: check.error });
5608
+ const id = decodeURIComponent(entryMatch[1]);
5609
+ if (!isTrashEntryId(id)) return json(res, 400, { error: "invalid trash id" });
5610
+ if (!await purgeTrashEntry(paths, id)) return json(res, 404, { error: "trash entry not found" });
5611
+ return json(res, 200, { ok: true });
5612
+ }
5613
+ next();
5614
+ } catch (err) {
5615
+ json(res, 500, { error: String(err.message ?? err) });
5616
+ }
5617
+ });
5618
+ }
5619
+ //#endregion
5620
+ //#region src/lemonriver/share/identity.ts
5621
+ /**
5622
+ * Finds the deck a package came from. Packing writes the share id back to the
5623
+ * deck that was sent, so after a copy is imported two decks can carry it. The
5624
+ * imported one is the one the user means by "the one I already have".
5625
+ */
5626
+ async function shareIdOwner(userCwd, shareId, preferredId = "") {
5627
+ const dir = path.dirname(boardStructurePath(userCwd, "x"));
5628
+ const names = await fs.readdir(dir).catch(() => []);
5629
+ let importedAt = Number.NEGATIVE_INFINITY;
5630
+ let importedId = null;
5631
+ let preferred = null;
5632
+ let first = null;
5633
+ for (const name of names) {
5634
+ if (!name.endsWith(".json")) continue;
5635
+ const record = await readBoardFile(path.join(dir, name)).catch(() => ({}));
5636
+ if (record.shareId !== shareId) continue;
5637
+ const id = name.slice(0, -5);
5638
+ first ??= id;
5639
+ if (id === preferredId) preferred = id;
5640
+ const imported = record.imported;
5641
+ if (typeof imported?.at === "number" && imported.at > importedAt) {
5642
+ importedAt = imported.at;
5643
+ importedId = id;
5644
+ }
5645
+ }
5646
+ return importedId ?? preferred ?? first;
5647
+ }
5648
+ //#endregion
5649
+ //#region src/app/lemonriver/share/model.ts
5650
+ /** The parts of a share package both ends must agree on. */
5651
+ const SHARE_FORMAT = "lemonriver";
5652
+ const SHARE_ROOT = "LemonRiver-files";
5653
+ const SHARE_MANIFEST = "manifest.json";
5654
+ const SHARE_APP_NAME = "LemonRiver";
5655
+ const KIND = ["share", "backup"];
5656
+ function isRecord(value) {
5657
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5658
+ }
5659
+ function readDeck(raw) {
5660
+ if (!isRecord(raw)) return null;
5661
+ const { slideId, title, shareId } = raw;
5662
+ if (typeof slideId !== "string" || slideId === "") return null;
5663
+ if (typeof title !== "string") return null;
5664
+ if (typeof shareId !== "string" || shareId === "") return null;
5665
+ const pages = typeof raw.pages === "number" && raw.pages >= 0 ? Math.round(raw.pages) : null;
5666
+ const thumbs = typeof raw.thumbs === "number" && raw.thumbs >= 0 ? Math.round(raw.thumbs) : 0;
5667
+ return {
5668
+ slideId,
5669
+ title,
5670
+ pages,
5671
+ shareId,
5672
+ theme: typeof raw.theme === "string" && raw.theme !== "" ? raw.theme : null,
5673
+ thumbs
5674
+ };
5675
+ }
5676
+ /**
5677
+ * Reads a manifest without trusting any of it. A version above ours is its own
5678
+ * answer, because the package may still be perfectly well formed.
5679
+ */
5680
+ function sanitizeManifest(raw) {
5681
+ if (!isRecord(raw)) return {
5682
+ ok: false,
5683
+ code: "bad-manifest",
5684
+ detail: "manifest is not an object"
5685
+ };
5686
+ if (raw.format !== "lemonriver") return {
5687
+ ok: false,
5688
+ code: "not-a-package",
5689
+ detail: "this zip is not a LemonRiver package"
5690
+ };
5691
+ const version = raw.version;
5692
+ if (typeof version !== "number" || !Number.isInteger(version) || version < 1) return {
5693
+ ok: false,
5694
+ code: "bad-manifest",
5695
+ detail: "manifest has no usable version"
5696
+ };
5697
+ const app = isRecord(raw.app) ? raw.app : {};
5698
+ const appVersion = typeof app.version === "string" ? app.version : "";
5699
+ if (version > 1) return {
5700
+ ok: false,
5701
+ code: "newer-version",
5702
+ detail: `made by a newer LemonRiver (${appVersion || "unknown version"})`,
5703
+ appVersion
5704
+ };
5705
+ const kind = raw.kind;
5706
+ if (typeof kind !== "string" || !KIND.includes(kind)) return {
5707
+ ok: false,
5708
+ code: "bad-manifest",
5709
+ detail: "manifest has no usable kind"
5710
+ };
5711
+ if (!Array.isArray(raw.decks) || raw.decks.length === 0) return {
5712
+ ok: false,
5713
+ code: "bad-manifest",
5714
+ detail: "manifest lists no decks"
5715
+ };
5716
+ const decks = [];
5717
+ for (const entry of raw.decks) {
5718
+ const deck = readDeck(entry);
5719
+ if (!deck) return {
5720
+ ok: false,
5721
+ code: "bad-manifest",
5722
+ detail: "manifest has a broken deck entry"
5723
+ };
5724
+ decks.push(deck);
5725
+ }
5726
+ if (!isRecord(raw.files)) return {
5727
+ ok: false,
5728
+ code: "bad-manifest",
5729
+ detail: "manifest lists no files"
5730
+ };
5731
+ const files = {};
5732
+ for (const [file, digest] of Object.entries(raw.files)) {
5733
+ if (typeof digest !== "string" || digest === "") return {
5734
+ ok: false,
5735
+ code: "bad-manifest",
5736
+ detail: `no checksum for ${file}`
5737
+ };
5738
+ files[file] = digest;
5739
+ }
5740
+ const createdAt = typeof raw.createdAt === "number" && Number.isFinite(raw.createdAt) ? raw.createdAt : 0;
5741
+ return {
5742
+ ok: true,
5743
+ manifest: {
5744
+ format: SHARE_FORMAT,
5745
+ version,
5746
+ kind,
5747
+ app: {
5748
+ name: typeof app.name === "string" ? app.name : SHARE_APP_NAME,
5749
+ version: appVersion
5750
+ },
5751
+ createdAt,
5752
+ decks,
5753
+ files
5754
+ }
5755
+ };
5756
+ }
5757
+ /** The keys a board record may not carry into a package or back out of one. */
5758
+ const BOARD_STRIP_KEYS = [
5759
+ "applyBackup",
5760
+ "applyColumns",
5761
+ "applyColumnsBackup",
5762
+ "applying",
5763
+ "lastApply"
5764
+ ];
5765
+ function stripBoardRecord(record) {
5766
+ const kept = {};
5767
+ for (const [key, value] of Object.entries(record)) {
5768
+ if (BOARD_STRIP_KEYS.includes(key)) continue;
5769
+ kept[key] = value;
5770
+ }
5771
+ return kept;
5772
+ }
5773
+ //#endregion
5774
+ //#region src/app/lemonriver/share/naming.ts
5775
+ const RESERVED = /* @__PURE__ */ new Set([
5776
+ "/",
5777
+ "\\",
5778
+ ":",
5779
+ "*",
5780
+ "?",
5781
+ "\"",
5782
+ "<",
5783
+ ">",
5784
+ "|"
5785
+ ]);
5786
+ const MAX_BASE = 80;
5787
+ function clean(raw) {
5788
+ let out = "";
5789
+ for (const character of raw) {
5790
+ const code = character.codePointAt(0) ?? 0;
5791
+ if (code < 32 || code === 127) continue;
5792
+ if (RESERVED.has(character)) continue;
5793
+ out += character;
5794
+ }
5795
+ return out.replace(/\s+/g, " ").trim().slice(0, MAX_BASE).trim();
5796
+ }
5797
+ /** What the user can call a file without tripping over macOS, Windows or Finder. */
5798
+ function safeFileName(raw, fallback) {
5799
+ const name = clean(raw);
5800
+ if (name !== "") return name;
5801
+ const fallbackName = clean(fallback);
5802
+ return fallbackName !== "" ? fallbackName : "LemonRiver";
5803
+ }
5804
+ function two(n) {
5805
+ return String(n).padStart(2, "0");
5806
+ }
5807
+ function dayStamp(now) {
5808
+ const date = new Date(now);
5809
+ return `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())}`;
5810
+ }
5811
+ /** One deck is named after itself; a set of them is a backup with a date. */
5812
+ function packageBaseName(decks, now) {
5813
+ if (decks.length === 1) {
5814
+ const [deck] = decks;
5815
+ return safeFileName(deck.title, deck.slideId);
5816
+ }
5817
+ return safeFileName(`LemonRiver 备份 ${dayStamp(now)}`, `LemonRiver-${dayStamp(now)}`);
5818
+ }
5819
+ /** Finder and Explorer both treat these as the same name. */
5820
+ function uniqueFileName(base, taken) {
5821
+ const used = new Set([...taken].map((name) => name.toLowerCase()));
5822
+ if (!used.has(base.toLowerCase())) return base;
5823
+ for (let n = 2;; n++) {
5824
+ const candidate = `${base} (${n})`;
5825
+ if (!used.has(candidate.toLowerCase())) return candidate;
5826
+ }
5827
+ }
5828
+ /** A deck that arrives beside one with the same id gets its own. */
5829
+ function freeImportSlideId(slideId, taken) {
5830
+ const used = new Set([...taken].map((id) => id.toLowerCase()));
5831
+ if (!used.has(slideId.toLowerCase())) return slideId;
5832
+ for (let n = 1;; n++) {
5833
+ const candidate = n === 1 ? `${slideId}-imported` : `${slideId}-imported-${n}`;
5834
+ if (!used.has(candidate.toLowerCase())) return candidate;
5835
+ }
5836
+ }
5837
+ const EXTRA_EXTENSIONS = /* @__PURE__ */ new Set([
5838
+ "pdf",
5839
+ "html",
5840
+ "txt"
5841
+ ]);
5842
+ /** The PDF and the how-to-open page ride at the top of the zip. */
5843
+ function isValidExtraName(name) {
5844
+ if (name === "" || name.startsWith(".") || name.includes("/") || name.includes("\\")) return false;
5845
+ if (name.includes("\0")) return false;
5846
+ const dot = name.lastIndexOf(".");
5847
+ if (dot <= 0) return false;
5848
+ return EXTRA_EXTENSIONS.has(name.slice(dot + 1).toLowerCase());
5849
+ }
5850
+ //#endregion
5851
+ //#region src/lemonriver/share/archive.ts
5852
+ const DEFAULT_ZIP_LIMITS = {
5853
+ maxFiles: 5e3,
5854
+ maxFileBytes: 104857600,
5855
+ maxTotalBytes: 524288e3
5856
+ };
5857
+ function sha256(bytes) {
5858
+ return createHash("sha256").update(bytes).digest("hex");
5859
+ }
5860
+ /**
5861
+ * Unpacks without ever trusting a size the archive declares after the fact:
5862
+ * the filter sees each entry's expanded size before fflate allocates it.
5863
+ */
5864
+ function unpackZip(bytes, limits = DEFAULT_ZIP_LIMITS) {
5865
+ let count = 0;
5866
+ let total = 0;
5867
+ let problem = null;
5868
+ let files;
5869
+ try {
5870
+ files = unzipSync(bytes, { filter: (file) => {
5871
+ if (problem) return false;
5872
+ if (isJunkPath(file.name)) return false;
5873
+ count += 1;
5874
+ if (count > limits.maxFiles) {
5875
+ problem = {
5876
+ code: "too-many-files",
5877
+ detail: `the package holds more than ${limits.maxFiles} files`
5878
+ };
5879
+ return false;
5880
+ }
5881
+ if (file.originalSize > limits.maxFileBytes) {
5882
+ problem = {
5883
+ code: "too-large",
5884
+ detail: `${file.name} unpacks to more than ${limits.maxFileBytes} bytes`
5885
+ };
5886
+ return false;
5887
+ }
5888
+ total += file.originalSize;
5889
+ if (total > limits.maxTotalBytes) {
5890
+ problem = {
5891
+ code: "too-large",
5892
+ detail: `the package unpacks to more than ${limits.maxTotalBytes} bytes`
5893
+ };
5894
+ return false;
5895
+ }
5896
+ return true;
5897
+ } });
5898
+ } catch {
5899
+ return {
5900
+ ok: false,
5901
+ code: "not-a-package",
5902
+ detail: "this file is not a zip"
5903
+ };
5904
+ }
5905
+ if (problem) {
5906
+ const failed = problem;
5907
+ return {
5908
+ ok: false,
5909
+ code: failed.code,
5910
+ detail: failed.detail
5911
+ };
5912
+ }
5913
+ const out = /* @__PURE__ */ new Map();
5914
+ for (const [name, data] of Object.entries(files)) {
5915
+ if (name.endsWith("/")) continue;
5916
+ out.set(name, data);
5917
+ }
5918
+ return {
5919
+ ok: true,
5920
+ files: out
5921
+ };
5922
+ }
5923
+ //#endregion
5924
+ //#region src/lemonriver/share/inspect.ts
5925
+ function failure(code, detail, extra = {}) {
5926
+ return {
5927
+ ok: false,
5928
+ code,
5929
+ detail,
5930
+ ...extra
5931
+ };
5932
+ }
5933
+ /**
5934
+ * A package is a zip of `LemonRiver-files/`. Three shapes turn up in the wild:
5935
+ * the folder inside another folder, at the root, or zipped by hand so the zip
5936
+ * root *is* the folder.
5937
+ */
5938
+ function findPrefix(files) {
5939
+ let best = null;
5940
+ for (const name of files.keys()) {
5941
+ let prefix = null;
5942
+ if (name === "manifest.json") prefix = "";
5943
+ else if (name === `LemonRiver-files/manifest.json`) prefix = `${SHARE_ROOT}/`;
5944
+ else if (name.endsWith(`/LemonRiver-files/manifest.json`)) prefix = name.slice(0, name.length - 13);
5945
+ if (prefix === null) continue;
5946
+ if (best === null || prefix.length < best.length) best = prefix;
5947
+ }
5948
+ return best;
5949
+ }
5950
+ function inspectBytes(bytes, limits) {
5951
+ const unpacked = unpackZip(bytes, limits);
5952
+ if (!unpacked.ok) return failure(unpacked.code, unpacked.detail);
5953
+ const prefix = findPrefix(unpacked.files);
5954
+ if (prefix === null) return failure("not-a-package", `no ${SHARE_ROOT}/${SHARE_MANIFEST} in the zip`);
5955
+ const inside = /* @__PURE__ */ new Map();
5956
+ for (const [name, data] of unpacked.files) {
5957
+ if (!name.startsWith(prefix)) continue;
5958
+ const rel = name.slice(prefix.length);
5959
+ if (rel === "" || rel === "manifest.json") continue;
5960
+ inside.set(rel, data);
5961
+ }
5962
+ const manifestBytes = unpacked.files.get(`${prefix}${SHARE_MANIFEST}`);
5963
+ if (!manifestBytes) return failure("bad-manifest", `no ${SHARE_ROOT}/${SHARE_MANIFEST} in the zip`);
5964
+ let raw;
5965
+ try {
5966
+ raw = JSON.parse(new TextDecoder().decode(manifestBytes));
5967
+ } catch {
5968
+ return failure("bad-manifest", "manifest.json is not readable JSON");
5969
+ }
5970
+ const read = sanitizeManifest(raw);
5971
+ if (!read.ok) return failure(read.code, read.detail, { ...read.appVersion ? { appVersion: read.appVersion } : {} });
5972
+ const manifest = read.manifest;
5973
+ const badPaths = [];
5974
+ let badCode = "bad-path";
5975
+ let badDetail = "";
5976
+ for (const rel of [...Object.keys(manifest.files), ...inside.keys()]) {
5977
+ const problem = packagePathProblem(rel);
5978
+ if (!problem) continue;
5979
+ badPaths.push(rel);
5980
+ badCode = problem.code;
5981
+ badDetail = `${rel}: ${problem.detail}`;
5982
+ }
5983
+ if (badPaths.length > 0) return failure(badCode, badDetail, { paths: badPaths });
5984
+ const missing = Object.keys(manifest.files).filter((rel) => !inside.has(rel));
5985
+ if (missing.length > 0) return failure("missing-file", `${missing[0]} is listed but not in the zip`, { paths: missing });
5986
+ const extra = [...inside.keys()].filter((rel) => !(rel in manifest.files));
5987
+ if (extra.length > 0) return failure("extra-file", `${extra[0]} is in the zip but not in the manifest`, { paths: extra });
5988
+ const wrong = Object.keys(manifest.files).filter((rel) => {
5989
+ const data = inside.get(rel);
5990
+ return data ? sha256(data) !== manifest.files[rel] : false;
5991
+ });
5992
+ if (wrong.length > 0) return failure("checksum", `${wrong[0]} does not match its checksum`, { paths: wrong });
5993
+ return {
5994
+ ok: true,
5995
+ manifest,
5996
+ files: inside
5997
+ };
5998
+ }
5999
+ /** The files a package holds for one deck, keyed relative to the package root. */
6000
+ function deckFiles(files, slideId) {
6001
+ const prefix = `slides/${slideId}/`;
6002
+ const out = [];
6003
+ for (const [rel, data] of files) {
6004
+ if (!rel.startsWith(prefix)) continue;
6005
+ out.push({
6006
+ path: rel.slice(prefix.length),
6007
+ data
6008
+ });
6009
+ }
6010
+ return out.sort((a, b) => a.path.localeCompare(b.path));
6011
+ }
6012
+ //#endregion
6013
+ //#region src/lemonriver/share/import.ts
6014
+ const BOARD_LIMIT = 5242880;
6015
+ async function localSlideIds(slidesRoot) {
6016
+ const names = await fs.readdir(slidesRoot).catch(() => []);
6017
+ return new Set(names);
6018
+ }
6019
+ function importableBoard(bytes) {
6020
+ if (!bytes) return null;
6021
+ if (bytes.length > BOARD_LIMIT) return null;
6022
+ try {
6023
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
6024
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
6025
+ return parsed;
6026
+ } catch {
6027
+ return null;
6028
+ }
6029
+ }
6030
+ async function importDecks(zipBytes, requests, deps) {
6031
+ const inspected = inspectBytes(zipBytes);
6032
+ if (!inspected.ok) return {
6033
+ ok: false,
6034
+ status: 400,
6035
+ error: `${inspected.code}: ${inspected.detail}`
6036
+ };
6037
+ const manifest = inspected.manifest;
6038
+ const warnings = [];
6039
+ const imported = [];
6040
+ const taken = await localSlideIds(deps.slidesRoot);
6041
+ for (const request of requests) {
6042
+ if (request.mode !== "copy" && request.mode !== "replace") return {
6043
+ ok: false,
6044
+ status: 400,
6045
+ error: "mode must be copy or replace"
6046
+ };
6047
+ const deck = manifest.decks.find((entry) => entry.slideId === request.slideId);
6048
+ if (!deck) return {
6049
+ ok: false,
6050
+ status: 400,
6051
+ error: `package has no deck ${request.slideId}`
6052
+ };
6053
+ const files = deckFiles(inspected.files, deck.slideId);
6054
+ if (files.length === 0) return {
6055
+ ok: false,
6056
+ status: 400,
6057
+ error: `package has no files for ${deck.slideId}`
6058
+ };
6059
+ const boardBytes = inspected.files.get(`board/${deck.slideId}.json`);
6060
+ const board = importableBoard(boardBytes);
6061
+ if (boardBytes && !board) {
6062
+ warnings.push(`${deck.slideId}: its board record is unreadable, so it is not imported`);
6063
+ continue;
6064
+ }
6065
+ let slideId;
6066
+ if (request.mode === "replace") {
6067
+ const owner = await shareIdOwner(deps.userCwd, deck.shareId, deck.slideId);
6068
+ if (!owner || !SHARE_SLIDE_ID_RE.test(owner)) return {
6069
+ ok: false,
6070
+ status: 409,
6071
+ error: `nothing on this machine to replace for ${deck.title}`
6072
+ };
6073
+ const moved = await moveSlideToTrash({
6074
+ slidesRoot: deps.slidesRoot,
6075
+ manifestPath: deps.manifestPath,
6076
+ trashRoot: trashRootFor(deps.userCwd)
6077
+ }, owner, deps.now);
6078
+ if (!moved.ok) return {
6079
+ ok: false,
6080
+ status: moved.status,
6081
+ error: moved.error
6082
+ };
6083
+ slideId = owner;
6084
+ } else slideId = freeImportSlideId(deck.slideId, taken);
6085
+ taken.add(slideId);
6086
+ const staging = path.join(deps.workDir, "staging", slideId);
6087
+ try {
6088
+ await fs.rm(staging, {
6089
+ recursive: true,
6090
+ force: true
6091
+ });
6092
+ for (const file of files) {
6093
+ const target = path.join(staging, file.path);
6094
+ if (!target.startsWith(staging + path.sep)) throw new Error("path escaped staging");
6095
+ await fs.mkdir(path.dirname(target), { recursive: true });
6096
+ await fs.writeFile(target, file.data);
6097
+ }
6098
+ await fs.mkdir(deps.slidesRoot, { recursive: true });
6099
+ await fs.rename(staging, path.join(deps.slidesRoot, slideId));
6100
+ } catch (err) {
6101
+ await fs.rm(staging, {
6102
+ recursive: true,
6103
+ force: true
6104
+ }).catch(() => {});
6105
+ return {
6106
+ ok: false,
6107
+ status: 500,
6108
+ error: `could not write ${slideId}: ${String(err)}`
6109
+ };
6110
+ }
6111
+ const record = board ? stripBoardRecord(board) : {};
6112
+ record.shareId = deck.shareId;
6113
+ record.imported = {
6114
+ at: deps.now,
6115
+ fromVersion: manifest.app.version
6116
+ };
6117
+ const outline = record.outline;
6118
+ if (outline && typeof outline === "object" && !Array.isArray(outline)) {
6119
+ const value = outline;
6120
+ if (value.state === "building") {
6121
+ value.paused = true;
6122
+ value.dispatched = null;
6123
+ }
6124
+ }
6125
+ const file = boardStructurePath(deps.userCwd, slideId);
6126
+ await fs.mkdir(path.dirname(file), { recursive: true });
6127
+ await fs.writeFile(file, `${JSON.stringify(record, null, 2)}\n`);
6128
+ if (deck.theme) for (const suffix of [".md", ".demo.tsx"]) {
6129
+ const from = inspected.files.get(`themes/${deck.theme}${suffix}`);
6130
+ if (!from) continue;
6131
+ const target = path.join(deps.userCwd, "themes", `${deck.theme}${suffix}`);
6132
+ const current = await fs.readFile(target).catch(() => null);
6133
+ if (current) {
6134
+ if (!current.equals(Buffer.from(from))) warnings.push(`theme ${deck.theme}${suffix} kept this machine's copy`);
6135
+ continue;
6136
+ }
6137
+ await fs.mkdir(path.dirname(target), { recursive: true });
6138
+ await fs.writeFile(target, from);
6139
+ }
6140
+ imported.push({
6141
+ from: deck.slideId,
6142
+ slideId
6143
+ });
6144
+ }
6145
+ return {
6146
+ ok: true,
6147
+ imported,
6148
+ warnings
6149
+ };
6150
+ }
6151
+ const INBOX_TOKEN_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
6152
+ function inboxRoot(userCwd) {
6153
+ return path.join(userCwd, "node_modules", ".open-slide", "share-inbox");
6154
+ }
6155
+ async function savePackage(root, token, bytes) {
6156
+ const dir = path.join(root, token);
6157
+ await fs.mkdir(dir, { recursive: true });
6158
+ await fs.writeFile(path.join(dir, "package.zip"), bytes);
6159
+ }
6160
+ async function readPackage(root, token) {
6161
+ if (!INBOX_TOKEN_RE.test(token)) return null;
6162
+ try {
6163
+ return new Uint8Array(await fs.readFile(path.join(root, token, "package.zip")));
6164
+ } catch {
6165
+ return null;
6166
+ }
6167
+ }
6168
+ async function dropPackage(root, token) {
6169
+ if (!INBOX_TOKEN_RE.test(token)) return;
6170
+ await fs.rm(path.join(root, token), {
6171
+ recursive: true,
6172
+ force: true
6173
+ });
6174
+ }
6175
+ /** Inspection leaves a zip behind; a day is long enough to decide to import it. */
6176
+ async function cleanupInbox(root, now = Date.now()) {
6177
+ let names;
6178
+ try {
6179
+ names = await fs.readdir(root);
6180
+ } catch {
6181
+ return;
6182
+ }
6183
+ for (const name of names) {
6184
+ const dir = path.join(root, name);
6185
+ try {
6186
+ if (now - (await fs.stat(dir)).mtimeMs > 864e5) await fs.rm(dir, {
6187
+ recursive: true,
6188
+ force: true
6189
+ });
6190
+ } catch {}
6191
+ }
6192
+ }
6193
+ //#endregion
6194
+ //#region src/lemonriver/share/local-files.ts
6195
+ /** Every file of a deck on this machine, keyed relative to its folder. */
6196
+ async function readDeckFiles(slidesRoot, slideId) {
6197
+ const out = /* @__PURE__ */ new Map();
6198
+ const root = path.join(slidesRoot, slideId);
6199
+ const walk = async (dir, prefix) => {
6200
+ const entries = await fs.readdir(dir, { withFileTypes: true });
6201
+ for (const entry of entries) {
6202
+ if (entry.name === "node_modules" || entry.name === ".DS_Store" || entry.name.startsWith(".")) continue;
6203
+ const fallback = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
6204
+ const full = path.join(dir, entry.name);
6205
+ if (entry.isDirectory()) {
6206
+ await walk(full, fallback);
6207
+ continue;
6208
+ }
6209
+ if (!entry.isFile()) continue;
6210
+ out.set(fallback, new Uint8Array(await fs.readFile(full)));
6211
+ }
6212
+ };
6213
+ await walk(root, "");
6214
+ return out;
6215
+ }
6216
+ //#endregion
6217
+ //#region src/lemonriver/share/pack.ts
6218
+ const ENTRY_NAMES$1 = [
6219
+ "index.tsx",
6220
+ "index.jsx",
6221
+ "index.ts",
6222
+ "index.js"
6223
+ ];
6224
+ const SOURCE_RE = /\.(?:tsx|jsx|ts|js|mjs)$/;
6225
+ const ASSET_REF = /@assets\/([^\s'"`\\]+)/g;
6226
+ /** Reads `meta.theme` out of a slide source without running it. */
6227
+ function readMetaThemeInSource(source) {
6228
+ let ast;
3809
6229
  try {
3810
- const entry = toEntry(id, JSON.parse(await fs.readFile(path.join(dir, ENTRY_FILE), "utf8")));
3811
- return entry && await exists(path.join(dir, SLIDE_DIR)) ? entry : null;
6230
+ ast = parse(source, {
6231
+ sourceType: "module",
6232
+ plugins: ["typescript", "jsx"],
6233
+ errorRecovery: true
6234
+ });
3812
6235
  } catch {
3813
6236
  return null;
3814
6237
  }
6238
+ const body = ast.program?.body ?? [];
6239
+ for (const statement of body) {
6240
+ if (statement.type !== "ExportNamedDeclaration") continue;
6241
+ const declaration = statement.declaration;
6242
+ if (declaration?.type !== "VariableDeclaration") continue;
6243
+ for (const item of declaration.declarations ?? []) {
6244
+ const id = item.id;
6245
+ if (id?.type !== "Identifier" || id.name !== "meta") continue;
6246
+ const init = item.init;
6247
+ if (init?.type !== "ObjectExpression") return null;
6248
+ for (const property of init.properties ?? []) {
6249
+ if (property.type !== "ObjectProperty" || property.computed) continue;
6250
+ const key = property.key;
6251
+ if ((key?.type === "Identifier" ? key.name : key?.value) !== "theme") continue;
6252
+ const value = property.value;
6253
+ return typeof value?.value === "string" ? value.value : null;
6254
+ }
6255
+ return null;
6256
+ }
6257
+ }
6258
+ return null;
3815
6259
  }
3816
- async function idTaken(slidesRoot, slideId) {
6260
+ async function exists(file) {
3817
6261
  try {
3818
- const want = slideId.toLowerCase();
3819
- return (await fs.readdir(slidesRoot)).some((name) => name.toLowerCase() === want);
6262
+ await fs.access(file);
6263
+ return true;
3820
6264
  } catch {
3821
6265
  return false;
3822
6266
  }
3823
6267
  }
3824
- async function freeSlideId(slidesRoot, slideId) {
3825
- if (!await idTaken(slidesRoot, slideId)) return slideId;
3826
- for (let n = 1;; n++) {
3827
- const candidate = n === 1 ? `${slideId}-restored` : `${slideId}-restored-${n}`;
3828
- if (!await idTaken(slidesRoot, candidate)) return candidate;
6268
+ async function walk(dir, prefix, out) {
6269
+ const entries = await fs.readdir(dir, { withFileTypes: true });
6270
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
6271
+ if (entry.name === "node_modules" || entry.name === ".DS_Store" || entry.name.startsWith(".")) continue;
6272
+ const full = path.join(dir, entry.name);
6273
+ const rel = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
6274
+ if (entry.isDirectory()) {
6275
+ await walk(full, rel, out);
6276
+ continue;
6277
+ }
6278
+ if (!entry.isFile()) continue;
6279
+ out.set(rel, new Uint8Array(await fs.readFile(full)));
3829
6280
  }
3830
6281
  }
3831
- async function listTrash(paths, now = Date.now()) {
3832
- let names;
3833
- try {
3834
- names = await fs.readdir(paths.trashRoot);
3835
- } catch {
3836
- return [];
3837
- }
3838
- const entries = [];
6282
+ async function deckEntry(slideDir) {
6283
+ for (const name of ENTRY_NAMES$1) try {
6284
+ return {
6285
+ name,
6286
+ source: await fs.readFile(path.join(slideDir, name), "utf8")
6287
+ };
6288
+ } catch {}
6289
+ return null;
6290
+ }
6291
+ function relativeAssetRef(fromFile, target) {
6292
+ const from = path.posix.dirname(fromFile);
6293
+ const rel = path.posix.relative(from === "." ? "" : from, target);
6294
+ return rel.startsWith("..") ? rel : `./${rel}`;
6295
+ }
6296
+ /**
6297
+ * Rewrites `@assets/…` to a path inside the package, copying the global file
6298
+ * next to the deck. The workspace's own sources are never touched.
6299
+ */
6300
+ async function localizeAssets(opts) {
6301
+ const names = /* @__PURE__ */ new Set();
6302
+ for (const match of opts.source.matchAll(ASSET_REF)) names.add(match[1]);
6303
+ if (names.size === 0) return opts.source;
6304
+ let source = opts.source;
3839
6305
  for (const name of names) {
3840
- const entry = await readEntry(paths.trashRoot, name);
3841
- if (!entry) continue;
3842
- if (now >= entry.expiresAt) {
3843
- await purgeTrashEntry(paths, entry.id);
6306
+ const globalFile = path.join(opts.globalAssetsRoot, name);
6307
+ let globalBytes;
6308
+ try {
6309
+ globalBytes = new Uint8Array(await fs.readFile(globalFile));
6310
+ } catch {
6311
+ opts.warnings.push(`global asset ${name} is missing; left the reference as it was`);
3844
6312
  continue;
3845
6313
  }
3846
- entries.push(entry);
6314
+ const packaged = `slides/${opts.slideId}/assets/${name}`;
6315
+ const own = opts.packageFiles.get(packaged);
6316
+ let target = `assets/${name}`;
6317
+ if (own) {
6318
+ if (own.length === globalBytes.length && own.every((byte, i) => byte === globalBytes[i])) target = `assets/${name}`;
6319
+ else {
6320
+ const dot = name.lastIndexOf(".");
6321
+ target = `assets/${dot > 0 ? name.slice(0, dot) : name}-shared${dot > 0 ? name.slice(dot) : ""}`;
6322
+ opts.packageFiles.set(`slides/${opts.slideId}/${target}`, globalBytes);
6323
+ }
6324
+ } else opts.packageFiles.set(packaged, globalBytes);
6325
+ source = source.split(`@assets/${name}`).join(relativeAssetRef(opts.relFile, target));
3847
6326
  }
3848
- return entries.sort((a, b) => b.deletedAt - a.deletedAt);
6327
+ return source;
3849
6328
  }
3850
- async function moveSlideToTrash(paths, slideId, now = Date.now()) {
3851
- if (!SLIDE_ID_RE.test(slideId)) return {
6329
+ async function packDecks(request, deps) {
6330
+ const warnings = [];
6331
+ const decks = [];
6332
+ const packageFiles = /* @__PURE__ */ new Map();
6333
+ for (const extra of request.extras) if (!isValidExtraName(extra.name)) return {
3852
6334
  ok: false,
3853
6335
  status: 400,
3854
- error: "invalid slideId"
3855
- };
3856
- const slideDir = inside(paths.slidesRoot, slideId);
3857
- if (!slideDir || !await exists(slideDir)) return {
3858
- ok: false,
3859
- status: 404,
3860
- error: "slide not found"
6336
+ error: `bad extra file name: ${extra.name}`
3861
6337
  };
3862
- let deletedAt = now;
3863
- while (await exists(path.join(paths.trashRoot, `${slideId}.${deletedAt}`))) deletedAt++;
3864
- const id = `${slideId}.${deletedAt}`;
3865
- const entryDir = path.join(paths.trashRoot, id);
3866
- const manifest = await readManifest(paths.manifestPath);
3867
- const folderId = manifest.assignments[slideId] ?? null;
3868
- const title = await readTitle(slideDir, slideId);
3869
- await fs.mkdir(entryDir, { recursive: true });
3870
- await fs.writeFile(path.join(entryDir, ENTRY_FILE), `${JSON.stringify({
3871
- slideId,
3872
- title,
3873
- folderId,
3874
- deletedAt
3875
- }, null, 2)}\n`, "utf8");
3876
- try {
3877
- await moveDir(slideDir, path.join(entryDir, SLIDE_DIR));
3878
- } catch (err) {
3879
- await fs.rm(entryDir, {
3880
- recursive: true,
3881
- force: true
6338
+ const badPaths = [];
6339
+ for (const slideId of request.slideIds) {
6340
+ if (!SHARE_SLIDE_ID_RE.test(slideId)) return {
6341
+ ok: false,
6342
+ status: 400,
6343
+ error: `bad slideId: ${slideId}`
6344
+ };
6345
+ const slideDir = path.join(deps.slidesRoot, slideId);
6346
+ if (!await exists(slideDir)) return {
6347
+ ok: false,
6348
+ status: 404,
6349
+ error: `slide ${slideId} not found`
6350
+ };
6351
+ const collected = /* @__PURE__ */ new Map();
6352
+ await walk(slideDir, "", collected);
6353
+ for (const rel of collected.keys()) {
6354
+ const problem = packagePathProblem(`slides/${slideId}/${rel}`);
6355
+ if (problem) {
6356
+ badPaths.push(`slides/${slideId}/${rel}: ${problem.detail}`);
6357
+ continue;
6358
+ }
6359
+ packageFiles.set(`slides/${slideId}/${rel}`, collected.get(rel));
6360
+ }
6361
+ if (badPaths.length > 0) continue;
6362
+ const entry = await deckEntry(slideDir);
6363
+ const titleRead = entry ? readMetaTitleInSource(entry.source) : { kind: "missing" };
6364
+ const title = titleRead.kind === "found" ? titleRead.title : safeFileName("", slideId);
6365
+ const theme = entry ? readMetaThemeInSource(entry.source) : null;
6366
+ for (const [rel, data] of [...packageFiles]) {
6367
+ if (!rel.startsWith(`slides/${slideId}/`)) continue;
6368
+ if (!SOURCE_RE.test(rel)) continue;
6369
+ const rewritten = await localizeAssets({
6370
+ source: new TextDecoder().decode(data),
6371
+ relFile: rel.slice(`slides/${slideId}/`.length),
6372
+ slideId,
6373
+ packageFiles,
6374
+ globalAssetsRoot: deps.globalAssetsRoot,
6375
+ warnings
6376
+ });
6377
+ if (rewritten !== new TextDecoder().decode(data)) packageFiles.set(rel, strToU8(rewritten));
6378
+ }
6379
+ if (theme) for (const suffix of [".md", ".demo.tsx"]) {
6380
+ const file = path.join(deps.userCwd, "themes", `${theme}${suffix}`);
6381
+ const packaged = `themes/${theme}${suffix}`;
6382
+ if (packageFiles.has(packaged)) continue;
6383
+ try {
6384
+ packageFiles.set(packaged, new Uint8Array(await fs.readFile(file)));
6385
+ } catch {}
6386
+ }
6387
+ const boardFile = boardStructurePath(deps.userCwd, slideId);
6388
+ const hasBoard = await exists(boardFile);
6389
+ const record = hasBoard ? await readBoardFile(boardFile) : {};
6390
+ const stored = typeof record.shareId === "string" ? record.shareId : "";
6391
+ const shareId = stored !== "" ? stored : deps.newShareId();
6392
+ if (stored === "") await updateBoardFile(boardFile, { shareId });
6393
+ if (hasBoard) packageFiles.set(`board/${slideId}.json`, strToU8(`${JSON.stringify(stripBoardRecord(record), null, 2)}\n`));
6394
+ const thumbs = request.thumbs[slideId] ?? [];
6395
+ thumbs.forEach((base64, index) => {
6396
+ const name = String(index + 1).padStart(2, "0");
6397
+ packageFiles.set(`thumbs/${slideId}/${name}.jpg`, Buffer.from(base64, "base64"));
3882
6398
  });
3883
- throw err;
3884
- }
3885
- if (folderId !== null) {
3886
- delete manifest.assignments[slideId];
3887
- await writeManifest(paths.manifestPath, manifest);
3888
- }
3889
- return {
3890
- ok: true,
3891
- entry: {
3892
- id,
6399
+ decks.push({
3893
6400
  slideId,
3894
6401
  title,
3895
- folderId,
3896
- deletedAt,
3897
- expiresAt: deletedAt + TRASH_RETENTION_MS
3898
- }
3899
- };
3900
- }
3901
- async function restoreTrashEntry(paths, id, beforeMove = () => {}) {
3902
- const entry = await readEntry(paths.trashRoot, id);
3903
- if (!entry) return {
3904
- ok: false,
3905
- status: 404,
3906
- error: "trash entry not found"
3907
- };
3908
- const entryDir = path.join(paths.trashRoot, id);
3909
- const slideId = await freeSlideId(paths.slidesRoot, entry.slideId);
3910
- const slideDir = inside(paths.slidesRoot, slideId);
3911
- if (!slideDir) return {
6402
+ pages: typeof request.pages[slideId] === "number" ? request.pages[slideId] : null,
6403
+ shareId,
6404
+ theme,
6405
+ thumbs: thumbs.length
6406
+ });
6407
+ }
6408
+ if (badPaths.length > 0) return {
3912
6409
  ok: false,
3913
6410
  status: 400,
3914
- error: "invalid slideId"
3915
- };
3916
- await fs.mkdir(paths.slidesRoot, { recursive: true });
3917
- beforeMove(slideId);
3918
- await moveDir(path.join(entryDir, SLIDE_DIR), slideDir);
3919
- await fs.rm(entryDir, {
3920
- recursive: true,
3921
- force: true
3922
- });
3923
- if (entry.folderId !== null) {
3924
- const manifest = await readManifest(paths.manifestPath);
3925
- if (manifest.folders.some((f) => f.id === entry.folderId)) {
3926
- manifest.assignments[slideId] = entry.folderId;
3927
- await writeManifest(paths.manifestPath, manifest);
3928
- }
3929
- }
6411
+ error: "the deck holds files a package may not carry",
6412
+ paths: badPaths
6413
+ };
6414
+ const files = {};
6415
+ for (const [rel, data] of packageFiles) files[rel] = sha256(data);
6416
+ const manifest = {
6417
+ format: SHARE_FORMAT,
6418
+ version: 1,
6419
+ kind: request.kind,
6420
+ app: {
6421
+ name: "LemonRiver",
6422
+ version: deps.coreVersion
6423
+ },
6424
+ createdAt: deps.now,
6425
+ decks,
6426
+ files
6427
+ };
6428
+ const entries = {};
6429
+ for (const [rel, data] of packageFiles) entries[`${SHARE_ROOT}/${rel}`] = data;
6430
+ entries[`${SHARE_ROOT}/${SHARE_MANIFEST}`] = strToU8(`${JSON.stringify(manifest, null, 2)}\n`);
6431
+ for (const extra of request.extras) entries[extra.name] = Buffer.from(extra.base64, "base64");
6432
+ const zipped = zipSync(entries, { level: 6 });
6433
+ await fs.mkdir(deps.sharedRoot, { recursive: true });
6434
+ const taken = await fs.readdir(deps.sharedRoot).catch(() => []);
6435
+ const fileName = uniqueFileName(packageBaseName(decks.map((deck) => ({
6436
+ title: deck.title,
6437
+ slideId: deck.slideId
6438
+ })), deps.now), taken.map((name) => name.replace(/\.zip$/i, "")));
6439
+ const target = path.join(deps.sharedRoot, `${fileName}.zip`);
6440
+ await fs.writeFile(target, zipped);
3930
6441
  return {
3931
6442
  ok: true,
3932
- slideId
6443
+ path: target,
6444
+ name: `${fileName}.zip`,
6445
+ size: zipped.length,
6446
+ warnings
3933
6447
  };
3934
6448
  }
3935
- async function purgeTrashEntry(paths, id) {
3936
- if (!isTrashEntryId(id)) return false;
3937
- const dir = inside(paths.trashRoot, id);
3938
- if (!dir || !await exists(dir)) return false;
3939
- await fs.rm(dir, {
3940
- recursive: true,
3941
- force: true
3942
- });
3943
- return true;
6449
+ //#endregion
6450
+ //#region src/lemonriver/share/reveal.ts
6451
+ /**
6452
+ * Show a package in the file manager. Only a path this process wrote itself is
6453
+ * allowed, so a page cannot ask us to open anything else on the machine.
6454
+ */
6455
+ function revealPath(target, deps) {
6456
+ if (!deps.produced.has(target)) return {
6457
+ ok: false,
6458
+ status: 403,
6459
+ error: "this path was not produced here"
6460
+ };
6461
+ if (deps.platform === "darwin") deps.exec("open", ["-R", target]);
6462
+ else if (deps.platform === "win32") deps.exec("explorer.exe", ["/select,", target]);
6463
+ else deps.exec("xdg-open", [path.dirname(target)]);
6464
+ return { ok: true };
3944
6465
  }
3945
6466
  //#endregion
3946
- //#region src/lemonriver/trash/routes.ts
6467
+ //#region src/lemonriver/share/routes.ts
6468
+ const PACK_BODY_LIMIT = 268435456;
6469
+ const ZIP_BODY_LIMIT = 536870912;
6470
+ const ZIP_TYPES = /* @__PURE__ */ new Set(["application/zip", "application/octet-stream"]);
3947
6471
  const ENTRY_NAMES = [
3948
6472
  "index.tsx",
3949
6473
  "index.jsx",
3950
6474
  "index.ts",
3951
6475
  "index.js"
3952
6476
  ];
3953
- const DECKS_CHANGED_EVENT = "lemonriver:decks-changed";
3954
- function registerTrashRoutes(server, ctx) {
3955
- const paths = {
3956
- slidesRoot: ctx.slidesRoot,
3957
- manifestPath: ctx.manifestPath,
3958
- trashRoot: trashRootFor(ctx.userCwd)
3959
- };
3960
- const quietWatcher = (slideId) => {
3961
- for (const name of ENTRY_NAMES) recordWrite(path.join(ctx.slidesRoot, slideId, name));
3962
- };
6477
+ function headerValue(req, name) {
6478
+ const raw = req.headers[name];
6479
+ return (Array.isArray(raw) ? String(raw[0]) : String(raw ?? "")).split(",")[0].trim();
6480
+ }
6481
+ async function readRaw(req, limit) {
6482
+ return await new Promise((resolve, reject) => {
6483
+ const chunks = [];
6484
+ let size = 0;
6485
+ req.on("data", (chunk) => {
6486
+ size += chunk.length;
6487
+ if (size > limit) {
6488
+ reject(new BodyTooLargeError());
6489
+ req.destroy();
6490
+ return;
6491
+ }
6492
+ chunks.push(chunk);
6493
+ });
6494
+ req.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
6495
+ req.on("error", reject);
6496
+ });
6497
+ }
6498
+ function stringMap(value) {
6499
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
6500
+ const out = {};
6501
+ for (const [key, entry] of Object.entries(value)) {
6502
+ if (!Array.isArray(entry)) continue;
6503
+ out[key] = entry.filter((item) => typeof item === "string");
6504
+ }
6505
+ return out;
6506
+ }
6507
+ function numberMap(value) {
6508
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
6509
+ const out = {};
6510
+ for (const [key, entry] of Object.entries(value)) if (typeof entry === "number" && Number.isFinite(entry)) out[key] = entry;
6511
+ return out;
6512
+ }
6513
+ async function deckTitle(userCwd, slideId) {
6514
+ const outline = (await readBoardFile(boardStructurePath(userCwd, slideId)).catch(() => ({}))).outline;
6515
+ const brief = typeof outline?.brief === "string" ? outline.brief.trim() : "";
6516
+ if (brief !== "") return brief;
6517
+ for (const name of ENTRY_NAMES) try {
6518
+ const source = await fs.readFile(path.join(userCwd, "slides", slideId, name), "utf8");
6519
+ const read = readMetaTitleInSource(source);
6520
+ if (read.kind === "found") return read.title;
6521
+ } catch {}
6522
+ return slideId;
6523
+ }
6524
+ function registerShareRoutes(server, ctx) {
6525
+ const inbox = inboxRoot(ctx.userCwd);
6526
+ const sharedRoot = path.join(ctx.userCwd, "shared");
6527
+ const produced = /* @__PURE__ */ new Set();
3963
6528
  const reloadClients = () => {
3964
6529
  invalidateSlidesModule(server);
3965
6530
  server.ws.send({
@@ -3967,62 +6532,210 @@ function registerTrashRoutes(server, ctx) {
3967
6532
  event: DECKS_CHANGED_EVENT
3968
6533
  });
3969
6534
  };
3970
- server.middlewares.use("/__lr/trash", async (req, res, next) => {
6535
+ server.middlewares.use("/__lr/share", async (req, res, next) => {
3971
6536
  const url = new URL(req.url ?? "/", "http://local");
3972
6537
  const method = req.method ?? "GET";
3973
6538
  try {
3974
- if (method === "GET" && url.pathname === "/") return json(res, 200, { entries: await listTrash(paths) });
3975
- if (method === "POST" && url.pathname === "/") {
6539
+ if (method === "GET" && url.pathname === "/version") return json(res, 200, { version: ctx.coreVersion });
6540
+ if (method === "POST" && url.pathname === "/pack") {
6541
+ const check = validateMutationRequest(req, { requireJsonBody: true });
6542
+ if (!check.ok) return json(res, check.status, { error: check.error });
6543
+ const body = await readBody(req, PACK_BODY_LIMIT);
6544
+ const slideIds = Array.isArray(body?.slideIds) ? body.slideIds.filter((id) => typeof id === "string") : [];
6545
+ if (slideIds.length === 0) return json(res, 400, { error: "slideIds is empty" });
6546
+ const kind = body?.kind === "backup" ? "backup" : "share";
6547
+ const extrasRaw = Array.isArray(body?.extras) ? body.extras : [];
6548
+ const extras = [];
6549
+ for (const entry of extrasRaw) {
6550
+ const name = typeof entry?.name === "string" ? entry.name : "";
6551
+ const base64 = typeof entry?.base64 === "string" ? entry.base64 : "";
6552
+ extras.push({
6553
+ name,
6554
+ base64
6555
+ });
6556
+ }
6557
+ const packed = await packDecks({
6558
+ slideIds,
6559
+ kind,
6560
+ pages: numberMap(body?.pages),
6561
+ thumbs: stringMap(body?.thumbs),
6562
+ extras
6563
+ }, {
6564
+ userCwd: ctx.userCwd,
6565
+ slidesRoot: ctx.slidesRoot,
6566
+ globalAssetsRoot: ctx.globalAssetsRoot,
6567
+ coreVersion: ctx.coreVersion,
6568
+ sharedRoot,
6569
+ now: Date.now(),
6570
+ newShareId: () => randomUUID()
6571
+ });
6572
+ if (!packed.ok) return json(res, packed.status, {
6573
+ error: packed.error,
6574
+ paths: packed.paths ?? []
6575
+ });
6576
+ produced.add(packed.path);
6577
+ return json(res, 200, packed);
6578
+ }
6579
+ if (method === "POST" && url.pathname === "/reveal") {
3976
6580
  const check = validateMutationRequest(req, { requireJsonBody: true });
3977
6581
  if (!check.ok) return json(res, check.status, { error: check.error });
6582
+ if (!isLoopbackRequest(req)) return json(res, 403, { error: "local requests only" });
3978
6583
  const body = await readBody(req);
3979
- const slideId = typeof body?.slideId === "string" ? body.slideId : "";
3980
- if (!SLIDE_ID_RE.test(slideId)) return json(res, 400, { error: "invalid slideId" });
3981
- quietWatcher(slideId);
3982
- const moved = await moveSlideToTrash(paths, slideId);
3983
- if (!moved.ok) return json(res, moved.status, { error: moved.error });
3984
- json(res, 200, {
3985
- ok: true,
3986
- entry: moved.entry
6584
+ const revealed = revealPath(typeof body?.path === "string" ? body.path : "", {
6585
+ platform: process.platform,
6586
+ produced,
6587
+ exec: (file, args) => {
6588
+ execFile(file, args, { windowsHide: true }, () => {});
6589
+ }
3987
6590
  });
3988
- return reloadClients();
6591
+ if (!revealed.ok) return json(res, revealed.status, { error: revealed.error });
6592
+ return json(res, 200, { ok: true });
3989
6593
  }
3990
- const restoreMatch = url.pathname.match(/^\/([^/]+)\/restore$/);
3991
- if (method === "POST" && restoreMatch) {
6594
+ if (method === "POST" && url.pathname === "/inspect") {
6595
+ if (!ZIP_TYPES.has(headerValue(req, "content-type").toLowerCase())) return json(res, 415, { error: "content-type must be application/zip" });
3992
6596
  const check = validateMutationRequest(req);
3993
6597
  if (!check.ok) return json(res, check.status, { error: check.error });
3994
- const id = decodeURIComponent(restoreMatch[1]);
3995
- if (!isTrashEntryId(id)) return json(res, 400, { error: "invalid trash id" });
3996
- const restored = await restoreTrashEntry(paths, id, quietWatcher);
3997
- if (!restored.ok) return json(res, restored.status, { error: restored.error });
6598
+ const bytes = await readRaw(req, ZIP_BODY_LIMIT);
6599
+ await cleanupInbox(inbox);
6600
+ const inspected = inspectBytes(bytes);
6601
+ if (!inspected.ok) return json(res, 400, {
6602
+ ok: false,
6603
+ code: inspected.code,
6604
+ detail: inspected.detail,
6605
+ ...inspected.paths ? { paths: inspected.paths } : {}
6606
+ });
6607
+ const token = randomUUID();
6608
+ await savePackage(inbox, token, bytes);
6609
+ const localIds = new Set((await fs.readdir(ctx.slidesRoot).catch(() => [])).map((id) => id.toLowerCase()));
6610
+ const decks = [];
6611
+ for (const deck of inspected.manifest.decks) {
6612
+ const owner = await shareIdOwner(ctx.userCwd, deck.shareId, deck.slideId);
6613
+ let changes = null;
6614
+ if (owner) try {
6615
+ changes = compareDeck(await readDeckFiles(ctx.slidesRoot, owner), new Map(deckFiles(inspected.files, deck.slideId).map((file) => [file.path, file.data])));
6616
+ } catch {
6617
+ changes = null;
6618
+ }
6619
+ decks.push({
6620
+ slideId: deck.slideId,
6621
+ title: deck.title,
6622
+ pages: deck.pages,
6623
+ thumbs: deck.thumbs,
6624
+ theme: deck.theme,
6625
+ existing: owner ? {
6626
+ slideId: owner,
6627
+ title: await deckTitle(ctx.userCwd, owner)
6628
+ } : null,
6629
+ idTaken: localIds.has(deck.slideId.toLowerCase()),
6630
+ changes
6631
+ });
6632
+ }
6633
+ return json(res, 200, {
6634
+ ok: true,
6635
+ token,
6636
+ kind: inspected.manifest.kind,
6637
+ app: inspected.manifest.app,
6638
+ createdAt: inspected.manifest.createdAt,
6639
+ decks
6640
+ });
6641
+ }
6642
+ if (method === "POST" && url.pathname === "/import") {
6643
+ const check = validateMutationRequest(req, { requireJsonBody: true });
6644
+ if (!check.ok) return json(res, check.status, { error: check.error });
6645
+ const body = await readBody(req);
6646
+ const token = typeof body?.token === "string" ? body.token : "";
6647
+ const requested = Array.isArray(body?.decks) ? body.decks.filter((entry) => typeof entry === "object" && entry !== null).map((entry) => ({
6648
+ slideId: typeof entry.slideId === "string" ? entry.slideId : "",
6649
+ mode: entry.mode === "replace" ? "replace" : "copy"
6650
+ })) : [];
6651
+ if (token === "" || requested.length === 0) return json(res, 400, { error: "token and decks are required" });
6652
+ const bytes = await readPackage(inbox, token);
6653
+ if (!bytes) return json(res, 404, { error: "package not found" });
6654
+ const result = await importDecks(bytes, requested, {
6655
+ userCwd: ctx.userCwd,
6656
+ slidesRoot: ctx.slidesRoot,
6657
+ manifestPath: ctx.manifestPath,
6658
+ workDir: path.join(inbox, token),
6659
+ now: Date.now()
6660
+ });
6661
+ if (!result.ok) return json(res, result.status, { error: result.error });
6662
+ for (const entry of result.imported) for (const name of ENTRY_NAMES) recordWrite(path.join(ctx.slidesRoot, entry.slideId, name));
6663
+ await dropPackage(inbox, token);
3998
6664
  json(res, 200, {
3999
6665
  ok: true,
4000
- slideId: restored.slideId
6666
+ imported: result.imported,
6667
+ warnings: result.warnings
4001
6668
  });
4002
6669
  return reloadClients();
4003
6670
  }
4004
- const entryMatch = url.pathname.match(/^\/([^/]+)$/);
4005
- if (method === "DELETE" && entryMatch) {
4006
- const check = validateMutationRequest(req);
4007
- if (!check.ok) return json(res, check.status, { error: check.error });
4008
- const id = decodeURIComponent(entryMatch[1]);
4009
- if (!isTrashEntryId(id)) return json(res, 400, { error: "invalid trash id" });
4010
- if (!await purgeTrashEntry(paths, id)) return json(res, 404, { error: "trash entry not found" });
4011
- return json(res, 200, { ok: true });
6671
+ const thumb = /^\/inbox\/([^/]+)\/thumbs\/([^/]+)\/(\d{2,})\.jpg$/.exec(url.pathname);
6672
+ if (method === "GET" && thumb) {
6673
+ const [, token, slideId, name] = thumb;
6674
+ if (!SHARE_SLIDE_ID_RE.test(slideId)) return json(res, 404, { error: "not found" });
6675
+ const bytes = await readPackage(inbox, token);
6676
+ if (!bytes) return json(res, 404, { error: "not found" });
6677
+ const inspected = inspectBytes(bytes);
6678
+ if (!inspected.ok) return json(res, 404, { error: "not found" });
6679
+ const thumbBytes = inspected.files.get(`thumbs/${slideId}/${name}.jpg`);
6680
+ if (!thumbBytes) return json(res, 404, { error: "not found" });
6681
+ res.statusCode = 200;
6682
+ res.setHeader("content-type", "image/jpeg");
6683
+ res.setHeader("cache-control", "no-store");
6684
+ return res.end(Buffer.from(thumbBytes));
4012
6685
  }
4013
6686
  next();
4014
6687
  } catch (err) {
6688
+ if (err instanceof BodyTooLargeError) return json(res, 413, { error: "body too large" });
4015
6689
  json(res, 500, { error: String(err.message ?? err) });
4016
6690
  }
4017
6691
  });
4018
6692
  }
4019
6693
  //#endregion
6694
+ //#region src/lemonriver/templates/routes.ts
6695
+ const GUIDE_PATH = /^\/([A-Za-z0-9._-]+)\/guide$/;
6696
+ function text(res, status, body, type) {
6697
+ res.statusCode = status;
6698
+ res.setHeader("content-type", `${type}; charset=utf-8`);
6699
+ res.end(body);
6700
+ }
6701
+ function createTemplatesMiddleware(deps) {
6702
+ return async (req, res, next) => {
6703
+ if ((req.method ?? "GET") !== "GET") return next();
6704
+ const url = new URL(req.url ?? "/", "http://local");
6705
+ try {
6706
+ const root = resolveTemplatesRoot({
6707
+ coreRoot: deps.coreRoot,
6708
+ cwd: deps.cwd,
6709
+ env: deps.env
6710
+ });
6711
+ if (url.pathname === "/" || url.pathname === "") return json(res, 200, await readTemplateListing(root));
6712
+ const guide = GUIDE_PATH.exec(url.pathname);
6713
+ if (guide) {
6714
+ const body = await readTemplateGuide(root, guide[1]);
6715
+ if (body === null) return json(res, 404, { error: "template not found" });
6716
+ return text(res, 200, body, "text/markdown");
6717
+ }
6718
+ return next();
6719
+ } catch (err) {
6720
+ return json(res, 500, { error: String(err.message ?? err) });
6721
+ }
6722
+ };
6723
+ }
6724
+ function registerTemplateRoutes(server, ctx) {
6725
+ server.middlewares.use("/__lr/templates", createTemplatesMiddleware({
6726
+ coreRoot: corePackageRoot(),
6727
+ cwd: ctx.userCwd
6728
+ }));
6729
+ }
6730
+ //#endregion
4020
6731
  //#region src/lemonriver/routes.ts
4021
6732
  function registerLemonRiverRoutes(server, ctx) {
4022
6733
  registerBoardRoutes(server, ctx);
4023
6734
  registerTrashRoutes(server, ctx);
4024
6735
  registerDeckRoutes(server, ctx);
4025
6736
  registerOutlineRoutes(server, ctx);
6737
+ registerTemplateRoutes(server, ctx);
6738
+ registerShareRoutes(server, ctx);
4026
6739
  registerAgentProviderRoutes(server, ctx);
4027
6740
  }
4028
6741
  //#endregion
@@ -8377,6 +11090,10 @@ async function createViteConfig(opts) {
8377
11090
  userCwd,
8378
11091
  config
8379
11092
  }),
11093
+ templatesPlugin({
11094
+ coreRoot: PKG_ROOT,
11095
+ userCwd
11096
+ }),
8380
11097
  designPlugin({ userCwd }),
8381
11098
  apiPlugin({
8382
11099
  userCwd,