diff --git a/packages/schema/schemas/gardener.schema.json b/packages/schema/schemas/gardener.schema.json new file mode 100644 index 0000000..d6e2669 --- /dev/null +++ b/packages/schema/schemas/gardener.schema.json @@ -0,0 +1,17 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://rosea.invalid/schema/gardener.json", + "title": "Gardener", + "description": "The look of the player's gardener, chosen at the first open (.agents/features/planet-garden.md G6). Every value is from a fixed list: no free text, nothing that identifies a person. Kept on the device in `profile`; never sent, never in the rose file. No option recreates the book's boy: there is no scarf, coat, cape, suit or crown to choose.", + "type": "object", + "additionalProperties": false, + "required": ["presentation", "skin", "hair", "hairColour", "clothes", "hat"], + "properties": { + "presentation": { "enum": ["girl", "boy"] }, + "skin": { "enum": ["skin-1", "skin-2", "skin-3", "skin-4", "skin-5", "skin-6"] }, + "hair": { "enum": ["short", "curly", "ponytail", "braids", "bob", "bun"] }, + "hairColour": { "enum": ["black", "dark-brown", "brown", "auburn", "red", "fair"] }, + "clothes": { "enum": ["sage", "rose", "honey", "dusk", "plum"] }, + "hat": { "enum": ["straw-hat", "cap", "none"] } + } +} diff --git a/packages/schema/src/gardener.ts b/packages/schema/src/gardener.ts new file mode 100644 index 0000000..d1d84d7 --- /dev/null +++ b/packages/schema/src/gardener.ts @@ -0,0 +1,15 @@ +/** + * The gardener's fixed lists, read from gardener.schema.json itself, so the choice the player + * sees, the shape storage checks and the contract can never disagree (planet-garden.md G6). + */ +import schema from '../schemas/gardener.schema.json' with { type: 'json' }; +import type { Gardener } from './generated/index.js'; + +type Options = { readonly [K in keyof Gardener]: readonly Gardener[K][] }; + +export const GARDENER_OPTIONS: Options = Object.fromEntries( + Object.entries(schema.properties).map(([k, v]) => [k, v.enum]) +) as unknown as Options; + +/** The order the choice asks in. */ +export const GARDENER_FIELDS = schema.required as readonly (keyof Gardener)[]; diff --git a/packages/schema/src/index.ts b/packages/schema/src/index.ts index 9aff762..a99d1a4 100644 --- a/packages/schema/src/index.ts +++ b/packages/schema/src/index.ts @@ -1,2 +1,3 @@ export * from './constants.js'; export type * from './generated/index.js'; +export { GARDENER_FIELDS, GARDENER_OPTIONS } from './gardener.js'; diff --git a/packages/schema/src/validate.ts b/packages/schema/src/validate.ts index efb35d8..9fcc89e 100644 --- a/packages/schema/src/validate.ts +++ b/packages/schema/src/validate.ts @@ -9,10 +9,11 @@ */ import { Ajv, type ErrorObject, type ValidateFunction } from 'ajv'; import careEvent from '../schemas/care-event.schema.json' with { type: 'json' }; +import gardener from '../schemas/gardener.schema.json' with { type: 'json' }; import hopeSentence from '../schemas/hope-sentence.schema.json' with { type: 'json' }; import sentenceOpened from '../schemas/sentence-opened.schema.json' with { type: 'json' }; import trace from '../schemas/trace.schema.json' with { type: 'json' }; -import type { CareEvent, HopeSentence, SentenceOpened, Trace } from './generated/index.js'; +import type { CareEvent, Gardener, HopeSentence, SentenceOpened, Trace } from './generated/index.js'; export type SchemaResult = | { readonly ok: true; readonly value: T } @@ -40,4 +41,5 @@ function describe(error: ErrorObject): string { export const validateHopeSentence = wrap(ajv.compile(hopeSentence)); export const validateCareEvent = wrap(ajv.compile(careEvent)); export const validateSentenceOpened = wrap(ajv.compile(sentenceOpened)); +export const validateGardener = wrap(ajv.compile(gardener)); export const validateTrace = wrap(ajv.compile(trace)); diff --git a/packages/storage/src/index.ts b/packages/storage/src/index.ts index 7b31263..3eaea62 100644 --- a/packages/storage/src/index.ts +++ b/packages/storage/src/index.ts @@ -12,7 +12,7 @@ import Dexie, { type DexieOptions, type Table } from 'dexie'; import { newCare, newOpened, type NamedPlace } from '@rosea/engine'; import { isIdentity, type Identity } from '@rosea/identity'; -import { DATABASE_NAME, type CareEvent, type SentenceOpened } from '@rosea/schema'; +import { DATABASE_NAME, GARDENER_FIELDS, GARDENER_OPTIONS, type CareEvent, type Gardener, type SentenceOpened } from '@rosea/schema'; export { DATABASE_NAME }; @@ -34,6 +34,17 @@ interface KeyRow { } const SUNSET_PLACE = 'sunsetPlace'; +const GARDENER = 'gardener'; + +/** The shape check for a stored gardener: exactly the six fields, each from its list. */ +export function asGardener(value: unknown): Gardener | null { + if (typeof value !== 'object' || value === null) return null; + const v = value as Record; + const keys = GARDENER_FIELDS; + if (Object.keys(v).length !== keys.length) return null; + for (const k of keys) if (!(GARDENER_OPTIONS[k] as readonly unknown[]).includes(v[k])) return null; + return Object.fromEntries(keys.map((k) => [k, v[k]])) as unknown as Gardener; +} const SELF = 'self'; const PAST_KEYS = 'pastKeys'; @@ -55,6 +66,9 @@ export interface RoseFile { export interface Storage { /** The saved sunset place, or null if the player has not answered yet. */ loadSunsetPlace(): Promise; + /** The player's gardener, or null before they chose one (planet-garden.md G6). */ + loadGardener(): Promise; + saveGardener(look: Gardener): Promise; saveSunsetPlace(place: SunsetPlace): Promise; /** Appends one act of care. The log is never edited or shortened. */ appendCare(event: CareEvent): Promise; @@ -194,7 +208,7 @@ class RoseaDatabase extends Dexie { } /** What another tab changed (two-tabs.md W2): only which part, never the data. */ -export type Change = 'log' | 'place'; +export type Change = 'log' | 'place' | 'gardener'; /** The channel every tab of the garden announces its writes on (two-tabs.md W1). */ export const CHANGES_CHANNEL = `${DATABASE_NAME}-changes`; @@ -213,7 +227,7 @@ export function openStorage(options?: DexieOptions, settings: { readonly channel if (channel) { channel.onmessage = (message: MessageEvent) => { const what = message.data; - if (what !== 'log' && what !== 'place') return; + if (what !== 'log' && what !== 'place' && what !== 'gardener') return; for (const listener of listeners) { try { listener(what); @@ -250,6 +264,19 @@ export function openStorage(options?: DexieOptions, settings: { readonly channel await db.profile.put({ key: SUNSET_PLACE, value: plain }); announce('place'); }, + async loadGardener() { + const row = await db.profile.get(GARDENER); + if (row === undefined) return null; + const look = asGardener(row.value); + if (look === null) console.warn('storage: the saved gardener has an unknown shape; asking again', row.value); + return look; + }, + async saveGardener(look) { + const plain = asGardener(look); + if (plain === null) throw new TypeError('storage: refusing to save a gardener of an unknown shape'); + await db.profile.put({ key: GARDENER, value: plain }); + announce('gardener'); + }, async appendCare(event) { const plain = asCareEvent(event); if (plain === null) throw new TypeError('storage: refusing to append a care event of an unknown shape'); diff --git a/packages/storage/test/gardener.test.ts b/packages/storage/test/gardener.test.ts new file mode 100644 index 0000000..4beb3d8 --- /dev/null +++ b/packages/storage/test/gardener.test.ts @@ -0,0 +1,71 @@ +import { GARDENER_FIELDS, GARDENER_OPTIONS, type Gardener } from '@rosea/schema'; +import { validateGardener } from '@rosea/schema/validate'; +import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { asGardener, openStorage, type Change, type Storage } from '../src/index.js'; + +const look: Gardener = { presentation: 'girl', skin: 'skin-3', hair: 'braids', hairColour: 'auburn', clothes: 'sage', hat: 'straw-hat' }; +const KEY = 'K'.repeat(87); + +const opened: Storage[] = []; +const open = (indexedDB: IDBFactory = new IDBFactory(), channel: string | null = null): Storage => { + const s = openStorage({ indexedDB, IDBKeyRange }, { channel }); + opened.push(s); + return s; +}; +afterEach(() => { + for (const s of opened.splice(0)) s.close(); + vi.restoreAllMocks(); +}); + +describe('the gardener (planet-garden.md G6)', () => { + it('is null before the player chose, then kept across a reopen', async () => { + const factory = new IDBFactory(); + const s = open(factory); + expect(await s.loadGardener()).toBeNull(); + await s.saveGardener(new Proxy(look, {})); + s.close(); + expect(await open(factory).loadGardener()).toEqual(look); + }); + + it('refuses a value off its list, a missing field, an extra field, or free text', async () => { + const s = open(); + for (const bad of [ + { ...look, hat: 'crown' }, + { ...look, clothes: 'green suit' }, + { ...look, extra: 'a scarf' }, + (({ hat: _, ...rest }) => rest)(look), + { ...look, presentation: 'Marek' } + ]) { + await expect(s.saveGardener(bad as unknown as Gardener)).rejects.toThrow(/unknown shape/); + } + expect(await s.loadGardener()).toBeNull(); + }); + + it('the hand check, the schema and the lists agree', () => { + expect([...GARDENER_FIELDS].sort()).toEqual(Object.keys(GARDENER_OPTIONS).sort()); + for (const k of GARDENER_FIELDS) { + for (const v of GARDENER_OPTIONS[k]) expect(validateGardener({ ...look, [k]: v }).ok).toBe(true); + expect(asGardener({ ...look, [k]: 'other' })).toBeNull(); + expect(validateGardener({ ...look, [k]: 'other' }).ok).toBe(false); + } + expect(asGardener(look)).toEqual(look); + }); + + it('never offers what would recreate the book\'s boy', () => { + const everything = JSON.stringify(GARDENER_OPTIONS).toLowerCase(); + for (const word of ['scarf', 'coat', 'cape', 'suit', 'crown', 'sword', 'golden']) expect(everything).not.toContain(word); + }); + + it('is announced to the other tabs, and never travels in the rose file', async () => { + const factory = new IDBFactory(); + const a = open(factory, 'rosea-test-gardener'); + const b = open(factory, 'rosea-test-gardener'); + const heard: Change[] = []; + b.onChange((w) => heard.push(w)); + await a.saveGardener(look); + await new Promise((r) => setTimeout(r, 100)); + expect(heard).toEqual(['gardener']); + expect(JSON.stringify(await a.exportRose(KEY))).not.toMatch(/braids|auburn|skin-3|gardener/); + }); +});