/** * 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 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'; export type SchemaResult = | { readonly ok: true; readonly value: T } | { readonly ok: false; readonly errors: readonly string[] }; const ajv = new Ajv({ allErrors: true, strict: true }); function wrap(validate: ValidateFunction): (input: unknown) => SchemaResult { 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(ajv.compile(hopeSentence)); export const validateCareEvent = wrap(ajv.compile(careEvent)); export const validateSentenceOpened = wrap(ajv.compile(sentenceOpened)); export const validateTrace = wrap(ajv.compile(trace));