cortico-world-fun 0.3.0 → 0.7.5

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 (50) hide show
  1. package/CHANGELOG.md +571 -404
  2. package/PUBLISHING.md +37 -85
  3. package/README.md +199 -47
  4. package/assets/home/chibi-cards.webp +0 -0
  5. package/assets/home/chibi-chatting.webp +0 -0
  6. package/assets/home/chibi-cooking.webp +0 -0
  7. package/assets/home/chibi-gaming.webp +0 -0
  8. package/assets/home/chibi-idle.webp +0 -0
  9. package/assets/home/chibi-looking_outside.webp +0 -0
  10. package/assets/home/chibi-painting.webp +0 -0
  11. package/assets/home/chibi-reading.webp +0 -0
  12. package/assets/home/chibi-sleeping.webp +0 -0
  13. package/assets/home/chibi-watching.webp +0 -0
  14. package/assets/icon.png +0 -0
  15. package/describe.json +365 -48
  16. package/dist/webui.js +7515 -848
  17. package/package.json +16 -10
  18. package/src/ENV_PROMPT.md +11 -10
  19. package/src/bridge-echo-solo.json +137 -0
  20. package/src/config.js +356 -176
  21. package/src/creek-letter.js +3 -0
  22. package/src/definition.js +121 -106
  23. package/src/exploration.js +2 -2
  24. package/src/home-room.js +895 -0
  25. package/src/journeys.js +1 -1
  26. package/src/phases.js +5 -10
  27. package/src/place-cover.js +176 -0
  28. package/src/place-library.js +794 -0
  29. package/src/place-transfer.js +162 -0
  30. package/src/state.js +717 -596
  31. package/src/story-canon.js +21 -0
  32. package/src/story-dm.js +140 -0
  33. package/src/story-examples.js +597 -78
  34. package/src/story-free.js +298 -0
  35. package/src/story-images.js +474 -0
  36. package/src/story-library.js +187 -20
  37. package/src/story-node-limit.js +55 -0
  38. package/src/story-packs.js +333 -16
  39. package/src/story-panel.js +314 -0
  40. package/src/story-read.js +113 -0
  41. package/src/story-reliability.js +95 -0
  42. package/src/story-secrets.js +485 -0
  43. package/src/story-venue-migration.js +113 -0
  44. package/src/swapped-plaque-riddle.json +167 -0
  45. package/src/time.js +16 -0
  46. package/src/user-venues.js +44 -15
  47. package/src/venues.js +93 -9
  48. package/src/world.js +3690 -1847
  49. package/dist/artwork.js +0 -64
  50. package/dist/stories.js +0 -395
