@lemonriver/core 0.7.0 → 0.8.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 (38) hide show
  1. package/dist/{build-CKwrex8y.js → build-Bdagm0FU.js} +1 -1
  2. package/dist/cli/bin.js +4 -4
  3. package/dist/{config-B1_gk0sy.js → config-Begts3gq.js} +5921 -3971
  4. package/dist/{dev-DZ2Yzl2p.js → dev-DjjzmT28.js} +2 -2
  5. package/dist/{preview-hMDcuHfP.js → preview-C9y9MTY1.js} +1 -1
  6. package/dist/{update-CMRxtTc9.js → update-b1dSg_FW.js} +17 -17
  7. package/dist/vite/index.js +1 -1
  8. package/package.json +1 -1
  9. package/src/app/lemonriver/backup/client.ts +177 -0
  10. package/src/app/lemonriver/backup/guide.test.ts +45 -0
  11. package/src/app/lemonriver/backup/guide.ts +138 -0
  12. package/src/app/lemonriver/backup/model.test.ts +96 -0
  13. package/src/app/lemonriver/backup/model.ts +255 -0
  14. package/src/app/lemonriver/backup/places.test.ts +154 -0
  15. package/src/app/lemonriver/backup/places.ts +74 -0
  16. package/src/app/lemonriver/board/blocks/snapshot.ts +10 -2
  17. package/src/app/lemonriver/board/self-check-runner.tsx +60 -15
  18. package/src/app/lemonriver/features.test.ts +5 -0
  19. package/src/app/lemonriver/features.ts +11 -1
  20. package/src/app/lemonriver/help/help-page.tsx +262 -0
  21. package/src/app/lemonriver/help/model.test.ts +107 -0
  22. package/src/app/lemonriver/help/model.ts +96 -0
  23. package/src/app/lemonriver/routes.test.tsx +4 -2
  24. package/src/app/lemonriver/routes.tsx +2 -0
  25. package/src/app/lemonriver/settings/backup-restore-dialog.tsx +525 -0
  26. package/src/app/lemonriver/settings/backup-section.tsx +489 -0
  27. package/src/app/lemonriver/settings/settings-page.tsx +22 -0
  28. package/src/app/lemonriver/share/client.ts +6 -0
  29. package/src/app/lemonriver/share/import-dialog.tsx +14 -0
  30. package/src/app/lemonriver/share/paths.test.ts +41 -0
  31. package/src/app/lemonriver/share/paths.ts +45 -11
  32. package/src/app/lemonriver/share/share-dialog.tsx +54 -1
  33. package/src/app/lemonriver/text/en.ts +521 -0
  34. package/src/app/lemonriver/text/es.ts +79 -0
  35. package/src/app/lemonriver/text/ja.ts +76 -0
  36. package/src/app/lemonriver/text/types.ts +90 -0
  37. package/src/app/lemonriver/text/zh-cn.ts +497 -0
  38. package/src/app/lemonriver/text/zh-tw.ts +497 -0
@@ -1,6 +1,6 @@
1
- import { V as PKG_NAMES } from "./update-CMRxtTc9.js";
1
+ import { V as PKG_NAMES } from "./update-b1dSg_FW.js";
2
2
  import { a as printUrls, i as printShortcutsHint, n as formatError, o as shortcutsEnabled, r as printHeader, s as startupDuration, t as createCliLogger } from "./cli/bin.js";
3
- import { n as DEV_SUPERVISED_ENV, t as createViteConfig } from "./config-B1_gk0sy.js";
3
+ import { n as DEV_SUPERVISED_ENV, t as createViteConfig } from "./config-Begts3gq.js";
4
4
  import path from "node:path";
5
5
  import { existsSync } from "node:fs";
6
6
  import { fork } from "node:child_process";
@@ -1,5 +1,5 @@
1
1
  import { a as printUrls, i as printShortcutsHint, o as shortcutsEnabled, r as printHeader, s as startupDuration, t as createCliLogger } from "./cli/bin.js";
