Merge feature/rust-r3-anatomy-core into develop
ci / rust (push) Canceled after 0s
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s

This commit is contained in:
bchanot committed 2026-10-17 13:13:15 +02:00
commit 8df964bd91
142 files changed
+82721 -294

No files matched your search

+14
View File
@@ -88,3 +88,17 @@ Friction: the three `isolation: worktree` forks of R2 started at 605ee7c (an old
Root cause: harness side (base commit of the agent worktree), not reproducible from the repo; the removal refusal is the destructive-command policy.
Solution: forks briefed with the exact base commit and told to verify `git log -1`; diffs collected uncommitted and copied by literal paths. Leftover: `.claude/worktrees/agent-{a0cefd439bff650a2,a3f684449d0776ad1,af6ebe79b8f742039}` (3.2 GB) + 3 local temp branches at 22fea87 (merged), owner removes them (`git worktree remove --force <path>`, `git branch -d <branch>`).
Status: resolved 2026-10-14 — after R2 merged into develop (c3f28d8): 66 files checked blob by blob (60 identical to branch history, 6 = fork stub / merged mod lists / lifted `#[ignore]`), no process or agent on them, tip 22fea87 in develop → `git worktree remove --force` ×3 + `gitflow.sh delete` ×3 accepted this time. Harness base-commit cause stays upstream.
## BLK-011 | 2026-10-16 | Stopped-engine message promised "bilan conservé" with draft unsaved; dead "Réessayer" paths
Friction: 0279953 picked `core.stopped` from `CoreRuntime.stopped` alone: with sessionStorage full, reload restored older draft, edits lost silently; save banner advised PDF export (needs core). CoreUnavailable, export, import, new report still offered retry after stop; failed recovery below cap = dead end (nothing called `retry()` in editor; canvas button only rebuilt).
Root cause: terminal-state message not bound to persistence status (`saveFailed` existed, unread); retry labels audited only on the 8 alerts + canvas the patch touched, not every failure surface; runtime exit from `unavailable` only via explicit `retry()` called by useSheet alone.
Solution: 6371523 (BDR-055): `isUnsaved` selector drives variant + copy; CoreStoppedNotice on all core pages; runtime self-restart below cap; FAILED not held; ESLint census. Verifier CONFORME 12/12 (pass 2), security PASS 2 LOW.
Status: resolved 2026-10-16. Residuals: saveFailed also on refused archive (over-warns); offline restart never stops (copy on banner); beforeunload only in editor; trap-every-load draft → reload loop; GC finalizer of trapped-instance SheetHandle throws "memory access out of bounds" later (harmless, tests retain handles).
## BLK-012 | 2026-10-17 | Rescue copy not restorable; trapping draft stuck tab; work loss outside editor
Friction: JSON copy (6371523) had no in-app restore (Home picker PDF only; devtools only). Draft trapping `draft.restore` → CoreUnavailable reload each load, New report/Import FAILED, every re-read spent a recovery. beforeunload only in editor; New report / Import replaced bilan in progress (memory or slot) silently.
Root cause: copy shipped without restore path (round trip never tested in app); `internal` from draft read treated as transient core failure, no memory of trapping input; guard scoped to one route; session replacement unguarded since MVP.
Solution: 9bd9aca (BDR-056). Evidence: round trip identical (3 golden reports, slot + import); fuzz 37k draft.restore 0 traps, OOM only ~50 MB drafts (5 MB worst = 0.4-0.8 GB wasm). Verifier CONFORME 10/10, security PASS 2 LOW, check:all green.
Status: resolved 2026-10-17. Residuals: GC finalizer throws "memory access out of bounds" after stack-overflow trap (console only, live instance unaffected 50/50), ≤ 3 dead instances retained (~13.5 MB typical, ~4.5 MB each) until reload; raw lone surrogate in archive text quarantines readable draft (unreachable, session.rs); copy lacks archive envelope; iOS Safari likely ignores beforeunload (dialog + copy are protection there); Retry clicked during ms-long recovery → reload screen; re-importing copy of trapping draft re-traps (spends recovery); copy near 16 MiB may OOM low-memory device; storage full + confirmed replace + reload restores replaced draft; `internal` may come from handle rebuild (Retry reopens).
+30
View File
@@ -406,3 +406,33 @@ Status: active; R2 delivered on feature/rust-r2-domain-core, awaiting owner vali
Owner refused U+FFFD replacement of lone surrogate escapes (silent alteration of historical user data). Chosen (owner, 2026-10-14): refusal + quarantine. `js::parse_json` no pre-pass; serde_json refuses escape like any error; failure classified by strict escape scan (on failure only) → `JsonReadError::LoneSurrogate` → closed kind `lone_surrogate` (parse_input, sheet.check, draft.restore, archive.import). App: draft → `osteo:quarantine:draft` verbatim + existing `editor.draft_quarantined`; session archive → `osteo:quarantine:archive`; import → `ImportError('lone_surrogate')` + new `home.import.error_lone_surrogate` (owner-chosen detailed wording FR/EN, file untouched); editor action → refused, report unchanged, `core.action_failed`; publish gate → `invalid_shape`. Oracles untouched: L1 cases now assert TS kept surrogate + Rust refuses; test loader spells lone escapes out as literal text (never U+FFFD).
Alt rejected: faithful preservation (own JSON reader + lossless WTF-16 string type over ~150 contract fields + serialiser, oracles re-frozen; multi-day, for corrupted/pasted-UTF-16 data only; door stays open since nothing is lost); in-band tunnel (placeholder code points mapped back at facade output; collisions with sheet strings, UTF-16 length drift, every output path must be post-processed: hacky).
Status: active; merged with R2.
## BDR-052 | 2026-10-14 | R2 maintenance: held session texts, resolution panel, save-failure banner
Owner rule: no user data removed/overwritten implicitly when save or quarantine fails. Owner UI choice (AskUserQuestion): resolution panel in editor (download exact copy, delete permanently w/ confirmation, open adapted version w/ confirmation for pre-rebase draft, retry); New report / Import refused while held → alert + panel; storage-full banner on refused draft (or archive) write; set-aside texts UI = later. Code: occupied quarantine slot never replaced; draft+archive pair set aside together (rollback own copy); restore returns `held`, opens nothing; mirror writes only on report change; new session reads unread draft via core first (unreadable → set aside, readable → replaced as before); reset no-op without open report. rustls 0.23.46 (4 advisories, none reachable); `supabase/.temp/cli-latest` untracked.
Alt rejected: dropping held texts after warning (owner rule); multi-slot quarantine (scope); refusing every New report over an unread readable draft (behaviour change, not asked).
Status: closed (merged aab61c2).
## BDR-053 | 2026-10-15 | R3 design: one Rust SVG reader, constant canvas op, highlight unexposed, declared stricter rules
Plan rev 2 after 3 challengers (32 findings). Reader = prescan (markup state machine, caps before parse: 2 MiB, BOM, DOCTYPE, depth 64, 20k elements, attrs 256/100k, 16 xmlns, raw `<` 100k `=` 200k) → roxmltree 0.21.1 → own tree (qualified names as written, TS allowlist parity) → allowlist + declared extras (SVG ns only, comments dropped, text only title/desc ≤ 4 KiB, root without class/style/transform/filter/mask/clip-path, id grammar, href/url( local only after ASCII/CSS whitespace) → reference graph (cycles refused, expansion ≤ 50k) → serialiser (control whitespace as char refs, output ≤ 4 MiB). Product drawing with any removal refused at load (LRN-055). Facade: only `view.canvas {viewId}` (stateless, memoised per view; data-state still restyled in place). Highlight composition = core fn proven vs TS (O3), no facade op until R4 (snapshot-based call). Behaviour = code where ANNOTATION-RENDERING.md differed (doc rewritten first). Canvas failure → existing degraded notice + retry.
Alt rejected: roxmltree alone with nodes_limit (recursion overflows wasm stack, measured); `svg.sanitize` / `view.highlighted` ops now (no consumer, wrong source for R4); states in the canvas op (dead: restyle runs after every build); dangling-ref removal (rendering change); duplicate-id refusal; property tests (no generator crate).
Status: active; R3 awaiting owner validation, not merged.
## BDR-054 | 2026-10-15 | R3 owner UX decisions: trigger names per language, three canvas failure states, retry policy
Owner validated after R3 review: (1) unnamed trigger → `data-anno-name-fr`/`-en` + title take opened view name per language, empty language falls back to other; display only (not identifier, not persisted); frozen oracles untouched, tests apply declared change (`with_trigger_names_per_language` / `withTriggerNamesPerLanguage`, MAKE refused). (2) canvas failures distinct: engine (core_unavailable, internal) → `sheet.core_unavailable` + Réessayer (fresh instance may succeed); view (svg_rejected, no_asset, unknown_view, invalid_character, parse) → `canvas.view_unavailable`, no retry; detail in core outcome + DEV console only. (3) recovery cap 3 kept; after it `CoreRuntime.stopped` → `core.stopped` ("reload the page, report kept in tab") in canvas and in the 8 action alerts (`coreFailureMessage`), no retry. Wording of the three messages accepted.
Alt rejected: correcting the TS renderer too (engine/pipeline frozen until R4/R5; invisible in PDF: data-* dropped, title not rasterised); retry for deterministic view failures; editing goldens.
Status: closed (decisions); R3 still awaiting owner LAN confirmation, not merged.
## BDR-055 | 2026-10-16 | Engine stopped vs unsaved draft: honest variant, core-free copy, restart not counted
Owner audit of 0279953 (stopped state) not satisfactory → owner choices (AskUserQuestion 2026-10-15): stopped + `isUnsaved` (saveFailed && report) → `core.stopped_unsaved` + "Télécharger une copie" (in-memory report JSON, `lib/download.ts`, no core); save fine → `core.stopped` + `core.reload` button; copy button also on `editor.save_failed` banner (any engine state); `beforeunload` guard in editor while unsaved; "plusieurs erreurs" (counter = page lifetime, not successive). One `CoreStoppedNotice`: editor banner slot, top of Home / New report, CoreUnavailable full page; canvas stopped text without button. Runtime: failed recovery below cap restarted by next call / `ready()` (`restartable` = unavailable && !stopped && generation > 0), compiled module kept, restart not counted (cap = traps); deferred status listeners. Core failure reading unread draft → FAILED, never held. ESLint census on failure keys. Commit 6371523.
Alt rejected: counting failed restarts toward cap (offline → stopped, reload offline fails too); retry button on every page (new UI, owner already removed dead retries); copy only once stopped (offline restart loop never reaches stopped, no rescue).
Status: closed; R3 still awaiting owner LAN confirmation, not merged, R4 not started.
## BDR-056 | 2026-10-17 | R3 final checks: rescue copy importable, trapping draft held, replace confirmed, guard app-wide
Owner brief 2026-10-16 + AskUserQuestion: (1) Home import also takes JSON rescue copy: sniff first KiB (`%PDF-` → PDF; `{` / .json → copy), cap MAX_ATTACHMENT_BYTES 16 MiB before read, fatal UTF-8, pure `readRescueCopy` → core `draft.restore` (no JS parse), then existing hydrateImport branch; UNREADABLE_DRAFT_KINDS → `invalid_copy`. (2) `internal` reading draft → held `engine_failure` row (+ archive companion), `TrapMemory` keyed on (draft, archive) pair: no re-read by mount / New report / Import, only panel Retry (`retryTrapped`); any discard clears; `held_blocked_engine` alert. SUPERSEDES BDR-055 "never held" for `internal` only (`core_unavailable` etc. stay FAILED). (3) ReplaceSessionDialog (Annuler / Ouvrir le bilan en cours / Remplacer, copy when unsaved) on New report submit + Home pick when report in memory or draft slot; Home picker clicked synchronously. (4) `useUnsavedGuard` once in App. Commit 9bd9aca.
Alt rejected: new store action openCopy (dup of hydrateImport, session change before validation); JS JSON.parse of copy (depth; core reads raw text); copy cap MAX_PDF_BYTES (50 MiB file cap, not JSON bound); trapped memory on draft text only (archive parsed in same call); fixing GC finalizer via glue internals.
Status: closed; R3 awaiting owner LAN validation, not merged, no R4, release 0.2.0 untouched.
+21
View File
@@ -164,3 +164,24 @@ Method: owner asked to fix L1 (no silent U+FFFD) + prove the 2 approved deletion
Result: verifier CONFORME 13/13 (floor 2 = the approved deletions, authorised by REQUEST); security PASS, 6 LOW: wasm-bindgen `&str` would re-encode a raw lone surrogate (unreachable, JSON.stringify callers; documented invariant), `pretty_json` proof op refuses as invalid_json, scanner not string-aware (classification only), newest-only quarantine slot, archive quarantine failure under full storage lets a later reset remove it (pre-existing R2, reported to owner), semgrep partial parse. Final: core 142, Node 915 (app 320, supabase 40, core-wasm 26), PGlite pgTAP 12 files, real stack 446/446, types no drift, check:all green 1 min 32 s, module 1,040,784 B raw / 339,933 B gzip.
Anomalies: refusal broke a test loader (oracle file freezes TS outputs with lone escapes) → loader spells escapes out, never normalises (LRN-055); `cargo deny advisories` (warn-only) shows RUSTSEC-2026-0346/0347/0348 on rustls 0.23.45 (worker, none applicable: no brotli, built-in session cache, no ECH) → bump follow-up; `supabase/.temp/cli-latest` tracked by mistake, rewritten by the CLI, restored; `export PATH=…` denied → absolute `~/.cargo/bin/cargo`; first commit with chained `git config` denied → plain commit OK.
Action: gitflow finish into develop (owner authorised after L1 + checks), worktree cleanup (BLK-010), R3 summary only.
## EVAL-022 | 2026-10-15 | R2 maintenance + R3 anatomy core — challengers, oracles, Chromium, verifier ×2, security ×3
Method: maintenance: AskUserQuestion for B UI, store rewrite + 27 tests, verifier (11/11, floor false positive on `cli-latest`) + security PASS (4 LOW fixed), check:all, merge. R3: 2 analyzers (facts), plan + 3 challengers (FATAL 3 / FATAL 6 / CONCERNS 4; blocker = roxmltree recursion, which I had measured independently) → rev 2; freeze O1–O6 with TS before any change; Rust reader/layer/compose; mutation checks per oracle test; wasm thresholds in fresh instances; app switch; Chromium DOM + 30 screenshots + perf vs develop baseline; CSP proof on image; verifier CONFORME 11/11; security PASS + MEDIUM (prescan closer desync) → fixed → pass 2 PASS (4M differential docs) + LOW (url whitespace) → fixed.
Result: all oracles green (O2 exact incl. order, O1/O3 tree-equal, 42 hostile + 10 generated declared or equal, 4 product SVGs untouched); Chromium live trees = O1, 30/30 pixel-identical; module 395.5 KB gz (+56); editor 503 vs 476 ms, detail 143 vs 125 ms (CPU ×4); check:all green.
Anomalies: my first prescan had the closer-overlap bug (security caught it, tests did not: corpus lacked overlapped closers); first wasm memory threshold measured leaked sessions (harness artefact) → per-case fresh instance; probe in perf script retained detached nodes (fake leak); `env` and `export` refused by harness → inline env vars; cargo fmt reformat broke python patch anchors ×3 (write whole file or re-read).
Action: owner LAN validation (TEST FONCTIONNEL / TEST GRAPHIQUE), owner decisions (EN trigger name, degraded wording), then merge; R4 not started.
## EVAL-023 | 2026-10-16 | Owner-requested audit of 0279953 + bugfix — independent auditor, 3 challengers + confirm, verifier ×2, security
Method: fresh general-purpose auditor on commit only (5 owner axes); claims re-read in code; /bugfix: plan → 3 blind challengers → rev 2 → confirm pass → rev 3; owner AskUserQuestion ×3 batches; bugfixer; gates.sh 5/5; verifier; security; doc-syncer.
Result: audit NOT satisfactory (3 defects: unsaved promise, 4 dead retries, recovery dead end) — all fixed 6371523; app 374 tests, core-wasm 37; verifier pass 1 ECARTS(3) (2 untested surfaces, helper out of scope) → pass 2 CONFORME 12/12; security PASS 2 LOW; docs NONE.
Anomalies: previous session's commit + CHANGELOG claimed "never a retry that cannot work" without surface census; challengers converged on dead end the plan fixed only on canvas; confirm pass found offline restart never reaching stopped → copy moved to save banner (owner choice). Executor found latent GC finalizer throw (not fixed).
Action: R3 stays unmerged until owner LAN confirmation; R4 not started.
## EVAL-024 | 2026-10-17 | R3 final checks — measurements, challengers ×3 + confirm, verifier, security, check:all
Method: scratch round-trip test (3 golden reports); fuzz agent (37k draft.restore on shipped wasm + 40 worst cases, OOM threshold); GC agent (Node --expose-gc, 50 recoveries, WeakRef probes, mitigations in scratch); owner AskUserQuestion ×3; plan → 3 blind challengers → rev 2 → confirm → rev 3; bugfixer with negative controls; gates.sh 4/4; verifier; security; check:all; doc-syncer.
Result: copy restorable in app; loop impossible with real drafts, defended anyway; work-loss paths closed; app 405 tests, check:all green (~75 s cached); verifier CONFORME 10/10 (1 floor ASSERT_DROP = guard test moved, authorized by plan); security PASS 2 LOW; docs NONE.
Anomalies: challengers caught trap re-read spending recoveries (2 lenses), BDR-055 contradiction, wrong "parity" cap (50 MiB file vs 16 MiB JSON) only on confirm pass; executor found Retry-during-recovery edge.
Action: owner LAN validation, then merge on owner go; no R4, no release, no deploy.
+12
View File
@@ -260,3 +260,15 @@ Owner: manual 10/10 validated, R2 accepted (architecture, migrations, contracts,
## 2026-10-14 (R2 maintenance)
Owner brief: maintenance before R3. bugfix/r2-maintenance: rustls 0.23.46 (4 advisories, none reachable: ring no ML-KEM, no ECH/brotli; e2e on new image, compose worker paused then restarted), `supabase/.temp/cli-latest` untracked, session texts held when set-aside fails (owner chose resolution panel + banner; quarantine UI deferred). Found 2 extra overwrite paths (mirror removed draft on any store change; newest-only slot overwrite). Editor effect loop (OOM) from per-render deps + fresh array setState → attempt guard. Verifier 11/11, security PASS 4 LOW fixed, check:all green. Merged into develop. Next: R3 plan + freeze.
## 2026-10-15 (Rust R3 delivered)
feature/rust-r3-anatomy-core: plan rev 2 after 3 challengers (32 findings; blocker = roxmltree recursion, measured overflow < 3,000 levels on 1 MiB → markup prescan before any parse). Freeze first: O1 canvas trees, O2 layer order, O3 36 highlights, O4/O5 36 hostile + 10 floods + 4 product SVGs, Chromium refs. Rust reader (prescan, tree, allowlist, reference graph, serialiser), layer, canvas/highlight compose, `view.canvas`; app canvas switched, denylist + anatomy dep deleted. All oracles green, mutation-checked; Chromium DOM = O1, 30/30 pixel-identical; module 396 KB gz (+56). check:all green. Gates dispatched; stop for owner validation, no merge, no R4.
- Same day: gates. Verifier CONFORME 11/11. Security PASS + MEDIUM (prescan closer searched inside its opener, `<!-->` hid 5,000 levels → stack overflow) fixed; pass 2 PASS (4M differential docs) + LOW url( whitespace fixed; verifier re-run CONFORME. Final check:all green, Chromium 30/30 identical. BDR-052/053, LRN-056, EVAL-022. Stop: owner LAN validation.
- 2026-10-15 owner UX decisions on R3: unnamed trigger names per language (contract doc first, Rust layer, declared change applied to frozen oracles, goldens untouched); canvas engine failure (retry) vs view failure (own message, no retry). check:all green, Chromium 30/30 identical + DOM = O1 (declared), verifier CONFORME 8/8, security PASS 0 findings. Owner LAN tests in progress; no merge, no R4.
- 2026-10-15 owner validated both UX fixes + retry on internal; asked 3-attempt cap then clear failure state: found canvas + 8 alerts would still offer retry after cap → `CoreRuntime.stopped` + `core.stopped` message, no retry. BDR-054. R3 not merged (LAN tests pending).
- 2026-10-16 owner asked final independent audit of 0279953 (stopped state): not satisfactory (unsaved draft promise false, 4 dead retries, recovery dead end). Owner choices: unsaved variant + core-free copy, reload button, copy on save banner, beforeunload, "plusieurs erreurs". Fixed 6371523 (runtime self-restart below cap, CoreStoppedNotice on core pages, FAILED not held, ESLint census); verifier CONFORME 12/12, security PASS. BDR-055, BLK-011, LRN-057, EVAL-023. R3 not merged (LAN pending), no R4.
## 2026-10-17 (R3 final checks)
Owner brief: 5 checks before R3 close. Copy round trip proven, no in-app restore → Home import reads copy via draft.restore. Loop: fuzz 37k 0 traps (OOM ~50 MB only) → defended: trapping pair held in panel, re-read only on Retry. Work loss: guard app-wide, replace dialog on New report / Import. GC finalizer harmless, bounded, recorded. 9bd9aca; verifier 10/10, security PASS, check:all green. BDR-056, BLK-012, LRN-058, EVAL-024. R3 not merged (LAN pending), no R4, no release, no deploy.
+28
View File
@@ -426,3 +426,31 @@ Apply: R3/R4/R5 ports (same oracle stack), any wasm loaded by Vite, any agent fa
Context: R2 rewrote lone surrogate escapes to U+FFFD before serde_json so JS-era texts still parsed (L1). Owner refused: silent change of historical data. Fix: drop pre-pass; serde_json already refuses; scan text only after failure to name kind (zero cost on valid input, exact refusal kind for UI message + quarantine). Trap found by fix: oracle file freezing TS outputs carried lone escapes → whole-file parse failed; test loader must spell escapes out as literal text (evidence kept), never re-normalise. Also: `u32::from_str_radix` accepts leading `+` → escape scanner checks hex digits explicitly.
Apply: any reader of user data (R3 SVG, R4 PDF reader, R5 pipeline) → refuse with closed kind + keep original, never repair silently; a leniency step needs explicit owner decision and declared-difference test.
## LRN-056 | 2026-10-15 | XML parser recursion, prescan closers, URL/CSS whitespace: three traps porting an SVG sanitiser
- roxmltree 0.21.1 recurses per nesting level (parse_element ↔ parse_content); 1 MiB wasm stack overflows between 1,000 and 3,000 levels; nodes_limit checked too late. Measure parser depth on the real stack size before trusting "iterative" claims (plan rev 1 said iterative: false). Fix = own markup prescan before any parse; fixed release only in unreleased git.
- A prescan must search each closer AFTER its whole opener (`-->` from +4, `]]>` from +9, `?>` from +2): searching from +1 let `<!-->` desync scanner vs XML grammar and hide 5,000 levels (security audit MEDIUM). Prove with differential fuzz vs the real parser (auditor ran ~4M docs) + calibrated small-stack run.
- Locality of `href` / `url(#…)` must follow the browser's parsers: URL parser strips only C0+space, CSS tokenizer only space/tab/newline. JS `trim()`/`\s` include NBSP/ideographic/BOM → `\u00A0#a` passes as local, resolves as relative URL. TS engine has the same flaw (declared difference).
- Mutation checks on oracle tests find blind spots: namespace check mutant passed until a rebound-prefix corpus case was added.
- vitest/React: effect with per-render deps (useT closure) + setState(new array) → infinite render loop (OOM); guard side-effectful restore per attempt with a ref.
- Visual parity: freeze happy-dom trees + Chromium screenshots BEFORE switch; same-build double capture gives the noise floor (30/30 identical); synthetic controls validate the comparator; baseline = `git archive develop` built in scratchpad (no worktree).
Apply: R4 PDF reader/writer (byte scanners, inflate), Step 13 uploads (reader in worker child), any parser fed untrusted input.
## LRN-057 | 2026-10-16 | Terminal-failure UX: bind data-safety promises to save status, census every retry surface
- Message promising data kept ("report kept in this tab") must read real persistence status (quota flag); else variant + core-free rescue (download of in-memory state).
- Capped recovery → enumerate EVERY failure surface (grep failure keys, retry handlers, full-page degraded states), not only those the patch touched; enforce with ESLint `no-restricted-syntax` on `t('<key>')` literals (dictionaries untouched, file-scoped exceptions; later block overrides earlier for same rule).
- Each "retry" label needs reachable path to the runtime's recovery; runtime-level restart on next call beats per-surface buttons.
- Rescue must exist in every non-ready state, not only terminal one: a restart loop offline never reaches "stopped".
- Status listeners from a state machine: notify via microtask, try/catch per listener, never inside load/recover try blocks; stable module-scope subscribe for useSyncExternalStore.
Apply: R4 PDF worker failure states, Step 8 avatar upload errors, any capped retry or offline mode.
## LRN-058 | 2026-10-17 | Rescue paths need proven restore; remember trapping inputs; sniff and cap before read
- "Download a copy" is no rescue until an in-app restore exists and a round-trip test proves equality; reuse the reader that already parses that format (here core `draft.restore`) instead of a new parser.
- Input that trapped a recoverable engine must be remembered (key = every input of the trapping call, e.g. draft + archive) and re-read only on explicit Retry: each re-read spends a capped recovery and pins dead-instance memory.
- Untrusted file pick: route by content from first KiB, apply that path's cap on `file.size` before any full read, decode UTF-8 with `fatal: true` (refuse, never alter).
- User text into i18n templates: `.replace(re, () => value)`; string replacement expands `$&`/`$'`.
- Picker opened from a confirm dialog: call `input.click()` synchronously in the confirm handler (user activation, WebKit).
Apply: any export/backup feature, R4 PDF reader worker failures, Step 13 uploads.
+15 -1
View File
@@ -188,7 +188,21 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [x] B session texts never overwritten after a failed set-aside (owner UI choice: resolution panel + save-failure banner) (e34b7f2, a37c50b, c97b0e7): occupied slot refused, pair set-aside with rollback, `held` restore result, mirror on report change only, guarded new/import, discard + open-adapted behind confirmation, banner (draft or archive write refused); 27 new tests (app 346)
- [x] gates: verifier 11/11 (floor false positive on `cli-latest`, clarified) + residual fixed; security PASS, 4 LOW fixed (archive refusal banner, download URL kept 30 s, header wording, comment); check:all green 1 min 29 s
- [ ] follow-ups: UI for set-aside (quarantined) texts (owner: later); PDF export revokes its object URL at once (WebKit may cancel the download); "New report" replaces a readable draft without asking (unchanged, owner to decide if wanted); `writeCachedPractitioner` throws on a full localStorage before the report is created (no data loss)
- [ ] R3 anatomy core: tree, one sanitiser, serialiser, layer renderer, `compose_view_svg`; app canvas switched; composed views frozen as trees first
- [ ] R3 anatomy core (owner go 2026-10-14; branch feature/rust-r3-anatomy-core; plan `.claude/tasks/plans/2026-10-14-rust-r3-anatomy-core.md` rev 2 after 3 challenges, 32 findings): prescan + tree + allowlist sanitiser + reference budget + serialiser + layer + canvas/highlight composition in `crates/core`; app canvas on `view.canvas`; denylist deleted
- [x] R3.0 freeze O1 canvas (47c5f49), O2 layer (969b872), O3 highlight (d1aa35e), O4/O5 sanitiser corpus (b440a2f, e316821), O6 Chromium references (scratchpad, 30/30 stable); roxmltree recursion measured (overflow < 3,000 levels on 1 MiB) → prescan (5f53aaa)
- [x] R3.0b ANNOTATION-RENDERING.md to the code (4e01710)
- [x] R3.1 svg prescan caps + tree + sanitiser + refs + number + serialiser (cargo O4/O5 green, mutation-checked) (a7b3d7a, 85c2183)
- [x] R3.2 layer (O2 exact) + compose (O1/O3 tree-equal) + op view.canvas + per-asset outcome + wasm thresholds (44 cases, no trap, ≤ 30.6 ms, ≤ 10.1 MiB) + SheetSession poison rule (67d9af3, 1ec9316, 842797b, 43a370a)
- [x] R3.3 app switch: canvas on view.canvas, denylist + anatomy dependency removed, hostile bundled sheet test (09a6cf7); app 352
- [x] R3.4 Chromium 156: live DOM = O1 (main, head), 30/30 screenshots pixel-identical, timings vs develop baseline (editor 503 vs 476 ms, detail 143 vs 125 ms at CPU ×4), 50 cycles heap +0.72 MiB nodes +0; CSP proof on the image ALL PASS; owner LAN run pending
- [x] R3.5 docs (RUST.md §9, CLAUDE.md, CHANGELOG, PDF_IMPORT_HARDENING, packages/README) (d6b5edb)
- [x] R3.6 gates: verifier CONFORME 11/11 ×2; security PASS ×3 (MEDIUM prescan closer desync + 3 LOW fixed: href/url( Unicode spaces, root painting attrs); check:all green 1 min 56 s; Chromium final 30/30 identical, DOM = O1
- [ ] R3 owner validation (LAN: TEST FONCTIONNEL + TEST GRAPHIQUE), then merge on the owner's go; R4 not started
- [x] R3 owner decisions 2026-10-15: unnamed trigger names per language (6882c6d, contract d8e9bd3); canvas engine failure (retry) vs view failure (no retry) (c0a5c8c)
- [x] R3 owner follow-up 2026-10-15: retry kept for `internal`; after the 3 recoveries a clear final state (`core.stopped`) in the canvas and the action alerts, no retry (BDR-054)
- [x] R3 owner-requested audit of 0279953 (2026-10-15/16): not satisfactory (unsaved draft promise, 4 dead retries, recovery dead end) → fixed 6371523 (BDR-055, BLK-011); verifier CONFORME 12/12, security PASS; residuals in BLK-011
- [x] R3 final checks 2026-10-17 (owner brief 2026-10-16): rescue copy importable from Home, trapping draft held (no reload loop), replace confirmation, guard app-wide → 9bd9aca (BDR-056, BLK-012); verifier CONFORME 10/10, security PASS, check:all green; residuals in BLK-012
- [ ] R3 follow-ups kept by the owner (2026-10-15): worker TLS exercised against a real HTTPS endpoint before the deployment that needs it; roxmltree limits + SVG prescan (pin the iterative release when published); Firefox/WebKit check; SVG references across drawings scoped per view before community uploads (Step 13); WASM size margin (396 of 600 KB) before R4; TypeScript PDF sanitiser still present until R4
- [ ] 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
- [ ] separate chore (D-R7): form constraints module + PGlite `pg_constraint`/config.toml parity test
@@ -0,0 +1,68 @@
# CONTRACT — core-stopped-audit-fix
- date: 2026-10-15 | flow: bugfix | branch: feature/rust-r3-anatomy-core
- status: active
- plan: .claude/tasks/plans/2026-10-15-core-stopped-audit-fix-1830.md (rev 3, owner-approved 2026-10-15)
- base: 0279953 (run every CHECK from the repository root)
## REQUEST (verbatim — IMMUTABLE)
Je valide le comportement d'arrêt définitif du moteur WASM après trois reprises, ainsi que les messages FR/EN proposés.
La disparition du bouton « Réessayer » et la correction des huit alertes sont approuvées.
Effectue un dernier audit indépendant, ciblé uniquement sur cette correction : compteur de reprises, distinction erreur temporaire/arrêt définitif, réinitialisation après rechargement, cohérence des messages et conservation des données.
Vérifie particulièrement que le message annonçant la conservation du bilan ne soit pas trompeur si l'enregistrement du brouillon a échoué (quota ou autre erreur). Réutilise autant que possible les mécanismes de persistance et d'alerte déjà existants.
Si cet audit est satisfaisant, conserve les résultats dans le suivi. Ne recommence pas les audits complets de R3.
Les corrections UX et les formulations sont désormais acceptées.
R3 reste non fusionnée jusqu'à ma confirmation de la validation manuelle LAN. Ne commence pas R4.
## CLARIFICATIONS
Q: stopped + last save refused: what replaces « votre bilan est conservé » ? / A: variant `core.stopped_unsaved` + « Télécharger une copie » (in-memory report as JSON, no core). FR « Le moteur de calcul de Faunosteo s'est arrêté après plusieurs erreurs, et l'espace de stockage de cet onglet est plein : vos dernières modifications ne sont pas enregistrées et seraient perdues en rechargeant la page. Téléchargez une copie avant de recharger. » EN "Faunosteo's computation engine stopped after several errors, and this tab's storage is full: your latest changes are not saved and would be lost if you reload the page. Download a copy before reloading." [gated 2026-10-15]
Q: « plusieurs erreurs successives » inaccurate? / A: reword to « plusieurs erreurs » / "several errors", rest of `core.stopped` unchanged. [gated 2026-10-15]
Q: reload button on the stopped notice? / A: yes, `core.reload` « Recharger la page » / "Reload the page", only when the save is fine, never in the unsaved variant. [gated 2026-10-15]
Q: copy button on the existing storage-full banner (engine not stopped)? / A: yes, always; banner text (`editor.save_failed`) unchanged. [gated 2026-10-15]
Q: confirm reload / close while the report is not saved in the tab? / A: yes, native `beforeunload` while unsaved. [gated 2026-10-15]
Q: stopped notice placement on Home and New report? / A: top of the page content, below the header; in the editor, in place of the storage-full banner. [gated 2026-10-15]
Q: (internal, orchestrator) test helper extension in tests/helpers/core.ts outside the listed scope? / A: accepted: shared test seam, no product effect. [gated 2026-10-15]
Q: plan rev 3 approved, run on the branch, no merge, no R4? / A: yes. [gated 2026-10-15]
## ACCEPTANCE CRITERIA
1. A failed recovery below the cap is restarted by the next call or `ready()` (not counted as a recovery, compiled module reused); a failed first load is not; the default cap is 3; the third failed recovery or the fourth trap stops; listeners are notified after a microtask and a throwing listener changes nothing (core-wasm tests).
CHECK: cd packages/core-wasm && npx vitest run tests/runtime.test.ts > /tmp/cs-rt.log 2>&1 && grep -qi "restart" tests/runtime.test.ts && grep -qi "subscribe" tests/runtime.test.ts && echo RUNTIME_OK
EXPECT: RUNTIME_OK
EVIDENCE: MET exit=0 marker-found :: RUNTIME_OK
2. FR and EN dictionaries hold `core.stopped_unsaved` and `core.reload`, and `core.stopped` no longer says « successives » / "successive".
CHECK: f=apps/app/src/i18n/fr.ts; e=apps/app/src/i18n/en.ts; for k in core.stopped_unsaved core.reload core.stopped; do grep -q "'$k'" $f && grep -q "'$k'" $e || exit 1; done; grep -A2 "'core.stopped'" $f | grep -q successives && exit 1; grep -A2 "'core.stopped'" $e | grep -qi successive && exit 1; grep -A2 "'core.stopped'" $f | grep -q "plusieurs erreurs" && echo I18N_OK
EXPECT: I18N_OK
EVIDENCE: MET exit=0 marker-found :: I18N_OK
3. The ESLint census refuses a direct `t('core.action_failed')` outside src/core/failure.ts (positive control), and the tree lints clean.
CHECK: cd apps/app && echo "export const x = (t: (k: string) => string) => t('core.action_failed')" | npx eslint --stdin --stdin-filename src/app/routes/Probe.tsx > /dev/null 2>&1 && exit 1; echo "export const x = (t: (k: string) => string) => t('editor.export_failed')" | npx eslint --stdin --stdin-filename src/app/routes/Probe.tsx > /dev/null 2>&1 && exit 1; npx eslint . --max-warnings 0 > /dev/null 2>&1 && echo CENSUS_OK
EXPECT: CENSUS_OK
EVIDENCE: MET exit=0 marker-found :: CENSUS_OK
4. The whole app suite, typecheck and lint pass.
CHECK: ./node_modules/.bin/pnpm typecheck > /tmp/cs-tc.log 2>&1 && ./node_modules/.bin/pnpm test:run > /tmp/cs-test.log 2>&1 && ./node_modules/.bin/pnpm lint > /tmp/cs-lint.log 2>&1 && echo SUITES_OK
EXPECT: SUITES_OK
EVIDENCE: MET exit=0 marker-found :: SUITES_OK
5. No golden, oracle, seed, Rust crate or frozen package changed since the base.
CHECK: n=$(git status --porcelain -- apps/app/tests/fixtures crates supabase packages/domain packages/pdf packages/anatomy | wc -l); m=$(git diff --stat 0279953 -- apps/app/tests/fixtures crates supabase packages/domain packages/pdf packages/anatomy | wc -l); [ "$n" = 0 ] && [ "$m" = 0 ] && echo FROZEN_OK
EXPECT: FROZEN_OK
EVIDENCE: MET exit=0 marker-found :: FROZEN_OK
6. Stopped engine, save fine: every core page (Editor banner slot, Home, New report, the full-page CoreUnavailable) shows `core.stopped` with a « Recharger la page » button and no « Réessayer »; action / export / import / new-report failures say `core.stopped`. Tested.
7. Stopped engine, last save refused (`saveFailed` with a report in memory): the same surfaces show `core.stopped_unsaved` with « Télécharger une copie », never the reload button; the downloaded Blob content equals `JSON.stringify(report)` of the in-memory report; no message on any page names a button absent from that page. Tested.
8. Engine not stopped, save refused: the editor banner keeps the `editor.save_failed` text and gains the core-free « Télécharger une copie » button; a `beforeunload` handler is registered exactly while the report is unsaved. Tested.
9. Canvas: « Réessayer » (engine failure, not stopped) calls `coreRuntime().retry()` before rebuilding; a canvas engine failure shown while the engine becomes stopped switches to the stopped text with no button (derived at render, reactive to `saveFailed`). Tested.
10. A core failure while reading an unread draft makes `initReport` / `hydrateImport` return `{ ok: false }` without `reason: 'held'`, the draft untouched; New report and Home no longer say `session.held_blocked` for it (state.heldSession.test.ts inverted accordingly).
11. `HeldSessionPanel` download behaviour unchanged (shared helper); `core/sheetOps.ts` comment no longer names `core.action_failed` as the shown message; RUST.md §9.4 and the CHANGELOG R3 owner-decisions line describe the restart, the stopped notice placement and both variants.
12. No merge, no R4 work, no change outside the FILE SCOPE.
## FILE SCOPE
packages/core-wasm/src/runtime.ts, packages/core-wasm/tests/runtime.test.ts,
apps/app/src/core/{runtime,failure,sheetOps}.ts, apps/app/src/lib/download.ts (new),
apps/app/src/components/report/{CoreStoppedNotice.tsx (new),CoreUnavailable.tsx,HeldSessionPanel.tsx},
apps/app/src/components/canvas/AnatomyCanvas.tsx,
apps/app/src/app/routes/{EditorRoute,NewReportRoute,HomeRoute}.tsx, apps/app/src/state/reportStore.ts,
apps/app/src/i18n/{fr,en}.ts, apps/app/eslint.config.js, apps/app/tests/unit/** (new or updated tests), apps/app/tests/helpers/core.ts (test seam `controlStopped`; internal, added after verifier pass 1),
docs/development/RUST.md, CHANGELOG.md
@@ -0,0 +1,37 @@
# CONTRACT — R3 owner decisions: trigger names per language, two canvas failure messages
- date: 2026-10-15 | flow: ad-hoc on the R3 branch, verifier gate | branch: feature/rust-r3-anatomy-core
- spec: owner brief 2026-10-15 "R3 : décisions UX" (decision 1, decision 2, final checks)
- diff range: 23895b9..HEAD (run every CHECK from the repository root; `. scripts/rust-env.sh` first for cargo)
## REQUEST (IMMUTABLE)
Decision 1: fix the inconsistency of view triggers without an explicit name: the fallback labels must follow the selected language, FR or EN. Do not change stable identifiers, internal references, historical data or archive content. Check the exact role of the two name attributes before changing them: any field used as an identifier or a persistent contract stays stable. Add tests of the translations and of the fallback when a translation is missing. No graphic redesign. Decision 2: distinguish the Rust/WASM engine that could not load from an SVG view that is invalid, refused or cannot be composed; distinct, understandable FR/EN messages; detailed technical errors kept in internal checks, no sensitive detail in the interface; no Retry button for a deterministic error no retry can fix; preserve user data, never erase or replace the refused drawing; targeted, no major design change. Final checks: Rust and WASM tests, anatomical integration tests, DOM parity and reference captures, FR/EN labels, report and PDF non-regression, `pnpm check:all`, relevant audits. Never modify existing goldens to hide a difference. Do not merge R3, do not start R4, no production or release change.
## CLARIFICATIONS
- The frozen R3 oracles keep the French name twice for the unnamed trigger; the tests apply the owner's declared change to them before comparing (`with_trigger_names_per_language` in crates/core/tests/common/svg_tree.rs, `withTriggerNamesPerLanguage` in apps/app/tests/helpers/svgTree.ts, `declared` in scripts/visual-canvas.mjs); the files are unchanged.
- The two name attributes are display data: read by the canvas tooltip (which skips triggers) and the native title; never an identifier (`data-anno-id` is), never persisted.
## ACCEPTANCE CRITERIA
1. No golden or oracle file changed in the range.
CHECK: git diff --stat 23895b9..HEAD -- apps/app/tests/fixtures crates/core/tests/oracles crates/core/tests/fixtures supabase/seed | wc -l
EXPECT: 0
2. An unnamed trigger takes the opened view's name per language, with a fallback; a named one keeps its names (Rust tests).
CHECK: . scripts/rust-env.sh && cargo test -p faunosteo-core --lib anatomy::layer 2>&1 | grep "test result"; cargo test -p faunosteo-core --test anatomy_layer 2>&1 | grep -E "an_unnamed_trigger_names_the_opened_view|test result"
EXPECT: 2 passed / the named test ok and 3 passed
3. The stable identifier and the persisted contracts are untouched: only the name attribute values of triggers changed in the layer code.
CHECK: git diff 23895b9..HEAD -- crates/core/src/anatomy/layer.rs | grep -E '^[+-] ' | grep -c 'data-anno-id'; git diff --stat 23895b9..HEAD -- crates/core/src/domain | wc -l
EXPECT: 0 / 0
4. The canvas distinguishes the two failures, with a retry only for the engine, and distinct FR/EN messages.
CHECK: grep -c "canvas.view_unavailable" apps/app/src/i18n/fr.ts apps/app/src/i18n/en.ts apps/app/src/components/canvas/AnatomyCanvas.tsx; grep -n "failure === 'engine' &&" apps/app/src/components/canvas/AnatomyCanvas.tsx | wc -l
EXPECT: fr.ts:1 en.ts:1 AnatomyCanvas.tsx:1 / 1
5. The interface shows no technical detail: the kind/detail go to the DEV console only.
CHECK: grep -n "console.warn" apps/app/src/anatomy/drawing.ts; grep -c "import.meta.env.DEV" apps/app/src/anatomy/drawing.ts
EXPECT: one console.warn line / 1
6. The canvas suites cover: the view failure (no retry, drawing and draft untouched), the engine failure (retry draws the view), both in English, and the O1 trees with the declared change.
CHECK: cd apps/app && npx vitest run tests/unit/components.AnatomyCanvas.test.tsx tests/unit/canvas.trees.test.tsx 2>&1 | grep -E "Tests "
EXPECT: Tests 13 passed (13)
7. The whole gate is green.
CHECK: ./node_modules/.bin/pnpm check:all > /tmp/r3d-verify.log 2>&1; echo "exit $?"; grep "apps/app test:run: Tests" /tmp/r3d-verify.log
EXPECT: exit 0 / Tests 354 passed (354)
8. The rendering contract changed before the rendering code.
CHECK: git log --format=%h 23895b9..HEAD -- docs/ANNOTATION-RENDERING.md crates/core/src/anatomy/layer.rs | tail -2
EXPECT: the docs commit d8e9bd3 is older than (listed after) the layer commit 6882c6d
@@ -0,0 +1,50 @@
# CONTRACT — Rust R3: anatomy core (SVG reader, layer, composition) and the editor canvas on it
- date: 2026-10-15 | flow: feature branch, plan + 3 challenges, verifier gate | branch: feature/rust-r3-anatomy-core
- status: dispatched after the code, test and doc commits
- spec: owner brief 2026-10-14 §2–§12 (R3); plan `.claude/tasks/plans/2026-10-14-rust-r3-anatomy-core.md` rev 2 (§2 decisions C1–C8, §3 oracles O1–O6, §5 end criteria); `docs/development/RUST.md` §9
- diff range: develop..HEAD (run every CHECK from the repository root; `. scripts/rust-env.sh` first for cargo)
## REQUEST (IMMUTABLE)
Migrate the anatomy core to Rust (review R3 scope): SVG analysis, anatomical tree building and manipulation, allowlist SVG sanitisation, view serialisation, marker rendering, view composition, highlights, the editor canvas adapted to the Rust core's results, integrated in crates/core and the wasm facade. React and the DOM keep their UI duties; the TypeScript PDF engine stays until R4 and the curation pipeline keeps its parts until R5; no TypeScript still consumed by those later steps deleted. Not a functional or graphic redesign. Visual parity mandatory: freeze the reference renderings before modifying the current engine (three reference reports, Step 6 golden views, main and detail views, markers and annotations, selections and highlights, laterality, vertebral zones, dimensions and positions, click behaviour); compare SVG/DOM trees by structure and semantic properties, not arbitrary attribute order; add real-browser visual comparisons distinguishing anti-aliasing from real regressions; no intentional graphic difference without the owner's prior validation. SVG security: element and attribute allowlist; scripts, JavaScript events and dangerous external references refused; internal references controlled; DTD and forbidden entities refused; size, element count, depth, complexity and `<use>` reference limits; malformed documents handled; ids needed by anatomical interactions kept; critical size and depth limits applied before any XML analysis that could consume excessive resources; no regex alone for structure; tested on hostile inputs; the allowlist must not silently remove a useful element of existing sheets (conflict → documented and owner asked). Preserve annotation ids, data-anno-id, zone references, SVG↔findings mapping, detail views, anatomical versions, archived snapshots, v2/v3 archives; never regenerate goldens to pass tests. Measure the module size (budget 600 KB gzip served; report a significant increase before keeping it), load time, memory, fluidity. Run native Rust tests, wasm facade tests, TS/Rust parity, frozen SVG oracles, hostile SVG and sanitisation security tests, annotation and interaction tests, browser rendering tests, report non-regression, PDF export/import tests, `pnpm check:all`. Do not merge R3 before the owner's validation; do not start R4; no production or release 0.2.0 change.
## CLARIFICATIONS
- `apps/app/tests/unit/canvas.trees.test.ts` is renamed to `.tsx` (it now mounts the canvas): a rename, no test deleted.
- The sanitiser oracle (`oracles/r3/sanitiser.json`) was regenerated as corpus files were added; the TypeScript it runs (`packages/pdf/src`, `packages/anatomy/src`) is unchanged on the branch (criterion 4), so every regeneration is the same TypeScript's verdict. `highlight.json` gained `edgeDocument` only; its cases and sanitised trees are unchanged since d1aa35e (criterion 4).
- Pass 2 (after the security audit, PASS + 1 MEDIUM + 2 LOW): the prescan searches each closer after its whole opener (`<!-->` desync), `href` locality on ASCII-trimmed text only, root `transform`/`filter`/`mask`/`clip-path` removed; 5 corpus files added (41), the wasm corpus has 49 cases; counts below updated.
- Pass 3 (security pass 2 on the fix: PASS + LOW): `url(` skips CSS whitespace only; corpus 42 files, wasm corpus 50 cases.
- Visual screenshots are uncommitted by design (plan O6); their result is recorded in RUST.md §9.3.
## ACCEPTANCE CRITERIA
1. The native Rust gate is green.
CHECK: bash scripts/rust-check.sh > /tmp/r3-verify-rust.log 2>&1; echo "exit $?"
EXPECT: exit 0
2. The R3 cargo suites pass: sanitiser verdicts (O4/O5), layer (O2), compositions (O1 + O3), facade op.
CHECK: . scripts/rust-env.sh && cargo test -p faunosteo-core --test svg_sanitiser --test anatomy_layer --test anatomy_compose --test anatomy_canvas_op 2>&1 | grep "test result" | awk '{s+=$4; f+=$6} END {print s, f}'
EXPECT: 11 0
3. The frozen R3 oracles of the canvas and the layer are unchanged since their freeze commits, and the highlight oracle's cases too.
CHECK: git diff --stat 47c5f49 -- apps/app/tests/fixtures/goldens/r3/ | wc -l; git diff --stat 969b872 -- crates/core/tests/oracles/r3/layer.json | wc -l; python3 -c "import json,subprocess;o=json.loads(subprocess.check_output(['git','show','d1aa35e:crates/core/tests/oracles/r3/highlight.json']));n=json.load(open('crates/core/tests/oracles/r3/highlight.json'));print(o['cases']==n['cases'] and o['sanitized']==n['sanitized'])"
EXPECT: 0 / 0 / True
4. The TypeScript renderer and engine are unchanged, and so are the Step 6 and R2 goldens and the seed (no golden regenerated).
CHECK: git diff --stat develop -- packages/pdf/src packages/anatomy/src | wc -l; git diff --stat develop -- apps/app/tests/fixtures/goldens/step6 apps/app/tests/fixtures/goldens/r2 supabase/seed | wc -l
EXPECT: 0 / 0
5. One sanitiser for the canvas: the app has no denylist, no parse of its own and no dependency on the TypeScript renderer.
CHECK: grep -rnE "sanitizeSvg|parseDrawing|@faunosteo/anatomy" apps/app/src | wc -l; grep -c "@faunosteo/anatomy" apps/app/package.json
EXPECT: 0 / 0
6. The size and depth bounds run before any parser.
CHECK: grep -n "prescan(text, &SVG_CAPS)?;" crates/core/src/anatomy/svg/tree.rs; grep -n "roxmltree::Document::parse_with_options" crates/core/src/anatomy/svg/tree.rs
EXPECT: the prescan line number is lower than the parse line number
7. The rendering contract was rewritten before the canvas switched.
CHECK: git merge-base --is-ancestor 4e01710 09a6cf7 && echo "doc first"
EXPECT: doc first
8. The Node gate is green on the rebuilt module, with the new suites.
CHECK: bash scripts/wasm-build.sh > /tmp/r3-verify-wasm.log 2>&1; grep "bytes raw" /tmp/r3-verify-wasm.log; ./node_modules/.bin/pnpm check > /tmp/r3-verify-check.log 2>&1; echo "exit $?"; grep -E "(apps/app|packages/core-wasm|packages/pdf|packages/anatomy) test:run: Tests" /tmp/r3-verify-check.log
EXPECT: gzip under 600000 bytes / exit 0 / app 352, core-wasm 29, pdf 140, anatomy 131, all passed
9. The hostile corpus runs through the shipped wasm under the stated budgets, and the canvas composes within its own.
CHECK: grep -E "R3 hostile corpus|R3 sheet handle" /tmp/r3-verify-check.log
EXPECT: a hostile-corpus line with 50 cases, slowest under 150 ms, largest growth under 32 MiB; a sheet-handle line with a warm head median under 15 ms
10. The hostile corpus covers the owner's classes (scripts, events, external and data references, DTD/entities, depth, element count, `<use>` count, cycles and expansion, malformed, namespaces, CSS, size).
CHECK: ls crates/core/tests/fixtures/svg/hostile | wc -l; ls crates/core/tests/fixtures/svg/hostile | tr '\n' ' '
EXPECT: 42 files including url-unicode-space, comment-desync-depth, comment-desync-attributes, href-unicode-space, root-presentation, and script, events, script-urls, external-use, data-and-images, external-urls, doctype-entities, malformed, namespaces, css, use-self-cycle, use-mutual-cycle, root-class-style, long-title
11. The docs record the phase: RUST.md §9 (proofs, measurements, differences, risks), CHANGELOG, CLAUDE.md map.
CHECK: grep -c "^## 9. R3" docs/development/RUST.md; grep -c "Rust R3, anatomy core" CHANGELOG.md; grep -c "anatomy/{svg/{prescan,tree,sanitize,refs,number,serialize},layer,compose}" CLAUDE.md
EXPECT: 1 / 1 / 1
@@ -0,0 +1,76 @@
# CONTRACT — r3-final-checks
- date: 2026-10-17 | flow: bugfix | branch: feature/rust-r3-anatomy-core
- status: active
- plan: .claude/tasks/plans/2026-10-17-r3-final-checks-0900.md (rev 2 + owner wording; owner-approved 2026-10-17)
- base: 9464651 (run every CHECK from the repository root)
## REQUEST (verbatim — IMMUTABLE)
# Faunosteo — Derniers contrôles R3 avant validation humaine
J'approuve les corrections apportées après l'audit indépendant, notamment la protection des bilans non enregistrés, les messages d'erreur communs, le téléchargement de secours et la gestion des reprises du moteur.
Avant de clôturer R3, vérifie les points suivants :
1. **Copie JSON de secours** : prouve qu'elle conserve toutes les données nécessaires du bilan, qu'elle est exploitable et qu'une procédure réelle permet de restaurer le travail. Si aucun import compatible n'existe, ne présente pas ce téléchargement comme une restauration complète : identifie la solution minimale nécessaire ou le blocage.
2. **Boucle de rechargement** : reproduis ou écarte le cas d'un brouillon qui provoque systématiquement un plantage du moteur. Si la boucle est réelle, empêche les rechargements sans fin tout en préservant le brouillon original. Pas de suppression silencieuse.
3. **Modifications non enregistrées** : vérifie les changements de page, les retours à l'accueil et les autres actions susceptibles de perdre du travail. La protection actuelle limitée à l'éditeur est acceptable seulement si aucun autre parcours exposé ne permet cette perte.
4. **Erreur de nettoyage mémoire** : détermine si elle est réellement sans conséquence, sans fuite ou accumulation après les reprises. Conserve-la dans le suivi si elle est non bloquante.
5. **Tests finaux** : exécute `pnpm check:all`, les tests de récupération concernés et les vérifications utiles. Si tu modifies le code, soumets le delta à un contrôle indépendant ciblé.
Ne lance pas de refonte générale. Privilégie les corrections minimales et cohérentes avec l'architecture validée.
À la fin, présente :
- Le résultat de ces vérifications.
- Les éventuels blocages réels.
- La méthode de restauration d'une copie JSON.
- Le résultat de `check:all`.
- La procédure finale de test LAN.
**R3 reste non fusionnée jusqu'à ma validation manuelle.**
Ne commence pas R4, ne publie pas la release 0.2.0 et ne déploie rien sur faunosteo.com.
## CLARIFICATIONS
Q: restore the JSON copy? / A: Home import also accepts the copy (.json, content-sniffed), read by the core's existing `draft.restore`. [gated 2026-10-17]
Q: trapping draft? / A: existing resolution panel, row « Brouillon que le moteur de calcul n'arrive pas à ouvrir ({size}) », download / retry / discard after confirmation. [gated 2026-10-17]
Q: replace confirmation? / A: always when a bilan is in progress (memory or draft slot); Annuler / Ouvrir le bilan en cours / Remplacer; copy button when unsaved. [gated 2026-10-17]
Q: beforeunload guard? / A: every page while unsaved. [gated 2026-10-17]
Q: exact wording? / A: the plan's "Owner wording" section, verbatim (import labels, error_invalid_copy, notice_engine, draft_engine_failure, held_blocked_engine, replace dialog texts and buttons). [gated 2026-10-17]
Q: (internal, orchestrator, after confirm challenger) copy cap MAX_ATTACHMENT_BYTES, sniff first KiB, memory keyed on (draft, archive), test seam, wrapped-glue trap source? / A: adopted (rev 3). [gated 2026-10-17]
Q: (internal, orchestrator, after verifier) floor ASSERT_DROP routes.coreStopped.test.tsx beforeunload test? / A: authorized: guard moved app-wide (owner choice 4), its 4 assertions moved to app.useUnsavedGuard.test.tsx (plan Tests 'guard test moved to the hook test'). [gated 2026-10-17]
Q: plan approved? / A: yes. [gated 2026-10-17]
## ACCEPTANCE CRITERIA
1. The new FR/EN keys exist in both dictionaries with the owner's FR text, and the import labels are reworded.
CHECK: f=apps/app/src/i18n/fr.ts; e=apps/app/src/i18n/en.ts; for k in home.import.error_invalid_copy session.held.notice_engine session.held.draft_engine_failure session.held_blocked_engine session.replace.title session.replace.body session.replace.body_unloaded session.replace.unsaved session.replace.open session.replace.confirm; do grep -q "'$k'" $f && grep -q "'$k'" $e || exit 1; done; grep -q "Importer un PDF ou une copie de secours" $f && grep -q "Choisir un fichier" $f && grep -q "Brouillon que le moteur de calcul n'arrive pas à ouvrir" $f && grep -q "Ouvrir le bilan en cours" $f && echo I18N_OK
EXPECT: I18N_OK
EVIDENCE: MET exit=0 marker-found :: I18N_OK
2. The beforeunload guard lives in one app-level hook, no longer in EditorRoute.
CHECK: test -f apps/app/src/app/useUnsavedGuard.ts && grep -q "useUnsavedGuard" apps/app/src/app/App.tsx && ! grep -q "beforeunload" apps/app/src/app/routes/EditorRoute.tsx && [ "$(grep -rl beforeunload apps/app/src | wc -l)" = 1 ] && echo GUARD_OK
EXPECT: GUARD_OK
EVIDENCE: MET exit=0 marker-found :: GUARD_OK
3. App suites, typecheck and lint pass.
CHECK: ./node_modules/.bin/pnpm typecheck > /tmp/fc-tc.log 2>&1 && ./node_modules/.bin/pnpm test:run > /tmp/fc-test.log 2>&1 && ./node_modules/.bin/pnpm lint > /tmp/fc-lint.log 2>&1 && echo SUITES_OK
EXPECT: SUITES_OK
EVIDENCE: MET exit=0 marker-found :: SUITES_OK
4. No golden, oracle, seed, Rust crate, frozen package or core-wasm source changed since the base.
CHECK: n=$(git status --porcelain -- apps/app/tests/fixtures crates supabase packages | wc -l); m=$(git diff --stat 9464651 -- apps/app/tests/fixtures crates supabase packages | wc -l); [ "$n" = 0 ] && [ "$m" = 0 ] && echo FROZEN_OK
EXPECT: FROZEN_OK
EVIDENCE: MET exit=0 marker-found :: FROZEN_OK
5. Rescue copy: a JSON copy (downloaded format, `JSON.stringify(report)`) imported from Home reopens a report deep-equal to the original for the three golden reports, routed by content from the first KiB (also without a .json name; never reading a whole over-cap file); a PDF still goes the PDF path; invalid JSON, unsupported version, lone surrogate, invalid UTF-8 and over-cap (> MAX_ATTACHMENT_BYTES) files → `home.import.error_invalid_copy` with store and session slots untouched and no held side effect; non-content core kinds → the engine message path. Tested.
6. Trapping draft: with a real poisoning runtime, the editor shows the resolution panel (engine_failure row + engine notice, never CoreUnavailable while the engine is not stopped); New report and Import show `session.held_blocked_engine` then the panel; the trapping (draft, archive) pair is not re-read by mount, New report, Import or remount (one trap total) — only the panel's Retry re-reads it; discard after confirmation removes only that text and clears the memory (draft or archive row); draft and archive are otherwise untouched. Tested.
7. Replace confirmation: New report submit and Home file pick show ReplaceSessionDialog when a report is in memory or a draft is in the slot (named / unloaded / unsaved-with-copy variants); Annuler changes nothing; Ouvrir le bilan en cours → /editor; Remplacer proceeds (Home: picker opened inside the same click handler); an animal name containing `$&` renders literally; no dialog when nothing is in progress. Tested.
8. Guard: unsaved → beforeunload prevented on every page (hook test + App mounts it), saved → not prevented. Tested.
9. Existing suites adapted without weakening assertions (coreStopped New report tests, heldSession New report over a draft, state.quarantine `internal` → engine_failure); BDR-055's `internal` clause superseded consistently in code, tests, RUST.md §8.3 / §8.7 / §9.4, CHANGELOG and CLAUDE.md folder list.
10. No merge, no R4, no release, no deploy, no change outside FILE SCOPE.
## FILE SCOPE
apps/app/src/app/{App.tsx,useUnsavedGuard.ts (new)}, apps/app/src/app/routes/{HomeRoute,NewReportRoute,EditorRoute}.tsx,
apps/app/src/state/reportStore.ts, apps/app/src/pdf/import.ts,
apps/app/src/components/report/{HeldSessionPanel.tsx,CoreStoppedNotice.tsx,ReplaceSessionDialog.tsx (new)},
apps/app/src/i18n/{fr,en}.ts, apps/app/tests/unit/** , apps/app/tests/helpers/**,
docs/development/RUST.md, CHANGELOG.md, CLAUDE.md (folder list only)
@@ -0,0 +1,136 @@
# PLAN — Rust R3: anatomy core (SVG prescan, parse, tree, allowlist sanitiser, serialiser, layer, composition, highlight) and the editor canvas on it
- date: 2026-10-14 | rev 2 (after 3 plan challenges: correctness FATAL(3), robustness FATAL(6), simplicity CONCERNS(4); 32 findings folded) | branch: feature/rust-r3-anatomy-core
- spec: owner brief 2026-10-14 §2–§12; `docs/development/RUST_ARCHITECTURE_REVIEW.md` II.2 rows "anatomy render" + "pdf svg / drawing.ts denylist", VI.2 R3, VI.4; CLAUDE.md "Rust by default", "Annotation rendering"; facts: scratchpad r3-render-facts.md, r3-sanitiser-facts.md
- not in scope: R4 (the TS PDF engine keeps its TS sanitiser and `composeViewSvg`; no facade op for the highlight), R5 (pipeline, review byte goldens), any visible change, release 0.2.0, deployment
## 1. Outcome
The editor canvas (main view, detail modal) draws a string the core composed from the loaded sheet:
the sanitised asset + the annotation layer, no state. The app keeps DOMParser, `importNode`,
`replaceChildren`, the in-place `data-state` restyle (it runs right after every build already),
click and tooltip delegation, the CSS. Deleted: the denylist `sanitizeSvg`, `parseDrawing`, the
parse cache, `statesRef`, the app's dependency on `@faunosteo/anatomy`. The highlighted composition
the engine needs at R4 exists in the core as a function over (document, sanitised tree, view,
highlight), proven against the TS freeze in cargo, not exposed through the facade (R4 designs its
own snapshot-based call, review II.2 row "pdf writer").
## 2. Decisions
- C1 Behaviour = the code where the doc differs (trigger without a name: both name attributes = the
opened view's FR name; shape by geometry type; twin radius `max(2, r-12)`; canvas viewBox fallback
`0 0 100 100`; highlight per (annotation, view)). `docs/ANNOTATION-RENDERING.md` rewritten FIRST to
describe the code (no rendering change). Follow-up for the owner: EN name of an unnamed trigger.
- C2 Resource bounds, in order, before any parser (robustness 1/2, correctness 1; roxmltree 0.21.1
recurses per nesting level: measured overflow of a 1 MiB stack between 1,000 and 3,000 levels;
fixed only in unreleased git):
1. 2 MiB UTF-8 (`too_large`); a leading BOM → `malformed` (xmldom parity).
2. `<!DOCTYPE`/`<!ENTITY` anywhere, case-insensitive → `doctype` (engine rule); roxmltree
`allow_dtd: false` as well.
3. Markup prescan (hand-written state machine, no regex: comments, CDATA, PIs, quoted values
skipped): depth ≤ 64 (`too_deep`), elements ≤ 20,000 counted on the raw text (removed subtrees
included: declared tighter), attributes per element ≤ 256 and in total ≤ 100,000, `xmlns`
declarations ≤ 16, raw `<` ≤ 100,000 and `=` ≤ 200,000 (roxmltree pre-allocates on those
counts) → `too_complex`.
4. roxmltree `nodes_limit` 200,000 (never reached once 3 holds; `too_complex` if it is).
5. Serialised output ≤ 8 MiB (`too_large`).
- C3 Sanitiser = the TS allowlist, matched like the TS on qualified names (raw names from roxmltree
positions: `s:path` and `x:href` removed, prefixed root `not_svg`, a root without namespace
accepted as SVG), with these declared differences (each an O4 row with both verdicts; none touches
a product SVG):
- an element must also be in the SVG namespace (or none, xmldom's default): `<path xmlns="evil">`
removed (TS keeps it);
- comments and PIs dropped (TS keeps them), not listed as removals; non-whitespace text kept only
inside `title`/`desc` (never rendered elsewhere; robustness 11);
- root element: `class` and `style` removed (inline SVG under page CSS: UI-redress risk,
robustness 5); `id` values must match `^[A-Za-z_][\w.:-]*$` everywhere, else removed;
- `stdDeviation`: JS `Number()` reproduced by hand (hex, `Infinity`, `''`→0, no `inf`/`nan`/`_`),
JS printing of the clamped list;
- reference graph (owner: internal references and `<use>` complexity): edges from `href`/
`xlink:href` and every `url(#id)` (fill, stroke, clip-path, mask, filter, style) to the first
element holding that id (document order, like browsers); a cycle → `reference_cycle`; the
expanded element count (each edge adds its target's expanded subtree, saturating, iterative,
early exit) ≤ 50,000 → `too_complex`. Dangling references are left alone (no rendering change;
simplicity 3a). The TS `<use>` count cap 256 is kept.
- removal policy unchanged (dropped + named in `removed`); a product asset with a non-empty
`removed` is refused at sheet load for the views on that asset (LRN-055: refuse, never repair).
- C4 Tree: own arena (roxmltree borrows its input), elements (local name, namespace, qualified name,
attributes in source order, children), text; recursion allowed after the depth cap (64).
Serialiser: XML 1.0, attributes escape `& < > "` and `\t \n \r` as character references, text
escapes `& < >` and `\r`; namespace declarations re-emitted where the source declared them; no XML
declaration. A code point XML 1.0 forbids in a layer input (label, `d`) → compose refuses
`invalid_character` (never replaced; today's DOM path would draw it, the string path cannot).
- C5 Numbers printed with `js_number`; `Math.max(2, r-12)` in f64.
- C6 Facade: one op on the sheet handle, `view.canvas { viewId }` → `{ svg }`, called once per (sheet,
view) and memoised on `SheetIndex` (constant string). Failure kinds: `unknown_view`, `no_asset`,
`svg_rejected` (with the reason in `detail`), `invalid_character`. The sheet load sanitises each
asset once into a per-asset outcome (tree or rejection); `LoadedSheet.assets` stays the RAW text
(snapshots archive it; r2 envelopes re-checked).
- C7 App: `drawing.ts` glue: `index.ops.canvasView(viewId)` → DOMParser `image/svg+xml` →
`parsererror` check → `document.importNode(root, true)`. On failure the canvas retries once (the
runtime recovers a trapped instance on the next call), then shows the existing degraded notice
(`sheet.core_unavailable` + `sheet.core_retry`, existing component) inside the canvas; the retry
rebuilds. Runtime hardening: `SheetSession` treats only a closed `invalid_sheet:` refusal as such
and poisons the instance on any other throw (robustness 9).
- C8 Budget: served module ≤ 600 KB gzip; a jump > 60 KB gzip reported before keeping it.
## 3. Oracles frozen with the TS code first (done before any change unless noted)
O1 canvas: `buildViewSvg` (happy-dom) full tree with no state per view + the layer for every state
set of the three reports (done, 47c5f49). After the switch: AnatomyCanvas mounted with each state
set, its DOM compared to the frozen trees.
O2 layer trees with attribute order: draft + edge document (done, 969b872).
O3 highlighted compositions as trees (text nodes included): 36 cases incl. an existing nested
`<defs>` and an own-asset detail view without viewBox (done, d1aa35e).
O4 sanitiser verdicts and sanitised trees on the hostile corpus (32 files + 10 generated specs) (done,
b440a2f, e316821); Rust rows: equal, or declared (C2/C3) with the Rust verdict asserted; a Rust
verdict looser than the TS fails unless declared.
O5 product SVGs (horse, paws, public logos): Rust output serialised, re-parsed, compared with the TS
sanitised tree (namespace declarations kept as declared) (frozen in O4's `legitimate`).
O6 Chromium: screenshots before/after on the same Chromium, uncommitted, 0-diff expected, the
method's own noise floor measured (before/before: 30/30 identical, done); the classifier only
reports, a non-zero diff is analysed. Plus one live-DOM dump of the canvas in Chromium compared
with O1.
## 4. Phases
R3.0 freeze (done) + ANNOTATION-RENDERING.md rewritten to the code.
R3.1 core `anatomy/svg/{prescan,tree,sanitize,refs,number,serialize}.rs`; cargo: prescan caps,
hostile corpus (O4), product SVGs (O5), deep/flood/namespace/attribute cases.
R3.2 core `anatomy/{layer,compose}.rs`: O2 exact (order), O3 tree-equal, canvas composition equal to
O1's frozen base; `LoadedSheet` per-asset outcome; op `view.canvas`; ts-rs types; core-wasm
tests on the shipped module: the corpus through wasm with no trap, thresholds below.
R3.3 app switch (C7), denylist and dependency deleted, AnatomyCanvas/EditorRoute/DetailModal suites,
O1 on the mounted canvas, hostile bundled sheet through the real core (correctness 9).
R3.4 Chromium: O6 after, DOM dump, timings on `pnpm preview:draft` (4× CPU throttle), 50 detail
open/close cycles memory, one forced trap; LAN desktop + phone check.
R3.5 docs: RUST.md §9, CLAUDE.md, CHANGELOG, PDF_IMPORT_HARDENING.md (reference budget exists in
the core, engine switch at R4), review VI.4 status.
R3.6 gates: `pnpm check:all`, fresh verifier, security-auditor; stop for the owner's validation.
## 5. End criteria (review VI.2 R3, amended)
1. Step 6 view facts unchanged (engine untouched); O2 exact, O3 and O1 tree-equal on the core.
2. O4 every row equal or declared; O5 zero removal and tree-equal on the 4 product SVGs.
3. One sanitiser for the canvas: no `sanitizeSvg`/`parseDrawing`/`@faunosteo/anatomy` in
`apps/app/src` (grep) and no `@faunosteo/anatomy` in `apps/app/package.json`; the engine keeps
its own until R4 (VI.2 item amended).
4. Thresholds (shipped wasm, Node): every hostile case answers a closed outcome with no trap,
≤ 150 ms each, wasm memory growth over the whole corpus ≤ 32 MiB; `view.canvas` main ≤ 15 ms
warm. Chromium preview build, 4× CPU: first canvas paint after the core is ready ≤ 300 ms, detail
open ≤ 150 ms; 50 open/close cycles: wasm memory flat after the first, JS heap growth ≤ 5 MB.
5. Visual: 0-diff on the 30 captures (any non-zero diff analysed and reported, never waved through).
6. Served module ≤ 600 KB gzip; app, core-wasm, cargo, pgTAP suites green; `pnpm check:all` green.
## 6. Kept / deleted (consumers named)
Deleted: `drawing.ts` denylist + `parseDrawing` + cache, `apps/app` → `@faunosteo/anatomy` dependency,
`statesRef`. Kept: `packages/anatomy/src/render/**` (engine R4, pipeline R5), `packages/pdf/src/svg/**`
(engine R4), `browserRasterizer.ts` (DOM adapter), the TS oracle generators (R4/R5 need them).
## 7. Risks
- happy-dom vs Chromium tree differences: covered by the Chromium DOM dump.
- New degraded state inside the canvas (C7) reuses an existing notice; reported to the owner.
- Declared stricter rules could refuse a future Step 13 upload: each is a closed reason, logged in
the review for Step 13.
@@ -0,0 +1,129 @@
# Plan — engine stopped: audit fixes on 0279953 (bugfix, branch feature/rust-r3-anatomy-core)
## Context
Commit 0279953 added `CoreRuntime.stopped` (recovery cap 3 spent), `coreStopped()`, `coreFailureMessage(t)`
(apps/app/src/core/failure.ts), canvas failure `engine_stopped`, key `core.stopped` ("reload the page, your
report is kept in this tab"). Independent audit found:
- A. `core.stopped` ignores `reportStore.saveFailed` (set by the draft mirror when sessionStorage refuses a write,
reportStore.ts:392-396, shown as banner `editor.save_failed` "Exportez le PDF pour les conserver",
EditorRoute.tsx:303). Once stopped, export needs the core (pdf/export.ts:37 `index.ops.snapshot`) → impossible.
Reload restores the last successful write → edits since the refused write lost, unannounced.
- B. Surfaces still offering a retry that cannot work once stopped: CoreUnavailable (EditorRoute.tsx:257,
`sheet.retry` → runtime.retry() returns false at cap), export catch (`editor.export_failed` "Réessayez"),
import (`home.import.error_core_unavailable` "Réessayez l'import"), NewReportRoute.tsx:55
(`sheet.core_unavailable`). Also `releaseUnreadSession` (reportStore.ts:248-262) returns false on a core
failure, so initReport / hydrateImport return HELD and the pages say `session.held_blocked` (wrong cause).
- C. Canvas "Réessayer" (AnatomyCanvas.tsx ~145) only bumps `attempt` (rebuild), never calls
`coreRuntime().retry()`: after a failed recovery below the cap (state unavailable, stopped false) it is a dead end.
- D. Stale comment core/sheetOps.ts:17; test gaps (default cap 3 unpinned, failed recovery below/at cap, no census
of call sites, no stopped+saveFailed test).
Owner choices (AskUserQuestion 2026-10-15):
1. stopped + save failed → variant message `core.stopped_unsaved` + "Télécharger une copie" button writing the
IN-MEMORY report as JSON, no core (rescue copy; not importable today, import reads PDFs only).
FR: « Le moteur de calcul de Faunosteo s'est arrêté après plusieurs erreurs, et l'espace de stockage de cet
onglet est plein : vos dernières modifications ne sont pas enregistrées et seraient perdues en rechargeant la
page. Téléchargez une copie avant de recharger. »
EN: "Faunosteo's computation engine stopped after several errors, and this tab's storage is full: your latest
changes are not saved and would be lost if you reload the page. Download a copy before reloading."
2. `core.stopped` wording: "plusieurs erreurs successives" → "plusieurs erreurs" (EN "several successive errors"
→ "several errors"); rest unchanged.
3. "Recharger la page" button (new key `core.reload`, FR « Recharger la page », EN "Reload the page") on the
stopped notice ONLY when the save is fine; never in the unsaved variant.
## Fix plan (rev 2, after 3 challengers)
1. packages/core-wasm/src/runtime.ts —
a. Self-restart after a failed recovery (closes C everywhere, not only on the canvas): `restartable` =
`state === 'unavailable' && !stopped && generation > 0` (an instance ran before: a failed recovery or a
failed restart; a failed FIRST load stays on useSheet's explicit retry). `ready()` on a restartable runtime
returns `this.retry()` (awaits the restart); every CORE_UNAVAILABLE answer of `invoke()` and of
`SheetSession.current()` on a restartable runtime kicks `void this.retry()` and still answers
CORE_UNAVAILABLE (the next user action works: "Réessayez" becomes true). No counter change: a restart is
not a recovery; the cap still counts traps. A restart keeps `compiled` when `generation > 0` (the module
already ran; only a failed FIRST load clears it), so a restart fetches a glue record, never recompiles.
b. Status listeners: `subscribe(listener): () => void`. Notification is deferred (`queueMicrotask`) after the
transition, never inside the try blocks of load/recover, each listener wrapped in try/catch; a throwing or
re-entrant listener cannot change the state machine.
2. apps/app/src/core/runtime.ts — module-scope `subscribeCore(cb) = coreRuntime().subscribe(cb)` (stable
identity) and `useCoreStopped()` = `useSyncExternalStore(subscribeCore, coreStopped)`. Used on the three core
pages only (Editor, Home, New report); creating the runtime object loads nothing (lazy load stays on ready()).
3. apps/app/src/state/reportStore.ts —
a. exported selector `isUnsaved(s) = s.saveFailed && s.report !== null` (one rule, used by the notice and the
alerts).
b. `releaseUnreadSession` / `mayStartSession` return `ActionResult`: set-aside failure → HELD; core cannot read
the unread draft (any kind outside UNREADABLE_DRAFT_KINDS) → FAILED (never HELD); initReport / hydrateImport:
`const may = mayStartSession(index); if (!may.ok) return may`. Nothing written in either case (unchanged).
4. apps/app/src/core/failure.ts — `stoppedMessageKey()` = `isUnsaved(useReportStore.getState()) ?
'core.stopped_unsaved' : 'core.stopped'`; `coreFailureMessage(t, fallbackKey = 'core.action_failed')`:
stopped → `t(stoppedMessageKey())`, else `t(fallbackKey)`.
5. apps/app/src/lib/download.ts (new) — `downloadJson(raw, stem)`: body of HeldSessionPanel's `downloadCopy`
(Blob application/json, anchor attached while clicked, URL revoked after 30 s, `<stem>-<todayIso()>.json`).
HeldSessionPanel calls it (behaviour unchanged).
6. apps/app/src/components/report/CoreStoppedNotice.tsx (new) — the one host of the stopped buttons. Reads
`useReportStore(isUnsaved)` and `report`. unsaved → Notice error `core.stopped_unsaved` + Button
`session.held.download` (reused key) → `downloadJson(JSON.stringify(report), 'faunosteo-brouillon')`;
otherwise Notice error `core.stopped` + Button `core.reload` → `window.location.reload()`. Never a retry.
`CoreStoppedBanner` (same file or inline) = `useCoreStopped() ? <CoreStoppedNotice/> : null`.
7. Placement (persistent, whenever stopped, so alerts never name a button that is not on the page):
- EditorRoute banner slot: stopped → `<CoreStoppedNotice/>` (same margins as the save banner) INSTEAD of
`editor.save_failed`; not stopped + saveFailed → `editor.save_failed` text + the same core-free
"Télécharger une copie" button [rev 3, owner gate Q1]: the rescue exists in every engine state (a restart that
keeps failing offline never reaches `stopped`).
- [rev 3, owner gate Q2] `beforeunload` guard while `isUnsaved` (native browser confirm), registered in
EditorRoute; removed when the save recovers.
- HomeRoute and NewReportRoute: `<CoreStoppedBanner/>` at the top of the page content (below the header), so the
unsaved variant's download is on every page that can show its text.
- CoreUnavailable: `useCoreStopped()` → `<main><CoreStoppedNotice/></main>` instead of notice + retry.
8. apps/app/src/components/canvas/AnatomyCanvas.tsx — the engine variant is derived at render: a build failure
`engine` with `useCoreStopped()` true (or a build `engine_stopped`) → Notice with the stopped text chosen from
`useReportStore(isUnsaved)` (reactive), no button (the page banner holds the buttons; DetailModal never opens once stopped: a zone click is a core call).
"Réessayer" (engine only): `void coreRuntime().retry().finally(() => setAttempt(n => n + 1))`.
9. Alerts / error lines: EditorRoute export catch → `coreFailureMessage(t, 'editor.export_failed')`;
NewReportRoute:55 → `coreFailureMessage(t, 'sheet.core_unavailable')`; HomeRoute `importErrorMessage`
core_unavailable → `coreFailureMessage(t, 'home.import.error_core_unavailable')`; HomeRoute hydrateImport
`!ok`: `reason === 'held'` → held alert + navigate (unchanged), else throw `ImportError('core_unavailable')`.
10. apps/app/src/core/sheetOps.ts:17 comment → "shows `coreFailureMessage`".
11. i18n fr.ts / en.ts — `core.stopped` reworded (choice 2); new `core.stopped_unsaved`, `core.reload`.
12. ESLint (apps/app/eslint.config.js): `no-restricted-syntax` on `t('core.action_failed')`,
`t('editor.export_failed')`, `t('home.import.error_core_unavailable')`, `t('sheet.core_unavailable')` call
literals in src, except src/core/failure.ts, and for `sheet.core_unavailable` also CoreUnavailable.tsx and
AnatomyCanvas.tsx (the census, codebase idiom; dictionaries are not call sites).
13. docs/development/RUST.md §9.4 (+ §8 runtime note if it describes recovery) and the CHANGELOG R3 owner-decisions
line: restart on next action after a failed recovery; stopped notice on the core pages (reload, or unsaved
variant with copy); export / import / new report say the stopped message.
## Tests
- core-wasm runtime.test.ts: default cap = 3 (three recoveries succeed, fourth trap → stopped, retry false);
failed recovery below the cap → stopped false, then the next call kicks a restart and the call after it
succeeds; `ready()` after a failed recovery restarts and resolves true; third recovery fails → stopped true, no
restart kicked; a failed first load is NOT restarted by a call (only retry()); subscribe notified (after a
microtask) on the transition to stopped, a throwing listener does not change the state, unsubscribe stops it.
- AnatomyCanvas: engine retry calls `coreRuntime().retry()` (spy) then rebuilds; engine_stopped shows the stopped
text (unsaved variant when isUnsaved) and no button.
- CoreStoppedNotice: save fine → `core.stopped` + reload button, no retry; isUnsaved → `core.stopped_unsaved` +
download whose Blob content equals JSON.stringify(report).
- EditorRoute: stopped → banner notice replaces `editor.save_failed`; not stopped + saveFailed → save banner
with the copy button; beforeunload registered only while isUnsaved; export failure while stopped → stopped alert.
- runtime: a restart after a failed recovery reuses `compiled` (compile called once).
- HomeRoute / NewReportRoute: stopped → banner present; stopped + unsaved → download button on the page.
- state.heldSession.test.ts:268-280 inverted: core cannot read the draft → `{ ok: false }` without
`reason: 'held'`, draft untouched; same for hydrateImport.
- ESLint rule proven: lint fails on a sample `t('core.action_failed')` outside failure.ts (rule test via
`pnpm lint` on the tree + one RuleTester-free check: the tree lints clean).
- `pnpm typecheck && pnpm test:run && pnpm lint` green; core-wasm vitest green (TS-only runtime change, no wasm
rebuild; stamp unaffected).
## Known residuals (recorded, not fixed here)
- `saveFailed` also covers a refused archive write (BDR-052 banner semantics, pre-existing): the unsaved variant
over-warns then; the copy holds the report, the archive is the imported PDF still on disk.
- Kinds such as `rebase_failed` (sheet defect) answer FAILED → "Réessayez" (generic; near-unreachable).
- Home while not stopped but the engine cannot restart (offline) and saveFailed: no banner there; the editor
banner holds the copy.
- New report banner "Recharger la page" discards a typed form (shown from page entry, so usually before typing).
- New report / import while an open report has saveFailed replace it (pre-existing; deliberate user action).
- A draft that traps the core on every load → reload loop (pre-existing).
## Out of scope
R4, merge, the frozen PDF engine, Rust crates, goldens; making the JSON copy importable.
@@ -0,0 +1,143 @@
# Plan — R3 final checks: rescue copy import, trapping draft, replace confirmation, app-wide guard
Branch feature/rust-r3-anatomy-core (commit in place; no merge, no R4, no release, no deploy). Base 9464651.
Owner brief 2026-10-16 + choices (AskUserQuestion 2026-10-16/17).
## Diagnosis (evidence)
- Rescue copy = `JSON.stringify(report)` = byte format of `osteo:draft` (persistence.writeOrRemove). Proven: 3 golden
reports (v2full, demo, v2unresolved) round trip identical through `restoreDraft` (draft slot) and through the
core import (bare v3). No app path accepts it today (Home picker: PDF only) → not restorable without devtools.
The copy lacks the imported archive envelope (snapshot/branding/labels): the original PDF keeps it; report data
complete.
- Trapping draft: fuzz 37k `draft.restore` calls on the shipped core, 0 `internal`; OOM trap only from ~50 MB drafts
(sessionStorage ≤ ~5-10 MB). Real risk = low-memory device on a pathological 5 MB draft (0.4-0.8 GB wasm). If it
traps: restore() maps `internal` to `core_unavailable` → CoreUnavailable "Réessayer" = reload → same trap each load;
New report / Import FAILED (releaseUnreadSession). Tab stuck, draft kept, no in-app exit (closing the tab loses it).
- Work loss paths: beforeunload guard only in EditorRoute (`unsaved`): reload / close / OAuth full-page redirect from
Home, New report, /app, /login lose an unsaved report silently. New report (initReport) and Import (hydrateImport)
replace the bilan in progress (memory or draft slot) without confirmation, saved or not.
- GC finalizer: harmless (dead instance only, live instance 50/50 correct, no app handler); retained memory bounded
to 3 dead instances (~13.5 MB typical), freed on reload. Mitigations rely on glue internals or run code on a dead
instance, no memory gain → record only (no code).
- Side finding (record only): a raw lone surrogate in the stored archive text fails the whole `draft.restore` with
`lone_surrogate` → readable draft quarantined; unreachable (the app escapes surrogates; session.rs change needs
owner ask per CLAUDE.md).
RELATED MEMORY: honors BDR-052 (no user data removed/overwritten implicitly; held panel = resolution UI), BDR-054/055
(stopped notice, copy, guard), BLK-011 (census of every failure surface), LRN-055 (refuse, never alter), LRN-057.
## Fix plan (rev 2, after 3 challengers)
RELATED MEMORY correction: this plan SUPERSEDES BDR-055's clause "core failure reading unread draft → FAILED, never
held" for `internal` only (a trap reading the draft): it becomes the held engine_failure row; `core_unavailable` and
other core kinds stay FAILED. New BDR-056 records it; CHANGELOG R3 line amended; state.quarantine.test.ts updated.
1. Rescue copy import (owner choice 1) — no new store action
- apps/app/src/pdf/import.ts: pure `readRescueCopy(text, index): RebaseOutcome` beside importAttachment:
`index.ops.restoreDraft(text, null)`; ok → `outcome.value.rebase`; kinds in the store's UNREADABLE_DRAFT_KINDS
(export it from reportStore, or move the set to a shared module) → ImportError `invalid_copy`; every other kind
(core_unavailable, internal, rebase_failed, invalid_sheet, invalid_shape…) → ImportError `core_unavailable`.
- HomeRoute.importFile: route by content from `file.slice(0, 1024)` only (never read a whole oversized file):
starts with `%PDF-` → PDF path (its existing MAX_PDF_BYTES check); else first non-whitespace byte (after an
optional UTF-8 BOM) is `{`, or the name ends `.json` / type `application/json` → copy path; else PDF path
(existing invalid_pdf). [rev 3] Copy cap = MAX_ATTACHMENT_BYTES (16 MiB, exported by @faunosteo/pdf: the same
bound the PDF path puts on the JSON that reaches the core), checked on `file.size` before any read; over →
invalid_copy.
Copy path: decode with `new TextDecoder('utf-8', { fatal: true })` (failure → invalid_copy, LRN-055: refuse,
never alter); `loadSheetIndex`; `readRescueCopy`; THEN the existing `hydrateImport({ report: rebase.report,
archive: null }, index)` branch (held / FAILED handling unchanged). Copy read before any session change.
- After open: `rebase.rebased` → alert `editor.draft_rebased` (reused); navigate /editor.
- Picker accept adds `application/json,.json`. i18n: home.import.title / cta reworded, new
home.import.error_invalid_copy (exact texts below). ImportErrorKind + `invalid_copy`.
2. Trapping draft (owner choice 2) — no re-read of a known-trapping draft
- reportStore closure `trapped: { draft: string; archive: string | null } | null` [rev 3: keyed on the PAIR the
trapping call read]. `restore()` and `releaseUnreadSession`: when the slot pair equals `trapped` → answer held
engine_failure / HELD WITHOUT calling the core. Otherwise call restoreDraft;
`internal` → `trappedDraft = draft`, answer held engine_failure (rows: draft `engine_failure` + archive
`companion` when present) / HELD; draft and archive stay in place (no copy, no removal).
- Only the panel's explicit "Réessayer" re-reads it: `RestoreOptions.retryTrapped` (or equivalent) clears
trappedDraft before the read. Any discard (draft or archive row) clears it [rev 3]. A test seam clears it between tests (the closure
survives `useReportStore.setState`).
- HELD result tells its cause (e.g. `{ ok: false, reason: 'held', engine: true }`); NewReportRoute / HomeRoute
pick `session.held_blocked_engine` for it, `session.held_blocked` otherwise; both then navigate /editor (unchanged).
- EditorRoute: a restore answering held keeps the panel; restoreFailed (CoreUnavailable) only for
`core_unavailable` as today. With the memory, the editor read after New report / Import costs no trap.
- HeldText reason + `engine_failure`; HeldSessionPanel: row label `session.held.draft_engine_failure`; notice
`session.held.notice_engine` when a row is engine_failure.
3. Replace confirmation (owner choice 3)
- One component `components/report/ReplaceSessionDialog.tsx` (props open, onCancel, onOpen, onConfirm), used by
HomeRoute and NewReportRoute. Body: named (`session.replace.body`, `{animal}` substituted with a FUNCTION
replacement `() => name`, never a string pattern) when the report is in memory; `session.replace.body_unloaded`
otherwise; when `isUnsaved`: `session.replace.unsaved` + CopyReportButton. Buttons common.cancel /
session.replace.open (→ navigate /editor) / session.replace.confirm.
- `sessionInProgress()` = report in memory || `readSessionText('draft') !== null`.
- NewReportRoute submit: in progress → dialog; Remplacer → the existing submit continues.
- HomeRoute "Choisir un fichier": in progress → dialog; Remplacer calls `fileRef.current.click()` SYNCHRONOUSLY in
its onClick (user activation; WebKit), then the import runs as today.
4. App-wide guard (owner choice 4): `src/app/useUnsavedGuard.ts` (beforeunload while `isUnsaved`), called once in
App.tsx (inside the providers, outside the route tree); removed from EditorRoute.
5. Docs: RUST.md §8.3 (guard now app-wide), §8.7 item 3 (held reasons + engine_failure; New report / Import confirm
replacement), §9.4 (rescue copy import via draft.restore; trapping draft → panel, no re-read); CHANGELOG R3 lines
amended (line 15 statement on held corrected for `internal`); CLAUDE.md folder list adds ReplaceSessionDialog and
app/useUnsavedGuard.ts.
## Tests
- New: copy round trip through Home (JSON File, content-sniffed, also without .json name) equals the in-memory report
for the 3 golden reports; rebased copy alert; invalid JSON / v1 / lone surrogate / invalid UTF-8 / > cap →
error_invalid_copy, store and slots untouched, no held side effect (copy read before session start); core kinds →
coreFailureMessage path; PDF still routed by `%PDF-`.
- New: trapping draft on a REAL poisoning runtime [rev 3: a CoreSource wrapping the real glue whose
`SheetHandle.call` throws `WebAssembly.RuntimeError` for `draft.restore`; pkg-proofs has no trapping op]: mount editor →
panel engine_failure; New report and Import → engine held alert + panel, total traps = 1 across mount + New report +
Import + remount; panel Retry re-reads (trap 2); discard (confirmed) removes only the draft and clears the memory;
never CoreUnavailable while the engine is not stopped.
- New: ReplaceSessionDialog on New report submit and Home pick (memory and slot-only cases), named / unloaded / unsaved
variants, Annuler keeps everything, Ouvrir → /editor, Remplacer proceeds (Home: picker click called in the same
handler); `$&` in the animal name rendered literally; no dialog when nothing in progress.
- New: useUnsavedGuard via renderHook (saved → not prevented, unsaved → prevented, recovered → not) + App mounts it;
EditorRoute no longer registers its own.
- Adapted (assertions kept, a "Remplacer" click added where a report/draft is present): routes.coreStopped.test.tsx
(New report tests, beforeEach report; guard test moved to the hook test), routes.heldSession.test.tsx (New report
over a draft), state.quarantine.test.ts (internal → held engine_failure), any HomeRoute import test with a session.
- `pnpm typecheck && pnpm test:run && pnpm lint`; then `pnpm check:all`.
## Known residuals (record, no code)
- Importing the rescue copy of a trapping draft re-runs the trapping input (copy path is pure): likely a new trap
with the engine message; a copy near the 16 MiB cap may OOM on a low-memory device (same exposure as a PDF).
- `internal` can come from a handle rebuild, not the draft: the row may blame a sound draft (Retry reopens it).
- The held panel's archive copy (envelope JSON) is not importable as a rescue copy (draft.restore reads reports); the
draft copy is; the archive came from a PDF the practitioner has.
- Storage full + confirmed replace + reload: the slot still holds the replaced report's draft (pre-existing mirror
semantics: a refused write keeps the previous value).
- iOS/iPadOS Safari likely ignores beforeunload: the replace dialog and the copy button are the protection there
(LAN test on the owner's devices).
- restore(): `invalid_shape` / `rebase_failed` (sheet defects) still map to core_unavailable (CoreUnavailable).
- GC finalizer throw after a stack-overflow trap (console only), 3 dead instances retained (~13.5 MB) until reload.
- Raw lone surrogate in archive text quarantines a readable draft (unreachable; session.rs contract).
- Copy lacks the archive envelope (original PDF keeps it).
## Owner wording (pass B, gated 2026-10-17) — exact texts
- home.import.title « Importer un PDF ou une copie de secours » / "Import a PDF or a rescue copy"; home.import.cta
« Choisir un fichier » / "Choose a file"; home.import.description unchanged.
- home.import.error_invalid_copy « Ce fichier n'est pas une copie de secours Faunosteo lisible par cette version.
Import refusé ; le fichier n'a pas été modifié. » / "This file is not a Faunosteo rescue copy this version can
read. Import refused; the file was not changed."
- Rebased copy → existing editor.draft_rebased alert.
- session.held.notice_engine « Le moteur de calcul n'arrive pas à ouvrir un brouillon de cet onglet. Il est
conservé tel quel ; rien n'a été supprimé. Téléchargez-en une copie, réessayez, ou supprimez-le pour commencer un
nouveau bilan. » / "Faunosteo's computation engine cannot open a draft of this tab. It is kept as is; nothing was
deleted. Download a copy, try again, or delete it to start a new report."
- session.held.draft_engine_failure « Brouillon que le moteur de calcul n'arrive pas à ouvrir ({size}) » / EN
"Draft the computation engine cannot open ({size})".
- session.held_blocked_engine « Un brouillon de cet onglet fait échouer le moteur de calcul : il doit d'abord être
récupéré ou supprimé. L'éditeur va s'ouvrir pour le résoudre. » / "A draft of this tab makes the computation
engine fail: recover or delete it first. The editor will open to resolve it." [gated 2026-10-17]
- session.replace.title « Remplacer le bilan en cours ? » / "Replace the report in progress?"
- session.replace.body « Le bilan de {animal} sera remplacé dans cet onglet. Exportez-le en PDF pour le garder. » /
"The report of {animal} will be replaced in this tab. Export it as a PDF to keep it."
- session.replace.body_unloaded « Le bilan en cours dans cet onglet sera remplacé. Ouvrez-le et exportez-le en PDF
pour le garder. » / "The report in progress in this tab will be replaced. Open it and export it as a PDF to keep it."
- session.replace.unsaved « Ses dernières modifications ne sont pas enregistrées dans l'onglet. » / "Its latest
changes are not saved in this tab." + CopyReportButton.
- Buttons: common.cancel « Annuler »; session.replace.open « Ouvrir le bilan en cours » / "Open the report in
progress"; session.replace.confirm « Remplacer » / "Replace".
+9
View File
@@ -6,6 +6,15 @@ Versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Changed (Rust R3, anatomy core, 2026-10-15; validated by the owner's LAN acceptance and merged 2026-10-17)
- **The editor canvas draws what the Rust core composes** (`crates/core/src/anatomy`): one SVG reader for every drawing the product shows (bounds checked by a markup scanner before any XML parser, the engine's allowlist matched the same way, a reference graph refusing cycles and expansions over 50,000 elements, a serialiser that re-reads to the same tree), the annotation layer and the view composition, reached through the new `view.canvas` operation and memoised per view. The canvas keeps its in-place selection styling, click and tooltip delegation. The browser-side denylist and the app's dependency on the TypeScript renderer are gone; the PDF engine and the curation pipeline keep the TypeScript renderer until R4 and R5.
- **No visible change**, proven first with the TypeScript: canvas trees of both views and 28 selection states, layer trees with attribute order, 36 PDF highlight compositions, 36 hostile SVGs and 10 generated floods, the 4 product SVGs untouched; in Chromium 156 the live canvas trees equal the frozen ones and 30 screenshots (desktop and phone) are pixel-identical before and after. The Step 6 goldens are untouched.
- Declared differences, none on a product drawing: elements outside the SVG namespace removed, comments dropped, no `class`/`style` on the inline root, stricter ids, text only in `title`/`desc` (4 KiB each), floods and reference cycles refused, a product drawing the allowlist would alter refused at load instead of silently cut, a canvas that cannot be composed shows the existing degraded notice with a retry (`docs/development/RUST.md` §9.4).
- `docs/ANNOTATION-RENDERING.md` rewritten to describe the code exactly (no rendering change). Module 396 KB gzip (+56 KB, budget 600 KB).
- Owner decisions after the R3 review: a detail-view trigger without its own name now carries the opened view's name in each language (the English attribute and the tooltip title used to repeat the French name); the canvas tells an engine that did not load ("Réessayer") from a view whose drawing is refused or cannot be composed (its own message, no retry); after its three recoveries the engine shows a clear final state, never a retry that cannot work: in the canvas, the editor banner slot, the top of Home and New report and the full-page notice, and in the action, export, import and new-report alerts. Two variants: report saved in the tab ("Recharger la page"), or tab storage full ("Télécharger une copie" of the in-memory report, no reload button, native confirmation before leaving). A recovery that fails below the cap is restarted by the next call (the canvas "Réessayer" now restarts the engine), and a core failure reading the tab draft no longer reports a held session (except a trap of the engine on the draft, `internal`, held as an engine failure since the final checks below).
- R3 final checks (owner decisions 2026-10-17): **the rescue copy can be restored**: the Home picker now accepts the JSON downloaded by "Télécharger une copie" next to the PDF (routed by content, strict UTF-8, size cap, read by the core's draft restore; a refused file changes nothing). **A draft that traps the engine** (out of memory) no longer loops on the reload screen: the editor shows the resolution panel with the draft kept as is, New report and Import say so and open it, the trapping draft is read once, and only "Réessayer" reads it again. **New report and the file pick ask before replacing a bilan in progress** (cancel, open it, replace), and the "unsaved changes" browser prompt now guards every page, not only the editor. Documented in `docs/development/RUST.md` §8.3, §8.7 item 3 and §9.4 item 9.
### Security (maintenance after R2, 2026-10-14)
- **Worker TLS: rustls 0.23.45 → 0.23.46** (`Cargo.lock` only, through `ureq` 3.4.2): RUSTSEC-2026-0346 (session values' `Debug` printed TLS secrets), 0347 (ECH rejection), 0348 (Brotli certificate decompression), 0349 (unauthenticated ServerHello pinning the next key exchange group). None reached the worker as configured (ring provider without ML-KEM groups, no ECH, no `brotli` feature, sessions never printed); the bump removes them anyway. No API or feature change; the patch also fixes `StreamOwned` flushing and surfaces a connection's fatal error on the next write. `cargo deny check advisories` clean.
+15 -9
View File
@@ -196,6 +196,7 @@ faunosteo/
│ ├─ assets/brand/ ← the four PDF branding logos, bundled by Vite (?inline / ?raw / ?url), never fetched
│ ├─ app/
│ │ ├─ App.tsx ← root router
│ │ ├─ useUnsavedGuard.ts ← beforeunload while the report is unsaved, called once in App
│ │ ├─ routes/{Home,NewReport,Editor,NotFound}Route.tsx
│ │ ├─ routes/auth/{Login,Signup,ForgotPassword,ResetPassword,AuthCallback}Route.tsx
│ │ ├─ routes/app/{Dashboard,Account}Route.tsx ← behind RequireAuth, inside AppLayout
@@ -219,7 +220,7 @@ faunosteo/
│ │ ├─ reportStore.ts ← Zustand store (Report v3, core-built reports, actions answer { ok }) + persistence.ts (raw texts, quarantine keys)
│ │ ├─ localeStore.ts ← locale Zustand store (persisted to localStorage)
│ │ └─ practitionerCache.ts ← localStorage prefill
│ ├─ anatomy/drawing.ts ← sanitised asset + generated annotation layer → inline <svg> per view
│ ├─ anatomy/drawing.ts ← the core's composed view (`view.canvas`) → DOMParser → importNode (R3; no sanitiser here)
│ ├─ components/
│ │ ├─ ui/{Button,ButtonLink,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip,Icon,FormField,Notice}.tsx
│ │ ├─ canvas/{AnatomyCanvas,DetailModal}.tsx
@@ -227,7 +228,7 @@ faunosteo/
│ │ │ VertebraPicker,SeveritySelector,LateralityPicker,
│ │ │ FreeTextFindingInput}.tsx
│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,EditInfosDialog,DisclaimerDialog,
│ │ │ ConclusionPanel,NextAppointmentPicker,CoreUnavailable,HeldSessionPanel}.tsx
│ │ │ ConclusionPanel,NextAppointmentPicker,CoreUnavailable,HeldSessionPanel,ReplaceSessionDialog}.tsx
│ │ ├─ brand/{Brand,AppHeader,Footer,LanguageSwitcher,HomeSpaceLink}.tsx
│ │ ├─ auth/{AuthLayout,OAuthButtons,PasswordField,UnavailableNotice,AuthLink}.tsx
│ │ ├─ shell/{AppLayout,SidebarNav,MobileDrawer,UserBadge,SignOutButton}.tsx
@@ -258,7 +259,7 @@ faunosteo/
├─ packages/domain/ ← @faunosteo/domain (pure, no DOM, zod only): anatomical-sheet (document, integrity rules, sheet-index), report (v3, v2 migration, rebase), archive (sheet snapshot, envelope v1, branding, labels, layered reader)
│ ├─ src/anatomical-sheet/{schema,validate,create}.ts ← canonical sheet document + integrity rules
│ └─ tests/{fixtures/horse-slice.ts,*.test.ts}
├─ packages/anatomy/ ← @faunosteo/anatomy: legacy importer, curation pipeline, pure annotation-layer renderer + view composer (`./render`)
├─ packages/anatomy/ ← @faunosteo/anatomy: legacy importer, curation pipeline, frozen TS annotation-layer renderer + view composer (`./render`: PDF engine until R4, pipeline until R5; the app no longer depends on it)
├─ packages/pdf/ ← @faunosteo/pdf: browser-free PDF engine — src/{export,read,text,branding}.ts, attachment/, svg/{parse,sanitize,view}.ts, render/, i18n/; tests reproduce the Step 6 goldens
│ ├─ src/legacy/{svg,catalog,regions,ids,report,importer}.ts, src/cli/import-equine.ts
│ ├─ src/curation/{schema,targets,fields,ops,rename,apply,types,assets,labels,stats,changelog,review-report,overlay,seed,sources,pipeline}.ts ← changeset → draft
@@ -279,7 +280,7 @@ faunosteo/
├─ packages/README.md ← shared packages index
├─ packages/core-wasm/ ← @faunosteo/core-wasm: CoreRuntime (lazy, poison, recovery) + Node source, pkg/ shipped and pkg-proofs/ (built, git-ignored, BUILD_STAMP), ts-rs types (committed), frozen N-1 reader (tests/n-1), tests
├─ crates/ ← Rust workspace (Cargo.toml, rust-toolchain.toml, deny.toml, clippy.toml, .cargo/config.toml at the root)
│ ├─ core/ ← faunosteo-core: domain/{js,sheet,report,archive,editor,session} (contracts and rules), ops.rs + facade.rs (`call`, `call_with_sheet`), json (JS number printing); tests/{oracles,conformance,fixtures} frozen from the TypeScript; no I/O, no clock (lint-enforced)
│ ├─ core/ ← faunosteo-core: domain/{js,sheet,report,archive,editor,session} (contracts and rules), anatomy/{svg/{prescan,tree,sanitize,refs,number,serialize},layer,compose} (R3: the one SVG reader, the layer, canvas + highlight composition), ops.rs + facade.rs (`call`, `call_with_sheet`), json (JS number printing); tests/{oracles,conformance,fixtures} frozen from the TypeScript (oracles/r3, fixtures/svg/hostile); no I/O, no clock (lint-enforced)
│ ├─ wasm/ ← faunosteo-wasm: wasm-bindgen facade (core_version, call, SheetHandle; trap exports in the proofs build only)
│ └─ worker/ ← faunosteo-worker: plain main; `decode` sandboxed child (rlimits, seccomp allowlist, image → libwebp), parent Spawner + RIFF check; R1 `run` loop: config, log (JSON lines, allowlist), keys, backend trait + http (ureq, PostgREST rpc + Storage objects), job, sweep, watchdog; Dockerfile, scripts/derive-seccomp.sh
├─ scripts/{rust-env,rust-check,wasm-build,check-all,avatar-e2e}.sh, wasm-stamp.mjs ← native Rust gate, wasm build (pkg + pkg-proofs + stamp), the pre-merge gate (`pnpm check:all`), the real-stack avatar e2e
@@ -311,7 +312,9 @@ Sheet loading (Rust core, RUST.md §8)
document and migration map, index → index_data → SheetIndex (tables only) + ops (sheet-bound core calls)
SVG interaction
→ AnatomyCanvas builds the view: sanitised asset + renderAnnotationLayer() (markers from the document; TS until R3)
→ AnatomyCanvas builds the view once per (sheet, view): index.canvasSvg(view) = core `view.canvas` (the drawing read
once at sheet load: prescan caps → roxmltree → allowlist → reference graph; framed + annotation layer) → DOMParser
→ importNode; data-state restyled in place; a failed build shows the degraded notice with a retry
→ delegated click on [data-anno-id] → sheet.ops.zoneClick(observation, id) (one core call: decision + new observation)
→ open_view → DetailModal (same drawing, view_box crop, or the view's own asset)
→ open_vertebra_picker (initial selection from the core) / open_laterality_picker (sides present) → pickers
@@ -395,8 +398,11 @@ Database (Supabase)
- `docs/design/` holds the owner-validated mockups (Step 7 file = target for the whole SaaS shell: sidebar entries, dashboard tiles, Mon compte tabs, mobile tab bar). Any new screen follows them; elements they show that no step has built yet are listed in `docs/design/README.md` with their owning step. A redesign needs a new validated file there first.
### Annotation rendering
- docs/ANNOTATION-RENDERING.md is the source of truth: the drawing carries no annotation element, the app draws
the markers from the document (`@faunosteo/anatomy/render`), with the attributes listed there
- docs/ANNOTATION-RENDERING.md is the source of truth: the drawing carries no annotation element, the markers are
drawn from the document (Rust core for the canvas since R3, `crates/core/src/anatomy`; the frozen TS renderer
`@faunosteo/anatomy/render` for the PDF engine and the pipeline until R4/R5, same output), with the attributes listed there
- Every SVG the product draws goes through the core's one reader (`anatomy::svg::read_svg`): caps before any parse,
allowlist, reference graph; a product drawing with anything removed is refused at load, never repaired
- Never rely on element id, className or a label for click targeting or behaviour — always `data-anno-id`
and the annotation's fields (`laterality`, `vertebral_region_code`, `opens_view_id`)
- Marker look (radii, opacities, strokes) is renderer style; colours are document data (`color` on categories
@@ -512,8 +518,8 @@ Database (Supabase)
Study and roadmap: `docs/development/RUST_ARCHITECTURE_REVIEW.md` (validated with
the amendments of Annex C). Done: R0, R1 (worker), R2 (domain core used by the app,
`docs/development/RUST.md` §8). Next: R3 (anatomy core), R4 (PDF core), R5
(pipeline); release 0.2.0 unaffected.
`docs/development/RUST.md` §8), R3 (anatomy core: SVG reader, layer, composition; editor canvas on it,
RUST.md §9; validated and merged 2026-10-17). Next: R4 (PDF core), R5 (pipeline); release 0.2.0 unaffected.
- Any logic that can run in Rust with no significant loss (features, UX,
graphics, data compatibility, security, reliability, useful performance,
Generated
+10
View File
@@ -186,6 +186,7 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
name = "faunosteo-core"
version = "0.1.0"
dependencies = [
"roxmltree",
"serde",
"serde_json",
"ts-rs",
@@ -664,6 +665,15 @@ dependencies = [
"libc",
]
[[package]]
name = "roxmltree"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb"
dependencies = [
"memchr",
]
[[package]]
name = "rustls"
version = "0.23.46"
+4
View File
@@ -24,6 +24,10 @@ serde_json = { version = "1.0.154", features = ["preserve_order", "float_roundtr
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"
# SVG reading (R3): a read-only XML tree, DTD refused by default, node limit; positions give
# the qualified names the allowlist matches. Its tree building recurses: the core prescan caps
# the nesting depth before any parse (crates/core/src/anatomy/svg/prescan.rs).
roxmltree = { version = "=0.21.1", default-features = false, features = ["std", "positions"] }
# 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
@@ -27,6 +27,7 @@ contract.
- **Detail views** — click the head trigger to open the head view (a crop of the same drawing, or a view's own asset)
- **PDF export** — A4 portrait with rasterized views, structured observations, and the full Report v3 JSON as a native PDF attachment; older v2 PDFs import through a generated migration map
- **PDF re-import** — open a previously exported PDF to restore the session for a follow-up
- **Rescue copy (JSON)**: when the tab cannot save the report (storage full) or the computation engine stops, "Télécharger une copie" saves the report in progress as a `.json` file. To restore it, open the home page, "Choisir un fichier", and pick that file: the report reopens in the editor. The copy holds the report only. It does not replace the original PDF, which stays the archive of record for past reports (the frozen sheet snapshot, logos and labels it was produced with).
- **Bilingual UI** — full FR/EN interface with a one-click language switcher; default locale auto-detected from the browser, then persisted
- **Configurable identity** — site name, brand, footer, tagline all come from env vars; nothing hardcoded
- **Practitioner cache** — last-used practitioner block prefilled via localStorage
+39
View File
@@ -3,6 +3,21 @@ import tseslint from 'typescript-eslint'
import pluginReact from 'eslint-plugin-react'
import pluginReactHooks from 'eslint-plugin-react-hooks'
/**
* Census of the call sites of the keys that must go through `coreFailureMessage`: once the
* engine stopped, a direct `t('<key>')` would tell the practitioner to retry (owner
* decision 2026-10-15). Dictionaries and key strings passed as arguments are not call sites.
*/
const failureKeySelector = (key) => ({
selector: `CallExpression[callee.name='t'][arguments.0.value='${key}']`,
message: `Use coreFailureMessage(t, '${key}') (src/core/failure.ts), not a direct t() call.`,
})
const FAILURE_KEYS = [
'core.action_failed',
'editor.export_failed',
'home.import.error_core_unavailable',
]
export default tseslint.config(
{ ignores: ['dist/**', 'node_modules/**', 'coverage/**'] },
{
@@ -58,4 +73,28 @@ export default tseslint.config(
],
},
},
{
files: ['src/**/*.{ts,tsx}'],
ignores: [
'src/core/failure.ts',
'src/components/report/CoreUnavailable.tsx',
'src/components/canvas/AnatomyCanvas.tsx',
],
rules: {
'no-restricted-syntax': [
'error',
...[...FAILURE_KEYS, 'sheet.core_unavailable'].map(failureKeySelector),
],
},
},
{
// These two own the degraded engine notice, which names `sheet.core_unavailable`.
files: [
'src/components/report/CoreUnavailable.tsx',
'src/components/canvas/AnatomyCanvas.tsx',
],
rules: {
'no-restricted-syntax': ['error', ...FAILURE_KEYS.map(failureKeySelector)],
},
},
)
-1
View File
@@ -15,7 +15,6 @@
"report:compare": "tsx scripts/compare-reports.ts"
},
"dependencies": {
"@faunosteo/anatomy": "workspace:*",
"@faunosteo/core-wasm": "workspace:*",
"@faunosteo/domain": "workspace:*",
"@faunosteo/pdf": "workspace:*",
+30 -85
View File
@@ -1,97 +1,42 @@
import {
createLayerElement,
renderAnnotationLayer,
viewBoxOf,
} from '@faunosteo/anatomy/render'
import type { SheetView } from '@faunosteo/core-wasm/types'
import { coreStopped } from '@/core/runtime'
import type { SheetIndex } from '@/services/sheetIndex'
/**
* Builds the inline SVG of one view: the sheet's drawing (sanitised asset
* text) framed on the view's box, plus the annotation layer generated from
* the document. The drawing is parsed once per asset and cloned per view.
* The inline SVG of one view, as the core composed it (R3): the sheet's drawing, read and
* sanitised by the core's allowlist at load, framed on the view, with the annotation layer
* last (docs/ANNOTATION-RENDERING.md). The browser only parses the text (`DOMParser` never
* runs scripts) and imports the tree into the page.
*/
const SVG_NS = 'http://www.w3.org/2000/svg'
const FORBIDDEN_TAGS = ['script', 'foreignObject', 'iframe', 'object', 'embed']
export type ViewStates = ReadonlyMap<string, 'current'>
/** Drops scripts, embedded documents, event handlers and script URLs (LRN-025). */
export function sanitizeSvg(root: Element): void {
for (const tag of FORBIDDEN_TAGS) {
for (const el of Array.from(root.getElementsByTagName(tag))) el.remove()
}
for (const el of Array.from(root.querySelectorAll('*'))) {
for (const attr of Array.from(el.attributes)) {
const name = attr.name.toLowerCase()
const value = attr.value.trim().toLowerCase()
if (name.startsWith('on') || value.startsWith('javascript:')) {
el.removeAttribute(attr.name)
}
}
}
/**
* Why a view cannot be drawn: the engine did not run (a retry may succeed), the engine
* stopped after its three recoveries (only a reload starts it again), or the view
* itself cannot be drawn (a refused drawing, a view the core cannot compose: retrying
* changes nothing). The technical kind stays in the core's outcome and the DEV console.
*/
export type ViewFailure = 'engine' | 'engine_stopped' | 'view'
export type ViewBuild = { ok: true; svg: SVGSVGElement } | { ok: false; failure: ViewFailure }
const ENGINE_KINDS: ReadonlySet<string> = new Set(['core_unavailable', 'internal'])
function failed(failure: ViewFailure, kind: string, detail?: string): ViewBuild {
if (import.meta.env.DEV) console.warn(`canvas: ${kind}`, detail ?? '')
return { ok: false, failure }
}
export function parseDrawing(svgText: string): SVGSVGElement {
const doc = new DOMParser().parseFromString(svgText, 'image/svg+xml')
if (doc.querySelector('parsererror')) throw new Error('invalid SVG asset')
const root = doc.documentElement
if (root.tagName.toLowerCase() !== 'svg')
throw new Error('asset root is not <svg>')
sanitizeSvg(root)
return root as unknown as SVGSVGElement
}
const parsed = new Map<string, SVGSVGElement>()
function drawingOf(index: SheetIndex, assetId: string): SVGSVGElement {
const key = `${index.sheet.ref.documentSha256}:${assetId}`
let root = parsed.get(key)
if (!root) {
const text = index.sheet.assets[assetId]
if (text === undefined) throw new Error(`asset ${assetId} not bundled`)
root = parseDrawing(text)
parsed.set(key, root)
export function buildViewSvg(index: SheetIndex, viewId: string): ViewBuild {
const text = index.canvasSvg(viewId)
if (!text.ok) {
const engine = coreStopped() ? 'engine_stopped' : 'engine'
return failed(ENGINE_KINDS.has(text.kind) ? engine : 'view', text.kind, text.detail)
}
return root
}
/** The asset a view draws: its own, else its parent's (a crop). */
export function assetOfView(index: SheetIndex, view: SheetView): string {
if (view.svg_asset_id) return view.svg_asset_id
if (view.kind === 'detail') {
const parent = index.view(view.parent_view_id)
if (parent) return assetOfView(index, parent)
const parsed = new DOMParser().parseFromString(text.value, 'image/svg+xml')
const root = parsed.documentElement
if (parsed.querySelector('parsererror') || root.localName !== 'svg') {
return failed('view', 'parse')
}
throw new Error(`view ${view.id} has no asset`)
}
export function buildViewSvg(
index: SheetIndex,
viewId: string,
states: ViewStates,
): SVGSVGElement {
const view = index.view(viewId)
if (!view) throw new Error(`unknown view ${viewId}`)
const source = drawingOf(index, assetOfView(index, view))
const svg = document.createElementNS(SVG_NS, 'svg')
for (const attr of Array.from(source.attributes)) {
if (attr.name === 'width' || attr.name === 'height') continue
svg.setAttribute(attr.name, attr.value)
}
svg.setAttribute(
'viewBox',
viewBoxOf(view) ?? source.getAttribute('viewBox') ?? '0 0 100 100',
)
for (const child of Array.from(source.childNodes)) {
svg.appendChild(document.importNode(child, true))
}
const layer = renderAnnotationLayer({
document: index.sheet.document,
viewId,
states,
})
svg.appendChild(createLayerElement(document, layer) as unknown as Node)
return svg
return { ok: true, svg: document.importNode(root, true) as unknown as SVGSVGElement }
}
+3
View File
@@ -16,6 +16,7 @@ import ResetPasswordRoute from './routes/auth/ResetPasswordRoute'
import AuthCallbackRoute from './routes/auth/AuthCallbackRoute'
import DashboardRoute from './routes/app/DashboardRoute'
import AccountRoute from './routes/app/AccountRoute'
import { useUnsavedGuard } from './useUnsavedGuard'
/** The local tool: unchanged routes, no account needed, shared footer. */
function LocalToolShell() {
@@ -58,6 +59,8 @@ export function AppRoutes() {
}
export default function App() {
// The store is not a context: one call above the route tree guards every page.
useUnsavedGuard()
return (
<ConfigProvider>
<AuthProvider>
+25 -10
View File
@@ -14,6 +14,7 @@ import EditInfosDialog, {
type Identity,
} from '@/components/report/EditInfosDialog'
import DisclaimerDialog from '@/components/report/DisclaimerDialog'
import CoreStoppedNotice, { CopyReportButton } from '@/components/report/CoreStoppedNotice'
import CoreUnavailable from '@/components/report/CoreUnavailable'
import HeldSessionPanel from '@/components/report/HeldSessionPanel'
import Notice from '@/components/ui/Notice'
@@ -36,6 +37,8 @@ import type { ExportWarning } from '@faunosteo/pdf'
import type { RebaseOutcome } from '@faunosteo/core-wasm/types'
import { useT } from '@/i18n/useT'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
import { coreFailureMessage } from '@/core/failure'
import { useCoreStopped } from '@/core/runtime'
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
@@ -71,6 +74,7 @@ export default function EditorRoute() {
const { report, activeObservationIndex: activeIndex } = store
// Without a report yet (draft restore), the default species' sheet carries the migration map.
const sheet = useSheet(report?.animal.speciesId ?? DEFAULT_SPECIES_ID)
const stopped = useCoreStopped()
const [detailViewId, setDetailViewId] = useState<string | null>(null)
const [vertebraTarget, setVertebraTarget] = useState<VertebraTarget | null>(
@@ -161,7 +165,7 @@ export default function EditorRoute() {
const activeObs =
activeIndex >= 0 ? report.observations[activeIndex] : undefined
const outcome = sheet.index.ops.zoneClick(activeObs ?? null, annotationId)
if (!outcome.ok) return window.alert(t('core.action_failed'))
if (!outcome.ok) return window.alert(coreFailureMessage(t))
const click = outcome.value
if (click.observation) store.updateObservation(activeIndex, click.observation)
switch (click.kind) {
@@ -189,7 +193,7 @@ export default function EditorRoute() {
/** A store action the core ran: the practitioner hears about a failure. */
const guarded = useCallback(
(result: ActionResult) => {
if (!result.ok) window.alert(t('core.action_failed'))
if (!result.ok) window.alert(coreFailureMessage(t))
},
[t],
)
@@ -198,7 +202,7 @@ export default function EditorRoute() {
function openVertebraPicker(index: SheetIndex, zoneIndex: number) {
if (!activeObs) return
const outcome = index.ops.vertebraInitial(activeObs, zoneIndex)
if (!outcome.ok) return window.alert(t('core.action_failed'))
if (!outcome.ok) return window.alert(coreFailureMessage(t))
setVertebraTarget({ zoneIndex, initial: outcome.value })
}
@@ -207,7 +211,7 @@ export default function EditorRoute() {
if (!obs) return
const outcome = index.ops.removeZoneAt(obs, zoneIndex)
if (outcome.ok) store.updateObservation(i, outcome.value)
else window.alert(t('core.action_failed'))
else window.alert(coreFailureMessage(t))
}
function acknowledgeDisclaimer() {
@@ -247,7 +251,7 @@ export default function EditorRoute() {
}
} catch (err) {
console.error('PDF export failed', err)
window.alert(t('editor.export_failed'))
window.alert(coreFailureMessage(t, 'editor.export_failed'))
} finally {
setExporting(false)
}
@@ -271,7 +275,11 @@ export default function EditorRoute() {
restoreOptions.current = { replaceOriginal: true }
retryRestore()
}}
onRetry={retryRestore}
onRetry={() => {
// The one explicit way to read a draft the engine trapped on again.
restoreOptions.current = { retryTrapped: true }
retryRestore()
}}
/>
)
}
@@ -299,10 +307,17 @@ export default function EditorRoute() {
})
}
/>
{store.saveFailed && (
<Notice tone="error" className="mx-4 sm:mx-6 mt-4">
{t('editor.save_failed')}
</Notice>
{stopped ? (
<CoreStoppedNotice className="mx-4 sm:mx-6 mt-4" />
) : (
store.saveFailed && (
<Notice tone="error" className="mx-4 sm:mx-6 mt-4">
<p>{t('editor.save_failed')}</p>
<div className="mt-2">
<CopyReportButton />
</div>
</Notice>
)
)}
<div className="flex-1 grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-4 sm:gap-6 p-4 sm:p-6">
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none flex flex-col">
+102 -12
View File
@@ -6,18 +6,28 @@ import type {
} from '@faunosteo/core-wasm/types'
import AppHeader from '@/components/brand/AppHeader'
import HomeSpaceLink from '@/components/brand/HomeSpaceLink'
import { CoreStoppedBanner } from '@/components/report/CoreStoppedNotice'
import ReplaceSessionDialog from '@/components/report/ReplaceSessionDialog'
import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card'
import {
importAttachment,
ImportError,
MAX_ATTACHMENT_BYTES,
MAX_PDF_BYTES,
readAttachment,
readRescueCopy,
} from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import {
isSessionInProgress,
useReportStore,
type ImportedSession,
} from '@/state/reportStore'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
import { useT } from '@/i18n/useT'
import { coreFailureMessage } from '@/core/failure'
type Translate = ReturnType<typeof useT>
@@ -105,8 +115,47 @@ function importErrorMessage(err: unknown, t: Translate): string {
return t('home.import.error_no_attachment')
case 'lone_surrogate':
return t('home.import.error_lone_surrogate')
case 'invalid_copy':
return t('home.import.error_invalid_copy')
case 'core_unavailable':
return t('home.import.error_core_unavailable')
return coreFailureMessage(t, 'home.import.error_core_unavailable')
}
}
/** What a picked file read into: the session to open and the alert lines to show after. */
interface ImportRead {
session: ImportedSession
index: SheetIndex
lines: string[]
}
const SNIFF_BYTES = 1024
const PDF_MAGIC = '%PDF-'
/** First non-blank byte of the head, after an optional UTF-8 byte order mark. */
function firstContentByte(head: Uint8Array): number | undefined {
const start = head[0] === 0xef && head[1] === 0xbb && head[2] === 0xbf ? 3 : 0
return head.slice(start).find((b) => ![0x20, 0x09, 0x0a, 0x0d].includes(b))
}
/**
* Routes by content, from the first KiB only: a PDF starts with its magic, a rescue copy
* is JSON (an object) or is named as such; anything else goes the PDF path and its error.
*/
function isRescueCopy(file: File, head: Uint8Array): boolean {
const start = new TextDecoder('latin1').decode(head.slice(0, PDF_MAGIC.length))
if (start === PDF_MAGIC) return false
if (firstContentByte(head) === 0x7b) return true
return file.name.toLowerCase().endsWith('.json') || file.type === 'application/json'
}
/** The copy's text, refused (never altered) when it is over the cap or not valid UTF-8. */
async function readCopyText(file: File): Promise<string> {
if (file.size > MAX_ATTACHMENT_BYTES) throw new ImportError('invalid_copy')
try {
return new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer())
} catch {
throw new ImportError('invalid_copy')
}
}
@@ -118,10 +167,11 @@ export default function HomeRoute() {
const sheet = useSheetAvailability(DEFAULT_SPECIES_ID)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [confirmingReplace, setConfirmingReplace] = useState(false)
const t = useT()
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
async function importFile(file: File) {
/** A Faunosteo PDF: its attachment, read and rebased by the core on the loaded sheet. */
async function readPdf(file: File): Promise<ImportRead> {
// The engine refuses the same size; checking first keeps a huge file out of memory.
if (file.size > MAX_PDF_BYTES) throw new ImportError('invalid_pdf')
const bytes = new Uint8Array(await file.arrayBuffer())
@@ -129,18 +179,43 @@ export default function HomeRoute() {
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
if (!index) throw new ImportError('core_unavailable')
const { read: outcome, rebase } = importAttachment(attachment, index)
const opened = hydrateImport(
{ report: rebase.report, archive: outcome.archive },
return {
session: { report: rebase.report, archive: outcome.archive },
index,
)
lines: importMessages(outcome, rebase, t),
}
}
/** A rescue copy: read before any session change, so a refusal leaves the tab untouched. */
async function readCopy(file: File): Promise<ImportRead> {
const text = await readCopyText(file)
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
if (!index) throw new ImportError('core_unavailable')
const rebase = readRescueCopy(text, index)
const count = String(rebase.unresolvedZones + rebase.unresolvedFindings)
return {
session: { report: rebase.report, archive: null },
index,
lines: rebase.rebased ? [t('editor.draft_rebased').replace('{count}', count)] : [],
}
}
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
async function importFile(file: File) {
const head = new Uint8Array(await file.slice(0, SNIFF_BYTES).arrayBuffer())
const read = isRescueCopy(file, head) ? await readCopy(file) : await readPdf(file)
const opened = hydrateImport(read.session, read.index)
// A tab text that could not be set aside would be overwritten: resolve it first.
if (!opened.ok) {
window.alert(t('session.held_blocked'))
// A core failure reading the tab's draft is an engine error, not a held text.
if (opened.reason !== 'held') throw new ImportError('core_unavailable')
window.alert(
t(opened.engine ? 'session.held_blocked_engine' : 'session.held_blocked'),
)
navigate('/editor')
return
}
const lines = importMessages(outcome, rebase, t)
if (lines.length > 0) window.alert(lines.join('\n\n'))
if (read.lines.length > 0) window.alert(read.lines.join('\n\n'))
navigate('/editor')
}
@@ -166,6 +241,7 @@ export default function HomeRoute() {
<AppHeader>
<HomeSpaceLink />
</AppHeader>
<CoreStoppedBanner className="mx-4 sm:mx-6 mt-4" />
<section className="flex-1 grid place-items-center px-4 sm:px-6">
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
{noSheet && (
@@ -203,14 +279,18 @@ export default function HomeRoute() {
<input
ref={fileRef}
type="file"
accept="application/pdf,.pdf"
accept="application/pdf,.pdf,application/json,.json"
className="hidden"
onChange={onPickFile}
/>
<Button
variant="secondary"
size="lg"
onClick={() => fileRef.current?.click()}
onClick={() =>
isSessionInProgress()
? setConfirmingReplace(true)
: fileRef.current?.click()
}
disabled={busy || sheet.status !== 'ready'}
>
{busy ? t('home.import.loading') : t('home.import.cta')}
@@ -219,6 +299,16 @@ export default function HomeRoute() {
</Card>
</div>
</section>
<ReplaceSessionDialog
open={confirmingReplace}
onCancel={() => setConfirmingReplace(false)}
onOpen={() => navigate('/editor')}
onConfirm={() => {
// The picker opens inside this click: a later call loses the user activation.
fileRef.current?.click()
setConfirmingReplace(false)
}}
/>
</main>
)
}
+27 -5
View File
@@ -4,6 +4,8 @@ import type { Animal, Owner, Practitioner } from '@faunosteo/core-wasm/types'
import PractitionerForm from '@/components/report/PractitionerForm'
import AnimalForm from '@/components/report/AnimalForm'
import AppHeader from '@/components/brand/AppHeader'
import { CoreStoppedBanner } from '@/components/report/CoreStoppedNotice'
import ReplaceSessionDialog from '@/components/report/ReplaceSessionDialog'
import Button from '@/components/ui/Button'
import Input from '@/components/ui/Input'
import Label from '@/components/ui/Label'
@@ -12,9 +14,10 @@ import {
readCachedPractitioner,
writeCachedPractitioner,
} from '@/state/practitionerCache'
import { useReportStore } from '@/state/reportStore'
import { isSessionInProgress, useReportStore } from '@/state/reportStore'
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
import { useT } from '@/i18n/useT'
import { coreFailureMessage } from '@/core/failure'
/** The one species this build ships a sheet for. */
export const DEFAULT_SPECIES_ID = 'equine'
@@ -33,6 +36,7 @@ export default function NewReportRoute() {
})
const [owner, setOwner] = useState<Owner>({ name: '' })
const [date, setDate] = useState(todayIso())
const [confirmingReplace, setConfirmingReplace] = useState(false)
useEffect(() => {
const cached = readCachedPractitioner()
@@ -45,13 +49,19 @@ export default function NewReportRoute() {
owner.name.trim() &&
sheet.status === 'ready'
async function submit() {
function submit() {
if (!canSubmit || sheet.status !== 'ready') return
if (isSessionInProgress()) setConfirmingReplace(true)
else void createReport()
}
async function createReport() {
if (sheet.status !== 'ready') return
writeCachedPractitioner(practitioner)
// The loaded sheet lets the store read a draft this page never opened before replacing it.
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
if (!index) {
window.alert(t('sheet.core_unavailable'))
window.alert(coreFailureMessage(t, 'sheet.core_unavailable'))
return
}
const created = initReport(
@@ -69,15 +79,18 @@ export default function NewReportRoute() {
)
if (created.ok) navigate('/editor')
else if (created.reason === 'held') {
window.alert(t('session.held_blocked'))
window.alert(
t(created.engine ? 'session.held_blocked_engine' : 'session.held_blocked'),
)
navigate('/editor')
} else window.alert(t('core.action_failed'))
} else window.alert(coreFailureMessage(t))
}
return (
<main className="min-h-screen">
<AppHeader />
<div className="max-w-3xl mx-auto px-4 sm:px-6 py-6 sm:py-8 space-y-6 sm:space-y-8">
<CoreStoppedBanner />
<h1 className="font-serif text-2xl sm:text-3xl">
{t('new_report.title')}
</h1>
@@ -126,6 +139,15 @@ export default function NewReportRoute() {
</Button>
</div>
</div>
<ReplaceSessionDialog
open={confirmingReplace}
onCancel={() => setConfirmingReplace(false)}
onOpen={() => navigate('/editor')}
onConfirm={() => {
setConfirmingReplace(false)
void createReport()
}}
/>
</main>
)
}
+19
View File
@@ -0,0 +1,19 @@
import { useEffect } from 'react'
import { isUnsaved, useReportStore } from '@/state/reportStore'
/**
* The report lives only in this tab's memory while the tab's storage refuses its writes:
* on any page, the browser asks before a reload, a close or a full-page redirect.
*/
export function useUnsavedGuard(): void {
const unsaved = useReportStore(isUnsaved)
useEffect(() => {
if (!unsaved) return
const guard = (event: BeforeUnloadEvent) => {
event.preventDefault()
event.returnValue = ''
}
window.addEventListener('beforeunload', guard)
return () => window.removeEventListener('beforeunload', guard)
}, [unsaved])
}
@@ -1,8 +1,14 @@
import { useCallback, useEffect, useLayoutEffect, useRef } from 'react'
import { buildViewSvg, type ViewStates } from '@/anatomy/drawing'
import { useCallback, useEffect, useRef, useState } from 'react'
import { buildViewSvg, type ViewFailure, type ViewStates } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex'
import { coreRuntime, useCoreStopped } from '@/core/runtime'
import { stoppedMessageKey } from '@/core/failure'
import { useLocaleStore } from '@/state/localeStore'
import { isUnsaved, useReportStore } from '@/state/reportStore'
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import { useT } from '@/i18n/useT'
export interface AnatomyCanvasProps {
index: SheetIndex
@@ -14,15 +20,26 @@ export interface AnatomyCanvasProps {
const ANNOTATED = '[data-anno-id]'
/** `engine_stopped` is replaced at render by the stopped text that fits the save state. */
const FAILURE_MESSAGE: Record<ViewFailure, string> = {
engine: 'sheet.core_unavailable',
engine_stopped: 'core.stopped',
view: 'canvas.view_unavailable',
}
function annotatedTarget(event: Event): Element | null {
const target = event.target
return target instanceof Element ? target.closest(ANNOTATED) : null
}
/**
* One view of the sheet: the drawing plus the annotation layer generated
* from the document, rebuilt when the view changes and restyled in place
* when the selection changes. Clicks are delegated on `data-anno-id`.
* One view of the sheet: the drawing plus the annotation layer, composed by
* the core (R3), rebuilt when the view changes and restyled in place when the
* selection changes (the restyle runs right after every build). Clicks are
* delegated on `data-anno-id`. When the engine cannot run, the canvas shows the
* degraded notice with a retry (none once the engine stopped for good: the page's stopped
* notice holds the buttons); when the view itself cannot be drawn (a drawing
* refused or impossible to compose), a notice without retry: nothing would change.
*/
export default function AnatomyCanvas({
index,
@@ -35,17 +52,29 @@ export default function AnatomyCanvas({
const svgRef = useRef<HTMLDivElement | null>(null)
const tooltipRef = useRef<HTMLDivElement | null>(null)
const locale = useLocaleStore((s) => s.locale)
// Latest states for the build effect, which must only re-run on a view change.
const statesRef = useRef(states)
useLayoutEffect(() => {
statesRef.current = states
}, [states])
const t = useT()
// Each retry builds again; a failed build leaves the canvas empty behind the notice.
const [attempt, setAttempt] = useState(0)
const [failure, setFailure] = useState<ViewFailure | null>(null)
// Derived at render: an engine failure shown while the engine stops becomes the stopped text.
const stopped = useCoreStopped()
const unsaved = useReportStore(isUnsaved)
const engineStopped = failure === 'engine_stopped' || (failure === 'engine' && stopped)
// A failed recovery below the cap needs the runtime restarted before the view is built again.
const retryEngine = useCallback(() => {
void coreRuntime()
.retry()
.finally(() => setAttempt((n) => n + 1))
}, [])
useEffect(() => {
const host = svgRef.current
if (!host) return
host.replaceChildren(buildViewSvg(index, viewId, statesRef.current))
}, [index, viewId])
const build = buildViewSvg(index, viewId)
setFailure(build.ok ? null : build.failure)
host.replaceChildren(...(build.ok ? [build.svg] : []))
}, [index, viewId, attempt])
useEffect(() => {
const host = svgRef.current
@@ -55,7 +84,7 @@ export default function AnatomyCanvas({
if (state) el.setAttribute('data-state', state)
else el.removeAttribute('data-state')
})
}, [states, index, viewId])
}, [states, index, viewId, attempt])
useEffect(() => {
const host = svgRef.current
@@ -123,6 +152,18 @@ export default function AnatomyCanvas({
className="w-full h-full [&>svg]:max-w-full [&>svg]:max-h-full [&>svg]:mx-auto"
/>
<div ref={tooltipRef} className="zone-tooltip" style={{ opacity: 0 }} />
{failure && (
<div className="absolute inset-0 grid place-items-center p-4">
<div className="space-y-3 max-w-sm">
<Notice tone="error">
{t(engineStopped ? stoppedMessageKey(unsaved) : FAILURE_MESSAGE[failure])}
</Notice>
{failure === 'engine' && !engineStopped && (
<Button onClick={retryEngine}>{t('sheet.core_retry')}</Button>
)}
</div>
</div>
)}
</div>
)
}
@@ -20,6 +20,7 @@ import { pickLabel } from '@/i18n/pickLocaleLabel'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import type { Locale } from '@/i18n/types'
import { coreFailureMessage } from '@/core/failure'
export interface ObservationCardProps {
observation: Observation
@@ -168,7 +169,7 @@ export default function ObservationCard({
...(side ? { side } : {}),
})
if (outcome.ok) onChange(outcome.value)
else window.alert(t('core.action_failed'))
else window.alert(coreFailureMessage(t))
}
const removeFinding = (target: Finding) =>
onChange({
@@ -10,6 +10,7 @@ import { useLocaleStore } from '@/state/localeStore'
import { isObservable, type SheetIndex } from '@/services/sheetIndex'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import { useT } from '@/i18n/useT'
import { coreFailureMessage } from '@/core/failure'
/** The zone the vertebra picker edits, with its initial selection (computed on open). */
export interface VertebraTarget {
@@ -63,7 +64,7 @@ export default function ObservationPickers({
if (!fresh) return
const outcome = run(fresh)
if (outcome.ok) updateObservation(activeIndex, outcome.value)
else window.alert(t('core.action_failed'))
else window.alert(coreFailureMessage(t))
}
return (
@@ -11,6 +11,7 @@ import { pickLabel } from '@/i18n/pickLocaleLabel'
import { reportOps } from '@/core/reportOps'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import { coreFailureMessage } from '@/core/failure'
export interface VertebraPickerProps {
open: boolean
@@ -68,7 +69,7 @@ export default function VertebraPicker({
const apply = (action: VertebraAction) => {
const outcome = reportOps.selectVertebrae(selected, action)
if (outcome.ok) setSelected(outcome.value)
else window.alert(t('core.action_failed'))
else window.alert(coreFailureMessage(t))
}
const toggle = (region: string, index: number) =>
apply({ kind: 'toggle', region, index })
@@ -0,0 +1,57 @@
import { useCoreStopped } from '@/core/runtime'
import { downloadJson } from '@/lib/download'
import { isUnsaved, useReportStore } from '@/state/reportStore'
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import { useT } from '@/i18n/useT'
/**
* Saves the in-memory report as JSON. It needs no engine: this is the rescue copy when the
* tab's storage refused the last write and the PDF export cannot run.
*/
export function CopyReportButton() {
const t = useT()
const report = useReportStore((s) => s.report)
if (!report) return null
return (
<Button
variant="secondary"
onClick={() => downloadJson(JSON.stringify(report), 'faunosteo-brouillon')}
>
{t('session.held.download')}
</Button>
)
}
export interface CoreStoppedNoticeProps {
className?: string
}
/**
* The final state of the engine (three recoveries spent), never a retry: reload the page
* when the tab's copy of the report is saved; when it is not, the text says so and offers
* the copy instead of the reload (a reload would lose the latest edits).
*/
export default function CoreStoppedNotice({ className = '' }: CoreStoppedNoticeProps) {
const t = useT()
const unsaved = useReportStore(isUnsaved)
return (
<Notice tone="error" className={className}>
<p>{t(unsaved ? 'core.stopped_unsaved' : 'core.stopped')}</p>
<div className="mt-2">
{unsaved ? (
<CopyReportButton />
) : (
<Button variant="secondary" onClick={() => window.location.reload()}>
{t('core.reload')}
</Button>
)}
</div>
</Notice>
)
}
/** The notice on the pages that run the core, shown only once the engine stopped. */
export function CoreStoppedBanner({ className = '' }: CoreStoppedNoticeProps) {
return useCoreStopped() ? <CoreStoppedNotice className={className} /> : null
}
@@ -1,5 +1,7 @@
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import CoreStoppedNotice from '@/components/report/CoreStoppedNotice'
import { useCoreStopped } from '@/core/runtime'
import { useT } from '@/i18n/useT'
export interface CoreUnavailableProps {
@@ -8,10 +10,19 @@ export interface CoreUnavailableProps {
/**
* Degraded state of the sheet pages when the core module cannot run (CSP, network, an old
* browser, a refused sheet): the session data stays where it is, the practitioner retries.
* browser, a refused sheet): the session data stays where it is, the practitioner retries. Once the engine
* stopped for good, the stopped notice replaces the retry, which could not work.
*/
export default function CoreUnavailable({ onRetry }: CoreUnavailableProps) {
const t = useT()
const stopped = useCoreStopped()
if (stopped) {
return (
<main className="p-6 max-w-xl">
<CoreStoppedNotice />
</main>
)
}
return (
<main className="p-6 space-y-3 max-w-xl">
<Notice tone="error">{t('sheet.core_unavailable')}</Notice>
@@ -2,7 +2,7 @@ import { useState } from 'react'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import Notice from '@/components/ui/Notice'
import { todayIso } from '@/lib/dates'
import { downloadJson } from '@/lib/download'
import { readSessionText, type SessionText } from '@/state/persistence'
import type { HeldText } from '@/state/reportStore'
import { useT } from '@/i18n/useT'
@@ -18,30 +18,15 @@ export interface HeldSessionPanelProps {
type Pending = { action: 'discard'; text: SessionText } | { action: 'open' }
const REVOKE_DELAY_MS = 30_000
const FILE_STEM: Record<SessionText, string> = {
draft: 'faunosteo-brouillon',
archive: 'faunosteo-archive',
}
/**
* Saves the stored text verbatim. It is JSON.stringify output, whose lone surrogates are
* `\uXXXX` escapes, so the UTF-8 Blob is lossless. This copy may be the last one before
* a deletion: the anchor is attached while clicked and the URL revoked later, since some
* engines (WebKit) cancel a download whose URL is revoked at once.
*/
/** Saves the stored text verbatim (it is JSON.stringify output). */
function downloadCopy(text: SessionText): void {
const raw = readSessionText(text)
if (raw === null) return
const url = URL.createObjectURL(new Blob([raw], { type: 'application/json' }))
const a = document.createElement('a')
a.href = url
a.download = `${FILE_STEM[text]}-${todayIso()}.json`
document.body.appendChild(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(url), REVOKE_DELAY_MS)
if (raw !== null) downloadJson(raw, FILE_STEM[text])
}
function rowLabelKey(item: HeldText): string {
@@ -71,7 +56,13 @@ export default function HeldSessionPanel({
return (
<main className="p-4 sm:p-6 space-y-4 max-w-2xl">
<Notice tone="error">{t('session.held.notice')}</Notice>
<Notice tone="error">
{t(
held.some((item) => item.reason === 'engine_failure')
? 'session.held.notice_engine'
: 'session.held.notice',
)}
</Notice>
<ul className="space-y-3">
{held.map((item) => (
<li
@@ -0,0 +1,54 @@
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import { CopyReportButton } from '@/components/report/CoreStoppedNotice'
import { isUnsaved, useReportStore } from '@/state/reportStore'
import { useT } from '@/i18n/useT'
export interface ReplaceSessionDialogProps {
open: boolean
onCancel: () => void
/** Leaves for the editor, where the bilan in progress is. */
onOpen: () => void
onConfirm: () => void
}
/**
* Asked before a new report or an import replaces the bilan in progress in this tab,
* saved or not: the practitioner cancels, goes back to it, or replaces it knowingly.
* An unsaved report (tab storage full) comes with its rescue copy.
*/
export default function ReplaceSessionDialog({
open,
onCancel,
onOpen,
onConfirm,
}: ReplaceSessionDialogProps) {
const t = useT()
const report = useReportStore((s) => s.report)
const unsaved = useReportStore(isUnsaved)
const body = report
? t('session.replace.body').replace(/\{animal\}/, () => report.animal.name)
: t('session.replace.body_unloaded')
return (
<Dialog open={open} onClose={onCancel} title={t('session.replace.title')} size="sm">
<p className="text-sm text-[var(--color-ink-muted)]">{body}</p>
{unsaved && (
<div className="mt-3 space-y-2">
<p className="text-sm">{t('session.replace.unsaved')}</p>
<CopyReportButton />
</div>
)}
<div className="mt-4 flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={onCancel}>
{t('common.cancel')}
</Button>
<Button type="button" variant="secondary" onClick={onOpen}>
{t('session.replace.open')}
</Button>
<Button type="button" variant="danger" onClick={onConfirm}>
{t('session.replace.confirm')}
</Button>
</div>
</Dialog>
)
}
+22
View File
@@ -0,0 +1,22 @@
import type { useT } from '@/i18n/useT'
import { isUnsaved, useReportStore } from '@/state/reportStore'
import { coreStopped } from './runtime'
/** The stopped text: the unsaved variant when the tab's copy of the report is stale. */
export function stoppedMessageKey(unsaved: boolean): string {
return unsaved ? 'core.stopped_unsaved' : 'core.stopped'
}
/**
* The alert after a core action failed: the fallback ("try again") while a retry can work;
* once the engine stopped after its three recoveries, the clear final state instead of a
* retry that cannot succeed (owner decision 2026-10-15). Callers with their own fallback
* key pass it; this file is the only place that names these keys in a `t()` call.
*/
export function coreFailureMessage(
t: ReturnType<typeof useT>,
fallbackKey = 'core.action_failed',
): string {
if (!coreStopped()) return t(fallbackKey)
return t(stoppedMessageKey(isUnsaved(useReportStore.getState())))
}
+16
View File
@@ -1,3 +1,4 @@
import { useSyncExternalStore } from 'react'
import glueUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm.js?url'
import wasmUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm_bg.wasm?url'
import {
@@ -34,6 +35,21 @@ const browserSource: CoreSource = {
let runtime: CoreRuntime | null = null
/** Whether the page's runtime spent its recoveries (never creates the runtime). */
export function coreStopped(): boolean {
return runtime?.stopped ?? false
}
/** Subscribes to the runtime's status changes (stable identity for `useSyncExternalStore`). */
export function subscribeCore(listener: () => void): () => void {
return coreRuntime().subscribe(listener)
}
/** Whether the engine stopped for good on this page; re-renders when it does. */
export function useCoreStopped(): boolean {
return useSyncExternalStore(subscribeCore, coreStopped)
}
/** The page's runtime, created on first use. */
export function coreRuntime(): CoreRuntime {
runtime ??= new CoreRuntime(browserSource)
+11 -1
View File
@@ -1,6 +1,7 @@
import type { CoreOutcome, SheetSession } from '@faunosteo/core-wasm'
import type {
ArchiveImport,
CanvasView,
DraftRestore,
LateralSide,
Observation,
@@ -13,7 +14,7 @@ import type {
/**
* The sheet-bound rules of the editor, run by the core on the session's sheet (R2): one
* call per user action or load, never in a render. Each returns the core's outcome; the
* caller stops on `ok: false` (nothing is written, the action shows `core.action_failed`).
* caller stops on `ok: false` (nothing is written, the action shows `coreFailureMessage`).
*/
export interface FindingToggle {
@@ -89,6 +90,15 @@ export class SheetOps {
return this.run('archive.import', attachment)
}
/**
* The editor canvas of a view: the sheet's drawing, sanitised once at load, with the
* annotation layer (R3). Failures: `unknown_view`, `no_asset`, `svg_rejected` (the reason
* in `detail`), `invalid_character`.
*/
canvasView(viewId: string): CoreOutcome<CanvasView> {
return this.run('view.canvas', { viewId })
}
/** The snapshot of this sheet an archive of `report` carries. */
snapshot(report: Report): CoreOutcome<SheetSnapshot> {
return this.run('archive.snapshot', { report })
+26 -2
View File
@@ -19,15 +19,17 @@ export const en: Dict = {
'home.new_report.description':
'Start a new osteopathic report for an animal.',
'home.new_report.cta': 'Start',
'home.import.title': 'Import a PDF',
'home.import.title': 'Import a PDF or a rescue copy',
'home.import.description':
'Reopen a previous report generated by this app to follow up.',
'home.import.cta': 'Choose a PDF',
'home.import.cta': 'Choose a file',
'home.import.loading': 'Reading…',
'home.import.error_core_unavailable':
'The reading engine could not be loaded. Try the import again.',
'home.import.error_generic': 'Failed to read the PDF.',
'home.import.error_invalid_pdf': 'This file is not a readable PDF.',
'home.import.error_invalid_copy':
'This file is not a Faunosteo rescue copy this version can read. Import refused; the file was not changed.',
'home.import.error_no_attachment':
'This PDF was not generated by Faunosteo (no data detected).',
'home.import.error_incompatible_version':
@@ -122,6 +124,21 @@ export const en: Dict = {
"Open",
'session.held_blocked':
"A draft in this tab must be recovered or deleted first: it could not be set aside and would be overwritten. The editor will open to resolve it.",
'session.held.notice_engine':
"Faunosteo's computation engine cannot open a draft of this tab. It is kept as is; nothing was deleted. Download a copy, try again, or delete it to start a new report.",
'session.held.draft_engine_failure':
"Draft the computation engine cannot open ({size})",
'session.held_blocked_engine':
"A draft of this tab makes the computation engine fail: recover or delete it first. The editor will open to resolve it.",
'session.replace.title': 'Replace the report in progress?',
'session.replace.body':
"The report of {animal} will be replaced in this tab. Export it as a PDF to keep it.",
'session.replace.body_unloaded':
"The report in progress in this tab will be replaced. Open it and export it as a PDF to keep it.",
'session.replace.unsaved':
"Its latest changes are not saved in this tab.",
'session.replace.open': 'Open the report in progress',
'session.replace.confirm': 'Replace',
'editor.edit_infos': 'Edit info',
'editor.edit_dialog_title': 'Edit information',
'editor.disclaimer_title': 'Legal scope of animal osteopathy',
@@ -201,6 +218,13 @@ export const en: Dict = {
'sheet.core_unavailable':
"Faunosteo's computation engine could not be loaded. Your session data is kept.",
'sheet.core_retry': 'Retry',
'core.stopped':
"Faunosteo's computation engine stopped after several errors. Reload the page to start it again: your report is kept in this tab.",
'core.stopped_unsaved':
"Faunosteo's computation engine stopped after several errors, and this tab's storage is full: your latest changes are not saved and would be lost if you reload the page. Download a copy before reloading.",
'core.reload': 'Reload the page',
'canvas.view_unavailable':
"This anatomical view cannot be displayed: its drawing was refused by the safety checks or could not be composed. Your report is not changed.",
'core.action_failed':
'This action could not be applied. Try again; your report was not changed.',
+26 -2
View File
@@ -21,15 +21,17 @@ export const fr: Dict = {
'home.new_report.description':
"Démarrer un nouveau bilan d'ostéopathie sur un animal.",
'home.new_report.cta': 'Commencer',
'home.import.title': 'Importer un PDF',
'home.import.title': 'Importer un PDF ou une copie de secours',
'home.import.description':
'Reprendre un bilan précédent généré par cette application pour effectuer un suivi.',
'home.import.cta': 'Choisir un PDF',
'home.import.cta': 'Choisir un fichier',
'home.import.loading': 'Lecture…',
'home.import.error_core_unavailable':
"Le moteur de lecture n'a pas pu être chargé. Réessayez l'import.",
'home.import.error_generic': 'Erreur de lecture du PDF.',
'home.import.error_invalid_pdf': "Ce fichier n'est pas un PDF lisible.",
'home.import.error_invalid_copy':
"Ce fichier n'est pas une copie de secours Faunosteo lisible par cette version. Import refusé ; le fichier n'a pas été modifié.",
'home.import.error_no_attachment':
"Ce PDF n'a pas été généré par Faunosteo (pas de données détectées).",
'home.import.error_incompatible_version':
@@ -128,6 +130,21 @@ export const fr: Dict = {
"Ouvrir",
'session.held_blocked':
"Un brouillon de cet onglet doit d'abord être récupéré ou supprimé : il n'a pas pu être mis de côté et serait écrasé. L'éditeur va s'ouvrir pour le résoudre.",
'session.held.notice_engine':
"Le moteur de calcul n'arrive pas à ouvrir un brouillon de cet onglet. Il est conservé tel quel ; rien n'a été supprimé. Téléchargez-en une copie, réessayez, ou supprimez-le pour commencer un nouveau bilan.",
'session.held.draft_engine_failure':
"Brouillon que le moteur de calcul n'arrive pas à ouvrir ({size})",
'session.held_blocked_engine':
"Un brouillon de cet onglet fait échouer le moteur de calcul : il doit d'abord être récupéré ou supprimé. L'éditeur va s'ouvrir pour le résoudre.",
'session.replace.title': 'Remplacer le bilan en cours ?',
'session.replace.body':
"Le bilan de {animal} sera remplacé dans cet onglet. Exportez-le en PDF pour le garder.",
'session.replace.body_unloaded':
"Le bilan en cours dans cet onglet sera remplacé. Ouvrez-le et exportez-le en PDF pour le garder.",
'session.replace.unsaved':
"Ses dernières modifications ne sont pas enregistrées dans l'onglet.",
'session.replace.open': 'Ouvrir le bilan en cours',
'session.replace.confirm': 'Remplacer',
'editor.edit_infos': 'Modifier les infos',
'editor.edit_dialog_title': 'Modifier les informations',
'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale",
@@ -215,6 +232,13 @@ export const fr: Dict = {
'sheet.core_unavailable':
"Le moteur de calcul de Faunosteo n'a pas pu être chargé. Vos données de session sont conservées.",
'sheet.core_retry': 'Réessayer',
'core.stopped':
"Le moteur de calcul de Faunosteo s'est arrêté après plusieurs erreurs. Rechargez la page pour le relancer : votre bilan est conservé dans cet onglet.",
'core.stopped_unsaved':
"Le moteur de calcul de Faunosteo s'est arrêté après plusieurs erreurs, et l'espace de stockage de cet onglet est plein : vos dernières modifications ne sont pas enregistrées et seraient perdues en rechargeant la page. Téléchargez une copie avant de recharger.",
'core.reload': 'Recharger la page',
'canvas.view_unavailable':
"Cette vue anatomique ne peut pas être affichée : son dessin a été refusé par les contrôles de sécurité ou n'a pas pu être composé. Votre bilan n'est pas modifié.",
'core.action_failed':
"Cette action n'a pas pu être appliquée. Réessayez ; votre bilan n'a pas été modifié.",
+20
View File
@@ -0,0 +1,20 @@
import { todayIso } from '@/lib/dates'
const REVOKE_DELAY_MS = 30_000
/**
* Saves `raw` as `<stem>-<date>.json`. A lone surrogate in a JSON.stringify output is a
* `\uXXXX` escape, so the UTF-8 Blob is lossless. This copy may be the last one before a
* deletion: the anchor is attached while clicked and the URL revoked later, since some
* engines (WebKit) cancel a download whose URL is revoked at once.
*/
export function downloadJson(raw: string, stem: string): void {
const url = URL.createObjectURL(new Blob([raw], { type: 'application/json' }))
const a = document.createElement('a')
a.href = url
a.download = `${stem}-${todayIso()}.json`
document.body.appendChild(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(url), REVOKE_DELAY_MS)
}
+19 -2
View File
@@ -1,21 +1,24 @@
import type { ArchiveImport } from '@faunosteo/core-wasm/types'
import type { ArchiveImport, RebaseOutcome } from '@faunosteo/core-wasm/types'
import {
ArchiveReadError,
readAttachedDocument,
type ArchiveReadErrorKind,
} from '@faunosteo/pdf'
import type { SheetIndex } from '@/services/sheetIndex'
import { UNREADABLE_DRAFT_KINDS } from '@/state/reportStore'
export { MAX_PDF_BYTES } from '@faunosteo/pdf'
export { MAX_ATTACHMENT_BYTES, MAX_PDF_BYTES } from '@faunosteo/pdf'
/**
* `lone_surrogate`: the attachment escapes a lone UTF-16 surrogate, which the
* core cannot read without altering it (L1): refused, the file untouched.
* `invalid_copy`: a file offered as a rescue copy that this build cannot read.
*/
export type ImportErrorKind =
| ArchiveReadErrorKind
| 'core_unavailable'
| 'lone_surrogate'
| 'invalid_copy'
/**
* Localization-agnostic import error. Carries a kind discriminant + an
@@ -84,3 +87,17 @@ export async function importReportFromPdf(
): Promise<ArchiveImport> {
return importAttachment(await readAttachment(pdfBytes), index)
}
/**
* A rescue copy (`JSON.stringify(report)`, the byte format of the tab's draft)
* read by the core's draft restore, no archive beside it. Content the core
* refuses is `invalid_copy`; any other failure is the engine's or the sheet's.
*/
export function readRescueCopy(text: string, index: SheetIndex): RebaseOutcome {
const outcome = index.ops.restoreDraft(text, null)
if (outcome.ok) return outcome.value.rebase
if (UNREADABLE_DRAFT_KINDS.has(outcome.kind)) {
throw new ImportError('invalid_copy')
}
throw new ImportError('core_unavailable')
}
+13 -4
View File
@@ -10,6 +10,7 @@ import type {
SheetView,
VertebralRegion,
} from '@faunosteo/core-wasm/types'
import type { CoreOutcome } from '@faunosteo/core-wasm'
import type { SheetOps } from '@/core/sheetOps'
/**
@@ -29,8 +30,6 @@ export interface LoadedSheetView {
schemaVersion: number
/** The document as the core parsed it (defaults filled in). */
document: AnatomicalSheetDocument
/** SVG text by `svg_asset_id` (the canvas draws them until R3). */
assets: Readonly<Record<string, string>>
}
function at<T>(
@@ -53,10 +52,11 @@ export class SheetIndex {
readonly mainViewId: string
private readonly spine: ReadonlySet<string>
private readonly nodes: ReadonlySet<string>
/** The composed canvas of each view: constant for a loaded sheet, composed once (R3). */
private readonly canvases = new Map<string, string>()
constructor(
private readonly data: SheetIndexData,
assets: Readonly<Record<string, string>>,
readonly ops: SheetOps,
) {
const { document } = data
@@ -66,13 +66,22 @@ export class SheetIndex {
speciesId: data.speciesId,
schemaVersion: data.schemaVersion,
document,
assets,
}
this.mainViewId = data.mainViewId
this.spine = new Set(data.spineIds)
this.nodes = new Set(data.nodeKeys)
}
/** The SVG text of a view's canvas (sanitised drawing + annotation layer), from the core. */
canvasSvg(viewId: string): CoreOutcome<string> {
const known = this.canvases.get(viewId)
if (known !== undefined) return { ok: true, value: known }
const outcome = this.ops.canvasView(viewId)
if (!outcome.ok) return outcome
this.canvases.set(viewId, outcome.value.svg)
return { ok: true, value: outcome.value.svg }
}
view(id: string): SheetView | undefined {
return at(this.data.document.views, this.data.viewById, id)
}
+1 -1
View File
@@ -49,7 +49,7 @@ async function loadIntoCore(speciesId: string): Promise<SheetLoad> {
const session = coreRuntime().sheet(JSON.stringify(bundle))
const data = session.call<SheetIndexData>('index_data', '')
if (data.ok) {
const index = new SheetIndex(data.value, bundle.assets, new SheetOps(session))
const index = new SheetIndex(data.value, new SheetOps(session))
return { status: 'ready', index }
}
return {
+89 -16
View File
@@ -20,6 +20,7 @@ import {
ARCHIVE_KEY,
quarantine,
quarantineSession,
readSessionText,
removeSessionText,
sessionStorageArchivePersistence,
sessionStoragePersistence,
@@ -57,17 +58,20 @@ export interface ActionResult {
ok: boolean
/** Refused because a session text is held (it could not be set aside and would be lost). */
reason?: 'held'
/** With `held`: the engine itself fails on the tab's draft (a trap), not a storage problem. */
engine?: boolean
}
/**
* A session text kept in place because its safety copy failed (storage full, or the
* quarantine slot already holds an earlier text): `unreadable` by this build, the
* archive `companion` of an unreadable draft, or a draft whose `pre_rebase` original
* could not be kept before the rebase replaces it.
* could not be kept before the rebase replaces it, or a draft the engine trapped on
* (`engine_failure`, kept as is).
*/
export interface HeldText {
text: SessionText
reason: 'unreadable' | 'companion' | 'pre_rebase'
reason: 'unreadable' | 'companion' | 'pre_rebase' | 'engine_failure'
/** UTF-8 size of the stored text, for the resolution panel. */
bytes: number
}
@@ -75,6 +79,8 @@ export interface HeldText {
export interface RestoreOptions {
/** The practitioner confirmed that the rebased draft may replace its original. */
replaceOriginal?: boolean
/** The practitioner asked to read a draft the engine trapped on again. */
retryTrapped?: boolean
}
/** What a draft restore did; `null` from the action when there was nothing to restore. */
@@ -116,6 +122,8 @@ export interface ReportStore {
) => RestoreResult | null
/** Removes a held session text, on the practitioner's confirmed request; no-op once a report is open. */
discardSessionText: (text: SessionText) => void
/** Forgets the draft the engine trapped on (test seam; every discard does it too). */
clearTrapped: () => void
addObservation: () => ActionResult
removeObservation: (index: number) => ActionResult
moveObservationUp: (index: number) => ActionResult
@@ -140,6 +148,11 @@ type Getter = () => ReportStore
const OK: ActionResult = { ok: true }
const FAILED: ActionResult = { ok: false }
const HELD: ActionResult = { ok: false, reason: 'held' }
const HELD_ENGINE: ActionResult = { ok: false, reason: 'held', engine: true }
/** The tab's storage refused the last write: the in-memory report is the only copy. */
export const isUnsaved = (s: Pick<ReportStore, 'saveFailed' | 'report'>): boolean =>
s.saveFailed && s.report !== null
function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) {
set((s) => (s.report ? update(s.report, s) : s))
@@ -168,7 +181,7 @@ function applyCore(
* (`lone_surrogate`: reading it would alter a string, L1). Any other failure is the core's
* or the sheet's and leaves the draft in place.
*/
const UNREADABLE_DRAFT_KINDS: ReadonlySet<string> = new Set([
export const UNREADABLE_DRAFT_KINDS: ReadonlySet<string> = new Set([
'invalid',
'unsupported_version',
'lone_surrogate',
@@ -182,6 +195,37 @@ function held(text: SessionText, reason: HeldText['reason'], raw: string): HeldT
return { text, reason, bytes: utf8Bytes(raw) }
}
/**
* The (draft, archive) pair a `draft.restore` call trapped on. The same pair is never read
* again until the practitioner retries: each read of it would spend an engine recovery.
*/
interface TrapMemory {
matches: (draft: string, archiveText: string | null) => boolean
remember: (draft: string, archiveText: string | null) => void
clear: () => void
}
function createTrapMemory(): TrapMemory {
let trapped: { draft: string; archive: string | null } | null = null
return {
matches: (draft, archiveText) =>
trapped !== null && trapped.draft === draft && trapped.archive === archiveText,
remember: (draft, archiveText) => {
trapped = { draft, archive: archiveText }
},
clear: () => {
trapped = null
},
}
}
/** The held rows of a trapped draft: the draft, and its archive when one is beside it. */
function engineFailureRows(draft: string, archiveText: string | null): HeldText[] {
const rows = [held('draft', 'engine_failure', draft)]
if (archiveText !== null) rows.push(held('archive', 'companion', archiveText))
return rows
}
type Restored = { result: RestoreResult; patch?: Patch } | null
/** An archive with no draft beside it can never be restored: set it aside, or hold it. */
@@ -208,12 +252,21 @@ function restore(
persistence: ReportPersistence,
archives: ArchivePersistence,
options: RestoreOptions,
trap: TrapMemory,
): Restored {
const draft = persistence.loadText()
const archiveText = archives.loadText()
if (draft === null) return restoreOrphanArchive(archiveText)
if (options.retryTrapped) trap.clear()
if (trap.matches(draft, archiveText)) {
return { result: { kind: 'held', held: engineFailureRows(draft, archiveText) } }
}
const outcome = index.ops.restoreDraft(draft, archiveText)
if (!outcome.ok) {
if (outcome.kind === 'internal') {
trap.remember(draft, archiveText)
return { result: { kind: 'held', held: engineFailureRows(draft, archiveText) } }
}
// Only an unreadable draft is set aside; a core or sheet failure leaves it in place.
if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) {
return { result: { kind: 'core_unavailable' } }
@@ -243,29 +296,38 @@ function restore(
/**
* Before a new session replaces texts this page never read: an unreadable draft (and its
* archive) or an unreadable archive is set aside first; a readable draft is replaced as
* before. False when something could not be set aside, or could not even be read.
* before. HELD when something could not be set aside, or when the engine traps on the draft
* (`engine`: kept as is); FAILED when the core could not even read the draft (not a held
* text: nothing is set aside, nothing is written).
*/
function releaseUnreadSession(
index: SheetIndex,
persistence: ReportPersistence,
archives: ArchivePersistence,
): boolean {
trap: TrapMemory,
): ActionResult {
const draft = persistence.loadText()
const archiveText = archives.loadText()
if (draft === null) return restoreOrphanArchive(archiveText) === null
if (draft === null) return restoreOrphanArchive(archiveText) === null ? OK : HELD
if (trap.matches(draft, archiveText)) return HELD_ENGINE
const outcome = index.ops.restoreDraft(draft, archiveText)
if (!outcome.ok) {
if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) return false
return quarantineSession(draft, archiveText)
if (outcome.kind === 'internal') {
trap.remember(draft, archiveText)
return HELD_ENGINE
}
if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) return FAILED
return quarantineSession(draft, archiveText) ? OK : HELD
}
if (!outcome.value.archiveRejected || archiveText === null) return true
return quarantine('archive', archiveText, ARCHIVE_KEY)
if (!outcome.value.archiveRejected || archiveText === null) return OK
return quarantine('archive', archiveText, ARCHIVE_KEY) ? OK : HELD
}
export function createReportStore(
persistence: ReportPersistence,
archives: ArchivePersistence,
) {
const trap = createTrapMemory()
/** The archive mirror is explicit: these actions are the session's edges. */
// The archive of this session could not be written: the tab's copy lacks it (banner).
let archiveRefused = false
@@ -278,9 +340,10 @@ export function createReportStore(
}
/** A new session may start: either one is open (its texts are this store's), or none is left unread. */
const mayStartSession = (index: SheetIndex) =>
store.getState().report !== null ||
releaseUnreadSession(index, persistence, archives)
const mayStartSession = (index: SheetIndex): ActionResult =>
store.getState().report !== null
? OK
: releaseUnreadSession(index, persistence, archives, trap)
const store = create<ReportStore>((set, get) => ({
report: null,
@@ -289,7 +352,8 @@ export function createReportStore(
saveFailed: false,
initReport: (draft, sheet, index) => {
if (!mayStartSession(index)) return HELD
const may = mayStartSession(index)
if (!may.ok) return may
const outcome = reportOps.newReport({
draft,
sheet,
@@ -303,14 +367,15 @@ export function createReportStore(
},
hydrateImport: ({ report, archive }, index) => {
if (!mayStartSession(index)) return HELD
const may = mayStartSession(index)
if (!may.ok) return may
set(withArchive({ report, activeObservationIndex: 0 }, archive))
return OK
},
restoreDraft: (index, options = {}) => {
if (get().report) return null
const restored = restore(index, persistence, archives, options)
const restored = restore(index, persistence, archives, options, trap)
if (!restored) return null
if (restored.patch) set(restored.patch)
return restored.result
@@ -318,9 +383,12 @@ export function createReportStore(
discardSessionText: (text) => {
if (get().report) return
trap.clear()
removeSessionText(text)
},
clearTrapped: () => trap.clear(),
addObservation: () =>
applyCore(
set,
@@ -401,3 +469,8 @@ export const useReportStore = createReportStore(
sessionStoragePersistence,
sessionStorageArchivePersistence,
)
/** A bilan is in progress in this tab: in memory, or as a draft this page never opened. */
export function isSessionInProgress(): boolean {
return useReportStore.getState().report !== null || readSessionText('draft') !== null
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+51 -2
View File
@@ -1,11 +1,24 @@
import { CoreRuntime } from '@faunosteo/core-wasm'
import { nodeCoreRuntime } from '@faunosteo/core-wasm/node'
import { CoreRuntime, type CoreSource } from '@faunosteo/core-wasm'
import { nodeCoreRuntime, nodeCoreSource } from '@faunosteo/core-wasm/node'
/** A loaded runtime on the shipped build (the package's Node source). */
export function testCoreRuntime(): Promise<CoreRuntime> {
return nodeCoreRuntime('pkg')
}
/**
* Makes `runtime.stopped` follow a flag the test controls; the returned setter flips it and
* notifies the subscribers, as the runtime does on its own transition to stopped.
*/
export function controlStopped(runtime: CoreRuntime, initial: boolean) {
let stopped = initial
Object.defineProperty(runtime, 'stopped', { get: () => stopped, configurable: true })
return (next: boolean) => {
stopped = next
;(runtime as unknown as { notify(): void }).notify()
}
}
/** A runtime whose module never loads (CSP refusal, network failure). */
export function unavailableCoreRuntime(): CoreRuntime {
return new CoreRuntime({
@@ -13,3 +26,39 @@ export function unavailableCoreRuntime(): CoreRuntime {
importGlue: () => Promise.reject(new TypeError('blocked')),
})
}
/**
* A real runtime on the shipped module whose `SheetHandle.call` throws a
* `WebAssembly.RuntimeError` (as an out-of-memory trap does) for `draft.restore`
* calls whose input contains `marker`; `traps.count` counts them. The runtime
* poisons and recovers exactly as in production (three recoveries).
*/
export async function trappingCoreRuntime(marker: string) {
const source = nodeCoreSource('pkg')
const traps = { count: 0 }
const wrapped: CoreSource = {
compile: () => source.compile(),
importGlue: async (instance) => {
const glue = await source.importGlue(instance)
const Real = glue.SheetHandle
class Trapping extends Real {
call(op: string, input: string): string {
if (op === 'draft.restore' && input.includes(marker)) {
traps.count += 1
throw new WebAssembly.RuntimeError('unreachable')
}
return super.call(op, input)
}
}
return {
default: glue.default,
core_version: glue.core_version,
call: glue.call,
SheetHandle: Trapping,
}
},
}
const runtime = new CoreRuntime(wrapped)
if (!(await runtime.ready())) throw new Error('trapping runtime failed to load')
return { runtime, traps }
}
+1 -1
View File
@@ -132,5 +132,5 @@ export function sheetFromBundle(bundle: BundledSheetData): SheetIndex {
const session = coreRuntime().sheet(JSON.stringify(bundle))
const data = session.call<SheetIndexData>('index_data', '')
if (!data.ok) throw new Error(`sheet refused by the core: ${data.kind}`)
return new SheetIndex(data.value, bundle.assets, new SheetOps(session))
return new SheetIndex(data.value, new SheetOps(session))
}
+103
View File
@@ -0,0 +1,103 @@
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { expect } from 'vitest'
import { FIXTURES_DIR } from './goldens'
/**
* R3 freeze (plan 2026-10-14 §3 O1): a DOM tree as structure and semantic
* properties, never bytes. Elements by namespace + local name, attributes as
* a map keyed by qualified name (their order is not part of the contract),
* children in document order with text nodes kept (the canvas imports the
* drawing's whitespace), comments and processing instructions named.
*/
export type TreeNode =
| {
ns: string | null
name: string
attrs: Record<string, string>
children: TreeNode[]
}
| { text: string }
| { comment: string }
| { pi: string }
const ELEMENT = 1
const TEXT = 3
const CDATA = 4
const PI = 7
const COMMENT = 8
export function treeOf(node: Node): TreeNode {
if (node.nodeType === TEXT || node.nodeType === CDATA) {
return { text: node.nodeValue ?? '' }
}
if (node.nodeType === COMMENT) return { comment: node.nodeValue ?? '' }
if (node.nodeType === PI) return { pi: node.nodeName }
if (node.nodeType !== ELEMENT) throw new Error(`node type ${node.nodeType}`)
const el = node as Element
const attrs: Record<string, string> = {}
for (const name of Array.from(el.attributes, (a) => a.name).sort()) {
attrs[name] = el.getAttribute(name) ?? ''
}
return {
ns: el.namespaceURI,
name: el.localName,
attrs,
children: Array.from(el.childNodes, treeOf),
}
}
export const R3_GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/r3')
/** `MAKE_R3_GOLDEN=1` writes the R3 freeze; never set it without the owner's decision once frozen. */
export const MAKE_R3_GOLDEN = process.env.MAKE_R3_GOLDEN === '1'
/**
* Compares `actual` with the frozen R3 golden `name`. `declared` applies an owner-validated
* change to the frozen value before comparing (the file itself never changes); with one,
* rewriting the golden is refused.
*/
export function checkR3Golden(
name: string,
actual: unknown,
declared?: (frozen: unknown) => unknown,
): void {
const file = resolve(R3_GOLDEN_DIR, name)
if (MAKE_R3_GOLDEN && declared) throw new Error(`${name}: frozen, a declared change applies`)
if (MAKE_R3_GOLDEN) {
mkdirSync(R3_GOLDEN_DIR, { recursive: true })
writeFileSync(file, `${JSON.stringify(actual, null, 1)}\n`)
return
}
const frozen: unknown = JSON.parse(readFileSync(file, 'utf8'))
expect(actual, name).toEqual(declared ? declared(frozen) : frozen)
}
export interface ViewName {
id: string
fr: string
en: string
}
/**
* Owner decision 2026-10-15 (R3): a trigger without a name of its own carries the opened
* view's name in each language; the TypeScript freeze carries the French name twice. Applied
* to a frozen tree (a deep copy): `data-anno-name-en` takes the English name and the title
* text reads "FR / EN". Mirrors `crates/core/tests/common/svg_tree.rs`.
*/
export function withTriggerNamesPerLanguage(tree: unknown, views: readonly ViewName[]): unknown {
const copy = structuredClone(tree)
const visit = (node: unknown): void => {
if (typeof node !== 'object' || node === null) return
const n = node as { attrs?: Record<string, string>; text?: string; children?: unknown[] }
const view = views.find((v) => v.id === n.attrs?.['data-anno-opens-view'])
if (view && n.attrs?.['data-anno-name-en'] === view.fr) n.attrs['data-anno-name-en'] = view.en
for (const v of views) {
if (n.text === `${v.fr} / ${v.fr}`) n.text = `${v.fr} / ${v.en}`
}
n.children?.forEach(visit)
if (!('attrs' in n) && !('children' in n)) Object.values(n).forEach(visit)
}
visit(copy)
return copy
}
@@ -0,0 +1,69 @@
/**
* The beforeunload guard is app-wide (R3 final checks): prevented exactly while the report
* is unsaved, on any page; App mounts it, the editor no longer registers its own.
*/
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, render, renderHook, waitFor } from '@testing-library/react'
import App from '@/app/App'
import { useUnsavedGuard } from '@/app/useUnsavedGuard'
import { useReportStore } from '@/state/reportStore'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
sessionStorage.clear()
useReportStore.setState({ report: null, archive: null, saveFailed: false })
useReportStore.getState().hydrateImport({ report: minimalReport(sheet), archive: null }, sheet)
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
useReportStore.setState({ report: null, saveFailed: false })
})
const leave = () => {
const event = new Event('beforeunload', { cancelable: true })
window.dispatchEvent(event)
return event.defaultPrevented
}
function fillStorage() {
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
act(() => useReportStore.getState().setConclusion('edited after the quota'))
expect(useReportStore.getState().saveFailed).toBe(true)
}
describe('useUnsavedGuard', () => {
it('prevents the unload exactly while the report is unsaved', async () => {
renderHook(() => useUnsavedGuard())
expect(leave()).toBe(false)
fillStorage()
await waitFor(() => expect(leave()).toBe(true))
vi.restoreAllMocks()
act(() => useReportStore.getState().setConclusion('saved again'))
await waitFor(() => expect(leave()).toBe(false))
})
it('leaves the listener off once the hook unmounts', async () => {
const { unmount } = renderHook(() => useUnsavedGuard())
fillStorage()
await waitFor(() => expect(leave()).toBe(true))
unmount()
expect(leave()).toBe(false)
})
it('is mounted by App, on a page that is not the editor', async () => {
window.history.pushState({}, '', '/')
render(<App />)
expect(leave()).toBe(false)
fillStorage()
await waitFor(() => expect(leave()).toBe(true))
})
})
+95
View File
@@ -0,0 +1,95 @@
/**
* R3 freeze O1 (plan 2026-10-14 §3), now the switch's oracle: the editor canvas as the
* TypeScript built it before the anatomy core moved to Rust (frozen at 47c5f49, never
* regenerated to make this pass). For each view, the whole tree with no state; for every
* state set the editor can produce from the three reference reports (each observation
* active, zones of every view, as EditorRoute builds them) plus "every annotation", the
* annotation layer of the mounted canvas (the core composes, the canvas restyles in place).
* Trees compared by structure and semantic properties, never by bytes or attribute order.
*/
import { afterEach, beforeAll, describe, expect, it } from 'vitest'
import { cleanup, render, waitFor } from '@testing-library/react'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
import { buildViewSvg, type ViewStates } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
import {
buildGoldenReports,
GOLDEN_REPORTS,
type GoldenReports,
} from '../helpers/goldenReports'
import {
checkR3Golden,
treeOf,
withTriggerNamesPerLanguage,
type TreeNode,
} from '../helpers/svgTree'
let sheet: SheetIndex
let golden: GoldenReports
beforeAll(async () => {
sheet = await loadTestSheet()
golden = buildGoldenReports(sheet)
})
afterEach(cleanup)
const VIEWS = ['main', 'head'] as const
/** The state sets of the editor: no selection, every observation of the three reports, all. */
function stateCases(): Array<[string, ViewStates]> {
const cases: Array<[string, ViewStates]> = [['none', new Map()]]
for (const name of GOLDEN_REPORTS) {
for (const obs of golden.reports[name].observations) {
const states = new Map<string, 'current'>()
obs.zones.forEach((z) => states.set(z.annotationId, 'current'))
cases.push([`${name}:${obs.id}`, states])
}
}
const all = new Map<string, 'current'>()
sheet.sheet.document.annotations.forEach((a) => all.set(a.id, 'current'))
cases.push(['all', all])
return cases
}
/** The layer is the last element child of the root; everything before it is the drawing. */
function layerOf(tree: TreeNode): TreeNode {
if (!('children' in tree)) throw new Error('not an element')
const last = tree.children.at(-1)
if (!last || !('attrs' in last) || last.attrs['data-layer'] !== 'annotations') {
throw new Error('the layer is not the last child')
}
return last
}
/** The declared change of the owner's decision 2026-10-15, on the draft's views. */
function declared(frozen: unknown): unknown {
const views = sheet.sheet.document.views.map((v) => ({ id: v.id, ...v.name }))
return withTriggerNamesPerLanguage(frozen, views)
}
async function mountedLayer(viewId: string, states: ViewStates): Promise<TreeNode> {
const { container, unmount } = render(
<AnatomyCanvas index={sheet} viewId={viewId} states={states} onZoneClick={() => undefined} />,
)
await waitFor(() => expect(container.querySelector('svg')).not.toBeNull())
const layer = layerOf(treeOf(container.querySelector('svg')!))
unmount()
return layer
}
describe.each(VIEWS)('the %s canvas', (viewId) => {
it('builds the frozen tree with no state', () => {
const build = buildViewSvg(sheet, viewId)
if (!build.ok) throw new Error(`canvas ${viewId}: ${build.failure}`)
checkR3Golden(`canvas.${viewId}.json`, treeOf(build.svg), declared)
})
it('shows the frozen layer for every state set of the reference reports', async () => {
const layers: Record<string, TreeNode> = {}
for (const [name, states] of stateCases()) {
layers[name] = await mountedLayer(viewId, states)
}
expect(Object.keys(layers).length).toBeGreaterThan(8)
checkR3Golden(`canvas.${viewId}.layers.json`, layers, declared)
})
})
@@ -1,9 +1,17 @@
import { beforeAll, describe, expect, it, vi, afterEach } from 'vitest'
import { cleanup, render, waitFor } from '@testing-library/react'
import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
import { buildViewSvg, parseDrawing, sanitizeSvg } from '@/anatomy/drawing'
import { coreRuntime } from '@/core/runtime'
import { coreFailureMessage } from '@/core/failure'
import { useReportStore } from '@/state/reportStore'
import { buildViewSvg } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
import { controlStopped } from '../helpers/core'
import { bundledSheet, loadTestSheet, minimalReport, sheetFromBundle } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
@@ -11,10 +19,24 @@ beforeAll(async () => {
})
afterEach(cleanup)
/** The composed view, or a test failure naming why it is missing. */
function svgOf(index: SheetIndex, viewId: string): SVGSVGElement {
const build = buildViewSvg(index, viewId)
if (!build.ok) throw new Error(`${viewId}: ${build.failure}`)
return build.svg
}
/** The bundled sheet with its drawing replaced by `svg` (a hostile asset). */
async function sheetDrawing(svg: string): Promise<SheetIndex> {
const bundle = await bundledSheet()
const assets = Object.fromEntries(Object.keys(bundle.assets).map((id) => [id, svg]))
return sheetFromBundle({ ...bundle, assets })
}
describe('buildViewSvg', () => {
it('frames the main view on the asset box and the head view on its crop of the same drawing', () => {
const main = buildViewSvg(sheet, 'main', new Map())
const head = buildViewSvg(sheet, 'head', new Map())
const main = svgOf(sheet, 'main')
const head = svgOf(sheet, 'head')
expect(main.getAttribute('viewBox')).toBe('0 0 2073.4 1629.4')
expect(head.getAttribute('viewBox')).toBe('60 100 500 380')
expect(main.querySelectorAll('path').length).toBe(
@@ -27,25 +49,23 @@ describe('buildViewSvg', () => {
expect(main.hasAttribute('width')).toBe(false)
})
it('applies states as data-state on the generated markers', () => {
const svg = buildViewSvg(sheet, 'main', new Map([['stifle', 'current']]))
const marked = Array.from(
svg.querySelectorAll('[data-state="current"]'),
).map((el) => el.getAttribute('data-anno-id'))
expect(marked).toEqual(['stifle', 'stifle'])
it('composes the view once per sheet (a constant text) and carries no state', () => {
expect(sheet.canvasSvg('main')).toEqual(sheet.canvasSvg('main'))
expect(svgOf(sheet, 'main').querySelector('[data-state]')).toBeNull()
})
it('sanitises scripts, embedded documents and handlers out of an asset', () => {
const root = parseDrawing(
it('refuses a drawing the core would have to alter: nothing of it reaches the page (LRN-025)', async () => {
const hostile = await sheetDrawing(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"><script>alert(1)</script><g onclick="x()"><a href="javascript:void(0)"><path d="M0 0"/></a></g><foreignObject/></svg>',
)
sanitizeSvg(root)
expect(root.querySelector('script')).toBeNull()
expect(root.querySelector('foreignObject')).toBeNull()
expect(root.querySelector('g')!.hasAttribute('onclick')).toBe(false)
expect(root.querySelector('a')!.hasAttribute('href')).toBe(false)
expect(root.querySelector('path')).not.toBeNull()
expect(() => parseDrawing('<not svg')).toThrow()
expect(hostile.canvasSvg('main')).toMatchObject({ ok: false, kind: 'svg_rejected' })
expect(buildViewSvg(hostile, 'main')).toEqual({ ok: false, failure: 'view' })
const malformed = await sheetDrawing('<not svg')
expect(malformed.canvasSvg('main')).toMatchObject({
ok: false,
kind: 'svg_rejected',
detail: 'malformed',
})
})
})
@@ -74,6 +94,128 @@ describe('AnatomyCanvas', () => {
expect(onZoneClick).toHaveBeenCalledTimes(1)
})
it('applies the states right after the build, on both elements of a point', async () => {
const { container } = render(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map([['stifle', 'current']])}
onZoneClick={() => undefined}
/>,
)
await waitFor(() =>
expect(container.querySelector('[data-anno-id="stifle"]')).not.toBeNull(),
)
const marked = Array.from(
container.querySelectorAll('[data-state="current"]'),
).map((el) => el.getAttribute('data-anno-id'))
expect(marked).toEqual(['stifle', 'stifle'])
})
it('names a view it cannot draw, offers no retry and keeps the drawing and the draft as they are', async () => {
useLocaleStore.setState({ locale: 'fr' })
const drawing = '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'
const hostile = await sheetDrawing(drawing)
sessionStorage.setItem('osteo:draft', '{"kept":true}')
const { container } = render(
<AnatomyCanvas index={hostile} viewId="main" states={new Map()} onZoneClick={() => undefined} />,
)
await screen.findByText(fr['canvas.view_unavailable']!)
expect(screen.queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
expect(container.querySelector('script, [data-layer], [data-anno-id]')).toBeNull()
// The refused drawing stays the bundle's own text; the session is untouched.
expect(hostile.canvasSvg('main')).toMatchObject({ ok: false, kind: 'svg_rejected' })
expect(sessionStorage.getItem('osteo:draft')).toBe('{"kept":true}')
})
it('offers a retry when the engine did not run, and draws the view once it does', async () => {
useLocaleStore.setState({ locale: 'fr' })
const user = userEvent.setup()
let engineDown = true
const flaky = Object.create(sheet) as SheetIndex
flaky.canvasSvg = (viewId: string) =>
engineDown ? { ok: false, kind: 'core_unavailable' } : sheet.canvasSvg(viewId)
const { container } = render(
<AnatomyCanvas index={flaky} viewId="main" states={new Map()} onZoneClick={() => undefined} />,
)
await screen.findByText(fr['sheet.core_unavailable']!)
expect(screen.queryByText(fr['canvas.view_unavailable']!)).toBeNull()
engineDown = false
const retry = vi.spyOn(coreRuntime(), 'retry')
await user.click(screen.getByRole('button', { name: fr['sheet.core_retry'] }))
// The engine is restarted first, then the view is built again.
expect(retry).toHaveBeenCalledTimes(1)
await waitFor(() => expect(container.querySelector('[data-anno-id="hip"]')).not.toBeNull())
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
retry.mockRestore()
})
it('after the recoveries are spent, shows the final state with no retry; alerts say the same', async () => {
useLocaleStore.setState({ locale: 'fr' })
const setStopped = controlStopped(coreRuntime(), true)
try {
const down = Object.create(sheet) as SheetIndex
down.canvasSvg = () => ({ ok: false, kind: 'internal' })
render(<AnatomyCanvas index={down} viewId="main" states={new Map()} onZoneClick={() => undefined} />)
await screen.findByText(fr['core.stopped']!)
expect(screen.queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
expect(coreFailureMessage((k: string) => fr[k]!)).toBe(fr['core.stopped'])
} finally {
setStopped(false)
}
expect(coreFailureMessage((k: string) => fr[k]!)).toBe(fr['core.action_failed'])
expect(coreFailureMessage((k: string) => fr[k]!, 'editor.export_failed')).toBe(
fr['editor.export_failed'],
)
})
it('switches a shown engine failure to the stopped text when the engine stops, per save state', async () => {
useLocaleStore.setState({ locale: 'fr' })
const setStopped = controlStopped(coreRuntime(), false)
try {
const down = Object.create(sheet) as SheetIndex
down.canvasSvg = () => ({ ok: false, kind: 'core_unavailable' })
render(<AnatomyCanvas index={down} viewId="main" states={new Map()} onZoneClick={() => undefined} />)
await screen.findByText(fr['sheet.core_unavailable']!)
expect(screen.getByRole('button', { name: fr['sheet.core_retry'] })).toBeInTheDocument()
act(() => setStopped(true))
await screen.findByText(fr['core.stopped']!)
expect(screen.queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
// The draft mirror hits a full storage: the report only lives in memory.
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
act(() => useReportStore.setState({ report: minimalReport(sheet) }))
expect(useReportStore.getState().saveFailed).toBe(true)
await screen.findByText(fr['core.stopped_unsaved']!)
expect(screen.queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
expect(
coreFailureMessage((k: string) => fr[k]!, 'editor.export_failed'),
).toBe(fr['core.stopped_unsaved'])
} finally {
setStopped(false)
vi.restoreAllMocks()
useReportStore.setState({ report: null, saveFailed: false })
}
})
it('words both failures in English too', async () => {
useLocaleStore.setState({ locale: 'en' })
const hostile = await sheetDrawing('<svg xmlns="http://www.w3.org/2000/svg"><script/></svg>')
const first = render(
<AnatomyCanvas index={hostile} viewId="main" states={new Map()} onZoneClick={() => undefined} />,
)
await screen.findByText(en['canvas.view_unavailable']!)
first.unmount()
const down = Object.create(sheet) as SheetIndex
down.canvasSvg = () => ({ ok: false, kind: 'internal' })
render(<AnatomyCanvas index={down} viewId="main" states={new Map()} onZoneClick={() => undefined} />)
await screen.findByText(en['sheet.core_unavailable']!)
expect(screen.getByRole('button', { name: en['sheet.core_retry'] })).toBeInTheDocument()
useLocaleStore.setState({ locale: 'fr' })
})
it('restyles in place when the states change', async () => {
const { container, rerender } = render(
<AnatomyCanvas
@@ -211,3 +211,32 @@ describe('HomeRoute import: size gate', () => {
expect(useReportStore.getState().report).toBeNull()
})
})
describe('HomeRoute import: a core failure reading the tab draft', () => {
it('shows the engine error line, not the held-session alert', async () => {
importMock.mockReturnValue(outcome({ migrated: false }))
const real = useReportStore.getState().hydrateImport
useReportStore.setState({ hydrateImport: () => ({ ok: false }) })
try {
await mountAndPickPdf()
await screen.findByText(fr['home.import.error_core_unavailable']!)
expect(alertMock()).not.toHaveBeenCalled()
expect(screen.queryByTestId('editor-route')).toBeNull()
} finally {
useReportStore.setState({ hydrateImport: real })
}
})
it('still alerts and opens the editor for a held session text', async () => {
importMock.mockReturnValue(outcome({ migrated: false }))
const real = useReportStore.getState().hydrateImport
useReportStore.setState({ hydrateImport: () => ({ ok: false, reason: 'held' }) })
try {
await mountAndPickPdf()
await screen.findByTestId('editor-route')
expect(alertMock()).toHaveBeenCalledWith(fr['session.held_blocked'])
} finally {
useReportStore.setState({ hydrateImport: real })
}
})
})
@@ -0,0 +1,150 @@
/**
* The rescue copy (`JSON.stringify(report)`, the downloaded format) imported from Home:
* routed by content from the first KiB, read by the core's draft restore, opened as the
* original report; every refusal leaves the store and the tab's slots untouched.
*/
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import HomeRoute from '@/app/routes/HomeRoute'
import { MAX_ATTACHMENT_BYTES } from '@/pdf/import'
import { DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { buildGoldenReports, GOLDEN_REPORTS } from '../helpers/goldenReports'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
useReportStore.setState({ report: null, archive: null, activeObservationIndex: 0 })
useReportStore.getState().clearTrapped()
vi.stubGlobal('alert', vi.fn())
})
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
async function pick(file: File) {
render(
<MemoryRouter initialEntries={['/']}>
<Routes>
<Route path="/" element={<HomeRoute />} />
<Route path="/editor" element={<p data-testid="editor-route" />} />
</Routes>
</MemoryRouter>,
)
const button = screen.getByRole('button', { name: fr['home.import.cta'] })
await waitFor(() => expect(button).toBeEnabled())
fireEvent.change(document.querySelector('input[type="file"]')!, {
target: { files: [file] },
})
}
const copyFile = (text: string, name = 'faunosteo-brouillon.json') =>
new File([text], name, { type: 'application/json' })
describe('opening a rescue copy', () => {
it.each(GOLDEN_REPORTS)('reopens the %s report equal to the original', async (name) => {
const { reports } = buildGoldenReports(sheet)
await pick(copyFile(JSON.stringify(reports[name])))
await screen.findByTestId('editor-route')
expect(useReportStore.getState().report).toEqual(reports[name])
expect(useReportStore.getState().archive).toBeNull()
})
it('routes by content: no .json name, no type, leading blanks and a BOM', async () => {
const report = minimalReport(sheet, { conclusion: 'sniffed' })
const text = ` \n${JSON.stringify(report)}`
await pick(new File([text], 'secours'))
await screen.findByTestId('editor-route')
expect(useReportStore.getState().report).toEqual(report)
})
it('announces a copy rebased on another sheet revision', async () => {
const stale = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: 'c'.repeat(64) },
observations: [
{
id: 'o',
zones: [{ annotationId: 'point-gone', viewId: 'main' }],
findings: [],
freeTextFindings: [],
comment: '',
},
],
})
await pick(copyFile(JSON.stringify(stale)))
await screen.findByTestId('editor-route')
expect(window.alert).toHaveBeenCalledWith(
fr['editor.draft_rebased']!.replace('{count}', '1'),
)
})
it('still sends a PDF down the PDF path', async () => {
await pick(new File(['%PDF-1.7 not really'], 'bilan.pdf', { type: 'application/pdf' }))
await screen.findByText(fr['home.import.error_no_attachment']!)
expect(screen.queryByText(fr['home.import.error_invalid_copy']!)).toBeNull()
})
})
describe('refusing a file', () => {
const unreadable = JSON.stringify({ version: 7 })
const refused: [string, () => File][] = [
['invalid JSON', () => copyFile('{not json')],
['an unsupported version', () => copyFile(JSON.stringify({ version: 1 }))],
[
'a lone surrogate',
() => copyFile(JSON.stringify(minimalReport(sheet, { conclusion: 'a\ud800b' }))),
],
[
'invalid UTF-8',
() => new File([new Uint8Array([0x7b, 0xff, 0xfe, 0x7d])], 'copie.json'),
],
]
async function expectUntouched() {
await screen.findByText(fr['home.import.error_invalid_copy']!)
expect(useReportStore.getState().report).toBeNull()
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(unreadable)
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
expect(window.alert).not.toHaveBeenCalled()
expect(screen.queryByTestId('editor-route')).toBeNull()
}
it.each(refused)('%s: error line, nothing changed, nothing held', async (_label, make) => {
sessionStorage.setItem(DRAFT_KEY, unreadable)
await pick(make())
await expectUntouched()
})
it('an over-cap file is refused before any full read', async () => {
sessionStorage.setItem(DRAFT_KEY, unreadable)
const file = copyFile('{"version":3}')
Object.defineProperty(file, 'size', { value: MAX_ATTACHMENT_BYTES + 1 })
const read = vi.spyOn(file, 'arrayBuffer')
await pick(file)
await expectUntouched()
expect(read).not.toHaveBeenCalled()
})
it.each(['internal', 'rebase_failed'])(
'the core kind %s takes the engine message path, not the copy message',
async (kind) => {
vi.spyOn(sheet.ops, 'restoreDraft').mockReturnValue({ ok: false, kind } as never)
await pick(copyFile(JSON.stringify(minimalReport(sheet))))
await screen.findByText(fr['home.import.error_core_unavailable']!)
expect(screen.queryByText(fr['home.import.error_invalid_copy']!)).toBeNull()
expect(useReportStore.getState().report).toBeNull()
},
)
})
@@ -0,0 +1,271 @@
/**
* The engine stopped for good (three recoveries spent, owner decision 2026-10-15): the
* stopped notice on every core page, its two variants (tab copy saved: reload; tab storage
* full: download a copy), no retry anywhere, the editor's save banner with its copy button,
* and the stopped alerts (the beforeunload guard has its own hook test).
*/
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import EditorRoute from '@/app/routes/EditorRoute'
import HomeRoute from '@/app/routes/HomeRoute'
import NewReportRoute from '@/app/routes/NewReportRoute'
import CoreUnavailable from '@/components/report/CoreUnavailable'
import { coreRuntime } from '@/core/runtime'
import { exportReportToPdf } from '@/pdf/export'
import { readAttachment } from '@/pdf/import'
import { loadSheetIndex } from '@/sheets/useSheet'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { controlStopped } from '../helpers/core'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
vi.mock('@/pdf/export', () => ({ exportReportToPdf: vi.fn() }))
vi.mock('@/pdf/import', async (importOriginal) => ({
...(await importOriginal<typeof import('@/pdf/import')>()),
readAttachment: vi.fn(),
}))
vi.mock('@/sheets/useSheet', async (importOriginal) => ({
...(await importOriginal<typeof import('@/sheets/useSheet')>()),
loadSheetIndex: vi.fn((await importOriginal<typeof import('@/sheets/useSheet')>()).loadSheetIndex),
}))
let sheet: SheetIndex
let setStopped: (next: boolean) => void
const blobs: Blob[] = []
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
sessionStorage.setItem('osteo:disclaimer-shown', '1')
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
vi.stubGlobal('alert', vi.fn())
useReportStore.setState({ report: null, archive: null, activeObservationIndex: 0 })
useReportStore.getState().hydrateImport({ report: minimalReport(sheet), archive: null }, sheet)
setStopped = controlStopped(coreRuntime(), true)
blobs.length = 0
URL.createObjectURL = vi.fn((blob: Blob | MediaSource) => {
blobs.push(blob as Blob)
return 'blob:faunosteo-test'
})
URL.revokeObjectURL = vi.fn()
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined)
})
afterEach(() => {
setStopped(false)
cleanup()
vi.restoreAllMocks()
vi.unstubAllGlobals()
useReportStore.setState({ report: null, saveFailed: false })
})
/** The tab's storage is full from now on: the next change of the report is not saved. */
function fillStorage() {
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
act(() => useReportStore.getState().setConclusion('edited after the quota'))
expect(useReportStore.getState().saveFailed).toBe(true)
}
const retryButton = () => screen.queryByRole('button', { name: fr['sheet.core_retry'] })
const reloadButton = () => screen.queryByRole('button', { name: fr['core.reload'] })
const copyButton = () => screen.queryByRole('button', { name: fr['session.held.download'] })
function expectSavedVariant() {
expect(screen.getByText(fr['core.stopped']!)).toBeInTheDocument()
expect(reloadButton()).toBeInTheDocument()
expect(copyButton()).toBeNull()
expect(retryButton()).toBeNull()
}
async function expectUnsavedVariant() {
expect(screen.getByText(fr['core.stopped_unsaved']!)).toBeInTheDocument()
expect(reloadButton()).toBeNull()
expect(retryButton()).toBeNull()
await userEvent.setup().click(copyButton()!)
expect(blobs).toHaveLength(1)
expect(blobs[0]!.type).toBe('application/json')
expect(await blobs[0]!.text()).toBe(JSON.stringify(useReportStore.getState().report))
}
const inRouter = (node: React.ReactNode) =>
render(<MemoryRouter initialEntries={['/']}>{node}</MemoryRouter>)
describe('the stopped notice on the pages that run the core', () => {
it('Home, New report and the full-page notice: reload when the save is fine', async () => {
inRouter(<HomeRoute />)
expectSavedVariant()
cleanup()
inRouter(<NewReportRoute />)
expectSavedVariant()
cleanup()
render(<CoreUnavailable onRetry={() => undefined} />)
expectSavedVariant()
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
})
it('Home, New report and the full-page notice: a copy of the in-memory report when storage is full', async () => {
fillStorage()
inRouter(<HomeRoute />)
await expectUnsavedVariant()
cleanup()
blobs.length = 0
inRouter(<NewReportRoute />)
await expectUnsavedVariant()
cleanup()
blobs.length = 0
render(<CoreUnavailable onRetry={() => undefined} />)
await expectUnsavedVariant()
})
it('is absent while the engine runs, and appears when it stops', async () => {
setStopped(false)
inRouter(<HomeRoute />)
expect(screen.queryByText(fr['core.stopped']!)).toBeNull()
act(() => setStopped(true))
await screen.findByText(fr['core.stopped']!)
})
it('keeps the full-page retry while the engine is not stopped', () => {
setStopped(false)
render(<CoreUnavailable onRetry={() => undefined} />)
expect(screen.getByText(fr['sheet.core_unavailable']!)).toBeInTheDocument()
expect(retryButton()).toBeInTheDocument()
})
})
describe('EditorRoute', () => {
const mountEditor = () => inRouter(<EditorRoute />)
it('puts the stopped notice in the banner slot, in place of the storage-full text', async () => {
mountEditor()
await screen.findByText(fr['core.stopped']!)
expectSavedVariant()
fillStorage()
await screen.findByText(fr['core.stopped_unsaved']!)
expect(screen.queryByText(fr['editor.save_failed']!)).toBeNull()
expect(screen.getAllByText(fr['core.stopped_unsaved']!)).toHaveLength(1)
await expectUnsavedVariant()
})
it('keeps the storage-full text and adds the copy button when the engine runs', async () => {
setStopped(false)
mountEditor()
await screen.findByTestId('sheet-status')
expect(screen.queryByText(fr['editor.save_failed']!)).toBeNull()
fillStorage()
await screen.findByText(fr['editor.save_failed']!)
expect(screen.queryByText(fr['core.stopped_unsaved']!)).toBeNull()
await userEvent.setup().click(copyButton()!)
expect(await blobs[0]!.text()).toBe(JSON.stringify(useReportStore.getState().report))
})
it('says the stopped text when the export fails once the engine stopped', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
vi.mocked(exportReportToPdf).mockRejectedValue(new Error('core_unavailable'))
mountEditor()
await userEvent.setup().click(await screen.findByRole('button', { name: fr['editor.export']! }))
await waitFor(() => expect(window.alert).toHaveBeenCalledWith(fr['core.stopped']))
})
it('says the unsaved stopped text for an export that fails with a full storage', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
vi.mocked(exportReportToPdf).mockRejectedValue(new Error('core_unavailable'))
mountEditor()
const button = await screen.findByRole('button', { name: fr['editor.export']! })
fillStorage()
await userEvent.setup().click(button)
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['core.stopped_unsaved']),
)
})
it('keeps the export message while the engine is not stopped', async () => {
setStopped(false)
vi.spyOn(console, 'error').mockImplementation(() => undefined)
vi.mocked(exportReportToPdf).mockRejectedValue(new Error('render exploded'))
mountEditor()
await userEvent.setup().click(await screen.findByRole('button', { name: fr['editor.export']! }))
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['editor.export_failed']),
)
})
})
describe('the stopped text on the Home import line and the New report alert', () => {
const realLoad = vi.mocked(loadSheetIndex).getMockImplementation()!
beforeEach(() => {
vi.mocked(loadSheetIndex).mockResolvedValue(null)
vi.mocked(readAttachment).mockResolvedValue({ version: 3 })
})
afterEach(() => vi.mocked(loadSheetIndex).mockImplementation(realLoad))
async function pickPdf() {
inRouter(<HomeRoute />)
const button = screen.getByRole('button', { name: fr['home.import.cta'] })
await waitFor(() => expect(button).toBeEnabled())
const file = new File([new Uint8Array([37, 80, 68, 70])], 'bilan.pdf')
fireEvent.change(document.querySelector('input[type="file"]')!, {
target: { files: [file] },
})
}
async function submitNewReport() {
const user = userEvent.setup()
inRouter(<NewReportRoute />)
await user.type(screen.getByLabelText(fr['form.practitioner.name']!), 'Dr X')
await user.type(screen.getByLabelText(fr['form.animal.name']!), 'Rex')
await user.type(screen.getByLabelText(fr['form.owner.name']!), 'Y')
const submit = screen.getByRole('button', { name: fr['new_report.submit']! })
await waitFor(() => expect(submit).toBeEnabled())
await user.click(submit)
// A report is in progress (beforeEach): replacing it is confirmed first.
await user.click(await screen.findByRole('button', { name: fr['session.replace.confirm']! }))
}
it('Home import: the engine error line says the stopped text', async () => {
await pickPdf()
await screen.findByText(fr['core.stopped']!, { selector: 'p.text-red-700' })
expect(screen.queryByText(fr['home.import.error_core_unavailable']!)).toBeNull()
})
it('Home import: the unsaved stopped text when storage is full', async () => {
fillStorage()
await pickPdf()
await screen.findByText(fr['core.stopped_unsaved']!, { selector: 'p.text-red-700' })
})
it('Home import: keeps the engine error line while the engine is not stopped', async () => {
setStopped(false)
await pickPdf()
await screen.findByText(fr['home.import.error_core_unavailable']!)
})
it('New report: the alert says the stopped text', async () => {
await submitNewReport()
await waitFor(() => expect(window.alert).toHaveBeenCalledWith(fr['core.stopped']))
})
it('New report: the unsaved stopped text when storage is full', async () => {
fillStorage()
await submitNewReport()
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['core.stopped_unsaved']),
)
})
it('New report: keeps the sheet alert while the engine is not stopped', async () => {
setStopped(false)
await submitNewReport()
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['sheet.core_unavailable']),
)
})
})
@@ -177,6 +177,10 @@ describe('a new report over a held draft', () => {
const submit = screen.getByRole('button', { name: fr['new_report.submit'] })
await waitFor(() => expect(submit).toBeEnabled())
await user.click(submit)
// A draft sits in the slot: replacing it is confirmed first.
await user.click(
await screen.findByRole('button', { name: fr['session.replace.confirm']! }),
)
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked']),
)
@@ -0,0 +1,194 @@
/**
* Replacing the bilan in progress (R3 final checks): New report and the Home file pick ask
* first when a report is in memory or a draft sits in the slot (named, unloaded and
* unsaved variants); Annuler changes nothing, Ouvrir goes back to the editor, Remplacer
* proceeds; nothing in progress, no dialog.
*/
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import HomeRoute from '@/app/routes/HomeRoute'
import NewReportRoute from '@/app/routes/NewReportRoute'
import { DRAFT_KEY } from '@/state/persistence'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
localStorage.clear()
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
saveFailed: false,
})
useReportStore.getState().clearTrapped()
vi.stubGlobal('alert', vi.fn())
})
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
vi.restoreAllMocks()
useReportStore.setState({ report: null, saveFailed: false })
})
const mount = (path: '/' | '/new') =>
render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/" element={<HomeRoute />} />
<Route path="/new" element={<NewReportRoute />} />
<Route path="/editor" element={<p data-testid="editor-route" />} />
</Routes>
</MemoryRouter>,
)
const openReport = (animalName = 'Mistral') =>
useReportStore.getState().hydrateImport(
{ report: minimalReport(sheet, { animal: { speciesId: 'equine', name: animalName } }), archive: null },
sheet,
)
async function submitForm(user: ReturnType<typeof userEvent.setup>) {
await user.type(screen.getByLabelText(fr['form.practitioner.name']!), 'Dr X')
await user.type(screen.getByLabelText(fr['form.animal.name']!), 'Rex')
await user.type(screen.getByLabelText(fr['form.owner.name']!), 'Y')
const submit = screen.getByRole('button', { name: fr['new_report.submit']! })
await waitFor(() => expect(submit).toBeEnabled())
await user.click(submit)
}
const button = (key: string) => screen.getByRole('button', { name: fr[key]! })
/** A button of the open dialog (the page behind has its own Annuler). */
const dialogButton = (key: string) =>
within(screen.getByRole('dialog')).getByRole('button', { name: fr[key]! })
describe('New report over a bilan in progress', () => {
it('names the animal of the report in memory and replaces it on Remplacer', async () => {
const user = userEvent.setup()
openReport()
mount('/new')
await submitForm(user)
const dialog = await screen.findByRole('dialog')
expect(dialog).toHaveTextContent(fr['session.replace.body']!.replace('{animal}', 'Mistral'))
expect(dialog).not.toHaveTextContent(fr['session.replace.unsaved']!)
await user.click(button('session.replace.confirm'))
await screen.findByTestId('editor-route')
expect(useReportStore.getState().report?.animal.name).toBe('Rex')
})
it('renders an animal name with a replacement pattern literally', async () => {
const user = userEvent.setup()
openReport('Rex$&$1')
mount('/new')
await submitForm(user)
expect(await screen.findByRole('dialog')).toHaveTextContent('Le bilan de Rex$&$1 sera')
})
it('uses the unloaded text for a draft this page never opened', async () => {
const user = userEvent.setup()
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
mount('/new')
await submitForm(user)
expect(await screen.findByRole('dialog')).toHaveTextContent(fr['session.replace.body_unloaded']!)
})
it('adds the unsaved line and the copy button when the tab storage is full', async () => {
const user = userEvent.setup()
openReport()
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
act(() => useReportStore.getState().setConclusion('edited'))
mount('/new')
await submitForm(user)
const dialog = await screen.findByRole('dialog')
expect(dialog).toHaveTextContent(fr['session.replace.unsaved']!)
expect(dialog).toHaveTextContent(fr['session.held.download']!)
})
it('Annuler changes nothing and Ouvrir goes to the editor', async () => {
const user = userEvent.setup()
openReport()
const before = useReportStore.getState().report
mount('/new')
await submitForm(user)
await screen.findByRole('dialog')
await user.click(dialogButton('common.cancel'))
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(useReportStore.getState().report).toBe(before)
await user.click(button('new_report.submit'))
await screen.findByRole('dialog')
await user.click(button('session.replace.open'))
await screen.findByTestId('editor-route')
expect(useReportStore.getState().report).toBe(before)
})
it('asks nothing when no bilan is in progress', async () => {
const user = userEvent.setup()
mount('/new')
await submitForm(user)
await screen.findByTestId('editor-route')
expect(screen.queryByRole('dialog')).toBeNull()
expect(useReportStore.getState().report?.animal.name).toBe('Rex')
})
})
describe('the Home file pick over a bilan in progress', () => {
const pickButton = () => button('home.import.cta')
const enabled = () => waitFor(() => expect(pickButton()).toBeEnabled())
it('asks first; Remplacer opens the picker inside the same click', async () => {
const user = userEvent.setup()
openReport()
const click = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined)
mount('/')
await enabled()
await user.click(pickButton())
expect(await screen.findByRole('dialog')).toHaveTextContent('Mistral')
expect(click).not.toHaveBeenCalled()
fireEvent.click(button('session.replace.confirm'))
expect(click).toHaveBeenCalledOnce()
})
it('Annuler never opens the picker; Ouvrir goes to the editor; the report stays', async () => {
const user = userEvent.setup()
openReport()
const before = useReportStore.getState().report
const click = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined)
mount('/')
await enabled()
await user.click(pickButton())
await user.click(dialogButton('common.cancel'))
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
await user.click(pickButton())
await user.click(button('session.replace.open'))
await screen.findByTestId('editor-route')
expect(click).not.toHaveBeenCalled()
expect(useReportStore.getState().report).toBe(before)
})
it('also asks for a draft only in the slot (unloaded text), nothing otherwise', async () => {
const user = userEvent.setup()
const click = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined)
mount('/')
await enabled()
await user.click(pickButton())
expect(screen.queryByRole('dialog')).toBeNull()
expect(click).toHaveBeenCalledOnce()
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
await user.click(pickButton())
expect(await screen.findByRole('dialog')).toHaveTextContent(fr['session.replace.body_unloaded']!)
expect(click).toHaveBeenCalledOnce()
})
})
@@ -0,0 +1,181 @@
/**
* A draft the engine traps on (R3 final checks): on a real poisoning runtime the editor
* shows the resolution panel (engine_failure row, engine notice), never the reload screen
* while the engine is not stopped; New report and Import answer the engine message then
* open the panel; the trapping (draft, archive) pair is read once (one trap across mount,
* New report, Import and remount); only the panel's Retry reads it again; a confirmed
* discard removes the draft and clears the memory.
*/
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import EditorRoute from '@/app/routes/EditorRoute'
import HomeRoute from '@/app/routes/HomeRoute'
import NewReportRoute from '@/app/routes/NewReportRoute'
import { setCoreRuntime } from '@/core/runtime'
import { bundledSheetProvider } from '@/sheets/provider'
import { setSheetProvider } from '@/sheets/useSheet'
import { useReportStore } from '@/state/reportStore'
import { DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { testCoreRuntime, trappingCoreRuntime } from '../helpers/core'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
const MARKER = 'trap-me'
let sheet: SheetIndex
let draft: string
let traps: { count: number }
let engineStopped: () => boolean
let engineReady: () => Promise<boolean>
beforeAll(async () => {
sheet = await loadTestSheet()
draft = JSON.stringify(minimalReport(sheet, { conclusion: MARKER }))
})
beforeEach(async () => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
localStorage.clear()
sessionStorage.setItem('osteo:disclaimer-shown', '1')
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
vi.stubGlobal('alert', vi.fn())
useReportStore.setState({ report: null, archive: null, activeObservationIndex: 0 })
useReportStore.getState().clearTrapped()
const trapping = await trappingCoreRuntime(MARKER)
traps = trapping.traps
engineStopped = () => trapping.runtime.stopped
engineReady = () => trapping.runtime.ready()
setCoreRuntime(trapping.runtime)
setSheetProvider(bundledSheetProvider)
// After the reset (an empty store mirrors no draft): the tab as a reload finds it.
sessionStorage.setItem(DRAFT_KEY, draft)
})
afterEach(async () => {
cleanup()
vi.unstubAllGlobals()
vi.restoreAllMocks()
useReportStore.getState().clearTrapped()
setCoreRuntime(await testCoreRuntime())
setSheetProvider(bundledSheetProvider)
})
const routes = (initial: string) =>
render(
<MemoryRouter initialEntries={[initial]}>
<Routes>
<Route path="/" element={<HomeRoute />} />
<Route path="/new" element={<NewReportRoute />} />
<Route path="/editor" element={<EditorRoute />} />
</Routes>
</MemoryRouter>,
)
async function expectEnginePanel() {
await screen.findByText(fr['session.held.notice_engine']!)
expect(screen.getByTestId('held-draft')).toHaveTextContent(
fr['session.held.draft_engine_failure']!.replace('{size}', /\d+ Ko/.exec(
screen.getByTestId('held-draft').textContent ?? '',
)![0]),
)
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
}
async function submitNewReport(user: ReturnType<typeof userEvent.setup>) {
await user.type(screen.getByLabelText(fr['form.practitioner.name']!), 'Dr X')
await user.type(screen.getByLabelText(fr['form.animal.name']!), 'Rex')
await user.type(screen.getByLabelText(fr['form.owner.name']!), 'Y')
const submit = screen.getByRole('button', { name: fr['new_report.submit']! })
await waitFor(() => expect(submit).toBeEnabled())
await user.click(submit)
await user.click(
await screen.findByRole('button', { name: fr['session.replace.confirm']! }),
)
}
async function pickCopy(user: ReturnType<typeof userEvent.setup>) {
const pick = screen.getByRole('button', { name: fr['home.import.cta']! })
await waitFor(() => expect(pick).toBeEnabled())
await user.click(pick)
vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined)
await user.click(
await screen.findByRole('button', { name: fr['session.replace.confirm']! }),
)
const copy = JSON.stringify(minimalReport(sheet, { id: 'other' }))
fireEvent.change(document.querySelector('input[type="file"]')!, {
target: { files: [new File([copy], 'copie.json', { type: 'application/json' })] },
})
}
describe('a draft the engine traps on', () => {
it('opens the engine_failure panel, never the reload screen', async () => {
routes('/editor')
await expectEnginePanel()
expect(traps.count).toBe(1)
expect(engineStopped()).toBe(false)
expect(useReportStore.getState().report).toBeNull()
})
it('is read once across mount, New report, Import and remount', async () => {
const user = userEvent.setup()
routes('/editor')
await expectEnginePanel()
cleanup()
routes('/new')
await submitNewReport(user)
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked_engine']),
)
await expectEnginePanel()
cleanup()
routes('/')
await pickCopy(user)
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked_engine']),
)
await expectEnginePanel()
cleanup()
routes('/editor')
await expectEnginePanel()
expect(traps.count).toBe(1)
expect(useReportStore.getState().report).toBeNull()
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
})
it('reads the pair again only on the panel Retry', async () => {
const user = userEvent.setup()
routes('/editor')
await expectEnginePanel()
// The instance that trapped is replaced in the background: retry on the fresh one.
await engineReady()
await user.click(screen.getByRole('button', { name: fr['session.held.retry'] }))
await waitFor(() => expect(traps.count).toBe(2))
await expectEnginePanel()
})
it('removes only the draft after the confirmation and forgets the trap', async () => {
const user = userEvent.setup()
routes('/editor')
await expectEnginePanel()
await user.click(screen.getByRole('button', { name: fr['session.held.discard'] }))
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
await user.click(
screen.getByRole('button', { name: fr['session.held.discard_confirm'] }),
)
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
cleanup()
await engineReady()
// The memory is gone: the same text, stored again, is read (and traps) anew.
sessionStorage.setItem(DRAFT_KEY, draft)
routes('/editor')
await expectEnginePanel()
expect(traps.count).toBe(2)
})
})
@@ -265,18 +265,21 @@ describe('a new session over texts this page never read (after a reload)', () =>
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
})
it('is refused when the core cannot read the draft at all', () => {
it('fails (not held) when the core cannot read the draft at all, touching nothing', () => {
const draft = JSON.stringify(minimalReport(sheet))
sessionStorage.setItem(DRAFT_KEY, draft)
const broken = {
...sheet,
ops: { restoreDraft: () => ({ ok: false, kind: 'core_unavailable' }) },
} as unknown as SheetIndex
expect(store().initReport(newDraft(), sheet.sheet.ref, broken)).toEqual({
ok: false,
reason: 'held',
})
const before = snapshotStorage()
expect(store().initReport(newDraft(), sheet.sheet.ref, broken)).toEqual({ ok: false })
expect(
store().hydrateImport({ report: minimalReport(sheet), archive: null }, broken),
).toEqual({ ok: false })
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
expect(snapshotStorage()).toEqual(before)
expect(store().report).toBeNull()
})
})
+87 -1
View File
@@ -32,6 +32,7 @@ beforeEach(() => {
archive: null,
activeObservationIndex: 0,
})
useReportStore.getState().clearTrapped()
})
afterEach(() => vi.restoreAllMocks())
@@ -91,7 +92,7 @@ describe('an unreadable draft', () => {
})
describe('a core failure while reading the draft', () => {
it.each(['core_unavailable', 'internal', 'rebase_failed'])(
it.each(['core_unavailable', 'rebase_failed'])(
'%s leaves the draft and the archive untouched',
(kind) => {
const draft = JSON.stringify(minimalReport(sheet))
@@ -109,6 +110,91 @@ describe('a core failure while reading the draft', () => {
)
})
describe('a core trap while reading the draft (internal)', () => {
/** A sheet whose draft restore traps (`internal`), counting the reads. */
function trappingSheet() {
const calls = { n: 0 }
const index = {
...sheet,
ops: {
restoreDraft: () => {
calls.n += 1
return { ok: false, kind: 'internal' }
},
},
} as unknown as SheetIndex
return { index, calls }
}
const draftText = () => JSON.stringify(minimalReport(sheet))
function seed() {
const draft = draftText()
sessionStorage.setItem(DRAFT_KEY, draft)
sessionStorage.setItem(ARCHIVE_KEY, '{"kept":true}')
return draft
}
it('holds the draft (engine_failure) and its archive, both untouched', () => {
const draft = seed()
const { index } = trappingSheet()
const result = useReportStore.getState().restoreDraft(index)
expect(result).toMatchObject({
kind: 'held',
held: [
{ text: 'draft', reason: 'engine_failure' },
{ text: 'archive', reason: 'companion' },
],
})
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBe('{"kept":true}')
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
expect(useReportStore.getState().report).toBeNull()
})
it('never reads the same pair again, except on the explicit retry', () => {
seed()
const { index, calls } = trappingSheet()
const store = useReportStore.getState()
store.restoreDraft(index)
expect(store.restoreDraft(index)).toMatchObject({ kind: 'held' })
expect(calls.n).toBe(1)
store.restoreDraft(index, { retryTrapped: true })
expect(calls.n).toBe(2)
})
it('answers a new session HELD with the engine cause, without a second read', () => {
seed()
const { index, calls } = trappingSheet()
const store = useReportStore.getState()
store.restoreDraft(index)
const draft = { practitioner: { name: 'p' } } as never
expect(store.initReport(draft, sheet.sheet.ref, index)).toEqual({
ok: false,
reason: 'held',
engine: true,
})
expect(store.hydrateImport({ report: minimalReport(sheet), archive: null }, index)).toEqual({
ok: false,
reason: 'held',
engine: true,
})
expect(calls.n).toBe(1)
})
it('reads again once the stored pair changed, or after a discard', () => {
seed()
const { index, calls } = trappingSheet()
const store = useReportStore.getState()
store.restoreDraft(index)
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet, { conclusion: 'x' })))
store.restoreDraft(index)
expect(calls.n).toBe(2)
store.discardSessionText('archive')
store.restoreDraft(index)
expect(calls.n).toBe(3)
})
})
describe('an unreadable archive beside a readable draft', () => {
it('goes to its quarantine key while the draft restores', () => {
sessionStorage.setItem(
+1
View File
@@ -19,6 +19,7 @@ ts = ["dep:ts-rs"]
serde.workspace = true
serde_json.workspace = true
url.workspace = true
roxmltree.workspace = true
ts-rs = { workspace = true, optional = true }
[lints]
+236
View File
@@ -0,0 +1,236 @@
//! Composition of one view (`docs/ANNOTATION-RENDERING.md`): the sanitised drawing framed on
//! the view, with its annotation layer last. Two forms, as the TypeScript has them: the
//! editor canvas (`apps/app/src/anatomy/drawing.ts`: a fresh root, `0 0 100 100` when no box
//! is known, the interactive layer) and the PDF highlight (`packages/anatomy/src/render/
//! compose.ts`: the asset's root framed in place, the selected markers only, recoloured, the
//! halo filter on request). Both take a sanitised tree, never text.
use std::collections::HashSet;
use super::layer::{LayerError, find_view, render_layer, view_box_of};
use super::svg::serialize::is_xml_text;
use super::svg::{Element, Node};
use crate::domain::sheet::AnatomicalSheetDocument;
pub const HIGHLIGHT_FILL: &str = "#b85a3f";
pub const HIGHLIGHT_FILL_OPACITY: &str = "0.85";
pub const HALO_FILTER_ID: &str = "osteo-halo";
const CANVAS_FALLBACK_VIEW_BOX: &str = "0 0 100 100";
/// Why a view cannot be composed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComposeError {
UnknownView,
/// A label or a path of the layer holds a code point XML 1.0 cannot carry.
InvalidCharacter,
}
impl From<LayerError> for ComposeError {
fn from(_: LayerError) -> Self {
Self::UnknownView
}
}
/// The asset a view draws: its own, else the first up its parent chain (cycle-safe).
pub fn asset_id_of_view<'a>(
document: &'a AnatomicalSheetDocument,
view_id: &str,
) -> Option<&'a str> {
let mut visited: HashSet<&str> = HashSet::new();
let mut current = find_view(document, view_id);
while let Some(view) = current {
if let Some(asset) = view.svg_asset_id() {
return Some(asset);
}
if !visited.insert(view.id()) {
return None;
}
current = view.parent_view_id().and_then(|p| find_view(document, p));
}
None
}
/// The editor canvas of `view_id` drawn on `asset` (its sanitised drawing), no state: the
/// canvas sets `data-state` in place after every build.
pub fn compose_canvas(
document: &AnatomicalSheetDocument,
view_id: &str,
asset: &Element,
) -> Result<Element, ComposeError> {
let view = find_view(document, view_id).ok_or(ComposeError::UnknownView)?;
let mut root = Element {
qname: "svg".to_owned(),
namespace: asset.namespace.clone(),
attrs: asset
.attrs
.iter()
.filter(|a| a.qname != "width" && a.qname != "height")
.cloned()
.collect(),
children: asset.children.clone(),
};
let view_box = view_box_of(view)
.or_else(|| asset.attr("viewBox").map(str::to_owned))
.unwrap_or_else(|| CANVAS_FALLBACK_VIEW_BOX.to_owned());
root.set_attr("viewBox", view_box);
let layer = render_layer(document, view_id, &HashSet::new())?;
root.children.push(Node::Element(checked(layer)?));
Ok(root)
}
/// The PDF view of `view_id`: `asset` (sanitised, consumed) framed on the view, the markers
/// of `annotation_ids` only, recoloured, with the halo filter when `halo`.
pub fn compose_highlight(
document: &AnatomicalSheetDocument,
view_id: &str,
mut asset: Element,
annotation_ids: &HashSet<&str>,
halo: bool,
) -> Result<Element, ComposeError> {
let view = find_view(document, view_id).ok_or(ComposeError::UnknownView)?;
if let Some(view_box) = view_box_of(view) {
asset.set_attr("viewBox", view_box);
}
asset.remove_attr("width");
asset.remove_attr("height");
if halo {
ensure_halo_filter(&mut asset);
}
let layer = render_layer(document, view_id, &HashSet::new())?;
let layer = highlight_layer(layer, annotation_ids, halo);
asset.children.push(Node::Element(checked(layer)?));
Ok(asset)
}
/// The layer reduced to the selected annotations, recoloured, every `data-*` dropped.
fn highlight_layer(mut layer: Element, ids: &HashSet<&str>, halo: bool) -> Element {
layer.attrs.retain(|a| !a.qname.starts_with("data-"));
let children = std::mem::take(&mut layer.children);
layer.children = children
.into_iter()
.filter_map(|child| match child {
Node::Element(e) if e.attr("data-anno-id").is_some_and(|id| ids.contains(id)) => {
Some(Node::Element(highlight_element(e, halo)))
}
_ => None,
})
.collect();
layer
}
/// `{ ...withoutData(attrs), fill, 'fill-opacity' }` then `filter`: JavaScript keeps an
/// existing key in place and appends a new one.
fn highlight_element(mut element: Element, halo: bool) -> Element {
element.attrs.retain(|a| !a.qname.starts_with("data-"));
element.set_attr("fill", HIGHLIGHT_FILL.to_owned());
element.set_attr("fill-opacity", HIGHLIGHT_FILL_OPACITY.to_owned());
if halo {
element.set_attr("filter", format!("url(#{HALO_FILTER_ID})"));
}
element
}
/// One halo filter per root: in the first `<defs>` of the drawing, else in a new `<defs>`
/// placed first; nothing when a `filter#osteo-halo` already exists.
fn ensure_halo_filter(root: &mut Element) {
if has_halo_filter(root) {
return;
}
if !append_to_first_defs(root) {
let defs = Element::svg("defs", Vec::new(), vec![Node::Element(halo_filter())]);
root.children.insert(0, Node::Element(defs));
}
}
fn has_halo_filter(element: &Element) -> bool {
element.element_children().any(|c| {
(c.qname == "filter" && c.attr("id") == Some(HALO_FILTER_ID)) || has_halo_filter(c)
})
}
/// Appends the halo to the first `<defs>` below `element` (document order).
fn append_to_first_defs(element: &mut Element) -> bool {
for child in &mut element.children {
let Node::Element(child) = child else {
continue;
};
if child.qname == "defs" {
child.children.push(Node::Element(halo_filter()));
return true;
}
if append_to_first_defs(child) {
return true;
}
}
false
}
fn halo_filter() -> Element {
let blur = |std: &str, result: &str| {
Node::Element(Element::svg(
"feGaussianBlur",
vec![
("in", "SourceGraphic".to_owned()),
("stdDeviation", std.to_owned()),
("result", result.to_owned()),
],
Vec::new(),
))
};
let inputs = [
"haloWide",
"haloWide",
"haloWide",
"haloTight",
"haloTight",
"SourceGraphic",
];
let merge = Element::svg(
"feMerge",
Vec::new(),
inputs
.iter()
.map(|i| {
Node::Element(Element::svg(
"feMergeNode",
vec![("in", (*i).to_owned())],
Vec::new(),
))
})
.collect(),
);
let attrs = vec![
("id", HALO_FILTER_ID.to_owned()),
("x", "-100%".to_owned()),
("y", "-100%".to_owned()),
("width", "300%".to_owned()),
("height", "300%".to_owned()),
("filterUnits", "userSpaceOnUse".to_owned()),
];
Element::svg(
"filter",
attrs,
vec![
blur("18", "haloWide"),
blur("8", "haloTight"),
Node::Element(merge),
],
)
}
/// The layer carries document strings: refuse one XML cannot carry (never replace it).
fn checked(layer: Element) -> Result<Element, ComposeError> {
if xml_safe(&layer) {
Ok(layer)
} else {
Err(ComposeError::InvalidCharacter)
}
}
fn xml_safe(element: &Element) -> bool {
element.attrs.iter().all(|a| is_xml_text(&a.value))
&& element.children.iter().all(|c| match c {
Node::Element(e) => xml_safe(e),
Node::Text(t) => is_xml_text(t),
})
}
+304
View File
@@ -0,0 +1,304 @@
//! The annotation layer of one view (`packages/anatomy/src/render/layer.ts`, contract
//! `docs/ANNOTATION-RENDERING.md`): markers drawn from the document, in document order, with
//! the TypeScript attribute order (the review drawings are byte goldens of it until R5).
use std::collections::{HashMap, HashSet};
use super::svg::{Element, Node};
use crate::domain::sheet::{
AnatomicalSheetDocument, Annotation, Geometry, Laterality, LocalizedText, SheetView,
};
use crate::json::js_number;
pub const FALLBACK_COLOR: &str = "#888888";
/// Why a layer cannot be drawn.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LayerError {
UnknownView,
}
/// The view of that id (first match, as `Array.find`).
pub fn find_view<'a>(
document: &'a AnatomicalSheetDocument,
view_id: &str,
) -> Option<&'a SheetView> {
document.views.iter().find(|v| v.id() == view_id)
}
/// `renderAnnotationLayer({ document, viewId, states })`: `states` holds the ids marked
/// `data-state="current"`.
pub fn render_layer(
document: &AnatomicalSheetDocument,
view_id: &str,
states: &HashSet<&str>,
) -> Result<Element, LayerError> {
let view = find_view(document, view_id).ok_or(LayerError::UnknownView)?;
let context = Context {
twin_opacity: if view.is_main() { "0.65" } else { "0.5" },
categories: document
.categories
.iter()
.map(|c| (c.id.as_str(), c.color.as_deref()))
.collect(),
view_names: document.views.iter().map(|v| (v.id(), v.name())).collect(),
states,
};
let children = document
.annotations
.iter()
.filter(|a| a.view_id() == view_id)
.flat_map(|a| context.elements(a))
.map(Node::Element)
.collect();
let attrs = vec![
("data-layer", "annotations".to_owned()),
("data-view-id", view_id.to_owned()),
];
Ok(Element::svg("g", attrs, children))
}
struct Context<'a> {
twin_opacity: &'static str,
/// Last duplicate wins, as a JavaScript `Map` built from the list.
categories: HashMap<&'a str, Option<&'a str>>,
view_names: HashMap<&'a str, &'a LocalizedText>,
states: &'a HashSet<&'a str>,
}
type Attrs = Vec<(&'static str, String)>;
impl Context<'_> {
fn elements(&self, annotation: &Annotation) -> Vec<Element> {
let (geometry, color) = match annotation {
Annotation::Observable(a) => (a.geometry.as_ref(), a.color.as_deref()),
Annotation::DetailTrigger(a) => (a.geometry.as_ref(), a.color.as_deref()),
};
let Some(geometry) = geometry else {
return Vec::new();
};
let color = color
.or_else(|| {
self.categories
.get(annotation.category_id())
.copied()
.flatten()
})
.unwrap_or(FALLBACK_COLOR)
.to_owned();
let data = self.data_attrs(annotation);
let label = format!(
"{} / {}",
value_of(&data, "data-anno-name-fr"),
value_of(&data, "data-anno-name-en")
);
if annotation.trigger().is_some() {
return vec![shape(geometry, &color, trigger_visual(), &data, &label)];
}
match geometry {
Geometry::Circle(c) => self.point(c.cx, c.cy, c.r, &color, &data, &label),
_ => vec![shape(geometry, &color, zone_visual(), &data, &label)],
}
}
fn data_attrs(&self, annotation: &Annotation) -> Attrs {
let mut data: Attrs = vec![("data-anno-id", annotation.id().to_owned())];
match annotation {
Annotation::DetailTrigger(t) => {
let opened = self.view_names.get(t.opens_view_id.as_str()).copied();
data.push(("data-anno-kind", "detail_trigger".to_owned()));
data.push(("data-anno-lateral", laterality(t.laterality).to_owned()));
data.push(("data-anno-opens-view", t.opens_view_id.clone()));
let names = match &t.name {
Some(n) => (n.fr.as_str(), n.en.as_str()),
None => opened.map_or(("", ""), localized_names),
};
data.push(("data-anno-name-fr", names.0.to_owned()));
data.push(("data-anno-name-en", names.1.to_owned()));
}
Annotation::Observable(o) => {
let kind = match o.kind {
crate::domain::sheet::ObservableKind::Point => "point",
crate::domain::sheet::ObservableKind::Zone => "zone",
};
data.push(("data-anno-kind", kind.to_owned()));
data.push(("data-anno-lateral", laterality(o.laterality).to_owned()));
data.push(("data-anno-name-fr", o.name.fr.clone()));
data.push(("data-anno-name-en", o.name.en.clone()));
if let Some(zone) = o.finding_zone_id.as_deref().filter(|z| !z.is_empty()) {
data.push(("data-anno-zone", zone.to_owned()));
}
if let Some(region) = o.vertebral_region_code.as_deref().filter(|r| !r.is_empty()) {
data.push(("data-anno-region", region.to_owned()));
}
}
}
if self.states.contains(annotation.id()) {
data.push(("data-state", "current".to_owned()));
}
data
}
/// A transparent hitbox, then the visible twin on top.
fn point(
&self,
cx: f64,
cy: f64,
r: f64,
color: &str,
data: &Attrs,
label: &str,
) -> Vec<Element> {
let mut hitbox: Attrs = vec![
("cx", js_number(cx)),
("cy", js_number(cy)),
("r", js_number(r)),
("fill", "transparent".to_owned()),
("pointer-events", "all".to_owned()),
("style", "cursor:pointer".to_owned()),
];
hitbox.extend(data.iter().cloned());
let mut visible: Attrs = vec![
("cx", js_number(cx)),
("cy", js_number(cy)),
("r", js_number(2.0_f64.max(r - 12.0))),
("fill", color.to_owned()),
("fill-opacity", self.twin_opacity.to_owned()),
("stroke", "#000".to_owned()),
("stroke-width", "1.5".to_owned()),
("pointer-events", "none".to_owned()),
];
visible.extend(data.iter().cloned());
vec![
titled("circle", hitbox, label),
titled("circle", visible, label),
]
}
}
/// A trigger without a name of its own takes the opened view's name in each language
/// (owner decision 2026-10-15; until R3 both attributes carried the French name). A language
/// left empty falls back to the other one.
fn localized_names(name: &LocalizedText) -> (&str, &str) {
let fr = if name.fr.is_empty() {
&name.en
} else {
&name.fr
};
let en = if name.en.is_empty() {
&name.fr
} else {
&name.en
};
(fr, en)
}
fn value_of<'a>(attrs: &'a Attrs, name: &str) -> &'a str {
attrs
.iter()
.find(|(k, _)| *k == name)
.map_or("", |(_, v)| v.as_str())
}
fn laterality(value: Laterality) -> &'static str {
match value {
Laterality::Unpaired => "unpaired",
Laterality::Bilateral => "bilateral",
Laterality::Left => "left",
Laterality::Right => "right",
}
}
fn zone_visual() -> Attrs {
vec![
("fill-opacity", "0.3".to_owned()),
("stroke-width", "2".to_owned()),
("pointer-events", "all".to_owned()),
("style", "cursor:pointer".to_owned()),
]
}
fn trigger_visual() -> Attrs {
vec![
("fill-opacity", "0.06".to_owned()),
("stroke-width", "2".to_owned()),
("stroke-dasharray", "8,4".to_owned()),
("pointer-events", "all".to_owned()),
("style", "cursor:pointer".to_owned()),
("class", "detail-zone".to_owned()),
]
}
/// The tag and geometry attributes of a shape.
fn geometry_attrs(geometry: &Geometry) -> (&'static str, Attrs) {
match geometry {
Geometry::Circle(c) => (
"circle",
vec![
("cx", js_number(c.cx)),
("cy", js_number(c.cy)),
("r", js_number(c.r)),
],
),
Geometry::Polygon(p) => {
let points: Vec<String> = p
.points
.iter()
.map(|pt| format!("{},{}", js_number(pt.0), js_number(pt.1)))
.collect();
("polygon", vec![("points", points.join(" "))])
}
Geometry::Path(path) => ("path", vec![("d", path.d.clone())]),
}
}
/// `{ ...geometry, fill, stroke, ...visual, ...data }` with the title child.
fn shape(geometry: &Geometry, color: &str, visual: Attrs, data: &Attrs, label: &str) -> Element {
let (tag, mut attrs) = geometry_attrs(geometry);
attrs.push(("fill", color.to_owned()));
attrs.push(("stroke", color.to_owned()));
attrs.extend(visual);
attrs.extend(data.iter().cloned());
titled(tag, attrs, label)
}
fn titled(tag: &str, attrs: Attrs, label: &str) -> Element {
let title = Element::svg("title", Vec::new(), vec![Node::Text(label.to_owned())]);
Element::svg(tag, attrs, vec![Node::Element(title)])
}
/// `viewBoxOf(view)`: the view box as the four numbers, JavaScript printing.
pub fn view_box_of(view: &SheetView) -> Option<String> {
view.view_box().map(|b| {
format!(
"{} {} {} {}",
js_number(b.min_x),
js_number(b.min_y),
js_number(b.width),
js_number(b.height)
)
})
}
#[cfg(test)]
mod tests {
use super::*;
fn text(fr: &str, en: &str) -> LocalizedText {
LocalizedText {
fr: fr.to_owned(),
en: en.to_owned(),
}
}
#[test]
fn an_unnamed_trigger_takes_the_opened_view_name_in_each_language() {
assert_eq!(localized_names(&text("Tête", "Head")), ("Tête", "Head"));
}
#[test]
fn a_missing_language_falls_back_to_the_other() {
assert_eq!(localized_names(&text("Tête", "")), ("Tête", "Tête"));
assert_eq!(localized_names(&text("", "Head")), ("Head", "Head"));
}
}
+6
View File
@@ -0,0 +1,6 @@
//! The anatomy core (R3): SVG reading and sanitising, the annotation layer drawn from the
//! sheet document, and the composition of a view (canvas and highlight).
pub mod compose;
pub mod layer;
pub mod svg;
+20
View File
@@ -0,0 +1,20 @@
//! SVG text → bounded, sanitised tree → text (plan R3 C2–C4). One reader for every SVG the
//! product draws: the sheet drawings now, the branding and Step 13 uploads later.
pub mod number;
pub mod prescan;
pub mod refs;
pub mod sanitize;
pub mod serialize;
pub mod tree;
pub use sanitize::Sanitized;
pub use tree::{Element, Node, SvgRejection};
/// Bounds, parses, sanitises and checks the references of an SVG text.
pub fn read_svg(text: &str) -> Result<Sanitized, SvgRejection> {
let root = tree::parse_svg(text)?;
let sanitized = sanitize::sanitize(root)?;
refs::check_references(&sanitized.root)?;
Ok(sanitized)
}
+183
View File
@@ -0,0 +1,183 @@
//! The JavaScript number semantics the engine's `stdDeviation` clamp relies on
//! (`packages/pdf/src/svg/sanitize.ts`): `String.prototype.trim`, `split(/[\s,]+/)`,
//! `Number(string)` and `String(number)`. Written by hand because Rust's `f64::from_str`
//! accepts `inf`, `nan` and `infinity` where `Number` gives NaN, and refuses `0x10` where
//! `Number` gives 16.
use crate::json::js_number;
/// ECMAScript WhiteSpace and LineTerminator (what `trim` removes and `\s` matches).
pub fn is_js_space(c: char) -> bool {
matches!(
c,
'\t' | '\n' | '\u{0B}' | '\u{0C}' | '\r' | ' ' | '\u{A0}' | '\u{1680}' | '\u{2000}'
..='\u{200A}'
| '\u{2028}'
| '\u{2029}'
| '\u{202F}'
| '\u{205F}'
| '\u{3000}'
| '\u{FEFF}'
)
}
/// `value.trim().split(/[\s,]+/)`.
pub fn js_split_list(value: &str) -> Vec<&str> {
let trimmed = value.trim_matches(is_js_space);
let mut parts = Vec::new();
let mut rest = trimmed;
loop {
match rest.find(|c: char| is_js_space(c) || c == ',') {
None => {
parts.push(rest);
return parts;
}
Some(at) => {
parts.push(&rest[..at]);
rest = rest[at..].trim_start_matches(|c: char| is_js_space(c) || c == ',');
}
}
}
}
/// `Number(text)`: StringToNumber of ECMAScript.
pub fn js_number_of(text: &str) -> f64 {
let s = text.trim_matches(is_js_space);
if s.is_empty() {
return 0.0;
}
if let Some(value) = radix_literal(s) {
return value;
}
let (sign, unsigned) = match s.as_bytes()[0] {
b'+' => (1.0, &s[1..]),
b'-' => (-1.0, &s[1..]),
_ => (1.0, s),
};
if unsigned == "Infinity" {
return sign * f64::INFINITY;
}
if !is_decimal_literal(unsigned) {
return f64::NAN;
}
unsigned.parse::<f64>().map_or(f64::NAN, |v| sign * v)
}
/// `0x…`, `0o…`, `0b…` (no sign allowed, as in ECMAScript).
fn radix_literal(s: &str) -> Option<f64> {
let radix = match s.get(..2)? {
"0x" | "0X" => 16,
"0o" | "0O" => 8,
"0b" | "0B" => 2,
_ => return None,
};
let digits = &s[2..];
if digits.is_empty() {
return Some(f64::NAN);
}
let mut value = 0.0_f64;
for c in digits.chars() {
match c.to_digit(radix) {
Some(d) => value = value * f64::from(radix) + f64::from(d),
None => return Some(f64::NAN),
}
}
Some(value)
}
/// StrUnsignedDecimalLiteral without `Infinity`: digits [. digits] | . digits, then an
/// optional exponent.
fn is_decimal_literal(s: &str) -> bool {
let b = s.as_bytes();
let mut i = 0;
let digits = |i: &mut usize| {
let start = *i;
while b.get(*i).is_some_and(u8::is_ascii_digit) {
*i += 1;
}
*i - start
};
let integer = digits(&mut i);
let mut fraction = 0;
if b.get(i) == Some(&b'.') {
i += 1;
fraction = digits(&mut i);
}
if integer + fraction == 0 {
return false;
}
if matches!(b.get(i), Some(b'e' | b'E')) {
i += 1;
if matches!(b.get(i), Some(b'+' | b'-')) {
i += 1;
}
if digits(&mut i) == 0 {
return false;
}
}
i == b.len()
}
/// `String(number)`, non-finite values included.
pub fn js_to_string(value: f64) -> String {
if value.is_nan() {
"NaN".to_owned()
} else if value.is_infinite() {
if value > 0.0 { "Infinity" } else { "-Infinity" }.to_owned()
} else {
js_number(value)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_numbers_as_javascript_does() {
let cases: [(&str, f64); 14] = [
("", 0.0),
(" ", 0.0),
("2.5", 2.5),
(" +5 ", 5.0),
(".5", 0.5),
("5.", 5.0),
("1e3", 1000.0),
("1e-7", 1e-7),
("0x10", 16.0),
("0b11", 3.0),
("Infinity", f64::INFINITY),
("-Infinity", f64::NEG_INFINITY),
("-0x10", f64::NAN),
("1_0", f64::NAN),
];
for (text, expected) in cases {
let got = js_number_of(text);
assert!(
got == expected || (got.is_nan() && expected.is_nan()),
"{text:?} → {got}"
);
}
for text in [
"inf", "nan", "infinity", "NaN", "e5", "1e", ".", "0x", "1.2.3",
] {
assert!(js_number_of(text).is_nan(), "{text:?}");
}
}
#[test]
fn splits_lists_as_the_engine_does() {
assert_eq!(js_split_list(" 200 , 1_0"), ["200", "1_0"]);
assert_eq!(js_split_list("+5,1e3"), ["+5", "1e3"]);
assert_eq!(js_split_list(""), [""]);
assert_eq!(js_split_list(",5"), ["", "5"]);
assert_eq!(js_split_list("5,"), ["5", ""]);
}
#[test]
fn prints_non_finite_values_as_javascript_does() {
assert_eq!(js_to_string(f64::NEG_INFINITY), "-Infinity");
assert_eq!(js_to_string(1e-7), "1e-7");
assert_eq!(js_to_string(100.0), "100");
}
}
+386
View File
@@ -0,0 +1,386 @@
//! Bounds an SVG text before any XML parser sees it (plan R3 C2). roxmltree 0.21 builds its
//! tree recursively, one level per element, enough to overflow the 1 MiB wasm stack between
//! 1,000 and 3,000 nesting levels (measured 2026-10-14); it also pre-allocates on the raw
//! counts of `<` and `=`, checks duplicate attributes quadratically and copies inherited
//! namespaces per declaring element. So the depth, the element, attribute and namespace
//! counts are taken here by a markup scanner: comments, CDATA sections, processing
//! instructions and quoted attribute values are skipped as the XML grammar defines them,
//! never by pattern matching. The scan is an upper bound of what a parser would build;
//! anything it cannot close is malformed.
/// The resource limits of one SVG text.
#[derive(Debug, Clone, Copy)]
pub struct SvgCaps {
/// UTF-8 bytes of the whole text.
pub max_bytes: usize,
/// Elements, the root included.
pub max_elements: usize,
/// Nesting depth, the root at depth 1.
pub max_depth: usize,
/// Attributes of one element (roxmltree's duplicate check is quadratic in it).
pub max_attributes_per_element: usize,
pub max_attributes: usize,
/// `xmlns` and `xmlns:*` declarations.
pub max_namespace_declarations: usize,
/// Raw `<` and `=` bytes, comments and text included.
pub max_open_brackets: usize,
pub max_equals: usize,
}
/// The engine's caps (`packages/pdf/src/svg/sanitize.ts` SANITIZER_CAPS) plus the bounds R3
/// adds before parsing.
pub const SVG_CAPS: SvgCaps = SvgCaps {
max_bytes: 2 * 1024 * 1024,
max_elements: 20_000,
max_depth: 64,
max_attributes_per_element: 256,
max_attributes: 100_000,
max_namespace_declarations: 16,
max_open_brackets: 100_000,
max_equals: 200_000,
};
/// Why a text is refused before parsing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrescanError {
TooLarge,
/// A `<!DOCTYPE` or `<!ENTITY` anywhere, comments included (the engine's rule).
Doctype,
TooDeep,
TooManyElements,
/// Attribute, namespace or raw markup counts over their caps.
TooComplex,
Malformed,
}
/// What the scan counted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Prescan {
pub elements: usize,
pub depth: usize,
}
/// Checks the caps of `text`; on success the text may be handed to the parser.
pub fn prescan(text: &str, caps: &SvgCaps) -> Result<Prescan, PrescanError> {
if text.len() > caps.max_bytes {
return Err(PrescanError::TooLarge);
}
// xmldom refuses a byte order mark; roxmltree would skip it.
if text.starts_with('\u{feff}') {
return Err(PrescanError::Malformed);
}
let bytes = text.as_bytes();
if declares_doctype(bytes) {
return Err(PrescanError::Doctype);
}
let count = |b: u8| bytes.iter().filter(|&&x| x == b).count();
if count(b'<') > caps.max_open_brackets || count(b'=') > caps.max_equals {
return Err(PrescanError::TooComplex);
}
let mut scan = Scan::new(bytes);
while let Some(open) = find(bytes, b"<", scan.at) {
scan.at = open;
scan.markup(caps)?;
}
if scan.depth != 0 {
return Err(PrescanError::Malformed);
}
Ok(scan.counted)
}
struct Scan<'a> {
bytes: &'a [u8],
at: usize,
depth: usize,
attributes: usize,
declarations: usize,
counted: Prescan,
}
/// What one start tag holds.
struct Tag {
self_closing: bool,
attributes: usize,
declarations: usize,
}
impl<'a> Scan<'a> {
fn new(bytes: &'a [u8]) -> Self {
Self {
bytes,
at: 0,
depth: 0,
attributes: 0,
declarations: 0,
counted: Prescan {
elements: 0,
depth: 0,
},
}
}
/// Consumes the markup starting at `self.at` (a `<`).
fn markup(&mut self, caps: &SvgCaps) -> Result<(), PrescanError> {
let rest = &self.bytes[self.at..];
// Each closer is searched after its whole opener, as the XML grammar reads it:
// `<!-->` does not close the comment it opens (security audit R3, MEDIUM).
if rest.starts_with(b"<!--") {
return self.skip_past(4, b"-->");
}
if rest.starts_with(b"<![CDATA[") {
return self.skip_past(9, b"]]>");
}
if rest.starts_with(b"<?") {
return self.skip_past(2, b"?>");
}
if rest.starts_with(b"<!") {
return Err(PrescanError::Malformed);
}
if rest.starts_with(b"</") {
self.skip_past(2, b">")?;
self.depth = self.depth.checked_sub(1).ok_or(PrescanError::Malformed)?;
return Ok(());
}
let tag = self.skip_tag()?;
self.count_attributes(&tag, caps)?;
self.open_element(tag.self_closing, caps)
}
fn count_attributes(&mut self, tag: &Tag, caps: &SvgCaps) -> Result<(), PrescanError> {
self.attributes += tag.attributes;
self.declarations += tag.declarations;
if tag.attributes > caps.max_attributes_per_element
|| self.attributes > caps.max_attributes
|| self.declarations > caps.max_namespace_declarations
{
return Err(PrescanError::TooComplex);
}
Ok(())
}
fn open_element(&mut self, self_closing: bool, caps: &SvgCaps) -> Result<(), PrescanError> {
self.counted.elements += 1;
if self.counted.elements > caps.max_elements {
return Err(PrescanError::TooManyElements);
}
let depth = self.depth + 1;
if depth > caps.max_depth {
return Err(PrescanError::TooDeep);
}
self.counted.depth = self.counted.depth.max(depth);
if !self_closing {
self.depth = depth;
}
Ok(())
}
/// Moves past `end`, searched from `opener` bytes after the markup's `<`.
fn skip_past(&mut self, opener: usize, end: &[u8]) -> Result<(), PrescanError> {
let found = find(self.bytes, end, self.at + opener).ok_or(PrescanError::Malformed)?;
self.at = found + end.len();
Ok(())
}
/// Skips a start tag, quoted values included, counting its attributes (an `=` outside
/// quotes) and its namespace declarations (an attribute name starting with `xmlns`).
fn skip_tag(&mut self) -> Result<Tag, PrescanError> {
let mut tag = Tag {
self_closing: false,
attributes: 0,
declarations: 0,
};
let mut quote: Option<u8> = None;
let mut i = self.at + 1;
while let Some(&b) = self.bytes.get(i) {
match (quote, b) {
(Some(q), _) if b == q => quote = None,
(Some(_), _) => {}
(None, b'"' | b'\'') => quote = Some(b),
(None, b'<') => return Err(PrescanError::Malformed),
(None, b'=') => tag.attributes += 1,
(None, b'>') => {
self.at = i + 1;
tag.self_closing = self.bytes[i - 1] == b'/';
return Ok(tag);
}
(None, _) if declaration_at(self.bytes, i) => tag.declarations += 1,
(None, _) => {}
}
i += 1;
}
Err(PrescanError::Malformed)
}
}
/// An attribute name starting with `xmlns` begins at `i` (right after whitespace).
fn declaration_at(bytes: &[u8], i: usize) -> bool {
bytes[i - 1].is_ascii_whitespace() && bytes[i..].starts_with(b"xmlns")
}
fn find(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> {
haystack
.get(from..)?
.windows(needle.len())
.position(|w| w == needle)
.map(|p| p + from)
}
/// `/<!(DOCTYPE|ENTITY)/i` on the raw text, as the engine refuses it.
fn declares_doctype(bytes: &[u8]) -> bool {
let mut from = 0;
while let Some(at) = find(bytes, b"<!", from) {
let word = bytes.get(at + 2..).unwrap_or_default();
let starts = |w: &[u8]| word.len() >= w.len() && word[..w.len()].eq_ignore_ascii_case(w);
if starts(b"DOCTYPE") || starts(b"ENTITY") {
return true;
}
from = at + 2;
}
false
}
#[cfg(test)]
mod tests {
use super::*;
const SVG: &str = "<svg xmlns=\"http://www.w3.org/2000/svg\">";
fn nested(depth: usize) -> String {
format!(
"{SVG}{}{}</svg>",
"<g>".repeat(depth - 1),
"</g>".repeat(depth - 1)
)
}
#[test]
fn counts_depth_and_elements_with_the_root_at_depth_one() {
let text = format!("{SVG}<g><path d=\"M0 0\"/></g><path/></svg>");
assert_eq!(
prescan(&text, &SVG_CAPS),
Ok(Prescan {
elements: 4,
depth: 3
})
);
}
#[test]
fn refuses_depth_and_element_counts_over_the_caps() {
assert!(prescan(&nested(64), &SVG_CAPS).is_ok());
assert_eq!(prescan(&nested(65), &SVG_CAPS), Err(PrescanError::TooDeep));
let many = |n: usize| format!("{SVG}{}</svg>", "<path/>".repeat(n - 1));
assert!(prescan(&many(20_000), &SVG_CAPS).is_ok());
assert_eq!(
prescan(&many(20_001), &SVG_CAPS),
Err(PrescanError::TooManyElements)
);
}
#[test]
fn stops_a_deep_text_at_the_cap_without_recursion() {
// 99,000 levels (under the `<` cap): the parser would overflow the wasm stack; the scan stops at 65.
let text = format!("{SVG}{}", "<g>".repeat(99_000));
assert_eq!(prescan(&text, &SVG_CAPS), Err(PrescanError::TooDeep));
}
#[test]
fn refuses_a_text_over_the_byte_cap_before_reading_it() {
let pad = "x".repeat(SVG_CAPS.max_bytes);
assert_eq!(
prescan(&pad, &SVG_CAPS),
Ok(Prescan {
elements: 0,
depth: 0
})
);
let over = format!("{pad}x");
assert_eq!(prescan(&over, &SVG_CAPS), Err(PrescanError::TooLarge));
}
#[test]
fn skips_markup_that_is_not_an_element() {
let text = format!(
"<?xml version=\"1.0\"?>{SVG}<!-- <g><g> --><![CDATA[<g>]]><?pi <g>?><g a='>' b=\"<\"/></svg>"
);
// A quoted `<` is malformed XML: the scan skips it (still an upper bound), the parser refuses it.
assert_eq!(
prescan(&text, &SVG_CAPS),
Ok(Prescan {
elements: 2,
depth: 2
})
);
}
#[test]
fn refuses_attribute_namespace_and_markup_floods() {
let attrs = |n: usize| (0..n).map(|i| format!(" a{i}=\"{i}\"")).collect::<String>();
let one = |n: usize| format!("{SVG}<path{}/></svg>", attrs(n));
assert!(prescan(&one(256), &SVG_CAPS).is_ok());
assert_eq!(prescan(&one(257), &SVG_CAPS), Err(PrescanError::TooComplex));
let declarations = (0..16)
.map(|i| format!(" xmlns:n{i}=\"u{i}\""))
.collect::<String>();
let ns = format!("<svg xmlns=\"http://www.w3.org/2000/svg\"{declarations}/>");
assert_eq!(prescan(&ns, &SVG_CAPS), Err(PrescanError::TooComplex));
let brackets = format!("{SVG}<!--{}--></svg>", "<".repeat(100_001));
assert_eq!(prescan(&brackets, &SVG_CAPS), Err(PrescanError::TooComplex));
let bom = format!("\u{feff}{SVG}</svg>");
assert_eq!(prescan(&bom, &SVG_CAPS), Err(PrescanError::Malformed));
}
#[test]
fn a_closer_overlapping_its_opener_does_not_close_it() {
// `<!-->` keeps the comment open until the next `-->`: what follows is still counted.
let deep = format!(
"{SVG}<!--></svg><![CDATA[-->{}{}</svg><!--]]>-->",
"<g>".repeat(100),
"</g>".repeat(100)
);
assert_eq!(prescan(&deep, &SVG_CAPS), Err(PrescanError::TooDeep));
assert_eq!(
prescan(&format!("{SVG}<!-->"), &SVG_CAPS),
Err(PrescanError::Malformed)
);
assert_eq!(
prescan(&format!("{SVG}<?></svg>"), &SVG_CAPS),
Err(PrescanError::Malformed)
);
assert_eq!(
prescan(&format!("{SVG}<![CDATA[]]></svg>"), &SVG_CAPS),
Ok(Prescan {
elements: 1,
depth: 1
})
);
}
#[test]
fn refuses_doctype_and_entity_anywhere_and_unclosed_markup() {
for text in [
"<!DOCTYPE svg><svg/>",
"<svg><!-- <!doctype x --></svg>",
"<svg><!ENTITY a 'b'></svg>",
] {
assert_eq!(
prescan(text, &SVG_CAPS),
Err(PrescanError::Doctype),
"{text}"
);
}
for text in [
"<svg><!-- x </svg>",
"<svg a=\"x></svg>",
"<svg><g></svg>",
"</g>",
"<svg><![CDATA[ </svg>",
] {
assert_eq!(
prescan(text, &SVG_CAPS),
Err(PrescanError::Malformed),
"{text}"
);
}
}
}
+211
View File
@@ -0,0 +1,211 @@
//! Internal references of a sanitised tree (owner brief R3 §5: internal references and the
//! complexity of `<use>`). The sanitiser already keeps only `#id` targets; here every
//! `href` / `xlink:href` and every `url(#id)` becomes an edge to the first element holding
//! that id (document order, as browsers resolve it). A cycle through tree and reference edges
//! is refused, and so is a document whose expanded size passes the budget: each reference
//! adds the expanded size of its target, so 256 `<use>` of a large group, nested uses or a
//! clip path instantiated many times are all counted. The walk is iterative (reference
//! chains are not bounded by the depth cap) and saturating, with an early exit.
use std::collections::HashMap;
use super::sanitize::{local_reference_text, url_targets};
use super::tree::{Element, Node, SvgRejection};
/// Expanded elements a drawing may instantiate (the product's drawing: a few thousand).
pub const MAX_EXPANDED_ELEMENTS: u64 = 50_000;
struct Flat {
edges: Vec<usize>,
}
/// Checks the reference graph of `root`; answers the expanded element count.
pub fn check_references(root: &Element) -> Result<u64, SvgRejection> {
let (flat, refs) = flatten(root);
let ids = first_ids(root);
let mut graph: Vec<Flat> = flat;
for (node, targets) in refs {
for id in targets {
if let Some(&target) = ids.get(id.as_str()) {
graph[node].edges.push(target);
}
}
}
expanded_size(&graph)
}
/// Elements in document order with their child edges, and the reference ids of each.
fn flatten(root: &Element) -> (Vec<Flat>, Vec<(usize, Vec<String>)>) {
let mut flat = Vec::new();
let mut refs = Vec::new();
push_element(root, &mut flat, &mut refs);
(flat, refs)
}
fn push_element(
element: &Element,
flat: &mut Vec<Flat>,
refs: &mut Vec<(usize, Vec<String>)>,
) -> usize {
let index = flat.len();
flat.push(Flat { edges: Vec::new() });
let targets = reference_ids(element);
if !targets.is_empty() {
refs.push((index, targets));
}
for child in &element.children {
if let Node::Element(child) = child {
let child_index = push_element(child, flat, refs);
flat[index].edges.push(child_index);
}
}
index
}
/// First element of each id, in document order (the same order `flatten` numbers them).
fn first_ids(root: &Element) -> HashMap<&str, usize> {
let mut ids = HashMap::new();
let mut counter = 0;
collect_ids(root, &mut counter, &mut ids);
ids
}
fn collect_ids<'a>(element: &'a Element, counter: &mut usize, ids: &mut HashMap<&'a str, usize>) {
if let Some(id) = element.attr("id") {
ids.entry(id).or_insert(*counter);
}
*counter += 1;
for child in element.element_children() {
collect_ids(child, counter, ids);
}
}
/// Ids named by `href`, `xlink:href` (`#id`) and every `url(#id)` of the element.
fn reference_ids(element: &Element) -> Vec<String> {
let mut ids = Vec::new();
for attr in &element.attrs {
if attr.qname == "href" || attr.qname == "xlink:href" {
if let Some(id) = local_reference_text(&attr.value).strip_prefix('#') {
ids.push(id.to_owned());
}
continue;
}
ids.extend(url_targets(&attr.value));
}
ids
}
/// Post-order walk with an explicit stack: grey = on the current path (a cycle when met
/// again), black = size known.
fn expanded_size(graph: &[Flat]) -> Result<u64, SvgRejection> {
#[derive(Clone, Copy, PartialEq)]
enum Mark {
White,
Grey,
Black,
}
if graph.is_empty() {
return Ok(0);
}
let mut mark = vec![Mark::White; graph.len()];
let mut size = vec![0_u64; graph.len()];
let mut stack: Vec<(usize, usize)> = vec![(0, 0)];
mark[0] = Mark::Grey;
while let Some(&mut (node, ref mut next)) = stack.last_mut() {
if let Some(&target) = graph[node].edges.get(*next) {
*next += 1;
match mark[target] {
Mark::Grey => return Err(SvgRejection::ReferenceCycle),
Mark::White => {
mark[target] = Mark::Grey;
stack.push((target, 0));
}
Mark::Black => {}
}
continue;
}
let total = graph[node]
.edges
.iter()
.fold(1_u64, |sum, &t| sum.saturating_add(size[t]));
if total > MAX_EXPANDED_ELEMENTS {
return Err(SvgRejection::TooComplex);
}
size[node] = total;
mark[node] = Mark::Black;
stack.pop();
}
Ok(size[0])
}
#[cfg(test)]
mod tests {
use super::*;
use crate::anatomy::svg::tree::parse_svg;
fn check(body: &str) -> Result<u64, SvgRejection> {
let text = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">{body}</svg>"
);
let root = parse_svg(&text).unwrap_or_else(|e| panic!("{e:?}"));
check_references(&root)
}
#[test]
fn counts_each_reference_as_its_target_expanded() {
// root + path + 3 uses each expanding the path (1): 1 + 1 + 3 × 2
assert_eq!(
check("<path id=\"p\"/><use href=\"#p\"/><use href=\"#p\"/><use xlink:href=\"#p\"/>"),
Ok(8)
);
// a dangling reference adds nothing; a colour is not a reference
assert_eq!(check("<path fill=\"url(#none)\"/>"), Ok(2));
assert_eq!(
check("<g id=\"ff9500\"><path fill=\"#ff9500\"/></g>"),
Ok(3)
);
}
#[test]
fn refuses_cycles_through_use_paint_and_clip_paths() {
assert_eq!(
check("<g id=\"a\"><use href=\"#a\"/></g>"),
Err(SvgRejection::ReferenceCycle)
);
assert_eq!(
check("<g id=\"a\"><use href=\"#b\"/></g><g id=\"b\"><use href=\"#a\"/></g>"),
Err(SvgRejection::ReferenceCycle)
);
assert_eq!(
check(
"<clipPath id=\"c\"><use href=\"#g\"/></clipPath><g id=\"g\"><path clip-path=\"url(#c)\"/></g>"
),
Err(SvgRejection::ReferenceCycle)
);
assert_eq!(
check(
"<linearGradient id=\"a\" xlink:href=\"#b\"/><linearGradient id=\"b\" xlink:href=\"#a\"/>"
),
Err(SvgRejection::ReferenceCycle)
);
}
#[test]
fn refuses_an_expansion_over_the_budget_without_overflow() {
// 8 levels × 30 uses: 30^8 instances; refused early, no overflow.
let mut body = String::from("<path id=\"l0\"/>");
for level in 1..=8 {
body.push_str(&format!(
"<g id=\"l{level}\">{}</g>",
format!("<use href=\"#l{}\"/>", level - 1).repeat(30)
));
}
assert_eq!(check(&body), Err(SvgRejection::TooComplex));
// 200 uses of a 300-element group: 60,000 > 50,000
let group = format!("<g id=\"big\">{}</g>", "<path/>".repeat(299));
assert_eq!(
check(&format!("{group}{}", "<use href=\"#big\"/>".repeat(200))),
Err(SvgRejection::TooComplex)
);
}
}
+419
View File
@@ -0,0 +1,419 @@
//! The allowlist sanitiser (STEP6 §15, `packages/pdf/src/svg/sanitize.ts`), one for every
//! SVG the product draws. The engine's lists and value rules, matched on qualified names
//! like the engine; plus the declared R3 rules (plan C3): elements in the SVG namespace only,
//! no `class`/`style` on the root (inline SVG lives under the page's CSS), `id` values in the
//! reference grammar, no text outside `title`/`desc`. A refused element goes with its
//! subtree, a refused attribute alone; both are named in `removed` (names, never values).
use super::number::{js_number_of, js_split_list, js_to_string};
use super::tree::{Element, Node, SvgRejection, XLINK_NS};
const ALLOWED_ELEMENTS: [&str; 28] = [
"svg",
"g",
"path",
"circle",
"ellipse",
"rect",
"line",
"polyline",
"polygon",
"defs",
"linearGradient",
"radialGradient",
"stop",
"filter",
"feGaussianBlur",
"feMerge",
"feMergeNode",
"feOffset",
"feFlood",
"feComposite",
"feBlend",
"feColorMatrix",
"clipPath",
"mask",
"title",
"desc",
"switch",
"use",
];
const ALLOWED_ATTRIBUTES: [&str; 74] = [
"id",
"class",
"d",
"cx",
"cy",
"r",
"rx",
"ry",
"x",
"y",
"x1",
"y1",
"x2",
"y2",
"dx",
"dy",
"width",
"height",
"points",
"transform",
"viewBox",
"version",
"preserveAspectRatio",
"fill",
"fill-opacity",
"fill-rule",
"stroke",
"stroke-width",
"stroke-linecap",
"stroke-linejoin",
"stroke-opacity",
"stroke-dasharray",
"stroke-dashoffset",
"stroke-miterlimit",
"opacity",
"filter",
"clip-path",
"clip-rule",
"mask",
"display",
"visibility",
"color",
"gradientUnits",
"gradientTransform",
"spreadMethod",
"offset",
"stop-color",
"stop-opacity",
"stdDeviation",
"in",
"in2",
"result",
"mode",
"operator",
"k1",
"k2",
"k3",
"k4",
"flood-color",
"flood-opacity",
"type",
"values",
"color-interpolation-filters",
"filterUnits",
"primitiveUnits",
"systemLanguage",
"font-family",
"font-size",
"font-weight",
"xmlns",
"xmlns:xlink",
"xlink:href",
"href",
"style",
];
/// CSS-like values: a function call there is a reference or an exploit.
const PRESENTATION_ATTRIBUTES: [&str; 27] = [
"fill",
"fill-opacity",
"fill-rule",
"stroke",
"stroke-width",
"stroke-linecap",
"stroke-linejoin",
"stroke-opacity",
"stroke-dasharray",
"stroke-dashoffset",
"stroke-miterlimit",
"opacity",
"filter",
"clip-path",
"clip-rule",
"mask",
"display",
"visibility",
"color",
"stop-color",
"stop-opacity",
"flood-color",
"flood-opacity",
"color-interpolation-filters",
"font-family",
"font-size",
"font-weight",
];
/// The engine's cap on `<use>` elements and on each `stdDeviation` number.
pub const MAX_USES: usize = 256;
pub const MAX_STD_DEVIATION: f64 = 100.0;
/// A `title` or `desc` text is a tooltip: longer is refused whole (never cut), so a text
/// node cannot inflate the composed view (`>` is written `&gt;`).
pub const MAX_TEXT_BYTES: usize = 4 * 1024;
const STYLE_FORBIDDEN: [&str; 5] = [
"expression(",
"image-set(",
"@import",
"javascript:",
"behavior:",
];
/// A sanitised tree and what was taken out of it.
#[derive(Debug, Clone, PartialEq)]
pub struct Sanitized {
pub root: Element,
/// `tag` and `tag@attribute` in document order (empty on the product's SVGs).
pub removed: Vec<String>,
}
/// Sanitises a parsed root (the caller parsed it with `tree::parse_svg`).
pub fn sanitize(mut root: Element) -> Result<Sanitized, SvgRejection> {
let mut walk = Walk {
removed: Vec::new(),
uses: 0,
};
// The inline root lives under the page: no page classes or styles, nothing that paints
// outside its box (security audit R3, LOW).
for name in ["class", "style", "transform", "filter", "mask", "clip-path"] {
if root.attr(name).is_some() {
root.remove_attr(name);
walk.removed.push(format!("svg@{name}"));
}
}
walk.visit(&mut root)?;
Ok(Sanitized {
root,
removed: walk.removed,
})
}
struct Walk {
removed: Vec<String>,
uses: usize,
}
impl Walk {
fn visit(&mut self, element: &mut Element) -> Result<(), SvgRejection> {
if element.qname == "use" {
self.uses += 1;
if self.uses > MAX_USES {
return Err(SvgRejection::TooManyUses);
}
}
self.sanitize_attributes(element);
let keeps_text = matches!(element.qname.as_str(), "title" | "desc");
let children = std::mem::take(&mut element.children);
for child in children {
match child {
Node::Element(mut child) if element_allowed(&child) => {
self.visit(&mut child)?;
element.children.push(Node::Element(child));
}
Node::Element(child) => self.removed.push(child.qname),
Node::Text(text) if is_xml_space(&text) => element.children.push(Node::Text(text)),
Node::Text(text) if keeps_text => {
if text.len() > MAX_TEXT_BYTES {
return Err(SvgRejection::TooComplex);
}
element.children.push(Node::Text(text));
}
Node::Text(_) => {}
}
}
Ok(())
}
fn sanitize_attributes(&mut self, element: &mut Element) {
let tag = element.qname.clone();
element.attrs.retain(|a| {
let keep = ALLOWED_ATTRIBUTES.contains(&a.qname.as_str())
&& namespace_fits(&a.qname, a.namespace.as_deref())
&& value_acceptable(&a.qname, &a.value);
if !keep {
self.removed.push(format!("{tag}@{}", a.qname));
}
keep
});
clamp_std_deviation(element);
}
}
fn element_allowed(element: &Element) -> bool {
ALLOWED_ELEMENTS.contains(&element.qname.as_str()) && element.is_svg_namespace()
}
/// `xlink:href` must be in the xlink namespace; every other kept name is unprefixed.
fn namespace_fits(qname: &str, namespace: Option<&str>) -> bool {
match qname {
"xlink:href" => namespace == Some(XLINK_NS),
"xmlns" | "xmlns:xlink" => true,
_ => namespace.is_none(),
}
}
fn is_xml_space(text: &str) -> bool {
text.chars().all(|c| matches!(c, ' ' | '\t' | '\n' | '\r'))
}
/// The engine's value rules, in its order, then the R3 id grammar.
fn value_acceptable(qname: &str, value: &str) -> bool {
if value.contains('\\') || !urls_are_local(value) {
return false;
}
match qname {
"href" | "xlink:href" => is_local_reference(local_reference_text(value)),
"id" => is_reference_name(value),
"style" => !style_forbidden(value) && calls_only_local_url(value),
_ if PRESENTATION_ATTRIBUTES.contains(&qname) => calls_only_local_url(value),
_ => true,
}
}
/// CSS whitespace (what the tokenizer skips inside `url(`).
fn is_css_space(c: char) -> bool {
matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0C')
}
/// An `href` as the URL parser reads it: only ASCII whitespace is stripped (the engine
/// trimmed JavaScript spaces, so a no-break space before `#a` passed as local and resolved
/// as a relative URL).
pub fn local_reference_text(value: &str) -> &str {
value.trim_matches(|c: char| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0C'))
}
/// `^#[A-Za-z_][\w.:-]*$`.
fn is_local_reference(value: &str) -> bool {
value.strip_prefix('#').is_some_and(is_reference_name)
}
/// `[A-Za-z_][\w.:-]*`, the whole value.
pub fn is_reference_name(value: &str) -> bool {
let mut chars = value.chars();
chars
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | ':' | '-'))
}
/// Byte offsets right after each case-insensitive `url(`.
fn url_openings(value: &str) -> impl Iterator<Item = usize> + '_ {
let lower = value.to_ascii_lowercase();
let mut from = 0;
std::iter::from_fn(move || {
let at = lower.get(from..)?.find("url(")? + from;
from = at + 4;
Some(from)
})
}
/// After `url(`: whitespace, an optional quote, whitespace; returns the offset of the next
/// character. Only CSS whitespace is skipped, as the browser's CSS tokenizer skips it: the
/// engine skipped JavaScript spaces, so a no-break space before `#a` read as local but the
/// browser resolves it as a relative URL (security audit R3, pass 2).
fn skip_url_prefix(value: &str, at: usize) -> usize {
let rest = &value[at..];
let mut chars = rest.char_indices().peekable();
let skip_space = |chars: &mut std::iter::Peekable<std::str::CharIndices<'_>>| {
while chars.peek().is_some_and(|&(_, c)| is_css_space(c)) {
chars.next();
}
};
skip_space(&mut chars);
if chars.peek().is_some_and(|&(_, c)| c == '\'' || c == '"') {
chars.next();
}
skip_space(&mut chars);
at + chars.peek().map_or(rest.len(), |&(i, _)| i)
}
/// The ids of the value's `url(#id)` references, in order.
pub fn url_targets(value: &str) -> Vec<String> {
url_openings(value)
.filter_map(|at| value[skip_url_prefix(value, at)..].strip_prefix('#'))
.map(|rest| {
rest.chars()
.take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | ':' | '-'))
.collect::<String>()
})
.filter(|id| !id.is_empty())
.collect()
}
/// Every `url(` in the value points inside the document (`url(#…)`).
fn urls_are_local(value: &str) -> bool {
url_openings(value).all(|at| value[skip_url_prefix(value, at)..].starts_with('#'))
}
/// No `(` once the `url(#` openings are taken out.
fn calls_only_local_url(value: &str) -> bool {
let mut cut = String::with_capacity(value.len());
let mut kept_from = 0;
for at in url_openings(value) {
let next = skip_url_prefix(value, at);
if value[next..].starts_with('#') {
cut.push_str(&value[kept_from..at - 4]);
kept_from = next + 1;
}
}
cut.push_str(&value[kept_from..]);
!cut.contains('(')
}
fn style_forbidden(value: &str) -> bool {
let lower = value.to_ascii_lowercase();
STYLE_FORBIDDEN.iter().any(|f| lower.contains(f))
}
/// Clamps every number of a `stdDeviation` list to 100; a list with a NaN loses the
/// attribute; the value is rewritten only when a number was clamped.
fn clamp_std_deviation(element: &mut Element) {
let Some(raw) = element.attr("stdDeviation") else {
return;
};
let numbers: Vec<f64> = js_split_list(raw).into_iter().map(js_number_of).collect();
if numbers.iter().any(|n| n.is_nan()) {
element.remove_attr("stdDeviation");
return;
}
if numbers.iter().all(|&n| n <= MAX_STD_DEVIATION) {
return;
}
let clamped: Vec<String> = numbers
.iter()
.map(|&n| js_to_string(n.min(MAX_STD_DEVIATION)))
.collect();
element.set_attr("stdDeviation", clamped.join(" "));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn url_rules_match_the_engine() {
assert!(
urls_are_local("url(#a)") && urls_are_local("URL( '#a')") && urls_are_local("none")
);
assert!(!urls_are_local("url(http://e)") && !urls_are_local("url("));
// JavaScript's `\s` takes the newline, then `#` follows: local.
assert!(urls_are_local("url(\n#a)"));
assert!(calls_only_local_url("url(#a) url( \"#b\")"));
assert!(!calls_only_local_url("rgb(1,2,3)") && !calls_only_local_url("url(#a) blur(2)"));
}
#[test]
fn reference_grammar() {
assert!(
is_local_reference("#lg_1.a:b-c")
&& !is_local_reference("#1a")
&& !is_local_reference("x")
);
assert!(
is_reference_name("osteo-halo") && !is_reference_name("") && !is_reference_name("a b")
);
}
}
+98
View File
@@ -0,0 +1,98 @@
//! Tree → SVG text (plan R3 C4). XML 1.0 without a declaration; the root carries the SVG
//! namespace declaration (added when the source had none, as xmldom does); every other
//! declaration stays where the source made it. Escapes keep a re-parse identical: in
//! attribute values `& < > "` and the whitespace a parser would normalise (`\t \n \r` as
//! character references), in text `& < >` and `\r`. Empty elements are self-closed.
use super::tree::{Element, Node, SVG_NS};
/// The text of `root` and its subtree.
pub fn serialize(root: &Element) -> String {
let mut out = String::with_capacity(4096);
let declares = root.attrs.iter().any(|a| a.qname == "xmlns");
write_element(&mut out, root, !declares);
out
}
fn write_element(out: &mut String, element: &Element, add_namespace: bool) {
out.push('<');
out.push_str(&element.qname);
if add_namespace {
out.push_str(" xmlns=\"");
out.push_str(SVG_NS);
out.push('"');
}
for attr in &element.attrs {
out.push(' ');
out.push_str(&attr.qname);
out.push_str("=\"");
escape_into(out, &attr.value, true);
out.push('"');
}
if element.children.is_empty() {
out.push_str("/>");
return;
}
out.push('>');
for child in &element.children {
match child {
Node::Element(e) => write_element(out, e, false),
Node::Text(t) => escape_into(out, t, false),
}
}
out.push_str("</");
out.push_str(&element.qname);
out.push('>');
}
fn escape_into(out: &mut String, text: &str, attribute: bool) {
for c in text.chars() {
match c {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'\r' => out.push_str("&#13;"),
'"' if attribute => out.push_str("&quot;"),
'\t' if attribute => out.push_str("&#9;"),
'\n' if attribute => out.push_str("&#10;"),
_ => out.push(c),
}
}
}
/// Whether XML 1.0 can carry `text` at all (Char production): layer inputs come from the
/// document, which allows any string.
pub fn is_xml_text(text: &str) -> bool {
text.chars().all(|c| {
matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..)
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::anatomy::svg::tree::parse_svg;
#[test]
fn a_reparse_gives_the_same_tree() {
let text = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"><title>a &amp; b &lt; c\r\nd</title>\n <path d=\"M0 0\" id=\"x&#9;y&#10;z&#13;\" fill=\"&quot;&gt;\"/><linearGradient xlink:href=\"#x\"/></svg>";
let first = parse_svg(text).unwrap_or_else(|e| panic!("{e:?}"));
let again = parse_svg(&serialize(&first)).unwrap_or_else(|e| panic!("{e:?}"));
assert_eq!(first, again);
}
#[test]
fn declares_the_svg_namespace_when_the_source_did_not() {
let root = parse_svg("<svg><path/></svg>").unwrap_or_else(|e| panic!("{e:?}"));
assert_eq!(
serialize(&root),
"<svg xmlns=\"http://www.w3.org/2000/svg\"><path/></svg>"
);
}
#[test]
fn tells_text_xml_cannot_carry() {
assert!(is_xml_text("Hanche « gauche » 😀\t\n"));
assert!(!is_xml_text("a\u{1}b") && !is_xml_text("\u{FFFE}") && !is_xml_text("\u{B}"));
}
}
+259
View File
@@ -0,0 +1,259 @@
//! The SVG tree the core owns (roxmltree's borrows its input text): elements with their
//! qualified name as written, the resolved namespace, attributes in source order (namespace
//! declarations first, as attributes named `xmlns` / `xmlns:p`), and text. Depth is capped
//! at 64 by the prescan before any tree exists, so recursion over it is bounded.
use super::prescan::{PrescanError, SVG_CAPS, prescan};
pub const SVG_NS: &str = "http://www.w3.org/2000/svg";
pub const XLINK_NS: &str = "http://www.w3.org/1999/xlink";
pub const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";
/// A node kept in the tree. Comments and processing instructions are not read (R3 C3).
#[derive(Debug, Clone, PartialEq)]
pub enum Node {
Element(Element),
Text(String),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Element {
/// The name as written (`path`, `s:path`): the allowlist matches it, like the engine.
pub qname: String,
/// The resolved namespace; `None` when the document declares none (xmldom reads such an
/// element as SVG under `image/svg+xml`).
pub namespace: Option<String>,
pub attrs: Vec<Attribute>,
pub children: Vec<Node>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Attribute {
pub qname: String,
pub namespace: Option<String>,
pub value: String,
}
impl Element {
/// A new element in the SVG namespace (the layer and the halo filter).
pub fn svg(name: &str, attrs: Vec<(&str, String)>, children: Vec<Node>) -> Self {
Self {
qname: name.to_owned(),
namespace: Some(SVG_NS.to_owned()),
attrs: attrs
.into_iter()
.map(|(qname, value)| Attribute {
qname: qname.to_owned(),
namespace: None,
value,
})
.collect(),
children,
}
}
pub fn attr(&self, qname: &str) -> Option<&str> {
self.attrs
.iter()
.find(|a| a.qname == qname)
.map(|a| a.value.as_str())
}
/// Sets an attribute in place (keeps its position), or appends it.
pub fn set_attr(&mut self, qname: &str, value: String) {
match self.attrs.iter_mut().find(|a| a.qname == qname) {
Some(a) => a.value = value,
None => self.attrs.push(Attribute {
qname: qname.to_owned(),
namespace: None,
value,
}),
}
}
pub fn remove_attr(&mut self, qname: &str) {
self.attrs.retain(|a| a.qname != qname);
}
/// The local name (after the prefix, if any).
pub fn local_name(&self) -> &str {
self.qname.rsplit(':').next().unwrap_or(&self.qname)
}
pub fn is_svg_namespace(&self) -> bool {
self.namespace.as_deref().is_none_or(|ns| ns == SVG_NS)
}
pub fn element_children(&self) -> impl Iterator<Item = &Element> {
self.children.iter().filter_map(|n| match n {
Node::Element(e) => Some(e),
Node::Text(_) => None,
})
}
}
/// Why an SVG text is refused (closed codes, `reason()` is the wire form).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SvgRejection {
TooLarge,
Doctype,
Malformed,
NotSvg,
TooManyElements,
TooDeep,
TooManyUses,
TooComplex,
ReferenceCycle,
}
impl SvgRejection {
pub fn reason(self) -> &'static str {
match self {
Self::TooLarge => "too_large",
Self::Doctype => "doctype",
Self::Malformed => "malformed",
Self::NotSvg => "not_svg",
Self::TooManyElements => "too_many_elements",
Self::TooDeep => "too_deep",
Self::TooManyUses => "too_many_uses",
Self::TooComplex => "too_complex",
Self::ReferenceCycle => "reference_cycle",
}
}
}
impl From<PrescanError> for SvgRejection {
fn from(error: PrescanError) -> Self {
match error {
PrescanError::TooLarge => Self::TooLarge,
PrescanError::Doctype => Self::Doctype,
PrescanError::TooDeep => Self::TooDeep,
PrescanError::TooManyElements => Self::TooManyElements,
PrescanError::TooComplex => Self::TooComplex,
PrescanError::Malformed => Self::Malformed,
}
}
}
/// Never reached once the prescan passed (its caps are lower); a backstop on parser memory.
const NODES_LIMIT: u32 = 200_000;
/// Bounds, parses and reads an SVG text into the core's tree; the root must be `<svg>` in the
/// SVG namespace (or none), written unprefixed.
pub fn parse_svg(text: &str) -> Result<Element, SvgRejection> {
prescan(text, &SVG_CAPS)?;
let options = roxmltree::ParsingOptions {
allow_dtd: false,
nodes_limit: NODES_LIMIT,
..roxmltree::ParsingOptions::default()
};
let document = roxmltree::Document::parse_with_options(text, options).map_err(|e| match e {
roxmltree::Error::NodesLimitReached => SvgRejection::TooComplex,
roxmltree::Error::DtdDetected => SvgRejection::Doctype,
_ => SvgRejection::Malformed,
})?;
let root = element_of(document.root_element(), text, None);
if root.qname != "svg" || !root.is_svg_namespace() {
return Err(SvgRejection::NotSvg);
}
Ok(root)
}
/// The qualified name as written: the bytes after `<` up to whitespace, `/` or `>`.
fn written_name(text: &str, start: usize) -> String {
text[start + 1..]
.split(|c: char| c.is_ascii_whitespace() || c == '/' || c == '>')
.next()
.unwrap_or_default()
.to_owned()
}
fn element_of(
node: roxmltree::Node<'_, '_>,
text: &str,
parent: Option<roxmltree::Node<'_, '_>>,
) -> Element {
let mut attrs = declarations_of(node, parent);
attrs.extend(node.attributes().map(|a| Attribute {
qname: text[a.range_qname()].to_owned(),
namespace: a.namespace().map(str::to_owned),
value: a.value().to_owned(),
}));
let children = node
.children()
.filter_map(|child| {
if child.is_element() {
Some(Node::Element(element_of(child, text, Some(node))))
} else if child.is_text() {
Some(Node::Text(child.text().unwrap_or_default().to_owned()))
} else {
None
}
})
.collect();
Element {
qname: written_name(text, node.range().start),
namespace: node.tag_name().namespace().map(str::to_owned),
attrs,
children,
}
}
/// The namespaces declared on this element: in scope here and not in the parent's scope.
fn declarations_of(
node: roxmltree::Node<'_, '_>,
parent: Option<roxmltree::Node<'_, '_>>,
) -> Vec<Attribute> {
let inherited: Vec<(Option<&str>, &str)> = parent
.map(|p| p.namespaces().map(|n| (n.name(), n.uri())).collect())
.unwrap_or_default();
node.namespaces()
.filter(|n| n.name() != Some("xml") && !inherited.contains(&(n.name(), n.uri())))
.map(|n| Attribute {
qname: n
.name()
.map_or_else(|| "xmlns".to_owned(), |p| format!("xmlns:{p}")),
namespace: Some(XMLNS_NS.to_owned()),
value: n.uri().to_owned(),
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_names_as_written_namespaces_and_declarations() {
let text = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 1 1\"><g id=\"a\">\n <use xlink:href=\"#a\"/></g></svg>";
let root = parse_svg(text).unwrap_or_else(|e| panic!("{e:?}"));
let names: Vec<&str> = root.attrs.iter().map(|a| a.qname.as_str()).collect();
assert_eq!(names, ["xmlns", "xmlns:xlink", "viewBox"]);
let g = root
.element_children()
.next()
.unwrap_or_else(|| panic!("g"));
assert!(g.attrs.iter().all(|a| !a.qname.starts_with("xmlns")));
assert_eq!(g.children.len(), 2);
let Node::Element(use_el) = &g.children[1] else {
panic!("use")
};
assert_eq!(use_el.attrs[0].qname, "xlink:href");
assert_eq!(use_el.attrs[0].namespace.as_deref(), Some(XLINK_NS));
}
#[test]
fn refuses_a_prefixed_or_foreign_root_and_accepts_one_without_namespace() {
let prefixed = "<s:svg xmlns:s=\"http://www.w3.org/2000/svg\"/>";
assert_eq!(parse_svg(prefixed), Err(SvgRejection::NotSvg));
assert_eq!(
parse_svg("<svg xmlns=\"http://e\"/>"),
Err(SvgRejection::NotSvg)
);
assert!(parse_svg("<svg><path/></svg>").is_ok());
assert_eq!(
parse_svg("<svg><path xlink:href=\"#p\"/></svg>"),
Err(SvgRejection::Malformed)
);
}
}
+29
View File
@@ -8,6 +8,7 @@ use serde::Deserialize;
use super::index::{IndexedDocument, NoMainView, SheetIndex};
use super::schema::AnatomicalSheetDocument;
use crate::anatomy::svg::{Element, read_svg};
use crate::domain::archive::SheetStatus;
use crate::domain::js::JsInt;
use crate::domain::report::{ReportMigrationMap, SheetRef};
@@ -49,6 +50,23 @@ pub struct LoadedSheet {
pub asset_hashes: HashMap<String, String>,
pub migration_map: ReportMigrationMap,
index: SheetIndex,
/// Each asset read once at load (R3): the sanitised tree, or why it cannot be drawn. A
/// rejection only affects the views on that asset; `assets` keeps the raw texts (the
/// snapshot archives them).
drawings: HashMap<String, Drawing>,
}
/// A sheet drawing ready to compose, or the closed reason it cannot be drawn: the reader's
/// rejection, or `removed …` when the allowlist would take something out of a product
/// drawing (refused, never repaired: LRN-055).
pub type Drawing = Result<Element, String>;
fn read_drawing(text: &str) -> Drawing {
match read_svg(text) {
Ok(read) if read.removed.is_empty() => Ok(read.root),
Ok(read) => Err(format!("removed {}", read.removed.join(", "))),
Err(rejection) => Err(rejection.reason().to_owned()),
}
}
/// Why a bundled sheet cannot be loaded.
@@ -78,6 +96,11 @@ impl LoadedSheet {
let document = AnatomicalSheetDocument::deserialize(&data.document)?;
let migration_map = ReportMigrationMap::deserialize(&data.migration_map)?;
let index = SheetIndex::build(&document)?;
let drawings = data
.assets
.iter()
.map(|(id, text)| (id.clone(), read_drawing(text)))
.collect();
let r = data.reference;
Ok(Self {
status: data.status,
@@ -93,6 +116,7 @@ impl LoadedSheet {
asset_hashes: data.asset_hashes,
migration_map,
index,
drawings,
})
}
@@ -103,4 +127,9 @@ impl LoadedSheet {
pub fn index(&self) -> &SheetIndex {
&self.index
}
/// The drawing of an asset; `None` when the bundle has no such asset.
pub fn drawing(&self, asset_id: &str) -> Option<&Drawing> {
self.drawings.get(asset_id)
}
}
+1
View File
@@ -5,6 +5,7 @@
//! (`crates/wasm`), the worker and the tools. R0 ships the serialisation rules and the
//! first contract types; the business rules arrive with R2.
pub mod anatomy;
pub mod domain;
pub mod facade;
pub mod json;
+48
View File
@@ -7,6 +7,8 @@ use serde_json::Value;
#[cfg(feature = "ts")]
use ts_rs::TS;
use crate::anatomy::compose::{ComposeError, asset_id_of_view, compose_canvas};
use crate::anatomy::svg::serialize::serialize;
use crate::domain::archive::build_sheet_snapshot;
use crate::domain::editor::{
self, EditorError, LeafClick, MoveDirection, NewReportDraft, NewReportStamp, VertebraAction,
@@ -215,6 +217,7 @@ pub fn on_sheet(sheet: &LoadedSheet, op: &str, input: &str) -> Option<Outcome> {
"draft.restore" => draft_restore(sheet, input),
"archive.import" => archive_import(sheet, input),
"archive.snapshot" => archive_snapshot(sheet, input),
"view.canvas" => view_canvas(sheet, input),
_ => return None,
})
}
@@ -339,3 +342,48 @@ fn archive_snapshot(sheet: &LoadedSheet, input: &str) -> Outcome {
let input: SnapshotInput = parse_input(input)?;
to_value(&build_sheet_snapshot(sheet, &input.report))
}
// ---------------------------------------------------------------------------
// Anatomy (R3)
#[derive(Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CanvasViewInput {
pub view_id: String,
}
/// The editor canvas of one view, as SVG text the browser parses.
#[derive(serde::Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct CanvasView {
pub svg: String,
}
/// A composed view larger than this is refused (plan R3 C2: output bounded; the product
/// drawing composes to 143 KiB).
pub const MAX_COMPOSED_BYTES: usize = 4 * 1024 * 1024;
fn view_canvas(sheet: &LoadedSheet, input: &str) -> Outcome {
let input: CanvasViewInput = parse_input(input)?;
let document = &sheet.document;
if !document.views.iter().any(|v| v.id() == input.view_id) {
return Err(Failure::new("unknown_view", &input.view_id));
}
let asset_id = asset_id_of_view(document, &input.view_id)
.ok_or_else(|| Failure::new("no_asset", &input.view_id))?;
let drawing = match sheet.drawing(asset_id) {
None => return Err(Failure::new("no_asset", asset_id)),
Some(Err(reason)) => return Err(Failure::new("svg_rejected", reason)),
Some(Ok(drawing)) => drawing,
};
let canvas = compose_canvas(document, &input.view_id, drawing).map_err(|e| match e {
ComposeError::UnknownView => Failure::new("unknown_view", &input.view_id),
ComposeError::InvalidCharacter => Failure::new("invalid_character", &input.view_id),
})?;
let svg = serialize(&canvas);
if svg.len() > MAX_COMPOSED_BYTES {
return Err(Failure::new("svg_rejected", "too_large"));
}
to_value(&CanvasView { svg })
}
+84
View File
@@ -0,0 +1,84 @@
//! R3 facade: `view.canvas` on the loaded sheet. The drawing is read once at load; a view
//! answers its composed canvas, a rejected or unknown asset a closed kind for that view only.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use common::svg_tree::{tree_value, view_names, with_trigger_names_per_language};
use faunosteo_core::anatomy::svg::tree::parse_svg;
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::sheet::{BundledSheetData, LoadedSheet};
use faunosteo_core::facade::call_with_sheet;
use serde_json::{Value, json};
const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft";
const HORSE_ID: &str = "7f767f74-3b36-51a7-8465-52dd7e2ead4a";
fn sheet_with(horse: &str) -> LoadedSheet {
let payload = json!({
"status": "draft",
"ref": {
"sheet_id": "s", "version_id": null, "document_sha256": "0".repeat(64),
"schema_version": 2, "species_id": "equine"
},
"document": parse_json(&common::repo_file(&format!("{SEED}/document.json"))).unwrap(),
"migrationMap": parse_json(&common::repo_file(&format!("{SEED}/report-migration-map.json"))).unwrap(),
"assets": { HORSE_ID: horse }, "assetHashes": { HORSE_ID: "0".repeat(64) }
});
let data: BundledSheetData = serde_json::from_value(payload).unwrap();
LoadedSheet::from_bundle(data).unwrap()
}
fn call(sheet: &LoadedSheet, input: Value) -> Value {
serde_json::from_str(&call_with_sheet(sheet, "view.canvas", &input.to_string())).unwrap()
}
/// A frozen canvas golden with the declared trigger-name change applied.
fn golden(name: &str, sheet: &LoadedSheet) -> Value {
let text = common::repo_file(&format!("apps/app/tests/fixtures/goldens/r3/{name}"));
let mut frozen: Value = serde_json::from_str(&text).unwrap();
with_trigger_names_per_language(&mut frozen, &view_names(&sheet.document));
frozen
}
#[test]
fn each_view_answers_the_frozen_canvas() {
let sheet = sheet_with(&common::repo_file(&format!("{SEED}/assets/horse.svg")));
for view in ["main", "head"] {
let out = call(&sheet, json!({ "viewId": view }));
assert_eq!(out["ok"], true, "{out}");
let svg = out["value"]["svg"].as_str().unwrap();
assert_eq!(
tree_value(&parse_svg(svg).unwrap()),
golden(&format!("canvas.{view}.json"), &sheet),
"{view}"
);
}
}
#[test]
fn closed_kinds_for_an_unknown_view_a_rejected_or_altered_drawing_and_bad_input() {
let horse = common::repo_file(&format!("{SEED}/assets/horse.svg"));
let sheet = sheet_with(&horse);
assert_eq!(
call(&sheet, json!({ "viewId": "nope" }))["kind"],
"unknown_view"
);
assert_eq!(
call(&sheet, json!({ "view": "main" }))["kind"],
"invalid_shape"
);
let deep = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\">{}</svg>",
"<g>".repeat(80) + &"</g>".repeat(80)
);
let rejected = call(&sheet_with(&deep), json!({ "viewId": "main" }));
assert_eq!(
(rejected["kind"].as_str(), rejected["detail"].as_str()),
(Some("svg_rejected"), Some("too_deep"))
);
let scripted = horse.replacen("<path", "<script>alert(1)</script><path onclick=\"x\"", 1);
let altered = call(&sheet_with(&scripted), json!({ "viewId": "head" }));
assert_eq!(altered["kind"], "svg_rejected");
assert_eq!(altered["detail"], "removed script, path@onclick");
}
+156
View File
@@ -0,0 +1,156 @@
//! R3 O1 + O3: the Rust compositions against the TypeScript trees frozen before the switch.
//! O3 (`oracles/r3/highlight.json`, `packages/pdf/tests/r3.highlight-oracles.test.ts`): the
//! engine's highlighted view for every observation and view of the three reference reports
//! and an edge sheet. O1 (`apps/app/tests/fixtures/goldens/r3/canvas.*.json`,
//! `apps/app/tests/unit/canvas.trees.test.ts`): the editor canvas of each view with no state,
//! and its layer for every state set of the reference reports. Trees compared as structure,
//! text nodes included; the Rust tree is the composition serialised and read again.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use std::collections::HashSet;
use common::svg_tree::{reread, tree_value, view_names, with_trigger_names_per_language};
use faunosteo_core::anatomy::compose::{asset_id_of_view, compose_canvas, compose_highlight};
use faunosteo_core::anatomy::layer::render_layer;
use faunosteo_core::anatomy::svg::{Element, read_svg};
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
use serde::Deserialize;
use serde_json::{Value, json};
const HORSE: &str = "supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg";
fn draft() -> AnatomicalSheetDocument {
let (_, draft) = common::oracle_file("sheet.draft.json");
AnatomicalSheetDocument::deserialize(&draft["output"]).unwrap()
}
fn sanitized(text: &str) -> Element {
read_svg(text).unwrap().root
}
/// The frozen case's root rebuilt: root attributes, children before the asset, the asset's
/// children (the shared sanitised tree, or the case's own), the layer.
fn expected(case: &Value, oracle: &Value) -> Value {
let mut children = case["before"].as_array().unwrap().clone();
match &case["asset"] {
Value::String(reference) => {
let id = reference.strip_prefix("asset:").unwrap();
children.extend(
oracle["sanitized"][id]["children"]
.as_array()
.unwrap()
.iter()
.cloned(),
);
}
own => children.extend(own.as_array().unwrap().iter().cloned()),
}
children.push(case["layer"].clone());
let root = &case["root"];
json!({ "ns": root["ns"], "name": root["name"], "attrs": root["attrs"], "children": children })
}
#[test]
fn every_highlighted_view_equals_the_engine_tree() {
let (_, oracle) = common::oracle_file("r3/highlight.json");
let horse = sanitized(&common::repo_file(HORSE));
let draft = draft();
let edge = AnatomicalSheetDocument::deserialize(&oracle["edgeDocument"]).unwrap();
let edge_assets = &oracle["edgeAssets"];
let edge_main = sanitized(edge_assets["main"].as_str().unwrap());
let edge_own = sanitized(edge_assets["own"].as_str().unwrap());
let cases = oracle["cases"].as_array().unwrap();
assert_eq!(cases.len(), 36);
for case in cases {
let view = case["viewId"].as_str().unwrap();
let is_edge = case["sheet"] == "edge";
let document = if is_edge { &edge } else { &draft };
let asset_id = asset_id_of_view(document, view).unwrap();
let asset = if !is_edge {
horse.clone()
} else if asset_id == edge_assets["ownAssetId"] {
edge_own.clone()
} else {
edge_main.clone()
};
let ids: HashSet<&str> = case["observation"]["zones"]
.as_array()
.unwrap()
.iter()
.filter(|z| z["viewId"] == view)
.map(|z| z["annotationId"].as_str().unwrap())
.collect();
let main = document
.views
.iter()
.find(|v| v.id() == view)
.unwrap()
.is_main();
let composed = compose_highlight(document, view, asset, &ids, main).unwrap();
let label = format!("{} {} {view}", case["sheet"], case["observation"]["id"]);
let mut frozen = expected(case, &oracle);
with_trigger_names_per_language(&mut frozen, &view_names(document));
assert_eq!(reread(&composed), frozen, "{label}");
}
}
/// A frozen canvas golden with the declared trigger-name change applied (draft views).
fn canvas_golden(name: &str) -> Value {
let text = common::repo_file(&format!("apps/app/tests/fixtures/goldens/r3/{name}"));
let mut frozen: Value = serde_json::from_str(&text).unwrap();
with_trigger_names_per_language(&mut frozen, &view_names(&draft()));
frozen
}
#[test]
fn every_canvas_equals_the_frozen_tree_and_every_state_set_its_layer() {
let horse = sanitized(&common::repo_file(HORSE));
let draft = draft();
for view in ["main", "head"] {
let canvas = compose_canvas(&draft, view, &horse).unwrap();
assert_eq!(
reread(&canvas),
canvas_golden(&format!("canvas.{view}.json")),
"{view}"
);
let layers: Value = serde_json::from_str(&common::repo_file(&format!(
"apps/app/tests/fixtures/goldens/r3/canvas.{view}.layers.json"
)))
.unwrap();
for (name, frozen) in layers.as_object().unwrap() {
let mut frozen = frozen.clone();
with_trigger_names_per_language(&mut frozen, &view_names(&draft));
let frozen = &frozen;
let states = frozen_states(frozen);
let ids: HashSet<&str> = states.iter().map(String::as_str).collect();
let layer = render_layer(&draft, view, &ids).unwrap();
assert_eq!(tree_value(&layer), *frozen, "{view} {name}");
}
}
}
/// The annotation ids a frozen layer marks `data-state="current"`.
fn frozen_states(layer: &Value) -> Vec<String> {
let mut ids = Vec::new();
for child in layer["children"].as_array().unwrap() {
let attrs = &child["attrs"];
if attrs["data-state"] == "current" {
ids.push(attrs["data-anno-id"].as_str().unwrap().to_owned());
}
}
ids
}
#[test]
fn a_label_xml_cannot_carry_is_refused_never_replaced() {
let mut draft = draft();
let horse = sanitized(&common::repo_file(HORSE));
if let Some(faunosteo_core::domain::sheet::Annotation::Observable(a)) =
draft.annotations.first_mut()
{
a.name.en = "bad\u{1}name".to_owned();
}
assert!(compose_canvas(&draft, "main", &horse).is_err());
}
+140
View File
@@ -0,0 +1,140 @@
//! R3 O2: the Rust annotation layer equals the TypeScript layer tree frozen by
//! `packages/anatomy/tests/r3.layer-oracles.test.ts`, attribute order included (the review
//! drawings are byte goldens of that order until R5).
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use std::collections::HashSet;
use common::svg_tree::{view_names, with_trigger_names_per_language};
use faunosteo_core::anatomy::layer::render_layer;
use faunosteo_core::anatomy::svg::{Element, Node};
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
use serde::Deserialize;
use serde_json::{Map, Value, json};
/// `LayerElement` as the TypeScript writes it: tag, ordered attributes, children, text.
fn layer_value(element: &Element) -> Value {
let attrs: Map<String, Value> = element
.attrs
.iter()
.map(|a| (a.qname.clone(), Value::String(a.value.clone())))
.collect();
let mut text = None;
let mut children = Vec::new();
for child in &element.children {
match child {
Node::Element(e) => children.push(layer_value(e)),
Node::Text(t) => text = Some(t.clone()),
}
}
let mut out = json!({ "tag": element.qname, "attrs": attrs, "children": children });
if let Some(t) = text {
out["text"] = Value::String(t);
}
out
}
/// Attribute names in order, at every level: what `==` on maps would not check.
fn orders(value: &Value, out: &mut Vec<Vec<String>>) {
out.push(
value["attrs"]
.as_object()
.unwrap()
.keys()
.cloned()
.collect(),
);
for child in value["children"].as_array().unwrap() {
orders(child, out);
}
}
#[test]
fn every_frozen_layer_is_reproduced_with_its_attribute_order() {
let (_, oracle) = common::oracle_file("r3/layer.json");
let (_, draft) = common::oracle_file("sheet.draft.json");
let draft = AnatomicalSheetDocument::deserialize(&draft["output"]).unwrap();
let edge = AnatomicalSheetDocument::deserialize(&oracle["edge"]).unwrap();
let cases = oracle["cases"].as_array().unwrap();
assert_eq!(cases.len(), 8);
for case in cases {
let document = if case["doc"] == "draft" {
&draft
} else {
&edge
};
let view = case["viewId"].as_str().unwrap();
let states: HashSet<&str> = case["states"]
.as_array()
.unwrap()
.iter()
.map(|s| s.as_str().unwrap())
.collect();
let layer = layer_value(&render_layer(document, view, &states).unwrap());
let label = format!("{} {} {:?}", case["doc"], view, states.len());
let mut frozen = case["layer"].clone();
with_trigger_names_per_language(&mut frozen, &view_names(document));
assert_eq!(layer, frozen, "{label}");
let (mut ours, mut theirs) = (Vec::new(), Vec::new());
orders(&layer, &mut ours);
orders(&frozen, &mut theirs);
assert_eq!(ours, theirs, "{label}: attribute order");
}
}
#[test]
fn an_unknown_view_is_refused() {
let (_, oracle) = common::oracle_file("r3/layer.json");
let edge = AnatomicalSheetDocument::deserialize(&oracle["edge"]).unwrap();
assert!(render_layer(&edge, "nope", &HashSet::new()).is_err());
}
#[test]
fn an_unnamed_trigger_names_the_opened_view_in_each_language_and_a_named_one_keeps_its_names() {
let (_, draft) = common::oracle_file("sheet.draft.json");
let draft = AnatomicalSheetDocument::deserialize(&draft["output"]).unwrap();
let layer = render_layer(&draft, "main", &HashSet::new()).unwrap();
let trigger = layer
.element_children()
.find(|e| e.attr("data-anno-id") == Some("head-trigger"))
.unwrap();
assert_eq!(
trigger.attr("data-anno-name-fr"),
Some("Tête (vue latérale gauche)")
);
assert_eq!(
trigger.attr("data-anno-name-en"),
Some("Head (left lateral view)")
);
let title = trigger.element_children().next().unwrap();
assert_eq!(
title.children,
[Node::Text(
"Tête (vue latérale gauche) / Head (left lateral view)".to_owned()
)]
);
// The edge document: an unnamed trigger on a view named Tête / Head, a named one.
let (_, oracle) = common::oracle_file("r3/layer.json");
let edge = AnatomicalSheetDocument::deserialize(&oracle["edge"]).unwrap();
let layer = render_layer(&edge, "main", &HashSet::new()).unwrap();
let names = |id: &str| {
let e = layer
.element_children()
.find(|e| e.attr("data-anno-id") == Some(id))
.unwrap();
(
e.attr("data-anno-name-fr").unwrap().to_owned(),
e.attr("data-anno-name-en").unwrap().to_owned(),
)
};
assert_eq!(
names("trigger-circle"),
("Tête".to_owned(), "Head".to_owned())
);
assert_eq!(
names("trigger-named"),
("Ouvrir".to_owned(), "Open".to_owned())
);
}
+2
View File
@@ -6,6 +6,8 @@
clippy::expect_used
)]
pub mod svg_tree;
use faunosteo_core::domain::js::{find_lone_surrogate, parse_json};
use serde_json::Value;
+79
View File
@@ -0,0 +1,79 @@
//! SVG trees as structure for the R3 oracles: namespace, local name, attributes by qualified
//! name (sorted), children with text, the shape the TypeScript generators freeze.
#![allow(dead_code, clippy::unwrap_used)]
use std::collections::BTreeMap;
use faunosteo_core::anatomy::svg::serialize::serialize;
use faunosteo_core::anatomy::svg::tree::{SVG_NS, parse_svg};
use faunosteo_core::anatomy::svg::{Element, Node};
use serde_json::{Value, json};
pub fn tree_value(element: &Element) -> Value {
let attrs: BTreeMap<&str, &str> = element
.attrs
.iter()
.map(|a| (a.qname.as_str(), a.value.as_str()))
.collect();
let children: Vec<Value> = element
.children
.iter()
.map(|n| match n {
Node::Element(e) => tree_value(e),
Node::Text(t) => json!({ "text": t }),
})
.collect();
json!({
"ns": element.namespace.as_deref().unwrap_or(SVG_NS),
"name": element.local_name(),
"attrs": attrs,
"children": children,
})
}
/// The element serialised and read again by the core, as a tree.
pub fn reread(element: &Element) -> Value {
tree_value(&parse_svg(&serialize(element)).unwrap())
}
/// Owner decision 2026-10-15 (R3): a trigger without a name of its own carries the opened
/// view's name in each language (the TypeScript freeze carries the French name twice). The
/// frozen trees stay as frozen; this declared change is applied to them before comparing:
/// `data-anno-name-en` takes the view's English name and the title reads "FR / EN".
pub fn with_trigger_names_per_language(tree: &mut Value, views: &[(String, String, String)]) {
if let Some(attrs) = tree.get_mut("attrs").and_then(Value::as_object_mut) {
let opened = attrs
.get("data-anno-opens-view")
.and_then(Value::as_str)
.map(str::to_owned);
let view = opened.and_then(|id| views.iter().find(|(v, _, _)| *v == id));
if let Some((_, fr, en)) = view
&& attrs.get("data-anno-name-en").and_then(Value::as_str) == Some(fr.as_str())
{
attrs.insert("data-anno-name-en".to_owned(), Value::String(en.clone()));
}
}
if let Some(text) = tree.get_mut("text") {
for (_, fr, en) in views {
if text.as_str() == Some(format!("{fr} / {fr}").as_str()) {
*text = Value::String(format!("{fr} / {en}"));
}
}
}
if let Some(children) = tree.get_mut("children").and_then(Value::as_array_mut) {
for child in children {
with_trigger_names_per_language(child, views);
}
}
}
/// (view id, FR name, EN name) of a document, for `with_trigger_names_per_language`.
pub fn view_names(
document: &faunosteo_core::domain::sheet::AnatomicalSheetDocument,
) -> Vec<(String, String, String)> {
document
.views
.iter()
.map(|v| (v.id().to_owned(), v.name().fr.clone(), v.name().en.clone()))
.collect()
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><a id="l"><path d="M0 0h1"/></a><animate attributeName="href" values="javascript:alert(1)"/><set attributeName="onclick" to="alert(1)"/><animateTransform attributeName="transform"/></svg>

After

Width:  |  Height:  |  Size: 270 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg"><path d="M0 0h1"/></svg>
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg"><g><![CDATA[]]><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></g></svg>

After

Width:  |  Height:  |  Size: 555 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg"><!--></svg><![CDATA[--><path a0="0" a1="1" a2="2" a3="3" a4="4" a5="5" a6="6" a7="7" a8="8" a9="9" a10="10" a11="11" a12="12" a13="13" a14="14" a15="15" a16="16" a17="17" a18="18" a19="19" a20="20" a21="21" a22="22" a23="23" a24="24" a25="25" a26="26" a27="27" a28="28" a29="29" a30="30" a31="31" a32="32" a33="33" a34="34" a35="35" a36="36" a37="37" a38="38" a39="39" a40="40" a41="41" a42="42" a43="43" a44="44" a45="45" a46="46" a47="47" a48="48" a49="49" a50="50" a51="51" a52="52" a53="53" a54="54" a55="55" a56="56" a57="57" a58="58" a59="59" a60="60" a61="61" a62="62" a63="63" a64="64" a65="65" a66="66" a67="67" a68="68" a69="69" a70="70" a71="71" a72="72" a73="73" a74="74" a75="75" a76="76" a77="77" a78="78" a79="79" a80="80" a81="81" a82="82" a83="83" a84="84" a85="85" a86="86" a87="87" a88="88" a89="89" a90="90" a91="91" a92="92" a93="93" a94="94" a95="95" a96="96" a97="97" a98="98" a99="99" a100="100" a101="101" a102="102" a103="103" a104="104" a105="105" a106="106" a107="107" a108="108" a109="109" a110="110" a111="111" a112="112" a113="113" a114="114" a115="115" a116="116" a117="117" a118="118" a119="119" a120="120" a121="121" a122="122" a123="123" a124="124" a125="125" a126="126" a127="127" a128="128" a129="129" a130="130" a131="131" a132="132" a133="133" a134="134" a135="135" a136="136" a137="137" a138="138" a139="139" a140="140" a141="141" a142="142" a143="143" a144="144" a145="145" a146="146" a147="147" a148="148" a149="149" a150="150" a151="151" a152="152" a153="153" a154="154" a155="155" a156="156" a157="157" a158="158" a159="159" a160="160" a161="161" a162="162" a163="163" a164="164" a165="165" a166="166" a167="167" a168="168" a169="169" a170="170" a171="171" a172="172" a173="173" a174="174" a175="175" a176="176" a177="177" a178="178" a179="179" a180="180" a181="181" a182="182" a183="183" a184="184" a185="185" a186="186" a187="187" a188="188" a189="189" a190="190" a191="191" a192="192" a193="193" a194="194" a195="195" a196="196" a197="197" a198="198" a199="199" a200="200" a201="201" a202="202" a203="203" a204="204" a205="205" a206="206" a207="207" a208="208" a209="209" a210="210" a211="211" a212="212" a213="213" a214="214" a215="215" a216="216" a217="217" a218="218" a219="219" a220="220" a221="221" a222="222" a223="223" a224="224" a225="225" a226="226" a227="227" a228="228" a229="229" a230="230" a231="231" a232="232" a233="233" a234="234" a235="235" a236="236" a237="237" a238="238" a239="239" a240="240" a241="241" a242="242" a243="243" a244="244" a245="245" a246="246" a247="247" a248="248" a249="249" a250="250" a251="251" a252="252" a253="253" a254="254" a255="255" a256="256" a257="257" a258="258" a259="259" a260="260" a261="261" a262="262" a263="263" a264="264" a265="265" a266="266" a267="267" a268="268" a269="269" a270="270" a271="271" a272="272" a273="273" a274="274" a275="275" a276="276" a277="277" a278="278" a279="279" a280="280" a281="281" a282="282" a283="283" a284="284" a285="285" a286="286" a287="287" a288="288" a289="289" a290="290" a291="291" a292="292" a293="293" a294="294" a295="295" a296="296" a297="297" a298="298" a299="299" a300="300" a301="301" a302="302" a303="303" a304="304" a305="305" a306="306" a307="307" a308="308" a309="309" a310="310" a311="311" a312="312" a313="313" a314="314" a315="315" a316="316" a317="317" a318="318" a319="319" a320="320" a321="321" a322="322" a323="323" a324="324" a325="325" a326="326" a327="327" a328="328" a329="329" a330="330" a331="331" a332="332" a333="333" a334="334" a335="335" a336="336" a337="337" a338="338" a339="339" a340="340" a341="341" a342="342" a343="343" a344="344" a345="345" a346="346" a347="347" a348="348" a349="349" a350="350" a351="351" a352="352" a353="353" a354="354" a355="355" a356="356" a357="357" a358="358" a359="359" a360="360" a361="361" a362="362" a363="363" a364="364" a365="365" a366="366" a367="367" a368="368" a369="369" a370="370" a371="371" a372="372" a373="373" a374="374" a375="375" a376="376" a377="377" a378="378" a379="379" a380="380" a381="381" a382="382" a383="383" a384="384" a385="385" a386="386" a387="387" a388="388" a389="389" a390="390" a391="391" a392="392" a393="393" a394="394" a395="395" a396="396" a397="397" a398="398" a399="399" a400="400" a401="401" a402="402" a403="403" a404="404" a405="405" a406="406" a407="407" a408="408" a409="409" a410="410" a411="411" a412="412" a413="413" a414="414" a415="415" a416="416" a417="417" a418="418" a419="419" a420="420" a421="421" a422="422" a423="423" a424="424" a425="425" a426="426" a427="427" a428="428" a429="429" a430="430" a431="431" a432="432" a433="433" a434="434" a435="435" a436="436" a437="437" a438="438" a439="439" a440="440" a441="441" a442="442" a443="443" a444="444" a445="445" a446="446" a447="447" a448="448" a449="449" a450="450" a451="451" a452="452" a453="453" a454="454" a455="455" a456="456" a457="457" a458="458" a459="459" a460="460" a461="461" a462="462" a463="463" a464="464" a465="465" a466="466" a467="467" a4Line truncated

After

Width:  |  Height:  |  Size: 36 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg"><!--></svg><![CDATA[--><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><g><Line truncated

After

Width:  |  Height:  |  Size: 34 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg"><!-- a comment --><?pi data?><g>text <![CDATA[x<y]]><path d="M0 0h1"/></g></svg>

After

Width:  |  Height:  |  Size: 120 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg"><path d="M0 0" style="position:fixed;width:100vw;height:100vh"/><path d="M0 0" style="fill:red;\66 ill:url(x)"/><path d="M0 0" style="background:image-set(url(x) 1x)"/><path d="M0 0" style="behavior:url(x.htc)"/><path d="M0 0" style="fill:expression(alert(1))"/><path d="M0 0" style="fill:rgb(1,2,3)"/><path d="M0 0" style="fill:#fff;stroke:none;cursor:pointer"/><path d="M0 0" style="content:attr(x)"/></svg>

After

Width:  |  Height:  |  Size: 449 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><linearGradient id="a"/><linearGradient id="b" xlink:href="#a"/><path d="M0 0h1" fill="url(#missing)"/><use href="#nope"/><path d="M0 0h1" stroke="url(#b)"/></svg>

After

Width:  |  Height:  |  Size: 246 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><use href="data:image/svg+xml;base64,PHN2Zz48L3N2Zz4="/><image href="data:image/png;base64,iVBOR" width="1" height="1"/><image xlink:href="http://evil.test/i.png"/></svg>

After

Width:  |  Height:  |  Size: 253 B

@@ -0,0 +1,3 @@
<?xml version="1.0"?>
<!DOCTYPE svg [<!ENTITY a "aaaaaaaaaa"><!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;">]>
<svg xmlns="http://www.w3.org/2000/svg"><text>&b;</text></svg>

After

Width:  |  Height:  |  Size: 170 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg"><!-- <!DOCTYPE note --><path d="M0 0h1"/></svg>

After

Width:  |  Height:  |  Size: 87 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg"><path id="x" d="M0 0h1"/><g id="x"/></svg>

After

Width:  |  Height:  |  Size: 82 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg"><path d="M0 0h1" fill="&#x75;rl(http://evil.test/x)"/><path d="M0 0h1" fill="&amp;#x75;"/><path d="M0 0h1" fill="#&#x30;00"/></svg>

After

Width:  |  Height:  |  Size: 171 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"><path d="M0 0h1" onclick="alert(2)" ONMOUSEOVER="x"/><g onfocusin="y"/></svg>

After

Width:  |  Height:  |  Size: 135 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg"><path d="M0 0h1" fill="url(http://evil.test/p)"/><path d="M0 0h1" style="fill:url(https://evil.test/p)"/><path d="url(//e)"/><path d="M0 0" filter="url( #ok)"/><filter id="ok"/></svg>

After

Width:  |  Height:  |  Size: 223 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path id="p" d="M0 0h1"/><use href="http://evil.test/x.svg#a"/><use xlink:href="//evil.test/x.svg#b"/><use href="#p"/></svg>

After

Width:  |  Height:  |  Size: 207 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg"><foreignObject width="10" height="10"><div xmlns="http://www.w3.org/1999/xhtml">x</div></foreignObject><iframe src="x"/><object data="x"/><embed src="x"/><path d="M0 0h1"/></svg>

After

Width:  |  Height:  |  Size: 218 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path id="a" d="M0 0h1"/><use href=" #a"/><use xlink:href="#a"/><use href=" #a "/></svg>

After

Width:  |  Height:  |  Size: 175 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg"><g id="1abc"/><g id="ok_1.a:b-c"/><g id="root"/><g id="a b"/></svg>

After

Width:  |  Height:  |  Size: 107 B

Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff. Show more