@@ -0,0 +1,895 @@
1
+ /**
2
+ * 「家」的 2D 房间状态:一个独立的 `fun/home/room.json` + 内容寻址的图片目录。
3
+ *
4
+ * 三条底线(都有测试守着):
5
+ * 1. **不碰 `state.json`**——这里只写 `fun/home/`,行进中的行程、故事、回忆一个字节都不动。
6
+ * 2. **读不落盘**——`snapshot()` / `readArt()` 只读;写只有那几个 `set*`。
7
+ * 3. **坏文件不覆盖**——`room.json` 解析不了就整份留在原地,面板转只读,写操作全拒。
8
+ *
9
+ * 版本:`room.json` v1(P0–P2)与 v2(P4 起)。v2 多了 `placements`、`art.foreground`、
10
+ * `art.painting`;v1 读进来先在内存里补成 v2,**第一次写才落成 v2**(只读方法仍然不落盘)。
11
+ * 旧字段一个都不丢:迁移只加缺省值。
12
+ *
13
+ * 图片复用地点封面的校验器(`place-cover.js`):同一个 8 MiB 上限、同一组格式、
14
+ * 同一个 `<sha256>.<ext>` 内容寻址命名;读盘时再用 `storedCover()` 复核一遍,
15
+ * 防止文件被换掉之后仍被当成原图显示。
16
+ */
17
+ import { randomUUID } from 'node:crypto';
18
+ import { constants } from 'node:fs';
19
+ import { lstat, mkdir, open, readdir, readFile, rename, unlink } from 'node:fs/promises';
20
+ import { join } from 'node:path';
21
+ import { COVER_ID, decodeCover, MAX_COVER_BYTES, storedCover } from './place-cover.js';
22
+
23
+ export const ACTIVITIES = Object.freeze([
24
+ 'idle', 'reading', 'watching', 'cards', 'gaming',
25
+ 'painting', 'cooking', 'looking_outside', 'sleeping', 'chatting',
26
+ ]);
27
+
28
+ export const ACTIVITY_LABELS = Object.freeze({
29
+ idle: '发呆',
30
+ reading: '读书',
31
+ watching: '刷视频',
32
+ cards: '打牌',
33
+ gaming: '打游戏',
34
+ painting: '画画',
35
+ cooking: '做饭',
36
+ looking_outside: '看窗外',
37
+ sleeping: '睡觉',
38
+ chatting: '和主人聊天',
39
+ });
40
+
41
+ export const ACTIVITY_HINTS = Object.freeze({
42
+ idle: '什么也不做,就在家里待着。',
43
+ reading: '翻一本旧书,或者一本一直没读完的。',
44
+ watching: '刷一会儿视频,手机举在手里。',
45
+ cards: '摊开一副牌,自己跟自己玩。',
46
+ gaming: '坐在毯子上打一会儿游戏。',
47
+ painting: '在画架前涂点颜色。',
48
+ cooking: '在厨房角煮点东西。',
49
+ looking_outside: '站在窗边,看外面。',
50
+ sleeping: '蜷在沙发上睡一会儿。',
51
+ chatting: '转过身来,跟主人说话。',
52
+ });
53
+
54
+ const MAX_ROOM_BYTES = 256 * 1024;
55
+ const MAX_ART_FILES = 64;
56
+ const MAX_ART_BYTES = 128 * 1024 * 1024;
57
+ const MAX_NOTE = 120;
58
+ const MAX_PLAN = 60;
59
+ const MAX_HOTSPOTS = 12;
60
+ const MAX_HOTSPOT_NOTE = 60;
61
+ const MIN_SCALE = 0.1;
62
+ const MAX_SCALE = 2;
63
+ const MAX_SNAPSHOTS = 100;
64
+ const SNAPSHOT_ID = /^\d{10,20}$/;
65
+ const REF = /^[a-f0-9]{64}\.(?:png|jpg|gif|webp)$/;
66
+ const HOTSPOT_ID = /^[a-z0-9-]{1,32}$/;
67
+ const SOURCES = new Set(['default', 'panel']);
68
+
69
+ /**
70
+ * 时段默认活动(服务端按 Asia/Shanghai 小时算)。
71
+ *
72
+ * **只影响展示,不写盘**:`source: 'default'` 时看到的活动由这里决定;
73
+ * 用户点任意活动之后 `source: 'panel'`,文件里的活动才开始固定。
74
+ * 六个时段见任务书 §4。
75
+ */
76
+ export function defaultActivityAt(hour) {
77
+ const h = Number.isFinite(hour) ? ((Math.trunc(hour) % 24) + 24) % 24 : 0;
78
+ if (h < 8) return 'sleeping';
79
+ if (h < 11) return 'looking_outside';
80
+ if (h < 14) return 'cooking';
81
+ if (h < 18) return 'reading';
82
+ if (h < 21) return 'gaming';
83
+ return 'watching';
84
+ }
85
+
86
+ /**
87
+ * 四段光:morning 05–10、day 11–16、dusk 17–19、night 20–04。
88
+ * 只用来盖一层薄色罩;现有三张背景是画风变体,不按时段换图。
89
+ */
90
+ export function phaseAtHour(hour) {
91
+ const h = Number.isFinite(hour) ? ((Math.trunc(hour) % 24) + 24) % 24 : 0;
92
+ if (h >= 5 && h < 11) return 'morning';
93
+ if (h >= 11 && h < 17) return 'day';
94
+ if (h >= 17 && h < 20) return 'dusk';
95
+ return 'night';
96
+ }
97
+
98
+ /**
99
+ * 纪念品落到哪个固定位置:票根→书架、杯子→茶几、玩偶/挂件→沙发边、花草→窗台。
100
+ * 认不出的仍放书架(不丢、不摆到地板上)。
101
+ */
102
+ export function souvenirCategory(name) {
103
+ const text = String(name ?? '');
104
+ if (/(票根|门票|小票)/.test(text)) return 'ticket';
105
+ if (/杯/.test(text)) return 'cup';
106
+ if (/(玩偶|娃娃|公仔|挂件)/.test(text)) return 'doll';
107
+ if (/(野花|花束|植物|绿植|盆栽|一束)/.test(text)) return 'plant';
108
+ return 'shelf';
109
+ }
110
+
111
+ export class HomeRoomError extends Error {
112
+ constructor(code, message) {
113
+ super(message);
114
+ this.name = 'HomeRoomError';
115
+ this.code = code;
116
+ }
117
+ }
118
+
119
+ const fail = (code, message) => { throw new HomeRoomError(code, message); };
120
+ const isObject = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
121
+ const clone = (value) => JSON.parse(JSON.stringify(value));
122
+ const round3 = (value) => Math.round(value * 1000) / 1000;
123
+
124
+ export function blankRoom() {
125
+ return {
126
+ version: 2,
127
+ revision: 0,
128
+ room: { activity: 'idle', since: null, source: 'default', note: '', plan: '' },
129
+ art: { background: '', characters: {}, hotspots: [], foreground: '', painting: '' },
130
+ placements: {},
131
+ updatedAt: null,
132
+ };
133
+ }
134
+
135
+ function hotspotShape(item) {
136
+ return {
137
+ id: item.id,
138
+ x: item.x,
139
+ y: item.y,
140
+ label: item.label,
141
+ ...(item.note ? { note: item.note } : {}),
142
+ };
143
+ }
144
+
145
+ function placementShape(item) {
146
+ return { x: item.x, y: item.y, scale: item.scale };
147
+ }
148
+
149
+ function charactersOf(characters) {
150
+ const result = {};
151
+ for (const activity of ACTIVITIES) {
152
+ if (characters[activity]) result[activity] = characters[activity];
153
+ }
154
+ return result;
155
+ }
156
+
157
+ function placementsOf(placements) {
158
+ const result = {};
159
+ for (const activity of ACTIVITIES) {
160
+ if (placements[activity]) result[activity] = placementShape(placements[activity]);
161
+ }
162
+ return result;
163
+ }
164
+
165
+ /** 房间引用的全部图片 digest(去重、稳定顺序)。导出清单和快照缺图判断共用。 */
166
+ function refsOf(state) {
167
+ const refs = [state.art.background, ...Object.values(state.art.characters),
168
+ state.art.foreground, state.art.painting].filter(Boolean);
169
+ return [...new Set(refs)];
170
+ }
171
+
172
+ /** 从文件头认图片类型;认不出就交给 decodeCover 去拒。 */
173
+ function mimeOfBytes(bytes) {
174
+ if (bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'))) return 'image/png';
175
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
176
+ if (bytes.length >= 6 && ['GIF87a', 'GIF89a'].includes(bytes.toString('ascii', 0, 6))) return 'image/gif';
177
+ if (bytes.length >= 12 && bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP') return 'image/webp';
178
+ return '';
179
+ }
180
+
181
+ function roomOf(state) {
182
+ return {
183
+ activity: state.room.activity,
184
+ since: state.room.since,
185
+ source: state.room.source,
186
+ note: state.room.note,
187
+ // 空 plan 整条省略:老文件(没有这个键)读进来再写回去仍然合法、可比较。
188
+ ...(state.room.plan ? { plan: state.room.plan } : {}),
189
+ };
190
+ }
191
+
192
+ /** v2 的固定字段顺序:写盘和读盘对同一条记录必须逐字节一致,否则会被当成「被改过」。 */
193
+ function canonicalV2(state) {
194
+ return {
195
+ version: 2,
196
+ revision: state.revision,
197
+ room: roomOf(state),
198
+ art: {
199
+ background: state.art.background,
200
+ characters: charactersOf(state.art.characters),
201
+ hotspots: state.art.hotspots.map(hotspotShape),
202
+ foreground: state.art.foreground,
203
+ painting: state.art.painting,
204
+ },
205
+ placements: placementsOf(state.placements ?? {}),
206
+ updatedAt: state.updatedAt,
207
+ };
208
+ }
209
+
210
+ /** v1 的形状:没有 placements / foreground / painting,读旧文件时逐字节对得上。 */
211
+ function canonicalV1(state) {
212
+ return {
213
+ version: 1,
214
+ revision: state.revision,
215
+ room: roomOf(state),
216
+ art: {
217
+ background: state.art.background,
218
+ characters: charactersOf(state.art.characters),
219
+ hotspots: state.art.hotspots.map(hotspotShape),
220
+ },
221
+ updatedAt: state.updatedAt,
222
+ };
223
+ }
224
+
225
+ function cleanNote(value) {
226
+ if (value === undefined || value === null) return '';
227
+ if (typeof value !== 'string') fail('INVALID_ROOM', '房间备注必须是文字。');
228
+ const note = value.trim();
229
+ if (note.length > MAX_NOTE) fail('INVALID_ROOM', `房间备注最多 ${MAX_NOTE} 个字。`);
230
+ if (/[\u0000-\u001f\u007f]/u.test(note)) fail('INVALID_ROOM', '房间备注里不能有控制字符。');
231
+ return note;
232
+ }
233
+
234
+ /** 「今天想做什么」:≤60 字;空串表示不写这个键(老文件继续逐字节合法)。 */
235
+ function cleanPlan(value) {
236
+ if (value === undefined || value === null) return '';
237
+ if (typeof value !== 'string') fail('INVALID_ROOM', '「今天想做什么」必须是文字。');
238
+ const plan = value.trim();
239
+ if (plan.length > MAX_PLAN) fail('INVALID_ROOM', `「今天想做什么」最多 ${MAX_PLAN} 个字。`);
240
+ if (/[\u0000-\u001f\u007f]/u.test(plan)) fail('INVALID_ROOM', '「今天想做什么」里不能有控制字符。');
241
+ return plan;
242
+ }
243
+
244
+ function cleanActivity(value) {
245
+ if (!ACTIVITIES.includes(value)) fail('INVALID_ACTIVITY', '不认识这个活动。');
246
+ return value;
247
+ }
248
+
249
+ function cleanHotspots(value) {
250
+ if (!Array.isArray(value)) fail('INVALID_ROOM', '热点必须是一个列表。');
251
+ if (value.length > MAX_HOTSPOTS) fail('LIMIT', `热点最多 ${MAX_HOTSPOTS} 个。`);
252
+ const seen = new Set();
253
+ return value.map((item) => {
254
+ if (!isObject(item)) fail('INVALID_ROOM', '热点格式不对。');
255
+ const id = typeof item.id === 'string' ? item.id.trim() : '';
256
+ if (!HOTSPOT_ID.test(id) || seen.has(id)) fail('INVALID_ROOM', '热点 ID 只能是小写字母、数字和短横线,且不能重复。');
257
+ seen.add(id);
258
+ const x = Number(item.x);
259
+ const y = Number(item.y);
260
+ if (!Number.isFinite(x) || !Number.isFinite(y) || x < 0 || x > 1 || y < 0 || y > 1) {
261
+ fail('INVALID_ROOM', '热点的位置必须是 0 到 1 之间的小数。');
262
+ }
263
+ const label = typeof item.label === 'string' ? item.label.trim().slice(0, 24) : '';
264
+ const note = typeof item.note === 'string' ? item.note.trim().slice(0, MAX_HOTSPOT_NOTE) : '';
265
+ if (/[\u0000-\u001f\u007f]/u.test(note)) fail('INVALID_ROOM', '热点那句里不能有控制字符。');
266
+ return { id, x: round3(x), y: round3(y), label, ...(note ? { note } : {}) };
267
+ });
268
+ }
269
+
270
+ /** 位置微调:只接受十个活动键;只存提交上来的(UI 负责只提交改过的)。 */
271
+ function cleanPlacements(value) {
272
+ if (!isObject(value)) fail('INVALID_ROOM', '位置微调必须是一份对象。');
273
+ const result = {};
274
+ for (const [activity, placement] of Object.entries(value)) {
275
+ if (!ACTIVITIES.includes(activity)) fail('INVALID_ROOM', '位置微调里有不认识的活动。');
276
+ if (!isObject(placement)) fail('INVALID_ROOM', '位置微调格式不对。');
277
+ const x = Number(placement.x);
278
+ const y = Number(placement.y);
279
+ const scale = Number(placement.scale);
280
+ if (!Number.isFinite(x) || x < 0 || x > 1 || !Number.isFinite(y) || y < 0 || y > 1) {
281
+ fail('INVALID_ROOM', '位置微调的 x/y 必须是 0 到 1 之间的小数。');
282
+ }
283
+ if (!Number.isFinite(scale) || scale < MIN_SCALE || scale > MAX_SCALE) {
284
+ fail('INVALID_ROOM', `位置微调的缩放要在 ${MIN_SCALE} 到 ${MAX_SCALE} 之间。`);
285
+ }
286
+ result[activity] = { x: round3(x), y: round3(y), scale: round3(scale) };
287
+ }
288
+ return result;
289
+ }
290
+
291
+ function readState(raw) {
292
+ if (!isObject(raw)) fail('DAMAGED_ROOM', '房间档案不是一份 JSON 对象。');
293
+ if (raw.version !== 1 && raw.version !== 2) fail('DAMAGED_ROOM', '房间档案版本不认识。');
294
+ if (!isObject(raw.room) || !isObject(raw.art) || !isObject(raw.art.characters)
295
+ || !Array.isArray(raw.art.hotspots)) fail('DAMAGED_ROOM', '房间档案缺少字段。');
296
+ const version = raw.version;
297
+ const state = {
298
+ version: 2,
299
+ revision: raw.revision,
300
+ room: {
301
+ activity: raw.room.activity,
302
+ since: raw.room.since,
303
+ source: raw.room.source,
304
+ note: raw.room.note ?? '',
305
+ plan: raw.room.plan ?? '',
306
+ },
307
+ art: {
308
+ background: raw.art.background ?? '',
309
+ characters: raw.art.characters,
310
+ hotspots: cleanHotspots(raw.art.hotspots),
311
+ foreground: version === 2 ? raw.art.foreground ?? '' : '',
312
+ painting: version === 2 ? raw.art.painting ?? '' : '',
313
+ },
314
+ placements: version === 2 ? cleanPlacements(raw.placements ?? {}) : {},
315
+ updatedAt: raw.updatedAt ?? null,
316
+ };
317
+ const expected = version === 1 ? canonicalV1(state) : canonicalV2(state);
318
+ if (JSON.stringify(expected) !== JSON.stringify(raw)) fail('DAMAGED_ROOM', '房间档案损坏,已保留原文件。');
319
+
320
+ const okActivity = ACTIVITIES.includes(state.room.activity);
321
+ const okSince = state.room.since === null || (Number.isFinite(state.room.since) && state.room.since > 0);
322
+ const okRevision = Number.isSafeInteger(state.revision) && state.revision >= 0;
323
+ const okSource = SOURCES.has(state.room.source);
324
+ const okNote = typeof state.room.note === 'string' && state.room.note === state.room.note.trim()
325
+ && state.room.note.length <= MAX_NOTE && !/[\u0000-\u001f\u007f]/u.test(state.room.note);
326
+ const okPlan = typeof state.room.plan === 'string' && state.room.plan === state.room.plan.trim()
327
+ && state.room.plan.length <= MAX_PLAN && !/[\u0000-\u001f\u007f]/u.test(state.room.plan);
328
+ const okBackground = state.art.background === '' || REF.test(state.art.background);
329
+ const okForeground = state.art.foreground === '' || REF.test(state.art.foreground);
330
+ const okPainting = state.art.painting === '' || REF.test(state.art.painting);
331
+ const okCharacters = Object.entries(state.art.characters)
332
+ .every(([activity, ref]) => ACTIVITIES.includes(activity) && REF.test(ref));
333
+ const okUpdated = state.updatedAt === null || (Number.isFinite(state.updatedAt) && state.updatedAt > 0);
334
+ if (!okActivity || !okSince || !okRevision || !okSource || !okNote || !okPlan
335
+ || !okBackground || !okForeground || !okPainting || !okCharacters || !okUpdated) {
336
+ fail('DAMAGED_ROOM', '房间档案损坏,已保留原文件。');
337
+ }
338
+ return state;
339
+ }
340
+
341
+ async function readBounded(file) {
342
+ let entry;
343
+ try {
344
+ entry = await lstat(file);
345
+ } catch (error) {
346
+ if (error?.code === 'ENOENT') return null;
347
+ throw error;
348
+ }
349
+ if (!entry.isFile() || entry.size > MAX_ROOM_BYTES) fail('DAMAGED_ROOM', '房间档案无效或过大。');
350
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
351
+ try {
352
+ const bytes = Buffer.alloc(entry.size);
353
+ let offset = 0;
354
+ while (offset < bytes.length) {
355
+ const part = await handle.read(bytes, offset, bytes.length - offset, offset);
356
+ if (!part.bytesRead) fail('DAMAGED_ROOM', '房间档案在读取时被改动。');
357
+ offset += part.bytesRead;
358
+ }
359
+ return bytes.toString('utf8');
360
+ } finally {
361
+ await handle.close();
362
+ }
363
+ }
364
+
365
+ function snapshotRecord(raw) {
366
+ if (!isObject(raw)) fail('INVALID_ROOM', '快照不是一份 JSON 对象。');
367
+ if (raw.version !== 1) fail('INVALID_ROOM', '快照版本不认识。');
368
+ const at = Number(raw.at);
369
+ if (!Number.isFinite(at) || at <= 0) fail('INVALID_ROOM', '快照时间不对。');
370
+ if (!isObject(raw.room) || !isObject(raw.art) || !isObject(raw.art.characters)
371
+ || !Array.isArray(raw.art.hotspots) || !isObject(raw.placements) || !Array.isArray(raw.keepsakes)) {
372
+ fail('INVALID_ROOM', '快照缺少字段。');
373
+ }
374
+ return {
375
+ version: 1,
376
+ at,
377
+ phase: typeof raw.phase === 'string' ? raw.phase : 'day',
378
+ room: {
379
+ activity: ACTIVITIES.includes(raw.room.activity) ? raw.room.activity : 'idle',
380
+ label: typeof raw.room.label === 'string' ? raw.room.label : '',
381
+ note: typeof raw.room.note === 'string' ? raw.room.note : '',
382
+ plan: typeof raw.room.plan === 'string' ? raw.room.plan : '',
383
+ },
384
+ art: {
385
+ background: typeof raw.art.background === 'string' ? raw.art.background : '',
386
+ characters: isObject(raw.art.characters) ? { ...raw.art.characters } : {},
387
+ hotspots: cleanHotspots(raw.art.hotspots),
388
+ foreground: typeof raw.art.foreground === 'string' ? raw.art.foreground : '',
389
+ painting: typeof raw.art.painting === 'string' ? raw.art.painting : '',
390
+ },
391
+ placements: cleanPlacements(raw.placements),
392
+ keepsakes: raw.keepsakes.slice(0, 5).map((item) => ({
393
+ name: typeof item?.name === 'string' ? item.name.slice(0, 40) : '',
394
+ placeName: typeof item?.placeName === 'string' ? item.placeName.slice(0, 40) : '',
395
+ day: typeof item?.day === 'string' ? item.day.slice(0, 10) : '',
396
+ category: typeof item?.category === 'string' ? item.category.slice(0, 12) : 'shelf',
397
+ })),
398
+ };
399
+ }
400
+
401
+ async function atomicWrite(file, text) {
402
+ const tmp = `${file}.${randomUUID()}.tmp`;
403
+ let handle;
404
+ let created = false;
405
+ try {
406
+ handle = await open(tmp, 'wx', 0o600);
407
+ created = true;
408
+ await handle.writeFile(text, 'utf8');
409
+ await handle.sync();
410
+ await handle.close();
411
+ handle = null;
412
+ await rename(tmp, file);
413
+ } catch (error) {
414
+ await handle?.close().catch(() => {});
415
+ if (created) await unlink(tmp).catch(() => {});
416
+ throw error;
417
+ }
418
+ }
419
+
420
+ export class HomeRoom {
421
+ #dir;
422
+ #file;
423
+ #artDir;
424
+ #snapDir;
425
+ #now;
426
+ /** 内置 Q 版立绘的目录(随包走,不进用户数据目录)。 */
427
+ #builtinDir = new URL('../assets/home/', import.meta.url);
428
+ #builtinIds = null;
429
+
430
+ constructor({ dataDir, now = () => Date.now() } = {}) {
431
+ this.#dir = join(dataDir, 'fun', 'home');
432
+ this.#file = join(this.#dir, 'room.json');
433
+ this.#artDir = join(this.#dir, 'art');
434
+ this.#snapDir = join(this.#dir, 'snapshots');
435
+ this.#now = now;
436
+ }
437
+
438
+ roomFile() { return this.#file; }
439
+ artDir() { return this.#artDir; }
440
+ snapshotsDir() { return this.#snapDir; }
441
+
442
+ /** 内置 Q 版立绘有哪几个活动(目录只扫一次;没带素材就当没有)。 */
443
+ async builtinIds() {
444
+ if (this.#builtinIds) return this.#builtinIds;
445
+ let names = [];
446
+ try { names = await readdir(this.#builtinDir); } catch { /* 没带素材:走纯 CSS 房间 */ }
447
+ this.#builtinIds = ACTIVITIES.filter((id) => names.some((name) => name.startsWith(`chibi-${id}.`)));
448
+ return this.#builtinIds;
449
+ }
450
+
451
+ /** 一张内置立绘;这个活动没有就退回 idle,不编图。 */
452
+ async #builtinArt(activity) {
453
+ const ids = await this.builtinIds();
454
+ if (!ids.length) return null;
455
+ const id = ids.includes(activity) ? activity : (ids.includes('idle') ? 'idle' : ids[0]);
456
+ for (const ext of ['webp', 'png']) {
457
+ try {
458
+ const bytes = await readFile(new URL(`chibi-${id}.${ext}`, this.#builtinDir));
459
+ const mime = mimeOfBytes(bytes) || (ext === 'webp' ? 'image/webp' : 'image/png');
460
+ return { dataUrl: `data:${mime};base64,${bytes.toString('base64')}`, mime, bytes: bytes.length, builtin: id };
461
+ } catch (error) {
462
+ if (error?.code === 'ENOENT') continue;
463
+ throw error;
464
+ }
465
+ }
466
+ return null;
467
+ }
468
+
469
+ /** 读盘;缺失 = 全新的空房间,坏文件 = 只读模式(绝不拿空状态覆盖)。 */
470
+ async #load() {
471
+ let text;
472
+ try {
473
+ text = await readBounded(this.#file);
474
+ } catch (error) {
475
+ if (error instanceof HomeRoomError) return { state: blankRoom(), damaged: true, warning: error.message };
476
+ throw error;
477
+ }
478
+ if (text === null) return { state: blankRoom(), damaged: false, warning: '' };
479
+ try {
480
+ return { state: readState(JSON.parse(text)), damaged: false, warning: '' };
481
+ } catch {
482
+ return { state: blankRoom(), damaged: true, warning: '房间档案损坏,已保留原文件。' };
483
+ }
484
+ }
485
+
486
+ #public(state) {
487
+ const since = Number.isFinite(state.room.since) ? state.room.since : null;
488
+ const elapsedMinutes = since === null ? null : Math.max(0, Math.floor((this.#now() - since) / 60000));
489
+ return {
490
+ version: 2,
491
+ revision: state.revision,
492
+ room: {
493
+ activity: state.room.activity,
494
+ label: ACTIVITY_LABELS[state.room.activity],
495
+ hint: ACTIVITY_HINTS[state.room.activity],
496
+ since,
497
+ elapsedMinutes,
498
+ note: state.room.note,
499
+ plan: state.room.plan ?? '',
500
+ source: state.room.source,
501
+ },
502
+ art: {
503
+ background: state.art.background,
504
+ characters: { ...state.art.characters },
505
+ hotspots: state.art.hotspots.map((item) => ({ ...item })),
506
+ foreground: state.art.foreground,
507
+ painting: state.art.painting,
508
+ },
509
+ placements: placementsOf(state.placements ?? {}),
510
+ };
511
+ }
512
+
513
+ async snapshot() {
514
+ const { state, damaged, warning } = await this.#load();
515
+ const pub = this.#public(state);
516
+ pub.art.builtin = await this.builtinIds();
517
+ return { ...pub, damaged, warning };
518
+ }
519
+
520
+ /** 一张图的数据;没有这张就返回 null(缺图不是错误)。 */
521
+ async readArt(slot, activity) {
522
+ const { state } = await this.#load();
523
+ let ref = '';
524
+ if (slot === 'background') ref = state.art.background;
525
+ else if (slot === 'foreground') ref = state.art.foreground;
526
+ else if (slot === 'painting') ref = state.art.painting;
527
+ else if (slot === 'character') ref = state.art.characters[activity] ?? state.art.characters.idle ?? '';
528
+ else fail('INVALID_ROOM', '只支持背景、前景、画架和角色图。');
529
+ if (!ref) {
530
+ // 没传过角色图就用内置 Q 版立绘;其他槽位缺图就是缺图。
531
+ if (slot !== 'character') return null;
532
+ return await this.#builtinArt(activity);
533
+ }
534
+ const path = join(this.#artDir, ref);
535
+ let entry;
536
+ try {
537
+ entry = await lstat(path);
538
+ } catch (error) {
539
+ if (error?.code === 'ENOENT') return null;
540
+ throw error;
541
+ }
542
+ if (!entry.isFile() || entry.size > MAX_COVER_BYTES) fail('DAMAGED_ROOM', '这张图已经不可读了。');
543
+ const stored = storedCover(ref, await readFile(path));
544
+ return { dataUrl: stored.dataUrl, mime: stored.mime, bytes: stored.byteLength };
545
+ }
546
+
547
+ async #mutate(revision, mutate, { collect = true } = {}) {
548
+ const { state, damaged, warning } = await this.#load();
549
+ if (damaged) fail('DAMAGED_ROOM', warning || '房间档案损坏,已保留原文件;先修好它再改。');
550
+ if (revision !== state.revision) fail('STALE_ROOM', '房间刚刚被改过,刷新后再试。');
551
+ const draft = clone(state);
552
+ const images = mutate(draft) ?? [];
553
+ const next = canonicalV2({ ...draft, revision: state.revision + 1, updatedAt: this.#now() });
554
+ await this.#write(next, images);
555
+ if (collect) await this.#collect(next, state);
556
+ // canonical 会省略空 plan;内存里的状态仍要有这个字段,面板才知道「没有」。
557
+ return this.#public({ ...next, room: { ...next.room, plan: draft.room.plan ?? '' } });
558
+ }
559
+
560
+ async #write(state, images) {
561
+ await mkdir(this.#artDir, { recursive: true });
562
+ if (images.length) {
563
+ const entries = await readdir(this.#artDir, { withFileTypes: true });
564
+ const known = new Set(entries.filter((entry) => COVER_ID.test(entry.name)).map((entry) => entry.name));
565
+ const additions = [...new Map(images.map((image) => [image.cover, image])).values()]
566
+ .filter((image) => !known.has(image.cover));
567
+ let total = additions.reduce((sum, image) => sum + image.bytes.length, 0);
568
+ for (const entry of entries) {
569
+ if (!entry.isFile()) fail('DAMAGED_ROOM', '素材目录里有不认识的条目。');
570
+ total += (await lstat(join(this.#artDir, entry.name))).size;
571
+ }
572
+ if (known.size + additions.length > MAX_ART_FILES) fail('LIMIT', '房间素材数量到上限了。');
573
+ if (total > MAX_ART_BYTES) fail('LIMIT', '房间素材总量到上限了。');
574
+ for (const image of additions) {
575
+ const handle = await open(join(this.#artDir, image.cover), 'wx', 0o600);
576
+ try {
577
+ await handle.writeFile(image.bytes);
578
+ await handle.sync();
579
+ } finally {
580
+ await handle.close();
581
+ }
582
+ }
583
+ }
584
+ await atomicWrite(this.#file, JSON.stringify(state, null, 2));
585
+ }
586
+
587
+ /** 换图/清图之后把没人引用的旧文件删掉;只删素材目录里符合命名规则的文件。 */
588
+ async #collect(next, previous) {
589
+ const keep = new Set([
590
+ next.art.background, next.art.foreground, next.art.painting,
591
+ ...Object.values(next.art.characters),
592
+ ].filter(Boolean));
593
+ const before = new Set([
594
+ previous.art.background, previous.art.foreground, previous.art.painting,
595
+ ...Object.values(previous.art.characters),
596
+ ].filter(Boolean));
597
+ for (const ref of before) {
598
+ if (keep.has(ref) || !REF.test(ref)) continue;
599
+ await unlink(join(this.#artDir, ref)).catch(() => {});
600
+ }
601
+ }
602
+
603
+ async setActivity(activity, { note, since, revision } = {}) {
604
+ const id = cleanActivity(activity);
605
+ const nextNote = note === undefined ? undefined : cleanNote(note);
606
+ const at = Number.isFinite(since) && since > 0 ? since : this.#now();
607
+ const { state } = await this.#load();
608
+ const sameActivity = state.room.activity === id;
609
+ const sameNote = nextNote === undefined || state.room.note === nextNote;
610
+ if (sameActivity && sameNote && state.room.since !== null && state.room.source === 'panel') return this.#public(state);
611
+ return this.#mutate(revision, (draft) => {
612
+ draft.room.activity = id;
613
+ draft.room.since = sameActivity ? (draft.room.since ?? at) : at;
614
+ draft.room.source = 'panel';
615
+ if (nextNote !== undefined) draft.room.note = nextNote;
616
+ });
617
+ }
618
+
619
+ async setNote(note, revision) {
620
+ const text = cleanNote(note);
621
+ const { state } = await this.#load();
622
+ if (state.room.note === text) return this.#public(state);
623
+ return this.#mutate(revision, (draft) => { draft.room.note = text; });
624
+ }
625
+
626
+ /** 手写的「今天想做什么」:空串 = 清掉(文件里连这个键都不留)。 */
627
+ async setPlan(plan, revision) {
628
+ const text = cleanPlan(plan);
629
+ const { state } = await this.#load();
630
+ if (state.room.plan === text) return this.#public(state);
631
+ return this.#mutate(revision, (draft) => { draft.room.plan = text; });
632
+ }
633
+
634
+ async setBackground(dataUrl, revision) {
635
+ const image = decodeCover(dataUrl);
636
+ return this.#mutate(revision, (draft) => {
637
+ draft.art.background = image.cover;
638
+ return [image];
639
+ });
640
+ }
641
+
642
+ async clearBackground(revision) {
643
+ const { state } = await this.#load();
644
+ if (!state.art.background) return this.#public(state);
645
+ return this.#mutate(revision, (draft) => { draft.art.background = ''; });
646
+ }
647
+
648
+ async setForeground(dataUrl, revision) {
649
+ const image = decodeCover(dataUrl);
650
+ return this.#mutate(revision, (draft) => {
651
+ draft.art.foreground = image.cover;
652
+ return [image];
653
+ });
654
+ }
655
+
656
+ async clearForeground(revision) {
657
+ const { state } = await this.#load();
658
+ if (!state.art.foreground) return this.#public(state);
659
+ return this.#mutate(revision, (draft) => { draft.art.foreground = ''; });
660
+ }
661
+
662
+ /**
663
+ * 画架/相框:用户 `ctx.pickPath` 选的本地图片复制进 `art/`。
664
+ * 不调生图工作室,也不读它的库;只走自己的图片校验。
665
+ */
666
+ async attachPainting(path, revision) {
667
+ if (typeof path !== 'string' || !path.trim()) fail('INVALID_ROOM', '没有选中要挂的图片。');
668
+ let bytes;
669
+ try {
670
+ bytes = await readFile(path);
671
+ } catch {
672
+ fail('INVALID_COVER', '选中的图片读不出来。');
673
+ }
674
+ if (bytes.length > MAX_COVER_BYTES) fail('LIMIT', '这张图超过 8 MiB。');
675
+ const mime = mimeOfBytes(bytes);
676
+ if (!mime) fail('INVALID_COVER', '只支持 PNG / JPEG / GIF / WebP 图片。');
677
+ const image = decodeCover(`data:${mime};base64,${bytes.toString('base64')}`);
678
+ return this.#mutate(revision, (draft) => {
679
+ draft.art.painting = image.cover;
680
+ return [image];
681
+ });
682
+ }
683
+
684
+ async clearPainting(revision) {
685
+ const { state } = await this.#load();
686
+ if (!state.art.painting) return this.#public(state);
687
+ return this.#mutate(revision, (draft) => { draft.art.painting = ''; });
688
+ }
689
+
690
+ async setCharacter(activity, dataUrl, revision) {
691
+ const id = cleanActivity(activity);
692
+ const image = decodeCover(dataUrl);
693
+ return this.#mutate(revision, (draft) => {
694
+ draft.art.characters[id] = image.cover;
695
+ return [image];
696
+ });
697
+ }
698
+
699
+ async clearCharacter(activity, revision) {
700
+ const id = cleanActivity(activity);
701
+ const { state } = await this.#load();
702
+ if (!state.art.characters[id]) return this.#public(state);
703
+ return this.#mutate(revision, (draft) => { delete draft.art.characters[id]; });
704
+ }
705
+
706
+ async saveHotspots(hotspots, revision) {
707
+ const list = cleanHotspots(hotspots ?? []);
708
+ const { state } = await this.#load();
709
+ if (JSON.stringify(state.art.hotspots) === JSON.stringify(list)) return this.#public(state);
710
+ return this.#mutate(revision, (draft) => { draft.art.hotspots = list; });
711
+ }
712
+
713
+ async savePlacements(placements, revision) {
714
+ const list = cleanPlacements(placements ?? {});
715
+ const { state } = await this.#load();
716
+ if (JSON.stringify(placementsOf(state.placements)) === JSON.stringify(placementsOf(list))) return this.#public(state);
717
+ return this.#mutate(revision, (draft) => { draft.placements = list; });
718
+ }
719
+
720
+ /** 快照目录里的一条记录;图片只留 digest,不复制字节。 */
721
+ async listSnapshots() {
722
+ let entries;
723
+ try {
724
+ entries = await readdir(this.#snapDir, { withFileTypes: true });
725
+ } catch (error) {
726
+ if (error?.code === 'ENOENT') return { items: [] };
727
+ throw error;
728
+ }
729
+ const items = [];
730
+ for (const entry of entries) {
731
+ if (!entry.isFile() || !entry.name.endsWith('.json')) continue;
732
+ const id = entry.name.slice(0, -5);
733
+ if (!SNAPSHOT_ID.test(id)) continue;
734
+ let record;
735
+ try {
736
+ record = snapshotRecord(JSON.parse(await readFile(join(this.#snapDir, entry.name), 'utf8')));
737
+ } catch {
738
+ continue;
739
+ }
740
+ const missing = [];
741
+ for (const ref of refsOf({ art: { ...record.art, characters: record.art.characters } })) {
742
+ try {
743
+ const info = await lstat(join(this.#artDir, ref));
744
+ if (!info.isFile()) missing.push(ref);
745
+ } catch {
746
+ missing.push(ref);
747
+ }
748
+ }
749
+ items.push({
750
+ id,
751
+ at: record.at,
752
+ phase: record.phase,
753
+ activity: record.room.activity,
754
+ label: record.room.label,
755
+ note: record.room.note,
756
+ keepsakes: record.keepsakes,
757
+ missing: missing.length,
758
+ data: record,
759
+ });
760
+ }
761
+ items.sort((a, b) => Number(b.id) - Number(a.id));
762
+ return { items };
763
+ }
764
+
765
+ /** 存一张快照:图片按 digest 引用,不复制字节;不升 room 的 revision。 */
766
+ async saveSnapshot(payload = {}) {
767
+ const record = snapshotRecord({
768
+ version: 1,
769
+ at: this.#now(),
770
+ phase: payload.phase,
771
+ room: payload.room ?? {},
772
+ art: payload.art ?? {},
773
+ placements: payload.placements ?? {},
774
+ hotspots: payload.art?.hotspots ?? [],
775
+ keepsakes: payload.keepsakes ?? [],
776
+ });
777
+ let entries = [];
778
+ try {
779
+ entries = await readdir(this.#snapDir, { withFileTypes: true });
780
+ } catch (error) {
781
+ if (error?.code !== 'ENOENT') throw error;
782
+ }
783
+ if (entries.filter((entry) => entry.isFile() && entry.name.endsWith('.json')).length >= MAX_SNAPSHOTS) {
784
+ fail('LIMIT', `快照最多 ${MAX_SNAPSHOTS} 张,先删几张再存。`);
785
+ }
786
+ const taken = new Set(entries.map((entry) => entry.name.replace(/\.json$/, '')));
787
+ let id = String(record.at);
788
+ while (taken.has(id)) id = String(Number(id) + 1);
789
+ await mkdir(this.#snapDir, { recursive: true });
790
+ await atomicWrite(join(this.#snapDir, `${id}.json`), JSON.stringify(record, null, 2));
791
+ return { id, at: record.at };
792
+ }
793
+
794
+ async removeSnapshot(id) {
795
+ if (!SNAPSHOT_ID.test(String(id ?? ''))) fail('INVALID_ROOM', '快照 ID 不对。');
796
+ await unlink(join(this.#snapDir, `${id}.json`)).catch((error) => {
797
+ if (error?.code !== 'ENOENT') throw error;
798
+ });
799
+ }
800
+
801
+ /** 导出:room.json + 图片引用清单 + 快照索引,**不含任何图片字节**。 */
802
+ async exportRoom() {
803
+ const { state, damaged, warning } = await this.#load();
804
+ if (damaged) fail('DAMAGED_ROOM', warning || '房间档案损坏,不能导出。');
805
+ const snapshots = await this.listSnapshots();
806
+ return {
807
+ format: 1,
808
+ exportedAt: this.#now(),
809
+ room: canonicalV2(state),
810
+ artRefs: refsOf(state),
811
+ snapshots: snapshots.items.map(({ id, data }) => ({ id, data })),
812
+ };
813
+ }
814
+
815
+ #isEmptyRoom(state, snapshots) {
816
+ return state.revision === 0 && refsOf(state).length === 0
817
+ && state.art.hotspots.length === 0 && Object.keys(state.placements).length === 0
818
+ && !state.room.note && !state.room.plan && snapshots.items.length === 0;
819
+ }
820
+
821
+ /**
822
+ * 导入:**只在空房间**允许。图片逐张校验;先写快照、最后写 room.json,
823
+ * 任何一步失败都把新建的文件删掉,原房间保持“没有”。
824
+ */
825
+ async importRoom(payload) {
826
+ const { state: current, damaged, warning } = await this.#load();
827
+ if (damaged) fail('DAMAGED_ROOM', warning || '房间档案损坏,不能导入。');
828
+ const existing = await this.listSnapshots();
829
+ if (!this.#isEmptyRoom(current, existing)) fail('INVALID_ROOM', '只有空房间能导入备份;先恢复默认或清空房间。');
830
+ if (!isObject(payload) || !isObject(payload.room)) fail('INVALID_ROOM', '备份里没有房间数据。');
831
+ const imported = readState(payload.room);
832
+ const refs = refsOf(imported);
833
+ const declared = Array.isArray(payload.artRefs) ? payload.artRefs : null;
834
+ if (!declared || declared.length !== refs.length
835
+ || JSON.stringify([...declared].sort()) !== JSON.stringify([...refs].sort())) {
836
+ fail('INVALID_ROOM', '图片引用清单和房间数据对不上。');
837
+ }
838
+ for (const ref of refs) {
839
+ let bytes;
840
+ try {
841
+ const info = await lstat(join(this.#artDir, ref));
842
+ if (!info.isFile() || info.size > MAX_COVER_BYTES) throw new Error('bad');
843
+ bytes = await readFile(join(this.#artDir, ref));
844
+ storedCover(ref, bytes);
845
+ } catch {
846
+ fail('INVALID_ROOM', `备份里的图片缺失或已损坏:${ref}`);
847
+ }
848
+ }
849
+ const snapshots = Array.isArray(payload.snapshots) ? payload.snapshots : [];
850
+ const cleanSnapshots = [];
851
+ for (const entry of snapshots) {
852
+ const id = String(entry?.id ?? '');
853
+ if (!SNAPSHOT_ID.test(id)) fail('INVALID_ROOM', '备份里的快照 ID 不对。');
854
+ const data = snapshotRecord(entry?.data);
855
+ for (const ref of refsOf(data)) {
856
+ let ok = false;
857
+ try {
858
+ ok = (await lstat(join(this.#artDir, ref))).isFile();
859
+ } catch {
860
+ ok = false;
861
+ }
862
+ if (!ok) fail('INVALID_ROOM', `快照引用的图片不在了:${ref}`);
863
+ }
864
+ cleanSnapshots.push({ id, data });
865
+ }
866
+ await mkdir(this.#snapDir, { recursive: true });
867
+ const created = [];
868
+ try {
869
+ for (const { id, data } of cleanSnapshots) {
870
+ await atomicWrite(join(this.#snapDir, `${id}.json`), JSON.stringify(data, null, 2));
871
+ created.push(id);
872
+ }
873
+ await atomicWrite(this.#file, JSON.stringify(canonicalV2({
874
+ ...imported, revision: 0, updatedAt: this.#now(),
875
+ }), null, 2));
876
+ } catch (error) {
877
+ for (const id of created) await unlink(join(this.#snapDir, `${id}.json`)).catch(() => {});
878
+ await unlink(this.#file).catch(() => {});
879
+ throw error;
880
+ }
881
+ return this.#public({ ...imported, revision: 0, updatedAt: this.#now() });
882
+ }
883
+
884
+ /** 恢复默认:活动回「随时段变」、清备注/热点/位置;**图片保留**(素材不是状态)。 */
885
+ async resetRoom(revision) {
886
+ return this.#mutate(revision, (draft) => {
887
+ draft.room.activity = 'idle';
888
+ draft.room.since = this.#now();
889
+ draft.room.source = 'default';
890
+ draft.room.note = '';
891
+ draft.art.hotspots = [];
892
+ draft.placements = {};
893
+ }, { collect: false });
894
+ }
895
+ }