[repo] Workspace: Scaffold Phase 0 with schema, engine, content, ui and the PWA shell
pnpm + turbo workspace with the commands from CLAUDE.md §3. The contracts from §6 as JSON Schemas with generated types; localDay as the one place a day is computed; the forbidden-word list shared by lint:copy and the library validator, with 13 negative fixtures; a Svelte 5 PWA shell built under /Rosea/ with a meta CSP. E2E and offline suites run against the built bundle; the offline one closes the server rather than emulating. Analysis: .agents/features/phase0-workspace.md
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "@rosea/content",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "The hope library and planets' scripts as data, the library validator, and the one list of forbidden words.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./validate": "./src/validator.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json",
|
||||
"test": "vitest run --reporter=verbose"
|
||||
},
|
||||
"dependencies": {
|
||||
"@rosea/schema": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "5.9.3",
|
||||
"vitest": "3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* The core of `pnpm lint:copy` (CLAUDE.md §5.6, §7): what a player could read in
|
||||
* a file, and what is wrong with it. The script walks files; this decides.
|
||||
*/
|
||||
import { findForbidden } from './forbidden.js';
|
||||
|
||||
export interface CopyProblem {
|
||||
readonly line: number;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes comments, keeping line numbers. Comments are where the rules are
|
||||
* explained, and a rule must be nameable in the file that enforces it.
|
||||
* `//` after a `:` is a URL, not a comment.
|
||||
*/
|
||||
export function stripComments(source: string): string {
|
||||
const blank = (m: string): string => m.replace(/[^\n]/g, ' ');
|
||||
return source
|
||||
.replace(/<!--[\s\S]*?-->/g, blank)
|
||||
.replace(/\/\*[\s\S]*?\*\//g, blank)
|
||||
.replace(/(?<![:\\])\/\/[^\n]*/g, blank);
|
||||
}
|
||||
|
||||
// *Domi* is the ecosystem's word and never stands alone (CLAUDE.md preamble).
|
||||
const DOMI_ALONE = /(?<!(?:Rosea|Panda|Amicitia)[\s\u00a0])\bDomi\b/g;
|
||||
|
||||
/** Problems in one file's player-visible text. */
|
||||
export function lintCopy(source: string): CopyProblem[] {
|
||||
const text = stripComments(source);
|
||||
const lineOf = (index: number): number => text.slice(0, index).split('\n').length;
|
||||
const problems: CopyProblem[] = [];
|
||||
|
||||
for (const hit of findForbidden(text)) {
|
||||
problems.push({ line: lineOf(hit.index), message: `'${hit.term}' (${hit.category}): ${hit.why}` });
|
||||
}
|
||||
|
||||
for (const m of text.matchAll(DOMI_ALONE)) {
|
||||
problems.push({
|
||||
line: lineOf(m.index),
|
||||
message: "'Domi' on its own: the product is always Rosea Domi, and Domi never appears alone"
|
||||
});
|
||||
}
|
||||
|
||||
return problems.sort((a, b) => a.line - b.line);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* The one list of words and names that never reach a player (CLAUDE.md §5.6
|
||||
* rules 3 and 4). `lint:copy` and the library validator both read it, so the two
|
||||
* can never disagree.
|
||||
*
|
||||
* Matching is whole-word and case-insensitive, with inflections spelled out.
|
||||
* A stem match (`heal*`) would also catch *health*, and a rose can be healthy.
|
||||
*
|
||||
* `treat` is banned outright, including the fox's food: he eats *berries*.
|
||||
* `patient` is banned too. Patience is the cure Gandalf's spirit offers, so the
|
||||
* product may say *patience* and *patiently* but never *patient*.
|
||||
*/
|
||||
|
||||
export type ForbiddenCategory = 'medical' | 'unnamed-state' | 'little-prince' | 'tolkien';
|
||||
|
||||
export interface ForbiddenTerm {
|
||||
readonly term: string;
|
||||
readonly category: ForbiddenCategory;
|
||||
readonly why: string;
|
||||
}
|
||||
|
||||
const MEDICAL =
|
||||
'A medical claim pulls the product toward EU medical-device rules (CLAUDE.md §5.6 rule 3). Rosea comforts; it does not treat.';
|
||||
const UNNAMED =
|
||||
'The game never names the state for the player (CLAUDE.md §5.6 rule 4). It lets them feel seen instead.';
|
||||
const PRINCE = 'Nothing from The Little Prince by name or quote: one idea is borrowed, never its text (CLAUDE.md §5.6 rule 3).';
|
||||
const TOLKIEN = "Gandalf's spirit, never a name or a quote from Tolkien's works (CLAUDE.md §5.6 rule 3).";
|
||||
|
||||
const terms = (category: ForbiddenCategory, why: string, list: readonly string[]): ForbiddenTerm[] =>
|
||||
list.map((term) => ({ term, category, why }));
|
||||
|
||||
export const FORBIDDEN: readonly ForbiddenTerm[] = [
|
||||
...terms('medical', MEDICAL, [
|
||||
'therapy', 'therapies', 'therapist', 'therapists', 'therapeutic', 'therapeutically',
|
||||
'treat', 'treats', 'treated', 'treating', 'treatment', 'treatments',
|
||||
'heal', 'heals', 'healed', 'healing', 'healer', 'healers',
|
||||
'cure', 'cures', 'cured', 'curing', 'curative',
|
||||
'diagnose', 'diagnoses', 'diagnosed', 'diagnosing', 'diagnosis', 'diagnostic',
|
||||
'symptom', 'symptoms', 'symptomatic',
|
||||
'patient', 'patients',
|
||||
'disorder', 'disorders'
|
||||
]),
|
||||
...terms('unnamed-state', UNNAMED, ['lonely', 'lonelier', 'loneliest', 'loneliness']),
|
||||
...terms('little-prince', PRINCE, [
|
||||
'Little Prince', 'Petit Prince', 'Malý princ', 'Saint-Exupéry', 'Saint-Exupery', 'Exupéry', 'Exupery', 'B-612', 'B612'
|
||||
]),
|
||||
...terms('tolkien', TOLKIEN, [
|
||||
'Tolkien', 'Gandalf', 'Mithrandir', 'Frodo', 'Bilbo', 'Samwise', 'Aragorn', 'Galadriel', 'Sauron',
|
||||
'Mordor', 'Rivendell', 'Middle-earth', 'Middle earth', 'hobbit', 'hobbits', 'Lothlórien', 'Lothlorien'
|
||||
])
|
||||
];
|
||||
|
||||
export interface ForbiddenHit {
|
||||
readonly term: string;
|
||||
readonly category: ForbiddenCategory;
|
||||
readonly why: string;
|
||||
/** Index into the scanned text. */
|
||||
readonly index: number;
|
||||
}
|
||||
|
||||
const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/[\s-]+/g, '[\\s\\u00a0-]+');
|
||||
|
||||
// Letters and digits on either side mean it is part of a longer word: *treaty*
|
||||
// does not contain *treat*. Hyphens and apostrophes are boundaries, so
|
||||
// *self-healing* is caught.
|
||||
const PATTERNS = FORBIDDEN.map((entry) => ({
|
||||
entry,
|
||||
regex: new RegExp(`(?<![\\p{L}\\p{N}])${escape(entry.term)}(?![\\p{L}\\p{N}])`, 'giu')
|
||||
}));
|
||||
|
||||
/** Every forbidden term in `text`, in order of appearance. */
|
||||
export function findForbidden(text: string): ForbiddenHit[] {
|
||||
const hits: ForbiddenHit[] = [];
|
||||
for (const { entry, regex } of PATTERNS) {
|
||||
regex.lastIndex = 0;
|
||||
for (let m = regex.exec(text); m !== null; m = regex.exec(text)) {
|
||||
hits.push({ ...entry, index: m.index });
|
||||
}
|
||||
}
|
||||
return hits.sort((a, b) => a.index - b.index);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { lintCopy, stripComments, type CopyProblem } from './copy-lint.js';
|
||||
export { FORBIDDEN, findForbidden, type ForbiddenCategory, type ForbiddenHit, type ForbiddenTerm } from './forbidden.js';
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* The hope-library validator (CLAUDE.md §5.5, §5.6 rule 2, §6.1).
|
||||
*
|
||||
* The schema says what shape an entry has. This says whether it may be shown
|
||||
* to a person: sourced, public domain or the author's own, short enough to
|
||||
* read at sunset, free of forbidden words, and not promising anything.
|
||||
*
|
||||
* Its negative fixtures in `content/fixtures/` ARE the validator: a rule here
|
||||
* without a fixture proving it fires is a review blocker.
|
||||
*/
|
||||
import type { HopeSentence } from '@rosea/schema';
|
||||
import { validateHopeSentence } from '@rosea/schema/validate';
|
||||
import { findForbidden } from './forbidden.js';
|
||||
|
||||
export type Rule =
|
||||
| 'schema'
|
||||
| 'no-source'
|
||||
| 'not-public-domain'
|
||||
| 'translation-under-copyright'
|
||||
| 'too-long'
|
||||
| 'promises-outcome'
|
||||
| 'forbidden-word'
|
||||
| 'no-tradition'
|
||||
| 'duplicate-id';
|
||||
|
||||
export interface Problem {
|
||||
readonly id: string;
|
||||
readonly rule: Rule;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
/** Characters per language. A sentence opened at sunset is read on a phone, once. */
|
||||
export const LENGTH_CAP = 240;
|
||||
|
||||
/**
|
||||
* The tradition tag for a line the author wrote for Rosea. Those are not public
|
||||
* domain, and need not be: the author owns them (CLAUDE.md §5.6 rule 2).
|
||||
*/
|
||||
export const AUTHOR_TRADITION = 'rosea';
|
||||
|
||||
/**
|
||||
* Translations known to be in the public domain. Anything else is assumed to
|
||||
* be under copyright until someone checks and adds it here, with the source of
|
||||
* that check in the commit.
|
||||
*/
|
||||
export const PUBLIC_DOMAIN_TRANSLATIONS: ReadonlySet<string> = new Set([
|
||||
'KJV', // King James Version, 1611/1769
|
||||
'Bible kralická', // 1579–1613
|
||||
'ASV', // American Standard Version, 1901
|
||||
'Douay-Rheims', // 1582–1610, Challoner revision 1752
|
||||
'YLT', // Young's Literal Translation, 1862
|
||||
'WEB' // World English Bible, dedicated to the public domain
|
||||
]);
|
||||
|
||||
/**
|
||||
* Phrasings that promise an outcome. A heuristic, so a hit means "a human must
|
||||
* read this", and the entry fails until one does. An honest `promisesOutcome:
|
||||
* true` fails the same way.
|
||||
*/
|
||||
const OUTCOME_PHRASES: readonly RegExp[] = [
|
||||
/\beverything will be\b/i,
|
||||
/\b(it|you|things) will (all )?(be|get) (better|fine|okay|ok|alright|all right|well)\b/i,
|
||||
/\byou will (find|never|always|soon)\b/i,
|
||||
/\bi promise\b/i,
|
||||
/\bguarantee/i
|
||||
];
|
||||
|
||||
const idOf = (input: unknown): string =>
|
||||
typeof input === 'object' && input !== null && typeof (input as { id?: unknown }).id === 'string'
|
||||
? (input as { id: string }).id
|
||||
: '(no id)';
|
||||
|
||||
/** Every reason `input` may not be shown to a player. Empty means it may. */
|
||||
export function validateEntry(input: unknown): Problem[] {
|
||||
const id = idOf(input);
|
||||
const problem = (rule: Rule, message: string): Problem => ({ id, rule, message });
|
||||
const problems: Problem[] = [];
|
||||
|
||||
const schema = validateHopeSentence(input);
|
||||
if (!schema.ok) {
|
||||
for (const error of schema.errors) {
|
||||
if (/^\(root\) .*'source'/.test(error)) {
|
||||
problems.push(problem('no-source', 'has no source: every sentence names where it comes from'));
|
||||
} else if (/^\/source .*'tradition'|^\/source\/tradition /.test(error)) {
|
||||
problems.push(problem('no-tradition', 'has no tradition tag: the library stays mixed, so each line says which one it is from'));
|
||||
} else {
|
||||
problems.push(problem('schema', error));
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
const entry: HopeSentence = schema.value;
|
||||
const { source } = entry;
|
||||
|
||||
if (!source.publicDomain && source.tradition !== AUTHOR_TRADITION) {
|
||||
problems.push(
|
||||
problem('not-public-domain', `source '${source.work}' is not verified public domain, and the author did not write it for Rosea`)
|
||||
);
|
||||
}
|
||||
|
||||
if (source.translation !== null && !PUBLIC_DOMAIN_TRANSLATIONS.has(source.translation)) {
|
||||
problems.push(
|
||||
problem(
|
||||
'translation-under-copyright',
|
||||
`translation '${source.translation}' is not on the public-domain list; a modern translation is usually still under copyright`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
for (const [lang, text] of Object.entries(entry.text)) {
|
||||
if (text === undefined) continue;
|
||||
|
||||
const length = [...text].length;
|
||||
if (length > LENGTH_CAP) {
|
||||
problems.push(problem('too-long', `${lang} text is ${length} characters, over the length cap of ${LENGTH_CAP}`));
|
||||
}
|
||||
|
||||
for (const hit of findForbidden(text)) {
|
||||
problems.push(problem('forbidden-word', `${lang} text contains '${hit.term}' (${hit.category}): ${hit.why}`));
|
||||
}
|
||||
|
||||
const phrase = OUTCOME_PHRASES.find((p) => p.test(text));
|
||||
if (phrase !== undefined) {
|
||||
problems.push(problem('promises-outcome', `${lang} text may promise an outcome (${phrase.source}): needs human review`));
|
||||
}
|
||||
}
|
||||
|
||||
if (entry.promisesOutcome) {
|
||||
problems.push(problem('promises-outcome', 'is marked promisesOutcome: comfort never promises what will happen'));
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/** Validates a whole library: every entry, plus ids unique across all of them. */
|
||||
export function validateLibrary(entries: readonly unknown[]): Problem[] {
|
||||
const problems = entries.flatMap(validateEntry);
|
||||
const seen = new Set<string>();
|
||||
for (const entry of entries) {
|
||||
const id = idOf(entry);
|
||||
if (seen.has(id)) {
|
||||
problems.push({ id, rule: 'duplicate-id', message: `id '${id}' is used more than once; a message between players would be ambiguous` });
|
||||
}
|
||||
seen.add(id);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { lintCopy, stripComments } from '../src/copy-lint.js';
|
||||
|
||||
describe('lint:copy core', () => {
|
||||
it('reports a forbidden word in a string, with its line', () => {
|
||||
const problems = lintCopy("export const a = 'ok';\nexport const b = 'A gentle therapy';\n");
|
||||
expect(problems).toHaveLength(1);
|
||||
expect(problems[0]?.line).toBe(2);
|
||||
expect(problems[0]?.message).toContain('therapy');
|
||||
});
|
||||
|
||||
it('reports a forbidden word in Svelte markup', () => {
|
||||
expect(lintCopy('<p>For the lonely.</p>')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('ignores comments, where rules are explained', () => {
|
||||
expect(lintCopy('// never say therapy\n/* nor lonely */\n<!-- nor Gandalf -->\nconst ok = 1;')).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps line numbers when it strips a multi-line comment', () => {
|
||||
const problems = lintCopy("/*\n\n*/\nconst s = 'cure';");
|
||||
expect(problems[0]?.line).toBe(4);
|
||||
});
|
||||
|
||||
it('does not mistake a URL for a comment', () => {
|
||||
expect(stripComments("'https://example.invalid/cure'")).toContain('cure');
|
||||
});
|
||||
|
||||
it("reports 'Domi' standing alone", () => {
|
||||
expect(lintCopy("const title = 'Domi';")).toHaveLength(1);
|
||||
expect(lintCopy("const title = 'Welcome to Domi';")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("accepts 'Domi' after its first word", () => {
|
||||
expect(lintCopy("'Rosea Domi', 'Panda Domi', 'Amicitia Domi'")).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts clean shell copy', () => {
|
||||
expect(lintCopy("preparing: 'The garden is being prepared.'")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { FORBIDDEN, findForbidden } from '../src/forbidden.js';
|
||||
|
||||
const terms = (text: string): string[] => findForbidden(text).map((h) => h.term);
|
||||
|
||||
describe('forbidden words — what is caught', () => {
|
||||
it('catches every listed term on its own', () => {
|
||||
const missed = FORBIDDEN.filter(({ term }) => !terms(`before ${term} after`).includes(term)).map((t) => t.term);
|
||||
expect(missed).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['A soft THERAPY for the soul', 'therapy'],
|
||||
['self-healing petals', 'healing'],
|
||||
["the rose's lonely planet", 'lonely'],
|
||||
['Loneliness.', 'loneliness'],
|
||||
['a treat for the fox', 'treat'],
|
||||
['be patient with yourself', 'patient'],
|
||||
['Middle-earth', 'Middle-earth'],
|
||||
['Middle earth', 'Middle-earth'],
|
||||
['Malý princ', 'Malý princ'],
|
||||
['Saint-Exupéry wrote', 'Saint-Exupéry']
|
||||
])('"%s" contains %s', (text, term) => {
|
||||
expect(terms(text)).toContain(term);
|
||||
});
|
||||
|
||||
it('reports hits in reading order', () => {
|
||||
expect(terms('cure first, then therapy')).toEqual(['cure', 'therapy']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('forbidden words — what is NOT caught', () => {
|
||||
it.each([
|
||||
'a treaty between two roses',
|
||||
'a healthy rose',
|
||||
'patience, and patiently waiting',
|
||||
'the lamplighter on his planet',
|
||||
'the king, the vain man, the businessman',
|
||||
'a fox among the berries',
|
||||
'Rosea Domi'
|
||||
])('"%s" is clean', (text) => {
|
||||
expect(terms(text)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { LENGTH_CAP, validateEntry, validateLibrary, type Rule } from '../src/validator.js';
|
||||
|
||||
const fixturesDir = fileURLToPath(new URL('../../../content/fixtures', import.meta.url));
|
||||
|
||||
interface Fixture {
|
||||
readonly expect: Rule;
|
||||
readonly why: string;
|
||||
readonly entry?: unknown;
|
||||
readonly entries?: readonly unknown[];
|
||||
}
|
||||
|
||||
const fixtures = readdirSync(fixturesDir)
|
||||
.filter((f) => f.endsWith('.json'))
|
||||
.sort()
|
||||
.map((file) => ({ file, fixture: JSON.parse(readFileSync(join(fixturesDir, file), 'utf8')) as Fixture }));
|
||||
|
||||
const valid = {
|
||||
id: 'valid-entry',
|
||||
text: { en: 'Fixture text, not a real sentence.', cs: 'Testovací text.' },
|
||||
source: {
|
||||
work: 'Fixture',
|
||||
author: null,
|
||||
tradition: 'biblical',
|
||||
translation: 'KJV',
|
||||
publicDomain: true,
|
||||
verifiedBy: 'Fixture',
|
||||
verifiedAt: '2026-11-01'
|
||||
},
|
||||
use: ['sunset', 'comfort'],
|
||||
tone: 'gentle',
|
||||
promisesOutcome: false
|
||||
};
|
||||
|
||||
describe('library validator — negative fixtures', () => {
|
||||
it('finds the fixtures', () => {
|
||||
// A glob matching nothing would pass every case below.
|
||||
expect(fixtures.length).toBeGreaterThanOrEqual(13);
|
||||
});
|
||||
|
||||
it.each(fixtures)('$file fails with its named rule', ({ fixture }) => {
|
||||
const problems = fixture.entries !== undefined ? validateLibrary(fixture.entries) : validateEntry(fixture.entry);
|
||||
expect(problems.map((p) => p.rule), fixture.why).toContain(fixture.expect);
|
||||
for (const p of problems) expect(p.message.length, 'each problem says what is wrong').toBeGreaterThan(10);
|
||||
});
|
||||
|
||||
it('every rule the validator has is proved by at least one fixture', () => {
|
||||
const proved = new Set(fixtures.map(({ fixture }) => fixture.expect));
|
||||
const RULES: readonly Rule[] = [
|
||||
'schema',
|
||||
'no-source',
|
||||
'not-public-domain',
|
||||
'translation-under-copyright',
|
||||
'too-long',
|
||||
'promises-outcome',
|
||||
'forbidden-word',
|
||||
'no-tradition',
|
||||
'duplicate-id'
|
||||
];
|
||||
expect(RULES.filter((r) => !proved.has(r))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('library validator — what passes', () => {
|
||||
it('accepts a sourced, public-domain, short, gentle entry', () => {
|
||||
expect(validateEntry(valid)).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts a line the author wrote for Rosea, though it is not public domain', () => {
|
||||
const own = { ...valid, source: { ...valid.source, tradition: 'rosea', translation: null, publicDomain: false } };
|
||||
expect(validateEntry(own)).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts text exactly at the length cap, counting characters and not UTF-16 units', () => {
|
||||
const atCap = { ...valid, text: { en: 'ř'.repeat(LENGTH_CAP) } };
|
||||
expect(validateEntry(atCap)).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts an empty library, and says nothing about it', () => {
|
||||
expect(validateLibrary([])).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "@rosea/engine",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Pure. No I/O, no DOM, no Date.now(), no Math.random(). Time and randomness are parameters.",
|
||||
"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/schema": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"eslint": "9.39.5",
|
||||
"fast-check": "3.23.2",
|
||||
"typescript": "5.9.3",
|
||||
"vitest": "3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { isLocalDay, localDay, type LocalDay } from './time/localDay.js';
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* The ONLY place in the repository where a day is computed (CLAUDE.md §7).
|
||||
*
|
||||
* A day is always local to a named IANA time zone, and the zone is always a
|
||||
* parameter. The engine never asks the device which zone it is in: the app
|
||||
* passes the zone of the city the player chose, or the device's own zone as the
|
||||
* fallback (CLAUDE.md §4 `profile`).
|
||||
*
|
||||
* Never `toISOString().slice(0, 10)`: that is the UTC day, and in Prague it
|
||||
* records Monday-evening care as Tuesday's.
|
||||
*/
|
||||
|
||||
/** A calendar day, `YYYY-MM-DD`, in some player's local time. */
|
||||
export type LocalDay = string;
|
||||
|
||||
const LOCAL_DAY = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
// Memoised per zone. Constructing a DateTimeFormat costs far more than using one.
|
||||
// This is a cache of a pure function's machinery, not state: the output depends
|
||||
// only on the arguments.
|
||||
const formatters = new Map<string, Intl.DateTimeFormat>();
|
||||
|
||||
function formatterFor(timeZone: string): Intl.DateTimeFormat {
|
||||
let formatter = formatters.get(timeZone);
|
||||
if (formatter === undefined) {
|
||||
// Throws RangeError for an unknown zone, which is the right failure: a
|
||||
// mistyped zone silently falling back to UTC is the bug this module exists
|
||||
// to prevent.
|
||||
formatter = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone,
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
calendar: 'iso8601',
|
||||
numberingSystem: 'latn'
|
||||
});
|
||||
formatters.set(timeZone, formatter);
|
||||
}
|
||||
return formatter;
|
||||
}
|
||||
|
||||
/** The local calendar day of `epochMs` in `timeZone`. */
|
||||
export function localDay(epochMs: number, timeZone: string): LocalDay {
|
||||
if (!Number.isFinite(epochMs)) {
|
||||
throw new RangeError(`localDay: epochMs must be a finite number, got ${String(epochMs)}`);
|
||||
}
|
||||
|
||||
const parts = formatterFor(timeZone).formatToParts(epochMs);
|
||||
const part = (type: Intl.DateTimeFormatPartTypes): string => {
|
||||
const value = parts.find((p) => p.type === type)?.value;
|
||||
if (value === undefined) throw new RangeError(`localDay: no ${type} for ${epochMs} in ${timeZone}`);
|
||||
return value;
|
||||
};
|
||||
|
||||
const day = `${part('year')}-${part('month')}-${part('day')}`;
|
||||
if (!LOCAL_DAY.test(day)) {
|
||||
// Years before 1000 or after 9999 would not be four digits. No player tends
|
||||
// a rose then; refusing is better than writing an ambiguous day to the log.
|
||||
throw new RangeError(`localDay: ${epochMs} gives an unrepresentable day '${day}'`);
|
||||
}
|
||||
return day;
|
||||
}
|
||||
|
||||
/** Whether `value` has the shape of a LocalDay. Does not check that the date exists. */
|
||||
export function isLocalDay(value: string): value is LocalDay {
|
||||
return LOCAL_DAY.test(value);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isLocalDay, localDay } from '../src/time/localDay.js';
|
||||
|
||||
const at = (iso: string): number => Date.parse(iso);
|
||||
|
||||
describe('localDay — golden cases', () => {
|
||||
it.each([
|
||||
// Prague, 2026 spring-forward day (29 March, 02:00 CET -> 03:00 CEST).
|
||||
['2026-03-28T23:30:00Z', 'Europe/Prague', '2026-03-29'], // 00:30 CET, first half-hour of the short day
|
||||
['2026-03-29T21:59:00Z', 'Europe/Prague', '2026-03-29'], // 23:59 CEST, last minute of it
|
||||
['2026-03-29T22:00:00Z', 'Europe/Prague', '2026-03-30'],
|
||||
// Prague, 2026 fall-back day (25 October, 03:00 CEST -> 02:00 CET), 25 hours long.
|
||||
['2026-10-24T22:00:00Z', 'Europe/Prague', '2026-10-25'],
|
||||
['2026-10-25T22:59:00Z', 'Europe/Prague', '2026-10-25'], // 23:59 CET
|
||||
['2026-10-25T23:00:00Z', 'Europe/Prague', '2026-10-26'],
|
||||
// Southern hemisphere: Sydney is ahead of UTC, so its morning is UTC's yesterday.
|
||||
['2026-11-01T21:00:00Z', 'Australia/Sydney', '2026-11-02'],
|
||||
// Reykjavík has no DST and sits on UTC: the one zone where UTC days are right.
|
||||
['2026-06-21T23:59:00Z', 'Atlantic/Reykjavik', '2026-06-21'],
|
||||
// The edges of the clock face.
|
||||
['2026-01-01T10:00:00Z', 'Pacific/Kiritimati', '2026-01-02'], // UTC+14
|
||||
['2026-01-01T10:00:00Z', 'Etc/GMT+12', '2025-12-31'] // UTC-12
|
||||
])('%s in %s is %s', (iso, zone, expected) => {
|
||||
expect(localDay(at(iso), zone)).toBe(expected);
|
||||
});
|
||||
|
||||
it('Monday evening in Anchorage is Monday, though UTC already says Tuesday', () => {
|
||||
// 2026-10-26 is a Monday. 20:00 AKDT = 04:00 UTC on Tuesday.
|
||||
const mondayEvening = at('2026-10-27T04:00:00Z');
|
||||
expect(localDay(mondayEvening, 'America/Anchorage')).toBe('2026-10-26');
|
||||
expect(new Date(mondayEvening).toISOString().slice(0, 10)).toBe('2026-10-27'); // the trap, measured
|
||||
});
|
||||
|
||||
it('just after midnight on Tuesday in Prague is Tuesday, though UTC still says Monday', () => {
|
||||
const tuesdayNight = at('2026-10-26T23:30:00Z'); // 00:30 CET on Tuesday 27th
|
||||
expect(localDay(tuesdayNight, 'Europe/Prague')).toBe('2026-10-27');
|
||||
});
|
||||
});
|
||||
|
||||
describe('localDay — refusals', () => {
|
||||
it('throws on an unknown zone instead of falling back to UTC', () => {
|
||||
expect(() => localDay(0, 'Europe/Atlantis')).toThrow(RangeError);
|
||||
});
|
||||
|
||||
it('throws on a non-finite time', () => {
|
||||
expect(() => localDay(Number.NaN, 'Europe/Prague')).toThrow(RangeError);
|
||||
expect(() => localDay(Number.POSITIVE_INFINITY, 'Europe/Prague')).toThrow(RangeError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('localDay — properties', () => {
|
||||
const ZONES = [
|
||||
'Europe/Prague',
|
||||
'Atlantic/Reykjavik',
|
||||
'Europe/Oslo', // Tromsø's zone
|
||||
'America/Guayaquil', // Quito's zone
|
||||
'Australia/Sydney',
|
||||
'America/Anchorage',
|
||||
'Pacific/Kiritimati',
|
||||
'Etc/GMT+12'
|
||||
] as const;
|
||||
|
||||
// 2000-01-01 .. 2100-01-01: every year a player could plausibly be in.
|
||||
const instant = fc.integer({ min: Date.UTC(2000, 0, 1), max: Date.UTC(2100, 0, 1) });
|
||||
const zone = fc.constantFrom(...ZONES);
|
||||
const HOUR = 3_600_000;
|
||||
|
||||
it('always returns a well-formed day', () => {
|
||||
fc.assert(fc.property(instant, zone, (t, z) => isLocalDay(localDay(t, z))));
|
||||
});
|
||||
|
||||
it('never goes backwards in time, across DST changes included', () => {
|
||||
fc.assert(
|
||||
fc.property(instant, fc.integer({ min: 0, max: 72 * HOUR }), zone, (t, dt, z) => {
|
||||
return localDay(t, z) <= localDay(t + dt, z);
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('always advances within 26 hours (no local day is longer than 25)', () => {
|
||||
fc.assert(fc.property(instant, zone, (t, z) => localDay(t, z) < localDay(t + 26 * HOUR, z)));
|
||||
});
|
||||
|
||||
it('is deterministic: the same arguments give the same day', () => {
|
||||
fc.assert(fc.property(instant, zone, (t, z) => localDay(t, z) === localDay(t, z)));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Proves the engine-purity lint rule (eslint.config.mjs, CLAUDE.md §7) fires.
|
||||
*
|
||||
* A guard that has only ever been seen NOT firing has not been tested. Each
|
||||
* banned construct is linted as if it lived in packages/engine/src, and must be
|
||||
* reported. The same snippet placed outside the engine must not be, which proves
|
||||
* the rule is scoped and not a global ban someone will turn off in anger.
|
||||
*/
|
||||
import { ESLint } from 'eslint';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const repoRoot = fileURLToPath(new URL('../../..', import.meta.url));
|
||||
const eslint = new ESLint({ cwd: repoRoot });
|
||||
|
||||
const ENGINE_FILE = 'packages/engine/src/__purity_probe__.ts';
|
||||
const OUTSIDE_FILE = 'packages/ui/src/__purity_probe__.ts';
|
||||
|
||||
async function messages(code: string, filePath: string): Promise<string[]> {
|
||||
const [result] = await eslint.lintText(code, { filePath });
|
||||
if (result === undefined) throw new Error('ESLint returned no result');
|
||||
return result.messages.map((m) => `${m.ruleId ?? 'fatal'}: ${m.message}`);
|
||||
}
|
||||
|
||||
const IMPURE: readonly [what: string, code: string][] = [
|
||||
['Date.now()', 'export const t = Date.now();'],
|
||||
['new Date() with no argument', 'export const d = new Date();'],
|
||||
['Date() called as a function', 'export const s = Date();'],
|
||||
['Math.random()', 'export const r = Math.random();'],
|
||||
['fetch()', "export const p = fetch('/x');"],
|
||||
['localStorage', "export const v = localStorage.getItem('x');"],
|
||||
['indexedDB', "export const o = indexedDB.open('x');"],
|
||||
['document', 'export const b = document.body;'],
|
||||
['window', 'export const w = window.innerWidth;'],
|
||||
['navigator', 'export const l = navigator.language;'],
|
||||
['crypto', 'export const c = crypto.randomUUID();'],
|
||||
['setTimeout', 'setTimeout(() => 0, 1);'],
|
||||
['performance.now()', 'export const n = performance.now();'],
|
||||
['the device time zone', 'export const z = Intl.DateTimeFormat().resolvedOptions().timeZone;'],
|
||||
['a UTC day', 'export const day = new Date(0).toISOString().slice(0, 10);'],
|
||||
['a Node built-in', "import { readFileSync } from 'node:fs'; export const f = readFileSync;"]
|
||||
];
|
||||
|
||||
describe('engine purity lint rule', () => {
|
||||
it.each(IMPURE)('reports %s inside packages/engine/src', async (_what, code) => {
|
||||
const found = await messages(code, ENGINE_FILE);
|
||||
expect(found.filter((m) => m.startsWith('fatal')), 'snippet must parse').toEqual([]);
|
||||
expect(found.some((m) => /^no-restricted-/.test(m)), found.join('\n')).toBe(true);
|
||||
});
|
||||
|
||||
it.each(IMPURE)('does not report %s outside the engine', async (_what, code) => {
|
||||
const found = await messages(code, OUTSIDE_FILE);
|
||||
expect(found.filter((m) => /^no-restricted-/.test(m))).toEqual([]);
|
||||
});
|
||||
|
||||
it('allows a Date built from an explicit instant', async () => {
|
||||
expect(await messages('export const d = new Date(1761500000000);', ENGINE_FILE)).toEqual([]);
|
||||
});
|
||||
|
||||
it('the real engine sources are clean', async () => {
|
||||
const results = await eslint.lintFiles(['packages/engine/src/**/*.ts']);
|
||||
expect(results.length, 'the glob must match engine sources').toBeGreaterThan(0);
|
||||
const problems = results.flatMap((r) => r.messages.map((m) => `${r.filePath}:${m.line} ${m.message}`));
|
||||
expect(problems).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@rosea/schema",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "THE source of truth: JSON Schemas for hope sentences, care events and traces; generated types; the validator. Imports nothing from this repository.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./validate": "./src/validate.ts",
|
||||
"./schemas/*": "./schemas/*"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "node scripts/generate-types.mjs && tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json",
|
||||
"test": "vitest run --reporter=verbose"
|
||||
},
|
||||
"dependencies": {
|
||||
"ajv": "8.20.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"json-schema-to-typescript": "15.0.4",
|
||||
"typescript": "5.9.3",
|
||||
"vitest": "3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$id": "https://rosea.invalid/schema/care-event.json",
|
||||
"title": "CareEvent",
|
||||
"description": "One act of care, append-only and never edited (CLAUDE.md §6.2). The other event kinds arrive with docs/GAMEPLAY.md.",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["kind", "ts", "localDay", "from", "to", "act", "trace", "messageId", "clientVersion"],
|
||||
"properties": {
|
||||
"kind": { "const": "care" },
|
||||
"ts": { "description": "Epoch milliseconds. Stays on the device; never part of a trace.", "type": "integer", "minimum": 0 },
|
||||
"localDay": {
|
||||
"description": "The player's local day, from engine/src/time/localDay.ts and nowhere else.",
|
||||
"type": "string",
|
||||
"pattern": "^\\d{4}-\\d{2}-\\d{2}$"
|
||||
},
|
||||
"from": { "$ref": "#/definitions/publicKey" },
|
||||
"to": { "$ref": "#/definitions/publicKey" },
|
||||
"act": { "type": "string", "enum": ["water", "shade", "weed", "petals"] },
|
||||
"trace": { "type": "string", "pattern": "^petal:[a-z]+(-[a-z]+)*$" },
|
||||
"messageId": {
|
||||
"description": "A hope-library id or null. Never text: the pattern admits no space, so no sentence fits (CLAUDE.md §5.6 rule 1).",
|
||||
"oneOf": [
|
||||
{ "type": "string", "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$", "maxLength": 64 },
|
||||
{ "type": "null" }
|
||||
]
|
||||
},
|
||||
"clientVersion": { "type": "string", "pattern": "^\\d+\\.\\d+\\.\\d+$" }
|
||||
},
|
||||
"definitions": {
|
||||
"publicKey": {
|
||||
"description": "An opaque base64url public key. Its exact encoding is decided with packages/identity.",
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{32,128}$"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$id": "https://rosea.invalid/schema/hope-sentence.json",
|
||||
"title": "HopeSentence",
|
||||
"description": "One entry of the curated hope library (CLAUDE.md §6.1). The only words one player can send another are ids of these.",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["id", "text", "source", "use", "tone", "promisesOutcome"],
|
||||
"properties": {
|
||||
"id": {
|
||||
"description": "Stable, lowercase, hyphenated. A message between players carries only this.",
|
||||
"type": "string",
|
||||
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$",
|
||||
"maxLength": 64
|
||||
},
|
||||
"text": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["en"],
|
||||
"properties": {
|
||||
"en": { "type": "string", "minLength": 1 },
|
||||
"cs": { "type": "string", "minLength": 1 }
|
||||
}
|
||||
},
|
||||
"source": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["work", "author", "tradition", "translation", "publicDomain", "verifiedBy", "verifiedAt"],
|
||||
"properties": {
|
||||
"work": { "type": "string", "minLength": 1 },
|
||||
"author": { "type": ["string", "null"] },
|
||||
"tradition": {
|
||||
"description": "A lowercase tag such as `biblical` or `stoic`. `rosea` marks a line the author wrote for this game.",
|
||||
"type": "string",
|
||||
"pattern": "^[a-z]+(-[a-z]+)*$"
|
||||
},
|
||||
"translation": { "type": ["string", "null"] },
|
||||
"publicDomain": { "type": "boolean" },
|
||||
"verifiedBy": { "type": "string", "minLength": 1 },
|
||||
"verifiedAt": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" }
|
||||
}
|
||||
},
|
||||
"use": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"uniqueItems": true,
|
||||
"items": { "type": "string", "enum": ["sunset", "comfort", "thanks"] }
|
||||
},
|
||||
"tone": { "type": "string", "pattern": "^[a-z]+(-[a-z]+)*$" },
|
||||
"promisesOutcome": { "type": "boolean" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$id": "https://rosea.invalid/schema/trace.json",
|
||||
"title": "Trace",
|
||||
"description": "An anonymous shared-sky trace, Phase 4, opt-in only (CLAUDE.md §6.3). No timestamp finer than a day, no precise location, no free text, no link to the friend graph.",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["traceId", "geocell", "dayBucket", "gesture", "sig"],
|
||||
"properties": {
|
||||
"traceId": { "description": "Random and rotating.", "type": "string", "pattern": "^[A-Za-z0-9_-]{16,64}$" },
|
||||
"geocell": {
|
||||
"description": "A coarse cell id. The cell system and its density-adaptive size are decided in the Phase 4 feature doc.",
|
||||
"type": "string",
|
||||
"pattern": "^[a-z0-9]{4,16}$"
|
||||
},
|
||||
"dayBucket": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" },
|
||||
"gesture": { "type": "string", "enum": ["petal", "light"] },
|
||||
"sig": { "type": "string", "pattern": "^[A-Za-z0-9_-]{16,256}$" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// Generates TypeScript types from the JSON Schemas (CLAUDE.md §7: contract types
|
||||
// are generated, never hand-written). Output is git-ignored; `build` runs first
|
||||
// in every turbo task that needs it.
|
||||
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
||||
import { basename, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { compile } from 'json-schema-to-typescript';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
const schemaDir = join(root, 'schemas');
|
||||
const outDir = join(root, 'src', 'generated');
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
|
||||
const banner = '/* Generated by packages/schema/scripts/generate-types.mjs. Do not edit. */';
|
||||
const names = [];
|
||||
|
||||
for (const file of readdirSync(schemaDir).filter((f) => f.endsWith('.schema.json')).sort()) {
|
||||
const schema = JSON.parse(readFileSync(join(schemaDir, file), 'utf8'));
|
||||
const name = basename(file, '.schema.json');
|
||||
const ts = await compile(schema, schema.title, { bannerComment: banner, additionalProperties: false });
|
||||
writeFileSync(join(outDir, `${name}.ts`), ts);
|
||||
names.push(name);
|
||||
}
|
||||
|
||||
writeFileSync(
|
||||
join(outDir, 'index.ts'),
|
||||
`${banner}\n${names.map((n) => `export type * from './${n}.js';`).join('\n')}\n`
|
||||
);
|
||||
|
||||
console.log(`[schema] generated types for ${names.length} schemas: ${names.join(', ')}`);
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* The product's name, in one of the three places it may appear in source
|
||||
* (CLAUDE.md preamble). The other two are `apps/rosea/index.html` and the web
|
||||
* manifest, which `apps/rosea/vite.config.ts` builds from these constants.
|
||||
*
|
||||
* `Rosea` is a working name. Renaming must stay a one-commit operation: change
|
||||
* these, `index.html`, the `@rosea/*` scope and nothing else.
|
||||
*/
|
||||
|
||||
/** What the player reads. *Domi* never appears alone. */
|
||||
export const PRODUCT_NAME = 'Rosea Domi';
|
||||
|
||||
/** The short form, for the home-screen label. */
|
||||
export const PRODUCT_SHORT_NAME = 'Rosea';
|
||||
|
||||
/** The IndexedDB database name (CLAUDE.md §4). Changes together with the name. */
|
||||
export const DATABASE_NAME = 'rosea';
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './constants.js';
|
||||
export type * from './generated/index.js';
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Schema validation, for Node only: scripts, tests and the library validator.
|
||||
*
|
||||
* It is a separate entry point (`@rosea/schema/validate`) on purpose. Ajv
|
||||
* compiles validators with `new Function`, which the app's CSP forbids
|
||||
* (`script-src 'self'`, no `'unsafe-eval'`). Importing it from the browser bundle
|
||||
* would fail at runtime, not at build time. When the app needs to validate, it
|
||||
* gets standalone pre-compiled validators (GAP_ANALYSIS G0.12).
|
||||
*/
|
||||
import { Ajv, type ErrorObject, type ValidateFunction } from 'ajv';
|
||||
import careEvent from '../schemas/care-event.schema.json' with { type: 'json' };
|
||||
import hopeSentence from '../schemas/hope-sentence.schema.json' with { type: 'json' };
|
||||
import trace from '../schemas/trace.schema.json' with { type: 'json' };
|
||||
import type { CareEvent, HopeSentence, Trace } from './generated/index.js';
|
||||
|
||||
export type SchemaResult<T> =
|
||||
| { readonly ok: true; readonly value: T }
|
||||
| { readonly ok: false; readonly errors: readonly string[] };
|
||||
|
||||
const ajv = new Ajv({ allErrors: true, strict: true });
|
||||
|
||||
function wrap<T>(validate: ValidateFunction): (input: unknown) => SchemaResult<T> {
|
||||
return (input) =>
|
||||
validate(input)
|
||||
? { ok: true, value: input as T }
|
||||
: { ok: false, errors: (validate.errors ?? []).map(describe) };
|
||||
}
|
||||
|
||||
function describe(error: ErrorObject): string {
|
||||
const where = error.instancePath === '' ? '(root)' : error.instancePath;
|
||||
// Ajv already names a missing property in its message; an extra one it does not.
|
||||
const extra =
|
||||
error.keyword === 'additionalProperties'
|
||||
? ` '${String((error.params as { additionalProperty?: unknown }).additionalProperty)}'`
|
||||
: '';
|
||||
return `${where} ${error.message ?? error.keyword}${extra}`;
|
||||
}
|
||||
|
||||
export const validateHopeSentence = wrap<HopeSentence>(ajv.compile(hopeSentence));
|
||||
export const validateCareEvent = wrap<CareEvent>(ajv.compile(careEvent));
|
||||
export const validateTrace = wrap<Trace>(ajv.compile(trace));
|
||||
@@ -0,0 +1,112 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { validateCareEvent, validateHopeSentence, validateTrace } from '../src/validate.js';
|
||||
|
||||
const KEY_A = 'A'.repeat(43);
|
||||
const KEY_B = 'b_-'.repeat(15);
|
||||
|
||||
const careEvent = {
|
||||
kind: 'care',
|
||||
ts: 1761500000000,
|
||||
localDay: '2026-10-24',
|
||||
from: KEY_A,
|
||||
to: KEY_B,
|
||||
act: 'water',
|
||||
trace: 'petal:pale-pink',
|
||||
messageId: 'ps-23-4',
|
||||
clientVersion: '0.1.0'
|
||||
};
|
||||
|
||||
const sentence = {
|
||||
id: 'ps-23-4',
|
||||
text: { en: 'Placeholder text for a schema test.' },
|
||||
source: {
|
||||
work: 'Psalms 23:4',
|
||||
author: null,
|
||||
tradition: 'biblical',
|
||||
translation: 'KJV',
|
||||
publicDomain: true,
|
||||
verifiedBy: 'Test',
|
||||
verifiedAt: '2026-11-01'
|
||||
},
|
||||
use: ['sunset'],
|
||||
tone: 'gentle',
|
||||
promisesOutcome: false
|
||||
};
|
||||
|
||||
const trace = {
|
||||
traceId: 'r'.repeat(22),
|
||||
geocell: 'u2fkb',
|
||||
dayBucket: '2026-10-24',
|
||||
gesture: 'petal',
|
||||
sig: 's'.repeat(64)
|
||||
};
|
||||
|
||||
describe('hope sentence', () => {
|
||||
it('accepts a complete entry', () => {
|
||||
expect(validateHopeSentence(sentence)).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it('rejects an entry with no source', () => {
|
||||
const { source: _source, ...rest } = sentence;
|
||||
const result = validateHopeSentence(rest);
|
||||
expect(result.ok).toBe(false);
|
||||
expect(!result.ok && result.errors.join('\n')).toContain("'source'");
|
||||
});
|
||||
|
||||
it('rejects an id with a space, because an id is what travels between players', () => {
|
||||
expect(validateHopeSentence({ ...sentence, id: 'you are seen' }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects an unknown use', () => {
|
||||
expect(validateHopeSentence({ ...sentence, use: ['push-notification'] }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('care event', () => {
|
||||
it('accepts every act the rose has', () => {
|
||||
for (const act of ['water', 'shade', 'weed', 'petals']) {
|
||||
expect(validateCareEvent({ ...careEvent, act }), act).toMatchObject({ ok: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects the acts §6.2 used to list by mistake', () => {
|
||||
for (const act of ['wind', 'light']) {
|
||||
expect(validateCareEvent({ ...careEvent, act }).ok, act).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts a null messageId', () => {
|
||||
expect(validateCareEvent({ ...careEvent, messageId: null })).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it('rejects free text in messageId (CLAUDE.md §5.6 rule 1)', () => {
|
||||
expect(validateCareEvent({ ...careEvent, messageId: 'meet me at the station' }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a missing localDay', () => {
|
||||
const { localDay: _day, ...rest } = careEvent;
|
||||
expect(validateCareEvent(rest).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects any extra field, so nothing rides along unseen', () => {
|
||||
expect(validateCareEvent({ ...careEvent, note: 'hello' }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('trace', () => {
|
||||
it('accepts a day-bucketed trace', () => {
|
||||
expect(validateTrace(trace)).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it('rejects a day bucket finer than a day', () => {
|
||||
expect(validateTrace({ ...trace, dayBucket: '2026-10-24T18:42' }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a timestamp field', () => {
|
||||
expect(validateTrace({ ...trace, ts: 1761500000000 }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a precise coordinate in place of a cell', () => {
|
||||
expect(validateTrace({ ...trace, geocell: '50.0755,14.4378' }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "@rosea/ui",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Svelte components, tokens and copy/. Renders what the engine returns; decides nothing.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"svelte": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"svelte": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
},
|
||||
"./copy": "./src/copy/en.ts",
|
||||
"./tokens.css": "./src/tokens.css"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "svelte-check --threshold error --output human",
|
||||
"typecheck": "svelte-check --threshold error --output human",
|
||||
"test": "vitest run --reporter=verbose"
|
||||
},
|
||||
"dependencies": {
|
||||
"@rosea/schema": "workspace:*"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"svelte": "^5.56.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/vite-plugin-svelte": "5.1.1",
|
||||
"@testing-library/svelte": "5.4.2",
|
||||
"jsdom": "25.0.1",
|
||||
"svelte": "5.56.9",
|
||||
"svelte-check": "4.7.6",
|
||||
"typescript": "5.9.3",
|
||||
"vite": "6.4.3",
|
||||
"vitest": "3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<script lang="ts">
|
||||
import { PRODUCT_NAME } from '@rosea/schema';
|
||||
import { en } from './copy/en.js';
|
||||
</script>
|
||||
|
||||
<main class="shell">
|
||||
<h1>{PRODUCT_NAME}</h1>
|
||||
<p>{en.shell.preparing}</p>
|
||||
</main>
|
||||
|
||||
<style>
|
||||
.shell {
|
||||
min-height: 100dvh;
|
||||
display: grid;
|
||||
place-content: center;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-4);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-family: var(--font-display);
|
||||
font-weight: 400;
|
||||
font-size: clamp(2rem, 8vw, 3.5rem);
|
||||
letter-spacing: 0.02em;
|
||||
color: var(--rose);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: var(--ink-soft);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Every string a player reads lives under copy/ (CLAUDE.md §7) and passes
|
||||
* `pnpm lint:copy`. Plain English; Czech arrives as `cs.ts` with the same shape.
|
||||
*
|
||||
* The product name is not repeated here: it comes from @rosea/schema, one of the
|
||||
* three places it may live.
|
||||
*/
|
||||
export const en = {
|
||||
shell: {
|
||||
/** The one line on the Phase 0 page. True, calm, and asks nothing. */
|
||||
preparing: 'The garden is being prepared.'
|
||||
}
|
||||
} as const;
|
||||
|
||||
export type Copy = typeof en;
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as Shell } from './Shell.svelte';
|
||||
export { en, type Copy } from './copy/en.js';
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Design tokens. Placeholders until docs/ART.md sets the palette: they exist so
|
||||
* components reference tokens from the first commit, never raw colours.
|
||||
* System fonts only: nothing is fetched from a CDN (CLAUDE.md §4).
|
||||
*/
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
|
||||
--paper: #fbf6f1;
|
||||
--ink: #2b2324;
|
||||
--ink-soft: #6b5d5e;
|
||||
--rose: #b4485e;
|
||||
|
||||
--font-body: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
--font-display: Georgia, 'Times New Roman', serif;
|
||||
|
||||
--space-1: 0.25rem;
|
||||
--space-2: 0.5rem;
|
||||
--space-3: 1rem;
|
||||
--space-4: 1.5rem;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--paper: #1d1819;
|
||||
--ink: #f1e8e6;
|
||||
--ink-soft: #b8a9a8;
|
||||
--rose: #e8899b;
|
||||
}
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
font-family: var(--font-body);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export default {};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { PRODUCT_NAME } from '@rosea/schema';
|
||||
import { cleanup, render, screen } from '@testing-library/svelte';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import Shell from '../src/Shell.svelte';
|
||||
import { en } from '../src/copy/en.js';
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe('Shell', () => {
|
||||
it('names the product in the page heading, from the schema constant', () => {
|
||||
render(Shell);
|
||||
expect(screen.getByRole('heading', { level: 1 }).textContent).toBe(PRODUCT_NAME);
|
||||
});
|
||||
|
||||
it('shows its one line from copy/, and no control to press', () => {
|
||||
render(Shell);
|
||||
expect(screen.getByText(en.shell.preparing)).toBeTruthy();
|
||||
expect(screen.queryAllByRole('button')).toEqual([]);
|
||||
expect(screen.queryAllByRole('link')).toEqual([]);
|
||||
});
|
||||
|
||||
it('is a landmark, so a screen reader can find it', () => {
|
||||
render(Shell);
|
||||
expect(screen.getByRole('main')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node", "svelte"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.svelte", "test/**/*.ts", "vitest.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { svelte } from '@sveltejs/vite-plugin-svelte';
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [svelte()],
|
||||
// Svelte resolves its client build only under the `browser` condition.
|
||||
resolve: { conditions: ['browser'] },
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
include: ['test/**/*.test.ts']
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user