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 = '' 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 = 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') }) })