dsh-ccx 0.8.9 → 0.9.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 (49) hide show
  1. package/LICENSE +21 -21
  2. package/NOTICE +23 -23
  3. package/README.md +151 -143
  4. package/assets/icon.svg +27 -27
  5. package/cordis.patch.yml +16 -16
  6. package/lib/client.js +1481 -2244
  7. package/lib/index.js +716 -449
  8. package/lib/vendor/code-codex/ascii-tiles.js +145 -0
  9. package/lib/vendor/code-codex/aurora-ionosphere.js +7 -6
  10. package/lib/vendor/code-codex/black-hole.js +10 -7
  11. package/lib/vendor/code-codex/blinking-squares.js +6 -13
  12. package/lib/vendor/code-codex/cloud-train.js +9 -8
  13. package/lib/vendor/code-codex/galleries.json +100 -100
  14. package/lib/vendor/code-codex/glow-horizon.js +1 -1
  15. package/lib/vendor/code-codex/heavenly-cloud.js +5 -4
  16. package/lib/vendor/code-codex/milky-way.js +3 -2
  17. package/lib/vendor/code-codex/mountain.js +5 -4
  18. package/lib/vendor/code-codex/particle-image.js +435 -14
  19. package/lib/vendor/code-codex/pixel-sculpt.js +85 -5
  20. package/lib/vendor/code-codex/scene-defaults.json +94 -1
  21. package/lib/vendor/code-codex/scene-schemas.json +1008 -0
  22. package/lib/vendor/code-codex/shallow-ocean-thumbnails.json +12 -0
  23. package/lib/vendor/code-codex/shallow-ocean.js +5094 -0
  24. package/lib/vendor/code-codex/spectral-drape.js +172 -0
  25. package/package.json +70 -59
  26. package/src/client/api.ts +90 -0
  27. package/src/client/background/layer.ts +187 -0
  28. package/src/client/background/pixel-sculpt.ts +167 -0
  29. package/src/client/background/scene-runner.ts +317 -0
  30. package/src/client/background/shallow-ocean.ts +344 -0
  31. package/src/client/background/vendor-loader.ts +297 -0
  32. package/src/client/background/wallpaper.ts +87 -0
  33. package/src/client/index.ts +247 -0
  34. package/src/client/surfaces/corner-patch.ts +100 -0
  35. package/src/client/surfaces/surface-css.ts +155 -0
  36. package/src/client/ui/draft.ts +105 -0
  37. package/src/client/ui/icons.ts +47 -0
  38. package/src/client/ui/panel.ts +1524 -0
  39. package/src/client/ui/shallow-ocean-panel.ts +376 -0
  40. package/src/client/ui/styles.ts +1471 -0
  41. package/src/host/fence.ts +78 -0
  42. package/src/host/index.ts +26 -0
  43. package/src/host/routes.ts +367 -0
  44. package/src/host/storage.ts +109 -0
  45. package/src/host/window-chrome.ts +53 -0
  46. package/src/shared/constants.ts +239 -0
  47. package/src/shared/sanitize.ts +110 -0
  48. package/src/shared/types.ts +145 -0
  49. package/tsconfig.json +16 -0
