chore(workspace): R5.7 delete packages/anatomy and packages/domain

The TS pipeline, domain, upload script and legacy scripts leave; xmldom out of the
lockfile, Dockerfile copies trimmed. LEDGER.tsv (407 cases) and FILES.tsv (112 files)
record each disposition; r4 and r5 census tests guard the tree, lockfile and
production imports.
This commit is contained in:
bchanot committed 2026-10-25 04:00:07 +01:00
1 parent 0da7d3ab9f
commit 1b359598ab
124 files changed
+910 -17475

No files matched your search

-20
View File
@@ -1,20 +0,0 @@
import globals from 'globals'
import tseslint from 'typescript-eslint'
export default tseslint.config(
{ ignores: ['node_modules/**'] },
{
files: ['**/*.ts'],
extends: [...tseslint.configs.recommended],
languageOptions: {
globals: { ...globals.node, ...globals.es2022 },
},
rules: {
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_' },
],
},
},
)
-37
View File
@@ -1,37 +0,0 @@
{
"name": "@faunosteo/anatomy",
"version": "0.1.0",
"private": true,
"description": "Faunosteo anatomy tooling: deterministic legacy importer, curation pipeline (changeset \u2192 draft, report migration map) and the pure annotation-layer renderer shared with the application",
"license": "MIT",
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts",
"./render": "./src/render/index.ts"
},
"scripts": {
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest",
"test:run": "vitest run",
"lint": "eslint . --max-warnings 0",
"build": "tsc -p tsconfig.json --noEmit",
"import:equine": "tsx src/cli/import-equine.ts"
},
"dependencies": {
"@faunosteo/domain": "workspace:*",
"zod": "^3.24.1"
},
"devDependencies": {
"@types/node": "^20.19.41",
"@xmldom/xmldom": "^0.9.8",
"eslint": "^9.17.0",
"globals": "^15.14.0",
"prettier": "^3.4.2",
"tsx": "^4.19.2",
"typescript": "^5.7.2",
"typescript-eslint": "^8.19.0",
"vitest": "^3.2.7"
}
}
-119
View File
@@ -1,119 +0,0 @@
/**
* Generates the two GENERATED folders of the official equine sheet from
* the legacy sources and the AUTHORED curation files:
*
* supabase/seed/anatomical-sheets/equine/legacy-import/ baseline
* supabase/seed/anatomical-sheets/equine/draft/ working revision
*
* pnpm import:equine (from the repository root)
*
* Output is byte-identical across runs; files a run no longer produces are
* removed from those two folders. Commit the result and review the reports.
*/
import { copyFile, mkdir, readdir, rm, writeFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
buildEquineDraft,
EQUINE_DRAFT_DIR,
EQUINE_LEGACY_IMPORT_DIR,
EQUINE_SOURCE_PATHS,
HEAD_VIEW_ID,
importEquineLegacy,
parseViewBox,
readEquineCuration,
readEquineSources,
renderArtifacts,
renderDraftArtifacts,
type DraftResult,
type ImportResult,
} from '../index'
const REPO_ROOT = fileURLToPath(new URL('../../../../', import.meta.url))
/** File contents by path relative to a generated folder. */
type FolderFiles = Record<string, string | { copyFrom: string }>
async function writeFolder(dir: string, files: FolderFiles): Promise<void> {
for (const [name, content] of Object.entries(files)) {
const path = join(dir, name)
await mkdir(dirname(path), { recursive: true })
if (typeof content === 'string') await writeFile(path, content, 'utf8')
else await copyFile(join(REPO_ROOT, content.copyFrom), path)
}
}
/** Removes what this run did not produce, inside the folder only. */
async function removeStale(dir: string, files: FolderFiles): Promise<void> {
const entries = await readdir(dir, { recursive: true, withFileTypes: true })
for (const entry of entries) {
if (!entry.isFile()) continue
const path = join(entry.parentPath, entry.name)
const name = path.slice(dir.length + 1)
if (!(name in files)) await rm(path)
}
}
async function generate(folder: string, files: FolderFiles): Promise<void> {
const dir = join(REPO_ROOT, folder)
await writeFolder(dir, files)
await removeStale(dir, files)
}
function legacyAssets(): FolderFiles {
const files: FolderFiles = {}
for (const source of [
EQUINE_SOURCE_PATHS.mainSvg,
EQUINE_SOURCE_PATHS.headSvg,
]) {
files[`assets/${source.slice(source.lastIndexOf('/') + 1)}`] = {
copyFrom: source,
}
}
return files
}
function legacySummary(result: ImportResult): string {
const errors = result.issues.filter((i) => i.severity === 'error').length
return (
`${EQUINE_LEGACY_IMPORT_DIR}: ${result.stats.annotations} annotations, ` +
`${result.stats.nodes} nodes, ${result.anomalies.length} anomalies, ` +
`${errors} integrity errors, ${result.issues.length - errors} warnings`
)
}
function draftSummary(draft: DraftResult): string {
const changes = draft.changes.length
return (
`${EQUINE_DRAFT_DIR}: ${changes} changes (CHG-000 included), ` +
`${draft.records.length} records, ${draft.statsAfter.nodes} nodes, ` +
`${draft.assets.length} asset, 0 integrity errors, ${draft.issues.length} warnings`
)
}
async function main(): Promise<void> {
const input = await readEquineSources(REPO_ROOT)
const result = importEquineLegacy(input)
const curation = await readEquineCuration(REPO_ROOT)
const draft = buildEquineDraft({
importResult: result,
legacyMainSvgBytes: input.mainSvg.bytes,
headViewBox: parseViewBox(result.viewBoxes[HEAD_VIEW_ID] ?? null),
...curation,
})
await generate(EQUINE_LEGACY_IMPORT_DIR, {
...(await renderArtifacts(result)),
...legacyAssets(),
})
await generate(EQUINE_DRAFT_DIR, {
...(await renderDraftArtifacts(draft, result.anomalies)),
[`assets/${draft.assets[0]!.file}`]: draft.cleanedSvg,
})
console.log(legacySummary(result))
console.log(draftSummary(draft))
}
main().catch((error: unknown) => {
console.error(error instanceof Error ? error.message : error)
process.exit(1)
})
@@ -1,26 +0,0 @@
import { DOMParser, XMLSerializer } from '@xmldom/xmldom'
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
import { composeViewSvg } from '../render/compose'
/**
* The drawing of one view exactly as the application renders it: the
* cleaned asset framed on the view's box plus the annotation layer the app
* generates from the document. Written under draft/review/app-<view>.svg
* so the markers and the framing can be compared with the legacy files
* before and after a change, outside the browser. Parse and serialise
* here; the composition itself is the shared `composeViewSvg`.
*/
export interface AppReviewInput {
cleanedSvg: string
document: AnatomicalSheetDocumentInput
viewId: string
}
export function renderAppReviewDrawing(input: AppReviewInput): string {
const doc = new DOMParser().parseFromString(input.cleanedSvg, 'image/svg+xml')
const root = doc.documentElement
if (!root || root.tagName !== 'svg') throw new Error('not an SVG document')
composeViewSvg({ root, document: input.document, viewId: input.viewId })
return new XMLSerializer().serializeToString(doc)
}
-134
View File
@@ -1,134 +0,0 @@
import {
AnatomicalSheetDocumentSchema,
validateSheetDocument,
type AnatomicalSheetDocumentInput,
type Reference,
type SheetIssue,
} from '@faunosteo/domain'
import { applyOp, assertDeclared } from './ops'
import {
changeSummary,
needsConfirmation,
type Change,
type ChangeSummary,
type Changeset,
} from './schema'
import { allFindings, topCollection, type Item } from './targets'
import type { ChangeRecord, CurationResult } from './types'
/**
* Applies a changeset on a baseline document, deterministically and with a
* record per elementary edit. The references file replaces the document
* registry first (it is the source of truth). Any op that cannot apply
* exactly as written, and any integrity error left at the end, throws:
* a curated document is never produced from a partially applied changeset.
*
* Review rule: a level B or C change never leaves what it touched
* (findings, finding categories, annotations: every item a set, add, cite,
* rename or move resolved to, whole added subtrees and subtree scopes
* included) as inherited or reviewed. After its ops, the applier sets
* `review_status = 'to_confirm'` on each one and records that edit under the
* same change id. An explicit 'reviewed' in such a change throws. Level A
* is untouched by the rule.
*/
/** Findings and annotations of the document, by item, with their target. */
function reviewable(doc: Item): Map<Item, string> {
const map = new Map<Item, string>()
for (const { item, target } of allFindings(doc)) map.set(item, target)
for (const item of topCollection(doc, 'annotation')) {
map.set(item, `annotation:${String(item.id)}`)
}
return map
}
/** Marks every touched item still in the document 'to_confirm'. */
function markToConfirm(
doc: Item,
change: ChangeSummary,
touched: readonly Item[],
records: ChangeRecord[],
) {
const targets = reviewable(doc)
for (const item of new Set(touched)) {
const target = targets.get(item)
if (target === undefined || item.review_status === 'to_confirm') continue
const before = item.review_status ?? 'inherited'
item.review_status = 'to_confirm'
const op = {
op: 'set',
target,
field: 'review_status',
value: 'to_confirm',
} as const
records.push({
change,
op,
target,
field: 'review_status',
before,
after: 'to_confirm',
})
}
}
function applyChange(doc: Item, change: Change, records: ChangeRecord[]) {
const summarised = changeSummary(change)
try {
assertDeclared(doc, change.reference_ids)
} catch (error) {
throw new Error(`${change.id}: ${(error as Error).message}`)
}
const touched: Item[] = []
change.ops.forEach((op, index) => {
try {
applyOp({ doc, change: summarised, op, records, touched })
} catch (error) {
throw new Error(`${change.id} op ${index}: ${(error as Error).message}`)
}
})
if (needsConfirmation(change.level)) {
markToConfirm(doc, summarised, touched, records)
}
}
function describe(issues: readonly { path: string; message: string }[]) {
return issues.map((issue) => `${issue.path}: ${issue.message}`).join('; ')
}
/**
* Shape (Zod) then integrity check of a curated document. Throws on any
* shape issue or integrity error; returns the warnings, which are allowed.
*/
export function curatedIssues(doc: AnatomicalSheetDocumentInput): SheetIssue[] {
const parsed = AnatomicalSheetDocumentSchema.safeParse(doc)
if (!parsed.success) {
const issues = parsed.error.issues.map((issue) => ({
path: issue.path.join('.'),
message: issue.message,
}))
throw new Error(`curated document is not shape-valid: ${describe(issues)}`)
}
const issues = validateSheetDocument(parsed.data)
const errors = issues.filter((issue) => issue.severity === 'error')
if (errors.length > 0) {
throw new Error(
`curated document has integrity errors: ${describe(errors)}`,
)
}
return issues
}
export function applyChangeset(
baseline: AnatomicalSheetDocumentInput,
references: readonly Reference[],
changeset: Changeset,
): CurationResult {
const doc = structuredClone(baseline) as unknown as Item
doc.references = structuredClone(references)
const records: ChangeRecord[] = []
for (const change of changeset.changes) applyChange(doc, change, records)
const document = doc as unknown as AnatomicalSheetDocumentInput
curatedIssues(document)
return { document, records }
}
-59
View File
@@ -1,59 +0,0 @@
import { DOMParser, XMLSerializer, type Element } from '@xmldom/xmldom'
import type { ViewBox } from '@faunosteo/domain'
import { assetIdFromSha256, sha256Hex } from '../legacy/ids'
import type { AssetRecord } from '../legacy/types'
/**
* The curated sheet draws one clean anatomy: the legacy annotation layer
* (hitboxes, visual markers, the head detail-zone) now lives in the
* document as data, so every element carrying data-anno-id leaves the
* drawing. Everything else is serialised back untouched (xmldom keeps the
* declaration, attribute order and whitespace).
*/
export const CLEANED_ASSET_FILE = 'horse.svg'
/** Sizing the legacy app inlined on the root; the app sizes the drawing now. */
const LEGACY_ROOT_STYLE = 'width: 100%; height: auto; max-width: 100%;'
function annotatedElements(root: Element): Element[] {
const all = Array.from(root.getElementsByTagName('*'))
return all.filter((element) => element.hasAttribute('data-anno-id'))
}
export function stripLegacyAnnotations(svgText: string): string {
const doc = new DOMParser().parseFromString(svgText, 'image/svg+xml')
const root = doc.documentElement
if (!root || root.tagName !== 'svg') throw new Error('not an SVG document')
for (const element of annotatedElements(root)) {
element.parentNode?.removeChild(element)
}
if (root.getAttribute('style') === LEGACY_ROOT_STYLE) {
root.removeAttribute('style')
}
return new XMLSerializer().serializeToString(doc)
}
/** Manifest entry of the cleaned drawing; id derived from its sha256. */
export function cleanedAsset(bytes: Uint8Array): AssetRecord {
const sha256 = sha256Hex(bytes)
return {
file: CLEANED_ASSET_FILE,
sha256,
byte_size: bytes.byteLength,
svg_asset_id: assetIdFromSha256(sha256),
}
}
/** SVG viewBox attribute ("minX minY width height") → document view_box. */
export function parseViewBox(raw: string | null): ViewBox {
const numbers = (raw ?? '')
.trim()
.split(/[\s,]+/)
.map(Number)
const [min_x, min_y, width, height] = numbers
if (numbers.length !== 4 || numbers.some((n) => !Number.isFinite(n))) {
throw new Error(`invalid viewBox "${raw}"`)
}
return { min_x: min_x!, min_y: min_y!, width: width!, height: height! }
}
-132
View File
@@ -1,132 +0,0 @@
import { code, table } from '../markdown'
import { KIND_LABELS, LEVEL_LABELS, LEVELS } from './labels'
import { needsConfirmation, type ChangeLevel } from './schema'
import { statRows, type DocumentStats } from './stats'
import { isItem } from './targets'
import type { MigrationMapStats } from './migration-map'
import type { ChangeRecord } from './types'
/**
* French CHANGELOG of the working revision: volumes before / after, then
* one table per change level with every elementary edit. Pure formatting
* of the records, deterministic (no dates).
*/
const MAX_VALUE_LENGTH = 120
function isLabel(value: unknown): value is Record<string, string> {
if (!isItem(value)) return false
const entries = Object.entries(value)
return (
entries.length > 0 &&
entries.every(
([k, v]) => (k === 'fr' || k === 'en') && typeof v === 'string',
)
)
}
/** Compact text of a recorded value: labels as text, objects as JSON. */
export function compactValue(value: unknown): string {
let text: string
if (typeof value === 'string') text = value
else if (isLabel(value)) text = Object.values(value).join(' / ')
else text = JSON.stringify(value)
if (text.length <= MAX_VALUE_LENGTH) return text
return `${text.slice(0, MAX_VALUE_LENGTH - 1)}…`
}
export function recordSubject(record: ChangeRecord): string {
return record.field === null
? record.target
: `${record.target}.${record.field}`
}
function recordRow(record: ChangeRecord): string[] {
const { change } = record
return [
`${code(change.id)} ${change.title.fr}`,
code(recordSubject(record)),
compactValue(record.before),
compactValue(record.after),
KIND_LABELS[change.kind],
change.rationale,
change.reference_ids.map(code).join(', ') || '-',
needsConfirmation(change.level) ? 'oui' : 'non',
]
}
function levelSection(level: ChangeLevel, records: readonly ChangeRecord[]) {
const rows = records.filter((r) => r.change.level === level).map(recordRow)
const head = [
'Changement',
'Objet',
'Avant',
'Après',
'Nature',
'Justification',
'Références',
'Confirmation requise',
]
const body =
rows.length === 0 ? 'Aucun changement de ce niveau.' : table(head, rows)
return `## ${LEVEL_LABELS[level]}\n\n${body}`
}
function comparison(before: DocumentStats, after: DocumentStats): string {
const afterRows = new Map(statRows(after))
const rows = statRows(before).map(([label, value]) => [
label,
value,
afterRows.get(label) ?? 0,
])
return `## Comparaison quantitative\n\n${table(['Indicateur', 'Avant', 'Après'], rows)}`
}
function intro(): string {
return [
'# Journal des changements : révision de travail',
'',
'Généré par `pnpm import:equine` : import historique (`legacy-import/`) ' +
'puis changements rédigés (`curation/changes.json`). Ne pas modifier ' +
'à la main : relancer la commande.',
'',
'Niveaux : A = erreur démontrée, B = amélioration étayée, C = point ' +
'incertain. Les niveaux B et C demandent une confirmation professionnelle.',
].join('\n')
}
/** Fate of the legacy finding nodes a Report v2 may cite (report-migration-map.json). */
function migration(stats: MigrationMapStats): string {
const rows = [
['Nœuds du catalogue historique', String(stats.nodes)],
['Chemin identique', String(stats.identical)],
[
'Chemin renommé ou déplacé (suivi des renommages)',
String(stats.remapped),
],
[
'Relogé sous une autre catégorie (correspondance unique)',
String(stats.rehomed),
],
[
'Retiré : le bilan garde le constat avec ses libellés figés',
String(stats.removed),
],
]
return `## Migration des bilans v2\n\n${table(['Nœuds', 'Nombre'], rows)}`
}
export function renderChangelog(
result: { records: readonly ChangeRecord[] },
before: DocumentStats,
after: DocumentStats,
migrationStats: MigrationMapStats,
): string {
const sections = [
intro(),
comparison(before, after),
migration(migrationStats),
...LEVELS.map((level) => levelSection(level, result.records)),
]
return `${sections.join('\n\n')}\n`
}
-80
View File
@@ -1,80 +0,0 @@
import { isItem, type Item, type ParsedTarget } from './targets'
/**
* Fields a `set` may write, per kind of item. Ids are left out on purpose:
* an id changes through `rename`, which also rewrites every reference to
* it. Unlisted field → the op fails instead of writing a stray key.
*/
const SETTABLE: Record<string, readonly string[]> = {
document: ['name', 'description', 'scope_disclaimer', 'attribution'],
region: ['name', 'count', 'count_range'],
reference: ['type', 'citation', 'url', 'doi'],
category: ['name', 'color'],
view: ['name', 'svg_asset_id', 'view_box', 'parent_view_id'],
annotation: [
'name',
'kind',
'view_id',
'category_id',
'laterality',
'geometry',
'review_status',
'finding_zone_id',
'vertebral_region_code',
'opens_view_id',
'color',
],
zone: ['name'],
finding_category: [
'kind',
'name',
'description',
'reference_ids',
'review_status',
],
finding_node: [
'name',
'description',
'requires_vet_referral',
'reference_ids',
'review_status',
],
}
export function splitField(field: string): string[] {
const path = field.split('.')
if (path.includes('')) throw new Error(`malformed field "${field}"`)
return path
}
/** Item kind of the settable table; a finding is a category or a node. */
export function fieldKind(target: ParsedTarget, isCategory?: boolean): string {
if (target.kind !== 'finding') return target.kind
const category = isCategory ?? target.ids.length === 2
return category ? 'finding_category' : 'finding_node'
}
export function isSettable(kind: string, field: string): boolean {
return SETTABLE[kind]?.includes(splitField(field)[0]!) ?? false
}
export function readField(item: Item, field: string): unknown {
let value: unknown = item
for (const key of splitField(field)) {
if (!isItem(value)) return undefined
value = value[key]
}
return value
}
/** Writes a deep copy of value; missing intermediate objects are created. */
export function writeField(item: Item, field: string, value: unknown): void {
const path = splitField(field)
let holder = item
for (const key of path.slice(0, -1)) {
if (!isItem(holder[key])) holder[key] = {}
holder = holder[key] as Item
}
holder[path[path.length - 1]!] = structuredClone(value)
}
-53
View File
@@ -1,53 +0,0 @@
export { applyChangeset, curatedIssues } from './apply'
export {
CLEANED_ASSET_FILE,
cleanedAsset,
parseViewBox,
stripLegacyAnnotations,
} from './assets'
export { compactValue, renderChangelog } from './changelog'
export {
buildEquineDraft,
DRAFT_SEED_SQL_FILE,
MIGRATION_MAP_FILE,
SHEET_REF_FILE,
renderDraftArtifacts,
type DraftInput,
type DraftResult,
} from './pipeline'
export {
buildReportMigrationMap,
type MigrationMapInput,
type MigrationMapStats,
} from './migration-map'
export { renderAppReviewDrawing, type AppReviewInput } from './app-review'
export {
REVIEW_OVERLAY_DIR,
overlayMarkers,
renderReviewOverlay,
type OverlayInput,
} from './overlay'
export { renderReviewReport, type ReviewReportInput } from './review-report'
export {
ASSET_CHANGE_ID,
ChangeSchema,
ChangesetSchema,
OpSchema,
ReferencesFileSchema,
needsConfirmation,
} from './schema'
export type * from './schema'
export {
DOCUMENT_DOLLAR_TAG,
DRAFT_CHANGE_NOTE,
renderDraftSeedSql,
type DraftSeedParams,
} from './seed'
export {
CURATION_FILES,
readEquineCuration,
type CurationInput,
} from './sources'
export { documentStats, statRows, type DocumentStats } from './stats'
export { parseTarget, formatTarget } from './targets'
export type { ChangeRecord, CurationResult } from './types'
-29
View File
@@ -1,29 +0,0 @@
import type { ChangeKind, ChangeLevel, ChangePriority } from './schema'
/** French labels shared by the CHANGELOG and the review report. */
export const KIND_LABELS: Record<ChangeKind, string> = {
correction: 'Correction',
terminology: 'Terminologie',
translation: 'Traduction',
restructure: 'Réorganisation',
enrichment: 'Ajout',
reference: 'Référence',
geometry: 'Géométrie',
removal: 'Suppression',
technical: 'Technique',
}
export const LEVEL_LABELS: Record<ChangeLevel, string> = {
A: 'Niveau A : erreurs démontrées',
B: 'Niveau B : améliorations étayées (confirmation requise)',
C: 'Niveau C : points incertains (question au professionnel)',
}
export const PRIORITY_LABELS: Record<ChangePriority, string> = {
high: 'haute',
medium: 'moyenne',
low: 'basse',
}
export const LEVELS: readonly ChangeLevel[] = ['A', 'B', 'C']
@@ -1,178 +0,0 @@
import type { ReportMigrationMap, SheetRef } from '@faunosteo/domain'
import type { LegacyIdMap } from '../legacy/types'
import { allFindings, topCollection, type Item } from './targets'
import type { ChangeRecord } from './types'
/**
* Report migration map: where every identifier a Report v2 may carry lands
* in the curated draft. Annotations come from the legacy id map (then
* follow annotation renames), finding paths from replaying the applier's
* rename, move and remove records over every node of the legacy baseline.
* A node removed with its category and re-added under another category at
* the same relative place (the sphenoid restructure) is re-homed when the
* match is unique; anything else stays null = "removed", and the report
* keeps the finding with its snapshots.
*/
const FINDING = 'finding:'
export interface MigrationMapInput {
baseline: Item
final: Item
legacyIdMap: LegacyIdMap
records: readonly ChangeRecord[]
sheet: SheetRef
mainViewId: string
}
export interface MigrationMapStats {
nodes: number
identical: number
remapped: number
rehomed: number
removed: number
}
interface PathEntry {
legacy: string
current: string | null
rehomed: boolean
}
function strip(target: string): string {
return target.slice(FINDING.length)
}
function lastSegment(path: string): string {
return path.slice(path.lastIndexOf('/') + 1)
}
function withLastSegment(path: string, id: string): string {
const cut = path.lastIndexOf('/')
return cut < 0 ? id : `${path.slice(0, cut + 1)}${id}`
}
function replacePrefix(entries: PathEntry[], from: string, to: string | null) {
for (const entry of entries) {
const current = entry.current
if (current === null) continue
if (current === from) entry.current = to
else if (current.startsWith(`${from}/`)) {
entry.current = to === null ? null : `${to}${current.slice(from.length)}`
}
}
}
function applyRecord(
entries: PathEntry[],
ids: { annotations: Map<string, string>; views: Map<string, string> },
record: ChangeRecord,
) {
const { op, target } = record
if (op.op !== 'rename' && op.op !== 'remove' && op.op !== 'move') return
if (target.startsWith(FINDING)) {
const from = strip(target)
if (op.op === 'rename')
replacePrefix(entries, from, withLastSegment(from, op.id))
if (op.op === 'remove') replacePrefix(entries, from, null)
if (op.op === 'move')
replacePrefix(entries, from, `${strip(op.to)}/${lastSegment(from)}`)
return
}
const [kind, id] = target.split(':', 2) as [string, string]
if (kind === 'zone') {
for (const entry of entries) {
if (entry.current?.startsWith(`${id}/`)) {
entry.current =
op.op === 'remove'
? null
: `${op.op === 'rename' ? op.id : id}${entry.current.slice(id.length)}`
}
}
return
}
if (op.op === 'rename' && (kind === 'annotation' || kind === 'view')) {
const map = kind === 'annotation' ? ids.annotations : ids.views
for (const [legacy, current] of map)
if (current === id) map.set(legacy, op.id)
}
}
/** `zone/<any category>/<rest>` present exactly once in the final document. */
function rehome(entry: PathEntry, finalPaths: ReadonlySet<string>): void {
const [zone, , ...rest] = entry.legacy.split('/')
if (rest.length === 0) return
const tail = `/${rest.join('/')}`
const matches = [...finalPaths].filter(
(p) =>
p.startsWith(`${zone}/`) &&
p.endsWith(tail) &&
p.split('/').length === rest.length + 2,
)
if (matches.length === 1) {
entry.current = matches[0]!
entry.rehomed = true
}
}
function annotationNames(doc: Item): Map<string, { fr: string; en: string }> {
const names = new Map<string, { fr: string; en: string }>()
for (const a of topCollection(doc, 'annotation')) {
const name = a.name as { fr?: string; en?: string } | null
names.set(String(a.id), { fr: name?.fr ?? '', en: name?.en ?? '' })
}
return names
}
export function buildReportMigrationMap(input: MigrationMapInput): {
map: ReportMigrationMap
stats: MigrationMapStats
} {
const entries: PathEntry[] = allFindings(input.baseline).map((e) => ({
legacy: strip(e.target),
current: strip(e.target),
rehomed: false,
}))
const ids = {
annotations: new Map(Object.entries(input.legacyIdMap.annotations)),
views: new Map(Object.entries(input.legacyIdMap.views)),
}
for (const record of input.records) applyRecord(entries, ids, record)
const finalPaths = new Set(
allFindings(input.final).map((e) => strip(e.target)),
)
for (const entry of entries) {
if (entry.current !== null && !finalPaths.has(entry.current))
entry.current = null
if (entry.current === null) rehome(entry, finalPaths)
}
const legacyNames = annotationNames(input.baseline)
const importIds = new Map(Object.entries(input.legacyIdMap.annotations))
const annotations: ReportMigrationMap['annotations'] = {}
for (const [legacy, finalId] of ids.annotations) {
annotations[legacy] = {
id: finalId,
name: legacyNames.get(importIds.get(legacy)!) ?? { fr: '', en: '' },
}
}
const finding_paths: Record<string, string | null> = {}
for (const entry of entries) finding_paths[entry.legacy] = entry.current
const map: ReportMigrationMap = {
schema_version: 1,
sheet: input.sheet,
main_view_id: input.mainViewId,
views: Object.fromEntries(ids.views),
annotations,
finding_paths,
}
const stats: MigrationMapStats = {
nodes: entries.length,
identical: entries.filter((e) => e.current === e.legacy).length,
remapped: entries.filter(
(e) => e.current !== null && e.current !== e.legacy && !e.rehomed,
).length,
rehomed: entries.filter((e) => e.rehomed).length,
removed: entries.filter((e) => e.current === null).length,
}
return { map, stats }
}
-225
View File
@@ -1,225 +0,0 @@
import { isDeepStrictEqual } from 'node:util'
import { fieldKind, isSettable, readField, writeField } from './fields'
import { propagateRename } from './rename'
import { needsConfirmation, type Op, type Position } from './schema'
import {
childList,
childPrefix,
findingScope,
isItem,
keyField,
locate,
topCollection,
type Item,
type Located,
type TargetKind,
} from './targets'
import { record, type OpContext } from './types'
/**
* The six op kinds of a change. Each one resolves its target, edits the
* working document in place and records what it changed; anything it
* cannot do exactly as written throws (the caller adds change id and op
* index to the message).
*/
type OpOf<K extends Op['op']> = Extract<Op, { op: K }>
const COLLECTION_KIND: Record<string, TargetKind> = {
references: 'reference',
categories: 'category',
views: 'view',
annotations: 'annotation',
finding_zones: 'zone',
regions: 'region',
}
function assertFree(list: Item[], key: string, id: string, self?: Item) {
if (list.some((entry) => entry !== self && entry[key] === id)) {
throw new Error(`"${id}" already exists among its siblings`)
}
}
function insertionIndex(list: Item[], key: string, position?: Position) {
if (position === undefined) return list.length
if (typeof position === 'number') {
if (position > list.length)
throw new Error(`position ${position} out of range`)
return position
}
const anchor = 'after' in position ? position.after : position.before
const index = list.findIndex((entry) => entry[key] === anchor)
if (index < 0) throw new Error(`unknown sibling "${anchor}"`)
return 'after' in position ? index + 1 : index
}
function unknownField(op: OpOf<'set'>): Error {
return new Error(`unknown field "${op.field}" on "${op.target}"`)
}
/** A B or C change leaves findings to the professional: no 'reviewed'. */
function assertNotReviewed(ctx: OpContext, op: OpOf<'set'>) {
if (op.field !== 'review_status' || op.value !== 'reviewed') return
if (needsConfirmation(ctx.change.level)) {
throw new Error(
`level ${ctx.change.level} cannot set ` +
`"${op.target}" review_status to "reviewed"`,
)
}
}
function setSelf(ctx: OpContext, located: Located, op: OpOf<'set'>) {
if (!isSettable(fieldKind(located.target), op.field)) throw unknownField(op)
ctx.touched.push(located.item)
const before = readField(located.item, op.field)
writeField(located.item, op.field, op.value)
record(ctx, op.target, op.field, { before, after: op.value })
}
/** Target and descendants that carry the field; unchanged items are skipped. */
function setSubtree(ctx: OpContext, located: Located, op: OpOf<'set'>) {
if (located.target.kind !== 'finding') {
throw new Error(`scope subtree needs a finding target, got "${op.target}"`)
}
const entries = findingScope(located, 'subtree').filter((entry) =>
isSettable(fieldKind(located.target, entry.isCategory), op.field),
)
if (entries.length === 0) throw unknownField(op)
ctx.touched.push(...entries.map((entry) => entry.item))
for (const { target, item } of entries) {
const before = readField(item, op.field)
if (isDeepStrictEqual(before, op.value)) continue
writeField(item, op.field, op.value)
record(ctx, target, op.field, { before, after: op.value })
}
}
function applySet(ctx: OpContext, op: OpOf<'set'>): void {
assertNotReviewed(ctx, op)
const located = locate(ctx.doc, op.target)
if ((op.scope ?? 'self') === 'self') setSelf(ctx, located, op)
else setSubtree(ctx, located, op)
}
function applyRename(ctx: OpContext, op: OpOf<'rename'>): void {
const { target, siblings, item } = locate(ctx.doc, op.target)
if (siblings === null) throw new Error('the document has no id to rename')
const key = keyField(target.kind)
assertFree(siblings, key, op.id, item)
const before = structuredClone(item)
const from = String(item[key])
item[key] = op.id
ctx.touched.push(item)
record(ctx, op.target, null, { before, after: item })
propagateRename(ctx, { kind: target.kind, from, to: op.id })
}
interface Destination {
list: Item[]
key: 'id' | 'code'
prefix: string
}
function addDestination(ctx: OpContext, op: OpOf<'add'>): Destination {
const parent = locate(ctx.doc, op.target)
if (parent.target.kind !== 'document') {
if (op.field)
throw new Error(`field "${op.field}" is only valid on document`)
return { list: childList(parent), key: 'id', prefix: childPrefix(parent) }
}
if (!op.field) throw new Error('add on document needs a field')
const kind = COLLECTION_KIND[op.field]!
const list = topCollection(ctx.doc, kind)
return { list, key: keyField(kind), prefix: `${kind}:` }
}
function descendants(item: Item): Item[] {
const children = Array.isArray(item.children) ? (item.children as Item[]) : []
return children.flatMap((child) => [child, ...descendants(child)])
}
function applyAdd(ctx: OpContext, op: OpOf<'add'>): void {
if (!isItem(op.value)) throw new Error('add needs an object value')
const dest = addDestination(ctx, op)
const id = op.value[dest.key]
if (typeof id !== 'string') {
throw new Error(`the added item needs a string "${dest.key}"`)
}
assertFree(dest.list, dest.key, id)
const index = insertionIndex(dest.list, dest.key, op.position)
const added = structuredClone(op.value)
dest.list.splice(index, 0, added)
ctx.touched.push(added, ...descendants(added))
record(ctx, dest.prefix + id, null, { before: null, after: op.value })
}
function applyRemove(ctx: OpContext, op: OpOf<'remove'>): void {
const { siblings, item } = locate(ctx.doc, op.target)
if (siblings === null) throw new Error('the document cannot be removed')
siblings.splice(siblings.indexOf(item), 1)
record(ctx, op.target, null, { before: item, after: null })
}
/** `after` of a move record is the new target path of the item. */
function applyMove(ctx: OpContext, op: OpOf<'move'>): void {
const source = locate(ctx.doc, op.target)
if (source.target.kind !== 'finding') {
throw new Error(`only findings move, got "${op.target}"`)
}
if (op.to === op.target || op.to.startsWith(`${op.target}/`)) {
throw new Error(`cannot move "${op.target}" into itself`)
}
const parent = locate(ctx.doc, op.to)
const list = childList(parent)
const id = String(source.item.id)
assertFree(list, 'id', id, source.item)
source.siblings!.splice(source.siblings!.indexOf(source.item), 1)
list.splice(insertionIndex(list, 'id', op.position), 0, source.item)
ctx.touched.push(source.item)
const after = childPrefix(parent) + id
record(ctx, op.target, null, { before: source.item, after })
}
/** Every cited id must be declared in the document references. */
export function assertDeclared(doc: Item, ids: readonly string[]): void {
const declared = new Set(topCollection(doc, 'reference').map((r) => r.id))
const missing = ids.filter((id) => !declared.has(id))
if (missing.length > 0) {
throw new Error(`undeclared reference(s): ${missing.join(', ')}`)
}
}
/** Appends citations in order, never twice on the same item. */
function applyCite(ctx: OpContext, op: OpOf<'cite'>): void {
assertDeclared(ctx.doc, op.reference_ids)
const located = locate(ctx.doc, op.target)
const scope = findingScope(located, op.scope ?? 'self')
ctx.touched.push(...scope.map((entry) => entry.item))
for (const { target, item } of scope) {
const before = Array.isArray(item.reference_ids) ? item.reference_ids : []
const added = [...new Set(op.reference_ids)].filter(
(id) => !before.includes(id),
)
if (added.length === 0) continue
item.reference_ids = [...before, ...added]
record(ctx, target, 'reference_ids', { before, after: item.reference_ids })
}
}
export function applyOp(ctx: OpContext): void {
const op = ctx.op
switch (op.op) {
case 'set':
return applySet(ctx, op)
case 'rename':
return applyRename(ctx, op)
case 'add':
return applyAdd(ctx, op)
case 'remove':
return applyRemove(ctx, op)
case 'move':
return applyMove(ctx, op)
case 'cite':
return applyCite(ctx, op)
}
}
-214
View File
@@ -1,214 +0,0 @@
import {
DOMParser,
XMLSerializer,
type Document,
type Element,
} from '@xmldom/xmldom'
import type { AnatomicalSheetDocumentInput, Geometry } from '@faunosteo/domain'
import { isDeepStrictEqual } from 'node:util'
/**
* Before/after drawing of one view for the professional review: the
* cleaned anatomy, the curated annotations as an SVG layer, and the
* baseline position of every moved or removed annotation beside it
* (dashed). Pure data, deterministic, opens in any browser.
*/
export const REVIEW_OVERLAY_DIR = 'review'
const SVG_NS = 'http://www.w3.org/2000/svg'
const LAYER_ID = 'review-annotations'
type Doc = AnatomicalSheetDocumentInput
type Annotation = Doc['annotations'][number]
type Status = 'unchanged' | 'moved' | 'added' | 'removed'
const STYLE: Record<Status, Record<string, string>> = {
unchanged: { stroke: '#1d4ed8', fill: '#1d4ed8', 'fill-opacity': '0.12' },
moved: { stroke: '#15803d', fill: '#15803d', 'fill-opacity': '0.2' },
added: { stroke: '#15803d', fill: '#15803d', 'fill-opacity': '0.2' },
// fill-opacity rather than fill="none": some rasterizers drop unfilled shapes.
removed: {
stroke: '#b91c1c',
fill: '#b91c1c',
'fill-opacity': '0.04',
'stroke-dasharray': '8 6',
},
}
interface Marker {
id: string
geometry: Geometry
status: Status
}
function withGeometry(annotations: readonly Annotation[], viewId: string) {
return annotations.filter((a) => a.view_id === viewId && a.geometry !== null)
}
/** Curated annotations with their status, then the baseline shapes they left. */
export function overlayMarkers(
before: Doc,
after: Doc,
viewId: string,
): Marker[] {
const previous = new Map(
withGeometry(before.annotations, viewId).map((a) => [a.id, a.geometry!]),
)
const markers: Marker[] = []
for (const a of withGeometry(after.annotations, viewId)) {
const old = previous.get(a.id)
const status: Status =
old === undefined
? 'added'
: isDeepStrictEqual(old, a.geometry)
? 'unchanged'
: 'moved'
markers.push({ id: a.id, geometry: a.geometry!, status })
if (status === 'moved') {
markers.push({ id: a.id, geometry: old!, status: 'removed' })
}
}
const kept = new Set(after.annotations.map((a) => a.id))
for (const [id, geometry] of previous) {
if (!kept.has(id)) markers.push({ id, geometry, status: 'removed' })
}
return markers
}
function shapeElement(doc: Document, geometry: Geometry): Element {
switch (geometry.type) {
case 'circle': {
const el = doc.createElementNS(SVG_NS, 'circle')
el.setAttribute('cx', String(geometry.cx))
el.setAttribute('cy', String(geometry.cy))
el.setAttribute('r', String(geometry.r))
return el
}
case 'polygon': {
const el = doc.createElementNS(SVG_NS, 'polygon')
el.setAttribute(
'points',
geometry.points.map(([x, y]) => `${x},${y}`).join(' '),
)
return el
}
case 'path': {
const el = doc.createElementNS(SVG_NS, 'path')
el.setAttribute('d', geometry.d)
return el
}
}
}
function labelAnchor(geometry: Geometry): [number, number] | null {
if (geometry.type === 'circle') {
return [geometry.cx, geometry.cy - geometry.r - 4]
}
if (geometry.type === 'polygon') {
const n = geometry.points.length
const [sx, sy] = geometry.points.reduce(
([ax, ay], [x, y]) => [ax + x, ay + y],
[0, 0],
)
return [sx / n, sy / n]
}
return null
}
function markerGroup(
doc: Document,
layer: Element,
marker: Marker,
fontSize: number,
) {
const group = doc.createElementNS(SVG_NS, 'g')
group.setAttribute('data-review-id', marker.id)
group.setAttribute('data-review-status', marker.status)
const shape = shapeElement(doc, marker.geometry)
for (const [k, v] of Object.entries(STYLE[marker.status])) {
shape.setAttribute(k, v)
}
shape.setAttribute('stroke-width', String(fontSize / 8))
const title = doc.createElementNS(SVG_NS, 'title')
title.appendChild(doc.createTextNode(`${marker.id} (${marker.status})`))
group.appendChild(title)
group.appendChild(shape)
const anchor = labelAnchor(marker.geometry)
if (anchor && marker.status !== 'removed') {
const text = doc.createElementNS(SVG_NS, 'text')
text.setAttribute('x', String(anchor[0]))
text.setAttribute('y', String(anchor[1]))
text.setAttribute('text-anchor', 'middle')
text.setAttribute('font-family', 'sans-serif')
text.setAttribute('font-size', String(fontSize))
text.setAttribute('fill', STYLE[marker.status].stroke!)
text.appendChild(doc.createTextNode(marker.id))
group.appendChild(text)
}
layer.appendChild(group)
}
function legend(
doc: Document,
layer: Element,
[x, y]: [number, number],
fontSize: number,
) {
const lines = [
['unchanged', 'bleu : inchangé'],
[
'moved',
'vert : déplacé ou ajouté (pointillé rouge = position précédente)',
],
['removed', 'rouge pointillé : retiré'],
] as const
lines.forEach(([status, label], i) => {
const text = doc.createElementNS(SVG_NS, 'text')
text.setAttribute('x', String(x))
text.setAttribute('y', String(y + (i + 1) * fontSize * 1.3))
text.setAttribute('font-family', 'sans-serif')
text.setAttribute('font-size', String(fontSize))
text.setAttribute('fill', STYLE[status].stroke!)
text.appendChild(doc.createTextNode(label))
layer.appendChild(text)
})
}
export interface OverlayInput {
cleanedSvg: string
before: Doc
after: Doc
viewId: string
}
/** The review drawing of one view, framed on that view's box. */
export function renderReviewOverlay(input: OverlayInput): string {
const doc = new DOMParser().parseFromString(input.cleanedSvg, 'image/svg+xml')
const root = doc.documentElement
if (!root || root.tagName !== 'svg') throw new Error('not an SVG document')
const view = input.after.views.find((v) => v.id === input.viewId)
if (!view) throw new Error(`unknown view "${input.viewId}"`)
if (view.view_box) {
const { min_x, min_y, width, height } = view.view_box
root.setAttribute('viewBox', `${min_x} ${min_y} ${width} ${height}`)
}
root.removeAttribute('width')
root.removeAttribute('height')
const box = (root.getAttribute('viewBox') ?? '0 0 1000 1000')
.split(/[\s,]+/)
.map(Number)
// ~1% of the frame width, never below 10 units (detail views are small).
const fontSize = Math.max(Math.round(box[2]! / 90), 10)
const layer = doc.createElementNS(SVG_NS, 'g')
layer.setAttribute('id', LAYER_ID)
for (const marker of overlayMarkers(
input.before,
input.after,
input.viewId,
)) {
markerGroup(doc, layer, marker, fontSize)
}
legend(doc, layer, [box[0]! + fontSize, box[1]!], fontSize)
root.appendChild(layer)
return new XMLSerializer().serializeToString(doc)
}
-224
View File
@@ -1,224 +0,0 @@
import type {
AnatomicalSheetDocumentInput,
Reference,
SheetIssue,
ViewBox,
} from '@faunosteo/domain'
import { formatJson, formatMarkdown } from '../format'
import { HEAD_VIEW_ID, MAIN_VIEW_ID } from '../legacy/importer'
import type {
Anomaly,
AssetRecord,
ImportResult,
LegacyIdMap,
} from '../legacy/types'
import { applyChangeset, curatedIssues } from './apply'
import { cleanedAsset, stripLegacyAnnotations } from './assets'
import { renderChangelog } from './changelog'
import { REVIEW_OVERLAY_DIR, renderReviewOverlay } from './overlay'
import { buildReportMigrationMap } from './migration-map'
import { renderAppReviewDrawing } from './app-review'
import { sha256Hex } from '../legacy/ids'
import { renderReviewReport } from './review-report'
import {
ASSET_CHANGE_ID,
changeSummary,
type Change,
type ChangeSummary,
type Changeset,
} from './schema'
import { DRAFT_CHANGE_NOTE, renderDraftSeedSql } from './seed'
import { documentStats, type DocumentStats } from './stats'
import type { ChangeRecord } from './types'
/**
* Legacy import → curated working draft. The asset step runs first as the
* reserved change CHG-000 (one cleaned drawing, head view = crop), then
* the authored changeset; both land in the same records, so the CHANGELOG
* lists them alike. Deterministic: same inputs, same bytes.
*/
export const DRAFT_SEED_SQL_FILE = 'equine_draft.sql'
export interface DraftInput {
importResult: ImportResult
legacyMainSvgBytes: Uint8Array
headViewBox: ViewBox
references: readonly Reference[]
changeset: Changeset
}
export interface DraftResult {
document: AnatomicalSheetDocumentInput
/** Legacy import the changeset was applied to. */
baseline: AnatomicalSheetDocumentInput
legacyIdMap: LegacyIdMap
records: ChangeRecord[]
changes: ChangeSummary[]
assets: AssetRecord[]
/** Cleaned drawing, written as draft/assets/<assets[0].file>. */
cleanedSvg: string
statsBefore: DocumentStats
statsAfter: DocumentStats
/** Integrity warnings of the curated document (errors throw). */
issues: SheetIssue[]
sheetId: string
}
function assetChange(asset: AssetRecord, headViewBox: ViewBox): Change {
return {
id: ASSET_CHANGE_ID,
level: 'A',
kind: 'technical',
title: {
fr: 'Un seul dessin, vue tête = recadrage',
en: 'Single drawing, head view = crop',
},
rationale:
'Les deux fichiers historiques portent le même dessin (tracés ' +
'identiques) et les marqueurs sont désormais des données de la ' +
'fiche : un seul dessin nettoyé, la vue tête en est un recadrage.',
reference_ids: [],
priority: 'medium',
ops: [
{
op: 'set',
target: `view:${MAIN_VIEW_ID}`,
field: 'svg_asset_id',
value: asset.svg_asset_id,
},
{
op: 'set',
target: `view:${HEAD_VIEW_ID}`,
field: 'svg_asset_id',
value: null,
},
{
op: 'set',
target: `view:${HEAD_VIEW_ID}`,
field: 'view_box',
value: headViewBox,
},
],
}
}
function assertNotReserved(changeset: Changeset): void {
if (changeset.changes.some((change) => change.id === ASSET_CHANGE_ID)) {
throw new Error(`${ASSET_CHANGE_ID} is reserved for the asset step`)
}
}
export function buildEquineDraft(input: DraftInput): DraftResult {
assertNotReserved(input.changeset)
const legacyText = new TextDecoder('utf-8', { fatal: true }).decode(
input.legacyMainSvgBytes,
)
const cleanedSvg = stripLegacyAnnotations(legacyText)
const asset = cleanedAsset(new TextEncoder().encode(cleanedSvg))
const changes = [
assetChange(asset, input.headViewBox),
...input.changeset.changes,
]
const baseline = input.importResult.document
const result = applyChangeset(baseline, input.references, { changes })
return {
document: result.document,
baseline,
legacyIdMap: input.importResult.legacyIdMap,
records: result.records,
changes: changes.map(changeSummary),
assets: [asset],
cleanedSvg,
statsBefore: documentStats(baseline),
statsAfter: documentStats(result.document),
issues: curatedIssues(result.document),
sheetId: input.importResult.sheetId,
}
}
/** One review drawing per view, under review/annotations-<view>.svg. */
function reviewOverlays(draft: DraftResult): Record<string, string> {
const files: Record<string, string> = {}
for (const view of draft.document.views) {
files[`${REVIEW_OVERLAY_DIR}/annotations-${view.id}.svg`] =
renderReviewOverlay({
cleanedSvg: draft.cleanedSvg,
before: draft.baseline,
after: draft.document,
viewId: view.id,
})
}
return files
}
export const SHEET_REF_FILE = 'sheet-ref.json'
export const MIGRATION_MAP_FILE = 'report-migration-map.json'
/** What a report references: the sheet and the exact document bytes. */
function sheetRef(draft: DraftResult, documentJson: string) {
return {
sheetId: draft.sheetId,
versionId: null,
documentSha256: sha256Hex(documentJson),
}
}
/** The application's own rendering of each view, for the visual check. */
function appReviewDrawings(draft: DraftResult): Record<string, string> {
const files: Record<string, string> = {}
for (const view of draft.document.views) {
files[`${REVIEW_OVERLAY_DIR}/app-${view.id}.svg`] = renderAppReviewDrawing({
cleanedSvg: draft.cleanedSvg,
document: draft.document,
viewId: view.id,
})
}
return files
}
/** Text artifacts of the draft folder, keyed by file name. */
export async function renderDraftArtifacts(
draft: DraftResult,
legacyAnomalies: readonly Anomaly[],
): Promise<Record<string, string>> {
const documentJson = await formatJson(draft.document)
const ref = sheetRef(draft, documentJson)
const migration = buildReportMigrationMap({
baseline: draft.baseline as Record<string, unknown>,
final: draft.document as Record<string, unknown>,
legacyIdMap: draft.legacyIdMap,
records: draft.records,
sheet: ref,
mainViewId: MAIN_VIEW_ID,
})
const changelog = renderChangelog(
draft,
draft.statsBefore,
draft.statsAfter,
migration.stats,
)
const review = renderReviewReport({ ...draft, legacyAnomalies })
return {
'document.json': documentJson,
'assets.json': await formatJson(draft.assets),
[SHEET_REF_FILE]: await formatJson({
sheet_id: ref.sheetId,
version_id: ref.versionId,
document_sha256: ref.documentSha256,
schema_version: draft.document.schema_version,
species_id: draft.document.species_id,
}),
[MIGRATION_MAP_FILE]: await formatJson(migration.map),
...reviewOverlays(draft),
...appReviewDrawings(draft),
'CHANGELOG.md': await formatMarkdown(changelog),
'REVIEW-REPORT.md': await formatMarkdown(review),
[DRAFT_SEED_SQL_FILE]: renderDraftSeedSql({
sheetId: draft.sheetId,
assets: draft.assets,
documentJson,
changeNote: DRAFT_CHANGE_NOTE,
}),
}
}
-57
View File
@@ -1,57 +0,0 @@
import { allFindings, topCollection, type TargetKind } from './targets'
import { record, type OpContext } from './types'
/**
* Rename propagation: every field pointing at the renamed id follows, and
* each rewrite is a record of its own so the CHANGELOG shows the cascade.
*/
interface Link {
kind: 'annotation' | 'view'
field: string
}
const LINKS: Partial<Record<TargetKind, readonly Link[]>> = {
zone: [{ kind: 'annotation', field: 'finding_zone_id' }],
region: [{ kind: 'annotation', field: 'vertebral_region_code' }],
view: [
{ kind: 'view', field: 'parent_view_id' },
{ kind: 'annotation', field: 'view_id' },
{ kind: 'annotation', field: 'opens_view_id' },
],
category: [{ kind: 'annotation', field: 'category_id' }],
}
interface Rename {
kind: TargetKind
from: string
to: string
}
function followLink(ctx: OpContext, link: Link, rename: Rename): void {
for (const item of topCollection(ctx.doc, link.kind)) {
if (item[link.field] !== rename.from) continue
item[link.field] = rename.to
record(ctx, `${link.kind}:${String(item.id)}`, link.field, {
before: rename.from,
after: rename.to,
})
}
}
function followCitations(ctx: OpContext, rename: Rename): void {
for (const { target, item } of allFindings(ctx.doc)) {
const ids = item.reference_ids
if (!Array.isArray(ids) || !ids.includes(rename.from)) continue
const after = ids.map((id: unknown) =>
id === rename.from ? rename.to : id,
)
record(ctx, target, 'reference_ids', { before: ids, after })
item.reference_ids = after
}
}
export function propagateRename(ctx: OpContext, rename: Rename): void {
if (rename.kind === 'reference') return followCitations(ctx, rename)
for (const link of LINKS[rename.kind] ?? []) followLink(ctx, link, rename)
}
@@ -1,206 +0,0 @@
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
import type { Anomaly } from '../legacy/types'
import { code, table } from '../markdown'
import { compactValue, recordSubject } from './changelog'
import { KIND_LABELS, PRIORITY_LABELS } from './labels'
import {
needsConfirmation,
type ChangePriority,
type ChangeSummary,
} from './schema'
import { statRows, type DocumentStats } from './stats'
import { allFindings, zoneFindings, type Item } from './targets'
import type { ChangeRecord } from './types'
/**
* French review report for the osteopath, ten fixed sections. It only
* formats data (changes, records, stats, references): no medical content
* is written here, every statement comes from the authored changeset.
*/
export interface ReviewReportInput {
changes: readonly ChangeSummary[]
records: readonly ChangeRecord[]
document: AnatomicalSheetDocumentInput
statsBefore: DocumentStats
legacyAnomalies: readonly Anomaly[]
}
type Section = (input: ReviewReportInput) => string
const NONE = 'Aucun élément dans cette révision.'
const PRIORITY_ORDER: readonly ChangePriority[] = ['high', 'medium', 'low']
function subjects(input: ReviewReportInput, change: ChangeSummary): string {
const own = input.records.filter((r) => r.change.id === change.id)
return [...new Set(own.map(recordSubject))].map(code).join(', ')
}
function references(ids: readonly string[]): string {
return ids.length === 0 ? 'aucune' : ids.map(code).join(', ')
}
function changeLine(input: ReviewReportInput, change: ChangeSummary): string {
const confirm = needsConfirmation(change.level) ? 'oui' : 'non'
return (
`- ${code(change.id)} ${change.title.fr} (niveau ${change.level}, ` +
`${KIND_LABELS[change.kind]}, confirmation requise : ${confirm}). ` +
`${change.rationale} Objets : ${subjects(input, change)}. ` +
`Références : ${references(change.reference_ids)}.` +
(change.question ? ` Question : ${change.question}` : '')
)
}
function changeList(
input: ReviewReportInput,
keep: (c: ChangeSummary) => boolean,
) {
const lines = input.changes.filter(keep).map((c) => changeLine(input, c))
return lines.length === 0 ? NONE : lines.join('\n')
}
const initialQuality: Section = (input) => {
const toValidate = input.legacyAnomalies.filter(
(a) => a.level === 'a_valider',
)
return [
`L'import historique signale ${input.legacyAnomalies.length} anomalies, ` +
`dont ${toValidate.length} à valider (détail dans ` +
'`legacy-import/IMPORT-REPORT.md`).',
'',
table(
['Indicateur (import historique)', 'Valeur'],
statRows(input.statsBefore),
),
].join('\n')
}
const mainErrors: Section = (input) =>
changeList(
input,
(c) => c.level === 'A' && (c.kind === 'correction' || c.kind === 'removal'),
)
const translations: Section = (input) => {
const changes = input.changes.filter((c) => c.kind === 'translation')
const ids = new Set(changes.map((c) => c.id))
const touched = input.records.filter((r) => ids.has(r.change.id))
const targets = [...new Set(touched.map(recordSubject))]
const head =
`${changes.length} changement(s) de traduction, ` +
`${targets.length} objet(s) traduit(s).`
return targets.length === 0
? head
: `${head}\n\n${targets.map((t) => `- ${code(t)}`).join('\n')}`
}
function vetFlagChanges(input: ReviewReportInput): string {
const flips = input.records.filter((r) => r.field === 'requires_vet_referral')
if (flips.length === 0)
return 'Aucun renvoi vétérinaire modifié dans cette révision.'
const line = (r: ChangeRecord) =>
`- ${code(r.target)} : ${compactValue(r.before)} → ` +
`${compactValue(r.after)} (${code(r.change.id)})`
return flips.map(line).join('\n')
}
function vetFlagsPerZone(doc: AnatomicalSheetDocumentInput): string {
const rows = (doc.finding_zones as unknown as Item[]).flatMap((zone) => {
const flags = zoneFindings(zone).filter(
(e) => e.item.requires_vet_referral === true,
)
return flags.length === 0 ? [] : [[code(String(zone.id)), flags.length]]
})
return rows.length === 0
? 'Aucun renvoi vétérinaire.'
: table(['Zone', 'Renvois vétérinaires'], rows)
}
const clinicalVigilance: Section = (input) =>
[
'Renvois vétérinaires modifiés :',
'',
vetFlagChanges(input),
'',
'Renvois vétérinaires de la fiche, par zone :',
'',
vetFlagsPerZone(input.document),
].join('\n')
function citationCount(doc: AnatomicalSheetDocumentInput, id: string): number {
return allFindings(doc as unknown as Item).filter((e) => {
const ids = e.item.reference_ids
return Array.isArray(ids) && ids.includes(id)
}).length
}
const bibliography: Section = (input) => {
const lines = input.document.references.map((ref, index) => {
const links = [
ref.url ? `URL : ${ref.url}` : '',
ref.doi ? `DOI : ${ref.doi}` : '',
].filter(Boolean)
const where = links.length > 0 ? ` (${links.join(', ')})` : ''
const cited = citationCount(input.document, ref.id)
return (
`${index + 1}. ${code(ref.id)} ${ref.citation}${where}, ` +
`cité par ${cited} nœud(s).`
)
})
return lines.length === 0 ? 'Aucune référence déclarée.' : lines.join('\n')
}
function byPriorityThenId(a: ChangeSummary, b: ChangeSummary): number {
const rank =
PRIORITY_ORDER.indexOf(a.priority) - PRIORITY_ORDER.indexOf(b.priority)
if (rank !== 0) return rank
if (a.id === b.id) return 0
return a.id < b.id ? -1 : 1
}
const professionalDecisions: Section = (input) => {
const questions = input.changes
.filter((c) => c.question !== undefined)
.sort(byPriorityThenId)
if (questions.length === 0) return 'Aucune question ouverte.'
return questions
.map(
(c, index) =>
`${index + 1}. ${code(c.id)} (priorité ${PRIORITY_LABELS[c.priority]}) : ` +
`${c.question ?? ''} Références : ${references(c.reference_ids)}.`,
)
.join('\n')
}
const SECTIONS: ReadonlyArray<[string, Section]> = [
['1. Qualité des données initiales', initialQuality],
['2. Principales erreurs anatomiques et ostéopathiques', mainErrors],
['3. Corrections effectuées', (i) => changeList(i, (c) => c.level === 'A')],
['4. Ajouts', (i) => changeList(i, (c) => c.kind === 'enrichment')],
[
'5. Réorganisations du catalogue',
(i) => changeList(i, (c) => c.kind === 'restructure'),
],
['6. Éléments incertains', (i) => changeList(i, (c) => c.level === 'C')],
['7. Traductions', translations],
['8. Points de vigilance clinique', clinicalVigilance],
['9. Bibliographie', bibliography],
['10. Décisions réservées au professionnel', professionalDecisions],
]
function intro(): string {
return [
'# Rapport de revue : révision de travail',
'',
'Généré par `pnpm import:equine` à partir des changements rédigés ' +
'(`curation/changes.json`). Ne pas modifier à la main. Rien n’est ' +
'publié : la révision reste un brouillon jusqu’à la décision du professionnel.',
].join('\n')
}
export function renderReviewReport(input: ReviewReportInput): string {
const sections = SECTIONS.map(
([title, render]) => `## ${title}\n\n${render(input)}`,
)
return `${[intro(), ...sections].join('\n\n')}\n`
}
-172
View File
@@ -1,172 +0,0 @@
import { ReferenceSchema } from '@faunosteo/domain'
import { z } from 'zod'
/**
* Authored curation inputs (supabase/seed/anatomical-sheets/<species>/
* curation/): a changeset of traceable changes applied on the legacy
* baseline, and the references registry they cite. Every object is strict
* so a typo in a hand-written file fails loud instead of being ignored.
*/
/** A demonstrated error, B supported improvement, C uncertain (question). */
export const ChangeLevelSchema = z.enum(['A', 'B', 'C'])
export const ChangeKindSchema = z.enum([
'correction',
'terminology',
'translation',
'restructure',
'enrichment',
'reference',
'geometry',
'removal',
'technical',
])
export const ChangePrioritySchema = z.enum(['high', 'medium', 'low'])
/** Reserved for the asset step of the pipeline, never authored. */
export const ASSET_CHANGE_ID = 'CHG-000'
const TargetSchema = z.string().min(1)
const PositionSchema = z.union([
z.number().int().min(0),
z.object({ after: z.string().min(1) }).strict(),
z.object({ before: z.string().min(1) }).strict(),
])
const ScopeSchema = z.enum(['self', 'subtree'])
/** Document-level collections an `add` on 'document' may extend. */
export const DocumentCollectionSchema = z.enum([
'references',
'categories',
'views',
'annotations',
'finding_zones',
'regions',
])
const SetOpSchema = z
.object({
op: z.literal('set'),
target: TargetSchema,
field: z.string().min(1),
value: z.unknown(),
scope: ScopeSchema.optional(),
})
.strict()
const RenameOpSchema = z
.object({
op: z.literal('rename'),
target: TargetSchema,
id: z.string().min(1),
})
.strict()
const AddOpSchema = z
.object({
op: z.literal('add'),
target: TargetSchema,
field: DocumentCollectionSchema.optional(),
value: z.unknown(),
position: PositionSchema.optional(),
})
.strict()
const RemoveOpSchema = z
.object({ op: z.literal('remove'), target: TargetSchema })
.strict()
const MoveOpSchema = z
.object({
op: z.literal('move'),
target: TargetSchema,
to: TargetSchema,
position: PositionSchema.optional(),
})
.strict()
const CiteOpSchema = z
.object({
op: z.literal('cite'),
target: TargetSchema,
reference_ids: z.array(z.string().min(1)).min(1),
scope: ScopeSchema.optional(),
})
.strict()
export const OpSchema = z.discriminatedUnion('op', [
SetOpSchema,
RenameOpSchema,
AddOpSchema,
RemoveOpSchema,
MoveOpSchema,
CiteOpSchema,
])
export const ChangeSchema = z
.object({
id: z.string().regex(/^CHG-\d{3,}$/),
level: ChangeLevelSchema,
kind: ChangeKindSchema,
title: z.object({ fr: z.string().min(1), en: z.string().min(1) }).strict(),
rationale: z.string().min(1),
reference_ids: z.array(z.string().min(1)),
question: z.string().min(1).optional(),
priority: ChangePrioritySchema.default('medium'),
ops: z.array(OpSchema).min(1),
})
.strict()
.refine((change) => change.level !== 'C' || change.question !== undefined, {
message: 'a level C change needs a question',
path: ['question'],
})
function duplicates(ids: readonly string[]): string[] {
return ids.filter((id, index) => ids.indexOf(id) !== index)
}
export const ChangesetSchema = z
.object({ changes: z.array(ChangeSchema) })
.strict()
.superRefine((set, ctx) => {
for (const id of duplicates(set.changes.map((c) => c.id))) {
ctx.addIssue({ code: 'custom', message: `duplicate change id ${id}` })
}
})
export const ReferencesFileSchema = z
.object({ references: z.array(ReferenceSchema) })
.strict()
.superRefine((file, ctx) => {
for (const id of duplicates(file.references.map((r) => r.id))) {
ctx.addIssue({ code: 'custom', message: `duplicate reference id ${id}` })
}
})
export type ChangeLevel = z.infer<typeof ChangeLevelSchema>
export type ChangeKind = z.infer<typeof ChangeKindSchema>
export type ChangePriority = z.infer<typeof ChangePrioritySchema>
export type Position = z.infer<typeof PositionSchema>
export type Op = z.infer<typeof OpSchema>
export type Change = z.output<typeof ChangeSchema>
export type ChangeInput = z.input<typeof ChangeSchema>
export type Changeset = z.output<typeof ChangesetSchema>
export type ReferencesFile = z.output<typeof ReferencesFileSchema>
/** A change as cited by its records: everything but the ops. */
export type ChangeSummary = Omit<Change, 'ops'>
/** Derived, never stored: only a demonstrated error needs no sign-off. */
export function needsConfirmation(level: ChangeLevel): boolean {
return level !== 'A'
}
export function changeSummary(change: Change): ChangeSummary {
const summary: Partial<Change> = { ...change }
delete summary.ops
return summary as ChangeSummary
}
-125
View File
@@ -1,125 +0,0 @@
import type { AssetRecord } from '../legacy/types'
/**
* Idempotent and converging PostgreSQL seed of an official sheet's working
* DRAFT. Runs as the database owner in `supabase db reset` and in the
* PGlite harness. A fresh database gets the draft through
* private.insert_sheet_draft (audited, null actor); a database still
* holding an older draft as the sheet's only version gets its content
* replaced in place. Published rows are never touched and nothing is
* published: that stays a human act through publish_sheet_version.
*/
export const DOCUMENT_DOLLAR_TAG = '$equine_doc$'
const SHEET_DESCRIPTION =
'Fiche anatomique officielle du cheval ' +
'(import des données historiques, brouillon à valider)'
export const DRAFT_CHANGE_NOTE =
'Révision de travail 4c (audit anatomique et ostéopathique) ' +
'sur l’import des données historiques'
export interface DraftSeedParams {
sheetId: string
assets: readonly AssetRecord[]
/** document.json text, embedded verbatim in a dollar-quoted literal. */
documentJson: string
changeNote: string
}
/** Only ever fed fixed values; doubled quotes keep it literal-safe. */
function sqlText(value: string): string {
return `'${value.replace(/'/g, "''")}'`
}
function header(): string {
return [
'-- Official equine anatomical sheet: working revision, DRAFT.',
'-- Generated by `pnpm import:equine` (packages/anatomy): do not edit by hand.',
'-- Idempotent and converging. Never publishes: the version stays in status',
'-- draft until a platform admin validates REVIEW-REPORT.md and publishes it.',
].join('\n')
}
function sheetInsert(sheetId: string): string {
return [
'insert into public.anatomical_sheets',
' (id, species_id, name, slug, description, creator_user_id, is_official, visibility)',
'values (',
` ${sqlText(sheetId)}, 'equine', 'Faunosteo / Cheval', 'faunosteo-cheval',`,
` ${sqlText(SHEET_DESCRIPTION)},`,
" null, true, 'private'",
')',
'on conflict (id) do nothing;',
].join('\n')
}
function assetInserts(sheetId: string, assets: readonly AssetRecord[]): string {
const rows = assets.map(
(a) =>
` (${sqlText(a.svg_asset_id)}, ${sqlText(sheetId)}, ${sqlText(a.sha256)}, ` +
`${a.byte_size}, 'image/svg+xml', ${sqlText(a.file)})`,
)
return [
'insert into public.anatomical_sheet_assets',
' (id, sheet_id, sha256, byte_size, content_type, file_name)',
'values',
rows.join(',\n'),
'on conflict (sheet_id, sha256) do nothing;',
].join('\n')
}
function documentLiteral(documentJson: string): string {
if (documentJson.includes(DOCUMENT_DOLLAR_TAG)) {
throw new Error(
`document JSON contains the dollar-quote tag ${DOCUMENT_DOLLAR_TAG}`,
)
}
return `${DOCUMENT_DOLLAR_TAG}${documentJson.trimEnd()}${DOCUMENT_DOLLAR_TAG}::jsonb`
}
function draftInsert(params: DraftSeedParams, literal: string): string {
const sheet = sqlText(params.sheetId)
return [
'select private.insert_sheet_draft(',
' null,',
` ${sheet},`,
` ${literal},`,
` ${sqlText(params.changeNote)}`,
')',
'where not exists (',
` select 1 from public.anatomical_sheet_versions where sheet_id = ${sheet}`,
');',
].join('\n')
}
/**
* Only when the sheet's single version is a draft whose content differs;
* the document literal is read once through the derived table.
*/
function draftConverge(params: DraftSeedParams, literal: string): string {
const sheet = sqlText(params.sheetId)
return [
'update public.anatomical_sheet_versions v',
`set content = d.content, change_note = ${sqlText(params.changeNote)}`,
`from (select ${literal} as content) d`,
`where v.sheet_id = ${sheet} and v.status = 'draft'`,
' and v.content <> d.content',
' and (select count(*) from public.anatomical_sheet_versions o',
` where o.sheet_id = ${sheet}) = 1;`,
].join('\n')
}
export function renderDraftSeedSql(params: DraftSeedParams): string {
const literal = documentLiteral(params.documentJson)
return (
[
header(),
sheetInsert(params.sheetId),
assetInserts(params.sheetId, params.assets),
draftInsert(params, literal),
draftConverge(params, literal),
].join('\n\n') + '\n'
)
}
-38
View File
@@ -1,38 +0,0 @@
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import type { Reference } from '@faunosteo/domain'
import { EQUINE_CURATION_DIR } from '../legacy/sources'
import { ChangesetSchema, ReferencesFileSchema, type Changeset } from './schema'
/**
* The authored curation files of the equine sheet. Both are required: a
* missing or invalid file stops the pipeline (no silent empty changeset).
*/
export const CURATION_FILES = {
references: 'references.json',
changes: 'changes.json',
} as const
export interface CurationInput {
references: Reference[]
changeset: Changeset
}
async function readJson(path: string): Promise<unknown> {
return JSON.parse(await readFile(path, 'utf8')) as unknown
}
export async function readEquineCuration(
repoRoot: string,
): Promise<CurationInput> {
const dir = join(repoRoot, EQUINE_CURATION_DIR)
const [references, changes] = await Promise.all([
readJson(join(dir, CURATION_FILES.references)),
readJson(join(dir, CURATION_FILES.changes)),
])
return {
references: ReferencesFileSchema.parse(references).references,
changeset: ChangesetSchema.parse(changes),
}
}
-133
View File
@@ -1,133 +0,0 @@
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
import { allFindings, type FindingEntry, type Item } from './targets'
/**
* Volumes of a sheet document, compared before / after curation in the
* CHANGELOG and shown for the baseline in the review report. Nodes count
* finding categories too, as countTree does in the import report.
*/
const ANNOTATION_KINDS = ['point', 'zone', 'detail_trigger'] as const
const REVIEW_STATUSES = ['inherited', 'reviewed', 'to_confirm'] as const
type Counts = Record<string, number>
export interface DocumentStats {
views: number
assets: number
annotations: number
annotationsByKind: Counts
annotationCategories: number
findingZones: number
findingCategories: number
nodes: number
leaves: number
vetReferrals: number
descriptions: number
descriptionsFrOnly: number
references: number
citedNodes: number
nodesByReviewStatus: Counts
annotationsByReviewStatus: Counts
regionsWithCountRange: number
}
function countBy<T>(
items: readonly T[],
keys: readonly string[],
key: (item: T) => string,
) {
const counts: Counts = Object.fromEntries(keys.map((k) => [k, 0]))
for (const item of items) counts[key(item)] = (counts[key(item)] ?? 0) + 1
return counts
}
function description(item: Item): { fr: boolean; en: boolean } {
const text = (item.description ?? {}) as { fr?: string; en?: string }
return { fr: Boolean(text.fr), en: Boolean(text.en) }
}
function isLeaf(entry: FindingEntry): boolean {
const children = entry.item.children
return !Array.isArray(children) || children.length === 0
}
function isCited(entry: FindingEntry): boolean {
const ids = entry.item.reference_ids
return Array.isArray(ids) && ids.length > 0
}
function findingStats(findings: readonly FindingEntry[]) {
const texts = findings.map((entry) => description(entry.item))
return {
findingCategories: findings.filter((entry) => entry.isCategory).length,
nodes: findings.length,
leaves: findings.filter(isLeaf).length,
vetReferrals: findings.filter((e) => e.item.requires_vet_referral === true)
.length,
descriptions: texts.filter((t) => t.fr || t.en).length,
descriptionsFrOnly: texts.filter((t) => t.fr && !t.en).length,
citedNodes: findings.filter(isCited).length,
nodesByReviewStatus: countBy(findings, REVIEW_STATUSES, (e) =>
String(e.item.review_status ?? 'inherited'),
),
}
}
export function documentStats(
doc: AnatomicalSheetDocumentInput,
): DocumentStats {
const assets = doc.views.flatMap((v) =>
v.svg_asset_id ? [v.svg_asset_id] : [],
)
return {
views: doc.views.length,
assets: new Set(assets).size,
annotations: doc.annotations.length,
annotationsByKind: countBy(
doc.annotations,
ANNOTATION_KINDS,
(a) => a.kind,
),
annotationCategories: doc.categories.length,
findingZones: doc.finding_zones.length,
...findingStats(allFindings(doc as unknown as Item)),
references: doc.references.length,
annotationsByReviewStatus: countBy(doc.annotations, REVIEW_STATUSES, (a) =>
String(a.review_status ?? 'inherited'),
),
regionsWithCountRange: doc.vertebral_config.regions.filter(
(r) => r.count_range,
).length,
}
}
function countRows(label: string, counts: Counts): Array<[string, number]> {
return Object.entries(counts).map(([key, value]) => [
`${label} (${key})`,
value,
])
}
/** Labelled rows, fixed order, French labels. */
export function statRows(stats: DocumentStats): Array<[string, number]> {
return [
['Vues', stats.views],
['Dessins SVG distincts', stats.assets],
['Annotations', stats.annotations],
...countRows('Annotations', stats.annotationsByKind),
...countRows('Annotations, revue', stats.annotationsByReviewStatus),
["Catégories d'annotation", stats.annotationCategories],
['Zones de constats', stats.findingZones],
['Catégories de constats', stats.findingCategories],
['Nœuds (catégories incluses)', stats.nodes],
['Feuilles', stats.leaves],
['Renvois vétérinaires', stats.vetReferrals],
...countRows('Nœuds, revue', stats.nodesByReviewStatus),
['Descriptions', stats.descriptions],
['Descriptions en français seulement', stats.descriptionsFrOnly],
['Références bibliographiques', stats.references],
['Nœuds cités', stats.citedNodes],
['Régions vertébrales avec plage documentée', stats.regionsWithCountRange],
]
}
-195
View File
@@ -1,195 +0,0 @@
/**
* Target grammar of the changeset (one string per target):
*
* document | region:<code> | reference:<id> | category:<id> | view:<id>
* annotation:<id> | zone:<zoneId> | finding:<zoneId>/<catId>[/<nodeId>…]
*
* A finding path walks ids from the zone down; ids are unique among
* siblings, so the path names one category or node. Resolution works on
* the plain JSON form of the document: the changeset reaches any field
* without one accessor per type, and the final Zod parse checks the shape.
*/
export type Item = Record<string, unknown>
export type TargetKind =
| 'document'
| 'region'
| 'reference'
| 'category'
| 'view'
| 'annotation'
| 'zone'
| 'finding'
export interface ParsedTarget {
kind: TargetKind
ids: string[]
}
/** A resolved target: the item and the list that holds it (null: root). */
export interface Located {
target: ParsedTarget
siblings: Item[] | null
item: Item
}
/** One finding category or node met while walking a zone's tree. */
export interface FindingEntry {
target: string
item: Item
isCategory: boolean
}
const COLLECTION_KINDS: ReadonlySet<string> = new Set([
'region',
'reference',
'category',
'view',
'annotation',
'zone',
'finding',
])
export function isItem(value: unknown): value is Item {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
export function parseTarget(target: string): ParsedTarget {
if (target === 'document') return { kind: 'document', ids: [] }
const colon = target.indexOf(':')
const kind = target.slice(0, colon)
const rest = target.slice(colon + 1)
if (colon < 1 || !COLLECTION_KINDS.has(kind) || rest === '') {
throw new Error(`unknown target "${target}"`)
}
const ids = kind === 'finding' ? rest.split('/') : [rest]
if (ids.includes('') || (kind === 'finding' && ids.length < 2)) {
throw new Error(`malformed target "${target}"`)
}
return { kind: kind as TargetKind, ids }
}
export function formatTarget(target: ParsedTarget): string {
if (target.kind === 'document') return 'document'
return `${target.kind}:${target.ids.join('/')}`
}
/** Regions are keyed by their free code, everything else by a stable id. */
export function keyField(kind: TargetKind): 'id' | 'code' {
return kind === 'region' ? 'code' : 'id'
}
function listAt(holder: Item, key: string): Item[] {
const list = holder[key]
if (!Array.isArray(list)) throw new Error(`document has no list "${key}"`)
return list as Item[]
}
/** Top-level list holding the items of a target kind. */
export function topCollection(doc: Item, kind: TargetKind): Item[] {
switch (kind) {
case 'region':
return listAt(doc.vertebral_config as Item, 'regions')
case 'reference':
return listAt(doc, 'references')
case 'category':
return listAt(doc, 'categories')
case 'view':
return listAt(doc, 'views')
case 'annotation':
return listAt(doc, 'annotations')
default:
return listAt(doc, 'finding_zones')
}
}
function findIn(list: Item[], key: string, id: string, target: string): Item {
const item = list.find((entry) => entry[key] === id)
if (!item) throw new Error(`unknown target "${target}" (no "${id}")`)
return item
}
/** Children of a finding item; lean leaves get an empty list on demand. */
export function childrenOf(item: Item): Item[] {
if (!Array.isArray(item.children)) item.children = []
return item.children as Item[]
}
function locateFinding(doc: Item, target: ParsedTarget, raw: string) {
const zone = findIn(topCollection(doc, 'zone'), 'id', target.ids[0]!, raw)
let siblings = listAt(zone, 'categories')
let item = findIn(siblings, 'id', target.ids[1]!, raw)
for (const id of target.ids.slice(2)) {
siblings = Array.isArray(item.children) ? (item.children as Item[]) : []
item = findIn(siblings, 'id', id, raw)
}
return { target, siblings, item }
}
/** Resolves a target string or throws "unknown target". */
export function locate(doc: Item, raw: string): Located {
const target = parseTarget(raw)
if (target.kind === 'document') return { target, siblings: null, item: doc }
if (target.kind === 'finding') return locateFinding(doc, target, raw)
const siblings = topCollection(doc, target.kind)
const item = findIn(siblings, keyField(target.kind), target.ids[0]!, raw)
return { target, siblings, item }
}
/** The item and every descendant node, depth first, in document order. */
function walk(item: Item, target: string, depth: number): FindingEntry[] {
const own = { target, item, isCategory: depth === 0 }
const children = Array.isArray(item.children) ? (item.children as Item[]) : []
const nested = children.flatMap((child) =>
walk(child, `${target}/${String(child.id)}`, depth + 1),
)
return [own, ...nested]
}
/** Every finding category and node of a zone, depth first. */
export function zoneFindings(zone: Item): FindingEntry[] {
return listAt(zone, 'categories').flatMap((category) =>
walk(category, `finding:${String(zone.id)}/${String(category.id)}`, 0),
)
}
/** Every finding category and node of the document. */
export function allFindings(doc: Item): FindingEntry[] {
return topCollection(doc, 'zone').flatMap(zoneFindings)
}
/**
* Finding items an op touches. A finding target alone ('self') or with its
* descendants ('subtree'); a zone target stands for its categories alone
* ('self') or its whole tree ('subtree'): a zone carries no citation.
*/
export function findingScope(
located: Located,
scope: 'self' | 'subtree',
): FindingEntry[] {
const { target, item } = located
if (target.kind === 'zone') {
const entries = zoneFindings(item)
return scope === 'subtree' ? entries : entries.filter((e) => e.isCategory)
}
if (target.kind !== 'finding') {
throw new Error(`"${formatTarget(target)}" is not a finding or a zone`)
}
const depth = target.ids.length === 2 ? 0 : 1
const entries = walk(item, formatTarget(target), depth)
return scope === 'subtree' ? entries : entries.slice(0, 1)
}
/** The list an add or a move inserts into under a zone or a finding. */
export function childList(parent: Located): Item[] {
if (parent.target.kind === 'zone') return listAt(parent.item, 'categories')
if (parent.target.kind === 'finding') return childrenOf(parent.item)
throw new Error(`"${formatTarget(parent.target)}" holds no findings`)
}
/** Target prefix of the items of childList(parent). */
export function childPrefix(parent: Located): string {
if (parent.target.kind === 'zone') return `finding:${parent.target.ids[0]}/`
return `${formatTarget(parent.target)}/`
}
-49
View File
@@ -1,49 +0,0 @@
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
import type { ChangeSummary, Op } from './schema'
import type { Item } from './targets'
/**
* One elementary edit of the curated document, kept for the CHANGELOG.
* `before` / `after` are deep copies: the field value for a set, the whole
* item for a rename, remove or move, null on the missing side.
*/
export interface ChangeRecord {
change: ChangeSummary
op: Op
target: string
field: string | null
before: unknown
after: unknown
}
export interface CurationResult {
document: AnatomicalSheetDocumentInput
records: ChangeRecord[]
}
/** State shared by the op functions of one change. */
export interface OpContext {
doc: Item
change: ChangeSummary
op: Op
records: ChangeRecord[]
/** Items the change edited, in order; the applier marks them at the end. */
touched: Item[]
}
/** Absent values are recorded as null so records stay plain JSON. */
export function record(
ctx: OpContext,
target: string,
field: string | null,
values: { before: unknown; after: unknown },
): void {
ctx.records.push({
change: ctx.change,
op: ctx.op,
target,
field,
before: structuredClone(values.before ?? null),
after: structuredClone(values.after ?? null),
})
}
-30
View File
@@ -1,30 +0,0 @@
import { format } from 'prettier'
/**
* Prettier formatting of the generated artifacts with the repository
* options, so `prettier --check` accepts the committed files as generated
* (no exclusion needed). Shared by the legacy import and the draft.
*/
const PRETTIER_OPTIONS = {
semi: false,
singleQuote: true,
tabWidth: 2,
useTabs: false,
trailingComma: 'all',
printWidth: 80,
bracketSpacing: true,
arrowParens: 'always',
endOfLine: 'lf',
} as const
export function formatJson(value: unknown): Promise<string> {
return format(JSON.stringify(value, null, 2), {
...PRETTIER_OPTIONS,
parser: 'json',
})
}
export function formatMarkdown(text: string): Promise<string> {
return format(text, { ...PRETTIER_OPTIONS, parser: 'markdown' })
}
-3
View File
@@ -1,3 +0,0 @@
export * from './legacy'
export * from './curation'
export * from './render'
-207
View File
@@ -1,207 +0,0 @@
import type {
AnatomicalSheetDocumentInput,
Geometry,
Laterality,
} from '@faunosteo/domain'
import { normaliseCategoryId } from './categories'
import { slugify } from './ids'
import { inferRegionCode } from './regions'
import type { LegacyAnnotation } from './svg'
import type { Anomaly, AnnotationRow, RegionInference } from './types'
/**
* Legacy SVG annotation → canonical annotation. The finding zone link is
* resolved here, once, by exact FR + EN equality with the catalog (audit 06
* §4); the document then carries finding_zone_id explicitly and nothing
* matches labels at runtime.
*/
export interface AnnotationContext {
viewId: string
fileName: string
/** `${name_fr}\n${name_en}` → catalog zone key. */
zoneByNames: ReadonlyMap<string, string>
}
/** Authoring form: review_status stays implicit ('inherited'). */
export type AnnotationInput =
AnatomicalSheetDocumentInput['annotations'][number]
export interface MappedAnnotation {
annotation: AnnotationInput
row: AnnotationRow
region: RegionInference | null
anomalies: Anomaly[]
}
export function zoneNameKey(fr: string, en: string): string {
return `${fr}\n${en}`
}
function anomaly(code: string, subject: string, message: string): Anomaly {
return { code, level: 'a_valider', subject, message }
}
function laterality(a: LegacyAnnotation, out: Anomaly[]): Laterality {
if (a.lateral === 'bilateral') return 'bilateral'
if (a.lateral === null || a.lateral === 'unpaired') return 'unpaired'
out.push(
anomaly(
'annotation.laterality.unknown',
a.id,
`Latéralité « ${a.lateral} » inconnue, importée en « unpaired ».`,
),
)
return 'unpaired'
}
function describeGeometry(geometry: Geometry | null): string {
if (geometry === null) return 'aucune'
if (geometry.type === 'circle') {
return `cercle (${geometry.cx}, ${geometry.cy}) r ${geometry.r}`
}
if (geometry.type === 'polygon') {
return `polygone ${geometry.points.length} points`
}
return 'chemin'
}
function regionOf(a: LegacyAnnotation, out: Anomaly[]): RegionInference | null {
if (a.special === null) return null
if (a.special !== 'vertebral-precision') {
out.push(
anomaly(
'annotation.special.unknown',
a.id,
`special « ${a.special} » ignoré.`,
),
)
return null
}
const match = inferRegionCode(a.nameFr, a.nameEn)
if (!match) {
out.push(
anomaly(
'annotation.region.unknown',
a.id,
'Région vertébrale non déduite.',
),
)
}
return {
annotationId: a.id,
label: match?.label ?? a.nameFr ?? a.nameEn ?? a.id,
root: match?.root ?? null,
code: match?.code ?? null,
}
}
function triggerName(a: LegacyAnnotation, out: Anomaly[]) {
if (a.nameFr && a.nameEn) return { fr: a.nameFr, en: a.nameEn }
out.push({
code: 'annotation.trigger.unnamed',
level: 'informatif',
subject: a.id,
message:
'Déclencheur de vue détail sans nom (name null), comme dans le SVG.',
})
return null
}
function mapTrigger(
a: LegacyAnnotation,
ctx: AnnotationContext,
out: Anomaly[],
) {
const annotation: AnnotationInput = {
id: `${a.opensDetail}-trigger`,
kind: 'detail_trigger',
view_id: ctx.viewId,
category_id: normaliseCategoryId(a.category ?? ''),
laterality: laterality(a, out),
geometry: a.geometry,
name: triggerName(a, out),
opens_view_id: a.opensDetail ?? '',
}
return { annotation, region: null }
}
/** Missing labels fall back to the other language, never silently. */
function observableName(a: LegacyAnnotation, out: Anomaly[]) {
const fr = a.nameFr ?? a.nameEn ?? a.id
if (a.nameFr === null) {
out.push(
anomaly(
'annotation.name_fr.missing',
a.id,
`data-anno-name-fr absent : nom FR repris de « ${fr} ».`,
),
)
}
if (a.nameEn === null) {
out.push(
anomaly(
'annotation.name_en.missing',
a.id,
`data-anno-name-en absent : nom EN copié du FR « ${fr} », à traduire.`,
),
)
}
return { fr, en: a.nameEn ?? fr }
}
function mapObservable(
a: LegacyAnnotation,
ctx: AnnotationContext,
out: Anomaly[],
) {
const name = observableName(a, out)
const zoneId = ctx.zoneByNames.get(zoneNameKey(name.fr, name.en)) ?? null
if (zoneId === null) {
out.push(
anomaly(
'annotation.unmapped',
a.id,
'Annotation non reliée à une zone de constats.',
),
)
}
const region = regionOf(a, out)
const annotation: AnnotationInput = {
id: zoneId ?? slugify(name.en),
kind: a.tagName === 'circle' ? 'point' : 'zone',
view_id: ctx.viewId,
category_id: normaliseCategoryId(a.category ?? ''),
laterality: laterality(a, out),
geometry: a.geometry,
name,
finding_zone_id: zoneId,
vertebral_region_code: region?.code ?? null,
}
return { annotation, region }
}
export function mapAnnotation(
a: LegacyAnnotation,
ctx: AnnotationContext,
): MappedAnnotation {
const anomalies: Anomaly[] = []
const { annotation, region } = a.opensDetail
? mapTrigger(a, ctx, anomalies)
: mapObservable(a, ctx, anomalies)
const row: AnnotationRow = {
legacyId: a.id,
newId: annotation.id,
viewId: ctx.viewId,
kind: annotation.kind,
laterality: annotation.laterality,
regionCode:
annotation.kind === 'detail_trigger'
? null
: annotation.vertebral_region_code,
findingZoneId:
annotation.kind === 'detail_trigger' ? null : annotation.finding_zone_id,
geometry: describeGeometry(annotation.geometry),
}
return { annotation, row, region, anomalies }
}
-22
View File
@@ -1,22 +0,0 @@
import { formatJson, formatMarkdown } from '../format'
import { renderImportReport } from './report'
import type { ImportResult } from './types'
/**
* Text artifacts of the generated legacy-import folder, keyed by path
* relative to supabase/seed/anatomical-sheets/equine/legacy-import/. This
* folder is the baseline of the curation: it carries no SQL, the draft
* folder holds the only seed.
*/
/** Deterministic: same result in, same bytes out. */
export async function renderArtifacts(
result: ImportResult,
): Promise<Record<string, string>> {
return {
'document.json': await formatJson(result.document),
'legacy-id-map.json': await formatJson(result.legacyIdMap),
'assets.json': await formatJson(result.assets),
'IMPORT-REPORT.md': await formatMarkdown(renderImportReport(result)),
}
}
@@ -1,41 +0,0 @@
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
import type { Anomaly } from './types'
/**
* Lists every FR/EN text the importer writes itself (no source file holds
* it), derived from the document so the list can never drift from what is
* written. Annotation categories are reported by categories.ts.
*/
export const AUTHORED_LABEL_CODE = 'label.authored'
function authored(subject: string, text: { fr?: string; en?: string }) {
const parts = [
text.fr === undefined ? null : `FR « ${text.fr} »`,
text.en === undefined ? null : `EN « ${text.en} »`,
].filter((part): part is string => part !== null)
const anomaly: Anomaly = {
code: AUTHORED_LABEL_CODE,
level: 'a_valider',
subject,
message: `Libellé écrit par l'importateur : ${parts.join(', ')}.`,
}
return anomaly
}
export function regionLabelSubject(code: string): string {
return `vertebral_config.${code}`
}
export function authoredLabelAnomalies(
document: AnatomicalSheetDocumentInput,
): Anomaly[] {
return [
authored('name', document.name),
authored('description', document.description),
...document.views.map((v) => authored(`views.${v.id}`, v.name)),
...document.vertebral_config.regions.map((r) =>
authored(regionLabelSubject(r.code), r.name),
),
]
}
@@ -1,102 +0,0 @@
import type { LegacyCatalog, LegacyNode } from './catalog'
import type { Anomaly } from './types'
/**
* Catalog-wide findings that need a business decision or an explanation.
* Nothing here alters the data: the importer copies the catalog verbatim
* and these checks only describe what a reviewer must know.
*/
const PREFIXED = /^(.+)-(dysfunctions|observations)$/
/** A prefixed category id that names another zone (sphenoid → ssb-…). */
function foreignPrefixAnomalies(catalog: LegacyCatalog): Anomaly[] {
const zoneIds = Object.keys(catalog.zones)
const out: Anomaly[] = []
for (const [zoneId, zone] of Object.entries(catalog.zones)) {
for (const category of zone.categories) {
const match = PREFIXED.exec(category.id)
if (!match || match[1] === zoneId || !zoneIds.includes(match[1]!))
continue
out.push({
code: 'finding.category.foreign_prefix',
level: 'a_valider',
subject: `${zoneId}/${category.id}`,
message:
`Identifiant de catégorie dupliqué entre ${zoneId} et ${match[1]} ; ` +
`${zoneId}-${match[2]} attendu ; décision ostéopathe requise. ` +
'Importé tel quel (non renommé).',
})
}
}
return out
}
function childIds(category: LegacyNode): string {
return (category.children ?? []).map((c) => c.id).join(', ')
}
/** Same 'anamnesis' id everywhere, different content per zone family. */
function anamnesisVariants(catalog: LegacyCatalog): Anomaly[] {
const variants = new Map<string, string[]>()
for (const [zoneId, zone] of Object.entries(catalog.zones)) {
const category = zone.categories.find((c) => c.id === 'anamnesis')
if (!category) continue
const key = childIds(category)
variants.set(key, [...(variants.get(key) ?? []), zoneId])
}
return [...variants.entries()].map(([children, zones], index) => ({
code: 'finding.anamnesis.variant',
level: 'informatif',
subject: `anamnesis variante ${index + 1}/${variants.size}`,
message: `Zones ${zones.join(', ')} : ${children}.`,
}))
}
function collectIds(nodes: readonly LegacyNode[], into: Set<string>): void {
for (const node of nodes) {
into.add(node.id)
collectIds(node.children ?? [], into)
}
}
/** Locale-independent order: artifacts must not vary with the process. */
function byCodePoint(a: string, b: string): number {
if (a === b) return 0
return a < b ? -1 : 1
}
/** Node ids are unique among siblings only; a finding is (zone, path). */
function crossZoneDuplicates(catalog: LegacyCatalog): Anomaly[] {
const zonesById = new Map<string, number>()
for (const zone of Object.values(catalog.zones)) {
const ids = new Set<string>()
collectIds(zone.categories, ids)
for (const id of ids) zonesById.set(id, (zonesById.get(id) ?? 0) + 1)
}
const shared = [...zonesById.entries()].filter(([, n]) => n > 1)
const top = [...shared].sort((a, b) => b[1] - a[1] || byCodePoint(a[0], b[0]))
return [
{
code: 'finding.id.shared_across_zones',
level: 'informatif',
subject: `${shared.length} identifiants`,
message:
'Identifiants de nœuds réutilisés entre zones (unicité entre frères ' +
'seulement, adressage par zone + chemin). Les plus fréquents : ' +
top
.slice(0, 8)
.map(([id, n]) => `${id} (${n})`)
.join(', ') +
'.',
},
]
}
export function catalogAnomalies(catalog: LegacyCatalog): Anomaly[] {
return [
...foreignPrefixAnomalies(catalog),
...anamnesisVariants(catalog),
...crossZoneDuplicates(catalog),
]
}
-249
View File
@@ -1,249 +0,0 @@
import type {
FindingCategoryKind,
FindingNodeInput,
LocalizedOptionalText,
} from '@faunosteo/domain'
import { isStableId, slugify } from './ids'
import type { Anomaly, ZoneStats } from './types'
/**
* Legacy findings catalog (pathologies.json, schema 2.0) → canonical
* finding zones in the lean authoring form: optional keys are written only
* when the source carries them, so the document stays as small as the
* catalog and the parser fills the defaults.
*/
export interface LegacyNode {
id: string
name_fr: string
name_en: string
description_fr?: string
description_en?: string
requires_vet_referral?: boolean
/** Inline citations of the legacy format; none exist, see importer guard. */
sources?: unknown[]
children?: LegacyNode[]
}
export interface LegacyZone {
id: string
name_fr: string
name_en: string
categories: LegacyNode[]
}
export interface LegacyCatalog {
schema_version: string
scope_disclaimer?: string
species?: { id: string; name_fr: string; name_en: string }
zones: Record<string, LegacyZone>
}
export interface CategoryInput {
id: string
kind: FindingCategoryKind
name: { fr: string; en: string }
description?: LocalizedOptionalText
children: FindingNodeInput[]
}
export interface ZoneInput {
id: string
name: { fr: string; en: string }
categories: CategoryInput[]
}
export interface MappedCatalog {
zones: ZoneInput[]
zoneStats: ZoneStats[]
nodeIdMap: Record<string, string>
missingDescriptionEn: number
sources: number
anomalies: Anomaly[]
}
/** Mutable tallies of one catalog walk; never shared between runs. */
interface WalkState {
nodeIdMap: Record<string, string>
anomalies: Anomaly[]
missingDescriptionEn: number
sources: number
}
export function parseLegacyCatalog(json: string): LegacyCatalog {
const catalog = JSON.parse(json) as LegacyCatalog
if (typeof catalog?.zones !== 'object' || catalog.zones === null) {
throw new Error('pathologies.json: "zones" object missing')
}
return catalog
}
export function categoryKind(categoryId: string): FindingCategoryKind {
if (categoryId.endsWith('-dysfunctions')) return 'dysfunction'
if (categoryId.endsWith('-observations')) return 'consultation_reason'
if (categoryId === 'anamnesis') return 'anamnesis'
return 'custom'
}
function description(node: LegacyNode): LocalizedOptionalText | undefined {
if (node.description_fr === undefined && node.description_en === undefined) {
return undefined
}
const text: LocalizedOptionalText = {}
if (node.description_fr !== undefined) text.fr = node.description_fr
if (node.description_en !== undefined) text.en = node.description_en
return text
}
function stableNodeId(id: string, path: string[], state: WalkState): string {
if (isStableId(id)) return id
const next = slugify(id) || 'node'
const key = [...path, id].join('/')
state.nodeIdMap[key] = next
state.anomalies.push({
code: 'finding.id.slugified',
level: 'a_valider',
subject: key,
message: `Identifiant hors motif stable, remplacé par « ${next} ».`,
})
return next
}
function tallyNode(node: LegacyNode, state: WalkState): void {
if (node.description_fr !== undefined && node.description_en === undefined) {
state.missingDescriptionEn += 1
}
state.sources += node.sources?.length ?? 0
}
function mapNode(
node: LegacyNode,
path: string[],
state: WalkState,
): FindingNodeInput {
tallyNode(node, state)
const id = stableNodeId(node.id, path, state)
const out: FindingNodeInput = {
id,
name: { fr: node.name_fr, en: node.name_en },
}
const text = description(node)
if (text) out.description = text
if (node.requires_vet_referral === true) out.requires_vet_referral = true
if (node.children) {
out.children = node.children.map((c) =>
mapNode(c, [...path, node.id], state),
)
}
return out
}
function mapCategory(
zoneId: string,
category: LegacyNode,
state: WalkState,
): CategoryInput {
tallyNode(category, state)
const kind = categoryKind(category.id)
if (kind === 'custom') {
state.anomalies.push({
code: 'finding.category.kind_unknown',
level: 'a_valider',
subject: `${zoneId}/${category.id}`,
message: 'Type de catégorie non reconnu, importé en « custom ».',
})
}
const path = [zoneId, category.id]
const out: CategoryInput = {
id: stableNodeId(category.id, [zoneId], state),
kind,
name: { fr: category.name_fr, en: category.name_en },
children: (category.children ?? []).map((c) => mapNode(c, path, state)),
}
const text = description(category)
if (text) out.description = text
return out
}
/** Counts categories as nodes, as the audit does (792 = 78 + 714). */
export function countTree(
nodes: ReadonlyArray<LegacyNode | FindingNodeInput>,
): TreeCounts {
let total = { nodes: 0, leaves: 0, vetReferrals: 0 }
for (const node of nodes) {
const children = node.children ?? []
const sub = countTree(children)
total = {
nodes: total.nodes + 1 + sub.nodes,
leaves: total.leaves + sub.leaves + (children.length === 0 ? 1 : 0),
vetReferrals:
total.vetReferrals +
sub.vetReferrals +
(node.requires_vet_referral ? 1 : 0),
}
}
return total
}
function zoneStatsOf(zone: LegacyZone): ZoneStats {
const counts = countTree(zone.categories)
const categoryLeaves = zone.categories.filter((c) => !c.children?.length)
return {
zoneId: zone.id,
nodes: counts.nodes,
leaves: counts.leaves - categoryLeaves.length,
vetReferrals: counts.vetReferrals,
}
}
export interface TreeCounts {
nodes: number
leaves: number
vetReferrals: number
}
/** Throws when the output tree does not hold exactly the input tree. */
export function assertNothingDropped(
zoneId: string,
before: TreeCounts,
after: TreeCounts,
): void {
const keys = ['nodes', 'leaves', 'vetReferrals'] as const
const diff = keys.filter((key) => before[key] !== after[key])
if (diff.length === 0) return
const detail = diff.map((k) => `${k} ${before[k]} in, ${after[k]} out`)
throw new Error(`zone ${zoneId}: ${detail.join('; ')}`)
}
function mapZone(key: string, zone: LegacyZone, state: WalkState): ZoneInput {
if (zone.id !== key) throw new Error(`zone key ${key} ≠ id ${zone.id}`)
const mapped: ZoneInput = {
id: key,
name: { fr: zone.name_fr, en: zone.name_en },
categories: zone.categories.map((c) => mapCategory(key, c, state)),
}
assertNothingDropped(
key,
countTree(zone.categories),
countTree(mapped.categories),
)
return mapped
}
export function mapCatalog(catalog: LegacyCatalog): MappedCatalog {
const state: WalkState = {
nodeIdMap: {},
anomalies: [],
missingDescriptionEn: 0,
sources: 0,
}
const entries = Object.entries(catalog.zones)
return {
zones: entries.map(([key, zone]) => mapZone(key, zone, state)),
zoneStats: entries.map(([, zone]) => zoneStatsOf(zone)),
nodeIdMap: state.nodeIdMap,
missingDescriptionEn: state.missingDescriptionEn,
sources: state.sources,
anomalies: state.anomalies,
}
}
-98
View File
@@ -1,98 +0,0 @@
import type { AnnotationCategory } from '@faunosteo/domain'
import type { LegacyAnnotation } from './svg'
import type { Anomaly } from './types'
/**
* SVG annotation categories → canonical categories. The legacy editor
* slugified labels byte-wise, so accented letters became '-'
* ("Charnières vertébrales" → charni-res-vert-brales). Those technical
* slugs are normalised here and every change is reported; labels the
* importer had to write are reported as "to validate".
*/
/** Degraded legacy slug → real slug. Other slugs are kept as they are. */
const SLUG_FIXES: Readonly<Record<string, string>> = {
'charni-res-vert-brales': 'charnieres-vertebrales',
'cadrans-du-cr-ne': 'cadrans-du-crane',
}
/** Labels authored by the importer, keyed by normalised slug. */
const LABELS: Readonly<Record<string, { fr: string; en: string }>> = {
articulations: { fr: 'Articulations', en: 'Joints' },
os: { fr: 'Os', en: 'Bones' },
'zone-colonne': { fr: 'Zone colonne', en: 'Spine' },
'charnieres-vertebrales': {
fr: 'Charnières vertébrales',
en: 'Vertebral hinges',
},
'cadrans-du-crane': { fr: 'Cadrans du crâne', en: 'Skull quadrants' },
}
export interface MappedCategories {
categories: AnnotationCategory[]
idMap: Record<string, string>
anomalies: Anomaly[]
}
export function normaliseCategoryId(legacy: string): string {
return SLUG_FIXES[legacy] ?? legacy
}
/**
* data-anno-category-name is used only when it is a real label: in the
* equine SVGs it repeats the slug ("articulations", "os"), so the readable
* label of the table wins and the report says so.
*/
function frenchName(legacy: string, categoryName: string | null): string {
const id = normaliseCategoryId(legacy)
if (categoryName && categoryName !== legacy) return categoryName
return LABELS[id]?.fr ?? id
}
function labelAnomaly(id: string, fr: string, en: string): Anomaly {
return {
code: 'category.label.authored',
level: 'a_valider',
subject: id,
message: `Libellé écrit par l'importateur : FR « ${fr} », EN « ${en} ».`,
}
}
function slugAnomaly(legacy: string, id: string): Anomaly {
return {
code: 'category.slug.normalised',
level: 'a_valider',
subject: legacy,
message: `Slug technique dégradé (accents perdus) normalisé en « ${id} ».`,
}
}
function firstSeen(annotations: readonly LegacyAnnotation[]) {
const seen = new Map<string, string | null>()
for (const a of annotations) {
if (a.category === null) continue
if (!seen.has(a.category) || seen.get(a.category) === null) {
seen.set(a.category, a.categoryName)
}
}
return seen
}
/** Categories in order of first appearance across the SVGs. */
export function mapCategories(
annotations: readonly LegacyAnnotation[],
): MappedCategories {
const result: MappedCategories = { categories: [], idMap: {}, anomalies: [] }
for (const [legacy, categoryName] of firstSeen(annotations)) {
const id = normaliseCategoryId(legacy)
const name = {
fr: frenchName(legacy, categoryName),
en: LABELS[id]?.en ?? id,
}
result.categories.push({ id, name, color: null })
result.idMap[legacy] = id
if (id !== legacy) result.anomalies.push(slugAnomaly(legacy, id))
result.anomalies.push(labelAnomaly(id, name.fr, name.en))
}
return result
}
-54
View File
@@ -1,54 +0,0 @@
import { createHash } from 'node:crypto'
import { STABLE_ID_PATTERN } from '@faunosteo/domain'
/**
* Deterministic identifiers. The importer must produce byte-identical
* output across runs, so nothing here is random or time-based.
*
* UUIDs are name-based in the RFC 4122 version 5 style, with SHA-256 in
* place of SHA-1: the first 16 bytes of sha256(<namespace string>), the
* version nibble forced to 5 and the variant bits to 10xx. Assets use
* 'faunosteo:asset:' + the file's sha256 (same bytes, same id), the sheet
* uses 'faunosteo:sheet:<species>:v<n>'.
*/
export function sha256Hex(data: Uint8Array | string): string {
return createHash('sha256').update(data).digest('hex')
}
export function deterministicUuid(name: string): string {
const bytes = createHash('sha256').update(name).digest().subarray(0, 16)
bytes[6] = (bytes[6] & 0x0f) | 0x50
bytes[8] = (bytes[8] & 0x3f) | 0x80
const hex = bytes.toString('hex')
return [
hex.slice(0, 8),
hex.slice(8, 12),
hex.slice(12, 16),
hex.slice(16, 20),
hex.slice(20, 32),
].join('-')
}
export function assetIdFromSha256(fileSha256: string): string {
return deterministicUuid(`faunosteo:asset:${fileSha256}`)
}
export function sheetIdFor(speciesId: string, version: number): string {
return deterministicUuid(`faunosteo:sheet:${speciesId}:v${version}`)
}
/** Lowercase, accents stripped (NFD), every other run of chars → '-'. */
export function slugify(label: string): string {
return label
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 64)
}
export function isStableId(id: string): boolean {
return STABLE_ID_PATTERN.test(id)
}
-343
View File
@@ -1,343 +0,0 @@
import {
AnatomicalSheetDocumentSchema,
SHEET_DOCUMENT_SCHEMA_VERSION,
validateSheetDocument,
type AnatomicalSheetDocumentInput,
type SheetView,
} from '@faunosteo/domain'
import {
mapAnnotation,
zoneNameKey,
type AnnotationInput,
type MappedAnnotation,
} from './annotations'
import {
mapCatalog,
parseLegacyCatalog,
type LegacyCatalog,
type MappedCatalog,
} from './catalog'
import { authoredLabelAnomalies } from './authored-labels'
import { catalogAnomalies } from './catalog-checks'
import { mapCategories, type MappedCategories } from './categories'
import { assetIdFromSha256, sha256Hex, sheetIdFor } from './ids'
import { parseAnnotatedSvg, type ParsedSvg } from './svg'
import type {
Anomaly,
AssetRecord,
EquineLegacyInput,
ImportResult,
ImportStats,
LegacyIdMap,
SourceDigest,
SvgSource,
} from './types'
import {
parseVertebralFormula,
vertebralRegions,
type LegacyVertebralFormula,
} from './vertebrae'
/**
* One-off, deterministic import of the historical equine assets into the
* first canonical anatomical sheet document (Step 4b). The result is a
* DRAFT for business review: every correction is listed in `anomalies`,
* nothing is published.
*/
export const EQUINE_SPECIES_ID = 'equine'
export const EQUINE_SHEET_VERSION = 1
export const MAIN_VIEW_ID = 'main'
export const HEAD_VIEW_ID = 'head'
interface ParsedSources {
assets: AssetRecord[]
main: ParsedSvg
head: ParsedSvg
catalog: LegacyCatalog
formula: LegacyVertebralFormula
}
interface Mapped {
annotations: MappedAnnotation[]
categories: MappedCategories
catalog: MappedCatalog
}
function assetRecord(source: SvgSource): AssetRecord {
const sha256 = sha256Hex(source.bytes)
return {
file: source.fileName,
sha256,
byte_size: source.bytes.byteLength,
svg_asset_id: assetIdFromSha256(sha256),
}
}
function textDigest(file: string, text: string): SourceDigest {
const bytes = new TextEncoder().encode(text)
return { file, sha256: sha256Hex(bytes), byte_size: bytes.byteLength }
}
function svgText(source: SvgSource): string {
return new TextDecoder('utf-8', { fatal: true }).decode(source.bytes)
}
function parseSources(input: EquineLegacyInput): ParsedSources {
return {
assets: [assetRecord(input.mainSvg), assetRecord(input.headSvg)],
main: parseAnnotatedSvg(svgText(input.mainSvg), input.mainSvg.fileName),
head: parseAnnotatedSvg(svgText(input.headSvg), input.headSvg.fileName),
catalog: parseLegacyCatalog(input.catalogJson),
formula: parseVertebralFormula(input.vertebraeSource),
}
}
function mapSources(sources: ParsedSources): Mapped {
const catalog = mapCatalog(sources.catalog)
const zoneByNames = new Map(
catalog.zones.map((z) => [zoneNameKey(z.name.fr, z.name.en), z.id]),
)
const views = [
{ viewId: MAIN_VIEW_ID, svg: sources.main, file: sources.assets[0]! },
{ viewId: HEAD_VIEW_ID, svg: sources.head, file: sources.assets[1]! },
]
const annotations = views.flatMap(({ viewId, svg, file }) =>
svg.annotations.map((a) =>
mapAnnotation(a, { viewId, fileName: file.file, zoneByNames }),
),
)
const legacy = [...sources.main.annotations, ...sources.head.annotations]
return { annotations, categories: mapCategories(legacy), catalog }
}
function buildViews(assets: AssetRecord[]): SheetView[] {
return [
{
id: MAIN_VIEW_ID,
kind: 'main',
name: { fr: 'Vue générale', en: 'Overview' },
svg_asset_id: assets[0]!.svg_asset_id,
view_box: null,
},
{
id: HEAD_VIEW_ID,
kind: 'detail',
parent_view_id: MAIN_VIEW_ID,
name: { fr: 'Tête', en: 'Head' },
svg_asset_id: assets[1]!.svg_asset_id,
view_box: null,
},
]
}
function buildDocument(
sources: ParsedSources,
mapped: Mapped,
): AnatomicalSheetDocumentInput {
const disclaimer = sources.catalog.scope_disclaimer
return {
schema_version: SHEET_DOCUMENT_SCHEMA_VERSION,
species_id: EQUINE_SPECIES_ID,
name: { fr: 'Cheval', en: 'Horse' },
description: {
fr: 'Fiche anatomique officielle Faunosteo',
en: 'Official Faunosteo anatomical sheet',
},
scope_disclaimer: disclaimer === undefined ? {} : { fr: disclaimer },
attribution: {
authors: ['Faunosteo'],
license: null,
notes:
'Import des données historiques: Horse.svg, Horse_head.svg, ' +
`pathologies.json (schema ${sources.catalog.schema_version})`,
},
vertebral_config: { regions: vertebralRegions(sources.formula) },
references: [],
categories: mapped.categories.categories,
views: buildViews(sources.assets),
annotations: mapped.annotations.map((m) => m.annotation),
finding_zones: mapped.catalog.zones,
}
}
function buildIdMap(sources: ParsedSources, mapped: Mapped): LegacyIdMap {
return {
views: { [HEAD_VIEW_ID]: HEAD_VIEW_ID },
annotations: Object.fromEntries(
mapped.annotations.map((m) => [m.row.legacyId, m.row.newId]),
),
categories: mapped.categories.idMap,
finding_nodes: mapped.catalog.nodeIdMap,
assets: Object.fromEntries(
sources.assets.map((a) => [a.file, a.svg_asset_id]),
),
}
}
function countBy(
annotations: readonly AnnotationInput[],
test: (a: AnnotationInput) => boolean,
) {
return annotations.filter(test).length
}
function buildStats(
sources: ParsedSources,
document: AnatomicalSheetDocumentInput,
mapped: Mapped,
): ImportStats {
const annotations = document.annotations
const totals = mapped.catalog.zoneStats
const sum = (key: 'nodes' | 'leaves' | 'vetReferrals') =>
totals.reduce((acc, zone) => acc + zone[key], 0)
return {
legacyAnnotations:
sources.main.annotations.length + sources.head.annotations.length,
annotations: annotations.length,
annotationsByView: {
[MAIN_VIEW_ID]: countBy(annotations, (a) => a.view_id === MAIN_VIEW_ID),
[HEAD_VIEW_ID]: countBy(annotations, (a) => a.view_id === HEAD_VIEW_ID),
},
linkedAnnotations: countBy(
annotations,
(a) => a.kind !== 'detail_trigger' && a.finding_zone_id !== null,
),
triggers: countBy(annotations, (a) => a.kind === 'detail_trigger'),
views: document.views.length,
vertebralAnnotations: countBy(
annotations,
(a) => a.kind !== 'detail_trigger' && a.vertebral_region_code !== null,
),
bilateral: countBy(annotations, (a) => a.laterality === 'bilateral'),
findingZones: document.finding_zones.length,
nodes: sum('nodes'),
leaves: sum('leaves'),
vetReferrals: sum('vetReferrals'),
missingDescriptionEn: mapped.catalog.missingDescriptionEn,
sources: mapped.catalog.sources,
}
}
/** Every data-anno-id read from the SVGs must be written once. */
function assertAnnotationsKept(stats: ImportStats): void {
if (stats.legacyAnnotations === stats.annotations) return
throw new Error(
`${stats.legacyAnnotations} annotations read, ${stats.annotations} written`,
)
}
/**
* The canonical document cites a shared references registry; the legacy
* inline `sources` are not mapped. None exist today: refuse to drop any.
*/
function assertNoInlineSources(stats: ImportStats): void {
if (stats.sources === 0) return
throw new Error(
`${stats.sources} inline legacy sources found: map them to references`,
)
}
function sourceAnomalies(
sources: ParsedSources,
stats: ImportStats,
): Anomaly[] {
const out: Anomaly[] = []
const add = (code: string, subject: string, message: string) =>
out.push({ code, level: 'a_valider', subject, message })
if (stats.missingDescriptionEn > 0) {
add(
'finding.description_en.missing',
'pathologies.json',
`${stats.missingDescriptionEn} descriptions sans traduction anglaise ` +
`(clé « en » absente, rien d'inventé).`,
)
}
if (sources.catalog.scope_disclaimer !== undefined) {
add(
'document.scope_disclaimer.no_en',
'scope_disclaimer',
'Texte de périmètre légal en français seulement : traduction anglaise à rédiger.',
)
}
const range = sources.formula.variesRange ?? 'non précisée'
add(
'vertebral.cd.capped',
'Cd',
`Caudales plafonnées à ${sources.formula.counts.Cd} pour le sélecteur, ` +
`alors que l'espèce varie (${range}) selon le commentaire source.`,
)
if (stats.sources === 0) {
add(
'finding.sources.none',
'pathologies.json',
'Aucune source bibliographique sur les nœuds, alors que la règle ' +
'projet en demande au moins une par entrée.',
)
}
return out
}
function informativeNotes(): Anomaly[] {
return [
{
code: 'annotation.geometry.hitbox',
level: 'informatif',
subject: 'géométrie',
message:
'Géométrie lue sur le premier élément de chaque annotation (zone ' +
"de clic), le marqueur visuel n'est pas importé.",
},
]
}
function collectAnomalies(
sources: ParsedSources,
mapped: Mapped,
stats: ImportStats,
document: AnatomicalSheetDocumentInput,
): Anomaly[] {
return [
...authoredLabelAnomalies(document),
...sources.main.anomalies,
...sources.head.anomalies,
...mapped.annotations.flatMap((m) => m.anomalies),
...mapped.categories.anomalies,
...mapped.catalog.anomalies,
...catalogAnomalies(sources.catalog),
...sourceAnomalies(sources, stats),
...informativeNotes(),
]
}
export function importEquineLegacy(input: EquineLegacyInput): ImportResult {
const sources = parseSources(input)
const mapped = mapSources(sources)
const document = buildDocument(sources, mapped)
const parsed = AnatomicalSheetDocumentSchema.parse(document)
const stats = buildStats(sources, document, mapped)
assertAnnotationsKept(stats)
assertNoInlineSources(stats)
return {
document,
legacyIdMap: buildIdMap(sources, mapped),
assets: sources.assets,
sourceDigests: [
textDigest('pathologies.json', input.catalogJson),
textDigest('vertebrae.ts', input.vertebraeSource),
],
sheetId: sheetIdFor(EQUINE_SPECIES_ID, EQUINE_SHEET_VERSION),
viewBoxes: {
[MAIN_VIEW_ID]: sources.main.viewBox,
[HEAD_VIEW_ID]: sources.head.viewBox,
},
annotationRows: mapped.annotations.map((m) => m.row),
regionInferences: mapped.annotations.flatMap((m) =>
m.region ? [m.region] : [],
),
zoneStats: mapped.catalog.zoneStats,
stats,
anomalies: collectAnomalies(sources, mapped, stats, document),
issues: validateSheetDocument(parsed),
}
}
-19
View File
@@ -1,19 +0,0 @@
export { importEquineLegacy, HEAD_VIEW_ID, MAIN_VIEW_ID } from './importer'
export { renderArtifacts } from './artifacts'
export { renderImportReport } from './report'
export {
readEquineSources,
EQUINE_CURATION_DIR,
EQUINE_DRAFT_DIR,
EQUINE_LEGACY_IMPORT_DIR,
EQUINE_SOURCE_PATHS,
} from './sources'
export {
assetIdFromSha256,
deterministicUuid,
sha256Hex,
sheetIdFor,
slugify,
} from './ids'
export { inferRegionCode } from './regions'
export type * from './types'
-46
View File
@@ -1,46 +0,0 @@
/**
* Spine region inference from legacy labels, kept in the importer only
* (ANATOMICAL_SHEET_MODEL.md §2: no label parsing at runtime). Same roots
* and order as the legacy regionFromLabel (audit 07 §2): FR label first,
* then EN, first root in test order wins.
*/
const REGION_ROOTS: ReadonlyArray<{ code: string; roots: string[] }> = [
{ code: 'C', roots: ['cervic'] },
{ code: 'T', roots: ['thorac', 'dors'] },
{ code: 'L', roots: ['lombair', 'lumbar'] },
{ code: 'S', roots: ['sacral', 'sacre'] },
{ code: 'Cd', roots: ['caudal', 'coccyg'] },
]
export interface RegionMatch {
code: string
root: string
label: string
}
function normalise(label: string): string {
return label.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()
}
function matchLabel(label: string): RegionMatch | null {
const text = normalise(label)
for (const { code, roots } of REGION_ROOTS) {
const root = roots.find((candidate) => text.includes(candidate))
if (root) return { code, root, label }
}
return null
}
/** Null when neither label carries a known root: the caller reports it. */
export function inferRegionCode(
nameFr: string | null,
nameEn: string | null,
): RegionMatch | null {
const labels = [nameFr, nameEn].filter((l): l is string => Boolean(l))
for (const label of labels) {
const match = matchLabel(label)
if (match) return match
}
return null
}
-325
View File
@@ -1,325 +0,0 @@
import { SHEET_DOCUMENT_SCHEMA_VERSION } from '@faunosteo/domain'
import { AUTHORED_LABEL_CODE, regionLabelSubject } from './authored-labels'
import { countTree } from './catalog'
import { code, table } from '../markdown'
import type { Anomaly, ImportResult } from './types'
/**
* French Markdown import report, written for an osteopath (what to
* validate) and for the developer (what was mapped and how). No dates and
* no environment data: the report is a committed, byte-stable artifact.
*/
function intro(result: ImportResult): string {
return [
"# Rapport d'import : fiche anatomique équine v1",
'',
'Généré par `pnpm import:equine` à partir des données historiques. ' +
'Ne pas modifier à la main : relancer la commande.',
'',
`Statut : **brouillon** (version 1 en \`draft\`), jamais publié par ` +
`le seed. Fiche \`${result.sheetId}\`, espèce \`${result.document.species_id}\`.`,
'',
'Les éléments de la section « Anomalies à valider » demandent une ' +
'décision métier avant toute publication.',
].join('\n')
}
function sourcesSection(result: ImportResult): string {
const assetRows = result.assets.map((a) => [
code(a.file),
a.byte_size,
code(a.sha256),
code(a.svg_asset_id),
])
const otherRows = result.sourceDigests.map((d) => [
code(d.file),
d.byte_size,
code(d.sha256),
'-',
])
const viewBoxes = Object.entries(result.viewBoxes).map(
([view, box]) =>
`- vue \`${view}\` : viewBox \`${box ?? 'absent'}\` (view_box du ` +
`document laissé à null, le SVG porte le sien)`,
)
return [
'## 1. Sources et empreintes',
'',
table(
['Fichier', 'Octets', 'sha256', "Id d'asset"],
[...assetRows, ...otherRows],
),
'',
"Les ids d'asset sont dérivés du sha256 du fichier (UUID déterministe), " +
"les deux SVG sont copiés à l'identique dans `assets/`.",
'',
...viewBoxes,
].join('\n')
}
function volumesSection(result: ImportResult): string {
const s = result.stats
const out = countTree(
result.document.finding_zones.flatMap((z) => z.categories),
)
const rows: Array<[string, number]> = [
['Annotations', s.annotations],
['dont vue `main` (Horse.svg)', s.annotationsByView.main ?? 0],
['dont vue `head` (Horse_head.svg)', s.annotationsByView.head ?? 0],
['Annotations reliées à une zone de constats', s.linkedAnnotations],
['Déclencheurs de vue détail', s.triggers],
['Vues', s.views],
['Zones vertébrales avec code de région', s.vertebralAnnotations],
['Annotations bilatérales', s.bilateral],
['Zones de constats (catalogue)', s.findingZones],
['Nœuds (catégories incluses)', s.nodes],
['Feuilles', s.leaves],
['Orientations vétérinaires', s.vetReferrals],
]
return [
'## 2. Volumes',
'',
table(['Mesure', 'Valeur'], rows),
'',
'Contrôle entrée = sortie, compté des deux côtés (sources lues, ' +
"document écrit). L'importateur s'arrête au moindre écart :",
'',
table(
['Contrôle', 'Lu (sources)', 'Écrit (document)'],
[
[
'Annotations (data-anno-id distincts)',
s.legacyAnnotations,
s.annotations,
],
['Nœuds (catégories incluses)', s.nodes, out.nodes],
['Feuilles', s.leaves, out.leaves],
['Orientations vétérinaires', s.vetReferrals, out.vetReferrals],
],
),
].join('\n')
}
function annotationsSection(result: ImportResult): string {
const rows = result.annotationRows.map((r) => [
code(r.legacyId),
code(r.newId),
r.viewId,
r.kind,
r.laterality,
r.regionCode,
r.findingZoneId === null ? '-' : code(r.findingZoneId),
r.geometry,
])
return [
'## 3. Annotations',
'',
table(
[
'Id historique',
'Nouvel id',
'Vue',
'Type',
'Latéralité',
'Région',
'Zone de constats',
'Géométrie',
],
rows,
),
].join('\n')
}
function categoriesSection(result: ImportResult): string {
const legacyOf = Object.fromEntries(
Object.entries(result.legacyIdMap.categories).map(([legacy, id]) => [
id,
legacy,
]),
)
const authored = new Set(
result.anomalies
.filter((a) => a.code === 'category.label.authored')
.map((a) => a.subject),
)
const rows = result.document.categories.map((c) => [
code(legacyOf[c.id] ?? c.id),
code(c.id),
c.name.fr,
c.name.en,
authored.has(c.id) ? 'importateur, à valider' : 'SVG',
])
return [
"## 4. Catégories d'annotation",
'',
table(
['Id SVG', 'Id', 'Libellé FR', 'Libellé EN', 'Origine du libellé'],
rows,
),
'',
"Couleur : `null` partout (les couleurs du SVG restent dans l'asset). " +
'Dans les SVG, `data-anno-category-name` répète le slug (`articulations`, ' +
"`os`) : ce n'est pas un libellé, le libellé lisible de la table " +
"de l'importateur est utilisé.",
].join('\n')
}
function vertebralSection(result: ImportResult): string {
const authored = new Set(
result.anomalies
.filter((a) => a.code === AUTHORED_LABEL_CODE)
.map((a) => a.subject),
)
const regions = result.document.vertebral_config.regions.map((r) => [
code(r.code),
r.name.fr,
r.name.en,
r.count,
authored.has(regionLabelSubject(r.code))
? 'importateur, à valider'
: 'source',
])
const inferences = result.regionInferences.map((i) => [
code(result.legacyIdMap.annotations[i.annotationId] ?? i.annotationId),
i.label,
i.root === null ? '-' : code(i.root),
code(i.code),
])
return [
'## 5. Configuration vertébrale',
'',
table(
['Code', 'Nom FR', 'Nom EN', 'Vertèbres', 'Origine du libellé'],
regions,
),
'',
'Nombres de vertèbres : `vertebrae.ts`. Noms de région : écrits par ' +
"l'importateur (aucune source ne les porte).",
'',
'Codes de région déduits des libellés (racines `cervic`, `thorac`/`dors`, ' +
'`lombair`/`lumbar`, `sacral`/`sacre`, `caudal`/`coccyg`, FR puis ' +
'EN). Déduction faite une fois ici, le document porte le code :',
'',
table(['Annotation', 'Libellé lu', 'Racine', 'Code'], inferences),
].join('\n')
}
function findingsSection(result: ImportResult): string {
const names = new Map(
result.document.finding_zones.map((z) => [z.id, z.name.fr]),
)
const rows = result.zoneStats.map((z) => [
code(z.zoneId),
names.get(z.zoneId) ?? '-',
z.nodes,
z.leaves,
z.vetReferrals,
])
const s = result.stats
rows.push(['**Total**', '', s.nodes, s.leaves, s.vetReferrals])
return [
'## 6. Arbre de constats par zone',
'',
'Copie fidèle du catalogue : ids, libellés, descriptions présentes, ' +
'orientations vétérinaires et sources. Ordre des zones et des catégories ' +
'conservé. Nœuds = catégories incluses.',
'',
table(['Zone', 'Nom', 'Nœuds', 'Feuilles', 'Orientations vét.'], rows),
].join('\n')
}
function anomalyRows(anomalies: readonly Anomaly[]) {
return anomalies.map((a) => [code(a.code), a.subject, a.message])
}
function anomaliesSection(result: ImportResult): string {
const toValidate = result.anomalies.filter((a) => a.level === 'a_valider')
const informative = result.anomalies.filter((a) => a.level === 'informatif')
return [
'## 7. Anomalies à valider',
'',
`${toValidate.length} points demandent une décision, ${informative.length} sont informatifs.`,
'',
'### À valider',
'',
table(['Code', 'Objet', 'Détail'], anomalyRows(toValidate)),
'',
'### Informatif',
'',
table(['Code', 'Objet', 'Détail'], anomalyRows(informative)),
].join('\n')
}
/** Source keys the document does not carry, and where they live now. */
const NOT_CARRIED_OVER = [
'`schema_version` du catalogue (`2.0`) : version du format historique, ' +
`remplacée par \`schema_version: ${SHEET_DOCUMENT_SCHEMA_VERSION}\` du document canonique ; la valeur ` +
"d'origine est citée dans `attribution.notes`.",
'bloc `species` du catalogue (`equine`, Cheval / Horse) : porté par ' +
'`species_id` du document et par la table `public.species` ; le nom ' +
'de la fiche est écrit séparément (voir anomalies `label.authored`).',
'second élément graphique de chaque annotation (marqueur visuel) : ' +
"reste dans l'asset SVG copié à l'identique, le document ne garde que " +
'la zone de clic.',
'`data-anno-category-name` : répète le slug technique (`articulations`, ' +
"`os`), ce n'est pas un libellé ; le libellé de catégorie vient de la " +
"table de l'importateur (section 4).",
]
function notImportedSection(result: ImportResult): string {
const dropped = result.annotationRows.filter((r) => r.geometry === 'aucune')
const lines =
dropped.length === 0
? ['Aucune donnée métier écartée.']
: dropped.map(
(r) => `- géométrie de \`${r.legacyId}\` (forme non prise en charge)`,
)
return [
'## 8. Données non importées',
'',
...lines,
'',
'Non repris par construction :',
'',
...NOT_CARRIED_OVER.map((line) => `- ${line}`),
].join('\n')
}
function validationSection(result: ImportResult): string {
const errors = result.issues.filter((i) => i.severity === 'error')
const warnings = result.issues.filter((i) => i.severity === 'warning')
const rows = result.issues.map((i) => [
i.severity,
code(i.code),
code(i.path),
i.message,
])
return [
'## 9. Résultat de validation',
'',
'- Forme (`AnatomicalSheetDocumentSchema`) : conforme.',
`- Intégrité (\`validateSheetDocument\`) : ${errors.length} erreur(s), ` +
`${warnings.length} avertissement(s).`,
...(rows.length
? ['', table(['Gravité', 'Code', 'Chemin', 'Message'], rows)]
: []),
].join('\n')
}
export function renderImportReport(result: ImportResult): string {
return (
[
intro(result),
sourcesSection(result),
volumesSection(result),
annotationsSection(result),
categoriesSection(result),
vertebralSection(result),
findingsSection(result),
anomaliesSection(result),
notImportedSection(result),
validationSection(result),
].join('\n\n') + '\n'
)
}
-54
View File
@@ -1,54 +0,0 @@
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import type { EquineLegacyInput } from './types'
/**
* Locations of the legacy equine sources and of the seed folders, all
* relative to the repository root. Shared by the CLI and the golden tests.
*/
export const EQUINE_SOURCE_PATHS = {
mainSvg: 'supabase/seed/anatomical-sheets/equine/legacy-sources/Horse.svg',
headSvg: 'supabase/seed/anatomical-sheets/equine/legacy-sources/Horse_head.svg',
catalog: 'supabase/seed/anatomical-sheets/equine/legacy-sources/pathologies.json',
vertebrae: 'supabase/seed/anatomical-sheets/equine/legacy-sources/vertebrae.ts',
} as const
const EQUINE_SEED_ROOT = 'supabase/seed/anatomical-sheets/equine'
/** GENERATED baseline: the legacy import, untouched by curation. */
export const EQUINE_LEGACY_IMPORT_DIR = `${EQUINE_SEED_ROOT}/legacy-import`
/** AUTHORED inputs: changes.json and references.json, never generated. */
export const EQUINE_CURATION_DIR = `${EQUINE_SEED_ROOT}/curation`
/** GENERATED working revision: curated document, cleaned asset, seed. */
export const EQUINE_DRAFT_DIR = `${EQUINE_SEED_ROOT}/draft`
function fileName(path: string): string {
return path.slice(path.lastIndexOf('/') + 1)
}
export async function readEquineSources(
repoRoot: string,
): Promise<EquineLegacyInput> {
const read = (path: string) => readFile(join(repoRoot, path))
const [main, head, catalog, vertebrae] = await Promise.all([
read(EQUINE_SOURCE_PATHS.mainSvg),
read(EQUINE_SOURCE_PATHS.headSvg),
read(EQUINE_SOURCE_PATHS.catalog),
read(EQUINE_SOURCE_PATHS.vertebrae),
])
return {
mainSvg: {
fileName: fileName(EQUINE_SOURCE_PATHS.mainSvg),
bytes: new Uint8Array(main),
},
headSvg: {
fileName: fileName(EQUINE_SOURCE_PATHS.headSvg),
bytes: new Uint8Array(head),
},
catalogJson: catalog.toString('utf8'),
vertebraeSource: vertebrae.toString('utf8'),
}
}
-116
View File
@@ -1,116 +0,0 @@
import { DOMParser, type Element } from '@xmldom/xmldom'
import type { Geometry } from '@faunosteo/domain'
import type { Anomaly } from './types'
/**
* Reads the annotation layer of a legacy SVG (data-anno-* attributes of the
* historical files under supabase/seed/anatomical-sheets/equine/legacy-sources).
* Each annotation is drawn by one or two elements sharing a data-anno-id
* (hitbox first, visual marker second); the importer keeps one record per
* id, attributes and geometry taken from the first element.
*/
export interface LegacyAnnotation {
id: string
tagName: string
elementCount: number
nameFr: string | null
nameEn: string | null
category: string | null
categoryName: string | null
lateral: string | null
special: string | null
opensDetail: string | null
geometry: Geometry | null
}
export interface ParsedSvg {
viewBox: string | null
annotations: LegacyAnnotation[]
anomalies: Anomaly[]
}
function attr(element: Element, name: string): string | null {
return element.hasAttribute(name) ? element.getAttribute(name) : null
}
function parsePoints(raw: string): Array<[number, number]> {
const numbers = raw
.trim()
.split(/[\s,]+/)
.map(Number)
const pairs: Array<[number, number]> = []
for (let i = 0; i + 1 < numbers.length; i += 2) {
pairs.push([numbers[i]!, numbers[i + 1]!])
}
return pairs
}
/** Circle and polygon are the only shapes the legacy editor produces. */
function readGeometry(element: Element): Geometry | null {
if (element.tagName === 'circle') {
return {
type: 'circle',
cx: Number(attr(element, 'cx')),
cy: Number(attr(element, 'cy')),
r: Number(attr(element, 'r')),
}
}
if (element.tagName === 'polygon') {
return {
type: 'polygon',
points: parsePoints(attr(element, 'points') ?? ''),
}
}
return null
}
function readAnnotation(element: Element, id: string): LegacyAnnotation {
return {
id,
tagName: element.tagName,
elementCount: 1,
nameFr: attr(element, 'data-anno-name-fr'),
nameEn: attr(element, 'data-anno-name-en'),
category: attr(element, 'data-anno-category'),
categoryName: attr(element, 'data-anno-category-name'),
lateral: attr(element, 'data-anno-lateral'),
special: attr(element, 'data-anno-special'),
opensDetail: attr(element, 'data-anno-opens-detail'),
geometry: readGeometry(element),
}
}
function geometryAnomaly(fileName: string, a: LegacyAnnotation): Anomaly {
return {
code: 'svg.geometry.unsupported',
level: 'a_valider',
subject: `${fileName} ${a.id}`,
message: `Élément <${a.tagName}> non pris en charge : géométrie non importée (null).`,
}
}
/** Document order is kept: it is the order of the annotations table. */
export function parseAnnotatedSvg(text: string, fileName: string): ParsedSvg {
const doc = new DOMParser().parseFromString(text, 'image/svg+xml')
const root = doc.documentElement
const byId = new Map<string, LegacyAnnotation>()
const elements = doc.getElementsByTagName('*')
for (let i = 0; i < elements.length; i += 1) {
const element = elements.item(i)!
const id = attr(element, 'data-anno-id')
if (id === null) continue
const known = byId.get(id)
if (known) known.elementCount += 1
else byId.set(id, readAnnotation(element, id))
}
const annotations = [...byId.values()]
const anomalies = annotations
.filter((a) => a.geometry === null)
.map((a) => geometryAnomaly(fileName, a))
return {
viewBox: root ? attr(root, 'viewBox') : null,
annotations,
anomalies,
}
}
-115
View File
@@ -1,115 +0,0 @@
import type {
AnatomicalSheetDocumentInput,
SheetIssue,
} from '@faunosteo/domain'
/**
* Shared shapes of the legacy importer. Anomalies are never silent: every
* correction or gap the importer meets lands in the import report so an
* osteopath can validate it before the draft is published.
*/
/** 'a_valider' needs a business decision; 'informatif' only explains. */
export type AnomalyLevel = 'a_valider' | 'informatif'
export interface Anomaly {
code: string
level: AnomalyLevel
subject: string
message: string
}
/** One SVG file handed to the importer, bytes untouched. */
export interface SvgSource {
fileName: string
bytes: Uint8Array
}
/** The four legacy sources, read by the caller (CLI or tests). */
export interface EquineLegacyInput {
mainSvg: SvgSource
headSvg: SvgSource
catalogJson: string
vertebraeSource: string
}
export interface AssetRecord {
file: string
sha256: string
byte_size: number
svg_asset_id: string
}
export interface LegacyIdMap {
views: Record<string, string>
annotations: Record<string, string>
categories: Record<string, string>
finding_nodes: Record<string, string>
assets: Record<string, string>
}
/** How the region code of a spine annotation was inferred from labels. */
export interface RegionInference {
annotationId: string
label: string
root: string | null
code: string | null
}
export interface AnnotationRow {
legacyId: string
newId: string
viewId: string
kind: string
laterality: string
regionCode: string | null
findingZoneId: string | null
geometry: string
}
export interface ZoneStats {
zoneId: string
nodes: number
leaves: number
vetReferrals: number
}
/** Digest of a non-asset source, shown in the report. */
export interface SourceDigest {
file: string
sha256: string
byte_size: number
}
export interface ImportStats {
legacyAnnotations: number
annotations: number
annotationsByView: Record<string, number>
linkedAnnotations: number
triggers: number
views: number
vertebralAnnotations: number
bilateral: number
findingZones: number
nodes: number
leaves: number
vetReferrals: number
missingDescriptionEn: number
sources: number
}
/** Everything the report and the seed need, computed once. */
export interface ImportResult {
document: AnatomicalSheetDocumentInput
legacyIdMap: LegacyIdMap
assets: AssetRecord[]
sourceDigests: SourceDigest[]
sheetId: string
viewBoxes: Record<string, string | null>
annotationRows: AnnotationRow[]
regionInferences: RegionInference[]
zoneStats: ZoneStats[]
stats: ImportStats
anomalies: Anomaly[]
issues: SheetIssue[]
}
-51
View File
@@ -1,51 +0,0 @@
/**
* Reads the legacy vertebral formula from the source text of
* apps/app/src/domain/species/equine/vertebrae.ts. The file is parsed as
* text, not imported: it depends on the app's '@/…' alias, which this
* package does not resolve.
*/
export interface LegacyVertebralFormula {
counts: Record<string, number>
/** "varies A–B" range from the source comment, when stated. */
variesRange: string | null
}
const REGION_ORDER = ['C', 'T', 'L', 'S', 'Cd'] as const
export function parseVertebralFormula(source: string): LegacyVertebralFormula {
const body = /=\s*\{([^}]*)\}/.exec(source)?.[1]
if (!body) throw new Error('vertebrae.ts: formula object not found')
const counts: Record<string, number> = {}
for (const match of body.matchAll(/(\w+)\s*:\s*(\d+)/g)) {
counts[match[1]!] = Number(match[2])
}
for (const code of REGION_ORDER) {
if (!(code in counts))
throw new Error(`vertebrae.ts: region ${code} missing`)
}
const range = /varies\s+(\d+)\s*[–-]\s*(\d+)/.exec(source)
return {
counts,
variesRange: range ? `${range[1]}–${range[2]}` : null,
}
}
export const VERTEBRAL_REGION_ORDER = REGION_ORDER
const REGION_NAMES: Readonly<Record<string, { fr: string; en: string }>> = {
C: { fr: 'Cervicales', en: 'Cervical' },
T: { fr: 'Thoraciques', en: 'Thoracic' },
L: { fr: 'Lombaires', en: 'Lumbar' },
S: { fr: 'Sacrales', en: 'Sacral' },
Cd: { fr: 'Caudales', en: 'Caudal' },
}
/** Ordered C → Cd, the order of the legacy picker tabs. */
export function vertebralRegions(formula: LegacyVertebralFormula) {
return REGION_ORDER.map((code) => ({
code,
name: { ...REGION_NAMES[code]! },
count: formula.counts[code]!,
}))
}
-21
View File
@@ -1,21 +0,0 @@
/**
* Markdown building blocks of the generated French reports. Cells are
* escaped so a pipe or a newline in data never breaks a table.
*/
export function cell(value: string | number | null): string {
if (value === null) return '-'
return String(value).replace(/\|/g, '\\|').replace(/\n/g, ' ')
}
export function table(
head: string[],
rows: Array<Array<string | number | null>>,
): string {
const lines = [head, head.map(() => '---'), ...rows.map((r) => r.map(cell))]
return lines.map((line) => `| ${line.join(' | ')} |`).join('\n')
}
export function code(value: string | null): string {
return value === null ? '-' : `\`${value}\``
}
-196
View File
@@ -1,196 +0,0 @@
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
import {
createLayerElement,
SVG_NS,
type MinimalDocument,
type MinimalElement,
type MinimalNode,
} from './dom'
import { renderAnnotationLayer, viewBoxOf, type LayerElement } from './layer'
/**
* Composes the drawing of one view: the parsed asset framed on the view's
* box plus the annotation layer rendered from the document. With a
* `highlight`, the layer keeps only the selected annotations, styled for
* print (legacy picture: accent fill, halo on the main view, no data
* attributes). Works on any DOM Level 2 implementation (a Node parser or
* the browser DOM): the caller parses and serialises.
*/
export const HALO_FILTER_ID = 'osteo-halo'
export const HIGHLIGHT_FILL = '#b85a3f'
export const HIGHLIGHT_FILL_OPACITY = '0.85'
/** DOM Level 2 surface the composer needs on the `<svg>` root. */
export interface ComposeElement extends MinimalElement {
readonly ownerDocument: MinimalDocument | null
readonly firstChild: MinimalNode | null
getAttribute(name: string): string | null
removeAttribute(name: string): void
insertBefore(node: MinimalNode, reference: MinimalNode | null): unknown
getElementsByTagName(tag: string): ComposeElementList
}
export interface ComposeElementList {
readonly length: number
item(index: number): ComposeElement | null
}
export interface ComposeHighlight {
/** Annotation ids kept on the layer; every other marker is dropped. */
annotationIds: ReadonlySet<string>
/** Wrap the kept markers in the `osteo-halo` filter (main view). */
halo: boolean
}
export interface ComposeInput<Root extends ComposeElement = ComposeElement> {
root: Root
document: AnatomicalSheetDocumentInput
viewId: string
highlight?: ComposeHighlight
}
/** Frames `root` on the view, appends the layer `<g>` last, returns `root`. */
export function composeViewSvg<Root extends ComposeElement>(
input: ComposeInput<Root>,
): Root {
const { root, document, viewId, highlight } = input
const view = document.views.find((v) => v.id === viewId)
if (!view) throw new Error(`unknown view "${viewId}"`)
const box = viewBoxOf(view)
if (box) root.setAttribute('viewBox', box)
root.removeAttribute('width')
root.removeAttribute('height')
if (highlight?.halo) ensureHaloFilter(root)
const rendered = renderAnnotationLayer({ document, viewId })
const layer = highlight ? highlightLayer(rendered, highlight) : rendered
root.appendChild(createLayerElement(documentOf(root), layer))
return root
}
/** Typed nullable by the DOM; an element taken from a parsed document has one. */
function documentOf(root: ComposeElement): MinimalDocument {
if (!root.ownerDocument) throw new Error('root has no owner document')
return root.ownerDocument
}
/**
* The layer reduced to the selected annotations (both elements of a point),
* each with the accent fill and, when asked, the halo filter. No `data-*`
* attribute survives: the result is a picture, not an interactive layer.
*/
export function highlightLayer(
layer: LayerElement,
highlight: ComposeHighlight,
): LayerElement {
const children = layer.children
.filter((child) =>
highlight.annotationIds.has(child.attrs['data-anno-id'] ?? ''),
)
.map((child) => highlightElement(child, highlight.halo))
return { ...layer, attrs: withoutDataAttrs(layer.attrs), children }
}
function highlightElement(node: LayerElement, halo: boolean): LayerElement {
const attrs: Record<string, string> = {
...withoutDataAttrs(node.attrs),
fill: HIGHLIGHT_FILL,
'fill-opacity': HIGHLIGHT_FILL_OPACITY,
}
if (halo) attrs.filter = `url(#${HALO_FILTER_ID})`
return { ...node, attrs }
}
function withoutDataAttrs(
attrs: Record<string, string>,
): Record<string, string> {
return Object.fromEntries(
Object.entries(attrs).filter(([name]) => !name.startsWith('data-')),
)
}
/**
* Adds the Gaussian-blur "halo" filter so the highlighted markers stay
* visible on the whole-animal view once rasterised at print scale. One
* filter per root: a second call finds it and leaves the tree alone.
*/
function ensureHaloFilter(root: ComposeElement): void {
if (hasElementWithId(root, 'filter', HALO_FILTER_ID)) return
const defs = root.getElementsByTagName('defs').item(0) ?? createDefs(root)
defs.appendChild(haloFilter(documentOf(root)))
}
function hasElementWithId(
root: ComposeElement,
tag: string,
id: string,
): boolean {
const list = root.getElementsByTagName(tag)
for (let i = 0; i < list.length; i++) {
if (list.item(i)?.getAttribute('id') === id) return true
}
return false
}
/** `<defs>` as the first child: the asset's own filters sit at the root. */
function createDefs(root: ComposeElement): MinimalElement {
const defs = documentOf(root).createElementNS(SVG_NS, 'defs')
root.insertBefore(defs, root.firstChild)
return defs
}
function svgElement(
doc: MinimalDocument,
tag: string,
attrs: Record<string, string>,
): MinimalElement {
const element = doc.createElementNS(SVG_NS, tag)
for (const [name, value] of Object.entries(attrs)) {
element.setAttribute(name, value)
}
return element
}
function haloFilter(doc: MinimalDocument): MinimalElement {
const filter = svgElement(doc, 'filter', {
id: HALO_FILTER_ID,
x: '-100%',
y: '-100%',
width: '300%',
height: '300%',
filterUnits: 'userSpaceOnUse',
})
filter.appendChild(gaussianBlur(doc, '18', 'haloWide'))
filter.appendChild(gaussianBlur(doc, '8', 'haloTight'))
filter.appendChild(haloMerge(doc))
return filter
}
function gaussianBlur(
doc: MinimalDocument,
stdDeviation: string,
result: string,
): MinimalElement {
return svgElement(doc, 'feGaussianBlur', {
in: 'SourceGraphic',
stdDeviation,
result,
})
}
/** Three wide blurs, two tight ones, then the marker itself on top. */
function haloMerge(doc: MinimalDocument): MinimalElement {
const merge = svgElement(doc, 'feMerge', {})
const inputs = [
'haloWide',
'haloWide',
'haloWide',
'haloTight',
'haloTight',
'SourceGraphic',
]
for (const input of inputs) {
merge.appendChild(svgElement(doc, 'feMergeNode', { in: input }))
}
return merge
}
-38
View File
@@ -1,38 +0,0 @@
import type { LayerElement } from './layer'
/**
* Materialises a layer tree with any DOM implementation (browser document,
* xmldom in the pipeline). Only the handful of methods used are required,
* so this module compiles without the DOM lib.
*/
export const SVG_NS = 'http://www.w3.org/2000/svg'
export interface MinimalNode {
appendChild(child: MinimalNode): unknown
}
export interface MinimalElement extends MinimalNode {
setAttribute(name: string, value: string): void
}
export interface MinimalDocument {
createElementNS(ns: string, tag: string): MinimalElement
createTextNode(text: string): MinimalNode
}
export function createLayerElement(
doc: MinimalDocument,
node: LayerElement,
): MinimalElement {
const element = doc.createElementNS(SVG_NS, node.tag)
for (const [name, value] of Object.entries(node.attrs)) {
element.setAttribute(name, value)
}
if (node.text !== undefined)
element.appendChild(doc.createTextNode(node.text))
for (const child of node.children) {
element.appendChild(createLayerElement(doc, child))
}
return element
}
-33
View File
@@ -1,33 +0,0 @@
export {
DETAIL_VIEW_STYLE,
FALLBACK_COLOR,
LAYER_ATTRIBUTE,
LAYER_NAME,
MAIN_VIEW_STYLE,
renderAnnotationLayer,
styleForView,
viewBoxOf,
type AnnotationState,
type LayerElement,
type LayerInput,
type MarkerStyle,
} from './layer'
export {
createLayerElement,
SVG_NS,
type MinimalDocument,
type MinimalElement,
type MinimalNode,
} from './dom'
export { serializeLayer } from './serialize'
export {
composeViewSvg,
HALO_FILTER_ID,
HIGHLIGHT_FILL,
HIGHLIGHT_FILL_OPACITY,
highlightLayer,
type ComposeElement,
type ComposeElementList,
type ComposeHighlight,
type ComposeInput,
} from './compose'
-261
View File
@@ -1,261 +0,0 @@
import type {
AnatomicalSheetDocumentInput,
Geometry,
SheetView,
} from '@faunosteo/domain'
/**
* Annotation layer of one view, as pure data: the SVG elements the
* application draws over the sheet's drawing, reproducing the legacy
* markers (transparent hitbox + visible twin per point, filled polygon per
* spine zone, dashed outline per detail trigger). The elements carry the
* `data-anno-*` attributes the click delegation, the tooltip and the CSS
* states read, so the drawing itself needs no annotation element at all.
* No DOM here: `dom.ts` materialises the tree, `serialize.ts` prints it.
*/
export interface LayerElement {
tag: 'g' | 'circle' | 'polygon' | 'path' | 'title'
attrs: Record<string, string>
children: LayerElement[]
text?: string
}
/** Visual constants of the legacy markers, per view kind. */
export interface MarkerStyle {
/** Visible circle radius = hitbox radius − inset (34→22, 30→18, 27→15). */
visibleInset: number
visibleFillOpacity: number
visibleStroke: string
visibleStrokeWidth: number
zoneFillOpacity: number
zoneStrokeWidth: number
triggerFillOpacity: number
triggerStrokeWidth: number
triggerDash: string
}
const BASE_STYLE: Omit<MarkerStyle, 'visibleFillOpacity'> = {
visibleInset: 12,
visibleStroke: '#000',
visibleStrokeWidth: 1.5,
zoneFillOpacity: 0.3,
zoneStrokeWidth: 2,
triggerFillOpacity: 0.06,
triggerStrokeWidth: 2,
triggerDash: '8,4',
}
export const MAIN_VIEW_STYLE: MarkerStyle = {
...BASE_STYLE,
visibleFillOpacity: 0.65,
}
export const DETAIL_VIEW_STYLE: MarkerStyle = {
...BASE_STYLE,
visibleFillOpacity: 0.5,
}
/** When neither the annotation nor its category names a colour. */
export const FALLBACK_COLOR = '#888888'
export const LAYER_ATTRIBUTE = 'data-layer'
export const LAYER_NAME = 'annotations'
export type AnnotationState = 'current'
export interface LayerInput {
document: AnatomicalSheetDocumentInput
viewId: string
/** Annotation id → state, applied as `data-state`. */
states?: ReadonlyMap<string, AnnotationState>
}
type Annotation = AnatomicalSheetDocumentInput['annotations'][number]
export function styleForView(view: Pick<SheetView, 'kind'>): MarkerStyle {
return view.kind === 'main' ? MAIN_VIEW_STYLE : DETAIL_VIEW_STYLE
}
function el(
tag: LayerElement['tag'],
attrs: Record<string, string>,
children: LayerElement[] = [],
): LayerElement {
return { tag, attrs, children }
}
function title(text: string): LayerElement {
return { tag: 'title', attrs: {}, children: [], text }
}
function geometryAttrs(
geometry: Geometry,
): [LayerElement['tag'], Record<string, string>] {
switch (geometry.type) {
case 'circle':
return [
'circle',
{
cx: String(geometry.cx),
cy: String(geometry.cy),
r: String(geometry.r),
},
]
case 'polygon':
return [
'polygon',
{ points: geometry.points.map(([x, y]) => `${x},${y}`).join(' ') },
]
case 'path':
return ['path', { d: geometry.d }]
}
}
function colorOf(
a: Annotation,
categories: Map<string, string | null>,
): string {
return a.color ?? categories.get(a.category_id) ?? FALLBACK_COLOR
}
/** Attributes shared by every element of one annotation. */
function dataAttrs(
a: Annotation,
input: LayerInput,
viewName: string,
): Record<string, string> {
const attrs: Record<string, string> = {
'data-anno-id': a.id,
'data-anno-kind': a.kind,
'data-anno-lateral': a.laterality,
}
if (a.kind === 'detail_trigger') {
attrs['data-anno-opens-view'] = a.opens_view_id
attrs['data-anno-name-fr'] = a.name?.fr ?? viewName
attrs['data-anno-name-en'] = a.name?.en ?? viewName
} else {
attrs['data-anno-name-fr'] = a.name.fr
attrs['data-anno-name-en'] = a.name.en
if (a.finding_zone_id) attrs['data-anno-zone'] = a.finding_zone_id
if (a.vertebral_region_code)
attrs['data-anno-region'] = a.vertebral_region_code
}
const state = input.states?.get(a.id)
if (state) attrs['data-state'] = state
return attrs
}
function pointElements(
geometry: Extract<Geometry, { type: 'circle' }>,
color: string,
style: MarkerStyle,
data: Record<string, string>,
label: string,
): LayerElement[] {
const hitbox = el(
'circle',
{
...geometryAttrs(geometry)[1],
fill: 'transparent',
'pointer-events': 'all',
style: 'cursor:pointer',
...data,
},
[title(label)],
)
const visible = el(
'circle',
{
cx: String(geometry.cx),
cy: String(geometry.cy),
r: String(Math.max(2, geometry.r - style.visibleInset)),
fill: color,
'fill-opacity': String(style.visibleFillOpacity),
stroke: style.visibleStroke,
'stroke-width': String(style.visibleStrokeWidth),
'pointer-events': 'none',
...data,
},
[title(label)],
)
return [hitbox, visible]
}
function shapeElement(
geometry: Geometry,
color: string,
visual: Record<string, string>,
data: Record<string, string>,
label: string,
): LayerElement {
const [tag, attrs] = geometryAttrs(geometry)
return el(tag, { ...attrs, fill: color, stroke: color, ...visual, ...data }, [
title(label),
])
}
function annotationElements(
a: Annotation,
input: LayerInput,
style: MarkerStyle,
categories: Map<string, string | null>,
viewName: string,
): LayerElement[] {
if (!a.geometry) return []
const color = colorOf(a, categories)
const data = dataAttrs(a, input, viewName)
const label = `${data['data-anno-name-fr']} / ${data['data-anno-name-en']}`
if (a.kind === 'detail_trigger') {
const visual = {
'fill-opacity': String(style.triggerFillOpacity),
'stroke-width': String(style.triggerStrokeWidth),
'stroke-dasharray': style.triggerDash,
'pointer-events': 'all',
style: 'cursor:pointer',
class: 'detail-zone',
}
return [shapeElement(a.geometry, color, visual, data, label)]
}
if (a.geometry.type === 'circle') {
return pointElements(a.geometry, color, style, data, label)
}
const visual = {
'fill-opacity': String(style.zoneFillOpacity),
'stroke-width': String(style.zoneStrokeWidth),
'pointer-events': 'all',
style: 'cursor:pointer',
}
return [shapeElement(a.geometry, color, visual, data, label)]
}
/** The layer `<g>` of one view: every annotation of that view, in document order. */
export function renderAnnotationLayer(input: LayerInput): LayerElement {
const { document, viewId } = input
const view = document.views.find((v) => v.id === viewId)
if (!view) throw new Error(`unknown view "${viewId}"`)
const style = styleForView(view)
const categories = new Map(
document.categories.map((c) => [c.id, c.color ?? null]),
)
const viewNames = new Map(document.views.map((v) => [v.id, v.name.fr]))
const children = document.annotations
.filter((a) => a.view_id === viewId)
.flatMap((a) => {
const opened =
a.kind === 'detail_trigger'
? (viewNames.get(a.opens_view_id) ?? '')
: ''
return annotationElements(a, input, style, categories, opened)
})
return el(
'g',
{ [LAYER_ATTRIBUTE]: LAYER_NAME, 'data-view-id': viewId },
children,
)
}
/** `viewBox` attribute value the view renders with, or null for the asset's own. */
export function viewBoxOf(view: SheetView): string | null {
const box = view.view_box
return box ? `${box.min_x} ${box.min_y} ${box.width} ${box.height}` : null
}
-25
View File
@@ -1,25 +0,0 @@
import type { LayerElement } from './layer'
/** Serialises a layer tree to SVG text (review drawings, tests). */
function escape(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
export function serializeLayer(node: LayerElement, indent = ''): string {
const attrs = Object.entries(node.attrs)
.map(([k, v]) => ` ${k}="${escape(v)}"`)
.join('')
if (node.text !== undefined) {
return `${indent}<${node.tag}${attrs}>${escape(node.text)}</${node.tag}>`
}
if (node.children.length === 0) return `${indent}<${node.tag}${attrs}/>`
const inner = node.children
.map((child) => serializeLayer(child, `${indent} `))
.join('\n')
return `${indent}<${node.tag}${attrs}>\n${inner}\n${indent}</${node.tag}>`
}
@@ -1,529 +0,0 @@
import { applyChangeset, type CurationResult, type Op } from '../src'
import { changesetOf, MINI_REFERENCES, miniSheet } from './fixtures/mini-sheet'
type Plain = Record<string, unknown>
function plain(value: unknown): Plain {
return value as Plain
}
function nodes(item: Plain): Plain[] {
return (item.children ?? []) as Plain[]
}
function run(ops: Op[]): CurationResult {
return applyChangeset(miniSheet(), MINI_REFERENCES, changesetOf(ops))
}
function zone(result: CurationResult, id: string): Plain {
return plain(result.document.finding_zones.find((z) => z.id === id))
}
function hipDysfunctions(result: CurationResult): Plain {
return (zone(result, 'hip').categories as Plain[])[0]!
}
function annotation(result: CurationResult, id: string): Plain {
return plain(result.document.annotations.find((a) => a.id === id))
}
function childIds(node: Plain): string[] {
return nodes(node).map((child) => child.id as string)
}
const MOBILITY = 'finding:hip/hip-dysfunctions/mobility'
describe('applyChangeset: set', () => {
it('sets a field and records before / after', () => {
const result = run([
{
op: 'set',
target: 'region:C',
field: 'count_range',
value: { min: 6, max: 8 },
},
])
expect(result.document.vertebral_config.regions[0]!.count_range).toEqual({
min: 6,
max: 8,
})
expect(result.records).toHaveLength(1)
expect(result.records[0]).toMatchObject({
target: 'region:C',
field: 'count_range',
before: null,
after: { min: 6, max: 8 },
})
})
it('creates a missing nested object for a dot path', () => {
const result = run([
{
op: 'set',
target: MOBILITY,
field: 'description.en',
value: 'Mobility',
},
])
expect(nodes(hipDysfunctions(result))[0]!.description).toEqual({
en: 'Mobility',
})
})
it('applies a subtree set to the target and every descendant', () => {
const result = run([
{
op: 'set',
target: 'finding:hip/hip-dysfunctions',
field: 'review_status',
value: 'to_confirm',
scope: 'subtree',
},
])
expect(result.records.map((r) => r.target)).toEqual([
'finding:hip/hip-dysfunctions',
MOBILITY,
`${MOBILITY}/flexion`,
`${MOBILITY}/extension`,
'finding:hip/hip-dysfunctions/pain',
])
expect(nodes(nodes(hipDysfunctions(result))[0]!)[1]!.review_status).toBe(
'to_confirm',
)
})
it('skips items without the field and items already at the value', () => {
const result = run([
{
op: 'set',
target: 'finding:neck/neck-dysfunctions',
field: 'requires_vet_referral',
value: true,
scope: 'subtree',
},
])
expect(result.records.map((r) => r.target)).toEqual([
'finding:neck/neck-dysfunctions/stiffness',
])
})
})
describe('applyChangeset: rename', () => {
it('renames a zone and the annotations follow, one record each', () => {
const result = run([{ op: 'rename', target: 'zone:hip', id: 'hip-joint' }])
expect(zone(result, 'hip-joint')).toBeDefined()
const hip = annotation(result, 'hip')
expect(hip.finding_zone_id).toBe('hip-joint')
expect(result.records.map((r) => [r.target, r.field])).toEqual([
['zone:hip', null],
['annotation:hip', 'finding_zone_id'],
])
expect(plain(result.records[0]!.before).id).toBe('hip')
})
it('renames a region code and the vertebral annotations follow', () => {
const result = run([{ op: 'rename', target: 'region:C', id: 'Cv' }])
expect(result.document.vertebral_config.regions[0]!.code).toBe('Cv')
const neck = annotation(result, 'neck')
expect(neck.vertebral_region_code).toBe('Cv')
})
it('renames a view: parent links and trigger targets follow', () => {
const result = run([{ op: 'rename', target: 'view:head', id: 'skull' }])
const trigger = annotation(result, 'head-trigger')
expect(trigger.opens_view_id).toBe('skull')
expect(result.records.map((r) => r.field)).toEqual([null, 'opens_view_id'])
})
it('renames a main view: parent_view_id and view_id follow', () => {
const result = run([{ op: 'rename', target: 'view:main', id: 'overview' }])
expect(plain(result.document.views[1]).parent_view_id).toBe('overview')
expect(
result.document.annotations.every((a) => a.view_id === 'overview'),
).toBe(true)
})
it('renames an annotation category: annotations follow', () => {
const result = run([
{ op: 'rename', target: 'category:joints', id: 'articulations' },
])
const hip = result.document.annotations.find((a) => a.id === 'hip')!
expect(hip.category_id).toBe('articulations')
})
it('renames a reference: every citation follows', () => {
const result = run([
{ op: 'cite', target: MOBILITY, reference_ids: ['atlas'] },
{ op: 'rename', target: 'reference:atlas', id: 'atlas-2' },
])
expect(nodes(hipDysfunctions(result))[0]!.reference_ids).toEqual([
'atlas-2',
])
expect(result.records.at(-1)).toMatchObject({
target: MOBILITY,
field: 'reference_ids',
before: ['atlas'],
after: ['atlas-2'],
})
})
})
describe('applyChangeset: add, remove, move', () => {
const node = (id: string) => ({ id, name: { fr: id, en: id } })
it.each([
[{ after: 'flexion' }, ['flexion', 'new', 'extension']],
[{ before: 'flexion' }, ['new', 'flexion', 'extension']],
[1, ['flexion', 'new', 'extension']],
[undefined, ['flexion', 'extension', 'new']],
] as const)('adds a node at position %j', (position, expected) => {
const op: Op = { op: 'add', target: MOBILITY, value: node('new') }
if (position !== undefined) op.position = position
const result = run([op])
expect(childIds(nodes(hipDysfunctions(result))[0]!)).toEqual(expected)
expect(result.records[0]).toMatchObject({
target: `${MOBILITY}/new`,
before: null,
})
})
it('adds children under a lean leaf', () => {
const result = run([
{ op: 'add', target: `${MOBILITY}/flexion`, value: node('left') },
])
expect(childIds(nodes(nodes(hipDysfunctions(result))[0]!)[0]!)).toEqual([
'left',
])
})
it('adds a zone, an annotation and a reference at document level', () => {
const result = run([
{
op: 'add',
target: 'document',
field: 'finding_zones',
value: { id: 'back', name: { fr: 'Dos', en: 'Back' }, categories: [] },
},
{
op: 'add',
target: 'document',
field: 'annotations',
position: { after: 'neck' },
value: {
id: 'back',
kind: 'zone',
view_id: 'main',
category_id: 'bones',
laterality: 'unpaired',
geometry: null,
name: { fr: 'Dos', en: 'Back' },
finding_zone_id: 'back',
vertebral_region_code: 'T',
},
},
{
op: 'add',
target: 'document',
field: 'references',
value: {
id: 'book',
type: 'book',
citation: 'Book',
url: null,
doi: null,
},
},
{ op: 'cite', target: 'finding:hip/anamnesis', reference_ids: ['book'] },
])
expect(result.document.annotations.map((a) => a.id)).toEqual([
'hip',
'neck',
'back',
'head-trigger',
])
expect(result.records.map((r) => r.target)).toEqual([
'zone:back',
'annotation:back',
'reference:book',
'finding:hip/anamnesis',
])
})
it('removes a node and records the whole item', () => {
const result = run([{ op: 'remove', target: MOBILITY }])
expect(childIds(hipDysfunctions(result))).toEqual(['pain'])
expect(result.records[0]).toMatchObject({ target: MOBILITY, after: null })
expect(childIds(plain(result.records[0]!.before))).toEqual([
'flexion',
'extension',
])
})
it('moves a node into a sibling, then across zones', () => {
const result = run([
{
op: 'move',
target: 'finding:hip/hip-dysfunctions/pain',
to: MOBILITY,
position: { before: 'flexion' },
},
{
op: 'move',
target: 'finding:neck/neck-dysfunctions/stiffness',
to: 'finding:hip/anamnesis',
},
])
expect(childIds(nodes(hipDysfunctions(result))[0]!)).toEqual([
'pain',
'flexion',
'extension',
])
expect(childIds((zone(result, 'hip').categories as Plain[])[1]!)).toEqual([
'trauma',
'stiffness',
])
expect(result.records.map((r) => r.after)).toEqual([
`${MOBILITY}/pain`,
'finding:hip/anamnesis/stiffness',
])
})
})
describe('applyChangeset: cite', () => {
it('cites one item without duplicates', () => {
const result = run([
{ op: 'cite', target: MOBILITY, reference_ids: ['atlas'] },
{ op: 'cite', target: MOBILITY, reference_ids: ['atlas', 'paper'] },
])
expect(nodes(hipDysfunctions(result))[0]!.reference_ids).toEqual([
'atlas',
'paper',
])
expect(
nodes(nodes(hipDysfunctions(result))[0]!)[0]!.reference_ids,
).toBeUndefined()
expect(result.records).toHaveLength(2)
})
it('cites a subtree, and a zone stands for its categories', () => {
const subtree = run([
{
op: 'cite',
target: MOBILITY,
reference_ids: ['atlas'],
scope: 'subtree',
},
])
expect(subtree.records.map((r) => r.target)).toEqual([
MOBILITY,
`${MOBILITY}/flexion`,
`${MOBILITY}/extension`,
])
const own = run([
{ op: 'cite', target: 'zone:hip', reference_ids: ['paper'] },
])
expect(own.records.map((r) => r.target)).toEqual([
'finding:hip/hip-dysfunctions',
'finding:hip/anamnesis',
])
})
})
describe('applyChangeset: errors fail loud', () => {
it.each([
[
[{ op: 'set', target: 'zone:nope', field: 'name', value: {} }],
'unknown target',
],
[
[{ op: 'set', target: 'finding:hip', field: 'name', value: {} }],
'malformed target',
],
[
[{ op: 'set', target: 'galaxy:x', field: 'name', value: {} }],
'unknown target',
],
[
[{ op: 'set', target: 'zone:hip', field: 'colour', value: 1 }],
'unknown field',
],
[
[{ op: 'set', target: 'zone:hip', field: 'id', value: 'x' }],
'unknown field',
],
[
[
{
op: 'add',
target: MOBILITY,
value: { id: 'flexion', name: { fr: 'a', en: 'a' } },
},
],
'already exists',
],
[
[
{
op: 'add',
target: MOBILITY,
value: { id: 'x', name: { fr: 'a', en: 'a' } },
position: { after: 'nope' },
},
],
'unknown sibling',
],
[[{ op: 'rename', target: 'zone:hip', id: 'neck' }], 'already exists'],
[
[{ op: 'cite', target: MOBILITY, reference_ids: ['ghost'] }],
'undeclared reference',
],
[
[{ op: 'move', target: MOBILITY, to: `${MOBILITY}/flexion` }],
'into itself',
],
] as Array<[Op[], string]>)('%j → %s', (ops, message) => {
expect(() => run(ops)).toThrow(message)
expect(() => run(ops)).toThrow('CHG-001 op 0')
})
it('rejects a change citing an undeclared reference', () => {
const changeset = changesetOf(
[{ op: 'remove', target: `${MOBILITY}/flexion` }],
{
reference_ids: ['ghost'],
},
)
expect(() =>
applyChangeset(miniSheet(), MINI_REFERENCES, changeset),
).toThrow('CHG-001: undeclared reference(s): ghost')
})
it('rejects an integrity error left after the ops', () => {
const remove: Op[] = [{ op: 'remove', target: 'zone:hip' }]
expect(() => run(remove)).toThrow('integrity errors')
expect(() => run(remove)).toThrow('Finding zone "hip" does not exist')
})
it('rejects a shape error left after the ops', () => {
expect(() =>
run([{ op: 'set', target: 'region:C', field: 'count', value: 'seven' }]),
).toThrow('not shape-valid')
})
})
describe('applyChangeset: purity', () => {
const ops: Op[] = [
{ op: 'rename', target: 'zone:hip', id: 'hip-joint' },
{
op: 'cite',
target: 'zone:hip-joint',
reference_ids: ['atlas'],
scope: 'subtree',
},
]
it('is deterministic', () => {
expect(run(ops)).toEqual(run(ops))
})
it('never mutates its inputs', () => {
const baseline = miniSheet()
const references = structuredClone(MINI_REFERENCES)
const changeset = changesetOf(ops)
const copies = structuredClone({ baseline, references, changeset })
const result = applyChangeset(baseline, references, changeset)
expect({ baseline, references, changeset }).toEqual(copies)
expect(result.document.references).toEqual(references)
expect(result.document.references).not.toBe(references)
})
})
describe('applyChangeset: review rule of levels B and C', () => {
const B = { level: 'B' } as const
const withLevel = (ops: Op[], extra = B) =>
applyChangeset(miniSheet(), MINI_REFERENCES, changesetOf(ops, extra))
const status = (item: Plain) => item.review_status
it('marks a node set by a B change to_confirm, with a record', () => {
const result = withLevel([
{
op: 'set',
target: MOBILITY,
field: 'name',
value: { fr: 'a', en: 'a' },
},
])
const node = nodes(hipDysfunctions(result))[0]!
expect(status(node)).toBe('to_confirm')
const last = result.records[result.records.length - 1]!
expect(last).toMatchObject({
target: MOBILITY,
field: 'review_status',
before: 'inherited',
after: 'to_confirm',
})
expect(last.change.id).toBe('CHG-001')
})
it('marks every node of an added subtree', () => {
const value = {
id: 'new',
name: { fr: 'n', en: 'n' },
children: [{ id: 'leaf', name: { fr: 'l', en: 'l' } }],
}
const result = withLevel([
{ op: 'add', target: 'finding:hip/hip-dysfunctions', value },
])
const added = nodes(hipDysfunctions(result)).find((n) => n.id === 'new')!
expect(status(added)).toBe('to_confirm')
expect(status(nodes(added)[0]!)).toBe('to_confirm')
})
it('marks cited targets under a C change', () => {
const result = withLevel(
[{ op: 'cite', target: MOBILITY, reference_ids: ['atlas'] }],
{ level: 'C', question: 'Q?' } as never,
)
expect(status(nodes(hipDysfunctions(result))[0]!)).toBe('to_confirm')
})
it('marks an annotation set by a B change', () => {
const result = withLevel([
{
op: 'set',
target: 'annotation:hip',
field: 'name',
value: { fr: 'h', en: 'h' },
},
])
expect(status(annotation(result, 'hip'))).toBe('to_confirm')
})
it('leaves a level A change untouched', () => {
const result = run([
{
op: 'set',
target: MOBILITY,
field: 'name',
value: { fr: 'a', en: 'a' },
},
])
expect(status(nodes(hipDysfunctions(result))[0]!)).not.toBe('to_confirm')
expect(result.records).toHaveLength(1)
})
it('throws when a B change sets review_status to reviewed', () => {
expect(() =>
withLevel([
{
op: 'set',
target: MOBILITY,
field: 'review_status',
value: 'reviewed',
},
]),
).toThrow(
/CHG-001 op 0: level B cannot set "finding:hip\/hip-dysfunctions\/mobility"/,
)
})
})
@@ -1,79 +0,0 @@
import { DOMParser } from '@xmldom/xmldom'
import { createHash } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import {
EQUINE_SOURCE_PATHS,
assetIdFromSha256,
cleanedAsset,
parseViewBox,
stripLegacyAnnotations,
} from '../src'
import { REPO_ROOT } from './helpers'
let source: string
let cleaned: string
function count(text: string, pattern: RegExp): number {
return [...text.matchAll(pattern)].length
}
beforeAll(async () => {
source = await readFile(join(REPO_ROOT, EQUINE_SOURCE_PATHS.mainSvg), 'utf8')
cleaned = stripLegacyAnnotations(source)
})
describe('stripLegacyAnnotations on the real Horse.svg', () => {
it('removes exactly the elements carrying data-anno-id', () => {
const annotated = count(source, /<[a-z]+\b[^>]*\sdata-anno-id="/g)
const elements = (text: string) => count(text, /<[a-zA-Z]+[\s/>]/g)
expect(annotated).toBe(30) // 12 points × (hitbox + marker) + 6 polygons
// each annotated element carries one <title> child, removed with it
const titles = count(source, /data-anno-id="[^"]*"[^>]*><title>/g)
expect(elements(source) - elements(cleaned)).toBe(annotated + titles)
})
it('keeps the 270 drawing paths and every non-annotation byte', () => {
expect(count(source, /<path\b/g)).toBe(270)
expect(count(cleaned, /<path\b/g)).toBe(270)
expect(cleaned).not.toContain('data-anno-')
expect(cleaned.startsWith('<?xml version="1.0" encoding="UTF-8"?>')).toBe(
true,
)
expect(cleaned).not.toContain('max-width: 100%')
})
it('is deterministic and parses as XML', () => {
expect(stripLegacyAnnotations(source)).toBe(cleaned)
const errors: string[] = []
const doc = new DOMParser({
onError: (level, message) => {
if (level !== 'warning') errors.push(message)
},
}).parseFromString(cleaned, 'image/svg+xml')
expect(errors).toEqual([])
expect(doc.documentElement?.tagName).toBe('svg')
})
it('describes the cleaned bytes with their sha256', () => {
const bytes = new TextEncoder().encode(cleaned)
const asset = cleanedAsset(bytes)
const sha256 = createHash('sha256').update(bytes).digest('hex')
expect(asset).toEqual({
file: 'horse.svg',
sha256,
byte_size: bytes.byteLength,
svg_asset_id: assetIdFromSha256(sha256),
})
})
it('reads a viewBox into a document view_box', () => {
expect(parseViewBox('60 100 500 380')).toEqual({
min_x: 60,
min_y: 100,
width: 500,
height: 380,
})
expect(() => parseViewBox('1 2 3')).toThrow('invalid viewBox')
})
})
@@ -1,271 +0,0 @@
/**
* Per-leaf adapter test over the committed seed: every leaf of the legacy
* catalog (612) and every legacy annotation (27) travels through the real
* Report v2 → v3 migration with the generated map, then is checked against
* the curated draft document itself, not against the map alone.
*/
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import {
AnatomicalSheetDocumentSchema,
ReportMigrationMapSchema,
ReportV2Schema,
findingPathKey,
migrateReportV2ToV3,
readReportDocument,
type AnatomicalSheetDocument,
type Annotation,
type Finding,
type FindingCategory,
type FindingNode,
type ObservationV2,
type ReportMigrationMap,
type ReportV2,
} from '@faunosteo/domain'
import { beforeAll, describe, expect, it } from 'vitest'
import { EQUINE_DRAFT_DIR, EQUINE_LEGACY_IMPORT_DIR } from '../src'
import { REPO_ROOT } from './helpers'
interface LegacyLeaf {
zoneId: string
path: string[]
name: { fr: string; en: string }
vet: boolean
}
/** Every leaf of a document's finding trees, in document order. */
export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] {
const out: LegacyLeaf[] = []
const walk = (
zoneId: string,
nodes: readonly (FindingCategory | FindingNode)[],
prefix: string[],
) => {
for (const node of nodes) {
const path = [...prefix, node.id]
if (node.children.length > 0) walk(zoneId, node.children, path)
else {
const vet =
'requires_vet_referral' in node && node.requires_vet_referral
out.push({ zoneId, path, name: node.name, vet })
}
}
}
for (const zone of doc.finding_zones) walk(zone.id, zone.categories, [])
return out
}
/** One v2 observation per zone holding every leaf of that zone as a finding. */
export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
const byZone = new Map<string, ObservationV2>()
for (const leaf of leaves) {
let obs = byZone.get(leaf.zoneId)
if (!obs) {
obs = {
id: `obs-${leaf.zoneId}`,
zones: [],
findings: [],
freeTextFindings: [],
comment: '',
}
byZone.set(leaf.zoneId, obs)
}
obs.findings.push({
zoneId: leaf.zoneId,
path: leaf.path,
labelFrSnapshot: leaf.name.fr,
labelEnSnapshot: leaf.name.en || leaf.name.fr,
...(leaf.vet ? { requiresVetReferral: true } : {}),
})
}
return ReportV2Schema.parse({
version: 2,
id: 'all-leaves',
createdAt: '2026-10-10T00:00:00Z',
date: '2026-10-10',
practitioner: { name: 'Synthetic' },
animal: { speciesId: 'equine', name: 'Synthetic' },
owner: { name: 'Synthetic' },
observations: [...byZone.values()],
conclusion: '',
recommendations: '',
})
}
function nodeAt(
doc: AnatomicalSheetDocument,
zoneId: string,
path: readonly string[],
): FindingCategory | FindingNode | undefined {
const zone = doc.finding_zones.find((z) => z.id === zoneId)
let node: FindingCategory | FindingNode | undefined = zone?.categories.find(
(c) => c.id === path[0],
)
for (const segment of path.slice(1)) {
node = node?.children.find((n) => n.id === segment)
}
return node
}
async function readJson(relative: string): Promise<unknown> {
return JSON.parse(await readFile(join(REPO_ROOT, relative), 'utf8'))
}
let baseline: AnatomicalSheetDocument
let draft: AnatomicalSheetDocument
let map: ReportMigrationMap
let leaves: LegacyLeaf[]
let findings: Finding[]
beforeAll(async () => {
baseline = AnatomicalSheetDocumentSchema.parse(
await readJson(`${EQUINE_LEGACY_IMPORT_DIR}/document.json`),
)
draft = AnatomicalSheetDocumentSchema.parse(
await readJson(`${EQUINE_DRAFT_DIR}/document.json`),
)
map = ReportMigrationMapSchema.parse(
await readJson(`${EQUINE_DRAFT_DIR}/report-migration-map.json`),
)
leaves = legacyLeaves(baseline)
const { report } = migrateReportV2ToV3(leavesAsV2Report(leaves), map)
findings = report.observations.flatMap((o) => o.findings)
})
describe('every legacy leaf through the v2 → v3 migration', () => {
it('migrates the 612 leaves: 442 identical, 141 moved, 29 removed', () => {
expect(leaves).toHaveLength(612)
expect(findings).toHaveLength(612)
const fates = { identical: 0, moved: 0, removed: 0 }
leaves.forEach((leaf, i) => {
const out = findings[i]!
const same =
out.findingZoneId === leaf.zoneId &&
out.path.join('/') === leaf.path.join('/')
if (out.unresolved) fates.removed += 1
else if (same) fates.identical += 1
else fates.moved += 1
})
expect(fates).toEqual({ identical: 442, moved: 141, removed: 29 })
})
it('lands every resolved leaf on a leaf of the draft document', () => {
for (const out of findings) {
if (out.unresolved) continue
const node = nodeAt(draft, out.findingZoneId, out.path)
const where = `${out.findingZoneId}/${out.path.join('/')}`
expect(node, where).toBeDefined()
expect(node!.children, where).toHaveLength(0)
}
})
it('keeps the legacy snapshots and the vet flag verbatim on every finding', () => {
leaves.forEach((leaf, i) => {
const out = findings[i]!
expect(out.labelFrSnapshot).toBe(leaf.name.fr)
expect(out.labelEnSnapshot).toBe(leaf.name.en || leaf.name.fr)
expect(out.requiresVetReferral ?? false).toBe(leaf.vet)
})
})
it('flags exactly the leaves the curation removed, with their legacy path kept', () => {
const removed = leaves.filter(
(leaf) =>
map.finding_paths[findingPathKey(leaf.zoneId, leaf.path)] === null,
)
expect(removed).toHaveLength(29)
const flagged = findings.filter((f) => f.unresolved)
expect(
flagged.map((f) => `${f.findingZoneId}/${f.path.join('/')}`),
).toEqual(removed.map((leaf) => findingPathKey(leaf.zoneId, leaf.path)))
for (const f of flagged) {
expect(nodeAt(draft, f.findingZoneId, f.path)).toBeUndefined()
}
})
it('moves the 141 relocated leaves inside their zone: 134 under a renamed category, 7 renamed leaves', () => {
const fates = { category: 0, leaf: 0 }
leaves.forEach((leaf, i) => {
const out = findings[i]!
if (out.unresolved || out.path.join('/') === leaf.path.join('/')) return
expect(out.findingZoneId, leaf.path.join('/')).toBe(leaf.zoneId)
if (out.path.at(-1) === leaf.path.at(-1)) fates.category += 1
else fates.leaf += 1
})
expect(fates).toEqual({ category: 134, leaf: 7 })
})
it('reads the migrated report back unchanged (v3 is stable)', () => {
const { report } = migrateReportV2ToV3(leavesAsV2Report(leaves), map)
const again = readReportDocument(report, map)
expect(again.report).toEqual(report)
expect(again.unresolvedZones).toBe(0)
expect(again.unresolvedFindings).toBe(0)
})
})
describe('every legacy annotation as a report zone', () => {
it('maps the 26 observable legacy ids to annotations of the right view, names snapshotted', () => {
const triggers = new Set(
draft.annotations
.filter((a) => a.kind === 'detail_trigger')
.map((a) => a.id),
)
const legacyIds = Object.keys(map.annotations).filter(
(id) => !triggers.has(map.annotations[id]!.id),
)
expect(legacyIds).toHaveLength(26)
const headIds = new Set(
draft.annotations.filter((a) => a.view_id === 'head').map((a) => a.id),
)
const v2 = leavesAsV2Report([])
v2.observations = [
{
id: 'zones',
zones: legacyIds.map((boneId) =>
headIds.has(map.annotations[boneId]!.id)
? { boneId, detailSourceId: 'head' }
: { boneId },
),
findings: [],
freeTextFindings: [],
comment: '',
},
]
const out = migrateReportV2ToV3(v2, map)
expect(out.unresolvedZones).toBe(0)
out.report.observations[0]!.zones.forEach((zone, i) => {
const anno = draft.annotations.find((a) => a.id === zone.annotationId)
expect(anno, zone.annotationId).toBeDefined()
expect(anno!.view_id).toBe(zone.viewId)
expect(zone.labelFrSnapshot).toBe(map.annotations[legacyIds[i]!]!.name.fr)
})
})
it('keeps vertebrae on the spine zones with region codes the draft defines', () => {
const codes = new Set(draft.vertebral_config.regions.map((r) => r.code))
const spine = draft.annotations.filter(
(a): a is Extract<Annotation, { kind: 'point' | 'zone' }> =>
a.kind !== 'detail_trigger' && a.vertebral_region_code !== null,
)
expect(spine).toHaveLength(5)
for (const anno of spine)
expect(codes.has(anno.vertebral_region_code!)).toBe(true)
const legacyId = Object.keys(map.annotations).find(
(id) => map.annotations[id]!.id === 'cervical',
)!
const v2 = leavesAsV2Report([])
v2.observations = [
{
id: 'spine',
zones: [{ boneId: legacyId, vertebrae: [{ region: 'C', index: 7 }] }],
findings: [],
freeTextFindings: [],
comment: '',
},
]
const zone = migrateReportV2ToV3(v2, map).report.observations[0]!.zones[0]!
expect(zone.vertebrae).toEqual([{ region: 'C', index: 7 }])
expect(codes.has(zone.vertebrae![0]!.region)).toBe(true)
})
})
@@ -1,183 +0,0 @@
import { ReportMigrationMapSchema } from '@faunosteo/domain'
import { beforeAll, describe, expect, it } from 'vitest'
import {
applyChangeset,
buildReportMigrationMap,
type DraftResult,
type ImportResult,
} from '../src'
import { changesetOf, MINI_REFERENCES, miniSheet } from './fixtures/mini-sheet'
import { runDraft } from './helpers'
const SHEET = {
sheetId: 'sheet',
versionId: null,
documentSha256: 'f'.repeat(64),
}
describe('report migration map on the real draft', () => {
let result: ImportResult
let draft: DraftResult
let map: ReturnType<typeof buildReportMigrationMap>['map']
let stats: ReturnType<typeof buildReportMigrationMap>['stats']
beforeAll(async () => {
;({ result, draft } = await runDraft())
;({ map, stats } = buildReportMigrationMap({
baseline: draft.baseline as Record<string, unknown>,
final: draft.document as Record<string, unknown>,
legacyIdMap: draft.legacyIdMap,
records: draft.records,
sheet: SHEET,
mainViewId: 'main',
}))
})
it('is a valid map covering every legacy node, with the expected fates', () => {
expect(ReportMigrationMapSchema.parse(map)).toBeTruthy()
expect(stats).toEqual({
nodes: 792,
identical: 571,
remapped: 180,
rehomed: 7,
removed: 34,
})
expect(Object.keys(map.finding_paths)).toHaveLength(792)
})
it('maps every legacy annotation with its legacy labels and the views', () => {
expect(Object.keys(map.annotations)).toHaveLength(27)
expect(map.annotations['point-mpbwtst0']).toEqual({
id: 'hip',
name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' },
})
expect(map.annotations['zone-mpby55kd']).toEqual({
id: 'head-trigger',
name: { fr: '', en: '' },
})
expect(map.views).toEqual({ head: 'head' })
expect(map.main_view_id).toBe('main')
expect(result.legacyIdMap.annotations['point-mpbwtst0']).toBe('hip')
})
it('every target path exists in the draft; identical, renamed, re-homed and removed cases', () => {
const final = new Set<string>()
for (const zone of draft.document.finding_zones) {
const walk = (
nodes: readonly { id: string; children?: readonly unknown[] }[],
prefix: string,
) => {
for (const n of nodes) {
final.add(`${prefix}/${n.id}`)
walk((n.children ?? []) as never, `${prefix}/${n.id}`)
}
}
walk(zone.categories as never, zone.id)
}
for (const target of Object.values(map.finding_paths)) {
if (target !== null) expect(final.has(target), target).toBe(true)
}
expect(
map.finding_paths['hip/hip-dysfunctions/articular/restriction-flexion'],
).toBe('hip/hip-dysfunctions/articular/restriction-flexion')
expect(
map.finding_paths[
'cervical/cervical-observations/stumbling-proprioceptive'
],
).toBe('cervical/cervical-consultation-reasons/stumbling-proprioceptive')
expect(
map.finding_paths[
'sacroiliac/sacroiliac-dysfunctions/muscular/sacrotuberous-tension'
],
).toBe('sacroiliac/sacroiliac-dysfunctions/muscular/sacrotuberous-ligament')
expect(
map.finding_paths['sphenoid/ssb-dysfunctions/sutures/sphenopetrosal'],
).toBe('sphenoid/sphenoid-dysfunctions/sutures/sphenopetrosal')
expect(
map.finding_paths['ssb/ssb-dysfunctions/sutures/sphenozygomatic'],
).toBeNull()
expect(
map.finding_paths['frontal/frontal-dysfunctions/sutures/frontozygomatic'],
).toBeNull()
})
})
describe('report migration map replay on a synthetic changeset', () => {
function mapOf(ops: Parameters<typeof changesetOf>[0]) {
const baseline = miniSheet()
const result = applyChangeset(baseline, MINI_REFERENCES, changesetOf(ops))
return buildReportMigrationMap({
baseline: miniSheet() as never,
final: result.document as never,
legacyIdMap: {
views: { head: 'head' },
annotations: { 'legacy-hip': 'hip' },
categories: {},
finding_nodes: {},
assets: {},
},
records: result.records,
sheet: SHEET,
mainViewId: 'main',
})
}
it('follows a rename, a move and a removal, and a renamed annotation', () => {
const { map, stats } = mapOf([
{
op: 'rename',
target: 'finding:hip/hip-dysfunctions/mobility',
id: 'motion',
},
{
op: 'move',
target: 'finding:hip/hip-dysfunctions/motion/flexion',
to: 'finding:hip/anamnesis',
},
{ op: 'remove', target: 'finding:neck/neck-dysfunctions/vet' },
{ op: 'rename', target: 'annotation:hip', id: 'coxofemoral' },
])
expect(map.finding_paths['hip/hip-dysfunctions/mobility/extension']).toBe(
'hip/hip-dysfunctions/motion/extension',
)
expect(map.finding_paths['hip/hip-dysfunctions/mobility/flexion']).toBe(
'hip/anamnesis/flexion',
)
expect(map.finding_paths['neck/neck-dysfunctions/vet']).toBeNull()
expect(map.finding_paths['neck/neck-dysfunctions/stiffness']).toBe(
'neck/neck-dysfunctions/stiffness',
)
expect(map.annotations['legacy-hip']!.id).toBe('coxofemoral')
expect(stats.removed).toBe(1)
})
it('re-homes a node whose category was replaced by another one holding the same path', () => {
const { map, stats } = mapOf([
{
op: 'add',
target: 'zone:hip',
value: {
id: 'hip-new',
kind: 'dysfunction',
name: { fr: 'N', en: 'N' },
children: [
{
id: 'mobility',
name: { fr: 'M', en: 'M' },
children: [{ id: 'flexion', name: { fr: 'F', en: 'F' } }],
},
],
},
},
{ op: 'remove', target: 'finding:hip/hip-dysfunctions' },
])
expect(map.finding_paths['hip/hip-dysfunctions/mobility/flexion']).toBe(
'hip/hip-new/mobility/flexion',
)
expect(
map.finding_paths['hip/hip-dysfunctions/mobility/extension'],
).toBeNull()
expect(map.finding_paths['hip/hip-dysfunctions']).toBeNull()
expect(stats.rehomed).toBe(2)
})
})
@@ -1,83 +0,0 @@
import { DOMParser } from '@xmldom/xmldom'
import { describe, expect, it } from 'vitest'
import { overlayMarkers, renderReviewOverlay } from '../src'
import { miniSheet } from './fixtures/mini-sheet'
const DRAWING =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="10">' +
'<path d="M0 0h10"/></svg>'
function moved() {
const after = miniSheet()
const hip = after.annotations.find((a) => a.id === 'hip')!
hip.geometry = { type: 'circle', cx: 50, cy: 60, r: 3 }
after.annotations.push({
...hip,
id: 'knee',
geometry: {
type: 'polygon',
points: [
[0, 0],
[10, 0],
[5, 5],
],
},
})
return after
}
describe('review overlay', () => {
it('marks moved annotations with their previous position', () => {
const markers = overlayMarkers(miniSheet(), moved(), 'main')
const byId = (id: string) => markers.filter((m) => m.id === id)
expect(byId('hip').map((m) => m.status)).toEqual(['moved', 'removed'])
expect(byId('knee').map((m) => m.status)).toEqual(['added'])
expect(markers.every((m) => m.geometry !== null)).toBe(true)
})
it('reports an annotation dropped by the changeset', () => {
const after = miniSheet()
after.annotations = after.annotations.filter((a) => a.id !== 'hip')
const markers = overlayMarkers(miniSheet(), after, 'main')
expect(markers.find((m) => m.id === 'hip')?.status).toBe('removed')
})
it('renders a framed SVG with one group per marker and a legend', () => {
const svg = renderReviewOverlay({
cleanedSvg: DRAWING,
before: miniSheet(),
after: moved(),
viewId: 'main',
})
const root = new DOMParser().parseFromString(
svg,
'image/svg+xml',
).documentElement!
expect(root.getAttribute('width')).toBeNull()
const groups = Array.from(root.getElementsByTagName('g')).filter((g) =>
g.hasAttribute('data-review-id'),
)
expect(groups.map((g) => g.getAttribute('data-review-status'))).toEqual([
'moved',
'removed',
'added',
])
expect(svg).toContain('stroke-dasharray')
expect(svg).toContain('inchangé')
expect(svg).toContain('<path d="M0 0h10"/>')
})
it('frames a detail view on its view box', () => {
const after = moved()
const svg = renderReviewOverlay({
cleanedSvg: DRAWING,
before: miniSheet(),
after,
viewId: after.views[1]!.id,
})
const box = after.views[1]!.view_box!
expect(svg).toContain(
`viewBox="${box.min_x} ${box.min_y} ${box.width} ${box.height}"`,
)
})
})
@@ -1,110 +0,0 @@
import {
AnatomicalSheetDocumentSchema,
validateSheetDocument,
} from '@faunosteo/domain'
import {
buildEquineDraft,
DRAFT_SEED_SQL_FILE,
renderDraftArtifacts,
type DraftResult,
type ImportResult,
} from '../src'
import { changesetOf } from './fixtures/mini-sheet'
import { runDraft } from './helpers'
const VIEW_BOX = { min_x: 0, min_y: 0, width: 1, height: 1 }
let result: ImportResult
let draft: DraftResult
let artifacts: Record<string, string>
beforeAll(async () => {
;({ result, draft } = await runDraft())
artifacts = await renderDraftArtifacts(draft, result.anomalies)
})
const REVIEW_HEADINGS = [
'1. Qualité des données initiales',
'2. Principales erreurs anatomiques et ostéopathiques',
'3. Corrections effectuées',
'4. Ajouts',
'5. Réorganisations du catalogue',
'6. Éléments incertains',
'7. Traductions',
'8. Points de vigilance clinique',
'9. Bibliographie',
'10. Décisions réservées au professionnel',
]
describe('equine working draft (real sources + committed curation)', () => {
it('validates with zero integrity error', () => {
const parsed = AnatomicalSheetDocumentSchema.parse(draft.document)
const errors = validateSheetDocument(parsed).filter(
(i) => i.severity === 'error',
)
expect(errors).toEqual([])
expect(draft.sheetId).toBe(result.sheetId)
})
it('carries one drawing and the curated content', () => {
expect(draft.statsBefore.assets).toBe(2)
expect(draft.statsAfter.assets).toBe(1)
expect(draft.assets).toHaveLength(1)
const [main, head] = draft.document.views
expect(main!.svg_asset_id).toBe(draft.assets[0]!.svg_asset_id)
expect(head).toMatchObject({
svg_asset_id: null,
view_box: { min_x: 60, min_y: 100, width: 500, height: 380 },
})
const cd = draft.document.vertebral_config.regions.find(
(r) => r.code === 'Cd',
)
expect(cd!.count_range).toEqual({ min: 15, max: 21 })
// Carpus zone added, linked from its annotation (CHG carpus_zone).
const carpus = draft.document.annotations.find((a) => a.id === 'carpus')
expect(carpus).toMatchObject({ finding_zone_id: 'carpus', kind: 'point' })
expect(draft.document.finding_zones.some((z) => z.id === 'carpus')).toBe(
true,
)
// Node volume: 792 legacy − SSB duplicates − absent sutures + carpus & flags.
expect(draft.statsAfter.nodes).toBe(811)
expect(draft.statsAfter.descriptionsFrOnly).toBe(0)
})
it('lists CHG-000 and the Cd range change in the CHANGELOG', () => {
const changelog = artifacts['CHANGELOG.md']!
expect(changelog).toContain('## Comparaison quantitative')
expect(changelog).toMatch(/\| `CHG-000` .*`view:head\.view_box`/)
expect(changelog).toMatch(/\| `CHG-\d{3}` .*`region:Cd\.count_range`/)
})
it('writes the ten review sections in order', () => {
const headings = [
...artifacts['REVIEW-REPORT.md']!.matchAll(/^## (.+)$/gm),
].map((m) => m[1])
expect(headings).toEqual(REVIEW_HEADINGS)
})
it('seeds a converging draft and never publishes', () => {
const sql = artifacts[DRAFT_SEED_SQL_FILE]!
expect(sql).toContain('private.insert_sheet_draft')
expect(sql).toMatch(
/update public\.anatomical_sheet_versions[\s\S]*status = 'draft'/,
)
expect(sql).not.toContain('publish_sheet_version')
})
it('refuses a changeset that reuses the reserved CHG-000', () => {
const [own] = changesetOf([{ op: 'remove', target: 'zone:hip' }]).changes
const changeset = { changes: [{ ...own!, id: 'CHG-000' }] }
const input = { importResult: result, legacyMainSvgBytes: new Uint8Array() }
expect(() =>
buildEquineDraft({
...input,
headViewBox: VIEW_BOX,
references: [],
changeset,
}),
).toThrow('CHG-000 is reserved')
})
})
@@ -1,85 +0,0 @@
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import {
ChangesetSchema,
EQUINE_CURATION_DIR,
ReferencesFileSchema,
needsConfirmation,
} from '../src'
import { REPO_ROOT } from './helpers'
async function committed(file: string): Promise<unknown> {
return JSON.parse(
await readFile(join(REPO_ROOT, EQUINE_CURATION_DIR, file), 'utf8'),
)
}
const CHANGE = {
id: 'CHG-002',
level: 'B',
kind: 'terminology',
title: { fr: 'Titre', en: 'Title' },
rationale: 'Raison',
reference_ids: [],
ops: [{ op: 'remove', target: 'zone:x' }],
}
describe('curation schemas', () => {
it('parse the committed curation files', async () => {
const changeset = ChangesetSchema.parse(await committed('changes.json'))
const ids = changeset.changes.map((c) => c.id)
expect(ids[0]).toBe('CHG-001')
expect(ids).toEqual([...ids].sort())
expect(new Set(ids).size).toBe(ids.length)
expect(changeset.changes.every((c) => c.level !== 'C' || c.question)).toBe(
true,
)
const refs = ReferencesFileSchema.parse(await committed('references.json'))
const refIds = refs.references.map((r) => r.id)
expect(refIds).toContain('legacy-catalog')
expect(new Set(refIds).size).toBe(refIds.length)
const cited = new Set(changeset.changes.flatMap((c) => c.reference_ids))
for (const id of cited) expect(refIds).toContain(id)
})
it.each([
[
'an unknown op',
{ ...CHANGE, ops: [{ op: 'replace', target: 'zone:x' }] },
],
['a level C change without question', { ...CHANGE, level: 'C' }],
['a bad change id', { ...CHANGE, id: 'CHANGE-1' }],
['a change without ops', { ...CHANGE, ops: [] }],
['an unknown key', { ...CHANGE, needs_confirmation: true }],
])('rejects %s', (_label, change) => {
expect(ChangesetSchema.safeParse({ changes: [change] }).success).toBe(false)
})
it('accepts a level C change with its question', () => {
const change = {
...CHANGE,
level: 'C',
question: 'Faut-il ?',
priority: 'high',
}
expect(ChangesetSchema.safeParse({ changes: [change] }).success).toBe(true)
})
it('rejects duplicate change ids and duplicate reference ids', () => {
expect(
ChangesetSchema.safeParse({ changes: [CHANGE, CHANGE] }).success,
).toBe(false)
const ref = { id: 'a', type: 'web', citation: 'A', url: null, doi: null }
expect(
ReferencesFileSchema.safeParse({ references: [ref, ref] }).success,
).toBe(false)
})
it('derives needs_confirmation from the level', () => {
expect(['A', 'B', 'C'].map((l) => needsConfirmation(l as 'A'))).toEqual([
false,
true,
true,
])
})
})
-23
View File
@@ -1,23 +0,0 @@
import {
AnatomicalSheetDocumentSchema,
validateSheetDocument,
} from '@faunosteo/domain'
import { importEquineLegacy, renderArtifacts } from '../src'
import { loadInput, runImport } from './helpers'
describe('equine document', () => {
it('parses and validates with no error and no warning', async () => {
const { document, issues } = await runImport()
const parsed = AnatomicalSheetDocumentSchema.parse(document)
expect(validateSheetDocument(parsed)).toEqual([])
expect(issues).toEqual([])
})
it('is deterministic: same result and same bytes on two runs', async () => {
const input = await loadInput()
const first = importEquineLegacy(input)
const second = importEquineLegacy(input)
expect(second).toEqual(first)
expect(await renderArtifacts(second)).toEqual(await renderArtifacts(first))
})
})
-175
View File
@@ -1,175 +0,0 @@
import type {
AnatomicalSheetDocumentInput,
FindingNodeInput,
Reference,
} from '@faunosteo/domain'
import type { ChangeInput, Changeset, Op } from '../../src'
import { ChangesetSchema } from '../../src'
/**
* Small synthetic sheet for the curation unit tests: two finding zones with
* nested nodes, two observable annotations, one detail view opened by a
* trigger. Lean input form, zero integrity issue as written.
*/
function leaf(
id: string,
extra: Partial<FindingNodeInput> = {},
): FindingNodeInput {
return { id, name: { fr: `${id} fr`, en: `${id} en` }, ...extra }
}
export const MINI_REFERENCES: Reference[] = [
{
id: 'atlas',
type: 'book',
citation: 'Atlas of anatomy',
url: null,
doi: null,
},
{
id: 'paper',
type: 'journal',
citation: 'A paper',
url: null,
doi: '10.1/x',
},
]
export function miniSheet(): AnatomicalSheetDocumentInput {
return {
schema_version: 2,
species_id: 'equine',
name: { fr: 'Mini', en: 'Mini' },
description: {},
scope_disclaimer: {},
attribution: { authors: [], license: null, notes: null },
vertebral_config: {
regions: [
{ code: 'C', name: { fr: 'Cervicales', en: 'Cervical' }, count: 7 },
{ code: 'T', name: { fr: 'Thoraciques', en: 'Thoracic' }, count: 18 },
],
},
references: [],
categories: [
{
id: 'joints',
name: { fr: 'Articulations', en: 'Joints' },
color: null,
},
{ id: 'bones', name: { fr: 'Os', en: 'Bones' }, color: null },
],
views: [
{
id: 'main',
kind: 'main',
name: { fr: 'Vue', en: 'View' },
svg_asset_id: '3f6c1b52-8a4e-4d17-9b0c-5e2a7d91c4f8',
view_box: null,
},
{
id: 'head',
kind: 'detail',
parent_view_id: 'main',
name: { fr: 'Tête', en: 'Head' },
svg_asset_id: null,
view_box: { min_x: 0, min_y: 0, width: 10, height: 10 },
},
],
annotations: [
{
id: 'hip',
kind: 'point',
view_id: 'main',
category_id: 'joints',
laterality: 'bilateral',
geometry: { type: 'circle', cx: 1, cy: 2, r: 3 },
name: { fr: 'Hanche', en: 'Hip' },
finding_zone_id: 'hip',
vertebral_region_code: null,
},
{
id: 'neck',
kind: 'zone',
view_id: 'main',
category_id: 'bones',
laterality: 'unpaired',
geometry: null,
name: { fr: 'Cou', en: 'Neck' },
finding_zone_id: 'neck',
vertebral_region_code: 'C',
},
{
id: 'head-trigger',
kind: 'detail_trigger',
view_id: 'main',
category_id: 'bones',
laterality: 'unpaired',
geometry: null,
name: null,
opens_view_id: 'head',
},
],
finding_zones: [
{
id: 'hip',
name: { fr: 'Hanche', en: 'Hip' },
categories: [
{
id: 'hip-dysfunctions',
kind: 'dysfunction',
name: { fr: 'Dysfonctions', en: 'Dysfunctions' },
children: [
leaf('mobility', {
children: [leaf('flexion'), leaf('extension')],
}),
leaf('pain'),
],
},
{
id: 'anamnesis',
kind: 'anamnesis',
name: { fr: 'Anamnèse', en: 'Anamnesis' },
children: [leaf('trauma')],
},
],
},
{
id: 'neck',
name: { fr: 'Cou', en: 'Neck' },
categories: [
{
id: 'neck-dysfunctions',
kind: 'dysfunction',
name: { fr: 'Dysfonctions', en: 'Dysfunctions' },
children: [
leaf('stiffness'),
leaf('vet', { requires_vet_referral: true }),
],
},
],
},
],
}
}
/** One level A change carrying the given ops, parsed like changes.json. */
export function changesetOf(
ops: Op[],
extra: Partial<ChangeInput> = {},
): Changeset {
return ChangesetSchema.parse({
changes: [
{
id: 'CHG-001',
level: 'A',
kind: 'technical',
title: { fr: 'Essai', en: 'Test' },
rationale: 'Essai',
reference_ids: [],
ops,
...extra,
},
],
})
}
-57
View File
@@ -1,57 +0,0 @@
import { readFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import { join } from 'node:path'
import {
buildEquineDraft,
EQUINE_SOURCE_PATHS,
HEAD_VIEW_ID,
importEquineLegacy,
parseViewBox,
readEquineCuration,
readEquineSources,
type DraftResult,
type EquineLegacyInput,
type ImportResult,
} from '../src'
import type { LegacyCatalog } from '../src/legacy/catalog'
/** Tests run on the real legacy sources, never on copies. */
export const REPO_ROOT = fileURLToPath(new URL('../../../', import.meta.url))
export function loadInput(): Promise<EquineLegacyInput> {
return readEquineSources(REPO_ROOT)
}
export async function runImport(): Promise<ImportResult> {
return importEquineLegacy(await loadInput())
}
export async function loadCatalog(): Promise<LegacyCatalog> {
const text = await readFile(
join(REPO_ROOT, EQUINE_SOURCE_PATHS.catalog),
'utf8',
)
return JSON.parse(text) as LegacyCatalog
}
export async function legacyAnnoIds(path: string): Promise<string[]> {
const text = await readFile(join(REPO_ROOT, path), 'utf8')
const ids = [...text.matchAll(/data-anno-id="([^"]+)"/g)].map((m) => m[1]!)
return [...new Set(ids)]
}
/** Legacy import + committed curation files → the working draft. */
export async function runDraft(): Promise<{
result: ImportResult
draft: DraftResult
}> {
const input = await loadInput()
const result = importEquineLegacy(input)
const draft = buildEquineDraft({
importResult: result,
legacyMainSvgBytes: input.mainSvg.bytes,
headViewBox: parseViewBox(result.viewBoxes[HEAD_VIEW_ID] ?? null),
...(await readEquineCuration(REPO_ROOT)),
})
return { result, draft }
}
@@ -1,103 +0,0 @@
import type { FindingNodeInput } from '@faunosteo/domain'
import { EQUINE_SOURCE_PATHS, type ImportResult } from '../src'
import { legacyAnnoIds, runImport } from './helpers'
let result: ImportResult
beforeAll(async () => {
result = await runImport()
})
describe('equine import volumes', () => {
it('imports 27 annotations, 26 linked to a finding zone', () => {
const annotations = result.document.annotations
expect(annotations).toHaveLength(27)
const linked = annotations.filter(
(a) => a.kind !== 'detail_trigger' && a.finding_zone_id !== null,
)
expect(linked).toHaveLength(26)
})
it('has two views and one trigger opening head from main', () => {
expect(result.document.views.map((v) => v.id)).toEqual(['main', 'head'])
const triggers = result.document.annotations.filter(
(a) => a.kind === 'detail_trigger',
)
expect(triggers).toHaveLength(1)
expect(triggers[0]).toMatchObject({
view_id: 'main',
opens_view_id: 'head',
})
})
it('codes exactly the five zone-colonne polygons with C, T, L, S, Cd', () => {
const coded = result.document.annotations.filter(
(a) => a.kind !== 'detail_trigger' && a.vertebral_region_code !== null,
)
expect(coded).toHaveLength(5)
expect(new Set(coded.map((a) => a.kind))).toEqual(new Set(['zone']))
expect(new Set(coded.map((a) => a.category_id))).toEqual(
new Set(['zone-colonne']),
)
const codes = coded.map((a) =>
a.kind === 'detail_trigger' ? null : a.vertebral_region_code,
)
expect(new Set(codes)).toEqual(new Set(['C', 'T', 'L', 'S', 'Cd']))
})
it('counts 9 bilateral annotations', () => {
const bilateral = result.document.annotations.filter(
(a) => a.laterality === 'bilateral',
)
expect(bilateral).toHaveLength(9)
})
it('writes 792 nodes, 612 leaves, 41 vet referrals in the document', () => {
const counts = { nodes: 0, leaves: 0, vet: 0 }
const walk = (nodes: readonly FindingNodeInput[]): void => {
for (const node of nodes) {
counts.nodes += 1
if (!node.children?.length) counts.leaves += 1
if (node.requires_vet_referral === true) counts.vet += 1
walk(node.children ?? [])
}
}
for (const zone of result.document.finding_zones) {
counts.nodes += zone.categories.length
for (const category of zone.categories) walk(category.children)
}
expect(counts).toEqual({ nodes: 792, leaves: 612, vet: 41 })
})
it('reports the input side from the sources: 27 ids, 26 zones, 792/612/41', () => {
expect(result.document.finding_zones).toHaveLength(26)
expect(result.stats).toMatchObject({
legacyAnnotations: 27,
findingZones: 26,
nodes: 792,
leaves: 612,
vetReferrals: 41,
})
})
it('maps every data-anno-id of both SVGs', async () => {
const ids = [
...(await legacyAnnoIds(EQUINE_SOURCE_PATHS.mainSvg)),
...(await legacyAnnoIds(EQUINE_SOURCE_PATHS.headSvg)),
]
expect(ids).toHaveLength(27)
expect(Object.keys(result.legacyIdMap.annotations).sort()).toEqual(
ids.sort(),
)
})
it('places the nine head annotations in view head', async () => {
const headIds = await legacyAnnoIds(EQUINE_SOURCE_PATHS.headSvg)
const newIds = new Set(
headIds.map((id) => result.legacyIdMap.annotations[id]),
)
const inHead = result.document.annotations.filter((a) => newIds.has(a.id))
expect(inHead).toHaveLength(9)
expect(inHead.every((a) => a.view_id === 'head')).toBe(true)
})
})
@@ -1,47 +0,0 @@
import { DOCUMENT_DOLLAR_TAG, renderDraftSeedSql } from '../src'
import { mapAnnotation } from '../src/legacy/annotations'
import { assertNothingDropped } from '../src/legacy/catalog'
import { parseAnnotatedSvg } from '../src/legacy/svg'
import { runImport } from './helpers'
/** Guards that never fire on today's data, proven on synthetic inputs. */
const SVG_WITHOUT_EN = `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10">
<circle cx="1" cy="2" r="3" data-anno-id="point-x"
data-anno-name-fr="Garrot" data-anno-category="os"/>
</svg>`
describe('importer guards', () => {
it('throws when a zone loses a vet referral', () => {
const before = { nodes: 10, leaves: 7, vetReferrals: 2 }
const after = { nodes: 10, leaves: 7, vetReferrals: 1 }
expect(() => assertNothingDropped('hip', before, after)).toThrow(
'zone hip: vetReferrals 2 in, 1 out',
)
expect(() => assertNothingDropped('hip', before, before)).not.toThrow()
})
it('copies FR into EN when data-anno-name-en is absent, and says so', () => {
const [legacy] = parseAnnotatedSvg(SVG_WITHOUT_EN, 'x.svg').annotations
const mapped = mapAnnotation(legacy!, {
viewId: 'main',
fileName: 'x.svg',
zoneByNames: new Map(),
})
expect(mapped.annotation.name).toEqual({ fr: 'Garrot', en: 'Garrot' })
expect(mapped.anomalies.map((a) => [a.code, a.level])).toContainEqual([
'annotation.name_en.missing',
'a_valider',
])
})
it('refuses a document that contains the dollar-quote tag', async () => {
const result = await runImport()
const documentJson = JSON.stringify({ note: DOCUMENT_DOLLAR_TAG })
const params = { sheetId: result.sheetId, assets: [], changeNote: 'x' }
expect(() => renderDraftSeedSql({ ...params, documentJson })).toThrow(
DOCUMENT_DOLLAR_TAG,
)
})
})
@@ -1,128 +0,0 @@
import type { FindingNodeInput } from '@faunosteo/domain'
import { renderImportReport, type ImportResult } from '../src'
import type { LegacyCatalog, LegacyNode } from '../src/legacy/catalog'
import { loadCatalog, runImport } from './helpers'
let result: ImportResult
let catalog: LegacyCatalog
beforeAll(async () => {
;[result, catalog] = await Promise.all([runImport(), loadCatalog()])
})
function annotation(id: string) {
const found = result.document.annotations.find((a) => a.id === id)
if (!found) throw new Error(`annotation ${id} missing`)
return found
}
function zone(id: string) {
const found = result.document.finding_zones.find((z) => z.id === id)
if (!found) throw new Error(`zone ${id} missing`)
return found
}
/** Id skeleton of a tree: same shape whatever the label language. */
function idTree(
nodes: ReadonlyArray<LegacyNode | FindingNodeInput>,
): unknown[] {
return nodes.map((n) => [n.id, idTree(n.children ?? [])])
}
describe('equine import special cases', () => {
it('turns vertebral-precision into a region code', () => {
expect(annotation('lumbar')).toMatchObject({
kind: 'zone',
vertebral_region_code: 'L',
finding_zone_id: 'lumbar',
})
expect(annotation('caudal')).toMatchObject({ vertebral_region_code: 'Cd' })
})
it('makes data-anno-lateral explicit', () => {
expect(annotation('hip').laterality).toBe('bilateral')
expect(annotation('c7-t1').laterality).toBe('unpaired')
})
it('imports the trigger without name and without finding zone', () => {
const trigger = annotation('head-trigger')
expect(trigger.kind).toBe('detail_trigger')
expect(trigger.name).toBeNull()
expect(trigger).not.toHaveProperty('finding_zone_id')
})
it('keeps ssb-dysfunctions under sphenoid and names it in the report', () => {
expect(zone('sphenoid').categories[0]!.id).toBe('ssb-dysfunctions')
expect(zone('ssb').categories[0]!.id).toBe('ssb-dysfunctions')
const report = renderImportReport(result)
expect(report).toContain('sphenoid/ssb-dysfunctions')
expect(report).toContain('sphenoid-dysfunctions attendu')
})
it('keeps the anamnesis category in all zones with its three variants', () => {
const imported = result.document.finding_zones.map((z) => {
const category = z.categories.find((c) => c.id === 'anamnesis')
expect(category?.kind).toBe('anamnesis')
return idTree(category?.children ?? []).join('|')
})
const legacy = Object.values(catalog.zones).map((z) =>
idTree(
z.categories.find((c) => c.id === 'anamnesis')!.children ?? [],
).join('|'),
)
expect(imported).toHaveLength(26)
expect(imported).toEqual(legacy)
expect(new Set(imported).size).toBe(3)
})
it('writes no en key where description_en is absent', () => {
const category = zone('parietal').categories.find(
(c) => c.id === 'anamnesis',
)!
expect(category.description).toEqual({
fr: catalog.zones.parietal!.categories[2]!.description_fr,
})
const mobility = zone('parietal').categories[0]!.children[0]!
expect(mobility.description).toBeDefined()
expect(mobility.description).not.toHaveProperty('en')
})
it('maps category kinds from their ids', () => {
const kinds = zone('hip').categories.map((c) => [c.id, c.kind])
expect(kinds).toEqual([
['hip-dysfunctions', 'dysfunction'],
['hip-observations', 'consultation_reason'],
['anamnesis', 'anamnesis'],
])
})
it('preserves node ids at every level of every zone', () => {
for (const [key, legacy] of Object.entries(catalog.zones)) {
expect(idTree(zone(key).categories)).toEqual(idTree(legacy.categories))
}
})
it('writes the lean form: no default keys on plain leaves', () => {
const leaf = zone('parietal').categories[0]!.children[0]!.children![0]!
expect(Object.keys(leaf).sort()).toEqual(['id', 'name'])
})
})
describe('importer-authored labels', () => {
it('declares every label written without a source', () => {
const subjects = result.anomalies
.filter((a) => a.code === 'label.authored' && a.level === 'a_valider')
.map((a) => a.subject)
expect(subjects).toEqual([
'name',
'description',
'views.main',
'views.head',
'vertebral_config.C',
'vertebral_config.T',
'vertebral_config.L',
'vertebral_config.S',
'vertebral_config.Cd',
])
})
})
@@ -1,43 +0,0 @@
import { describe, expect, it } from 'vitest'
import { inferRegionCode } from '../src/legacy/regions'
const code = (fr: string | null, en: string | null = null) =>
inferRegionCode(fr, en)?.code
describe('inferRegionCode', () => {
it('matches FR roots, with and without accents', () => {
expect(code('Vertèbres cervicales')).toBe('C')
expect(code('Vertebres cervicales')).toBe('C')
expect(code('Vertèbres thoraciques')).toBe('T')
expect(code('Vertebres thoraciques')).toBe('T')
expect(code('Vertèbres lombaires')).toBe('L')
expect(code('Vertèbres sacrales')).toBe('S')
expect(code('Vertèbres sacrées')).toBe('S')
expect(code('Vertèbres caudales')).toBe('Cd')
expect(code('Vertèbres coccygiennes')).toBe('Cd')
expect(code('Région dorsale')).toBe('T')
})
it('matches EN roots when the FR label is absent', () => {
expect(code(null, 'Cervical Vertebrae')).toBe('C')
expect(code(null, 'Thoracic Vertebrae')).toBe('T')
expect(code(null, 'Lumbar Vertebrae')).toBe('L')
expect(code(null, 'Sacral Vertebrae')).toBe('S')
expect(code(null, 'Coccygeal Vertebrae')).toBe('Cd')
})
it('returns null when no root matches', () => {
expect(inferRegionCode('Épaule', 'Shoulder')).toBeNull()
expect(inferRegionCode('', '')).toBeNull()
expect(inferRegionCode(null, null)).toBeNull()
})
it('reports the matched root and label, FR before EN', () => {
expect(inferRegionCode('Vertèbres lombaires', 'Cervical')).toEqual({
code: 'L',
root: 'lombair',
label: 'Vertèbres lombaires',
})
expect(code('Épaule', 'Cervical Vertebrae')).toBe('C')
})
})
@@ -1,162 +0,0 @@
/**
* R3 freeze O2 (plan 2026-10-14 §3): the annotation layer as the TypeScript
* renderer builds it, attribute order kept, for the Rust layer to reproduce
* exactly. Cases: the curated draft (main, head; no state, a state set,
* every annotation) and an edge document covering what the draft lacks
* (shape by geometry type, twin radius floor, exponent numbers, path
* geometry, a circle trigger without a name, colour fallback, laterality).
* `MAKE_R3_ORACLES=1` writes `crates/core/tests/oracles/r3/layer.json`;
* otherwise the TypeScript still matches its own freeze (it is frozen too).
*/
import { readFileSync, mkdirSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import {
AnatomicalSheetDocumentSchema,
type AnatomicalSheetDocument,
type AnatomicalSheetDocumentInput,
} from '@faunosteo/domain'
import { renderAnnotationLayer, type AnnotationState } from '../src/render'
import { miniSheet } from './fixtures/mini-sheet'
const HERE = dirname(fileURLToPath(import.meta.url))
const ORACLES = resolve(HERE, '../../../crates/core/tests/oracles')
const OUT = resolve(ORACLES, 'r3/layer.json')
const MAKE = process.env.MAKE_R3_ORACLES === '1'
function draft(): AnatomicalSheetDocument {
const file = JSON.parse(readFileSync(resolve(ORACLES, 'sheet.draft.json'), 'utf8'))
return file.output as AnatomicalSheetDocument
}
const observable = {
category_id: 'joints',
laterality: 'unpaired' as const,
finding_zone_id: 'hip',
vertebral_region_code: null,
}
/** The mini sheet plus one annotation per behaviour the draft never exercises. */
export function edgeDocument(): AnatomicalSheetDocument {
const base = miniSheet()
const doc: AnatomicalSheetDocumentInput = {
...base,
categories: [
{ id: 'joints', name: { fr: 'Articulations', en: 'Joints' }, color: '#ff9500' },
{ id: 'bones', name: { fr: 'Os', en: 'Bones' }, color: null },
],
annotations: [
...base.annotations,
{
...observable,
id: 'point-polygon',
kind: 'point',
view_id: 'main',
laterality: 'left',
geometry: { type: 'polygon', points: [[0.1, 0.2], [1.5e-7, 3], [2, 1e21]] },
name: { fr: 'Polygone « point »', en: 'Point & <polygon>' },
},
{
...observable,
id: 'zone-circle',
kind: 'zone',
view_id: 'main',
laterality: 'right',
geometry: { type: 'circle', cx: 743.0451049804688, cy: 0.30000000000000004, r: 12.5 },
name: { fr: 'Zone ronde', en: 'Round zone' },
color: '#123456',
},
{
...observable,
id: 'zone-path',
kind: 'zone',
view_id: 'main',
category_id: 'bones',
geometry: { type: 'path', d: 'M0 0 L10 10 Z' },
name: { fr: 'Chemin', en: 'Path' },
finding_zone_id: null,
vertebral_region_code: 'T',
},
{
id: 'trigger-circle',
kind: 'detail_trigger',
view_id: 'main',
category_id: 'missing-category',
laterality: 'unpaired',
geometry: { type: 'circle', cx: 5, cy: 5, r: 40 },
name: null,
opens_view_id: 'head',
},
{
id: 'trigger-named',
kind: 'detail_trigger',
view_id: 'main',
category_id: 'bones',
laterality: 'unpaired',
geometry: { type: 'polygon', points: [[0, 0], [1, 0], [1, 1]] },
name: { fr: 'Ouvrir', en: 'Open' },
opens_view_id: 'head',
},
{
...observable,
id: 'head-point',
kind: 'point',
view_id: 'head',
laterality: 'bilateral',
geometry: { type: 'circle', cx: 1, cy: 1, r: 27.5 },
name: { fr: 'Tête', en: 'Head' },
},
],
}
return AnatomicalSheetDocumentSchema.parse(doc)
}
interface LayerCase {
doc: 'draft' | 'edge'
viewId: string
states: string[]
layer: unknown
}
function layerCase(
name: LayerCase['doc'],
document: AnatomicalSheetDocument,
viewId: string,
states: string[],
): LayerCase {
const map = new Map<string, AnnotationState>(states.map((id) => [id, 'current']))
return { doc: name, viewId, states, layer: renderAnnotationLayer({ document, viewId, states: map }) }
}
function cases(): { edge: AnatomicalSheetDocument; cases: LayerCase[] } {
const d = draft()
const e = edgeDocument()
const allDraft = d.annotations.map((a) => a.id)
const allEdge = e.annotations.map((a) => a.id)
return {
edge: e,
cases: [
layerCase('draft', d, 'main', []),
layerCase('draft', d, 'main', ['hip', 'cervical', 'head-trigger', 'atm']),
layerCase('draft', d, 'main', allDraft),
layerCase('draft', d, 'head', []),
layerCase('draft', d, 'head', ['atm', 'frontal', 'hip']),
layerCase('edge', e, 'main', []),
layerCase('edge', e, 'main', allEdge),
layerCase('edge', e, 'head', ['head-point']),
],
}
}
describe('R3 layer oracles (TypeScript freeze)', () => {
it('matches the frozen layer trees', () => {
const actual = cases()
if (MAKE) {
mkdirSync(dirname(OUT), { recursive: true })
writeFileSync(OUT, `${JSON.stringify(actual, null, 1)}\n`)
return
}
expect(actual).toEqual(JSON.parse(readFileSync(OUT, 'utf8')))
})
})
File diff suppressed because it is too large. Load diff
@@ -1,391 +0,0 @@
/**
* R5.2 freeze (owner brief 2026-10-22 §9): the formatting and JavaScript
* semantics the Rust pipeline must reproduce, recorded from the tools
* themselves on generic inputs, not only on the equine data. Three oracles
* under crates/core/tests/oracles/r5/:
*
* - prettier-json.json: `formatJson` (Prettier 3, parser json, the
* repository options) over synthetic values probing the layout rules:
* short arrays collapsed, number arrays filled, the 80-column boundary at
* several depths and key widths, nested arrays, objects, empty
* containers, Unicode widths.
* - markdown-tables.json: `formatMarkdown` over raw tables as
* `markdown.ts` writes them (alignment, padding, Unicode widths, escaped
* pipes, empty cells).
* - js-semantics.json: `slugify`, `deterministicUuid`, `inferRegionCode`,
* `Number()`, the points split of the SVG reader, `Math.round`,
* `Object.entries` key order of `JSON.parse`, `toLowerCase`, NFD.
*
* `MAKE_R5_ORACLES=1` writes the files; otherwise the tools still match the
* freeze.
*/
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { formatJson, formatMarkdown } from '../src/format'
import { table } from '../src/markdown'
import { deterministicUuid, inferRegionCode, slugify } from '../src'
const HERE = dirname(fileURLToPath(import.meta.url))
const OUT = resolve(HERE, '../../../crates/core/tests/oracles/r5')
const MAKE = process.env.MAKE_R5_ORACLES === '1'
/** Numbers of `digits` characters each, deterministic. */
function numbers(count: number, digits: number): number[] {
return Array.from({ length: count }, (_, i) =>
Number(String((i * 7919 + 13) % 10 ** digits).padStart(1, '0')),
)
}
function strings(count: number, width: number): string[] {
return Array.from({ length: count }, (_, i) =>
`${String.fromCharCode(97 + (i % 26))}`.repeat(width),
)
}
/** One value per layout rule, each nested so the boundary moves. */
function jsonCases(): unknown[] {
const cases: unknown[] = [
{},
[],
{ a: {} },
{ a: [] },
{ a: [{}] },
{ a: [[]] },
{ a: [null, true, false] },
{ a: [1e21, -0, 1e-7, -5, 0.5, 123456789012345680000] },
{ a: [-1, -2, -3] },
{ a: [1, 'b', null] },
{ a: [[1, 2], [3]] },
{ a: [[1], [2]] },
{
a: [
[1, 2],
[3, 4],
],
},
{ a: [[1, 2], { b: 1 }] },
{ a: [{ b: 1 }, { c: 2 }] },
{
a: [
{ b: 1, c: 2 },
{ d: 3, e: 4 },
],
},
{
a: [
[
[1, 2],
[3, 4],
],
[[5, 6]],
],
},
{
a: [
['x', 'y'],
['z', 'w'],
],
},
{ a: [['x'], ['y', 'z']] },
{ 'clé é': ['é', 'à', '«»'], 漢字: ['漢字漢字', '😀'] },
{ a: ['é', 'full', '​'] },
{ a: 'x'.repeat(200), b: ['y'.repeat(100)] },
{ 'a"b': ['\\', '"', '\n', '\u0001'] },
]
for (const depth of [0, 1, 3, 6]) {
for (const key of ['k', 'key_of_twenty_chars_', 'k'.repeat(40)]) {
for (const count of [1, 2, 3, 8, 12, 13, 14, 15, 16, 30]) {
for (const digits of [1, 3, 4, 6]) {
let value: unknown = { [key]: numbers(count, digits) }
for (let d = 0; d < depth; d++) value = { n: value }
cases.push(value)
}
for (const width of [1, 5, 12]) {
let value: unknown = { [key]: strings(count, width), z: 1 }
for (let d = 0; d < depth; d++) value = { n: [value] }
cases.push(value)
}
}
}
}
for (let total = 70; total <= 90; total++) {
const pad = 'p'.repeat(total - 20)
cases.push({ [pad]: [1, 2] }, { [pad]: [1, 2], last: true })
cases.push({ [pad]: ['ab', 'cd'] }, [{ [pad]: [1, 2, 3] }])
cases.push({ x: [[Number('1'.repeat(Math.max(1, total - 70))), 2]] })
}
return cases
}
type Row = Array<string | number | null>
function tableCases(): Array<{ head: string[]; rows: Row[] }> {
return [
{ head: ['A', 'B'], rows: [['1', '2']] },
{
head: ['Mesure', 'Valeur'],
rows: [
['Nœuds', 792],
['x', null],
],
},
{ head: ['a'], rows: [['']] },
{
head: ['Code', 'Objet'],
rows: [
['`a|b`', 'x | y'],
['ligne\nsuite', ''],
],
},
{
head: ['é', 'é'],
rows: [
['àéîõü', 'ç'],
['–—', '«»'],
],
},
{
head: ['漢字', 'emoji'],
rows: [
['漢字漢字', '😀'],
['full', '👍🏽'],
],
},
{
head: ['ctl', 'zw'],
rows: [
['a\u0001b', 'a​b'],
['️', 'x'],
],
},
{
head: ['Long', 'Court'],
rows: [
['x'.repeat(150), 'y'],
['`code`', '**gras**'],
],
},
{ head: ['Total'], rows: [['**Total**'], ['']] },
{
head: ['n', 'm', 'o'],
rows: [
[1, 22, 333],
[4444, 5, 66],
],
},
]
}
/** IEEE 754 bits in hex: `String(-0)` is `"0"`, the bits keep the sign. */
function bitsOf(value: number): string {
const view = new DataView(new ArrayBuffer(8))
view.setFloat64(0, value)
return view.getBigUint64(0).toString(16).padStart(16, '0')
}
const SPACES = [' ', '\t', '\n', ' ', '', '
', ' ', '​']
function semantics() {
const slugInputs = [
'Cheval',
'Épaule',
'İstanbul',
'KK',
'ΣΑΣ ΟΔΟΣ',
'Straße',
'fin',
'full',
'Džemal',
'Ⅻ',
'x̧́y',
'①②',
'a—b–c',
'__a__',
'œuvre Æther',
'Ünïcödé',
'😀 smile',
'한국어',
'ğ ş ı',
'1/2 et 3/4',
'a'.repeat(63) + 'é' + 'b',
'-'.repeat(70) + 'z',
]
const uuidNames = [
'faunosteo:sheet:canine:v1',
'faunosteo:sheet:feline:v12',
'faunosteo:asset:' + 'f'.repeat(64),
'x'.repeat(1000),
'é',
'😀',
'\u0000',
]
const regionLabels: Array<[string | null, string | null]> = [
['Cervicales', null],
[null, 'Thoracic'],
['DORSALES', 'Lumbar'],
['Région sacrée', 'Sacral'],
['Coccygiennes', null],
['Lombaires', 'x'],
['Épaule', 'Shoulder'],
[null, null],
['', 'caudal'],
['Thoracolombaire', ''],
['CERVICALES', 'CERVICAL'],
['Sacrum', 'Sacrum'],
]
const numberTexts = [
'',
' ',
'12',
' 12 ',
'0x1A',
'0X1a',
'0b11',
'0o17',
'1e3',
'1E-3',
'.5',
'5.',
'+5',
'-5',
'Infinity',
'-Infinity',
'+Infinity',
'infinity',
'NaN',
'abc',
'1,5',
' 12 ',
'7',
'12px',
'1_000',
'00012',
'-0',
'0x',
'1e',
'1e+',
' \n\t3 ',
'
3',
'1.7976931348623157e309',
'5e-325',
'0.1e1',
'-.5',
'--5',
'+-5',
'0x-1',
]
const pointTexts = [
' 1,2 3,4 ',
'1,,2',
',1,2',
'1 2 3',
'',
'1e3,2',
' 1 2',
'1.5,2.25 ',
'1,2,3,4,5,6',
'a,b',
' ',
'1\n2\t3 4',
]
const roundValues = [
0.5, 1.5, 2.5, -0.5, -1.5, -2.5, 0.49999999999999994, -0.49999999999999994,
4503599627370495.5, -4503599627370495.5, 1e21, -0.4, 3.7, -3.7, 0, -0,
2.4999999999999996, 1.0000000000000002,
]
const keyTexts = [
'{"b":1,"2":2,"a":3,"1":4,"01":5,"4294967295":6,"4294967294":7,"-1":8,"1.5":9}',
'{"z":1,"y":2,"10":3,"9":4,"0":5}',
'{"a":1,"a":2,"b":3}',
]
return {
slugify: slugInputs.map((label) => ({ label, slug: slugify(label) })),
deterministicUuid: uuidNames.map((name) => ({
name,
uuid: deterministicUuid(name),
})),
inferRegionCode: regionLabels.map(([fr, en]) => ({
fr,
en,
match: inferRegionCode(fr, en),
})),
number: numberTexts.map((text) => {
const value = Number(text)
return { text, string: String(value), negativeZero: Object.is(value, -0) }
}),
points: pointTexts.map((text) => ({
text,
numbers: text
.trim()
.split(/[\s,]+/)
.map((n) => String(Number(n))),
})),
mathRound: roundValues.map((value) => {
const r = Math.round(value)
return {
bits: bitsOf(value),
value: String(value),
round: String(r),
negativeZero: Object.is(r, -0),
}
}),
objectEntriesOrder: keyTexts.map((text) => ({
text,
keys: Object.keys(JSON.parse(text) as object),
})),
trim: SPACES.map((space) => ({
text: `${space}x${space}`,
trimmed: `${space}x${space}`.trim(),
isSpace: /\s/.test(space),
})),
}
}
async function prettierJson() {
const cases = jsonCases()
const out = []
for (const value of cases) {
out.push({ input: JSON.stringify(value), output: await formatJson(value) })
}
return {
tool: 'prettier formatJson (packages/anatomy/src/format.ts)',
cases: out,
}
}
async function markdownTables() {
const out = []
for (const { head, rows } of tableCases()) {
const raw = `# T\n\n${table(head, rows)}\n`
out.push({ raw, output: await formatMarkdown(raw) })
}
return {
tool: 'prettier formatMarkdown (packages/anatomy/src/format.ts)',
cases: out,
}
}
function check(name: string, value: unknown): void {
const text = `${JSON.stringify(value)}\n`
if (MAKE) {
mkdirSync(OUT, { recursive: true })
writeFileSync(resolve(OUT, name), text)
}
expect(text).toBe(readFileSync(resolve(OUT, name), 'utf8'))
}
describe('R5.2 format and semantics oracles', () => {
it('prettier-json.json', async () => {
check('prettier-json.json', await prettierJson())
})
it('markdown-tables.json', async () => {
check('markdown-tables.json', await markdownTables())
})
it('js-semantics.json', () => {
check('js-semantics.json', semantics())
})
})
@@ -1,286 +0,0 @@
/**
* R5.2 freeze (owner brief 2026-10-22 §9): the TypeScript legacy importer on synthetic
* inputs, so the Rust port is held to the generic contract and not only to the equine
* files. Each case is a full importer input (two SVG texts, the catalog text, the
* vertebrae text); the oracle records the four rendered files and the result's parts, or
* the refusal. `MAKE_R5_ORACLES=1` writes crates/core/tests/oracles/r5/legacy-synthetic.json.
*/
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { importEquineLegacy, renderArtifacts } from '../src'
const HERE = dirname(fileURLToPath(import.meta.url))
const OUT = resolve(HERE, '../../../crates/core/tests/oracles/r5')
const MAKE = process.env.MAKE_R5_ORACLES === '1'
interface Case {
name: string
main: string
head: string
catalog: string
vertebrae: string
}
const SVG_HEAD = '<?xml version="1.0" encoding="UTF-8"?>\n'
function svg(viewBox: string | null, body: string): string {
const box = viewBox === null ? '' : ` viewBox="${viewBox}"`
return `${SVG_HEAD}<svg xmlns="http://www.w3.org/2000/svg"${box}>\n${body}\n</svg>\n`
}
function anno(
tag: string,
attrs: Record<string, string>,
geometry: string,
): string {
const data = Object.entries(attrs)
.map(([k, v]) => ` data-anno-${k}="${v}"`)
.join('')
return ` <${tag}${geometry}${data}/>`
}
const VERTEBRAE = `// varies 18 - 22 caudal
export const FORMULA = { C: 7, T: 18, L: 6, S: 5, Cd: 18, Cd: 20 }
`
function node(id: string, extra: Record<string, unknown> = {}) {
return { id, name_fr: `${id} fr`, name_en: `${id} en`, ...extra }
}
function zone(id: string, fr: string, en: string, categories: unknown[]) {
return { id, name_fr: fr, name_en: en, categories }
}
const CATALOG = {
schema_version: 2.5,
scope_disclaimer: 'Périmètre « test »',
zones: {
hip: zone('hip', 'Hanche', 'Hip', [
node('hip-dysfunctions', {
children: [
node('Épaule Gauche', { description_fr: 'seulement FR' }),
node('ok', { requires_vet_referral: true, children: [] }),
node('deep', {
children: [node('leaf', { description_en: 'EN only' })],
}),
],
}),
node('anamnesis', { children: [node('age'), node('use')] }),
node('spine-observations', { children: [node('ok')] }),
]),
'10': zone('10', 'Dix', 'Ten', [
node('anamnesis', { children: [node('age')] }),
]),
'2': zone('2', 'Deux', 'Two', [
node('weird'),
node('anamnesis', { children: [node('age'), node('use')] }),
]),
spine: zone('spine', 'Colonne', 'Spine', [
node('spine-dysfunctions', { children: [node('ok'), node('x y')] }),
]),
},
}
const MAIN_BODY = [
anno(
'circle',
{
id: 'a1',
'name-fr': 'Hanche',
'name-en': 'Hip',
category: 'articulations',
'category-name': 'articulations',
lateral: 'bilateral',
},
' cx="10.5" cy=" 20 " r=" 2 "',
),
anno(
'circle',
{ id: 'a1', 'name-fr': 'Hanche', 'name-en': 'Hip' },
' cx="1" cy="1" r="1"',
),
anno(
'polygon',
{
id: 'p1',
'name-fr': 'Colonne',
'name-en': 'Spine',
category: 'charni-res-vert-brales',
special: 'vertebral-precision',
lateral: 'left',
},
' points=" 1,2 3,4 5,6 7 "',
),
anno(
'polygon',
{
id: 'p2',
'name-fr': 'Région sacrée',
category: 'zone-colonne',
'category-name': 'Colonne vertébrale',
special: 'vertebral-precision',
},
' points="0x10,1e1 2,3 4,5"',
),
anno(
'rect',
{ id: 'r1', 'name-en': 'Rect only', category: 'os', special: 'other' },
' x="1" y="2"',
),
anno(
'circle',
{ id: 't1', 'opens-detail': 'head', category: 'cadrans-du-cr-ne' },
' cx="5" cy="5" r="2"',
),
anno(
'circle',
{
id: 'x1',
'name-fr': 'Dix',
'name-en': 'Ten',
category: 'os',
lateral: 'unpaired',
},
' cx="840.1692504882812" cy="-0" r="3"',
),
].join('\n')
const HEAD_BODY = [
anno(
'circle',
{ id: 'h1', 'name-fr': 'Deux', category: 'os' },
' cx="3" cy="4" r="5"',
),
anno(
'circle',
{ id: 'h2', 'name-fr': 'Deux', 'name-en': 'Two', category: 'os' },
' cx="3" cy="4" r="5"',
),
anno(
'circle',
{
id: 'a1',
'name-fr': 'Thoracique',
'name-en': 'Thoracic',
category: 'os',
special: 'vertebral-precision',
},
' cx="1" cy="1" r="1"',
),
].join('\n')
function cases(): Case[] {
const base: Case = {
name: 'generic',
main: svg('0 0 100 50', MAIN_BODY),
head: svg(null, HEAD_BODY),
catalog: JSON.stringify(CATALOG, null, 2),
vertebrae: VERTEBRAE,
}
const minimal: Case = {
name: 'minimal',
main:
'' +
svg(
'0 0 1 1',
anno(
'circle',
{ id: 'm', 'name-fr': 'Hanche', 'name-en': 'Hip', category: 'os' },
' cx="1" cy="1" r="1"',
),
),
head: svg('0 0 1 1', ''),
catalog: JSON.stringify({
schema_version: '2.0',
zones: {
hip: zone('hip', 'Hanche', 'Hip', [
node('hip-dysfunctions', { children: [node('a')] }),
]),
},
}),
vertebrae: 'const V = {C:7,T:18,L:6,S:5,Cd:21}',
}
const refusals: Case[] = [
{
...base,
name: 'schema',
main: base.main.replace('r="3"', 'r="Infinity"'),
},
{ ...base, name: 'no-zones', catalog: '{"schema_version":"2.0"}' },
{ ...base, name: 'catalog-bom', catalog: '' + base.catalog },
{
...base,
name: 'no-cd',
vertebrae: 'const V = { C: 7, T: 18, L: 6, S: 5 }',
},
{ ...base, name: 'no-formula', vertebrae: 'nothing here' },
{
...base,
name: 'inline-sources',
catalog: JSON.stringify({
zones: {
hip: zone('hip', 'Hanche', 'Hip', [node('c', { sources: [{}] })]),
},
}),
},
{
...base,
name: 'key-not-id',
catalog: JSON.stringify({
zones: { hip: zone('hop', 'Hanche', 'Hip', []) },
}),
},
{
...base,
name: 'truthy-referral',
catalog: JSON.stringify({
zones: {
hip: zone('hip', 'Hanche', 'Hip', [
node('c', {
children: [node('d', { requires_vet_referral: 'yes' })],
}),
]),
},
}),
},
]
return [base, minimal, ...refusals]
}
async function run(c: Case) {
const input = {
mainSvg: { fileName: 'Main.svg', bytes: new TextEncoder().encode(c.main) },
headSvg: { fileName: 'Head.svg', bytes: new TextEncoder().encode(c.head) },
catalogJson: c.catalog,
vertebraeSource: c.vertebrae,
}
try {
const result = importEquineLegacy(input)
const parts: Record<string, unknown> = { ...result }
delete parts.document
delete parts.legacyIdMap
return { ...c, ok: true, files: await renderArtifacts(result), parts }
} catch (error) {
return {
...c,
ok: false,
error: error instanceof Error ? error.message : String(error),
}
}
}
describe('R5.2 synthetic importer oracle', () => {
it('legacy-synthetic.json', async () => {
const rows = []
for (const c of cases()) rows.push(await run(c))
const text = `${JSON.stringify({ cases: rows })}\n`
const file = resolve(OUT, 'legacy-synthetic.json')
if (MAKE) {
mkdirSync(OUT, { recursive: true })
writeFileSync(file, text)
}
expect(text).toBe(readFileSync(file, 'utf8'))
})
})
@@ -1,306 +0,0 @@
/**
* R5.4 freeze (final gates, 2026-10-23): what Prettier's Markdown printer does to authored text
* in the two draft reports. The port reproduces only the table alignment and refuses the text
* Prettier would rewrite; this sweep, written by the TypeScript, holds it to that: every probe
* (a special character in six positions, whitespace patterns, Markdown constructs) is placed
* in a change title, rationale and question, a cited reference and a changed label, and the
* sha256 of the raw and formatted CHANGELOG and REVIEW-REPORT are frozen (400 of the probes
* come from a seeded generator, so unknown classes surface on their own; eight pairs open a
* construct in one field and close it in the question). `MAKE_R5_ORACLES=1` writes
* crates/core/tests/oracles/r5/markdown-sweep.json.
*/
import { createHash } from 'node:crypto'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import {
applyChangeset,
buildReportMigrationMap,
ChangesetSchema,
documentStats,
renderChangelog,
renderReviewReport,
} from '../src'
import { changeSummary } from '../src/curation/schema'
import { formatMarkdown } from '../src/format'
import { MINI_REFERENCES, miniSheet } from './fixtures/mini-sheet'
const HERE = dirname(fileURLToPath(import.meta.url))
function sha256(text: string): string {
return createHash('sha256').update(text, 'utf8').digest('hex')
}
const OUT = resolve(HERE, '../../../crates/core/tests/oracles/r5')
const MAKE = process.env.MAKE_R5_ORACLES === '1'
const LEGACY_ID_MAP = {
views: { head: 'head' },
annotations: { 'legacy-hip': 'hip', 'legacy-neck': 'neck' },
categories: {},
finding_nodes: {},
assets: {},
}
const CHARACTERS = [...'*_~\\`<>&[]!#$|+=^{}"\'%@:;?/()-.,’‘“”×≤≥±→–—…«»°≠']
function positions(c: string): string[] {
return [c, `${c}x`, `x${c}`, `a ${c} b`, `a${c}b`, `${c}${c}`]
}
const PATTERNS = [
'a b',
'a\tb',
' a',
'a ',
'a\nb',
'a\rb',
'a\n\nb',
'*important*',
'**gras**',
'a **b c** d',
'a**b**c',
'__init__ et _x',
'to_confirm',
'`code`',
'``double``',
'a\\|b',
'a|b',
'<b>gras</b>',
'[lien](https://example.org/x)',
'[a](<b>)',
'[a]( b )',
'[a](b "t")',
'[a](b (t))',
'[a](b&amp;c)',
'[a](b\\)c)',
'[a](https://x.org/a(b)c)',
']( )',
'![img](x.png)',
'[a][b]',
'<http://a&amp;b>',
'<https://example.org/x>',
'<a@b.co>',
'[[ a ]]',
'[[a]]',
'&#42;',
'&ast;',
'&#x2A;',
'&#95;',
'&lowbar;',
'&eacute;',
'doi 10.1/x<0697:toih>2.0',
'中_中',
'ア_ア',
'한_한',
'é_é',
'[a]( https://x.org )',
'**a****b**',
'\\**a**',
'x_**a**',
'**a**_x',
'** **',
'**Total**',
'(**a**)',
'a **b** c',
'Voir_https://example.org/x',
'Voir_www.example.org',
'https://x.org/**a **',
'https://x.org/a_b',
'Lien https://x.org/a_b fin',
'a\u00a0b',
'a\u2003b',
'a\u3000b',
'中文',
'مرحبا',
'e\u0301',
'Mesure a_b `c_`',
'Champ snake_case, voir x_y fin',
'to_do',
'voir [a `](b)` c',
'voir https://x.org/`<a`',
'a &#42 b',
'&#x2A',
'&#95',
'a&#95b',
'&lt x &',
'&#65 x &',
'![a\\"b]',
'![a|b]',
'![&amp]',
'![x]',
'[[ a [[b]]',
'[[a]] [[ b [[c]]',
'a & b',
'A&B',
'x &',
'https://x.org/?a=1&pid=2',
'https://x.org/?a=1&lt=2',
'https://x.org/?a&not=2',
'https://x.org/?a=1&amp=2',
'https://x.org/?a=1&copyx=2',
'&amp;',
'# titre',
'1. item',
'- item',
'> citation',
'Carmalt 2013 (≠ « palpation »), 3 %, 40 °C',
'a = b; c ? d : e',
'{"fr":"x"}',
'é ü ß ø Ω 中',
]
/** A seeded generator (a 32-bit LCG): the random probes are the same on every run. */
function randomProbes(count: number): string[] {
const alphabet = [
...'ab_*\\`[]()<>&#!~ :/.|"é中=;',
'&#',
'&amp',
'&lt',
'![',
'[[',
']]',
'https://',
'www.',
'**',
'\n',
'\u00a0',
]
let state = 20261023
const next = () => {
state = (Math.imul(state, 1664525) + 1013904223) >>> 0
return state
}
const out: string[] = []
for (let i = 0; i < count; i += 1) {
const length = 2 + (next() % 10)
let text = ''
for (let j = 0; j < length; j += 1)
text += alphabet[next() % alphabet.length]
out.push(text)
}
return out
}
function probes(): string[] {
return [...CHARACTERS.flatMap(positions), ...PATTERNS, ...randomProbes(400)]
}
/** Openers in the title, the rationale and every other field, closers in the question. */
const SPLIT = [
['[[', ']]'],
['[[ a', 'b ]]'],
['[[a', 'b]]'],
['{%', '%}'],
['[x', '](y)'],
['*a', 'b*'],
['_a', 'b_'],
['<b', '>'],
]
function changesFile(probe: string, referenceId: string, closer = probe) {
return {
changes: [
{
id: 'CHG-001',
level: 'C',
kind: 'correction',
title: { fr: `Titre ${probe}`, en: 'Title' },
rationale: `Raison ${probe} fin.`,
reference_ids: [],
question: `Question ${closer} ?`,
ops: [
{
op: 'add',
target: 'document',
field: 'references',
value: {
id: referenceId,
type: 'web',
citation: `Citation ${probe}`,
url: null,
doi: null,
},
},
{
op: 'cite',
target: 'finding:hip/hip-dysfunctions/mobility',
reference_ids: [referenceId],
},
{
op: 'set',
target: 'finding:hip/hip-dysfunctions/mobility',
field: 'name.en',
value: `Label ${probe}`,
},
{
op: 'set',
target: 'finding:hip/hip-dysfunctions/mobility/flexion',
field: 'name.fr',
value: probe,
},
],
},
],
}
}
async function run(probe: string, referenceId = 'probe_ref', closer = probe) {
const file = changesFile(probe, referenceId, closer)
const changeset = ChangesetSchema.parse(file)
const baseline = miniSheet()
const result = applyChangeset(baseline, MINI_REFERENCES, changeset)
const before = documentStats(baseline)
const after = documentStats(result.document)
const migration = buildReportMigrationMap({
baseline: miniSheet() as never,
final: result.document as never,
legacyIdMap: LEGACY_ID_MAP,
records: result.records,
sheet: { sheetId: 's', versionId: null, documentSha256: '0'.repeat(64) },
mainViewId: 'main',
})
const changelogRaw = renderChangelog(result, before, after, migration.stats)
const reviewRaw = renderReviewReport({
changes: changeset.changes.map(changeSummary),
records: result.records,
document: result.document,
statsBefore: before,
legacyAnomalies: [],
})
return {
probe: closer === probe ? probe : `${probe}|${closer}`,
reference_id: referenceId,
changes_file: file,
changelog_raw_sha256: sha256(changelogRaw),
changelog_sha256: sha256(await formatMarkdown(changelogRaw)),
review_raw_sha256: sha256(reviewRaw),
review_sha256: sha256(await formatMarkdown(reviewRaw)),
}
}
describe('R5.4 Markdown sweep oracle', () => {
it('markdown-sweep.json', async () => {
const rows = []
for (const probe of probes()) rows.push(await run(probe))
// A cited id ending with `_` puts a closing underscore in a generated code span.
for (const probe of ['to_do', 'a_b c', 'x'])
rows.push(await run(probe, 'probe_ref_'))
// A construct opened in one field and closed in another of the same line.
for (const [opener, closer] of SPLIT)
rows.push(await run(opener, 'probe_ref', closer))
const oracle = {
baseline: miniSheet(),
references: MINI_REFERENCES,
legacy_id_map: LEGACY_ID_MAP,
cases: rows,
}
const text = `${JSON.stringify(oracle)}\n`
const file = resolve(OUT, 'markdown-sweep.json')
if (MAKE) {
mkdirSync(OUT, { recursive: true })
writeFileSync(file, text)
}
expect(text).toBe(readFileSync(file, 'utf8'))
}, 120_000)
})
@@ -1,373 +0,0 @@
/**
* R5.1 freeze (plan 2026-10-22 §B.2): what the TypeScript pipeline computes
* and emits today, recorded for the Rust pipeline to reproduce. Three
* oracles under crates/core/tests/oracles/r5/:
*
* - pipeline.json: the intermediate values the generated files do not show
* (import stats, anomalies, rows, region inferences, change records,
* stats before and after, integrity warnings, migration stats) and the
* ledger of every generated file (bytes, sha256, the sha256 of the
* markdown before Prettier).
* - ids.json: the deterministic uuid and slug functions over every name the
* pipeline derives an id from, plus edge cases.
* - fingerprints.json: the sheet fingerprint of every JSON artifact under
* each D-R5 candidate rule, the ES6 printing of every non-integer number
* of the two documents, and the RFC 8785 vectors.
*
* `MAKE_R5_ORACLES=1` writes the files; otherwise the pipeline still matches
* its own freeze. The committed generated folders stay the byte oracle
* (seed.golden.test.ts); nothing here rewrites them.
*/
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { AnatomicalSheetDocumentSchema } from '@faunosteo/domain'
import {
buildReportMigrationMap,
deterministicUuid,
EQUINE_DRAFT_DIR,
EQUINE_LEGACY_IMPORT_DIR,
MAIN_VIEW_ID,
renderArtifacts,
renderChangelog,
renderDraftArtifacts,
renderImportReport,
renderReviewReport,
sha256Hex,
slugify,
type DraftResult,
type ImportResult,
} from '../src'
import { runDraft } from './helpers'
const HERE = dirname(fileURLToPath(import.meta.url))
const REPO = resolve(HERE, '../../..')
const OUT = resolve(REPO, 'crates/core/tests/oracles/r5')
const MAKE = process.env.MAKE_R5_ORACLES === '1'
type Json = Record<string, unknown>
/** The uuid and slug inputs the pipeline derives ids from, plus edges. */
const UUID_NAMES = [
'faunosteo:sheet:equine:v1',
'faunosteo:sheet:equine:v2',
'faunosteo:asset:0ea5202fa3b95bac167b87c12ee969ab0272e085b60c2d34dbca6202c5f08541',
'',
'faunosteo:sheet:équin:v1',
'faunosteo:asset:\u{1f40e}',
]
const SLUG_EDGES = [
'',
' ',
'Cheval',
'Épaule gauche',
'Vertèbres thoraciques T1–T18',
'Œil / orbite',
'Straße',
'Ørsted',
"Rein d'un cheval",
'ÀÉÎÕÜ ç ñ',
'--déjà--',
'a'.repeat(70),
'é'.repeat(70),
'DŽ Dž dž',
'İstanbul',
'12 côtes',
'Ça (combining cedilla)',
]
/** RFC 8785: UTF-16 member order, no whitespace, JSON.stringify scalars. */
function canonicalize(value: unknown): string {
if (value === null || typeof value !== 'object') return JSON.stringify(value)
if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`
const object = value as Json
const keys = Object.keys(object).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
const members = keys.map(
(k) => `${JSON.stringify(k)}:${canonicalize(object[k])}`,
)
return `{${members.join(',')}}`
}
/** RFC 8785 §3.2.3 examples: numbers and escapes, then member ordering. */
const RFC_VECTORS: Array<[string, string]> = [
[
'{"numbers": [333333333.33333329, 1E30, 4.50, 2e-3, 0.000000000000000000000000001], ' +
'"string": "\\u20ac$\\u000F\\u000aA\'\\u0042\\u0022\\u005c\\\\\\"\\/", "literals": [null, true, false]}',
'{"literals":[null,true,false],"numbers":[333333333.3333333,1e+30,4.5,0.002,1e-27],' +
'"string":"€$\\u000f\\nA\'B\\"\\\\\\\\\\"/"}',
],
[
'{"\\u20ac": "Euro Sign", "\\r": "Carriage Return", "\\ufb33": "Hebrew Letter Dalet With Dagesh", ' +
'"1": "One", "\\ud83d\\ude00": "Emoji: Grinning Face", "\\u0080": "Control", ' +
'"\\u00f6": "Latin Small Letter O With Diaeresis"}',
'{"\\r":"Carriage Return","1":"One","\u0080":"Control","ö":"Latin Small Letter O With Diaeresis",' +
'"€":"Euro Sign","😀":"Emoji: Grinning Face","דּ":"Hebrew Letter Dalet With Dagesh"}',
],
]
/** Every number of a JSON value that is not an integer, with its JS text. */
function nonIntegers(value: unknown, path: string, out: Json[]): void {
if (typeof value === 'number') {
if (!Number.isInteger(value)) out.push({ path, text: String(value) })
} else if (Array.isArray(value)) {
value.forEach((item, i) => nonIntegers(item, `${path}[${i}]`, out))
} else if (value && typeof value === 'object') {
for (const [k, v] of Object.entries(value as Json))
nonIntegers(v, `${path}.${k}`, out)
}
}
/** Every `name.fr` / `name.en` of a document, unique, in document order. */
function names(value: unknown, out: Set<string>): void {
if (Array.isArray(value)) {
for (const item of value) names(item, out)
} else if (value && typeof value === 'object') {
const object = value as Json
const name = object.name as Json | undefined
if (name && typeof name.fr === 'string') out.add(name.fr)
if (name && typeof name.en === 'string') out.add(name.en)
for (const v of Object.values(object)) names(v, out)
}
}
/**
* The input form is what the file holds (defaults omitted); the validated
* form is what every reader holds after the schema (defaults filled, Zod
* output order). A document.json row carries both.
*/
function fingerprintRow(file: string, text: string): Json {
const value = JSON.parse(text) as unknown
const pretty = JSON.stringify(value, null, 2)
const row: Json = {
file,
bytes: Buffer.byteLength(text),
today_file_bytes: sha256Hex(text),
a_js_pretty_newline: sha256Hex(`${pretty}\n`),
a_js_pretty: sha256Hex(pretty),
a_js_compact: sha256Hex(JSON.stringify(value)),
b_rfc8785: sha256Hex(canonicalize(value)),
prettier_equals_js_pretty: text === `${pretty}\n`,
}
if (file.endsWith('/document.json')) {
const validated = AnatomicalSheetDocumentSchema.parse(value)
row.a_js_pretty_validated = sha256Hex(JSON.stringify(validated, null, 2))
row.b_rfc8785_validated = sha256Hex(canonicalize(validated))
row.validated_equals_input = canonicalize(validated) === canonicalize(value)
}
return row
}
interface Run {
result: ImportResult
draft: DraftResult
legacyFiles: Record<string, string>
draftFiles: Record<string, string>
}
async function run(): Promise<Run> {
const { result, draft } = await runDraft()
return {
result,
draft,
legacyFiles: await renderArtifacts(result),
draftFiles: await renderDraftArtifacts(draft, result.anomalies),
}
}
function ledger(
folder: string,
files: Record<string, string>,
raw: Record<string, string>,
): Json[] {
return Object.entries(files).map(([file, text]) => ({
folder,
file,
bytes: Buffer.byteLength(text),
sha256: sha256Hex(text),
...(file in raw
? {
before_prettier_sha256: sha256Hex(raw[file]!),
prettier_changed: raw[file] !== text,
}
: {}),
}))
}
function pipelineOracle(r: Run): Json {
const { result, draft } = r
const documentJson = r.draftFiles['document.json']!
const migration = buildReportMigrationMap({
baseline: draft.baseline as Json,
final: draft.document as Json,
legacyIdMap: draft.legacyIdMap,
records: draft.records,
sheet: {
sheetId: draft.sheetId,
versionId: null,
documentSha256: sha256Hex(documentJson),
},
mainViewId: MAIN_VIEW_ID,
})
const rawLegacy = { 'IMPORT-REPORT.md': renderImportReport(result) }
const rawDraft = {
'CHANGELOG.md': renderChangelog(
draft,
draft.statsBefore,
draft.statsAfter,
migration.stats,
),
'REVIEW-REPORT.md': renderReviewReport({
...draft,
legacyAnomalies: result.anomalies,
}),
}
return {
frozen_from: 'packages/anatomy (TypeScript pipeline), R5.1',
legacy: {
sheetId: result.sheetId,
viewBoxes: result.viewBoxes,
stats: result.stats,
sourceDigests: result.sourceDigests,
assets: result.assets,
anomalies: result.anomalies,
issues: result.issues,
regionInferences: result.regionInferences,
zoneStats: result.zoneStats,
annotationRows: result.annotationRows,
},
draft: {
sheetId: draft.sheetId,
changes: draft.changes,
assets: draft.assets,
statsBefore: draft.statsBefore,
statsAfter: draft.statsAfter,
issues: draft.issues,
migrationStats: migration.stats,
records: draft.records,
},
artifacts: [
...ledger(EQUINE_LEGACY_IMPORT_DIR, r.legacyFiles, rawLegacy),
...ledger(EQUINE_DRAFT_DIR, r.draftFiles, rawDraft),
{
folder: EQUINE_DRAFT_DIR,
file: `assets/${draft.assets[0]!.file}`,
bytes: Buffer.byteLength(draft.cleanedSvg),
sha256: sha256Hex(draft.cleanedSvg),
},
],
}
}
function idsOracle(r: Run): Json {
const labels = new Set<string>()
names(r.result.document, labels)
names(r.draft.document, labels)
const slugInputs = [...SLUG_EDGES, ...labels]
return {
uuid: UUID_NAMES.map((name) => ({ name, uuid: deterministicUuid(name) })),
slug: slugInputs.map((label) => ({ label, slug: slugify(label) })),
}
}
function fingerprintsOracle(r: Run): Json {
const jsonFiles = [
...Object.entries(r.legacyFiles).map(
([f, t]) => [`${EQUINE_LEGACY_IMPORT_DIR}/${f}`, t] as const,
),
...Object.entries(r.draftFiles).map(
([f, t]) => [`${EQUINE_DRAFT_DIR}/${f}`, t] as const,
),
].filter(([file]) => file.endsWith('.json'))
const numbers: Json[] = []
nonIntegers(
JSON.parse(r.legacyFiles['document.json']!),
'legacy-import/document.json',
numbers,
)
nonIntegers(
JSON.parse(r.draftFiles['document.json']!),
'draft/document.json',
numbers,
)
return {
rules: {
today_file_bytes:
'sha256 of the Prettier-formatted JSON text the pipeline writes (pipeline.ts sheetRef)',
a_js_pretty_newline: 'sha256 of JSON.stringify(v, null, 2) + "\\n"',
a_js_pretty: 'sha256 of JSON.stringify(v, null, 2)',
a_js_compact: 'sha256 of JSON.stringify(v)',
b_rfc8785: 'sha256 of the RFC 8785 canonical text',
a_js_pretty_validated:
'document.json only: JSON.stringify(schema.parse(v), null, 2), the validated form (defaults filled)',
b_rfc8785_validated: 'document.json only: RFC 8785 of the validated form',
},
artifacts: jsonFiles.map(([file, text]) => fingerprintRow(file, text)),
numbers,
rfc8785_vectors: RFC_VECTORS.map(([input, canonical]) => ({
input,
canonical,
})),
}
}
function write(name: string, value: Json): string {
const text = `${JSON.stringify(value, null, 2)}\n`
if (MAKE) {
mkdirSync(OUT, { recursive: true })
writeFileSync(resolve(OUT, name), text)
}
return text
}
function frozen(name: string): string {
return readFileSync(resolve(OUT, name), 'utf8')
}
describe('R5.1 oracles (crates/core/tests/oracles/r5)', () => {
it('the RFC 8785 canonicaliser passes the RFC vectors', () => {
for (const [input, expected] of RFC_VECTORS) {
expect(canonicalize(JSON.parse(input))).toBe(expected)
}
})
it('pipeline.json: intermediate values and the artifact ledger', async () => {
const text = write('pipeline.json', pipelineOracle(await run()))
expect(text).toBe(frozen('pipeline.json'))
})
it('ids.json: deterministic uuids and slugs', async () => {
const text = write('ids.json', idsOracle(await run()))
expect(text).toBe(frozen('ids.json'))
})
it('fingerprints.json: the D-R5 matrix and the number printing', async () => {
const text = write('fingerprints.json', fingerprintsOracle(await run()))
expect(text).toBe(frozen('fingerprints.json'))
})
it('the ledger digests are the committed files (the golden folders)', async () => {
const oracle = JSON.parse(frozen('pipeline.json')) as {
artifacts: Array<{ folder: string; file: string; sha256: string }>
}
// Since R5.6 the two fingerprinted draft files are Rust's (`v1`); the ledger recorded the
// TypeScript's, frozen under `crates/core/tests/fixtures/r5-6/pre-switch` (the Rust suite
// `curation_draft` proves the committed ones are those under the declared rule).
const preSwitch = new Set(['sheet-ref.json', 'report-migration-map.json'])
for (const row of oracle.artifacts) {
const folder =
row.folder.endsWith('/draft') && preSwitch.has(row.file)
? 'crates/core/tests/fixtures/r5-6/pre-switch'
: row.folder
const committed = readFileSync(resolve(REPO, folder, row.file))
expect(sha256Hex(committed), `${row.folder}/${row.file}`).toBe(row.sha256)
}
})
it('two runs emit the same bytes for every artifact', async () => {
const [first, second] = [await run(), await run()]
expect(first.legacyFiles).toEqual(second.legacyFiles)
expect(first.draftFiles).toEqual(second.draftFiles)
expect(first.draft.cleanedSvg).toBe(second.draft.cleanedSvg)
})
})
@@ -1,308 +0,0 @@
/**
* R5.4 freeze (owner brief 2026-10-23 §4, "tester les cas nécessaires"): the TypeScript review
* files on synthetic changesets over the mini sheet and a small drawing, so the Rust port of
* the CHANGELOG, the review report, the review overlays and the application's drawings is held
* to the generic contract and not only to the equine data. Each case records the raw and the
* formatted Markdown and the four drawings. `MAKE_R5_ORACLES=1` writes
* crates/core/tests/oracles/r5/review-synthetic.json.
*/
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import {
applyChangeset,
buildReportMigrationMap,
ChangesetSchema,
documentStats,
renderAppReviewDrawing,
renderChangelog,
renderReviewOverlay,
renderReviewReport,
} from '../src'
import { changeSummary } from '../src/curation/schema'
import { formatMarkdown } from '../src/format'
import { MINI_REFERENCES, miniSheet } from './fixtures/mini-sheet'
const HERE = dirname(fileURLToPath(import.meta.url))
const OUT = resolve(HERE, '../../../crates/core/tests/oracles/r5')
const MAKE = process.env.MAKE_R5_ORACLES === '1'
type Json = Record<string, unknown>
const DRAWING = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 80" width="100" height="80">',
' <path d="M0 0 L10 10" fill="#ccbbaa"/>',
' <g id="body"><circle cx="5" cy="5" r="2" fill="#998877"/></g>',
'</svg>',
'',
].join('\n')
const LEGACY_ID_MAP = {
views: { head: 'head' },
annotations: { 'legacy-hip': 'hip', 'legacy-neck': 'neck' },
categories: {},
finding_nodes: {},
assets: {},
}
const SHEET = {
sheetId: '11111111-1111-5111-8111-111111111111',
versionId: null,
documentSha256: '0'.repeat(64),
}
const ANOMALIES = [
{ code: 'a.one', level: 'a_valider', subject: 's', message: 'm' },
{ code: 'a.two', level: 'informatif', subject: 's', message: 'm' },
{ code: 'a.three', level: 'a_valider', subject: 's', message: 'm' },
]
const MOBILITY = 'finding:hip/hip-dysfunctions/mobility'
function change(id: string, ops: unknown[], extra: Json = {}): Json {
return {
id,
level: 'A',
kind: 'technical',
title: { fr: 'Essai', en: 'Test' },
rationale: 'Essai',
reference_ids: [],
...extra,
ops,
}
}
interface Case {
name: string
changes_file: Json
}
const LONG = 'mot '.repeat(40)
const CASES: Case[] = [
{
name: 'every-section',
changes_file: {
changes: [
change(
'CHG-001',
[
{
op: 'set',
target: MOBILITY,
field: 'name',
value: { fr: 'Mobilité | pipe', en: 'Mobility\nline' },
},
{
op: 'set',
target: 'finding:neck/neck-dysfunctions/stiffness',
field: 'requires_vet_referral',
value: true,
},
{
op: 'set',
target: 'annotation:hip',
field: 'geometry',
value: { type: 'circle', cx: 30, cy: 20.5, r: 4 },
},
{
op: 'set',
target: 'annotation:neck',
field: 'geometry',
value: {
type: 'polygon',
points: [
[10, 10],
[20, 10],
[15, 25],
],
},
},
],
{ kind: 'correction', reference_ids: ['atlas'] },
),
change(
'CHG-002',
[
{
op: 'set',
target: `${MOBILITY}/flexion`,
field: 'description',
value: { fr: LONG, en: `${LONG}é` },
},
{
op: 'cite',
target: 'zone:hip',
reference_ids: ['paper'],
scope: 'subtree',
},
],
{ level: 'B', kind: 'translation', priority: 'high' },
),
change(
'CHG-010',
[
{
op: 'add',
target: MOBILITY,
value: {
id: 'rotation',
name: { fr: 'Rotation « axiale »', en: 'Axial rotation' },
},
},
],
{
level: 'C',
kind: 'enrichment',
question: 'Faut-il la garder ?',
priority: 'low',
reference_ids: ['paper'],
},
),
change(
'CHG-0011',
[{ op: 'remove', target: 'finding:hip/anamnesis/trauma' }],
{
level: 'C',
kind: 'restructure',
question: 'Retrait confirmé ?',
priority: 'high',
},
),
change('CHG-003', [{ op: 'remove', target: `${MOBILITY}/extension` }], {
kind: 'removal',
}),
],
},
},
{
name: 'detail-view-and-path',
changes_file: {
changes: [
change('CHG-001', [
{
op: 'add',
target: 'document',
field: 'annotations',
value: {
id: 'skull',
kind: 'point',
view_id: 'head',
category_id: 'bones',
laterality: 'unpaired',
geometry: { type: 'path', d: 'M1 1 L5 5' },
name: { fr: 'Crâne', en: 'Skull' },
finding_zone_id: 'neck',
vertebral_region_code: null,
},
},
{
op: 'set',
target: 'view:head',
field: 'view_box',
value: { min_x: 2.5, min_y: 1, width: 40, height: 30 },
},
]),
],
},
},
{
name: 'nothing-but-a-level-a',
changes_file: {
changes: [
change('CHG-001', [
{ op: 'set', target: 'document', field: 'name.en', value: 'Small' },
]),
],
},
},
{
// Prettier measures an emoji with its RGI table; the port refuses (declared: the report
// guard first, UnsupportedMarkdown, before the aligner's UnsupportedWidth of R5.2).
name: 'declared-emoji-in-a-cell',
changes_file: {
changes: [
change('CHG-001', [
{
op: 'set',
target: MOBILITY,
field: 'name.en',
value: 'Mobility 🐴',
},
]),
],
},
},
]
async function run(c: Case) {
const changeset = ChangesetSchema.parse(c.changes_file)
const baseline = miniSheet()
const result = applyChangeset(baseline, MINI_REFERENCES, changeset)
const before = documentStats(baseline)
const after = documentStats(result.document)
const migration = buildReportMigrationMap({
baseline: miniSheet() as never,
final: result.document as never,
legacyIdMap: LEGACY_ID_MAP,
records: result.records,
sheet: SHEET,
mainViewId: 'main',
})
const changelogRaw = renderChangelog(result, before, after, migration.stats)
const reviewRaw = renderReviewReport({
changes: changeset.changes.map(changeSummary),
records: result.records,
document: result.document,
statsBefore: before,
legacyAnomalies: ANOMALIES as never,
})
const drawings: Record<string, string> = {}
for (const view of result.document.views) {
drawings[`annotations-${view.id}`] = renderReviewOverlay({
cleanedSvg: DRAWING,
before: miniSheet(),
after: result.document,
viewId: view.id,
})
}
for (const view of result.document.views) {
drawings[`app-${view.id}`] = renderAppReviewDrawing({
cleanedSvg: DRAWING,
document: result.document,
viewId: view.id,
})
}
return {
...c,
changelog_raw: changelogRaw,
changelog: await formatMarkdown(changelogRaw),
review_raw: reviewRaw,
review: await formatMarkdown(reviewRaw),
drawings,
}
}
describe('R5.4 synthetic review oracle', () => {
it('review-synthetic.json', async () => {
const rows = []
for (const c of CASES) rows.push(await run(c))
const oracle = {
baseline: miniSheet(),
references: MINI_REFERENCES,
drawing: DRAWING,
anomalies: ANOMALIES,
legacy_id_map: LEGACY_ID_MAP,
cases: rows,
}
const text = `${JSON.stringify(oracle)}\n`
const file = resolve(OUT, 'review-synthetic.json')
if (MAKE) {
mkdirSync(OUT, { recursive: true })
writeFileSync(file, text)
}
expect(text).toBe(readFileSync(file, 'utf8'))
})
})
@@ -1,230 +0,0 @@
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { DOMParser, XMLSerializer, type Element } from '@xmldom/xmldom'
import { beforeAll, describe, expect, it } from 'vitest'
import {
composeViewSvg,
EQUINE_DRAFT_DIR,
HALO_FILTER_ID,
highlightLayer,
renderAnnotationLayer,
renderAppReviewDrawing,
type DraftResult,
type LayerElement,
} from '../src'
import { REPO_ROOT, runDraft } from './helpers'
const draftDir = join(REPO_ROOT, EQUINE_DRAFT_DIR)
const HALO_FILTER_MARKUP =
`<defs><filter id="${HALO_FILTER_ID}" x="-100%" y="-100%" width="300%" ` +
'height="300%" filterUnits="userSpaceOnUse">' +
'<feGaussianBlur in="SourceGraphic" stdDeviation="18" result="haloWide"/>' +
'<feGaussianBlur in="SourceGraphic" stdDeviation="8" result="haloTight"/>' +
'<feMerge><feMergeNode in="haloWide"/><feMergeNode in="haloWide"/>' +
'<feMergeNode in="haloWide"/><feMergeNode in="haloTight"/>' +
'<feMergeNode in="haloTight"/><feMergeNode in="SourceGraphic"/>' +
'</feMerge></filter></defs>'
let draft: DraftResult
let horseSvg: string
/** The committed cleaned drawing, parsed fresh for every test. */
function parseHorse(): Element {
const doc = new DOMParser().parseFromString(horseSvg, 'image/svg+xml')
return doc.documentElement!
}
function serialize(root: Element): string {
return new XMLSerializer().serializeToString(root.ownerDocument!)
}
function elements(list: { length: number; item(i: number): Element | null }) {
return Array.from({ length: list.length }, (_, i) => list.item(i)!)
}
/** Element children of the layer `<g>`, the last child of the root. */
function layerChildren(root: Element): Element[] {
const layer = root.lastChild as Element
expect(layer.nodeName).toBe('g')
return elements(layer.childNodes as never).filter((n) => n.nodeType === 1)
}
function dataAttributeCount(root: Element): number {
return (serialize(root).match(/ data-[a-z-]+="/g) ?? []).length
}
beforeAll(async () => {
;({ draft } = await runDraft())
const [asset] = draft.assets
horseSvg = await readFile(join(draftDir, 'assets', asset!.file), 'utf8')
})
describe('composeViewSvg with a highlight', () => {
it('keeps both elements of a selected point and the selected spine zone, haloed on the main view', () => {
const root = composeViewSvg({
root: parseHorse(),
document: draft.document,
viewId: 'main',
highlight: { annotationIds: new Set(['hip', 'cervical']), halo: true },
})
const kept = layerChildren(root)
expect(kept.map((e) => e.nodeName)).toEqual(['circle', 'circle', 'polygon'])
for (const element of kept) {
expect(element.getAttribute('fill')).toBe('#b85a3f')
expect(element.getAttribute('fill-opacity')).toBe('0.85')
expect(element.getAttribute('filter')).toBe(`url(#${HALO_FILTER_ID})`)
}
expect(kept[0]!.getAttribute('r')).toBe('34')
expect(kept[1]!.getAttribute('r')).toBe('22')
expect(root.getAttribute('viewBox')).toBe('0 0 2073.4 1629.4')
expect(root.hasAttribute('width')).toBe(false)
expect(root.hasAttribute('height')).toBe(false)
})
it('creates <defs> as the first child of an asset without one and fills it with the halo filter', () => {
const root = composeViewSvg({
root: parseHorse(),
document: draft.document,
viewId: 'main',
highlight: { annotationIds: new Set(['hip']), halo: true },
})
expect(root.firstChild!.nodeName).toBe('defs')
expect(root.getElementsByTagName('defs')).toHaveLength(1)
expect(serialize(root)).toContain(HALO_FILTER_MARKUP)
})
it('never duplicates the filter on a root that already holds it', () => {
const root = parseHorse()
const input = {
root,
document: draft.document,
viewId: 'main',
highlight: { annotationIds: new Set(['hip']), halo: true },
}
composeViewSvg(input)
composeViewSvg(input)
const filters = elements(root.getElementsByTagName('filter')).filter(
(f) => f.getAttribute('id') === HALO_FILTER_ID,
)
expect(filters).toHaveLength(1)
expect(root.getElementsByTagName('defs')).toHaveLength(1)
})
it('frames the head view on its view box without any halo', () => {
const root = composeViewSvg({
root: parseHorse(),
document: draft.document,
viewId: 'head',
highlight: { annotationIds: new Set(['parietal']), halo: false },
})
expect(root.getAttribute('viewBox')).toBe('60 100 500 380')
expect(root.getElementsByTagName('defs')).toHaveLength(0)
expect(serialize(root)).not.toContain(HALO_FILTER_ID)
const kept = layerChildren(root)
expect(kept.map((e) => e.nodeName)).toEqual(['circle', 'circle'])
for (const element of kept) {
expect(element.getAttribute('fill')).toBe('#b85a3f')
expect(element.hasAttribute('filter')).toBe(false)
}
})
it('leaves an empty layer when nothing is selected', () => {
const root = composeViewSvg({
root: parseHorse(),
document: draft.document,
viewId: 'main',
highlight: { annotationIds: new Set(), halo: true },
})
expect(layerChildren(root)).toHaveLength(0)
})
it('keeps the <title> of every kept marker and emits no data attribute', () => {
const root = composeViewSvg({
root: parseHorse(),
document: draft.document,
viewId: 'main',
highlight: { annotationIds: new Set(['hip', 'cervical']), halo: true },
})
const titles = elements(root.lastChild!.childNodes as never)
.filter((n) => n.nodeType === 1)
.map((e) => e.getElementsByTagName('title').item(0)!.textContent)
expect(titles).toEqual([
'Hanche (coxo-fémorale) / Hip joint',
'Hanche (coxo-fémorale) / Hip joint',
'Vertèbres cervicales / Cervical vertebrae',
])
expect(dataAttributeCount(root)).toBe(0)
})
it('refuses an unknown view', () => {
expect(() =>
composeViewSvg({
root: parseHorse(),
document: draft.document,
viewId: 'nope',
highlight: { annotationIds: new Set(), halo: false },
}),
).toThrow('unknown view')
})
})
describe('highlightLayer on the layer tree', () => {
function flatten(node: LayerElement): LayerElement[] {
return [node, ...node.children.flatMap(flatten)]
}
it('filters, restyles and strips data attributes without touching the input', () => {
const layer = renderAnnotationLayer({
document: draft.document,
viewId: 'main',
})
const before = JSON.stringify(layer)
const highlighted = highlightLayer(layer, {
annotationIds: new Set(['cervical']),
halo: false,
})
expect(JSON.stringify(layer)).toBe(before)
expect(highlighted.children).toHaveLength(1)
expect(highlighted.children[0]!.attrs).toMatchObject({
fill: '#b85a3f',
'fill-opacity': '0.85',
'stroke-width': '2',
})
expect(highlighted.children[0]!.attrs.filter).toBeUndefined()
const dataKeys = flatten(highlighted).flatMap((n) =>
Object.keys(n.attrs).filter((k) => k.startsWith('data-')),
)
expect(dataKeys).toEqual([])
})
})
describe('composeViewSvg without a highlight (review drawings)', () => {
it.each(['main', 'head'])(
'renderAppReviewDrawing(%s) equals the committed review drawing',
async (viewId) => {
const committed = await readFile(
join(draftDir, 'review', `app-${viewId}.svg`),
'utf8',
)
const rendered = renderAppReviewDrawing({
cleanedSvg: horseSvg,
document: draft.document,
viewId,
})
expect(rendered).toBe(committed)
},
)
it('keeps the full interactive layer with its data attributes', () => {
const root = composeViewSvg({
root: parseHorse(),
document: draft.document,
viewId: 'main',
})
expect(root.getElementsByTagName('defs')).toHaveLength(0)
expect((root.lastChild as Element).getAttribute('data-layer')).toBe(
'annotations',
)
expect(dataAttributeCount(root)).toBeGreaterThan(0)
})
})
-158
View File
@@ -1,158 +0,0 @@
import { DOMParser } from '@xmldom/xmldom'
import { beforeAll, describe, expect, it } from 'vitest'
import {
createLayerElement,
renderAnnotationLayer,
serializeLayer,
styleForView,
type DraftResult,
type LayerElement,
} from '../src'
import { miniSheet } from './fixtures/mini-sheet'
import { runDraft } from './helpers'
function flatten(node: LayerElement): LayerElement[] {
return [node, ...node.children.flatMap(flatten)]
}
function byId(layer: LayerElement, id: string): LayerElement[] {
return flatten(layer).filter((n) => n.attrs['data-anno-id'] === id)
}
describe('annotation layer on the real draft', () => {
let draft: DraftResult
beforeAll(async () => {
;({ draft } = await runDraft())
})
it('draws every annotation of the main view as the legacy pair, zone or trigger', () => {
const layer = renderAnnotationLayer({
document: draft.document,
viewId: 'main',
})
expect(layer.attrs).toEqual({
'data-layer': 'annotations',
'data-view-id': 'main',
})
const main = draft.document.annotations.filter((a) => a.view_id === 'main')
for (const a of main) {
const els = byId(layer, a.id)
if (a.kind === 'point')
expect(els.map((e) => e.tag)).toEqual(['circle', 'circle'])
else expect(els).toHaveLength(1)
}
const [hitbox, visible] = byId(layer, 'hip')
expect(hitbox!.attrs).toMatchObject({
r: '34',
fill: 'transparent',
'pointer-events': 'all',
'data-anno-lateral': 'bilateral',
'data-anno-zone': 'hip',
})
expect(visible!.attrs).toMatchObject({
r: '22',
fill: '#ff9500',
'fill-opacity': '0.65',
stroke: '#000',
'stroke-width': '1.5',
'pointer-events': 'none',
})
expect(hitbox!.children[0]).toMatchObject({
tag: 'title',
text: 'Hanche (coxo-fémorale) / Hip joint',
})
const [spine] = byId(layer, 'cervical')
expect(spine!.tag).toBe('polygon')
expect(spine!.attrs).toMatchObject({
fill: '#e100ff',
'fill-opacity': '0.3',
'stroke-width': '2',
'data-anno-region': 'C',
})
const [trigger] = byId(layer, 'head-trigger')
expect(trigger!.attrs).toMatchObject({
'data-anno-kind': 'detail_trigger',
'data-anno-opens-view': 'head',
'stroke-dasharray': '8,4',
'fill-opacity': '0.06',
class: 'detail-zone',
})
expect(trigger!.attrs['data-anno-name-fr']).toBe(
'Tête (vue latérale gauche)',
)
})
it('uses the detail style, the annotation colour override and the view box on the head view', () => {
const layer = renderAnnotationLayer({
document: draft.document,
viewId: 'head',
})
const [c0c1Hit, c0c1Vis] = byId(layer, 'c0-c1')
expect(c0c1Hit!.attrs.r).toBe('27')
expect(c0c1Vis!.attrs).toMatchObject({
r: '15',
fill: '#ff0000',
'fill-opacity': '0.5',
})
expect(byId(layer, 'atm')[1]!.attrs.fill).toBe('#ff8800')
expect(byId(layer, 'hyoid')[1]!.attrs.fill).toBe('#d507c4')
expect(byId(layer, 'parietal')[1]!.attrs.fill).toBe('#1baa08')
expect(styleForView(draft.document.views[1]!).visibleFillOpacity).toBe(0.5)
expect(flatten(layer).some((n) => n.attrs['data-anno-id'] === 'hip')).toBe(
false,
)
})
it('applies states as data-state on both elements of a point', () => {
const states = new Map([['hip', 'current' as const]])
const layer = renderAnnotationLayer({
document: draft.document,
viewId: 'main',
states,
})
expect(
byId(layer, 'hip').every((e) => e.attrs['data-state'] === 'current'),
).toBe(true)
expect(
byId(layer, 'stifle').every((e) => e.attrs['data-state'] === undefined),
).toBe(true)
})
it('materialises through a DOM and serialises to the same markup', () => {
const layer = renderAnnotationLayer({
document: draft.document,
viewId: 'head',
})
const doc = new DOMParser().parseFromString(
'<svg xmlns="http://www.w3.org/2000/svg"/>',
'image/svg+xml',
)
const element = createLayerElement(doc as never, layer) as unknown as {
getAttribute(name: string): string | null
getElementsByTagName(tag: string): { length: number }
}
expect(element.getAttribute('data-layer')).toBe('annotations')
expect(element.getElementsByTagName('circle')).toHaveLength(18)
const text = serializeLayer(layer)
expect(text).toContain('<g data-layer="annotations" data-view-id="head">')
expect(text).toContain('<title>Appareil hyoïdien / Hyoid apparatus</title>')
expect(text).not.toContain('<script')
})
})
describe('annotation layer edge cases', () => {
it('skips annotations without geometry and falls back to grey without any colour', () => {
const sheet = miniSheet()
const layer = renderAnnotationLayer({ document: sheet, viewId: 'main' })
const ids = new Set(
flatten(layer)
.map((n) => n.attrs['data-anno-id'])
.filter(Boolean),
)
expect(ids.has('hip')).toBe(true)
expect(byId(layer, 'hip')[1]!.attrs.fill).toBe('#888888')
expect(() =>
renderAnnotationLayer({ document: sheet, viewId: 'nope' }),
).toThrow('unknown view')
})
})
@@ -1,98 +0,0 @@
import { readdir, readFile } from 'node:fs/promises'
import { join } from 'node:path'
import {
EQUINE_DRAFT_DIR,
EQUINE_LEGACY_IMPORT_DIR,
EQUINE_SOURCE_PATHS,
renderArtifacts,
renderDraftArtifacts,
sha256Hex,
type AssetRecord,
type DraftResult,
} from '../src'
import { REPO_ROOT, runDraft } from './helpers'
const legacyDir = join(REPO_ROOT, EQUINE_LEGACY_IMPORT_DIR)
const draftDir = join(REPO_ROOT, EQUINE_DRAFT_DIR)
let legacy: Record<string, string>
let draftFiles: Record<string, string>
let draft: DraftResult
/** Recursive file list, relative to `dir`, with forward slashes. */
async function listFiles(dir: string): Promise<string[]> {
const entries = await readdir(dir, { recursive: true, withFileTypes: true })
return entries
.filter((entry) => entry.isFile())
.map((entry) => join(entry.parentPath, entry.name).slice(dir.length + 1))
}
beforeAll(async () => {
const run = await runDraft()
draft = run.draft
legacy = await renderArtifacts(run.result)
draftFiles = await renderDraftArtifacts(run.draft, run.result.anomalies)
})
describe('committed legacy-import folder (golden)', () => {
it.each([
'document.json',
'legacy-id-map.json',
'assets.json',
'IMPORT-REPORT.md',
])('%s equals a fresh run (rerun pnpm import:equine)', async (file) => {
expect(await readFile(join(legacyDir, file), 'utf8')).toBe(legacy[file])
})
it('carries no SQL: the draft folder holds the only seed', () => {
expect(Object.keys(legacy).some((file) => file.endsWith('.sql'))).toBe(
false,
)
})
it('copies the SVG assets byte for byte with the recorded sha256', async () => {
const assets = JSON.parse(legacy['assets.json']!) as AssetRecord[]
const sources = [EQUINE_SOURCE_PATHS.mainSvg, EQUINE_SOURCE_PATHS.headSvg]
for (const [index, asset] of assets.entries()) {
const copy = await readFile(join(legacyDir, 'assets', asset.file))
const original = await readFile(join(REPO_ROOT, sources[index]!))
expect(copy.equals(original)).toBe(true)
expect(sha256Hex(copy)).toBe(asset.sha256)
expect(copy.byteLength).toBe(asset.byte_size)
}
})
})
/**
* Since R5.6 the Rust pipeline writes the seed (`pnpm import:equine`) under the fingerprint
* convention `sha256-rfc8785-validated-v1`; this TypeScript generator (`import:equine:legacy`)
* keeps the historical one. Its two fingerprint-bearing files are compared with the pre-switch
* files it wrote (frozen under `crates/core/tests/fixtures/r5-6/pre-switch`, proven against the
* R5.1 ledger by the Rust suite `curation_draft`); every other file with the committed seed.
*/
const PRE_SWITCH = join(REPO_ROOT, 'crates/core/tests/fixtures/r5-6/pre-switch')
const FINGERPRINTED = new Set(['sheet-ref.json', 'report-migration-map.json'])
describe('committed draft folder (golden)', () => {
it('equals a fresh run for every produced file (the two fingerprinted ones before R5.6)', async () => {
for (const [file, content] of Object.entries(draftFiles)) {
const dir = FINGERPRINTED.has(file) ? PRE_SWITCH : draftDir
expect(await readFile(join(dir, file), 'utf8'), file).toBe(content)
}
})
it('holds no file the run does not produce', async () => {
const expected = [
...Object.keys(draftFiles),
...draft.assets.map((asset) => `assets/${asset.file}`),
]
expect((await listFiles(draftDir)).sort()).toEqual(expected.sort())
})
it('holds the cleaned drawing with the recorded sha256', async () => {
const [asset] = draft.assets
const bytes = await readFile(join(draftDir, 'assets', asset!.file))
expect(bytes.toString('utf8')).toBe(draft.cleanedSvg)
expect(sha256Hex(bytes)).toBe(asset!.sha256)
expect(bytes.byteLength).toBe(asset!.byte_size)
})
})
-21
View File
@@ -1,21 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022"],
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"isolatedModules": true,
"types": ["node", "vitest/globals"],
"noEmit": true
},
"include": ["src", "tests"],
"exclude": ["node_modules"]
}
-9
View File
@@ -1,9 +0,0 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
environment: 'node',
globals: true,
include: ['tests/**/*.test.ts'],
},
})
-20
View File
@@ -1,20 +0,0 @@
import globals from 'globals'
import tseslint from 'typescript-eslint'
export default tseslint.config(
{ ignores: ['node_modules/**'] },
{
files: ['**/*.ts'],
extends: [...tseslint.configs.recommended],
languageOptions: {
globals: { ...globals.node, ...globals.es2022 },
},
rules: {
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_' },
],
},
},
)
-34
View File
@@ -1,34 +0,0 @@
{
"name": "@faunosteo/domain",
"version": "0.1.0",
"private": true,
"description": "Faunosteo pure domain model: canonical anatomical sheet document, report document (v3 + v2 migration), Zod schemas and integrity rules",
"license": "MIT",
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts",
"./anatomical-sheet": "./src/anatomical-sheet/index.ts",
"./report": "./src/report/index.ts",
"./archive": "./src/archive/index.ts"
},
"scripts": {
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest",
"test:run": "vitest run",
"lint": "eslint . --max-warnings 0",
"build": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"zod": "^3.24.1"
},
"devDependencies": {
"@types/node": "^20.19.41",
"eslint": "^9.17.0",
"globals": "^15.14.0",
"typescript": "^5.7.2",
"typescript-eslint": "^8.19.0",
"vitest": "^3.2.7"
}
}
@@ -1,44 +0,0 @@
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: [] },
references: [],
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: [],
})
}
@@ -1,4 +0,0 @@
export * from './schema'
export * from './validate'
export * from './create'
export * from './sheet-index'
@@ -1,327 +0,0 @@
import { z } from 'zod'
/**
* Canonical anatomical sheet document, schema_version 2.
*
* 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,
* reference ids…) are checked by validateSheetDocument, not here, so a
* draft with dangling references can still be saved.
*
* Version 2 (Step 4c): shared bibliographic `references` registry cited by
* `reference_ids`, `review_status` on findings and annotations, optional
* `count_range` on vertebral regions. No version 1 document was ever
* published, so version 1 is not read any more.
*/
export const SHEET_DOCUMENT_SCHEMA_VERSION = 2
/** 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()
/**
* How far the sheet content was checked against references. `inherited` =
* taken over from a previous source without review; `reviewed` = checked
* and cited; `to_confirm` = changed or added on documented grounds, still
* awaiting a professional's confirmation.
*/
export const ReviewStatusSchema = z.enum(['inherited', 'reviewed', 'to_confirm'])
const CountRangeSchema = z
.object({ min: z.number().int().min(1), max: z.number().int().min(1) })
.strict()
/**
* `count` is the usual number of vertebrae (what the picker shows by
* default); `count_range` states the documented individual variation so a
* report may record a vertebra beyond the usual count. Null = no variation.
*/
export const VertebralRegionSchema = z
.object({
code: RegionCodeSchema,
name: LocalizedTextSchema,
count: z.number().int().min(1),
count_range: CountRangeSchema.nullable().default(null),
})
.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(),
review_status: ReviewStatusSchema.default('inherited'),
/** Marker colour of this annotation; null = the category colour. */
color: HexColorSchema.nullable().default(null),
}
/** 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,
])
/** Documents are shared across users: only web links, never javascript: URLs. */
const HttpUrlSchema = z
.string()
.url()
.refine((url) => /^https?:\/\//i.test(url), 'http(s) URL expected')
/**
* One bibliographic reference, declared once in the document and cited by
* id from any number of findings (an anatomy atlas backs hundreds of
* entries). `citation` is the human-readable form (author, title, edition,
* year, publisher or journal, location in the work when known).
*/
export const ReferenceSchema = z
.object({
id: StableIdSchema,
type: z.enum(['book', 'journal', 'standard', 'legal', 'web', 'manual']),
citation: z.string().min(1),
url: HttpUrlSchema.nullable().default(null),
doi: z.string().min(1).nullable().default(null),
})
.strict()
export type Reference = z.infer<typeof ReferenceSchema>
export type ReviewStatus = z.infer<typeof ReviewStatusSchema>
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
reference_ids: string[]
review_status: ReviewStatus
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
reference_ids?: string[]
review_status?: ReviewStatus
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),
reference_ids: z.array(StableIdSchema).default([]),
review_status: ReviewStatusSchema.default('inherited'),
children: z.array(FindingNodeSchema).default([]),
})
.strict(),
)
/** Typed business buckets; creators may add their own as 'custom'. */
export const FindingCategoryKindSchema = z.enum([
'dysfunction',
'consultation_reason',
'anamnesis',
'custom',
])
export const FindingCategorySchema = z
.object({
id: StableIdSchema,
kind: FindingCategoryKindSchema,
name: LocalizedTextSchema,
description: LocalizedOptionalTextSchema.default({}),
reference_ids: z.array(StableIdSchema).default([]),
review_status: ReviewStatusSchema.default('inherited'),
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,
references: z.array(ReferenceSchema),
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>
@@ -1,127 +0,0 @@
import type {
AnatomicalSheetDocument,
Annotation,
FindingCategory,
FindingNode,
FindingZone,
LocalizedText,
SheetView,
VertebralRegion,
} from './schema'
/**
* Read-only lookups over a sheet document. Everything the editor and the
* PDF engine derive from the sheet (zone names, finding paths, spine
* regions, trigger targets) comes from the document here, by stable id:
* no label drives logic. The index keeps the source it was built from so a
* caller gets back exactly what it passed (a loaded sheet with its migration
* map, or an archived snapshot).
*/
/** The minimum a sheet source carries: provenance, document, SVG text by asset id. */
export interface SheetIndexSource {
ref: { documentSha256: string }
document: AnatomicalSheetDocument
assets: Readonly<Record<string, string>>
}
export type ObservableAnnotation = Extract<
Annotation,
{ kind: 'point' | 'zone' }
>
export interface SheetIndex<S extends SheetIndexSource = SheetIndexSource> {
sheet: S
mainView: SheetView
view(id: string): SheetView | undefined
annotation(id: string): Annotation | undefined
annotationsOfView(viewId: string): Annotation[]
findingZone(id: string): FindingZone | undefined
/** The category or node at a path, undefined when absent from the sheet. */
nodeAt(
zoneId: string,
path: readonly string[],
): FindingCategory | FindingNode | undefined
regions(): VertebralRegion[]
region(code: string): VertebralRegion | undefined
/** The annotation that opens the vertebra picker for a region on a view. */
spineAnnotation(
regionCode: string,
viewId: string,
): ObservableAnnotation | undefined
/** Whether an annotation opens the vertebra picker. */
isSpine(annotationId: string): boolean
name(annotation: Annotation): LocalizedText
}
/** The label in a locale, the other locale as fallback, '' when none. */
export function pickLabel(
text: LocalizedText | null | undefined,
locale: 'fr' | 'en',
): string {
if (!text) return ''
return locale === 'en' ? text.en || text.fr : text.fr || text.en
}
export function isObservable(
a: Annotation | undefined,
): a is ObservableAnnotation {
return a !== undefined && a.kind !== 'detail_trigger'
}
function nodeAtPath(
zone: FindingZone | undefined,
path: readonly string[],
): FindingCategory | FindingNode | undefined {
if (!zone || path.length === 0) return undefined
let node: FindingCategory | FindingNode | undefined = zone.categories.find(
(c) => c.id === path[0],
)
for (const segment of path.slice(1)) {
if (!node) return undefined
node = node.children.find((n) => n.id === segment)
}
return node
}
export function buildSheetIndex<S extends SheetIndexSource>(
sheet: S,
): SheetIndex<S> {
const { document } = sheet
const views = new Map(document.views.map((v) => [v.id, v]))
const annotations = new Map(document.annotations.map((a) => [a.id, a]))
const zones = new Map(document.finding_zones.map((z) => [z.id, z]))
const regions = new Map(
document.vertebral_config.regions.map((r) => [r.code, r]),
)
const mainView = document.views.find((v) => v.kind === 'main')
if (!mainView) throw new Error('sheet has no main view')
return {
sheet,
mainView,
view: (id) => views.get(id),
annotation: (id) => annotations.get(id),
annotationsOfView: (viewId) =>
document.annotations.filter((a) => a.view_id === viewId),
findingZone: (id) => zones.get(id),
nodeAt: (zoneId, path) => nodeAtPath(zones.get(zoneId), path),
regions: () => document.vertebral_config.regions,
region: (code) => regions.get(code),
spineAnnotation: (code, viewId) =>
document.annotations.find(
(a): a is ObservableAnnotation =>
isObservable(a) &&
a.view_id === viewId &&
a.vertebral_region_code === code,
),
isSpine: (id) => {
const a = annotations.get(id)
return isObservable(a) && a.vertebral_region_code !== null
},
name: (a) =>
a.kind === 'detail_trigger'
? (a.name ?? views.get(a.opens_view_id)?.name ?? { fr: '', en: '' })
: a.name,
}
}
@@ -1,494 +0,0 @@
import type {
AnatomicalSheetDocument,
Annotation,
FindingNode,
SheetView,
VertebralRegion,
} 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
reference_ids: readonly 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 checkReferenceIdsUnique: Rule = (doc) =>
duplicateIssues(
doc.references.map((reference) => reference.id),
'reference.id.duplicate',
(index) => `references[${index}].id`,
)
/** A citation must point at a declared reference, at every depth. */
function citationIssues(
nodes: readonly FindingLevelItem[],
path: string,
known: ReadonlySet<string>,
): SheetIssue[] {
return nodes.flatMap((node, index) => {
const own = node.reference_ids.flatMap((id, refIndex) =>
known.has(id)
? []
: [
error(
'finding.reference.missing',
`${path}[${index}].reference_ids[${refIndex}]`,
`Reference "${id}" is not declared in references`,
),
],
)
const nested = citationIssues(
node.children,
`${path}[${index}].children`,
known,
)
return [...own, ...nested]
})
}
const checkFindingReferences: Rule = (doc) => {
const known = new Set(doc.references.map((reference) => reference.id))
return doc.finding_zones.flatMap((zone, index) =>
citationIssues(
zone.categories,
`finding_zones[${index}].categories`,
known,
),
)
}
/** The usual count must sit inside the documented variation. */
function countRangeIssue(region: VertebralRegion, index: number): SheetIssue[] {
const range = region.count_range
if (range === null) return []
if (range.min <= region.count && region.count <= range.max) return []
return [
error(
'region.count_range.invalid',
`vertebral_config.regions[${index}].count_range`,
`Region "${region.code}": count ${region.count} outside ` +
`${range.min}–${range.max}`,
),
]
}
const checkRegionCountRanges: Rule = (doc) =>
doc.vertebral_config.regions.flatMap(countRangeIssue)
const RULES: readonly Rule[] = [
checkMainViewCount,
checkViewIdsUnique,
checkViewParentsExist,
checkViewParentCycles,
checkViewsReachable,
checkViewAssets,
checkAnnotationIdsUnique,
checkAnnotationViews,
checkAnnotationCategories,
checkTriggerTargets,
checkAnnotationFindingZones,
checkAnnotationRegions,
checkAnnotationsHaveFindings,
checkRegionCodesUnique,
checkCategoryIdsUnique,
checkFindingZoneIdsUnique,
checkFindingSiblings,
checkFindingZonesReferenced,
checkReferenceIdsUnique,
checkFindingReferences,
checkRegionCountRanges,
]
/** 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)
}
-59
View File
@@ -1,59 +0,0 @@
import { z } from 'zod'
/**
* The visual identity a PDF archive embeds so a re-export needs no network
* and no `public/` folder (STEP6 §3.4): logos as PNG base64 or SVG text,
* credits with the URL and the text printed when the logo fails. Caps are
* STEP6 §15 (branding row).
*/
const KIB = 1024
const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/
/**
* `http(s)://` then printable ASCII without `"`, `'`, `(`, `)`, `<`, `>`
* or `\`: the URL is written into PDF link actions and must never be able
* to close a string literal or carry a control character. Expressed as the
* allowed ranges of printable ASCII (0x21-0x7e) minus those seven.
*/
const HTTP_URL_PATTERN = /^https?:\/\/[!#-&*-;=?-[\]-~]+$/
const HttpUrlSchema = z
.string()
.max(2048)
.url()
.regex(HTTP_URL_PATTERN, 'http(s) URL expected')
export const ImageAssetSchema = z.discriminatedUnion('kind', [
z
.object({
kind: z.literal('png'),
base64: z
.string()
.max(512 * KIB)
.regex(BASE64_PATTERN),
})
.strict(),
z.object({ kind: z.literal('svg'), svg: z.string().max(256 * KIB) }).strict(),
])
export type ImageAsset = z.infer<typeof ImageAssetSchema>
export const CreditSchema = z
.object({
logo: ImageAssetSchema.nullable(),
url: HttpUrlSchema,
fallbackText: z.string().max(128),
})
.strict()
export type Credit = z.infer<typeof CreditSchema>
export const BrandingSchema = z
.object({
siteUrl: HttpUrlSchema,
headerLogo: ImageAssetSchema.nullable(),
footerLogo: ImageAssetSchema.nullable(),
poweredBy: CreditSchema.nullable(),
partner: CreditSchema.nullable(),
})
.strict()
export type Branding = z.infer<typeof BrandingSchema>
-172
View File
@@ -1,172 +0,0 @@
import { z } from 'zod'
import { readReportDocument } from '../report/migrate'
import type { ReportMigrationMap } from '../report/migration-map'
import { REPORT_VERSION, ReportSchema, type Report } from '../report/v3'
import { BrandingSchema, type Branding } from './branding'
import { PdfLabelSetSchema, type PdfLabelSet } from './labels'
import {
SheetSnapshotSchema,
SnapshotError,
assertSnapshot,
type SheetSnapshot,
type SnapshotRejection,
} from './snapshot'
/**
* Attachment of a Step 6 PDF: the report (v3, unchanged) wrapped with the
* sheet snapshot, the branding and the PDF labels it was printed with
* (STEP6 §2.3). Reading is layered (§4, §14 "Read"): the report is located
* and parsed first so it is never lost because of its wrapper; the wrapper
* is then validated or dropped with a reason.
*/
export const ENVELOPE_FORMAT = 'faunosteo-report-archive'
export const ENVELOPE_VERSION = 1
export interface ReportArchiveEnvelope {
format: typeof ENVELOPE_FORMAT
envelopeVersion: typeof ENVELOPE_VERSION
/** ISO timestamp of the export. */
exportedAt: string
locale: 'fr' | 'en'
/** As exported, never rebased. */
report: Report
sheetSnapshot: SheetSnapshot
branding: Branding
labels: PdfLabelSet
}
/** Metadata is not strict: an additive v1 field never breaks an older reader. */
const EnvelopeMetadataSchema = z.object({
format: z.literal(ENVELOPE_FORMAT),
envelopeVersion: z.literal(ENVELOPE_VERSION),
exportedAt: z.string(),
locale: z.enum(['fr', 'en']),
})
/** Everything but the report and the snapshot, which the reader checks itself. */
const EnvelopeWrapperSchema = EnvelopeMetadataSchema.extend({
branding: BrandingSchema,
labels: PdfLabelSetSchema,
})
export const ReportArchiveEnvelopeSchema: z.ZodType<
ReportArchiveEnvelope,
z.ZodTypeDef,
unknown
> = EnvelopeWrapperSchema.extend({
report: ReportSchema,
sheetSnapshot: SheetSnapshotSchema,
})
export type ArchiveOrigin = 'envelope_v1' | 'bare_v3' | 'v2'
export interface ArchiveReadOutcome {
report: Report
origin: ArchiveOrigin
migrated: boolean
/** From the v2 migration; 0 for a v3 report. */
unresolvedZones: number
unresolvedFindings: number
/** The validated envelope, when accepted. */
archive: ReportArchiveEnvelope | null
/** Envelope present but its snapshot dropped. */
snapshotRejected?: SnapshotRejection
}
type Wrapped =
| { archive: ReportArchiveEnvelope }
| { snapshotRejected: SnapshotRejection }
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
/** An envelope of any version is recognised by a numeric envelopeVersion. */
function envelopeVersionOf(data: unknown): number | null {
if (!isRecord(data)) return null
const version = data.envelopeVersion
return typeof version === 'number' ? version : null
}
function reportVersionOf(data: unknown): number | null {
if (!isRecord(data)) return null
return typeof data.version === 'number' ? data.version : null
}
function snapshotMatches(snapshot: SheetSnapshot, report: Report): boolean {
return (
snapshot.ref.sheetId === report.sheet.sheetId &&
snapshot.ref.documentSha256 === report.sheet.documentSha256
)
}
/** Step 3 for a v1 envelope: wrapper schema → snapshot gate → sheet invariant. */
function readEnvelopeV1(
data: Record<string, unknown>,
report: Report,
): Wrapped {
const wrapper = EnvelopeWrapperSchema.safeParse(data)
if (!wrapper.success) return { snapshotRejected: 'schema' }
let snapshot: SheetSnapshot
try {
snapshot = assertSnapshot(data.sheetSnapshot)
} catch (error) {
if (error instanceof SnapshotError) {
return { snapshotRejected: error.reason }
}
throw error
}
if (!snapshotMatches(snapshot, report)) {
return { snapshotRejected: 'sheet_mismatch' }
}
return {
archive: {
format: wrapper.data.format,
envelopeVersion: wrapper.data.envelopeVersion,
exportedAt: wrapper.data.exportedAt,
locale: wrapper.data.locale,
report,
sheetSnapshot: snapshot,
branding: wrapper.data.branding,
labels: wrapper.data.labels,
},
}
}
/**
* Reads the JSON of a PDF attachment of any supported shape: bare Report v2
* or v3, or an archive envelope. The report is parsed first and always
* returned (`readReportDocument` throws UnsupportedReportVersionError for an
* unknown report version); the envelope is accepted whole or dropped with
* `snapshotRejected`.
*/
export function readArchiveDocument(
data: unknown,
map: ReportMigrationMap,
): ArchiveReadOutcome {
const envelopeVersion = envelopeVersionOf(data)
const reportData =
envelopeVersion !== null ? (data as Record<string, unknown>).report : data
const outcome = readReportDocument(reportData, map)
const migrated = reportVersionOf(reportData) !== REPORT_VERSION
const base: ArchiveReadOutcome = {
report: outcome.report,
origin: migrated ? 'v2' : 'bare_v3',
migrated,
unresolvedZones: outcome.unresolvedZones,
unresolvedFindings: outcome.unresolvedFindings,
archive: null,
}
if (envelopeVersion === null) return base
if (envelopeVersion !== ENVELOPE_VERSION) {
return { ...base, snapshotRejected: 'unsupported_envelope' }
}
const wrapped = readEnvelopeV1(
data as Record<string, unknown>,
outcome.report,
)
return 'archive' in wrapped
? { ...base, origin: 'envelope_v1', archive: wrapped.archive }
: { ...base, origin: 'envelope_v1', ...wrapped }
}
-4
View File
@@ -1,4 +0,0 @@
export * from './snapshot'
export * from './branding'
export * from './labels'
export * from './envelope'
-57
View File
@@ -1,57 +0,0 @@
import { z } from 'zod'
/**
* The static strings the PDF engine prints (section headings, metadata,
* severities, sides, footer credits), in both locales, frozen into the
* archive so a re-export renders the wording of the day. Exactly the dict
* keys apps/app/src/pdf read when Step 6 started.
*/
export const PDF_LABEL_KEYS = [
'pdf.empty',
'pdf.eyebrow.observation',
'pdf.eyebrow.synthesis',
'pdf.owner_prefix',
'pdf.section.comment',
'pdf.section.conclusion',
'pdf.section.findings_prefix',
'pdf.section.free_findings',
'pdf.section.next_appointment',
'pdf.section.recommendations',
'pdf.section.severity',
'pdf.section.zones',
'pdf.siret_prefix',
'pdf.subject',
'pdf.title.conclusion',
'pdf.title.suffix.bilan',
'pdf.view.detail_prefix',
'pdf.view.general',
'severity.mild',
'severity.moderate',
'severity.severe',
'lateral.left',
'lateral.right',
'footer.powered_by',
'footer.in_partnership',
] as const
export type PdfLabelKey = (typeof PDF_LABEL_KEYS)[number]
export type PdfLabels = Record<PdfLabelKey, string>
export interface PdfLabelSet {
fr: PdfLabels
en: PdfLabels
}
const labelShape = Object.fromEntries(
PDF_LABEL_KEYS.map((key) => [key, z.string().max(256)]),
) as Record<PdfLabelKey, z.ZodString>
export const PdfLabelsSchema: z.ZodType<PdfLabels> = z
.object(labelShape)
.strict()
/** Strict: every key present in both locales, no extra key. */
export const PdfLabelSetSchema: z.ZodType<PdfLabelSet> = z
.object({ fr: PdfLabelsSchema, en: PdfLabelsSchema })
.strict()
-425
View File
@@ -1,425 +0,0 @@
import { z } from 'zod'
import {
AnatomicalSheetDocumentSchema,
type AnatomicalSheetDocument,
type FindingCategory,
type FindingNode,
type FindingZone,
type SheetView,
} from '../anatomical-sheet/schema'
import { validateSheetDocument } from '../anatomical-sheet/validate'
import type { SheetIndexSource } from '../anatomical-sheet/sheet-index'
import { SheetRefSchema, type Report, type SheetRef } from '../report/v3'
/**
* The sheet a report archive carries so an old bilan re-renders without the
* current catalog (STEP6 §2.2). The snapshot keeps the shape the renderer and
* the sheet index consume: a valid, lean `AnatomicalSheetDocument` (every
* view, annotation, category and region; finding trees pruned to the paths
* the report uses; bibliography emptied) plus the SVG text of every asset a
* view reaches. `assertSnapshot` is the single gate an imported snapshot
* passes (STEP6 §15 caps, integrity, reachable assets).
*/
const SHA256_PATTERN = /^[0-9a-f]{64}$/
const MIB = 1024 * 1024
/** Hard limits on an imported snapshot; every excess is a `caps` rejection. */
export const SNAPSHOT_CAPS = {
views: 64,
annotations: 1024,
findingNodes: 8192,
findingDepth: 8,
labelChars: 512,
assets: 4,
assetBytes: 2 * MIB,
assetsTotalBytes: 6 * MIB,
} as const
export type SheetSnapshotRef = SheetRef & {
schemaVersion: number
speciesId: string
}
export interface SheetSnapshotAsset {
svgAssetId: string
/** Content address from the seed manifest; a provenance pointer, not a tamper check. */
sha256: string | null
svg: string
}
export interface SheetSnapshot {
status: 'draft' | 'published'
ref: SheetSnapshotRef
/** Lean, valid document (schema v2, strict). */
document: AnatomicalSheetDocument
assets: SheetSnapshotAsset[]
}
export const SheetSnapshotRefSchema: z.ZodType<SheetSnapshotRef> =
SheetRefSchema.extend({
schemaVersion: z.number().int().positive(),
speciesId: z.string().min(1),
}).strict()
const SheetSnapshotAssetSchema = z
.object({
svgAssetId: z.string().uuid(),
sha256: z.string().regex(SHA256_PATTERN).nullable(),
svg: z.string().max(SNAPSHOT_CAPS.assetBytes),
})
.strict()
/** Shape tier only: caps beyond the schema and integrity live in assertSnapshot. */
export const SheetSnapshotSchema: z.ZodType<
SheetSnapshot,
z.ZodTypeDef,
unknown
> = z
.object({
status: z.enum(['draft', 'published']),
ref: SheetSnapshotRefSchema,
document: AnatomicalSheetDocumentSchema,
assets: z.array(SheetSnapshotAssetSchema).max(SNAPSHOT_CAPS.assets),
})
.strict()
/** What a loaded sheet provides to build a snapshot from. */
export interface SnapshotSource {
status: 'draft' | 'published'
ref: SheetRef
speciesId: string
schemaVersion: number
document: AnatomicalSheetDocument
/** SVG text by `svg_asset_id`. */
assets: Readonly<Record<string, string>>
/** sha256 by `svg_asset_id` (seed manifest); absent → null in the snapshot. */
assetHashes?: Readonly<Record<string, string>>
}
export type SnapshotRejection =
| 'unsupported_envelope'
| 'schema'
| 'caps'
| 'integrity'
| 'sheet_mismatch'
/** Thrown by assertSnapshot; `reason` is what the import reports. */
export class SnapshotError extends Error {
constructor(
public readonly reason: SnapshotRejection,
detail: string,
) {
super(`snapshot rejected (${reason}): ${detail}`)
this.name = 'SnapshotError'
}
}
/** Own-key lookup: ids come from documents (`__proto__` is not an entry). */
function own<T>(
record: Readonly<Record<string, T>>,
key: string,
): T | undefined {
return Object.hasOwn(record, key) ? record[key] : undefined
}
/** The asset a view draws: its own, else the first one up its parent chain. */
function assetOfView(
view: SheetView,
views: ReadonlyMap<string, SheetView>,
): string | null {
const visited = new Set<string>()
let current: SheetView | undefined = view
while (current && !visited.has(current.id)) {
if (current.svg_asset_id !== null) return current.svg_asset_id
visited.add(current.id)
current =
current.kind === 'detail' ? views.get(current.parent_view_id) : undefined
}
return null
}
/** Asset ids reachable from the views, in view order, each once. */
function reachableAssetIds(document: AnatomicalSheetDocument): string[] {
const views = new Map(document.views.map((v) => [v.id, v]))
const ids: string[] = []
for (const view of document.views) {
const id = assetOfView(view, views)
if (id !== null && !ids.includes(id)) ids.push(id)
}
return ids
}
// ---------------------------------------------------------------------------
// Build
/** Finding paths of the report grouped by zone, resolved and unresolved alike. */
function pathsByZone(report: Report): Map<string, string[][]> {
const byZone = new Map<string, string[][]>()
for (const observation of report.observations) {
for (const finding of observation.findings) {
const paths = byZone.get(finding.findingZoneId) ?? []
paths.push(finding.path)
byZone.set(finding.findingZoneId, paths)
}
}
return byZone
}
/** Keeps, in document order, the nodes at `depth` of some path and their used descendants. */
function pruneNodes(
nodes: readonly FindingNode[],
paths: readonly string[][],
depth: number,
): FindingNode[] {
return nodes
.filter((node) => paths.some((path) => path[depth] === node.id))
.map((node) => ({
id: node.id,
name: { ...node.name },
description: {},
requires_vet_referral: node.requires_vet_referral,
reference_ids: [],
review_status: node.review_status,
children: pruneNodes(
node.children,
paths.filter((path) => path[depth] === node.id),
depth + 1,
),
}))
}
function pruneCategories(
categories: readonly FindingCategory[],
paths: readonly string[][],
): FindingCategory[] {
return categories
.filter((category) => paths.some((path) => path[0] === category.id))
.map((category) => ({
id: category.id,
kind: category.kind,
name: { ...category.name },
description: {},
reference_ids: [],
review_status: category.review_status,
children: pruneNodes(
category.children,
paths.filter((path) => path[0] === category.id),
1,
),
}))
}
function pruneZone(zone: FindingZone, paths: readonly string[][]): FindingZone {
return {
id: zone.id,
name: { ...zone.name },
categories: pruneCategories(zone.categories, paths),
}
}
function leanDocument(
document: AnatomicalSheetDocument,
report: Report,
): AnatomicalSheetDocument {
const used = pathsByZone(report)
return {
schema_version: document.schema_version,
species_id: document.species_id,
name: structuredClone(document.name),
description: structuredClone(document.description),
scope_disclaimer: structuredClone(document.scope_disclaimer),
attribution: structuredClone(document.attribution),
vertebral_config: structuredClone(document.vertebral_config),
references: [],
categories: structuredClone(document.categories),
views: structuredClone(document.views),
annotations: structuredClone(document.annotations),
finding_zones: document.finding_zones.map((zone) =>
pruneZone(zone, used.get(zone.id) ?? []),
),
}
}
function snapshotAssets(sheet: SnapshotSource): SheetSnapshotAsset[] {
const assets: SheetSnapshotAsset[] = []
for (const svgAssetId of reachableAssetIds(sheet.document)) {
const svg = own(sheet.assets, svgAssetId)
if (svg === undefined) continue
const sha256 = sheet.assetHashes
? (own(sheet.assetHashes, svgAssetId) ?? null)
: null
assets.push({ svgAssetId, sha256, svg })
}
return assets
}
/**
* The snapshot of `sheet` a given report needs: pure, deterministic
* (document order everywhere), inputs untouched. Finding trees keep only the
* categories and nodes on a path some finding of the report names, as far as
* those nodes exist; a missing asset is left out and caught by assertSnapshot.
*/
export function buildSheetSnapshot(
sheet: SnapshotSource,
report: Report,
): SheetSnapshot {
return {
status: sheet.status,
ref: {
sheetId: sheet.ref.sheetId,
versionId: sheet.ref.versionId,
documentSha256: sheet.ref.documentSha256,
schemaVersion: sheet.schemaVersion,
speciesId: sheet.speciesId,
},
document: leanDocument(sheet.document, report),
assets: snapshotAssets(sheet),
}
}
// ---------------------------------------------------------------------------
// Assert
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function childrenOf(node: unknown): unknown[] {
if (!isRecord(node)) return []
const children = node.children
return Array.isArray(children) ? children : []
}
/**
* Depth of the finding trees, checked on the raw input before Zod recurses
* into it (an attacker-sized tree must not drive the parser). Iterative:
* an explicit stack of (node, depth) pairs, categories at depth 1.
*/
function assertFindingDepth(input: unknown): void {
if (!isRecord(input) || !isRecord(input.document)) return
const zones = input.document.finding_zones
if (!Array.isArray(zones)) return
const stack: Array<[unknown, number]> = []
for (const zone of zones) {
if (!isRecord(zone) || !Array.isArray(zone.categories)) continue
for (const category of zone.categories) stack.push([category, 1])
}
while (stack.length > 0) {
const [node, depth] = stack.pop()!
if (depth > SNAPSHOT_CAPS.findingDepth) {
throw new SnapshotError(
'caps',
`finding depth over ${SNAPSHOT_CAPS.findingDepth}`,
)
}
for (const child of childrenOf(node)) stack.push([child, depth + 1])
}
}
function countFindingNodes(document: AnatomicalSheetDocument): number {
let count = 0
const stack: Array<FindingCategory | FindingNode> =
document.finding_zones.flatMap((zone) => zone.categories)
while (stack.length > 0) {
count += 1
stack.push(...stack.pop()!.children)
}
return count
}
/**
* Longest `name` label (`fr` or `en`) anywhere in the document: sheet, views,
* annotations, categories, regions, finding zones and nodes. Free texts
* (`description`, `scope_disclaimer`) are not labels and carry no cap here.
*/
function longestName(document: AnatomicalSheetDocument): number {
let longest = 0
const stack: unknown[] = [document]
while (stack.length > 0) {
const value = stack.pop()
if (Array.isArray(value)) stack.push(...value)
if (!isRecord(value)) continue
const name = value.name
if (isRecord(name)) {
for (const key of ['fr', 'en']) {
const text = name[key]
if (typeof text === 'string') longest = Math.max(longest, text.length)
}
}
stack.push(...Object.values(value))
}
return longest
}
function utf8Length(text: string): number {
return new TextEncoder().encode(text).byteLength
}
function assertCaps(snapshot: SheetSnapshot): void {
const over = (what: string) => new SnapshotError('caps', `${what} over cap`)
const { document, assets } = snapshot
if (document.views.length > SNAPSHOT_CAPS.views) throw over('views')
if (document.annotations.length > SNAPSHOT_CAPS.annotations) {
throw over('annotations')
}
if (countFindingNodes(document) > SNAPSHOT_CAPS.findingNodes) {
throw over('finding nodes')
}
if (longestName(document) > SNAPSHOT_CAPS.labelChars) throw over('label')
if (assets.length > SNAPSHOT_CAPS.assets) throw over('assets')
const sizes = assets.map((asset) => utf8Length(asset.svg))
if (sizes.some((size) => size > SNAPSHOT_CAPS.assetBytes)) throw over('asset')
const total = sizes.reduce((sum, size) => sum + size, 0)
if (total > SNAPSHOT_CAPS.assetsTotalBytes) throw over('assets total')
}
function assertIntegrity(snapshot: SheetSnapshot): void {
const errors = validateSheetDocument(snapshot.document).filter(
(issue) => issue.severity === 'error',
)
if (errors.length > 0) {
throw new SnapshotError('integrity', errors[0]!.code)
}
const present = new Set(snapshot.assets.map((asset) => asset.svgAssetId))
const views = new Map(snapshot.document.views.map((v) => [v.id, v]))
for (const view of snapshot.document.views) {
const assetId = assetOfView(view, views)
if (assetId === null || !present.has(assetId)) {
throw new SnapshotError('integrity', `view "${view.id}" reaches no asset`)
}
}
}
/**
* The single gate of an imported snapshot, in this order: finding depth on
* the raw input → shape (`schema`) → caps (§15) → sheet integrity rules and
* every view reaching an asset carried by the snapshot (`integrity`).
* Returns the parsed snapshot; throws SnapshotError with the reason.
*/
export function assertSnapshot(snapshot: unknown): SheetSnapshot {
assertFindingDepth(snapshot)
const parsed = SheetSnapshotSchema.safeParse(snapshot)
if (!parsed.success) {
throw new SnapshotError(
'schema',
parsed.error.issues[0]?.message ?? 'invalid',
)
}
assertCaps(parsed.data)
assertIntegrity(parsed.data)
return parsed.data
}
/** Adapter: a snapshot as the sheet index reads it (assets array → record). */
export function snapshotIndexSource(
snapshot: SheetSnapshot,
): SheetIndexSource & { ref: SheetSnapshotRef } {
return {
ref: snapshot.ref,
document: snapshot.document,
assets: Object.fromEntries(
snapshot.assets.map((asset) => [asset.svgAssetId, asset.svg]),
),
}
}
-3
View File
@@ -1,3 +0,0 @@
export * from './anatomical-sheet'
export * from './report'
export * from './archive'
-37
View File
@@ -1,37 +0,0 @@
import { z } from 'zod'
/**
* Identity snapshots carried by every report version: who wrote it, on
* which animal, for which owner. Copied into the report at creation so a
* report stays readable when the underlying records change (BDR-010).
*/
export const PractitionerSchema = z.object({
name: z.string().min(1),
cabinet: z.string().optional(),
contact: z.string().optional(),
/** SIRET, 14-digit French business identifier (not validated). */
siret: z.string().optional(),
})
export type Practitioner = z.infer<typeof PractitionerSchema>
export const AnimalSchema = z.object({
/** Species of the animal; the sheet the report references matches it. */
speciesId: z.string().min(1),
name: z.string().min(1),
breed: z.string().optional(),
age: z.string().optional(),
})
export type Animal = z.infer<typeof AnimalSchema>
export const OwnerSchema = z.object({ name: z.string().min(1) })
export type Owner = z.infer<typeof OwnerSchema>
export const NextAppointmentSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('date'), date: z.string() }),
z.object({ kind: z.literal('period'), text: z.string() }),
])
export type NextAppointment = z.infer<typeof NextAppointmentSchema>
export const LateralSideSchema = z.enum(['left', 'right'])
export type LateralSide = z.infer<typeof LateralSideSchema>
-32
View File
@@ -1,32 +0,0 @@
export * from './identity'
export * from './v3'
export {
FindingV2Schema,
ObservationV2Schema,
ObservationZoneV2Schema,
ReportV2Schema,
SeverityV2Schema,
VertebraV2Schema,
VertebralRegionV2Schema,
type FindingV2,
type ObservationV2,
type ObservationZoneV2,
type ReportV2,
type SeverityV2,
} from './v2'
export {
ReportMigrationMapSchema,
findingPathKey,
type ReportMigrationMap,
} from './migration-map'
export {
migrateReportV2ToV3,
readReportDocument,
UnsupportedReportVersionError,
type MigrationOutcome,
} from './migrate'
export {
rebaseReportOnSheet,
type RebaseIndex,
type RebaseOutcome,
} from './rebase'
-167
View File
@@ -1,167 +0,0 @@
import { findingPathKey, type ReportMigrationMap } from './migration-map'
import {
ReportV2Schema,
type FindingV2,
type ObservationV2,
type ObservationZoneV2,
type ReportV2,
type SeverityV2,
} from './v2'
import {
REPORT_VERSION,
ReportSchema,
type Finding,
type Observation,
type Report,
type ReportZone,
type Severity,
} from './v3'
/**
* Lifts a Report v2 (PDF attachment or sessionStorage draft of the deployed
* application) to v3 against the migration map of the reference sheet.
* Never throws on content: a zone or finding the map cannot place is kept
* verbatim with its snapshots and flagged `unresolved`, so the practitioner's
* data survives any catalog change and stays identifiable.
*/
/** Own-key lookup: ids come from untrusted documents (`__proto__` is not an entry). */
function own<T>(record: Record<string, T>, key: string): T | undefined {
return Object.hasOwn(record, key) ? record[key] : undefined
}
const SEVERITY: Record<SeverityV2, Severity> = {
légère: 'mild',
modérée: 'moderate',
sévère: 'severe',
}
export interface MigrationOutcome {
report: Report
/** Zones whose legacy id has no annotation in the map. */
unresolvedZones: number
/** Findings whose legacy path no longer exists in the sheet. */
unresolvedFindings: number
}
function migrateZone(
zone: ObservationZoneV2,
map: ReportMigrationMap,
): ReportZone {
const entry = own(map.annotations, zone.boneId)
const viewId = zone.detailSourceId
? (own(map.views, zone.detailSourceId) ?? zone.detailSourceId)
: map.main_view_id
const out: ReportZone = { annotationId: entry?.id ?? zone.boneId, viewId }
if (zone.side) out.side = zone.side
if (zone.vertebrae) out.vertebrae = zone.vertebrae.map((v) => ({ ...v }))
if (entry) {
out.labelFrSnapshot = entry.name.fr
out.labelEnSnapshot = entry.name.en
} else {
out.unresolved = true
}
return out
}
function migrateFinding(finding: FindingV2, map: ReportMigrationMap): Finding {
const mapped = own(
map.finding_paths,
findingPathKey(finding.zoneId, finding.path),
)
const out: Finding = {
findingZoneId: finding.zoneId,
path: [...finding.path],
labelFrSnapshot: finding.labelFrSnapshot,
labelEnSnapshot: finding.labelEnSnapshot,
}
if (finding.requiresVetReferral) out.requiresVetReferral = true
if (finding.side) out.side = finding.side
if (typeof mapped === 'string') {
const [zoneId, ...path] = mapped.split('/')
out.findingZoneId = zoneId!
out.path = path
} else {
// null = removed by curation; undefined = never part of the legacy catalog.
out.unresolved = true
}
return out
}
function migrateObservation(
obs: ObservationV2,
map: ReportMigrationMap,
): Observation {
const out: Observation = {
id: obs.id,
zones: obs.zones.map((z) => migrateZone(z, map)),
findings: obs.findings.map((f) => migrateFinding(f, map)),
freeTextFindings: [...obs.freeTextFindings],
comment: obs.comment,
}
if (obs.severity) out.severity = SEVERITY[obs.severity]
return out
}
export function migrateReportV2ToV3(
report: ReportV2,
map: ReportMigrationMap,
): MigrationOutcome {
const observations = report.observations.map((o) =>
migrateObservation(o, map),
)
const migrated: Report = {
version: REPORT_VERSION,
id: report.id,
createdAt: report.createdAt,
date: report.date,
practitioner: report.practitioner,
animal: report.animal,
owner: report.owner,
sheet: { ...map.sheet },
observations,
conclusion: report.conclusion,
recommendations: report.recommendations,
localAnnotations: [],
}
if (report.nextAppointment) migrated.nextAppointment = report.nextAppointment
const zones = observations.flatMap((o) => o.zones)
const findings = observations.flatMap((o) => o.findings)
return {
report: ReportSchema.parse(migrated),
unresolvedZones: zones.filter((z) => z.unresolved).length,
unresolvedFindings: findings.filter((f) => f.unresolved).length,
}
}
/** Thrown for a report whose version this code cannot read. */
export class UnsupportedReportVersionError extends Error {
constructor(public readonly foundVersion: number | null) {
super(`unsupported report version: ${foundVersion ?? 'unknown'}`)
this.name = 'UnsupportedReportVersionError'
}
}
function versionOf(data: unknown): number | null {
if (data === null || typeof data !== 'object') return null
const v = (data as { version?: unknown }).version
return typeof v === 'number' ? v : null
}
/**
* Reads a report document of any supported version (2 or 3) and returns it
* as v3. Zod errors propagate: a document of a known version that does not
* parse is corrupt, not old.
*/
export function readReportDocument(
data: unknown,
map: ReportMigrationMap,
): MigrationOutcome {
const version = versionOf(data)
if (version === REPORT_VERSION) {
const report = ReportSchema.parse(data)
return { report, unresolvedZones: 0, unresolvedFindings: 0 }
}
if (version === 2) return migrateReportV2ToV3(ReportV2Schema.parse(data), map)
throw new UnsupportedReportVersionError(version)
}
@@ -1,40 +0,0 @@
import { z } from 'zod'
import { SheetRefSchema } from './v3'
/**
* Correspondence between the legacy identifiers a Report v2 carries and the
* canonical sheet a Report v3 references. Generated by the curation pipeline
* (`draft/report-migration-map.json`), never written by hand: annotations
* come from the legacy id map, finding paths from the applier's rename and
* removal records. A `null` finding path means "removed from the sheet":
* the migration keeps the finding with its snapshots and flags it.
*/
const LocalizedNameSchema = z.object({ fr: z.string(), en: z.string() })
export const ReportMigrationMapSchema = z.object({
schema_version: z.literal(1),
sheet: SheetRefSchema,
/** Id of the view a v2 zone without `detailSourceId` belongs to. */
main_view_id: z.string().min(1),
/** Legacy detail popup key → view id. */
views: z.record(z.string(), z.string().min(1)),
/** Legacy `data-anno-id` → annotation id and the legacy labels. */
annotations: z.record(
z.string(),
z.object({ id: z.string().min(1), name: LocalizedNameSchema }),
),
/**
* `<zoneId>/<path segments joined by '/'>` of every legacy finding node →
* the same key in the sheet, or null when the node was removed.
*/
finding_paths: z.record(z.string(), z.string().nullable()),
})
export type ReportMigrationMap = z.infer<typeof ReportMigrationMapSchema>
export function findingPathKey(
zoneId: string,
path: readonly string[],
): string {
return `${zoneId}/${path.join('/')}`
}
-137
View File
@@ -1,137 +0,0 @@
import type {
SheetIndex,
SheetIndexSource,
} from '../anatomical-sheet/sheet-index'
import type { Annotation, LocalizedText } from '../anatomical-sheet/schema'
import type { SheetSnapshot } from '../archive/snapshot'
import {
ReportSchema,
type Finding,
type Observation,
type Report,
type ReportZone,
type SheetRef,
} from './v3'
/**
* Moves an imported report onto the sheet the application has loaded
* (STEP6 §3.5). A report written on another revision of the sheet keeps
* every datum: a zone or finding the loaded sheet no longer holds is flagged
* `unresolved`, its labels taken from the archived snapshot when the report
* carries none, and the report now references the loaded sheet. Nothing
* happens when the report already sits on the loaded sheet.
*/
/** An index whose source names its sheet (a loaded sheet or a snapshot). */
export type RebaseIndex = SheetIndex<SheetIndexSource & { ref: SheetRef }>
export interface RebaseOutcome {
report: Report
/** Zones and findings newly flagged by this rebase. */
unresolvedZones: number
unresolvedFindings: number
rebased: boolean
}
interface Counters {
zones: number
findings: number
}
/** The name the archived snapshot gives an annotation (a trigger: its view's). */
function archivedName(
archived: SheetSnapshot | null,
annotationId: string,
): LocalizedText | undefined {
if (!archived) return undefined
const annotation: Annotation | undefined = archived.document.annotations.find(
(a) => a.id === annotationId,
)
if (!annotation) return undefined
if (annotation.kind !== 'detail_trigger') return annotation.name
const view = archived.document.views.find(
(v) => v.id === annotation.opens_view_id,
)
return annotation.name ?? view?.name
}
function flagZone(
zone: ReportZone,
archived: SheetSnapshot | null,
): ReportZone {
const out: ReportZone = { ...zone, unresolved: true }
const name = archivedName(archived, zone.annotationId)
if (name) {
out.labelFrSnapshot ??= name.fr
out.labelEnSnapshot ??= name.en
}
return out
}
function rebaseZone(
zone: ReportZone,
index: RebaseIndex,
archived: SheetSnapshot | null,
counters: Counters,
): ReportZone {
if (zone.unresolved) return { ...zone }
const known =
index.annotation(zone.annotationId) !== undefined &&
index.view(zone.viewId) !== undefined
if (known) return { ...zone }
counters.zones += 1
return flagZone(zone, archived)
}
function rebaseFinding(
finding: Finding,
index: RebaseIndex,
counters: Counters,
): Finding {
if (finding.unresolved) return { ...finding }
if (index.nodeAt(finding.findingZoneId, finding.path)) return { ...finding }
counters.findings += 1
return { ...finding, unresolved: true }
}
function rebaseObservation(
observation: Observation,
index: RebaseIndex,
archived: SheetSnapshot | null,
counters: Counters,
): Observation {
return {
...observation,
zones: observation.zones.map((z) =>
rebaseZone(z, index, archived, counters),
),
findings: observation.findings.map((f) =>
rebaseFinding(f, index, counters),
),
}
}
export function rebaseReportOnSheet(
report: Report,
index: RebaseIndex,
archived: SheetSnapshot | null,
): RebaseOutcome {
if (report.sheet.documentSha256 === index.sheet.ref.documentSha256) {
return { report, unresolvedZones: 0, unresolvedFindings: 0, rebased: false }
}
const counters: Counters = { zones: 0, findings: 0 }
const { sheetId, versionId, documentSha256 } = index.sheet.ref
const rebased: Report = {
...report,
sheet: { sheetId, versionId, documentSha256 },
observations: report.observations.map((o) =>
rebaseObservation(o, index, archived, counters),
),
}
return {
report: ReportSchema.parse(rebased),
unresolvedZones: counters.zones,
unresolvedFindings: counters.findings,
rebased: true,
}
}
-72
View File
@@ -1,72 +0,0 @@
import { z } from 'zod'
import {
AnimalSchema,
LateralSideSchema,
NextAppointmentSchema,
OwnerSchema,
PractitionerSchema,
} from './identity'
/**
* Report document version 2, exactly as the deployed application wrote it
* (PDF attachments of the practitioner's archive, sessionStorage drafts).
* Kept as an INPUT format only: nothing writes v2 any more, `migrate.ts`
* lifts it to v3. Field comments describe the legacy meaning.
*/
export const SeverityV2Schema = z.enum(['légère', 'modérée', 'sévère'])
export type SeverityV2 = z.infer<typeof SeverityV2Schema>
export const VertebralRegionV2Schema = z.enum(['C', 'T', 'L', 'S', 'Cd'])
export const VertebraV2Schema = z.object({
region: VertebralRegionV2Schema,
index: z.number().int().positive(),
})
export const ObservationZoneV2Schema = z.object({
/** The legacy SVG `data-anno-id` (e.g. `point-mpbwtst0`). */
boneId: z.string().min(1),
/** Legacy detail popup key (`head`) when the zone came from that view. */
detailSourceId: z.string().optional(),
vertebrae: z.array(VertebraV2Schema).optional(),
side: LateralSideSchema.optional(),
})
export type ObservationZoneV2 = z.infer<typeof ObservationZoneV2Schema>
export const FindingV2Schema = z.object({
/** Legacy catalog zone key (equal to the canonical finding zone id). */
zoneId: z.string().min(1),
/** Node ids from the zone's categories down to the leaf. */
path: z.array(z.string().min(1)).min(1),
labelFrSnapshot: z.string().min(1),
labelEnSnapshot: z.string().min(1),
requiresVetReferral: z.boolean().optional(),
side: LateralSideSchema.optional(),
})
export type FindingV2 = z.infer<typeof FindingV2Schema>
export const ObservationV2Schema = z.object({
id: z.string().min(1),
zones: z.array(ObservationZoneV2Schema),
findings: z.array(FindingV2Schema),
freeTextFindings: z.array(z.string()),
severity: SeverityV2Schema.optional(),
comment: z.string(),
})
export type ObservationV2 = z.infer<typeof ObservationV2Schema>
export const ReportV2Schema = z.object({
version: z.literal(2),
id: z.string().min(1),
createdAt: z.string(),
date: z.string(),
practitioner: PractitionerSchema,
animal: AnimalSchema,
owner: OwnerSchema,
observations: z.array(ObservationV2Schema),
conclusion: z.string(),
recommendations: z.string(),
nextAppointment: NextAppointmentSchema.optional(),
})
export type ReportV2 = z.infer<typeof ReportV2Schema>
-97
View File
@@ -1,97 +0,0 @@
import { z } from 'zod'
import {
AnimalSchema,
LateralSideSchema,
NextAppointmentSchema,
OwnerSchema,
PractitionerSchema,
} from './identity'
/**
* Report document version 3: a report written on the canonical anatomical
* sheet. Zones name an annotation of a view of an exact sheet, findings a
* node path of a finding zone, both by stable ids; every label the report
* needs to stay readable without the sheet is snapshotted. Breaking change
* → version 4; additive optional fields keep the version.
*/
export const REPORT_VERSION = 3
export const SeveritySchema = z.enum(['mild', 'moderate', 'severe'])
export type Severity = z.infer<typeof SeveritySchema>
/** Region codes are the sheet's `vertebral_config` codes, checked at runtime. */
export const VertebraSchema = z.object({
region: z.string().min(1),
index: z.number().int().positive(),
})
export type Vertebra = z.infer<typeof VertebraSchema>
/** The sheet document a report was built on, by content. */
export const SheetRefSchema = z.object({
sheetId: z.string().min(1),
/** Database version id once the sheet lives in the database; null for a bundled draft. */
versionId: z.string().min(1).nullable(),
/** sha256 of the document file the report was written against. */
documentSha256: z.string().regex(/^[0-9a-f]{64}$/),
})
export type SheetRef = z.infer<typeof SheetRefSchema>
export const ReportZoneSchema = z.object({
annotationId: z.string().min(1),
viewId: z.string().min(1),
side: LateralSideSchema.optional(),
vertebrae: z.array(VertebraSchema).optional(),
/** Annotation name at selection time (or legacy name at migration). */
labelFrSnapshot: z.string().optional(),
labelEnSnapshot: z.string().optional(),
/** Set by the migration when the legacy id has no canonical annotation. */
unresolved: z.literal(true).optional(),
})
export type ReportZone = z.infer<typeof ReportZoneSchema>
export const FindingSchema = z.object({
findingZoneId: z.string().min(1),
/** Node ids from the zone's categories down to the leaf. */
path: z.array(z.string().min(1)).min(1),
labelFrSnapshot: z.string().min(1),
labelEnSnapshot: z.string().min(1),
requiresVetReferral: z.boolean().optional(),
side: LateralSideSchema.optional(),
/** Set by the migration when the path no longer exists in the sheet; data kept. */
unresolved: z.literal(true).optional(),
})
export type Finding = z.infer<typeof FindingSchema>
export const ObservationSchema = z.object({
id: z.string().min(1),
zones: z.array(ReportZoneSchema),
findings: z.array(FindingSchema),
freeTextFindings: z.array(z.string()),
severity: SeveritySchema.optional(),
comment: z.string(),
})
export type Observation = z.infer<typeof ObservationSchema>
export const ReportSchema = z.object({
version: z.literal(REPORT_VERSION),
id: z.string().min(1),
/** ISO timestamp of report creation. */
createdAt: z.string(),
/** ISO date of the clinical encounter. */
date: z.string(),
practitioner: PractitionerSchema,
animal: AnimalSchema,
owner: OwnerSchema,
sheet: SheetRefSchema,
observations: z.array(ObservationSchema),
conclusion: z.string(),
recommendations: z.string(),
nextAppointment: NextAppointmentSchema.optional(),
/** Reserved for report-only points (OPEN_QUESTIONS Q6); empty until defined. */
localAnnotations: z.array(z.unknown()).max(0).default([]),
})
export type Report = z.infer<typeof ReportSchema>
export type ReportInput = z.input<typeof ReportSchema>
export type { LateralSide, NextAppointment } from './identity'
@@ -1,169 +0,0 @@
import {
AnatomicalSheetDocumentSchema,
FindingNodeSchema,
StableIdSchema,
type AnatomicalSheetDocumentInput,
} from '../src'
import { horseSlice, horseSliceInput } from './fixtures/horse-slice'
type Tree = Record<string, unknown>
type Mutation = (doc: Tree) => void
/** Walks `path` inside a JSON tree; mutations break the typed shape on purpose. */
function at(doc: Tree, path: (string | number)[]): Tree {
return path.reduce<Tree>((node, key) => node[key] as Tree, doc)
}
function set(doc: Tree, path: (string | number)[], value: unknown): void {
at(doc, path.slice(0, -1))[String(path.at(-1))] = value
}
function unset(doc: Tree, path: (string | number)[]): void {
delete at(doc, path.slice(0, -1))[String(path.at(-1))]
}
/** Applies a mutation to the lean fixture and reports whether it parses. */
function parsesAfter(mutate: Mutation): boolean {
const doc = horseSliceInput() as unknown as Tree
mutate(doc)
return AnatomicalSheetDocumentSchema.safeParse(doc).success
}
describe('AnatomicalSheetDocumentSchema', () => {
it('accepts the horse slice fixture', () => {
const result = AnatomicalSheetDocumentSchema.safeParse(horseSliceInput())
expect(result.success).toBe(true)
})
it('accepts a parsed document again (output is valid input)', () => {
expect(AnatomicalSheetDocumentSchema.parse(horseSlice())).toEqual(
horseSlice(),
)
})
const rejections: Array<[string, Mutation]> = [
['an unknown top-level key', (d) => set(d, ['extra'], true)],
['an unknown nested key', (d) => set(d, ['views', 0, 'zoom'], 2)],
[
'a stable id with spaces',
(d) => set(d, ['annotations', 0, 'id'], 'Hip Joint'),
],
['a stable id with an accent', (d) => set(d, ['categories', 0, 'id'], 'É')],
['an empty stable id', (d) => set(d, ['finding_zones', 0, 'id'], '')],
['schema_version 1', (d) => set(d, ['schema_version'], 1)],
[
'a non-uuid svg_asset_id',
(d) => set(d, ['views', 0, 'svg_asset_id'], 'horse'),
],
[
'a polygon with 2 points',
(d) =>
set(
d,
['annotations', 1, 'geometry', 'points'],
[
[0, 0],
[1, 1],
],
),
],
[
'a circle with r 0',
(d) => set(d, ['annotations', 0, 'geometry', 'r'], 0),
],
[
'a region count of 0',
(d) => set(d, ['vertebral_config', 'regions', 0, 'count'], 0),
],
['a missing en label', (d) => unset(d, ['name', 'en'])],
[
'a detail view without parent_view_id',
(d) => unset(d, ['views', 1, 'parent_view_id']),
],
[
'a detail_trigger with finding_zone_id',
(d) => set(d, ['annotations', 3, 'finding_zone_id'], 'hip'),
],
[
'a javascript: reference url',
(d) => set(d, ['references', 0, 'url'], 'javascript:alert(1)'),
],
[
'a reference type foo',
(d) => set(d, ['references', 0, 'type'], 'foo'),
],
[
'a review_status foo',
(d) => set(d, ['annotations', 0, 'review_status'], 'foo'),
],
[
'a count_range with min 0',
(d) =>
set(d, ['vertebral_config', 'regions', 4, 'count_range', 'min'], 0),
],
[
'a finding category kind foo',
(d) => set(d, ['finding_zones', 0, 'categories', 0, 'kind'], 'foo'),
],
]
it.each(rejections)('rejects %s', (_label, mutate) => {
expect(parsesAfter(mutate)).toBe(false)
})
})
describe('StableIdSchema', () => {
it.each(['hip', 'c7-t1', 'view_main', '0'])('accepts %s', (id) => {
expect(StableIdSchema.safeParse(id).success).toBe(true)
})
it.each(['Hip Joint', 'É', '', '-hip', 'a'.repeat(65)])(
'rejects %j',
(id) => {
expect(StableIdSchema.safeParse(id).success).toBe(false)
},
)
})
describe('FindingNodeSchema defaults', () => {
it('fills the optional keys of a lean node, recursively', () => {
const node = FindingNodeSchema.parse({
id: 'articular',
name: { fr: 'Articulaire', en: 'Articular' },
children: [{ id: 'flexion', name: { fr: 'Flexion', en: 'Flexion' } }],
})
expect(node.description).toEqual({})
expect(node.requires_vet_referral).toBe(false)
expect(node.reference_ids).toEqual([])
expect(node.review_status).toBe('inherited')
expect(node.children[0]).toEqual({
id: 'flexion',
name: { fr: 'Flexion', en: 'Flexion' },
description: {},
requires_vet_referral: false,
reference_ids: [],
review_status: 'inherited',
children: [],
})
})
it('keeps explicit values of the fixture', () => {
const doc = horseSlice()
const lameness = doc.finding_zones[0].categories[1].children[0]
expect(lameness.requires_vet_referral).toBe(true)
const trauma = doc.finding_zones[0].categories[2].children[0]
expect(trauma.reference_ids).toEqual(['legacy-catalog'])
expect(doc.vertebral_config.regions[4].count_range).toEqual({
min: 15,
max: 21,
})
expect(doc.vertebral_config.regions[0].count_range).toBeNull()
expect(doc.annotations[0].review_status).toBe('inherited')
})
it('does not add default keys to the lean input', () => {
const input: AnatomicalSheetDocumentInput = horseSliceInput()
const leaf = input.finding_zones[2].categories[0].children[0]
expect(Object.keys(leaf)).toEqual(['id', 'name'])
})
})
@@ -1,473 +0,0 @@
import {
AnatomicalSheetDocumentSchema,
SheetValidationError,
assertPublishable,
createEmptySheetDocument,
isPublishable,
validateSheetDocument,
type AnatomicalSheetDocument,
type Annotation,
type SheetView,
} from '../src'
import { HORSE_MAIN_ASSET_ID, horseSlice } from './fixtures/horse-slice'
/** [code, path] pairs: what each rule test pins down. */
function issuesOf(doc: AnatomicalSheetDocument): Array<[string, string]> {
return validateSheetDocument(doc).map((issue) => [issue.code, issue.path])
}
function mutated(
mutate: (doc: AnatomicalSheetDocument) => void,
): AnatomicalSheetDocument {
const doc = horseSlice()
mutate(doc)
return doc
}
function point(id: string, fields: Partial<Annotation> = {}): Annotation {
return {
id,
kind: 'point',
view_id: 'view-main',
category_id: 'articulations',
laterality: 'bilateral',
geometry: null,
review_status: 'inherited',
color: null,
name: { fr: id, en: id },
finding_zone_id: 'hip',
vertebral_region_code: null,
...fields,
} as Annotation
}
function trigger(id: string, viewId: string, opensViewId: string) {
return {
id,
kind: 'detail_trigger',
view_id: viewId,
category_id: 'cadrans-du-crane',
laterality: 'unpaired',
geometry: null,
review_status: 'inherited',
color: null,
name: null,
opens_view_id: opensViewId,
} satisfies Annotation
}
function detailView(id: string, parentId: string) {
return {
id,
kind: 'detail',
name: { fr: id, en: id },
parent_view_id: parentId,
svg_asset_id: HORSE_MAIN_ASSET_ID,
view_box: null,
} satisfies SheetView
}
describe('validateSheetDocument on the horse slice', () => {
it('reports no error and no warning', () => {
expect(validateSheetDocument(horseSlice())).toEqual([])
})
})
describe('integrity rules (one mutation per code)', () => {
it('view.main.count', () => {
const doc = mutated((d) => {
d.views.push({ ...d.views[0], id: 'view-alt' })
})
expect(issuesOf(doc)).toEqual([['view.main.count', 'views']])
})
it('view.main.count with no main view', () => {
const doc = mutated((d) => {
d.views = d.views.filter((view) => view.kind !== 'main')
})
const codes = issuesOf(doc).map(([code]) => code)
expect(codes).toContain('view.main.count')
})
it('view.id.duplicate', () => {
const doc = mutated((d) => {
d.views.push(structuredClone(d.views[1]))
})
expect(issuesOf(doc)).toEqual([['view.id.duplicate', 'views[2].id']])
})
it('view.parent.missing', () => {
const doc = mutated((d) => {
d.views.push(detailView('view-orphan', 'view-ghost'))
})
expect(issuesOf(doc)).toEqual([
['view.parent.missing', 'views[2].parent_view_id'],
])
})
it('view.parent.cycle (terminates on a two-view loop)', () => {
const doc = mutated((d) => {
d.views.push(detailView('view-a', 'view-b'))
d.views.push(detailView('view-b', 'view-a'))
d.annotations.push(trigger('open-a', 'view-b', 'view-a'))
d.annotations.push(trigger('open-b', 'view-a', 'view-b'))
})
expect(issuesOf(doc)).toEqual([
['view.parent.cycle', 'views[2].parent_view_id'],
['view.parent.cycle', 'views[3].parent_view_id'],
])
})
it('view.parent.cycle on a self-parent', () => {
const doc = mutated((d) => {
d.views.push(detailView('view-self', 'view-self'))
d.annotations.push(trigger('open-self', 'view-self', 'view-self'))
})
expect(issuesOf(doc)).toEqual([
['view.parent.cycle', 'views[2].parent_view_id'],
])
})
it('view.unreachable', () => {
const doc = mutated((d) => {
d.annotations = d.annotations.filter((a) => a.id !== 'head-trigger')
})
expect(issuesOf(doc)).toEqual([['view.unreachable', 'views[1]']])
})
it('view.asset.missing on the main view', () => {
const doc = mutated((d) => {
d.views[0].svg_asset_id = null
})
expect(issuesOf(doc)).toEqual([
['view.asset.missing', 'views[0].svg_asset_id'],
])
})
it('view.asset.missing on a detail view without asset nor view_box', () => {
const doc = mutated((d) => {
d.views[1].view_box = null
})
expect(issuesOf(doc)).toEqual([['view.asset.missing', 'views[1].view_box']])
})
it('annotation.id.duplicate (across views)', () => {
const doc = mutated((d) => {
d.annotations.push({ ...structuredClone(d.annotations[4]) })
d.annotations[6].view_id = 'view-main'
})
expect(issuesOf(doc)).toEqual([
['annotation.id.duplicate', 'annotations[6].id'],
])
})
it('annotation.view.missing', () => {
const doc = mutated((d) => {
d.annotations.push(point('ghost', { view_id: 'view-ghost' }))
})
expect(issuesOf(doc)).toEqual([
['annotation.view.missing', 'annotations[6].view_id'],
])
})
it('annotation.category.missing', () => {
const doc = mutated((d) => {
d.annotations[0].category_id = 'os'
})
expect(issuesOf(doc)).toEqual([
['annotation.category.missing', 'annotations[0].category_id'],
])
})
it('annotation.opens_view.invalid when the target is not a child', () => {
const doc = mutated((d) => {
d.annotations.push(trigger('loop', 'view-head', 'view-head'))
})
expect(issuesOf(doc)).toEqual([
['annotation.opens_view.invalid', 'annotations[6].opens_view_id'],
])
})
it('annotation.opens_view.invalid when the target is main or absent', () => {
const doc = mutated((d) => {
d.annotations.push(trigger('to-main', 'view-main', 'view-main'))
d.annotations.push(trigger('to-ghost', 'view-main', 'view-ghost'))
})
expect(issuesOf(doc)).toEqual([
['annotation.opens_view.invalid', 'annotations[6].opens_view_id'],
['annotation.opens_view.invalid', 'annotations[7].opens_view_id'],
])
})
it('annotation.finding_zone.missing', () => {
const doc = mutated((d) => {
d.annotations.push(point('stifle', { finding_zone_id: 'stifle' }))
})
expect(issuesOf(doc)).toEqual([
['annotation.finding_zone.missing', 'annotations[6].finding_zone_id'],
])
})
it('annotation.region.missing', () => {
const doc = mutated((d) => {
const cervical = d.annotations[1]
if (cervical.kind === 'detail_trigger') throw new Error('fixture')
cervical.vertebral_region_code = 'Q'
})
expect(issuesOf(doc)).toEqual([
['annotation.region.missing', 'annotations[1].vertebral_region_code'],
])
})
it('annotation.no_findings is a warning', () => {
const doc = mutated((d) => {
d.annotations.push(point('mandible', { finding_zone_id: null }))
})
expect(issuesOf(doc)).toEqual([
['annotation.no_findings', 'annotations[6].finding_zone_id'],
])
expect(validateSheetDocument(doc)[0].severity).toBe('warning')
})
it('region.code.duplicate', () => {
const doc = mutated((d) => {
const regions = d.vertebral_config.regions
regions.push(structuredClone(regions[0]))
})
expect(issuesOf(doc)).toEqual([
['region.code.duplicate', 'vertebral_config.regions[5].code'],
])
})
it('category.id.duplicate', () => {
const doc = mutated((d) => {
d.categories.push(structuredClone(d.categories[0]))
})
expect(issuesOf(doc)).toEqual([
['category.id.duplicate', 'categories[4].id'],
])
})
it('finding_zone.id.duplicate', () => {
const doc = mutated((d) => {
d.finding_zones.push(structuredClone(d.finding_zones[0]))
})
expect(issuesOf(doc)).toEqual([
['finding_zone.id.duplicate', 'finding_zones[5].id'],
])
})
it('finding.id.duplicate among finding categories', () => {
const doc = mutated((d) => {
const categories = d.finding_zones[0].categories
categories.push(structuredClone(categories[0]))
})
expect(issuesOf(doc)).toEqual([
['finding.id.duplicate', 'finding_zones[0].categories[3].id'],
])
})
it('finding.id.duplicate among nested children', () => {
const doc = mutated((d) => {
const articular = d.finding_zones[0].categories[0].children[0]
articular.children.push(structuredClone(articular.children[0]))
})
expect(issuesOf(doc)).toEqual([
[
'finding.id.duplicate',
'finding_zones[0].categories[0].children[0].children[2].id',
],
])
})
it('finding ids may repeat across different sibling arrays', () => {
const doc = mutated((d) => {
const hip = d.finding_zones[0].categories
hip[1].children.push(structuredClone(hip[0].children[0]))
})
expect(issuesOf(doc)).toEqual([])
})
it('reference.id.duplicate', () => {
const doc = mutated((d) => {
d.references.push(structuredClone(d.references[0]))
})
expect(issuesOf(doc)).toEqual([
['reference.id.duplicate', 'references[1].id'],
])
})
it('finding.reference.missing on a category and on a nested node', () => {
const doc = mutated((d) => {
const hip = d.finding_zones[0].categories
hip[0].reference_ids = ['nav-2017']
hip[0].children[0].children[0].reference_ids = ['legacy-catalog', 'x']
})
expect(issuesOf(doc)).toEqual([
[
'finding.reference.missing',
'finding_zones[0].categories[0].reference_ids[0]',
],
[
'finding.reference.missing',
'finding_zones[0].categories[0].children[0].children[0].reference_ids[1]',
],
])
})
it('region.count_range.invalid when count sits outside the range', () => {
const doc = mutated((d) => {
d.vertebral_config.regions[4].count_range = { min: 19, max: 21 }
})
expect(issuesOf(doc)).toEqual([
['region.count_range.invalid', 'vertebral_config.regions[4].count_range'],
])
})
it('region.count_range accepts count on the bounds', () => {
const doc = mutated((d) => {
d.vertebral_config.regions[4].count_range = { min: 18, max: 18 }
})
expect(issuesOf(doc)).toEqual([])
})
it('finding_zone.unreferenced is a warning', () => {
const doc = mutated((d) => {
d.finding_zones.push({
id: 'stifle',
name: { fr: 'Grasset', en: 'Stifle' },
categories: [],
})
})
expect(issuesOf(doc)).toEqual([
['finding_zone.unreferenced', 'finding_zones[5]'],
])
expect(validateSheetDocument(doc)[0].severity).toBe('warning')
})
})
describe('publication gate', () => {
it('accepts the fixture', () => {
expect(isPublishable(validateSheetDocument(horseSlice()))).toBe(true)
expect(() => assertPublishable(horseSlice())).not.toThrow()
})
it('accepts a document with warnings only', () => {
const doc = mutated((d) => {
d.annotations.push(point('mandible', { finding_zone_id: null }))
})
expect(validateSheetDocument(doc)).toHaveLength(1)
expect(isPublishable(validateSheetDocument(doc))).toBe(true)
expect(() => assertPublishable(doc)).not.toThrow()
})
it('refuses a document with an error, exposing the issues', () => {
const doc = mutated((d) => {
d.views[0].svg_asset_id = null
})
expect(isPublishable(validateSheetDocument(doc))).toBe(false)
let caught: unknown
try {
assertPublishable(doc)
} catch (thrown) {
caught = thrown
}
expect(caught).toBeInstanceOf(SheetValidationError)
const codes = (caught as SheetValidationError).issues.map((i) => i.code)
expect(codes).toEqual(['view.asset.missing'])
})
})
describe('createEmptySheetDocument', () => {
const empty = () =>
createEmptySheetDocument({
species_id: 'equine',
name: { fr: 'Nouvelle fiche', en: 'New sheet' },
})
it('is valid for the shape tier', () => {
expect(AnatomicalSheetDocumentSchema.safeParse(empty()).success).toBe(true)
expect(empty().views).toEqual([
expect.objectContaining({
id: 'view-main',
kind: 'main',
svg_asset_id: null,
view_box: null,
}),
])
})
it('is not publishable: the main view has no asset', () => {
const issues = validateSheetDocument(empty())
expect(issues.map((issue) => issue.code)).toEqual(['view.asset.missing'])
expect(() => assertPublishable(empty())).toThrow(SheetValidationError)
})
})
/** True for a { fr?, en? } label object, the only thing a translator edits. */
function isLabel(value: unknown): value is Record<string, string> {
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
return false
}
const keys = Object.keys(value)
return keys.length > 0 && keys.every((key) => key === 'fr' || key === 'en')
}
/** Rewrites every label with arbitrary strings, leaving all else intact. */
function mapLabels(
value: unknown,
rewrite: (label: Record<string, string>) => unknown,
): unknown {
if (isLabel(value)) return rewrite(value)
if (Array.isArray(value)) return value.map((v) => mapLabels(v, rewrite))
if (value === null || typeof value !== 'object') return value
return Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, mapLabels(v, rewrite)]),
)
}
/** Every id and reference: values of keys named id, *_id or code. */
function collectIds(value: unknown, out: string[] = []): string[] {
if (Array.isArray(value)) value.forEach((v) => collectIds(v, out))
else if (value !== null && typeof value === 'object') {
for (const [key, v] of Object.entries(value)) {
const isRef = key === 'id' || key.endsWith('_id') || key.endsWith('code')
if (isRef && typeof v === 'string') out.push(`${key}=${v}`)
else collectIds(v, out)
}
}
return out
}
describe('ID stability under translation', () => {
it('keeps ids, references and validation output when labels change', () => {
const original = horseSlice()
let counter = 0
const relabeled = AnatomicalSheetDocumentSchema.parse(
mapLabels(original, (label) =>
Object.fromEntries(
Object.keys(label).map((locale) => [locale, `x${counter++}`]),
),
),
)
expect(counter).toBeGreaterThan(50)
expect(JSON.stringify(relabeled)).not.toEqual(JSON.stringify(original))
expect(collectIds(relabeled)).toEqual(collectIds(original))
const strip = () => null
expect(mapLabels(relabeled, strip)).toEqual(mapLabels(original, strip))
expect(validateSheetDocument(relabeled)).toEqual(
validateSheetDocument(original),
)
})
it('keeps validation output identical on a broken document too', () => {
const broken = mutated((d) => {
d.annotations[0].category_id = 'os'
d.views[1].view_box = null
})
const relabeled = mapLabels(broken, () => ({ fr: 'a', en: 'b' }))
expect(validateSheetDocument(relabeled as AnatomicalSheetDocument)).toEqual(
validateSheetDocument(broken),
)
})
})
@@ -1,178 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
BrandingSchema,
PDF_LABEL_KEYS,
PdfLabelSetSchema,
type Branding,
type PdfLabels,
} from '../src'
export function sampleBranding(): Branding {
return {
siteUrl: 'https://faunosteo.com',
headerLogo: { kind: 'png', base64: 'iVBORw0KGgo=' },
footerLogo: null,
poweredBy: {
logo: null,
url: 'https://zenquality.fr',
fallbackText: 'zenquality.fr',
},
partner: {
logo: { kind: 'svg', svg: '<svg xmlns="http://www.w3.org/2000/svg"/>' },
url: 'https://www.instagram.com/paws.iin.harmony',
fallbackText: '@paws.iin.harmony',
},
}
}
export function sampleLabels(): PdfLabels {
return Object.fromEntries(
PDF_LABEL_KEYS.map((key) => [key, key]),
) as PdfLabels
}
describe('BrandingSchema', () => {
it('accepts the current identity and both image kinds', () => {
expect(BrandingSchema.parse(sampleBranding())).toEqual(sampleBranding())
const bare = {
siteUrl: 'http://localhost:5173',
headerLogo: null,
footerLogo: null,
poweredBy: null,
partner: null,
}
expect(BrandingSchema.parse(bare)).toEqual(bare)
})
it.each([
['unknown key', (b: Branding) => ({ ...b, extra: 1 })],
[
'non-http URL',
(b: Branding) => ({ ...b, siteUrl: 'javascript:alert(1)' }),
],
['ftp URL', (b: Branding) => ({ ...b, siteUrl: 'ftp://x.test/a' })],
[
'URL over 2048 chars',
(b: Branding) => ({
...b,
siteUrl: `https://x.test/${'a'.repeat(2048)}`,
}),
],
[
'PNG base64 over 512 KiB',
(b: Branding) => ({
...b,
headerLogo: { kind: 'png', base64: 'A'.repeat(512 * 1024 + 4) },
}),
],
[
'PNG base64 with foreign characters',
(b: Branding) => ({
...b,
headerLogo: { kind: 'png', base64: '<svg/>' },
}),
],
[
'SVG over 256 KiB',
(b: Branding) => ({
...b,
footerLogo: { kind: 'svg', svg: 'x'.repeat(256 * 1024 + 1) },
}),
],
[
'fallback text over 128 chars',
(b: Branding) => ({
...b,
poweredBy: { ...b.poweredBy!, fallbackText: 'x'.repeat(129) },
}),
],
[
'credit with unknown key',
(b: Branding) => ({ ...b, partner: { ...b.partner!, extra: true } }),
],
])('rejects %s', (_name, mutate) => {
expect(BrandingSchema.safeParse(mutate(sampleBranding())).success).toBe(
false,
)
})
})
/** Closes a PDF `(` string literal and chains an action: must never reach the engine. */
const INJECTION_URL =
'https://a.example/) /Next << /S /JavaScript /JS (app.alert\\(1\\)) >> /Z ('
describe('BrandingSchema URLs', () => {
it.each([
'https://faunosteo.com',
'https://zenquality.fr',
'https://www.instagram.com/paws.iin.harmony',
'http://localhost:5173',
'https://x.test/a-b_c~d?e=1&f=2#frag',
`https://x.test/${'a'.repeat(2048 - 'https://x.test/'.length)}`,
])('accepts %s', (url) => {
const branding = { ...sampleBranding(), siteUrl: url }
expect(BrandingSchema.safeParse(branding).success).toBe(true)
})
it.each([
['a closing parenthesis', 'https://a.example/)'],
['an opening parenthesis', 'https://a.example/('],
['a PDF action injection', INJECTION_URL],
['a backslash', 'https://a.example/a\\b'],
['a space', 'https://a.example/a b'],
['a tab', 'https://a.example/a\tb'],
['a control character', 'https://a.example/a\u0001b'],
['DEL', 'https://a.example/a\u007fb'],
['an angle bracket', 'https://a.example/<x>'],
['a double quote', 'https://a.example/"x'],
['a single quote', "https://a.example/'x"],
['a non-ASCII character', 'https://a.example/é'],
['no host', 'https://'],
['a scheme in upper case', 'HTTPS://a.example/'],
])('rejects %s in the site URL and in a credit URL', (_name, url) => {
const site = { ...sampleBranding(), siteUrl: url }
expect(BrandingSchema.safeParse(site).success).toBe(false)
const base = sampleBranding()
const credit = { ...base, partner: { ...base.partner!, url } }
expect(BrandingSchema.safeParse(credit).success).toBe(false)
})
})
describe('PdfLabelSetSchema', () => {
it('lists 25 distinct keys and accepts a complete set in both locales', () => {
expect(PDF_LABEL_KEYS).toHaveLength(25)
expect(new Set(PDF_LABEL_KEYS).size).toBe(25)
const set = { fr: sampleLabels(), en: sampleLabels() }
expect(PdfLabelSetSchema.parse(set)).toEqual(set)
})
it('rejects a missing key, an extra key, a long value, a missing locale', () => {
const missing: Partial<PdfLabels> = sampleLabels()
delete missing['pdf.empty']
expect(
PdfLabelSetSchema.safeParse({ fr: missing, en: sampleLabels() }).success,
).toBe(false)
expect(
PdfLabelSetSchema.safeParse({
fr: { ...sampleLabels(), 'pdf.extra': 'x' },
en: sampleLabels(),
}).success,
).toBe(false)
expect(
PdfLabelSetSchema.safeParse({
fr: { ...sampleLabels(), 'pdf.subject': 'x'.repeat(257) },
en: sampleLabels(),
}).success,
).toBe(false)
expect(PdfLabelSetSchema.safeParse({ fr: sampleLabels() }).success).toBe(
false,
)
expect(
PdfLabelSetSchema.safeParse({
fr: sampleLabels(),
en: sampleLabels(),
de: sampleLabels(),
}).success,
).toBe(false)
})
})
@@ -1,211 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
ENVELOPE_FORMAT,
ENVELOPE_VERSION,
ReportArchiveEnvelopeSchema,
UnsupportedReportVersionError,
buildSheetSnapshot,
migrateReportV2ToV3,
readArchiveDocument,
readReportDocument,
type ReportArchiveEnvelope,
} from '../src'
import fullV2 from './fixtures/report-v2.full.json'
import { sampleBranding, sampleLabels } from './archive.branding-labels.test'
import { loadDraftSheet } from './helpers/draft-sheet'
import {
leavesAsV2Report,
legacyLeaves,
loadLegacyBaseline,
} from './helpers/legacy-leaves'
const draft = loadDraftSheet()
const map = draft.migrationMap
const { report } = readReportDocument(fullV2, map)
/** A fresh envelope as JSON.parse of an attachment would give it. */
function envelope(): ReportArchiveEnvelope {
const env: ReportArchiveEnvelope = {
format: ENVELOPE_FORMAT,
envelopeVersion: ENVELOPE_VERSION,
exportedAt: '2026-10-11T10:00:00.000Z',
locale: 'fr',
report,
sheetSnapshot: buildSheetSnapshot(draft, report),
branding: sampleBranding(),
labels: { fr: sampleLabels(), en: sampleLabels() },
}
return JSON.parse(JSON.stringify(env)) as ReportArchiveEnvelope
}
type Raw = Record<string, unknown>
const raw = (env: ReportArchiveEnvelope): Raw => env as unknown as Raw
describe('readArchiveDocument: bare reports', () => {
it('reads a bare v3 as is', () => {
const outcome = readArchiveDocument(JSON.parse(JSON.stringify(report)), map)
expect(outcome).toEqual({
report,
origin: 'bare_v3',
migrated: false,
unresolvedZones: 0,
unresolvedFindings: 0,
archive: null,
})
})
it('migrates a bare v2 with the counts of the migration', () => {
const outcome = readArchiveDocument(fullV2, map)
expect(outcome.origin).toBe('v2')
expect(outcome.migrated).toBe(true)
expect(outcome.archive).toBeNull()
expect(outcome.report).toEqual(report)
expect(outcome.snapshotRejected).toBeUndefined()
const leaves = leavesAsV2Report(legacyLeaves(loadLegacyBaseline()))
const expected = migrateReportV2ToV3(leaves, map)
const migrated = readArchiveDocument(leaves, map)
expect(expected.unresolvedFindings).toBeGreaterThan(0)
expect(migrated.unresolvedFindings).toBe(expected.unresolvedFindings)
expect(migrated.unresolvedZones).toBe(expected.unresolvedZones)
expect(migrated.report).toEqual(expected.report)
})
it('throws for a report version it cannot read, or a non-object', () => {
expect(() => readArchiveDocument({ ...report, version: 1 }, map)).toThrow(
UnsupportedReportVersionError,
)
for (const data of [null, undefined, 'report', 42, [report]]) {
expect(() => readArchiveDocument(data, map)).toThrow(
UnsupportedReportVersionError,
)
}
})
})
describe('readArchiveDocument: envelopes', () => {
it('accepts a valid v1 envelope whole', () => {
const env = envelope()
const outcome = readArchiveDocument(env, map)
expect(outcome.origin).toBe('envelope_v1')
expect(outcome.migrated).toBe(false)
expect(outcome.unresolvedZones).toBe(0)
expect(outcome.snapshotRejected).toBeUndefined()
expect(outcome.report).toEqual(report)
expect(outcome.archive).toEqual(env)
expect(ReportArchiveEnvelopeSchema.parse(env)).toEqual(env)
})
it('keeps the report of an envelope version it does not know', () => {
const outcome = readArchiveDocument(
{ ...envelope(), envelopeVersion: 2 },
map,
)
expect(outcome.report).toEqual(report)
expect(outcome.origin).toBe('bare_v3')
expect(outcome.archive).toBeNull()
expect(outcome.snapshotRejected).toBe('unsupported_envelope')
})
it('names the report version when the wrapped report is unknown', () => {
const env = raw(envelope())
env.report = { ...report, version: 4 }
let thrown: unknown
try {
readArchiveDocument(env, map)
} catch (error) {
thrown = error
}
expect(thrown).toBeInstanceOf(UnsupportedReportVersionError)
expect((thrown as UnsupportedReportVersionError).foundVersion).toBe(4)
})
it('ignores unknown metadata keys, __proto__ included, within v1', () => {
const env = raw(envelope())
env.futureField = { anything: true }
const outcome = readArchiveDocument(env, map)
expect(outcome.archive).not.toBeNull()
expect('futureField' in outcome.archive!).toBe(false)
const text = JSON.stringify(envelope()).replace(
'"format"',
'"__proto__":{"polluted":true},"format"',
)
const polluted = readArchiveDocument(JSON.parse(text), map)
expect(polluted.archive).not.toBeNull()
expect(({} as { polluted?: boolean }).polluted).toBeUndefined()
expect(Object.hasOwn(polluted.archive!, '__proto__')).toBe(false)
})
it('drops the envelope on a wrapper fault (schema): branding, labels, metadata', () => {
const branding = raw(envelope())
branding.branding = { ...sampleBranding(), siteUrl: 'javascript:alert(1)' }
expect(readArchiveDocument(branding, map)).toMatchObject({
report,
origin: 'envelope_v1',
archive: null,
snapshotRejected: 'schema',
})
const labels = raw(envelope())
labels.labels = { fr: sampleLabels() }
expect(readArchiveDocument(labels, map).snapshotRejected).toBe('schema')
const locale = raw(envelope())
locale.locale = 'de'
expect(readArchiveDocument(locale, map).snapshotRejected).toBe('schema')
const format = raw(envelope())
format.format = 'other'
expect(readArchiveDocument(format, map).snapshotRejected).toBe('schema')
})
it('drops a snapshot over the caps or failing its own schema', () => {
const caps = envelope()
caps.sheetSnapshot.document.name.fr = 'x'.repeat(513)
expect(readArchiveDocument(caps, map)).toMatchObject({
report,
archive: null,
snapshotRejected: 'caps',
})
const schema = raw(envelope())
schema.sheetSnapshot = { ...envelope().sheetSnapshot, extra: 1 }
expect(readArchiveDocument(schema, map).snapshotRejected).toBe('schema')
const missing = raw(envelope())
delete missing.sheetSnapshot
expect(readArchiveDocument(missing, map).snapshotRejected).toBe('schema')
const integrity = envelope()
integrity.sheetSnapshot.assets = []
expect(readArchiveDocument(integrity, map).snapshotRejected).toBe(
'integrity',
)
})
it('drops a snapshot of another sheet than the report (sheet_mismatch)', () => {
const sha = envelope()
sha.sheetSnapshot.ref.documentSha256 = 'f'.repeat(64)
expect(readArchiveDocument(sha, map)).toMatchObject({
report,
origin: 'envelope_v1',
archive: null,
snapshotRejected: 'sheet_mismatch',
})
const id = envelope()
id.sheetSnapshot.ref.sheetId = 'another-sheet'
expect(readArchiveDocument(id, map).snapshotRejected).toBe('sheet_mismatch')
})
it('migrates a v2 report found inside an envelope and still checks the snapshot', () => {
const env = raw(envelope())
env.report = fullV2
const outcome = readArchiveDocument(env, map)
expect(outcome.origin).toBe('envelope_v1')
expect(outcome.migrated).toBe(true)
expect(outcome.report).toEqual(report)
expect(outcome.archive?.report).toEqual(report)
})
})
@@ -1,366 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
AnatomicalSheetDocumentSchema,
REPORT_VERSION,
SNAPSHOT_CAPS,
SnapshotError,
assertSnapshot,
buildSheetIndex,
buildSheetSnapshot,
readReportDocument,
snapshotIndexSource,
validateSheetDocument,
type Report,
type SheetSnapshot,
type SnapshotRejection,
type SnapshotSource,
} from '../src'
import { HORSE_MAIN_ASSET_ID, horseSlice } from './fixtures/horse-slice'
import fullV2 from './fixtures/report-v2.full.json'
import { loadDraftSheet } from './helpers/draft-sheet'
import {
leavesAsV2Report,
legacyLeaves,
loadLegacyBaseline,
} from './helpers/legacy-leaves'
const SHA = 'b'.repeat(64)
const HASH = 'c'.repeat(64)
const SVG = '<svg xmlns="http://www.w3.org/2000/svg"></svg>'
function sliceSource(): SnapshotSource {
return {
status: 'draft',
ref: { sheetId: 'sheet-1', versionId: null, documentSha256: SHA },
speciesId: 'equine',
schemaVersion: 2,
document: horseSlice(),
assets: { [HORSE_MAIN_ASSET_ID]: SVG },
assetHashes: { [HORSE_MAIN_ASSET_ID]: HASH },
}
}
function sliceReport(): Report {
return {
version: REPORT_VERSION,
id: 'r1',
createdAt: '2026-10-10T10:00:00Z',
date: '2026-10-10',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
sheet: { sheetId: 'sheet-1', versionId: null, documentSha256: SHA },
observations: [
{
id: 'obs-1',
zones: [{ annotationId: 'hip', viewId: 'view-main' }],
findings: [
{
findingZoneId: 'hip',
path: ['hip-dysfunctions', 'articular', 'restriction-flexion'],
labelFrSnapshot: 'Restriction en flexion',
labelEnSnapshot: 'Flexion restriction',
},
{
findingZoneId: 'hip',
path: ['hip-dysfunctions', 'articular', 'ghost-leaf'],
labelFrSnapshot: 'Disparu',
labelEnSnapshot: 'Gone',
unresolved: true,
},
{
findingZoneId: 'sphenoid',
path: ['ssb-dysfunctions', 'physiological', 'torsion-right'],
labelFrSnapshot: 'Torsion droite',
labelEnSnapshot: 'Right torsion',
},
],
freeTextFindings: [],
comment: '',
},
],
conclusion: '',
recommendations: '',
localAnnotations: [],
}
}
function sliceSnapshot(): SheetSnapshot {
return buildSheetSnapshot(sliceSource(), sliceReport())
}
function rejection(input: unknown): SnapshotRejection | 'accepted' {
try {
assertSnapshot(input)
return 'accepted'
} catch (error) {
if (error instanceof SnapshotError) return error.reason
throw error
}
}
describe('buildSheetSnapshot on the equine draft', () => {
const draft = loadDraftSheet()
const { report } = readReportDocument(fullV2, draft.migrationMap)
const snapshot = buildSheetSnapshot(draft, report)
it('keeps every view, annotation, category and region, empties the bibliography', () => {
expect(snapshot.document.views).toEqual(draft.document.views)
expect(snapshot.document.annotations).toEqual(draft.document.annotations)
expect(snapshot.document.categories).toEqual(draft.document.categories)
expect(snapshot.document.vertebral_config).toEqual(
draft.document.vertebral_config,
)
expect(snapshot.document.references).toEqual([])
expect(snapshot.document.name).toEqual(draft.document.name)
expect(snapshot.document.scope_disclaimer).toEqual(
draft.document.scope_disclaimer,
)
expect(snapshot.document.attribution).toEqual(draft.document.attribution)
expect(snapshot.document.species_id).toBe('equine')
expect(snapshot.document.schema_version).toBe(2)
})
it('prunes finding trees to the paths the report uses, every zone kept', () => {
expect(snapshot.document.finding_zones.map((z) => z.id)).toEqual(
draft.document.finding_zones.map((z) => z.id),
)
const c7 = snapshot.document.finding_zones.find((z) => z.id === 'c7-t1')!
expect(c7.categories).toHaveLength(1)
expect(c7.categories[0]).toMatchObject({
id: 'c7-t1-dysfunctions',
kind: 'dysfunction',
description: {},
reference_ids: [],
})
expect(c7.categories[0]!.children.map((n) => n.id)).toEqual(['segmental'])
expect(c7.categories[0]!.children[0]!.children).toMatchObject([
{ id: 'fixation', description: {}, reference_ids: [], children: [] },
])
const used = new Set(
report.observations.flatMap((o) =>
o.findings.map((f) => f.findingZoneId),
),
)
for (const zone of snapshot.document.finding_zones) {
if (!used.has(zone.id)) expect(zone.categories, zone.id).toEqual([])
else expect(zone.categories.length, zone.id).toBeGreaterThan(0)
}
})
it('carries the reachable asset with its manifest hash and the full ref', () => {
const [assetId] = Object.keys(draft.assets)
expect(snapshot.assets).toEqual([
{
svgAssetId: assetId,
sha256: draft.assetHashes[assetId!],
svg: draft.assets[assetId!],
},
])
expect(snapshot.ref).toEqual({
...draft.ref,
schemaVersion: 2,
speciesId: 'equine',
})
expect(snapshot.status).toBe('draft')
})
it('is a valid document with no integrity error, under 250,000 bytes pretty-printed', () => {
expect(() =>
AnatomicalSheetDocumentSchema.parse(snapshot.document),
).not.toThrow()
const errors = validateSheetDocument(snapshot.document).filter(
(i) => i.severity === 'error',
)
expect(errors).toEqual([])
const bytes = Buffer.byteLength(JSON.stringify(snapshot, null, 2), 'utf8')
console.log(
`snapshot (report-v2.full on the draft, pretty JSON): ${bytes} bytes`,
)
expect(bytes).toBeLessThan(250_000)
expect(assertSnapshot(snapshot)).toEqual(snapshot)
})
it('is pure and deterministic', () => {
const before = JSON.stringify(draft.document)
const again = buildSheetSnapshot(draft, report)
expect(JSON.stringify(draft.document)).toBe(before)
expect(again).toEqual(snapshot)
expect(again.document.views).not.toBe(draft.document.views)
})
it('keeps what exists of an unresolved path and nothing else (legacy leaves)', () => {
const v2 = leavesAsV2Report(legacyLeaves(loadLegacyBaseline()))
const migrated = readReportDocument(v2, draft.migrationMap)
expect(migrated.unresolvedFindings).toBeGreaterThan(0)
const snap = buildSheetSnapshot(draft, migrated.report)
expect(assertSnapshot(snap)).toEqual(snap)
const index = buildSheetIndex(snapshotIndexSource(snap))
const findings = migrated.report.observations.flatMap((o) => o.findings)
for (const finding of findings) {
const node = index.nodeAt(finding.findingZoneId, finding.path)
if (finding.unresolved)
expect(node, finding.path.join('/')).toBeUndefined()
else expect(node, finding.path.join('/')).toBeDefined()
}
expect(index.sheet.ref.sheetId).toBe(draft.ref.sheetId)
expect(index.sheet.assets[snap.assets[0]!.svgAssetId]).toBe(
snap.assets[0]!.svg,
)
})
})
describe('buildSheetSnapshot on the slice', () => {
it('copies review_status and requires_vet_referral, skips an asset it has no text for', () => {
const snapshot = sliceSnapshot()
const hip = snapshot.document.finding_zones.find((z) => z.id === 'hip')!
expect(hip.categories.map((c) => c.id)).toEqual(['hip-dysfunctions'])
expect(hip.categories[0]!.review_status).toBe('inherited')
expect(hip.categories[0]!.children[0]!.children.map((n) => n.id)).toEqual([
'restriction-flexion',
])
const sphenoid = snapshot.document.finding_zones.find(
(z) => z.id === 'sphenoid',
)!
expect(sphenoid.categories[0]!.children[0]!.children[0]).toMatchObject({
id: 'torsion-right',
requires_vet_referral: false,
})
expect(snapshot.assets).toEqual([
{ svgAssetId: HORSE_MAIN_ASSET_ID, sha256: HASH, svg: SVG },
])
const noHash = { ...sliceSource(), assetHashes: undefined }
expect(
buildSheetSnapshot(noHash, sliceReport()).assets[0]!.sha256,
).toBeNull()
const noSvg = { ...sliceSource(), assets: {} }
expect(buildSheetSnapshot(noSvg, sliceReport()).assets).toEqual([])
})
})
describe('assertSnapshot', () => {
it('accepts the slice snapshot and returns the parsed copy', () => {
const snapshot = sliceSnapshot()
const parsed = assertSnapshot(JSON.parse(JSON.stringify(snapshot)))
expect(parsed).toEqual(snapshot)
})
it('rejects a finding tree deeper than the cap before parsing anything (caps)', () => {
let node: unknown = { id: 'leaf' }
for (let depth = 0; depth < SNAPSHOT_CAPS.findingDepth; depth += 1) {
node = { id: `n${depth}`, children: [node] }
}
const raw = {
garbage: true,
document: { finding_zones: [{ categories: [node] }] },
}
expect(rejection(raw)).toBe('caps')
const shallow = {
document: { finding_zones: [{ categories: [{ id: 'c' }] }] },
}
expect(rejection(shallow)).toBe('schema')
expect(rejection({ document: { finding_zones: 'x' } })).toBe('schema')
})
it('rejects shape faults (schema): unknown key, missing field, too many assets, non-object', () => {
expect(rejection({ ...sliceSnapshot(), extra: 1 })).toBe('schema')
const noStatus: Partial<SheetSnapshot> = sliceSnapshot()
delete noStatus.status
expect(rejection(noStatus)).toBe('schema')
const many = sliceSnapshot()
many.assets = Array.from({ length: 5 }, (_, i) => ({
svgAssetId: `00000000-0000-4000-8000-00000000000${i}`,
sha256: null,
svg: SVG,
}))
expect(rejection(many)).toBe('schema')
expect(rejection(null)).toBe('schema')
expect(rejection('snapshot')).toBe('schema')
expect(rejection([sliceSnapshot()])).toBe('schema')
})
it('rejects a __proto__ key without polluting anything', () => {
const raw = JSON.parse(
JSON.stringify(sliceSnapshot()).replace(
'"status"',
'"__proto__":{"polluted":1},"status"',
),
)
expect(rejection(raw)).toBe('schema')
expect(({} as { polluted?: number }).polluted).toBeUndefined()
})
it('rejects counts over the caps (caps)', () => {
const views = sliceSnapshot()
views.document.views.push(
...Array.from({ length: SNAPSHOT_CAPS.views }, (_, i) => ({
...views.document.views[1]!,
id: `extra-${i}`,
})),
)
expect(rejection(views)).toBe('caps')
const annotations = sliceSnapshot()
annotations.document.annotations.push(
...Array.from({ length: SNAPSHOT_CAPS.annotations }, (_, i) => ({
...annotations.document.annotations[0]!,
id: `extra-${i}`,
})),
)
expect(rejection(annotations)).toBe('caps')
const nodes = sliceSnapshot()
const category = nodes.document.finding_zones[0]!.categories[0]!
category.children = Array.from(
{ length: SNAPSHOT_CAPS.findingNodes },
(_, i) => ({
id: `leaf-${i}`,
name: { fr: 'x', en: 'x' },
description: {},
requires_vet_referral: false,
reference_ids: [],
review_status: 'inherited',
children: [],
}),
)
expect(rejection(nodes)).toBe('caps')
const label = sliceSnapshot()
label.document.name.fr = 'x'.repeat(SNAPSHOT_CAPS.labelChars + 1)
expect(rejection(label)).toBe('caps')
})
it('rejects oversize assets in bytes, single and total (caps)', () => {
const big = sliceSnapshot()
// 1.1M two-byte code points: under the schema's char cap, over 2 MiB.
big.assets[0]!.svg = 'é'.repeat(1_100_000)
expect(rejection(big)).toBe('caps')
const total = sliceSnapshot()
total.assets = Array.from({ length: 4 }, (_, i) => ({
svgAssetId:
i === 0
? HORSE_MAIN_ASSET_ID
: `00000000-0000-4000-8000-00000000000${i}`,
sha256: null,
svg: 'a'.repeat(1_600_000),
}))
expect(rejection(total)).toBe('caps')
})
it('rejects integrity faults: a sheet rule error, a view reaching no carried asset', () => {
const rule = sliceSnapshot()
rule.document.finding_zones = rule.document.finding_zones.filter(
(z) => z.id !== 'atm',
)
expect(rejection(rule)).toBe('integrity')
const noAsset = sliceSnapshot()
noAsset.assets = []
expect(rejection(noAsset)).toBe('integrity')
const otherAsset = sliceSnapshot()
otherAsset.assets[0]!.svgAssetId = '00000000-0000-4000-8000-000000000009'
expect(rejection(otherAsset)).toBe('integrity')
})
})
-447
View File
@@ -1,447 +0,0 @@
import {
AnatomicalSheetDocumentSchema,
type AnatomicalSheetDocument,
type AnatomicalSheetDocumentInput,
type FindingNodeInput,
} from '../../src'
/**
* Reduced equine sheet built from the real assets: labels come from
* apps/app/public/species/equine/{Horse,Horse_head}.svg and from
* apps/app/src/domain/species/equine/pathologies.json. It exercises two
* views (one cropped detail), a trigger, a spine region, a bilateral joint,
* the three finding kinds, a two-level tree, a vet referral and a source.
* It references every finding zone, so it validates with zero issues.
*/
export const HORSE_MAIN_ASSET_ID = '3f6c1b52-8a4e-4d17-9b0c-5e2a7d91c4f8'
function leaf(id: string, fr: string, en: string): FindingNodeInput {
return { id, name: { fr, en } }
}
const ANAMNESIS = {
id: 'anamnesis',
kind: 'anamnesis',
name: {
fr: 'Anamnèse / facteurs rapportés',
en: 'Anamnesis / reported factors',
},
description: {
fr: "Facteurs rapportés par le propriétaire lors de l'anamnèse",
},
} as const
const OBSERVATIONS_NAME = {
fr: 'Observations / motifs de consultation',
en: 'Observations / consultation reasons',
}
const DYSFUNCTIONS_NAME = {
fr: 'Dysfonctions ostéopathiques',
en: 'Osteopathic dysfunctions',
}
const TRAUMA = leaf(
'trauma-direct',
'Traumatisme rapporté (choc, chute)',
'Reported trauma (blow, fall)',
)
const STRESS = leaf(
'stress-context',
'Contexte de stress / changement',
'Stress / change context',
)
const HIP_ZONE = {
id: 'hip',
name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' },
categories: [
{
id: 'hip-dysfunctions',
kind: 'dysfunction',
name: DYSFUNCTIONS_NAME,
children: [
{
id: 'articular',
name: {
fr: 'Restrictions de mobilité articulaire',
en: 'Articular mobility restrictions',
},
children: [
leaf(
'restriction-flexion',
'Restriction en flexion',
'Flexion restriction',
),
leaf(
'restriction-extension',
'Restriction en extension',
'Extension restriction',
),
],
},
],
},
{
id: 'hip-observations',
kind: 'consultation_reason',
name: OBSERVATIONS_NAME,
children: [
{
...leaf(
'limb-lameness',
'Boiterie rapportée (membre concerné)',
'Reported lameness (affected limb)',
),
requires_vet_referral: true,
},
],
},
{
...ANAMNESIS,
children: [
{ ...TRAUMA, reference_ids: ['legacy-catalog'] },
],
},
],
} satisfies AnatomicalSheetDocumentInput['finding_zones'][number]
const CERVICAL_ZONE = {
id: 'cervical',
name: { fr: 'Vertèbres cervicales', en: 'Cervical Vertebrae' },
categories: [
{
id: 'cervical-dysfunctions',
kind: 'dysfunction',
name: DYSFUNCTIONS_NAME,
children: [
{
id: 'muscular',
name: {
fr: 'Tensions musculaires paravertébrales',
en: 'Paravertebral muscle tensions',
},
children: [
leaf('splenius-tension', 'Tension du splénius', 'Splenius tension'),
],
},
],
},
{
id: 'cervical-observations',
kind: 'consultation_reason',
name: OBSERVATIONS_NAME,
children: [
{
...leaf(
'stumbling-proprioceptive',
'Trébuchements / déficit proprioceptif rapporté',
'Reported stumbling / proprioceptive deficit',
),
requires_vet_referral: true,
},
],
},
{ ...ANAMNESIS, children: [TRAUMA] },
],
} satisfies AnatomicalSheetDocumentInput['finding_zones'][number]
const C7_T1_ZONE = {
id: 'c7-t1',
name: {
fr: 'Charnière C7-T1 (cervico-thoracique)',
en: 'C7-T1 (Cervicothoracic)',
},
categories: [
{
id: 'c7-t1-dysfunctions',
kind: 'dysfunction',
name: DYSFUNCTIONS_NAME,
children: [
leaf(
'restriction-rotation',
'Restriction en rotation',
'Rotation restriction',
),
],
},
{
id: 'c7-t1-observations',
kind: 'consultation_reason',
name: OBSERVATIONS_NAME,
children: [
leaf(
'base-neck-stiffness',
"Raideur de la base de l'encolure",
'Base-of-neck stiffness',
),
],
},
{ ...ANAMNESIS, children: [STRESS] },
],
} satisfies AnatomicalSheetDocumentInput['finding_zones'][number]
const ATM_ZONE = {
id: 'atm',
name: {
fr: 'Articulation Temporo-Mandibulaire (ATM)',
en: 'Temporomandibular Joint (TMJ)',
},
categories: [
{
id: 'atm-dysfunctions',
kind: 'dysfunction',
name: {
fr: "Dysfonctions ostéopathiques de l'ATM",
en: 'Osteopathic TMJ dysfunctions',
},
children: [
leaf('masseter-tension', 'Tension du masséter', 'Masseter tension'),
],
},
{
id: 'atm-observations',
kind: 'consultation_reason',
name: OBSERVATIONS_NAME,
children: [
leaf(
'bit-defense',
'Réactions de défense au mors',
'Defense reactions to bit',
),
],
},
{
...ANAMNESIS,
children: [
leaf(
'dental-context',
'Suite de soin dentaire récent',
'Post recent dental care',
),
],
},
],
} satisfies AnatomicalSheetDocumentInput['finding_zones'][number]
const SPHENOID_ZONE = {
id: 'sphenoid',
name: { fr: 'Sphénoïde', en: 'Sphenoid' },
categories: [
{
id: 'ssb-dysfunctions',
kind: 'dysfunction',
name: DYSFUNCTIONS_NAME,
children: [
{
id: 'physiological',
name: {
fr: 'Lésions physiologiques (SSB)',
en: 'Physiological lesions (SBS)',
},
children: [
leaf('torsion-right', 'Torsion droite', 'Right torsion'),
leaf('torsion-left', 'Torsion gauche', 'Left torsion'),
],
},
],
},
{
id: 'sphenoid-observations',
kind: 'consultation_reason',
name: OBSERVATIONS_NAME,
children: [
leaf(
'post-trauma-head',
'Suite de traumatisme crânien',
'Post head trauma',
),
],
},
{ ...ANAMNESIS, children: [TRAUMA, STRESS] },
],
} satisfies AnatomicalSheetDocumentInput['finding_zones'][number]
const HORSE_SLICE_INPUT: AnatomicalSheetDocumentInput = {
schema_version: 2,
species_id: 'equine',
name: { fr: 'Cheval (extrait)', en: 'Horse (slice)' },
description: {
fr: 'Extrait de la fiche équine pour les tests du modèle',
en: 'Equine sheet slice for model tests',
},
scope_disclaimer: {
fr:
"Les éléments listés correspondent au périmètre légal de l'ostéopathie " +
'animale : dysfonctions ostéopathiques palpées, observations cliniques ' +
"et motifs de consultation. Aucun diagnostic médical n'est posé. " +
'Toute pathologie organique relève du vétérinaire.',
},
attribution: { authors: ['Faunosteo'], license: 'MIT', notes: null },
vertebral_config: {
regions: [
{ code: 'C', name: { fr: 'Cervicales', en: 'Cervical' }, count: 7 },
{ code: 'T', name: { fr: 'Thoraciques', en: 'Thoracic' }, count: 18 },
{ code: 'L', name: { fr: 'Lombaires', en: 'Lumbar' }, count: 6 },
{ code: 'S', name: { fr: 'Sacrées', en: 'Sacral' }, count: 5 },
{
code: 'Cd',
name: { fr: 'Caudales', en: 'Caudal' },
count: 18,
count_range: { min: 15, max: 21 },
},
],
},
references: [
{
id: 'legacy-catalog',
type: 'manual',
citation: 'Legacy equine catalog (pathologies.json, schema 2.0)',
},
],
categories: [
{
id: 'articulations',
name: { fr: 'Articulations', en: 'Joints' },
color: '#ff9500',
},
{
id: 'zone-colonne',
name: { fr: 'Zone colonne', en: 'Spine zone' },
color: '#e100ff',
},
{
id: 'charnieres-vertebrales',
name: { fr: 'Charnières vertébrales', en: 'Vertebral junctions' },
color: '#ff0000',
},
{
id: 'cadrans-du-crane',
name: { fr: 'Cadrans du crâne', en: 'Skull quadrants' },
color: '#1baa08',
},
],
views: [
{
id: 'view-main',
kind: 'main',
name: { fr: 'Cheval entier', en: 'Whole horse' },
svg_asset_id: HORSE_MAIN_ASSET_ID,
view_box: null,
},
{
id: 'view-head',
kind: 'detail',
name: { fr: 'Tête', en: 'Head' },
parent_view_id: 'view-main',
svg_asset_id: null,
view_box: { min_x: 60, min_y: 100, width: 500, height: 380 },
},
],
annotations: [
{
id: 'hip',
kind: 'point',
view_id: 'view-main',
category_id: 'articulations',
laterality: 'bilateral',
geometry: { type: 'circle', cx: 1516, cy: 695, r: 34 },
name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' },
finding_zone_id: 'hip',
vertebral_region_code: null,
},
{
id: 'cervical-vertebrae',
kind: 'zone',
view_id: 'view-main',
category_id: 'zone-colonne',
laterality: 'unpaired',
geometry: {
type: 'polygon',
points: [
[468, 276],
[489, 216],
[558, 248],
[586, 339],
[552, 461],
[524, 370],
],
},
name: { fr: 'Vertèbres cervicales', en: 'Cervical Vertebrae' },
finding_zone_id: 'cervical',
vertebral_region_code: 'C',
},
{
id: 'hinge-c7-t1',
kind: 'point',
view_id: 'view-main',
category_id: 'charnieres-vertebrales',
laterality: 'unpaired',
geometry: { type: 'circle', cx: 840.17, cy: 399.08, r: 30 },
name: {
fr: 'Charnière C7-T1 (cervico-thoracique)',
en: 'C7-T1 (Cervicothoracic)',
},
finding_zone_id: 'c7-t1',
vertebral_region_code: null,
},
{
id: 'head-trigger',
kind: 'detail_trigger',
view_id: 'view-main',
category_id: 'cadrans-du-crane',
laterality: 'unpaired',
geometry: {
type: 'polygon',
points: [
[454, 332],
[429, 202],
[349, 154],
[234, 279],
[164, 384],
[234, 468],
],
},
name: null,
opens_view_id: 'view-head',
},
{
id: 'atm',
kind: 'point',
view_id: 'view-head',
category_id: 'articulations',
laterality: 'bilateral',
geometry: { type: 'circle', cx: 384.94, cy: 314.02, r: 27 },
name: {
fr: 'Articulation Temporo-Mandibulaire (ATM)',
en: 'Temporomandibular Joint (TMJ)',
},
finding_zone_id: 'atm',
vertebral_region_code: null,
},
{
id: 'sphenoid',
kind: 'point',
view_id: 'view-head',
category_id: 'cadrans-du-crane',
laterality: 'unpaired',
geometry: { type: 'circle', cx: 299, cy: 298, r: 27 },
name: { fr: 'Sphénoïde', en: 'Sphenoid' },
finding_zone_id: 'sphenoid',
vertebral_region_code: null,
},
],
finding_zones: [HIP_ZONE, CERVICAL_ZONE, C7_T1_ZONE, ATM_ZONE, SPHENOID_ZONE],
}
/** Lean authoring form, as a creator or the importer would write it. */
export function horseSliceInput(): AnatomicalSheetDocumentInput {
return structuredClone(HORSE_SLICE_INPUT)
}
/** Parsed (total) document; a fresh copy so tests can mutate it freely. */
export function horseSlice(): AnatomicalSheetDocument {
return AnatomicalSheetDocumentSchema.parse(horseSliceInput())
}
@@ -1,73 +0,0 @@
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { join, resolve } from 'node:path'
import {
AnatomicalSheetDocumentSchema,
ReportMigrationMapSchema,
type ReportMigrationMap,
type SnapshotSource,
} from '../../src'
/**
* The committed equine draft (`pnpm import:equine`) as the application
* bundles it: document, reference, SVG assets and their manifest hashes,
* plus the v2 → v3 migration map. Read from the seed, never copied.
*/
export const DRAFT_DIR = resolve(
fileURLToPath(import.meta.url),
'../../../../../supabase/seed/anatomical-sheets/equine/draft',
)
interface SeedRef {
sheet_id: string
version_id: string | null
document_sha256: string
schema_version: number
species_id: string
}
interface SeedAsset {
file: string
sha256: string
svg_asset_id: string
}
function json<T>(name: string): T {
return JSON.parse(readFileSync(join(DRAFT_DIR, name), 'utf8')) as T
}
export interface DraftSheet extends SnapshotSource {
assetHashes: Readonly<Record<string, string>>
migrationMap: ReportMigrationMap
}
export function loadDraftSheet(): DraftSheet {
const ref = json<SeedRef>('sheet-ref.json')
const manifest = json<SeedAsset[]>('assets.json')
const assets: Record<string, string> = {}
const assetHashes: Record<string, string> = {}
for (const asset of manifest) {
assets[asset.svg_asset_id] = readFileSync(
join(DRAFT_DIR, 'assets', asset.file),
'utf8',
)
assetHashes[asset.svg_asset_id] = asset.sha256
}
return {
status: 'draft',
ref: {
sheetId: ref.sheet_id,
versionId: ref.version_id,
documentSha256: ref.document_sha256,
},
speciesId: ref.species_id,
schemaVersion: ref.schema_version,
document: AnatomicalSheetDocumentSchema.parse(json('document.json')),
assets,
assetHashes,
migrationMap: ReportMigrationMapSchema.parse(
json('report-migration-map.json'),
),
}
}
@@ -1,95 +0,0 @@
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { resolve } from 'node:path'
import {
AnatomicalSheetDocumentSchema,
ReportV2Schema,
type AnatomicalSheetDocument,
type FindingCategory,
type FindingNode,
type ObservationV2,
type ReportV2,
} from '../../src'
/**
* The legacy catalog as the application's archive knew it: every leaf of the
* generated baseline (`legacy-import/document.json`) becomes a Report v2
* finding, grouped in one observation per zone. Same recipe as the app and
* anatomy helpers; migrated through the draft map it yields the unresolved
* items (sphenoid / ssb leaves) a Phase 0 golden was frozen with.
*/
const BASELINE = resolve(
fileURLToPath(import.meta.url),
'../../../../../supabase/seed/anatomical-sheets/equine/legacy-import/document.json',
)
export interface LegacyLeaf {
zoneId: string
path: string[]
name: { fr: string; en: string }
vet: boolean
}
export function loadLegacyBaseline(): AnatomicalSheetDocument {
return AnatomicalSheetDocumentSchema.parse(
JSON.parse(readFileSync(BASELINE, 'utf8')),
)
}
export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] {
const out: LegacyLeaf[] = []
const walk = (
zoneId: string,
nodes: readonly (FindingCategory | FindingNode)[],
prefix: string[],
) => {
for (const node of nodes) {
const path = [...prefix, node.id]
if (node.children.length > 0) walk(zoneId, node.children, path)
else {
const vet =
'requires_vet_referral' in node && node.requires_vet_referral
out.push({ zoneId, path, name: node.name, vet })
}
}
}
for (const zone of doc.finding_zones) walk(zone.id, zone.categories, [])
return out
}
export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
const byZone = new Map<string, ObservationV2>()
for (const leaf of leaves) {
let obs = byZone.get(leaf.zoneId)
if (!obs) {
obs = {
id: `obs-${leaf.zoneId}`,
zones: [],
findings: [],
freeTextFindings: [],
comment: '',
}
byZone.set(leaf.zoneId, obs)
}
obs.findings.push({
zoneId: leaf.zoneId,
path: leaf.path,
labelFrSnapshot: leaf.name.fr,
labelEnSnapshot: leaf.name.en || leaf.name.fr,
...(leaf.vet ? { requiresVetReferral: true } : {}),
})
}
return ReportV2Schema.parse({
version: 2,
id: 'all-leaves',
createdAt: '2026-10-10T00:00:00Z',
date: '2026-10-10',
practitioner: { name: 'Synthetic' },
animal: { speciesId: 'equine', name: 'Synthetic' },
owner: { name: 'Synthetic' },
observations: [...byZone.values()],
conclusion: '',
recommendations: '',
})
}
File diff suppressed because it is too large. Load diff
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more