@lemonriver/core 0.6.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 (44) hide show
  1. package/dist/{build-RlcGG-Ve.js → build-CKwrex8y.js} +1 -1
  2. package/dist/cli/bin.js +3 -3
  3. package/dist/{config-BJT87wE9.js → config-B1_gk0sy.js} +1641 -60
  4. package/dist/{dev-DR-j_xda.js → dev-DZ2Yzl2p.js} +1 -1
  5. package/dist/{preview-BTAhTb5B.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/chrome/app-chrome.tsx +12 -1
  9. package/src/app/lemonriver/features.test.ts +5 -0
  10. package/src/app/lemonriver/features.ts +2 -1
  11. package/src/app/lemonriver/feedback/pending-toast.ts +7 -2
  12. package/src/app/lemonriver/home/deck-card.tsx +10 -1
  13. package/src/app/lemonriver/home/home-page.tsx +52 -1
  14. package/src/app/lemonriver/share/capture.ts +76 -0
  15. package/src/app/lemonriver/share/client.ts +162 -0
  16. package/src/app/lemonriver/share/codes.test.ts +49 -0
  17. package/src/app/lemonriver/share/codes.ts +30 -0
  18. package/src/app/lemonriver/share/compare.test.ts +199 -0
  19. package/src/app/lemonriver/share/compare.ts +367 -0
  20. package/src/app/lemonriver/share/drop.ts +84 -0
  21. package/src/app/lemonriver/share/folder.test.ts +42 -0
  22. package/src/app/lemonriver/share/folder.ts +29 -0
  23. package/src/app/lemonriver/share/freeze.ts +51 -0
  24. package/src/app/lemonriver/share/guide.test.ts +78 -0
  25. package/src/app/lemonriver/share/guide.ts +222 -0
  26. package/src/app/lemonriver/share/import-dialog.tsx +391 -0
  27. package/src/app/lemonriver/share/import-entry.tsx +106 -0
  28. package/src/app/lemonriver/share/model.ts +150 -0
  29. package/src/app/lemonriver/share/naming.test.ts +59 -0
  30. package/src/app/lemonriver/share/naming.ts +71 -0
  31. package/src/app/lemonriver/share/paths.test.ts +75 -0
  32. package/src/app/lemonriver/share/paths.ts +181 -0
  33. package/src/app/lemonriver/share/pdf.test.ts +79 -0
  34. package/src/app/lemonriver/share/pdf.ts +169 -0
  35. package/src/app/lemonriver/share/share-dialog.tsx +286 -0
  36. package/src/app/lemonriver/share/summary.ts +47 -0
  37. package/src/app/lemonriver/slide-extensions.tsx +69 -23
  38. package/src/app/lemonriver/templates/library-page.tsx +5 -2
  39. package/src/app/lemonriver/text/en.ts +67 -0
  40. package/src/app/lemonriver/text/es.ts +67 -0
  41. package/src/app/lemonriver/text/ja.ts +67 -0
  42. package/src/app/lemonriver/text/types.ts +78 -0
  43. package/src/app/lemonriver/text/zh-cn.ts +62 -0
  44. package/src/app/lemonriver/text/zh-tw.ts +62 -0
@@ -7,7 +7,7 @@ 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";
@@ -16,6 +16,7 @@ import os from "node:os";
16
16
  import * as t from "@babel/types";
17
17
  import { isJSXElement, isJSXFragment } from "@babel/types";
18
18
  import fg from "fast-glob";
19
+ import { strToU8, unzipSync, zipSync } from "fflate";
19
20
  //#region src/app/lemonriver/templates/knobs.ts
20
21
  const KNOB_KEYS$1 = [
21
22
  "formal",
@@ -174,7 +175,7 @@ const MIN_TYPE_FLOOR = {
174
175
  min: 16,
175
176
  max: 20
176
177
  };
177
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
178
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
178
179
  const text$2 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : null;
179
180
  const KNOB_KEYS = [
180
181
  "formal",
@@ -182,11 +183,11 @@ const KNOB_KEYS = [
182
183
  "motion"
183
184
  ];
184
185
  function readDesign(raw) {
185
- if (!isRecord(raw)) return null;
186
+ if (!isRecord$1(raw)) return null;
186
187
  const palette = raw.palette;
187
188
  const fonts = raw.fonts;
188
189
  const typeScale = raw.typeScale;
189
- if (!isRecord(palette) || !isRecord(fonts) || !isRecord(typeScale)) return null;
190
+ if (!isRecord$1(palette) || !isRecord$1(fonts) || !isRecord$1(typeScale)) return null;
190
191
  const bg = text$2(palette.bg);
191
192
  const ink = text$2(palette.text);
192
193
  const accent = text$2(palette.accent);
@@ -217,9 +218,9 @@ function readDesign(raw) {
217
218
  };
218
219
  }
219
220
  function readOverrides(raw) {
220
- if (!isRecord(raw)) return void 0;
221
+ if (!isRecord$1(raw)) return void 0;
221
222
  const out = {};
222
- if (isRecord(raw.palette)) {
223
+ if (isRecord$1(raw.palette)) {
223
224
  const palette = {};
224
225
  for (const key of [
225
226
  "bg",
@@ -231,7 +232,7 @@ function readOverrides(raw) {
231
232
  }
232
233
  if (Object.keys(palette).length > 0) out.palette = palette;
233
234
  }
234
- if (isRecord(raw.fonts)) {
235
+ if (isRecord$1(raw.fonts)) {
235
236
  const fonts = {};
236
237
  for (const key of ["display", "body"]) {
237
238
  const value = text$2(raw.fonts[key]);
@@ -239,7 +240,7 @@ function readOverrides(raw) {
239
240
  }
240
241
  if (Object.keys(fonts).length > 0) out.fonts = fonts;
241
242
  }
242
- if (isRecord(raw.typeScale)) {
243
+ if (isRecord$1(raw.typeScale)) {
243
244
  const typeScale = {};
244
245
  for (const key of ["hero", "body"]) {
245
246
  const value = raw.typeScale[key];
@@ -252,12 +253,12 @@ function readOverrides(raw) {
252
253
  return Object.keys(out).length > 0 ? out : void 0;
253
254
  }
254
255
  function readKnobEnd(raw) {
255
- if (!isRecord(raw)) return null;
256
+ if (!isRecord$1(raw)) return null;
256
257
  const label = text$2(raw.label);
257
258
  if (!label) return null;
258
259
  const design = readOverrides(raw.design);
259
260
  const flags = {};
260
- if (isRecord(raw.flags)) {
261
+ if (isRecord$1(raw.flags)) {
261
262
  for (const [key, value] of Object.entries(raw.flags)) if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") flags[key] = value;
262
263
  }
263
264
  const end = { label };
@@ -266,11 +267,11 @@ function readKnobEnd(raw) {
266
267
  return end;
267
268
  }
268
269
  function readKnobs(raw) {
269
- if (!isRecord(raw)) return null;
270
+ if (!isRecord$1(raw)) return null;
270
271
  const knobs = {};
271
272
  for (const key of KNOB_KEYS) {
272
273
  const knob = raw[key];
273
- if (!isRecord(knob)) return null;
274
+ if (!isRecord$1(knob)) return null;
274
275
  const left = readKnobEnd(knob.left);
275
276
  const right = readKnobEnd(knob.right);
276
277
  if (!left || !right) return null;
@@ -285,7 +286,7 @@ function readFonts(raw) {
285
286
  if (!Array.isArray(raw)) return null;
286
287
  const fonts = [];
287
288
  for (const entry of raw) {
288
- if (!isRecord(entry)) return null;
289
+ if (!isRecord$1(entry)) return null;
289
290
  const file = text$2(entry.file);
290
291
  const license = text$2(entry.license);
291
292
  if (!file || !license) return null;
@@ -302,7 +303,7 @@ function readFonts(raw) {
302
303
  * than half-read.
303
304
  */
304
305
  function sanitizeTemplate(raw, expectedId) {
305
- if (!isRecord(raw)) return {
306
+ if (!isRecord$1(raw)) return {
306
307
  ok: false,
307
308
  reason: "not a JSON object"
308
309
  };
@@ -416,7 +417,7 @@ function sanitizeTemplate(raw, expectedId) {
416
417
  }
417
418
  /** The board record written when a template is applied; anything else is ignored. */
418
419
  function sanitizeAppliedTemplate(raw) {
419
- if (!isRecord(raw)) return null;
420
+ if (!isRecord$1(raw)) return null;
420
421
  const id = text$2(raw.id);
421
422
  const appliedAt = raw.appliedAt;
422
423
  if (!id || typeof appliedAt !== "number" || !Number.isFinite(appliedAt)) return null;
@@ -427,7 +428,7 @@ function sanitizeAppliedTemplate(raw) {
427
428
  };
428
429
  }
429
430
  function sanitizeKnobValues(raw) {
430
- if (!isRecord(raw)) return {};
431
+ if (!isRecord$1(raw)) return {};
431
432
  const values = {};
432
433
  for (const key of KNOB_KEYS) {
433
434
  const value = raw[key];
@@ -3098,7 +3099,7 @@ async function moveBoardRecord(userCwd, fromId, toId) {
3098
3099
  }
3099
3100
  //#endregion
3100
3101
  //#region src/lemonriver/board/apply.ts
3101
- async function readDeck(ctx, slideId) {
3102
+ async function readDeck$1(ctx, slideId) {
3102
3103
  const entry = resolveSlideEntry(ctx.slidesRoot, slideId);
3103
3104
  const source = entry ? await readSlideSource(entry) : null;
3104
3105
  if (source === null) return null;
@@ -3164,7 +3165,7 @@ async function startApply(ctx, slideId, task = { kind: "changes" }, lang = "en")
3164
3165
  status: 409,
3165
3166
  error: "an apply is already running"
3166
3167
  };
3167
- const deck = await readDeck(ctx, slideId);
3168
+ const deck = await readDeck$1(ctx, slideId);
3168
3169
  if (!deck) return {
3169
3170
  ok: false,
3170
3171
  status: 422,
@@ -3413,7 +3414,7 @@ async function collectApply(ctx, store, sessionId, userItemId) {
3413
3414
  return;
3414
3415
  }
3415
3416
  const beforeColumns = Array.isArray(stored.applyColumns) ? stored.applyColumns : [];
3416
- const deck = await readDeck(ctx, slideId);
3417
+ const deck = await readDeck$1(ctx, slideId);
3417
3418
  const newKeys = deck ? deck.keys : beforeColumns.flatMap((column) => column.keys);
3418
3419
  const beforeKeys = new Set(beforeColumns.flatMap((column) => column.keys));
3419
3420
  const created = newKeys.filter((key) => !beforeKeys.has(key));
@@ -3498,7 +3499,7 @@ const SKIP_KEYS = /* @__PURE__ */ new Set([
3498
3499
  "trailingComments",
3499
3500
  "innerComments"
3500
3501
  ]);
3501
- function walk(ast, visit, accept) {
3502
+ function walk$1(ast, visit, accept) {
3502
3503
  let stopped = false;
3503
3504
  const recurse = (node) => {
3504
3505
  if (stopped || !node || typeof node !== "object") return;
@@ -3522,10 +3523,10 @@ function walk(ast, visit, accept) {
3522
3523
  const isJsx = (n) => isJSXElement(n) || isJSXFragment(n);
3523
3524
  const acceptAll = () => true;
3524
3525
  function walkJsx(ast, visit) {
3525
- walk(ast, visit, isJsx);
3526
+ walk$1(ast, visit, isJsx);
3526
3527
  }
3527
3528
  function walkAll(ast, visit) {
3528
- walk(ast, visit, acceptAll);
3529
+ walk$1(ast, visit, acceptAll);
3529
3530
  }
3530
3531
  /** Parse with error recovery; recoverable syntax errors are kept in `errors`. */
3531
3532
  function tryParse(source) {
@@ -4076,7 +4077,7 @@ function registerBoardRoutes(server, ctx) {
4076
4077
  }
4077
4078
  //#endregion
4078
4079
  //#region src/lemonriver/decks/routes.ts
4079
- const ENTRY_NAMES$1 = [
4080
+ const ENTRY_NAMES$4 = [
4080
4081
  "index.tsx",
4081
4082
  "index.jsx",
4082
4083
  "index.ts",
@@ -4092,7 +4093,7 @@ async function readDeckTimes(slidesRoot) {
4092
4093
  const decks = {};
4093
4094
  for (const name of names) {
4094
4095
  if (!SLIDE_ID_RE.test(name)) continue;
4095
- for (const entry of ENTRY_NAMES$1) try {
4096
+ for (const entry of ENTRY_NAMES$4) try {
4096
4097
  const stat = await fs.stat(path.join(slidesRoot, name, entry));
4097
4098
  decks[name] = { modifiedAt: Math.round(stat.mtimeMs) };
4098
4099
  break;
@@ -4553,41 +4554,509 @@ function registerOutlineRoutes(server, ctx) {
4553
4554
  });
4554
4555
  }
4555
4556
  //#endregion
4556
- //#region src/lemonriver/templates/routes.ts
4557
- const GUIDE_PATH = /^\/([A-Za-z0-9._-]+)\/guide$/;
4558
- function text(res, status, body, type) {
4559
- res.statusCode = status;
4560
- res.setHeader("content-type", `${type}; charset=utf-8`);
4561
- res.end(body);
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));
4562
4567
  }
4563
- function createTemplatesMiddleware(deps) {
4564
- return async (req, res, next) => {
4565
- if ((req.method ?? "GET") !== "GET") return next();
4566
- const url = new URL(req.url ?? "/", "http://local");
4567
- try {
4568
- const root = resolveTemplatesRoot({
4569
- coreRoot: deps.coreRoot,
4570
- cwd: deps.cwd,
4571
- env: deps.env
4568
+ /**
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.
4571
+ */
4572
+ function normalizeAssets(source) {
4573
+ return source.replace(/(?:\.{1,2}\/)+assets\//g, "@assets/");
4574
+ }
4575
+ function compress(source) {
4576
+ return normalizeAssets(source).replace(/\s+/g, "");
4577
+ }
4578
+ function slice(source, node) {
4579
+ if (node.start == null || node.end == null) return "";
4580
+ return source.slice(node.start, node.end);
4581
+ }
4582
+ function unwrapExport(node) {
4583
+ return node.type === "ExportNamedDeclaration" && node.declaration ? node.declaration : node;
4584
+ }
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);
4588
+ }
4589
+ function parseDeck(source) {
4590
+ let body;
4591
+ try {
4592
+ body = parse(source, {
4593
+ sourceType: "module",
4594
+ plugins: ["typescript", "jsx"],
4595
+ errorRecovery: true
4596
+ }).program.body;
4597
+ } catch {
4598
+ return {
4599
+ ok: false,
4600
+ pages: [],
4601
+ notes: null,
4602
+ shared: ""
4603
+ };
4604
+ }
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))
4572
4652
  });
4573
- if (url.pathname === "/" || url.pathname === "") return json(res, 200, await readTemplateListing(root));
4574
- const guide = GUIDE_PATH.exec(url.pathname);
4575
- if (guide) {
4576
- const body = await readTemplateGuide(root, guide[1]);
4577
- if (body === null) return json(res, 404, { error: "template not found" });
4578
- return text(res, 200, body, "text/markdown");
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)));
4579
4670
  }
4580
- return next();
4581
- } catch (err) {
4582
- return json(res, 500, { error: String(err.message ?? err) });
4671
+ continue;
4583
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")
4584
4681
  };
4585
4682
  }
4586
- function registerTemplateRoutes(server, ctx) {
4587
- server.middlewares.use("/__lr/templates", createTemplatesMiddleware({
4588
- coreRoot: corePackageRoot(),
4589
- cwd: ctx.userCwd
4590
- }));
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");
4591
5060
  }
4592
5061
  //#endregion
4593
5062
  //#region src/vite/recent-writes.ts
@@ -4887,7 +5356,7 @@ function inside(root, id) {
4887
5356
  const dir = path.resolve(root, id);
4888
5357
  return dir.startsWith(path.resolve(root) + path.sep) ? dir : null;
4889
5358
  }
4890
- async function exists(p) {
5359
+ async function exists$1(p) {
4891
5360
  try {
4892
5361
  await fs.access(p);
4893
5362
  return true;
@@ -4939,7 +5408,7 @@ async function readEntry(trashRoot, id) {
4939
5408
  if (!dir) return null;
4940
5409
  try {
4941
5410
  const entry = toEntry(id, JSON.parse(await fs.readFile(path.join(dir, ENTRY_FILE), "utf8")));
4942
- return entry && await exists(path.join(dir, SLIDE_DIR)) ? entry : null;
5411
+ return entry && await exists$1(path.join(dir, SLIDE_DIR)) ? entry : null;
4943
5412
  } catch {
4944
5413
  return null;
4945
5414
  }
@@ -4985,13 +5454,13 @@ async function moveSlideToTrash(paths, slideId, now = Date.now()) {
4985
5454
  error: "invalid slideId"
4986
5455
  };
4987
5456
  const slideDir = inside(paths.slidesRoot, slideId);
4988
- if (!slideDir || !await exists(slideDir)) return {
5457
+ if (!slideDir || !await exists$1(slideDir)) return {
4989
5458
  ok: false,
4990
5459
  status: 404,
4991
5460
  error: "slide not found"
4992
5461
  };
4993
5462
  let deletedAt = now;
4994
- while (await exists(path.join(paths.trashRoot, `${slideId}.${deletedAt}`))) deletedAt++;
5463
+ while (await exists$1(path.join(paths.trashRoot, `${slideId}.${deletedAt}`))) deletedAt++;
4995
5464
  const id = `${slideId}.${deletedAt}`;
4996
5465
  const entryDir = path.join(paths.trashRoot, id);
4997
5466
  const manifest = await readManifest(paths.manifestPath);
@@ -5066,7 +5535,7 @@ async function restoreTrashEntry(paths, id, beforeMove = () => {}) {
5066
5535
  async function purgeTrashEntry(paths, id) {
5067
5536
  if (!isTrashEntryId(id)) return false;
5068
5537
  const dir = inside(paths.trashRoot, id);
5069
- if (!dir || !await exists(dir)) return false;
5538
+ if (!dir || !await exists$1(dir)) return false;
5070
5539
  await fs.rm(dir, {
5071
5540
  recursive: true,
5072
5541
  force: true
@@ -5075,7 +5544,7 @@ async function purgeTrashEntry(paths, id) {
5075
5544
  }
5076
5545
  //#endregion
5077
5546
  //#region src/lemonriver/trash/routes.ts
5078
- const ENTRY_NAMES = [
5547
+ const ENTRY_NAMES$2 = [
5079
5548
  "index.tsx",
5080
5549
  "index.jsx",
5081
5550
  "index.ts",
@@ -5089,7 +5558,7 @@ function registerTrashRoutes(server, ctx) {
5089
5558
  trashRoot: trashRootFor(ctx.userCwd)
5090
5559
  };
5091
5560
  const quietWatcher = (slideId) => {
5092
- for (const name of ENTRY_NAMES) recordWrite(path.join(ctx.slidesRoot, slideId, name));
5561
+ for (const name of ENTRY_NAMES$2) recordWrite(path.join(ctx.slidesRoot, slideId, name));
5093
5562
  };
5094
5563
  const reloadClients = () => {
5095
5564
  invalidateSlidesModule(server);
@@ -5148,6 +5617,1117 @@ function registerTrashRoutes(server, ctx) {
5148
5617
  });
5149
5618
  }
5150
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;
6229
+ try {
6230
+ ast = parse(source, {
6231
+ sourceType: "module",
6232
+ plugins: ["typescript", "jsx"],
6233
+ errorRecovery: true
6234
+ });
6235
+ } catch {
6236
+ return null;
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;
6259
+ }
6260
+ async function exists(file) {
6261
+ try {
6262
+ await fs.access(file);
6263
+ return true;
6264
+ } catch {
6265
+ return false;
6266
+ }
6267
+ }
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)));
6280
+ }
6281
+ }
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;
6305
+ for (const name of names) {
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`);
6312
+ continue;
6313
+ }
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));
6326
+ }
6327
+ return source;
6328
+ }
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 {
6334
+ ok: false,
6335
+ status: 400,
6336
+ error: `bad extra file name: ${extra.name}`
6337
+ };
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"));
6398
+ });
6399
+ decks.push({
6400
+ slideId,
6401
+ title,
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 {
6409
+ ok: false,
6410
+ status: 400,
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);
6441
+ return {
6442
+ ok: true,
6443
+ path: target,
6444
+ name: `${fileName}.zip`,
6445
+ size: zipped.length,
6446
+ warnings
6447
+ };
6448
+ }
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 };
6465
+ }
6466
+ //#endregion
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"]);
6471
+ const ENTRY_NAMES = [
6472
+ "index.tsx",
6473
+ "index.jsx",
6474
+ "index.ts",
6475
+ "index.js"
6476
+ ];
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();
6528
+ const reloadClients = () => {
6529
+ invalidateSlidesModule(server);
6530
+ server.ws.send({
6531
+ type: "custom",
6532
+ event: DECKS_CHANGED_EVENT
6533
+ });
6534
+ };
6535
+ server.middlewares.use("/__lr/share", async (req, res, next) => {
6536
+ const url = new URL(req.url ?? "/", "http://local");
6537
+ const method = req.method ?? "GET";
6538
+ try {
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") {
6580
+ const check = validateMutationRequest(req, { requireJsonBody: true });
6581
+ if (!check.ok) return json(res, check.status, { error: check.error });
6582
+ if (!isLoopbackRequest(req)) return json(res, 403, { error: "local requests only" });
6583
+ const body = await readBody(req);
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
+ }
6590
+ });
6591
+ if (!revealed.ok) return json(res, revealed.status, { error: revealed.error });
6592
+ return json(res, 200, { ok: true });
6593
+ }
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" });
6596
+ const check = validateMutationRequest(req);
6597
+ if (!check.ok) return json(res, check.status, { error: check.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);
6664
+ json(res, 200, {
6665
+ ok: true,
6666
+ imported: result.imported,
6667
+ warnings: result.warnings
6668
+ });
6669
+ return reloadClients();
6670
+ }
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));
6685
+ }
6686
+ next();
6687
+ } catch (err) {
6688
+ if (err instanceof BodyTooLargeError) return json(res, 413, { error: "body too large" });
6689
+ json(res, 500, { error: String(err.message ?? err) });
6690
+ }
6691
+ });
6692
+ }
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
5151
6731
  //#region src/lemonriver/routes.ts
5152
6732
  function registerLemonRiverRoutes(server, ctx) {
5153
6733
  registerBoardRoutes(server, ctx);
@@ -5155,6 +6735,7 @@ function registerLemonRiverRoutes(server, ctx) {
5155
6735
  registerDeckRoutes(server, ctx);
5156
6736
  registerOutlineRoutes(server, ctx);
5157
6737
  registerTemplateRoutes(server, ctx);
6738
+ registerShareRoutes(server, ctx);
5158
6739
  registerAgentProviderRoutes(server, ctx);
5159
6740
  }
5160
6741
  //#endregion