@@ -0,0 +1,344 @@
1
+ import { SHALLOW_OCEAN_EVENTS } from '../../shared/constants';
2
+ import type { OceanEventJournalState, SceneParamMap, VendorRendererInstance } from '../../shared/types';
3
+ import { ensureVendorScene } from './vendor-loader';
4
+
5
+ export const SHALLOW_OCEAN_JOURNAL_KEY = 'code-codex:shallow-ocean-events:v1';
6
+ const EVENT_IDS: string[] = SHALLOW_OCEAN_EVENTS.map((e) => e[0]);
7
+
8
+ export function normalizeEventJournal(input: unknown): OceanEventJournalState {
9
+ const value = input && typeof input === 'object' ? (input as Record<string, unknown>) : {};
10
+ const known = (v: unknown): string[] =>
11
+ EVENT_IDS.filter((id) => Array.isArray(v) && v.includes(id));
12
+ const discovered = known(value.discovered);
13
+ return {
14
+ discovered,
15
+ excluded: discovered.length === EVENT_IDS.length ? known(value.excluded) : [],
16
+ };
17
+ }
18
+
19
+ export class OceanEventJournal {
20
+ private current: OceanEventJournalState;
21
+ private listeners = new Set<() => void>();
22
+
23
+ constructor() {
24
+ try {
25
+ const raw = localStorage.getItem(SHALLOW_OCEAN_JOURNAL_KEY) ?? '{}';
26
+ this.current = normalizeEventJournal(JSON.parse(raw));
27
+ } catch {
28
+ this.current = normalizeEventJournal(null);
29
+ }
30
+ }
31
+
32
+ get state(): OceanEventJournalState {
33
+ return {
34
+ discovered: [...this.current.discovered],
35
+ excluded: [...this.current.excluded],
36
+ };
37
+ }
38
+
39
+ get included(): string[] {
40
+ return EVENT_IDS.filter((id) => !this.current.excluded.includes(id));
41
+ }
42
+
43
+ subscribe(listener: () => void): () => void {
44
+ this.listeners.add(listener);
45
+ return () => {
46
+ this.listeners.delete(listener);
47
+ };
48
+ }
49
+
50
+ discover(id: string): void {
51
+ if (!EVENT_IDS.includes(id) || this.current.discovered.includes(id)) return;
52
+ this.commit({
53
+ ...this.current,
54
+ discovered: [...this.current.discovered, id],
55
+ });
56
+ }
57
+
58
+ toggle(id: string): void {
59
+ if (this.current.discovered.length !== EVENT_IDS.length || !EVENT_IDS.includes(id)) return;
60
+ const excluded = this.current.excluded.includes(id)
61
+ ? this.current.excluded.filter((item) => item !== id)
62
+ : [...this.current.excluded, id];
63
+ this.commit({ ...this.current, excluded });
64
+ }
65
+
66
+ private commit(next: OceanEventJournalState): void {
67
+ const normalized = normalizeEventJournal(next);
68
+ try {
69
+ localStorage.setItem(SHALLOW_OCEAN_JOURNAL_KEY, JSON.stringify(normalized));
70
+ } catch {
71
+ // Continue with in-memory journal even if storage quota is blocked
72
+ }
73
+ this.current = normalized;
74
+ for (const listener of this.listeners) {
75
+ try {
76
+ listener();
77
+ } catch {
78
+ // Ignore subscriber failures
79
+ }
80
+ }
81
+ }
82
+ }
83
+
84
+ interface ShallowOceanRendererInstance extends VendorRendererInstance {
85
+ addCreature?: (kind: string, u?: number, v?: number) => Promise<void> | void;
86
+ previewEvent?: (kind: string) => void;
87
+ action?: (act: string) => void;
88
+ diagnostics?: {
89
+ parameters?: Record<string, number>;
90
+ } | null;
91
+ }
92
+
93
+ type ShallowOceanCtor = new (
94
+ target: HTMLElement,
95
+ canvas: HTMLCanvasElement,
96
+ settings: SceneParamMap,
97
+ onError: (msg: string) => void,
98
+ interactive: boolean,
99
+ eventHooks: {
100
+ included: () => string[];
101
+ started: (id: string) => void;
102
+ },
103
+ ) => ShallowOceanRendererInstance;
104
+
105
+ export interface OceanCreatureSyncPayload {
106
+ silverCount: number;
107
+ reefCount: number;
108
+ clownCount: number;
109
+ sharkCount: number;
110
+ turtleCount: number;
111
+ defaultCreaturesEnabled: number;
112
+ }
113
+
114
+ export class ShallowOceanController {
115
+ readonly journal = new OceanEventJournal();
116
+ private devMode = false;
117
+ private populationGeneration = 0;
118
+ private populationQueue: Promise<void> = Promise.resolve();
119
+ private renderer: ShallowOceanRendererInstance | null = null;
120
+ private currentSettings: SceneParamMap = {};
121
+ private listeners = new Set<() => void>();
122
+ private syncCallback: ((patch: Partial<OceanCreatureSyncPayload>) => void) | null = null;
123
+
124
+ get developerMode(): boolean {
125
+ return this.devMode;
126
+ }
127
+
128
+ get hasRenderer(): boolean {
129
+ return this.renderer !== null;
130
+ }
131
+
132
+ get eventJournal(): OceanEventJournalState {
133
+ return this.journal.state;
134
+ }
135
+
136
+ setSyncCallback(cb: ((patch: Partial<OceanCreatureSyncPayload>) => void) | null): void {
137
+ this.syncCallback = cb;
138
+ }
139
+
140
+ subscribe(listener: () => void): () => void {
141
+ this.listeners.add(listener);
142
+ const unsubJournal = this.journal.subscribe(listener);
143
+ return () => {
144
+ this.listeners.delete(listener);
145
+ unsubJournal();
146
+ };
147
+ }
148
+
149
+ private notify(): void {
150
+ for (const listener of this.listeners) {
151
+ try {
152
+ listener();
153
+ } catch {
154
+ // Ignore subscriber failures
155
+ }
156
+ }
157
+ }
158
+
159
+ setDeveloperMode(enabled: boolean): void {
160
+ if (this.devMode === enabled) return;
161
+ this.devMode = enabled;
162
+ this.applyEffectiveSettings();
163
+ this.notify();
164
+ }
165
+
166
+ toggleEvent(id: string): void {
167
+ this.journal.toggle(id);
168
+ }
169
+
170
+ private effectiveSettings(settings: SceneParamMap): SceneParamMap {
171
+ return this.devMode ? { ...settings, eventsEnabled: 0 } : { ...settings };
172
+ }
173
+
174
+ private applyEffectiveSettings(): void {
175
+ try {
176
+ this.renderer?.setSettings?.(this.effectiveSettings(this.currentSettings));
177
+ } catch {
178
+ // Ignore renderer errors on settings push
179
+ }
180
+ }
181
+
182
+ async mount(
183
+ stage: HTMLDivElement,
184
+ initialSettings: SceneParamMap,
185
+ onStatus: (msg?: string) => void,
186
+ isStillCurrent: () => boolean,
187
+ ): Promise<VendorRendererInstance> {
188
+ this.currentSettings = { ...initialSettings };
189
+ const entry = await ensureVendorScene('shallow-ocean');
190
+ if (!isStillCurrent()) {
191
+ throw new Error('stale mount');
192
+ }
193
+
194
+ const Ctor = entry.exports?.ShallowOceanRenderer as ShallowOceanCtor | undefined;
195
+ if (typeof Ctor !== 'function') {
196
+ // Fallback to generic startup if named constructor is absent
197
+ const inst = entry.startup(stage, onStatus);
198
+ this.renderer = inst as ShallowOceanRendererInstance;
199
+ this.notify();
200
+ return inst;
201
+ }
202
+
203
+ stage.setAttribute('data-code-codex-shallow-ocean-layer', 'true');
204
+ const canvas = document.createElement('canvas');
205
+ canvas.className = 'code-codex-particle-canvas code-codex-shallow-ocean-canvas';
206
+ canvas.style.cssText = 'width:100%;height:100%;display:block;';
207
+ stage.appendChild(canvas);
208
+
209
+ const inst = new Ctor(
210
+ stage,
211
+ canvas,
212
+ this.effectiveSettings(this.currentSettings),
213
+ onStatus,
214
+ true,
215
+ {
216
+ included: () => this.journal.included,
217
+ started: (id: string) => {
218
+ if (this.devMode) return;
219
+ this.journal.discover(id);
220
+ },
221
+ },
222
+ );
223
+ this.renderer = inst;
224
+ this.notify();
225
+
226
+ return {
227
+ ready: inst.ready,
228
+ setSettings: (next: Record<string, unknown>) => {
229
+ this.currentSettings = { ...(next as SceneParamMap) };
230
+ this.applyEffectiveSettings();
231
+ },
232
+ replay: () => {
233
+ inst.replay?.();
234
+ },
235
+ dispose: () => {
236
+ this.populationGeneration++;
237
+ if (this.renderer === inst) {
238
+ this.renderer = null;
239
+ }
240
+ try {
241
+ inst.dispose?.();
242
+ } catch {
243
+ // Ignore
244
+ }
245
+ this.notify();
246
+ },
247
+ };
248
+ }
249
+
250
+ addCreature(kind: string, u = 0.5, v = 0.5): Promise<void> {
251
+ const generation = this.populationGeneration;
252
+ const op = this.populationQueue
253
+ .catch(() => {})
254
+ .then(async () => {
255
+ if (generation !== this.populationGeneration) return;
256
+ const inst = this.renderer;
257
+ if (!inst || typeof inst.addCreature !== 'function') {
258
+ throw new Error('请先启用“浅海字迹”背景后再投放生物');
259
+ }
260
+ await inst.addCreature(kind, u, v);
261
+ if (generation !== this.populationGeneration || inst !== this.renderer) return;
262
+ const params = inst.diagnostics?.parameters;
263
+ if (params && this.syncCallback) {
264
+ const patch: Partial<OceanCreatureSyncPayload> = {};
265
+ const keys: Array<keyof OceanCreatureSyncPayload> = [
266
+ 'silverCount',
267
+ 'reefCount',
268
+ 'clownCount',
269
+ 'sharkCount',
270
+ 'turtleCount',
271
+ 'defaultCreaturesEnabled',
272
+ ];
273
+ for (const k of keys) {
274
+ const val = Number(params[k]);
275
+ if (Number.isFinite(val)) patch[k] = val;
276
+ }
277
+ this.syncCallback(patch);
278
+ }
279
+ });
280
+ this.populationQueue = op;
281
+ return op;
282
+ }
283
+
284
+ clearCreatures(): void {
285
+ this.populationGeneration++;
286
+ try {
287
+ this.renderer?.action?.('clear');
288
+ } catch {
289
+ // Ignore
290
+ }
291
+ this.syncCallback?.({
292
+ defaultCreaturesEnabled: 0,
293
+ silverCount: 0,
294
+ reefCount: 0,
295
+ clownCount: 0,
296
+ sharkCount: 0,
297
+ turtleCount: 0,
298
+ });
299
+ }
300
+
301
+ resetPopulation(): void {
302
+ this.populationGeneration++;
303
+ try {
304
+ this.renderer?.action?.('reset-population');
305
+ } catch {
306
+ // Ignore
307
+ }
308
+ }
309
+
310
+ previewEvent(kind: string): void {
311
+ if (!this.renderer || typeof this.renderer.previewEvent !== 'function') {
312
+ throw new Error('请先启用“浅海字迹”背景后再预览事件');
313
+ }
314
+ this.renderer.previewEvent(kind);
315
+ }
316
+
317
+ action(act: string): void {
318
+ this.renderer?.action?.(act);
319
+ }
320
+
321
+ dispose(): void {
322
+ this.populationGeneration++;
323
+ this.devMode = false;
324
+ this.renderer = null;
325
+ this.syncCallback = null;
326
+ this.listeners.clear();
327
+ }
328
+ }
329
+
330
+ let sharedOceanController: ShallowOceanController | null = null;
331
+
332
+ export function getShallowOceanController(): ShallowOceanController {
333
+ if (!sharedOceanController) {
334
+ sharedOceanController = new ShallowOceanController();
335
+ }
336
+ return sharedOceanController;
337
+ }
338
+
339
+ export function disposeShallowOceanController(): void {
340
+ if (sharedOceanController) {
341
+ sharedOceanController.dispose();
342
+ sharedOceanController = null;
343
+ }
344
+ }
@@ -0,0 +1,297 @@
1
+ import { API_BASE, STORE_KEYS } from '../../shared/constants';
2
+ import type { VendorModuleEntry } from '../../shared/types';
3
+ import { apiGet } from '../api';
4
+
5
+ const REGISTRY_SYM = Symbol.for('code-codex:background-modules:v1');
6
+ const GALLERIES_SYM = Symbol.for('code-codex:default-galleries:v1');
7
+
8
+ interface GalleryMetaImage {
9
+ id: string;
10
+ name: string;
11
+ type: string;
12
+ size: number;
13
+ sha256: string;
14
+ createdAt?: number;
15
+ dataFile: string;
16
+ thumbFile?: string;
17
+ }
18
+
19
+ interface GalleryMeta {
20
+ count: number;
21
+ version: number;
22
+ images: GalleryMetaImage[];
23
+ }
24
+
25
+ interface SeededGalleryEntry {
26
+ id: string;
27
+ name: string;
28
+ type: string;
29
+ size: number;
30
+ sha256: string;
31
+ data: string;
32
+ thumbnail?: string;
33
+ createdAt: number;
34
+ }
35
+
36
+ const vendorScriptTags = new Map<string, HTMLScriptElement>();
37
+ const vendorLoadPromises = new Map<string, Promise<VendorModuleEntry>>();
38
+ const galleryPromises = new Map<string, Promise<boolean>>();
39
+
40
+ export function registry(): Map<string, VendorModuleEntry> | null {
41
+ const reg = (window as unknown as Record<symbol, unknown>)[REGISTRY_SYM];
42
+ return reg instanceof Map ? (reg as Map<string, VendorModuleEntry>) : null;
43
+ }
44
+
45
+ function bufferToBase64(buf: ArrayBuffer): string {
46
+ const bytes = new Uint8Array(buf);
47
+ const parts: string[] = [];
48
+ const chunk = 0x8000;
49
+ for (let i = 0; i < bytes.length; i += chunk) {
50
+ parts.push(String.fromCharCode(...bytes.subarray(i, i + chunk)));
51
+ }
52
+ return btoa(parts.join(''));
53
+ }
54
+
55
+ async function fetchMediaBase64(file: string): Promise<string> {
56
+ const resp = await fetch(`${API_BASE}/vendor-media?file=${encodeURIComponent(file)}`, {
57
+ credentials: 'omit',
58
+ });
59
+ if (!resp.ok) throw new Error(`media HTTP ${resp.status}`);
60
+ return bufferToBase64(await resp.arrayBuffer());
61
+ }
62
+
63
+ /**
64
+ * Lazy-load a vendor background module bundle and resolve its registered entry.
65
+ */
66
+ export function ensureVendorScene(id: string): Promise<VendorModuleEntry> {
67
+ const existing = registry()?.get(id);
68
+ if (existing) return Promise.resolve(existing);
69
+
70
+ const inflight = vendorLoadPromises.get(id);
71
+ if (inflight) return inflight;
72
+
73
+ const promise = new Promise<VendorModuleEntry>((resolve, reject) => {
74
+ let settled = false;
75
+ let timer: ReturnType<typeof setInterval> | null = null;
76
+ let waits = 0;
77
+
78
+ const cleanup = () => {
79
+ if (timer) {
80
+ clearInterval(timer);
81
+ timer = null;
82
+ }
83
+ };
84
+
85
+ const succeed = (entry: VendorModuleEntry) => {
86
+ if (settled) return;
87
+ settled = true;
88
+ cleanup();
89
+ resolve(entry);
90
+ };
91
+
92
+ const fail = (err: Error) => {
93
+ if (settled) return;
94
+ settled = true;
95
+ cleanup();
96
+ vendorLoadPromises.delete(id);
97
+ vendorScriptTags.delete(id);
98
+ reject(err);
99
+ };
100
+
101
+ const checkRegistry = (): boolean => {
102
+ const entry = registry()?.get(id);
103
+ if (entry) {
104
+ succeed(entry);
105
+ return true;
106
+ }
107
+ return false;
108
+ };
109
+
110
+ let tag = vendorScriptTags.get(id);
111
+ if (!tag) {
112
+ tag = document.createElement('script');
113
+ tag.src = `${API_BASE}/vendor/${encodeURIComponent(id)}.js`;
114
+ tag.onload = () => {
115
+ if (!checkRegistry()) {
116
+ // Allow a brief tick for synchronous registration after script execution
117
+ setTimeout(() => {
118
+ if (!settled && !checkRegistry()) {
119
+ fail(new Error(`vendor registry missing after load: ${id}`));
120
+ }
121
+ }, 120);
122
+ }
123
+ };
124
+ tag.onerror = () => {
125
+ fail(new Error(`vendor script load failed: ${id}`));
126
+ };
127
+ vendorScriptTags.set(id, tag);
128
+ (document.head || document.documentElement).appendChild(tag);
129
+ }
130
+
131
+ timer = setInterval(() => {
132
+ if (checkRegistry()) return;
133
+ if (++waits > 150) {
134
+ fail(new Error(`registry timeout: ${id}`));
135
+ }
136
+ }, 60);
137
+ });
138
+
139
+ vendorLoadPromises.set(id, promise);
140
+ return promise;
141
+ }
142
+
143
+ /**
144
+ * Seed default media galleries into window[Symbol.for("code-codex:default-galleries:v1")]
145
+ * for gallery-backed renderers (particle-image / pixel-sculpt).
146
+ */
147
+ export function ensureGallery(id: string): Promise<boolean> {
148
+ const cached = galleryPromises.get(id);
149
+ if (cached) return cached;
150
+
151
+ const promise = (async () => {
152
+ const index = await apiGet<Record<string, GalleryMeta>>('/vendor-galleries.json');
153
+ const meta = index?.[id];
154
+ if (!meta) throw new Error(`gallery index missing: ${id}`);
155
+
156
+ const entries = await Promise.all(
157
+ meta.images.map(async (img): Promise<SeededGalleryEntry> => {
158
+ const data = await fetchMediaBase64(img.dataFile);
159
+ const entry: SeededGalleryEntry = {
160
+ id: img.id,
161
+ name: img.name,
162
+ type: img.type,
163
+ size: img.size,
164
+ sha256: img.sha256,
165
+ data,
166
+ createdAt: img.createdAt || 0,
167
+ };
168
+ if (img.thumbFile) {
169
+ entry.thumbnail = await fetchMediaBase64(img.thumbFile);
170
+ }
171
+ return entry;
172
+ }),
173
+ );
174
+
175
+ const images = new Map<string, SeededGalleryEntry>();
176
+ for (const item of entries) {
177
+ images.set(item.id, item);
178
+ }
179
+
180
+ const win = window as unknown as Record<symbol, Map<string, unknown> | undefined>;
181
+ const reg = (win[GALLERIES_SYM] = win[GALLERIES_SYM] || new Map<string, unknown>());
182
+ reg.set(id, { count: meta.count, version: meta.version, images });
183
+ return true;
184
+ })().catch((err) => {
185
+ galleryPromises.delete(id);
186
+ throw err;
187
+ });
188
+
189
+ galleryPromises.set(id, promise);
190
+ return promise;
191
+ }
192
+
193
+ function looksSelected(storeObj: Record<string, unknown> | null): boolean {
194
+ if (!storeObj) return false;
195
+ const ids = storeObj.selectedImageIds;
196
+ return Boolean((Array.isArray(ids) && ids.length > 0) || storeObj.activeImageId);
197
+ }
198
+
199
+ /**
200
+ * Idempotently restore selectedImageIds/activeImageId for particle-image if IndexedDB
201
+ * already contains images while localStorage selection keys are empty.
202
+ */
203
+ export function ensureGallerySelection(id: string): Promise<null> {
204
+ if (id !== 'particle-image') return Promise.resolve(null);
205
+ const key = STORE_KEYS[id];
206
+ if (!key) return Promise.resolve(null);
207
+
208
+ return new Promise<null>((resolve) => {
209
+ let done = false;
210
+ const finish = () => {
211
+ if (!done) {
212
+ done = true;
213
+ resolve(null);
214
+ }
215
+ };
216
+
217
+ try {
218
+ const raw = localStorage.getItem(key);
219
+ if (raw && looksSelected(JSON.parse(raw))) {
220
+ finish();
221
+ return;
222
+ }
223
+ } catch {
224
+ // Continue to IndexedDB fallback
225
+ }
226
+
227
+ try {
228
+ const req = indexedDB.open('code-codex-particle-image-background');
229
+ req.onupgradeneeded = () => {
230
+ try {
231
+ req.transaction?.abort();
232
+ } catch {
233
+ // Ignore abort errors
234
+ }
235
+ finish();
236
+ };
237
+ req.onsuccess = () => {
238
+ const db = req.result;
239
+ let settled = false;
240
+ const closeDb = () => {
241
+ try {
242
+ db.close();
243
+ } catch {
244
+ // Ignore
245
+ }
246
+ };
247
+ try {
248
+ const rq = db.transaction('images', 'readonly').objectStore('images').getAll();
249
+ rq.onsuccess = () => {
250
+ closeDb();
251
+ if (settled) return;
252
+ settled = true;
253
+ const rows = ((rq.result as Array<Record<string, unknown>>) || []).filter(
254
+ (r) => r && r.id !== '__codeCodex_default_media_v1__' && (r.blob || r.file),
255
+ );
256
+ if (!rows.length) {
257
+ finish();
258
+ return;
259
+ }
260
+ rows.sort((a, b) => Number(a.createdAt || 0) - Number(b.createdAt || 0));
261
+ let cur: Record<string, unknown> = {};
262
+ try {
263
+ cur = JSON.parse(localStorage.getItem(key) || '{}') || {};
264
+ } catch {
265
+ cur = {};
266
+ }
267
+ if (!looksSelected(cur)) {
268
+ cur.selectedImageIds = rows.map((r) => r.id);
269
+ cur.activeImageId = rows[0].id;
270
+ try {
271
+ localStorage.setItem(key, JSON.stringify(cur));
272
+ } catch {
273
+ // Ignore quota/storage errors
274
+ }
275
+ }
276
+ finish();
277
+ };
278
+ rq.onerror = () => {
279
+ closeDb();
280
+ if (!settled) {
281
+ settled = true;
282
+ finish();
283
+ }
284
+ };
285
+ } catch {
286
+ closeDb();
287
+ finish();
288
+ }
289
+ };
290
+ req.onerror = finish;
291
+ req.onblocked = finish;
292
+ setTimeout(finish, 3000);
293
+ } catch {
294
+ finish();
295
+ }
296
+ });
297
+ }