diff --git a/packages/storage/package.json b/packages/storage/package.json new file mode 100644 index 0000000..099dcc9 --- /dev/null +++ b/packages/storage/package.json @@ -0,0 +1,26 @@ +{ + "name": "@rosea/storage", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Dexie. The ONLY module that touches IndexedDB (CLAUDE.md §2, §4).", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "typecheck": "tsc -p tsconfig.json", + "test": "vitest run --reporter=verbose" + }, + "dependencies": { + "@rosea/engine": "workspace:*", + "dexie": "4.4.6" + }, + "devDependencies": { + "fake-indexeddb": "6.2.5", + "typescript": "5.9.3", + "vitest": "3.2.7" + } +} diff --git a/packages/storage/src/index.ts b/packages/storage/src/index.ts new file mode 100644 index 0000000..2760d02 --- /dev/null +++ b/packages/storage/src/index.ts @@ -0,0 +1,82 @@ +/** + * The ONLY module that touches IndexedDB (CLAUDE.md §2). The database `rosea` and its + * stores are listed in CLAUDE.md §4; each store arrives with the feature that writes + * it. So far: `profile`, written by the sunset-place question + * (.agents/features/sunset-place.md). + * + * The database name changes together with the product name (CLAUDE.md preamble). + */ +import Dexie, { type DexieOptions, type Table } from 'dexie'; +import type { NamedPlace } from '@rosea/engine'; + +export const DATABASE_NAME = 'rosea'; + +/** Where the player wants their sunset: a town they chose, or the guess from the device's zone. */ +export type SunsetPlace = { readonly kind: 'town'; readonly town: NamedPlace } | { readonly kind: 'device-zone' }; + +interface ProfileRow { + readonly key: string; + readonly value: unknown; +} + +const SUNSET_PLACE = 'sunsetPlace'; + +export interface Profile { + /** The saved sunset place, or null if the player has not answered yet. */ + loadSunsetPlace(): Promise; + saveSunsetPlace(place: SunsetPlace): Promise; + close(): void; +} + +const isNumberIn = (x: unknown, limit: number): x is number => typeof x === 'number' && Number.isFinite(x) && Math.abs(x) <= limit; +const isString = (x: unknown): x is string => typeof x === 'string'; + +/** The shape check a stored value must pass. A value from an older version or a broken write fails it. */ +export function asSunsetPlace(value: unknown): SunsetPlace | null { + if (typeof value !== 'object' || value === null) return null; + const v = value as Record; + if (v['kind'] === 'device-zone') return { kind: 'device-zone' }; + if (v['kind'] !== 'town' || typeof v['town'] !== 'object' || v['town'] === null) return null; + const t = v['town'] as Record; + if (!isString(t['name']) || t['name'] === '' || !isString(t['region']) || !isString(t['country']) || !isString(t['timeZone'])) return null; + if (!isNumberIn(t['lat'], 90) || !isNumberIn(t['lon'], 180)) return null; + return { kind: 'town', town: { name: t['name'], region: t['region'], country: t['country'], lat: t['lat'], lon: t['lon'], timeZone: t['timeZone'] } }; +} + +class RoseaDatabase extends Dexie { + profile!: Table; + + constructor(options?: DexieOptions) { + super(DATABASE_NAME, options); + this.version(1).stores({ profile: 'key' }); + } +} + +/** + * Opens the player's database. `options` lets a test pass fake-indexeddb; the app + * passes nothing and gets the browser's IndexedDB. + */ +export function openProfile(options?: DexieOptions): Profile { + const db = new RoseaDatabase(options); + return { + async loadSunsetPlace() { + const row = await db.profile.get(SUNSET_PLACE); + if (row === undefined) return null; + const place = asSunsetPlace(row.value); + // Never swallowed: a broken record is said out loud, then the question is asked again. + if (place === null) console.warn('storage: the saved sunset place has an unknown shape; asking again', row.value); + return place; + }, + async saveSunsetPlace(place) { + // Write a fresh plain copy, never the caller's object: a Svelte 5 state Proxy + // cannot be structured-cloned, and IndexedDB refuses it (DataCloneError). The + // same shape check as on reading, so nothing malformed is ever written. + const plain = asSunsetPlace(place); + if (plain === null) throw new TypeError('storage: refusing to save a sunset place of an unknown shape'); + await db.profile.put({ key: SUNSET_PLACE, value: plain }); + }, + close() { + db.close(); + } + }; +} diff --git a/packages/storage/test/profile.test.ts b/packages/storage/test/profile.test.ts new file mode 100644 index 0000000..06e3a81 --- /dev/null +++ b/packages/storage/test/profile.test.ts @@ -0,0 +1,105 @@ +import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { asSunsetPlace, openProfile, type Profile, type SunsetPlace } from '../src/index.js'; + +const brno: SunsetPlace = { + kind: 'town', + town: { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' } +}; + +const opened: Profile[] = []; +/** A fresh, empty fake database per call unless one is passed: tests never share state. */ +function open(indexedDB: IDBFactory = new IDBFactory()): Profile { + const p = openProfile({ indexedDB, IDBKeyRange }); + opened.push(p); + return p; +} + +afterEach(() => { + for (const p of opened.splice(0)) p.close(); + vi.restoreAllMocks(); +}); + +describe('the profile store — the sunset place', () => { + it('reads null before the player has answered', async () => { + expect(await open().loadSunsetPlace()).toBeNull(); + }); + + it('keeps a chosen town, and keeps it across a reopen', async () => { + const factory = new IDBFactory(); + const first = open(factory); + await first.saveSunsetPlace(brno); + first.close(); + expect(await open(factory).loadSunsetPlace()).toEqual(brno); + }); + + it('keeps "not now" as the device zone, not as a town', async () => { + const p = open(); + await p.saveSunsetPlace({ kind: 'device-zone' }); + expect(await p.loadSunsetPlace()).toEqual({ kind: 'device-zone' }); + }); + + it('saves a place handed over inside a Proxy, as Svelte 5 state is, by writing a plain copy', async () => { + // Found by the e2e suite: IndexedDB cannot clone a Proxy, and the UI's towns live in $state. + const proxied = new Proxy(brno, {}) as SunsetPlace; + expect(() => structuredClone(proxied)).toThrow(); + const p = open(); + await p.saveSunsetPlace(proxied); + expect(await p.loadSunsetPlace()).toEqual(brno); + }); + + it('refuses to write a place of the wrong shape', async () => { + await expect(open().saveSunsetPlace({ kind: 'town' } as unknown as SunsetPlace)).rejects.toThrow(/unknown shape/); + }); + + it('a new choice replaces the old one', async () => { + const p = open(); + await p.saveSunsetPlace({ kind: 'device-zone' }); + await p.saveSunsetPlace(brno); + expect(await p.loadSunsetPlace()).toEqual(brno); + }); + + it('a record of the wrong shape reads as no answer, and says so in the console', async () => { + const factory = new IDBFactory(); + // Write a broken record straight into the store, as an old version or a torn write might. + const p = open(factory); + await p.saveSunsetPlace(brno); + p.close(); + await new Promise((resolve, reject) => { + const req = factory.open('rosea'); + req.onsuccess = () => { + const tx = req.result.transaction('profile', 'readwrite'); + tx.objectStore('profile').put({ key: 'sunsetPlace', value: { kind: 'town', town: { name: 'Brno', lat: 'north' } } }); + tx.oncomplete = () => { req.result.close(); resolve(); }; + tx.onerror = () => reject(tx.error); + }; + req.onerror = () => reject(req.error); + }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + expect(await open(factory).loadSunsetPlace()).toBeNull(); + expect(warn).toHaveBeenCalledWith(expect.stringMatching(/unknown shape/), expect.anything()); + }); + + it('a database that cannot open rejects, so the app can fall back to the session', async () => { + const broken = new IDBFactory(); + broken.open = () => { throw new DOMException('blocked by the browser', 'SecurityError'); }; + await expect(openProfile({ indexedDB: broken, IDBKeyRange }).loadSunsetPlace()).rejects.toThrow(); + }); +}); + +describe('asSunsetPlace — the shape check', () => { + it.each([ + [null], [42], ['town'], [{ kind: 'gps' }], [{ kind: 'town' }], + [{ kind: 'town', town: { ...(brno as { town: object }).town, lat: 91 } }], + [{ kind: 'town', town: { ...(brno as { town: object }).town, lon: Number.NaN } }], + [{ kind: 'town', town: { ...(brno as { town: object }).town, name: '' } }], + [{ kind: 'town', town: { ...(brno as { town: object }).town, timeZone: 7 } }] + ])('refuses %j', (value) => { + expect(asSunsetPlace(value)).toBeNull(); + }); + + it('keeps only the fields it knows', () => { + const extra = { kind: 'town', town: { ...(brno as { town: object }).town, gps: [49.2, 16.6] } }; + expect(asSunsetPlace(extra)).toEqual(brno); + }); +}); diff --git a/packages/storage/tsconfig.json b/packages/storage/tsconfig.json new file mode 100644 index 0000000..2cbda19 --- /dev/null +++ b/packages/storage/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src/**/*.ts", "test/**/*.ts"] +}