2
- import { t as createViteConfig } from "./config-B1_gk0sy.js";
2
+ import { t as createViteConfig } from "./config-Begts3gq.js";
3
3
  import { mergeConfig, preview as preview$1 } from "vite";
4
4
  //#region src/cli/preview.ts
5
5
  async function preview(opts = {}) {
@@ -1,7 +1,7 @@
1
1
  import path from "node:path";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { spawn } from "node:child_process";
4
- import fs from "node:fs/promises";
4
+ import fs$1 from "node:fs/promises";
5
5
  import { parse } from "@babel/parser";
6
6
  import { randomUUID } from "node:crypto";
7
7
  //#region src/branding.ts
@@ -143,7 +143,7 @@ const SLIDE_ID_RE = /^[a-z0-9_-]+$/i;
143
143
  async function slideIdTaken(root, slideId) {
144
144
  let names;
145
145
  try {
146
- names = await fs.readdir(root);
146
+ names = await fs$1.readdir(root);
147
147
  } catch {
148
148
  return false;
149
149
  }
@@ -215,7 +215,7 @@ async function rmSlideDir(slidesRoot, slideId) {
215
215
  const dir = path.resolve(slidesRoot, slideId);
216
216
  if (!dir.startsWith(slidesRoot + path.sep)) return false;
217
217
  try {
218
- await fs.rm(dir, {
218
+ await fs$1.rm(dir, {
219
219
  recursive: true,
220
220
  force: true
221
221
  });
@@ -238,7 +238,7 @@ async function duplicateSlideDir(slidesRoot, slideId, desiredId) {
238
238
  error: "invalid slideId"
239
239
  };
240
240
  try {
241
- await fs.access(path.join(srcDir, "index.tsx"));
241
+ await fs$1.access(path.join(srcDir, "index.tsx"));
242
242
  } catch {
243
243
  return {
244
244
  ok: false,
@@ -284,7 +284,7 @@ async function duplicateSlideDir(slidesRoot, slideId, desiredId) {
284
284
  const srcEntry = path.join(srcDir, "index.tsx");
285
285
  let copiedEntrySource;
286
286
  try {
287
- const source = await fs.readFile(srcEntry, "utf8");
287
+ const source = await fs$1.readFile(srcEntry, "utf8");
288
288
  const metaTitle = readMetaTitleInSource(source);
289
289
  if (metaTitle.kind === "unsupported") return {
290
290
  ok: false,
@@ -306,12 +306,12 @@ async function duplicateSlideDir(slidesRoot, slideId, desiredId) {
306
306
  };
307
307
  }
308
308
  try {
309
- await fs.cp(srcDir, dstDir, {
309
+ await fs$1.cp(srcDir, dstDir, {
310
310
  recursive: true,
311
311
  errorOnExist: true,
312
312
  force: false
313
313
  });
314
- await fs.writeFile(path.join(dstDir, "index.tsx"), copiedEntrySource, "utf8");
314
+ await fs$1.writeFile(path.join(dstDir, "index.tsx"), copiedEntrySource, "utf8");
315
315
  return {
316
316
  ok: true,
317
317
  slideId: newId
@@ -343,13 +343,13 @@ export default [Blank] satisfies Page[];
343
343
  }
344
344
  async function createBlankSlideDir(slidesRoot, specifier = PKG_NAME) {
345
345
  const root = path.resolve(slidesRoot);
346
- await fs.mkdir(root, { recursive: true });
346
+ await fs$1.mkdir(root, { recursive: true });
347
347
  for (let suffix = 1; suffix < 1e3; suffix++) {
348
348
  const slideId = suffix === 1 ? "untitled" : `untitled-${suffix}`;
349
349
  if (await slideIdTaken(root, slideId)) continue;
350
350
  const dir = path.join(root, slideId);
351
351
  try {
352
- await fs.mkdir(dir);
352
+ await fs$1.mkdir(dir);
353
353
  } catch (err) {
354
354
  if (err.code === "EEXIST") continue;
355
355
  return {
@@ -359,7 +359,7 @@ async function createBlankSlideDir(slidesRoot, specifier = PKG_NAME) {
359
359
  };
360
360
  }
361
361
  const file = path.join(dir, "index.tsx");
362
- await fs.writeFile(file, blankSlideSource((/* @__PURE__ */ new Date()).toISOString(), specifier), "utf8");
362
+ await fs$1.writeFile(file, blankSlideSource((/* @__PURE__ */ new Date()).toISOString(), specifier), "utf8");
363
363
  return {
364
364
  ok: true,
365
365
  slideId,
@@ -389,7 +389,7 @@ async function renameSlideDir(slidesRoot, slideId, desiredId) {
389
389
  error: "invalid slideId"
390
390
  };
391
391
  try {
392
- await fs.access(path.join(from, "index.tsx"));
392
+ await fs$1.access(path.join(from, "index.tsx"));
393
393
  } catch {
394
394
  return {
395
395
  ok: false,
@@ -407,7 +407,7 @@ async function renameSlideDir(slidesRoot, slideId, desiredId) {
407
407
  if (await slideIdTaken(root, candidate)) continue;
408
408
  const to = path.join(root, candidate);
409
409
  try {
410
- await fs.rename(from, to);
410
+ await fs$1.rename(from, to);
411
411
  } catch (err) {
412
412
  const code = err.code;
413
413
  if (code === "EEXIST" || code === "ENOTEMPTY") continue;
@@ -783,7 +783,7 @@ function emptyManifest() {
783
783
  }
784
784
  async function readManifest(file) {
785
785
  try {
786
- const raw = await fs.readFile(file, "utf8");
786
+ const raw = await fs$1.readFile(file, "utf8");
787
787
  const parsed = JSON.parse(raw);
788
788
  return {
789
789
  folders: Array.isArray(parsed.folders) ? parsed.folders : [],
@@ -795,8 +795,8 @@ async function readManifest(file) {
795
795
  }
796
796
  }
797
797
  async function writeManifest(file, manifest) {
798
- await fs.mkdir(path.dirname(file), { recursive: true });
799
- await fs.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
798
+ await fs$1.mkdir(path.dirname(file), { recursive: true });
799
+ await fs$1.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
800
800
  }
801
801
  function newFolderId() {
802
802
  return shortId("f");
@@ -899,7 +899,7 @@ function resolveSlideEntryPath(ctx, slideId) {
899
899
  }
900
900
  async function readSlideSource(file) {
901
901
  try {
902
- return await fs.readFile(file, "utf8");
902
+ return await fs$1.readFile(file, "utf8");
903
903
  } catch (err) {
904
904
  if (err.code === "ENOENT") return null;
905
905
  throw err;
@@ -952,7 +952,7 @@ async function fetchLatest(pkg, now) {
952
952
  }
953
953
  async function fileExists(file) {
954
954
  try {
955
- await fs.access(file);
955
+ await fs$1.access(file);
956
956
  return true;
957
957
  } catch {
958
958
  return false;
@@ -1,2 +1,2 @@
1
- import { t as createViteConfig } from "../config-B1_gk0sy.js";
1
+ import { t as createViteConfig } from "../config-Begts3gq.js";
2
2
  export { createViteConfig };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lemonriver/core",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "The LemonRiver runtime: deck viewer, story board, present mode, agent panel and export.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -0,0 +1,177 @@
1
+ import type {
2
+ BackupJob,
3
+ BackupListItem,
4
+ BackupPlace,
5
+ BackupPreview,
6
+ BackupSettings,
7
+ PrefsSnapshot,
8
+ } from './model';
9
+
10
+ async function call<T>(method: string, url: string, body?: unknown): Promise<T> {
11
+ const response = await fetch(url, {
12
+ method,
13
+ ...(body === undefined
14
+ ? {}
15
+ : { headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }),
16
+ });
17
+ const data = (await response.json().catch(() => ({}))) as T & { error?: string };
18
+ if (!response.ok) throw new Error(data?.error ?? `HTTP ${response.status}`);
19
+ return data;
20
+ }
21
+
22
+ export type PlaceAnswer = { path: string } | { cancelled: true } | { unsupported: true };
23
+
24
+ export async function backupSettings(): Promise<{ settings: BackupSettings; dir: string | null }> {
25
+ return await call('GET', '/__lr/backup/settings');
26
+ }
27
+
28
+ export async function saveBackupSettings(patch: {
29
+ folder?: string | null;
30
+ auto?: boolean;
31
+ keep?: number;
32
+ }): Promise<{ ok: true; settings: BackupSettings } | { ok: false; code: string }> {
33
+ const response = await fetch('/__lr/backup/settings', {
34
+ method: 'POST',
35
+ headers: { 'content-type': 'application/json' },
36
+ body: JSON.stringify(patch),
37
+ });
38
+ const data = (await response.json().catch(() => ({}))) as {
39
+ ok?: boolean;
40
+ code?: string;
41
+ settings?: BackupSettings;
42
+ error?: string;
43
+ };
44
+ if (!response.ok || !data.ok || !data.settings) {
45
+ return { ok: false, code: data.code ?? 'failed' };
46
+ }
47
+ return { ok: true, settings: data.settings };
48
+ }
49
+
50
+ export async function backupPlaces(): Promise<BackupPlace[]> {
51
+ const data = await call<{ places: BackupPlace[] }>('GET', '/__lr/backup/places');
52
+ return data.places;
53
+ }
54
+
55
+ async function pick(url: string, locale: string): Promise<PlaceAnswer> {
56
+ const response = await fetch(url, {
57
+ method: 'POST',
58
+ headers: { 'content-type': 'application/json' },
59
+ body: JSON.stringify({ locale }),
60
+ });
61
+ const data = (await response.json().catch(() => ({}))) as PlaceAnswer & { error?: string };
62
+ if (response.status === 501 || 'unsupported' in data) return { unsupported: true };
63
+ if (!response.ok) throw new Error(data?.error ?? `HTTP ${response.status}`);
64
+ return data;
65
+ }
66
+
67
+ export async function pickBackupFolder(locale: string): Promise<PlaceAnswer> {
68
+ return await pick('/__lr/backup/choose-folder', locale);
69
+ }
70
+
71
+ export async function pickBackupFile(locale: string): Promise<PlaceAnswer> {
72
+ return await pick('/__lr/backup/choose-file', locale);
73
+ }
74
+
75
+ export async function backupList(): Promise<BackupListItem[]> {
76
+ const data = await call<{ backups: BackupListItem[] }>('GET', '/__lr/backup/list');
77
+ return data.backups;
78
+ }
79
+
80
+ export type InspectAnswer =
81
+ | { ok: true; path: string; preview: BackupPreview }
82
+ | { ok: false; code: string; detail: string };
83
+
84
+ export async function inspectBackup(path: string): Promise<InspectAnswer> {
85
+ const response = await fetch('/__lr/backup/inspect', {
86
+ method: 'POST',
87
+ headers: { 'content-type': 'application/json' },
88
+ body: JSON.stringify({ path }),
89
+ });
90
+ const data = (await response.json().catch(() => ({}))) as {
91
+ ok?: boolean;
92
+ code?: string;
93
+ detail?: string;
94
+ error?: string;
95
+ preview?: BackupPreview;
96
+ };
97
+ if (!response.ok || !data.ok || !data.preview) {
98
+ return {
99
+ ok: false,
100
+ code: data.code ?? 'failed',
101
+ detail: data.detail ?? data.error ?? '',
102
+ };
103
+ }
104
+ return { ok: true, path, preview: data.preview };
105
+ }
106
+
107
+ export async function startBackup(locale: string): Promise<{ jobId: string; running: boolean }> {
108
+ return await call('POST', '/__lr/backup/run', { locale });
109
+ }
110
+
111
+ export async function startRestore(
112
+ path: string,
113
+ decks: string[],
114
+ prefs: boolean,
115
+ ): Promise<{ jobId: string; running: boolean }> {
116
+ return await call('POST', '/__lr/backup/restore', { path, decks, prefs });
117
+ }
118
+
119
+ export async function backupJob(id: string): Promise<BackupJob> {
120
+ return await call('GET', `/__lr/backup/job/${id}`);
121
+ }
122
+
123
+ export async function revealBackup(path: string): Promise<boolean> {
124
+ try {
125
+ await call('POST', '/__lr/backup/reveal', { path });
126
+ return true;
127
+ } catch {
128
+ return false;
129
+ }
130
+ }
131
+
132
+ export async function sendPrefs(prefs: PrefsSnapshot): Promise<void> {
133
+ await call('POST', '/__lr/backup/prefs', { prefs }).catch(() => {});
134
+ }
135
+
136
+ /** Polls a running job until it settles. */
137
+ export async function waitForJob(
138
+ id: string,
139
+ onUpdate: (job: BackupJob) => void,
140
+ intervalMs = 700,
141
+ ): Promise<BackupJob> {
142
+ for (;;) {
143
+ const job = await backupJob(id);
144
+ onUpdate(job);
145
+ if (job.state !== 'running') return job;
146
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
147
+ }
148
+ }
149
+
150
+ // A restore invalidates the slides module, so the page reloads before the
151
+ // dialog can show how it went. The job id survives the reload in this tab.
152
+ const PENDING_RESTORE = 'lemonriver:backup-restore-job';
153
+
154
+ export function pendingRestoreJob(): string | null {
155
+ try {
156
+ const raw = sessionStorage.getItem(PENDING_RESTORE);
157
+ if (!raw) return null;
158
+ const parsed: unknown = JSON.parse(raw);
159
+ if (typeof parsed !== 'object' || parsed === null) return null;
160
+ const id = (parsed as { id?: unknown }).id;
161
+ return typeof id === 'string' && id !== '' ? id : null;
162
+ } catch {
163
+ return null;
164
+ }
165
+ }
166
+
167
+ export function rememberRestoreJob(id: string): void {
168
+ try {
169
+ sessionStorage.setItem(PENDING_RESTORE, JSON.stringify({ id }));
170
+ } catch {}
171
+ }
172
+
173
+ export function forgetRestoreJob(): void {
174
+ try {
175
+ sessionStorage.removeItem(PENDING_RESTORE);
176
+ } catch {}
177
+ }
@@ -0,0 +1,45 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { buildRestoreGuide, formatSize, restoreGuideFileName } from './guide.ts';
3
+
4
+ const AT = new Date(2026, 10, 1, 21, 30).getTime();
5
+
6
+ describe('the restore guide inside a backup', () => {
7
+ it('says how to restore, in the language of the interface', () => {
8
+ const zh = buildRestoreGuide({
9
+ createdAt: AT,
10
+ decks: 3,
11
+ sizeBytes: 620 * 1024 * 1024,
12
+ appVersion: '0.8.0',
13
+ locale: 'zh-CN',
14
+ });
15
+ expect(zh).toContain('LemonRiver 备份 · 2026-11-01 21:30');
16
+ expect(zh).toContain('3 份演示 · 620 MB · 用 LemonRiver 0.8.0 备份');
17
+ expect(zh).toContain('从备份恢复');
18
+ expect(zh).toContain('https://github.com/SegawaBeer/lemonriver/releases');
19
+ expect(zh).not.toContain('<script');
20
+
21
+ const en = buildRestoreGuide({
22
+ createdAt: AT,
23
+ decks: 1,
24
+ sizeBytes: 2048,
25
+ appVersion: '0.8.0',
26
+ locale: 'en',
27
+ });
28
+ expect(en).toContain('LemonRiver backup · 2026-11-01 21:30');
29
+ expect(en).toContain('1 decks · 2 KB · Made with LemonRiver 0.8.0');
30
+ expect(en).toContain('Settings → Backup');
31
+ });
32
+
33
+ it('names the file per language', () => {
34
+ expect(restoreGuideFileName('zh-CN')).toBe('怎么恢复.html');
35
+ expect(restoreGuideFileName('zh-TW')).toBe('怎麼還原.html');
36
+ expect(restoreGuideFileName('en')).toBe('How to restore.html');
37
+ });
38
+
39
+ it('formats sizes the way the backup line shows them', () => {
40
+ expect(formatSize(900)).toBe('900 B');
41
+ expect(formatSize(18 * 1024)).toBe('18 KB');
42
+ expect(formatSize(620 * 1024 * 1024)).toBe('620 MB');
43
+ expect(formatSize(1.5 * 1024 * 1024 * 1024)).toBe('1.5 GB');
44
+ });
45
+ });
@@ -0,0 +1,138 @@
1
+ /**
2
+ * The how-to-restore page inside a backup zip. Same rules as the share guide:
3
+ * standalone, no script, every string escaped.
4
+ */
5
+
6
+ import { type GuideLocale, guideLocaleFor, htmlEscape } from '../share/guide.ts';
7
+
8
+ export type RestoreGuideInput = {
9
+ createdAt: number;
10
+ decks: number;
11
+ sizeBytes: number;
12
+ appVersion: string;
13
+ locale: GuideLocale;
14
+ };
15
+
16
+ const RELEASES_URL = 'https://github.com/SegawaBeer/lemonriver/releases';
17
+
18
+ export function restoreGuideFileName(locale: GuideLocale): string {
19
+ if (locale === 'zh-CN') return '怎么恢复.html';
20
+ if (locale === 'zh-TW') return '怎麼還原.html';
21
+ return 'How to restore.html';
22
+ }
23
+
24
+ export function restoreGuideLocale(id: string): GuideLocale {
25
+ return guideLocaleFor(id);
26
+ }
27
+
28
+ export function formatSize(bytes: number): string {
29
+ if (bytes >= 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
30
+ if (bytes >= 1024 * 1024) return `${Math.round(bytes / (1024 * 1024))} MB`;
31
+ if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
32
+ return `${bytes} B`;
33
+ }
34
+
35
+ type Phrases = {
36
+ lang: string;
37
+ heading: (date: string) => string;
38
+ sub: (decks: number, size: string, version: string) => string;
39
+ steps: (url: string) => string[];
40
+ replaces: string;
41
+ footer: string;
42
+ };
43
+
44
+ const PHRASES: Record<GuideLocale, Phrases> = {
45
+ 'zh-CN': {
46
+ lang: 'zh-CN',
47
+ heading: (date) => `LemonRiver 备份 · ${date}`,
48
+ sub: (decks, size, version) => `${decks} 份演示 · ${size} · 用 LemonRiver ${version} 备份`,
49
+ steps: (url) => [
50
+ `打开 LemonRiver(换了电脑就先装好,下载地址 ${url} )。`,
51
+ '打开「设置 → 备份」,点「从备份恢复…」,选这个压缩包。',
52
+ '勾选要恢复的演示,点「恢复」。',
53
+ ],
54
+ replaces: '你电脑上同名的演示会先移进回收站,30 天内能找回。',
55
+ footer: '不要解开这个压缩包改里面的文件,改了会恢复失败。',
56
+ },
57
+ 'zh-TW': {
58
+ lang: 'zh-TW',
59
+ heading: (date) => `LemonRiver 備份 · ${date}`,
60
+ sub: (decks, size, version) => `${decks} 份演示 · ${size} · 用 LemonRiver ${version} 備份`,
61
+ steps: (url) => [
62
+ `打開 LemonRiver(換了電腦就先裝好,下載位址 ${url} )。`,
63
+ '打開「設定 → 備份」,點「從備份還原…」,選這個壓縮檔。',
64
+ '勾選要還原的演示,點「還原」。',
65
+ ],
66
+ replaces: '你電腦上同名的演示會先移進回收站,30 天內能找回。',
67
+ footer: '不要解開這個壓縮檔改裡面的檔案,改了會還原失敗。',
68
+ },
69
+ en: {
70
+ lang: 'en',
71
+ heading: (date) => `LemonRiver backup · ${date}`,
72
+ sub: (decks, size, version) => `${decks} decks · ${size} · Made with LemonRiver ${version}`,
73
+ steps: (url) => [
74
+ `Open LemonRiver. On a new computer, install it first: ${url}.`,
75
+ 'Open Settings → Backup, click “Restore from backup…”, and pick this zip.',
76
+ 'Tick the decks you want back and click “Restore”.',
77
+ ],
78
+ replaces:
79
+ 'A deck with the same name on your computer goes to the recycle bin first and can be brought back for 30 days.',
80
+ footer: 'Do not unpack the zip and edit what is inside; the restore will fail.',
81
+ },
82
+ };
83
+
84
+ function formatDateTime(createdAt: number): string {
85
+ const date = new Date(createdAt);
86
+ const pad = (value: number) => String(value).padStart(2, '0');
87
+ const day = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
88
+ const time = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
89
+ return `${day} ${time}`;
90
+ }
91
+
92
+ export function buildRestoreGuide(input: RestoreGuideInput): string {
93
+ const p = PHRASES[input.locale];
94
+ const heading = htmlEscape(p.heading(formatDateTime(input.createdAt)));
95
+ const sub = htmlEscape(p.sub(input.decks, formatSize(input.sizeBytes), input.appVersion));
96
+ const steps = p
97
+ .steps(RELEASES_URL)
98
+ .map((step) =>
99
+ htmlEscape(step).replace(RELEASES_URL, `<a href="${RELEASES_URL}">${RELEASES_URL}</a>`),
100
+ );
101
+
102
+ return `<!doctype html>
103
+ <html lang="${p.lang}">
104
+ <head>
105
+ <meta charset="utf-8">
106
+ <meta name="viewport" content="width=device-width, initial-scale=1">
107
+ <title>${heading}</title>
108
+ <style>
109
+ :root { color-scheme: light dark; }
110
+ body { margin: 0 auto; padding: 40px 24px 72px; max-width: 680px; font: 16px/1.7 -apple-system, "PingFang SC", "Microsoft YaHei", system-ui, sans-serif; color: #1c1c1e; background: #fff; }
111
+ h1 { font-size: 28px; line-height: 1.25; margin: 0 0 8px; }
112
+ .sub { margin: 0 0 32px; color: #6b6b70; font-size: 14px; }
113
+ ol { margin: 0; padding-left: 1.4em; }
114
+ li { margin: 6px 0; }
115
+ .note { margin: 16px 0 0; padding: 12px 14px; border-radius: 10px; background: #f2f2f7; }
116
+ footer { margin-top: 40px; padding-top: 16px; border-top: 1px solid #e5e5ea; color: #6b6b70; font-size: 14px; }
117
+ a { color: #0a58ca; }
118
+ @media (prefers-color-scheme: dark) {
119
+ body { color: #f2f2f7; background: #1c1c1e; }
120
+ .sub, footer { color: #a1a1a6; }
121
+ .note { background: #2c2c2e; }
122
+ footer { border-top-color: #2c2c2e; }
123
+ a { color: #6cb2ff; }
124
+ }
125
+ </style>
126
+ </head>
127
+ <body>
128
+ <h1>${heading}</h1>
129
+ <p class="sub">${sub}</p>
130
+ <ol>
131
+ ${steps.map((step) => `<li>${step}</li>`).join('\n')}
132
+ </ol>
133
+ <p class="note">${htmlEscape(p.replaces)}</p>
134
+ <footer>${htmlEscape(p.footer)}</footer>
135
+ </body>
136
+ </html>
137
+ `;
138
+ }
@@ -0,0 +1,96 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ backupDue,
4
+ backupFileStem,
5
+ DAY_MS,
6
+ DEFAULT_KEEP,
7
+ isCompressedFile,
8
+ looksLikeBackupName,
9
+ PREFS_KEYS,
10
+ sanitizePrefs,
11
+ sanitizeSettings,
12
+ } from './model.ts';
13
+
14
+ const SETTINGS = { folder: '/Users/me/Backups', auto: true, keep: 7, last: null, written: [] };
15
+
16
+ describe('backup settings', () => {
17
+ it('falls back to a usable default', () => {
18
+ expect(sanitizeSettings(null)).toEqual({
19
+ folder: null,
20
+ auto: false,
21
+ keep: DEFAULT_KEEP,
22
+ last: null,
23
+ written: [],
24
+ });
25
+ expect(sanitizeSettings({ folder: 'relative/path' }).folder).toBeNull();
26
+ expect(sanitizeSettings({ keep: 5 }).keep).toBe(DEFAULT_KEEP);
27
+ expect(sanitizeSettings({ keep: 30 }).keep).toBe(30);
28
+ expect(sanitizeSettings({ written: ['a.zip', 'a.zip', 'x/y.zip'] }).written).toEqual(['a.zip']);
29
+ });
30
+
31
+ it('knows when the daily backup is due', () => {
32
+ const now = 1_800_000_000_000;
33
+ expect(backupDue(sanitizeSettings({ ...SETTINGS, auto: false }), now)).toBe(false);
34
+ expect(backupDue(sanitizeSettings({ ...SETTINGS, folder: null }), now)).toBe(false);
35
+ expect(backupDue(sanitizeSettings(SETTINGS), now)).toBe(true);
36
+ expect(
37
+ backupDue(
38
+ sanitizeSettings({ ...SETTINGS, last: { at: now - 23 * 3600_000, ok: true } }),
39
+ now,
40
+ ),
41
+ ).toBe(false);
42
+ expect(
43
+ backupDue(sanitizeSettings({ ...SETTINGS, last: { at: now - DAY_MS - 1, ok: true } }), now),
44
+ ).toBe(true);
45
+ });
46
+
47
+ it('waits an hour before retrying a failed backup', () => {
48
+ const now = 1_800_000_000_000;
49
+ const failed = { at: now - 10 * 60_000, ok: false, path: '', size: 0, error: 'denied' };
50
+ expect(backupDue(sanitizeSettings({ ...SETTINGS, last: failed }), now)).toBe(false);
51
+ const older = { ...failed, at: now - 2 * 3600_000 };
52
+ expect(backupDue(sanitizeSettings({ ...SETTINGS, last: older }), now)).toBe(true);
53
+ });
54
+
55
+ it('names the file after the local date and time', () => {
56
+ const at = new Date(2026, 10, 1, 21, 30).getTime();
57
+ expect(backupFileStem(at)).toBe('LemonRiver 备份 2026-11-01 2130');
58
+ });
59
+
60
+ it('stores formats that are already compressed', () => {
61
+ expect(isCompressedFile('photo.JPG')).toBe(true);
62
+ expect(isCompressedFile('report.pdf')).toBe(true);
63
+ expect(isCompressedFile('deck.pptx')).toBe(true);
64
+ expect(isCompressedFile('index.tsx')).toBe(false);
65
+ expect(isCompressedFile('notes.md')).toBe(false);
66
+ });
67
+
68
+ it('counts only its own file names as backups', () => {
69
+ expect(looksLikeBackupName('LemonRiver 备份 2026-11-01 2130.zip')).toBe(true);
70
+ expect(looksLikeBackupName('my stuff.zip')).toBe(false);
71
+ expect(looksLikeBackupName('LemonRiver 备份 notes.txt')).toBe(false);
72
+ });
73
+ });
74
+
75
+ describe('prefs that travel with a backup', () => {
76
+ it('keeps the whitelist and drops everything else', () => {
77
+ const kept = sanitizePrefs({
78
+ theme: 'dark',
79
+ 'open-slide:locale': 'zh-CN',
80
+ 'lemonriver:agent-prefs': '{"tone":"steady"}',
81
+ 'open-slide:agent-auto-approve': 'true',
82
+ 'lemonriver:session': 'secret',
83
+ 'open-slide:home-sort': 3,
84
+ });
85
+ expect(kept).toEqual({
86
+ theme: 'dark',
87
+ 'open-slide:locale': 'zh-CN',
88
+ 'lemonriver:agent-prefs': '{"tone":"steady"}',
89
+ });
90
+ });
91
+
92
+ it('never carries agent auto-approve', () => {
93
+ expect(PREFS_KEYS as readonly string[]).not.toContain('open-slide:agent-auto-approve');
94
+ expect(sanitizePrefs({ 'open-slide:agent-auto-approve': 'true' })).toEqual({});
95
+ });
96
+ });