Add document data model and validation

Define the sections/records/items schema with secret-flagged fields and
a validator with tests. build.js bundles model.js. The PDF-derived seed
lives in the gitignored data/ directory.

Closes #3

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 08:04:03 -05:00
parent 9fa6096a6c
commit 2c713f3a9b
3 changed files with 167 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ const read = (p) => readFileSync(join(root, 'src', p), 'utf8');
const out = read('index.html')
.replace('/*__CSS__*/', () => read('style.css'))
// Plain-script bundle: drop ES `export` so modules concatenate into one scope.
.replace('/*__JS__*/', () => [read('crypto.js').replace(/^export /gm, ''), read('app.js')].join('\n'))
.replace('/*__JS__*/', () => ['crypto.js', 'model.js'].map((f) => read(f).replace(/^export /gm, '')).concat(read('app.js')).join('\n'))
.replace('/*__PAYLOAD__*/', () => '');
mkdirSync(join(root, 'dist'), { recursive: true });

113
src/model.js Normal file
View File

@@ -0,0 +1,113 @@
// Data model for the document (plaintext JSON before encryption).
// Pure functions, no DOM; runs in browsers and Node. build.js strips `export`.
//
// Document:
// { schemaVersion: 1,
// meta: { owner, title, lastUpdated: 'YYYY-MM-DD' },
// sections: [ Section ] }
//
// Section (ordered). `kind` decides which body it has:
// 'text' -> { body: string } free narrative ("Start here")
// 'records' -> { records: [Record] } accounts, people, places, items
// 'steps' -> { items: [Item] } ordered instructions (wind-down)
// 'checklist' -> { items: [Item] } things still to add/do
// Every section has { id, title, kind } and may have { intro: string }.
//
// Record: { id, title, status: 'ok'|'tbd', updated: 'YYYY-MM-DD',
// fields: [{ label, value, secret?: boolean }], notes?: string }
// Item: { id, text, status: 'open'|'done'|'tbd', detail?: string }
//
// Ids are unique across the whole document. `secret` fields are masked
// in the UI and optionally in print output.
export const SCHEMA_VERSION = 1;
export const SECTION_KINDS = ['text', 'records', 'steps', 'checklist'];
export const RECORD_STATUSES = ['ok', 'tbd'];
export const ITEM_STATUSES = ['open', 'done', 'tbd'];
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
const isStr = (v) => typeof v === 'string';
const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
export function emptyDocument(owner = '', title = 'In the event of my death or incapacity') {
return {
schemaVersion: SCHEMA_VERSION,
meta: { owner, title, lastUpdated: new Date().toISOString().slice(0, 10) },
sections: [],
};
}
// Returns a list of human-readable problems; empty means valid.
export function validate(doc) {
const errs = [];
const seen = new Set();
const checkId = (id, where) => {
if (!isStr(id) || !id) errs.push(`${where}: missing id`);
else if (seen.has(id)) errs.push(`${where}: duplicate id "${id}"`);
else seen.add(id);
};
if (!isObj(doc)) return ['document must be an object'];
if (doc.schemaVersion !== SCHEMA_VERSION) errs.push(`schemaVersion must be ${SCHEMA_VERSION}`);
if (!isObj(doc.meta)) errs.push('meta must be an object');
else {
if (!isStr(doc.meta.owner)) errs.push('meta.owner must be a string');
if (!isStr(doc.meta.title)) errs.push('meta.title must be a string');
if (!DATE_RE.test(doc.meta.lastUpdated ?? '')) errs.push('meta.lastUpdated must be YYYY-MM-DD');
}
if (!Array.isArray(doc.sections)) return [...errs, 'sections must be an array'];
doc.sections.forEach((s, i) => {
const where = `sections[${i}]`;
if (!isObj(s)) return errs.push(`${where}: must be an object`);
checkId(s.id, where);
if (!isStr(s.title) || !s.title) errs.push(`${where}: missing title`);
if (s.intro !== undefined && !isStr(s.intro)) errs.push(`${where}: intro must be a string`);
if (!SECTION_KINDS.includes(s.kind)) return errs.push(`${where}: unknown kind "${s.kind}"`);
if (s.kind === 'text') {
if (!isStr(s.body)) errs.push(`${where}: text section needs a body string`);
} else if (s.kind === 'records') {
if (!Array.isArray(s.records)) return errs.push(`${where}: records must be an array`);
s.records.forEach((r, j) => checkRecord(r, `${where}.records[${j}]`));
} else {
if (!Array.isArray(s.items)) return errs.push(`${where}: items must be an array`);
s.items.forEach((it, j) => checkItem(it, `${where}.items[${j}]`));
}
});
function checkRecord(r, where) {
if (!isObj(r)) return errs.push(`${where}: must be an object`);
checkId(r.id, where);
if (!isStr(r.title) || !r.title) errs.push(`${where}: missing title`);
if (!RECORD_STATUSES.includes(r.status)) errs.push(`${where}: bad status "${r.status}"`);
if (!DATE_RE.test(r.updated ?? '')) errs.push(`${where}: updated must be YYYY-MM-DD`);
if (r.notes !== undefined && !isStr(r.notes)) errs.push(`${where}: notes must be a string`);
if (!Array.isArray(r.fields)) return errs.push(`${where}: fields must be an array`);
r.fields.forEach((f, k) => {
const fw = `${where}.fields[${k}]`;
if (!isObj(f)) return errs.push(`${fw}: must be an object`);
if (!isStr(f.label) || !f.label) errs.push(`${fw}: missing label`);
if (!isStr(f.value)) errs.push(`${fw}: value must be a string`);
if (f.secret !== undefined && typeof f.secret !== 'boolean') errs.push(`${fw}: secret must be a boolean`);
});
}
function checkItem(it, where) {
if (!isObj(it)) return errs.push(`${where}: must be an object`);
checkId(it.id, where);
if (!isStr(it.text) || !it.text) errs.push(`${where}: missing text`);
if (!ITEM_STATUSES.includes(it.status)) errs.push(`${where}: bad status "${it.status}"`);
if (it.detail !== undefined && !isStr(it.detail)) errs.push(`${where}: detail must be a string`);
}
return errs;
}
export function assertValid(doc) {
const errs = validate(doc);
if (errs.length) throw new Error('Invalid document:\n- ' + errs.join('\n- '));
return doc;
}

