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

+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,
}
}
}