feat(domain): canonical anatomical sheet document, integrity rules, tests

This commit is contained in:
bchanot committed 2026-10-08 23:42:42 +02:00
1 parent aea8902711
commit 36812f4625
13 files changed
+1849

No files matched your search

@@ -0,0 +1,43 @@
import {
AnatomicalSheetDocumentSchema,
SHEET_DOCUMENT_SCHEMA_VERSION,
type AnatomicalSheetDocument,
type LocalizedText,
} from './schema'
export interface NewSheetDocumentParams {
species_id: string
name: LocalizedText
}
export const MAIN_VIEW_ID = 'view-main'
/**
* Starting point of a new sheet: shape-valid so it can be saved as a draft
* at once, but not publishable until the main view gets its SVG asset.
*/
export function createEmptySheetDocument(
params: NewSheetDocumentParams,
): AnatomicalSheetDocument {
return AnatomicalSheetDocumentSchema.parse({
schema_version: SHEET_DOCUMENT_SCHEMA_VERSION,
species_id: params.species_id,
name: params.name,
description: {},
scope_disclaimer: {},
attribution: { authors: [], license: null, notes: null },
vertebral_config: { regions: [] },
categories: [],
views: [
{
id: MAIN_VIEW_ID,
kind: 'main',
name: { fr: 'Vue principale', en: 'Main view' },
svg_asset_id: null,
view_box: null,
},
],
annotations: [],
finding_zones: [],
})
}
@@ -0,0 +1,3 @@
export * from './schema'
export * from './validate'
export * from './create'
@@ -0,0 +1,280 @@
import { z } from 'zod'
/**
* Canonical anatomical sheet document, schema_version 1.
*
* Shape contract of docs/development/ANATOMICAL_SHEET_MODEL.md §2. Every
* object is strict: a canonical document must not silently carry fields no
* version of the schema defines. Cross-references (view ids, zone ids…) are
* checked by validateSheetDocument, not here, so a draft with dangling
* references can still be saved.
*/
export const SHEET_DOCUMENT_SCHEMA_VERSION = 1
/** Ids are never derived from labels, so translations never move them. */
export const STABLE_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/
export const StableIdSchema = z.string().regex(STABLE_ID_PATTERN)
/** Region codes are free (C, T, L, S, Cd for the horse), case included. */
export const RegionCodeSchema = z
.string()
.regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,15}$/)
export const LocalizedTextSchema = z
.object({ fr: z.string().min(1), en: z.string().min(1) })
.strict()
export const LocalizedOptionalTextSchema = z
.object({ fr: z.string().optional(), en: z.string().optional() })
.strict()
export const VertebralRegionSchema = z
.object({
code: RegionCodeSchema,
name: LocalizedTextSchema,
count: z.number().int().min(1),
})
.strict()
const HexColorSchema = z.string().regex(/^#[0-9a-fA-F]{6}$/)
export const AnnotationCategorySchema = z
.object({
id: StableIdSchema,
name: LocalizedTextSchema,
color: HexColorSchema.nullable(),
})
.strict()
const CoordinateSchema = z.number().finite()
export const ViewBoxSchema = z
.object({
min_x: CoordinateSchema,
min_y: CoordinateSchema,
width: CoordinateSchema.positive(),
height: CoordinateSchema.positive(),
})
.strict()
/** Null asset on a detail view means "parent asset cropped by view_box". */
const viewCommon = {
id: StableIdSchema,
name: LocalizedTextSchema,
svg_asset_id: z.string().uuid().nullable(),
view_box: ViewBoxSchema.nullable(),
}
const MainViewSchema = z
.object({ ...viewCommon, kind: z.literal('main') })
.strict()
const DetailViewSchema = z
.object({
...viewCommon,
kind: z.literal('detail'),
parent_view_id: StableIdSchema,
})
.strict()
/** Views form a tree: a detail names its parent, any depth. */
export const SheetViewSchema = z.discriminatedUnion('kind', [
MainViewSchema,
DetailViewSchema,
])
const CircleSchema = z
.object({
type: z.literal('circle'),
cx: CoordinateSchema,
cy: CoordinateSchema,
r: CoordinateSchema.positive(),
})
.strict()
const PolygonSchema = z
.object({
type: z.literal('polygon'),
points: z.array(z.tuple([CoordinateSchema, CoordinateSchema])).min(3),
})
.strict()
const PathSchema = z
.object({ type: z.literal('path'), d: z.string().min(1) })
.strict()
export const GeometrySchema = z.discriminatedUnion('type', [
CircleSchema,
PolygonSchema,
PathSchema,
])
/** Explicit on every annotation: absence no longer carries meaning. */
export const LateralitySchema = z.enum([
'unpaired',
'bilateral',
'left',
'right',
])
const annotationCommon = {
id: StableIdSchema,
view_id: StableIdSchema,
category_id: StableIdSchema,
laterality: LateralitySchema,
geometry: GeometrySchema.nullable(),
}
/** Observable annotations link to findings through one explicit field. */
const observableFields = {
...annotationCommon,
name: LocalizedTextSchema,
finding_zone_id: StableIdSchema.nullable(),
vertebral_region_code: RegionCodeSchema.nullable(),
}
const PointAnnotationSchema = z
.object({ ...observableFields, kind: z.literal('point') })
.strict()
const ZoneAnnotationSchema = z
.object({ ...observableFields, kind: z.literal('zone') })
.strict()
/** Navigation only: a trigger never carries findings. */
const DetailTriggerAnnotationSchema = z
.object({
...annotationCommon,
kind: z.literal('detail_trigger'),
name: LocalizedTextSchema.nullable(),
opens_view_id: StableIdSchema,
})
.strict()
export const AnnotationSchema = z.discriminatedUnion('kind', [
PointAnnotationSchema,
ZoneAnnotationSchema,
DetailTriggerAnnotationSchema,
])
export const SourceRefSchema = z
.object({
type: z.enum(['manual', 'journal', 'database', 'web']),
citation: z.string().min(1),
url: z.string().url().optional(),
})
.strict()
export type SourceRef = z.infer<typeof SourceRefSchema>
export type LocalizedText = z.infer<typeof LocalizedTextSchema>
export type LocalizedOptionalText = z.infer<typeof LocalizedOptionalTextSchema>
/** Parsed node: every optional key of the authoring form is filled in. */
export interface FindingNode {
id: string
name: LocalizedText
description: LocalizedOptionalText
requires_vet_referral: boolean
sources: SourceRef[]
children: FindingNode[]
}
/** Authoring form: leaves stay lean, hundreds of them carry no empty keys. */
export interface FindingNodeInput {
id: string
name: LocalizedText
description?: LocalizedOptionalText
requires_vet_referral?: boolean
sources?: SourceRef[]
children?: FindingNodeInput[]
}
export const FindingNodeSchema: z.ZodType<
FindingNode,
z.ZodTypeDef,
FindingNodeInput
> = z.lazy(() =>
z
.object({
id: StableIdSchema,
name: LocalizedTextSchema,
description: LocalizedOptionalTextSchema.default({}),
requires_vet_referral: z.boolean().default(false),
sources: z.array(SourceRefSchema).default([]),
children: z.array(FindingNodeSchema).default([]),
})
.strict(),
)
/** Typed business buckets; creators may add their own as 'custom'. */
export const FindingCategoryKindSchema = z.enum([
'dysfunction',
'observation',
'anamnesis',
'custom',
])
export const FindingCategorySchema = z
.object({
id: StableIdSchema,
kind: FindingCategoryKindSchema,
name: LocalizedTextSchema,
description: LocalizedOptionalTextSchema.default({}),
children: z.array(FindingNodeSchema),
})
.strict()
export const FindingZoneSchema = z
.object({
id: StableIdSchema,
name: LocalizedTextSchema,
categories: z.array(FindingCategorySchema),
})
.strict()
const AttributionSchema = z
.object({
authors: z.array(z.string().min(1)),
license: z.string().min(1).nullable(),
notes: z.string().min(1).nullable(),
})
.strict()
const VertebralConfigSchema = z
.object({ regions: z.array(VertebralRegionSchema) })
.strict()
export const AnatomicalSheetDocumentSchema = z
.object({
schema_version: z.literal(SHEET_DOCUMENT_SCHEMA_VERSION),
species_id: StableIdSchema,
name: LocalizedTextSchema,
description: LocalizedOptionalTextSchema,
scope_disclaimer: LocalizedOptionalTextSchema,
attribution: AttributionSchema,
vertebral_config: VertebralConfigSchema,
categories: z.array(AnnotationCategorySchema),
views: z.array(SheetViewSchema),
annotations: z.array(AnnotationSchema),
finding_zones: z.array(FindingZoneSchema),
})
.strict()
export type AnatomicalSheetDocument = z.output<
typeof AnatomicalSheetDocumentSchema
>
export type AnatomicalSheetDocumentInput = z.input<
typeof AnatomicalSheetDocumentSchema
>
export type VertebralRegion = z.infer<typeof VertebralRegionSchema>
export type AnnotationCategory = z.infer<typeof AnnotationCategorySchema>
export type ViewBox = z.infer<typeof ViewBoxSchema>
export type SheetView = z.infer<typeof SheetViewSchema>
export type Geometry = z.infer<typeof GeometrySchema>
export type Laterality = z.infer<typeof LateralitySchema>
export type Annotation = z.infer<typeof AnnotationSchema>
export type FindingCategoryKind = z.infer<typeof FindingCategoryKindSchema>
export type FindingCategory = z.output<typeof FindingCategorySchema>
export type FindingZone = z.output<typeof FindingZoneSchema>
@@ -0,0 +1,426 @@
import type {
AnatomicalSheetDocument,
Annotation,
FindingNode,
SheetView,
} from './schema'
/**
* Integrity tier of the sheet model (ANATOMICAL_SHEET_MODEL.md §2.1).
*
* The shape tier (Zod) accepts dangling references so drafts can be saved
* mid-edit; this tier lists every inconsistency for the editor and gates
* publication. Each rule is one function; codes are part of the contract
* shared with the SQL re-check (private.sheet_document_issues).
*/
export type SheetIssueSeverity = 'error' | 'warning'
export interface SheetIssue {
code: string
severity: SheetIssueSeverity
path: string
message: string
}
type Rule = (doc: AnatomicalSheetDocument) => SheetIssue[]
type ObservableAnnotation = Exclude<Annotation, { kind: 'detail_trigger' }>
type TriggerAnnotation = Extract<Annotation, { kind: 'detail_trigger' }>
type DetailView = Extract<SheetView, { kind: 'detail' }>
/** A sibling level of the finding tree: categories or node children. */
interface FindingLevelItem {
id: string
children: readonly FindingNode[]
}
function error(code: string, path: string, message: string): SheetIssue {
return { code, severity: 'error', path, message }
}
function warning(code: string, path: string, message: string): SheetIssue {
return { code, severity: 'warning', path, message }
}
/** Indexes of entries whose value already appeared earlier in the list. */
function repeatedIndexes(values: readonly string[]): number[] {
const seen = new Set<string>()
const repeated: number[] = []
values.forEach((value, index) => {
if (seen.has(value)) repeated.push(index)
seen.add(value)
})
return repeated
}
function duplicateIssues(
values: readonly string[],
code: string,
pathOf: (index: number) => string,
): SheetIssue[] {
return repeatedIndexes(values).map((index) =>
error(code, pathOf(index), `Duplicate id "${values[index]}"`),
)
}
function isObservable(
annotation: Annotation,
): annotation is ObservableAnnotation {
return annotation.kind !== 'detail_trigger'
}
function isTrigger(annotation: Annotation): annotation is TriggerAnnotation {
return annotation.kind === 'detail_trigger'
}
function viewsById(doc: AnatomicalSheetDocument): Map<string, SheetView> {
const byId = new Map<string, SheetView>()
for (const view of doc.views) if (!byId.has(view.id)) byId.set(view.id, view)
return byId
}
/** Rendering starts from a single root drawing. */
const checkMainViewCount: Rule = (doc) => {
const count = doc.views.filter((view) => view.kind === 'main').length
if (count === 1) return []
return [
error('view.main.count', 'views', `Expected 1 main view, found ${count}`),
]
}
const checkViewIdsUnique: Rule = (doc) =>
duplicateIssues(
doc.views.map((view) => view.id),
'view.id.duplicate',
(index) => `views[${index}].id`,
)
const checkViewParentsExist: Rule = (doc) => {
const byId = viewsById(doc)
return doc.views.flatMap((view, index) =>
view.kind === 'detail' && !byId.has(view.parent_view_id)
? [
error(
'view.parent.missing',
`views[${index}].parent_view_id`,
`Parent view "${view.parent_view_id}" does not exist`,
),
]
: [],
)
}
/**
* True when the parent chain loops before reaching the main view. A
* missing parent ends the walk: that case is view.parent.missing.
*/
function loopsBeforeMain(view: DetailView, byId: Map<string, SheetView>) {
const visited = new Set<string>([view.id])
let current: SheetView = view
while (current.kind === 'detail') {
const parent = byId.get(current.parent_view_id)
if (!parent) return false
if (visited.has(parent.id)) return true
visited.add(parent.id)
current = parent
}
return false
}
const checkViewParentCycles: Rule = (doc) => {
const byId = viewsById(doc)
return doc.views.flatMap((view, index) =>
view.kind === 'detail' && loopsBeforeMain(view, byId)
? [
error(
'view.parent.cycle',
`views[${index}].parent_view_id`,
`Parent chain of "${view.id}" never reaches the main view`,
),
]
: [],
)
}
function isOpenedFromParent(
view: DetailView,
doc: AnatomicalSheetDocument,
): boolean {
return doc.annotations.some(
(annotation) =>
isTrigger(annotation) &&
annotation.opens_view_id === view.id &&
annotation.view_id === view.parent_view_id,
)
}
/** A detail view nobody can open is dead content for the practitioner. */
const checkViewsReachable: Rule = (doc) => {
const byId = viewsById(doc)
return doc.views.flatMap((view, index) =>
view.kind === 'detail' &&
byId.has(view.parent_view_id) &&
!isOpenedFromParent(view, doc)
? [
error(
'view.unreachable',
`views[${index}]`,
`No detail_trigger in "${view.parent_view_id}" opens "${view.id}"`,
),
]
: [],
)
}
/** Every view must have something to draw: its own asset or a crop. */
function viewAssetIssue(view: SheetView, index: number): SheetIssue[] {
if (view.svg_asset_id !== null) return []
if (view.kind === 'main') {
return [
error(
'view.asset.missing',
`views[${index}].svg_asset_id`,
`Main view "${view.id}" has no SVG asset`,
),
]
}
if (view.view_box !== null) return []
return [
error(
'view.asset.missing',
`views[${index}].view_box`,
`Detail view "${view.id}" has neither an asset nor a view_box`,
),
]
}
const checkViewAssets: Rule = (doc) => doc.views.flatMap(viewAssetIssue)
/** Report points are keyed by annotation id across every view. */
const checkAnnotationIdsUnique: Rule = (doc) =>
duplicateIssues(
doc.annotations.map((annotation) => annotation.id),
'annotation.id.duplicate',
(index) => `annotations[${index}].id`,
)
const checkAnnotationViews: Rule = (doc) => {
const byId = viewsById(doc)
return doc.annotations.flatMap((annotation, index) =>
byId.has(annotation.view_id)
? []
: [
error(
'annotation.view.missing',
`annotations[${index}].view_id`,
`View "${annotation.view_id}" does not exist`,
),
],
)
}
const checkAnnotationCategories: Rule = (doc) => {
const ids = new Set(doc.categories.map((category) => category.id))
return doc.annotations.flatMap((annotation, index) =>
ids.has(annotation.category_id)
? []
: [
error(
'annotation.category.missing',
`annotations[${index}].category_id`,
`Category "${annotation.category_id}" does not exist`,
),
],
)
}
/** A trigger opens a direct child of the view it is drawn in. */
function opensChildOfOwnView(
trigger: TriggerAnnotation,
byId: Map<string, SheetView>,
): boolean {
const target = byId.get(trigger.opens_view_id)
return target?.kind === 'detail' && target.parent_view_id === trigger.view_id
}
const checkTriggerTargets: Rule = (doc) => {
const byId = viewsById(doc)
return doc.annotations.flatMap((annotation, index) =>
isTrigger(annotation) && !opensChildOfOwnView(annotation, byId)
? [
error(
'annotation.opens_view.invalid',
`annotations[${index}].opens_view_id`,
`"${annotation.opens_view_id}" is not a detail child of ` +
`"${annotation.view_id}"`,
),
]
: [],
)
}
const checkAnnotationFindingZones: Rule = (doc) => {
const ids = new Set(doc.finding_zones.map((zone) => zone.id))
return doc.annotations.flatMap((annotation, index) =>
isObservable(annotation) &&
annotation.finding_zone_id !== null &&
!ids.has(annotation.finding_zone_id)
? [
error(
'annotation.finding_zone.missing',
`annotations[${index}].finding_zone_id`,
`Finding zone "${annotation.finding_zone_id}" does not exist`,
),
]
: [],
)
}
const checkAnnotationRegions: Rule = (doc) => {
const codes = new Set(doc.vertebral_config.regions.map((r) => r.code))
return doc.annotations.flatMap((annotation, index) =>
isObservable(annotation) &&
annotation.vertebral_region_code !== null &&
!codes.has(annotation.vertebral_region_code)
? [
error(
'annotation.region.missing',
`annotations[${index}].vertebral_region_code`,
`Vertebral region "${annotation.vertebral_region_code}" ` +
'is not configured',
),
]
: [],
)
}
/** Allowed in a draft, but a click on it would offer nothing to record. */
const checkAnnotationsHaveFindings: Rule = (doc) =>
doc.annotations.flatMap((annotation, index) =>
isObservable(annotation) && annotation.finding_zone_id === null
? [
warning(
'annotation.no_findings',
`annotations[${index}].finding_zone_id`,
`Annotation "${annotation.id}" is linked to no finding zone`,
),
]
: [],
)
const checkRegionCodesUnique: Rule = (doc) =>
duplicateIssues(
doc.vertebral_config.regions.map((region) => region.code),
'region.code.duplicate',
(index) => `vertebral_config.regions[${index}].code`,
)
const checkCategoryIdsUnique: Rule = (doc) =>
duplicateIssues(
doc.categories.map((category) => category.id),
'category.id.duplicate',
(index) => `categories[${index}].id`,
)
const checkFindingZoneIdsUnique: Rule = (doc) =>
duplicateIssues(
doc.finding_zones.map((zone) => zone.id),
'finding_zone.id.duplicate',
(index) => `finding_zones[${index}].id`,
)
/**
* Findings are addressed by (zone, path[]) as Finding.path does today, so
* ids only need to be unique among siblings, at every depth.
*/
function siblingIssues(
nodes: readonly FindingLevelItem[],
path: string,
): SheetIssue[] {
const own = duplicateIssues(
nodes.map((node) => node.id),
'finding.id.duplicate',
(index) => `${path}[${index}].id`,
)
const nested = nodes.flatMap((node, index) =>
siblingIssues(node.children, `${path}[${index}].children`),
)
return [...own, ...nested]
}
const checkFindingSiblings: Rule = (doc) =>
doc.finding_zones.flatMap((zone, index) =>
siblingIssues(zone.categories, `finding_zones[${index}].categories`),
)
/** Allowed in a draft, but nothing on the drawing can reach this zone. */
const checkFindingZonesReferenced: Rule = (doc) => {
const referenced = new Set(
doc.annotations.filter(isObservable).map((a) => a.finding_zone_id),
)
return doc.finding_zones.flatMap((zone, index) =>
referenced.has(zone.id)
? []
: [
warning(
'finding_zone.unreferenced',
`finding_zones[${index}]`,
`No annotation points to finding zone "${zone.id}"`,
),
],
)
}
const RULES: readonly Rule[] = [
checkMainViewCount,
checkViewIdsUnique,
checkViewParentsExist,
checkViewParentCycles,
checkViewsReachable,
checkViewAssets,
checkAnnotationIdsUnique,
checkAnnotationViews,
checkAnnotationCategories,
checkTriggerTargets,
checkAnnotationFindingZones,
checkAnnotationRegions,
checkAnnotationsHaveFindings,
checkRegionCodesUnique,
checkCategoryIdsUnique,
checkFindingZoneIdsUnique,
checkFindingSiblings,
checkFindingZonesReferenced,
]
/** Lists every integrity issue of a shape-valid document. */
export function validateSheetDocument(
doc: AnatomicalSheetDocument,
): SheetIssue[] {
return RULES.flatMap((rule) => rule(doc))
}
/** Warnings never block publication; errors always do. */
export function isPublishable(issues: readonly SheetIssue[]): boolean {
return !issues.some((issue) => issue.severity === 'error')
}
export class SheetValidationError extends Error {
readonly issues: SheetIssue[]
constructor(issues: SheetIssue[]) {
const errors = issues.filter((issue) => issue.severity === 'error')
super(
`Sheet document is not publishable: ${errors.length} error(s), ` +
`first: ${errors[0]?.code ?? 'none'}`,
)
this.name = 'SheetValidationError'
this.issues = issues
}
}
/** TypeScript-side publication gate, mirrored by SQL at publish time. */
export function assertPublishable(doc: AnatomicalSheetDocument): void {
const issues = validateSheetDocument(doc)
if (!isPublishable(issues)) throw new SheetValidationError(issues)
}
+1
View File
@@ -0,0 +1 @@
export * from './anatomical-sheet'