53
test/model.test.js Normal file
View File

@@ -0,0 +1,53 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { existsSync, readFileSync } from 'node:fs';
import { validate, emptyDocument, assertValid } from '../src/model.js';
const good = () => ({
schemaVersion: 1,
meta: { owner: 'A', title: 'T', lastUpdated: '2022-04-14' },
sections: [
{ id: 's-text', title: 'Intro', kind: 'text', body: 'hi' },
{ id: 's-rec', title: 'Bank', kind: 'records', records: [
{ id: 'r1', title: 'Acct', status: 'ok', updated: '2022-04-14',
fields: [{ label: 'PIN', value: '', secret: true }], notes: 'n' } ] },
{ id: 's-steps', title: 'Steps', kind: 'steps', items: [
{ id: 'i1', text: 'Do it', status: 'open', detail: 'how' } ] },
{ id: 's-list', title: 'Add', kind: 'checklist', items: [
{ id: 'i2', text: 'More', status: 'tbd' } ] },
],
});
test('valid document passes; emptyDocument is valid', () => {
assert.deepEqual(validate(good()), []);
assert.deepEqual(validate(emptyDocument('Me')), []);
assert.equal(assertValid(good()).meta.owner, 'A');
});
test('rejects structural problems', () => {
const cases = [
[(d) => { d.schemaVersion = 2; }, /schemaVersion/],
[(d) => { d.meta.lastUpdated = 'yesterday'; }, /lastUpdated/],
[(d) => { d.sections[0].kind = 'weird'; }, /unknown kind/],
[(d) => { d.sections[1].records[0].status = 'maybe'; }, /bad status/],
[(d) => { d.sections[1].records[0].fields[0].secret = 'yes'; }, /secret must be a boolean/],
[(d) => { d.sections[1].records[0].fields[0].value = 5; }, /value must be a string/],
[(d) => { d.sections[2].items[0].status = 'x'; }, /bad status/],
[(d) => { d.sections[1].records[0].id = 's-text'; }, /duplicate id/],
[(d) => { delete d.sections[3].items; }, /items must be an array/],
[(d) => { delete d.sections[0].body; }, /body/],
];
for (const [mutate, re] of cases) {
const d = good();
mutate(d);
assert.match(validate(d).join('\n'), re);
}
assert.throws(() => assertValid({}), /Invalid document/);
assert.deepEqual(validate(null), ['document must be an object']);
});
// data/ is gitignored (private), so this only runs on a machine that has the seed.
test('data/seed.json, when present, is valid', { skip: !existsSync('data/seed.json') }, () => {
const seed = JSON.parse(readFileSync('data/seed.json', 'utf8'));
assert.deepEqual(validate(seed), []);
});