feat(domain): R2.1 Rust contracts of the sheet, report and archive documents

Sheet document v2, report v3 / v2 / identity, migration map, sheet snapshot,
branding, PDF labels and archive envelope ported from the Zod schemas with
their exact semantics: strict objects where Zod is strict, optional fields
absent (never null), nullable fields required, integers as JavaScript
numbers, UTF-16 caps, hand-checked patterns, url crate for .url(), lone
surrogate escapes read as U+FFFD (L1, owner confirmation pending).
Fields in Zod schema order (PDF labels in the engine dictionary order):
the curated and legacy sheets, the demo report and the three frozen
archive envelopes print byte for byte as their Zod / attachment form.
ts-rs types regenerated; plan rev 2 after three plan challenges.
This commit is contained in:
bchanot committed 2026-10-14 00:04:01 +02:00
1 parent 3114d67959
commit ee0700887f
87 files changed
+2657 -148

No files matched your search

+10
View File
@@ -164,6 +164,16 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [ ] R0.11 follow-ups for the CI/CD step (owner): ci.yml push/PR triggers stay live, so registering a runner starts PR builds at once (keep, or switch to workflow_dispatch until then); `actions/*@v4` mutable tags (Step 27); advisories cadence while no nightly runs (`cargo deny check advisories` is warn-only in check:all); `--remap-path-prefix` if native and builder wasm must match byte for byte
- [x] R1 = Step 8 worker in Rust (delivered 2026-10-13 on feature/step-08-files-foundation, see Step 8 block; awaiting owner validation): decode child dispatched before any thread, empty env, RLIMIT_AS/CPU, traced seccomp allowlist, `image` + `moxcms` + `libwebp-sys` in the child, parent RIFF-header check only, 512 KiB output cap, per-stage deadlines, service key
- [ ] R2 domain core (before Step 9): sheet/report/archive contracts, `SheetHandle` + `SheetIndexData`, reducers, Finding builder, vertebra selection, publish gate; wasm facade (JSON strings, ts-rs types, poison + reinstantiate, lazy init); app switched; 3 envelopes frozen first; N-1 reader test; draft quarantine; conformance fixtures + generated pgTAP; `packages/domain` frozen for engine/pipeline
- plan + contract: `.claude/tasks/plans/2026-10-13-rust-r2-domain-core.md` (rev 2 after 3 challenges, 45 findings folded); branch `feature/rust-r2-domain-core`; owner wording of the 4 new strings validated 2026-10-13
- [x] R2.0 freeze: 3 archive envelopes (demo, v2full, v2unresolved; FR, no logos, fixed time) + verbatim N-1 Zod copy (`packages/core-wasm/tests/n-1`) (3114d67); Zod output oracles of the reference documents (`crates/core/tests/oracles`)
- [ ] R2.0b characterisation set of the TS quirks (migrate, rebase, reducers, numeric literals, surrogates) + hostile-input verdict table per constraint site
- [ ] R2.1 Rust contracts: js semantics, sheet, report v2/v3/identity/map, snapshot/branding/labels/envelope; ts-rs types; byte-equal on oracles + frozen envelopes
- [ ] R2.2 Rust rules: 21 integrity rules + check, create_empty, index + SheetIndexData, read/migrate, rebase, snapshot build/assert, envelope layered read, draft restore; ported domain suites; conformance fixtures + generated pgTAP 011 + drift test
- [ ] R2.3 Rust editor rules: zone click + reducers, finding toggle, vertebra initial/sync/select, report new/add/remove/move
- [ ] R2.4 facade + runtime: SheetHandle, ops, typed failures; core-wasm runtime (lazy, generation, poison, spare glue, cap 3, retry), Node/browser sources, globalSetup stamp, pkg vs pkg-proofs; trap/load tests; size; checkpoint report to the owner
- [ ] R2.5 app switch: provider/useSheet degraded states, SheetIndex class, store `{ok}` actions, persistence + quarantine, click chain, pickers, finding picker, import/export, Home + /new availability, publish gate fail-closed, ESLint restriction, pickLocaleLabel, deletions; suites green, changed assertions listed
- [ ] R2.6 images + serving: Dockerfile wasm stage, ignores, nginx compression, check:all, CSP proof on the image (Chromium + Firefox/WebKit if present), measurements
- [ ] R2.7 docs (RUST.md R2 + census, CLAUDE.md, WORKSPACE, TEST_STRATEGY, packages/README, DEPLOY note, CHANGELOG), verifier + security gates, memory, LAN manual procedure; STOP (no merge)
- [ ] R3 anatomy core: tree, one sanitiser, serialiser, layer renderer, `compose_view_svg`; app canvas switched; composed views frozen as trees first
- [ ] R4 pdf core: reader (Web Worker, BLK-009 browser measurements) + writer (`pdf-writer`, Std14 AFM, draw log; lines/rects/colours golden frozen with the TS engine first, D-R2) + `report-compare` tool; `packages/pdf` deleted; N-1 scanner reads R4 PDFs
- [ ] R5 curation pipeline + importer + upload tool: seed golden regenerated once (new `documentSha256`, D-R5), `packages/anatomy` + `packages/domain` deleted, docs map; all before Step 13
@@ -0,0 +1,113 @@
# PLAN — Rust R2: domain core (contracts, rules, sheet handle, reducers) + app switch
- date: 2026-10-13 | branch: `feature/rust-r2-domain-core` (off develop 1a7ee7d)
- spec: `docs/development/RUST_ARCHITECTURE_REVIEW.md` (rev 2 + Annex C), rows II.2 / VI.2 R2 / VI.3 R2 / VI.4, decisions D-R11, D-R12 (gated functions ported, behaviour preserved), D-R13; owner brief 2026-10-13 (R2 go)
- out of scope: R3 (sanitiser, layer renderer, compose), R4 (PDF reader byte scan, writer, report-compare CLI), R5 (pipeline, importer, upload tool, `packages/domain` deletion), Step 9, CI/CD, deploy, release 0.2.0, any graphic change
- stop: after R2 delivery; no merge into develop before the owner's validation
## 0. Facts this plan rests on (inventory 2026-10-13)
- `packages/domain` (2,298 lines, 9 test files): sheet schema (strict Zod), 21 integrity rules, `createEmptySheetDocument`, `buildSheetIndex` (10 closures over Maps, last duplicate wins), report v3 / v2 (strip Zod), migration map, `migrateReportV2ToV3`, `readReportDocument`, `rebaseReportOnSheet`, archive snapshot (`buildSheetSnapshot`, `assertSnapshot` with caps, `snapshotIndexSource`), envelope v1 (`readArchiveDocument`, `ReportArchiveEnvelopeSchema`), branding, labels (25 keys).
- Consumers of `packages/domain` after R2: `packages/pdf` (engine, R4), `packages/anatomy` (pipeline + render, R3/R5), `apps/app/scripts` (`report:compare`, R4), N-1 test fixtures. The app `src/` stops importing it (VI.4).
- App logic to move: `services/zoneInteraction.ts` (213 lines: click decision + 7 reducers + `collectVertebrae` / `syncVertebrae`), `FindingsTreePicker.toggleLeaf` (Finding builder), `VertebraPicker` toggle / all / none, `reportStore` rules (`newReport`, `emptyObservation`, add / remove / move / replace), `persistence` parsing (draft via `readReportDocument`, archive via `ReportArchiveEnvelopeSchema`), `sheets/provider` parsing, `pdf/import.ts` layered read (via engine `readReportArchive` = byte scan + `readArchiveDocument`), `pdf/export.ts` `buildSheetSnapshot`, `packages/supabase` publish gate (`assertPublishable`).
- Display helpers kept in TypeScript (review II.2 class C): `zoneLabel`, `describeZone`, `zoneTrees`, `unresolvedFindings`, import message lines, `isIdentityComplete`, `pickLabel`, `FreeTextFindingInput` trimming (form glue), identity / conclusion / recommendations / next-appointment setters (Zustand assignments of form values; no validation exists today, adding one is a behaviour change: deviation from the review's "set_* validation", stated).
- Routes are static imports; `HomeRoute` and `NewReportRoute` call `useSheet` today (the sheet bundle loads on `/`).
- The engine's `readAttachedDocument` returns `JSON.parse` output after a depth pre-scan capped at 64; `readReportArchive` = that + `readArchiveDocument` + error mapping (`incompatible_version` when a numeric unknown version, else `no_attachment`).
- Zod 3.25.76 semantics to reproduce: object output in schema key order; `.optional()` = absent ok, `null` rejected, absent stays absent; `.nullable()` = key required unless `.default(null)`; `.strict()` rejects unknown keys, others strip; `.int()` = `Number.isInteger` (accepts `2.0`, `1e20`); `.min/.max` on strings count UTF-16 units; `.url()` = `new URL()` succeeds; `.uuid()` = Zod regex; JS regex `$` = end of input; discriminated unions dispatch on the tag.
- R0 facts kept: `serde_json` `preserve_order` + `float_roundtrip`, `js_number` formatter, panic = abort on wasm32, an instance is unusable after a trap, a fresh instance needs a fresh glue module record (cache-busting import).
## 1. Decisions of this plan (internal; trade-offs stated)
| # | Decision | Why / alternative rejected |
|---|---|---|
| P1 | Every JSON input is read `text → serde_json::Value → typed`. Before parsing, a pre-pass rewrites `\uD800`–`\uDFFF` escapes that are not a valid surrogate pair to `�` (JSON.parse keeps lone surrogates, serde_json refuses them). Recursion limit 128 (drafts and bundles < 20 deep; archive JSON is pre-scanned at 64 by the TS scanner). | Value-first gives JSON.parse duplicate-key semantics (last value, first position) and lets one parse feed both the layered reader and the typed structs. Refusing lone surrogates would lose a whole report that TypeScript accepts; replacing them is the smallest divergence (leniency decision L1, pinned by a fixture, reported). |
| P2 | Typed structs use serde derive plus field helpers that reproduce Zod: `opt` (absent ok, `null` refused, skipped when `None`), `nullable` (key required, `null` ok), `nullable_default` (absent → `null`), `deny_unknown_fields` exactly where Zod is `.strict()`. Integers are `JsInt` (any finite number with an integer value, kept as f64, printed by `js_number`). Constrained strings are newtypes checked by hand (UTF-16 length, the id / region / colour / sha256 / base64 / uuid / branding-URL patterns). `.url()` = `url` crate parse (WHATWG, as `new URL`), size measured; no `regex` crate. | Serde's implicit `None` for a missing `Option` and its `null`-as-`None` would silently widen what Zod accepts. f64 integers keep `1e20` or `2.0` accepted and printed as JavaScript does. |
| P3 | Discriminated unions (views, annotations, geometry, next appointment, image asset) are untagged enums whose variant structs carry a literal tag field at the Zod schema position (annotations and views: `kind` after the common fields; geometry, next appointment, image asset: tag first). Every struct declares its fields in Zod schema order. | Zod parse output order = schema order; serde's internally tagged enums would print the tag first and break byte equality with `JSON.stringify(ZodSchema.parse(x), null, 2)`, which is the strongest serialisation oracle available. D-R11 (struct order) holds. |
| P4 | Behaviour is ported site by site, quirks included: index maps last-duplicate-wins (as `new Map`), `viewsById` first-wins in the rules, `find` first-wins for `spineAnnotation` and tree paths, JS truthiness (`detailSourceId ""` → main view, `vertebrae: []` kept, `requiresVetReferral: false` dropped), `??=` on rebase labels, `unsupported_envelope` keeping the report origin, a malformed map entry failing the read (no new "never throws" behaviour). | Owner rule: no business behaviour change without a decision. Unifying policies is a later decision, not a side effect. |
| P5 | `SheetHandle` (wasm-bindgen struct) owns the loaded sheet: status, ref, species, schema version, normalized document, assets, asset hashes, migration map and the Rust index. `handle.index_data()` returns `SheetIndexData` once: normalized document, `viewById` / `annotationById` / `findingZoneById` / `regionByCode` (positions, last wins), `annotationsByView` (positions, document order), `spine[region][view]` (position, first wins), `spineIds`, `names[annotationId]`, `nodeKeys` (paths reachable by first-wins walk). The app's `SheetIndex` becomes a class over that data with today's method names (accessors only, `Object.hasOwn`), plus `ops` = the sheet-bound core calls. The handle does not run the integrity rules at load (today's behaviour); a missing main view is a load failure. | ~14 modules keep calling `sheet.annotation(id)` etc., no wasm call in a render, no rule in TypeScript. The canvas keeps the TS renderer (R3) on the normalized document and the TS asset record. |
| P6 | One core call per user action. `zone.click` returns the decision and, when the observation changes, the new observation, plus what the UI needs (`sidesPresent` for the laterality picker, `zoneIndex`). The vertebra picker's initial selection (`collectVertebrae`) is computed when the picker opens (click or chip), never in render. Vertebra grid display (`count`, `count_range`, extended state) stays React. | Review III.3 rule 1 (no call in a render path). |
| P7 | Store: every report entering the store passes the core (`report.new`, draft restore, import, `hydrateReport`), every observation write passes `report.replace_observation` (shape-checked, stripped), list rules are core calls (`add` / `remove` / `move` observation). Field assignments of form values stay Zustand (see §0). A failed core call leaves the state unchanged and raises the `core.action_failed` alert. `hydrateReport` now parses (the "stores as is" characterisation test changes by design, stated). | "Rust parser = single entry" (review I.2); one-line delegations. |
| P8 | Lazy core: `useSheet` (editor, new report) and the import action load it; `HomeRoute` gets the sheet availability from the bundle without the core and loads the core only when a file is chosen; `/login`, `/app/*`, Mon compte never reference it. The glue JS and the `.wasm` are emitted as Vite assets (`?url`), never bundled into a route chunk, fetched on first need. | Owner: no wasm on pages that do not need it. |
| P9 | Runtime: synchronous calls after `await ready()`. A `WebAssembly.RuntimeError` poisons the instance: the failing call returns `{ok:false, kind:'internal'}`, a fresh instance is created in the background (cache-busting dynamic import of the glue asset URL + new `WebAssembly` instance), sheet handles are rebuilt lazily from their retained source text, calls made meanwhile return `core_unavailable`. A load failure (fetch, CSP, compile) gives `core_unavailable` with `retry()` evicting the cached promise. | Review III.3 rules 5 and 6; R0 proof (no reuse after a trap). Async calls everywhere would reintroduce the double-click races the click chain avoids with `getState()`. |
| P10 | Two wasm builds: `packages/core-wasm/pkg/` (shipped, no `proofs` feature) and `pkg-proofs/` (trap exports, tests only). | R0 follow-up "drop --features proofs at R2"; the trap test still needs a trap. |
| P11 | Import = engine byte scan (`readAttachedDocument`, TS, frozen until R4) → `JSON.stringify` → core `archive.import` (layered read + rebase in one call) → the same `ImportError` mapping. Export = core `archive.snapshot` → frozen TS engine (still asserts and writes). | D-R12 go; R4 owns the scanner and the writer. |
| P12 | Draft quarantine: an unreadable `osteo:draft` or `osteo:archive` moves to `osteo:quarantine` (JSON list of `{key, at, raw}`, newest last, cap 10) before anything overwrites it; the draft case raises the `editor.draft_quarantined` alert. | VI.3 R2 row; today's silent drop is a loss. |
| P13 | Publish gate: `publishSheetVersion(client, versionId, validate)` takes the core validator (dependency injection); conformance fixtures `crates/core/tests/conformance/*.json` (document, Rust issues with paths, SQL codes) run in cargo and in a generated `supabase/tests/011_sheet_conformance.sql`; a cargo drift test regenerates and compares the SQL file. | Review III.4. |
| P14 | N-1 reader: the Zod schemas shipped at 1a7ee7d copied verbatim under `packages/core-wasm/tests/n-1/` (frozen, survives R5); a vitest parses every Rust-written report, draft, snapshot and envelope fixture with them. | Review III.3 rule 7, VI.3. |
| P15 | Parity corpus: a TS generator mutates small valid bases (report v3, report v2, horse-slice document, snapshot, branding, labels, envelope, migration map) field by field (delete, `null`, wrong type, empty, unknown key, `2.0`, `-1`, `1e20`, long strings at the caps) and records Zod's outcome (accepted output text or refused); committed under `crates/core/tests/parity/`; cargo asserts the same outcome and byte-equal output; a vitest drift test re-runs Zod on it while `packages/domain` exists. | "Freeze with the old code, then switch" without a dual-run harness. |
| P16 | `apps/app/src` imports nothing from `@faunosteo/domain` (ESLint `no-restricted-imports`); `pickLabel` moves to `apps/app/src/i18n/pickLabel.ts`; types come from `@faunosteo/core-wasm` (ts-rs). The `apps/app` package keeps the dependency for `scripts/` (R4). | VI.4. |
| P17 | App image: wasm stage (`rust:1.99.0-bookworm`, wasm target, `wasm-bindgen-cli` at the `Cargo.lock` version, BuildKit cache mounts) before the Node stage; nginx serves a precompressed `.wasm.gz` (`gzip_static`) when the module is present, else `gzip on` for `application/wasm` (decided on the image's `nginx -V`). Size budget test: served module ≤ 600 KB gzip. | D-R13; the VPS never builds (DEPLOY.md note). |
| P18 | CSP proof on the real image: headless Chromium behind an nginx with the DEPLOY.md headers runs the editor path (new report, zone click, picker, export, import); a variant without `'wasm-unsafe-eval'` shows the degraded state while `/login` stays usable. | VI.2 R2 end criteria. |
Visible strings, wording validated by the owner 2026-10-13 (the recommended options):
- `sheet.core_unavailable`: « Le moteur de calcul de Faunosteo n'a pas pu être chargé. Vos données de session sont conservées. » / "Faunosteo's computation engine could not be loaded. Your session data is kept."; `sheet.core_retry`: « Réessayer » / "Retry" (editor and new-report degraded notice).
- `core.action_failed` (alert): « Cette action n'a pas pu être appliquée. Réessayez ; votre bilan n'a pas été modifié. » / "This action could not be applied. Try again; your report was not changed."
- `editor.draft_quarantined` (alert): « Le brouillon de cet onglet n'a pas pu être relu par cette version de Faunosteo. Il a été mis de côté, pas supprimé. » / "This tab's draft could not be read by this version of Faunosteo. It was set aside, not deleted."
- `home.import.error_core_unavailable` (import error line): « Le moteur de lecture n'a pas pu être chargé. Réessayez l'import. » / "The reading engine could not be loaded. Try the import again."
## 2. Core operations (facade `call(op, json)` and `SheetHandle.call(op, json)`)
Envelope unchanged: `{"ok":true,"value":…}` | `{"ok":false,"kind":…,"detail":…}`. Kinds: `invalid_json`, `invalid_shape`, `unknown_op`, `internal`, plus per-op kinds below.
Free ops:
- `sheet.check` (document) → `{issues: SheetIssue[], publishable}`; `invalid_shape` when the strict schema refuses.
- `sheet.create_empty` ({species_id, name}) → document.
- `report.new` ({draft, sheet: SheetRef, id, createdAt, observationId}) → Report (draft observations kept, else one empty observation with `observationId`).
- `report.add_observation` ({report, id}) → Report; `report.remove_observation` ({report, index}) → Report; `report.move_observation` ({report, index, direction: 'up' | 'down'}) → Report (no-op at the ends); `report.replace_observation` ({report, index, observation}) → Report (`invalid_shape` when the observation does not parse).
- `vertebra.select` ({selection, action: {kind:'toggle', region, index} | {kind:'all', region, count} | {kind:'none', region}}) → Vertebra[].
- `archive.parse_envelope` (envelope JSON) → envelope (full v1 schema, shape tier, as `ReportArchiveEnvelopeSchema`).
Sheet ops (`SheetHandle`):
- constructor `SheetHandle.load(bundleJson)` → handle | error kind `invalid_sheet`; `index_data()` → `SheetIndexData`.
- `draft.restore` ({draft: string, archive: envelope | null}) → `{report, rebase: RebaseOutcome}`; kinds `unsupported_version {found}`, `invalid`.
- `archive.import` (attachment data) → `{read: ArchiveReadOutcome, rebase: RebaseOutcome}`; kinds `incompatible_version {found}` (numeric unknown version), `no_attachment` (anything else).
- `archive.snapshot` ({report}) → SheetSnapshot.
- `report.rebase` ({report, archived: snapshot | null}) → RebaseOutcome.
- `zone.click` ({observation: Observation | null, annotationId}) → `{kind: 'ignore' | 'open_view' | 'activate_fallback' | 'open_vertebra_picker' | 'open_laterality_picker' | 'remove_both_sides' | 'toggle', viewId?, observation?, zoneIndex?, sidesPresent?}`.
- `zone.add_sides` ({observation, annotationId, sides}) → Observation; `zone.remove_at` ({observation, index}) → Observation.
- `vertebra.initial` ({observation, zoneIndex}) → Vertebra[]; `vertebra.sync` ({observation, selection, viewId}) → Observation.
- `finding.toggle` ({observation, findingZoneId, path, side?}) → Observation (adds the built finding with snapshots and the vet flag, or removes the matching one).
## 3. Phases (one commit or more each; checkpoints reported when a consumer switches)
- **R2.0 Freeze (TS, before any switch)**: the three archive envelopes (`demo`, `v2full`, `v2unresolved`, fr, fixed `exportedAt`) and their bare reports exported by the current path, committed as goldens; N-1 schema copy; parity corpus generator + corpus; `horse-slice.ts` and `mini-sheet.ts` converted to JSON fixtures; characterisation of the click chain and store outputs that no test pins (exact objects).
- **R2.1 Contracts in Rust**: `domain/js.rs` (JsInt, UTF-16 lengths, patterns, own-key semantics, surrogate pre-pass), sheet schema, report v2 / v3 / identity / migration map, snapshot / branding / labels / envelope structs, ts-rs export; parity corpus green; byte equality with `JSON.stringify(Zod.parse(x), null, 2)` on the seed draft, demo report, v2 fixtures.
- **R2.2 Rules in Rust**: 21 rules + `check`, `create_empty`, index + `SheetIndexData`, `readReportDocument` + migration (612-leaf suite), rebase (exact objects), snapshot build / assert (caps, depth), envelope layered read (decision table); suites ported from `packages/domain/tests` with their exact expectations; conformance fixtures + generated pgTAP + drift test.
- **R2.3 Editor rules in Rust**: zone click + reducers (13-case suite + characterisation), finding toggle, vertebra initial / sync / select, report ops.
- **R2.4 Facade + runtime**: `crates/wasm` (`call`, `SheetHandle`, no proofs in the shipped build), `packages/core-wasm` runtime (lazy, poison, re-instantiate, retry, Node and browser sources, typed client), the trap / load-failure / handle-rebuild tests, size test.
- **R2.5 App switch**: provider + `useSheet` (+ degraded state), `SheetIndex` class, store + persistence + quarantine, click chain + pickers + findings picker, import / export, Home lazy core, publish gate, ESLint restriction, `pickLabel` move, codemod of type imports; deletion of `services/zoneInteraction.ts`, `services/sheetIndex.ts` re-exports and the data-building code in components; app suites green with their assertions (renamed calls only, each changed assertion listed).
- **R2.6 Images and serving**: Dockerfile wasm stage, `.dockerignore`, nginx compression, `check:all` stages (two wasm builds), CSP headless proof on the image, measurements (raw / gzip size, instantiate time, op timings, page-load impact, memory).
- **R2.7 Docs and gates**: RUST.md R2 section (migrated components, deleted TS, exceptions, measurements, census), CLAUDE.md, WORKSPACE.md, TEST_STRATEGY.md, packages/README.md, DEPLOY.md note, CHANGELOG; verifier + security gates; memory; owner manual procedure on the LAN.
## 4. Oracles (end criteria, review VI.2 R2 row)
1. Domain suites ported to cargo with exact expectations (validate code + path lists, migrate incl. 612 leaves, rebase exact objects, envelope decision table, branding / labels, snapshot caps); parity corpus 100 % equal.
2. App service / store / component / route suites pass on the core with their assertions; changed assertions listed one by one.
3. The three frozen envelopes: the Rust-path export parses with the frozen N-1 Zod schemas and is semantically equal (deep equal) to the frozen one; bytes differ only by key order (D-R11).
4. The 39 step6 goldens and the seed golden untouched (`git diff --stat` on their dirs empty).
5. `pnpm build` with the wasm; the module is not referenced by the auth / account chunks; served module ≤ 600 KB gzip.
6. App image boots under the production CSP headers in headless Chromium (editor path works); without `'wasm-unsafe-eval'` the editor shows the degraded state and `/login` works.
7. A deliberate trap (proofs build) re-instantiates and the next call succeeds with a rebuilt handle.
8. `pnpm check:all` green; `pnpm db:test` on the real stack with the generated pgTAP file; verifier CONFORME; security PASS.
9. Grep census: no `@faunosteo/domain` import under `apps/app/src`; no `decideZoneClick` / `syncVertebrae` / `buildSheetIndex` / `buildSheetSnapshot` / `rebaseReportOnSheet` / `readReportDocument` reachable from `apps/app/src`.
10. Owner manual FR / EN flow on the LAN (procedure delivered).
## 5. Revision 2 (2026-10-14, after three plan challenges: correctness CONCERNS(2), robustness FATAL(7) incl. 1 BLOCKER, simplicity CONCERNS(3); 45 findings)
Supersedes the rows of §1–§4 it names.
- **P7 replaced** (all three lenses): only core-built observations and reports enter the store through the core (`report.new`, draft restore, import, the reducers' outputs). Form-value edits of an observation (comment, severity, free text, finding removal by identity) stay Zustand assignments, like the identity and text setters. `report.replace_observation` is dropped. Store actions that call the core return `{ ok }`; callers (`NewReportRoute`, `HomeRoute`, the click chain) stop on failure (no navigation, no picker). `hydrateReport` is deleted (test-only seam; tests seed with `hydrateImport` or `setState`).
- **Editor degraded state (robustness BLOCKER 1, correctness 11)**: `useSheet` gets `core_unavailable` and `invalid_sheet` states; `EditorRoute` never redirects in those states, renders the notice + retry, and never restores or overwrites `osteo:draft` while the core has not read it. Test: reload `/editor` with the core failing, draft intact.
- **Runtime (robustness 2, 3, 9, 10)**: every sheet op resolves the handle through the runtime with an instance generation; calls into a poisoned glue record are refused (including `free`). The compiled `WebAssembly.Module` is kept; one spare glue record is pre-imported after a successful load so a re-instantiation needs no network; at most 3 re-instantiations per page, then `core_unavailable` ("reload"). `retry()` clears the runtime, `useSheet` and provider caches. A vitest `globalSetup` fails (never skips) when `pkg/` or `pkg-proofs/` is missing or its build stamp (hash of `crates/**` + `Cargo.lock`, written by `scripts/wasm-build.sh`) differs from the tree. The trap → re-instantiate → next call test also runs once in headless Chromium on a build linked to `pkg-proofs` (best effort; recorded if not obtainable).
- **Quarantine (robustness 4, 5, 16; simplicity 13; correctness 10)**: only the content kinds (`invalid`, `unsupported_version`) quarantine; any other kind leaves the keys untouched and shows the degraded state. Raw text goes to `osteo:quarantine:draft` / `osteo:quarantine:archive` (newest only); the source key is removed only after the quarantine write succeeded; a draft rebased with unresolved items keeps its raw pre-rebase text in `osteo:quarantine:draft-pre-rebase`. Paths that never read the draft (New report / Import from Home after a reload) keep today's semantics (a new session replaces the tab draft). No recovery UI at R2 (stated residual).
- **SheetIndexData minimal (simplicity 3, correctness 3)**: `mainViewId` (first `main` view by position), `viewById`, `annotationById`, `findingZoneById` (positions, last wins), `names[annotationId]`, `spineIds` (last-wins annotation, observable with a region), `nodeKeys` keyed by the JSON text of `[zoneId, ...path]` (collision-free) reachable by the first-wins walk on the last-wins zone, plus the normalized document. No `annotationsByView`, `spine`, `regionByCode` (no TS reader after the switch). `regions()` reads the document.
- **Ops (simplicity 4, correctness 4, 8, 13)**: exposed only with a TS caller: `sheet.check` (publish gate), `report.new`, `report.add_observation`, `report.remove_observation`, `report.move_observation`, `vertebra.select` (called in the tap handler, never in a state updater), sheet ops `draft.restore` ({draft: string, archive: string | null} → report, rebase, parsed archive or `archiveRejected`), `archive.import`, `archive.snapshot`, `zone.click` (returns the initial vertebra selection for `open_vertebra_picker`), `zone.add_sides`, `zone.remove_at`, `vertebra.initial` (chip path), `vertebra.sync`, `finding.toggle` (takes the clicked leaf's position among its siblings; parents walked first-wins as `findNode`). `sheet.create_empty`, `report.rebase`, `archive.parse_envelope` are Rust functions with cargo tests, no op. The failure envelope gains an optional numeric `found` (js_number).
- **Oracles (simplicity 2, correctness 1, 5, 6, 7, 12)**: the full mutation corpus is dropped. Instead: (a) Zod output oracles of the reference documents (`crates/core/tests/oracles`, done: draft and legacy sheets, demo v3, v2 fixtures, migration map, byte-equal); (b) a characterisation set frozen from the TS functions for the quirks (`detailSourceId: ""`, `requiresVetReferral: false`, `vertebrae: []`, `collectVertebrae` concatenated-key collision, `syncVertebrae` region order and second spine zone, rebase `??=`, malformed map entry, numeric literals `3.0` / `1e0`, lone surrogate lowercase escapes); (c) a table of hostile inputs per constraint site with Zod's accept/refuse verdict (vitest writes it with `MAKE_R2_ORACLES=1`, cargo asserts it); (d) type-level equality of ts-rs types against `z.output` per contract (vitest `expectTypeOf`); the golden-report helper switches to the core migration for the Rust run; the publish-gate tests use the real Node core. Oracle 9 reworded: "not imported by `apps/app/src`" (the engine keeps its TS index and reader until R4).
- **Fail-closed publish gate (robustness 17)**: `publishSheetVersion(client, versionId, validate)`, `validate` required; anything but `{ok: true, value: {publishable: true}}` throws before the RPC; test with a failing core.
- **Pages (simplicity 11)**: Home and `/new` read the sheet availability from the bundle without the core; the core loads at `/new` submit, on an import file pick, and in the editor.
- **Display glue accepted (simplicity 12)**: `VertebraPicker` `has` and the grid extent, `FindingsTreePicker` `matches` / `isLeafSelected` / `countSelectedUnder`, `ObservationCard` `zoneTrees` / `unresolvedFindings` / `describeZone`, import message lines: render-time predicates over core data, listed in the RUST.md census.
- **Docker / serving (robustness 12, 14, 15, 13; simplicity 9, 10)**: `packages/core-wasm/package.json` in the manifest COPY list; `pkg-proofs/` git- and docker-ignored; wasm-bindgen runs in the same RUN as the cache-mounted cargo build; the wasm-bindgen version shares the builder's `ARG` line, `scripts/wasm-build.sh` keeps the `Cargo.lock` guard; a check that the shipped `pkg/faunosteo_wasm.d.ts` has no proof export. CSP proof = `docker/csp-proof` extended to the app image: with the keyword the editor loads and one zone click works; without it the editor shows the degraded state and `/login` works; network-level assertion that `/login` and `/app/account` request neither the glue nor the `.wasm`; Firefox and WebKit too when their Playwright builds are present (else recorded). DEPLOY.md: R2+ images are never built on the VPS; the CSP must carry `'wasm-unsafe-eval'` before an R2 image is deployed.
- **Kept, with reason**: the N-1 verbatim copy (already committed; permanent, survives R5); `vertebra.select` in the core (review II.2 class A, owner listed "Sélection vertébrale"); one gate for R2 with an owner-facing checkpoint report after R2.4 (no stop: the owner asked to stop after R2).
- **Interim risks stated (robustness 8, 11)**: the import reads up to the 16 MiB attachment in the long-lived main instance until R4 moves it to a Worker; no React error boundary is added (no UI change at R2), every core entry point catches.
- **Owner decision to confirm at delivery (correctness 9)**: L1, a lone UTF-16 surrogate escape in a draft or an archive becomes U+FFFD instead of refusing the document.
- `pickLabel` → the existing `apps/app/src/i18n/pickLocaleLabel.ts` (object overload), no new copy (simplicity 6). `mini-sheet.ts` conversion dropped (R3/R5, simplicity 8). `url` crate size measured at R2.4 against the budget (simplicity 14).
Generated
+1
View File
@@ -189,6 +189,7 @@ dependencies = [
"serde",
"serde_json",
"ts-rs",
"url",
]
[[package]]
+3 -1
View File
@@ -21,7 +21,9 @@ serde = { version = "1.0.229", features = ["derive"] }
# float_roundtrip: the default parser is a fast path that can be one ULP off (found by the R0
# proof: 1715.4285714285713 came back as 1715.428571428571); JavaScript parses correctly.
serde_json = { version = "1.0.154", features = ["preserve_order", "float_roundtrip"] }
ts-rs = { version = "12.0", features = ["serde-compat"] }
ts-rs = { version = "12.0", features = ["serde-compat", "no-serde-warnings"] }
# Zod `.url()` is `new URL()`: the WHATWG parser of the url crate reproduces it (R2 plan P2).
url = "2.5.8"
# The CLI in docker/rust-builder.Dockerfile must be this exact version.
wasm-bindgen = "=0.2.129"
image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp"] }
+1
View File
@@ -18,6 +18,7 @@ ts = ["dep:ts-rs"]
[dependencies]
serde.workspace = true
serde_json.workspace = true
url.workspace = true
ts-rs = { workspace = true, optional = true }
[lints]
+136
View File
@@ -0,0 +1,136 @@
//! The visual identity an archive embeds (`archive/branding.ts`, STEP6 §3.4, caps §15).
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
#[cfg(feature = "ts")]
use ts_rs::TS;
use crate::domain::js::{self, literal};
const KIB: usize = 1024;
literal!(KindPng, "png");
literal!(KindSvg, "svg");
/// `http(s)://` then printable ASCII without `"`, `'`, `(`, `)`, `<`, `>` or `\`: the URL is
/// written into PDF link actions. Also at most 2048 characters and a valid URL.
fn is_branding_url(text: &str) -> bool {
let rest = text
.strip_prefix("https://")
.or_else(|| text.strip_prefix("http://"));
let Some(rest) = rest else { return false };
js::utf16_len(text) <= 2048
&& !rest.is_empty()
&& rest
.bytes()
.all(|b| (0x21..=0x7e).contains(&b) && !b"\"'()<>\\".contains(&b))
&& js::is_url(text)
}
fn branding_url<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let text = String::deserialize(d)?;
if is_branding_url(&text) {
Ok(text)
} else {
Err(D::Error::custom("http(s) URL expected"))
}
}
fn capped<'de, D: Deserializer<'de>>(d: D, max: usize) -> Result<String, D::Error> {
let text = String::deserialize(d)?;
if js::utf16_len(&text) <= max {
Ok(text)
} else {
Err(D::Error::custom("string over its cap"))
}
}
fn png_base64<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let text = capped(d, 512 * KIB)?;
if js::is_base64(&text) {
Ok(text)
} else {
Err(D::Error::custom("invalid base64"))
}
}
fn svg_text<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
capped(d, 256 * KIB)
}
fn fallback_text<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
capped(d, 128)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct PngAsset {
pub kind: KindPng,
#[serde(deserialize_with = "png_base64")]
pub base64: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct SvgAsset {
pub kind: KindSvg,
#[serde(deserialize_with = "svg_text")]
pub svg: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(untagged)]
pub enum ImageAsset {
Png(PngAsset),
Svg(SvgAsset),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Credit {
#[serde(deserialize_with = "js::nullable")]
pub logo: Option<ImageAsset>,
#[serde(deserialize_with = "branding_url")]
pub url: String,
#[serde(deserialize_with = "fallback_text")]
pub fallback_text: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Branding {
#[serde(deserialize_with = "branding_url")]
pub site_url: String,
#[serde(deserialize_with = "js::nullable")]
pub header_logo: Option<ImageAsset>,
#[serde(deserialize_with = "js::nullable")]
pub footer_logo: Option<ImageAsset>,
#[serde(deserialize_with = "js::nullable")]
pub powered_by: Option<Credit>,
#[serde(deserialize_with = "js::nullable")]
pub partner: Option<Credit>,
}
#[cfg(test)]
mod tests {
use super::is_branding_url;
#[test]
fn branding_urls_follow_the_zod_pattern() {
assert!(is_branding_url("https://faunosteo.com"));
assert!(is_branding_url("http://a.b/c?d=e#f"));
assert!(!is_branding_url("https://a.b/(x)"));
assert!(!is_branding_url("ftp://a.b"));
assert!(!is_branding_url("https://"));
assert!(!is_branding_url("https://a b"));
assert!(!is_branding_url(&format!(
"https://a.b/{}",
"x".repeat(2048)
)));
}
}
@@ -0,0 +1,56 @@
//! The attachment of a Step 6 PDF (`archive/envelope.ts`, STEP6 §2.3): the report wrapped
//! with the sheet snapshot, the branding and the labels it was printed with. Metadata is not
//! strict: an additive v1 field never breaks an older reader.
use serde::{Deserialize, Serialize};
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::branding::Branding;
use super::labels::PdfLabelSet;
use super::snapshot::SheetSnapshot;
use crate::domain::js::{literal, number_literal};
use crate::domain::report::Report;
literal!(EnvelopeFormat, "faunosteo-report-archive");
number_literal!(EnvelopeVersion1, 1);
pub const ENVELOPE_VERSION: u32 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "lowercase")]
pub enum Locale {
Fr,
En,
}
/// `EnvelopeMetadataSchema.extend({branding, labels})`: what the layered reader checks
/// before the snapshot gate.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvelopeWrapper {
pub format: EnvelopeFormat,
pub envelope_version: EnvelopeVersion1,
pub exported_at: String,
pub locale: Locale,
pub branding: Branding,
pub labels: PdfLabelSet,
}
/// An archive envelope, in the order the engine writes it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct ReportArchiveEnvelope {
pub format: EnvelopeFormat,
pub envelope_version: EnvelopeVersion1,
/// ISO timestamp of the export.
pub exported_at: String,
pub locale: Locale,
/// As exported, never rebased.
pub report: Report,
pub sheet_snapshot: SheetSnapshot,
pub branding: Branding,
pub labels: PdfLabelSet,
}
+116
View File
@@ -0,0 +1,116 @@
//! The static strings the PDF engine prints, in both locales, frozen into the archive
//! (`archive/labels.ts`): exactly 25 keys, strict, each at most 256 UTF-16 units.
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
#[cfg(feature = "ts")]
use ts_rs::TS;
use crate::domain::js;
/// The 25 keys, in the order of `PDF_LABEL_KEYS`.
pub const PDF_LABEL_KEYS: [&str; 25] = [
"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",
];
const LABEL_MAX: usize = 256;
fn label<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let text = String::deserialize(d)?;
if js::utf16_len(&text) <= LABEL_MAX {
Ok(text)
} else {
Err(D::Error::custom("label over 256 characters"))
}
}
/// Fields in the order of the engine dictionaries (`packages/pdf/src/i18n`), which is the
/// order every shipped attachment carries.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct PdfLabels {
#[serde(rename = "pdf.eyebrow.observation", deserialize_with = "label")]
pub pdf_eyebrow_observation: String,
#[serde(rename = "pdf.eyebrow.synthesis", deserialize_with = "label")]
pub pdf_eyebrow_synthesis: String,
#[serde(rename = "pdf.title.conclusion", deserialize_with = "label")]
pub pdf_title_conclusion: String,
#[serde(rename = "pdf.section.zones", deserialize_with = "label")]
pub pdf_section_zones: String,
#[serde(rename = "pdf.section.findings_prefix", deserialize_with = "label")]
pub pdf_section_findings_prefix: String,
#[serde(rename = "pdf.section.free_findings", deserialize_with = "label")]
pub pdf_section_free_findings: String,
#[serde(rename = "pdf.section.severity", deserialize_with = "label")]
pub pdf_section_severity: String,
#[serde(rename = "pdf.section.comment", deserialize_with = "label")]
pub pdf_section_comment: String,
#[serde(rename = "pdf.section.conclusion", deserialize_with = "label")]
pub pdf_section_conclusion: String,
#[serde(rename = "pdf.section.recommendations", deserialize_with = "label")]
pub pdf_section_recommendations: String,
#[serde(rename = "pdf.section.next_appointment", deserialize_with = "label")]
pub pdf_section_next_appointment: String,
#[serde(rename = "pdf.view.general", deserialize_with = "label")]
pub pdf_view_general: String,
#[serde(rename = "pdf.view.detail_prefix", deserialize_with = "label")]
pub pdf_view_detail_prefix: String,
#[serde(rename = "pdf.empty", deserialize_with = "label")]
pub pdf_empty: String,
#[serde(rename = "pdf.owner_prefix", deserialize_with = "label")]
pub pdf_owner_prefix: String,
#[serde(rename = "pdf.siret_prefix", deserialize_with = "label")]
pub pdf_siret_prefix: String,
#[serde(rename = "pdf.title.suffix.bilan", deserialize_with = "label")]
pub pdf_title_suffix_bilan: String,
#[serde(rename = "pdf.subject", deserialize_with = "label")]
pub pdf_subject: String,
#[serde(rename = "severity.mild", deserialize_with = "label")]
pub severity_mild: String,
#[serde(rename = "severity.moderate", deserialize_with = "label")]
pub severity_moderate: String,
#[serde(rename = "severity.severe", deserialize_with = "label")]
pub severity_severe: String,
#[serde(rename = "lateral.left", deserialize_with = "label")]
pub lateral_left: String,
#[serde(rename = "lateral.right", deserialize_with = "label")]
pub lateral_right: String,
#[serde(rename = "footer.powered_by", deserialize_with = "label")]
pub footer_powered_by: String,
#[serde(rename = "footer.in_partnership", deserialize_with = "label")]
pub footer_in_partnership: String,
}
/// Strict: every key present in both locales, no extra key.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct PdfLabelSet {
pub fr: PdfLabels,
pub en: PdfLabels,
}
+11
View File
@@ -0,0 +1,11 @@
//! Archive contracts: the sheet snapshot, the branding, the PDF labels and the envelope.
pub mod branding;
pub mod envelope;
pub mod labels;
pub mod snapshot;
pub use branding::*;
pub use envelope::*;
pub use labels::*;
pub use snapshot::*;
+115
View File
@@ -0,0 +1,115 @@
//! The sheet a report archive carries (`archive/snapshot.ts`, STEP6 §2.2): a valid, lean
//! sheet document plus the SVG text of every asset a view reaches. This file holds the shape;
//! the build and the import gate are in `snapshot_rules.rs`.
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
#[cfg(feature = "ts")]
use ts_rs::TS;
use crate::domain::js::{self, JsInt};
use crate::domain::report::v3::sha256;
use crate::domain::sheet::AnatomicalSheetDocument;
use crate::domain::sheet::schema::check;
const MIB: usize = 1024 * 1024;
/// Hard limits on an imported snapshot; every excess is a `caps` rejection.
pub struct SnapshotCaps;
impl SnapshotCaps {
pub const VIEWS: usize = 64;
pub const ANNOTATIONS: usize = 1024;
pub const FINDING_NODES: usize = 8192;
pub const FINDING_DEPTH: usize = 8;
pub const LABEL_CHARS: usize = 512;
pub const ASSETS: usize = 4;
pub const ASSET_BYTES: usize = 2 * MIB;
pub const ASSETS_TOTAL_BYTES: usize = 6 * MIB;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "lowercase")]
pub enum SheetStatus {
Draft,
Published,
}
/// `SheetRefSchema.extend({schemaVersion, speciesId}).strict()`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SheetSnapshotRef {
#[serde(deserialize_with = "check::non_empty")]
pub sheet_id: String,
#[serde(deserialize_with = "check::nullable_non_empty")]
pub version_id: Option<String>,
#[serde(deserialize_with = "sha256")]
pub document_sha256: String,
#[serde(deserialize_with = "check::positive_int")]
#[cfg_attr(feature = "ts", ts(type = "number"))]
pub schema_version: JsInt,
#[serde(deserialize_with = "check::non_empty")]
pub species_id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SheetSnapshotAsset {
#[serde(deserialize_with = "uuid")]
pub svg_asset_id: String,
/// Content address from the seed manifest; a provenance pointer, not a tamper check.
#[serde(deserialize_with = "nullable_sha256")]
pub sha256: Option<String>,
#[serde(deserialize_with = "asset_svg")]
pub svg: String,
}
fn uuid<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let text = String::deserialize(d)?;
if js::is_uuid(&text) {
Ok(text)
} else {
Err(D::Error::custom("invalid uuid"))
}
}
fn nullable_sha256<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
match Option::<String>::deserialize(d)? {
Some(text) if !js::is_sha256_hex(&text) => Err(D::Error::custom("invalid sha256")),
other => Ok(other),
}
}
fn asset_svg<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let text = String::deserialize(d)?;
if js::utf16_len(&text) <= SnapshotCaps::ASSET_BYTES {
Ok(text)
} else {
Err(D::Error::custom("asset over cap"))
}
}
fn capped_assets<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<SheetSnapshotAsset>, D::Error> {
let assets = Vec::<SheetSnapshotAsset>::deserialize(d)?;
if assets.len() <= SnapshotCaps::ASSETS {
Ok(assets)
} else {
Err(D::Error::custom("too many assets"))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct SheetSnapshot {
pub status: SheetStatus,
#[serde(rename = "ref")]
pub reference: SheetSnapshotRef,
/// Lean, valid document (schema v2, strict).
pub document: AnatomicalSheetDocument,
#[serde(deserialize_with = "capped_assets")]
pub assets: Vec<SheetSnapshotAsset>,
}
+346
View File
@@ -0,0 +1,346 @@
//! JavaScript and Zod semantics the ported contracts depend on (R2 plan P1, P2).
//!
//! The TypeScript domain reads JSON with `JSON.parse` and validates it with Zod 3: lone
//! surrogate escapes are kept, a duplicate key keeps its last value at its first position,
//! `.int()` accepts any number with an integer value (`2.0`, `1e20`), string lengths count
//! UTF-16 code units, and the patterns are JavaScript regular expressions whose `$` only
//! matches at the end of the input. The helpers below reproduce exactly that, so a document
//! the old code accepted is accepted here and prints the same.
use std::borrow::Cow;
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
/// Reads JSON text as `JSON.parse` does, as far as a Rust string allows: an escape of a
/// lone UTF-16 surrogate (which `JSON.parse` keeps and Rust strings cannot hold) becomes
/// U+FFFD instead of refusing the whole document (leniency decision L1).
pub fn parse_json(text: &str) -> Result<Value, serde_json::Error> {
serde_json::from_str(&replace_lone_surrogates(text))
}
/// Rewrites `\uD800`–`\uDFFF` escapes that are not a high + low pair to `�`.
/// Escapes are consumed left to right, so `\\u…` (an escaped backslash) is left alone.
pub fn replace_lone_surrogates(text: &str) -> Cow<'_, str> {
let bytes = text.as_bytes();
let mut out: Option<String> = None;
let mut copied = 0;
let mut i = 0;
while i < bytes.len() {
if bytes[i] != b'\\' {
i += 1;
continue;
}
let Some(unit) = escape_unit(bytes, i) else {
i += 2;
continue;
};
if (0xD800..=0xDBFF).contains(&unit)
&& escape_unit(bytes, i + 6).is_some_and(|low| (0xDC00..=0xDFFF).contains(&low))
{
i += 12;
continue;
}
if (0xD800..=0xDFFF).contains(&unit) {
let buffer = out.get_or_insert_with(|| String::with_capacity(text.len()));
buffer.push_str(&text[copied..i]);
buffer.push_str("\\uFFFD");
copied = i + 6;
}
i += 6;
}
match out {
None => Cow::Borrowed(text),
Some(mut buffer) => {
buffer.push_str(&text[copied..]);
Cow::Owned(buffer)
}
}
}
/// The code unit of a `\uXXXX` escape starting at `at`, if there is one.
fn escape_unit(bytes: &[u8], at: usize) -> Option<u32> {
let hex = bytes.get(at..at + 6)?;
if hex[0] != b'\\' || hex[1] != b'u' {
return None;
}
let digits = std::str::from_utf8(&hex[2..]).ok()?;
u32::from_str_radix(digits, 16).ok()
}
/// Length of a string as JavaScript's `.length` counts it (UTF-16 code units).
pub fn utf16_len(text: &str) -> usize {
text.encode_utf16().count()
}
/// An integer as Zod's `.int()` accepts it: any finite number with no fraction, kept as the
/// JavaScript number it is and printed as JavaScript prints it.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)]
pub struct JsInt(f64);
impl JsInt {
pub fn new(value: f64) -> Option<Self> {
(value.is_finite() && value.fract() == 0.0).then_some(Self(value))
}
pub fn get(self) -> f64 {
self.0
}
}
impl From<u32> for JsInt {
fn from(value: u32) -> Self {
Self(f64::from(value))
}
}
impl Serialize for JsInt {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
// Exact below 2^53: printed as an integer by every formatter; beyond, the float
// goes through `js_number` like JavaScript.
if self.0.abs() < 9_007_199_254_740_992.0 {
#[allow(clippy::cast_possible_truncation)]
return serializer.serialize_i64(self.0 as i64);
}
serializer.serialize_f64(self.0)
}
}
impl<'de> Deserialize<'de> for JsInt {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = f64::deserialize(deserializer)?;
Self::new(value).ok_or_else(|| D::Error::custom("expected an integer"))
}
}
/// `.optional()`: absent is fine, an explicit `null` is refused (serde alone would read it
/// as absent). Used with `#[serde(default, deserialize_with = "js::present")]`.
pub fn present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
T::deserialize(deserializer).map(Some)
}
/// `.nullable()` without a default: the key is required, `null` is a value. Used with
/// `#[serde(deserialize_with = "js::nullable")]` (no `default`, so a missing key fails).
pub fn nullable<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
Option::<T>::deserialize(deserializer)
}
/// `z.string().min(1)`.
pub fn non_empty(text: &str) -> bool {
!text.is_empty()
}
/// `/^[a-z0-9][a-z0-9_-]{0,63}$/` (stable ids).
pub fn is_stable_id(text: &str) -> bool {
let bytes = text.as_bytes();
!bytes.is_empty()
&& bytes.len() <= 64
&& matches!(bytes[0], b'a'..=b'z' | b'0'..=b'9')
&& bytes[1..]
.iter()
.all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'_' | b'-'))
}
/// `/^[A-Za-z0-9][A-Za-z0-9_-]{0,15}$/` (vertebral region codes).
pub fn is_region_code(text: &str) -> bool {
let bytes = text.as_bytes();
!bytes.is_empty()
&& bytes.len() <= 16
&& bytes[0].is_ascii_alphanumeric()
&& bytes[1..]
.iter()
.all(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'-')
}
/// `/^#[0-9a-fA-F]{6}$/`.
pub fn is_hex_color(text: &str) -> bool {
let bytes = text.as_bytes();
bytes.len() == 7 && bytes[0] == b'#' && bytes[1..].iter().all(u8::is_ascii_hexdigit)
}
/// `/^[0-9a-f]{64}$/`.
pub fn is_sha256_hex(text: &str) -> bool {
text.len() == 64 && text.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}
/// `/^[A-Za-z0-9+/]*={0,2}$/`.
pub fn is_base64(text: &str) -> bool {
let body = text.trim_end_matches('=');
text.len() - body.len() <= 2
&& body
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'/')
}
/// Zod 3's `.uuid()` pattern: 8-4-4-4-12 hexadecimal digits, any case, any version.
pub fn is_uuid(text: &str) -> bool {
let bytes = text.as_bytes();
bytes.len() == 36
&& bytes.iter().enumerate().all(|(index, byte)| match index {
8 | 13 | 18 | 23 => *byte == b'-',
_ => byte.is_ascii_hexdigit(),
})
}
/// Zod's `.url()`: `new URL(text)` succeeds (WHATWG parser).
pub fn is_url(text: &str) -> bool {
url::Url::parse(text).is_ok()
}
/// A string literal field (the tag of a discriminated union, a format name): reads only
/// that literal and prints it, at the position the Zod schema declares it.
macro_rules! literal {
($name:ident, $value:literal) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct $name;
impl serde::Serialize for $name {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str($value)
}
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
use serde::de::Error as _;
let text = <String as serde::Deserialize>::deserialize(deserializer)?;
if text == $value {
Ok($name)
} else {
Err(D::Error::custom(concat!("expected \"", $value, "\"")))
}
}
}
#[cfg(feature = "ts")]
impl ts_rs::TS for $name {
type WithoutGenerics = Self;
type OptionInnerType = Self;
fn name(_: &ts_rs::Config) -> String {
format!("\"{}\"", $value)
}
fn inline(cfg: &ts_rs::Config) -> String {
Self::name(cfg)
}
}
};
}
/// A number literal field (a document version): reads any JSON number equal to it (`2.0`
/// included, as `z.literal(2)` after `JSON.parse`) and prints the integer.
macro_rules! number_literal {
($name:ident, $value:literal) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct $name;
impl serde::Serialize for $name {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_u32($value)
}
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
use serde::de::Error as _;
if <f64 as serde::Deserialize>::deserialize(deserializer)? == f64::from($value) {
Ok($name)
} else {
Err(D::Error::custom(concat!("expected ", $value)))
}
}
}
#[cfg(feature = "ts")]
impl ts_rs::TS for $name {
type WithoutGenerics = Self;
type OptionInnerType = Self;
fn name(_: &ts_rs::Config) -> String {
stringify!($value).to_owned()
}
fn inline(cfg: &ts_rs::Config) -> String {
Self::name(cfg)
}
}
};
}
pub(crate) use {literal, number_literal};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lone_surrogates_become_replacement_characters() {
assert_eq!(replace_lone_surrogates("\"a\\ud800b\""), "\"a\\uFFFDb\"");
assert_eq!(replace_lone_surrogates("\"\\udc00\""), "\"\\uFFFD\"");
assert_eq!(
replace_lone_surrogates("\"\\ud83d\\ude00\""),
"\"\\ud83d\\ude00\""
);
assert_eq!(replace_lone_surrogates("\"\\\\ud800\""), "\"\\\\ud800\"");
assert_eq!(
replace_lone_surrogates("\"\\ud800\\ud800\""),
"\"\\uFFFD\\uFFFD\""
);
assert!(matches!(replace_lone_surrogates("plain"), Cow::Borrowed(_)));
let Ok(value) = parse_json("{\"t\":\"x\\ud800\"}") else {
panic!("lenient parse failed");
};
assert_eq!(value["t"], "x\u{FFFD}");
}
#[test]
fn duplicate_keys_keep_the_last_value_at_the_first_position() {
let Ok(value) = parse_json(r#"{"a":1,"b":2,"a":3}"#) else {
panic!("parse failed");
};
assert_eq!(value.to_string(), r#"{"a":3,"b":2}"#);
}
#[test]
fn js_int_accepts_integer_valued_numbers_only() {
let parsed: Vec<Option<JsInt>> = ["2", "2.0", "1e20", "-0", "2.5"]
.iter()
.map(|t| serde_json::from_str::<JsInt>(t).ok())
.collect();
assert_eq!(parsed[0].map(JsInt::get), Some(2.0));
assert_eq!(parsed[1].map(JsInt::get), Some(2.0));
assert_eq!(parsed[2].map(JsInt::get), Some(1e20));
assert!(parsed[3].is_some());
assert!(parsed[4].is_none());
let printed = crate::json::to_js_pretty(&[JsInt(2.0), JsInt(1e20), JsInt(-0.0)]);
assert_eq!(
printed.ok().as_deref(),
Some("[\n 2,\n 100000000000000000000,\n 0\n]")
);
}
#[test]
fn utf16_lengths_count_surrogate_pairs_twice() {
assert_eq!(utf16_len("é"), 1);
assert_eq!(utf16_len("😀"), 2);
}
#[test]
fn patterns_match_the_zod_regular_expressions() {
assert!(is_stable_id("view-main") && is_stable_id(&"a".repeat(64)));
assert!(!is_stable_id("_x") && !is_stable_id("A") && !is_stable_id(&"a".repeat(65)));
assert!(!is_stable_id("a\n"));
assert!(is_region_code("Cd") && !is_region_code("-C") && !is_region_code(""));
assert!(is_hex_color("#a0B1c2") && !is_hex_color("#a0B1c"));
assert!(is_sha256_hex(&"0".repeat(64)) && !is_sha256_hex(&"A".repeat(64)));
assert!(is_base64("") && is_base64("QUJD==") && !is_base64("QUJD===") && !is_base64("a=b"));
assert!(is_uuid("123e4567-E89B-12d3-a456-426614174000"));
assert!(!is_uuid("123e4567e89b12d3a456426614174000"));
assert!(is_url("https://example.org/a?b#c") && !is_url("not a url") && !is_url("http://"));
}
}
+4 -5
View File
@@ -1,9 +1,8 @@
//! Data contracts of the core.
//!
//! R0 carries the Report v3 reference types (sheet reference, zone, vertebra) to prove the
//! serialisation rules against the current Zod schemas; the full contracts and the rules
//! arrive at R2 (review Part VI.2).
//! Data contracts and business rules of the core (R2: sheet, report, archive, editor rules).
pub mod archive;
pub mod js;
pub mod report;
pub mod sheet;
pub use report::{LateralSide, ReportZone, SheetRef, Unresolved, Vertebra};
-137
View File
@@ -1,137 +0,0 @@
//! Report v3 reference types (`packages/domain/src/report/v3.ts`), field order as the Zod
//! schemas declare it. Optional fields are absent when unset and nullable fields are `null`
//! (review I.2): the serde attributes below are the contract, not a convenience.
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "ts")]
use ts_rs::TS;
/// Reference of the anatomical sheet a report was written against (`Report.sheet`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct SheetRef {
pub sheet_id: String,
/// Database version id once the sheet lives in the database; `null` for a bundled draft.
pub version_id: Option<String>,
/// sha256 of the document file the report was written against.
pub document_sha256: String,
}
/// Side of a bilateral zone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "lowercase")]
pub enum LateralSide {
Left,
Right,
}
/// One vertebra of a spine zone: the region code and the 1-based index in that region.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct Vertebra {
pub region: String,
pub index: u32,
}
/// A zone of an observation. Unknown keys are ignored on input, as the Zod schema strips
/// them; optional fields are written only when set.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct ReportZone {
pub annotation_id: String,
pub view_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub side: Option<LateralSide>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub vertebrae: Option<Vec<Vertebra>>,
/// Annotation name at selection time (or legacy name at migration).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub label_fr_snapshot: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub label_en_snapshot: Option<String>,
/// Set by the migration when the legacy id has no canonical annotation.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional, type = "true"))]
pub unresolved: Option<Unresolved>,
}
/// The literal `true` flag of a zone or finding the sheet cannot place
/// (`z.literal(true).optional()` in Zod).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Unresolved;
impl Serialize for Unresolved {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_bool(true)
}
}
impl<'de> Deserialize<'de> for Unresolved {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if bool::deserialize(deserializer)? {
Ok(Unresolved)
} else {
Err(D::Error::custom(
"unresolved must be the literal true when present",
))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::json::to_js_pretty;
#[test]
fn optional_fields_are_absent_and_nullable_fields_are_null() {
let zone = ReportZone {
annotation_id: "hip".to_owned(),
view_id: "main".to_owned(),
..ReportZone::default()
};
let Ok(text) = to_js_pretty(&zone) else {
panic!("serialisation failed");
};
assert_eq!(
text,
"{\n \"annotationId\": \"hip\",\n \"viewId\": \"main\"\n}"
);
let sheet = SheetRef {
sheet_id: "faunosteo-cheval".to_owned(),
version_id: None,
document_sha256: "0".repeat(64),
};
let Ok(text) = to_js_pretty(&sheet) else {
panic!("serialisation failed");
};
assert!(text.contains("\"versionId\": null"));
}
#[test]
fn unresolved_accepts_true_only() {
let parsed: Result<ReportZone, _> =
serde_json::from_str(r#"{"annotationId":"a","viewId":"v","unresolved":true}"#);
assert_eq!(parsed.ok().and_then(|z| z.unresolved), Some(Unresolved));
let refused: Result<ReportZone, _> =
serde_json::from_str(r#"{"annotationId":"a","viewId":"v","unresolved":false}"#);
assert!(refused.is_err());
}
#[test]
fn unknown_keys_are_ignored_like_the_zod_strip_schema() {
let parsed: Result<ReportZone, _> =
serde_json::from_str(r#"{"annotationId":"a","viewId":"v","extra":1}"#);
assert!(parsed.is_ok());
}
}
+104
View File
@@ -0,0 +1,104 @@
//! Identity snapshots carried by every report version (`report/identity.ts`, BDR-010).
//! Report objects are not strict in Zod: unknown keys are ignored and dropped.
use serde::{Deserialize, Serialize};
#[cfg(feature = "ts")]
use ts_rs::TS;
use crate::domain::js::{self, literal};
use crate::domain::sheet::schema::check;
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct Practitioner {
#[serde(deserialize_with = "check::non_empty")]
pub name: String,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub cabinet: Option<String>,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub contact: Option<String>,
/// SIRET, 14-digit French business identifier (not validated).
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub siret: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct Animal {
/// Species of the animal; the sheet the report references matches it.
#[serde(deserialize_with = "check::non_empty")]
pub species_id: String,
#[serde(deserialize_with = "check::non_empty")]
pub name: String,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub breed: Option<String>,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub age: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct Owner {
#[serde(deserialize_with = "check::non_empty")]
pub name: String,
}
literal!(KindDate, "date");
literal!(KindPeriod, "period");
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct NextAppointmentDate {
pub kind: KindDate,
pub date: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct NextAppointmentPeriod {
pub kind: KindPeriod,
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(untagged)]
pub enum NextAppointment {
Date(NextAppointmentDate),
Period(NextAppointmentPeriod),
}
/// Side of a bilateral zone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "lowercase")]
pub enum LateralSide {
Left,
Right,
}
@@ -0,0 +1,69 @@
//! Correspondence between the legacy identifiers of a Report v2 and the canonical sheet
//! (`report/migration-map.ts`), generated by the curation pipeline. A `null` finding path
//! means "removed from the sheet".
use std::collections::HashMap;
use serde::de::Error as _;
use serde::{Deserialize, Deserializer};
use super::v3::SheetRef;
use crate::domain::js::number_literal;
use crate::domain::sheet::schema::check;
number_literal!(MigrationMapVersion1, 1);
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct LegacyName {
pub fr: String,
pub en: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct MappedAnnotation {
#[serde(deserialize_with = "check::non_empty")]
pub id: String,
pub name: LegacyName,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct ReportMigrationMap {
pub schema_version: MigrationMapVersion1,
pub sheet: SheetRef,
/// Id of the view a v2 zone without `detailSourceId` belongs to.
#[serde(deserialize_with = "check::non_empty")]
pub main_view_id: String,
/// Legacy detail popup key → view id.
#[serde(deserialize_with = "view_record")]
pub views: HashMap<String, String>,
/// Legacy `data-anno-id` → annotation id and the legacy labels.
#[serde(deserialize_with = "record")]
pub annotations: HashMap<String, MappedAnnotation>,
/// `<zoneId>/<path…>` of every legacy finding node → the same key in the sheet, or null.
#[serde(deserialize_with = "record")]
pub finding_paths: HashMap<String, Option<String>>,
}
/// `z.record(…)`: Zod drops a `__proto__` key while rebuilding the object.
fn record<'de, D, T>(d: D) -> Result<HashMap<String, T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
let mut entries = HashMap::<String, T>::deserialize(d)?;
entries.remove("__proto__");
Ok(entries)
}
fn view_record<'de, D: Deserializer<'de>>(d: D) -> Result<HashMap<String, String>, D::Error> {
let views: HashMap<String, String> = record(d)?;
if views.values().any(String::is_empty) {
return Err(D::Error::custom("empty view id"));
}
Ok(views)
}
/// `findingPathKey(zoneId, path)`.
pub fn finding_path_key(zone_id: &str, path: &[String]) -> String {
format!("{zone_id}/{}", path.join("/"))
}
+10
View File
@@ -0,0 +1,10 @@
//! Report contracts: v3 (current), v2 (input only), the migration map, migration and rebase.
pub mod identity;
pub mod migration_map;
pub mod v2;
pub mod v3;
pub use identity::*;
pub use migration_map::{ReportMigrationMap, finding_path_key};
pub use v3::*;
+104
View File
@@ -0,0 +1,104 @@
//! Report document version 2 (`report/v2.ts`), exactly as the deployed application wrote it.
//! An INPUT format only: nothing writes v2 any more, `migrate.rs` lifts it to v3.
use serde::de::Error as _;
use serde::{Deserialize, Deserializer};
use super::identity::{Animal, LateralSide, NextAppointment, Owner, Practitioner};
use super::v3::finding_path;
use crate::domain::js::{self, JsInt, number_literal};
use crate::domain::sheet::schema::check;
number_literal!(ReportVersion2, 2);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub enum SeverityV2 {
#[serde(rename = "légère")]
Legere,
#[serde(rename = "modérée")]
Moderee,
#[serde(rename = "sévère")]
Severe,
}
/// A vertebra of the legacy model: regions C, T, L, S, Cd only.
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct VertebraV2 {
#[serde(deserialize_with = "legacy_region")]
pub region: String,
#[serde(deserialize_with = "check::positive_int")]
pub index: JsInt,
}
fn legacy_region<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let region = String::deserialize(d)?;
if matches!(region.as_str(), "C" | "T" | "L" | "S" | "Cd") {
Ok(region)
} else {
Err(D::Error::custom("unknown legacy vertebral region"))
}
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ObservationZoneV2 {
/// The legacy SVG `data-anno-id`.
#[serde(deserialize_with = "check::non_empty")]
pub bone_id: String,
/// Legacy detail popup key (`head`) when the zone came from that view.
#[serde(default, deserialize_with = "js::present")]
pub detail_source_id: Option<String>,
#[serde(default, deserialize_with = "js::present")]
pub vertebrae: Option<Vec<VertebraV2>>,
#[serde(default, deserialize_with = "js::present")]
pub side: Option<LateralSide>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FindingV2 {
/// Legacy catalog zone key (equal to the canonical finding zone id).
#[serde(deserialize_with = "check::non_empty")]
pub zone_id: String,
#[serde(deserialize_with = "finding_path")]
pub path: Vec<String>,
#[serde(deserialize_with = "check::non_empty")]
pub label_fr_snapshot: String,
#[serde(deserialize_with = "check::non_empty")]
pub label_en_snapshot: String,
#[serde(default, deserialize_with = "js::present")]
pub requires_vet_referral: Option<bool>,
#[serde(default, deserialize_with = "js::present")]
pub side: Option<LateralSide>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ObservationV2 {
#[serde(deserialize_with = "check::non_empty")]
pub id: String,
pub zones: Vec<ObservationZoneV2>,
pub findings: Vec<FindingV2>,
pub free_text_findings: Vec<String>,
#[serde(default, deserialize_with = "js::present")]
pub severity: Option<SeverityV2>,
pub comment: String,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportV2 {
pub version: ReportVersion2,
#[serde(deserialize_with = "check::non_empty")]
pub id: String,
pub created_at: String,
pub date: String,
pub practitioner: Practitioner,
pub animal: Animal,
pub owner: Owner,
pub observations: Vec<ObservationV2>,
pub conclusion: String,
pub recommendations: String,
#[serde(default, deserialize_with = "js::present")]
pub next_appointment: Option<NextAppointment>,
}
+250
View File
@@ -0,0 +1,250 @@
//! Report document version 3 (`report/v3.ts`): zones name an annotation of a view, findings a
//! node path of a finding zone, both by stable ids, with the labels snapshotted. Fields in Zod
//! schema order; `.optional()` fields are absent when unset, nullable ones print `null`.
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::identity::{Animal, LateralSide, NextAppointment, Owner, Practitioner};
use crate::domain::js::{self, JsInt, number_literal};
use crate::domain::sheet::schema::check;
pub const REPORT_VERSION: u32 = 3;
number_literal!(ReportVersion3, 3);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Mild,
Moderate,
Severe,
}
/// One vertebra: the sheet's region code and the 1-based index in that region.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct Vertebra {
#[serde(deserialize_with = "check::non_empty")]
pub region: String,
#[serde(deserialize_with = "check::positive_int")]
#[cfg_attr(feature = "ts", ts(type = "number"))]
pub index: JsInt,
}
/// The sheet document a report was built on, by content.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct SheetRef {
#[serde(deserialize_with = "check::non_empty")]
pub sheet_id: String,
/// Database version id once the sheet lives in the database; `null` for a bundled draft.
#[serde(deserialize_with = "check::nullable_non_empty")]
pub version_id: Option<String>,
/// sha256 of the document file the report was written against.
#[serde(deserialize_with = "sha256")]
pub document_sha256: String,
}
pub(crate) fn sha256<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let text = String::deserialize(d)?;
if js::is_sha256_hex(&text) {
Ok(text)
} else {
Err(D::Error::custom("invalid sha256"))
}
}
/// The literal `true` flag of a zone or finding the sheet cannot place.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Unresolved;
impl Serialize for Unresolved {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_bool(true)
}
}
impl<'de> Deserialize<'de> for Unresolved {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if bool::deserialize(deserializer)? {
Ok(Unresolved)
} else {
Err(D::Error::custom(
"unresolved must be the literal true when present",
))
}
}
}
#[cfg(feature = "ts")]
impl TS for Unresolved {
type WithoutGenerics = Self;
type OptionInnerType = Self;
fn name(_: &ts_rs::Config) -> String {
"true".to_owned()
}
fn inline(cfg: &ts_rs::Config) -> String {
Self::name(cfg)
}
}
/// A zone of an observation.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct ReportZone {
#[serde(deserialize_with = "check::non_empty")]
pub annotation_id: String,
#[serde(deserialize_with = "check::non_empty")]
pub view_id: String,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub side: Option<LateralSide>,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub vertebrae: Option<Vec<Vertebra>>,
/// Annotation name at selection time (or legacy name at migration).
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub label_fr_snapshot: Option<String>,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub label_en_snapshot: Option<String>,
/// Set by the migration when the legacy id has no canonical annotation.
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub unresolved: Option<Unresolved>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct Finding {
#[serde(deserialize_with = "check::non_empty")]
pub finding_zone_id: String,
/// Node ids from the zone's categories down to the leaf.
#[serde(deserialize_with = "finding_path")]
pub path: Vec<String>,
#[serde(deserialize_with = "check::non_empty")]
pub label_fr_snapshot: String,
#[serde(deserialize_with = "check::non_empty")]
pub label_en_snapshot: String,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub requires_vet_referral: Option<bool>,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub side: Option<LateralSide>,
/// Set by the migration when the path no longer exists in the sheet; data kept.
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub unresolved: Option<Unresolved>,
}
/// `z.array(z.string().min(1)).min(1)`.
pub(crate) fn finding_path<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
let path = check::non_empty_strings(d)?;
if path.is_empty() {
Err(D::Error::custom("a finding path has at least one segment"))
} else {
Ok(path)
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct Observation {
#[serde(deserialize_with = "check::non_empty")]
pub id: String,
pub zones: Vec<ReportZone>,
pub findings: Vec<Finding>,
pub free_text_findings: Vec<String>,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub severity: Option<Severity>,
pub comment: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct Report {
pub version: ReportVersion3,
#[serde(deserialize_with = "check::non_empty")]
pub id: String,
/// ISO timestamp of report creation.
pub created_at: String,
/// ISO date of the clinical encounter.
pub date: String,
pub practitioner: Practitioner,
pub animal: Animal,
pub owner: Owner,
pub sheet: SheetRef,
pub observations: Vec<Observation>,
pub conclusion: String,
pub recommendations: String,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub next_appointment: Option<NextAppointment>,
/// Reserved for report-only points (OPEN_QUESTIONS Q6); empty until defined.
#[serde(default, deserialize_with = "no_local_annotations")]
#[cfg_attr(feature = "ts", ts(type = "Array<unknown>"))]
pub local_annotations: Vec<Value>,
}
/// `z.array(z.unknown()).max(0).default([])`.
fn no_local_annotations<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<Value>, D::Error> {
let items = Vec::<Value>::deserialize(d)?;
if items.is_empty() {
Ok(items)
} else {
Err(D::Error::custom("localAnnotations must be empty"))
}
}
+5
View File
@@ -0,0 +1,5 @@
//! The anatomical sheet: document contract, integrity rules, index.
pub mod schema;
pub use schema::*;
+669
View File
@@ -0,0 +1,669 @@
//! Canonical anatomical sheet document, schema_version 2
//! (`packages/domain/src/anatomical-sheet/schema.ts`, ANATOMICAL_SHEET_MODEL.md §2).
//!
//! Every object is strict as in Zod (`deny_unknown_fields`); fields are declared in the Zod
//! schema order, so a parsed document prints as `JSON.stringify(Schema.parse(x), null, 2)`.
//! Cross-references are the integrity tier (`validate.rs`), not the shape.
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
#[cfg(feature = "ts")]
use ts_rs::TS;
use crate::domain::js::{self, JsInt};
pub const SHEET_DOCUMENT_SCHEMA_VERSION: u32 = 2;
/// Field checks, each one a Zod constraint of the schema.
pub(crate) mod check {
use serde::de::Error as _;
use serde::{Deserialize, Deserializer};
use crate::domain::js::{self, JsInt};
fn checked<'de, D: Deserializer<'de>>(
deserializer: D,
rule: fn(&str) -> bool,
what: &str,
) -> Result<String, D::Error> {
let text = String::deserialize(deserializer)?;
if rule(&text) {
Ok(text)
} else {
Err(D::Error::custom(format!("invalid {what}")))
}
}
pub fn non_empty<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
checked(d, js::non_empty, "empty string")
}
pub fn stable_id<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
checked(d, js::is_stable_id, "stable id")
}
pub fn region_code<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
checked(d, js::is_region_code, "region code")
}
pub fn stable_ids<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
let ids = Vec::<String>::deserialize(d)?;
if ids.iter().all(|id| js::is_stable_id(id)) {
Ok(ids)
} else {
Err(D::Error::custom("invalid stable id"))
}
}
pub fn non_empty_strings<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
let items = Vec::<String>::deserialize(d)?;
if items.iter().all(|item| !item.is_empty()) {
Ok(items)
} else {
Err(D::Error::custom("empty string"))
}
}
fn nullable_checked<'de, D: Deserializer<'de>>(
deserializer: D,
rule: fn(&str) -> bool,
what: &str,
) -> Result<Option<String>, D::Error> {
match Option::<String>::deserialize(deserializer)? {
Some(text) if !rule(&text) => Err(D::Error::custom(format!("invalid {what}"))),
other => Ok(other),
}
}
pub fn nullable_stable_id<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
nullable_checked(d, js::is_stable_id, "stable id")
}
pub fn nullable_region_code<'de, D: Deserializer<'de>>(
d: D,
) -> Result<Option<String>, D::Error> {
nullable_checked(d, js::is_region_code, "region code")
}
pub fn nullable_hex_color<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
nullable_checked(d, js::is_hex_color, "colour")
}
pub fn nullable_uuid<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
nullable_checked(d, js::is_uuid, "uuid")
}
pub fn nullable_non_empty<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
nullable_checked(d, js::non_empty, "empty string")
}
/// `z.string().url().refine(/^https?:\/\//i)`, nullable.
pub fn nullable_http_url<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
nullable_checked(d, is_reference_url, "http(s) URL")
}
fn is_reference_url(text: &str) -> bool {
let scheme = text.get(..8).unwrap_or(text).to_ascii_lowercase();
(scheme.starts_with("http://") || scheme.starts_with("https://")) && js::is_url(text)
}
/// `z.number().int().min(1)` (and `.positive()` on integers).
pub fn positive_int<'de, D: Deserializer<'de>>(d: D) -> Result<JsInt, D::Error> {
let value = JsInt::deserialize(d)?;
if value.get() >= 1.0 {
Ok(value)
} else {
Err(D::Error::custom("expected an integer of at least 1"))
}
}
/// `z.number().finite()`.
pub fn finite<'de, D: Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
let value = f64::deserialize(d)?;
if value.is_finite() {
Ok(value)
} else {
Err(D::Error::custom("expected a finite number"))
}
}
/// `z.number().finite().positive()`.
pub fn positive<'de, D: Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
let value = finite(d)?;
if value > 0.0 {
Ok(value)
} else {
Err(D::Error::custom("expected a positive number"))
}
}
}
use crate::domain::js::{literal, number_literal};
literal!(KindMain, "main");
literal!(KindDetail, "detail");
literal!(KindDetailTrigger, "detail_trigger");
literal!(TypeCircle, "circle");
literal!(TypePolygon, "polygon");
literal!(TypePath, "path");
number_literal!(SchemaVersion2, 2);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct LocalizedText {
#[serde(deserialize_with = "check::non_empty")]
pub fr: String,
#[serde(deserialize_with = "check::non_empty")]
pub en: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct LocalizedOptionalText {
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub fr: Option<String>,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub en: Option<String>,
}
/// How far the content was checked against references.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum ReviewStatus {
#[default]
Inherited,
Reviewed,
ToConfirm,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct CountRange {
#[serde(deserialize_with = "check::positive_int")]
#[cfg_attr(feature = "ts", ts(type = "number"))]
pub min: JsInt,
#[serde(deserialize_with = "check::positive_int")]
#[cfg_attr(feature = "ts", ts(type = "number"))]
pub max: JsInt,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct VertebralRegion {
#[serde(deserialize_with = "check::region_code")]
pub code: String,
pub name: LocalizedText,
#[serde(deserialize_with = "check::positive_int")]
#[cfg_attr(feature = "ts", ts(type = "number"))]
pub count: JsInt,
#[serde(default)]
pub count_range: Option<CountRange>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct AnnotationCategory {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
pub name: LocalizedText,
#[serde(deserialize_with = "check::nullable_hex_color")]
pub color: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct ViewBox {
#[serde(deserialize_with = "check::finite")]
pub min_x: f64,
#[serde(deserialize_with = "check::finite")]
pub min_y: f64,
#[serde(deserialize_with = "check::positive")]
pub width: f64,
#[serde(deserialize_with = "check::positive")]
pub height: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct MainView {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
pub name: LocalizedText,
#[serde(deserialize_with = "check::nullable_uuid")]
pub svg_asset_id: Option<String>,
#[serde(deserialize_with = "js::nullable")]
pub view_box: Option<ViewBox>,
pub kind: KindMain,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct DetailView {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
pub name: LocalizedText,
#[serde(deserialize_with = "check::nullable_uuid")]
pub svg_asset_id: Option<String>,
#[serde(deserialize_with = "js::nullable")]
pub view_box: Option<ViewBox>,
pub kind: KindDetail,
#[serde(deserialize_with = "check::stable_id")]
pub parent_view_id: String,
}
/// Views form a tree: a detail names its parent, any depth.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(untagged)]
pub enum SheetView {
Main(MainView),
Detail(DetailView),
}
impl SheetView {
pub fn id(&self) -> &str {
match self {
Self::Main(view) => &view.id,
Self::Detail(view) => &view.id,
}
}
pub fn name(&self) -> &LocalizedText {
match self {
Self::Main(view) => &view.name,
Self::Detail(view) => &view.name,
}
}
pub fn svg_asset_id(&self) -> Option<&str> {
match self {
Self::Main(view) => view.svg_asset_id.as_deref(),
Self::Detail(view) => view.svg_asset_id.as_deref(),
}
}
pub fn view_box(&self) -> Option<&ViewBox> {
match self {
Self::Main(view) => view.view_box.as_ref(),
Self::Detail(view) => view.view_box.as_ref(),
}
}
/// The parent of a detail view; `None` for the main view.
pub fn parent_view_id(&self) -> Option<&str> {
match self {
Self::Main(_) => None,
Self::Detail(view) => Some(&view.parent_view_id),
}
}
pub fn is_main(&self) -> bool {
matches!(self, Self::Main(_))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct Circle {
#[serde(rename = "type")]
pub kind: TypeCircle,
#[serde(deserialize_with = "check::finite")]
pub cx: f64,
#[serde(deserialize_with = "check::finite")]
pub cy: f64,
#[serde(deserialize_with = "check::positive")]
pub r: f64,
}
/// A polygon point: a pair of finite numbers.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct Point(pub f64, pub f64);
impl<'de> Deserialize<'de> for Point {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let (x, y) = <(f64, f64)>::deserialize(deserializer)?;
if x.is_finite() && y.is_finite() {
Ok(Point(x, y))
} else {
Err(D::Error::custom("expected finite coordinates"))
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct Polygon {
#[serde(rename = "type")]
pub kind: TypePolygon,
#[serde(deserialize_with = "at_least_three")]
pub points: Vec<Point>,
}
fn at_least_three<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<Point>, D::Error> {
let points = Vec::<Point>::deserialize(d)?;
if points.len() >= 3 {
Ok(points)
} else {
Err(D::Error::custom("a polygon has at least 3 points"))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct PathGeometry {
#[serde(rename = "type")]
pub kind: TypePath,
#[serde(deserialize_with = "check::non_empty")]
pub d: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(untagged)]
pub enum Geometry {
Circle(Circle),
Polygon(Polygon),
Path(PathGeometry),
}
/// Explicit on every annotation: absence no longer carries meaning.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum Laterality {
Unpaired,
Bilateral,
Left,
Right,
}
/// The two observable annotation kinds share one shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum ObservableKind {
Point,
Zone,
}
/// A point or zone annotation: observable, linked to findings by one explicit field.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct ObservableAnnotation {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
#[serde(deserialize_with = "check::stable_id")]
pub view_id: String,
#[serde(deserialize_with = "check::stable_id")]
pub category_id: String,
pub laterality: Laterality,
#[serde(deserialize_with = "js::nullable")]
pub geometry: Option<Geometry>,
#[serde(default)]
pub review_status: ReviewStatus,
#[serde(default, deserialize_with = "check::nullable_hex_color")]
pub color: Option<String>,
pub name: LocalizedText,
#[serde(deserialize_with = "check::nullable_stable_id")]
pub finding_zone_id: Option<String>,
#[serde(deserialize_with = "check::nullable_region_code")]
pub vertebral_region_code: Option<String>,
pub kind: ObservableKind,
}
/// Navigation only: a trigger opens a detail view and never carries findings.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct DetailTriggerAnnotation {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
#[serde(deserialize_with = "check::stable_id")]
pub view_id: String,
#[serde(deserialize_with = "check::stable_id")]
pub category_id: String,
pub laterality: Laterality,
#[serde(deserialize_with = "js::nullable")]
pub geometry: Option<Geometry>,
#[serde(default)]
pub review_status: ReviewStatus,
#[serde(default, deserialize_with = "check::nullable_hex_color")]
pub color: Option<String>,
pub kind: KindDetailTrigger,
#[serde(deserialize_with = "js::nullable")]
pub name: Option<LocalizedText>,
#[serde(deserialize_with = "check::stable_id")]
pub opens_view_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(untagged)]
pub enum Annotation {
Observable(ObservableAnnotation),
DetailTrigger(DetailTriggerAnnotation),
}
impl Annotation {
pub fn id(&self) -> &str {
match self {
Self::Observable(a) => &a.id,
Self::DetailTrigger(a) => &a.id,
}
}
pub fn view_id(&self) -> &str {
match self {
Self::Observable(a) => &a.view_id,
Self::DetailTrigger(a) => &a.view_id,
}
}
pub fn category_id(&self) -> &str {
match self {
Self::Observable(a) => &a.category_id,
Self::DetailTrigger(a) => &a.category_id,
}
}
pub fn observable(&self) -> Option<&ObservableAnnotation> {
match self {
Self::Observable(a) => Some(a),
Self::DetailTrigger(_) => None,
}
}
pub fn trigger(&self) -> Option<&DetailTriggerAnnotation> {
match self {
Self::Observable(_) => None,
Self::DetailTrigger(a) => Some(a),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum ReferenceType {
Book,
Journal,
Standard,
Legal,
Web,
Manual,
}
/// One bibliographic reference, declared once and cited by id.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct Reference {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
#[serde(rename = "type")]
pub kind: ReferenceType,
#[serde(deserialize_with = "check::non_empty")]
pub citation: String,
#[serde(default, deserialize_with = "check::nullable_http_url")]
pub url: Option<String>,
#[serde(default, deserialize_with = "check::nullable_non_empty")]
pub doi: Option<String>,
}
/// A finding node; every optional key of the authoring form is filled in when parsed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct FindingNode {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
pub name: LocalizedText,
#[serde(default)]
pub description: LocalizedOptionalText,
#[serde(default)]
pub requires_vet_referral: bool,
#[serde(default, deserialize_with = "check::stable_ids")]
pub reference_ids: Vec<String>,
#[serde(default)]
pub review_status: ReviewStatus,
#[serde(default)]
pub children: Vec<FindingNode>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum FindingCategoryKind {
Dysfunction,
ConsultationReason,
Anamnesis,
Custom,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct FindingCategory {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
pub kind: FindingCategoryKind,
pub name: LocalizedText,
#[serde(default)]
pub description: LocalizedOptionalText,
#[serde(default, deserialize_with = "check::stable_ids")]
pub reference_ids: Vec<String>,
#[serde(default)]
pub review_status: ReviewStatus,
pub children: Vec<FindingNode>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct FindingZone {
#[serde(deserialize_with = "check::stable_id")]
pub id: String,
pub name: LocalizedText,
pub categories: Vec<FindingCategory>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct Attribution {
#[serde(deserialize_with = "check::non_empty_strings")]
pub authors: Vec<String>,
#[serde(deserialize_with = "check::nullable_non_empty")]
pub license: Option<String>,
#[serde(deserialize_with = "check::nullable_non_empty")]
pub notes: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct VertebralConfig {
pub regions: Vec<VertebralRegion>,
}
/// The canonical sheet document (schema_version 2).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(deny_unknown_fields)]
pub struct AnatomicalSheetDocument {
pub schema_version: SchemaVersion2,
#[serde(deserialize_with = "check::stable_id")]
pub species_id: String,
pub name: LocalizedText,
pub description: LocalizedOptionalText,
pub scope_disclaimer: LocalizedOptionalText,
pub attribution: Attribution,
pub vertebral_config: VertebralConfig,
pub references: Vec<Reference>,
pub categories: Vec<AnnotationCategory>,
pub views: Vec<SheetView>,
pub annotations: Vec<Annotation>,
pub finding_zones: Vec<FindingZone>,
}
/// A category or a node of a finding tree: what `nodeAt` returns.
pub enum FindingTreeItem<'a> {
Category(&'a FindingCategory),
Node(&'a FindingNode),
}
impl<'a> FindingTreeItem<'a> {
pub fn id(&self) -> &'a str {
match self {
Self::Category(c) => &c.id,
Self::Node(n) => &n.id,
}
}
pub fn name(&self) -> &'a LocalizedText {
match self {
Self::Category(c) => &c.name,
Self::Node(n) => &n.name,
}
}
pub fn children(&self) -> &'a [FindingNode] {
match self {
Self::Category(c) => &c.children,
Self::Node(n) => &n.children,
}
}
/// Categories carry no vet flag (`'requires_vet_referral' in leaf` is false for them).
pub fn requires_vet_referral(&self) -> bool {
match self {
Self::Category(_) => false,
Self::Node(n) => n.requires_vet_referral,
}
}
}
+25
View File
@@ -0,0 +1,25 @@
//! Shared helpers of the core integration tests: repository files and the Zod oracles.
#![allow(
dead_code,
clippy::disallowed_methods,
clippy::unwrap_used,
clippy::expect_used
)]
use serde_json::Value;
/// A repository file, by path from the repository root.
pub fn repo_file(relative: &str) -> String {
let path = format!("{}/../../{relative}", env!("CARGO_MANIFEST_DIR"));
std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{path}: {error}"))
}
/// A Zod oracle (`crates/core/tests/oracles/<name>`): its source file and the Zod output in
/// the JavaScript pretty form.
pub fn zod_oracle(name: &str) -> (String, String) {
let oracle: Value =
serde_json::from_str(&repo_file(&format!("crates/core/tests/oracles/{name}"))).unwrap();
let source = oracle["source"].as_str().unwrap().to_owned();
let output = faunosteo_core::json::to_js_pretty(&oracle["output"]).unwrap();
(repo_file(&source), output)
}
@@ -0,0 +1 @@
{"source":"supabase/seed/anatomical-sheets/equine/draft/report-migration-map.json","output":{"schema_version":1,"sheet":{"sheetId":"503dc301-a8b1-50d4-9e44-0919b2fc2916","versionId":null,"documentSha256":"27c7383c445c73dc2001ebf4794a3ea63d416910bbbaa0d7848dd720de7c2660"},"main_view_id":"main","views":{"head":"head"},"annotations":{"point-mpbwrkp0":{"id":"hind-fetlock","name":{"fr":"Boulet post. (métatarso-phalangien)","en":"Hind fetlock"}},"point-mpbwsi9q":{"id":"hock","name":{"fr":"Jarret (tarsien)","en":"Hock"}},"point-mpbwt4fa":{"id":"stifle","name":{"fr":"Grasset (fémoro-tibial)","en":"Stifle"}},"point-mpbwtst0":{"id":"hip","name":{"fr":"Hanche (coxo-fémorale)","en":"Hip joint"}},"point-mpbwugty":{"id":"sacroiliac","name":{"fr":"Articulation Sacro-Iliaque","en":"Sacroiliac Joint"}},"point-mpbwv4xy":{"id":"shoulder","name":{"fr":"Épaule (scapulo-humérale)","en":"Shoulder joint"}},"point-mpbwvpvt":{"id":"elbow","name":{"fr":"Coude (huméro-radial)","en":"Elbow joint"}},"point-mpbwwaru":{"id":"fore-fetlock","name":{"fr":"Boulet ant. (métacarpo-phalangien)","en":"Fore fetlock"}},"point-mpbwwxvn":{"id":"fore-sesamoids","name":{"fr":"Sésamoïdes ant. (boulet)","en":"Forelimb Sesamoids"}},"point-mpbwxnb4":{"id":"l6-s1","name":{"fr":"Charnière L6-S1 (lombo-sacrée)","en":"L6-S1 (Lumbosacral)"}},"point-mpbwyd9i":{"id":"t18-l1","name":{"fr":"Charnière T18-L1 (dorso-lombaire)","en":"T18-L1 (Thoracolumbar)"}},"point-mpbwyyc9":{"id":"c7-t1","name":{"fr":"Charnière C7-T1 (cervico-thoracique)","en":"C7-T1 (Cervicothoracic)"}},"zone-mpbx00jq":{"id":"caudal","name":{"fr":"Vertèbres caudales","en":"Coccygeal Vertebrae"}},"zone-mpbx0xnp":{"id":"sacral","name":{"fr":"Vertèbres sacrales","en":"Sacral Vertebrae"}},"zone-mpbx1rm9":{"id":"lumbar","name":{"fr":"Vertèbres lombaires","en":"Lumbar Vertebrae"}},"zone-mpbx2rpe":{"id":"thoracic","name":{"fr":"Vertèbres thoraciques","en":"Thoracic Vertebrae"}},"zone-mpbx5hx2":{"id":"cervical","name":{"fr":"Vertèbres cervicales","en":"Cervical Vertebrae"}},"zone-mpby55kd":{"id":"head-trigger","name":{"fr":"","en":""}},"point-mpbykomv":{"id":"parietal","name":{"fr":"Pariétal","en":"Parietal bone"}},"point-mpbylh35":{"id":"frontal","name":{"fr":"Frontal","en":"Frontal bone"}},"point-mpbymcln":{"id":"sphenoid","name":{"fr":"Sphénoïde","en":"Sphenoid"}},"point-mpbyn2k3":{"id":"temporal","name":{"fr":"Temporel","en":"Temporal"}},"point-mpbynls5":{"id":"occipital","name":{"fr":"Occipital","en":"Occipital"}},"point-mpbyo7zq":{"id":"atm","name":{"fr":"Articulation Temporo-Mandibulaire (ATM)","en":"Temporomandibular Joint (TMJ)"}},"point-mpbyphay":{"id":"ssb","name":{"fr":"Synchondrose Sphéno-Basilaire (SSB)","en":"Spheno-Basilar Synchondrosis (SBS)"}},"point-mpbyq841":{"id":"hyoid","name":{"fr":"Hyoïde","en":"Hyoid"}},"point-mpbyqxbg":{"id":"c0-c1","name":{"fr":"Charnière C0-C1 (occipito-atloïdienne)","en":"C0-C1 (Occipito-atlantal)"}}},"finding_paths":{"parietal/parietal-dysfunctions":"parietal/parietal-dysfunctions","parietal/parietal-dysfunctions/mobility":"parietal/parietal-dysfunctions/mobility","parietal/parietal-dysfunctions/mobility/flexion-external-rotation":"parietal/parietal-dysfunctions/mobility/flexion-external-rotation","parietal/parietal-dysfunctions/mobility/extension-internal-rotation":"parietal/parietal-dysfunctions/mobility/extension-internal-rotation","parietal/parietal-dysfunctions/mobility/global-restriction":"parietal/parietal-dysfunctions/mobility/global-restriction","parietal/parietal-dysfunctions/intraosseous":"parietal/parietal-dysfunctions/intraosseous","parietal/parietal-dysfunctions/intraosseous/squama-deformation":"parietal/parietal-dysfunctions/intraosseous/squama-deformation","parietal/parietal-dysfunctions/intraosseous/interparietal-compression":"parietal/parietal-dysfunctions/intraosseous/interparietal-compression","parietal/parietal-dysfunctions/sutures":"parietal/parietal-dysfunctions/sutures","parietal/parietal-dysfunctions/sutures/frontoparietal":"parietal/parietal-dysfunctions/sutures/frontoparietal","parietal/parietal-dysfunctions/sutures/parieto-occipital":"parietal/parietal-dysfunctions/sutures/parieto-occipital","parietal/parietal-dysfunctions/sutures/parieto-temporal":"parietal/parietal-dysfunctions/sutures/parieto-temporal","parietal/parietal-dysfunctions/sutures/sphenoparietal":"parietal/parietal-dysfunctions/sutures/sphenoparietal","parietal/parietal-dysfunctions/sutures/interparietal":"parietal/parietal-dysfunctions/sutures/sagittal","parietal/parietal-observations":"parietal/parietal-consultation-reasons","parietal/parietal-observations/behavior-change":"parietal/parietal-consultation-reasons/behavior-change","parietal/parietal-observations/behavior-change/head-touch-hypersensitivity":"parietal/parietal-consultation-reasons/behavior-change/head-touch-hypersensitivity","parietal/parietal-observations/behavior-change/new-irritability":"parietal/parietal-consultation-reasons/behavior-change/new-irritability","parietal/parietLine truncated
@@ -0,0 +1 @@
{"source":"apps/app/tests/fixtures/report-v2.full.json","output":{"version":2,"id":"fixture-full-v2","createdAt":"2026-06-01T09:00:00.000Z","date":"2026-06-01","practitioner":{"name":"Dr. Claire Dupont","cabinet":"Cabinet Équi-Ostéo","contact":"claire@example.test","siret":"12345678901234"},"animal":{"speciesId":"equine","name":"Mistral","breed":"Selle Français","age":"9 ans"},"owner":{"name":"Jean Martin"},"observations":[{"id":"obs-1","zones":[{"boneId":"point-mpbwyyc9"},{"boneId":"point-mpbwtst0","side":"left"},{"boneId":"point-mpbwtst0","side":"right"}],"findings":[{"zoneId":"c7-t1","path":["c7-t1-dysfunctions","segmental","fixation"],"labelFrSnapshot":"Fixation de la charnière","labelEnSnapshot":"Junction fixation"},{"zoneId":"hip","path":["hip-dysfunctions","articular","restriction-flexion"],"labelFrSnapshot":"Restriction en flexion","labelEnSnapshot":"Flexion restriction","side":"left"}],"freeTextFindings":["Sensibilité au garrot"],"severity":"modérée","comment":"Réagit à la palpation du garrot."},{"id":"obs-2","zones":[{"boneId":"zone-mpbx5hx2","vertebrae":[{"region":"C","index":3},{"region":"C","index":4}]}],"findings":[{"zoneId":"cervical","path":["cervical-observations","stumbling-proprioceptive"],"labelFrSnapshot":"Trébuchements / déficit proprioceptif rapporté","labelEnSnapshot":"Reported stumbling / proprioceptive deficit","requiresVetReferral":true}],"freeTextFindings":[],"severity":"sévère","comment":""},{"id":"obs-3","zones":[{"boneId":"point-mpbyo7zq","detailSourceId":"head"}],"findings":[{"zoneId":"atm","path":["atm-observations","headshaking"],"labelFrSnapshot":"Headshaking (secouement de tête)","labelEnSnapshot":"Headshaking","requiresVetReferral":true}],"freeTextFindings":[],"comment":"Vue détail tête."}],"conclusion":"Dysfonction cervico-thoracique avec compensation du bassin.","recommendations":"Repos 3 jours puis reprise progressive.","nextAppointment":{"kind":"date","date":"2026-07-01"}}}
@@ -0,0 +1 @@
{"source":"apps/app/tests/fixtures/report-v2.minimal.json","output":{"version":2,"id":"fixture-minimal-v2","createdAt":"2026-06-01T09:00:00.000Z","date":"2026-06-01","practitioner":{"name":"Dr. Dupont"},"animal":{"speciesId":"equine","name":"Mistral"},"owner":{"name":"Jean Martin"},"observations":[],"conclusion":"","recommendations":""}}
@@ -0,0 +1 @@
{"source":"apps/app/tests/fixtures/report-v3.demo.json","output":{"version":3,"id":"fixture-demo-v3","createdAt":"2026-10-11T09:30:00.000Z","date":"2026-10-11","practitioner":{"name":"Dr. Claire Dupont","cabinet":"Cabinet Équi-Ostéo","contact":"claire@example.test","siret":"12345678901234"},"animal":{"speciesId":"equine","name":"Mistral","breed":"Selle Français","age":"9 ans"},"owner":{"name":"Jean Martin"},"sheet":{"sheetId":"503dc301-a8b1-50d4-9e44-0919b2fc2916","versionId":null,"documentSha256":"27c7383c445c73dc2001ebf4794a3ea63d416910bbbaa0d7848dd720de7c2660"},"observations":[{"id":"obs-demo-1","zones":[{"annotationId":"c7-t1","viewId":"main","labelFrSnapshot":"Charnière C7-T1 (cervico-thoracique)","labelEnSnapshot":"C7-T1 junction (cervicothoracic)"},{"annotationId":"t18-l1","viewId":"main","labelFrSnapshot":"Charnière T18-L1 (thoraco-lombaire)","labelEnSnapshot":"T18-L1 junction (thoracolumbar)"}],"findings":[{"findingZoneId":"c7-t1","path":["c7-t1-dysfunctions","segmental","restriction-flexion"],"labelFrSnapshot":"Restriction en flexion","labelEnSnapshot":"Flexion restriction"},{"findingZoneId":"c7-t1","path":["c7-t1-dysfunctions","segmental","restriction-extension"],"labelFrSnapshot":"Restriction en extension","labelEnSnapshot":"Extension restriction"}],"freeTextFindings":[],"severity":"mild","comment":"Réagit à la palpation de la charnière."},{"id":"obs-demo-2","zones":[{"annotationId":"hip","viewId":"main","side":"left","labelFrSnapshot":"Hanche (coxo-fémorale)","labelEnSnapshot":"Hip joint"},{"annotationId":"hip","viewId":"main","side":"right","labelFrSnapshot":"Hanche (coxo-fémorale)","labelEnSnapshot":"Hip joint"}],"findings":[{"findingZoneId":"hip","path":["hip-dysfunctions","articular","restriction-flexion"],"labelFrSnapshot":"Restriction en flexion","labelEnSnapshot":"Flexion restriction","side":"left"},{"findingZoneId":"hip","path":["hip-dysfunctions","articular","restriction-abduction-adduction"],"labelFrSnapshot":"Restriction en abduction / adduction","labelEnSnapshot":"Abduction / adduction restriction","side":"right"}],"freeTextFindings":[],"severity":"moderate","comment":""},{"id":"obs-demo-3","zones":[{"annotationId":"cervical","viewId":"main","vertebrae":[{"region":"C","index":3},{"region":"C","index":4}],"labelFrSnapshot":"Vertèbres cervicales","labelEnSnapshot":"Cervical vertebrae"}],"findings":[{"findingZoneId":"cervical","path":["cervical-dysfunctions","segmental","localized-fixation"],"labelFrSnapshot":"Fixation segmentaire localisée (C2–C7)","labelEnSnapshot":"Localized segmental fixation (C2–C7)"}],"freeTextFindings":[],"severity":"severe","comment":"Fixation nette en latéroflexion droite."},{"id":"obs-demo-4","zones":[{"annotationId":"atm","viewId":"head","labelFrSnapshot":"Articulation temporo-mandibulaire (ATM)","labelEnSnapshot":"Temporomandibular joint (TMJ)"},{"annotationId":"frontal","viewId":"head","labelFrSnapshot":"Frontal","labelEnSnapshot":"Frontal bone"}],"findings":[{"findingZoneId":"frontal","path":["frontal-consultation-reasons","head-rubbing"],"labelFrSnapshot":"Frottements répétés de la tête rapportés","labelEnSnapshot":"Reported repeated head rubbing","requiresVetReferral":true},{"findingZoneId":"atm","path":["atm-dysfunctions","articular","restriction-opening"],"labelFrSnapshot":"Restriction à l'ouverture","labelEnSnapshot":"Opening restriction"}],"freeTextFindings":[],"comment":""},{"id":"obs-demo-5","zones":[{"annotationId":"sacroiliac","viewId":"main","side":"right","labelFrSnapshot":"Articulation sacro-iliaque","labelEnSnapshot":"Sacroiliac joint"},{"annotationId":"occipital","viewId":"head","labelFrSnapshot":"Occipital","labelEnSnapshot":"Occipital bone"}],"findings":[],"freeTextFindings":["Sensibilité au garrot","Tension du ligament nuchal"],"severity":"mild","comment":"Compensation probable."},{"id":"obs-demo-6","zones":[{"annotationId":"lumbar","viewId":"main","vertebrae":[{"region":"L","index":2},{"region":"L","index":3}],"labelFrSnapshot":"Vertèbres lombaires","labelEnSnapshot":"Lumbar vertebrae"},{"annotationId":"l6-s1","viewId":"main","labelFrSnapshot":"Charnière L6-S1 (lombo-sacrée)","labelEnSnapshot":"L6-S1 junction (lumbosacral joint)"}],"findings":[{"findingZoneId":"lumbar","path":["lumbar-dysfunctions","segmental","restriction-extension"],"labelFrSnapshot":"Restriction en extension","labelEnSnapshot":"Extension restriction"}],"freeTextFindings":["Raideur lombaire au pas"],"comment":""}],"conclusion":"Dysfonction cervico-thoracique avec compensation du bassin et tension crânienne associée.","recommendations":"Repos 3 jours puis reprise progressive ; contrôle vétérinaire pour les frottements de tête.","nextAppointment":{"kind":"period","text":"6 à 8 semaines"},"localAnnotations":[]}}
@@ -0,0 +1 @@
{"source":"supabase/seed/anatomical-sheets/equine/draft/document.json","output":{"schema_version":2,"species_id":"equine","name":{"fr":"Cheval","en":"Horse"},"description":{"fr":"Fiche anatomique officielle Faunosteo du cheval (Equus caballus)","en":"Official Faunosteo anatomical sheet of the horse (Equus caballus)"},"scope_disclaimer":{"fr":"Les éléments listés relèvent du périmètre légal de l'ostéopathie animale (art. L. 243-3 12° et R. 243-6 du Code rural et de la pêche maritime) : dysfonctions ostéopathiques palpées, observations cliniques et motifs de consultation rapportés. Aucun diagnostic médical n'est posé. Toute pathologie organique relève du vétérinaire ; conformément à l'art. R. 243-8, le propriétaire est orienté vers un vétérinaire lorsque les symptômes ou lésions nécessitent un diagnostic ou un traitement médical, persistent ou s'aggravent.","en":"The items listed fall within the legal scope of animal osteopathy in France (Articles L. 243-3 (12°) and R. 243-6 of the Code rural et de la pêche maritime): palpated osteopathic dysfunctions, clinical observations and reported reasons for consultation. No medical diagnosis is made. Any organic disease is a matter for a veterinarian; under Article R. 243-8 the owner is referred to a veterinarian whenever symptoms or lesions require a medical diagnosis or treatment, persist or worsen."},"attribution":{"authors":["Faunosteo"],"license":null,"notes":"Import des données historiques: Horse.svg, Horse_head.svg, pathologies.json (schema 2.0)"},"vertebral_config":{"regions":[{"code":"C","name":{"fr":"Cervicales","en":"Cervical"},"count":7,"count_range":null},{"code":"T","name":{"fr":"Thoraciques","en":"Thoracic"},"count":18,"count_range":{"min":17,"max":19}},{"code":"L","name":{"fr":"Lombaires","en":"Lumbar"},"count":6,"count_range":{"min":5,"max":6}},{"code":"S","name":{"fr":"Sacrales","en":"Sacral"},"count":5,"count_range":null},{"code":"Cd","name":{"fr":"Caudales","en":"Caudal"},"count":18,"count_range":{"min":15,"max":21}}]},"references":[{"id":"legacy-catalog","type":"manual","citation":"Catalogue historique Faunosteo (pathologies.json, schéma 2.0), import du 2026-10-09","url":null,"doi":null},{"id":"cr-l243-3","type":"legal","citation":"Code rural et de la pêche maritime, art. L. 243-3 12° (dérogation : actes d'ostéopathie animale ; texte consolidé non rouvert sur Légifrance, article confirmé par la réponse ministérielle QE 8187 et le CNOV)","url":"https://www.legifrance.gouv.fr/codes/article_lc/LEGIARTI000033449047","doi":null},{"id":"decret-2017-572","type":"legal","citation":"Décret n° 2017-572 du 19 avril 2017 relatif aux actes d'ostéopathie animale","url":"https://www.legifrance.gouv.fr/jorf/id/JORFTEXT000034450108","doi":null},{"id":"nav-2017","type":"standard","citation":"International Committee on Veterinary Gross Anatomical Nomenclature. Nomina Anatomica Veterinaria, 6e éd., 2017 (WAVA). Osteologia p. 11-16 (ossa cranii, os hyoideum), Arthrologia (suturae capitis, synchondroses cranii)","url":"https://www.vetmed.uni-leipzig.de/fileadmin/Fakult%C3%A4t_VMF/Institut_Veterin%C3%A4r-Anatomisches/Dokumente/NAV_6th-Edition-2017.pdf","doi":null},{"id":"sisson-1914","type":"book","citation":"Sisson S. The Anatomy of the Domestic Animals. Philadelphia : W.B. Saunders, 1914 (texte intégral ; éditions révisées Grossman 1953, Getty 1975). Crâne du cheval p. 52-69, hyoïde p. 70-71, articulations de la tête p. 214-217, muscles de la mandibule et de l'hyoïde p. 261-266","url":"https://archive.org/stream/anatomyofdomesti01siss/anatomyofdomesti01siss_djvu.txt","doi":null},{"id":"umn-large-animal","type":"web","citation":"University of Minnesota. Large Animal Anatomy (manuel ouvert), chapitre « Neck & Head », consulté le 2026-10-10","url":"https://open.lib.umn.edu/largeanimalanatomy/chapter/neck-head/","doi":null},{"id":"lim-2013","type":"journal","citation":"Lim CK, Saulez MN, Viljoen A, Carstens A. Basilar skull fracture in a Thoroughbred colt: radiography or computed tomography? J S Afr Vet Assoc 2013;84(1), art. 19","url":"https://scielo.org.za/scielo.php?script=sci_arttext&pid=S1019-91282013000100032","doi":null},{"id":"who-2010","type":"standard","citation":"Organisation mondiale de la Santé. Benchmarks for training in osteopathy. Genève : OMS, 2010. ISBN 978 92 4 159966 5 (section 1.2, « somatic dysfunction »)","url":"https://oialliance.org/wp-content/uploads/2024/02/BenchmarksforTraininginOsteopathy-1.pdf","doi":null},{"id":"guillaud-2016","type":"journal","citation":"Guillaud A, Darbois N, Monvoisin R, Pinsault N. Reliability of diagnosis and clinical efficacy of cranial osteopathy: a systematic review. PLoS ONE 2016;11(12):e0167823","url":"https://doi.org/10.1371/journal.pone.0167823","doi":"10.1371/journal.pone.0167823"},{"id":"jakel-2011","type":"journal","citation":"Jäkel A, von Hauenschild P. Therapeutic effects of cranial osteopathic manipulative medicine: a systematic review. J Am OsteLine truncated
@@ -0,0 +1 @@
{"source":"supabase/seed/anatomical-sheets/equine/legacy-import/document.json","output":{"schema_version":2,"species_id":"equine","name":{"fr":"Cheval","en":"Horse"},"description":{"fr":"Fiche anatomique officielle Faunosteo","en":"Official Faunosteo anatomical sheet"},"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":null,"notes":"Import des données historiques: Horse.svg, Horse_head.svg, pathologies.json (schema 2.0)"},"vertebral_config":{"regions":[{"code":"C","name":{"fr":"Cervicales","en":"Cervical"},"count":7,"count_range":null},{"code":"T","name":{"fr":"Thoraciques","en":"Thoracic"},"count":18,"count_range":null},{"code":"L","name":{"fr":"Lombaires","en":"Lumbar"},"count":6,"count_range":null},{"code":"S","name":{"fr":"Sacrales","en":"Sacral"},"count":5,"count_range":null},{"code":"Cd","name":{"fr":"Caudales","en":"Caudal"},"count":18,"count_range":null}]},"references":[],"categories":[{"id":"articulations","name":{"fr":"Articulations","en":"Joints"},"color":null},{"id":"os","name":{"fr":"Os","en":"Bones"},"color":null},{"id":"charnieres-vertebrales","name":{"fr":"Charnières vertébrales","en":"Vertebral hinges"},"color":null},{"id":"zone-colonne","name":{"fr":"Zone colonne","en":"Spine"},"color":null},{"id":"cadrans-du-crane","name":{"fr":"Cadrans du crâne","en":"Skull quadrants"},"color":null}],"views":[{"id":"main","name":{"fr":"Vue générale","en":"Overview"},"svg_asset_id":"8bc2cd09-5fca-54c6-a78e-bdd3f6abaa3a","view_box":null,"kind":"main"},{"id":"head","name":{"fr":"Tête","en":"Head"},"svg_asset_id":"5043348c-b84b-50c3-bbf8-01ff539d163c","view_box":null,"kind":"detail","parent_view_id":"main"}],"annotations":[{"id":"hind-fetlock","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":1523,"cy":1397,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Boulet post. (métatarso-phalangien)","en":"Hind fetlock"},"finding_zone_id":"hind-fetlock","vertebral_region_code":null,"kind":"point"},{"id":"hock","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":1542,"cy":1159,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Jarret (tarsien)","en":"Hock"},"finding_zone_id":"hock","vertebral_region_code":null,"kind":"point"},{"id":"stifle","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":1464,"cy":918,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Grasset (fémoro-tibial)","en":"Stifle"},"finding_zone_id":"stifle","vertebral_region_code":null,"kind":"point"},{"id":"hip","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":1516,"cy":695,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Hanche (coxo-fémorale)","en":"Hip joint"},"finding_zone_id":"hip","vertebral_region_code":null,"kind":"point"},{"id":"sacroiliac","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":1590,"cy":606,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Articulation Sacro-Iliaque","en":"Sacroiliac Joint"},"finding_zone_id":"sacroiliac","vertebral_region_code":null,"kind":"point"},{"id":"shoulder","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":784,"cy":907,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Épaule (scapulo-humérale)","en":"Shoulder joint"},"finding_zone_id":"shoulder","vertebral_region_code":null,"kind":"point"},{"id":"elbow","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":743.0451049804688,"cy":1193,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Coude (huméro-radial)","en":"Elbow joint"},"finding_zone_id":"elbow","vertebral_region_code":null,"kind":"point"},{"id":"fore-fetlock","view_id":"main","category_id":"articulations","laterality":"bilateral","geometry":{"type":"circle","cx":736,"cy":1379,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Boulet ant. (métacarpo-phalangien)","en":"Fore fetlock"},"finding_zone_id":"fore-fetlock","vertebral_region_code":null,"kind":"point"},{"id":"fore-sesamoids","view_id":"main","category_id":"os","laterality":"bilateral","geometry":{"type":"circle","cx":784,"cy":1371,"r":34},"review_status":"inherited","color":null,"name":{"fr":"Sésamoïdes ant. (boulet)","en":"Forelimb Sesamoids"},"finding_zone_id":"fore-sesamoids","vertebral_region_code":null,"kind":"point"},{"id":"l6-s1","view_id":"main","category_id":"charnieres-vertebrales","laterality":"unpaired","geometry":{"type":"circle","cx":1424.2662353515625,"Line truncated
+41
View File
@@ -0,0 +1,41 @@
//! Report contracts against the Zod oracles.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::report::v2::ReportV2;
use faunosteo_core::domain::report::{Report, ReportMigrationMap};
use faunosteo_core::json::to_js_pretty;
#[test]
fn the_demo_report_prints_as_zod_outputs_it() {
let (source, expected) = common::zod_oracle("report-v3.demo.json");
let report: Report = serde_json::from_value(parse_json(&source).unwrap()).unwrap();
assert_eq!(to_js_pretty(&report).unwrap(), expected);
}
#[test]
fn the_v2_fixtures_and_the_migration_map_parse() {
for name in ["report-v2.full.json", "report-v2.minimal.json"] {
let (source, _) = common::zod_oracle(name);
let parsed: Result<ReportV2, _> = serde_json::from_value(parse_json(&source).unwrap());
assert!(parsed.is_ok(), "{name}: {parsed:?}");
}
let (source, _) = common::zod_oracle("migration-map.draft.json");
let map: ReportMigrationMap = serde_json::from_value(parse_json(&source).unwrap()).unwrap();
assert!(map.annotations.len() > 20 && map.finding_paths.len() > 600);
}
#[test]
fn the_frozen_envelopes_parse_and_print_as_their_attachment() {
use faunosteo_core::domain::archive::ReportArchiveEnvelope;
for name in ["demo", "v2full", "v2unresolved"] {
let text = common::repo_file(&format!(
"apps/app/tests/fixtures/goldens/r2/envelope.{name}.fr.nologos.json"
));
let envelope: ReportArchiveEnvelope =
serde_json::from_value(parse_json(&text).unwrap()).unwrap();
assert_eq!(to_js_pretty(&envelope).unwrap(), text, "{name}");
}
}
+26
View File
@@ -0,0 +1,26 @@
//! The sheet document contract against the Zod oracles: the reference documents parse and
//! print byte for byte as `JSON.stringify(AnatomicalSheetDocumentSchema.parse(x), null, 2)`.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
use faunosteo_core::json::to_js_pretty;
fn assert_like_zod(oracle: &str) {
let (source, expected) = common::zod_oracle(oracle);
let document: AnatomicalSheetDocument =
serde_json::from_value(parse_json(&source).unwrap()).unwrap();
assert_eq!(to_js_pretty(&document).unwrap(), expected, "{oracle}");
}
#[test]
fn the_curated_draft_prints_as_zod_outputs_it() {
assert_like_zod("sheet.draft.json");
}
#[test]
fn the_legacy_import_baseline_prints_as_zod_outputs_it() {
assert_like_zod("sheet.legacy-import.json");
}
@@ -0,0 +1,18 @@
import { readdirSync, readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
/** The ts-rs output directory and its hand-kept index must list the same types. */
describe('types/index.ts', () => {
it('re-exports every generated type file', () => {
const dir = fileURLToPath(new URL('../types/', import.meta.url))
const generated = readdirSync(dir)
.filter((f) => f.endsWith('.ts') && f !== 'index.ts')
.map((f) => f.slice(0, -3))
.sort()
const index = readFileSync(`${dir}index.ts`, 'utf8')
const exported = [...index.matchAll(/export type \{ (\w+) \}/g)]
.map((m) => m[1])
.sort()
expect(exported).toEqual(generated)
})
})
@@ -0,0 +1,15 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Annotation } from "./Annotation";
import type { AnnotationCategory } from "./AnnotationCategory";
import type { Attribution } from "./Attribution";
import type { FindingZone } from "./FindingZone";
import type { LocalizedOptionalText } from "./LocalizedOptionalText";
import type { LocalizedText } from "./LocalizedText";
import type { Reference } from "./Reference";
import type { SheetView } from "./SheetView";
import type { VertebralConfig } from "./VertebralConfig";
/**
* The canonical sheet document (schema_version 2).
*/
export type AnatomicalSheetDocument = { schema_version: 2, species_id: string, name: LocalizedText, description: LocalizedOptionalText, scope_disclaimer: LocalizedOptionalText, attribution: Attribution, vertebral_config: VertebralConfig, references: Array<Reference>, categories: Array<AnnotationCategory>, views: Array<SheetView>, annotations: Array<Annotation>, finding_zones: Array<FindingZone>, };
+7
View File
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type Animal = {
/**
* Species of the animal; the sheet the report references matches it.
*/
speciesId: string, name: string, breed?: string, age?: string, };
+5
View File
@@ -0,0 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { DetailTriggerAnnotation } from "./DetailTriggerAnnotation";
import type { ObservableAnnotation } from "./ObservableAnnotation";
export type Annotation = ObservableAnnotation | DetailTriggerAnnotation;
@@ -0,0 +1,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { LocalizedText } from "./LocalizedText";
export type AnnotationCategory = { id: string, name: LocalizedText, color: string | null, };
+3
View File
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type Attribution = { authors: Array<string>, license: string | null, notes: string | null, };
+5
View File
@@ -0,0 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Credit } from "./Credit";
import type { ImageAsset } from "./ImageAsset";
export type Branding = { siteUrl: string, headerLogo: ImageAsset | null, footerLogo: ImageAsset | null, poweredBy: Credit | null, partner: Credit | null, };
+3
View File
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type Circle = { type: "circle", cx: number, cy: number, r: number, };
+3
View File
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type CountRange = { min: number, max: number, };
+4
View File
@@ -0,0 +1,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ImageAsset } from "./ImageAsset";
export type Credit = { logo: ImageAsset | null, url: string, fallbackText: string, };
@@ -0,0 +1,10 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Geometry } from "./Geometry";
import type { Laterality } from "./Laterality";
import type { LocalizedText } from "./LocalizedText";
import type { ReviewStatus } from "./ReviewStatus";
/**
* Navigation only: a trigger opens a detail view and never carries findings.
*/
export type DetailTriggerAnnotation = { id: string, view_id: string, category_id: string, laterality: Laterality, geometry: Geometry | null, review_status: ReviewStatus, color: string | null, kind: "detail_trigger", name: LocalizedText | null, opens_view_id: string, };
+5
View File
@@ -0,0 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { LocalizedText } from "./LocalizedText";
import type { ViewBox } from "./ViewBox";
export type DetailView = { id: string, name: LocalizedText, svg_asset_id: string | null, view_box: ViewBox | null, kind: "detail", parent_view_id: string, };
+12
View File
@@ -0,0 +1,12 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { LateralSide } from "./LateralSide";
export type Finding = { findingZoneId: string,
/**
* Node ids from the zone's categories down to the leaf.
*/
path: Array<string>, labelFrSnapshot: string, labelEnSnapshot: string, requiresVetReferral?: boolean, side?: LateralSide,
/**
* Set by the migration when the path no longer exists in the sheet; data kept.
*/
unresolved?: true, };
@@ -0,0 +1,8 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { FindingCategoryKind } from "./FindingCategoryKind";
import type { FindingNode } from "./FindingNode";
import type { LocalizedOptionalText } from "./LocalizedOptionalText";
import type { LocalizedText } from "./LocalizedText";
import type { ReviewStatus } from "./ReviewStatus";
export type FindingCategory = { id: string, kind: FindingCategoryKind, name: LocalizedText, description: LocalizedOptionalText, reference_ids: Array<string>, review_status: ReviewStatus, children: Array<FindingNode>, };
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type FindingCategoryKind = "dysfunction" | "consultation_reason" | "anamnesis" | "custom";
+9
View File
@@ -0,0 +1,9 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { LocalizedOptionalText } from "./LocalizedOptionalText";
import type { LocalizedText } from "./LocalizedText";
import type { ReviewStatus } from "./ReviewStatus";
/**
* A finding node; every optional key of the authoring form is filled in when parsed.
*/
export type FindingNode = { id: string, name: LocalizedText, description: LocalizedOptionalText, requires_vet_referral: boolean, reference_ids: Array<string>, review_status: ReviewStatus, children: Array<FindingNode>, };
+5
View File
@@ -0,0 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { FindingCategory } from "./FindingCategory";
import type { LocalizedText } from "./LocalizedText";
export type FindingZone = { id: string, name: LocalizedText, categories: Array<FindingCategory>, };
+6
View File
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Circle } from "./Circle";
import type { PathGeometry } from "./PathGeometry";
import type { Polygon } from "./Polygon";
export type Geometry = Circle | Polygon | PathGeometry;
+5
View File
@@ -0,0 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { PngAsset } from "./PngAsset";
import type { SvgAsset } from "./SvgAsset";
export type ImageAsset = PngAsset | SvgAsset;
+6
View File
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Explicit on every annotation: absence no longer carries meaning.
*/
export type Laterality = "unpaired" | "bilateral" | "left" | "right";
+3
View File
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type Locale = "fr" | "en";
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type LocalizedOptionalText = { fr?: string, en?: string, };
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type LocalizedText = { fr: string, en: string, };
+5
View File
@@ -0,0 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { LocalizedText } from "./LocalizedText";
import type { ViewBox } from "./ViewBox";
export type MainView = { id: string, name: LocalizedText, svg_asset_id: string | null, view_box: ViewBox | null, kind: "main", };
@@ -0,0 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { NextAppointmentDate } from "./NextAppointmentDate";
import type { NextAppointmentPeriod } from "./NextAppointmentPeriod";
export type NextAppointment = NextAppointmentDate | NextAppointmentPeriod;
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type NextAppointmentDate = { kind: "date", date: string, };
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type NextAppointmentPeriod = { kind: "period", text: string, };
@@ -0,0 +1,11 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Geometry } from "./Geometry";
import type { Laterality } from "./Laterality";
import type { LocalizedText } from "./LocalizedText";
import type { ObservableKind } from "./ObservableKind";
import type { ReviewStatus } from "./ReviewStatus";
/**
* A point or zone annotation: observable, linked to findings by one explicit field.
*/
export type ObservableAnnotation = { id: string, view_id: string, category_id: string, laterality: Laterality, geometry: Geometry | null, review_status: ReviewStatus, color: string | null, name: LocalizedText, finding_zone_id: string | null, vertebral_region_code: string | null, kind: ObservableKind, };
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* The two observable annotation kinds share one shape.
*/
export type ObservableKind = "point" | "zone";
+6
View File
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Finding } from "./Finding";
import type { ReportZone } from "./ReportZone";
import type { Severity } from "./Severity";
export type Observation = { id: string, zones: Array<ReportZone>, findings: Array<Finding>, freeTextFindings: Array<string>, severity?: Severity, comment: string, };
+3
View File
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type Owner = { name: string, };
+3
View File
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type PathGeometry = { type: "path", d: string, };
+7
View File
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { PdfLabels } from "./PdfLabels";
/**
* Strict: every key present in both locales, no extra key.
*/
export type PdfLabelSet = { fr: PdfLabels, en: PdfLabels, };
+7
View File
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Fields in the order of the engine dictionaries (`packages/pdf/src/i18n`), which is the
* order every shipped attachment carries.
*/
export type PdfLabels = { "pdf.eyebrow.observation": string, "pdf.eyebrow.synthesis": string, "pdf.title.conclusion": string, "pdf.section.zones": string, "pdf.section.findings_prefix": string, "pdf.section.free_findings": string, "pdf.section.severity": string, "pdf.section.comment": string, "pdf.section.conclusion": string, "pdf.section.recommendations": string, "pdf.section.next_appointment": string, "pdf.view.general": string, "pdf.view.detail_prefix": string, "pdf.empty": string, "pdf.owner_prefix": string, "pdf.siret_prefix": string, "pdf.title.suffix.bilan": string, "pdf.subject": string, "severity.mild": string, "severity.moderate": string, "severity.severe": string, "lateral.left": string, "lateral.right": string, "footer.powered_by": string, "footer.in_partnership": string, };
+3
View File
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type PngAsset = { kind: "png", base64: string, };
+6
View File
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* A polygon point: a pair of finite numbers.
*/
export type Point = [number, number];
+4
View File
@@ -0,0 +1,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Point } from "./Point";
export type Polygon = { type: "polygon", points: Array<Point>, };
+7
View File
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type Practitioner = { name: string, cabinet?: string, contact?: string,
/**
* SIRET, 14-digit French business identifier (not validated).
*/
siret?: string, };
+7
View File
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ReferenceType } from "./ReferenceType";
/**
* One bibliographic reference, declared once and cited by id.
*/
export type Reference = { id: string, type: ReferenceType, citation: string, url: string | null, doi: string | null, };
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ReferenceType = "book" | "journal" | "standard" | "legal" | "web" | "manual";
+21
View File
@@ -0,0 +1,21 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Animal } from "./Animal";
import type { NextAppointment } from "./NextAppointment";
import type { Observation } from "./Observation";
import type { Owner } from "./Owner";
import type { Practitioner } from "./Practitioner";
import type { SheetRef } from "./SheetRef";
export type Report = { version: 3, id: string,
/**
* ISO timestamp of report creation.
*/
createdAt: string,
/**
* ISO date of the clinical encounter.
*/
date: string, practitioner: Practitioner, animal: Animal, owner: Owner, sheet: SheetRef, observations: Array<Observation>, conclusion: string, recommendations: string, nextAppointment?: NextAppointment,
/**
* Reserved for report-only points (OPEN_QUESTIONS Q6); empty until defined.
*/
localAnnotations: Array<unknown>, };
@@ -0,0 +1,19 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { Branding } from "./Branding";
import type { Locale } from "./Locale";
import type { PdfLabelSet } from "./PdfLabelSet";
import type { Report } from "./Report";
import type { SheetSnapshot } from "./SheetSnapshot";
/**
* An archive envelope, in the order the engine writes it.
*/
export type ReportArchiveEnvelope = { format: "faunosteo-report-archive", envelopeVersion: 1,
/**
* ISO timestamp of the export.
*/
exportedAt: string, locale: Locale,
/**
* As exported, never rebased.
*/
report: Report, sheetSnapshot: SheetSnapshot, branding: Branding, labels: PdfLabelSet, };
+1 -2
View File
@@ -3,8 +3,7 @@ import type { LateralSide } from "./LateralSide";
import type { Vertebra } from "./Vertebra";
/**
* A zone of an observation. Unknown keys are ignored on input, as the Zod schema strips
* them; optional fields are written only when set.
* A zone of an observation.
*/
export type ReportZone = { annotationId: string, viewId: string, side?: LateralSide, vertebrae?: Array<Vertebra>,
/**
+6
View File
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* How far the content was checked against references.
*/
export type ReviewStatus = "inherited" | "reviewed" | "to_confirm";
+3
View File
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type Severity = "mild" | "moderate" | "severe";
+1 -1
View File
@@ -1,7 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Reference of the anatomical sheet a report was written against (`Report.sheet`).
* The sheet document a report was built on, by content.
*/
export type SheetRef = { sheetId: string,
/**
+11
View File
@@ -0,0 +1,11 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { AnatomicalSheetDocument } from "./AnatomicalSheetDocument";
import type { SheetSnapshotAsset } from "./SheetSnapshotAsset";
import type { SheetSnapshotRef } from "./SheetSnapshotRef";
import type { SheetStatus } from "./SheetStatus";
export type SheetSnapshot = { status: SheetStatus, ref: SheetSnapshotRef,
/**
* Lean, valid document (schema v2, strict).
*/
document: AnatomicalSheetDocument, assets: Array<SheetSnapshotAsset>, };
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type SheetSnapshotAsset = { svgAssetId: string,
/**
* Content address from the seed manifest; a provenance pointer, not a tamper check.
*/
sha256: string | null, svg: string, };
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* `SheetRefSchema.extend({schemaVersion, speciesId}).strict()`.
*/
export type SheetSnapshotRef = { sheetId: string, versionId: string | null, documentSha256: string, schemaVersion: number, speciesId: string, };
+3
View File
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type SheetStatus = "draft" | "published";
+8
View File
@@ -0,0 +1,8 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { DetailView } from "./DetailView";
import type { MainView } from "./MainView";
/**
* Views form a tree: a detail names its parent, any depth.
*/
export type SheetView = MainView | DetailView;
+3
View File
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type SvgAsset = { kind: "svg", svg: string, };
+1 -1
View File
@@ -1,6 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* One vertebra of a spine zone: the region code and the 1-based index in that region.
* One vertebra: the sheet's region code and the 1-based index in that region.
*/
export type Vertebra = { region: string, index: number, };
@@ -0,0 +1,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { VertebralRegion } from "./VertebralRegion";
export type VertebralConfig = { regions: Array<VertebralRegion>, };
@@ -0,0 +1,5 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { CountRange } from "./CountRange";
import type { LocalizedText } from "./LocalizedText";
export type VertebralRegion = { code: string, name: LocalizedText, count: number, count_range: CountRange | null, };
+3
View File
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ViewBox = { min_x: number, min_y: number, width: number, height: number, };
+54 -1
View File
@@ -1,6 +1,59 @@
// Types of the core contracts, generated by ts-rs from crates/core (`pnpm rust:check`
// regenerates them; CI fails when the committed files drift from the Rust structs).
// regenerates them; the drift gate fails when the committed files differ from the Rust structs).
// This index lists every generated file: tests/types-index.test.ts keeps it complete.
export type { AnatomicalSheetDocument } from './AnatomicalSheetDocument'
export type { Animal } from './Animal'
export type { AnnotationCategory } from './AnnotationCategory'
export type { Annotation } from './Annotation'
export type { Attribution } from './Attribution'
export type { Branding } from './Branding'
export type { Circle } from './Circle'
export type { CountRange } from './CountRange'
export type { Credit } from './Credit'
export type { DetailTriggerAnnotation } from './DetailTriggerAnnotation'
export type { DetailView } from './DetailView'
export type { FindingCategoryKind } from './FindingCategoryKind'
export type { FindingCategory } from './FindingCategory'
export type { FindingNode } from './FindingNode'
export type { Finding } from './Finding'
export type { FindingZone } from './FindingZone'
export type { Geometry } from './Geometry'
export type { ImageAsset } from './ImageAsset'
export type { Laterality } from './Laterality'
export type { LateralSide } from './LateralSide'
export type { Locale } from './Locale'
export type { LocalizedOptionalText } from './LocalizedOptionalText'
export type { LocalizedText } from './LocalizedText'
export type { MainView } from './MainView'
export type { NextAppointmentDate } from './NextAppointmentDate'
export type { NextAppointmentPeriod } from './NextAppointmentPeriod'
export type { NextAppointment } from './NextAppointment'
export type { ObservableAnnotation } from './ObservableAnnotation'
export type { ObservableKind } from './ObservableKind'
export type { Observation } from './Observation'
export type { Owner } from './Owner'
export type { PathGeometry } from './PathGeometry'
export type { PdfLabelSet } from './PdfLabelSet'
export type { PdfLabels } from './PdfLabels'
export type { PngAsset } from './PngAsset'
export type { Point } from './Point'
export type { Polygon } from './Polygon'
export type { Practitioner } from './Practitioner'
export type { Reference } from './Reference'
export type { ReferenceType } from './ReferenceType'
export type { ReportArchiveEnvelope } from './ReportArchiveEnvelope'
export type { Report } from './Report'
export type { ReportZone } from './ReportZone'
export type { ReviewStatus } from './ReviewStatus'
export type { Severity } from './Severity'
export type { SheetRef } from './SheetRef'
export type { SheetSnapshotAsset } from './SheetSnapshotAsset'
export type { SheetSnapshotRef } from './SheetSnapshotRef'
export type { SheetSnapshot } from './SheetSnapshot'
export type { SheetStatus } from './SheetStatus'
export type { SheetView } from './SheetView'
export type { SvgAsset } from './SvgAsset'
export type { VertebralConfig } from './VertebralConfig'
export type { VertebralRegion } from './VertebralRegion'
export type { Vertebra } from './Vertebra'
export type { ViewBox } from './ViewBox'
+46
View File
@@ -0,0 +1,46 @@
/**
* R2 freeze (RUST_ARCHITECTURE_REVIEW VI.1): what the Zod schemas output for the reference
* documents, written once as `JSON.stringify(Schema.parse(x), null, 2)` under
* crates/core/tests/oracles so the Rust contracts are checked byte for byte against the
* TypeScript they replace. `MAKE_R2_ORACLES=1` writes them; otherwise they are asserted.
*/
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 type { z } from 'zod'
import {
AnatomicalSheetDocumentSchema,
ReportMigrationMapSchema,
ReportSchema,
ReportV2Schema,
} from '../src'
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')
const OUT = resolve(ROOT, 'crates/core/tests/oracles')
const MAKE = process.env.MAKE_R2_ORACLES === '1'
const SEED = 'supabase/seed/anatomical-sheets/equine'
const CASES: Array<[string, string, z.ZodTypeAny]> = [
['sheet.draft.json', `${SEED}/draft/document.json`, AnatomicalSheetDocumentSchema],
['sheet.legacy-import.json', `${SEED}/legacy-import/document.json`, AnatomicalSheetDocumentSchema],
['migration-map.draft.json', `${SEED}/draft/report-migration-map.json`, ReportMigrationMapSchema],
['report-v3.demo.json', 'apps/app/tests/fixtures/report-v3.demo.json', ReportSchema],
['report-v2.full.json', 'apps/app/tests/fixtures/report-v2.full.json', ReportV2Schema],
['report-v2.minimal.json', 'apps/app/tests/fixtures/report-v2.minimal.json', ReportV2Schema],
]
describe('Zod output oracles of the R2 switch', () => {
it.each(CASES)('%s', (name, source, schema) => {
const input: unknown = JSON.parse(readFileSync(resolve(ROOT, source), 'utf8'))
const text = JSON.stringify(schema.parse(input), null, 2)
const file = resolve(OUT, name)
if (MAKE) {
mkdirSync(OUT, { recursive: true })
writeFileSync(file, `${JSON.stringify({ source, output: JSON.parse(text) })}\n`)
}
const oracle = JSON.parse(readFileSync(file, 'utf8')) as { source: string; output: unknown }
expect(oracle.source).toBe(source)
expect(JSON.stringify(oracle.output, null, 2)).toBe(text)
})
})