diff --git a/.claude/memory/blockers.md b/.claude/memory/blockers.md index 998e4046..924517ac 100644 --- a/.claude/memory/blockers.md +++ b/.claude/memory/blockers.md @@ -74,3 +74,10 @@ Status: resolved (commit on feature/step-04-anatomical-sheet-model). Migration 20261010100000 replaces the CHECK with `document_schema_version = 2` without rewriting rows → errors on any DB seeded before 4c (dev only today). Cause: schema bump shipped as constraint change, not as data migration. Solution: before real data, data migration lifting stored documents (add `references: []`, `review_status` defaults) then CHECK; rule from user: incremental non-destructive migrations, never a reset. Documented ANATOMICAL_SHEET_MODEL.md §6. Status: open (no real data yet; treat before Step 7+ persistence of user reports). + +--- + +## BLK-009 | 2026-10-11 | pdf-lib inflates PDF object streams without cap at `PDFDocument.load` (import path) + +Security audit Step 6 (MEDIUM, pre-existing since Step 1 import): `PDFDocument.load` decodes every `/ObjStm` and xref stream eagerly with its own uncapped FlateStream; measured 408 KB PDF → 400 MB in 1.4 s, 468 MB RSS; `MAX_PDF_BYTES` 50 MiB allows ~50 GB. Attachment cap (16 MiB) covers the attachment only. Impact: tab freeze/OOM for the practitioner on a crafted PDF, no code execution. Cannot refuse `/ObjStm` (pdf-lib `save()` emits object streams in our own PDFs). Options: parse in a Web Worker (bounded blast radius), or locate the attachment by scanning bytes without a full load, or a capped custom decoder. pdf-lib 1.17.1 unmaintained since 2021 (LOW in the same audit). +Status: MITIGATED on the browser import path 2026-10-11 (60ee712: byte-scan attachment reader, no `PDFDocument.load` on untrusted bytes, export without object streams; ObjStm bomb read in 5 ms, +0.5 MiB RSS). Then 3a6e926: inflater fed in 16 KiB slices (Chromium read-ahead defeated the cancel: 4 GiB bomb +2.2 GB → +192 MB measured), shared 16 MiB candidate budget, bounded endstream search; final loop: candidates sorted by offset, JSON depth pre-scan. Audits ×3 PASS; worst measured costs on crafted files: +192 MB single bomb, ~0.5 s / ≤0.4 GB for 32 failing inflations, ~1 s deep JSON (before the pre-scan). GATE STILL OPEN before any external-user import (BDR-040): Firefox/Safari inflater read-ahead unmeasured (no browser test runner), Worker/server import with time+memory budget, pdf-lib replacement decision (unmaintained), report collection caps on read, `` nesting budget, low-end phone measurement. Plan: docs/development/PDF_IMPORT_HARDENING.md §5. Never close on passing tests alone. diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index 53a23fd2..ed1f200d 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -327,3 +327,19 @@ Status: closed. Sheet source: `SheetProvider` interface; Step 5 implementation = Vite virtual module `virtual:faunosteo-sheet` built from the seed draft (`vite/sheet-bundle.ts`), mode `SHEET_BUNDLE=draft|none`, default draft for dev server, none for builds/CI/Docker (`--build-arg SHEET_BUNDLE=draft` = explicit preview) → unvalidated draft never ships by accident (D2). Markers: pure renderer `@faunosteo/anatomy/render` (element tree, no DOM) reproduces legacy look (hitbox r + twin r−12, opacities 0.65/0.5, spine 0.3, trigger 0.06 dashed); colours = document data (`categories[].color`, additive `annotations[].color` for the head shades, schema_version stays 2 for additive optional fields); same renderer feeds `draft/review/app-.svg` for visual checks. Report v3 in packages/domain: `(annotationId, viewId)` zones with label snapshots, `(findingZoneId, path)` findings, severity codes, `sheet {sheetId, versionId|null, documentSha256}`, `unresolved: true` for what migration cannot place, `localAnnotations: []` reserved. Migration map generated by the pipeline from applier records (replay renames/moves/removals + unique re-homing): 792 nodes → 571/180/7/34. Interaction = pure service + reducers (BDR-019 kept); store = v3 + persistence adapter (v2 draft migrated on restore). D4 applied: registry, matchers, SVG parser, editors, pathology-editor, public species assets deleted; legacy sources moved to `supabase/seed/.../legacy-sources/` (importer input). Alt rejected: copying the draft into apps/app (duplication, drift); runtime fetch of `/sheets/*.json` (still public, no gain); UUID annotation ids (BDR-031); converting v3→v2 for attachments (lossy); per-view colour table in the app (horse knowledge in generic code). Status: closed; awaiting user validation of Step 5. + +--- + +## BDR-039 | 2026-10-11 | Step 6: autonomous PDF archives — lean-document snapshot, envelope v1, archived branding + labels, explicit rebase + +User-validated design (docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II). Attachment = envelope v1 `{format, envelopeVersion, exportedAt, locale, report v3, sheetSnapshot, branding, labels}` in one `osteo-report.json`, SVG inline as text. Snapshot = `{status, ref, document, assets}` where document = valid lean `AnatomicalSheetDocument` (all views/annotations/categories/regions, finding zones kept by id, trees pruned to used paths with ancestor labels, references emptied) → reuses sheet index, layer renderer, 21 integrity rules; no dedicated schema. Branding (logos base64/svg, credits, URLs) + label dict (fr+en) archived so future logo/wording changes never alter a re-render (user D7 adjustment). Engine `packages/pdf`: explicit inputs `{report, sheet, branding, labels, locale, rasterizer, exportedAt}`, no DOM lib, xmldom composition promoted from curation app-review, Rasterizer adapter (browser Image/canvas; resvg devDep for tests), per-view/per-logo degradation, export-side validation (caps, integrity, sheet invariant). Read = layered: report first (v3/v2 existing dispatch), envelope metadata tolerant, snapshot strict → `snapshotRejected` enum, report never lost; `attachment_stripped` via Info.Keywords stamp. Session: imported archive kept immutable (`osteo:archive`), working copy rebased explicitly on the loaded sheet (`rebaseReportOnSheet`, unresolved flags + labels from archived snapshot) (user D8 adjustment); re-export of the kept archive = technical support only, UX submitted after step. No CLI, no page change, no original v2 JSON re-embedded. +Alt rejected: dedicated SheetSnapshotSchema (rewrites lookups, loses integrity rules); separate embedded files per asset (first-EmbeddedFile reader, stripping risk); pruning views/annotations (saves ~0 KB, breaks trigger titles); snapshot discarded on import (user: keep for faithful re-read); crypto hash check of assets (self-referential; sha copied from catalog manifest as provenance pointer instead). +Status: closed (Step 6 validated by user 2026-10-11; D8 finalised in BDR-040). + +--- + +## BDR-040 | 2026-10-11 | Step 6 closure: no "re-export the original archive" button, visible rebase, BLK-009 gate + +User decisions after manual validation (logos and picker text confirmed OK on their side; Step 6 VALIDATED). (1) Re-export of the imported archive from the UI REFUSED permanently: the practitioner already holds the original PDF; no second button, no dedicated UX flow. Keep the archived snapshot, its integrity and the autonomy tests (engine `exportFromEnvelope` stays as the proof + future server use); the UI exports only the open working report. Do not propose this feature again. (2) Rebase on draft restore shown to the user (`editor.draft_rebased`) approved; import messages approved on principle with an explicit "full restoration" vs "partial recovery" headline. (3) BLK-009 treated now: byte-scan attachment extraction without pdf-lib load on import + export without object streams; remaining risks (worker/server import, pdf-lib replacement, read caps) stay an explicit BLOCKER gate before any external user import; never declared solved by passing tests alone. +Alt rejected: a re-export action on the home screen after import (same objection); a toast system for import feedback (no component, alert pattern kept). +Status: closed. diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index 8e80a667..7991392a 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -97,3 +97,21 @@ Result: verifier pass 1 ECARTS(2) = floor only (EVAL-011 prose "eslint-disable" Anomalies: verifier stage runs after executor edits only (concurrent reads otherwise); gates.sh needs `EVIDENCE: PENDING` placeholder lines on new criteria. Residuals noted, not fixed: ZodError message echoes closed-vocabulary received values (never names), `compareReport` computes v3 lines twice, template-literal lines >80 chars, locals >5 in two functions. Action: await user manual validation of Step 5; residuals in TODO follow-up. + +--- + +## EVAL-013 | 2026-10-11 | Step 6 autonomous PDF archives — 5 phases by executors, 3 verifier passes, 4 security audits + +Method: analysis (3 analyzers + measurements) challenged by 3 plan-challengers (correctness/robustness/simplicity, 48 findings folded in) → user validation with D7/D8/D13 adjustments → Part II contract (exact types) → one executor per phase (0 freeze goldens, 1 domain, 2 anatomy compose, 3 engine, 4 app) with closed contracts, orchestrator commits → whole-step verifier + security auditor → fix loops. +Result: Phase 0 froze 39 goldens (text/images/links per locale × logo mode, view facts) + 2 route characterisation tests with the OLD code; engine reproduced 36 goldens with 0 mismatch (views: data-* 2→0 and hidden-marker titles declared relaxed). Verifier pass 1 ECARTS(31) = all oracle/scope defects of MY contract (grep on parametrised table, xmldom filter, narrow FILE SCOPE, 3 deleted tests with moved coverage) → contract amended → pass 2 CONFORME 13/13. Security pass 1 BLOCK(1) HIGH real + PoC: archived branding URL written unescaped into `/URI` (PDF object injection via `exportFromEnvelope`), +3 MEDIUM/4 LOW → executor fixed (hex URI, strict URL schema, export re-validation, PNG IHDR budget, CSS-escape rules, NaN guard, file.size) → pass 2 PASS but 2 MEDIUM incl. a regression the fix introduced (UTF-16 BOM URI dead in poppler) + PNG double-IHDR bypass → executor → pass 3 PASS + 1 MEDIUM (UPNG nextZero spin on tEXt) → executor (chunk allowlist + IEND) → pass 4 PASS + 3 MEDIUM (UPNG `inflateRaw` spins on truncated IDAT with allowlisted chunks only; IHDR fields unvalidated; zero dimension) → executor: native bounded `inflateFlate` of the IDAT against the exact raw size, IHDR fields, sides ≥ 1, no interlace, raw ≤ 16 MiB → pass 5 focused. Lesson: a third-party decoder on untrusted bytes needs a native oracle in front, not a chunk allowlist. Final: 656 tests (194/21/130/88/223), typecheck, lint, build, docker ×4 green; goldens byte-identical since 8b86b92. +Anomalies: contract oracles written fast = 2 verifier passes lost (lesson: run every CHECK once before dispatching the verifier); security fix introduced a functional regression invisible to tests because the test reader decoded the BOM (lesson: assert raw bytes, cross-check with a real reader like poppler); executors denied `rm`/`git rm` (orchestrator deletes); one executor used `git stash` despite "no git state" (now forbidden explicitly in briefs); demo envelope with archived branding = 136 KB stored / 306 KB raw (raw > 250 KB, stored < 250 KB: reported, user said data first). +Action: await user manual validation + UX decision on re-export of the kept archive; BLK-009 (pdf-lib ObjStm inflation) before external users; react-router advisories (pre-existing) to bump in a chore. + +--- + +## EVAL-014 | 2026-10-11 | Step 6 closure round — manual-test feedback, BLK-009 scanner, final audits + +Method: user manual tests round 1 (logos absent, picker blurry) → reproduction attempts (headless Chromium dev/preview/Docker, Firefox 157 via esbuild harness + raw WebDriver BiDi client, CDP LayerTree, LCD-fringe metric, headed runs on the Wayland session) → fixes by executors → user round 2 confirmed both OK → closure decisions → BLK-009 implemented (byte-scan reader, no object streams) → verifier + 2 security audits + 1 fix loop. +Result: neither visual defect reproduced here (4 environments, 2 engines, 2 PDF renderers); shipped the environment-independent fixes (branding bundled, no fetch; warnings surfaced) and the user confirmed logos + crisp text. Scanner: verifier CONFORME 7/7; audit 1 PASS + 2 MEDIUM (Chromium DecompressionStream read-ahead defeats the cancel: +2.2 GB on a 4 GiB bomb; ×32 candidate CPU) → executor (16 KiB slice feeding, shared 16 MiB budget, monotonic bounded endstream search, `{` pre-check; 133 pdf tests) → audit 2 focused. Workspace 710 tests, build, docker green. +Anomalies: the blur fix of the previous round (will-change) had been marked PARTIALLY MET "desktop by user" — the user's "still blurry" came from that unverified half; this round could not verify real-GPU text rendering either (headless engines render grayscale AA, headed captures failed) → lesson: a screen-rendering defect needs the user's own capture + an A/B recipe early, not days of headless measurement. The Node vitest suite cannot observe browser stream read-ahead: record browser-only bounds as owed manual checks (PDF_IMPORT_HARDENING §5). +Action: BLK-009 stays "mitigated, gate open" (BDR-040); Step 6 finished into develop; release/0.2.0 prepped for the user's go. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 13d40d7b..65e604b1 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -199,3 +199,15 @@ Step 4 validated + finished into develop. User decisions on the 7 open points ## 2026-10-10 (session — Step 5 closed, Step 6 analysis) Step 5 validated + closed by user; LRN-045 (permanent will-change blurs text) written on develop. Step 6 analysis on chore/step-06-pdf-archive-analysis: 3 analyzers (PDF pipeline, data model, app/tests) → facts: export reads live SheetIndex (labels, views, asset, all annotations of view), 4 fetched logos + 3 hard-coded URLs, DOM in drawing/highlight/raster, attachment = bare v3 Flate'd by pdf-lib, getAttachments dead on pdf-lib 1.17.1, no report↔sheet check anywhere. Measured: lean snapshot envelope 172 KB raw / 51 KB stored (3 obs), 228 / 54 worst; SVG = 90% of stored. Plan: snapshot = lean AnatomicalSheetDocument + assets inline (reuses index/renderer/integrity rules), packages/pdf engine (xmldom compose promoted from app-review.ts, Rasterizer + Branding inputs, no DOM lib), envelope v1 layered reading (report never lost), rebase on import/restore keeps report.sheet == snapshot.ref, export-side caps. 3 plan-challengers GO WITH FIXES (16+19+13 findings folded in). docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md; TODO 6.0–6.7. Awaiting user decisions D1/D4/D6/D7/D8/D10/D12/D13; no implementation. + +## 2026-10-11 (Step 6 implementation) + +User validated the Step 6 analysis with D7 (branding archived), D8 (imported snapshot kept, explicit rebase, no new UI without UX gate), D13 (explicit import messages). Analysis chore branch finished; feature/step-06-pdf-archives. Part II contract (exact types) + BDR-039. Phases by executors: 0 freeze (39 goldens, demo fixture, bare v3 PDF, route characterisation), 1 domain (archive/{snapshot,envelope,branding,labels}, sheet-index moved, rebase, bundle asset hashes), 2 anatomy (composeViewSvg + highlightLayer promoted from app-review), 3 engine packages/pdf (xmldom composition, allowlist sanitiser, safeText, Rasterizer, envelope v1, layered reader, resvg test), 4 app (export/import on the engine, archive in session `osteo:archive`, rebase + 4 messages, legacy modules removed). Verifier ECARTS(31, all my contract's oracles/scope) → CONFORME. Security BLOCK(1) HIGH (URI injection via archived branding) → 4 fix loops (hex URI → ASCII hex after poppler regression, URL schema, export re-validation, PNG IHDR budget → chunk allowlist + IEND → native IDAT inflation against exact raw size + IHDR fields, CSS escapes, NaN, file.size) → PASS. Docs: PDF-FORMAT.md real, CLAUDE/README/WORKSPACE/DEPLOY/CHANGELOG. 656 tests, build + docker green. Sizes: demo envelope 55 KB stored no logos / 136 KB with archived branding (306 KB raw). LRN-046, BLK-009, EVAL-013. Awaiting user validation + UX decision for re-export of the kept archive; Step 7 not started. + +## 2026-10-11 (Step 6 manual-test feedback) + +User: step not merged; findings-picker text still blurry; footer logos absent in their PDFs; decisions: re-export from archive wanted (UX to propose), restore-rebase must be visible, exact labels to validate; BLK-009 analysis. Done on feature/step-06-pdf-archives: logos NOT reproduced (real export in headless Chromium dev/preview/Docker image + Firefox 157 engine harness: 4 logos embedded, 0 warnings, poppler + pdf.js render them) → branding bundled into the app (`src/assets/brand`, `?inline`/`?raw`, no fetch at all) + export returns warnings + `editor.export_warnings` alert (293a6e0); blur NOT reproduced (headless Chromium/Firefox, DPR 1/1.25/2, scrolling 9-leaf list, CDP LayerTree: no composited layer, no lingering animation/will-change; headed runs on the user's Wayland display failed to capture) → analysis + A/B recipe for the user; restore rebase alert `editor.draft_rebased` (e8f1734); docs/development/PDF_IMPORT_HARDENING.md (byte-scan reader + no object streams now; worker/parser later) (5ed4a4b). Root check 660 tests, build, docker green. Awaiting user: browser/zoom for the blur, UX choice for re-export, label validation. + +## 2026-10-11 (Step 6 closure) + +User round 2: logos OK, picker text crisp, flows OK → STEP 6 VALIDATED. Decisions BDR-040: re-export-archive button refused for good; restore-rebase alert approved; import headlines full/partial (62b8a43). BLK-009: byte-scan attachment reader + export without object streams (60ee712), verifier CONFORME, audit PASS+2 MEDIUM → slice-fed inflater + candidate budget (3a6e926), focused re-audit. EVAL-014. Then: gitflow finish into develop, release/0.2.0 prep (Milestone A) up to the human go; Step 7 not started (UX/design to discuss with ChatGPT first). diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index 799dfa5a..fe6efe86 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -345,3 +345,10 @@ Apply: any future CLI/log over report content (Step 6 server import, worker). Te Context: findings picker text blurry on screen, crisp in PDF (Step 5 validation). `motion.ul` kept inline `will-change: transform, opacity` after its 220 ms slide (computed transform `none`); list sat at fractional offset inside height-animated card (left 561.1875 px desktop, top 735.77 px mobile) → element stayed on own compositor layer, text resampled at non-integer position → blur. Fix = drop the prop; motion promotes the element itself while animating (1f0b710). Pattern: never set permanent `will-change` on text containers; let the animation lib promote for the duration. Diagnose with headless Chromium: computed `willChange`, bounding rect fractional offsets, edge-sharpness ratio before/after (headless has no LCD antialiasing → desktop delta flat, user confirms in real browser). Regression test = rendered element has no inline `will-change`. Apply: any `motion.*`/CSS transition on lists, cards, modals holding text; design-review audits. + +--- + +## LRN-046 | 2026-10-11 | Refactor a render pipeline behind goldens frozen in two fixture modes; lean-document snapshot beats a new schema + +Step 6 moved the PDF pipeline into `packages/pdf` with zero visible change. What made it provable: Phase 0 froze drawn text (page, x, y, size, font), image placements, link annotations and per-view structural facts with the OLD code, in two harness modes (logos absent / present via a fetch stub serving the real public/ bytes) and per locale (footer geometry depends on label width). Golden JSON = oracle; the port had 0 mismatch; the two intentional differences (hidden markers absent, data-* gone) were declared as relaxed fields, never by editing goldens. Snapshot shaped as a valid lean `AnatomicalSheetDocument` reused the index, the renderer and 21 integrity rules (3 challengers killed the dedicated-schema idea). Node-side xmldom composer already existed in curation (`app-review.ts`): promote, don't rewrite. resvg 0.40 panics on gradient fills culled by a cropped root viewBox (head view) → test adapter renders the full box and crops pixels; Chrome is fine. Executors denied `rm`/`git rm`: orchestrator deletes on literal relative paths after checking importers. +Apply: any pipeline extraction (Step 13 Supabase provider, Step 14 worker); any "snapshot" design: reuse the live schema minus content before inventing one. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 47da331a..e14a877f 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -100,14 +100,17 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo - [x] 5.10 final controls on the last lot: stale root script scaffold:species removed; verifier ×3 (2→1→CONFORME) + security ×2 PASS on criteria 16-18; EVAL-012 - [x] 5.11 user validation defect: findings picker text blurry on screen → permanent `will-change` on the list dropped (hotfix 1f0b710, regression test); PDF never affected - [ ] 5.12 follow-up (not Step 5): equine sheet anatomical enrichment with the osteopath + future sheet editor (Step 17); the 28 draft annotations (carpus added, points moved) are NOT a final catalog -- [ ] Step 6 — autonomous PDF archives (analysis + plan 2026-10-10 on chore/step-06-pdf-archive-analysis: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md, challenged on 3 lenses GO WITH FIXES; AWAITING USER VALIDATION of D1/D4/D6/D7/D8/D10/D12/D13 before implementation on feature/step-06-pdf-archives) +- [ ] Step 6 — autonomous PDF archives (analysis validated by user 2026-10-11 with D7 branding archived, D8 snapshot kept + explicit rebase, D13 messages → Part II contract + BDR-039; implementation on feature/step-06-pdf-archives, one executor per phase) - [x] 6.0 analysis: 3 analyzers (pipeline, model, app/tests) + size measurements (envelope 172 KB raw / 51 KB stored for 3 obs, 228 / 54 worst case) + 3 plan-challengers → plan rewritten - - [ ] 6.1 Phase 0 freeze with current code: demo report fixture, migrated-v2-with-unresolved builder, G3 bare v3 PDF, G1 text goldens (logos absent + present), G2 structural facts/placements/links, T12 HomeRoute + T13 EditorRoute characterisation - - [ ] 6.2 Phase 1 domain: sheet-index moved, archive/snapshot (buildSheetSnapshot, assertSnapshot, caps), archive/envelope (schema v1, layered readArchiveDocument, SnapshotRejection), report/rebase (rebaseReportOnSheet), bundle carries asset sha + status/name, tests - - [ ] 6.3 Phase 2 anatomy: render/compose.ts promoted from curation/app-review.ts, highlight on the layer tree, review drawing golden unchanged - - [ ] 6.4 Phase 3 packages/pdf: scaffold (no DOM lib, restricted globals, vitest node, Dockerfile, CI, README), svg/sanitize allowlist + horse.svg zero-removal, render moved, Branding/Rasterizer/exportedAt/safeText/dict, exportReportArchive (T3 both logo modes), readReportArchive (filename-first, layered, attachment_stripped; T4-T6, T8), T1/T7/T9/T10 resvg/T11, xmldom bundle size ≤ 50 KB gz - - [ ] 6.5 Phase 4 app: browserRasterizer, branding.ts, export/import on the engine, rebase on import + draft restore, 2 new messages, old render/attachment/highlight code + pdf.* keys removed, report:compare on engine API, T2/T14/T15, suite migrated 1:1 - - [ ] 6.6 Phase 5 docs + gates: PDF-FORMAT.md real, CLAUDE.md map, WORKSPACE.md rule, DEPLOY.md rollback note, CHANGELOG, BDR-014 note; pnpm check, docker build, verifier + security gates, EVAL; manual validation list + - [x] 6.1 Phase 0 freeze (8b86b92: 39 goldens, demo fixture, bare v3 PDF, T12/T13; 206 app tests) with current code: demo report fixture, migrated-v2-with-unresolved builder, G3 bare v3 PDF, G1 text goldens (logos absent + present), G2 structural facts/placements/links, T12 HomeRoute + T13 EditorRoute characterisation + - [x] 6.2 Phase 1 domain (cdc0943: 154 domain tests, snapshot 171 KB raw on the fixture): sheet-index moved, archive/snapshot (buildSheetSnapshot, assertSnapshot, caps), archive/envelope (schema v1, layered readArchiveDocument, SnapshotRejection), report/rebase (rebaseReportOnSheet), bundle carries asset sha + status/name, tests + - [x] 6.3 Phase 2 anatomy (6940926: composeViewSvg + highlightLayer, 130 anatomy tests): render/compose.ts promoted from curation/app-review.ts, highlight on the layer tree, review drawing golden unchanged + - [x] 6.4 Phase 3 packages/pdf (c179560: 53 engine tests, 36 goldens exact, resvg raster, demo envelope 55 KB / 136 KB stored): scaffold (no DOM lib, restricted globals, vitest node, Dockerfile, CI, README), svg/sanitize allowlist + horse.svg zero-removal, render moved, Branding/Rasterizer/exportedAt/safeText/dict, exportReportArchive (T3 both logo modes), readReportArchive (filename-first, layered, attachment_stripped; T4-T6, T8), T1/T7/T9/T10 resvg/T11, xmldom bundle size ≤ 50 KB gz + - [x] 6.5 Phase 4 app (9bd5173: 222 app tests, archive kept in session, rebase + alerts, legacy PDF modules removed, xmldom ≈ 31 KB gz in the main chunk): browserRasterizer, branding.ts, export/import on the engine, rebase on import + draft restore, 2 new messages, old render/attachment/highlight code + pdf.* keys removed, report:compare on engine API, T2/T14/T15, suite migrated 1:1 + - [x] 6.6 Phase 5 docs + gates (docs synced; verifier ECARTS(31 oracle/scope) → CONFORME 13/13; security BLOCK(1) → 4 fix loops → PASS; 656 tests, build, docker ×4 green) + - [x] 6.8 user manual tests round 1 (2026-10-11): logos and picker text confirmed OK by the user after branding bundled (293a6e0) and the investigation; restore-rebase alert (e8f1734); STEP 6 VALIDATED BY USER 2026-10-11 + - [x] 6.9 closure decisions (BDR-040): re-export-archive button REFUSED for good; import headlines full/partial (62b8a43); BLK-009 byte-scan reader + no object streams (60ee712), fresh security audit + verifier; gate before external users kept in PDF_IMPORT_HARDENING.md §5 + - [ ] 6.10 finish into develop, release/0.2.0 prepped (Milestone A) — tag/merge to main on the user's go; Step 7 NOT started (UX/design discussion first) - [ ] 6.7 follow-ups recorded for Step 13: catalog asset cap aligned with the archive cap (2 MiB), allowlist sanitiser at upload, app canvas sanitiser (EVAL-011) - [ ] 5 follow-up: allowlist SVG sanitiser before Storage-served assets (Step 13); orphan findings UX (D5) at the report UX step; report:compare residuals (ZodError reason genericised, v3 lines computed once, long template lines); 16 MiB attachment cap without direct test diff --git a/.claude/tasks/contracts/2026-10-11-step-06-attachment-scan.md b/.claude/tasks/contracts/2026-10-11-step-06-attachment-scan.md new file mode 100644 index 00000000..e28a4ea1 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-11-step-06-attachment-scan.md @@ -0,0 +1,23 @@ +# CONTRACT — step-06 bounded attachment extraction (BLK-009, options A + B) +- date: 2026-10-11 | flow: ship-feature (executor, security loop) | branch: feature/step-06-pdf-archives +- status: active +- spec: docs/development/PDF_IMPORT_HARDENING.md §2-§4 + +## REQUEST (IMMUTABLE) +Remove pdf-lib's parser from the import path: locate the Faunosteo attachment by scanning the PDF bytes, inflate it with the capped native inflater, never call `PDFDocument.load` on untrusted input in the browser. Export without object streams so the Filespec name and the Info keywords stay visible to the scanner. Existing archives (with object streams) must still import. Tests include an object-stream bomb that the new reader never inflates. + +## ACCEPTANCE CRITERIA +1. `packages/pdf/src/attachment/scan.ts`: `findEmbeddedFiles(bytes: Uint8Array): EmbeddedFileCandidate[]` walks the bytes (bounded by `MAX_PDF_BYTES`) for stream dictionaries containing `/Type /EmbeddedFile` (also `/Type/EmbeddedFile` without space), reads a direct `/Length N` when present else locates `endstream`, handles `stream\r\n` and `stream\n`, records `{ offset, length, filter: 'FlateDecode' | null, name: string | null }` where `name` comes from a visible `/Filespec` dict whose `/EF << /F n 0 R >>` points at that stream's object number (object header `n 0 obj` before the dict), when visible; candidates ordered: named `osteo-report*` first, then file order. `readAttachmentBytes(bytes): Promise`: for each candidate, raw bytes (or `inflateFlate` under `MAX_ATTACHMENT_BYTES` when Flate) → first whose decoded text parses as JSON with a numeric `envelopeVersion` or `version` wins; none → `no_attachment`, or `attachment_stripped` when the bytes carry the keyword stamp (`/Keywords` followed by a literal `(…)` or hex `<…>` string decoding to a text containing `faunosteo-archive`). + CHECK: cd packages/pdf && corepack pnpm vitest run tests/scan.test.ts 2>&1 | grep -E "Tests " | tail -1 + EXPECT: Tests .* passed +2. `readReportArchive(bytes, map)` uses the scanner only: `%PDF-` header check + size cap → `invalid_pdf`; no `PDFDocument.load` anywhere under `packages/pdf/src/read.ts` or `src/attachment/`; `readAttachedDocument` becomes `readAttachedDocument(bytes: Uint8Array): Promise` (bytes, not a PDFDocument) and the compare CLI (`apps/app/scripts/compare-reports.ts`) uses it without loading the PDF. + CHECK: grep -rn "PDFDocument.load\|PDFDocument\.load" packages/pdf/src apps/app/scripts | wc -l + EXPECT: 0 +3. Export: `pdfDoc.save({ useObjectStreams: false })`; a test asserts the saved bytes contain the literal `/Type /Filespec` with `(osteo-report.json)` (or its hex) in clear and no `/Type /ObjStm`; every golden suite stays green (goldens record text/images/links only). +4. Compatibility tests (`tests/scan.test.ts` + existing `read.test.ts`): the frozen fixtures `apps/app/tests/fixtures/report-v2.full.pdf`, `report-v2.minimal.pdf`, `report-v3.bare.pdf` (all written WITH object streams) import with the same outcomes as before; a fresh envelope PDF imports; a PDF with two embedded files (a decoy `EmbeddedFile` first, then the Faunosteo one) picks the Faunosteo one; a PDF whose `/Length` is an indirect reference (craft by hand) is read through the `endstream` fallback; `\r\n` after `stream`; a foreign PDF → `no_attachment`; a stamped PDF without attachment → `attachment_stripped` (write it with `useObjectStreams: false` so the stamp is visible; also document that older stamped files with object streams fall back to `no_attachment`). +5. Bomb test: a PDF containing an object stream (`/Type /ObjStm /Filter /FlateDecode`) whose data is a deflate bomb (≥ 64 MiB of zeros compressed to a few hundred KB, built in the test with node:zlib) plus a valid Faunosteo attachment: `readReportArchive` returns the report in under 2 s and the process RSS does not grow by more than 64 MiB (measure `process.memoryUsage().rss` before/after); the same bytes also carry an attachment-sized bomb variant: an `EmbeddedFile` stream inflating past 16 MiB → `no_attachment` (inflate cancelled), never a hang. +6. Docs: `docs/PDF-FORMAT.md` "Reading an archive" step 2 (byte scan, no object-graph parse, object streams never inflated) and "Known limits" (pdf-lib removed from the import path; remaining: CLI on the same scanner, pdf-lib kept for generation, prerequisites unchanged for external users); `docs/development/PDF_IMPORT_HARDENING.md` §4 marked done with the commit, §5 unchanged. +7. Green from the root: `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run`; `git diff --quiet 8b86b92 HEAD -- apps/app/tests/fixtures/goldens`. + +## FILE SCOPE +packages/pdf/src/{attachment/scan.ts (new), attachment/read.ts, attachment/inflate.ts, read.ts, export.ts, index.ts, errors.ts}, packages/pdf/tests/** , apps/app/scripts/compare-reports.ts, apps/app/scripts/compare/report.ts, apps/app/tests/unit/scripts.compare.test.ts, apps/app/tests/unit/pdf.import.test.ts (if it loads a PDFDocument), docs/PDF-FORMAT.md, docs/development/PDF_IMPORT_HARDENING.md. Nothing else. diff --git a/.claude/tasks/contracts/2026-10-11-step-06-phase-0-freeze.md b/.claude/tasks/contracts/2026-10-11-step-06-phase-0-freeze.md new file mode 100644 index 00000000..9c12007e --- /dev/null +++ b/.claude/tasks/contracts/2026-10-11-step-06-phase-0-freeze.md @@ -0,0 +1,27 @@ +# CONTRACT — step-06 phase 0 freeze +- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives +- status: active +- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II (§17 goldens, §13 types for naming only) + +## REQUEST (IMMUTABLE) +Freeze the current PDF pipeline behaviour before any refactor: new fixtures, goldens generated once with the current code, characterisation tests of the two routes. Production code under apps/app/src is NOT modified in this phase. + +## ACCEPTANCE CRITERIA +1. Fixture `apps/app/tests/fixtures/report-v3.demo.json`: valid Report v3 on the bundled draft (ids taken from draft/document.json), 6 observations covering: main view zones, head view zone, a spine zone with vertebrae, a bilateral zone with left and right sides, a vet-referral leaf (`requiresVetReferral: true`), a leaf whose label holds an en dash (U+2013), free-text findings, severities, comment, conclusion, recommendations, nextAppointment; `sheet` = the draft ref. + CHECK: cd apps/app && corepack pnpm vitest run tests/unit/pdf.goldens.test.ts 2>&1 | tail -3 + EXPECT: Tests .* passed +2. Goldens under `apps/app/tests/fixtures/goldens/step6/` exactly as spec §17 (text/images/links per report × locale × logo mode, views per report), generated by `MAKE_GOLDEN=1 corepack pnpm vitest run tests/unit/pdf.goldens.test.ts`, then asserted by the same file without the flag. Reports: v2full, demo, v2unresolved. Logo modes: nologos, logos. + CHECK: ls apps/app/tests/fixtures/goldens/step6 | wc -l + EXPECT: >= 20 +3. Fixture `apps/app/tests/fixtures/report-v3.bare.pdf`: the demo report exported by the current code (rasteriser stubbed 1×1, no logos), produced by the same MAKE_GOLDEN run; `tests/fixtures/README.md` documents the new files and the rule "never regenerate without a user decision". + CHECK: test -s apps/app/tests/fixtures/report-v3.bare.pdf && echo ok + EXPECT: ok +4. Characterisation tests `tests/unit/routes.HomeRoute.import.test.tsx` and `tests/unit/routes.EditorRoute.export.test.tsx` as spec §17 (import mocked at module level; alert text with count; the three current error kinds + generic; navigation to /editor; export call shape; download name; failure alert). + CHECK: cd apps/app && corepack pnpm vitest run tests/unit/routes.HomeRoute.import.test.tsx tests/unit/routes.EditorRoute.export.test.tsx 2>&1 | tail -3 + EXPECT: Tests .* passed +5. Whole app suite, typecheck and lint green; no file under apps/app/src changed. + CHECK: cd apps/app && corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run 2>&1 | tail -4; git -C /home/bchanot/Documents/faunosteo status --short apps/app/src | wc -l + EXPECT: Tests .* passed ; 0 + +## FILE SCOPE +apps/app/tests/** only (new test files, fixtures, goldens, helpers, README). No change under apps/app/src, packages/**, docs/**. diff --git a/.claude/tasks/contracts/2026-10-11-step-06-phase-1-domain.md b/.claude/tasks/contracts/2026-10-11-step-06-phase-1-domain.md new file mode 100644 index 00000000..68804939 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-11-step-06-phase-1-domain.md @@ -0,0 +1,26 @@ +# CONTRACT — step-06 phase 1 domain +- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives +- status: active +- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §13 (types), §14 "Read" steps 1-3 and "Bundle", §15 caps table (snapshot + branding rows), §2.2 (lean document content) + +## REQUEST (IMMUTABLE) +Give the domain package the archive contracts (sheet snapshot, envelope v1, branding, labels), the layered reader, the report rebase, and move the sheet index into the domain; make the bundle carry the asset hashes. Pure TypeScript + Zod, no DOM, no pdf-lib. The app keeps compiling and its suite stays green through re-export shims; no app behaviour changes in this phase. + +## ACCEPTANCE CRITERIA +1. `packages/domain/src/anatomical-sheet/sheet-index.ts` holds `buildSheetIndex`, `pickLabel`, `isObservable`, `SheetIndex`, `ObservableAnnotation`, `SheetIndexSource = { ref: { documentSha256: string }; document: AnatomicalSheetDocument; assets: Readonly> }` (generic so `SheetIndex['sheet']` keeps the caller's type: `buildSheetIndex(sheet: S): SheetIndex`); `pickLabel(text, locale: 'fr' | 'en')`. `apps/app/src/services/sheetIndex.ts` becomes a re-export of it (no other app file edited for this move). + CHECK: cd apps/app && corepack pnpm typecheck && corepack pnpm vitest run tests/unit/sheets.provider.test.ts 2>&1 | tail -2 + EXPECT: passed +2. `packages/domain/src/archive/` with `snapshot.ts` (`SheetSnapshotRef`, `SheetSnapshotAsset`, `SheetSnapshot`, `SheetSnapshotSchema`, `SnapshotSource`, `buildSheetSnapshot`, `assertSnapshot`, `SnapshotError`, `SnapshotRejection`, `snapshotIndexSource(snapshot): SheetIndexSource`), `branding.ts` (`ImageAsset`, `Credit`, `Branding`, `BrandingSchema`), `labels.ts` (`PDF_LABEL_KEYS`, `PdfLabels`, `PdfLabelSet`, `PdfLabelSetSchema`), `envelope.ts` (`ENVELOPE_FORMAT`, `ENVELOPE_VERSION`, `ReportArchiveEnvelope`, `ReportArchiveEnvelopeSchema`, `ArchiveOrigin`, `ArchiveReadOutcome`, `readArchiveDocument`), `index.ts`; exported as `@faunosteo/domain/archive` (package.json exports) and from the root index. Types and behaviour exactly as spec §13/§14; `SnapshotSource = { status; ref: SheetRef; speciesId; schemaVersion; document; assets; assetHashes? }` so that `LoadedSheet` satisfies it; snapshot `ref` = `{ ...sheet.ref, schemaVersion, speciesId }`. + CHECK: cd packages/domain && corepack pnpm vitest run tests/archive.snapshot.test.ts tests/archive.envelope.test.ts tests/archive.branding-labels.test.ts 2>&1 | tail -3 + EXPECT: Tests .* passed +3. `buildSheetSnapshot(sheet, report)` is pure and deterministic: document = all views, annotations, categories, vertebral_config, name/description/scope_disclaimer/attribution/species_id/schema_version kept; `references: []`; every finding zone kept as `{ id, name, categories }` where categories are pruned to the paths referenced by the report's findings (resolved or `unresolved`): category `{ id, kind, name, description: {}, reference_ids: [], review_status, children }`, node `{ id, name, description: {}, requires_vet_referral, reference_ids: [], review_status, children }`; zones not referenced have `categories: []`; assets = every asset reachable from a view (own `svg_asset_id` or parent chain), `sha256` from `assetHashes` or null. On the draft with the fixture report `apps/app/tests/fixtures/report-v2.full.json` migrated: the document passes `AnatomicalSheetDocumentSchema` and `validateSheetDocument` returns no `error` issue; pretty JSON of the snapshot (with the SVG) is under 250,000 bytes (print the number in the test output). +4. `assertSnapshot` order: iterative depth pre-check of `finding_zones[].categories[].children` (> 8 → `caps`) → `SheetSnapshotSchema.parse` (strict wrapper; failure → `schema`) → counters (views ≤ 64, annotations ≤ 1024, nodes ≤ 8192, any LocalizedText value > 512 chars, assets ≤ 4 / ≤ 2 MiB each / ≤ 6 MiB total → `caps`) → `validateSheetDocument` has an `error` → `integrity` → a view that reaches no asset present in `assets` → `integrity`. Tests cover each reason and the happy path. +5. `readArchiveDocument(data, map)` implements spec §14 "Read" steps 1-3 exactly, with these cases tested: bare v3 → `origin 'bare_v3'`, `archive null`, counts 0; bare v2 (fixture) → `'v2'`, `migrated true`, counts from the migration; envelope v1 valid → `'envelope_v1'`, `archive` = validated envelope, `migrated false`; envelope with `envelopeVersion: 2` and report v3 → report returned, `snapshotRejected 'unsupported_envelope'`; envelope v1 with report `version: 4` → throws `UnsupportedReportVersionError` with foundVersion 4; envelope v1 with unknown extra metadata key → accepted; envelope v1 with broken branding → `'schema'`; snapshot over caps → `'caps'`; snapshot ref sheetId/documentSha256 ≠ report.sheet → `'sheet_mismatch'`; `__proto__` keys harmless; non-object → throws. +6. `packages/domain/src/report/rebase.ts`: `rebaseReportOnSheet(report, index, archived)` as spec §13; tests: same sha → untouched, `rebased false`; different sha → unknown annotation → `unresolved: true` + labels from the archived snapshot's annotation name (both locales) when the zone had none; unknown viewId → unresolved; finding with no node → unresolved; already-unresolved items stay; resolved items untouched; `report.sheet` replaced by `index.sheet.ref`; output passes `ReportSchema`. +7. Bundle: `apps/app/vite/sheet-bundle.ts` payload gains `assetHashes` (from `assets.json` `sha256` by `svg_asset_id`); `apps/app/src/sheets/provider.ts` `BundledSheetData`/`LoadedSheet` gain `assetHashes: Readonly>` and `schemaVersion: number` (from `ref.schema_version`); `parseBundledSheet` fills them; `tests/unit/sheets.provider.test.ts` asserts the hash of the horse asset equals the manifest value. +8. Green everywhere: `corepack pnpm -r typecheck && corepack pnpm -r lint && corepack pnpm -r test:run` from the repo root (domain, anatomy, supabase, app). The Phase 0 golden tests and route characterisation tests under apps/app/tests must pass unchanged. + CHECK: cd /home/bchanot/Documents/faunosteo && corepack pnpm typecheck 2>&1 | tail -2 && corepack pnpm test:run 2>&1 | grep -E "Tests|Test Files" | tail -8 + EXPECT: all passed + +## FILE SCOPE +packages/domain/** (src/anatomical-sheet/sheet-index.ts new, src/archive/* new, src/report/rebase.ts new, index files, package.json exports, tests/archive.*.test.ts, tests/report.rebase.test.ts, tests/sheet-index.test.ts), apps/app/src/services/sheetIndex.ts (re-export only), apps/app/vite/sheet-bundle.ts, apps/app/src/sheets/provider.ts, apps/app/src/sheets/virtual-sheet.d.ts if needed, apps/app/tests/unit/sheets.provider.test.ts. Nothing under apps/app/src/pdf, packages/anatomy, packages/pdf. diff --git a/.claude/tasks/contracts/2026-10-11-step-06-phase-2-compose.md b/.claude/tasks/contracts/2026-10-11-step-06-phase-2-compose.md new file mode 100644 index 00000000..43b788ba --- /dev/null +++ b/.claude/tasks/contracts/2026-10-11-step-06-phase-2-compose.md @@ -0,0 +1,25 @@ +# CONTRACT — step-06 phase 2 compose +- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives +- status: active +- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §14 "composeViewSvg", §13 (Rasterizer not in scope here) + +## REQUEST (IMMUTABLE) +Promote the Node-side view composer of the curation pipeline (`packages/anatomy/src/curation/app-review.ts`) into the shared renderer as `composeViewSvg`, with an optional highlight applied on the LayerElement tree before it becomes DOM, so the PDF engine (Phase 3) can compose a highlighted view without a browser and without querySelector. The review drawings stay byte-identical. + +## ACCEPTANCE CRITERIA +1. `packages/anatomy/src/render/compose.ts` exports `composeViewSvg(input: { root: Element; document: AnatomicalSheetDocumentInput; viewId: string; highlight?: { annotationIds: ReadonlySet; halo: boolean } }): Element` and `HALO_FILTER_ID = 'osteo-halo'`; it uses only DOM Level 2 APIs on `root` and `root.ownerDocument` (no xmldom import, no querySelector, no `el.remove()`); exported from `packages/anatomy/src/render/index.ts`. + CHECK: grep -n "querySelector\|\.remove()\|xmldom" packages/anatomy/src/render/compose.ts; echo "rc=$?" + EXPECT: rc=1 +2. Without `highlight`, output = today's `renderAppReviewDrawing` output: `curation/app-review.ts` becomes a thin caller (parse with xmldom, call `composeViewSvg`, serialise) and the committed review drawings do not drift. + CHECK: cd packages/anatomy && corepack pnpm test:run 2>&1 | tail -3 + EXPECT: Tests .* passed (including the existing golden-artifacts test) +3. With `highlight`: only layer elements whose annotation id is in `annotationIds` remain; each gets `fill="#b85a3f"`, `fill-opacity="0.85"` and, when `halo`, `filter="url(#osteo-halo)"`; no `data-*` attribute is emitted on any layer element; `` children are kept; when `halo`, a `<defs>` (created as FIRST child when the asset has none) holds the `osteo-halo` filter exactly as `apps/app/src/pdf/render/observationPage.ts:157-197` (x/y "-100%", width/height "300%", filterUnits userSpaceOnUse, feGaussianBlur stdDeviation 18 result haloWide, feGaussianBlur stdDeviation 8 result haloTight, both in=SourceGraphic, feMerge of haloWide×3, haloTight×2, SourceGraphic); the layer `<g>` is appended last; `viewBox` set from `viewBoxOf(view)` when present; `width`/`height` removed from the root. + CHECK: cd packages/anatomy && corepack pnpm vitest run tests/render.compose.test.ts 2>&1 | tail -3 + EXPECT: Tests .* passed +4. Tests (xmldom, draft document + draft horse.svg): main view with two selected annotations (one point → both hitbox and twin highlighted, one spine zone), head view (no halo), nothing selected (layer empty), unknown view throws, idempotent halo (no duplicate filter when called on a root that already has one), highlight keeps `<title>`, zero `data-` attributes in the serialised output, review-mode output byte-identical to the previous `renderAppReviewDrawing` for both views. +5. `pnpm typecheck && pnpm lint && pnpm test:run` green in packages/anatomy; no other package changed. + CHECK: git -C /home/bchanot/Documents/faunosteo status --short | grep -v "^?? packages/anatomy\|^ M packages/anatomy" | grep -v ".claude/" | wc -l + EXPECT: 0 + +## FILE SCOPE +packages/anatomy/src/render/compose.ts (new), packages/anatomy/src/render/index.ts, packages/anatomy/src/curation/app-review.ts, packages/anatomy/tests/render.compose.test.ts (new). Nothing else. diff --git a/.claude/tasks/contracts/2026-10-11-step-06-phase-3-engine.md b/.claude/tasks/contracts/2026-10-11-step-06-phase-3-engine.md new file mode 100644 index 00000000..6e68688e --- /dev/null +++ b/.claude/tasks/contracts/2026-10-11-step-06-phase-3-engine.md @@ -0,0 +1,29 @@ +# CONTRACT — step-06 phase 3 engine +- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives +- status: active (phases 1 and 2 landed) +- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §13 (packages/pdf block), §14 (Export, Label policy, View SVG, Read), §15 (caps, sanitiser, text), §17 (goldens the engine must reproduce), §3.3 + +## REQUEST (IMMUTABLE) +Create `packages/pdf` (`@faunosteo/pdf`): the browser-free PDF engine that exports a report archive from explicit inputs (report, sheet snapshot, branding, labels, locale, rasterizer, exportedAt) and reads an archive back (layered reading). Render code moves from `apps/app/src/pdf` with its behaviour frozen by the Phase 0 goldens. The app is NOT wired in this phase (Phase 4); `apps/app/src` is not modified. + +## ACCEPTANCE CRITERIA +1. Package scaffold: `packages/pdf/{package.json,tsconfig.json,vitest.config.ts,eslint.config.js,src/,tests/}` following packages/domain conventions; dependencies `pdf-lib ^1.17.1`, `@pdf-lib/standard-fonts ^1.0.0` (for `Encodings.WinAnsi`), `@faunosteo/domain workspace:*`, `@faunosteo/anatomy workspace:*`, `@xmldom/xmldom ^0.9.8`; devDependencies as domain plus `@resvg/resvg-js` (latest 2.x) and `@pdf-lib/upng ^1.0.1` (PNG decode in tests); tsconfig `lib: ["ES2022"]`, `types: ["node","vitest/globals"]`; eslint on `src/**`: `no-restricted-globals` for fetch, window, document, Image, DOMParser, XMLSerializer, navigator, Buffer, process, require and `no-restricted-imports` for patterns `@/*`, `react*`, `node:*`; vitest `environment: 'node'`. Dockerfile copies `packages/pdf/package.json`; `packages/README.md` row updated. + CHECK: cd packages/pdf && corepack pnpm typecheck && corepack pnpm lint && echo ok + EXPECT: ok +2. Public API of `packages/pdf/src/index.ts` exactly spec §13: `exportReportArchive`, `exportFromEnvelope`, `readReportArchive`, `readAttachedDocument`, `ArchiveReadError` (kinds invalid_pdf | no_attachment | attachment_stripped | incompatible_version), `ArchiveExportError` (kinds snapshot_invalid | snapshot_too_large | sheet_mismatch | too_many_pages), `Rasterizer`, `ExportInput`, `ExportResult`, `ExportWarning`, `PdfLocale`, `defaultPdfLabels`, `PDF_KEYWORD`, `MAX_PDF_BYTES`, `MAX_ATTACHMENT_BYTES`, plus `composeHighlightedViewSvg(sheet: SheetSnapshot, viewId, observation): string` for tests and the app. +3. Export behaviour = spec §14 "Export" steps 1-10 and "Label policy"; branding images: `kind 'png'` → base64 decoded with `atob` → `embedPng`; `kind 'svg'` → sanitised + rasterised at width 1200 (height from its viewBox, same clamp) → `embedPng`; each slot fails alone (`logo_failed` warning); view raster failure → page without image + `view_raster_failed`; parallel rasterisation, sequential embedding in view order; `exportedAt` drives every date; `setKeywords([PDF_KEYWORD])`; envelope attached pretty-printed as `osteo-report.json`, description `Faunosteo report archive v1`. +4. Goldens (T3): `tests/goldens.test.ts` reproduces every Phase 0 golden under `apps/app/tests/fixtures/goldens/step6/` for the three reports (v2full migrated through the draft map, demo, v2unresolved rebuilt with the same recipe as Phase 0 — reuse the recipe by reading `apps/app/tests/helpers/legacyLeaves.ts` logic, copy what you need into `tests/helpers/`), two locales, two logo modes: text entries (page, text, x, y, size, font) identical; images identical; links identical (Phase 0 recorded images and links PER LOCALE: `images.<report>.<locale>.<logos>.json`, `links.<report>.<locale>.<logos>.json`, because the footer centres the powered-by block on the label width); views facts identical except `titles` and `dataAttributes` (hidden markers are absent in the engine and the layer `<g>` loses its `data-layer`/`data-view-id`: assert `titles` ≥ highlighted count and `dataAttributes === 0` instead of the golden's 2). Logo modes: `nologos` = Branding with every logo null and credits with fallback texts, fake rasterizer returning the 1×1 PNG; `logos` = Branding built from the real `apps/app/public` files (PNG base64, Paws SVG), fake rasterizer returning the 2×1 PNG for views AND for the partner SVG (same constants and the same single stub as Phase 0, see `apps/app/tests/helpers/goldens.ts`). Compose through `composeViewSvg` from `@faunosteo/anatomy/render` (generic `root: ComposeElement`, xmldom `Element` satisfies it) with `highlight: { annotationIds, halo: view.kind === 'main' }`. Any mismatch is a visible change: do not "fix" the golden; report it. + CHECK: cd packages/pdf && corepack pnpm vitest run tests/goldens.test.ts 2>&1 | tail -3 + EXPECT: Tests .* passed +5. T1 no-sheet re-export (`tests/reexport.test.ts`): export demo from a snapshot built with `buildSheetSnapshot` on the draft loaded from `supabase/seed/anatomical-sheets/equine/draft/` → `readReportArchive` → `exportFromEnvelope` → identical text/images/views facts; envelope deep-equal minus `exportedAt`; the test file imports nothing that knows the draft after the first export (the second export receives only the envelope). +6. Read (`tests/read.test.ts`, T4 T5 T6): roundtrip envelope → `readReportArchive` → `archive` deep-equals the exported envelope, `origin 'envelope_v1'`; `apps/app/tests/fixtures/report-v2.full.pdf` and `report-v2.minimal.pdf` → `'v2'`, migrated, then re-export → import again equals; the 612-leaf v2 report (recipe from legacyLeaves) → 29 unresolved findings kept through export/import; `report-v3.bare.pdf` → `'bare_v3'`, `archive null`; envelope v2 wrapper → report kept + `snapshotRejected 'unsupported_envelope'`; envelope v1 with report v4 → `incompatible_version` foundVersion 4; bare `version: 7` → 7; a PDF with `Keywords` containing `faunosteo-archive` and no attachment → `attachment_stripped`; a foreign PDF → `no_attachment`; the Filespec named `osteo-report.json` is chosen over an earlier unrelated `EmbeddedFile` in a crafted PDF; > 50 MiB → `invalid_pdf`. +7. Security (`tests/security.test.ts`, T8): 5 assets, a 3 MiB asset, depth 9, 1,025 annotations, a view chain cycle, a dangling `svg_asset_id`, `sheet_mismatch` → report imported and `snapshotRejected` with the right reason; hostile SVG assets (`<script>`, `onload`, `javascript:` href, external `<image>`, `<!ENTITY>`, `<style>` with `url(http…)`, 257 `<use>`, root `viewBox="0 0 1 100000"`) → removed / refused / clamped as spec §15, the export still succeeds for the removable ones with the hostile parts gone, and `assertSnapshot` refuses the oversized ones at export with a typed error and no file; `__proto__` ids harmless; 24 MB inflate bomb → null (move the existing test); `horse.svg` and `Paws_in_harmony.svg` sanitise with `removed: []` and a serialisation byte-identical to the parsed input. +8. Text (`tests/text.test.ts`, T9): `safeText` keeps en dash, em dash, accented letters, `•`, `·`; replaces `⚠`, `→`, an emoji by `?`; strips `\t`, U+2028, ESC; `wrapLines` and every drawText go through it (a report with `⚠` in a comment exports without throwing); `formatDate` returns a non-ISO input unchanged. +9. Raster (`tests/raster.test.ts`, T10, resvg): a real `Rasterizer` built on `@resvg/resvg-js` (`fitTo width`) renders the demo report's main and head highlighted views: PNG width = 1200, height = requested ±1, pixels within ±24 of `#b85a3f` present, non-white ratio in [0.01, 0.9]; a rasterizer that throws yields a PDF whose page has no image and one `view_raster_failed` warning. +10. Size (T7): demo envelope attachment stored bytes (the EmbeddedFile stream `contents.length` found through `enumerateIndirectObjects`) < 250,000; the test prints stored and raw sizes for `nologos` and `logos` brandings. +11. Everything green: `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run` in packages/pdf, and `corepack pnpm -r typecheck` at the root; `apps/app/src` untouched. + CHECK: git -C /home/bchanot/Documents/faunosteo status --short apps/app/src | wc -l + EXPECT: 0 + +## FILE SCOPE +packages/pdf/** (new), Dockerfile (one COPY line), packages/README.md (one row), pnpm-lock.yaml (install). Nothing under apps/app/src, packages/domain, packages/anatomy. diff --git a/.claude/tasks/contracts/2026-10-11-step-06-phase-4-app.md b/.claude/tasks/contracts/2026-10-11-step-06-phase-4-app.md new file mode 100644 index 00000000..cee19caf --- /dev/null +++ b/.claude/tasks/contracts/2026-10-11-step-06-phase-4-app.md @@ -0,0 +1,24 @@ +# CONTRACT — step-06 phase 4 app +- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives +- status: draft (dispatched after phase 3 lands) +- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §14 "App session", "Branding in the app", §16 messages, §17 (T12/T13 kept green), Part I §7 T2/T14/T15 + +## REQUEST (IMMUTABLE) +Wire the application onto `@faunosteo/pdf`: export through the engine with a snapshot, branding and the browser rasterizer; import through the engine with layered reading, kept archive and explicit rebase; new import messages; old PDF code removed; `report:compare` on the engine read API. No visual change to pages or app layout; alerts follow the existing `window.alert` pattern. + +## ACCEPTANCE CRITERIA +1. `apps/app/src/pdf/` contains only: `export.ts` (`exportReportToPdf(report, index, { locale }): Promise<Uint8Array>` kept as the route-facing signature, implemented as `exportReportArchive({ report, sheet: buildSheetSnapshot(index.sheet, report), branding: await loadBranding(), labels: defaultPdfLabels, locale, rasterizer: browserRasterizer, exportedAt: new Date() })`, warnings → `console.warn`), `import.ts` (`importReportFromPdf(bytes, map)` returning the engine's `ArchiveReadOutcome`; `ImportError` kinds `invalid_pdf | incompatible_version | no_attachment | attachment_stripped` mapped 1:1 from `ArchiveReadError`), `browserRasterizer.ts` (today's `svgToPng.ts` adapted to `(svg, { widthPx, heightPx }) => Promise<Uint8Array>`: the engine computes the size, the adapter sets width/height on the root and draws), `branding.ts` (`loadBranding(): Promise<Branding>` per spec §14). `render/`, `attachment.ts`, `fonts.ts`, `src/anatomy/drawing.ts`'s highlight code are deleted; `drawing.ts` keeps `buildViewSvg`/`parseDrawing`/`sanitizeSvg` for the canvas (unchanged behaviour). + CHECK: ls apps/app/src/pdf + EXPECT: branding.ts browserRasterizer.ts export.ts import.ts +2. Store/persistence per spec §14 "App session": `archive: ReportArchiveEnvelope | null` in `ReportStore`, `hydrateImport({ report, archive })`, `initReport`/`reset`/`hydrateReport` clear it, `osteo:archive` key written only on those actions, `restoreDraft(index)` rebases a stale draft and restores the archive; `ArchivePersistence` beside `ReportPersistence`; tests in `state.reportStore.test.ts` extended (archive kept across a draft restore, cleared on new report, not rewritten on edits: spy on setItem). +3. `HomeRoute`: `importReportFromPdf` → `rebaseReportOnSheet(outcome.report, sheet.index, outcome.archive?.sheetSnapshot ?? null)` → `hydrateImport` → one alert composed per spec §16 (lines: migrated / archive_ok / snapshot_rejected with reason label / rebased with count) → `/editor`; error mapping adds `attachment_stripped`. `EditorRoute` export path unchanged for the user (download name, failure alert). The Phase 0 characterisation tests `routes.HomeRoute.import.test.tsx` and `routes.EditorRoute.export.test.tsx` stay green with at most these edits: the mocked outcome objects gain `origin`/`archive` fields, and the export call-shape assertion stays `(report, index, { locale })`. +4. i18n: keys of spec §16 added to fr.ts and en.ts with the given wording; `pdf.*` keys removed from both app dicts (the engine owns them; `severity.*`, `lateral.*`, `footer.*` stay, the UI uses them); `i18n.keys.test.ts` parity green. +5. `scripts/compare-reports.ts` + `scripts/compare/report.ts`: read through `readAttachedDocument` from `@faunosteo/pdf` and `readArchiveDocument` from `@faunosteo/domain/archive`; an envelope prints one extra header line `archive v1 (snapshot kept | snapshot rejected: <reason>)` under the same escaping rules; `scripts.compare.test.ts` green. +6. New tests: `pdf.export.app.test.ts` (T2: export the demo fixture through `exportReportToPdf` with the real bundled sheet, then mutate a cloned LoadedSheet's labels and one geometry, re-export the ENVELOPE through `exportFromEnvelope` and assert the engine output facts equal the first export, not the mutated sheet; T13 call shape covered by Phase 0), `pdf.goldens.test.ts` adapted so the app export path reproduces the Phase 0 goldens through the engine (same spies; the `rasterizeSvg` mock becomes a mock of `@/pdf/browserRasterizer`), `routes.HomeRoute.archive.test.tsx` (T15: envelope import with same sha → archive kept in store, archive_ok alert; envelope whose sha differs → rebased alert with count, unresolved flags, labels filled, `report.sheet` updated; snapshot rejected outcome → snapshot_rejected alert with the reason label; `attachment_stripped` → its error message), `migration.leaves.test.ts` kept green (612 leaves through the new path). +7. Bundle cost: `SHEET_BUNDLE=draft corepack pnpm build` in apps/app succeeds; report the gzip size of the main JS chunk before (from `git stash`-free method: build develop in a worktree is NOT allowed; instead read the size printed by vite for the chunk containing xmldom and report the total gz of dist/assets/*.js) and the size of the xmldom portion if vite's output isolates it; ceiling 50 KB gz for xmldom's share, else report. +8. Green: from the repo root `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run && corepack pnpm build`; `grep -rn "fetch(" apps/app/src/pdf` shows only `branding.ts`. + CHECK: cd /home/bchanot/Documents/faunosteo && corepack pnpm test:run 2>&1 | grep -E "Test Files|Tests " | tail -8 + EXPECT: all passed + +## FILE SCOPE +apps/app/src/pdf/**, apps/app/src/anatomy/drawing.ts (removal of highlight-only code if any), apps/app/src/app/routes/{HomeRoute,EditorRoute,NewReportRoute}.tsx (minimal), apps/app/src/state/{reportStore,persistence}.ts, apps/app/src/i18n/{fr,en}.ts, apps/app/scripts/**, apps/app/package.json (dependency `@faunosteo/pdf: workspace:*`, drop `pdf-lib` only if no app code imports it anymore), apps/app/tests/** (adaptations named above; goldens JSON files never edited), CLAUDE.md folder map lines for apps/app/src/pdf (keep docs minimal; Phase 5 owns the docs). Nothing under packages/**. diff --git a/.claude/tasks/contracts/2026-10-11-step-06-security-fix-2.md b/.claude/tasks/contracts/2026-10-11-step-06-security-fix-2.md new file mode 100644 index 00000000..a3d7b6e5 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-11-step-06-security-fix-2.md @@ -0,0 +1,17 @@ +# CONTRACT — step-06 security fix 2 (after re-audit PASS with 2 MEDIUM) +- date: 2026-10-11 | flow: ship-feature (executor, security loop) | branch: feature/step-06-pdf-archives +- status: active + +## REQUEST (IMMUTABLE) +Close the two MEDIUM findings of the second audit without changing any page output: (1) the `/URI` written as `PDFHexString.fromText` is UTF-16BE with a BOM, so poppler-based viewers read a dead link (`þÿ…`); write the URL's ASCII bytes as a hex string instead, keeping the injection protection; (2) the PNG budget reads only the first IHDR while UPNG honours the last one: walk the chunk list, require exactly one IHDR (length 13) as the first chunk, refuse any later IHDR and the APNG chunks `acTL`, `fcTL`, `fdAT`. + +## ACCEPTANCE CRITERIA +1. `packages/pdf/src/render/linkAnnotation.ts` writes `URI: PDFHexString.of(<hex of the ASCII bytes>)`; a test asserts the saved bytes contain the hex form of `https://faunosteo.com` (uppercase or lowercase hex, no `FEFF`), that a reload through pdf-lib decodes `/URI` to the URL, and that the injection payload (cast past the schema) still yields no `/JavaScript`, `/Next` or `/JS` in the bytes. A character above 0x7e in the URL throws (the schema already refuses it) — test. + CHECK: cd packages/pdf && corepack pnpm vitest run tests/security.test.ts tests/goldens.test.ts 2>&1 | grep -E "Tests " | tail -1 + EXPECT: Tests .* passed +2. `packages/pdf/src/branding.ts` `pngHeaderIssue` walks chunks (length, type, data, CRC) until `IEND` or the end of the buffer: first chunk must be `IHDR` with length 13; any further `IHDR`, or `acTL`/`fcTL`/`fdAT`, or a chunk length that overruns the buffer → issue; the existing side/pixel caps stay. Tests: doubled IHDR (1×1 then 10000×10000) refused, APNG with `acTL` refused, truncated chunk length refused, the four real `public/` logos and the two fixture PNGs accepted; the export-level test asserts a doubled-IHDR header logo gives exactly `[{ kind: 'logo_failed', slot: 'headerLogo' }]` and `embedPng` never receives it. +3. `docs/PDF-FORMAT.md`: the PNG sentence says the chunk list is walked and a second IHDR or APNG chunk is refused (replace any "never decoded" wording); "Known limits" names the browser rasterizer (`apps/app/src/pdf/browserRasterizer.ts`) as the production path whose `<use>` expansion limits are not measured. +4. Green from the root: `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run`; `git diff --quiet 8b86b92 HEAD -- apps/app/tests/fixtures/goldens` (goldens untouched); link goldens still pass in both packages (the readers decode hex strings). + +## FILE SCOPE +packages/pdf/src/render/linkAnnotation.ts, packages/pdf/src/branding.ts, packages/pdf/tests/security.test.ts (and tests/helpers if a reader needs the ASCII-hex form), docs/PDF-FORMAT.md. Nothing else. diff --git a/.claude/tasks/contracts/2026-10-11-step-06-security-fix.md b/.claude/tasks/contracts/2026-10-11-step-06-security-fix.md new file mode 100644 index 00000000..10abc0b1 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-11-step-06-security-fix.md @@ -0,0 +1,23 @@ +# CONTRACT — step-06 security fix (after SECURITY BLOCK(1) + MEDIUM/LOW findings) +- date: 2026-10-11 | flow: ship-feature (executor, security loop) | branch: feature/step-06-pdf-archives +- status: verified (CONFORME on substance after oracle fix; security re-audit pending) + +## REQUEST (IMMUTABLE) +Close the HIGH finding (PDF object injection through an archived branding URL) at the sink and at the schema, and the cheap MEDIUM/LOW findings listed below. No behaviour change for valid inputs: the Step 6 goldens must stay green. Findings deferred with a documented limit: pdf-lib uncapped object-stream inflation (pre-existing, needs a Worker or a pre-scan that would refuse our own PDFs), `<use>` nesting expansion (resvg already refuses), Report v3 collection caps on read. + +## ACCEPTANCE CRITERIA +1. HIGH sink: `packages/pdf/src/render/linkAnnotation.ts` writes the URI as `PDFHexString.fromText(url)` (or escapes `\`, `(`, `)` and refuses control characters) so no URL can close the string literal; a test exports a PDF whose branding URL is `https://a.example/) /Next << /S /JavaScript /JS (app.alert\(1\)) >> /Z (` through `exportFromEnvelope` AFTER bypassing the schema with a cast, reloads the bytes with pdf-lib and asserts no `/JavaScript` action exists and the link's `/URI` decodes to the full original string (or the export is refused by criterion 3, in which case the test asserts the typed refusal and a second test proves the sink escaping on a URL with `)` that the schema accepts, if any). + CHECK: cd packages/pdf && corepack pnpm vitest run tests/security.test.ts 2>&1 | grep -E "Tests " | tail -1 + EXPECT: Tests .* passed + EVIDENCE: 2026-10-11 verifier pass 1 ECARTS(1) = this oracle (`tail -2` kept only the Duration line), behaviour MET (33/33, sink + schema + refusal tests read). Oracle corrected by the orchestrator; literal run → `Tests 33 passed (33)`. MET. +2. Schema: `HttpUrlSchema` in `packages/domain/src/archive/branding.ts` accepts only `^https?://[^\s()\\<>"'\x00-\x1f\x7f]+$` (ASCII, no parentheses, backslash, quotes, angle brackets, whitespace, control characters) and ≤ 2048 chars; the current real URLs (`https://faunosteo.com`, `https://zenquality.fr`, `https://www.instagram.com/paws.iin.harmony`) pass; domain tests cover accept/reject. +3. Export re-validates its inputs: `exportReportArchive` runs `BrandingSchema.parse(input.branding)` and `PdfLabelSetSchema.parse(input.labels)` first; a failure → `ArchiveExportError('branding_invalid')` (new kind, documented) before any page is drawn; test. +4. PNG budget: `packages/pdf/src/branding.ts` reads the PNG IHDR (signature + width/height at bytes 16-23) before `embedPng`; refuse when width × height > 16,777,216 (4096²) or either side > 8192, or when the signature is wrong → that slot fails alone with a `logo_failed` warning; test with a crafted IHDR. +5. Sanitiser hardening in `packages/pdf/src/svg/sanitize.ts`: any attribute value containing a backslash `\` is removed; in `style` attributes and in every presentation attribute, any `(` not part of `url(#` is refused (attribute removed); `image-set(`, `expression(`, `@import`, `javascript:`, `behavior:` refused as today. `horse.svg` and `Paws_in_harmony.svg` still sanitise with `removed: []` (existing test stays green); new tests for `u\72l(`, `image-set(`, `fill="u\72l(http://evil/x)"`. +6. NaN guard: `packages/pdf/src/svg/view.ts` raster size uses `Number.isFinite` on the view box numbers; a non-finite or ≤ 0 box falls back to the 0.6 ratio; test with `viewBox="0 0 1e999 1e999"` → a valid size, no NaN. +7. `apps/app/src/app/routes/HomeRoute.tsx` checks `file.size > MAX_PDF_BYTES` before `arrayBuffer()` and maps it to the `invalid_pdf` message; route test updated (`routes.HomeRoute.import.test.tsx` gains one case, others unchanged). +8. `docs/PDF-FORMAT.md` "Limits" gains: the URL rule, the PNG budget, and a "Known limits" paragraph: pdf-lib inflates PDF object streams without a cap when loading (a crafted PDF of a few hundred KB can expand to hundreds of MB in the tab; mitigation planned: parse in a Worker or locate the attachment without a full load), `<use>` expansion bounded by the rasterizer, Report collections not capped on read (export refuses above 500 observations). +9. Green: `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run` from the root; goldens untouched (`git diff --stat 8b86b92 HEAD -- apps/app/tests/fixtures/goldens` empty). + +## FILE SCOPE +packages/pdf/src/{render/linkAnnotation.ts,export.ts,errors.ts,branding.ts,svg/sanitize.ts,svg/view.ts,index.ts}, packages/pdf/tests/**, packages/domain/src/archive/branding.ts, packages/domain/tests/archive.branding-labels.test.ts, apps/app/src/app/routes/HomeRoute.tsx, apps/app/tests/unit/routes.HomeRoute.import.test.tsx, docs/PDF-FORMAT.md. Nothing else. diff --git a/.claude/tasks/contracts/2026-10-11-step-06-verify.md b/.claude/tasks/contracts/2026-10-11-step-06-verify.md new file mode 100644 index 00000000..aaf43154 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-11-step-06-verify.md @@ -0,0 +1,51 @@ +# CONTRACT — step-06 autonomous PDF archives (whole step, for the fresh verifier) +- date: 2026-10-11 | flow: ship-feature | branch: feature/step-06-pdf-archives +- status: active +- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md (Part II binding), docs/PDF-FORMAT.md; phase contracts 2026-10-11-step-06-phase-{0,1,2,3,4}-*.md + +## REQUEST (verbatim user requirements, 2026-10-11 — IMMUTABLE) +Un PDF Faunosteo doit rester lisible, interprétable et réexportable dans le futur, même si : la fiche anatomique originale a disparu ; le catalogue de constats a changé ; les identifiants ou les traductions ont évolué ; le logo Faunosteo a changé ; les ressources du site ne sont plus disponibles ; le bilan contient des éléments hérités ou non résolus. L'export ne doit nécessiter aucun chargement réseau. Preuve automatisée des scénarios : (1) exporter un bilan v3, supprimer l'accès à sa fiche actuelle, puis l'importer et le réexporter depuis son instantané ; (2) modifier le catalogue anatomique courant sans affecter l'interprétation des anciennes archives ; (3) modifier le branding courant sans altérer les ressources historiques d'une archive réexportée ; (4) importer un PDF v2, migrer son bilan et conserver ses éventuels éléments non résolus ; (5) comparer le contenu et le rendu des PDF FR/EN aux références enregistrées avant la refactorisation ; (6) rejeter proprement les instantanés dangereux, invalides ou excessivement volumineux, sans perdre les données récupérables du bilan ; (7) vérifier qu'aucun chargement réseau n'est nécessaire à la génération ; (8) tester la rasterisation réelle des SVG. Aucun changement graphique des pages. Instantané importé conservé en session, rebase explicite sur copie de travail. Messages FR/EN explicites, jamais une importation dégradée présentée comme parfaite. + +## ACCEPTANCE CRITERIA +1. Scenario 1 (no-sheet re-export) is a test in packages/pdf that re-exports from the envelope alone and compares text/images/views facts. + CHECK: grep -ln "exportFromEnvelope" packages/pdf/tests/*.test.ts | wc -l; cd packages/pdf && corepack pnpm vitest run tests/reexport.test.ts 2>&1 | tail -2 + EXPECT: >= 1 ; passed +2. Scenario 2 (catalog changed) is a test in apps/app that mutates the loaded sheet (labels + geometry) and proves the envelope re-export ignores it. + CHECK: grep -n "mutat\|renamed\|changed sheet\|exportFromEnvelope" apps/app/tests/unit/pdf.export.app.test.ts | head -3; cd apps/app && corepack pnpm vitest run tests/unit/pdf.export.app.test.ts 2>&1 | tail -2 + EXPECT: matches ; passed +3. Scenario 3 (branding changed) — the envelope carries `branding` and `labels`, and `exportFromEnvelope` uses them, not the caller's current branding: a test exports with branding A, re-exports the envelope while branding B is the app's current one, and the images/links/text of the re-export equal the first export. + CHECK: grep -rn "branding" packages/pdf/tests/reexport.test.ts apps/app/tests/unit/pdf.export.app.test.ts | grep -i "differ\|current\|B\b\|other" | head -3 + EXPECT: at least one assertion that the re-export does not use the current branding (if absent → ECART) +4. Scenario 4 (v2 import with unresolved items kept): v2 fixtures and the 612-leaf report import, unresolved items survive export → import. + CHECK: cd packages/pdf && corepack pnpm vitest run tests/read.test.ts 2>&1 | tail -2; cd ../../apps/app && corepack pnpm vitest run tests/unit/migration.leaves.test.ts 2>&1 | tail -2 + EXPECT: passed ; passed +5. Scenario 5 (goldens): the 39 Phase 0 goldens are unchanged in git since commit 8b86b92 and reproduced by the engine (packages/pdf/tests/goldens.test.ts) and by the app path (apps/app/tests/unit/pdf.goldens.test.ts). + CHECK: git diff --stat 8b86b92 HEAD -- apps/app/tests/fixtures/goldens | tail -1; cd packages/pdf && corepack pnpm vitest run tests/goldens.test.ts 2>&1 | tail -2; cd ../../apps/app && corepack pnpm vitest run tests/unit/pdf.goldens.test.ts 2>&1 | tail -2 + EXPECT: empty diff ; passed ; passed +6. Scenario 6 (hostile/oversized snapshots rejected, report kept): security tests cover caps, cycles, dangling asset, sheet_mismatch, hostile SVG, entity, use bomb, viewBox bomb, inflate bomb, __proto__; every rejection keeps `report`. + CHECK: cd packages/pdf && corepack pnpm vitest run tests/security.test.ts 2>&1 | grep -E "Tests|✓|passed" | tail -3; grep -cE "^\s*\[?'(five assets|3 MiB|depth 9|1,?025|cycle|dangling|sheet_mismatch)|reason: '" packages/pdf/tests/security.test.ts + EXPECT: 20 passed ; the rejection table lists the 7 cases (count ≥ 7 rows carrying a `reason:`), each asserted to keep `outcome.report` (one shared assertion over the parametrised table is accepted) +7. Scenario 7 (no network): packages/pdf has no `fetch`/DOM usage (lint rule + grep) and its suite runs in vitest `node` environment; the only `fetch(` under apps/app/src/pdf is in branding.ts. + CHECK: grep -rnE "\bfetch\(|\bwindow\.|globalThis\.document|\bnew Image\(|navigator\." packages/pdf/src | wc -l; grep -rln "from '@xmldom/xmldom'" packages/pdf/src | wc -l; grep -rnE "DOMParser|XMLSerializer" packages/pdf/src -l | xargs grep -L "@xmldom/xmldom" | wc -l; grep -rln "fetch(" apps/app/src/pdf; grep -n "environment" packages/pdf/vitest.config.ts; grep -c "no-restricted-globals" packages/pdf/eslint.config.js + EXPECT: 0 ; >= 1 ; 0 (every file using DOMParser/XMLSerializer imports them from xmldom) ; apps/app/src/pdf/branding.ts only ; node ; >= 1 +8. Scenario 8 (real raster): resvg-based test renders main and head views with dimension and highlight-colour assertions. + CHECK: cd packages/pdf && corepack pnpm vitest run tests/raster.test.ts 2>&1 | tail -2 + EXPECT: passed +9. Pages unchanged: no edit to render constants/layout beyond the move (compare `packages/pdf/src/render/*.ts` against `git show 8b86b92:apps/app/src/pdf/render/*.ts` — differences limited to imports, labels source, SheetIndex source, rasterizer call, safeText); goldens green (criterion 5). +10. Session: store holds `archive`, persisted under `osteo:archive` only on hydrateImport/hydrateReport/initReport/reset; `rebaseReportOnSheet` runs on import and draft restore; tests exist. + CHECK: grep -n "osteo:archive\|hydrateImport\|rebaseReportOnSheet" apps/app/src/state/*.ts apps/app/src/app/routes/HomeRoute.tsx apps/app/src/app/routes/EditorRoute.tsx | wc -l + EXPECT: >= 5 +11. Messages: fr.ts and en.ts carry `home.import.archive_ok`, `home.import.snapshot_rejected`, five `home.import.snapshot_reason.*`, `home.import.rebased`, `home.import.error_attachment_stripped`; HomeRoute composes them; i18n parity test green; `pdf.*` keys gone from the app dicts. + CHECK: grep -c "home.import.snapshot_reason\." apps/app/src/i18n/fr.ts apps/app/src/i18n/en.ts; grep -c "'pdf\." apps/app/src/i18n/fr.ts + EXPECT: 5 5 ; 0 +12. Whole workspace green and buildable: `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run && corepack pnpm build` from the root; `docker build -t faunosteo-step6 .` succeeds. + EVIDENCE: 2026-10-11 orchestrator: root typecheck/lint/test:run (154+21+130+53+222 = 580 tests) and build rc 0 at 9bd5173; `docker build -t faunosteo-step6 .` exit 0 (log in the session scratchpad, image tagged). MET. +13. Docs: docs/PDF-FORMAT.md describes envelope v1, snapshot content, layered reading, rebase, caps, sizes; CLAUDE.md folder map lists packages/pdf and the new apps/app/src/pdf files; CHANGELOG has the Step 6 entry; DEPLOY.md has the rollback note. + CHECK: grep -c "envelopeVersion\|snapshotRejected\|rebase" docs/PDF-FORMAT.md; grep -n "packages/pdf" CLAUDE.md | head -2 + EXPECT: >= 3 ; present + +## CLARIFICATIONS +- 2026-10-11 (orchestrator, after verifier pass 1 ECARTS(31): oracle defects + scope): CHECKs of criteria 6 and 7 rewritten above (the behaviour was met, the oracles counted the wrong thing). FILE SCOPE widened below to the structurally necessary files. Deleted tests authorised: `apps/app/tests/unit/pdf.attachment.test.ts` → replaced by `packages/pdf/tests/read.test.ts` (roundtrip, no_attachment, oversized) and `apps/app/tests/unit/pdf.import.test.ts`; `pdf.attachment.inflate.test.ts` → `packages/pdf/tests/security.test.ts` (inflate bomb); `pdf.svgToPng.test.ts` → `apps/app/tests/unit/pdf.browserRasterizer.test.ts`. The spec (Part II §18, Phase 4 contract criterion 1) planned the removal of the legacy modules with their tests. + +## FILE SCOPE +packages/pdf/**, packages/domain/** (src/archive, src/report/rebase.ts, src/anatomical-sheet/sheet-index.ts, barrels, package.json, tests), packages/anatomy/src/render/{compose,index}.ts, packages/anatomy/src/curation/app-review.ts, packages/anatomy/tests/render.compose.test.ts, apps/app/package.json, apps/app/src/services/sheetIndex.ts, .claude/** (memory, TODO, contracts), apps/app/src/pdf/**, apps/app/src/state/**, apps/app/src/app/routes/{HomeRoute,EditorRoute}.tsx, apps/app/src/i18n/{fr,en}.ts, apps/app/src/sheets/provider.ts, apps/app/vite/sheet-bundle.ts, apps/app/scripts/**, apps/app/tests/**, docs/**, CLAUDE.md, README.md, CHANGELOG.md, DEPLOY.md, Dockerfile, packages/README.md, pnpm-lock.yaml. diff --git a/CHANGELOG.md b/CHANGELOG.md index d23809e1..5abaeeb9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,9 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] -### Added (SaaS migration, plan Steps 3–4) +### Added (SaaS migration, plan Steps 3–6) +- **Autonomous PDF archives (Step 6)** — new `@faunosteo/pdf` engine (`packages/pdf`): the PDF is rendered from explicit inputs (report, sheet snapshot, branding, labels, locale, rasterizer, export date), with no network and no browser DOM; the attachment becomes a **report archive envelope v1** (`osteo-report.json`) carrying the Report v3, a lean but valid snapshot of the anatomical sheet (views, annotations, geometry, colours, relations, the finding paths used with their ancestor labels, the SVG drawing), the branding used at export and the FR/EN label dictionary, so an old bilan is reproduced identically after any catalog, wording or logo change. Layered reading keeps the report even when the wrapper or the snapshot is refused (closed reasons), v2 and bare v3 PDFs still import, a PDF whose attachment was stripped is recognised. Imported archives are kept in the session; a bilan reopened on a different sheet is rebased on a working copy with unresolved items flagged and their labels kept, and the import message says so. SVG assets go through an allowlist sanitiser with size and complexity caps checked at import and at export; a WinAnsi guard keeps any text from crashing the export. Pages unchanged (frozen by 39 goldens). `docs/PDF-FORMAT.md` written for real. - **Supabase foundation** — local stack (`supabase/config.toml`), migrations (schemas `private` / `audit`, `profiles`, platform roles with audited RPCs), pgTAP suite run on PGlite (`pnpm test:run`) and on the real stack (`pnpm db:test`), `@faunosteo/supabase` typed client + generated types. No UI change. - **Anatomical sheet model** — `@faunosteo/domain`: canonical sheet document (views tree, annotations with stable ids and explicit laterality, ordered vertebral regions, typed finding categories, explicit annotation → finding zone links, FR/EN labels) with integrity validation; tables `species`, `anatomical_sheets`, `anatomical_sheet_versions` (published rows immutable, one draft per sheet, deletion preconditions), `anatomical_sheet_assets`; lifecycle RPCs (create, draft, publish, deprecate, delete, fork with provenance, archive, assets) audited and under RLS. Spec: `docs/development/ANATOMICAL_SHEET_MODEL.md`. diff --git a/CLAUDE.md b/CLAUDE.md index d21c1166..8bc402f3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -17,7 +17,12 @@ audit log exist; Step 4 added the canonical anatomical sheet model (`packages/do tables `species`, `anatomical_sheets` / `_versions` / `_assets`). Step 5 moved the application onto that model: the editor renders the bundled reference sheet (the curated equine DRAFT, `SHEET_BUNDLE=draft`), writes Report v3 and imports v2 PDFs -through a generated migration map. The Supabase client is still unused by the UI. +through a generated migration map. Step 6 made the PDF an autonomous archive: the +`packages/pdf` engine renders from explicit inputs (report, sheet snapshot, branding, +labels, rasterizer) with no network and no DOM, and the attachment is an envelope v1 +carrying the report, a lean sheet snapshot, the branding and the labels used, so an old +bilan is reproduced identically after any catalog, wording or logo change +(`docs/PDF-FORMAT.md`). The Supabase client is still unused by the UI. MVP species: equine only. Open-source MIT. --- @@ -148,10 +153,11 @@ pnpm format # Prettier write ``` faunosteo/ ├─ apps/app/ ← @faunosteo/app (everything below until packages/) -├─ public/ ← logos only (no anatomy asset: the sheet is bundled) +├─ public/ ← favicons, env.js, site header logo only (PDF logos live in src/assets/brand; no anatomy asset) ├─ vite/sheet-bundle.ts ← Vite plugin: `virtual:faunosteo-sheet` (SHEET_BUNDLE=draft|none) ├─ scripts/compare-reports.ts ← `pnpm report:compare`: archive PDF vs v3 reading (pure part in scripts/compare/report.ts) ├─ src/ +│ ├─ assets/brand/ ← the four PDF branding logos, bundled by Vite (?inline / ?raw / ?url), never fetched │ ├─ app/ │ │ ├─ App.tsx ← root router │ │ ├─ routes/{Home,NewReport,Editor,NotFound}Route.tsx @@ -180,9 +186,9 @@ faunosteo/ │ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,EditInfosDialog,DisclaimerDialog, │ │ │ ConclusionPanel,NextAppointmentPicker}.tsx │ │ └─ brand/{Brand,AppHeader,Footer,LanguageSwitcher}.tsx -│ ├─ pdf/ -│ │ ├─ export.ts + import.ts + attachment.ts + fonts.ts -│ │ └─ render/{header,footer,observationPage,conclusionPage,svgToPng,text,logo,linkAnnotation}.ts +│ ├─ pdf/ ← app side of @faunosteo/pdf (engine in packages/pdf) +│ │ ├─ export.ts + import.ts ← exportReportToPdf (sheet snapshot + branding + browser rasterizer → engine), importReportFromPdf (ArchiveReadOutcome, ImportError kinds) +│ │ └─ branding.ts + browserRasterizer.ts ← bundled src/assets/brand logos (?inline / ?raw) → Branding; Image/canvas Rasterizer adapter │ ├─ lib/{dates,id,assert,supabase}.ts ← supabase.ts: getSupabaseClient() | null │ ├─ styles/{index,tokens}.css ← Tailwind v4 CSS-first │ └─ main.tsx @@ -201,10 +207,11 @@ faunosteo/ ├─ eslint.config.js, index.html, package.json (@faunosteo/app) ├─ tsconfig*.json, vite.config.ts, vitest.config.ts │ (end of apps/app) -├─ packages/domain/ ← @faunosteo/domain (pure, no DOM, zod only) +├─ 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 (`./render`) +├─ packages/anatomy/ ← @faunosteo/anatomy: legacy importer, curation pipeline, pure annotation-layer renderer + view composer (`./render`) +├─ 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 │ └─ tests/ ← counts preserved, special cases, determinism, curation ops, golden artifacts @@ -250,19 +257,23 @@ SVG interaction → open_vertebra_picker / open_laterality_picker → pickers → reducers (ensureZone, addSides, syncVertebrae) → toggle / remove_both_sides → updateObservation() in store -PDF export - → exportReportToPdf(report, sheet, { locale }) - → pdf-lib PDFDocument - → embedFonts (Helvetica body + TimesRoman heading — WinAnsi StandardFonts; TTF Inter/Fraunces planned) - → for each observation: addObservationPage (rasterize SVG → PNG) - → addConclusionPage - → attachReportJson (native EmbeddedFiles) - → Uint8Array → browser download +PDF export (app side: apps/app/src/pdf, engine: packages/pdf) + → exportReportToPdf(report, index, { locale }) + → buildSheetSnapshot(index.sheet, report) + loadBranding() (4 logos bundled at build time, no network) + defaultPdfLabels + → exportReportArchive({ report, sheet, branding, labels, locale, rasterizer: browserRasterizer, exportedAt }) + assertSnapshot (caps, integrity, sheet invariant) → fonts (WinAnsi StandardFonts, safeText guard) + → per observation: composeHighlightedViewSvg (xmldom: sanitise allowlist → composeViewSvg highlight) → rasterizer → page + → conclusion page, footer, envelope v1 attached as osteo-report.json, Keywords faunosteo-archive/1 + → { pdf, envelope, warnings } → { pdf, warnings } to EditorRoute → browser download, alert naming failed logo slots / views + → exportFromEnvelope(envelope, …) re-exports an archive from its own snapshot, branding and labels (no sheet) PDF import - → importReportFromPdf(bytes, migrationMap) - → extractReportJson → readReportDocument (v3 as is, v2 migrated, else incompatible_version) - → hydrateReport() → navigate /editor (unresolved zones/findings kept and flagged) + → importReportFromPdf(bytes, migrationMap) → readReportArchive (engine) + → byte scan for the EmbeddedFile stream (no pdf-lib parse on untrusted bytes, BLK-009): named osteo-report* first, + capped native inflation → layered reading: report (v3 as is, v2 migrated, else incompatible_version), + envelope metadata tolerant, snapshot/branding/labels strict → archive kept or snapshotRejected (closed reason) + → rebaseReportOnSheet(report, index, archivedSnapshot) when the loaded sheet differs (unresolved flags, labels kept) + → hydrateImport({ report, archive }) → one alert (archive_ok / snapshot_rejected / rebased / migrated) → navigate /editor Runtime config → Docker entrypoint writes env.js (window.__APP_CONFIG__) @@ -295,7 +306,7 @@ Database (Supabase) - Get the translate function in any component: `const t = useT()` then `t('common.cancel')` - `src/state/localeStore.ts` holds current `Locale` (`'fr' | 'en'`), persisted to `localStorage` key `osteo:locale`; default: navigator-detected `fr`/`en`, or `'fr'` if no match - Zone and finding names shown in the editor and the PDF come from the sheet document (`{ fr, en }` labels) and from the report's snapshots, not from the dict -- PDF static labels (section headings, metadata) come from the dict via `getDict(locale)` in `exportReportToPdf` +- PDF static labels (section headings, metadata) live in the engine (`packages/pdf/src/i18n`, `defaultPdfLabels`, 25 keys) and are archived in the envelope; the app dicts hold no `pdf.*` key ### Identity strings - NEVER hardcode APP_SITE_NAME, APP_BRAND_NAME, APP_FOOTER_NAME, APP_TAGLINE @@ -322,13 +333,15 @@ Database (Supabase) ### Stores - No direct store mutation outside Zustand actions - No business logic in components — delegate to store actions -- sessionStorage key: osteo:draft (auto-saved on every change, v3; a v2 draft is migrated on restore once the sheet is loaded) +- sessionStorage keys: osteo:draft (auto-saved on every change, v3; a v2 draft is migrated and a stale draft rebased on restore once the sheet is loaded) and osteo:archive (the imported archive envelope, written only on import / new report / reset, never on edits) - localStorage key: osteo:lastPractitioner (practitioner prefill cache) ### PDF - A4 portrait: 595.28 × 841.89 pt - No raw URLs in PDF output — abbreviated citations only -- JSON attachment filename must start with osteo-report; content = Report v3; import accepts v2 (migrated) and v3 +- JSON attachment filename must start with osteo-report; content = report archive envelope v1 (report v3 + sheet snapshot + branding + labels); import accepts bare v2 (migrated), bare v3 and envelope v1; a bad snapshot never loses the report +- The engine (`packages/pdf`) has no DOM lib, no fetch, no Node-only global (lint-enforced); rasterisation is an injected adapter; every SVG it receives is sanitised by allowlist with caps +- Page layout is frozen by the Step 6 goldens: any visible change needs a user decision and a golden regeneration - Fonts are StandardFonts (Helvetica/TimesRoman, WinAnsi encoding) — TTF Inter/Fraunces planned but not yet embedded. Any non-Latin-1 glyph in PDF text must use an ASCII surrogate until the TTF migration lands (e.g. `(!)` instead of `⚠`). ### Anatomical sheet content @@ -417,8 +430,9 @@ Database (Supabase) - Annotation rendering changes require updating docs/ANNOTATION-RENDERING.md first. - Never modify the legacy sources under `supabase/seed/anatomical-sheets/equine/legacy-sources/` — they are the importer's input (the user's historical files). -- Ask before any change to importReportFromPdf, extractReportJson or readAttachedDocument — these handle user data. -- After PDF roundtrip tests fail: check attachment bytes, then Zod validation (v3, or v2 through the migration map), then DecompressionStream inflation. +- Ask before any change to `readReportArchive`, `readArchiveDocument`, `readAttachedDocument` or `rebaseReportOnSheet` — they handle user data; archive readers never drop a schema version (envelope v1, Report v2/v3, sheet document v2). +- Import never parses untrusted PDF object graphs: the attachment is located by byte scan and inflated under the 16 MiB cap (BLK-009). Opening the import to external users is gated by `docs/development/PDF_IMPORT_HARDENING.md` §5 (BDR-040). +- After PDF roundtrip tests fail: check attachment bytes, then the layered reader (report first, envelope metadata, snapshot/branding/labels), then DecompressionStream inflation. Goldens under `apps/app/tests/fixtures/goldens/step6` are never regenerated without a user decision. - Node 24 / pnpm 10.13.1: `corepack enable` or `corepack pnpm`; never a global install. - SQL change: `pnpm --filter @faunosteo/supabase test:run` (PGlite) before commit; `pnpm db:reset && pnpm db:test` on the real stack when Docker is available; regenerate types (`pnpm db:types`). diff --git a/DEPLOY.md b/DEPLOY.md index c971bb34..d4016952 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -242,6 +242,12 @@ For zero-downtime updates, `docker compose up --build -d` rebuilds the image then recreates the container; the container restart is sub-second because nginx:alpine boots instantly. There is no warmup phase. +Rollback note (PDF archives, Step 6): PDFs exported by a Step 6 build carry +a report archive envelope. A build older than Step 6 reads such a PDF as "no +attachment"; a Step 6 build reads every older PDF (bare v2 and v3). Roll back +only with that limit in mind and tell the practitioners which build produced +their files. + --- ## Data persistence diff --git a/Dockerfile b/Dockerfile index e5ae5525..e66a3733 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,6 +13,7 @@ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./ COPY apps/app/package.json apps/app/ COPY packages/domain/package.json packages/domain/ COPY packages/anatomy/package.json packages/anatomy/ +COPY packages/pdf/package.json packages/pdf/ COPY packages/supabase/package.json packages/supabase/ RUN pnpm install --frozen-lockfile diff --git a/README.md b/README.md index c075f883..7b2caccc 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,9 @@ For production deployment (VPS provisioning, firewall, TLS, nginx reverse proxy, - [docs/ANNOTATION-RENDERING.md](docs/ANNOTATION-RENDERING.md) — annotation layer contract (markers drawn from the sheet document) - [docs/development/ANATOMICAL_SHEET_MODEL.md](docs/development/ANATOMICAL_SHEET_MODEL.md) — canonical anatomical sheet document, curation pipeline, report migration map - [docs/development/STEP5_MIGRATION_ANALYSIS.md](docs/development/STEP5_MIGRATION_ANALYSIS.md) — how the application moved onto the canonical sheet (Report v3) -- [docs/PDF-FORMAT.md](docs/PDF-FORMAT.md) — PDF page layout and attachment contract +- [docs/PDF-FORMAT.md](docs/PDF-FORMAT.md) — PDF pages, report archive envelope (snapshot, branding, labels), reading and limits +- [docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md](docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md) — why and how the PDF became an autonomous archive (Step 6) +- [docs/development/PDF_IMPORT_HARDENING.md](docs/development/PDF_IMPORT_HARDENING.md) — PDF import against decompression bombs: what lands now, what is required before external users - [docs/development/SUPABASE.md](docs/development/SUPABASE.md) — local Supabase stack, migrations, RLS tests, generated types - [DEPLOY.md](DEPLOY.md) — production VPS deploy guide (Docker + nginx + TLS + hardening) - [CHANGELOG.md](CHANGELOG.md) — versioned release notes @@ -125,12 +127,13 @@ faunosteo/ pnpm workspace (see docs/development/WORKSPACE.md) ├─ src/state/ Zustand store (Report v3) + persistence adapter + locale store ├─ src/anatomy/ drawing: sanitised asset + annotation layer → inline SVG per view ├─ src/components/ UI primitives, canvas, observation, report -├─ src/pdf/ export/import/attachment/fonts + renderers +├─ src/pdf/ app side of the PDF: snapshot + branding + browser rasterizer → @faunosteo/pdf engine ├─ src/lib/ id, dates, assert utilities ├─ src/styles/ Tailwind v4 CSS + design tokens ├─ tests/unit/ vitest tests on the bundled sheet (+ frozen v2 fixtures) ├─ packages/domain/ @faunosteo/domain: canonical sheet document + report document (v3, v2 migration) -├─ packages/anatomy/ @faunosteo/anatomy: legacy importer, curation pipeline, annotation-layer renderer +├─ packages/anatomy/ @faunosteo/anatomy: legacy importer, curation pipeline, annotation-layer renderer + view composer +├─ packages/pdf/ @faunosteo/pdf: browser-free PDF engine (explicit inputs, archive envelope v1, layered reader) ├─ packages/supabase/ @faunosteo/supabase: typed client, generated types, PGlite SQL test harness ├─ supabase/ CLI config, SQL migrations, local seed (incl. the equine sheet), pgTAP tests ├─ docker/ entrypoint.sh + nginx.conf diff --git a/apps/app/package.json b/apps/app/package.json index b90f8665..b10b734f 100644 --- a/apps/app/package.json +++ b/apps/app/package.json @@ -17,6 +17,7 @@ "dependencies": { "@faunosteo/anatomy": "workspace:*", "@faunosteo/domain": "workspace:*", + "@faunosteo/pdf": "workspace:*", "@faunosteo/supabase": "workspace:*", "motion": "^11.11.17", "pdf-lib": "^1.17.1", diff --git a/apps/app/scripts/compare-reports.ts b/apps/app/scripts/compare-reports.ts index 87ca0b24..d93ca7e4 100644 --- a/apps/app/scripts/compare-reports.ts +++ b/apps/app/scripts/compare-reports.ts @@ -18,14 +18,15 @@ import { readFileSync, readdirSync, statSync } from 'node:fs' import { basename, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' -import { PDFDocument } from 'pdf-lib' import { - readReportDocument, - REPORT_VERSION, + readArchiveDocument, UnsupportedReportVersionError, } from '@faunosteo/domain' -import { readAttachedDocument } from '../src/pdf/attachment' -import { MAX_PDF_BYTES } from '../src/pdf/import' +import { + ArchiveReadError, + MAX_PDF_BYTES, + readAttachedDocument, +} from '@faunosteo/pdf' import { parseBundledSheet } from '../src/sheets/provider' import { buildSheetIndex, type SheetIndex } from '../src/services/sheetIndex' import { @@ -57,6 +58,7 @@ function loadSheet(): SheetIndex { document: json('document.json'), migrationMap: json('report-migration-map.json'), assets: {}, + assetHashes: {}, }), ) } @@ -84,25 +86,35 @@ async function compareFile( if (!st.isFile()) throw new Error('not a regular file') if (st.size > MAX_PDF_BYTES) throw new Error('file too large') const bytes = new Uint8Array(readFileSync(path)) - const pdf = await PDFDocument.load(bytes, { ignoreEncryption: true }) - const raw = await readAttachedDocument(pdf) - const version = (raw as { version: number }).version + // Byte-scan reader (BLK-009): the PDF object graph is never parsed here. + const raw = await readAttachedDocument(bytes) try { - const outcome = readReportDocument(raw, sheet.sheet.migrationMap) - return compareReport(raw, outcome, version !== REPORT_VERSION, sheet, args) + const outcome = readArchiveDocument(raw, sheet.sheet.migrationMap) + return compareReport(raw, outcome, sheet, args) } catch (err) { if (err instanceof UnsupportedReportVersionError) { - throw new Error(`report version ${version} cannot be read`) + // The version is a number or null: nothing of the attachment is echoed. + throw new Error(`report version ${err.foundVersion} cannot be read`) } throw err } } +/** The engine's typed read failures, worded without echoing the file. */ +const READ_FAILURES: Record<ArchiveReadError['kind'], string> = { + invalid_pdf: 'not a readable PDF', + no_attachment: 'no Faunosteo attachment found', + attachment_stripped: + 'attachment stripped (the PDF is stamped as a Faunosteo archive)', + incompatible_version: 'report version cannot be read', +} + /** A missing or unreadable file is a failed entry, not a crash. */ function failureReason(err: unknown): string { const code = (err as NodeJS.ErrnoException | undefined)?.code if (code === 'ENOENT') return 'file not found' if (code === 'EACCES') return 'file not readable' + if (err instanceof ArchiveReadError) return READ_FAILURES[err.kind] // JSON.parse messages echo a fragment of the attachment. if (err instanceof SyntaxError) return 'attachment is not valid JSON' return err instanceof Error ? err.message : String(err) diff --git a/apps/app/scripts/compare/report.ts b/apps/app/scripts/compare/report.ts index 4917841c..bee013cd 100644 --- a/apps/app/scripts/compare/report.ts +++ b/apps/app/scripts/compare/report.ts @@ -1,9 +1,9 @@ import { ReportV2Schema, findingPathKey, + type ArchiveReadOutcome, type Finding, type FindingV2, - type MigrationOutcome, type ObservationZoneV2, type Report, type ReportZone, @@ -15,7 +15,8 @@ import { pickLabel, type SheetIndex } from '../../src/services/sheetIndex' * Pure comparison of a report document found in a PDF with its v3 reading: * a v2 archive is shown legacy id → canonical id line by line, a v3 report * is checked against the bundled sheet. Every item the sheet cannot place is - * marked `!! UNRESOLVED` with the reason, nothing is summarised away. + * marked `!! UNRESOLVED` with the reason, nothing is summarised away. A Step 6 + * envelope adds one header line saying whether its snapshot was kept. */ export const UNRESOLVED = '!! UNRESOLVED' @@ -186,13 +187,22 @@ function observationLines( return lines } +/** The report document inside the attachment: the envelope's, or the bare one. */ +function reportDataOf(raw: unknown): unknown { + const isEnvelope = + typeof raw === 'object' && + raw !== null && + typeof (raw as { envelopeVersion?: unknown }).envelopeVersion === 'number' + return isEnvelope ? (raw as { report: unknown }).report : raw +} + function migratedObservationLines( raw: unknown, report: Report, sheet: SheetIndex, opts: CompareOptions, ): string[][] { - const v2 = ReportV2Schema.parse(raw) + const v2 = ReportV2Schema.parse(reportDataOf(raw)) return v2.observations.map((legacy, i) => { const out = report.observations[i]! const severity = legacy.severity @@ -230,12 +240,22 @@ function countsOf(report: Report): Counts { } } +/** The envelope line: present only when the attachment was an archive. */ +function archiveLine(outcome: ArchiveReadOutcome): string[] { + if (outcome.archive) return ['archive v1 (snapshot kept)'] + if (outcome.snapshotRejected) { + return [`archive v1 (snapshot rejected: ${esc(outcome.snapshotRejected)})`] + } + return [] +} + function headerLines( source: 'v2' | 'v3', - report: Report, + outcome: ArchiveReadOutcome, sheet: SheetIndex, opts: CompareOptions, ): string[] { + const { report } = outcome const ref = sheet.sheet.ref const sameSheet = report.sheet.sheetId === ref.sheetId && @@ -246,6 +266,7 @@ function headerLines( const c = countsOf(report) const lines = [ source === 'v2' ? 'v2 → v3 (migrated)' : 'v3 (read as is)', + ...archiveLine(outcome), sheetLine, `id ${esc(report.id)} · date ${esc(report.date)} · ${c.observations} observations · ${c.zones} zones (${c.unresolvedZones} unresolved) · ${c.findings} findings (${c.unresolvedFindings} unresolved)`, ] @@ -273,17 +294,17 @@ function footerLines(report: Report, full: boolean): string[] { } /** - * `raw` is the attachment as found in the PDF, `outcome` its v3 reading - * (`readReportDocument`); `migrated` tells which vocabulary the lines use. + * `raw` is the attachment as found in the PDF (bare report or envelope), + * `outcome` its layered reading (`readArchiveDocument`); `outcome.migrated` + * tells which vocabulary the lines use. */ export function compareReport( raw: unknown, - outcome: MigrationOutcome, - migrated: boolean, + outcome: ArchiveReadOutcome, sheet: SheetIndex, opts: CompareOptions, ): Comparison { - const { report } = outcome + const { report, migrated } = outcome const source = migrated ? 'v2' : 'v3' const v3Lines = report.observations.map((o) => observationLines(o, sheet, opts), @@ -295,7 +316,7 @@ export function compareReport( ] return { source, - header: headerLines(source, report, sheet, opts), + header: headerLines(source, outcome, sheet, opts), observations: migrated ? migratedObservationLines(raw, report, sheet, opts) : v3Lines, diff --git a/apps/app/src/app/routes/EditorRoute.tsx b/apps/app/src/app/routes/EditorRoute.tsx index 4e39cdbe..c0858ea1 100644 --- a/apps/app/src/app/routes/EditorRoute.tsx +++ b/apps/app/src/app/routes/EditorRoute.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useNavigate } from 'react-router-dom' import AnatomyCanvas from '@/components/canvas/AnatomyCanvas' import DetailModal from '@/components/canvas/DetailModal' @@ -28,11 +28,23 @@ import { } from '@/services/zoneInteraction' import type { ViewStates } from '@/anatomy/drawing' import { exportReportToPdf } from '@/pdf/export' +import type { ExportWarning } from '@faunosteo/pdf' +import type { RebaseOutcome } from '@faunosteo/domain' import { useT } from '@/i18n/useT' import { DEFAULT_SPECIES_ID } from './NewReportRoute' const DISCLAIMER_FLAG = 'osteo:disclaimer-shown' +/** What the PDF lacks, named for the practitioner: logo slots and view ids. */ +function missingItemsOf(warnings: readonly ExportWarning[]): string[] { + return warnings.map((w) => (w.kind === 'logo_failed' ? w.slot : w.viewId)) +} + +/** Zones and findings a draft rebase could not find on the loaded sheet. */ +function unresolvedCountOf(outcome: RebaseOutcome): number { + return outcome.unresolvedZones + outcome.unresolvedFindings +} + /** Editor on the reference sheet: wires the canvas, the pickers and the store. */ export default function EditorRoute() { const navigate = useNavigate() @@ -49,19 +61,28 @@ export default function EditorRoute() { const [disclaimer, setDisclaimer] = useState<string | null>(null) const [exporting, setExporting] = useState(false) const [editDraft, setEditDraft] = useState<Identity | null>(null) + // One alert per restore, even if the effect runs again before the re-render. + const rebaseAlerted = useRef(false) useEffect(() => { window.scrollTo({ top: 0, left: 0, behavior: 'auto' }) }, []) // No report in memory: restore the per-tab draft once the sheet is known. + // A draft rebased on another sheet is announced with its unresolved count. useEffect(() => { if (report) return - if (sheet.status === 'ready') - store.restoreDraft(sheet.index.sheet.migrationMap) + if (sheet.status === 'ready') { + const outcome = store.restoreDraft(sheet.index) + if (outcome?.rebased && !rebaseAlerted.current) { + rebaseAlerted.current = true + const count = String(unresolvedCountOf(outcome)) + window.alert(t('editor.draft_rebased').replace('{count}', count)) + } + } if (sheet.status !== 'loading' && !useReportStore.getState().report) navigate('/') - }, [report, sheet, store, navigate]) + }, [report, sheet, store, navigate, t]) useEffect(() => { if (sheet.status !== 'ready' || typeof sessionStorage === 'undefined') @@ -145,14 +166,22 @@ export default function EditorRoute() { if (!report) return setExporting(true) try { - const bytes = await exportReportToPdf(report, index, { locale }) - const blob = new Blob([bytes as BlobPart], { type: 'application/pdf' }) + const { pdf, warnings } = await exportReportToPdf(report, index, { + locale, + }) + const blob = new Blob([pdf as BlobPart], { type: 'application/pdf' }) const url = URL.createObjectURL(blob) const a = document.createElement('a') a.href = url a.download = `bilan-${report.animal.name}-${report.date}.pdf` a.click() URL.revokeObjectURL(url) + const missing = missingItemsOf(warnings) + if (missing.length) { + window.alert( + t('editor.export_warnings').replace('{items}', missing.join(', ')), + ) + } } catch (err) { console.error('PDF export failed', err) window.alert(t('editor.export_failed')) diff --git a/apps/app/src/app/routes/HomeRoute.tsx b/apps/app/src/app/routes/HomeRoute.tsx index 0d0e61c6..044e4698 100644 --- a/apps/app/src/app/routes/HomeRoute.tsx +++ b/apps/app/src/app/routes/HomeRoute.tsx @@ -1,64 +1,142 @@ import { useNavigate } from 'react-router-dom' import { useRef, useState } from 'react' +import { + rebaseReportOnSheet, + type ArchiveReadOutcome, + type RebaseOutcome, +} from '@faunosteo/domain' import AppHeader from '@/components/brand/AppHeader' import Button from '@/components/ui/Button' import Card from '@/components/ui/Card' -import { importReportFromPdf, ImportError } from '@/pdf/import' +import { importReportFromPdf, ImportError, MAX_PDF_BYTES } from '@/pdf/import' import { useReportStore } from '@/state/reportStore' import { useSheet } from '@/sheets/useSheet' +import type { SheetIndex } from '@/services/sheetIndex' import { DEFAULT_SPECIES_ID } from './NewReportRoute' import { useT } from '@/i18n/useT' +type Translate = ReturnType<typeof useT> + +/** + * The detail lines of the import alert (STEP6 §16), in a fixed order: a + * lossy v2 migration, the archive kept, the snapshot dropped with its + * reason, the rebase onto the current sheet. Empty when nothing applies. + */ +function importDetailLines( + outcome: ArchiveReadOutcome, + rebase: RebaseOutcome, + t: Translate, +): string[] { + const lines: string[] = [] + const lost = outcome.unresolvedFindings + outcome.unresolvedZones + if (outcome.migrated && lost > 0) { + lines.push(t('home.import.migrated').replace('{count}', String(lost))) + } + if (outcome.archive) lines.push(t('home.import.archive_ok')) + if (outcome.snapshotRejected) { + lines.push( + t('home.import.snapshot_rejected').replace( + '{reason}', + t(`home.import.snapshot_reason.${outcome.snapshotRejected}`), + ), + ) + } + if (rebase.rebased) { + const count = rebase.unresolvedZones + rebase.unresolvedFindings + lines.push(t('home.import.rebased').replace('{count}', String(count))) + } + return lines +} + +/** + * Degraded recovery: something the practitioner must check. A rejected + * snapshot, a migration or a rebase that lost items. A rebase that resolved + * everything is a complete restoration on a different sheet. + */ +function isDegradedImport( + outcome: ArchiveReadOutcome, + rebase: RebaseOutcome, +): boolean { + const lost = outcome.unresolvedFindings + outcome.unresolvedZones + const rebaseLost = rebase.unresolvedZones + rebase.unresolvedFindings + return ( + outcome.snapshotRejected !== undefined || + (outcome.migrated && lost > 0) || + (rebase.rebased && rebaseLost > 0) + ) +} + +/** + * The one alert shown after a successful import: a headline that says + * whether the restoration is complete or partial, then the detail lines. + * Empty (no alert) when there is nothing to say: a bare v3 on the same sheet. + */ +function importMessages( + outcome: ArchiveReadOutcome, + rebase: RebaseOutcome, + t: Translate, +): string[] { + const details = importDetailLines(outcome, rebase, t) + if (details.length === 0) return [] + const headline = isDegradedImport(outcome, rebase) + ? t('home.import.degraded') + : t('home.import.complete') + return [headline, ...details] +} + +/** The error line under the import button, by ImportError kind. */ +function importErrorMessage(err: unknown, t: Translate): string { + if (!(err instanceof ImportError)) return t('home.import.error_generic') + switch (err.kind) { + case 'incompatible_version': + return t('home.import.error_incompatible_version').replace( + '{version}', + String(err.foundVersion ?? '?'), + ) + case 'invalid_pdf': + return t('home.import.error_invalid_pdf') + case 'attachment_stripped': + return t('home.import.error_attachment_stripped') + case 'no_attachment': + return t('home.import.error_no_attachment') + } +} + export default function HomeRoute() { const navigate = useNavigate() const fileRef = useRef<HTMLInputElement | null>(null) - const hydrate = useReportStore((s) => s.hydrateReport) + const hydrateImport = useReportStore((s) => s.hydrateImport) const sheet = useSheet(DEFAULT_SPECIES_ID) const [error, setError] = useState<string | null>(null) const [busy, setBusy] = useState(false) const t = useT() + /** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */ + async function importFile(file: File, index: SheetIndex) { + // 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()) + const outcome = await importReportFromPdf(bytes, index.sheet.migrationMap) + const rebase = rebaseReportOnSheet( + outcome.report, + index, + outcome.archive?.sheetSnapshot ?? null, + ) + hydrateImport({ report: rebase.report, archive: outcome.archive }) + const lines = importMessages(outcome, rebase, t) + if (lines.length > 0) window.alert(lines.join('\n\n')) + navigate('/editor') + } + async function onPickFile(e: React.ChangeEvent<HTMLInputElement>) { const file = e.target.files?.[0] if (!file || sheet.status !== 'ready') return setBusy(true) setError(null) try { - const bytes = new Uint8Array(await file.arrayBuffer()) - const outcome = await importReportFromPdf( - bytes, - sheet.index.sheet.migrationMap, - ) - if ( - outcome.migrated && - outcome.unresolvedFindings + outcome.unresolvedZones > 0 - ) { - window.alert( - t('home.import.migrated').replace( - '{count}', - String(outcome.unresolvedFindings + outcome.unresolvedZones), - ), - ) - } - hydrate(outcome.report) - navigate('/editor') + await importFile(file, sheet.index) } catch (err) { - if (err instanceof ImportError) { - if (err.kind === 'incompatible_version') { - setError( - t('home.import.error_incompatible_version').replace( - '{version}', - String(err.foundVersion ?? '?'), - ), - ) - } else if (err.kind === 'invalid_pdf') { - setError(t('home.import.error_invalid_pdf')) - } else { - setError(t('home.import.error_no_attachment')) - } - } else { - setError(t('home.import.error_generic')) - } + setError(importErrorMessage(err, t)) } finally { setBusy(false) if (fileRef.current) fileRef.current.value = '' diff --git a/apps/app/public/assets/faunosteo-horizontal-com-512.png b/apps/app/src/assets/brand/faunosteo-horizontal-com-512.png similarity index 100% rename from apps/app/public/assets/faunosteo-horizontal-com-512.png rename to apps/app/src/assets/brand/faunosteo-horizontal-com-512.png diff --git a/apps/app/public/assets/faunosteo_logo_horizontal-512.png b/apps/app/src/assets/brand/faunosteo-logo-horizontal-512.png similarity index 100% rename from apps/app/public/assets/faunosteo_logo_horizontal-512.png rename to apps/app/src/assets/brand/faunosteo-logo-horizontal-512.png diff --git a/apps/app/public/Paws_in_harmony.svg b/apps/app/src/assets/brand/paws-in-harmony.svg similarity index 100% rename from apps/app/public/Paws_in_harmony.svg rename to apps/app/src/assets/brand/paws-in-harmony.svg diff --git a/apps/app/public/brand/zenquality-logo-fr.png b/apps/app/src/assets/brand/zenquality-logo-fr.png similarity index 100% rename from apps/app/public/brand/zenquality-logo-fr.png rename to apps/app/src/assets/brand/zenquality-logo-fr.png diff --git a/apps/app/src/components/brand/Footer.tsx b/apps/app/src/components/brand/Footer.tsx index 84ff2c6b..f41fc4c2 100644 --- a/apps/app/src/components/brand/Footer.tsx +++ b/apps/app/src/components/brand/Footer.tsx @@ -1,5 +1,6 @@ import { useConfig } from '@/app/providers/ConfigProvider' import { useT } from '@/i18n/useT' +import pawsInHarmonyUrl from '@/assets/brand/paws-in-harmony.svg?url' export default function Footer() { const cfg = useConfig() @@ -37,7 +38,7 @@ export default function Footer() { className="text-[var(--color-accent)] hover:text-[var(--color-accent-strong)] transition-colors font-medium" > <img - src="/Paws_in_harmony.svg" + src={pawsInHarmonyUrl} alt="Paws in Harmony" className="h-6 w-auto inline-block align-middle" /> diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index f3119b51..5184cf04 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -30,8 +30,26 @@ export const en: Dict = { 'This PDF was not generated by Faunosteo (no data detected).', 'home.import.error_incompatible_version': 'This PDF uses format v{version}, which this version of the application cannot read (accepted formats: v2 and v3).', + 'home.import.complete': 'Full restoration.', + 'home.import.degraded': + 'Partial recovery: check the items flagged below.', 'home.import.migrated': 'Report imported from an older format. Findings not found in the current sheet: {count} (kept with their labels).', + 'home.import.archive_ok': + 'Faunosteo archive imported: report and the original sheet snapshot kept.', + 'home.import.snapshot_rejected': + 'Report recovered, but the original sheet snapshot was rejected ({reason}): this archive cannot be reproduced as is.', + 'home.import.snapshot_reason.unsupported_envelope': + 'archive from a newer version', + 'home.import.snapshot_reason.schema': 'invalid content', + 'home.import.snapshot_reason.caps': 'size or complexity over the limits', + 'home.import.snapshot_reason.integrity': 'inconsistent sheet', + 'home.import.snapshot_reason.sheet_mismatch': + "sheet differs from the report's", + 'home.import.rebased': + "Report opened on the current sheet, which differs from the archive's. Items not found: {count} (kept with their labels).", + 'home.import.error_attachment_stripped': + 'This Faunosteo PDF lost its embedded data (attachment removed by a viewer or an optimiser). Use the original file.', 'home.no_sheet.title': 'No anatomical sheet', 'home.no_sheet.description': 'This build of the application carries no anatomical sheet: no report can be created or imported.', @@ -51,6 +69,10 @@ export const en: Dict = { 'editor.export': 'Export as PDF', 'editor.exporting': 'Generating…', 'editor.export_failed': 'PDF generation failed. Retry or contact support.', + 'editor.export_warnings': + 'PDF exported with missing elements: {items}. Check the browser console.', + 'editor.draft_rebased': + 'Draft restored on an anatomical sheet different from the one it was created on. Items not found: {count} (kept with their labels).', 'editor.edit_infos': 'Edit info', 'editor.edit_dialog_title': 'Edit information', 'editor.disclaimer_title': 'Legal scope of animal osteopathy', @@ -150,25 +172,6 @@ export const en: Dict = { 'severity.moderate': 'moderate', 'severity.severe': 'severe', - 'pdf.eyebrow.observation': 'OBSERVATION', - 'pdf.eyebrow.synthesis': 'SYNTHESIS', - 'pdf.title.conclusion': 'Conclusion', - 'pdf.section.zones': 'ZONES', - 'pdf.section.findings_prefix': 'FINDINGS — ', - 'pdf.section.free_findings': 'FREE FINDINGS', - 'pdf.section.severity': 'SEVERITY', - 'pdf.section.comment': 'COMMENT', - 'pdf.section.conclusion': 'CONCLUSION', - 'pdf.section.recommendations': 'RECOMMENDATIONS', - 'pdf.section.next_appointment': 'NEXT APPOINTMENT', - 'pdf.view.general': 'GENERAL VIEW', - 'pdf.view.detail_prefix': 'DETAIL VIEW — ', - 'pdf.empty': '—', - 'pdf.owner_prefix': 'Owner: ', - 'pdf.siret_prefix': 'SIRET ', - 'pdf.title.suffix.bilan': 'Osteo report — ', - 'pdf.subject': 'Animal osteopathic report', - 'lang.group_label': 'Language', 'lang.switch_to_fr': 'Passer en français', 'lang.switch_to_en': 'Switch to English', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index a2afcf3a..9f03bee1 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -32,8 +32,26 @@ export const fr: Dict = { "Ce PDF n'a pas été généré par Faunosteo (pas de données détectées).", 'home.import.error_incompatible_version': "Ce PDF est au format v{version}, que cette version de l'application ne sait pas lire (formats acceptés : v2 et v3).", + 'home.import.complete': 'Restauration complète.', + 'home.import.degraded': + 'Récupération partielle : vérifiez les éléments signalés.', 'home.import.migrated': 'Bilan importé depuis un ancien format. Constats non retrouvés dans la fiche actuelle : {count} (conservés avec leurs libellés).', + 'home.import.archive_ok': + "Archive Faunosteo importée : bilan et instantané de la fiche d'origine conservés.", + 'home.import.snapshot_rejected': + "Bilan récupéré, mais l'instantané de la fiche d'origine a été rejeté ({reason}) : cette archive ne pourra pas être reproduite telle quelle.", + 'home.import.snapshot_reason.unsupported_envelope': + "archive d'une version plus récente", + 'home.import.snapshot_reason.schema': 'contenu invalide', + 'home.import.snapshot_reason.caps': 'taille ou complexité excessive', + 'home.import.snapshot_reason.integrity': 'fiche incohérente', + 'home.import.snapshot_reason.sheet_mismatch': + 'fiche différente de celle du bilan', + 'home.import.rebased': + "Bilan ouvert sur la fiche actuelle, différente de celle de l'archive. Éléments non retrouvés : {count} (conservés avec leurs libellés).", + 'home.import.error_attachment_stripped': + "Ce PDF Faunosteo a perdu ses données embarquées (pièce jointe supprimée par un lecteur ou un optimiseur). Utilisez le fichier d'origine.", 'home.no_sheet.title': 'Aucune fiche anatomique', 'home.no_sheet.description': "Cette version de l'application n'embarque aucune fiche anatomique : aucun bilan ne peut être créé ni importé.", @@ -57,6 +75,10 @@ export const fr: Dict = { 'editor.exporting': 'Génération…', 'editor.export_failed': 'Échec de la génération du PDF. Réessayez ou contactez le support.', + 'editor.export_warnings': + 'PDF exporté avec des éléments manquants : {items}. Vérifiez la console du navigateur.', + 'editor.draft_rebased': + 'Brouillon restauré sur une fiche anatomique différente de celle où il a été créé. Éléments non retrouvés : {count} (conservés avec leurs libellés).', '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", @@ -165,26 +187,6 @@ export const fr: Dict = { 'severity.moderate': 'modérée', 'severity.severe': 'sévère', - // pdf - 'pdf.eyebrow.observation': 'OBSERVATION', - 'pdf.eyebrow.synthesis': 'SYNTHÈSE', - 'pdf.title.conclusion': 'Conclusion', - 'pdf.section.zones': 'ZONES', - 'pdf.section.findings_prefix': 'CONSTATS — ', - 'pdf.section.free_findings': 'CONSTATS LIBRES', - 'pdf.section.severity': 'SÉVÉRITÉ', - 'pdf.section.comment': 'COMMENTAIRE', - 'pdf.section.conclusion': 'CONCLUSION', - 'pdf.section.recommendations': 'RECOMMANDATIONS', - 'pdf.section.next_appointment': 'PROCHAIN RENDEZ-VOUS', - 'pdf.view.general': 'VUE GÉNÉRALE', - 'pdf.view.detail_prefix': 'VUE DÉTAIL — ', - 'pdf.empty': '—', - 'pdf.owner_prefix': 'Propriétaire : ', - 'pdf.siret_prefix': 'SIRET ', - 'pdf.title.suffix.bilan': 'Bilan ostéo — ', - 'pdf.subject': "Bilan d'ostéopathie animalière", - // language switcher 'lang.group_label': 'Langue', 'lang.switch_to_fr': 'Passer en français', diff --git a/apps/app/src/pdf/attachment.ts b/apps/app/src/pdf/attachment.ts deleted file mode 100644 index 446d2120..00000000 --- a/apps/app/src/pdf/attachment.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { AFRelationship, type PDFDocument } from 'pdf-lib' -import { - readReportDocument, - REPORT_VERSION, - UnsupportedReportVersionError, - type MigrationOutcome, - type Report, - type ReportMigrationMap, -} from '@faunosteo/domain' - -/** - * The report document travels inside the PDF as a native attachment. - * Written as v3; read back as v3, or as v2 migrated through the sheet's - * migration map (the practitioner's archive). Any other version is refused - * with the found version. - */ - -const FILENAME = 'osteo-report.json' - -export class IncompatibleReportVersionError extends Error { - constructor(public readonly foundVersion: number | null) { - super(`incompatible_version:${foundVersion ?? 'unknown'}`) - this.name = 'IncompatibleReportVersionError' - } -} - -export async function attachReportJson( - pdfDoc: PDFDocument, - report: Report, -): Promise<void> { - const bytes = new TextEncoder().encode(JSON.stringify(report, null, 2)) - await pdfDoc.attach(bytes, FILENAME, { - mimeType: 'application/json', - description: `Faunosteo state v${REPORT_VERSION}`, - creationDate: new Date(), - modificationDate: new Date(), - afRelationship: AFRelationship.Data, - }) -} - -export interface ExtractedReport extends MigrationOutcome { - /** True when the attachment was an older version lifted to v3. */ - migrated: boolean -} - -/** - * The raw report document carried by the PDF, of whatever version, before - * any migration: what the archive check tool shows next to the v3 result. - * Throws when the PDF carries no Faunosteo attachment or an oversized one. - */ -export async function readAttachedDocument( - pdfDoc: PDFDocument, -): Promise<unknown> { - const bytes = await attachmentBytes(pdfDoc) - if (bytes.byteLength > MAX_ATTACHMENT_BYTES) { - throw new Error('attachment too large') - } - const data: unknown = JSON.parse(new TextDecoder().decode(bytes)) - // No numeric version at all: not a Faunosteo attachment (legacy message), not an old one. - if (versionOf(data) === null) { - throw new Error('attachment carries no report version') - } - return data -} - -export async function extractReportJson( - pdfDoc: PDFDocument, - map: ReportMigrationMap, -): Promise<ExtractedReport> { - const data = await readAttachedDocument(pdfDoc) - try { - return { - ...readReportDocument(data, map), - migrated: versionOf(data) !== REPORT_VERSION, - } - } catch (err) { - if (err instanceof UnsupportedReportVersionError) { - throw new IncompatibleReportVersionError(err.foundVersion) - } - throw err - } -} - -async function attachmentBytes(pdfDoc: PDFDocument): Promise<Uint8Array> { - const maybeApi = pdfDoc as unknown as { - getAttachments?: () => Array<{ name: string; data: Uint8Array }> - } - if (typeof maybeApi.getAttachments === 'function') { - const list = maybeApi.getAttachments() - if (list && list.length) { - const hit = - list.find( - (a) => a.name.startsWith('osteo-report') && a.name.endsWith('.json'), - ) ?? list[0] - return hit.data - } - } - const fallback = await traverseForJsonAttachment(pdfDoc) - if (!fallback) throw new Error('No osteo-report attachment found') - return fallback -} - -/** Hard ceiling on an attachment (inflated or not): a report is a few hundred KB at most. */ -const MAX_ATTACHMENT_BYTES = 16 * 1024 * 1024 - -function versionOf(data: unknown): number | null { - if (data === null || typeof data !== 'object') return null - const v = (data as { version?: unknown }).version - return typeof v === 'number' ? v : null -} - -interface RawObj { - contents?: Uint8Array - dict?: { entries?: () => Array<[unknown, unknown]> } -} - -/** - * Hard ceiling on inflated attachment size. A valid report JSON is far - * smaller; anything bigger is a decompression bomb or corruption. - */ -const MAX_INFLATED_BYTES = MAX_ATTACHMENT_BYTES - -/** Exported for tests. Returns null on failure or when the cap is exceeded. */ -export async function inflateFlate( - bytes: Uint8Array, -): Promise<Uint8Array | null> { - if (typeof DecompressionStream === 'undefined') return null - try { - const stream = new Blob([bytes as BlobPart]) - .stream() - .pipeThrough(new DecompressionStream('deflate')) - const reader = stream.getReader() - const chunks: Uint8Array[] = [] - let total = 0 - for (;;) { - const { done, value } = await reader.read() - if (done) break - total += value.byteLength - if (total > MAX_INFLATED_BYTES) { - await reader.cancel() - return null - } - chunks.push(value) - } - const out = new Uint8Array(total) - let offset = 0 - for (const c of chunks) { - out.set(c, offset) - offset += c.byteLength - } - return out - } catch { - return null - } -} - -function dictHasFlateFilter(entries: Array<[unknown, unknown]>): boolean { - for (const [k, v] of entries) { - if (String(k).includes('Filter') && String(v).includes('FlateDecode')) - return true - } - return false -} - -async function traverseForJsonAttachment( - pdfDoc: PDFDocument, -): Promise<Uint8Array | null> { - const ctx = ( - pdfDoc as unknown as { - context: { enumerateIndirectObjects(): Array<[unknown, RawObj]> } - } - ).context - for (const [, obj] of ctx.enumerateIndirectObjects()) { - if (!obj || typeof obj !== 'object') continue - if (!(obj.contents instanceof Uint8Array)) continue - const entries = obj.dict?.entries?.() ?? [] - let isEmbeddedFile = false - let isJsonSubtype = false - for (const [k, v] of entries) { - const ks = String(k) - const vs = String(v) - if (ks.includes('Type') && vs.includes('EmbeddedFile')) - isEmbeddedFile = true - // PDF name syntax escapes '/' as '#2F': /application#2Fjson - if ( - ks.includes('Subtype') && - (vs.includes('application/json') || vs.includes('application#2Fjson')) - ) { - isJsonSubtype = true - } - } - if (!isEmbeddedFile && !isJsonSubtype) continue - if (dictHasFlateFilter(entries)) { - const inflated = await inflateFlate(obj.contents) - if (inflated) return inflated - } - return obj.contents - } - return null -} diff --git a/apps/app/src/pdf/branding.ts b/apps/app/src/pdf/branding.ts new file mode 100644 index 00000000..8023773c --- /dev/null +++ b/apps/app/src/pdf/branding.ts @@ -0,0 +1,44 @@ +import type { Branding, ImageAsset } from '@faunosteo/domain' +import headerLogoDataUrl from '@/assets/brand/faunosteo-logo-horizontal-512.png?inline' +import footerLogoDataUrl from '@/assets/brand/faunosteo-horizontal-com-512.png?inline' +import poweredByLogoDataUrl from '@/assets/brand/zenquality-logo-fr.png?inline' +import partnerLogoSvg from '@/assets/brand/paws-in-harmony.svg?raw' + +/** + * The visual identity the export embeds (STEP6 §14 "Branding in the app"): + * the four logo files bundled with the application (`src/assets/brand`), so + * an export needs no network and no deployed file, plus the credit URLs. The + * result travels inside the archive, so a re-export never needs them again. + */ + +// shortcut: the site URL and the credit constants belong to the runtime +// config (ConfigProvider); they live here until AppConfig carries them. +const SITE_URL = 'https://faunosteo.com' +const POWERED_BY = { + url: 'https://zenquality.fr', + fallbackText: 'zenquality.fr', +} +const PARTNER = { + url: 'https://www.instagram.com/paws.iin.harmony', + fallbackText: '@paws.iin.harmony', +} + +const PNG_DATA_URL_PREFIX = 'data:image/png;base64,' + +/** A `?inline` PNG import is a base64 data URL; the engine wants the base64 alone. */ +function pngAsset(dataUrl: string): ImageAsset { + if (!dataUrl.startsWith(PNG_DATA_URL_PREFIX)) { + throw new Error('bundled logo is not a base64 PNG data URL') + } + return { kind: 'png', base64: dataUrl.slice(PNG_DATA_URL_PREFIX.length) } +} + +export async function loadBranding(): Promise<Branding> { + return { + siteUrl: SITE_URL, + headerLogo: pngAsset(headerLogoDataUrl), + footerLogo: pngAsset(footerLogoDataUrl), + poweredBy: { logo: pngAsset(poweredByLogoDataUrl), ...POWERED_BY }, + partner: { logo: { kind: 'svg', svg: partnerLogoSvg }, ...PARTNER }, + } +} diff --git a/apps/app/src/pdf/browserRasterizer.ts b/apps/app/src/pdf/browserRasterizer.ts new file mode 100644 index 00000000..9913621e --- /dev/null +++ b/apps/app/src/pdf/browserRasterizer.ts @@ -0,0 +1,100 @@ +import type { Rasterizer } from '@faunosteo/pdf' + +/** + * The browser side of the engine's rasterizer adapter: the engine has fixed + * the pixel size, this module only stamps it on the SVG root and lets the + * browser draw the SVG through an Image / canvas pair, which renders exactly + * what the practitioner sees in the inline anatomy canvas. + */ + +const SVG_NS = 'http://www.w3.org/2000/svg' +const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] + +function startsWithPngSignature(bytes: Uint8Array): boolean { + if (bytes.length < PNG_SIGNATURE.length) return false + return PNG_SIGNATURE.every((byte, i) => bytes[i] === byte) +} + +/** The root carries the namespace and the engine's size; nothing else changes. */ +function sizedSvg(svg: string, widthPx: number, heightPx: number): string { + const root = new DOMParser().parseFromString( + svg, + 'image/svg+xml', + ).documentElement + if (root.namespaceURI !== SVG_NS) root.setAttribute('xmlns', SVG_NS) + root.setAttribute('width', String(widthPx)) + root.setAttribute('height', String(heightPx)) + return new XMLSerializer().serializeToString(root) +} + +function loadImage(svg: string): Promise<HTMLImageElement> { + const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' }) + const url = URL.createObjectURL(blob) + const img = new Image() + img.decoding = 'sync' + img.crossOrigin = 'anonymous' + return new Promise<HTMLImageElement>((resolve, reject) => { + img.onload = () => resolve(img) + img.onerror = () => + reject(new Error('Browser failed to render the SVG into an Image')) + img.src = url + }).finally(() => URL.revokeObjectURL(url)) +} + +function drawOnWhiteCanvas( + img: HTMLImageElement, + widthPx: number, + heightPx: number, +): HTMLCanvasElement { + const canvas = document.createElement('canvas') + canvas.width = widthPx + canvas.height = heightPx + const ctx = canvas.getContext('2d') + if (!ctx) throw new Error('Canvas 2D context unavailable') + ctx.fillStyle = '#ffffff' + ctx.fillRect(0, 0, widthPx, heightPx) + ctx.drawImage(img, 0, 0, widthPx, heightPx) + return canvas +} + +function canvasBlob(canvas: HTMLCanvasElement): Promise<Blob | null> { + return new Promise((resolve) => canvas.toBlob(resolve, 'image/png')) +} + +/** Fallback when toBlob yields nothing: decode the data URL by hand. */ +function pngFromDataUrl(canvas: HTMLCanvasElement): Uint8Array { + const dataUrl = canvas.toDataURL('image/png') + if (!dataUrl.startsWith('data:image/png')) { + throw new Error( + `canvas.toDataURL produced non-PNG payload: ${dataUrl.slice(0, 32)}`, + ) + } + const comma = dataUrl.indexOf(',') + if (comma < 0) { + throw new Error('canvas.toDataURL returned a data URL without a payload') + } + const binary = atob(dataUrl.slice(comma + 1)) + const bytes = new Uint8Array(binary.length) + for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i) + if (!startsWithPngSignature(bytes)) { + throw new Error('canvas.toDataURL produced bytes without a PNG signature') + } + return bytes +} + +async function canvasToPng(canvas: HTMLCanvasElement): Promise<Uint8Array> { + const blob = await canvasBlob(canvas) + if (blob) { + const bytes = new Uint8Array(await blob.arrayBuffer()) + if (startsWithPngSignature(bytes)) return bytes + } + return pngFromDataUrl(canvas) +} + +export const browserRasterizer: Rasterizer = async ( + svg, + { widthPx, heightPx }, +) => { + const img = await loadImage(sizedSvg(svg, widthPx, heightPx)) + return canvasToPng(drawOnWhiteCanvas(img, widthPx, heightPx)) +} diff --git a/apps/app/src/pdf/export.ts b/apps/app/src/pdf/export.ts index 4414c759..d6dadbc4 100644 --- a/apps/app/src/pdf/export.ts +++ b/apps/app/src/pdf/export.ts @@ -1,97 +1,46 @@ -import { PDFDocument } from 'pdf-lib' -import type { Report } from '@faunosteo/domain' -import type { Locale } from '@/i18n/types' -import { getDict } from '@/i18n' -import type { SheetIndex } from '@/services/sheetIndex' -import { embedFonts } from './fonts' -import { addObservationPage } from './render/observationPage' -import { addConclusionPage } from './render/conclusionPage' -import { attachReportJson } from './attachment' -import { drawFooter } from './render/footer' +import { buildSheetSnapshot, type Report } from '@faunosteo/domain' import { - loadFaunosteoLogo, - loadFaunosteoComLogo, - loadZenqualityLogo, -} from './render/logo' -import { rasterizeSvg } from './render/svgToPng' + defaultPdfLabels, + exportReportArchive, + type ExportWarning, +} from '@faunosteo/pdf' +import type { Locale } from '@/i18n/types' +import type { SheetIndex } from '@/services/sheetIndex' +import { loadBranding } from './branding' +import { browserRasterizer } from './browserRasterizer' export interface PdfExportOptions { locale: Locale } +export interface PdfExportResult { + pdf: Uint8Array + /** Non-fatal engine warnings: a logo or a view that failed to embed. */ + warnings: ExportWarning[] +} + /** - * Exports a report to PDF from the in-memory document and the loaded sheet: - * labels and drawings come from the sheet, nothing is fetched except the - * partner logos. The v3 document is attached for re-import. + * Exports the report as an archive PDF through the engine: the loaded sheet + * becomes the snapshot the pages are drawn from and the attachment carries, + * the branding comes from the bundled logos, the browser rasterises the + * views. Warnings are logged and returned for the caller to surface. */ export async function exportReportToPdf( report: Report, - sheet: SheetIndex, + index: SheetIndex, opts: PdfExportOptions, -): Promise<Uint8Array> { - const { locale } = opts - const dict = getDict(locale) - const pdfDoc = await PDFDocument.create() - pdfDoc.setTitle(`${dict['pdf.title.suffix.bilan']}${report.animal.name}`) - pdfDoc.setAuthor(report.practitioner.name) - pdfDoc.setSubject(dict['pdf.subject']) - pdfDoc.setCreationDate(new Date()) - pdfDoc.setModificationDate(new Date()) - - const fonts = await embedFonts(pdfDoc) - - let headerLogoPdf = null - let footerLogoPdf = null - let zqLogoPdfImage = null - let pawsLogoPdf = null - try { - headerLogoPdf = await pdfDoc.embedPng(await loadFaunosteoLogo()) - } catch (err) { - console.warn('Faunosteo logo embed failed:', err) - } - try { - footerLogoPdf = await pdfDoc.embedPng(await loadFaunosteoComLogo()) - } catch (err) { - console.warn('Faunosteo -com logo embed failed:', err) - } - try { - zqLogoPdfImage = await pdfDoc.embedPng(await loadZenqualityLogo()) - } catch (err) { - console.warn('ZenQuality logo embed failed:', err) - } - try { - const resp = await fetch('/Paws_in_harmony.svg') - if (!resp.ok) throw new Error(`Paws logo fetch failed: HTTP ${resp.status}`) - pawsLogoPdf = await pdfDoc.embedPng(await rasterizeSvg(await resp.text())) - } catch (err) { - console.warn('Paws in Harmony logo embed failed:', err) - } - - const headerAssets = { logoPng: headerLogoPdf } - for (let i = 0; i < report.observations.length; i += 1) { - await addObservationPage({ - pdfDoc, - report, - observation: report.observations[i]!, - obsIndex: i, - fonts, - sheet, - locale, - headerAssets, - }) - } - await addConclusionPage(pdfDoc, report, fonts, locale, headerAssets) - - const pages = pdfDoc.getPages() - const footerAssets = { - logoPng: footerLogoPdf, - zqLogoPng: zqLogoPdfImage, - pawsLogoPng: pawsLogoPdf, - } - pages.forEach((page, idx) => { - drawFooter(page, fonts, idx + 1, pages.length, locale, footerAssets) +): Promise<PdfExportResult> { + const result = await exportReportArchive({ + report, + sheet: buildSheetSnapshot(index.sheet, report), + branding: await loadBranding(), + labels: defaultPdfLabels, + locale: opts.locale, + rasterizer: browserRasterizer, + exportedAt: new Date(), }) - - await attachReportJson(pdfDoc, report) - return pdfDoc.save() + for (const warning of result.warnings) { + console.warn('PDF export warning', warning) + } + return { pdf: result.pdf, warnings: result.warnings } } diff --git a/apps/app/src/pdf/import.ts b/apps/app/src/pdf/import.ts index e4a4ee8e..267ff5cf 100644 --- a/apps/app/src/pdf/import.ts +++ b/apps/app/src/pdf/import.ts @@ -1,15 +1,13 @@ -import { PDFDocument } from 'pdf-lib' -import type { ReportMigrationMap } from '@faunosteo/domain' +import type { ArchiveReadOutcome, ReportMigrationMap } from '@faunosteo/domain' import { - extractReportJson, - IncompatibleReportVersionError, - type ExtractedReport, -} from './attachment' + ArchiveReadError, + readReportArchive, + type ArchiveReadErrorKind, +} from '@faunosteo/pdf' -export type ImportErrorKind = - | 'invalid_pdf' - | 'incompatible_version' - | 'no_attachment' +export { MAX_PDF_BYTES } from '@faunosteo/pdf' + +export type ImportErrorKind = ArchiveReadErrorKind /** * Localization-agnostic import error. Carries a kind discriminant + an @@ -26,31 +24,22 @@ export class ImportError extends Error { } } -/** A Faunosteo PDF weighs a few hundred KB; anything larger is not one. */ -export const MAX_PDF_BYTES = 50 * 1024 * 1024 - /** - * Reads a Faunosteo PDF back into a report document (v3, or v2 migrated - * through the reference sheet's map). The outcome says whether a migration - * happened and how many zones or findings it could not place. + * Reads a Faunosteo PDF back through the engine: the report (v3 as is, v2 + * migrated through the sheet's map) and, when the file is a Step 6 archive, + * the validated envelope or the reason its snapshot was dropped. Engine + * failures become ImportError kinds, one to one. */ export async function importReportFromPdf( pdfBytes: Uint8Array, map: ReportMigrationMap, -): Promise<ExtractedReport> { - if (pdfBytes.byteLength > MAX_PDF_BYTES) throw new ImportError('invalid_pdf') - let pdfDoc: PDFDocument +): Promise<ArchiveReadOutcome> { try { - pdfDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true }) - } catch { - throw new ImportError('invalid_pdf') - } - try { - return await extractReportJson(pdfDoc, map) + return await readReportArchive(pdfBytes, map) } catch (err) { - if (err instanceof IncompatibleReportVersionError) { - throw new ImportError('incompatible_version', err.foundVersion) + if (err instanceof ArchiveReadError) { + throw new ImportError(err.kind, err.foundVersion) } - throw new ImportError('no_attachment') + throw err } } diff --git a/apps/app/src/pdf/render/footer.ts b/apps/app/src/pdf/render/footer.ts deleted file mode 100644 index 00849dfa..00000000 --- a/apps/app/src/pdf/render/footer.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { rgb, type PDFPage, type PDFImage } from 'pdf-lib' -import type { EmbeddedFonts } from '@/pdf/fonts' -import type { Locale } from '@/i18n/types' -import { getDict } from '@/i18n' -import { addLinkAnnotation } from './linkAnnotation' -import { MARGIN_X, COLOR_MUTED } from './constants' - -const FOOTER_BASE_Y = 20 -const FONT_SIZE = 8 - -export interface FooterAssets { - logoPng: PDFImage | null - zqLogoPng: PDFImage | null - pawsLogoPng: PDFImage | null -} - -export function drawFooter( - page: PDFPage, - fonts: EmbeddedFonts, - pageNumber: number, - totalPages: number, - locale: Locale, - assets: FooterAssets, -): void { - const dict = getDict(locale) - const { width } = page.getSize() - const accent = rgb(0.28, 0.56, 0.42) - - const logoW = 80 - const logoH = 30 - const rowY = FOOTER_BASE_Y + 14 - const separatorY = rowY + logoH + 6 - - page.drawLine({ - start: { x: MARGIN_X, y: separatorY }, - end: { x: width - MARGIN_X, y: separatorY }, - thickness: 0.5, - color: rgb(0.85, 0.83, 0.8), - }) - - if (assets.logoPng) { - page.drawImage(assets.logoPng, { - x: MARGIN_X, - y: rowY, - width: logoW, - height: logoH, - }) - addLinkAnnotation(page, { - x: MARGIN_X, - y: rowY, - width: logoW, - height: logoH, - url: 'https://faunosteo.com', - }) - } - - const poweredLabel = `${dict['footer.powered_by']} ` - const poweredLabelW = fonts.bodyRegular.widthOfTextAtSize( - poweredLabel, - FONT_SIZE, - ) - const zqLogoW = 70 - const zqLogoH = 16 - const zqFallback = 'zenquality.fr' - const zqFallbackW = fonts.bodyRegular.widthOfTextAtSize(zqFallback, FONT_SIZE) - const poweredBlockW = assets.zqLogoPng - ? poweredLabelW + zqLogoW - : poweredLabelW + zqFallbackW - const poweredX = (width - poweredBlockW) / 2 - const textBaseY = rowY + 6 - - page.drawText(poweredLabel, { - x: poweredX, - y: textBaseY, - size: FONT_SIZE, - font: fonts.bodyRegular, - color: COLOR_MUTED, - }) - const zqX = poweredX + poweredLabelW - if (assets.zqLogoPng) { - page.drawImage(assets.zqLogoPng, { - x: zqX, - y: rowY + 2, - width: zqLogoW, - height: zqLogoH, - }) - addLinkAnnotation(page, { - x: zqX, - y: rowY + 2, - width: zqLogoW, - height: zqLogoH, - url: 'https://zenquality.fr', - }) - } else { - page.drawText(zqFallback, { - x: zqX, - y: textBaseY, - size: FONT_SIZE, - font: fonts.bodyRegular, - color: accent, - }) - addLinkAnnotation(page, { - x: zqX, - y: textBaseY - 2, - width: zqFallbackW, - height: FONT_SIZE + 4, - url: 'https://zenquality.fr', - }) - } - - const partnerLabel = `${dict['footer.in_partnership']} ` - const partnerLabelW = fonts.bodyRegular.widthOfTextAtSize( - partnerLabel, - FONT_SIZE, - ) - const partnerUrl = 'https://www.instagram.com/paws.iin.harmony' - - if (assets.pawsLogoPng) { - const pawsLogoH = 16 - const pawsLogoW = - pawsLogoH * (assets.pawsLogoPng.width / assets.pawsLogoPng.height) - const partnerX = width - MARGIN_X - partnerLabelW - pawsLogoW - page.drawText(partnerLabel, { - x: partnerX, - y: textBaseY, - size: FONT_SIZE, - font: fonts.bodyRegular, - color: COLOR_MUTED, - }) - const pawsX = partnerX + partnerLabelW - page.drawImage(assets.pawsLogoPng, { - x: pawsX, - y: rowY + 2, - width: pawsLogoW, - height: pawsLogoH, - }) - addLinkAnnotation(page, { - x: pawsX, - y: rowY + 2, - width: pawsLogoW, - height: pawsLogoH, - url: partnerUrl, - }) - } else { - const handle = '@paws.iin.harmony' - const handleW = fonts.bodyRegular.widthOfTextAtSize(handle, FONT_SIZE) - const partnerX = width - MARGIN_X - partnerLabelW - handleW - page.drawText(partnerLabel, { - x: partnerX, - y: textBaseY, - size: FONT_SIZE, - font: fonts.bodyRegular, - color: COLOR_MUTED, - }) - page.drawText(handle, { - x: partnerX + partnerLabelW, - y: textBaseY, - size: FONT_SIZE, - font: fonts.bodyRegular, - color: accent, - }) - addLinkAnnotation(page, { - x: partnerX + partnerLabelW, - y: textBaseY - 2, - width: handleW, - height: FONT_SIZE + 4, - url: partnerUrl, - }) - } - - const pageText = `${pageNumber} / ${totalPages}` - const pageW = fonts.bodyRegular.widthOfTextAtSize(pageText, FONT_SIZE) - page.drawText(pageText, { - x: (width - pageW) / 2, - y: FOOTER_BASE_Y + 2, - size: FONT_SIZE, - font: fonts.bodyRegular, - color: COLOR_MUTED, - }) -} diff --git a/apps/app/src/pdf/render/header.ts b/apps/app/src/pdf/render/header.ts deleted file mode 100644 index 9578a74f..00000000 --- a/apps/app/src/pdf/render/header.ts +++ /dev/null @@ -1,100 +0,0 @@ -import type { PDFPage, PDFImage } from 'pdf-lib' -import type { EmbeddedFonts } from '@/pdf/fonts' -import type { Report } from '@faunosteo/domain' -import type { Locale } from '@/i18n/types' -import { getDict } from '@/i18n' -import { formatDate } from '@/lib/dates' -import { addLinkAnnotation } from './linkAnnotation' -import { MARGIN_X, COLOR_INK, COLOR_MUTED } from './constants' - -const TOP_Y = 800 -const LOGO_WIDTH = 100 -const LOGO_HEIGHT = 38 - -export interface HeaderAssets { - logoPng: PDFImage | null -} - -export function drawHeader( - page: PDFPage, - report: Report, - fonts: EmbeddedFonts, - locale: Locale, - assets: HeaderAssets, -): void { - const dict = getDict(locale) - const { width } = page.getSize() - - const y = TOP_Y - - const left = [ - report.practitioner.name, - report.practitioner.cabinet, - report.practitioner.contact, - report.practitioner.siret - ? `${dict['pdf.siret_prefix']}${report.practitioner.siret}` - : undefined, - ].filter(Boolean) as string[] - - left.forEach((line, i) => { - page.drawText(line, { - x: MARGIN_X, - y: y - i * 12, - size: i === 0 ? 11 : 9, - font: i === 0 ? fonts.bodyBold : fonts.bodyRegular, - color: i === 0 ? COLOR_INK : COLOR_MUTED, - }) - }) - - if (assets.logoPng) { - const logoX = (width - LOGO_WIDTH) / 2 - const logoY = y - LOGO_HEIGHT + 10 - page.drawImage(assets.logoPng, { - x: logoX, - y: logoY, - width: LOGO_WIDTH, - height: LOGO_HEIGHT, - }) - addLinkAnnotation(page, { - x: logoX, - y: logoY, - width: LOGO_WIDTH, - height: LOGO_HEIGHT, - url: 'https://faunosteo.com', - }) - } - - const animalLine = [ - report.animal.name, - report.animal.breed ? `(${report.animal.breed})` : '', - report.animal.age ? `· ${report.animal.age}` : '', - ] - .filter(Boolean) - .join(' ') - - const right = [ - animalLine, - `${dict['pdf.owner_prefix']}${report.owner.name}`, - formatDate(report.date, locale), - ] - right.forEach((line, i) => { - const size = i === 0 ? 11 : 9 - const font = i === 0 ? fonts.bodyBold : fonts.bodyRegular - const w = font.widthOfTextAtSize(line, size) - page.drawText(line, { - x: width - MARGIN_X - w, - y: y - i * 12, - size, - font, - color: i === 0 ? COLOR_INK : COLOR_MUTED, - }) - }) - - const separatorY = y - Math.max(left.length * 12, LOGO_HEIGHT) - 8 - page.drawLine({ - start: { x: MARGIN_X, y: separatorY }, - end: { x: width - MARGIN_X, y: separatorY }, - thickness: 0.5, - color: COLOR_MUTED, - }) -} diff --git a/apps/app/src/pdf/render/linkAnnotation.ts b/apps/app/src/pdf/render/linkAnnotation.ts deleted file mode 100644 index 19afeb5f..00000000 --- a/apps/app/src/pdf/render/linkAnnotation.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { PDFName, PDFArray, PDFString, type PDFPage } from 'pdf-lib' - -export interface LinkRect { - x: number - y: number - width: number - height: number - url: string -} - -export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void { - const context = page.doc.context - - const actionDict = context.obj({ - Type: 'Action', - S: 'URI', - URI: PDFString.of(rect.url), - }) - - const annotDict = context.obj({ - Type: 'Annot', - Subtype: 'Link', - Rect: [rect.x, rect.y, rect.x + rect.width, rect.y + rect.height], - Border: [0, 0, 0], - A: actionDict, - }) - - const annots = page.node.lookup(PDFName.of('Annots'), PDFArray) - if (annots) { - annots.push(context.register(annotDict)) - } else { - const arr = context.obj([context.register(annotDict)]) - page.node.set(PDFName.of('Annots'), arr) - } -} diff --git a/apps/app/src/pdf/render/logo.ts b/apps/app/src/pdf/render/logo.ts deleted file mode 100644 index f16f4de7..00000000 --- a/apps/app/src/pdf/render/logo.ts +++ /dev/null @@ -1,21 +0,0 @@ -const FAUNOSTEO_LOGO = '/assets/faunosteo_logo_horizontal-512.png' -const FAUNOSTEO_COM_LOGO = '/assets/faunosteo-horizontal-com-512.png' -const ZENQUALITY_LOGO = '/brand/zenquality-logo-fr.png' - -async function fetchPngBytes(path: string): Promise<Uint8Array> { - const resp = await fetch(path) - if (!resp.ok) throw new Error(`Logo fetch failed: HTTP ${resp.status}`) - return new Uint8Array(await resp.arrayBuffer()) -} - -export async function loadFaunosteoLogo(): Promise<Uint8Array> { - return fetchPngBytes(FAUNOSTEO_LOGO) -} - -export async function loadFaunosteoComLogo(): Promise<Uint8Array> { - return fetchPngBytes(FAUNOSTEO_COM_LOGO) -} - -export async function loadZenqualityLogo(): Promise<Uint8Array> { - return fetchPngBytes(ZENQUALITY_LOGO) -} diff --git a/apps/app/src/pdf/render/observationPage.ts b/apps/app/src/pdf/render/observationPage.ts deleted file mode 100644 index dda08110..00000000 --- a/apps/app/src/pdf/render/observationPage.ts +++ /dev/null @@ -1,627 +0,0 @@ -import { - rgb, - PageSizes, - type PDFDocument, - type PDFPage, - type PDFImage, -} from 'pdf-lib' -import type { - Finding, - Observation, - Report, - ReportZone, - Severity, -} from '@faunosteo/domain' -import type { EmbeddedFonts } from '@/pdf/fonts' -import type { Locale, Dict } from '@/i18n/types' -import { getDict } from '@/i18n' -import { pickLabel, type SheetIndex } from '@/services/sheetIndex' -import { buildViewSvg } from '@/anatomy/drawing' -import { drawHeader, type HeaderAssets } from './header' -import { rasterizeSvg } from './svgToPng' -import { wrapLines } from './text' -import { - MARGIN_X, - EYEBROW_Y_OFFSET, - TITLE_Y_OFFSET, - TITLE_RULE_OFFSET, - TITLE_RULE_WIDTH, - SECTION_LABEL_GAP, - COLOR_INK, - COLOR_MUTED, - COLOR_ACCENT, -} from './constants' - -const MARGIN_BOTTOM = 48 -const IMAGE_TOP_GAP = 32 -const IMAGE_LABEL_GAP = 14 -const IMAGE_BOTTOM_GAP = 14 -const IMAGE_COL_GAP = 16 -const IMAGE_ROW_GAP = 12 -const IMAGE_MIN_CELL_H = 60 -const TEXT_TOP_GAP = 10 -const TEXT_LINE_HEIGHT = 13 -const SECTION_BLOCK_GAP = 10 - -const COLOR_WHITE = rgb(1, 1, 1) - -const SEVERITY_BG: Record<Severity, ReturnType<typeof rgb>> = { - mild: rgb(0.55, 0.65, 0.45), - moderate: rgb(0.85, 0.55, 0.18), - severe: rgb(0.78, 0.2, 0.2), -} - -const SECTION_TEXT_SIZE = 10 -const SEPARATOR_GLYPH = '•' -const SEPARATOR_SIZE = 14 -const SEPARATOR_SIDE_GAP = 5 - -/** Width of the visible separator block including the empty space on each side. */ -function separatorWidth(fonts: EmbeddedFonts): number { - return ( - fonts.bodyBold.widthOfTextAtSize(SEPARATOR_GLYPH, SEPARATOR_SIZE) + - SEPARATOR_SIDE_GAP * 2 - ) -} - -/** Counts the line breaks a list of items would consume when laid out on a maxWidth line. */ -function countSegmentedLines( - items: string[], - fonts: EmbeddedFonts, - maxWidth: number, -): number { - if (items.length === 0) return 1 - const sepW = separatorWidth(fonts) - let lines = 1 - let x = 0 - for (let i = 0; i < items.length; i += 1) { - const itemW = fonts.bodyRegular.widthOfTextAtSize( - items[i]!, - SECTION_TEXT_SIZE, - ) - if (x + itemW > maxWidth && x > 0) { - lines += 1 - x = 0 - } - x += itemW - if (i < items.length - 1) { - if (x + sepW > maxWidth) { - lines += 1 - x = 0 - } else { - x += sepW - } - } - } - return lines -} - -/** - * Renders a list of items separated by a visibly larger accent-coloured - * bullet. Returns the cursor y *below* the last line drawn. - */ -function drawSegmentedText( - page: PDFPage, - items: string[], - startX: number, - startY: number, - maxWidth: number, - fonts: EmbeddedFonts, -): number { - if (items.length === 0) return startY - TEXT_LINE_HEIGHT - const sepW = separatorWidth(fonts) - const sepBaselineOffset = (SEPARATOR_SIZE - SECTION_TEXT_SIZE) * 0.3 - let x = startX - let y = startY - for (let i = 0; i < items.length; i += 1) { - const item = items[i]! - const itemW = fonts.bodyRegular.widthOfTextAtSize(item, SECTION_TEXT_SIZE) - if (x + itemW > startX + maxWidth && x > startX) { - x = startX - y -= TEXT_LINE_HEIGHT - } - page.drawText(item, { - x, - y, - size: SECTION_TEXT_SIZE, - font: fonts.bodyRegular, - color: COLOR_INK, - }) - x += itemW - if (i < items.length - 1) { - if (x + sepW > startX + maxWidth) { - x = startX - y -= TEXT_LINE_HEIGHT - } else { - page.drawText(SEPARATOR_GLYPH, { - x: x + SEPARATOR_SIDE_GAP, - y: y - sepBaselineOffset, - size: SEPARATOR_SIZE, - font: fonts.bodyBold, - color: COLOR_ACCENT, - }) - x += sepW - } - } - } - return y - TEXT_LINE_HEIGHT -} - -const SVG_NS = 'http://www.w3.org/2000/svg' -const HALO_FILTER_ID = 'osteo-halo' - -/** - * Adds a Gaussian-blur "halo" filter so the highlighted markers stay - * visible on the whole-animal view once rasterised at print scale. - */ -function ensureHaloFilter(root: SVGSVGElement): void { - const doc = root.ownerDocument - if (root.querySelector(`#${HALO_FILTER_ID}`)) return - let defs = root.querySelector('defs') - if (!defs) { - defs = doc.createElementNS(SVG_NS, 'defs') - root.insertBefore(defs, root.firstChild) - } - const filter = doc.createElementNS(SVG_NS, 'filter') - filter.setAttribute('id', HALO_FILTER_ID) - filter.setAttribute('x', '-100%') - filter.setAttribute('y', '-100%') - filter.setAttribute('width', '300%') - filter.setAttribute('height', '300%') - filter.setAttribute('filterUnits', 'userSpaceOnUse') - const wide = doc.createElementNS(SVG_NS, 'feGaussianBlur') - wide.setAttribute('in', 'SourceGraphic') - wide.setAttribute('stdDeviation', '18') - wide.setAttribute('result', 'haloWide') - filter.appendChild(wide) - const tight = doc.createElementNS(SVG_NS, 'feGaussianBlur') - tight.setAttribute('in', 'SourceGraphic') - tight.setAttribute('stdDeviation', '8') - tight.setAttribute('result', 'haloTight') - filter.appendChild(tight) - const merge = doc.createElementNS(SVG_NS, 'feMerge') - for (const input of [ - 'haloWide', - 'haloWide', - 'haloWide', - 'haloTight', - 'haloTight', - 'SourceGraphic', - ]) { - const n = doc.createElementNS(SVG_NS, 'feMergeNode') - n.setAttribute('in', input) - merge.appendChild(n) - } - filter.appendChild(merge) - defs.appendChild(filter) -} - -/** - * The view rendered from the sheet with the observation's zones of that - * view highlighted (legacy picture: accent fill, halo on the main view, - * other markers hidden, no data attributes left). - */ -export function highlightedViewSvg( - sheet: SheetIndex, - viewId: string, - observation: Observation, -): string { - const selected = new Set( - observation.zones - .filter((z) => z.viewId === viewId) - .map((z) => z.annotationId), - ) - const root = buildViewSvg(sheet, viewId, new Map()) - const applyHalo = sheet.view(viewId)?.kind === 'main' - if (applyHalo) ensureHaloFilter(root) - root.querySelectorAll<Element>('[data-anno-id]').forEach((el) => { - if (selected.has(el.getAttribute('data-anno-id') ?? '')) { - el.setAttribute('fill', '#b85a3f') - el.setAttribute('fill-opacity', '0.85') - if (applyHalo) el.setAttribute('filter', `url(#${HALO_FILTER_ID})`) - } else { - el.setAttribute('display', 'none') - } - Array.from(el.attributes) - .filter((a) => a.name.startsWith('data-')) - .forEach((a) => el.removeAttribute(a.name)) - }) - return new XMLSerializer().serializeToString(root) -} - -/** Parameters needed to render one observation page. */ -export interface ObservationPageContext { - pdfDoc: PDFDocument - report: Report - observation: Observation - obsIndex: number - fonts: EmbeddedFonts - sheet: SheetIndex - locale: Locale - headerAssets: HeaderAssets -} - -interface PageDrawContext { - page: PDFPage - fonts: EmbeddedFonts - width: number -} - -interface RenderedImage { - label: string - img: PDFImage - aspect: number -} - -interface ObservationSection { - label: string - value: string -} - -function drawObservationTitleBlock( - ctx: PageDrawContext, - dict: Dict, - obsIndex: number, - severity: Severity | undefined, -): number { - const { page, fonts } = ctx - const { height } = page.getSize() - const eyebrowY = height - EYEBROW_Y_OFFSET - const titleY = height - TITLE_Y_OFFSET - const obsLabel = String(obsIndex + 1).padStart(2, '0') - page.drawText(dict['pdf.eyebrow.observation']!, { - x: MARGIN_X, - y: eyebrowY, - size: 9, - font: fonts.bodyBold, - color: COLOR_ACCENT, - }) - page.drawText(obsLabel, { - x: MARGIN_X, - y: titleY, - size: 22, - font: fonts.headingRegular, - color: COLOR_INK, - }) - if (severity) { - const numW = fonts.headingRegular.widthOfTextAtSize(obsLabel, 22) - const sevText = (dict[`severity.${severity}`] ?? severity).toUpperCase() - const sevSize = 9 - const padX = 8 - const padY = 4 - const pillW = fonts.bodyBold.widthOfTextAtSize(sevText, sevSize) + padX * 2 - const pillH = sevSize + padY * 2 - const pillX = MARGIN_X + numW + 14 - const pillY = titleY + 4 - page.drawRectangle({ - x: pillX, - y: pillY, - width: pillW, - height: pillH, - color: SEVERITY_BG[severity] ?? COLOR_MUTED, - }) - page.drawText(sevText, { - x: pillX + padX, - y: pillY + padY, - size: sevSize, - font: fonts.bodyBold, - color: COLOR_WHITE, - }) - } - page.drawLine({ - start: { x: MARGIN_X, y: titleY - TITLE_RULE_OFFSET }, - end: { x: MARGIN_X + TITLE_RULE_WIDTH, y: titleY - TITLE_RULE_OFFSET }, - thickness: 2, - color: COLOR_ACCENT, - }) - return titleY -} - -/** Every view the observation touches, main first, each rasterised with its highlights. */ -async function buildObservationImages( - pdfDoc: PDFDocument, - sheet: SheetIndex, - observation: Observation, - locale: Locale, - dict: Dict, -): Promise<RenderedImage[]> { - const viewIds = [...new Set(observation.zones.map((z) => z.viewId))] - .filter((id) => sheet.view(id)) - .sort( - (a, b) => - Number(b === sheet.mainView.id) - Number(a === sheet.mainView.id), - ) - return Promise.all( - viewIds.map(async (viewId) => { - const view = sheet.view(viewId)! - const label = - view.kind === 'main' - ? dict['pdf.view.general']! - : `${dict['pdf.view.detail_prefix']}${pickLabel(view.name, locale).toUpperCase()}` - const png = await rasterizeSvg( - highlightedViewSvg(sheet, viewId, observation), - ) - const img = await pdfDoc.embedPng(png) - return { - label, - img, - aspect: img.width > 0 ? img.height / img.width : 0.6, - } - }), - ) -} - -function zoneText(z: ReportZone, sheet: SheetIndex, locale: Locale): string { - const annotation = sheet.annotation(z.annotationId) - if (annotation) return pickLabel(sheet.name(annotation), locale) - const snapshot = - locale === 'en' - ? z.labelEnSnapshot || z.labelFrSnapshot - : z.labelFrSnapshot || z.labelEnSnapshot - return snapshot || z.annotationId -} - -function describeObservationZones( - zones: ReportZone[], - sheet: SheetIndex, - locale: Locale, - dict: Dict, -): string { - return zones - .map((z) => { - const v = z.vertebrae?.length - ? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})` - : '' - const side = z.side - ? ` (${dict[z.side === 'left' ? 'lateral.left' : 'lateral.right']})` - : '' - return `${zoneText(z, sheet, locale)}${v}${side}` - }) - .join(' · ') -} - -function findingZoneName( - zoneId: string, - sheet: SheetIndex, - locale: Locale, -): string { - const zone = sheet.findingZone(zoneId) - return zone ? pickLabel(zone.name, locale) : zoneId -} - -/** Groups findings by zone+side, one section per group; snapshots give the text. */ -function buildFindingsSections( - findings: Finding[], - sheet: SheetIndex, - locale: Locale, - dict: Dict, -): ObservationSection[] { - const byZoneSide = new Map<string, Finding[]>() - for (const f of findings) { - const key = f.side ? `${f.findingZoneId}:${f.side}` : f.findingZoneId - byZoneSide.set(key, [...(byZoneSide.get(key) ?? []), f]) - } - const sections: ObservationSection[] = [] - for (const [key, group] of byZoneSide) { - const zoneId = key.split(':')[0]! - const side = group[0]?.side - let zoneName = findingZoneName(zoneId, sheet, locale) - if (side) - zoneName = `${zoneName} (${dict[side === 'left' ? 'lateral.left' : 'lateral.right']})` - const value = group - .map((f) => { - const lbl = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot - return f.requiresVetReferral ? `(!) ${lbl}` : lbl - }) - .join(' · ') - sections.push({ - label: `${dict['pdf.section.findings_prefix']}${zoneName.toUpperCase()}`, - value, - }) - } - return sections -} - -function buildObservationSections( - observation: Observation, - sheet: SheetIndex, - locale: Locale, - dict: Dict, -): ObservationSection[] { - const zonesText = describeObservationZones( - observation.zones, - sheet, - locale, - dict, - ) - const sections: ObservationSection[] = [ - { - label: dict['pdf.section.zones']!, - value: zonesText || dict['pdf.empty']!, - }, - ...buildFindingsSections(observation.findings, sheet, locale, dict), - ] - if (observation.freeTextFindings.length) { - sections.push({ - label: dict['pdf.section.free_findings']!, - value: observation.freeTextFindings.join(' · '), - }) - } - if (observation.severity) { - sections.push({ - label: dict['pdf.section.severity']!, - value: dict[`severity.${observation.severity}`] ?? observation.severity, - }) - } - if (observation.comment.trim()) { - sections.push({ - label: dict['pdf.section.comment']!, - value: observation.comment.trim(), - }) - } - return sections -} - -function estimateSectionsHeight( - sections: ObservationSection[], - fonts: EmbeddedFonts, - maxTextW: number, -): number { - let h = TEXT_TOP_GAP - for (const { value } of sections) { - const lineCount = value.includes(' · ') - ? countSegmentedLines(value.split(' · '), fonts, maxTextW) - : wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW).length - h += - SECTION_LABEL_GAP + 9 + lineCount * TEXT_LINE_HEIGHT + SECTION_BLOCK_GAP - } - return h -} - -/** Lays out the (up to 2-column) image grid; returns the cursor y below it. */ -function drawObservationImageGrid( - ctx: PageDrawContext, - rendered: RenderedImage[], - startY: number, - reservedBottom: number, -): number { - const { page, fonts, width } = ctx - let cursorY = startY - if (rendered.length === 0) return cursorY - const isSingle = rendered.length === 1 - const cols = isSingle ? 1 : 2 - const rows = Math.ceil(rendered.length / cols) - const fullCellW = (width - MARGIN_X * 2 - IMAGE_COL_GAP * (cols - 1)) / cols - const cellW = isSingle ? fullCellW / 2 : fullCellW - const singleOffsetX = isSingle ? (fullCellW - cellW) / 2 : 0 - const availH = Math.max(IMAGE_MIN_CELL_H, cursorY - reservedBottom) - const rowBudget = Math.max( - IMAGE_MIN_CELL_H, - (availH - rows * IMAGE_LABEL_GAP - (rows - 1) * IMAGE_ROW_GAP) / rows, - ) - for (let r = 0; r < rows; r += 1) { - const rowItems = rendered.slice(r * cols, r * cols + cols) - const cellHs = rowItems.map((it) => Math.min(cellW * it.aspect, rowBudget)) - const rowH = Math.max(0, ...cellHs) - rowItems.forEach((it, c) => { - const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP) - page.drawText(it.label, { - x, - y: cursorY, - size: 8, - font: fonts.bodyBold, - color: COLOR_ACCENT, - }) - }) - cursorY -= IMAGE_LABEL_GAP - rowItems.forEach((it, c) => { - const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP) - page.drawImage(it.img, { - x, - y: cursorY - cellHs[c]!, - width: cellW, - height: cellHs[c]!, - }) - }) - cursorY -= rowH - if (r < rows - 1) cursorY -= IMAGE_ROW_GAP - } - cursorY -= IMAGE_BOTTOM_GAP - return cursorY -} - -function drawObservationSections( - ctx: PageDrawContext, - sections: ObservationSection[], - startY: number, - maxTextW: number, -): number { - const { page, fonts } = ctx - let cursorY = startY - for (const { label, value } of sections) { - page.drawText(label, { - x: MARGIN_X, - y: cursorY, - size: 8, - font: fonts.bodyBold, - color: COLOR_ACCENT, - }) - cursorY -= SECTION_LABEL_GAP + 9 - if (value.includes(' · ')) { - cursorY = drawSegmentedText( - page, - value.split(' · '), - MARGIN_X, - cursorY, - maxTextW, - fonts, - ) - } else { - for (const line of wrapLines( - value, - fonts.bodyRegular, - SECTION_TEXT_SIZE, - maxTextW, - )) { - page.drawText(line, { - x: MARGIN_X, - y: cursorY, - size: SECTION_TEXT_SIZE, - font: fonts.bodyRegular, - color: COLOR_INK, - }) - cursorY -= TEXT_LINE_HEIGHT - } - } - cursorY -= SECTION_BLOCK_GAP - } - return cursorY -} - -export async function addObservationPage( - ctx: ObservationPageContext, -): Promise<void> { - const { - pdfDoc, - report, - observation, - obsIndex, - fonts, - sheet, - locale, - headerAssets, - } = ctx - const dict = getDict(locale) - const page = pdfDoc.addPage(PageSizes.A4) - const { width } = page.getSize() - drawHeader(page, report, fonts, locale, headerAssets) - - const drawCtx: PageDrawContext = { page, fonts, width } - const titleY = drawObservationTitleBlock( - drawCtx, - dict, - obsIndex, - observation.severity, - ) - const rendered = await buildObservationImages( - pdfDoc, - sheet, - observation, - locale, - dict, - ) - const maxTextW = width - MARGIN_X * 2 - const sections = buildObservationSections(observation, sheet, locale, dict) - const reservedBottom = - MARGIN_BOTTOM + - estimateSectionsHeight(sections, fonts, maxTextW) + - IMAGE_BOTTOM_GAP - let cursorY = drawObservationImageGrid( - drawCtx, - rendered, - titleY - IMAGE_TOP_GAP, - reservedBottom, - ) - cursorY -= TEXT_TOP_GAP - drawObservationSections(drawCtx, sections, cursorY, maxTextW) -} diff --git a/apps/app/src/pdf/render/svgToPng.ts b/apps/app/src/pdf/render/svgToPng.ts deleted file mode 100644 index d85ac7cf..00000000 --- a/apps/app/src/pdf/render/svgToPng.ts +++ /dev/null @@ -1,124 +0,0 @@ -const TARGET_WIDTH = 1200 -const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] - -function startsWithPngSignature(bytes: Uint8Array): boolean { - if (bytes.length < PNG_SIGNATURE.length) return false - for (let i = 0; i < PNG_SIGNATURE.length; i += 1) { - if (bytes[i] !== PNG_SIGNATURE[i]) return false - } - return true -} - -function ensureSvgAttributes( - svgString: string, - widthPx: number, - heightPx: number, -): string { - const doc = new DOMParser().parseFromString(svgString, 'image/svg+xml') - const root = doc.documentElement - if (root.namespaceURI !== 'http://www.w3.org/2000/svg') { - // Some serializers strip xmlns; force the SVG namespace so - // browsers will rasterize the blob URL as an image. - root.setAttribute('xmlns', 'http://www.w3.org/2000/svg') - } - if (!root.getAttribute('width')) root.setAttribute('width', String(widthPx)) - if (!root.getAttribute('height')) - root.setAttribute('height', String(heightPx)) - return new XMLSerializer().serializeToString(root) -} - -function readViewBox(svgString: string): { - widthPx: number - heightPx: number -} { - const doc = new DOMParser().parseFromString(svgString, 'image/svg+xml') - const vb = (doc.documentElement.getAttribute('viewBox') ?? '0 0 1000 600') - .split(/\s+/) - .map(Number) - const ratio = vb[3] > 0 && vb[2] > 0 ? vb[3] / vb[2] : 0.6 - const widthPx = Math.max(1, Math.round(TARGET_WIDTH)) - const heightPx = Math.max(1, Math.round(ratio * widthPx)) - return { widthPx, heightPx } -} - -async function rasterizeWithImageElement( - svgString: string, - widthPx: number, - heightPx: number, -): Promise<HTMLCanvasElement> { - const normalized = ensureSvgAttributes(svgString, widthPx, heightPx) - const svgBlob = new Blob([normalized], { - type: 'image/svg+xml;charset=utf-8', - }) - const url = URL.createObjectURL(svgBlob) - const img = new Image() - img.decoding = 'sync' - img.crossOrigin = 'anonymous' - try { - await new Promise<void>((resolve, reject) => { - img.onload = () => resolve() - img.onerror = () => - reject(new Error('Browser failed to render the SVG into an Image')) - img.src = url - }) - } finally { - // The Blob URL is single-use — release it once the Image has loaded - // (or failed). - URL.revokeObjectURL(url) - } - - const canvas = document.createElement('canvas') - canvas.width = widthPx - canvas.height = heightPx - const ctx = canvas.getContext('2d') - if (!ctx) throw new Error('Canvas 2D context unavailable') - ctx.fillStyle = '#ffffff' - ctx.fillRect(0, 0, widthPx, heightPx) - ctx.drawImage(img, 0, 0, widthPx, heightPx) - return canvas -} - -async function canvasToPngBytes( - canvas: HTMLCanvasElement, -): Promise<Uint8Array> { - const blob = await new Promise<Blob | null>((resolve) => { - canvas.toBlob((b) => resolve(b), 'image/png') - }) - if (blob) { - const bytes = new Uint8Array(await blob.arrayBuffer()) - if (startsWithPngSignature(bytes)) return bytes - } - const dataUrl = canvas.toDataURL('image/png') - if (!dataUrl.startsWith('data:image/png')) { - throw new Error( - `canvas.toDataURL produced non-PNG payload: ${dataUrl.slice(0, 32)}`, - ) - } - const comma = dataUrl.indexOf(',') - if (comma < 0) { - throw new Error('canvas.toDataURL returned a data URL without a payload') - } - const binary = atob(dataUrl.slice(comma + 1)) - const bytes = new Uint8Array(binary.length) - for (let i = 0; i < binary.length; i += 1) { - bytes[i] = binary.charCodeAt(i) - } - if (!startsWithPngSignature(bytes)) { - throw new Error('canvas.toDataURL produced bytes without a PNG signature') - } - return bytes -} - -/** - * Rasterizes an SVG string to a PNG byte array using the browser's native - * SVG-to-Image pipeline. The browser parses + draws the SVG via an - * Image/Blob URL pair, which renders identically to what the user sees in - * the inline anatomy canvas. - * - * @param svgString Serialized SVG (must declare `xmlns`) - */ -export async function rasterizeSvg(svgString: string): Promise<Uint8Array> { - const { widthPx, heightPx } = readViewBox(svgString) - const canvas = await rasterizeWithImageElement(svgString, widthPx, heightPx) - return canvasToPngBytes(canvas) -} diff --git a/apps/app/src/pdf/render/text.ts b/apps/app/src/pdf/render/text.ts deleted file mode 100644 index 0dbc58cd..00000000 --- a/apps/app/src/pdf/render/text.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { PDFFont } from 'pdf-lib' - -/** - * Greedy word-wrap: splits `text` into lines whose rendered width at - * `size` points stays within `max` for the given font. - */ -export function wrapLines( - text: string, - font: PDFFont, - size: number, - max: number, -): string[] { - const words = text.split(/\s+/) - const lines: string[] = [] - let line = '' - for (const w of words) { - const test = line ? `${line} ${w}` : w - if (font.widthOfTextAtSize(test, size) > max && line) { - lines.push(line) - line = w - } else { - line = test - } - } - if (line) lines.push(line) - return lines -} diff --git a/apps/app/src/services/sheetIndex.ts b/apps/app/src/services/sheetIndex.ts index 2ba60a2a..b21b3751 100644 --- a/apps/app/src/services/sheetIndex.ts +++ b/apps/app/src/services/sheetIndex.ts @@ -1,113 +1,11 @@ -import type { - Annotation, - FindingCategory, - FindingNode, - FindingZone, - LocalizedText, - SheetView, - VertebralRegion, -} from '@faunosteo/domain' -import type { Locale } from '@/i18n/types' +import type { SheetIndex as DomainSheetIndex } from '@faunosteo/domain' import type { LoadedSheet } from '@/sheets/provider' /** - * Read-only lookups over a loaded sheet. Everything the editor used to derive - * from SVG attributes, label matching or the species manifest comes from the - * document here, by stable id: no label drives logic. + * The sheet index lives in @faunosteo/domain since Step 6 (shared with the + * PDF engine). This shim keeps the app's import path and binds the index to + * the sheet the app loads, so `index.sheet` still carries the migration map. */ - -export type ObservableAnnotation = Extract< - Annotation, - { kind: 'point' | 'zone' } -> - -export interface SheetIndex { - sheet: LoadedSheet - mainView: SheetView - view(id: string): SheetView | undefined - annotation(id: string): Annotation | undefined - annotationsOfView(viewId: string): Annotation[] - findingZone(id: string): FindingZone | undefined - /** The category or node at a path, undefined when absent from the sheet. */ - nodeAt( - zoneId: string, - path: readonly string[], - ): FindingCategory | FindingNode | undefined - regions(): VertebralRegion[] - region(code: string): VertebralRegion | undefined - /** The annotation that opens the vertebra picker for a region on a view. */ - spineAnnotation( - regionCode: string, - viewId: string, - ): ObservableAnnotation | undefined - /** Whether an annotation opens the vertebra picker. */ - isSpine(annotationId: string): boolean - name(annotation: Annotation): LocalizedText -} - -export function pickLabel( - text: LocalizedText | null | undefined, - locale: Locale, -): string { - if (!text) return '' - return locale === 'en' ? text.en || text.fr : text.fr || text.en -} - -export function isObservable( - a: Annotation | undefined, -): a is ObservableAnnotation { - return a !== undefined && a.kind !== 'detail_trigger' -} - -export function buildSheetIndex(sheet: LoadedSheet): SheetIndex { - const { document } = sheet - const views = new Map(document.views.map((v) => [v.id, v])) - const annotations = new Map(document.annotations.map((a) => [a.id, a])) - const zones = new Map(document.finding_zones.map((z) => [z.id, z])) - const regions = new Map( - document.vertebral_config.regions.map((r) => [r.code, r]), - ) - const mainView = document.views.find((v) => v.kind === 'main') - if (!mainView) throw new Error('sheet has no main view') - - const nodeAt: SheetIndex['nodeAt'] = (zoneId, path) => { - const zone = zones.get(zoneId) - if (!zone || path.length === 0) return undefined - let node: FindingCategory | FindingNode | undefined = zone.categories.find( - (c) => c.id === path[0], - ) - for (const segment of path.slice(1)) { - if (!node) return undefined - node = node.children.find((n) => n.id === segment) - } - return node - } - - return { - sheet, - mainView, - view: (id) => views.get(id), - annotation: (id) => annotations.get(id), - annotationsOfView: (viewId) => - document.annotations.filter((a) => a.view_id === viewId), - findingZone: (id) => zones.get(id), - nodeAt, - regions: () => document.vertebral_config.regions, - region: (code) => regions.get(code), - spineAnnotation: (code, viewId) => - document.annotations.find( - (a): a is ObservableAnnotation => - isObservable(a) && - a.view_id === viewId && - a.vertebral_region_code === code, - ), - isSpine: (id) => { - const a = annotations.get(id) - return isObservable(a) && a.vertebral_region_code !== null - }, - name: (a) => - a.kind === 'detail_trigger' - ? (a.name ?? views.get(a.opens_view_id)?.name ?? { fr: '', en: '' }) - : a.name, - } -} +export { buildSheetIndex, isObservable, pickLabel } from '@faunosteo/domain' +export type { ObservableAnnotation } from '@faunosteo/domain' +export type SheetIndex = DomainSheetIndex<LoadedSheet> diff --git a/apps/app/src/sheets/provider.ts b/apps/app/src/sheets/provider.ts index a97a4d39..318c7bce 100644 --- a/apps/app/src/sheets/provider.ts +++ b/apps/app/src/sheets/provider.ts @@ -28,15 +28,21 @@ export interface BundledSheetData { document: unknown migrationMap: unknown assets: Record<string, string> + /** sha256 by `svg_asset_id`, from the seed manifest. */ + assetHashes: Record<string, string> } export interface LoadedSheet { status: SheetStatus ref: SheetRef speciesId: string + /** Document schema version of the sheet (`ref.schema_version`). */ + schemaVersion: number document: AnatomicalSheetDocument /** SVG text by `svg_asset_id`. */ assets: Readonly<Record<string, string>> + /** sha256 by `svg_asset_id`; carried into a report archive as provenance. */ + assetHashes: Readonly<Record<string, string>> migrationMap: ReportMigrationMap } @@ -56,8 +62,10 @@ export function parseBundledSheet(data: BundledSheetData): LoadedSheet { documentSha256: data.ref.document_sha256, }, speciesId: data.ref.species_id, + schemaVersion: data.ref.schema_version, document, assets: data.assets, + assetHashes: data.assetHashes, migrationMap, } } diff --git a/apps/app/src/state/persistence.ts b/apps/app/src/state/persistence.ts index 1923fcda..eddf60f4 100644 --- a/apps/app/src/state/persistence.ts +++ b/apps/app/src/state/persistence.ts @@ -1,13 +1,18 @@ import { readReportDocument, + ReportArchiveEnvelopeSchema, type Report, + type ReportArchiveEnvelope, type ReportMigrationMap, } from '@faunosteo/domain' /** - * Where the report document lives between renders. One implementation today - * (the per-tab sessionStorage draft, migrated from v2 on read); the Supabase - * and outbox adapters of later steps implement the same interface. + * Where the session lives between renders. The report draft is mirrored on + * every change; the archive an import brought along (the envelope of a + * Step 6 PDF) is written only when the session starts or ends, so a stale + * draft can still be rebased with the labels of its original sheet. One + * implementation today (per-tab sessionStorage); the Supabase and outbox + * adapters of later steps implement the same interfaces. */ export interface ReportPersistence { @@ -15,12 +20,33 @@ export interface ReportPersistence { save(report: Report | null): void } +export interface ArchivePersistence { + load(): ReportArchiveEnvelope | null + save(archive: ReportArchiveEnvelope | null): void +} + export const DRAFT_KEY = 'osteo:draft' +export const ARCHIVE_KEY = 'osteo:archive' function storage(): Storage | null { return typeof sessionStorage === 'undefined' ? null : sessionStorage } +function writeOrRemove(key: string, value: unknown): void { + const store = storage() + if (!store) return + if (value === null) { + store.removeItem(key) + return + } + try { + store.setItem(key, JSON.stringify(value)) + } catch (err) { + // Quota exceeded: the session goes on, only the mirror is lost. + if (import.meta.env.DEV) console.warn(`${key} not saved`, err) + } +} + export const sessionStoragePersistence: ReportPersistence = { load(map) { const raw = storage()?.getItem(DRAFT_KEY) @@ -33,9 +59,22 @@ export const sessionStoragePersistence: ReportPersistence = { } }, save(report) { - const store = storage() - if (!store) return - if (report) store.setItem(DRAFT_KEY, JSON.stringify(report)) - else store.removeItem(DRAFT_KEY) + writeOrRemove(DRAFT_KEY, report) + }, +} + +export const sessionStorageArchivePersistence: ArchivePersistence = { + load() { + const raw = storage()?.getItem(ARCHIVE_KEY) + if (!raw) return null + try { + const parsed = ReportArchiveEnvelopeSchema.safeParse(JSON.parse(raw)) + return parsed.success ? parsed.data : null + } catch { + return null + } + }, + save(archive) { + writeOrRemove(ARCHIVE_KEY, archive) }, } diff --git a/apps/app/src/state/reportStore.ts b/apps/app/src/state/reportStore.ts index 40ffc1ba..c85a293a 100644 --- a/apps/app/src/state/reportStore.ts +++ b/apps/app/src/state/reportStore.ts @@ -1,19 +1,24 @@ import { create } from 'zustand' import { + rebaseReportOnSheet, REPORT_VERSION, type Animal, type NextAppointment, type Observation, type Owner, type Practitioner, + type RebaseOutcome, type Report, - type ReportMigrationMap, + type ReportArchiveEnvelope, type SheetRef, } from '@faunosteo/domain' import { generateId } from '@/lib/id' import { nowIso } from '@/lib/dates' +import type { SheetIndex } from '@/services/sheetIndex' import { + sessionStorageArchivePersistence, sessionStoragePersistence, + type ArchivePersistence, type ReportPersistence, } from './persistence' @@ -21,7 +26,10 @@ import { * In-memory report document (v3) and its editing actions. Observation-level * zone rules live in services/zoneInteraction; the store only replaces * documents. The per-tab draft is mirrored through the persistence adapter - * and restored once the sheet (and its migration map) is known. + * and restored once the sheet is known; a draft written on another revision + * of the sheet is rebased on restore. The archive an import brought along + * (STEP6 §14 "App session") is kept beside the report for later operations + * and written only when the session starts or ends. */ /** What a new report needs before the store stamps version, id and dates. */ @@ -30,13 +38,26 @@ export type NewReportDraft = Omit< 'version' | 'id' | 'createdAt' | 'sheet' | 'localAnnotations' > +export interface ImportedSession { + report: Report + archive: ReportArchiveEnvelope | null +} + export interface ReportStore { report: Report | null + /** The envelope of the imported archive, as exported; null otherwise. */ + archive: ReportArchiveEnvelope | null activeObservationIndex: number initReport: (draft: NewReportDraft, sheet: SheetRef) => void hydrateReport: (report: Report) => void - /** Restores the per-tab draft; a no-op when a report is already open. */ - restoreDraft: (map: ReportMigrationMap) => void + /** Opens an imported report (already rebased) with its archive. */ + hydrateImport: (session: ImportedSession) => void + /** + * Restores the per-tab draft on the loaded sheet, rebasing it when it was + * written on another revision; a no-op when a report is already open. + * Returns the rebase outcome, null when nothing was restored. + */ + restoreDraft: (index: SheetIndex) => RebaseOutcome | null addObservation: () => void removeObservation: (index: number) => void moveObservationUp: (index: number) => void @@ -62,49 +83,79 @@ export function emptyObservation(): Observation { } } +/** A fresh v3 document: the store stamps version, id, dates and the sheet. */ +function newReport(draft: NewReportDraft, sheet: SheetRef): Report { + return { + ...draft, + version: REPORT_VERSION, + id: generateId(), + createdAt: nowIso(), + sheet, + observations: + draft.observations.length === 0 + ? [emptyObservation()] + : draft.observations, + localAnnotations: [], + } +} + function swapped(list: Observation[], i: number, j: number): Observation[] { const next = [...list] ;[next[i], next[j]] = [next[j]!, next[i]!] return next } -type Patch = Partial<Pick<ReportStore, 'report' | 'activeObservationIndex'>> +type Patch = Partial< + Pick<ReportStore, 'report' | 'archive' | 'activeObservationIndex'> +> type Setter = (fn: (s: ReportStore) => Patch | ReportStore) => void function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) { set((s) => (s.report ? update(s.report, s) : s)) } -export function createReportStore(persistence: ReportPersistence) { - const store = create<ReportStore>((set) => ({ +export function createReportStore( + persistence: ReportPersistence, + archives: ArchivePersistence, +) { + /** The archive mirror is explicit: these actions are the session's edges. */ + const withArchive = (patch: Patch, archive: ReportArchiveEnvelope | null) => { + archives.save(archive) + return { ...patch, archive } + } + + const store = create<ReportStore>((set, get) => ({ report: null, + archive: null, activeObservationIndex: 0, initReport: (draft, sheet) => - set({ - report: { - ...draft, - version: REPORT_VERSION, - id: generateId(), - createdAt: nowIso(), - sheet, - observations: - draft.observations.length === 0 - ? [emptyObservation()] - : draft.observations, - localAnnotations: [], - }, - activeObservationIndex: 0, - }), + set( + withArchive( + { report: newReport(draft, sheet), activeObservationIndex: 0 }, + null, + ), + ), - hydrateReport: (report) => set({ report, activeObservationIndex: 0 }), + hydrateReport: (report) => + set(withArchive({ report, activeObservationIndex: 0 }, null)), - restoreDraft: (map) => - set((s) => { - if (s.report) return s - const report = persistence.load(map) - return report ? { report, activeObservationIndex: 0 } : s - }), + hydrateImport: ({ report, archive }) => + set(withArchive({ report, activeObservationIndex: 0 }, archive)), + + restoreDraft: (index) => { + if (get().report) return null + const draft = persistence.load(index.sheet.migrationMap) + if (!draft) return null + const archive = archives.load() + const rebase = rebaseReportOnSheet( + draft, + index, + archive?.sheetSnapshot ?? null, + ) + set({ report: rebase.report, archive, activeObservationIndex: 0 }) + return rebase + }, addObservation: () => onReport(set, (r) => { @@ -177,10 +228,14 @@ export function createReportStore(persistence: ReportPersistence) { delete rest.nextAppointment return { report: next ? { ...rest, nextAppointment: next } : rest } }), - reset: () => set({ report: null, activeObservationIndex: 0 }), + reset: () => + set(withArchive({ report: null, activeObservationIndex: 0 }, null)), })) store.subscribe((state) => persistence.save(state.report)) return store } -export const useReportStore = createReportStore(sessionStoragePersistence) +export const useReportStore = createReportStore( + sessionStoragePersistence, + sessionStorageArchivePersistence, +) diff --git a/apps/app/tests/fixtures/README.md b/apps/app/tests/fixtures/README.md index fea41860..6d9b7020 100644 --- a/apps/app/tests/fixtures/README.md +++ b/apps/app/tests/fixtures/README.md @@ -3,11 +3,36 @@ Golden inputs frozen for the characterisation tests (plan Step 1). They describe the Report v2 document as the current application produces it. -| File | Content | -|---|---| -| `report-v2.full.json` | One report exercising every zone kind the editor can produce: plain hinge point, bilateral joint with both sides, spine zone with vertebrae, detail-popup zone, catalog findings (with and without vet referral and side), free text, severity, comment, conclusion, recommendations, dated next appointment. `boneId` values are the real `data-anno-id` of the legacy `Horse.svg` / `Horse_head.svg` now kept under `supabase/seed/anatomical-sheets/equine/legacy-sources/`; `zoneId`/`path` values exist in `pathologies.json`. | -| `report-v2.minimal.json` | Smallest valid v2 report (no observations). | -| `report-v2.full.pdf`, `report-v2.minimal.pdf` | The two reports exported by the v2 pipeline (commit 199e328, Step 5.0, rasteriser stubbed to a 1×1 PNG, no logos): the archive-like PDFs the v3 importer must read and migrate. Synthetic data only. | +| File | Content | +| --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `report-v2.full.json` | One report exercising every zone kind the editor can produce: plain hinge point, bilateral joint with both sides, spine zone with vertebrae, detail-popup zone, catalog findings (with and without vet referral and side), free text, severity, comment, conclusion, recommendations, dated next appointment. `boneId` values are the real `data-anno-id` of the legacy `Horse.svg` / `Horse_head.svg` now kept under `supabase/seed/anatomical-sheets/equine/legacy-sources/`; `zoneId`/`path` values exist in `pathologies.json`. | +| `report-v2.minimal.json` | Smallest valid v2 report (no observations). | +| `report-v2.full.pdf`, `report-v2.minimal.pdf` | The two reports exported by the v2 pipeline (commit 199e328, Step 5.0, rasteriser stubbed to a 1×1 PNG, no logos): the archive-like PDFs the v3 importer must read and migrate. Synthetic data only. | Do not edit these files to make a test pass: they are the behavioural oracle for the Report v2 → v3 adapter and for PDF regression. Add a new fixture instead. + +## Step 6 freeze (Phase 0, 2026-10-11) + +What the PDF pipeline produced right before the Step 6 refactor, recorded by +`tests/unit/pdf.goldens.test.ts` on the bundled draft sheet +(`docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md` §17). + +| File | Content | +| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `report-v3.demo.json` | Report v3 on the draft (ids from `draft/document.json`), 6 observations: main-view points, head-view points, spine zone with vertebrae, bilateral zone with both sides, a vet-referral leaf, a leaf whose label holds an en dash (U+2013), free-text findings, severities, comments, conclusion, recommendations, period next appointment; `sheet` = the draft ref at freeze time. | +| `report-v3.bare.pdf` | The demo report exported by the current code (rasteriser stubbed to a 1×1 PNG, no logos, FR): import fixture for the engine. | +| `goldens/step6/text.<report>.<locale>.<logos>.json` | Every `drawText` of the export, in drawing order: `{ page, text, x, y, size, font }`, numbers rounded to 2 decimals. | +| `goldens/step6/images.<report>.<locale>.<logos>.json` | Every `drawImage`: `{ page, x, y, width, height }`. Recorded per locale too: the footer centres the "powered by" block on the label width, so the ZenQuality logo shifts between FR and EN. | +| `goldens/step6/links.<report>.<locale>.<logos>.json` | Every `/Annot /Link` read back from the saved PDF: `{ page, rect, uri }`. Per locale for the same footer reason. | +| `goldens/step6/views.<report>.json` | Per `(observation, view)` of the report, the highlighted SVG parsed: `viewBox`, halo filter present, highlighted elements, visible non-highlighted markers, remaining `data-*` attributes, `<title>` count. | + +Reports: `v2full` (`report-v2.full.json` migrated), `demo` (`report-v3.demo.json`), +`v2unresolved` (legacy `sphenoid` and `ssb` leaves plus one `frontal` leaf, migrated; +zone-less, so its `images` and `views` goldens are empty). Logo modes: `nologos` +(every branding slot empty, 1×1 rasteriser) and `logos` (the four logo files bundled +under `apps/app/src/assets/brand`, rasteriser stubbed to a 2×1 PNG). + +Never regenerate these files without a user decision; the Step 6 engine must +reproduce them. Generation, once: `MAKE_GOLDEN=1 corepack pnpm vitest run +tests/unit/pdf.goldens.test.ts` from `apps/app`. diff --git a/apps/app/tests/fixtures/goldens/step6/images.demo.en.logos.json b/apps/app/tests/fixtures/goldens/step6/images.demo.en.logos.json new file mode 100644 index 00000000..ca6ae6f5 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/images.demo.en.logos.json @@ -0,0 +1,247 @@ +[ + { + "page": 0, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 0, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 1, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 1, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 2, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 2, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 3, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 3, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 4, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 4, + "x": 36, + "y": 547.07, + "width": 253.64, + "height": 126.82 + }, + { + "page": 4, + "x": 305.64, + "y": 547.07, + "width": 253.64, + "height": 126.82 + }, + { + "page": 5, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 5, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 6, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 0, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 0, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 0, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 1, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 1, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 1, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 2, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 2, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 2, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 3, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 3, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 3, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 4, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 4, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 4, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 5, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 5, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 5, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 6, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 6, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 6, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/images.demo.en.nologos.json b/apps/app/tests/fixtures/goldens/step6/images.demo.en.nologos.json new file mode 100644 index 00000000..0d6ed4cf --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/images.demo.en.nologos.json @@ -0,0 +1,51 @@ +[ + { + "page": 0, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + }, + { + "page": 1, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + }, + { + "page": 2, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + }, + { + "page": 3, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + }, + { + "page": 4, + "x": 36, + "y": 420.25, + "width": 253.64, + "height": 253.64 + }, + { + "page": 4, + "x": 305.64, + "y": 420.25, + "width": 253.64, + "height": 253.64 + }, + { + "page": 5, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/images.demo.fr.logos.json b/apps/app/tests/fixtures/goldens/step6/images.demo.fr.logos.json new file mode 100644 index 00000000..d719b49b --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/images.demo.fr.logos.json @@ -0,0 +1,247 @@ +[ + { + "page": 0, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 0, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 1, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 1, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 2, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 2, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 3, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 3, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 4, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 4, + "x": 36, + "y": 547.07, + "width": 253.64, + "height": 126.82 + }, + { + "page": 4, + "x": 305.64, + "y": 547.07, + "width": 253.64, + "height": 126.82 + }, + { + "page": 5, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 5, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 6, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 0, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 0, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 0, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 1, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 1, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 1, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 2, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 2, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 2, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 3, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 3, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 3, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 4, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 4, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 4, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 5, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 5, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 5, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 6, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 6, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 6, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/images.demo.fr.nologos.json b/apps/app/tests/fixtures/goldens/step6/images.demo.fr.nologos.json new file mode 100644 index 00000000..0d6ed4cf --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/images.demo.fr.nologos.json @@ -0,0 +1,51 @@ +[ + { + "page": 0, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + }, + { + "page": 1, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + }, + { + "page": 2, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + }, + { + "page": 3, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + }, + { + "page": 4, + "x": 36, + "y": 420.25, + "width": 253.64, + "height": 253.64 + }, + { + "page": 4, + "x": 305.64, + "y": 420.25, + "width": 253.64, + "height": 253.64 + }, + { + "page": 5, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/images.v2full.en.logos.json b/apps/app/tests/fixtures/goldens/step6/images.v2full.en.logos.json new file mode 100644 index 00000000..ee417e39 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/images.v2full.en.logos.json @@ -0,0 +1,135 @@ +[ + { + "page": 0, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 0, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 1, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 1, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 2, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 2, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 3, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 0, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 0, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 0, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 1, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 1, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 1, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 2, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 2, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 2, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 3, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 3, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 3, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/images.v2full.en.nologos.json b/apps/app/tests/fixtures/goldens/step6/images.v2full.en.nologos.json new file mode 100644 index 00000000..7a8d1db0 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/images.v2full.en.nologos.json @@ -0,0 +1,23 @@ +[ + { + "page": 0, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + }, + { + "page": 1, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + }, + { + "page": 2, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/images.v2full.fr.logos.json b/apps/app/tests/fixtures/goldens/step6/images.v2full.fr.logos.json new file mode 100644 index 00000000..348aa496 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/images.v2full.fr.logos.json @@ -0,0 +1,135 @@ +[ + { + "page": 0, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 0, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 1, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 1, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 2, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 2, + "x": 166.82, + "y": 543.07, + "width": 261.64, + "height": 130.82 + }, + { + "page": 3, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 0, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 0, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 0, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 1, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 1, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 1, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 2, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 2, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 2, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 3, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 3, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 3, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/images.v2full.fr.nologos.json b/apps/app/tests/fixtures/goldens/step6/images.v2full.fr.nologos.json new file mode 100644 index 00000000..7a8d1db0 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/images.v2full.fr.nologos.json @@ -0,0 +1,23 @@ +[ + { + "page": 0, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + }, + { + "page": 1, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + }, + { + "page": 2, + "x": 166.82, + "y": 412.25, + "width": 261.64, + "height": 261.64 + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/images.v2unresolved.en.logos.json b/apps/app/tests/fixtures/goldens/step6/images.v2unresolved.en.logos.json new file mode 100644 index 00000000..7e63b58e --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/images.v2unresolved.en.logos.json @@ -0,0 +1,114 @@ +[ + { + "page": 0, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 1, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 2, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 3, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 0, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 0, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 0, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 1, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 1, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 1, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 2, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 2, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 2, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 3, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 3, + "x": 284.49, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 3, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/images.v2unresolved.en.nologos.json b/apps/app/tests/fixtures/goldens/step6/images.v2unresolved.en.nologos.json new file mode 100644 index 00000000..fe51488c --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/images.v2unresolved.en.nologos.json @@ -0,0 +1 @@ +[] diff --git a/apps/app/tests/fixtures/goldens/step6/images.v2unresolved.fr.logos.json b/apps/app/tests/fixtures/goldens/step6/images.v2unresolved.fr.logos.json new file mode 100644 index 00000000..31347c95 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/images.v2unresolved.fr.logos.json @@ -0,0 +1,114 @@ +[ + { + "page": 0, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 1, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 2, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 3, + "x": 247.64, + "y": 772, + "width": 100, + "height": 38 + }, + { + "page": 0, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 0, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 0, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 1, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 1, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 1, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 2, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 2, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 2, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + }, + { + "page": 3, + "x": 36, + "y": 34, + "width": 80, + "height": 30 + }, + { + "page": 3, + "x": 286.43, + "y": 36, + "width": 70, + "height": 16 + }, + { + "page": 3, + "x": 527.28, + "y": 36, + "width": 32, + "height": 16 + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/images.v2unresolved.fr.nologos.json b/apps/app/tests/fixtures/goldens/step6/images.v2unresolved.fr.nologos.json new file mode 100644 index 00000000..fe51488c --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/images.v2unresolved.fr.nologos.json @@ -0,0 +1 @@ +[] diff --git a/apps/app/tests/fixtures/goldens/step6/links.demo.en.logos.json b/apps/app/tests/fixtures/goldens/step6/links.demo.en.logos.json new file mode 100644 index 00000000..3a324abf --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/links.demo.en.logos.json @@ -0,0 +1,282 @@ +[ + { + "page": 0, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 0, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 0, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 0, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 1, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 1, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 1, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 1, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 2, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 2, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 2, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 2, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 3, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 3, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 3, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 3, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 4, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 4, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 4, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 4, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 5, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 5, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 5, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 5, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 6, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 6, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 6, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 6, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/links.demo.en.nologos.json b/apps/app/tests/fixtures/goldens/step6/links.demo.en.nologos.json new file mode 100644 index 00000000..4f06528c --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/links.demo.en.nologos.json @@ -0,0 +1,142 @@ +[ + { + "page": 0, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 0, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 1, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 1, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 2, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 2, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 3, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 3, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 4, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 4, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 5, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 5, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 6, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 6, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/links.demo.fr.logos.json b/apps/app/tests/fixtures/goldens/step6/links.demo.fr.logos.json new file mode 100644 index 00000000..c6878456 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/links.demo.fr.logos.json @@ -0,0 +1,282 @@ +[ + { + "page": 0, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 0, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 0, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 0, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 1, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 1, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 1, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 1, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 2, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 2, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 2, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 2, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 3, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 3, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 3, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 3, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 4, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 4, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 4, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 4, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 5, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 5, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 5, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 5, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 6, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 6, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 6, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 6, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/links.demo.fr.nologos.json b/apps/app/tests/fixtures/goldens/step6/links.demo.fr.nologos.json new file mode 100644 index 00000000..b80f3ab0 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/links.demo.fr.nologos.json @@ -0,0 +1,142 @@ +[ + { + "page": 0, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 0, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 1, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 1, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 2, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 2, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 3, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 3, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 4, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 4, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 5, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 5, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 6, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 6, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/links.v2full.en.logos.json b/apps/app/tests/fixtures/goldens/step6/links.v2full.en.logos.json new file mode 100644 index 00000000..850e5327 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/links.v2full.en.logos.json @@ -0,0 +1,162 @@ +[ + { + "page": 0, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 0, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 0, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 0, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 1, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 1, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 1, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 1, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 2, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 2, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 2, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 2, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 3, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 3, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 3, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 3, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/links.v2full.en.nologos.json b/apps/app/tests/fixtures/goldens/step6/links.v2full.en.nologos.json new file mode 100644 index 00000000..8ace49de --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/links.v2full.en.nologos.json @@ -0,0 +1,82 @@ +[ + { + "page": 0, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 0, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 1, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 1, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 2, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 2, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 3, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 3, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/links.v2full.fr.logos.json b/apps/app/tests/fixtures/goldens/step6/links.v2full.fr.logos.json new file mode 100644 index 00000000..b9d18048 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/links.v2full.fr.logos.json @@ -0,0 +1,162 @@ +[ + { + "page": 0, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 0, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 0, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 0, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 1, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 1, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 1, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 1, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 2, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 2, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 2, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 2, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 3, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 3, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 3, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 3, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/links.v2full.fr.nologos.json b/apps/app/tests/fixtures/goldens/step6/links.v2full.fr.nologos.json new file mode 100644 index 00000000..bc15c728 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/links.v2full.fr.nologos.json @@ -0,0 +1,82 @@ +[ + { + "page": 0, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 0, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 1, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 1, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 2, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 2, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 3, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 3, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/links.v2unresolved.en.logos.json b/apps/app/tests/fixtures/goldens/step6/links.v2unresolved.en.logos.json new file mode 100644 index 00000000..850e5327 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/links.v2unresolved.en.logos.json @@ -0,0 +1,162 @@ +[ + { + "page": 0, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 0, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 0, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 0, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 1, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 1, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 1, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 1, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 2, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 2, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 2, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 2, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 3, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 3, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 3, + "rect": [ + 284.49, + 36, + 354.49, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 3, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/links.v2unresolved.en.nologos.json b/apps/app/tests/fixtures/goldens/step6/links.v2unresolved.en.nologos.json new file mode 100644 index 00000000..8ace49de --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/links.v2unresolved.en.nologos.json @@ -0,0 +1,82 @@ +[ + { + "page": 0, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 0, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 1, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 1, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 2, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 2, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 3, + "rect": [ + 298.39, + 38, + 340.6, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 3, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/links.v2unresolved.fr.logos.json b/apps/app/tests/fixtures/goldens/step6/links.v2unresolved.fr.logos.json new file mode 100644 index 00000000..b9d18048 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/links.v2unresolved.fr.logos.json @@ -0,0 +1,162 @@ +[ + { + "page": 0, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 0, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 0, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 0, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 1, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 1, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 1, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 1, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 2, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 2, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 2, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 2, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 3, + "rect": [ + 247.64, + 772, + 347.64, + 810 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 3, + "rect": [ + 36, + 34, + 116, + 64 + ], + "uri": "https://faunosteo.com" + }, + { + "page": 3, + "rect": [ + 286.43, + 36, + 356.43, + 52 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 3, + "rect": [ + 527.28, + 36, + 559.28, + 52 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/links.v2unresolved.fr.nologos.json b/apps/app/tests/fixtures/goldens/step6/links.v2unresolved.fr.nologos.json new file mode 100644 index 00000000..bc15c728 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/links.v2unresolved.fr.nologos.json @@ -0,0 +1,82 @@ +[ + { + "page": 0, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 0, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 1, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 1, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 2, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 2, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + }, + { + "page": 3, + "rect": [ + 300.32, + 38, + 342.53, + 50 + ], + "uri": "https://zenquality.fr" + }, + { + "page": 3, + "rect": [ + 489.12, + 38, + 559.28, + 50 + ], + "uri": "https://www.instagram.com/paws.iin.harmony" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/text.demo.en.logos.json b/apps/app/tests/fixtures/goldens/step6/text.demo.en.logos.json new file mode 100644 index 00000000..2eb58bc5 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/text.demo.en.logos.json @@ -0,0 +1,1274 @@ +[ + { + "page": 0, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "October 11, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "01", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 0, + "text": "MILD", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "GENERAL VIEW", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "C7-T1 junction (cervicothoracic)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 182.34, + "y": 504.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "T18-L1 junction (thoracolumbar)", + "x": 192.24, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "FINDINGS — C7-T1 JUNCTION (CERVICOTHORACIC)", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Flexion restriction", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 119.2, + "y": 468.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Extension restriction", + "x": 129.1, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SEVERITY", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "mild", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "COMMENT", + "x": 36, + "y": 411.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Réagit à la palpation de la charnière.", + "x": 36, + "y": 398.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "October 11, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "02", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 1, + "text": "MODERATE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "GENERAL VIEW", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Hip joint (Left)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 103.24, + "y": 504.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Hip joint (Right)", + "x": 113.14, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "FINDINGS — HIP JOINT (LEFT)", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Flexion restriction", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "FINDINGS — HIP JOINT (RIGHT)", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Abduction / adduction restriction", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SEVERITY", + "x": 36, + "y": 411.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "moderate", + "x": 36, + "y": 398.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "October 11, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "03", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 2, + "text": "SEVERE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "GENERAL VIEW", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Cervical vertebrae (C3, C4)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "FINDINGS — CERVICAL VERTEBRAE", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Localized segmental fixation (C2–C7)", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "SEVERITY", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "severe", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "COMMENT", + "x": 36, + "y": 411.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Fixation nette en latéroflexion droite.", + "x": 36, + "y": 398.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "October 11, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "04", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 3, + "text": "DETAIL VIEW — HEAD (LEFT LATERAL VIEW)", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Temporomandibular joint (TMJ)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "•", + "x": 179.07, + "y": 504.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Frontal bone", + "x": 188.97, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "FINDINGS — FRONTAL BONE", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "(!) Reported repeated head rubbing", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "FINDINGS — TEMPOROMANDIBULAR JOINT (TMJ)", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Opening restriction", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "October 11, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "05", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 4, + "text": "MILD", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "GENERAL VIEW", + "x": 36, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "DETAIL VIEW — HEAD (LEFT LATERAL VIEW)", + "x": 305.64, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "ZONES", + "x": 36, + "y": 523.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Sacroiliac joint (Right)", + "x": 36, + "y": 510.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "•", + "x": 138.24, + "y": 508.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Occipital bone", + "x": 148.14, + "y": 510.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "FREE FINDINGS", + "x": 36, + "y": 487.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Sensibilité au garrot", + "x": 36, + "y": 474.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "•", + "x": 129.37, + "y": 472.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Tension du ligament nuchal", + "x": 139.27, + "y": 474.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "SEVERITY", + "x": 36, + "y": 451.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "mild", + "x": 36, + "y": 438.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "COMMENT", + "x": 36, + "y": 415.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Compensation probable.", + "x": 36, + "y": 402.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "October 11, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "06", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 5, + "text": "GENERAL VIEW", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Lumbar vertebrae (L2, L3)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "•", + "x": 157.21, + "y": 504.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "L6-S1 junction (lumbosacral joint)", + "x": 167.11, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "FINDINGS — LUMBAR VERTEBRAE", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Extension restriction", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "FREE FINDINGS", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Raideur lombaire au pas", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 6, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "October 11, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "SYNTHESIS", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Conclusion", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 6, + "text": "CONCLUSION", + "x": 36, + "y": 691.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Dysfonction cervico-thoracique avec compensation du bassin et tension crânienne associée.", + "x": 36, + "y": 677.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 6, + "text": "RECOMMENDATIONS", + "x": 36, + "y": 645.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Repos 3 jours puis reprise progressive ; contrôle vétérinaire pour les frottements de tête.", + "x": 36, + "y": 631.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 6, + "text": "NEXT APPOINTMENT", + "x": 36, + "y": 599.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "6 à 8 semaines", + "x": 36, + "y": 585.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "1 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "2 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "3 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "4 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "5 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "6 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "7 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/text.demo.en.nologos.json b/apps/app/tests/fixtures/goldens/step6/text.demo.en.nologos.json new file mode 100644 index 00000000..b277a95c --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/text.demo.en.nologos.json @@ -0,0 +1,1386 @@ +[ + { + "page": 0, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "October 11, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "01", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 0, + "text": "MILD", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "GENERAL VIEW", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "C7-T1 junction (cervicothoracic)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 182.34, + "y": 374.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "T18-L1 junction (thoracolumbar)", + "x": 192.24, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "FINDINGS — C7-T1 JUNCTION (CERVICOTHORACIC)", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Flexion restriction", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 119.2, + "y": 338.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Extension restriction", + "x": 129.1, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SEVERITY", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "mild", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "COMMENT", + "x": 36, + "y": 280.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Réagit à la palpation de la charnière.", + "x": 36, + "y": 267.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "October 11, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "02", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 1, + "text": "MODERATE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "GENERAL VIEW", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Hip joint (Left)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 103.24, + "y": 374.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Hip joint (Right)", + "x": 113.14, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "FINDINGS — HIP JOINT (LEFT)", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Flexion restriction", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "FINDINGS — HIP JOINT (RIGHT)", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Abduction / adduction restriction", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SEVERITY", + "x": 36, + "y": 280.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "moderate", + "x": 36, + "y": 267.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "October 11, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "03", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 2, + "text": "SEVERE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "GENERAL VIEW", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Cervical vertebrae (C3, C4)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "FINDINGS — CERVICAL VERTEBRAE", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Localized segmental fixation (C2–C7)", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "SEVERITY", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "severe", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "COMMENT", + "x": 36, + "y": 280.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Fixation nette en latéroflexion droite.", + "x": 36, + "y": 267.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "October 11, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "04", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 3, + "text": "DETAIL VIEW — HEAD (LEFT LATERAL VIEW)", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Temporomandibular joint (TMJ)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "•", + "x": 179.07, + "y": 374.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Frontal bone", + "x": 188.97, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "FINDINGS — FRONTAL BONE", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "(!) Reported repeated head rubbing", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "FINDINGS — TEMPOROMANDIBULAR JOINT (TMJ)", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Opening restriction", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "October 11, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "05", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 4, + "text": "MILD", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "GENERAL VIEW", + "x": 36, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "DETAIL VIEW — HEAD (LEFT LATERAL VIEW)", + "x": 305.64, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "ZONES", + "x": 36, + "y": 396.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Sacroiliac joint (Right)", + "x": 36, + "y": 383.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "•", + "x": 138.24, + "y": 382.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Occipital bone", + "x": 148.14, + "y": 383.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "FREE FINDINGS", + "x": 36, + "y": 360.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Sensibilité au garrot", + "x": 36, + "y": 347.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "•", + "x": 129.37, + "y": 346.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Tension du ligament nuchal", + "x": 139.27, + "y": 347.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "SEVERITY", + "x": 36, + "y": 324.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "mild", + "x": 36, + "y": 311.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "COMMENT", + "x": 36, + "y": 288.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Compensation probable.", + "x": 36, + "y": 275.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "October 11, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "06", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 5, + "text": "GENERAL VIEW", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Lumbar vertebrae (L2, L3)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "•", + "x": 157.21, + "y": 374.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "L6-S1 junction (lumbosacral joint)", + "x": 167.11, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "FINDINGS — LUMBAR VERTEBRAE", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Extension restriction", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "FREE FINDINGS", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Raideur lombaire au pas", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 6, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "October 11, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "SYNTHESIS", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Conclusion", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 6, + "text": "CONCLUSION", + "x": 36, + "y": 691.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Dysfonction cervico-thoracique avec compensation du bassin et tension crânienne associée.", + "x": 36, + "y": 677.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 6, + "text": "RECOMMENDATIONS", + "x": 36, + "y": 645.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Repos 3 jours puis reprise progressive ; contrôle vétérinaire pour les frottements de tête.", + "x": 36, + "y": 631.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 6, + "text": "NEXT APPOINTMENT", + "x": 36, + "y": 599.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "6 à 8 semaines", + "x": 36, + "y": 585.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "1 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "2 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "3 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "4 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "5 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "6 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "7 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/text.demo.fr.logos.json b/apps/app/tests/fixtures/goldens/step6/text.demo.fr.logos.json new file mode 100644 index 00000000..de19422d --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/text.demo.fr.logos.json @@ -0,0 +1,1274 @@ +[ + { + "page": 0, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "11 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "01", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 0, + "text": "LÉGÈRE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "VUE GÉNÉRALE", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Charnière C7-T1 (cervico-thoracique)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 207.04, + "y": 504.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Charnière T18-L1 (thoraco-lombaire)", + "x": 216.94, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "CONSTATS — CHARNIÈRE C7-T1 (CERVICO-THORACIQUE)", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Restriction en flexion", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 133.66, + "y": 468.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Restriction en extension", + "x": 143.56, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SÉVÉRITÉ", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "légère", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "COMMENTAIRE", + "x": 36, + "y": 411.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Réagit à la palpation de la charnière.", + "x": 36, + "y": 398.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "11 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "02", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 1, + "text": "MODÉRÉE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "VUE GÉNÉRALE", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Hanche (coxo-fémorale) (Gauche)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 192.01, + "y": 504.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Hanche (coxo-fémorale) (Droite)", + "x": 201.91, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "CONSTATS — HANCHE (COXO-FÉMORALE) (GAUCHE)", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Restriction en flexion", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "CONSTATS — HANCHE (COXO-FÉMORALE) (DROITE)", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Restriction en abduction / adduction", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SÉVÉRITÉ", + "x": 36, + "y": 411.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "modérée", + "x": 36, + "y": 398.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "11 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "03", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 2, + "text": "SÉVÈRE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "VUE GÉNÉRALE", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Vertèbres cervicales (C3, C4)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "CONSTATS — VERTÈBRES CERVICALES", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Fixation segmentaire localisée (C2–C7)", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "SÉVÉRITÉ", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "sévère", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "COMMENTAIRE", + "x": 36, + "y": 411.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Fixation nette en latéroflexion droite.", + "x": 36, + "y": 398.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "11 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "04", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 3, + "text": "VUE DÉTAIL — TÊTE (VUE LATÉRALE GAUCHE)", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Articulation temporo-mandibulaire (ATM)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "•", + "x": 220.04, + "y": 504.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Frontal", + "x": 229.94, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "CONSTATS — FRONTAL", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "(!) Frottements répétés de la tête rapportés", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "CONSTATS — ARTICULATION TEMPORO-MANDIBULAIRE (ATM)", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Restriction à l'ouverture", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "11 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "05", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 4, + "text": "LÉGÈRE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "VUE GÉNÉRALE", + "x": 36, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "VUE DÉTAIL — TÊTE (VUE LATÉRALE GAUCHE)", + "x": 305.64, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "ZONES", + "x": 36, + "y": 523.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Articulation sacro-iliaque (Droite)", + "x": 36, + "y": 510.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "•", + "x": 186.43, + "y": 508.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Occipital", + "x": 196.33, + "y": 510.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "CONSTATS LIBRES", + "x": 36, + "y": 487.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Sensibilité au garrot", + "x": 36, + "y": 474.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "•", + "x": 129.37, + "y": 472.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Tension du ligament nuchal", + "x": 139.27, + "y": 474.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "SÉVÉRITÉ", + "x": 36, + "y": 451.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "légère", + "x": 36, + "y": 438.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "COMMENTAIRE", + "x": 36, + "y": 415.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Compensation probable.", + "x": 36, + "y": 402.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "11 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "06", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 5, + "text": "VUE GÉNÉRALE", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Vertèbres lombaires (L2, L3)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "•", + "x": 167.31, + "y": 504.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Charnière L6-S1 (lombo-sacrée)", + "x": 177.21, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "CONSTATS — VERTÈBRES LOMBAIRES", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Restriction en extension", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "CONSTATS LIBRES", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Raideur lombaire au pas", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 6, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "11 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "SYNTHÈSE", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Conclusion", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 6, + "text": "CONCLUSION", + "x": 36, + "y": 691.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Dysfonction cervico-thoracique avec compensation du bassin et tension crânienne associée.", + "x": 36, + "y": 677.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 6, + "text": "RECOMMANDATIONS", + "x": 36, + "y": 645.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Repos 3 jours puis reprise progressive ; contrôle vétérinaire pour les frottements de tête.", + "x": 36, + "y": 631.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 6, + "text": "PROCHAIN RENDEZ-VOUS", + "x": 36, + "y": 599.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "6 à 8 semaines", + "x": 36, + "y": 585.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "1 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "2 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "3 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "4 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "5 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "6 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "7 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/text.demo.fr.nologos.json b/apps/app/tests/fixtures/goldens/step6/text.demo.fr.nologos.json new file mode 100644 index 00000000..4099d731 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/text.demo.fr.nologos.json @@ -0,0 +1,1386 @@ +[ + { + "page": 0, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "11 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "01", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 0, + "text": "LÉGÈRE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "VUE GÉNÉRALE", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Charnière C7-T1 (cervico-thoracique)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 207.04, + "y": 374.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Charnière T18-L1 (thoraco-lombaire)", + "x": 216.94, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "CONSTATS — CHARNIÈRE C7-T1 (CERVICO-THORACIQUE)", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Restriction en flexion", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 133.66, + "y": 338.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Restriction en extension", + "x": 143.56, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SÉVÉRITÉ", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "légère", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "COMMENTAIRE", + "x": 36, + "y": 280.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Réagit à la palpation de la charnière.", + "x": 36, + "y": 267.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "11 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "02", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 1, + "text": "MODÉRÉE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "VUE GÉNÉRALE", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Hanche (coxo-fémorale) (Gauche)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 192.01, + "y": 374.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Hanche (coxo-fémorale) (Droite)", + "x": 201.91, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "CONSTATS — HANCHE (COXO-FÉMORALE) (GAUCHE)", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Restriction en flexion", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "CONSTATS — HANCHE (COXO-FÉMORALE) (DROITE)", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Restriction en abduction / adduction", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SÉVÉRITÉ", + "x": 36, + "y": 280.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "modérée", + "x": 36, + "y": 267.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "11 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "03", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 2, + "text": "SÉVÈRE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "VUE GÉNÉRALE", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Vertèbres cervicales (C3, C4)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "CONSTATS — VERTÈBRES CERVICALES", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Fixation segmentaire localisée (C2–C7)", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "SÉVÉRITÉ", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "sévère", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "COMMENTAIRE", + "x": 36, + "y": 280.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Fixation nette en latéroflexion droite.", + "x": 36, + "y": 267.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "11 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "04", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 3, + "text": "VUE DÉTAIL — TÊTE (VUE LATÉRALE GAUCHE)", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Articulation temporo-mandibulaire (ATM)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "•", + "x": 220.04, + "y": 374.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Frontal", + "x": 229.94, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "CONSTATS — FRONTAL", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "(!) Frottements répétés de la tête rapportés", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "CONSTATS — ARTICULATION TEMPORO-MANDIBULAIRE (ATM)", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Restriction à l'ouverture", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "11 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 4, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "05", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 4, + "text": "LÉGÈRE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "VUE GÉNÉRALE", + "x": 36, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "VUE DÉTAIL — TÊTE (VUE LATÉRALE GAUCHE)", + "x": 305.64, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "ZONES", + "x": 36, + "y": 396.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Articulation sacro-iliaque (Droite)", + "x": 36, + "y": 383.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "•", + "x": 186.43, + "y": 382.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Occipital", + "x": 196.33, + "y": 383.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "CONSTATS LIBRES", + "x": 36, + "y": 360.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Sensibilité au garrot", + "x": 36, + "y": 347.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "•", + "x": 129.37, + "y": 346.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Tension du ligament nuchal", + "x": 139.27, + "y": 347.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "SÉVÉRITÉ", + "x": 36, + "y": 324.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "légère", + "x": 36, + "y": 311.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 4, + "text": "COMMENTAIRE", + "x": 36, + "y": 288.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 4, + "text": "Compensation probable.", + "x": 36, + "y": 275.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "11 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 5, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "06", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 5, + "text": "VUE GÉNÉRALE", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Vertèbres lombaires (L2, L3)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "•", + "x": 167.31, + "y": 374.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Charnière L6-S1 (lombo-sacrée)", + "x": 177.21, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "CONSTATS — VERTÈBRES LOMBAIRES", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Restriction en extension", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 5, + "text": "CONSTATS LIBRES", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 5, + "text": "Raideur lombaire au pas", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 6, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "11 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 6, + "text": "SYNTHÈSE", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Conclusion", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 6, + "text": "CONCLUSION", + "x": 36, + "y": 691.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Dysfonction cervico-thoracique avec compensation du bassin et tension crânienne associée.", + "x": 36, + "y": 677.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 6, + "text": "RECOMMANDATIONS", + "x": 36, + "y": 645.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "Repos 3 jours puis reprise progressive ; contrôle vétérinaire pour les frottements de tête.", + "x": 36, + "y": 631.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 6, + "text": "PROCHAIN RENDEZ-VOUS", + "x": 36, + "y": 599.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 6, + "text": "6 à 8 semaines", + "x": 36, + "y": 585.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "1 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "2 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "3 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "4 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 4, + "text": "5 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 5, + "text": "6 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 6, + "text": "7 / 7", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/text.v2full.en.logos.json b/apps/app/tests/fixtures/goldens/step6/text.v2full.en.logos.json new file mode 100644 index 00000000..af8e47eb --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/text.v2full.en.logos.json @@ -0,0 +1,698 @@ +[ + { + "page": 0, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "June 1, 2026", + "x": 507.42, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "01", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 0, + "text": "MODERATE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "GENERAL VIEW", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "C7-T1 junction (cervicothoracic)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 182.34, + "y": 504.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Hip joint (Left)", + "x": 192.24, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 259.48, + "y": 504.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Hip joint (Right)", + "x": 269.38, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "FINDINGS — C7-T1 JUNCTION (CERVICOTHORACIC)", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Junction fixation", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "FINDINGS — HIP JOINT (LEFT)", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Flexion restriction", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "FREE FINDINGS", + "x": 36, + "y": 411.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sensibilité au garrot", + "x": 36, + "y": 398.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SEVERITY", + "x": 36, + "y": 375.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "moderate", + "x": 36, + "y": 362.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "COMMENT", + "x": 36, + "y": 339.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Réagit à la palpation du garrot.", + "x": 36, + "y": 326.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "June 1, 2026", + "x": 507.42, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "02", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 1, + "text": "SEVERE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "GENERAL VIEW", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Cervical vertebrae (C3, C4)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "FINDINGS — CERVICAL VERTEBRAE", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "(!) Reported stumbling / proprioceptive deficit", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SEVERITY", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "severe", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "June 1, 2026", + "x": 507.42, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "03", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 2, + "text": "DETAIL VIEW — HEAD (LEFT LATERAL VIEW)", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Temporomandibular joint (TMJ)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "FINDINGS — TEMPOROMANDIBULAR JOINT (TMJ)", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "(!) Headshaking", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "COMMENT", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Vue détail tête.", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "June 1, 2026", + "x": 507.42, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SYNTHESIS", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Conclusion", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 3, + "text": "CONCLUSION", + "x": 36, + "y": 691.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Dysfonction cervico-thoracique avec compensation du bassin.", + "x": 36, + "y": 677.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 3, + "text": "RECOMMENDATIONS", + "x": 36, + "y": 645.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Repos 3 jours puis reprise progressive.", + "x": 36, + "y": 631.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 3, + "text": "NEXT APPOINTMENT", + "x": 36, + "y": 599.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "July 1, 2026", + "x": 36, + "y": 585.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "1 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "2 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "3 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "4 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/text.v2full.en.nologos.json b/apps/app/tests/fixtures/goldens/step6/text.v2full.en.nologos.json new file mode 100644 index 00000000..95367884 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/text.v2full.en.nologos.json @@ -0,0 +1,762 @@ +[ + { + "page": 0, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "June 1, 2026", + "x": 507.42, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "01", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 0, + "text": "MODERATE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "GENERAL VIEW", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "C7-T1 junction (cervicothoracic)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 182.34, + "y": 374.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Hip joint (Left)", + "x": 192.24, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 259.48, + "y": 374.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Hip joint (Right)", + "x": 269.38, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "FINDINGS — C7-T1 JUNCTION (CERVICOTHORACIC)", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Junction fixation", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "FINDINGS — HIP JOINT (LEFT)", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Flexion restriction", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "FREE FINDINGS", + "x": 36, + "y": 280.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sensibilité au garrot", + "x": 36, + "y": 267.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SEVERITY", + "x": 36, + "y": 244.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "moderate", + "x": 36, + "y": 231.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "COMMENT", + "x": 36, + "y": 208.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Réagit à la palpation du garrot.", + "x": 36, + "y": 195.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "June 1, 2026", + "x": 507.42, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "02", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 1, + "text": "SEVERE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "GENERAL VIEW", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Cervical vertebrae (C3, C4)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "FINDINGS — CERVICAL VERTEBRAE", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "(!) Reported stumbling / proprioceptive deficit", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SEVERITY", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "severe", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "June 1, 2026", + "x": 507.42, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "03", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 2, + "text": "DETAIL VIEW — HEAD (LEFT LATERAL VIEW)", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Temporomandibular joint (TMJ)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "FINDINGS — TEMPOROMANDIBULAR JOINT (TMJ)", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "(!) Headshaking", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "COMMENT", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Vue détail tête.", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Owner: Jean Martin", + "x": 480.58, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "June 1, 2026", + "x": 507.42, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SYNTHESIS", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Conclusion", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 3, + "text": "CONCLUSION", + "x": 36, + "y": 691.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Dysfonction cervico-thoracique avec compensation du bassin.", + "x": 36, + "y": 677.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 3, + "text": "RECOMMENDATIONS", + "x": 36, + "y": 645.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Repos 3 jours puis reprise progressive.", + "x": 36, + "y": 631.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 3, + "text": "NEXT APPOINTMENT", + "x": 36, + "y": 599.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "July 1, 2026", + "x": 36, + "y": 585.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "1 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "2 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "3 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "4 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/text.v2full.fr.logos.json b/apps/app/tests/fixtures/goldens/step6/text.v2full.fr.logos.json new file mode 100644 index 00000000..9b1600a3 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/text.v2full.fr.logos.json @@ -0,0 +1,698 @@ +[ + { + "page": 0, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "1 juin 2026", + "x": 515.25, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "01", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 0, + "text": "MODÉRÉE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "VUE GÉNÉRALE", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Charnière C7-T1 (cervico-thoracique)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 207.04, + "y": 504.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Hanche (coxo-fémorale) (Gauche)", + "x": 216.94, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 372.95, + "y": 504.87, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Hanche (coxo-fémorale) (Droite)", + "x": 382.85, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "CONSTATS — CHARNIÈRE C7-T1 (CERVICO-THORACIQUE)", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Fixation de la charnière", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "CONSTATS — HANCHE (COXO-FÉMORALE) (GAUCHE)", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Restriction en flexion", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "CONSTATS LIBRES", + "x": 36, + "y": 411.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sensibilité au garrot", + "x": 36, + "y": 398.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SÉVÉRITÉ", + "x": 36, + "y": 375.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "modérée", + "x": 36, + "y": 362.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "COMMENTAIRE", + "x": 36, + "y": 339.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Réagit à la palpation du garrot.", + "x": 36, + "y": 326.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "1 juin 2026", + "x": 515.25, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "02", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 1, + "text": "SÉVÈRE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "VUE GÉNÉRALE", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Vertèbres cervicales (C3, C4)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "CONSTATS — VERTÈBRES CERVICALES", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "(!) Trébuchements / déficit proprioceptif rapporté", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SÉVÉRITÉ", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "sévère", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "1 juin 2026", + "x": 515.25, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "03", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 2, + "text": "VUE DÉTAIL — TÊTE (VUE LATÉRALE GAUCHE)", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "ZONES", + "x": 36, + "y": 519.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Articulation temporo-mandibulaire (ATM)", + "x": 36, + "y": 506.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "CONSTATS — ARTICULATION TEMPORO-MANDIBULAIRE (ATM)", + "x": 36, + "y": 483.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "(!) Headshaking (secouement de tête)", + "x": 36, + "y": 470.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "COMMENTAIRE", + "x": 36, + "y": 447.07, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Vue détail tête.", + "x": 36, + "y": 434.07, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "1 juin 2026", + "x": 515.25, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SYNTHÈSE", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Conclusion", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 3, + "text": "CONCLUSION", + "x": 36, + "y": 691.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Dysfonction cervico-thoracique avec compensation du bassin.", + "x": 36, + "y": 677.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 3, + "text": "RECOMMANDATIONS", + "x": 36, + "y": 645.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Repos 3 jours puis reprise progressive.", + "x": 36, + "y": 631.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 3, + "text": "PROCHAIN RENDEZ-VOUS", + "x": 36, + "y": 599.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "1 juillet 2026", + "x": 36, + "y": 585.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "1 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "2 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "3 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "4 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/text.v2full.fr.nologos.json b/apps/app/tests/fixtures/goldens/step6/text.v2full.fr.nologos.json new file mode 100644 index 00000000..9d887a40 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/text.v2full.fr.nologos.json @@ -0,0 +1,762 @@ +[ + { + "page": 0, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "1 juin 2026", + "x": 515.25, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "01", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 0, + "text": "MODÉRÉE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "VUE GÉNÉRALE", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Charnière C7-T1 (cervico-thoracique)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 207.04, + "y": 374.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Hanche (coxo-fémorale) (Gauche)", + "x": 216.94, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 372.95, + "y": 374.05, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Hanche (coxo-fémorale) (Droite)", + "x": 382.85, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "CONSTATS — CHARNIÈRE C7-T1 (CERVICO-THORACIQUE)", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Fixation de la charnière", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "CONSTATS — HANCHE (COXO-FÉMORALE) (GAUCHE)", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Restriction en flexion", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "CONSTATS LIBRES", + "x": 36, + "y": 280.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sensibilité au garrot", + "x": 36, + "y": 267.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "SÉVÉRITÉ", + "x": 36, + "y": 244.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "modérée", + "x": 36, + "y": 231.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "COMMENTAIRE", + "x": 36, + "y": 208.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Réagit à la palpation du garrot.", + "x": 36, + "y": 195.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "1 juin 2026", + "x": 515.25, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "02", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 1, + "text": "SÉVÈRE", + "x": 80, + "y": 727.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "VUE GÉNÉRALE", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Vertèbres cervicales (C3, C4)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "CONSTATS — VERTÈBRES CERVICALES", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "(!) Trébuchements / déficit proprioceptif rapporté", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "SÉVÉRITÉ", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "sévère", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "1 juin 2026", + "x": 515.25, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "03", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 2, + "text": "VUE DÉTAIL — TÊTE (VUE LATÉRALE GAUCHE)", + "x": 166.82, + "y": 687.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "ZONES", + "x": 36, + "y": 388.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Articulation temporo-mandibulaire (ATM)", + "x": 36, + "y": 375.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "CONSTATS — ARTICULATION TEMPORO-MANDIBULAIRE (ATM)", + "x": 36, + "y": 352.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "(!) Headshaking (secouement de tête)", + "x": 36, + "y": 339.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "COMMENTAIRE", + "x": 36, + "y": 316.25, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Vue détail tête.", + "x": 36, + "y": 303.25, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Dr. Claire Dupont", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Cabinet Équi-Ostéo", + "x": 36, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "claire@example.test", + "x": 36, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SIRET 12345678901234", + "x": 36, + "y": 764, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Mistral (Selle Français) · 9 ans", + "x": 402.16, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Propriétaire : Jean Martin", + "x": 458.2, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "1 juin 2026", + "x": 515.25, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SYNTHÈSE", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Conclusion", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 3, + "text": "CONCLUSION", + "x": 36, + "y": 691.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Dysfonction cervico-thoracique avec compensation du bassin.", + "x": 36, + "y": 677.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 3, + "text": "RECOMMANDATIONS", + "x": 36, + "y": 645.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Repos 3 jours puis reprise progressive.", + "x": 36, + "y": 631.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 3, + "text": "PROCHAIN RENDEZ-VOUS", + "x": 36, + "y": 599.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "1 juillet 2026", + "x": 36, + "y": 585.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "1 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "2 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "3 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "4 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/text.v2unresolved.en.logos.json b/apps/app/tests/fixtures/goldens/step6/text.v2unresolved.en.logos.json new file mode 100644 index 00000000..ad425d82 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/text.v2unresolved.en.logos.json @@ -0,0 +1,1458 @@ +[ + { + "page": 0, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Owner: Synthetic", + "x": 490.93, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "October 10, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "01", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 0, + "text": "ZONES", + "x": 36, + "y": 677.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "—", + "x": 36, + "y": 664.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "FINDINGS — SPHENOID BONE", + "x": 36, + "y": 641.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Flexion", + "x": 36, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 72.93, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Extension", + "x": 82.83, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 131.74, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Right torsion", + "x": 141.64, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 202.77, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Left torsion", + "x": 212.67, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 267.14, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Right side-bending rotation", + "x": 277.04, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 401.54, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Left side-bending rotation", + "x": 411.44, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 529.28, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Superior vertical strain", + "x": 36, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 140.67, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Inferior vertical strain", + "x": 150.57, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 248.27, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Right lateral strain", + "x": 258.17, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 343.55, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Left lateral strain", + "x": 353.45, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 432.17, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "SBS compression", + "x": 442.07, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 526.54, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Pre-sphenoid / post-sphenoid disengagement", + "x": 36, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 242.77, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Lesser wings dysfunction", + "x": 252.67, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 369.38, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Greater wings dysfunction", + "x": 379.28, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 499.88, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sphenopetrosal suture", + "x": 36, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 141.61, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sphenosquamous suture", + "x": 151.51, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 267.68, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sphenoparietal suture", + "x": 277.58, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 380.56, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Frontosphenoidal suture", + "x": 390.46, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 502.84, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sphenozygomatic suture", + "x": 36, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 151.05, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sphenomaxillary suture", + "x": 160.95, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 270.73, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sphenovomerine suture", + "x": 280.63, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 391.54, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sphenopalatine suture", + "x": 401.44, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 506.5, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "New irritability / aggressiveness", + "x": 36, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 180.63, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Apathy / withdrawal", + "x": 190.53, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 281.48, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Head touch hypersensitivity", + "x": 291.38, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 418.35, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Unexplained performance drop", + "x": 36, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 177.93, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "(!) Reported cycle irregularity", + "x": 187.83, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 321.74, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Post head trauma", + "x": 331.64, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 414.97, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Reported trauma (blow, fall)", + "x": 424.87, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Stress / change context", + "x": 36, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 145.2, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Postural context", + "x": 155.1, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 230.9, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Post recent dental care", + "x": 240.8, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 348.13, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Post veterinary intervention", + "x": 358.03, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 483.94, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "No identified cause", + "x": 36, + "y": 524.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Owner: Synthetic", + "x": 490.93, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "October 10, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "02", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 1, + "text": "ZONES", + "x": 36, + "y": 677.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "—", + "x": 36, + "y": 664.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "FINDINGS — SPHENO-OCCIPITAL SYNCHONDROSIS (SBS, SPHENOBASILAR)", + "x": 36, + "y": 641.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Flexion", + "x": 36, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 72.93, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Extension", + "x": 82.83, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 131.74, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Right torsion", + "x": 141.64, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 202.77, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Left torsion", + "x": 212.67, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 267.14, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Right side-bending rotation", + "x": 277.04, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 401.54, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Left side-bending rotation", + "x": 411.44, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 529.28, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Superior vertical strain", + "x": 36, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 140.67, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Inferior vertical strain", + "x": 150.57, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 248.27, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Right lateral strain", + "x": 258.17, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 343.55, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Left lateral strain", + "x": 353.45, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 432.17, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "SBS compression", + "x": 442.07, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 526.54, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Pre-sphenoid / post-sphenoid disengagement", + "x": 36, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 242.77, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Lesser wings dysfunction", + "x": 252.67, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 369.38, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Greater wings dysfunction", + "x": 379.28, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 499.88, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Sphenopetrosal suture", + "x": 36, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 141.61, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Sphenosquamous suture", + "x": 151.51, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 267.68, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Sphenoparietal suture", + "x": 277.58, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 380.56, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Frontosphenoidal suture", + "x": 390.46, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 502.84, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Sphenozygomatic suture", + "x": 36, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 151.05, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Sphenomaxillary suture", + "x": 160.95, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 270.73, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Sphenovomerine suture", + "x": 280.63, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 391.54, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Sphenopalatine suture", + "x": 401.44, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 506.5, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "New irritability / aggressiveness", + "x": 36, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 180.63, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Apathy / withdrawal", + "x": 190.53, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 281.48, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Head touch hypersensitivity", + "x": 291.38, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 418.35, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Unexplained performance drop", + "x": 36, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 177.93, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "(!) Reported cycle irregularity", + "x": 187.83, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 321.74, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Post head trauma", + "x": 331.64, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 414.97, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Reported trauma (blow, fall)", + "x": 424.87, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Stress / change context", + "x": 36, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 145.2, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Postural context", + "x": 155.1, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 230.9, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Post recent dental care", + "x": 240.8, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 348.13, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Post veterinary intervention", + "x": 358.03, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 483.94, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "No identified cause", + "x": 36, + "y": 524.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Owner: Synthetic", + "x": 490.93, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "October 10, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "03", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 2, + "text": "ZONES", + "x": 36, + "y": 677.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "—", + "x": 36, + "y": 664.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "FINDINGS — FRONTAL BONE", + "x": 36, + "y": 641.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Flexion (external rotation)", + "x": 36, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Owner: Synthetic", + "x": 490.93, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "October 10, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SYNTHESIS", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Conclusion", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 3, + "text": "CONCLUSION", + "x": 36, + "y": 691.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "—", + "x": 36, + "y": 677.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 3, + "text": "RECOMMENDATIONS", + "x": 36, + "y": 645.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "—", + "x": 36, + "y": 631.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "1 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "2 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "3 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Powered by ", + "x": 240.79, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "In partnership with ", + "x": 459.38, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "4 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/text.v2unresolved.en.nologos.json b/apps/app/tests/fixtures/goldens/step6/text.v2unresolved.en.nologos.json new file mode 100644 index 00000000..0cfa2484 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/text.v2unresolved.en.nologos.json @@ -0,0 +1,1522 @@ +[ + { + "page": 0, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Owner: Synthetic", + "x": 490.93, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "October 10, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "01", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 0, + "text": "ZONES", + "x": 36, + "y": 677.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "—", + "x": 36, + "y": 664.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "FINDINGS — SPHENOID BONE", + "x": 36, + "y": 641.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Flexion", + "x": 36, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 72.93, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Extension", + "x": 82.83, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 131.74, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Right torsion", + "x": 141.64, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 202.77, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Left torsion", + "x": 212.67, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 267.14, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Right side-bending rotation", + "x": 277.04, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 401.54, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Left side-bending rotation", + "x": 411.44, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 529.28, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Superior vertical strain", + "x": 36, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 140.67, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Inferior vertical strain", + "x": 150.57, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 248.27, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Right lateral strain", + "x": 258.17, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 343.55, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Left lateral strain", + "x": 353.45, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 432.17, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "SBS compression", + "x": 442.07, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 526.54, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Pre-sphenoid / post-sphenoid disengagement", + "x": 36, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 242.77, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Lesser wings dysfunction", + "x": 252.67, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 369.38, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Greater wings dysfunction", + "x": 379.28, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 499.88, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sphenopetrosal suture", + "x": 36, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 141.61, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sphenosquamous suture", + "x": 151.51, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 267.68, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sphenoparietal suture", + "x": 277.58, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 380.56, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Frontosphenoidal suture", + "x": 390.46, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 502.84, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sphenozygomatic suture", + "x": 36, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 151.05, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sphenomaxillary suture", + "x": 160.95, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 270.73, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sphenovomerine suture", + "x": 280.63, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 391.54, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Sphenopalatine suture", + "x": 401.44, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 506.5, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "New irritability / aggressiveness", + "x": 36, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 180.63, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Apathy / withdrawal", + "x": 190.53, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 281.48, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Head touch hypersensitivity", + "x": 291.38, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 418.35, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Unexplained performance drop", + "x": 36, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 177.93, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "(!) Reported cycle irregularity", + "x": 187.83, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 321.74, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Post head trauma", + "x": 331.64, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 414.97, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Reported trauma (blow, fall)", + "x": 424.87, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Stress / change context", + "x": 36, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 145.2, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Postural context", + "x": 155.1, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 230.9, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Post recent dental care", + "x": 240.8, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 348.13, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Post veterinary intervention", + "x": 358.03, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 483.94, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "No identified cause", + "x": 36, + "y": 524.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Owner: Synthetic", + "x": 490.93, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "October 10, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "02", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 1, + "text": "ZONES", + "x": 36, + "y": 677.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "—", + "x": 36, + "y": 664.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "FINDINGS — SPHENO-OCCIPITAL SYNCHONDROSIS (SBS, SPHENOBASILAR)", + "x": 36, + "y": 641.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Flexion", + "x": 36, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 72.93, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Extension", + "x": 82.83, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 131.74, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Right torsion", + "x": 141.64, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 202.77, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Left torsion", + "x": 212.67, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 267.14, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Right side-bending rotation", + "x": 277.04, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 401.54, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Left side-bending rotation", + "x": 411.44, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 529.28, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Superior vertical strain", + "x": 36, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 140.67, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Inferior vertical strain", + "x": 150.57, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 248.27, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Right lateral strain", + "x": 258.17, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 343.55, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Left lateral strain", + "x": 353.45, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 432.17, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "SBS compression", + "x": 442.07, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 526.54, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Pre-sphenoid / post-sphenoid disengagement", + "x": 36, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 242.77, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Lesser wings dysfunction", + "x": 252.67, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 369.38, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Greater wings dysfunction", + "x": 379.28, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 499.88, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Sphenopetrosal suture", + "x": 36, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 141.61, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Sphenosquamous suture", + "x": 151.51, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 267.68, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Sphenoparietal suture", + "x": 277.58, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 380.56, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Frontosphenoidal suture", + "x": 390.46, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 502.84, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Sphenozygomatic suture", + "x": 36, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 151.05, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Sphenomaxillary suture", + "x": 160.95, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 270.73, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Sphenovomerine suture", + "x": 280.63, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 391.54, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Sphenopalatine suture", + "x": 401.44, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 506.5, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "New irritability / aggressiveness", + "x": 36, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 180.63, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Apathy / withdrawal", + "x": 190.53, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 281.48, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Head touch hypersensitivity", + "x": 291.38, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 418.35, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Unexplained performance drop", + "x": 36, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 177.93, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "(!) Reported cycle irregularity", + "x": 187.83, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 321.74, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Post head trauma", + "x": 331.64, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 414.97, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Reported trauma (blow, fall)", + "x": 424.87, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Stress / change context", + "x": 36, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 145.2, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Postural context", + "x": 155.1, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 230.9, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Post recent dental care", + "x": 240.8, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 348.13, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Post veterinary intervention", + "x": 358.03, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 483.94, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "No identified cause", + "x": 36, + "y": 524.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Owner: Synthetic", + "x": 490.93, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "October 10, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "03", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 2, + "text": "ZONES", + "x": 36, + "y": 677.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "—", + "x": 36, + "y": 664.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "FINDINGS — FRONTAL BONE", + "x": 36, + "y": 641.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Flexion (external rotation)", + "x": 36, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Owner: Synthetic", + "x": 490.93, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "October 10, 2026", + "x": 489.74, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SYNTHESIS", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Conclusion", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 3, + "text": "CONCLUSION", + "x": 36, + "y": 691.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "—", + "x": 36, + "y": 677.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 3, + "text": "RECOMMENDATIONS", + "x": 36, + "y": 645.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "—", + "x": 36, + "y": 631.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "1 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "2 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "3 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Powered by ", + "x": 254.68, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "zenquality.fr", + "x": 298.39, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "In partnership with ", + "x": 421.22, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "4 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/text.v2unresolved.fr.logos.json b/apps/app/tests/fixtures/goldens/step6/text.v2unresolved.fr.logos.json new file mode 100644 index 00000000..c0e4060d --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/text.v2unresolved.fr.logos.json @@ -0,0 +1,1410 @@ +[ + { + "page": 0, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Propriétaire : Synthetic", + "x": 468.56, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "10 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "01", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 0, + "text": "ZONES", + "x": 36, + "y": 677.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "—", + "x": 36, + "y": 664.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "CONSTATS — SPHÉNOÏDE", + "x": 36, + "y": 641.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Flexion", + "x": 36, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 72.93, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Extension", + "x": 82.83, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 131.74, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Torsion droite", + "x": 141.64, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 206.57, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Torsion gauche", + "x": 216.47, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 289.19, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Side-bending rotation droite", + "x": 299.09, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 426.93, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Side-bending rotation gauche", + "x": 36, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 171.63, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Strain vertical haut", + "x": 181.53, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 269.39, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Strain vertical bas", + "x": 279.29, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 363.81, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Strain latéral droit", + "x": 373.71, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 456.87, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Strain latéral gauche", + "x": 466.77, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Compression SSB", + "x": 36, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 122.69, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Désengagement pré-sphénoïde / post-sphénoïde", + "x": 132.59, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 355.49, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Dysfonction des petites ailes", + "x": 365.39, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 496.81, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Dysfonction des grandes ailes", + "x": 36, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 173.89, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suture sphéno-pétreuse", + "x": 183.79, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 296.07, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suture sphéno-squameuse", + "x": 305.97, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 431.03, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suture sphéno-pariétale", + "x": 440.93, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Suture fronto-sphénoïdale", + "x": 36, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 156.62, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suture sphéno-zygomatique", + "x": 166.52, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 296.58, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suture sphéno-maxillaire", + "x": 306.48, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 422.07, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suture sphéno-vomérienne", + "x": 431.97, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Suture sphéno-palatine", + "x": 36, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 144.39, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Irritabilité / agressivité nouvelle", + "x": 154.29, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 295.8, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Apathie / repli", + "x": 305.7, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 371.84, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Hypersensibilité au toucher de la tête", + "x": 381.74, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Baisse de performance inexpliquée", + "x": 36, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 196.83, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "(!) Irrégularité de cyclicité rapportée", + "x": 206.73, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 369.45, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suite de traumatisme crânien", + "x": 379.35, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 514.2, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Traumatisme rapporté (choc, chute)", + "x": 36, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 198.79, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Contexte de stress / changement", + "x": 208.69, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 360.13, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Contexte postural (harnachement, position de travail)", + "x": 36, + "y": 524.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 275.4, + "y": 523.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suite de soin dentaire récent", + "x": 285.3, + "y": 524.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 417.59, + "y": 523.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suite d'intervention vétérinaire", + "x": 36, + "y": 511.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 175.14, + "y": 510.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Pas de cause identifiée", + "x": 185.04, + "y": 511.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Propriétaire : Synthetic", + "x": 468.56, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "10 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "02", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 1, + "text": "ZONES", + "x": 36, + "y": 677.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "—", + "x": 36, + "y": 664.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "CONSTATS — SYNCHONDROSE SPHÉNO-OCCIPITALE (SSB, SPHÉNO-BASILAIRE)", + "x": 36, + "y": 641.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Flexion", + "x": 36, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 72.93, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Extension", + "x": 82.83, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 131.74, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Torsion droite", + "x": 141.64, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 206.57, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Torsion gauche", + "x": 216.47, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 289.19, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Side-bending rotation droite", + "x": 299.09, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 426.93, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Side-bending rotation gauche", + "x": 36, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 171.63, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Strain vertical haut", + "x": 181.53, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 269.39, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Strain vertical bas", + "x": 279.29, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 363.81, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Strain latéral droit", + "x": 373.71, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 456.87, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Strain latéral gauche", + "x": 466.77, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Compression SSB", + "x": 36, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 122.69, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Désengagement pré-sphénoïde / post-sphénoïde", + "x": 132.59, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 355.49, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Dysfonction des petites ailes", + "x": 365.39, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 496.81, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Dysfonction des grandes ailes", + "x": 36, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 173.89, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suture sphéno-pétreuse", + "x": 183.79, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 296.07, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suture sphéno-squameuse", + "x": 305.97, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 431.03, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suture sphéno-pariétale", + "x": 440.93, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Suture fronto-sphénoïdale", + "x": 36, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 156.62, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suture sphéno-zygomatique", + "x": 166.52, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 296.58, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suture sphéno-maxillaire", + "x": 306.48, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 422.07, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suture sphéno-vomérienne", + "x": 431.97, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Suture sphéno-palatine", + "x": 36, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 144.39, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Irritabilité / agressivité nouvelle", + "x": 154.29, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 295.8, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Apathie / repli", + "x": 305.7, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 371.84, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Hypersensibilité au toucher de la tête", + "x": 381.74, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Baisse de performance inexpliquée", + "x": 36, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 196.83, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "(!) Irrégularité de cyclicité rapportée", + "x": 206.73, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 369.45, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suite de traumatisme crânien", + "x": 379.35, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 514.2, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Traumatisme rapporté (choc, chute)", + "x": 36, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 198.79, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Contexte de stress / changement", + "x": 208.69, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 360.13, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Contexte postural (harnachement, position de travail)", + "x": 36, + "y": 524.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 275.4, + "y": 523.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suite de soin dentaire récent", + "x": 285.3, + "y": 524.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 417.59, + "y": 523.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suite d'intervention vétérinaire", + "x": 36, + "y": 511.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 175.14, + "y": 510.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Pas de cause identifiée", + "x": 185.04, + "y": 511.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Propriétaire : Synthetic", + "x": 468.56, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "10 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "03", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 2, + "text": "ZONES", + "x": 36, + "y": 677.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "—", + "x": 36, + "y": 664.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "CONSTATS — FRONTAL", + "x": 36, + "y": 641.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "En flexion (rotation externe)", + "x": 36, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Propriétaire : Synthetic", + "x": 468.56, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "10 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SYNTHÈSE", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Conclusion", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 3, + "text": "CONCLUSION", + "x": 36, + "y": 691.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "—", + "x": 36, + "y": 677.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 3, + "text": "RECOMMANDATIONS", + "x": 36, + "y": 645.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "—", + "x": 36, + "y": 631.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "1 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "2 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "3 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Propulsé par ", + "x": 238.85, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "En partenariat avec ", + "x": 455.61, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "4 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/text.v2unresolved.fr.nologos.json b/apps/app/tests/fixtures/goldens/step6/text.v2unresolved.fr.nologos.json new file mode 100644 index 00000000..b0cfe175 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/text.v2unresolved.fr.nologos.json @@ -0,0 +1,1474 @@ +[ + { + "page": 0, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Propriétaire : Synthetic", + "x": 468.56, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "10 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 0, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "01", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 0, + "text": "ZONES", + "x": 36, + "y": 677.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "—", + "x": 36, + "y": 664.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "CONSTATS — SPHÉNOÏDE", + "x": 36, + "y": 641.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Flexion", + "x": 36, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 72.93, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Extension", + "x": 82.83, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 131.74, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Torsion droite", + "x": 141.64, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 206.57, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Torsion gauche", + "x": 216.47, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 289.19, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Side-bending rotation droite", + "x": 299.09, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 426.93, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Side-bending rotation gauche", + "x": 36, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 171.63, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Strain vertical haut", + "x": 181.53, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 269.39, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Strain vertical bas", + "x": 279.29, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 363.81, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Strain latéral droit", + "x": 373.71, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 456.87, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Strain latéral gauche", + "x": 466.77, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Compression SSB", + "x": 36, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 122.69, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Désengagement pré-sphénoïde / post-sphénoïde", + "x": 132.59, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 355.49, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Dysfonction des petites ailes", + "x": 365.39, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 496.81, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Dysfonction des grandes ailes", + "x": 36, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 173.89, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suture sphéno-pétreuse", + "x": 183.79, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 296.07, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suture sphéno-squameuse", + "x": 305.97, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 431.03, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suture sphéno-pariétale", + "x": 440.93, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Suture fronto-sphénoïdale", + "x": 36, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 156.62, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suture sphéno-zygomatique", + "x": 166.52, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 296.58, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suture sphéno-maxillaire", + "x": 306.48, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 422.07, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suture sphéno-vomérienne", + "x": 431.97, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Suture sphéno-palatine", + "x": 36, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 144.39, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Irritabilité / agressivité nouvelle", + "x": 154.29, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 295.8, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Apathie / repli", + "x": 305.7, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 371.84, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Hypersensibilité au toucher de la tête", + "x": 381.74, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Baisse de performance inexpliquée", + "x": 36, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 196.83, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "(!) Irrégularité de cyclicité rapportée", + "x": 206.73, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 369.45, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suite de traumatisme crânien", + "x": 379.35, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 514.2, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Traumatisme rapporté (choc, chute)", + "x": 36, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 198.79, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Contexte de stress / changement", + "x": 208.69, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 360.13, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Contexte postural (harnachement, position de travail)", + "x": 36, + "y": 524.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 275.4, + "y": 523.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suite de soin dentaire récent", + "x": 285.3, + "y": 524.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 417.59, + "y": 523.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Suite d'intervention vétérinaire", + "x": 36, + "y": 511.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 0, + "text": "•", + "x": 175.14, + "y": 510.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 0, + "text": "Pas de cause identifiée", + "x": 185.04, + "y": 511.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Propriétaire : Synthetic", + "x": 468.56, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "10 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 1, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "02", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 1, + "text": "ZONES", + "x": 36, + "y": 677.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "—", + "x": 36, + "y": 664.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "CONSTATS — SYNCHONDROSE SPHÉNO-OCCIPITALE (SSB, SPHÉNO-BASILAIRE)", + "x": 36, + "y": 641.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Flexion", + "x": 36, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 72.93, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Extension", + "x": 82.83, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 131.74, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Torsion droite", + "x": 141.64, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 206.57, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Torsion gauche", + "x": 216.47, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 289.19, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Side-bending rotation droite", + "x": 299.09, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 426.93, + "y": 627.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Side-bending rotation gauche", + "x": 36, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 171.63, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Strain vertical haut", + "x": 181.53, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 269.39, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Strain vertical bas", + "x": 279.29, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 363.81, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Strain latéral droit", + "x": 373.71, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 456.87, + "y": 614.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Strain latéral gauche", + "x": 466.77, + "y": 615.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Compression SSB", + "x": 36, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 122.69, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Désengagement pré-sphénoïde / post-sphénoïde", + "x": 132.59, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 355.49, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Dysfonction des petites ailes", + "x": 365.39, + "y": 602.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 496.81, + "y": 601.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Dysfonction des grandes ailes", + "x": 36, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 173.89, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suture sphéno-pétreuse", + "x": 183.79, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 296.07, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suture sphéno-squameuse", + "x": 305.97, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 431.03, + "y": 588.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suture sphéno-pariétale", + "x": 440.93, + "y": 589.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Suture fronto-sphénoïdale", + "x": 36, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 156.62, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suture sphéno-zygomatique", + "x": 166.52, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 296.58, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suture sphéno-maxillaire", + "x": 306.48, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 422.07, + "y": 575.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suture sphéno-vomérienne", + "x": 431.97, + "y": 576.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Suture sphéno-palatine", + "x": 36, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 144.39, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Irritabilité / agressivité nouvelle", + "x": 154.29, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 295.8, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Apathie / repli", + "x": 305.7, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 371.84, + "y": 562.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Hypersensibilité au toucher de la tête", + "x": 381.74, + "y": 563.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Baisse de performance inexpliquée", + "x": 36, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 196.83, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "(!) Irrégularité de cyclicité rapportée", + "x": 206.73, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 369.45, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suite de traumatisme crânien", + "x": 379.35, + "y": 550.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 514.2, + "y": 549.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Traumatisme rapporté (choc, chute)", + "x": 36, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 198.79, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Contexte de stress / changement", + "x": 208.69, + "y": 537.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 360.13, + "y": 536.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Contexte postural (harnachement, position de travail)", + "x": 36, + "y": 524.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 275.4, + "y": 523.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suite de soin dentaire récent", + "x": 285.3, + "y": 524.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 417.59, + "y": 523.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Suite d'intervention vétérinaire", + "x": 36, + "y": 511.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 1, + "text": "•", + "x": 175.14, + "y": 510.69, + "size": 14, + "font": "Helvetica-Bold" + }, + { + "page": 1, + "text": "Pas de cause identifiée", + "x": 185.04, + "y": 511.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "Propriétaire : Synthetic", + "x": 468.56, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "10 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 2, + "text": "OBSERVATION", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "03", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 2, + "text": "ZONES", + "x": 36, + "y": 677.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "—", + "x": 36, + "y": 664.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 2, + "text": "CONSTATS — FRONTAL", + "x": 36, + "y": 641.89, + "size": 8, + "font": "Helvetica-Bold" + }, + { + "page": 2, + "text": "En flexion (rotation externe)", + "x": 36, + "y": 628.89, + "size": 10, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Synthetic", + "x": 36, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Synthetic", + "x": 509.77, + "y": 800, + "size": 11, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Propriétaire : Synthetic", + "x": 468.56, + "y": 788, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "10 octobre 2026", + "x": 494.24, + "y": 776, + "size": 9, + "font": "Helvetica" + }, + { + "page": 3, + "text": "SYNTHÈSE", + "x": 36, + "y": 746.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "Conclusion", + "x": 36, + "y": 719.89, + "size": 22, + "font": "Times-Roman" + }, + { + "page": 3, + "text": "CONCLUSION", + "x": 36, + "y": 691.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "—", + "x": 36, + "y": 677.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 3, + "text": "RECOMMANDATIONS", + "x": 36, + "y": 645.89, + "size": 9, + "font": "Helvetica-Bold" + }, + { + "page": 3, + "text": "—", + "x": 36, + "y": 631.89, + "size": 11, + "font": "Helvetica" + }, + { + "page": 0, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 0, + "text": "1 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 1, + "text": "2 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 2, + "text": "3 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "Propulsé par ", + "x": 252.75, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "zenquality.fr", + "x": 300.32, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "En partenariat avec ", + "x": 417.45, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "@paws.iin.harmony", + "x": 489.12, + "y": 40, + "size": 8, + "font": "Helvetica" + }, + { + "page": 3, + "text": "4 / 4", + "x": 289.86, + "y": 22, + "size": 8, + "font": "Helvetica" + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/views.demo.json b/apps/app/tests/fixtures/goldens/step6/views.demo.json new file mode 100644 index 00000000..8197054a --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/views.demo.json @@ -0,0 +1,277 @@ +[ + { + "observationId": "obs-demo-1", + "viewId": "main", + "viewBox": "0 0 2073.4 1629.4", + "halo": true, + "highlighted": [ + { + "tag": "circle", + "cx": "1118", + "cy": "528", + "r": "30", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + }, + { + "tag": "circle", + "cx": "1118", + "cy": "528", + "r": "18", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + }, + { + "tag": "circle", + "cx": "865", + "cy": "528", + "r": "30", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + }, + { + "tag": "circle", + "cx": "865", + "cy": "528", + "r": "18", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + } + ], + "nonHighlightedVisible": 0, + "dataAttributes": 2, + "titles": 32 + }, + { + "observationId": "obs-demo-2", + "viewId": "main", + "viewBox": "0 0 2073.4 1629.4", + "halo": true, + "highlighted": [ + { + "tag": "circle", + "cx": "1585", + "cy": "612", + "r": "34", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + }, + { + "tag": "circle", + "cx": "1585", + "cy": "612", + "r": "22", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + } + ], + "nonHighlightedVisible": 0, + "dataAttributes": 2, + "titles": 32 + }, + { + "observationId": "obs-demo-3", + "viewId": "main", + "viewBox": "0 0 2073.4 1629.4", + "halo": true, + "highlighted": [ + { + "tag": "polygon", + "cx": null, + "cy": null, + "r": null, + "points": "468,276 489,216 558,248 586,339 607,401 625,447 649,510 695.1,528.4 728.9,520.1 765.3,472.8 816.8,453 796.5,543.7 730,600 646,604 593,565 552,461 524,370", + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + } + ], + "nonHighlightedVisible": 0, + "dataAttributes": 2, + "titles": 32 + }, + { + "observationId": "obs-demo-4", + "viewId": "head", + "viewBox": "60 100 500 380", + "halo": false, + "highlighted": [ + { + "tag": "circle", + "cx": "277", + "cy": "214", + "r": "27", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": null + }, + { + "tag": "circle", + "cx": "277", + "cy": "214", + "r": "15", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": null + }, + { + "tag": "circle", + "cx": "400", + "cy": "258", + "r": "27", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": null + }, + { + "tag": "circle", + "cx": "400", + "cy": "258", + "r": "15", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": null + } + ], + "nonHighlightedVisible": 0, + "dataAttributes": 2, + "titles": 18 + }, + { + "observationId": "obs-demo-5", + "viewId": "main", + "viewBox": "0 0 2073.4 1629.4", + "halo": true, + "highlighted": [ + { + "tag": "circle", + "cx": "1450", + "cy": "578", + "r": "34", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + }, + { + "tag": "circle", + "cx": "1450", + "cy": "578", + "r": "22", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + } + ], + "nonHighlightedVisible": 0, + "dataAttributes": 2, + "titles": 32 + }, + { + "observationId": "obs-demo-5", + "viewId": "head", + "viewBox": "60 100 500 380", + "halo": false, + "highlighted": [ + { + "tag": "circle", + "cx": "441", + "cy": "190", + "r": "27", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": null + }, + { + "tag": "circle", + "cx": "441", + "cy": "190", + "r": "15", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": null + } + ], + "nonHighlightedVisible": 0, + "dataAttributes": 2, + "titles": 18 + }, + { + "observationId": "obs-demo-6", + "viewId": "main", + "viewBox": "0 0 2073.4 1629.4", + "halo": true, + "highlighted": [ + { + "tag": "circle", + "cx": "1424", + "cy": "515", + "r": "30", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + }, + { + "tag": "circle", + "cx": "1424", + "cy": "515", + "r": "18", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + }, + { + "tag": "polygon", + "cx": null, + "cy": null, + "r": null, + "points": "1401.3,457.1 1386,562 1232,562 1130,552 1131.4,503.2 1260,475 1361,454.4", + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + } + ], + "nonHighlightedVisible": 0, + "dataAttributes": 2, + "titles": 32 + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/views.v2full.json b/apps/app/tests/fixtures/goldens/step6/views.v2full.json new file mode 100644 index 00000000..53d74ef9 --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/views.v2full.json @@ -0,0 +1,112 @@ +[ + { + "observationId": "obs-1", + "viewId": "main", + "viewBox": "0 0 2073.4 1629.4", + "halo": true, + "highlighted": [ + { + "tag": "circle", + "cx": "1585", + "cy": "612", + "r": "34", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + }, + { + "tag": "circle", + "cx": "1585", + "cy": "612", + "r": "22", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + }, + { + "tag": "circle", + "cx": "865", + "cy": "528", + "r": "30", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + }, + { + "tag": "circle", + "cx": "865", + "cy": "528", + "r": "18", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + } + ], + "nonHighlightedVisible": 0, + "dataAttributes": 2, + "titles": 32 + }, + { + "observationId": "obs-2", + "viewId": "main", + "viewBox": "0 0 2073.4 1629.4", + "halo": true, + "highlighted": [ + { + "tag": "polygon", + "cx": null, + "cy": null, + "r": null, + "points": "468,276 489,216 558,248 586,339 607,401 625,447 649,510 695.1,528.4 728.9,520.1 765.3,472.8 816.8,453 796.5,543.7 730,600 646,604 593,565 552,461 524,370", + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": "url(#osteo-halo)" + } + ], + "nonHighlightedVisible": 0, + "dataAttributes": 2, + "titles": 32 + }, + { + "observationId": "obs-3", + "viewId": "head", + "viewBox": "60 100 500 380", + "halo": false, + "highlighted": [ + { + "tag": "circle", + "cx": "400", + "cy": "258", + "r": "27", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": null + }, + { + "tag": "circle", + "cx": "400", + "cy": "258", + "r": "15", + "points": null, + "d": null, + "fill": "#b85a3f", + "fillOpacity": "0.85", + "filter": null + } + ], + "nonHighlightedVisible": 0, + "dataAttributes": 2, + "titles": 18 + } +] diff --git a/apps/app/tests/fixtures/goldens/step6/views.v2unresolved.json b/apps/app/tests/fixtures/goldens/step6/views.v2unresolved.json new file mode 100644 index 00000000..fe51488c --- /dev/null +++ b/apps/app/tests/fixtures/goldens/step6/views.v2unresolved.json @@ -0,0 +1 @@ +[] diff --git a/apps/app/tests/fixtures/report-v3.bare.pdf b/apps/app/tests/fixtures/report-v3.bare.pdf new file mode 100644 index 00000000..618b145b Binary files /dev/null and b/apps/app/tests/fixtures/report-v3.bare.pdf differ diff --git a/apps/app/tests/fixtures/report-v3.demo.json b/apps/app/tests/fixtures/report-v3.demo.json new file mode 100644 index 00000000..74e19b0a --- /dev/null +++ b/apps/app/tests/fixtures/report-v3.demo.json @@ -0,0 +1,239 @@ +{ + "version": 3, + "id": "fixture-demo-v3", + "createdAt": "2026-10-11T09:30:00.000Z", + "date": "2026-10-11", + "practitioner": { + "name": "Dr. Claire Dupont", + "cabinet": "Cabinet Équi-Ostéo", + "contact": "claire@example.test", + "siret": "12345678901234" + }, + "animal": { + "speciesId": "equine", + "name": "Mistral", + "breed": "Selle Français", + "age": "9 ans" + }, + "owner": { + "name": "Jean Martin" + }, + "sheet": { + "sheetId": "503dc301-a8b1-50d4-9e44-0919b2fc2916", + "versionId": null, + "documentSha256": "27c7383c445c73dc2001ebf4794a3ea63d416910bbbaa0d7848dd720de7c2660" + }, + "observations": [ + { + "id": "obs-demo-1", + "zones": [ + { + "annotationId": "c7-t1", + "viewId": "main", + "labelFrSnapshot": "Charnière C7-T1 (cervico-thoracique)", + "labelEnSnapshot": "C7-T1 junction (cervicothoracic)" + }, + { + "annotationId": "t18-l1", + "viewId": "main", + "labelFrSnapshot": "Charnière T18-L1 (thoraco-lombaire)", + "labelEnSnapshot": "T18-L1 junction (thoracolumbar)" + } + ], + "findings": [ + { + "findingZoneId": "c7-t1", + "path": ["c7-t1-dysfunctions", "segmental", "restriction-flexion"], + "labelFrSnapshot": "Restriction en flexion", + "labelEnSnapshot": "Flexion restriction" + }, + { + "findingZoneId": "c7-t1", + "path": ["c7-t1-dysfunctions", "segmental", "restriction-extension"], + "labelFrSnapshot": "Restriction en extension", + "labelEnSnapshot": "Extension restriction" + } + ], + "freeTextFindings": [], + "severity": "mild", + "comment": "Réagit à la palpation de la charnière." + }, + { + "id": "obs-demo-2", + "zones": [ + { + "annotationId": "hip", + "viewId": "main", + "side": "left", + "labelFrSnapshot": "Hanche (coxo-fémorale)", + "labelEnSnapshot": "Hip joint" + }, + { + "annotationId": "hip", + "viewId": "main", + "side": "right", + "labelFrSnapshot": "Hanche (coxo-fémorale)", + "labelEnSnapshot": "Hip joint" + } + ], + "findings": [ + { + "findingZoneId": "hip", + "path": ["hip-dysfunctions", "articular", "restriction-flexion"], + "labelFrSnapshot": "Restriction en flexion", + "labelEnSnapshot": "Flexion restriction", + "side": "left" + }, + { + "findingZoneId": "hip", + "path": [ + "hip-dysfunctions", + "articular", + "restriction-abduction-adduction" + ], + "labelFrSnapshot": "Restriction en abduction / adduction", + "labelEnSnapshot": "Abduction / adduction restriction", + "side": "right" + } + ], + "freeTextFindings": [], + "severity": "moderate", + "comment": "" + }, + { + "id": "obs-demo-3", + "zones": [ + { + "annotationId": "cervical", + "viewId": "main", + "vertebrae": [ + { + "region": "C", + "index": 3 + }, + { + "region": "C", + "index": 4 + } + ], + "labelFrSnapshot": "Vertèbres cervicales", + "labelEnSnapshot": "Cervical vertebrae" + } + ], + "findings": [ + { + "findingZoneId": "cervical", + "path": ["cervical-dysfunctions", "segmental", "localized-fixation"], + "labelFrSnapshot": "Fixation segmentaire localisée (C2–C7)", + "labelEnSnapshot": "Localized segmental fixation (C2–C7)" + } + ], + "freeTextFindings": [], + "severity": "severe", + "comment": "Fixation nette en latéroflexion droite." + }, + { + "id": "obs-demo-4", + "zones": [ + { + "annotationId": "atm", + "viewId": "head", + "labelFrSnapshot": "Articulation temporo-mandibulaire (ATM)", + "labelEnSnapshot": "Temporomandibular joint (TMJ)" + }, + { + "annotationId": "frontal", + "viewId": "head", + "labelFrSnapshot": "Frontal", + "labelEnSnapshot": "Frontal bone" + } + ], + "findings": [ + { + "findingZoneId": "frontal", + "path": ["frontal-consultation-reasons", "head-rubbing"], + "labelFrSnapshot": "Frottements répétés de la tête rapportés", + "labelEnSnapshot": "Reported repeated head rubbing", + "requiresVetReferral": true + }, + { + "findingZoneId": "atm", + "path": ["atm-dysfunctions", "articular", "restriction-opening"], + "labelFrSnapshot": "Restriction à l'ouverture", + "labelEnSnapshot": "Opening restriction" + } + ], + "freeTextFindings": [], + "comment": "" + }, + { + "id": "obs-demo-5", + "zones": [ + { + "annotationId": "sacroiliac", + "viewId": "main", + "side": "right", + "labelFrSnapshot": "Articulation sacro-iliaque", + "labelEnSnapshot": "Sacroiliac joint" + }, + { + "annotationId": "occipital", + "viewId": "head", + "labelFrSnapshot": "Occipital", + "labelEnSnapshot": "Occipital bone" + } + ], + "findings": [], + "freeTextFindings": [ + "Sensibilité au garrot", + "Tension du ligament nuchal" + ], + "severity": "mild", + "comment": "Compensation probable." + }, + { + "id": "obs-demo-6", + "zones": [ + { + "annotationId": "lumbar", + "viewId": "main", + "vertebrae": [ + { + "region": "L", + "index": 2 + }, + { + "region": "L", + "index": 3 + } + ], + "labelFrSnapshot": "Vertèbres lombaires", + "labelEnSnapshot": "Lumbar vertebrae" + }, + { + "annotationId": "l6-s1", + "viewId": "main", + "labelFrSnapshot": "Charnière L6-S1 (lombo-sacrée)", + "labelEnSnapshot": "L6-S1 junction (lumbosacral joint)" + } + ], + "findings": [ + { + "findingZoneId": "lumbar", + "path": ["lumbar-dysfunctions", "segmental", "restriction-extension"], + "labelFrSnapshot": "Restriction en extension", + "labelEnSnapshot": "Extension restriction" + } + ], + "freeTextFindings": ["Raideur lombaire au pas"], + "comment": "" + } + ], + "conclusion": "Dysfonction cervico-thoracique avec compensation du bassin et tension crânienne associée.", + "recommendations": "Repos 3 jours puis reprise progressive ; contrôle vétérinaire pour les frottements de tête.", + "nextAppointment": { + "kind": "period", + "text": "6 à 8 semaines" + }, + "localAnnotations": [] +} diff --git a/apps/app/tests/helpers/goldens.ts b/apps/app/tests/helpers/goldens.ts new file mode 100644 index 00000000..cf31b2cf --- /dev/null +++ b/apps/app/tests/helpers/goldens.ts @@ -0,0 +1,301 @@ +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { dirname, resolve } from 'node:path' +import { expect, vi } from 'vitest' +import { + PDFArray, + PDFDict, + PDFDocument, + PDFHexString, + PDFName, + PDFNumber, + PDFPage, + PDFString, +} from 'pdf-lib' +import type { + Branding, + Observation, + Report, + SheetSnapshot, +} from '@faunosteo/domain' +import { composeHighlightedViewSvg } from '@faunosteo/pdf' +import { nologosBranding } from './sheet' + +/** + * Step 6 Phase 0 freeze: what the PDF pipeline drew before the engine, + * recorded as JSON goldens (docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md + * §17) that the app export path must still reproduce. The recorder spies on + * pdf-lib, the link reader parses the saved bytes, the view snapshot parses + * the engine's highlighted SVG with the browser DOM. Numbers are rounded to + * 2 decimals; nothing ordered by drawing order is sorted. + */ + +/** 1×1 PNG (nologos: the legacy stub) and 2×1 PNG (logos: deterministic partner logo width). */ +export const ONE_PX_PNG = Uint8Array.from( + Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', + 'base64', + ), +) +export const TWO_BY_ONE_PNG = Uint8Array.from( + Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7QOjdAAAAD0lEQVR4nGPYEWX///9/AA0PBE/1T7nxAAAAAElFTkSuQmCC', + 'base64', + ), +) + +const HERE = dirname(fileURLToPath(import.meta.url)) +export const FIXTURES_DIR = resolve(HERE, '../fixtures') +export const GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/step6') + +/** `MAKE_GOLDEN=1` writes the goldens instead of asserting them. */ +export const MAKE_GOLDEN = process.env.MAKE_GOLDEN === '1' + +export type LogoMode = 'nologos' | 'logos' + +export interface TextEntry { + page: number + text: string + x: number | null + y: number | null + size: number | null + font: string | null +} + +export interface ImageEntry { + page: number + x: number | null + y: number | null + width: number | null + height: number | null +} + +export interface LinkEntry { + page: number + rect: number[] + uri: string +} + +export interface HighlightedElement { + tag: string + cx: string | null + cy: string | null + r: string | null + points: string | null + d: string | null + fill: string | null + fillOpacity: string | null + filter: string | null +} + +export interface ViewSnapshot { + observationId: string + viewId: string + viewBox: string | null + halo: boolean + highlighted: HighlightedElement[] + nonHighlightedVisible: number + dataAttributes: number + titles: number +} + +export function round2(value: unknown): number | null { + return typeof value === 'number' ? Math.round(value * 100) / 100 : null +} + +/** Pages are appended in order and never moved: the index at draw time is final. */ +function pageIndex(page: PDFPage): number { + return page.doc.getPages().indexOf(page) +} + +export interface DrawRecording { + texts: TextEntry[] + images: ImageEntry[] + stop(): void +} + +/** Records every drawText / drawImage while letting pdf-lib draw for real. */ +export function recordDrawing(): DrawRecording { + const texts: TextEntry[] = [] + const images: ImageEntry[] = [] + const drawText = PDFPage.prototype.drawText + const drawImage = PDFPage.prototype.drawImage + const textSpy = vi + .spyOn(PDFPage.prototype, 'drawText') + .mockImplementation(function (this: PDFPage, text, options) { + texts.push({ + page: pageIndex(this), + text, + x: round2(options?.x), + y: round2(options?.y), + size: round2(options?.size), + font: options?.font?.name ?? null, + }) + return drawText.call(this, text, options) + }) + const imageSpy = vi + .spyOn(PDFPage.prototype, 'drawImage') + .mockImplementation(function (this: PDFPage, image, options) { + images.push({ + page: pageIndex(this), + x: round2(options?.x), + y: round2(options?.y), + width: round2(options?.width), + height: round2(options?.height), + }) + return drawImage.call(this, image, options) + }) + return { + texts, + images, + stop: () => { + textSpy.mockRestore() + imageSpy.mockRestore() + }, + } +} + +function linkOf(dict: PDFDict, page: number): LinkEntry | null { + if (dict.get(PDFName.of('Subtype')) !== PDFName.of('Link')) return null + const rect = dict + .lookup(PDFName.of('Rect'), PDFArray) + .asArray() + .map((n) => round2((n as PDFNumber).asNumber()) ?? 0) + const uri = dict.lookup(PDFName.of('A'), PDFDict).lookup(PDFName.of('URI')) + const text = + uri instanceof PDFString || uri instanceof PDFHexString + ? uri.decodeText() + : String(uri) + return { page, rect, uri: text } +} + +/** Every `/Annot /Link` of the saved PDF, page by page, in annotation order. */ +export async function readLinks(bytes: Uint8Array): Promise<LinkEntry[]> { + const doc = await PDFDocument.load(bytes) + const out: LinkEntry[] = [] + doc.getPages().forEach((page, index) => { + const annots = page.node.Annots() + if (!annots) return + for (let i = 0; i < annots.size(); i += 1) { + const link = linkOf(annots.lookup(i, PDFDict), index) + if (link) out.push(link) + } + }) + return out +} + +/** + * The branding of one logo mode, for a test that mocks `@/pdf/branding`: + * `logos` is the real module (the bundled files), `nologos` every slot + * empty with the credits' fallback texts (the Phase 0 fetch 404). + */ +export async function brandingOf(mode: LogoMode): Promise<Branding> { + if (mode === 'nologos') return nologosBranding() + const real = + await vi.importActual<typeof import('@/pdf/branding')>('@/pdf/branding') + return real.loadBranding() +} + +const HIGHLIGHT_FILL = '#b85a3f' + +function highlightedOf(el: Element): HighlightedElement { + const attr = (name: string) => el.getAttribute(name) + return { + tag: el.tagName, + cx: attr('cx'), + cy: attr('cy'), + r: attr('r'), + points: attr('points'), + d: attr('d'), + fill: attr('fill'), + fillOpacity: attr('fill-opacity'), + filter: attr('filter'), + } +} + +/** Children of the annotation layer (last `<g>` of the root) still visible and not highlighted. */ +function countVisibleNonHighlighted(root: Element): number { + const layer = Array.from(root.children) + .filter((c) => c.tagName === 'g') + .at(-1) + if (!layer) return 0 + return Array.from(layer.children).filter( + (el) => + el.getAttribute('fill') !== HIGHLIGHT_FILL && + el.getAttribute('display') !== 'none', + ).length +} + +function countDataAttributes(root: Element): number { + return [root, ...Array.from(root.querySelectorAll('*'))].reduce( + (count, el) => + count + + Array.from(el.attributes).filter((a) => a.name.startsWith('data-')) + .length, + 0, + ) +} + +export function snapshotView( + sheet: SheetSnapshot, + observation: Observation, + viewId: string, +): ViewSnapshot { + const svg = composeHighlightedViewSvg(sheet, viewId, observation) + const root = new DOMParser().parseFromString( + svg, + 'image/svg+xml', + ).documentElement + return { + observationId: observation.id, + viewId, + viewBox: root.getAttribute('viewBox'), + halo: root.querySelector('filter#osteo-halo') !== null, + highlighted: Array.from( + root.querySelectorAll(`[fill="${HIGHLIGHT_FILL}"]`), + ).map(highlightedOf), + nonHighlightedVisible: countVisibleNonHighlighted(root), + dataAttributes: countDataAttributes(root), + titles: root.getElementsByTagName('title').length, + } +} + +/** The views an observation draws, in the pipeline's order: main first, then first appearance. */ +export function viewIdsOf( + sheet: SheetSnapshot, + observation: Observation, +): string[] { + const views = new Set(sheet.document.views.map((v) => v.id)) + const main = sheet.document.views.find((v) => v.kind === 'main')!.id + return [...new Set(observation.zones.map((z) => z.viewId))] + .filter((id) => views.has(id)) + .sort((a, b) => Number(b === main) - Number(a === main)) +} + +export function snapshotViews( + sheet: SheetSnapshot, + report: Report, +): ViewSnapshot[] { + return report.observations.flatMap((observation) => + viewIdsOf(sheet, observation).map((viewId) => + snapshotView(sheet, observation, viewId), + ), + ) +} + +export function readGolden<T = unknown>(name: string): T { + return JSON.parse(readFileSync(resolve(GOLDEN_DIR, name), 'utf8')) as T +} + +/** Writes the golden under MAKE_GOLDEN, asserts deep equality otherwise. */ +export function checkGolden(name: string, actual: unknown): void { + if (MAKE_GOLDEN) { + mkdirSync(GOLDEN_DIR, { recursive: true }) + writeFileSync( + resolve(GOLDEN_DIR, name), + `${JSON.stringify(actual, null, 2)}\n`, + ) + return + } + expect(actual, name).toEqual(readGolden(name)) +} diff --git a/apps/app/tests/helpers/sheet.ts b/apps/app/tests/helpers/sheet.ts index fec09f0e..1f31de19 100644 --- a/apps/app/tests/helpers/sheet.ts +++ b/apps/app/tests/helpers/sheet.ts @@ -1,8 +1,14 @@ import { + buildSheetSnapshot, + ENVELOPE_FORMAT, + ENVELOPE_VERSION, REPORT_VERSION, + type Branding, type Observation, type Report, + type ReportArchiveEnvelope, } from '@faunosteo/domain' +import { defaultPdfLabels } from '@faunosteo/pdf' import { loadSheetIndex } from '@/sheets/useSheet' import type { SheetIndex } from '@/services/sheetIndex' @@ -37,3 +43,39 @@ export function minimalReport( ...patch, } } + +/** The branding the app loads when every logo fetch fails (credits keep their text). */ +export function nologosBranding(): Branding { + return { + siteUrl: 'https://faunosteo.com', + headerLogo: null, + footerLogo: null, + poweredBy: { + logo: null, + url: 'https://zenquality.fr', + fallbackText: 'zenquality.fr', + }, + partner: { + logo: null, + url: 'https://www.instagram.com/paws.iin.harmony', + fallbackText: '@paws.iin.harmony', + }, + } +} + +/** A valid Step 6 envelope for `report`, snapshotted on `sheet` (no logos). */ +export function archiveEnvelope( + sheet: SheetIndex, + report: Report, +): ReportArchiveEnvelope { + return { + format: ENVELOPE_FORMAT, + envelopeVersion: ENVELOPE_VERSION, + exportedAt: '2026-10-11T12:00:00.000Z', + locale: 'fr', + report, + sheetSnapshot: buildSheetSnapshot(sheet.sheet, report), + branding: nologosBranding(), + labels: defaultPdfLabels, + } +} diff --git a/apps/app/tests/unit/i18n.keys.test.ts b/apps/app/tests/unit/i18n.keys.test.ts index 4d1c4c0a..1585919a 100644 --- a/apps/app/tests/unit/i18n.keys.test.ts +++ b/apps/app/tests/unit/i18n.keys.test.ts @@ -3,6 +3,9 @@ import { fr } from '@/i18n/fr' import { en } from '@/i18n/en' import { pickLocaleLabel } from '@/i18n/pickLocaleLabel' +// The pdf.* keys left the app dicts with Step 6: the engine owns them +// (@faunosteo/pdf defaultPdfLabels, parity tested there). + const REQUIRED = [ 'severity.mild', 'severity.moderate', @@ -11,14 +14,15 @@ const REQUIRED = [ 'home.import.error_invalid_pdf', 'home.import.error_no_attachment', 'home.import.error_generic', - 'pdf.section.zones', - 'pdf.section.findings_prefix', - 'pdf.section.free_findings', - 'pdf.section.severity', - 'pdf.section.comment', - 'pdf.view.general', - 'pdf.view.detail_prefix', - 'pdf.empty', + 'home.import.error_attachment_stripped', + 'home.import.archive_ok', + 'home.import.complete', + 'home.import.degraded', + 'home.import.snapshot_reason.unsupported_envelope', + 'home.import.snapshot_reason.schema', + 'home.import.snapshot_reason.caps', + 'home.import.snapshot_reason.integrity', + 'home.import.snapshot_reason.sheet_mismatch', 'sheet.status.draft', 'sheet.loading', 'vertebra.range_note', @@ -27,6 +31,9 @@ const REQUIRED = [ const PLACEHOLDERS: Record<string, string> = { 'home.import.error_incompatible_version': '{version}', 'home.import.migrated': '{count}', + 'home.import.rebased': '{count}', + 'home.import.snapshot_rejected': '{reason}', + 'editor.draft_rebased': '{count}', 'vertebra.extend_to': '{max}', } diff --git a/apps/app/tests/unit/migration.leaves.test.ts b/apps/app/tests/unit/migration.leaves.test.ts index c37446a7..4a72ebd5 100644 --- a/apps/app/tests/unit/migration.leaves.test.ts +++ b/apps/app/tests/unit/migration.leaves.test.ts @@ -19,15 +19,11 @@ import { loadLegacyBaseline, } from '../helpers/legacyLeaves' -const ONE_PX_PNG = Uint8Array.from( - Buffer.from( - 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', - 'base64', - ), -) -vi.mock('@/pdf/render/svgToPng', () => ({ - rasterizeSvg: vi.fn(async () => ONE_PX_PNG), -})) +// The factory runs when the engine first loads the adapter: fixed 1×1 PNG. +vi.mock('@/pdf/browserRasterizer', async () => { + const { ONE_PX_PNG } = await import('../helpers/goldens') + return { browserRasterizer: vi.fn(async () => ONE_PX_PNG) } +}) let sheet: SheetIndex let report: Report @@ -60,10 +56,14 @@ describe('the 612 legacy leaves in the application', () => { } }) - it('keeps every finding, resolved or not, through a v3 PDF export and import', async () => { - const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' }) + it('keeps every finding, resolved or not, through an archive PDF export and import', async () => { + const { pdf: bytes } = await exportReportToPdf(report, sheet, { + locale: 'fr', + }) const back = await importReportFromPdf(bytes, sheet.sheet.migrationMap) expect(back.migrated).toBe(false) + expect(back.origin).toBe('envelope_v1') + expect(back.archive).not.toBeNull() expect(back.report).toEqual(report) const again = back.report.observations.flatMap((o) => o.findings) expect(again.filter((f) => f.unresolved)).toHaveLength(29) diff --git a/apps/app/tests/unit/pdf.attachment.inflate.test.ts b/apps/app/tests/unit/pdf.attachment.inflate.test.ts deleted file mode 100644 index ae0781ad..00000000 --- a/apps/app/tests/unit/pdf.attachment.inflate.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, it, expect } from 'vitest' -import { inflateFlate } from '@/pdf/attachment' - -async function deflate(data: Uint8Array): Promise<Uint8Array> { - const stream = new Blob([data as BlobPart]) - .stream() - .pipeThrough(new CompressionStream('deflate')) - return new Uint8Array(await new Response(stream).arrayBuffer()) -} - -describe('inflateFlate decompression cap', () => { - it('inflates a normal-size payload', async () => { - const payload = new TextEncoder().encode( - JSON.stringify({ version: 2, hello: 'world' }), - ) - const out = await inflateFlate(await deflate(payload)) - expect(out).not.toBeNull() - expect(new TextDecoder().decode(out!)).toContain('hello') - }) - - it('returns null for a decompression bomb above the cap', async () => { - // 24 MB of zeros deflates to a few KB but inflates past the 16 MB cap - const bomb = await deflate(new Uint8Array(24 * 1024 * 1024)) - expect(bomb.byteLength).toBeLessThan(1024 * 1024) - const out = await inflateFlate(bomb) - expect(out).toBeNull() - }) -}) diff --git a/apps/app/tests/unit/pdf.attachment.test.ts b/apps/app/tests/unit/pdf.attachment.test.ts deleted file mode 100644 index 9ccbb2c3..00000000 --- a/apps/app/tests/unit/pdf.attachment.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { describe, it, expect, beforeAll } from 'vitest' -import { PDFDocument } from 'pdf-lib' -import { attachReportJson, extractReportJson } from '@/pdf/attachment' -import type { SheetIndex } from '@/services/sheetIndex' -import { loadTestSheet, minimalReport } from '../helpers/sheet' - -let sheet: SheetIndex -beforeAll(async () => { - sheet = await loadTestSheet() -}) - -describe('PDF attachment roundtrip', () => { - it('attaches and extracts the v3 report JSON', async () => { - const doc = await PDFDocument.create() - doc.addPage() - await attachReportJson( - doc, - minimalReport(sheet, { conclusion: 'tout va bien' }), - ) - const bytes = await doc.save() - - const reopened = await PDFDocument.load(bytes) - const out = await extractReportJson(reopened, sheet.sheet.migrationMap) - expect(out.report.conclusion).toBe('tout va bien') - expect(out.report.animal.name).toBe('Mistral') - expect(out.report.version).toBe(3) - expect(out.migrated).toBe(false) - }) - - it('throws on PDFs without the attachment', async () => { - const doc = await PDFDocument.create() - doc.addPage() - const bytes = await doc.save() - const reopened = await PDFDocument.load(bytes) - await expect( - extractReportJson(reopened, sheet.sheet.migrationMap), - ).rejects.toThrow() - }) -}) - -describe('size caps', () => { - it('refuses an oversized PDF before parsing it', async () => { - const { importReportFromPdf, ImportError, MAX_PDF_BYTES } = - await import('@/pdf/import') - const huge = new Uint8Array(MAX_PDF_BYTES + 1) - await expect( - importReportFromPdf(huge, sheet.sheet.migrationMap), - ).rejects.toBeInstanceOf(ImportError) - }) -}) diff --git a/apps/app/tests/unit/pdf.browserRasterizer.test.ts b/apps/app/tests/unit/pdf.browserRasterizer.test.ts new file mode 100644 index 00000000..800c267c --- /dev/null +++ b/apps/app/tests/unit/pdf.browserRasterizer.test.ts @@ -0,0 +1,81 @@ +/** + * Replaces pdf.svgToPng.test.ts: the browser rasterizer adapter stamps the + * engine's size on the SVG root, draws through Image/canvas and returns PNG + * bytes, with the toDataURL fallback when toBlob yields nothing. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { browserRasterizer } from '@/pdf/browserRasterizer' + +const PNG_BYTES = new Uint8Array([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x00, +]) +const SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>' +const SIZE = { widthPx: 10, heightPx: 6 } + +class MockImage { + decoding: 'sync' | 'async' | 'auto' = 'auto' + crossOrigin: string | null = null + onload: (() => void) | null = null + onerror: ((err?: unknown) => void) | null = null + private _src = '' + get src(): string { + return this._src + } + set src(value: string) { + this._src = value + queueMicrotask(() => this.onload?.()) + } +} + +const blobs: Blob[] = [] + +function mockCanvas(toBlob: (cb: BlobCallback) => void): HTMLCanvasElement { + const canvas = document.createElement('canvas') + canvas.getContext = (() => ({ + fillStyle: '', + fillRect: () => undefined, + drawImage: () => undefined, + })) as unknown as HTMLCanvasElement['getContext'] + canvas.toBlob = toBlob as HTMLCanvasElement['toBlob'] + vi.spyOn(document, 'createElement').mockImplementation(((tag: string) => + tag === 'canvas' + ? canvas + : ({} as HTMLElement)) as typeof document.createElement) + return canvas +} + +describe('browserRasterizer', () => { + beforeEach(() => { + blobs.length = 0 + vi.stubGlobal('Image', MockImage) + vi.stubGlobal('URL', { + createObjectURL: (blob: Blob) => { + blobs.push(blob) + return 'blob:mock' + }, + revokeObjectURL: () => undefined, + }) + }) + + it('returns PNG bytes for a valid SVG, sized by the engine', async () => { + const canvas = mockCanvas((cb) => + cb(new Blob([PNG_BYTES], { type: 'image/png' })), + ) + const out = await browserRasterizer(SVG, SIZE) + expect(out).toBeInstanceOf(Uint8Array) + expect(Array.from(out.slice(0, 4))).toEqual([0x89, 0x50, 0x4e, 0x47]) + expect([canvas.width, canvas.height]).toEqual([10, 6]) + const served = await blobs[0]!.text() + expect(served).toContain('width="10"') + expect(served).toContain('height="6"') + }) + + it('falls back to toDataURL when toBlob returns null', async () => { + const canvas = mockCanvas((cb) => cb(null)) + canvas.toDataURL = () => + 'data:image/png;base64,' + Buffer.from(PNG_BYTES).toString('base64') + const out = await browserRasterizer(SVG, SIZE) + expect(out[0]).toBe(0x89) + expect(out[1]).toBe(0x50) + }) +}) diff --git a/apps/app/tests/unit/pdf.export.app.test.ts b/apps/app/tests/unit/pdf.export.app.test.ts new file mode 100644 index 00000000..e62d4eb3 --- /dev/null +++ b/apps/app/tests/unit/pdf.export.app.test.ts @@ -0,0 +1,209 @@ +/** + * T2 and user scenario 3 (STEP6 §7): the archive the app exports is + * self-sufficient. Once exported, the catalog may change its labels and + * geometry and the deployment may ship other logos: a re-export from the + * envelope alone reproduces the first export, not the current resources. + */ +import { + describe, + it, + expect, + vi, + beforeAll, + afterAll, + afterEach, +} from 'vitest' +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { + buildSheetIndex, + buildSheetSnapshot, + ReportSchema, + type Branding, + type FindingCategory, + type FindingNode, + type Report, + type ReportArchiveEnvelope, +} from '@faunosteo/domain' +import { exportFromEnvelope, readReportArchive } from '@faunosteo/pdf' +import { exportReportToPdf } from '@/pdf/export' +import { browserRasterizer } from '@/pdf/browserRasterizer' +import { loadBranding } from '@/pdf/branding' +import type { LoadedSheet } from '@/sheets/provider' +import type { SheetIndex } from '@/services/sheetIndex' +import { loadTestSheet } from '../helpers/sheet' +import { + FIXTURES_DIR, + ONE_PX_PNG, + readLinks, + recordDrawing, + snapshotViews, + type ImageEntry, + type LinkEntry, + type TextEntry, +} from '../helpers/goldens' + +// Same fixed raster for every view and logo: images then depend on the +// branding and the layout only. +vi.mock('@/pdf/browserRasterizer', async () => { + const { TWO_BY_ONE_PNG } = await import('../helpers/goldens') + return { browserRasterizer: vi.fn(async () => TWO_BY_ONE_PNG) } +}) +// The bundled branding, unless a scenario swaps the deployment's logos. +const branding = vi.hoisted(() => ({ current: null as Branding | null })) +vi.mock('@/pdf/branding', async (importOriginal) => { + const real = await importOriginal<typeof import('@/pdf/branding')>() + return { + loadBranding: vi.fn(async () => branding.current ?? real.loadBranding()), + } +}) + +let sheet: SheetIndex +let demo: Report + +beforeAll(async () => { + sheet = await loadTestSheet() + demo = ReportSchema.parse( + JSON.parse( + readFileSync(resolve(FIXTURES_DIR, 'report-v3.demo.json'), 'utf8'), + ), + ) + vi.spyOn(console, 'warn').mockImplementation(() => undefined) +}) +afterEach(() => { + branding.current = null + vi.unstubAllGlobals() +}) +afterAll(() => vi.restoreAllMocks()) + +interface Facts { + texts: TextEntry[] + images: ImageEntry[] + links: LinkEntry[] +} + +/** Runs an export under the drawing recorder and reads the links back. */ +async function recorded<T extends { pdf: Uint8Array }>( + run: () => Promise<T>, +): Promise<T & Facts> { + const recording = recordDrawing() + try { + const result = await run() + const { texts, images } = recording + return { ...result, texts, images, links: await readLinks(result.pdf) } + } finally { + recording.stop() + } +} + +const facts = ({ texts, images, links }: Facts): Facts => ({ + texts, + images, + links, +}) + +/** The app export path, bundled logos, under the recorder. */ +function appExport(index: SheetIndex): Promise<Facts & { pdf: Uint8Array }> { + return recorded(() => exportReportToPdf(demo, index, { locale: 'fr' })) +} + +async function archiveOf(pdf: Uint8Array): Promise<ReportArchiveEnvelope> { + const outcome = await readReportArchive(pdf, sheet.sheet.migrationMap) + expect(outcome.origin).toBe('envelope_v1') + return outcome.archive! +} + +const REEXPORT = { + locale: 'fr' as const, + rasterizer: browserRasterizer, + exportedAt: new Date('2027-01-01T00:00:00.000Z'), +} + +function renameNodes(nodes: (FindingCategory | FindingNode)[]): void { + for (const node of nodes) { + node.name = { + fr: `${node.name.fr} (révisé)`, + en: `${node.name.en} (revised)`, + } + renameNodes(node.children) + } +} + +/** The catalog after a revision: every label changed, the hip marker moved. */ +function revisedSheet(source: LoadedSheet): LoadedSheet { + const next = structuredClone(source) + for (const a of next.document.annotations) { + if (a.name) { + a.name = { fr: `${a.name.fr} (révisé)`, en: `${a.name.en} (revised)` } + } + if (a.id === 'hip' && a.geometry?.type === 'circle') a.geometry.cx += 100 + } + for (const zone of next.document.finding_zones) { + zone.name = { + fr: `${zone.name.fr} (révisé)`, + en: `${zone.name.en} (revised)`, + } + renameNodes(zone.categories) + } + return next +} + +describe('the archive survives its resources', () => { + it('T2 catalog changed: the envelope re-exports the archived sheet, not the revised one', async () => { + const first = await appExport(sheet) + const archive = await archiveOf(first.pdf) + + // The revision is visible through the app path (labels and geometry)... + const revised = buildSheetIndex(revisedSheet(sheet.sheet)) + const onRevised = await appExport(revised) + expect(onRevised.texts).not.toEqual(first.texts) + const revisedViews = snapshotViews( + buildSheetSnapshot(revised.sheet, demo), + demo, + ) + const archivedViews = snapshotViews(archive.sheetSnapshot, demo) + expect(revisedViews).not.toEqual(archivedViews) + + // ...and absent from a re-export of the envelope alone. + const again = await recorded(() => exportFromEnvelope(archive, REEXPORT)) + expect(again.warnings).toEqual([]) + expect(facts(again)).toEqual(facts(first)) + expect( + snapshotViews(again.envelope.sheetSnapshot, again.envelope.report), + ).toEqual(archivedViews) + }, 60_000) + + it('scenario 3 branding changed: the envelope re-exports the archived branding and never fetches', async () => { + const first = await appExport(sheet) + const archive = await archiveOf(first.pdf) + + // The deployment now ships other logos: a 1×1 PNG everywhere, another partner SVG. + const onePx = { + kind: 'png' as const, + base64: Buffer.from(ONE_PX_PNG).toString('base64'), + } + const otherSvg = + '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect width="10" height="10"/></svg>' + branding.current = { + ...archive.branding, + headerLogo: onePx, + footerLogo: onePx, + poweredBy: { ...archive.branding.poweredBy!, logo: onePx }, + partner: { + ...archive.branding.partner!, + logo: { kind: 'svg', svg: otherSvg }, + }, + } + const current = await loadBranding() + expect(current.headerLogo).not.toBeNull() + expect(current).not.toEqual(archive.branding) + const fetchSpy = vi.fn() + vi.stubGlobal('fetch', fetchSpy) + + const again = await recorded(() => exportFromEnvelope(archive, REEXPORT)) + expect(fetchSpy).not.toHaveBeenCalled() + expect(again.warnings).toEqual([]) + expect(facts(again)).toEqual(facts(first)) + expect(again.envelope.branding).toEqual(archive.branding) + }, 60_000) +}) diff --git a/apps/app/tests/unit/pdf.goldens.test.ts b/apps/app/tests/unit/pdf.goldens.test.ts new file mode 100644 index 00000000..b0952259 --- /dev/null +++ b/apps/app/tests/unit/pdf.goldens.test.ts @@ -0,0 +1,218 @@ +/** + * Step 6 Phase 0 freeze (STEP6_PDF_ARCHIVE_ANALYSIS.md §17) replayed on the + * application export path: `exportReportToPdf` now runs the engine with the + * bundled sheet snapshotted, the bundled branding (mocked to every slot empty + * for the `nologos` mode, the real module for `logos`) and the browser + * rasterizer (mocked to fixed PNGs, as the Phase 0 stub was). Text, + * images and links goldens are asserted as frozen; `MAKE_GOLDEN=1` rewrites + * them, never without a user decision. Never regenerate `report-v3.bare.pdf`: + * it is the Step 5 bare export, an import fixture only. + */ +import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest' +import { PDFDocument } from 'pdf-lib' +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { + buildSheetSnapshot, + readReportDocument, + ReportSchema, + type Report, +} from '@faunosteo/domain' +import { exportReportToPdf } from '@/pdf/export' +import { importReportFromPdf } from '@/pdf/import' +import type { SheetIndex } from '@/services/sheetIndex' +import type { Locale } from '@/i18n/types' +import { loadTestSheet } from '../helpers/sheet' +import { + leavesAsV2Report, + legacyLeaves, + loadLegacyBaseline, +} from '../helpers/legacyLeaves' +import { + checkGolden, + FIXTURES_DIR, + ONE_PX_PNG, + readGolden, + readLinks, + recordDrawing, + snapshotViews, + TWO_BY_ONE_PNG, + type ImageEntry, + type LinkEntry, + type LogoMode, + type TextEntry, + type ViewSnapshot, +} from '../helpers/goldens' + +const raster = vi.hoisted(() => ({ png: new Uint8Array() })) +vi.mock('@/pdf/browserRasterizer', () => ({ + browserRasterizer: vi.fn(async () => raster.png), +})) +const logoMode = vi.hoisted(() => ({ current: 'nologos' as LogoMode })) +vi.mock('@/pdf/branding', async () => { + const { brandingOf } = await import('../helpers/goldens') + return { loadBranding: vi.fn(() => brandingOf(logoMode.current)) } +}) + +const REPORTS = ['v2full', 'demo', 'v2unresolved'] as const +type ReportName = (typeof REPORTS)[number] +const MODES: readonly LogoMode[] = ['nologos', 'logos'] +const BARE_PDF = resolve(FIXTURES_DIR, 'report-v3.bare.pdf') + +const readJson = (name: string): unknown => + JSON.parse(readFileSync(resolve(FIXTURES_DIR, name), 'utf8')) + +let sheet: SheetIndex +let reports: Record<ReportName, Report> +let unresolvedOfV2Unresolved = 0 + +/** sphenoid + ssb (the families the migration cannot place) plus one leaf that resolves. */ +function buildV2Unresolved(): Report { + const leaves = legacyLeaves(loadLegacyBaseline()) + const unresolvedFamilies = leaves.filter( + (l) => l.zoneId === 'sphenoid' || l.zoneId === 'ssb', + ) + const resolved = leaves.find((l) => l.zoneId === 'frontal')! + const outcome = readReportDocument( + leavesAsV2Report([...unresolvedFamilies, resolved]), + sheet.sheet.migrationMap, + ) + unresolvedOfV2Unresolved = outcome.unresolvedFindings + return outcome.report +} + +beforeAll(async () => { + sheet = await loadTestSheet() + reports = { + v2full: readReportDocument( + readJson('report-v2.full.json'), + sheet.sheet.migrationMap, + ).report, + demo: ReportSchema.parse(readJson('report-v3.demo.json')), + v2unresolved: buildV2Unresolved(), + } + vi.spyOn(console, 'warn').mockImplementation(() => undefined) +}) +afterAll(() => vi.restoreAllMocks()) + +interface Exported { + bytes: Uint8Array + texts: TextEntry[] + images: ImageEntry[] + links: LinkEntry[] +} + +async function exportWith( + report: Report, + mode: LogoMode, + locale: Locale, +): Promise<Exported> { + raster.png = mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG + logoMode.current = mode + const recording = recordDrawing() + try { + const { pdf: bytes } = await exportReportToPdf(report, sheet, { locale }) + const { texts, images } = recording + return { bytes, texts, images, links: await readLinks(bytes) } + } finally { + recording.stop() + } +} + +const pagesOf = (entries: readonly { page: number }[]) => + entries.map((e) => e.page) + +describe('golden inputs', () => { + it('the 2×1 PNG decodes as 2×1 and the 1×1 as 1×1', async () => { + const doc = await PDFDocument.create() + const two = await doc.embedPng(TWO_BY_ONE_PNG) + expect([two.width, two.height]).toEqual([2, 1]) + const one = await doc.embedPng(ONE_PX_PNG) + expect([one.width, one.height]).toEqual([1, 1]) + }) + + it('the demo report covers the sheet features the goldens must freeze', () => { + const { demo } = reports + expect(demo.observations).toHaveLength(6) + const zones = demo.observations.flatMap((o) => o.zones) + const findings = demo.observations.flatMap((o) => o.findings) + expect(zones.some((z) => z.viewId === 'head')).toBe(true) + expect(zones.some((z) => z.vertebrae?.length)).toBe(true) + expect( + zones.filter((z) => z.annotationId === 'hip').map((z) => z.side), + ).toEqual(['left', 'right']) + expect(findings.some((f) => f.requiresVetReferral)).toBe(true) + expect(findings.some((f) => f.labelFrSnapshot.includes('–'))).toBe(true) + expect(demo.observations.some((o) => o.freeTextFindings.length)).toBe(true) + expect(demo.nextAppointment).toBeDefined() + }) + + it('the v2unresolved report really carries unresolved findings', () => { + expect(unresolvedOfV2Unresolved).toBeGreaterThan(0) + const findings = reports.v2unresolved.observations.flatMap( + (o) => o.findings, + ) + expect(findings.filter((f) => f.unresolved)).toHaveLength( + unresolvedOfV2Unresolved, + ) + expect(findings.some((f) => !f.unresolved)).toBe(true) + }) +}) + +describe.each(REPORTS)('goldens of %s', (name) => { + describe.each(MODES)('%s', (mode) => { + // Images and links are recorded per locale too: the footer centres the + // "powered by" block on the label width, so the ZenQuality link (and its + // logo) shift between FR and EN. Only the pagination is locale-free. + it('text, images and links per locale; same pagination across locales', async () => { + const fr = await exportWith(reports[name], mode, 'fr') + const en = await exportWith(reports[name], mode, 'en') + for (const [locale, out] of [ + ['fr', fr], + ['en', en], + ] as const) { + checkGolden(`text.${name}.${locale}.${mode}.json`, out.texts) + checkGolden(`images.${name}.${locale}.${mode}.json`, out.images) + checkGolden(`links.${name}.${locale}.${mode}.json`, out.links) + } + expect(pagesOf(en.images)).toEqual(pagesOf(fr.images)) + expect(pagesOf(en.links)).toEqual(pagesOf(fr.links)) + }, 30_000) + }) + + // Hidden markers are absent in the engine (the browser hid them with + // display="none") and the layer <g> carries no data-* any more: `titles` + // shrinks to the highlighted markers plus the asset's own, and + // `dataAttributes` drops from 2 to 0. Everything else must match. + it('highlighted views: same facts but titles and data attributes', () => { + const snapshot = buildSheetSnapshot(sheet.sheet, reports[name]) + const actual = snapshotViews(snapshot, reports[name]) + const expected = readGolden<ViewSnapshot[]>(`views.${name}.json`) + const comparable = (v: ViewSnapshot) => ({ + observationId: v.observationId, + viewId: v.viewId, + viewBox: v.viewBox, + halo: v.halo, + highlighted: v.highlighted, + nonHighlightedVisible: v.nonHighlightedVisible, + }) + expect(actual.map(comparable)).toEqual(expected.map(comparable)) + for (const view of actual) { + expect(view.dataAttributes).toBe(0) + expect(view.titles).toBeGreaterThanOrEqual(view.highlighted.length) + } + for (const view of expected) expect(view.dataAttributes).toBe(2) + }) +}) + +describe('report-v3.bare.pdf', () => { + it('is the demo report exported bare by Step 5 and imports with no archive', async () => { + const bytes = new Uint8Array(readFileSync(BARE_PDF)) + const outcome = await importReportFromPdf(bytes, sheet.sheet.migrationMap) + expect(outcome.origin).toBe('bare_v3') + expect(outcome.migrated).toBe(false) + expect(outcome.archive).toBeNull() + expect(outcome.snapshotRejected).toBeUndefined() + expect(outcome.report).toEqual(reports.demo) + }) +}) diff --git a/apps/app/tests/unit/pdf.import.test.ts b/apps/app/tests/unit/pdf.import.test.ts new file mode 100644 index 00000000..fa8c0b37 --- /dev/null +++ b/apps/app/tests/unit/pdf.import.test.ts @@ -0,0 +1,48 @@ +/** + * Replaces pdf.attachment.test.ts and pdf.attachment.inflate.test.ts on the + * engine read API: the typed ImportError kinds the home route maps. The + * attachment roundtrip moved to pdf.roundtrip.test.ts ("attaches the + * envelope and roundtrips") and the engine's tests/read.test.ts (T4); the + * inflate bomb cap lives in the engine's tests/security.test.ts. + */ +import { describe, it, expect, beforeAll } from 'vitest' +import { PDFDocument } from 'pdf-lib' +import { importReportFromPdf, ImportError, MAX_PDF_BYTES } from '@/pdf/import' +import type { SheetIndex } from '@/services/sheetIndex' +import { loadTestSheet } from '../helpers/sheet' + +let sheet: SheetIndex +beforeAll(async () => { + sheet = await loadTestSheet() +}) + +/** Saved like the export (no object streams, BLK-009) so the keyword stamp is in clear. */ +async function pdfWithoutAttachment(keywords?: string[]): Promise<Uint8Array> { + const doc = await PDFDocument.create() + doc.addPage() + if (keywords) doc.setKeywords(keywords) + return doc.save({ useObjectStreams: false }) +} + +async function rejectsWith(bytes: Uint8Array, kind: string): Promise<void> { + const promise = importReportFromPdf(bytes, sheet.sheet.migrationMap) + await expect(promise).rejects.toBeInstanceOf(ImportError) + await expect(promise).rejects.toMatchObject({ kind }) +} + +describe('importReportFromPdf error kinds', () => { + it('no_attachment for a PDF without the attachment', async () => { + await rejectsWith(await pdfWithoutAttachment(), 'no_attachment') + }) + + it('attachment_stripped for a stamped archive whose attachment was removed', async () => { + await rejectsWith( + await pdfWithoutAttachment(['faunosteo-archive/1']), + 'attachment_stripped', + ) + }) + + it('invalid_pdf for an oversized file, before parsing it', async () => { + await rejectsWith(new Uint8Array(MAX_PDF_BYTES + 1), 'invalid_pdf') + }) +}) diff --git a/apps/app/tests/unit/pdf.roundtrip.test.ts b/apps/app/tests/unit/pdf.roundtrip.test.ts index dcd89c47..04afe9f5 100644 --- a/apps/app/tests/unit/pdf.roundtrip.test.ts +++ b/apps/app/tests/unit/pdf.roundtrip.test.ts @@ -1,8 +1,8 @@ /** - * Replaces char.pdfFull / pdf.roundtrip / pdf.zoneLabels: the v3 pipeline on - * the bundled sheet (drawn strings from the document, attachment v3, - * roundtrip FR/EN) and the import of the frozen v2 archive PDFs, migrated - * without silent loss. + * Replaces char.pdfFull / pdf.roundtrip / pdf.zoneLabels: the application + * export path on the engine with the bundled sheet (drawn strings from the + * document, envelope attachment, roundtrip FR/EN) and the import of the + * frozen v2 archive PDFs, migrated without silent loss. */ import { describe, @@ -17,25 +17,32 @@ import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib' import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { dirname, resolve } from 'node:path' -import type { Observation } from '@faunosteo/domain' +import { + buildSheetSnapshot, + type Observation, + type Report, +} from '@faunosteo/domain' +import { composeHighlightedViewSvg, defaultPdfLabels } from '@faunosteo/pdf' import { exportReportToPdf } from '@/pdf/export' import { importReportFromPdf, ImportError } from '@/pdf/import' -import { highlightedViewSvg } from '@/pdf/render/observationPage' -import { fr } from '@/i18n/fr' -import { en } from '@/i18n/en' import { formatDate } from '@/lib/dates' +import type { Locale } from '@/i18n/types' import type { SheetIndex } from '@/services/sheetIndex' import { loadTestSheet, minimalReport } from '../helpers/sheet' -const ONE_PX_PNG = Uint8Array.from( - Buffer.from( - 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', - 'base64', - ), -) -vi.mock('@/pdf/render/svgToPng', () => ({ - rasterizeSvg: vi.fn(async () => ONE_PX_PNG), -})) +// The factory runs when the engine first loads the adapter: fixed 1×1 PNG. +vi.mock('@/pdf/browserRasterizer', async () => { + const { ONE_PX_PNG } = await import('../helpers/goldens') + return { browserRasterizer: vi.fn(async () => ONE_PX_PNG) } +}) + +/** The static PDF strings now belong to the engine's label set. */ +const { fr, en } = defaultPdfLabels + +/** The bytes of an app export (its warnings are not under test here). */ +async function exportPdf(report: Report, locale: Locale): Promise<Uint8Array> { + return (await exportReportToPdf(report, sheet, { locale })).pdf +} const HERE = dirname(fileURLToPath(import.meta.url)) const fixture = (name: string) => @@ -43,23 +50,14 @@ const fixture = (name: string) => let sheet: SheetIndex let drawn: string[] = [] -const fetched: string[] = [] -const realFetch = globalThis.fetch beforeAll(async () => { sheet = await loadTestSheet() - globalThis.fetch = (async (input: RequestInfo | URL) => { - fetched.push(String(input)) - return new Response('not found', { status: 404 }) - }) as typeof fetch vi.spyOn(console, 'warn').mockImplementation(() => undefined) }) -afterAll(() => { - globalThis.fetch = realFetch -}) +afterAll(() => vi.restoreAllMocks()) beforeEach(() => { drawn = [] - fetched.length = 0 vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function ( this: PDFPage, text: string, @@ -121,7 +119,7 @@ describe('export on a full v3 report (FR)', () => { observations: [fullObservation()], conclusion: 'ok', }) - const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' }) + const bytes = await exportPdf(report, 'fr') const doc = await PDFDocument.load(bytes) expect(doc.getPageCount()).toBe(2) const zonesIdx = drawn.indexOf(fr['pdf.section.zones']!) @@ -145,24 +143,34 @@ describe('export on a full v3 report (FR)', () => { ) }) - it('attaches v3 and roundtrips in both locales', async () => { + it('attaches the envelope and roundtrips in both locales', async () => { const report = minimalReport(sheet, { observations: [fullObservation()] }) for (const locale of ['fr', 'en'] as const) { - const bytes = await exportReportToPdf(report, sheet, { locale }) + const bytes = await exportPdf(report, locale) const out = await importReportFromPdf(bytes, sheet.sheet.migrationMap) expect(out.migrated).toBe(false) + expect(out.origin).toBe('envelope_v1') expect(out.report).toEqual(report) + expect(out.archive?.locale).toBe(locale) + expect(out.archive?.sheetSnapshot.ref.documentSha256).toBe( + sheet.sheet.ref.documentSha256, + ) } }) - it('highlights the observation zones of a view and hides the other markers', () => { - const svg = highlightedViewSvg(sheet, 'main', fullObservation()) + // The engine draws only the observation's markers (the browser pipeline + // hid the others with display="none"); the view facts are frozen in + // pdf.goldens.test.ts "highlighted views". + it('highlights the observation zones of a view and omits the other markers', () => { + const report = minimalReport(sheet, { observations: [fullObservation()] }) + const snapshot = buildSheetSnapshot(sheet.sheet, report) + const svg = composeHighlightedViewSvg(snapshot, 'main', fullObservation()) expect(svg).toContain('viewBox="0 0 2073.4 1629.4"') expect(svg).toContain('fill="#b85a3f"') expect(svg).toContain('url(#osteo-halo)') - expect(svg).toContain('display="none"') + expect(svg).not.toContain('display="none"') expect(svg).not.toContain('data-anno-id') - const head = highlightedViewSvg(sheet, 'head', fullObservation()) + const head = composeHighlightedViewSvg(snapshot, 'head', fullObservation()) expect(head).toContain('viewBox="60 100 500 380"') expect(head).not.toContain('osteo-halo') }) @@ -235,7 +243,7 @@ describe('PDF content on a two-observation report', () => { it('draws free findings, comments, the conclusion page and the header on every page', async () => { const report = fullReport() - const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' }) + const bytes = await exportPdf(report, 'fr') const pages = (await PDFDocument.load(bytes)).getPageCount() expect(drawn).toContain(fr['pdf.section.free_findings']) expect(joined()).toContain('Sensibilité au garrot') @@ -252,25 +260,37 @@ describe('PDF content on a two-observation report', () => { expect(header).toBeGreaterThanOrEqual(pages) }) - it('sets the PDF metadata', async () => { - const bytes = await exportReportToPdf(fullReport(), sheet, { locale: 'fr' }) + it('sets the PDF metadata and the archive keyword', async () => { + const bytes = await exportPdf(fullReport(), 'fr') const doc = await PDFDocument.load(bytes) expect(doc.getTitle()).toBe(`${fr['pdf.title.suffix.bilan']}Mistral`) expect(doc.getAuthor()).toBe('Dr. Dupont') expect(doc.getSubject()).toBe(fr['pdf.subject']) + expect(doc.getKeywords()).toContain('faunosteo-archive/1') }) - it('fetches the logos at export time', async () => { - await exportReportToPdf(fullReport(), sheet, { locale: 'fr' }) - expect( - fetched.some( - (u) => u.endsWith('.png') || u.endsWith('Paws_in_harmony.svg'), - ), - ).toBe(true) + it('embeds the four bundled logos without any network request', async () => { + const fetchSpy = vi.fn() + vi.stubGlobal('fetch', fetchSpy) + try { + const { pdf, warnings } = await exportReportToPdf(fullReport(), sheet, { + locale: 'fr', + }) + expect(fetchSpy).not.toHaveBeenCalled() + expect(warnings).toEqual([]) + const out = await importReportFromPdf(pdf, sheet.sheet.migrationMap) + const branding = out.archive!.branding + expect(branding.headerLogo?.kind).toBe('png') + expect(branding.footerLogo?.kind).toBe('png') + expect(branding.poweredBy?.logo?.kind).toBe('png') + expect(branding.partner?.logo?.kind).toBe('svg') + } finally { + vi.unstubAllGlobals() + } }) - it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, "Faunosteo state v3"', async () => { - const bytes = await exportReportToPdf(fullReport(), sheet, { locale: 'fr' }) + it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, "Faunosteo report archive v1"', async () => { + const bytes = await exportPdf(fullReport(), 'fr') const doc = await PDFDocument.load(bytes) const objects = [...doc.context.enumerateIndirectObjects()].map(([, o]) => String(o), @@ -282,7 +302,7 @@ describe('PDF content on a two-observation report', () => { [...text] .map((c) => c.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0')) .join('') - expect(filespec).toContain(utf16('Faunosteo state v3')) + expect(filespec).toContain(utf16('Faunosteo report archive v1')) const embedded = objects.find((o) => o.includes('/Type /EmbeddedFile'))! expect(embedded).toContain('/Filter /FlateDecode') }) @@ -360,11 +380,12 @@ describe('import of the frozen v2 archive PDFs', () => { ) // Re-export and re-import: stable. const again = await importReportFromPdf( - await exportReportToPdf(report, sheet, { locale: 'fr' }), + await exportPdf(report, 'fr'), sheet.sheet.migrationMap, ) expect(again.report).toEqual(report) expect(again.migrated).toBe(false) + expect(again.origin).toBe('envelope_v1') }) it('keeps a v2 finding whose node was removed and a zone whose id is unknown, both flagged', async () => { @@ -431,7 +452,7 @@ describe('import of the frozen v2 archive PDFs', () => { expect(out.unresolvedZones).toBe(1) // The migrated document is a valid v3 document: exporting it again keeps the flags. const again = await importReportFromPdf( - await exportReportToPdf(out.report, sheet, { locale: 'en' }), + await exportPdf(out.report, 'en'), sheet.sheet.migrationMap, ) expect(again.report.observations[0]!.findings[0]!.unresolved).toBe(true) diff --git a/apps/app/tests/unit/pdf.svgToPng.test.ts b/apps/app/tests/unit/pdf.svgToPng.test.ts deleted file mode 100644 index d96850ad..00000000 --- a/apps/app/tests/unit/pdf.svgToPng.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' -import { rasterizeSvg } from '@/pdf/render/svgToPng' - -const PNG_BYTES = new Uint8Array([ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x00, -]) - -class MockImage { - decoding: 'sync' | 'async' | 'auto' = 'auto' - crossOrigin: string | null = null - onload: (() => void) | null = null - onerror: ((err?: unknown) => void) | null = null - private _src = '' - get src(): string { - return this._src - } - set src(value: string) { - this._src = value - queueMicrotask(() => this.onload?.()) - } -} - -describe('rasterizeSvg', () => { - beforeEach(() => { - vi.stubGlobal('Image', MockImage) - vi.stubGlobal('URL', { - createObjectURL: () => 'blob:mock', - revokeObjectURL: () => undefined, - }) - }) - - it('returns PNG bytes for a valid SVG', async () => { - const canvas = document.createElement('canvas') - canvas.getContext = (() => ({ - fillStyle: '', - fillRect: () => undefined, - drawImage: () => undefined, - })) as unknown as HTMLCanvasElement['getContext'] - canvas.toBlob = ((cb: BlobCallback) => { - cb(new Blob([PNG_BYTES], { type: 'image/png' })) - }) as HTMLCanvasElement['toBlob'] - vi.spyOn(document, 'createElement').mockImplementation(((tag: string) => - tag === 'canvas' - ? canvas - : ({} as HTMLElement)) as typeof document.createElement) - - const out = await rasterizeSvg( - '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>', - ) - expect(out).toBeInstanceOf(Uint8Array) - expect(out[0]).toBe(0x89) - expect(out[1]).toBe(0x50) - expect(out[2]).toBe(0x4e) - expect(out[3]).toBe(0x47) - }) - - it('falls back to toDataURL when toBlob returns null', async () => { - const canvas = document.createElement('canvas') - canvas.getContext = (() => ({ - fillStyle: '', - fillRect: () => undefined, - drawImage: () => undefined, - })) as unknown as HTMLCanvasElement['getContext'] - canvas.toBlob = ((cb: BlobCallback) => { - cb(null) - }) as HTMLCanvasElement['toBlob'] - canvas.toDataURL = () => - 'data:image/png;base64,' + Buffer.from(PNG_BYTES).toString('base64') - vi.spyOn(document, 'createElement').mockImplementation(((tag: string) => - tag === 'canvas' - ? canvas - : ({} as HTMLElement)) as typeof document.createElement) - - const out = await rasterizeSvg( - '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>', - ) - expect(out[0]).toBe(0x89) - expect(out[1]).toBe(0x50) - }) -}) diff --git a/apps/app/tests/unit/routes.EditorRoute.export.test.tsx b/apps/app/tests/unit/routes.EditorRoute.export.test.tsx new file mode 100644 index 00000000..24a1e274 --- /dev/null +++ b/apps/app/tests/unit/routes.EditorRoute.export.test.tsx @@ -0,0 +1,136 @@ +/** + * Step 6 Phase 0 characterisation of the export flow on the editor route, + * with `exportReportToPdf` mocked: the call shape (store report, loaded + * index, locale), the download name, the failure alert and the alert that + * names what the exported PDF lacks when the engine warned. + */ +import { + describe, + it, + expect, + vi, + beforeAll, + beforeEach, + afterEach, +} from 'vitest' +import { cleanup, 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 { exportReportToPdf } from '@/pdf/export' +import { useReportStore } from '@/state/reportStore' +import { useLocaleStore } from '@/state/localeStore' +import { fr } from '@/i18n/fr' +import { en } from '@/i18n/en' +import type { SheetIndex } from '@/services/sheetIndex' +import { loadTestSheet, minimalReport } from '../helpers/sheet' + +vi.mock('@/pdf/export', () => ({ exportReportToPdf: vi.fn() })) +const exportMock = vi.mocked(exportReportToPdf) +const PDF_BYTES = new Uint8Array([37, 80, 68, 70]) + +let sheet: SheetIndex +const downloads: string[] = [] +const realCreateObjectURL = URL.createObjectURL +const realRevokeObjectURL = URL.revokeObjectURL + +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 + useReportStore.setState({ report: null, activeObservationIndex: 0 }) + useReportStore.getState().hydrateReport(minimalReport(sheet)) + exportMock.mockReset() + downloads.length = 0 + URL.createObjectURL = vi.fn(() => 'blob:faunosteo-test') + URL.revokeObjectURL = vi.fn() + vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function ( + this: HTMLAnchorElement, + ) { + downloads.push(this.download) + }) + vi.stubGlobal('alert', vi.fn()) +}) +afterEach(() => { + cleanup() + vi.restoreAllMocks() + vi.unstubAllGlobals() + URL.createObjectURL = realCreateObjectURL + URL.revokeObjectURL = realRevokeObjectURL +}) + +async function mountAndExport(label: string): Promise<void> { + render( + <MemoryRouter initialEntries={['/editor']}> + <EditorRoute /> + </MemoryRouter>, + ) + const button = await screen.findByRole('button', { name: label }) + await userEvent.setup().click(button) +} + +describe('EditorRoute export', () => { + it('calls exportReportToPdf with the store report, the loaded index and the FR locale', async () => { + exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] }) + await mountAndExport(fr['editor.export']!) + await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1)) + const [report, index, options] = exportMock.mock.calls[0]! + expect(report).toBe(useReportStore.getState().report) + expect(index).toBe(sheet) + expect(options).toEqual({ locale: 'fr' }) + }) + + it('passes the active locale (EN)', async () => { + useLocaleStore.setState({ locale: 'en' }) + exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] }) + await mountAndExport(en['editor.export']!) + await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1)) + expect(exportMock.mock.calls[0]![2]).toEqual({ locale: 'en' }) + }) + + it('downloads bilan-<animal>-<date>.pdf through a blob URL it then revokes', async () => { + exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] }) + await mountAndExport(fr['editor.export']!) + await waitFor(() => expect(downloads).toHaveLength(1)) + expect(downloads[0]).toBe('bilan-Mistral-2026-10-10.pdf') + expect(URL.createObjectURL).toHaveBeenCalledTimes(1) + const blob = vi.mocked(URL.createObjectURL).mock.calls[0]![0] as Blob + expect(blob.type).toBe('application/pdf') + expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:faunosteo-test') + expect(window.alert).not.toHaveBeenCalled() + }) + + it('downloads then alerts editor.export_warnings naming the failed logo slots and views', async () => { + exportMock.mockResolvedValue({ + pdf: PDF_BYTES, + warnings: [ + { kind: 'logo_failed', slot: 'headerLogo' }, + { kind: 'view_raster_failed', observationId: 'obs-1', viewId: 'head' }, + ], + }) + await mountAndExport(fr['editor.export']!) + await waitFor(() => expect(window.alert).toHaveBeenCalledTimes(1)) + expect(downloads).toEqual(['bilan-Mistral-2026-10-10.pdf']) + expect(window.alert).toHaveBeenCalledWith( + 'PDF exporté avec des éléments manquants : headerLogo, head. Vérifiez la console du navigateur.', + ) + }) + + it('alerts editor.export_failed when the export rejects', async () => { + vi.spyOn(console, 'error').mockImplementation(() => undefined) + exportMock.mockRejectedValue(new Error('render exploded')) + await mountAndExport(fr['editor.export']!) + await waitFor(() => expect(window.alert).toHaveBeenCalledTimes(1)) + expect(window.alert).toHaveBeenCalledWith(fr['editor.export_failed']) + expect(downloads).toHaveLength(0) + await waitFor(() => + expect( + screen.getByRole('button', { name: fr['editor.export'] }), + ).toBeEnabled(), + ) + }) +}) diff --git a/apps/app/tests/unit/routes.EditorRoute.test.tsx b/apps/app/tests/unit/routes.EditorRoute.test.tsx index ba040887..2ec67c54 100644 --- a/apps/app/tests/unit/routes.EditorRoute.test.tsx +++ b/apps/app/tests/unit/routes.EditorRoute.test.tsx @@ -1,7 +1,8 @@ /** * The editor route on the bundled sheet: the click chain end to end (DOM * click on a generated marker → service → store), the detail view by its - * localized name, the sheet status line, the disclaimer once per session. + * localized name, the sheet status line, the disclaimer once per session, + * the draft restore (silent on the same sheet, one alert after a rebase). */ import { describe, @@ -40,6 +41,7 @@ beforeEach(() => { sessionStorage.clear() sessionStorage.setItem(DISCLAIMER_FLAG, '1') window.scrollTo = vi.fn() as unknown as typeof window.scrollTo + vi.stubGlobal('alert', vi.fn()) useReportStore.setState({ report: null, activeObservationIndex: 0 }) useReportStore.getState().hydrateReport( minimalReport(sheet, { @@ -58,6 +60,7 @@ beforeEach(() => { afterEach(() => { cleanup() vi.restoreAllMocks() + vi.unstubAllGlobals() }) const zonesOf = (i = 0) => @@ -199,7 +202,7 @@ describe('EditorRoute on the canonical sheet', () => { expect(sessionStorage.getItem(DISCLAIMER_FLAG)).toBe('1') }) - it('restores the per-tab draft when the store is empty, migrating a v2 one', async () => { + it('restores the per-tab draft when the store is empty, silently on the same sheet', async () => { const report = useReportStore.getState().report! useReportStore.setState({ report: null }) sessionStorage.setItem( @@ -208,5 +211,40 @@ describe('EditorRoute on the canonical sheet', () => { ) await mount() expect(useReportStore.getState().report?.id).toBe(report.id) + expect(window.alert).not.toHaveBeenCalled() + }) + + it('a draft from another sheet is rebased, its lost zone flagged, and announced once with the count', async () => { + const report = useReportStore.getState().report! + useReportStore.setState({ report: null }) + const foreign = { + ...report, + sheet: { ...report.sheet, documentSha256: '0'.repeat(64) }, + observations: [ + { + ...report.observations[0]!, + zones: [ + { + annotationId: 'ghost-zone', + viewId: 'main', + labelFrSnapshot: 'Zone disparue', + labelEnSnapshot: 'Vanished zone', + }, + ], + }, + ], + } + sessionStorage.setItem('osteo:draft', JSON.stringify(foreign)) + await mount() + const restored = useReportStore.getState().report! + expect(restored.sheet).toEqual(sheet.sheet.ref) + expect(restored.observations[0]!.zones[0]).toMatchObject({ + annotationId: 'ghost-zone', + unresolved: true, + }) + expect(window.alert).toHaveBeenCalledTimes(1) + expect(window.alert).toHaveBeenCalledWith( + fr['editor.draft_rebased'].replace('{count}', '1'), + ) }) }) diff --git a/apps/app/tests/unit/routes.HomeRoute.archive.test.tsx b/apps/app/tests/unit/routes.HomeRoute.archive.test.tsx new file mode 100644 index 00000000..7852927e --- /dev/null +++ b/apps/app/tests/unit/routes.HomeRoute.archive.test.tsx @@ -0,0 +1,269 @@ +/** + * T15 (STEP6 §7, §16): the home route on Step 6 archives, with + * `importReportFromPdf` mocked. Every alert opens with a headline: complete + * restoration or partial recovery. Same sheet: archive kept in the store and + * mirrored, complete + archive_ok. Other sheet: the report is rebased on the + * loaded sheet (unresolved flags, labels from the archived snapshot, sheet + * ref updated) and the alert says degraded with the count; a rebase that + * resolved everything stays complete. Snapshot rejected: degraded with the + * reason label. Attachment stripped: its error message. + */ +import { + describe, + it, + expect, + vi, + beforeAll, + beforeEach, + afterEach, +} from 'vitest' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { MemoryRouter, Route, Routes } from 'react-router-dom' +import type { + Annotation, + ArchiveReadOutcome, + Report, + ReportArchiveEnvelope, +} from '@faunosteo/domain' +import HomeRoute from '@/app/routes/HomeRoute' +import { ImportError, importReportFromPdf } from '@/pdf/import' +import { useReportStore } from '@/state/reportStore' +import { ARCHIVE_KEY } from '@/state/persistence' +import { useLocaleStore } from '@/state/localeStore' +import { fr } from '@/i18n/fr' +import type { SheetIndex } from '@/services/sheetIndex' +import { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet' + +vi.mock('@/pdf/import', async (importOriginal) => ({ + ...(await importOriginal<typeof import('@/pdf/import')>()), + importReportFromPdf: vi.fn(), +})) +const importMock = vi.mocked(importReportFromPdf) + +let sheet: SheetIndex + +beforeAll(async () => { + sheet = await loadTestSheet() +}) +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + sessionStorage.clear() + useReportStore.setState({ + report: null, + archive: null, + activeObservationIndex: 0, + }) + vi.stubGlobal('alert', vi.fn()) + importMock.mockReset() +}) +afterEach(() => { + cleanup() + vi.unstubAllGlobals() +}) + +const OTHER_SHA = 'b'.repeat(64) + +/** An outcome carrying a kept envelope (v3, nothing migrated). */ +function archived( + report: Report, + archive: ReportArchiveEnvelope | null, + patch: Partial<ArchiveReadOutcome> = {}, +): ArchiveReadOutcome { + return { + report, + origin: 'envelope_v1', + migrated: false, + unresolvedZones: 0, + unresolvedFindings: 0, + archive, + ...patch, + } +} + +function reportWithHip(): Report { + return minimalReport(sheet, { + observations: [ + { + id: 'o1', + zones: [{ annotationId: 'hip', viewId: 'main', side: 'left' }], + findings: [], + freeTextFindings: [], + comment: '', + }, + ], + }) +} + +/** + * A report written on another revision of the sheet: a zone and a finding + * path the loaded sheet does not hold, next to a zone it does. Its archived + * snapshot names the lost zone so the rebase can fill the label. + */ +function staleReportAndArchive(): { + report: Report + archive: ReportArchiveEnvelope +} { + const report = minimalReport(sheet, { + sheet: { ...sheet.sheet.ref, documentSha256: OTHER_SHA }, + observations: [ + { + id: 'o-stale', + zones: [ + { annotationId: 'point-gone', viewId: 'main' }, + { annotationId: 'hip', viewId: 'main', side: 'left' }, + ], + findings: [ + { + findingZoneId: 'hip', + path: ['hip-dysfunctions', 'gone'], + labelFrSnapshot: 'Constat disparu', + labelEnSnapshot: 'Gone finding', + }, + ], + freeTextFindings: [], + comment: '', + }, + ], + }) + const archive = archiveEnvelope(sheet, report) + archive.sheetSnapshot.ref.documentSha256 = OTHER_SHA + const gone: Annotation = { + ...sheet.annotation('hip')!, + id: 'point-gone', + name: { fr: 'Point disparu', en: 'Gone point' }, + } as Annotation + archive.sheetSnapshot.document.annotations.push(gone) + return { report, archive } +} + +async function mountAndPickPdf(): Promise<void> { + 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()) + const input = document.querySelector('input[type="file"]')! + const file = new File([new Uint8Array([37, 80, 68, 70])], 'bilan.pdf', { + type: 'application/pdf', + }) + fireEvent.change(input, { target: { files: [file] } }) +} + +const alertMock = () => vi.mocked(window.alert) +/** The alert split on its blank lines: headline first, then the detail lines. */ +const alertLines = () => + (alertMock().mock.calls[0]![0] as string).split('\n\n') +const errorText = () => screen.queryByText(/./, { selector: 'p.text-red-700' }) + +describe('HomeRoute import of a Step 6 archive', () => { + it('same sheet: keeps the archive in the store and its mirror, alerts archive_ok, no rebase', async () => { + const report = reportWithHip() + const archive = archiveEnvelope(sheet, report) + importMock.mockResolvedValue(archived(report, archive)) + await mountAndPickPdf() + await screen.findByTestId('editor-route') + const state = useReportStore.getState() + expect(state.report).toEqual(report) + expect(state.archive).toEqual(archive) + expect(JSON.parse(sessionStorage.getItem(ARCHIVE_KEY)!).report.id).toBe( + report.id, + ) + expect(alertMock()).toHaveBeenCalledTimes(1) + expect(alertLines()).toEqual([ + fr['home.import.complete'], + fr['home.import.archive_ok'], + ]) + }) + + it('other sheet: rebases onto the loaded sheet, labels from the archived snapshot, alert with the count', async () => { + const { report, archive } = staleReportAndArchive() + importMock.mockResolvedValue(archived(report, archive)) + await mountAndPickPdf() + await screen.findByTestId('editor-route') + const opened = useReportStore.getState().report! + expect(opened.sheet).toEqual(sheet.sheet.ref) + const [gone, hip] = opened.observations[0]!.zones + expect(gone).toMatchObject({ + unresolved: true, + labelFrSnapshot: 'Point disparu', + labelEnSnapshot: 'Gone point', + }) + expect(hip!.unresolved).toBeUndefined() + expect(opened.observations[0]!.findings[0]).toMatchObject({ + unresolved: true, + labelFrSnapshot: 'Constat disparu', + }) + // The archive stays as exported, never rebased. + expect(useReportStore.getState().archive).toEqual(archive) + expect(alertMock()).toHaveBeenCalledTimes(1) + expect(alertLines()).toEqual([ + fr['home.import.degraded'], + fr['home.import.archive_ok'], + fr['home.import.rebased']!.replace('{count}', '2'), + ]) + }) + + it('other sheet, everything resolved: complete headline, the rebased line says 0', async () => { + const report = minimalReport(sheet, { + sheet: { ...sheet.sheet.ref, documentSha256: OTHER_SHA }, + observations: reportWithHip().observations, + }) + const archive = archiveEnvelope(sheet, report) + archive.sheetSnapshot.ref.documentSha256 = OTHER_SHA + importMock.mockResolvedValue(archived(report, archive)) + await mountAndPickPdf() + await screen.findByTestId('editor-route') + const opened = useReportStore.getState().report! + expect(opened.sheet).toEqual(sheet.sheet.ref) + expect(opened.observations[0]!.zones[0]!.unresolved).toBeUndefined() + expect(alertMock()).toHaveBeenCalledTimes(1) + expect(alertLines()).toEqual([ + fr['home.import.complete'], + fr['home.import.archive_ok'], + fr['home.import.rebased']!.replace('{count}', '0'), + ]) + }) + + it('snapshot rejected: the report opens, the alert names the reason, no archive kept', async () => { + const report = reportWithHip() + importMock.mockResolvedValue( + archived(report, null, { snapshotRejected: 'caps' }), + ) + await mountAndPickPdf() + await screen.findByTestId('editor-route') + expect(useReportStore.getState().report).toEqual(report) + expect(useReportStore.getState().archive).toBeNull() + expect(sessionStorage.getItem(ARCHIVE_KEY)).toBeNull() + expect(alertMock()).toHaveBeenCalledTimes(1) + expect(alertLines()).toEqual([ + fr['home.import.degraded'], + fr['home.import.snapshot_rejected']!.replace( + '{reason}', + fr['home.import.snapshot_reason.caps']!, + ), + ]) + }) + + it('attachment_stripped → its error message, nothing opened', async () => { + importMock.mockRejectedValue(new ImportError('attachment_stripped')) + await mountAndPickPdf() + await waitFor(() => expect(errorText()).not.toBeNull()) + expect(errorText()!.textContent).toBe( + fr['home.import.error_attachment_stripped'], + ) + expect(screen.queryByTestId('editor-route')).toBeNull() + expect(useReportStore.getState().report).toBeNull() + expect(alertMock()).not.toHaveBeenCalled() + }) +}) diff --git a/apps/app/tests/unit/routes.HomeRoute.import.test.tsx b/apps/app/tests/unit/routes.HomeRoute.import.test.tsx new file mode 100644 index 00000000..3bb1d94c --- /dev/null +++ b/apps/app/tests/unit/routes.HomeRoute.import.test.tsx @@ -0,0 +1,184 @@ +/** + * Step 6 Phase 0 characterisation of the import flow on the home route, with + * `importReportFromPdf` mocked: the migration alert (degraded headline, then + * the count), the three ImportError kinds plus the generic error mapped to + * the FR messages, and the navigation to /editor on success. + */ +import { + describe, + it, + expect, + vi, + beforeAll, + beforeEach, + afterEach, +} from 'vitest' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { MemoryRouter, Route, Routes } from 'react-router-dom' +import type { ArchiveReadOutcome } from '@faunosteo/domain' +import HomeRoute from '@/app/routes/HomeRoute' +import { ImportError, importReportFromPdf, MAX_PDF_BYTES } from '@/pdf/import' +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' + +vi.mock('@/pdf/import', async (importOriginal) => ({ + ...(await importOriginal<typeof import('@/pdf/import')>()), + importReportFromPdf: vi.fn(), +})) +const importMock = vi.mocked(importReportFromPdf) + +let sheet: SheetIndex + +beforeAll(async () => { + sheet = await loadTestSheet() +}) +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + useReportStore.setState({ + report: null, + archive: null, + activeObservationIndex: 0, + }) + vi.stubGlobal('alert', vi.fn()) + importMock.mockReset() +}) +afterEach(() => { + cleanup() + vi.unstubAllGlobals() +}) + +/** The outcome shape importReportFromPdf resolves with (bare report, no archive). */ +function outcome(patch: { + migrated: boolean + unresolvedZones?: number + unresolvedFindings?: number +}): ArchiveReadOutcome { + return { + report: minimalReport(sheet), + origin: patch.migrated ? 'v2' : 'bare_v3', + archive: null, + unresolvedZones: 0, + unresolvedFindings: 0, + ...patch, + } +} + +/** A 4-byte "%PDF" file; the import is mocked, the bytes only travel. */ +function pdfFile(): File { + return new File([new Uint8Array([37, 80, 68, 70])], 'bilan.pdf', { + type: 'application/pdf', + }) +} + +async function mountAndPickPdf(file: File = pdfFile()): Promise<void> { + 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()) + const input = document.querySelector('input[type="file"]')! + fireEvent.change(input, { target: { files: [file] } }) +} + +const alertMock = () => vi.mocked(window.alert) +const errorText = () => screen.queryByText(/./, { selector: 'p.text-red-700' }) + +describe('HomeRoute import: success paths', () => { + it('passes the file bytes and the sheet migration map, hydrates, navigates to /editor', async () => { + importMock.mockResolvedValue(outcome({ migrated: false })) + await mountAndPickPdf() + await screen.findByTestId('editor-route') + expect(importMock).toHaveBeenCalledTimes(1) + const [bytes, map] = importMock.mock.calls[0]! + expect(bytes).toBeInstanceOf(Uint8Array) + expect(map).toBe(sheet.sheet.migrationMap) + expect(useReportStore.getState().report?.id).toBe('r1') + expect(alertMock()).not.toHaveBeenCalled() + }) + + it('alerts "degraded" then the unresolved count (zones + findings) after a lossy migration', async () => { + importMock.mockResolvedValue( + outcome({ migrated: true, unresolvedZones: 1, unresolvedFindings: 1 }), + ) + await mountAndPickPdf() + await screen.findByTestId('editor-route') + expect(alertMock()).toHaveBeenCalledTimes(1) + const message = alertMock().mock.calls[0]![0] as string + const [headline, ...lines] = message.split('\n\n') + expect(headline).toBe(fr['home.import.degraded']) + expect(lines).toEqual([ + fr['home.import.migrated']!.replace('{count}', '2'), + ]) + }) + + it('stays silent on a migration that lost nothing', async () => { + importMock.mockResolvedValue(outcome({ migrated: true })) + await mountAndPickPdf() + await screen.findByTestId('editor-route') + expect(alertMock()).not.toHaveBeenCalled() + }) +}) + +describe('HomeRoute import: error paths', () => { + const cases: Array<[string, Error, string]> = [ + [ + 'incompatible_version → message with the found version', + new ImportError('incompatible_version', 7), + fr['home.import.error_incompatible_version']!.replace('{version}', '7'), + ], + [ + 'invalid_pdf → unreadable PDF message', + new ImportError('invalid_pdf'), + fr['home.import.error_invalid_pdf']!, + ], + [ + 'no_attachment → not a Faunosteo PDF message', + new ImportError('no_attachment'), + fr['home.import.error_no_attachment']!, + ], + [ + 'generic Error → generic message', + new Error('disk on fire'), + fr['home.import.error_generic']!, + ], + ] + + it.each(cases)('%s', async (_label, error, expected) => { + importMock.mockRejectedValue(error) + await mountAndPickPdf() + await waitFor(() => expect(errorText()).not.toBeNull()) + expect(errorText()!.textContent).toBe(expected) + expect(screen.queryByTestId('editor-route')).toBeNull() + expect(useReportStore.getState().report).toBeNull() + expect(alertMock()).not.toHaveBeenCalled() + }) +}) + +describe('HomeRoute import: size gate', () => { + it('refuses a file over MAX_PDF_BYTES before reading it: unreadable PDF message', async () => { + const file = pdfFile() + Object.defineProperty(file, 'size', { value: MAX_PDF_BYTES + 1 }) + const read = vi.spyOn(file, 'arrayBuffer') + await mountAndPickPdf(file) + await waitFor(() => expect(errorText()).not.toBeNull()) + expect(errorText()!.textContent).toBe(fr['home.import.error_invalid_pdf']) + expect(read).not.toHaveBeenCalled() + expect(importMock).not.toHaveBeenCalled() + expect(screen.queryByTestId('editor-route')).toBeNull() + expect(useReportStore.getState().report).toBeNull() + }) +}) diff --git a/apps/app/tests/unit/scripts.compare.test.ts b/apps/app/tests/unit/scripts.compare.test.ts index a3be032c..8026a514 100644 --- a/apps/app/tests/unit/scripts.compare.test.ts +++ b/apps/app/tests/unit/scripts.compare.test.ts @@ -1,14 +1,18 @@ /** * The archive check tool (scripts/compare-reports.ts) on the frozen v2 PDF, - * on a synthetic v2 report with removed and unknown items, and on a v3 report. + * on a synthetic v2 report with removed and unknown items, on a v3 report + * and on a Step 6 envelope (archive header line). */ import { describe, it, expect, beforeAll } from 'vitest' -import { PDFDocument } from 'pdf-lib' import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { dirname, resolve } from 'node:path' -import { readReportDocument, type ReportV2 } from '@faunosteo/domain' -import { readAttachedDocument } from '@/pdf/attachment' +import { + readArchiveDocument, + readReportDocument, + type ReportV2, +} from '@faunosteo/domain' +import { readAttachedDocument } from '@faunosteo/pdf' import type { SheetIndex } from '@/services/sheetIndex' import { compareReport, @@ -18,7 +22,7 @@ import { renderSummary, UNRESOLVED, } from '../../scripts/compare/report' -import { loadTestSheet, minimalReport } from '../helpers/sheet' +import { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet' const HERE = dirname(fileURLToPath(import.meta.url)) const OPTS = { locale: 'fr' as const, full: false } @@ -32,9 +36,8 @@ function minimalV2(): ReportV2 { } function compareRaw(raw: unknown, full = false) { - const outcome = readReportDocument(raw, sheet.sheet.migrationMap) - const migrated = (raw as { version: number }).version !== 3 - return compareReport(raw, outcome, migrated, sheet, { ...OPTS, full }) + const outcome = readArchiveDocument(raw, sheet.sheet.migrationMap) + return compareReport(raw, outcome, sheet, { ...OPTS, full }) } beforeAll(async () => { @@ -44,8 +47,7 @@ beforeAll(async () => { describe('compareReport on the frozen v2 archive PDF', () => { it('shows every legacy zone and finding next to its canonical target', async () => { const bytes = readFileSync(resolve(HERE, '../fixtures/report-v2.full.pdf')) - const pdf = await PDFDocument.load(new Uint8Array(bytes)) - const raw = await readAttachedDocument(pdf) + const raw = await readAttachedDocument(new Uint8Array(bytes)) const c = compareRaw(raw) const lines = renderComparison('full.pdf', c) expect(c.source).toBe('v2') @@ -165,6 +167,35 @@ describe('compareReport on unresolved items', () => { expect(c.counts.unresolvedFindings).toBe(1) }) + it('prints the archive line of an envelope: snapshot kept, or rejected with its reason', () => { + const envelope = archiveEnvelope( + sheet, + minimalReport(sheet, { + observations: [ + { + id: 'o-env', + zones: [{ annotationId: 'hip', viewId: 'main', side: 'left' }], + findings: [], + freeTextFindings: [], + comment: '', + }, + ], + }), + ) + const kept = compareRaw(envelope) + expect(kept.source).toBe('v3') + expect(kept.header).toContain('archive v1 (snapshot kept)') + const text = renderComparison('env.pdf', kept).join('\n') + expect(text).toContain('hip@main left "Hanche (coxo-fémorale)"') + const rejected = compareRaw({ ...envelope, envelopeVersion: 2 }) + expect(rejected.header).toContain( + 'archive v1 (snapshot rejected: unsupported_envelope)', + ) + expect(compareRaw(envelope.report).header).not.toContain( + 'archive v1 (snapshot kept)', + ) + }) + it('warns when a v3 report was written on another sheet document', () => { const report = minimalReport(sheet, { sheet: { ...sheet.sheet.ref, documentSha256: 'b'.repeat(64) }, diff --git a/apps/app/tests/unit/sheets.provider.test.ts b/apps/app/tests/unit/sheets.provider.test.ts index ca7cee2a..d2e02ce4 100644 --- a/apps/app/tests/unit/sheets.provider.test.ts +++ b/apps/app/tests/unit/sheets.provider.test.ts @@ -2,6 +2,8 @@ * Replaces anatomy.horse / char.svgCatalogLink: the bundled reference sheet * loads, validates, and indexes as the canonical document says. */ +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' import { beforeAll, describe, expect, it } from 'vitest' import { bundledSheetProvider } from '@/sheets/provider' import { @@ -12,6 +14,12 @@ import { } from '@/services/sheetIndex' import { loadTestSheet } from '../helpers/sheet' +/** The seed manifest the bundle reads its asset hashes from. */ +const ASSET_MANIFEST = resolve( + __dirname, + '../../../../supabase/seed/anatomical-sheets/equine/draft/assets.json', +) + let sheet: SheetIndex beforeAll(async () => { sheet = await loadTestSheet() @@ -32,6 +40,19 @@ describe('bundled sheet provider', () => { ) expect(await bundledSheetProvider.getReferenceSheet('canine')).toBeNull() }) + + it('carries the schema version and the manifest hash of the horse asset', async () => { + const loaded = await bundledSheetProvider.getReferenceSheet('equine') + const manifest = JSON.parse(readFileSync(ASSET_MANIFEST, 'utf8')) as { + sha256: string + svg_asset_id: string + }[] + const horse = manifest[0]! + expect(loaded!.schemaVersion).toBe(2) + expect(Object.keys(loaded!.assetHashes)).toEqual([horse.svg_asset_id]) + expect(loaded!.assetHashes[horse.svg_asset_id]).toBe(horse.sha256) + expect(horse.sha256).toMatch(/^[0-9a-f]{64}$/) + }) }) describe('sheet index', () => { @@ -93,9 +114,12 @@ describe('sheet index', () => { .filter(isObservable) .map((a) => a.vertebral_region_code) .filter((c) => c !== null) - expect(sheet.regions().map((r) => r.code).sort()).toEqual( - [...carried].sort(), - ) + expect( + sheet + .regions() + .map((r) => r.code) + .sort(), + ).toEqual([...carried].sort()) }) it('resolves finding paths and reports absent ones', () => { diff --git a/apps/app/tests/unit/state.reportStore.test.ts b/apps/app/tests/unit/state.reportStore.test.ts index 2c7d5ae7..aa3bb0d8 100644 --- a/apps/app/tests/unit/state.reportStore.test.ts +++ b/apps/app/tests/unit/state.reportStore.test.ts @@ -1,17 +1,31 @@ /** * Replaces state.reportStore / state.reportStore.restore / .setters / - * state.draftMirror: the v3 store, its actions, the sessionStorage mirror - * and the migration of a v2 draft on restore. + * state.draftMirror: the v3 store, its actions, the sessionStorage mirror, + * the migration of a v2 draft on restore, and (Step 6) the archive kept + * beside the report and the rebase of a stale draft. */ -import { beforeAll, beforeEach, describe, expect, it } from 'vitest' +import { + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from 'vitest' +import type { Annotation } from '@faunosteo/domain' import { createReportStore, useReportStore, emptyObservation, } from '@/state/reportStore' -import { DRAFT_KEY, sessionStoragePersistence } from '@/state/persistence' +import { + ARCHIVE_KEY, + DRAFT_KEY, + sessionStoragePersistence, +} from '@/state/persistence' import type { SheetIndex } from '@/services/sheetIndex' -import { loadTestSheet, minimalReport } from '../helpers/sheet' +import { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet' import fullV2 from '../fixtures/report-v2.full.json' let sheet: SheetIndex @@ -20,8 +34,13 @@ beforeAll(async () => { }) beforeEach(() => { sessionStorage.clear() - useReportStore.setState({ report: null, activeObservationIndex: 0 }) + useReportStore.setState({ + report: null, + archive: null, + activeObservationIndex: 0, + }) }) +afterEach(() => vi.restoreAllMocks()) const draft = () => ({ date: '2026-10-10', @@ -117,12 +136,12 @@ describe('sessionStorage mirror and restore', () => { it('restores a v3 draft, and migrates a v2 draft left by the previous version', () => { const v3 = minimalReport(sheet, { conclusion: 'kept' }) sessionStorage.setItem(DRAFT_KEY, JSON.stringify(v3)) - useReportStore.getState().restoreDraft(sheet.sheet.migrationMap) + useReportStore.getState().restoreDraft(sheet) expect(useReportStore.getState().report?.conclusion).toBe('kept') useReportStore.setState({ report: null }) sessionStorage.setItem(DRAFT_KEY, JSON.stringify(fullV2)) - useReportStore.getState().restoreDraft(sheet.sheet.migrationMap) + useReportStore.getState().restoreDraft(sheet) const restored = useReportStore.getState().report! expect(restored.version).toBe(3) expect( @@ -139,16 +158,16 @@ describe('sessionStorage mirror and restore', () => { useReportStore.getState().initReport(draft(), sheet.sheet.ref) const before = useReportStore.getState().report sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet))) - useReportStore.getState().restoreDraft(sheet.sheet.migrationMap) + useReportStore.getState().restoreDraft(sheet) expect(useReportStore.getState().report).toBe(before) }) it('createReportStore accepts another persistence adapter', () => { const saved: unknown[] = [] - const store = createReportStore({ - load: () => null, - save: (r) => saved.push(r), - }) + const store = createReportStore( + { load: () => null, save: (r) => saved.push(r) }, + { load: () => null, save: () => undefined }, + ) store.getState().initReport(draft(), sheet.sheet.ref) expect(saved.at(-1)).toMatchObject({ version: 3 }) }) @@ -173,7 +192,133 @@ describe('store edge cases', () => { }) it('restoreDraft with no draft leaves the store empty', () => { - useReportStore.getState().restoreDraft(sheet.sheet.migrationMap) + useReportStore.getState().restoreDraft(sheet) expect(useReportStore.getState().report).toBeNull() }) }) + +describe('archive of an imported Step 6 PDF', () => { + const OTHER_SHA = 'b'.repeat(64) + it('hydrateImport keeps the archive and mirrors it under osteo:archive', () => { + const report = minimalReport(sheet) + const archive = archiveEnvelope(sheet, report) + useReportStore.getState().hydrateImport({ report, archive }) + expect(useReportStore.getState().archive).toEqual(archive) + expect(JSON.parse(sessionStorage.getItem(ARCHIVE_KEY)!).report.id).toBe( + report.id, + ) + expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).id).toBe(report.id) + }) + + it('the archive is written at the session edges only, never on an edit', () => { + const archiveSaves: unknown[] = [] + const store = createReportStore( + { load: () => null, save: () => undefined }, + { load: () => null, save: (a) => archiveSaves.push(a) }, + ) + const report = minimalReport(sheet) + const archive = archiveEnvelope(sheet, report) + store.getState().hydrateImport({ report, archive }) + expect(archiveSaves).toEqual([archive]) + store.getState().setConclusion('edited') + store.getState().addObservation() + store.getState().setRecommendations('again') + expect(archiveSaves).toHaveLength(1) + expect(store.getState().report?.conclusion).toBe('edited') + store.getState().reset() + expect(archiveSaves).toEqual([archive, null]) + }) + + it('restoreDraft brings the archive back with the draft', () => { + const report = minimalReport(sheet, { conclusion: 'kept' }) + const archive = archiveEnvelope(sheet, report) + useReportStore.getState().hydrateImport({ report, archive }) + // Emptying the state clears the draft mirror, not the archive mirror. + useReportStore.setState({ report: null, archive: null }) + expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull() + expect(sessionStorage.getItem(ARCHIVE_KEY)).not.toBeNull() + sessionStorage.setItem(DRAFT_KEY, JSON.stringify(report)) + const outcome = useReportStore.getState().restoreDraft(sheet) + expect(outcome).toMatchObject({ rebased: false }) + expect(useReportStore.getState().report?.conclusion).toBe('kept') + expect(useReportStore.getState().archive).toEqual(archive) + }) + + it.each([ + [ + 'initReport', + () => useReportStore.getState().initReport(draft(), sheet.sheet.ref), + ], + [ + 'hydrateReport', + () => useReportStore.getState().hydrateReport(minimalReport(sheet)), + ], + ['reset', () => useReportStore.getState().reset()], + ])('%s clears the archive and removes its mirror', (_name, act) => { + const report = minimalReport(sheet) + useReportStore + .getState() + .hydrateImport({ report, archive: archiveEnvelope(sheet, report) }) + act() + expect(useReportStore.getState().archive).toBeNull() + expect(sessionStorage.getItem(ARCHIVE_KEY)).toBeNull() + }) + + it('restoreDraft rebases a draft written on another revision of the sheet, labels from the archived snapshot', () => { + const stale = minimalReport(sheet, { + sheet: { ...sheet.sheet.ref, documentSha256: OTHER_SHA }, + observations: [ + { + id: 'o-stale', + zones: [ + { annotationId: 'point-gone', viewId: 'main' }, + { annotationId: 'hip', viewId: 'main', side: 'left' }, + ], + findings: [], + freeTextFindings: [], + comment: '', + }, + ], + }) + const archive = archiveEnvelope(sheet, stale) + archive.sheetSnapshot.ref.documentSha256 = OTHER_SHA + archive.sheetSnapshot.document.annotations.push({ + ...sheet.annotation('hip')!, + id: 'point-gone', + name: { fr: 'Point disparu', en: 'Gone point' }, + } as Annotation) + sessionStorage.setItem(DRAFT_KEY, JSON.stringify(stale)) + sessionStorage.setItem(ARCHIVE_KEY, JSON.stringify(archive)) + + const outcome = useReportStore.getState().restoreDraft(sheet) + expect(outcome).toMatchObject({ + rebased: true, + unresolvedZones: 1, + unresolvedFindings: 0, + }) + const restored = useReportStore.getState().report! + expect(restored.sheet).toEqual(sheet.sheet.ref) + expect(restored.observations[0]!.zones[0]).toMatchObject({ + unresolved: true, + labelFrSnapshot: 'Point disparu', + }) + expect(restored.observations[0]!.zones[1]!.unresolved).toBeUndefined() + expect(useReportStore.getState().archive).toEqual(archive) + // The mirror now holds the rebased draft. + expect( + JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).sheet.documentSha256, + ).toBe(sheet.sheet.ref.documentSha256) + }) + + it('ignores a corrupt or foreign osteo:archive', () => { + sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet))) + sessionStorage.setItem(ARCHIVE_KEY, '{not json') + useReportStore.getState().restoreDraft(sheet) + expect(useReportStore.getState().report).not.toBeNull() + expect(useReportStore.getState().archive).toBeNull() + useReportStore.setState({ report: null }) + sessionStorage.setItem(ARCHIVE_KEY, JSON.stringify({ hello: 'world' })) + useReportStore.getState().restoreDraft(sheet) + expect(useReportStore.getState().archive).toBeNull() + }) +}) diff --git a/apps/app/vite/sheet-bundle.ts b/apps/app/vite/sheet-bundle.ts index b9485e2e..70276067 100644 --- a/apps/app/vite/sheet-bundle.ts +++ b/apps/app/vite/sheet-bundle.ts @@ -7,7 +7,8 @@ import type { Plugin } from 'vite' * application as the virtual module `virtual:faunosteo-sheet`. * * Mode `draft` embeds `document.json`, `sheet-ref.json`, - * `report-migration-map.json` and the SVG assets of the seed folder; mode + * `report-migration-map.json`, the SVG assets of the seed folder and their + * manifest hashes (`assets.json`, carried into report archives); mode * `none` exports null and the app shows "no sheet configured". The default is * `draft` for the dev server and `none` for a build: a production bundle never * carries the medically unvalidated draft unless `SHEET_BUNDLE=draft` is set @@ -36,6 +37,7 @@ interface SeedFiles { document: unknown migrationMap: unknown assets: Record<string, string> + assetHashes: Record<string, string> watched: string[] } @@ -44,20 +46,24 @@ function readSeed(seedDir: string): SeedFiles { JSON.parse(readFileSync(join(seedDir, name), 'utf8')) as unknown const manifest = json('assets.json') as { file: string + sha256: string svg_asset_id: string }[] const assets: Record<string, string> = {} + const assetHashes: Record<string, string> = {} for (const asset of manifest) { assets[asset.svg_asset_id] = readFileSync( join(seedDir, 'assets', asset.file), 'utf8', ) + assetHashes[asset.svg_asset_id] = asset.sha256 } return { ref: json('sheet-ref.json'), document: json('document.json'), migrationMap: json('report-migration-map.json'), assets, + assetHashes, watched: [ 'sheet-ref.json', 'document.json', @@ -88,6 +94,7 @@ export function faunosteoSheetBundle(options: { document: seed.document, migrationMap: seed.migrationMap, assets: seed.assets, + assetHashes: seed.assetHashes, } return `export const bundledSheet = ${JSON.stringify(payload)}\n` }, diff --git a/docs/PDF-FORMAT.md b/docs/PDF-FORMAT.md index 0a70de92..35d493c6 100644 --- a/docs/PDF-FORMAT.md +++ b/docs/PDF-FORMAT.md @@ -1,33 +1,286 @@ -# PDF Format +# PDF format and report archive -Placeholder — to be written when implementing src/pdf/. +A Faunosteo PDF is both a document for the reader and an archive of the +bilan. The engine lives in `packages/pdf` (`@faunosteo/pdf`) and renders from +explicit inputs only: no network, no browser DOM, no access to the current +catalog. The attachment carries everything a future reader needs to +re-render the bilan when the anatomical sheet, the catalog, the labels or the +branding have changed since the export. Design record: +`docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md`. -Will cover: +## Pages -- A4 portrait dimensions (595.28 × 841.89 pt) -- Page layout: header / body / footer zones -- Observation page structure -- Conclusion page structure -- JSON attachment spec (EmbeddedFiles, afRelationship:Data) -- Font handling (pdf-lib StandardFonts Helvetica/Times-Roman, WinAnsi; TTF Inter/Fraunces planned, not shipped) -- Import/re-import roundtrip contract +- A4 portrait, 595.28 × 841.89 pt, 36 pt side margins. +- One page per observation, then one conclusion page. Every page carries the + header (logo, practitioner, animal, owner, date) and the footer (site logo, + "powered by" credit, partner credit, page `n / N`). +- Observation page: eyebrow + title, the views of the observation drawn with + its zones highlighted (main view first, head view as a crop of the same + asset), then zones, findings grouped by finding zone, free findings, + severity, comment. +- Conclusion page: conclusion, recommendations, next appointment. +- Fonts: pdf-lib StandardFonts Helvetica, Helvetica-Bold (body) and + Times-Roman (headings), WinAnsi encoding. Every printed string goes through + `safeText`: control characters are stripped and any glyph WinAnsi cannot + encode becomes `?` (en and em dashes, accented letters, `•`, `·` are fine; + `⚠` is not, hence the `(!)` vet-referral marker). +- Drawings: the sheet SVG asset is parsed with xmldom, sanitised (allowlist + below), framed on the view box, the marker layer is generated from the + document and the observation's zones are filled `#b85a3f` at 0.85 opacity + with a blur halo on the main view; every other marker is dropped. The SVG + is rasterised at 1200 px wide (aspect clamped to [0.2, 2.0]) by the + rasterizer the caller provides: `Image` + canvas in the browser, resvg in + Node tests. A failed raster leaves the page without that image and reports + a warning; the export never fails for a drawing. +- Document information: title, author, subject, dates = `exportedAt`, and + `Keywords: faunosteo-archive/1` so a PDF whose attachment was stripped by a + viewer is still recognised. +- Saved without object streams (`useObjectStreams: false`) since BLK-009: the + Filespec, its file name and the Info dictionary stay in clear, where the + byte-scan reader below can see them. Files produced earlier pack them into + an `/ObjStm`; their attachment stream is still in clear and still imports. -## Attachment versions (Step 5) +## Attachment: the report archive envelope (v1) -The attachment `osteo-report.json` carries the Report **v3** document -(`packages/domain/src/report/v3.ts`): zones by `(annotationId, viewId)`, -findings by `(findingZoneId, path)` with label snapshots, severity codes, -the `sheet` reference (sheet id, version id, sha256 of the document) and the -reserved `localAnnotations`. +One native embedded file (`EmbeddedFiles`, `AFRelationship /Data`) named +`osteo-report.json`, MIME `application/json`, description +`Faunosteo report archive v1`, Flate-compressed by pdf-lib. Pretty-printed +JSON, camelCase keys (the sheet document inside keeps its own snake_case +schema): -Import (`importReportFromPdf(bytes, migrationMap)`) accepts: +```json +{ + "format": "faunosteo-report-archive", + "envelopeVersion": 1, + "exportedAt": "2026-10-11T09:00:00.000Z", + "locale": "fr", + "report": { "version": 3, "...": "Report v3 exactly as exported" }, + "sheetSnapshot": { + "status": "draft", + "ref": { + "sheetId": "…", + "versionId": null, + "documentSha256": "…", + "schemaVersion": 2, + "speciesId": "equine" + }, + "document": { + "schema_version": 2, + "...": "lean, valid anatomical sheet document" + }, + "assets": [{ "svgAssetId": "…", "sha256": "…", "svg": "<svg …>" }] + }, + "branding": { + "siteUrl": "https://…", + "headerLogo": { "kind": "png", "base64": "…" }, + "footerLogo": { "kind": "png", "base64": "…" }, + "poweredBy": { + "logo": { "kind": "png", "base64": "…" }, + "url": "https://…", + "fallbackText": "…" + }, + "partner": { + "logo": { "kind": "svg", "svg": "<svg …>" }, + "url": "https://…", + "fallbackText": "…" + } + }, + "labels": { + "fr": { "pdf.section.zones": "ZONES", "...": "25 keys" }, + "en": { "...": "" } + } +} +``` -- v3: read as is; -- v2 (PDFs produced by the application before Step 5, the practitioner's - archive): migrated through the sheet's `report-migration-map.json`; a zone - or finding the map cannot place is kept with its snapshots and flagged - `unresolved: true`; the outcome reports `migrated` and the unresolved counts; -- any other version: `ImportError('incompatible_version', foundVersion)`. +### What the snapshot holds + +The snapshot is the sheet the bilan was built on, reduced to what the bilan +needs, as a **valid** anatomical sheet document (schema v2, same integrity +rules as the catalog): + +| Part | Content | +| ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ref` | sheet id, version id, sha256 of the full catalog document (provenance pointer), schema version, species | +| `document.views`, `annotations`, `categories`, `vertebral_config` | all of them: geometry, colours, names, anatomical relations (`finding_zone_id`, `vertebral_region_code`, `opens_view_id`, laterality) | +| `document.finding_zones` | every zone with its name; for the zones the report's findings use (resolved or `unresolved`), the categories pruned to the referenced paths with the name and vet flag of every node on the path; other zones keep `categories: []` | +| `document.references` | emptied (bibliography) | +| `document.name`, `description`, `scope_disclaimer`, `attribution` | kept | +| `assets` | the SVG text of every asset a view reaches, with the catalog's content hash when known | + +`branding` is the exact set of images, URLs and credit texts used at export; +the application builds it from logos bundled at build time +(`apps/app/src/assets/brand`), so the export makes no network request. +`labels` is the engine dictionary in both languages. A re-export of the +archive uses these three blocks and nothing from the current application, so +a new logo, a reworded heading or a curated sheet never changes how an old +bilan is reproduced. + +Invariant: `report.sheet.documentSha256 === sheetSnapshot.ref.documentSha256` +(and the sheet ids match). The export refuses to write a file that breaks it. + +### Sizes + +Measured on the demo report (6 observations, both views, equine draft): + +| Branding | Stored in the PDF (Flate) | Raw JSON | +| ----------------------------------------- | ------------------------- | -------- | +| no logos | 55 KB | 189 KB | +| full branding (3 PNG logos + partner SVG) | 136 KB | 306 KB | + +The drawing is the largest part (47 KB stored); the archived PNG logos add +about 80 KB stored. The 250 KB target applies to the stored size. + +## Reading an archive + +`readReportArchive(pdfBytes, migrationMap)` reads in layers so the report is +never lost because of its wrapper: + +1. The file must weigh at most 50 MiB and carry `%PDF-` within its first + KiB (`invalid_pdf`). Nothing else of the PDF syntax is required. +2. The attachment is located by a byte scan, never by parsing the PDF object + graph (BLK-009): every `/Type /EmbeddedFile` stream dictionary in clear + (a stream object can never sit inside an object stream) is a candidate, + with its direct `/Length` or, failing that, the distance to `endstream`; + a `/Filespec` dictionary in clear whose `/EF /F` points at the stream + gives it a name. Candidates named `osteo-report*` come first, then file + order; Flate data is fed to the platform inflater in 16 KiB slices, so + memory stays bounded in browsers too, under a 16 MiB cap (cancelled + beyond it); at most 16 MiB of candidate content is retained and parsed in + all (a cancelled inflation is not charged, so up to 32 oversized streams + may each cost one capped inflation of CPU, bounded, no memory retained), + a candidate not opening on `{` or nesting brackets deeper than 64 levels + is skipped unparsed, and the first one whose text is a JSON object with a + numeric `envelopeVersion` or `version` wins. Object streams, + cross-reference streams and page contents are never inflated. + No candidate: `attachment_stripped` when a `/Keywords` string in clear + contains `faunosteo-archive`, else `no_attachment`. A stamped file saved + with object streams (before BLK-009) hides its stamp and reads as + `no_attachment`. +3. The report is located (`data.report` inside an envelope, `data` for a + bare attachment) and read with the report reader: v3 as is, v2 migrated + through the sheet's `report-migration-map.json` (items the map cannot + place are kept with their labels and flagged `unresolved: true`), any + other version → `incompatible_version` with the version found. +4. Envelope metadata is read tolerantly (unknown keys ignored within v1). An + unknown `envelopeVersion` keeps the report and drops the snapshot + (`snapshotRejected: 'unsupported_envelope'`). The snapshot, branding and + labels are validated strictly; any failure drops the snapshot with a + closed reason (`schema`, `caps`, `integrity`, `sheet_mismatch`) and keeps + the report. + +| Archive | Produced by | Read as | +| -------------- | ------------------------- | ---------------------------------------------------------- | +| bare Report v2 | application before Step 5 | `origin 'v2'`, migrated, unresolved counts | +| bare Report v3 | Step 5 | `origin 'bare_v3'`, no archive | +| envelope v1 | Step 6 | `origin 'envelope_v1'`, archive kept or `snapshotRejected` | +| envelope v≥2 | future | report kept when its version is known, snapshot dropped | + +Readers never drop a schema version: sheet document schema v2 stays readable +as long as envelope v1 archives exist, as Report v2 does today. A rollback to +a pre-Step-6 application reads an envelope as "no attachment". + +### In the application + +Two operations are distinct: + +- **Re-read or re-export an archive**: `exportFromEnvelope(envelope, { locale, rasterizer, exportedAt })` + uses the archived snapshot, branding and labels. The imported archive is + kept in the session (`osteo:archive`), immutable. +- **Resume a bilan for editing**: the editor works on the loaded sheet. When + the archive's sheet differs from the loaded one, the report is **rebased** + on a working copy: zones and findings the loaded sheet cannot place are + flagged `unresolved: true`, their labels are filled from the archived + snapshot, and `report.sheet` becomes the loaded sheet. The import message + states the number of items not found; a degraded import is never shown as + a perfect restoration. + +## Limits and sanitising + +| Item | Cap | +| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| PDF file | 50 MiB | +| attachment, raw and inflated | 16 MiB | +| snapshot assets | ≤ 4, ≤ 2 MiB each, ≤ 6 MiB total | +| snapshot document | ≤ 64 views, ≤ 1,024 annotations, ≤ 8,192 finding nodes, depth ≤ 8, names ≤ 512 chars | +| branding | PNG base64 ≤ 512 KiB, SVG ≤ 256 KiB, http(s) URLs ≤ 2,048 chars | +| branding URL | `http(s)://` then printable ASCII only, without `"` `'` `(` `)` `<` `>` `\`, no space or control character | +| branding PNG | valid signature, one IHDR (13 bytes) first with a colour type and bit depth the spec allows, compression and filter method 0, no interlace; each side 1 to 8,192 px, ≤ 16,777,216 px (4096²), expected raw scanline size ≤ 16 MiB; then only `PLTE` `tRNS` `IDAT` `gAMA` `cHRM` `sRGB` `sBIT` `pHYs` `bKGD`, no chunk past the buffer, an empty `IEND` as the last bytes; the IDAT stream inflated natively and yielding exactly the raw scanline size | +| report at export | ≤ 500 observations, ≤ 8 views per observation | +| SVG sanitiser | ≤ 20,000 elements, nesting ≤ 64, ≤ 256 `<use>`, blur `stdDeviation` ≤ 100 | + +Every SVG that reaches the engine (sheet asset or branding) is untrusted: a +text containing `<!DOCTYPE` or `<!ENTITY` is refused; the parsed tree is +sanitised by allowlist (shapes, groups, gradients, the filter primitives the +drawings use, `clipPath`, `mask`, `switch`, `use`, `title`, `desc`; geometry, +presentation, gradient and filter attributes; `href` and `url()` only to a +`#fragment`; no `style` element, no `script`, `image`, `a`, `foreignObject`, +`text`, no event handler). An attribute value with a backslash is removed (a +CSS escape such as `u\72l(` would hide a reference), and a `style` or +presentation attribute may call no function other than `url(#…)`: `rgb(`, +`image-set(`, `expression(` and the like are removed with the attribute. The +reference drawings pass unchanged (tested). +The same caps are checked at export, so an export can never write a file its +own reader refuses. + +The branding URL rule exists because a URL is written into every page's +link action: pdf-lib does not escape a literal string, so the engine writes +the URI as a hex string and the schema refuses the characters that could +close a literal. The export re-validates the branding and the labels it +receives (`ArchiveExportError('branding_invalid')` before any page is +drawn), even from an archive that passed the reader. The URI itself is the +hex form of the URL's ASCII bytes (`<68747470…>`), not UTF-16 with a BOM, +so readers that take `/URI` as raw bytes (poppler) follow it. A PNG logo is +checked before pdf-lib's decoder (UPNG) sees it, because that decoder trusts +its input: it sizes its bitmap from whatever IHDR claims, its `inflateRaw` +never checks the input bound (a truncated or crafted IDAT stream makes it +read past the buffer and never return), and it scans text chunks for a NUL +byte that may be missing. The gate therefore validates, in order: the +signature and a first 13-byte IHDR; a width and height of at least 1 under +the pixel budget; a colour type and bit depth the PNG spec allows (0: 1 to +16 bits, 2 and 4 and 6: 8 or 16, 3: 1 to 8), compression and filter method +0 and no interlace (the archived logos are never interlaced, so Adam7 pass +sizes are not computed); an expected raw scanline size, +`(ceil(width × bits per pixel / 8) + 1) × height`, of at most 16 MiB, the +attachment cap the native inflater enforces (4096² at 8-bit RGBA is 67 MB +of scanlines and is refused; a 512 px wide logo is under 1 MB). That cap +bounds what is inflated, not what pdf-lib's decoder then allocates: the +decoder still expands any accepted image to a 32-bit RGBA buffer, so the +4096² pixel cap is what bounds memory (about 430 MB peak measured with four +4096² logos; real logos are 512 px wide). Then the chunk list, which must end on an empty `IEND` +that closes the file and may hold only the chunk types the decoder reads by +fixed offsets or by declared length (`PLTE`, `tRNS`, `IDAT`, `IEND`, +`gAMA`, `cHRM`, `sRGB`, `sBIT`, `pHYs`, `bKGD`): a second IHDR, an APNG +chunk, a text or profile chunk (`tEXt`, `iTXt`, `zTXt`, `iCCP`), an unknown +type, a chunk length past the end of the buffer, a missing IEND or bytes +after it refuse the slot. Last, the IDAT payloads are concatenated and +inflated with the platform's `DecompressionStream`, bounded to the expected +raw size: a truncated, corrupt or oversized stream, or one that does not +yield exactly that size, refuses the slot. The allowlist alone would not +make the decoder safe; the native inflation is what keeps it from reading +an unbounded stream. The archive accepts only PNGs ending on IEND, even +though the decoder reads a PNG without one. A refused slot alone prints its +fallback text and the export reports `logo_failed`. + +### Known limits + +- pdf-lib is out of the import path (BLK-009): the browser and the + `report:compare` CLI read the attachment by byte scan, so a crafted object + stream is never inflated (tested with a 64 MiB bomb: milliseconds, no + memory growth). pdf-lib stays on the export side, on trusted inputs, and + in tests that inspect exported files. What remains before external users + (`docs/development/PDF_IMPORT_HARDENING.md` §5): a Worker or server-side + budget for any path that still parses PDF objects, the pdf-lib dependency + decision, and read-side caps on report collections. +- The scanner reads what is in clear: an attachment whose stream dictionary + is malformed beyond `/Length` and `endstream`, or an encrypted file, yields + no candidate (`no_attachment`), as the previous reader did in practice. +- `<use>` expansion is bounded by the rasterizer, not by the sanitiser, + which only counts the `<use>` elements (≤ 256). resvg (tests) refuses an + oversized tree; the production path is the browser rasterizer + (`apps/app/src/pdf/browserRasterizer.ts`, `Image` + canvas), whose + limits on `<use>` expansion are not measured. +- Report v3 collections are not capped on read; the export refuses above + 500 observations and 8 views per observation. ## Checking an archive against its migration @@ -35,10 +288,12 @@ Import (`importReportFromPdf(bytes, migrationMap)`) accepts: more PDFs and prints it next to its v3 reading on the bundled reference sheet. It writes no output file: +- an envelope prints a header line `archive v1 (snapshot kept)` or + `archive v1 (snapshot rejected: <reason>)`; - a v2 archive PDF: every legacy zone (`data-anno-id`, side, vertebrae) and every legacy finding path is shown with its canonical target and the current label of that target (`same` when the path did not change); -- a v3 PDF: every zone and finding is checked against the sheet, and the +- a v3 report: every zone and finding is checked against the sheet, and the header says whether the report was written on the bundled sheet document; - anything the sheet cannot place is printed as `!! UNRESOLVED` with the reason: unknown legacy zone id, finding removed from the sheet by the @@ -49,10 +304,11 @@ Options: `--summary` (one line per file, counts and unresolved counts), `--full` (add the practitioner, animal and owner names and the real free texts; by default only identifiers, catalog labels, snapshots of unresolved items, counts and placeholders such as `comment (present)` are printed), -`--locale fr|en` (labels), `--diff a.pdf b.pdf` (compare the v3 -content of two PDFs: an archive and the PDF exported after importing it -should print `identical v3 content`; by default the texts are compared as -placeholders, so an edited text shows only when it appears or disappears; -`--full` compares the real texts and prints the differing lines). Every untrusted string is printed with control -characters escaped as `\uXXXX`. The tool exits 2 when a file could not -be read (no attachment, unknown version, oversized) and prints the reason. +`--locale fr|en` (labels), `--diff a.pdf b.pdf` (compare the v3 content of +two PDFs: an archive and the PDF exported after importing it should print +`identical v3 content`; by default the texts are compared as placeholders, +so an edited text shows only when it appears or disappears; `--full` +compares the real texts and prints the differing lines). Every untrusted +string is printed with control characters escaped as `\uXXXX`. The tool +exits 2 when a file could not be read (no attachment, unknown version, +oversized) and prints the reason. diff --git a/docs/development/PDF_IMPORT_HARDENING.md b/docs/development/PDF_IMPORT_HARDENING.md new file mode 100644 index 00000000..04da36b3 --- /dev/null +++ b/docs/development/PDF_IMPORT_HARDENING.md @@ -0,0 +1,114 @@ +# PDF import hardening — BLK-009 analysis + +Status 2026-10-11: analysis requested by the user after Step 6. §4 landed the +same day on `feature/step-06-pdf-archives` (options A + B, see §4 for the +commit); §5 lists what must land before the import is opened to external +users. + +## 1. The problem + +`readReportArchive` loads the whole PDF with pdf-lib (`PDFDocument.load`) +before looking for the attachment. pdf-lib's parser inflates every object +stream (`/ObjStm`) and cross-reference stream eagerly with its own, uncapped +inflater. Measured by the security audit: a 408 KB PDF expanded to 400 MB in +1.4 s (468 MB RSS); a 131 KB PDF to 128 MB. The ratio is about 1000:1, so the +50 MiB file cap still allows tens of gigabytes of expansion. Our 16 MiB caps +protect the attachment stream only, which the reader inflates itself. + +Effect: a crafted PDF freezes the practitioner's tab or kills it (out of +memory). No code execution, no data access. A file size limit cannot help: the +amplification lives inside the compression. + +Why `/ObjStm` cannot simply be refused: pdf-lib's `save()` writes object +streams by default (`useObjectStreams: true`), so every Faunosteo PDF +produced so far carries them, and refusing them would refuse the archive. + +## 2. What the reader actually needs from the file + +One embedded file stream, found through its `/Filespec`, and the document +keyword stamp. A PDF stream object can never live inside an object stream: +the `EmbeddedFile` dictionary and its data are always in clear text in the +file (`<< /Type /EmbeddedFile /Filter /FlateDecode /Length N … >> stream … +endstream`). Only the small dictionary objects (Filespec, Info, catalog) may +be packed into object streams. + +So the attachment can be located by scanning the bytes, without parsing the +PDF object graph at all. + +## 3. Options + +| Option | Protection | Cost | Verdict | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | +| A. Byte-scan reader: find `/Type /EmbeddedFile` streams, read `/Length` (direct integer, as pdf-lib writes it; fall back to `endstream` search), inflate with the existing capped `inflateFlate`, parse JSON; no `PDFDocument.load` on import | removes pdf-lib from the import path entirely: the only inflation is our capped one | one module (~120 lines) + tests on every fixture (v2, bare v3, envelope, object streams on/off, several streams, foreign PDF) | **recommended, can land now** | +| B. Export with `useObjectStreams: false` | the Filespec name, the Info keywords and the Filespec→EF link become visible to a byte scan, so the filename-first rule and the `attachment_stripped` detection keep working without the object graph; files a few KB larger | one save option; older PDFs keep their object streams, which A tolerates | **recommended with A** | +| C. Load in a Web Worker with a timeout and a memory budget | contains the damage (the tab survives, the worker dies) | worker bundling, message protocol, no memory cap API in browsers (only termination on timeout) | defence in depth, later | +| D. Pre-scan declared `/Length` of `/ObjStm` streams and refuse above a sum | partial: declared lengths are the compressed sizes, the expansion is unknown | small | insufficient alone | +| E. Replace pdf-lib's parser (fork `@cantoo/pdf-lib`, or `pdf.js` for reading) | maintained parser; pdf.js has its own limits | dependency change, larger bundle | evaluate for Step 14 (server-side import) | + +With A, the import path reads bytes, finds at most a few streams, inflates one +under 16 MiB, parses JSON under the existing schema caps. pdf-lib stays on +the export side (trusted inputs) and in the `report:compare` CLI (operator +tool, Node, acceptable risk but same fix applies). + +Edge cases A must handle: several `EmbeddedFile` streams (pick the one whose +Filespec name starts with `osteo-report` when visible, else the first whose +inflated content parses as a report or an envelope); `/Length` as an indirect +reference (pdf-lib writes direct lengths; other producers may not: fall back +to scanning for `endstream`); `\r\n` versus `\n` after `stream`; encrypted +PDFs (today loaded with `ignoreEncryption`: the attachment stream of an +encrypted file is encrypted too and would fail to inflate → `no_attachment`, +same outcome as today in practice); the 50 MiB file cap stays as the scan +bound. + +## 4. Done 2026-10-11 (feature/step-06-pdf-archives, commit: see commit 60ee712) + +1. Option A in `packages/pdf/src/attachment/scan.ts` + (`findEmbeddedFiles`, `readAttachmentBytes`, `hasArchiveStamp`), used by + `readReportArchive`; `readAttachedDocument(bytes)` takes the file bytes + and the `report:compare` CLI runs on the scanner too. No + `PDFDocument.load` remains under `packages/pdf/src` or `apps/app/scripts`. +2. Option B on export (`pdfDoc.save({ useObjectStreams: false })`): no visible + change; goldens unchanged (they record drawn text, images, links); the + envelope roundtrip tests prove the reader finds the attachment in both + layouts. +3. Tests (`packages/pdf/tests/scan.test.ts`): the three frozen fixtures (object + streams) and a fresh export; two embedded files with a decoy first; + indirect and wrong `/Length`; `\r\n` after `stream`; `/Type/EmbeddedFile` + without a space; hex and literal names and keywords; garbage inputs and + the 32-candidate cap; a 64 MiB object-stream bomb next to the real + attachment (report in milliseconds, RSS flat) and an `EmbeddedFile` bomb + (inflation cancelled at 16 MiB, `no_attachment`). +4. Docs: `docs/PDF-FORMAT.md` "Reading an archive" and "Known limits". + +Known trade-off: a stamped PDF saved before this change (object streams) +hides its `/Keywords`, so a stripped attachment on such a file reads as +`no_attachment` instead of `attachment_stripped`. + +## 5. Prerequisites before external users (Step 7+ sync, Step 14 worker) + +- Option A merged and the CLI on the scanner; no `PDFDocument.load` on any + untrusted input in the browser. +- A real-browser test of the inflate bound (Chromium, Firefox, Safari): the + vitest suite runs in Node and cannot see a browser inflater's read-ahead. + The audit of 60ee712 measured +2.2 GB RSS in Chromium on a 4 MB / 4 GiB + bomb before the inflater was fed in 16 KiB slices (+215 MB after); that + measurement is manual until a browser runner exists. +- Done: the candidate CPU/byte budget on the scanner: one 16 MiB budget of + retained and parsed content shared by every candidate (a cancelled + inflation is not charged, so up to 32 oversized streams may each cost one + capped inflation of CPU, bounded, no memory retained), a monotonic + `endstream` search over candidates sorted by data offset and bounded to + the cap, and no JSON parse for a candidate not opening on `{` or nesting + brackets deeper than 64 levels (linear byte pre-scan, strings skipped). +- Option C or a server-side import (Step 14) with a hard memory and time + budget per file, for any path that still parses PDF objects. +- Dependency decision on pdf-lib (unmaintained since 2021): keep it for + generation only, or move to the maintained fork; recorded as a Step 14 + question. +- Report collection caps on read (observations, zones, findings per + observation) so a hostile report cannot freeze the editor before the + export's own caps refuse it. +- The remaining low findings of the Step 6 audits: `<use>` nesting budget in + the sanitiser (today bounded by the rasterizer), the decoder memory + envelope of PNG logos (bounded by the 4096² cap, about 430 MB worst case + for four logos). diff --git a/docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md b/docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md index e6722ce0..635605d8 100644 --- a/docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md +++ b/docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md @@ -617,3 +617,376 @@ Definition of Done: no fetch and no DOM in `packages/pdf` (compile, lint, tests); T1–T15 green; Phase 0 goldens reproduced in both logo modes; demo envelope < 250 KB stored and raw; `docs/PDF-FORMAT.md` complete; v2 fixtures import and re-export; rebase alert shown when the draft changed. + +--- + +# Part II — Implementation contract (validated 2026-10-11) + +The user validated Part I on 2026-10-11 with three adjustments, recorded here +as the binding contract for the executors. Where Part I and Part II differ, +Part II wins. + +## 12. Validated adjustments + +- **D7 (branding).** The engine receives its branding explicitly and never + fetches. The archive **also stores the branding used at export** (logos, + partner credits, URLs, fallback texts) and the **label dictionary** (both + locales), so a future logo, wording or configuration change cannot alter + the reproduction of an old archive. Compact and safe representation, no + duplicated resource inside the envelope. Cost measured and reported. +- **D8 (imported snapshot).** The archive carried by an imported PDF is + **kept in the session**, immutable. Two operations are distinct in the + architecture: (1) re-read or re-export an archive from its own snapshot, + branding and labels, no rebase; (2) resume a bilan for editing on the + current sheet: an explicit rebase on a **working copy**, historical labels + of unresolvable items preserved. No new significant UI in this step: the + technical support (store, persistence, engine API) ships and the UX choice + for operation (1) is submitted to the user after the step. +- **D10, D12.** No change to the pages. No `report:reexport` CLI. +- **D13 (messages).** Explicit FR/EN messages for: an archive imported with + its snapshot; a snapshot rejected while the report was recovered; a rebase + with its count; a stripped attachment. A partial or degraded import is + never presented as a perfect restoration. +- **D1, D4, D6** as recommended in §9. + +## 13. Types (TypeScript, authoritative) + +All JSON contracts below are **camelCase**, like Report v3 and `SheetRef`; +the `AnatomicalSheetDocument` inside keeps its own snake_case schema. + +```ts +// packages/domain/src/archive/snapshot.ts +export interface SheetSnapshotRef { // sheet-ref.json, camelCase + sheetId: string; versionId: string | null; documentSha256: string /^[0-9a-f]{64}$/; + schemaVersion: number; speciesId: string; +} +export interface SheetSnapshotAsset { svgAssetId: string; sha256: string | null; svg: string } +export interface SheetSnapshot { + status: 'draft' | 'published'; + ref: SheetSnapshotRef; + document: AnatomicalSheetDocument; // lean, valid (schema v2, strict) + assets: SheetSnapshotAsset[]; +} +export const SheetSnapshotSchema: z.ZodType<SheetSnapshot> // strict + caps (§15) +export function buildSheetSnapshot(sheet: SnapshotSource, report: Report): SheetSnapshot +export interface SnapshotSource { // what LoadedSheet provides + status: 'draft' | 'published'; ref: SheetSnapshotRef; document: AnatomicalSheetDocument; + assets: Readonly<Record<string, string>>; // svg text by svgAssetId + assetHashes?: Readonly<Record<string, string>>; // sha256 by svgAssetId (seed manifest) +} +export function assertSnapshot(snapshot: SheetSnapshot): SheetSnapshot + // SheetSnapshotSchema.parse, validateSheetDocument(document) has no 'error' issue, + // every view resolves (own asset or parent chain) to an asset present in `assets`, + // document depth pre-check; throws SnapshotError(reason: SnapshotRejection) +export type SnapshotRejection = 'unsupported_envelope' | 'schema' | 'caps' | 'integrity' | 'sheet_mismatch' + +// packages/domain/src/archive/envelope.ts +export const ENVELOPE_FORMAT = 'faunosteo-report-archive' +export const ENVELOPE_VERSION = 1 +export interface ReportArchiveEnvelope { + format: typeof ENVELOPE_FORMAT; envelopeVersion: 1; + exportedAt: string; // ISO timestamp + locale: 'fr' | 'en'; + report: Report; // v3, as exported (never rebased) + sheetSnapshot: SheetSnapshot; + branding: Branding; + labels: PdfLabelSet; +} +export const ReportArchiveEnvelopeSchema: z.ZodType<ReportArchiveEnvelope> + // metadata object is NOT strict (unknown keys ignored within v1); report, sheetSnapshot, + // branding, labels are parsed by their own schemas +export type ArchiveOrigin = 'envelope_v1' | 'bare_v3' | 'v2' +export interface ArchiveReadOutcome { + report: Report; origin: ArchiveOrigin; migrated: boolean; + unresolvedZones: number; unresolvedFindings: number; // from the v2 migration + archive: ReportArchiveEnvelope | null; // the validated envelope, when accepted + snapshotRejected?: SnapshotRejection; // envelope present but snapshot dropped +} +export function readArchiveDocument(data: unknown, map: ReportMigrationMap): ArchiveReadOutcome + // throws UnsupportedReportVersionError (existing) when the REPORT version is unknown + +// packages/domain/src/archive/branding.ts +export type ImageAsset = { kind: 'png'; base64: string } | { kind: 'svg'; svg: string } +export interface Credit { logo: ImageAsset | null; url: string; fallbackText: string } +export interface Branding { + siteUrl: string; + headerLogo: ImageAsset | null; // today /assets/faunosteo_logo_horizontal-512.png + footerLogo: ImageAsset | null; // today /assets/faunosteo-horizontal-com-512.png + poweredBy: Credit | null; // today ZenQuality PNG, https://zenquality.fr, 'zenquality.fr' + partner: Credit | null; // today Paws SVG, instagram URL, '@paws.iin.harmony' +} +export const BrandingSchema: z.ZodType<Branding> // strict; base64 ≤ 512 KiB, svg ≤ 256 KiB, + // url http(s) only ≤ 2048, fallbackText ≤ 128 + +// packages/domain/src/archive/labels.ts +export const PDF_LABEL_KEYS = [ /* exactly the keys read by apps/app/src/pdf at HEAD: */ + 'pdf.empty','pdf.eyebrow.observation','pdf.eyebrow.synthesis','pdf.owner_prefix', + 'pdf.section.comment','pdf.section.conclusion','pdf.section.findings_prefix', + 'pdf.section.free_findings','pdf.section.next_appointment','pdf.section.recommendations', + 'pdf.section.severity','pdf.section.zones','pdf.siret_prefix','pdf.subject', + 'pdf.title.conclusion','pdf.title.suffix.bilan','pdf.view.detail_prefix','pdf.view.general', + 'severity.mild','severity.moderate','severity.severe','lateral.left','lateral.right', + 'footer.powered_by','footer.in_partnership' ] as const +export type PdfLabels = Record<(typeof PDF_LABEL_KEYS)[number], string> +export interface PdfLabelSet { fr: PdfLabels; en: PdfLabels } +export const PdfLabelSetSchema // strict, every key required, values ≤ 256 chars + +// packages/domain/src/report/rebase.ts +export interface RebaseOutcome { report: Report; unresolvedZones: number; unresolvedFindings: number; rebased: boolean } +export function rebaseReportOnSheet(report: Report, index: SheetIndex, archived: SheetSnapshot | null): RebaseOutcome + // rebased=false and report returned as is when report.sheet.documentSha256 === index.sheet.ref.documentSha256 + // else: zone with unknown annotationId or unknown viewId → unresolved: true, label snapshots + // filled from `archived` annotation names when absent; finding with no nodeAt(zoneId, path) + // → unresolved: true; items already unresolved stay; report.sheet = index.sheet.ref + +// packages/domain/src/anatomical-sheet/sheet-index.ts (moved from apps/app/src/services/sheetIndex.ts) +export interface SheetIndexSource { ref: SheetSnapshotRef-compatible { documentSha256 }; document: AnatomicalSheetDocument; assets: Readonly<Record<string,string>> } +export { buildSheetIndex, pickLabel, isObservable, type SheetIndex, type ObservableAnnotation } + // SheetIndex.sheet is typed as the source given; LoadedSheet satisfies it; SheetSnapshot does + // through a one-line adapter (assets array → record). `pickLabel` takes 'fr' | 'en'. + +// packages/pdf/src/index.ts +export type PdfLocale = 'fr' | 'en' +export type Rasterizer = (svg: string, size: { widthPx: number; heightPx: number }) => Promise<Uint8Array> +export interface ExportInput { + report: Report; sheet: SheetSnapshot; branding: Branding; labels: PdfLabelSet; + locale: PdfLocale; rasterizer: Rasterizer; exportedAt: Date; +} +export type ExportWarning = + | { kind: 'view_raster_failed'; observationId: string; viewId: string } + | { kind: 'logo_failed'; slot: 'headerLogo' | 'footerLogo' | 'poweredBy' | 'partner' } +export interface ExportResult { pdf: Uint8Array; envelope: ReportArchiveEnvelope; warnings: ExportWarning[] } +export function exportReportArchive(input: ExportInput): Promise<ExportResult> + // throws ArchiveExportError(kind: 'snapshot_invalid' | 'snapshot_too_large' | 'sheet_mismatch' | 'too_many_pages') +export function exportFromEnvelope(env: ReportArchiveEnvelope, opts: { locale: PdfLocale; rasterizer: Rasterizer; exportedAt: Date }): Promise<ExportResult> + // = exportReportArchive({ report: env.report, sheet: env.sheetSnapshot, branding: env.branding, labels: env.labels, ...opts }) +export type ArchiveReadErrorKind = 'invalid_pdf' | 'no_attachment' | 'attachment_stripped' | 'incompatible_version' +export class ArchiveReadError extends Error { kind: ArchiveReadErrorKind; foundVersion?: number | null } +export function readReportArchive(pdfBytes: Uint8Array, map: ReportMigrationMap): Promise<ArchiveReadOutcome> +export function readAttachedDocument(pdfDoc: PDFDocument): Promise<unknown> // raw JSON, for the compare CLI +export const MAX_PDF_BYTES, MAX_ATTACHMENT_BYTES +export const defaultPdfLabels: PdfLabelSet // verbatim copy of today's FR/EN strings +export const PDF_KEYWORD = 'faunosteo-archive/1' // Info.Keywords stamp +``` + +## 14. Behaviour + +**Export** (`exportReportArchive`): (1) `assertSnapshot(sheet)`; (2) refuse +when `report.sheet.documentSha256 !== sheet.ref.documentSha256` +(`sheet_mismatch`); (3) refuse `report.observations.length > 500` or any +observation with more than 8 distinct view ids (`too_many_pages`); (4) build +the envelope `{ format, envelopeVersion: 1, exportedAt, locale, report, +sheetSnapshot: sheet, branding, labels }`, serialise pretty (indent 2), refuse +above `MAX_ATTACHMENT_BYTES` (`snapshot_too_large`); (5) metadata: title, +author, subject (labels), creation and modification dates = `exportedAt`, +`setKeywords([PDF_KEYWORD])`; (6) fonts; (7) branding images: PNG → `embedPng` +(base64 decoded with `atob`), SVG → sanitise + rasterise at width 1200 px +(today's rule) → `embedPng`; each slot fails alone with a `logo_failed` +warning; (8) observation pages: rasterise every view of an observation in +parallel, then embed in view order (main first); a raster failure gives a +page without that image and a `view_raster_failed` warning; (9) conclusion +page, footer on every page, attach the envelope bytes as `osteo-report.json` +(`application/json`, description `Faunosteo report archive v1`, dates +`exportedAt`, `AFRelationship.Data`); (10) `save()`. + +**Label policy** (§3.1, unchanged wording): zone name = snapshot annotation +name by id (trigger: opened view's name), else report zone snapshot in the +locale (other locale as fallback), else the id; finding group heading = +snapshot finding-zone name by id, else the id upper-cased; finding text and +`(!)` from the report; views = unique view ids of the observation present in +the snapshot, main first; `unresolved` never consulted; every printed string +goes through `safeText` (§15). + +**View SVG** (`packages/pdf/src/svg/view.ts`): asset text refused if it +contains `<!DOCTYPE` or `<!ENTITY`; parsed with xmldom (`onError` throws on +`error` and `fatalError`); `sanitizeSvgRoot` (§15); `composeViewSvg` from +`@faunosteo/anatomy/render` with `highlight: { annotationIds, halo: +view.kind === 'main' }`; serialised; size = width 1200, height = round(1200 × +vbH / vbW) with the ratio clamped to [0.2, 2.0], view box = `view.view_box` +?? root `viewBox` ?? 0.6 ratio (today's fallback). + +**composeViewSvg** (`packages/anatomy/src/render/compose.ts`, promoted from +`curation/app-review.ts`, which now calls it with no highlight): +`({ root: Element, document, viewId, highlight?: { annotationIds: ReadonlySet<string>; halo: boolean } }) => Element`: +set `viewBox` from `viewBoxOf(view)` when present, remove `width`/`height`, +render the layer tree; with `highlight`: keep only layer elements whose +annotation id is selected, set `fill="#b85a3f"`, `fill-opacity="0.85"`, and +`filter="url(#osteo-halo)"` when `halo`, emit no `data-*` attribute, keep +`<title>`; when `halo`, ensure `<defs>` (created as first child when absent) +holds the `osteo-halo` filter exactly as `observationPage.ts:157-197` +(x/y −100%, width/height 300%, `filterUnits="userSpaceOnUse"`, blurs 18 and 8, +merge wide×3 + tight×2 + SourceGraphic); append the layer `<g>` last. + +**Read** (`readReportArchive`): size cap → `PDFDocument.load` (`invalid_pdf` +on failure) → attachment: the Filespec whose `/F` starts with `osteo-report`, +else the first `EmbeddedFile`, inflating `FlateDecode` streams under the cap +(`inflateFlate`, kept) → none: `attachment_stripped` when +`getKeywords()` contains `faunosteo-archive`, else `no_attachment` → cap → +`JSON.parse` → `readArchiveDocument(data, map)`: +1. locate the report: `data.report` when `typeof data.envelopeVersion === 'number'`, else `data`; +2. `readReportDocument(report, map)` (existing: v3 parsed, v2 migrated, other + → `UnsupportedReportVersionError(found)` → `incompatible_version`); +3. bare → `{ origin: 'bare_v3' | 'v2', archive: null }`; envelope with + `envelopeVersion !== 1` → `archive: null, snapshotRejected: 'unsupported_envelope'`; + envelope v1 → parse metadata + `sheetSnapshot` + `branding` + `labels`; + `BrandingSchema`/`PdfLabelSetSchema` failure → `'schema'`; + `assertSnapshot` failure → its reason; snapshot ref ≠ `report.sheet` → + `'sheet_mismatch'`; success → `archive` = the validated envelope. +Every other JSON failure → `no_attachment` as today. + +**App session** (`reportStore.ts`, `persistence.ts`): +- state `{ report: Report | null; archive: ReportArchiveEnvelope | null; activeObservationIndex }`; +- `hydrateReport(report)` kept (archive → null); new + `hydrateImport({ report, archive })`; `initReport` and `reset` clear `archive`; +- persistence: `osteo:draft` as today; `osteo:archive` written on + `hydrateImport`/`reset`/`initReport` only (not on every edit), restored with + the draft; `ArchivePersistence` beside `ReportPersistence`; +- `restoreDraft(index: SheetIndex)` loads the draft then rebases it on the + index when its sha differs (counts returned to the caller). +- `HomeRoute`: `readReportArchive` through `apps/app/src/pdf/import.ts` + (maps `ArchiveReadError` kinds to `ImportError` kinds, four kinds now) → + `rebaseReportOnSheet(outcome.report, index, outcome.archive?.sheetSnapshot ?? null)` + → `hydrateImport({ report: rebased, archive: outcome.archive })` → one + `window.alert` composed of the applicable lines (see §16) → `/editor`. +- `EditorRoute` export: `exportReportArchive({ report, sheet: buildSheetSnapshot(index.sheet, report), branding: await loadBranding(), labels: defaultPdfLabels, locale, rasterizer: browserRasterizer, exportedAt: new Date() })`; + download name unchanged; `warnings` logged with `console.warn`. +- The kept `archive` is exposed by the store for operation (1); no UI uses it + in this step (UX choice submitted after). + +**Branding in the app** (`apps/app/src/pdf/branding.ts`): `loadBranding(): +Promise<Branding>` fetches the four `public/` files by their current URLs +(each failure → slot `null` + `console.warn`, as today), PNG → base64, +Paws SVG kept as `{ kind: 'svg', svg }`; constants: `siteUrl +'https://faunosteo.com'`, poweredBy `{ url: 'https://zenquality.fr', +fallbackText: 'zenquality.fr' }`, partner `{ url: +'https://www.instagram.com/paws.iin.harmony', fallbackText: '@paws.iin.harmony' }`. +`// shortcut:` the site URL and partner constants live here until the config +carries them. + +**Bundle** (`vite/sheet-bundle.ts`, `sheets/provider.ts`): the payload gains +`assetHashes: Record<svg_asset_id, sha256>` from `assets.json`; `LoadedSheet` +gains `assetHashes`; `ref` gains `schemaVersion` and `speciesId` so it is a +`SheetSnapshotRef` (`SheetRef` of the report stays the 3-field subset). + +## 15. Caps, sanitiser, text + +| Item | Cap | +|---|---| +| PDF file | 50 MiB (existing) | +| attachment, raw and inflated | 16 MiB (existing) | +| snapshot assets | ≤ 4, each ≤ 2 MiB, total ≤ 6 MiB | +| snapshot document | ≤ 64 views, ≤ 1,024 annotations, ≤ 8,192 finding nodes, depth ≤ 8, labels ≤ 512 chars | +| branding | PNG base64 ≤ 512 KiB each, SVG ≤ 256 KiB, URLs http(s) ≤ 2,048 chars | +| report at export | ≤ 500 observations, ≤ 8 views per observation | +| sanitiser | ≤ 20,000 elements, nesting ≤ 64, ≤ 256 `<use>`, `stdDeviation` ≤ 100 | +| raster | width 1200 px, aspect clamped to [0.2, 2.0] | + +Sanitiser (`packages/pdf/src/svg/sanitize.ts`, `sanitizeSvgRoot(root: +Element): { removed: string[] }`, DOM Level 2 only: `childNodes`, +`attributes`, `removeAttribute`, `removeChild`, `tagName`): + +- elements kept: `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`; anything else is removed with its subtree (incl. `style`, + `script`, `image`, `a`, `foreignObject`, `text`, `feImage`, `feTurbulence`, + `feConvolveMatrix`, `animate*`, `set`); +- attributes kept: `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`; any other attribute (incl. every `on*`) is removed; +- `href`/`xlink:href` must match `^#[A-Za-z_][\w.:-]*$`; every `url(` in any + attribute value must be `url(#…)`; a `style` attribute containing `url(` + not followed by `#`, `expression(`, `@import`, `javascript:` or `behavior:` + is removed; `stdDeviation` above the cap is clamped; +- counters: elements, depth, `<use>`; over a cap → throws `SvgRejectedError`. +- `horse.svg` and `Paws_in_harmony.svg` must pass with `removed: []` and a + serialisation byte-identical to the parsed input (test). + +Text: `safeText(s: string): string` strips `\p{Cc}\p{Cf}

` except +none, then replaces every code point that +`Encodings.WinAnsi.canEncodeUnicodeCodePoint` (from +`@pdf-lib/standard-fonts`) refuses by `?`; used by `wrapLines`, every +`drawText` and `widthOfTextAtSize` in the engine; en and em dashes survive. +`formatDate` in the engine returns the input unchanged when it is not +`YYYY-MM-DD`. + +## 16. Messages (FR / EN keys, app dicts) + +| Key | FR | EN | +|---|---|---| +| `home.import.archive_ok` | Archive Faunosteo importée : bilan et instantané de la fiche d'origine conservés. | Faunosteo archive imported: report and the original sheet snapshot kept. | +| `home.import.snapshot_rejected` | Bilan récupéré, mais l'instantané de la fiche d'origine a été rejeté ({reason}) : cette archive ne pourra pas être reproduite telle quelle. | Report recovered, but the original sheet snapshot was rejected ({reason}): this archive cannot be reproduced as is. | +| `home.import.snapshot_reason.unsupported_envelope` | archive d'une version plus récente | archive from a newer version | +| `home.import.snapshot_reason.schema` | contenu invalide | invalid content | +| `home.import.snapshot_reason.caps` | taille ou complexité excessive | size or complexity over the limits | +| `home.import.snapshot_reason.integrity` | fiche incohérente | inconsistent sheet | +| `home.import.snapshot_reason.sheet_mismatch` | fiche différente de celle du bilan | sheet differs from the report's | +| `home.import.rebased` | Bilan ouvert sur la fiche actuelle, différente de celle de l'archive. Éléments non retrouvés : {count} (conservés avec leurs libellés). | Report opened on the current sheet, which differs from the archive's. Items not found: {count} (kept with their labels). | +| `home.import.error_attachment_stripped` | Ce PDF Faunosteo a perdu ses données embarquées (pièce jointe supprimée par un lecteur ou un optimiseur). Utilisez le fichier d'origine. | This Faunosteo PDF lost its embedded data (attachment removed by a viewer or an optimiser). Use the original file. | + +Alert composition after a successful import, lines joined by a blank line: +`migrated` (existing v2 message, when `origin === 'v2'` and counts > 0) · +`archive_ok` (when `archive` kept) · `snapshot_rejected` (when +`snapshotRejected`) · `rebased` (whenever the rebase ran, count may be 0). +No alert when nothing applies (bare v3 on the same sheet, as today). + +## 17. Goldens (Phase 0, frozen with the current code) + +Files under `apps/app/tests/fixtures/goldens/step6/`, JSON, numbers rounded +to 2 decimals, generated once by a `MAKE_GOLDEN=1` run of the golden test +file itself (`pdf.goldens.test.ts`: in generation mode it writes, otherwise it +asserts), and never regenerated without a user decision. + +- `text.<report>.<locale>.<logos>.json`: ordered `{ page, text, x, y, size, font }` + from a `PDFPage.prototype.drawText` spy (page = index of `this` in + `pdfDoc.getPages()` after save; font = `options.font.name`). +- `images.<report>.<logos>.json`: ordered `{ page, x, y, width, height }` from + a `drawImage` spy. +- `links.<report>.<logos>.json`: `{ page, rect, uri }` of every `/Annot /Link` + read back from the saved PDF. +- `views.<report>.json`: per `(observationId, viewId)`: `{ viewBox, halo, + highlighted: [{ tag, cx, cy, r, points, d, fill, fillOpacity, filter }], + nonHighlightedVisible: 0, dataAttributes: 0, titles }` from + `highlightedViewSvg` parsed with `DOMParser` (hidden markers are + `display="none"` today and absent in the engine: both count as not visible). +- Reports: `v2full` (migrated `report-v2.full.json`), `demo` + (`report-v3.demo.json`, new fixture: 6 observations covering main and head + views, vertebrae, bilateral sides, a vet-referral leaf, a leaf whose label + holds an en dash, free text, severity, next appointment), `v2unresolved` + (built with `tests/helpers/legacyLeaves.ts`: one observation per unresolved + leaf family, sphenoid and ssb, plus one resolved leaf). +- Logo modes: `nologos` (fetch 404) and `logos` (fetch stub serving the real + bytes of the four `public/` files; `rasterizeSvg` mocked to a fixed 2×1 PNG + so the partner logo width is deterministic). +- `report-v3.bare.pdf`: the demo report exported by the current code + (`nologos`), import fixture only. + +Characterisation tests written in Phase 0 and kept green unchanged: +`routes.HomeRoute.import.test.tsx` (v2 alert with count, four error kinds to +messages, navigation; `importReportFromPdf` mocked) and +`routes.EditorRoute.export.test.tsx` (export called with report, index and +locale; download name `bilan-<animal>-<date>.pdf`; failure alert). Phase 4 +adapts only the mocked module path and the call-shape assertion of T13 to the +engine API, nothing else. + +## 18. Executors and phases + +One executor per phase, closed contract in `.claude/tasks/contracts/`, TDD, +no commit (the orchestrator commits), report with test counts. Phases 1 and 2 +run in parallel. Verifier and security gates after Phase 5 and on request. + +| Phase | Owner | Exit | +|---|---|---| +| 0 freeze | executor | goldens + fixtures + T12/T13 committed, app suite green | +| 1 domain | executor | archive/{snapshot,envelope,branding,labels}, sheet-index moved, rebase, bundle hashes; domain + app suites green | +| 2 anatomy | executor | compose.ts, review drawing golden unchanged; anatomy suite green | +| 3 engine | executor | packages/pdf complete, T1 T3–T11 green, xmldom bundle size measured | +| 4 app | executor | routes, store, persistence, branding, messages; T2 T12–T15 green; old code removed | +| 5 docs + gates | orchestrator + verifier + security | docs, check, docker, EVAL | diff --git a/docs/development/WORKSPACE.md b/docs/development/WORKSPACE.md index e9ae2b32..f73196fa 100644 --- a/docs/development/WORKSPACE.md +++ b/docs/development/WORKSPACE.md @@ -90,8 +90,9 @@ Package-scoped: `pnpm --filter @faunosteo/app <script>`. ## 5. Conventions -- A package has `name` `@faunosteo/<name>`, `private: true` for apps, its own - `tsconfig.json`, tests under `tests/` (apps) or beside sources (packages). +- A package has `name` `@faunosteo/<name>`, `private: true`, its own standalone + `tsconfig.json` (no root tsconfig), tests under `tests/` (apps and packages + alike), `vitest` in `node` environment for packages. - Dependencies are declared where they are used (`apps/app/package.json`); the root holds only repository tooling (Prettier, pnpm). - Build scripts of dependencies run only for packages listed in diff --git a/packages/README.md b/packages/README.md index 96f5fd0d..527ad1b9 100644 --- a/packages/README.md +++ b/packages/README.md @@ -10,7 +10,7 @@ Planned packages and the step that creates each one: |---|---|---| | `@faunosteo/domain` | Zod schemas: anatomical sheet document + integrity rules (**created**, Step 4); report document, entitlement capabilities later | Step 4 (sheet model) | | `@faunosteo/anatomy` | legacy importer (**created**, Step 4b), curation pipeline: changeset → working draft + report migration map (**created**, Steps 4c/5), pure annotation-layer renderer `@faunosteo/anatomy/render` shared with the app (**created**, Step 5) | Step 4b (importer) | -| `@faunosteo/pdf` | export / import / attachment, render helpers | Step 6 (PDF v3) | +| `@faunosteo/pdf` | browser-free PDF engine (**created**, Step 6): report archive export from explicit inputs (report, sheet snapshot, branding, labels, rasterizer), layered archive reading, SVG sanitiser, page renderers | Step 6 (PDF archives) | | `@faunosteo/i18n` | FR/EN dictionaries (no React) + `useT` | first second consumer (public-web or worker) | | `@faunosteo/supabase` | browser client factory, generated database types, PGlite harness running the pgTAP suite, sheet publish gate | **created**, Step 3 | | `@faunosteo/config` | runtime config resolution shared by app, public-web, worker | with public-web | diff --git a/packages/anatomy/src/curation/app-review.ts b/packages/anatomy/src/curation/app-review.ts index 7ff13708..e979301b 100644 --- a/packages/anatomy/src/curation/app-review.ts +++ b/packages/anatomy/src/curation/app-review.ts @@ -1,14 +1,14 @@ import { DOMParser, XMLSerializer } from '@xmldom/xmldom' import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain' -import { createLayerElement } from '../render/dom' -import { renderAnnotationLayer, viewBoxOf } from '../render/layer' +import { composeViewSvg } from '../render/compose' /** * The drawing of one view exactly as the application renders it: the * cleaned asset framed on the view's box plus the annotation layer the app * generates from the document. Written under draft/review/app-<view>.svg * so the markers and the framing can be compared with the legacy files - * before and after a change, outside the browser. + * before and after a change, outside the browser. Parse and serialise + * here; the composition itself is the shared `composeViewSvg`. */ export interface AppReviewInput { @@ -21,16 +21,6 @@ export function renderAppReviewDrawing(input: AppReviewInput): string { const doc = new DOMParser().parseFromString(input.cleanedSvg, 'image/svg+xml') const root = doc.documentElement if (!root || root.tagName !== 'svg') throw new Error('not an SVG document') - const view = input.document.views.find((v) => v.id === input.viewId) - if (!view) throw new Error(`unknown view "${input.viewId}"`) - const box = viewBoxOf(view) - if (box) root.setAttribute('viewBox', box) - root.removeAttribute('width') - root.removeAttribute('height') - const layer = renderAnnotationLayer({ - document: input.document, - viewId: view.id, - }) - root.appendChild(createLayerElement(doc, layer) as never) + composeViewSvg({ root, document: input.document, viewId: input.viewId }) return new XMLSerializer().serializeToString(doc) } diff --git a/packages/anatomy/src/render/compose.ts b/packages/anatomy/src/render/compose.ts new file mode 100644 index 00000000..482e5dd5 --- /dev/null +++ b/packages/anatomy/src/render/compose.ts @@ -0,0 +1,196 @@ +import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain' +import { + createLayerElement, + SVG_NS, + type MinimalDocument, + type MinimalElement, + type MinimalNode, +} from './dom' +import { renderAnnotationLayer, viewBoxOf, type LayerElement } from './layer' + +/** + * Composes the drawing of one view: the parsed asset framed on the view's + * box plus the annotation layer rendered from the document. With a + * `highlight`, the layer keeps only the selected annotations, styled for + * print (legacy picture: accent fill, halo on the main view, no data + * attributes). Works on any DOM Level 2 implementation (a Node parser or + * the browser DOM): the caller parses and serialises. + */ + +export const HALO_FILTER_ID = 'osteo-halo' +export const HIGHLIGHT_FILL = '#b85a3f' +export const HIGHLIGHT_FILL_OPACITY = '0.85' + +/** DOM Level 2 surface the composer needs on the `<svg>` root. */ +export interface ComposeElement extends MinimalElement { + readonly ownerDocument: MinimalDocument | null + readonly firstChild: MinimalNode | null + getAttribute(name: string): string | null + removeAttribute(name: string): void + insertBefore(node: MinimalNode, reference: MinimalNode | null): unknown + getElementsByTagName(tag: string): ComposeElementList +} + +export interface ComposeElementList { + readonly length: number + item(index: number): ComposeElement | null +} + +export interface ComposeHighlight { + /** Annotation ids kept on the layer; every other marker is dropped. */ + annotationIds: ReadonlySet<string> + /** Wrap the kept markers in the `osteo-halo` filter (main view). */ + halo: boolean +} + +export interface ComposeInput<Root extends ComposeElement = ComposeElement> { + root: Root + document: AnatomicalSheetDocumentInput + viewId: string + highlight?: ComposeHighlight +} + +/** Frames `root` on the view, appends the layer `<g>` last, returns `root`. */ +export function composeViewSvg<Root extends ComposeElement>( + input: ComposeInput<Root>, +): Root { + const { root, document, viewId, highlight } = input + const view = document.views.find((v) => v.id === viewId) + if (!view) throw new Error(`unknown view "${viewId}"`) + const box = viewBoxOf(view) + if (box) root.setAttribute('viewBox', box) + root.removeAttribute('width') + root.removeAttribute('height') + if (highlight?.halo) ensureHaloFilter(root) + const rendered = renderAnnotationLayer({ document, viewId }) + const layer = highlight ? highlightLayer(rendered, highlight) : rendered + root.appendChild(createLayerElement(documentOf(root), layer)) + return root +} + +/** Typed nullable by the DOM; an element taken from a parsed document has one. */ +function documentOf(root: ComposeElement): MinimalDocument { + if (!root.ownerDocument) throw new Error('root has no owner document') + return root.ownerDocument +} + +/** + * The layer reduced to the selected annotations (both elements of a point), + * each with the accent fill and, when asked, the halo filter. No `data-*` + * attribute survives: the result is a picture, not an interactive layer. + */ +export function highlightLayer( + layer: LayerElement, + highlight: ComposeHighlight, +): LayerElement { + const children = layer.children + .filter((child) => + highlight.annotationIds.has(child.attrs['data-anno-id'] ?? ''), + ) + .map((child) => highlightElement(child, highlight.halo)) + return { ...layer, attrs: withoutDataAttrs(layer.attrs), children } +} + +function highlightElement(node: LayerElement, halo: boolean): LayerElement { + const attrs: Record<string, string> = { + ...withoutDataAttrs(node.attrs), + fill: HIGHLIGHT_FILL, + 'fill-opacity': HIGHLIGHT_FILL_OPACITY, + } + if (halo) attrs.filter = `url(#${HALO_FILTER_ID})` + return { ...node, attrs } +} + +function withoutDataAttrs( + attrs: Record<string, string>, +): Record<string, string> { + return Object.fromEntries( + Object.entries(attrs).filter(([name]) => !name.startsWith('data-')), + ) +} + +/** + * Adds the Gaussian-blur "halo" filter so the highlighted markers stay + * visible on the whole-animal view once rasterised at print scale. One + * filter per root: a second call finds it and leaves the tree alone. + */ +function ensureHaloFilter(root: ComposeElement): void { + if (hasElementWithId(root, 'filter', HALO_FILTER_ID)) return + const defs = root.getElementsByTagName('defs').item(0) ?? createDefs(root) + defs.appendChild(haloFilter(documentOf(root))) +} + +function hasElementWithId( + root: ComposeElement, + tag: string, + id: string, +): boolean { + const list = root.getElementsByTagName(tag) + for (let i = 0; i < list.length; i++) { + if (list.item(i)?.getAttribute('id') === id) return true + } + return false +} + +/** `<defs>` as the first child: the asset's own filters sit at the root. */ +function createDefs(root: ComposeElement): MinimalElement { + const defs = documentOf(root).createElementNS(SVG_NS, 'defs') + root.insertBefore(defs, root.firstChild) + return defs +} + +function svgElement( + doc: MinimalDocument, + tag: string, + attrs: Record<string, string>, +): MinimalElement { + const element = doc.createElementNS(SVG_NS, tag) + for (const [name, value] of Object.entries(attrs)) { + element.setAttribute(name, value) + } + return element +} + +function haloFilter(doc: MinimalDocument): MinimalElement { + const filter = svgElement(doc, 'filter', { + id: HALO_FILTER_ID, + x: '-100%', + y: '-100%', + width: '300%', + height: '300%', + filterUnits: 'userSpaceOnUse', + }) + filter.appendChild(gaussianBlur(doc, '18', 'haloWide')) + filter.appendChild(gaussianBlur(doc, '8', 'haloTight')) + filter.appendChild(haloMerge(doc)) + return filter +} + +function gaussianBlur( + doc: MinimalDocument, + stdDeviation: string, + result: string, +): MinimalElement { + return svgElement(doc, 'feGaussianBlur', { + in: 'SourceGraphic', + stdDeviation, + result, + }) +} + +/** Three wide blurs, two tight ones, then the marker itself on top. */ +function haloMerge(doc: MinimalDocument): MinimalElement { + const merge = svgElement(doc, 'feMerge', {}) + const inputs = [ + 'haloWide', + 'haloWide', + 'haloWide', + 'haloTight', + 'haloTight', + 'SourceGraphic', + ] + for (const input of inputs) { + merge.appendChild(svgElement(doc, 'feMergeNode', { in: input })) + } + return merge +} diff --git a/packages/anatomy/src/render/index.ts b/packages/anatomy/src/render/index.ts index 96b61d67..001c708e 100644 --- a/packages/anatomy/src/render/index.ts +++ b/packages/anatomy/src/render/index.ts @@ -20,3 +20,14 @@ export { type MinimalNode, } from './dom' export { serializeLayer } from './serialize' +export { + composeViewSvg, + HALO_FILTER_ID, + HIGHLIGHT_FILL, + HIGHLIGHT_FILL_OPACITY, + highlightLayer, + type ComposeElement, + type ComposeElementList, + type ComposeHighlight, + type ComposeInput, +} from './compose' diff --git a/packages/anatomy/tests/render.compose.test.ts b/packages/anatomy/tests/render.compose.test.ts new file mode 100644 index 00000000..d875556c --- /dev/null +++ b/packages/anatomy/tests/render.compose.test.ts @@ -0,0 +1,230 @@ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { DOMParser, XMLSerializer, type Element } from '@xmldom/xmldom' +import { beforeAll, describe, expect, it } from 'vitest' +import { + composeViewSvg, + EQUINE_DRAFT_DIR, + HALO_FILTER_ID, + highlightLayer, + renderAnnotationLayer, + renderAppReviewDrawing, + type DraftResult, + type LayerElement, +} from '../src' +import { REPO_ROOT, runDraft } from './helpers' + +const draftDir = join(REPO_ROOT, EQUINE_DRAFT_DIR) +const HALO_FILTER_MARKUP = + `<defs><filter id="${HALO_FILTER_ID}" x="-100%" y="-100%" width="300%" ` + + 'height="300%" filterUnits="userSpaceOnUse">' + + '<feGaussianBlur in="SourceGraphic" stdDeviation="18" result="haloWide"/>' + + '<feGaussianBlur in="SourceGraphic" stdDeviation="8" result="haloTight"/>' + + '<feMerge><feMergeNode in="haloWide"/><feMergeNode in="haloWide"/>' + + '<feMergeNode in="haloWide"/><feMergeNode in="haloTight"/>' + + '<feMergeNode in="haloTight"/><feMergeNode in="SourceGraphic"/>' + + '</feMerge></filter></defs>' + +let draft: DraftResult +let horseSvg: string + +/** The committed cleaned drawing, parsed fresh for every test. */ +function parseHorse(): Element { + const doc = new DOMParser().parseFromString(horseSvg, 'image/svg+xml') + return doc.documentElement! +} + +function serialize(root: Element): string { + return new XMLSerializer().serializeToString(root.ownerDocument!) +} + +function elements(list: { length: number; item(i: number): Element | null }) { + return Array.from({ length: list.length }, (_, i) => list.item(i)!) +} + +/** Element children of the layer `<g>`, the last child of the root. */ +function layerChildren(root: Element): Element[] { + const layer = root.lastChild as Element + expect(layer.nodeName).toBe('g') + return elements(layer.childNodes as never).filter((n) => n.nodeType === 1) +} + +function dataAttributeCount(root: Element): number { + return (serialize(root).match(/ data-[a-z-]+="/g) ?? []).length +} + +beforeAll(async () => { + ;({ draft } = await runDraft()) + const [asset] = draft.assets + horseSvg = await readFile(join(draftDir, 'assets', asset!.file), 'utf8') +}) + +describe('composeViewSvg with a highlight', () => { + it('keeps both elements of a selected point and the selected spine zone, haloed on the main view', () => { + const root = composeViewSvg({ + root: parseHorse(), + document: draft.document, + viewId: 'main', + highlight: { annotationIds: new Set(['hip', 'cervical']), halo: true }, + }) + const kept = layerChildren(root) + expect(kept.map((e) => e.nodeName)).toEqual(['circle', 'circle', 'polygon']) + for (const element of kept) { + expect(element.getAttribute('fill')).toBe('#b85a3f') + expect(element.getAttribute('fill-opacity')).toBe('0.85') + expect(element.getAttribute('filter')).toBe(`url(#${HALO_FILTER_ID})`) + } + expect(kept[0]!.getAttribute('r')).toBe('34') + expect(kept[1]!.getAttribute('r')).toBe('22') + expect(root.getAttribute('viewBox')).toBe('0 0 2073.4 1629.4') + expect(root.hasAttribute('width')).toBe(false) + expect(root.hasAttribute('height')).toBe(false) + }) + + it('creates <defs> as the first child of an asset without one and fills it with the halo filter', () => { + const root = composeViewSvg({ + root: parseHorse(), + document: draft.document, + viewId: 'main', + highlight: { annotationIds: new Set(['hip']), halo: true }, + }) + expect(root.firstChild!.nodeName).toBe('defs') + expect(root.getElementsByTagName('defs')).toHaveLength(1) + expect(serialize(root)).toContain(HALO_FILTER_MARKUP) + }) + + it('never duplicates the filter on a root that already holds it', () => { + const root = parseHorse() + const input = { + root, + document: draft.document, + viewId: 'main', + highlight: { annotationIds: new Set(['hip']), halo: true }, + } + composeViewSvg(input) + composeViewSvg(input) + const filters = elements(root.getElementsByTagName('filter')).filter( + (f) => f.getAttribute('id') === HALO_FILTER_ID, + ) + expect(filters).toHaveLength(1) + expect(root.getElementsByTagName('defs')).toHaveLength(1) + }) + + it('frames the head view on its view box without any halo', () => { + const root = composeViewSvg({ + root: parseHorse(), + document: draft.document, + viewId: 'head', + highlight: { annotationIds: new Set(['parietal']), halo: false }, + }) + expect(root.getAttribute('viewBox')).toBe('60 100 500 380') + expect(root.getElementsByTagName('defs')).toHaveLength(0) + expect(serialize(root)).not.toContain(HALO_FILTER_ID) + const kept = layerChildren(root) + expect(kept.map((e) => e.nodeName)).toEqual(['circle', 'circle']) + for (const element of kept) { + expect(element.getAttribute('fill')).toBe('#b85a3f') + expect(element.hasAttribute('filter')).toBe(false) + } + }) + + it('leaves an empty layer when nothing is selected', () => { + const root = composeViewSvg({ + root: parseHorse(), + document: draft.document, + viewId: 'main', + highlight: { annotationIds: new Set(), halo: true }, + }) + expect(layerChildren(root)).toHaveLength(0) + }) + + it('keeps the <title> of every kept marker and emits no data attribute', () => { + const root = composeViewSvg({ + root: parseHorse(), + document: draft.document, + viewId: 'main', + highlight: { annotationIds: new Set(['hip', 'cervical']), halo: true }, + }) + const titles = elements(root.lastChild!.childNodes as never) + .filter((n) => n.nodeType === 1) + .map((e) => e.getElementsByTagName('title').item(0)!.textContent) + expect(titles).toEqual([ + 'Hanche (coxo-fémorale) / Hip joint', + 'Hanche (coxo-fémorale) / Hip joint', + 'Vertèbres cervicales / Cervical vertebrae', + ]) + expect(dataAttributeCount(root)).toBe(0) + }) + + it('refuses an unknown view', () => { + expect(() => + composeViewSvg({ + root: parseHorse(), + document: draft.document, + viewId: 'nope', + highlight: { annotationIds: new Set(), halo: false }, + }), + ).toThrow('unknown view') + }) +}) + +describe('highlightLayer on the layer tree', () => { + function flatten(node: LayerElement): LayerElement[] { + return [node, ...node.children.flatMap(flatten)] + } + + it('filters, restyles and strips data attributes without touching the input', () => { + const layer = renderAnnotationLayer({ + document: draft.document, + viewId: 'main', + }) + const before = JSON.stringify(layer) + const highlighted = highlightLayer(layer, { + annotationIds: new Set(['cervical']), + halo: false, + }) + expect(JSON.stringify(layer)).toBe(before) + expect(highlighted.children).toHaveLength(1) + expect(highlighted.children[0]!.attrs).toMatchObject({ + fill: '#b85a3f', + 'fill-opacity': '0.85', + 'stroke-width': '2', + }) + expect(highlighted.children[0]!.attrs.filter).toBeUndefined() + const dataKeys = flatten(highlighted).flatMap((n) => + Object.keys(n.attrs).filter((k) => k.startsWith('data-')), + ) + expect(dataKeys).toEqual([]) + }) +}) + +describe('composeViewSvg without a highlight (review drawings)', () => { + it.each(['main', 'head'])( + 'renderAppReviewDrawing(%s) equals the committed review drawing', + async (viewId) => { + const committed = await readFile( + join(draftDir, 'review', `app-${viewId}.svg`), + 'utf8', + ) + const rendered = renderAppReviewDrawing({ + cleanedSvg: horseSvg, + document: draft.document, + viewId, + }) + expect(rendered).toBe(committed) + }, + ) + + it('keeps the full interactive layer with its data attributes', () => { + const root = composeViewSvg({ + root: parseHorse(), + document: draft.document, + viewId: 'main', + }) + expect(root.getElementsByTagName('defs')).toHaveLength(0) + expect((root.lastChild as Element).getAttribute('data-layer')).toBe( + 'annotations', + ) + expect(dataAttributeCount(root)).toBeGreaterThan(0) + }) +}) diff --git a/packages/domain/package.json b/packages/domain/package.json index 187daae2..0fda4db0 100644 --- a/packages/domain/package.json +++ b/packages/domain/package.json @@ -10,7 +10,8 @@ "exports": { ".": "./src/index.ts", "./anatomical-sheet": "./src/anatomical-sheet/index.ts", - "./report": "./src/report/index.ts" + "./report": "./src/report/index.ts", + "./archive": "./src/archive/index.ts" }, "scripts": { "typecheck": "tsc -p tsconfig.json --noEmit", diff --git a/packages/domain/src/anatomical-sheet/index.ts b/packages/domain/src/anatomical-sheet/index.ts index 0e850af9..c0c1d0e6 100644 --- a/packages/domain/src/anatomical-sheet/index.ts +++ b/packages/domain/src/anatomical-sheet/index.ts @@ -1,3 +1,4 @@ export * from './schema' export * from './validate' export * from './create' +export * from './sheet-index' diff --git a/packages/domain/src/anatomical-sheet/sheet-index.ts b/packages/domain/src/anatomical-sheet/sheet-index.ts new file mode 100644 index 00000000..5fa2fdd0 --- /dev/null +++ b/packages/domain/src/anatomical-sheet/sheet-index.ts @@ -0,0 +1,127 @@ +import type { + AnatomicalSheetDocument, + Annotation, + FindingCategory, + FindingNode, + FindingZone, + LocalizedText, + SheetView, + VertebralRegion, +} from './schema' + +/** + * Read-only lookups over a sheet document. Everything the editor and the + * PDF engine derive from the sheet (zone names, finding paths, spine + * regions, trigger targets) comes from the document here, by stable id: + * no label drives logic. The index keeps the source it was built from so a + * caller gets back exactly what it passed (a loaded sheet with its migration + * map, or an archived snapshot). + */ + +/** The minimum a sheet source carries: provenance, document, SVG text by asset id. */ +export interface SheetIndexSource { + ref: { documentSha256: string } + document: AnatomicalSheetDocument + assets: Readonly<Record<string, string>> +} + +export type ObservableAnnotation = Extract< + Annotation, + { kind: 'point' | 'zone' } +> + +export interface SheetIndex<S extends SheetIndexSource = SheetIndexSource> { + sheet: S + mainView: SheetView + view(id: string): SheetView | undefined + annotation(id: string): Annotation | undefined + annotationsOfView(viewId: string): Annotation[] + findingZone(id: string): FindingZone | undefined + /** The category or node at a path, undefined when absent from the sheet. */ + nodeAt( + zoneId: string, + path: readonly string[], + ): FindingCategory | FindingNode | undefined + regions(): VertebralRegion[] + region(code: string): VertebralRegion | undefined + /** The annotation that opens the vertebra picker for a region on a view. */ + spineAnnotation( + regionCode: string, + viewId: string, + ): ObservableAnnotation | undefined + /** Whether an annotation opens the vertebra picker. */ + isSpine(annotationId: string): boolean + name(annotation: Annotation): LocalizedText +} + +/** The label in a locale, the other locale as fallback, '' when none. */ +export function pickLabel( + text: LocalizedText | null | undefined, + locale: 'fr' | 'en', +): string { + if (!text) return '' + return locale === 'en' ? text.en || text.fr : text.fr || text.en +} + +export function isObservable( + a: Annotation | undefined, +): a is ObservableAnnotation { + return a !== undefined && a.kind !== 'detail_trigger' +} + +function nodeAtPath( + zone: FindingZone | undefined, + path: readonly string[], +): FindingCategory | FindingNode | undefined { + if (!zone || path.length === 0) return undefined + let node: FindingCategory | FindingNode | undefined = zone.categories.find( + (c) => c.id === path[0], + ) + for (const segment of path.slice(1)) { + if (!node) return undefined + node = node.children.find((n) => n.id === segment) + } + return node +} + +export function buildSheetIndex<S extends SheetIndexSource>( + sheet: S, +): SheetIndex<S> { + const { document } = sheet + const views = new Map(document.views.map((v) => [v.id, v])) + const annotations = new Map(document.annotations.map((a) => [a.id, a])) + const zones = new Map(document.finding_zones.map((z) => [z.id, z])) + const regions = new Map( + document.vertebral_config.regions.map((r) => [r.code, r]), + ) + const mainView = document.views.find((v) => v.kind === 'main') + if (!mainView) throw new Error('sheet has no main view') + + return { + sheet, + mainView, + view: (id) => views.get(id), + annotation: (id) => annotations.get(id), + annotationsOfView: (viewId) => + document.annotations.filter((a) => a.view_id === viewId), + findingZone: (id) => zones.get(id), + nodeAt: (zoneId, path) => nodeAtPath(zones.get(zoneId), path), + regions: () => document.vertebral_config.regions, + region: (code) => regions.get(code), + spineAnnotation: (code, viewId) => + document.annotations.find( + (a): a is ObservableAnnotation => + isObservable(a) && + a.view_id === viewId && + a.vertebral_region_code === code, + ), + isSpine: (id) => { + const a = annotations.get(id) + return isObservable(a) && a.vertebral_region_code !== null + }, + name: (a) => + a.kind === 'detail_trigger' + ? (a.name ?? views.get(a.opens_view_id)?.name ?? { fr: '', en: '' }) + : a.name, + } +} diff --git a/packages/domain/src/archive/branding.ts b/packages/domain/src/archive/branding.ts new file mode 100644 index 00000000..52b03f00 --- /dev/null +++ b/packages/domain/src/archive/branding.ts @@ -0,0 +1,59 @@ +import { z } from 'zod' + +/** + * The visual identity a PDF archive embeds so a re-export needs no network + * and no `public/` folder (STEP6 §3.4): logos as PNG base64 or SVG text, + * credits with the URL and the text printed when the logo fails. Caps are + * STEP6 §15 (branding row). + */ + +const KIB = 1024 +const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/ + +/** + * `http(s)://` then printable ASCII without `"`, `'`, `(`, `)`, `<`, `>` + * or `\`: the URL is written into PDF link actions and must never be able + * to close a string literal or carry a control character. Expressed as the + * allowed ranges of printable ASCII (0x21-0x7e) minus those seven. + */ +const HTTP_URL_PATTERN = /^https?:\/\/[!#-&*-;=?-[\]-~]+$/ + +const HttpUrlSchema = z + .string() + .max(2048) + .url() + .regex(HTTP_URL_PATTERN, 'http(s) URL expected') + +export const ImageAssetSchema = z.discriminatedUnion('kind', [ + z + .object({ + kind: z.literal('png'), + base64: z + .string() + .max(512 * KIB) + .regex(BASE64_PATTERN), + }) + .strict(), + z.object({ kind: z.literal('svg'), svg: z.string().max(256 * KIB) }).strict(), +]) +export type ImageAsset = z.infer<typeof ImageAssetSchema> + +export const CreditSchema = z + .object({ + logo: ImageAssetSchema.nullable(), + url: HttpUrlSchema, + fallbackText: z.string().max(128), + }) + .strict() +export type Credit = z.infer<typeof CreditSchema> + +export const BrandingSchema = z + .object({ + siteUrl: HttpUrlSchema, + headerLogo: ImageAssetSchema.nullable(), + footerLogo: ImageAssetSchema.nullable(), + poweredBy: CreditSchema.nullable(), + partner: CreditSchema.nullable(), + }) + .strict() +export type Branding = z.infer<typeof BrandingSchema> diff --git a/packages/domain/src/archive/envelope.ts b/packages/domain/src/archive/envelope.ts new file mode 100644 index 00000000..d2265ddd --- /dev/null +++ b/packages/domain/src/archive/envelope.ts @@ -0,0 +1,172 @@ +import { z } from 'zod' +import { readReportDocument } from '../report/migrate' +import type { ReportMigrationMap } from '../report/migration-map' +import { REPORT_VERSION, ReportSchema, type Report } from '../report/v3' +import { BrandingSchema, type Branding } from './branding' +import { PdfLabelSetSchema, type PdfLabelSet } from './labels' +import { + SheetSnapshotSchema, + SnapshotError, + assertSnapshot, + type SheetSnapshot, + type SnapshotRejection, +} from './snapshot' + +/** + * Attachment of a Step 6 PDF: the report (v3, unchanged) wrapped with the + * sheet snapshot, the branding and the PDF labels it was printed with + * (STEP6 §2.3). Reading is layered (§4, §14 "Read"): the report is located + * and parsed first so it is never lost because of its wrapper; the wrapper + * is then validated or dropped with a reason. + */ + +export const ENVELOPE_FORMAT = 'faunosteo-report-archive' +export const ENVELOPE_VERSION = 1 + +export interface ReportArchiveEnvelope { + format: typeof ENVELOPE_FORMAT + envelopeVersion: typeof ENVELOPE_VERSION + /** ISO timestamp of the export. */ + exportedAt: string + locale: 'fr' | 'en' + /** As exported, never rebased. */ + report: Report + sheetSnapshot: SheetSnapshot + branding: Branding + labels: PdfLabelSet +} + +/** Metadata is not strict: an additive v1 field never breaks an older reader. */ +const EnvelopeMetadataSchema = z.object({ + format: z.literal(ENVELOPE_FORMAT), + envelopeVersion: z.literal(ENVELOPE_VERSION), + exportedAt: z.string(), + locale: z.enum(['fr', 'en']), +}) + +/** Everything but the report and the snapshot, which the reader checks itself. */ +const EnvelopeWrapperSchema = EnvelopeMetadataSchema.extend({ + branding: BrandingSchema, + labels: PdfLabelSetSchema, +}) + +export const ReportArchiveEnvelopeSchema: z.ZodType< + ReportArchiveEnvelope, + z.ZodTypeDef, + unknown +> = EnvelopeWrapperSchema.extend({ + report: ReportSchema, + sheetSnapshot: SheetSnapshotSchema, +}) + +export type ArchiveOrigin = 'envelope_v1' | 'bare_v3' | 'v2' + +export interface ArchiveReadOutcome { + report: Report + origin: ArchiveOrigin + migrated: boolean + /** From the v2 migration; 0 for a v3 report. */ + unresolvedZones: number + unresolvedFindings: number + /** The validated envelope, when accepted. */ + archive: ReportArchiveEnvelope | null + /** Envelope present but its snapshot dropped. */ + snapshotRejected?: SnapshotRejection +} + +type Wrapped = + | { archive: ReportArchiveEnvelope } + | { snapshotRejected: SnapshotRejection } + +function isRecord(value: unknown): value is Record<string, unknown> { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +/** An envelope of any version is recognised by a numeric envelopeVersion. */ +function envelopeVersionOf(data: unknown): number | null { + if (!isRecord(data)) return null + const version = data.envelopeVersion + return typeof version === 'number' ? version : null +} + +function reportVersionOf(data: unknown): number | null { + if (!isRecord(data)) return null + return typeof data.version === 'number' ? data.version : null +} + +function snapshotMatches(snapshot: SheetSnapshot, report: Report): boolean { + return ( + snapshot.ref.sheetId === report.sheet.sheetId && + snapshot.ref.documentSha256 === report.sheet.documentSha256 + ) +} + +/** Step 3 for a v1 envelope: wrapper schema → snapshot gate → sheet invariant. */ +function readEnvelopeV1( + data: Record<string, unknown>, + report: Report, +): Wrapped { + const wrapper = EnvelopeWrapperSchema.safeParse(data) + if (!wrapper.success) return { snapshotRejected: 'schema' } + let snapshot: SheetSnapshot + try { + snapshot = assertSnapshot(data.sheetSnapshot) + } catch (error) { + if (error instanceof SnapshotError) { + return { snapshotRejected: error.reason } + } + throw error + } + if (!snapshotMatches(snapshot, report)) { + return { snapshotRejected: 'sheet_mismatch' } + } + return { + archive: { + format: wrapper.data.format, + envelopeVersion: wrapper.data.envelopeVersion, + exportedAt: wrapper.data.exportedAt, + locale: wrapper.data.locale, + report, + sheetSnapshot: snapshot, + branding: wrapper.data.branding, + labels: wrapper.data.labels, + }, + } +} + +/** + * Reads the JSON of a PDF attachment of any supported shape: bare Report v2 + * or v3, or an archive envelope. The report is parsed first and always + * returned (`readReportDocument` throws UnsupportedReportVersionError for an + * unknown report version); the envelope is accepted whole or dropped with + * `snapshotRejected`. + */ +export function readArchiveDocument( + data: unknown, + map: ReportMigrationMap, +): ArchiveReadOutcome { + const envelopeVersion = envelopeVersionOf(data) + const reportData = + envelopeVersion !== null ? (data as Record<string, unknown>).report : data + const outcome = readReportDocument(reportData, map) + const migrated = reportVersionOf(reportData) !== REPORT_VERSION + const base: ArchiveReadOutcome = { + report: outcome.report, + origin: migrated ? 'v2' : 'bare_v3', + migrated, + unresolvedZones: outcome.unresolvedZones, + unresolvedFindings: outcome.unresolvedFindings, + archive: null, + } + if (envelopeVersion === null) return base + if (envelopeVersion !== ENVELOPE_VERSION) { + return { ...base, snapshotRejected: 'unsupported_envelope' } + } + const wrapped = readEnvelopeV1( + data as Record<string, unknown>, + outcome.report, + ) + return 'archive' in wrapped + ? { ...base, origin: 'envelope_v1', archive: wrapped.archive } + : { ...base, origin: 'envelope_v1', ...wrapped } +} diff --git a/packages/domain/src/archive/index.ts b/packages/domain/src/archive/index.ts new file mode 100644 index 00000000..6b2bd63b --- /dev/null +++ b/packages/domain/src/archive/index.ts @@ -0,0 +1,4 @@ +export * from './snapshot' +export * from './branding' +export * from './labels' +export * from './envelope' diff --git a/packages/domain/src/archive/labels.ts b/packages/domain/src/archive/labels.ts new file mode 100644 index 00000000..217b856f --- /dev/null +++ b/packages/domain/src/archive/labels.ts @@ -0,0 +1,57 @@ +import { z } from 'zod' + +/** + * The static strings the PDF engine prints (section headings, metadata, + * severities, sides, footer credits), in both locales, frozen into the + * archive so a re-export renders the wording of the day. Exactly the dict + * keys apps/app/src/pdf read when Step 6 started. + */ + +export const PDF_LABEL_KEYS = [ + 'pdf.empty', + 'pdf.eyebrow.observation', + 'pdf.eyebrow.synthesis', + 'pdf.owner_prefix', + 'pdf.section.comment', + 'pdf.section.conclusion', + 'pdf.section.findings_prefix', + 'pdf.section.free_findings', + 'pdf.section.next_appointment', + 'pdf.section.recommendations', + 'pdf.section.severity', + 'pdf.section.zones', + 'pdf.siret_prefix', + 'pdf.subject', + 'pdf.title.conclusion', + 'pdf.title.suffix.bilan', + 'pdf.view.detail_prefix', + 'pdf.view.general', + 'severity.mild', + 'severity.moderate', + 'severity.severe', + 'lateral.left', + 'lateral.right', + 'footer.powered_by', + 'footer.in_partnership', +] as const + +export type PdfLabelKey = (typeof PDF_LABEL_KEYS)[number] +export type PdfLabels = Record<PdfLabelKey, string> + +export interface PdfLabelSet { + fr: PdfLabels + en: PdfLabels +} + +const labelShape = Object.fromEntries( + PDF_LABEL_KEYS.map((key) => [key, z.string().max(256)]), +) as Record<PdfLabelKey, z.ZodString> + +export const PdfLabelsSchema: z.ZodType<PdfLabels> = z + .object(labelShape) + .strict() + +/** Strict: every key present in both locales, no extra key. */ +export const PdfLabelSetSchema: z.ZodType<PdfLabelSet> = z + .object({ fr: PdfLabelsSchema, en: PdfLabelsSchema }) + .strict() diff --git a/packages/domain/src/archive/snapshot.ts b/packages/domain/src/archive/snapshot.ts new file mode 100644 index 00000000..11402a26 --- /dev/null +++ b/packages/domain/src/archive/snapshot.ts @@ -0,0 +1,425 @@ +import { z } from 'zod' +import { + AnatomicalSheetDocumentSchema, + type AnatomicalSheetDocument, + type FindingCategory, + type FindingNode, + type FindingZone, + type SheetView, +} from '../anatomical-sheet/schema' +import { validateSheetDocument } from '../anatomical-sheet/validate' +import type { SheetIndexSource } from '../anatomical-sheet/sheet-index' +import { SheetRefSchema, type Report, type SheetRef } from '../report/v3' + +/** + * The sheet a report archive carries so an old bilan re-renders without the + * current catalog (STEP6 §2.2). The snapshot keeps the shape the renderer and + * the sheet index consume: a valid, lean `AnatomicalSheetDocument` (every + * view, annotation, category and region; finding trees pruned to the paths + * the report uses; bibliography emptied) plus the SVG text of every asset a + * view reaches. `assertSnapshot` is the single gate an imported snapshot + * passes (STEP6 §15 caps, integrity, reachable assets). + */ + +const SHA256_PATTERN = /^[0-9a-f]{64}$/ +const MIB = 1024 * 1024 + +/** Hard limits on an imported snapshot; every excess is a `caps` rejection. */ +export const SNAPSHOT_CAPS = { + views: 64, + annotations: 1024, + findingNodes: 8192, + findingDepth: 8, + labelChars: 512, + assets: 4, + assetBytes: 2 * MIB, + assetsTotalBytes: 6 * MIB, +} as const + +export type SheetSnapshotRef = SheetRef & { + schemaVersion: number + speciesId: string +} + +export interface SheetSnapshotAsset { + svgAssetId: string + /** Content address from the seed manifest; a provenance pointer, not a tamper check. */ + sha256: string | null + svg: string +} + +export interface SheetSnapshot { + status: 'draft' | 'published' + ref: SheetSnapshotRef + /** Lean, valid document (schema v2, strict). */ + document: AnatomicalSheetDocument + assets: SheetSnapshotAsset[] +} + +export const SheetSnapshotRefSchema: z.ZodType<SheetSnapshotRef> = + SheetRefSchema.extend({ + schemaVersion: z.number().int().positive(), + speciesId: z.string().min(1), + }).strict() + +const SheetSnapshotAssetSchema = z + .object({ + svgAssetId: z.string().uuid(), + sha256: z.string().regex(SHA256_PATTERN).nullable(), + svg: z.string().max(SNAPSHOT_CAPS.assetBytes), + }) + .strict() + +/** Shape tier only: caps beyond the schema and integrity live in assertSnapshot. */ +export const SheetSnapshotSchema: z.ZodType< + SheetSnapshot, + z.ZodTypeDef, + unknown +> = z + .object({ + status: z.enum(['draft', 'published']), + ref: SheetSnapshotRefSchema, + document: AnatomicalSheetDocumentSchema, + assets: z.array(SheetSnapshotAssetSchema).max(SNAPSHOT_CAPS.assets), + }) + .strict() + +/** What a loaded sheet provides to build a snapshot from. */ +export interface SnapshotSource { + status: 'draft' | 'published' + ref: SheetRef + speciesId: string + schemaVersion: number + document: AnatomicalSheetDocument + /** SVG text by `svg_asset_id`. */ + assets: Readonly<Record<string, string>> + /** sha256 by `svg_asset_id` (seed manifest); absent → null in the snapshot. */ + assetHashes?: Readonly<Record<string, string>> +} + +export type SnapshotRejection = + | 'unsupported_envelope' + | 'schema' + | 'caps' + | 'integrity' + | 'sheet_mismatch' + +/** Thrown by assertSnapshot; `reason` is what the import reports. */ +export class SnapshotError extends Error { + constructor( + public readonly reason: SnapshotRejection, + detail: string, + ) { + super(`snapshot rejected (${reason}): ${detail}`) + this.name = 'SnapshotError' + } +} + +/** Own-key lookup: ids come from documents (`__proto__` is not an entry). */ +function own<T>( + record: Readonly<Record<string, T>>, + key: string, +): T | undefined { + return Object.hasOwn(record, key) ? record[key] : undefined +} + +/** The asset a view draws: its own, else the first one up its parent chain. */ +function assetOfView( + view: SheetView, + views: ReadonlyMap<string, SheetView>, +): string | null { + const visited = new Set<string>() + let current: SheetView | undefined = view + while (current && !visited.has(current.id)) { + if (current.svg_asset_id !== null) return current.svg_asset_id + visited.add(current.id) + current = + current.kind === 'detail' ? views.get(current.parent_view_id) : undefined + } + return null +} + +/** Asset ids reachable from the views, in view order, each once. */ +function reachableAssetIds(document: AnatomicalSheetDocument): string[] { + const views = new Map(document.views.map((v) => [v.id, v])) + const ids: string[] = [] + for (const view of document.views) { + const id = assetOfView(view, views) + if (id !== null && !ids.includes(id)) ids.push(id) + } + return ids +} + +// --------------------------------------------------------------------------- +// Build + +/** Finding paths of the report grouped by zone, resolved and unresolved alike. */ +function pathsByZone(report: Report): Map<string, string[][]> { + const byZone = new Map<string, string[][]>() + for (const observation of report.observations) { + for (const finding of observation.findings) { + const paths = byZone.get(finding.findingZoneId) ?? [] + paths.push(finding.path) + byZone.set(finding.findingZoneId, paths) + } + } + return byZone +} + +/** Keeps, in document order, the nodes at `depth` of some path and their used descendants. */ +function pruneNodes( + nodes: readonly FindingNode[], + paths: readonly string[][], + depth: number, +): FindingNode[] { + return nodes + .filter((node) => paths.some((path) => path[depth] === node.id)) + .map((node) => ({ + id: node.id, + name: { ...node.name }, + description: {}, + requires_vet_referral: node.requires_vet_referral, + reference_ids: [], + review_status: node.review_status, + children: pruneNodes( + node.children, + paths.filter((path) => path[depth] === node.id), + depth + 1, + ), + })) +} + +function pruneCategories( + categories: readonly FindingCategory[], + paths: readonly string[][], +): FindingCategory[] { + return categories + .filter((category) => paths.some((path) => path[0] === category.id)) + .map((category) => ({ + id: category.id, + kind: category.kind, + name: { ...category.name }, + description: {}, + reference_ids: [], + review_status: category.review_status, + children: pruneNodes( + category.children, + paths.filter((path) => path[0] === category.id), + 1, + ), + })) +} + +function pruneZone(zone: FindingZone, paths: readonly string[][]): FindingZone { + return { + id: zone.id, + name: { ...zone.name }, + categories: pruneCategories(zone.categories, paths), + } +} + +function leanDocument( + document: AnatomicalSheetDocument, + report: Report, +): AnatomicalSheetDocument { + const used = pathsByZone(report) + return { + schema_version: document.schema_version, + species_id: document.species_id, + name: structuredClone(document.name), + description: structuredClone(document.description), + scope_disclaimer: structuredClone(document.scope_disclaimer), + attribution: structuredClone(document.attribution), + vertebral_config: structuredClone(document.vertebral_config), + references: [], + categories: structuredClone(document.categories), + views: structuredClone(document.views), + annotations: structuredClone(document.annotations), + finding_zones: document.finding_zones.map((zone) => + pruneZone(zone, used.get(zone.id) ?? []), + ), + } +} + +function snapshotAssets(sheet: SnapshotSource): SheetSnapshotAsset[] { + const assets: SheetSnapshotAsset[] = [] + for (const svgAssetId of reachableAssetIds(sheet.document)) { + const svg = own(sheet.assets, svgAssetId) + if (svg === undefined) continue + const sha256 = sheet.assetHashes + ? (own(sheet.assetHashes, svgAssetId) ?? null) + : null + assets.push({ svgAssetId, sha256, svg }) + } + return assets +} + +/** + * The snapshot of `sheet` a given report needs: pure, deterministic + * (document order everywhere), inputs untouched. Finding trees keep only the + * categories and nodes on a path some finding of the report names, as far as + * those nodes exist; a missing asset is left out and caught by assertSnapshot. + */ +export function buildSheetSnapshot( + sheet: SnapshotSource, + report: Report, +): SheetSnapshot { + return { + status: sheet.status, + ref: { + sheetId: sheet.ref.sheetId, + versionId: sheet.ref.versionId, + documentSha256: sheet.ref.documentSha256, + schemaVersion: sheet.schemaVersion, + speciesId: sheet.speciesId, + }, + document: leanDocument(sheet.document, report), + assets: snapshotAssets(sheet), + } +} + +// --------------------------------------------------------------------------- +// Assert + +function isRecord(value: unknown): value is Record<string, unknown> { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function childrenOf(node: unknown): unknown[] { + if (!isRecord(node)) return [] + const children = node.children + return Array.isArray(children) ? children : [] +} + +/** + * Depth of the finding trees, checked on the raw input before Zod recurses + * into it (an attacker-sized tree must not drive the parser). Iterative: + * an explicit stack of (node, depth) pairs, categories at depth 1. + */ +function assertFindingDepth(input: unknown): void { + if (!isRecord(input) || !isRecord(input.document)) return + const zones = input.document.finding_zones + if (!Array.isArray(zones)) return + const stack: Array<[unknown, number]> = [] + for (const zone of zones) { + if (!isRecord(zone) || !Array.isArray(zone.categories)) continue + for (const category of zone.categories) stack.push([category, 1]) + } + while (stack.length > 0) { + const [node, depth] = stack.pop()! + if (depth > SNAPSHOT_CAPS.findingDepth) { + throw new SnapshotError( + 'caps', + `finding depth over ${SNAPSHOT_CAPS.findingDepth}`, + ) + } + for (const child of childrenOf(node)) stack.push([child, depth + 1]) + } +} + +function countFindingNodes(document: AnatomicalSheetDocument): number { + let count = 0 + const stack: Array<FindingCategory | FindingNode> = + document.finding_zones.flatMap((zone) => zone.categories) + while (stack.length > 0) { + count += 1 + stack.push(...stack.pop()!.children) + } + return count +} + +/** + * Longest `name` label (`fr` or `en`) anywhere in the document: sheet, views, + * annotations, categories, regions, finding zones and nodes. Free texts + * (`description`, `scope_disclaimer`) are not labels and carry no cap here. + */ +function longestName(document: AnatomicalSheetDocument): number { + let longest = 0 + const stack: unknown[] = [document] + while (stack.length > 0) { + const value = stack.pop() + if (Array.isArray(value)) stack.push(...value) + if (!isRecord(value)) continue + const name = value.name + if (isRecord(name)) { + for (const key of ['fr', 'en']) { + const text = name[key] + if (typeof text === 'string') longest = Math.max(longest, text.length) + } + } + stack.push(...Object.values(value)) + } + return longest +} + +function utf8Length(text: string): number { + return new TextEncoder().encode(text).byteLength +} + +function assertCaps(snapshot: SheetSnapshot): void { + const over = (what: string) => new SnapshotError('caps', `${what} over cap`) + const { document, assets } = snapshot + if (document.views.length > SNAPSHOT_CAPS.views) throw over('views') + if (document.annotations.length > SNAPSHOT_CAPS.annotations) { + throw over('annotations') + } + if (countFindingNodes(document) > SNAPSHOT_CAPS.findingNodes) { + throw over('finding nodes') + } + if (longestName(document) > SNAPSHOT_CAPS.labelChars) throw over('label') + if (assets.length > SNAPSHOT_CAPS.assets) throw over('assets') + const sizes = assets.map((asset) => utf8Length(asset.svg)) + if (sizes.some((size) => size > SNAPSHOT_CAPS.assetBytes)) throw over('asset') + const total = sizes.reduce((sum, size) => sum + size, 0) + if (total > SNAPSHOT_CAPS.assetsTotalBytes) throw over('assets total') +} + +function assertIntegrity(snapshot: SheetSnapshot): void { + const errors = validateSheetDocument(snapshot.document).filter( + (issue) => issue.severity === 'error', + ) + if (errors.length > 0) { + throw new SnapshotError('integrity', errors[0]!.code) + } + const present = new Set(snapshot.assets.map((asset) => asset.svgAssetId)) + const views = new Map(snapshot.document.views.map((v) => [v.id, v])) + for (const view of snapshot.document.views) { + const assetId = assetOfView(view, views) + if (assetId === null || !present.has(assetId)) { + throw new SnapshotError('integrity', `view "${view.id}" reaches no asset`) + } + } +} + +/** + * The single gate of an imported snapshot, in this order: finding depth on + * the raw input → shape (`schema`) → caps (§15) → sheet integrity rules and + * every view reaching an asset carried by the snapshot (`integrity`). + * Returns the parsed snapshot; throws SnapshotError with the reason. + */ +export function assertSnapshot(snapshot: unknown): SheetSnapshot { + assertFindingDepth(snapshot) + const parsed = SheetSnapshotSchema.safeParse(snapshot) + if (!parsed.success) { + throw new SnapshotError( + 'schema', + parsed.error.issues[0]?.message ?? 'invalid', + ) + } + assertCaps(parsed.data) + assertIntegrity(parsed.data) + return parsed.data +} + +/** Adapter: a snapshot as the sheet index reads it (assets array → record). */ +export function snapshotIndexSource( + snapshot: SheetSnapshot, +): SheetIndexSource & { ref: SheetSnapshotRef } { + return { + ref: snapshot.ref, + document: snapshot.document, + assets: Object.fromEntries( + snapshot.assets.map((asset) => [asset.svgAssetId, asset.svg]), + ), + } +} diff --git a/packages/domain/src/index.ts b/packages/domain/src/index.ts index 9fb87034..a0985a5c 100644 --- a/packages/domain/src/index.ts +++ b/packages/domain/src/index.ts @@ -1,2 +1,3 @@ export * from './anatomical-sheet' export * from './report' +export * from './archive' diff --git a/packages/domain/src/report/index.ts b/packages/domain/src/report/index.ts index 2fae55c0..f54991a1 100644 --- a/packages/domain/src/report/index.ts +++ b/packages/domain/src/report/index.ts @@ -25,3 +25,8 @@ export { UnsupportedReportVersionError, type MigrationOutcome, } from './migrate' +export { + rebaseReportOnSheet, + type RebaseIndex, + type RebaseOutcome, +} from './rebase' diff --git a/packages/domain/src/report/rebase.ts b/packages/domain/src/report/rebase.ts new file mode 100644 index 00000000..626c2b65 --- /dev/null +++ b/packages/domain/src/report/rebase.ts @@ -0,0 +1,137 @@ +import type { + SheetIndex, + SheetIndexSource, +} from '../anatomical-sheet/sheet-index' +import type { Annotation, LocalizedText } from '../anatomical-sheet/schema' +import type { SheetSnapshot } from '../archive/snapshot' +import { + ReportSchema, + type Finding, + type Observation, + type Report, + type ReportZone, + type SheetRef, +} from './v3' + +/** + * Moves an imported report onto the sheet the application has loaded + * (STEP6 §3.5). A report written on another revision of the sheet keeps + * every datum: a zone or finding the loaded sheet no longer holds is flagged + * `unresolved`, its labels taken from the archived snapshot when the report + * carries none, and the report now references the loaded sheet. Nothing + * happens when the report already sits on the loaded sheet. + */ + +/** An index whose source names its sheet (a loaded sheet or a snapshot). */ +export type RebaseIndex = SheetIndex<SheetIndexSource & { ref: SheetRef }> + +export interface RebaseOutcome { + report: Report + /** Zones and findings newly flagged by this rebase. */ + unresolvedZones: number + unresolvedFindings: number + rebased: boolean +} + +interface Counters { + zones: number + findings: number +} + +/** The name the archived snapshot gives an annotation (a trigger: its view's). */ +function archivedName( + archived: SheetSnapshot | null, + annotationId: string, +): LocalizedText | undefined { + if (!archived) return undefined + const annotation: Annotation | undefined = archived.document.annotations.find( + (a) => a.id === annotationId, + ) + if (!annotation) return undefined + if (annotation.kind !== 'detail_trigger') return annotation.name + const view = archived.document.views.find( + (v) => v.id === annotation.opens_view_id, + ) + return annotation.name ?? view?.name +} + +function flagZone( + zone: ReportZone, + archived: SheetSnapshot | null, +): ReportZone { + const out: ReportZone = { ...zone, unresolved: true } + const name = archivedName(archived, zone.annotationId) + if (name) { + out.labelFrSnapshot ??= name.fr + out.labelEnSnapshot ??= name.en + } + return out +} + +function rebaseZone( + zone: ReportZone, + index: RebaseIndex, + archived: SheetSnapshot | null, + counters: Counters, +): ReportZone { + if (zone.unresolved) return { ...zone } + const known = + index.annotation(zone.annotationId) !== undefined && + index.view(zone.viewId) !== undefined + if (known) return { ...zone } + counters.zones += 1 + return flagZone(zone, archived) +} + +function rebaseFinding( + finding: Finding, + index: RebaseIndex, + counters: Counters, +): Finding { + if (finding.unresolved) return { ...finding } + if (index.nodeAt(finding.findingZoneId, finding.path)) return { ...finding } + counters.findings += 1 + return { ...finding, unresolved: true } +} + +function rebaseObservation( + observation: Observation, + index: RebaseIndex, + archived: SheetSnapshot | null, + counters: Counters, +): Observation { + return { + ...observation, + zones: observation.zones.map((z) => + rebaseZone(z, index, archived, counters), + ), + findings: observation.findings.map((f) => + rebaseFinding(f, index, counters), + ), + } +} + +export function rebaseReportOnSheet( + report: Report, + index: RebaseIndex, + archived: SheetSnapshot | null, +): RebaseOutcome { + if (report.sheet.documentSha256 === index.sheet.ref.documentSha256) { + return { report, unresolvedZones: 0, unresolvedFindings: 0, rebased: false } + } + const counters: Counters = { zones: 0, findings: 0 } + const { sheetId, versionId, documentSha256 } = index.sheet.ref + const rebased: Report = { + ...report, + sheet: { sheetId, versionId, documentSha256 }, + observations: report.observations.map((o) => + rebaseObservation(o, index, archived, counters), + ), + } + return { + report: ReportSchema.parse(rebased), + unresolvedZones: counters.zones, + unresolvedFindings: counters.findings, + rebased: true, + } +} diff --git a/packages/domain/tests/archive.branding-labels.test.ts b/packages/domain/tests/archive.branding-labels.test.ts new file mode 100644 index 00000000..254488d2 --- /dev/null +++ b/packages/domain/tests/archive.branding-labels.test.ts @@ -0,0 +1,178 @@ +import { describe, expect, it } from 'vitest' +import { + BrandingSchema, + PDF_LABEL_KEYS, + PdfLabelSetSchema, + type Branding, + type PdfLabels, +} from '../src' + +export function sampleBranding(): Branding { + return { + siteUrl: 'https://faunosteo.com', + headerLogo: { kind: 'png', base64: 'iVBORw0KGgo=' }, + footerLogo: null, + poweredBy: { + logo: null, + url: 'https://zenquality.fr', + fallbackText: 'zenquality.fr', + }, + partner: { + logo: { kind: 'svg', svg: '<svg xmlns="http://www.w3.org/2000/svg"/>' }, + url: 'https://www.instagram.com/paws.iin.harmony', + fallbackText: '@paws.iin.harmony', + }, + } +} + +export function sampleLabels(): PdfLabels { + return Object.fromEntries( + PDF_LABEL_KEYS.map((key) => [key, key]), + ) as PdfLabels +} + +describe('BrandingSchema', () => { + it('accepts the current identity and both image kinds', () => { + expect(BrandingSchema.parse(sampleBranding())).toEqual(sampleBranding()) + const bare = { + siteUrl: 'http://localhost:5173', + headerLogo: null, + footerLogo: null, + poweredBy: null, + partner: null, + } + expect(BrandingSchema.parse(bare)).toEqual(bare) + }) + + it.each([ + ['unknown key', (b: Branding) => ({ ...b, extra: 1 })], + [ + 'non-http URL', + (b: Branding) => ({ ...b, siteUrl: 'javascript:alert(1)' }), + ], + ['ftp URL', (b: Branding) => ({ ...b, siteUrl: 'ftp://x.test/a' })], + [ + 'URL over 2048 chars', + (b: Branding) => ({ + ...b, + siteUrl: `https://x.test/${'a'.repeat(2048)}`, + }), + ], + [ + 'PNG base64 over 512 KiB', + (b: Branding) => ({ + ...b, + headerLogo: { kind: 'png', base64: 'A'.repeat(512 * 1024 + 4) }, + }), + ], + [ + 'PNG base64 with foreign characters', + (b: Branding) => ({ + ...b, + headerLogo: { kind: 'png', base64: '<svg/>' }, + }), + ], + [ + 'SVG over 256 KiB', + (b: Branding) => ({ + ...b, + footerLogo: { kind: 'svg', svg: 'x'.repeat(256 * 1024 + 1) }, + }), + ], + [ + 'fallback text over 128 chars', + (b: Branding) => ({ + ...b, + poweredBy: { ...b.poweredBy!, fallbackText: 'x'.repeat(129) }, + }), + ], + [ + 'credit with unknown key', + (b: Branding) => ({ ...b, partner: { ...b.partner!, extra: true } }), + ], + ])('rejects %s', (_name, mutate) => { + expect(BrandingSchema.safeParse(mutate(sampleBranding())).success).toBe( + false, + ) + }) +}) + +/** Closes a PDF `(` string literal and chains an action: must never reach the engine. */ +const INJECTION_URL = + 'https://a.example/) /Next << /S /JavaScript /JS (app.alert\\(1\\)) >> /Z (' + +describe('BrandingSchema URLs', () => { + it.each([ + 'https://faunosteo.com', + 'https://zenquality.fr', + 'https://www.instagram.com/paws.iin.harmony', + 'http://localhost:5173', + 'https://x.test/a-b_c~d?e=1&f=2#frag', + `https://x.test/${'a'.repeat(2048 - 'https://x.test/'.length)}`, + ])('accepts %s', (url) => { + const branding = { ...sampleBranding(), siteUrl: url } + expect(BrandingSchema.safeParse(branding).success).toBe(true) + }) + + it.each([ + ['a closing parenthesis', 'https://a.example/)'], + ['an opening parenthesis', 'https://a.example/('], + ['a PDF action injection', INJECTION_URL], + ['a backslash', 'https://a.example/a\\b'], + ['a space', 'https://a.example/a b'], + ['a tab', 'https://a.example/a\tb'], + ['a control character', 'https://a.example/a\u0001b'], + ['DEL', 'https://a.example/a\u007fb'], + ['an angle bracket', 'https://a.example/<x>'], + ['a double quote', 'https://a.example/"x'], + ['a single quote', "https://a.example/'x"], + ['a non-ASCII character', 'https://a.example/é'], + ['no host', 'https://'], + ['a scheme in upper case', 'HTTPS://a.example/'], + ])('rejects %s in the site URL and in a credit URL', (_name, url) => { + const site = { ...sampleBranding(), siteUrl: url } + expect(BrandingSchema.safeParse(site).success).toBe(false) + const base = sampleBranding() + const credit = { ...base, partner: { ...base.partner!, url } } + expect(BrandingSchema.safeParse(credit).success).toBe(false) + }) +}) + +describe('PdfLabelSetSchema', () => { + it('lists 25 distinct keys and accepts a complete set in both locales', () => { + expect(PDF_LABEL_KEYS).toHaveLength(25) + expect(new Set(PDF_LABEL_KEYS).size).toBe(25) + const set = { fr: sampleLabels(), en: sampleLabels() } + expect(PdfLabelSetSchema.parse(set)).toEqual(set) + }) + + it('rejects a missing key, an extra key, a long value, a missing locale', () => { + const missing: Partial<PdfLabels> = sampleLabels() + delete missing['pdf.empty'] + expect( + PdfLabelSetSchema.safeParse({ fr: missing, en: sampleLabels() }).success, + ).toBe(false) + expect( + PdfLabelSetSchema.safeParse({ + fr: { ...sampleLabels(), 'pdf.extra': 'x' }, + en: sampleLabels(), + }).success, + ).toBe(false) + expect( + PdfLabelSetSchema.safeParse({ + fr: { ...sampleLabels(), 'pdf.subject': 'x'.repeat(257) }, + en: sampleLabels(), + }).success, + ).toBe(false) + expect(PdfLabelSetSchema.safeParse({ fr: sampleLabels() }).success).toBe( + false, + ) + expect( + PdfLabelSetSchema.safeParse({ + fr: sampleLabels(), + en: sampleLabels(), + de: sampleLabels(), + }).success, + ).toBe(false) + }) +}) diff --git a/packages/domain/tests/archive.envelope.test.ts b/packages/domain/tests/archive.envelope.test.ts new file mode 100644 index 00000000..a8474a2a --- /dev/null +++ b/packages/domain/tests/archive.envelope.test.ts @@ -0,0 +1,211 @@ +import { describe, expect, it } from 'vitest' +import { + ENVELOPE_FORMAT, + ENVELOPE_VERSION, + ReportArchiveEnvelopeSchema, + UnsupportedReportVersionError, + buildSheetSnapshot, + migrateReportV2ToV3, + readArchiveDocument, + readReportDocument, + type ReportArchiveEnvelope, +} from '../src' +import fullV2 from './fixtures/report-v2.full.json' +import { sampleBranding, sampleLabels } from './archive.branding-labels.test' +import { loadDraftSheet } from './helpers/draft-sheet' +import { + leavesAsV2Report, + legacyLeaves, + loadLegacyBaseline, +} from './helpers/legacy-leaves' + +const draft = loadDraftSheet() +const map = draft.migrationMap +const { report } = readReportDocument(fullV2, map) + +/** A fresh envelope as JSON.parse of an attachment would give it. */ +function envelope(): ReportArchiveEnvelope { + const env: ReportArchiveEnvelope = { + format: ENVELOPE_FORMAT, + envelopeVersion: ENVELOPE_VERSION, + exportedAt: '2026-10-11T10:00:00.000Z', + locale: 'fr', + report, + sheetSnapshot: buildSheetSnapshot(draft, report), + branding: sampleBranding(), + labels: { fr: sampleLabels(), en: sampleLabels() }, + } + return JSON.parse(JSON.stringify(env)) as ReportArchiveEnvelope +} + +type Raw = Record<string, unknown> +const raw = (env: ReportArchiveEnvelope): Raw => env as unknown as Raw + +describe('readArchiveDocument: bare reports', () => { + it('reads a bare v3 as is', () => { + const outcome = readArchiveDocument(JSON.parse(JSON.stringify(report)), map) + expect(outcome).toEqual({ + report, + origin: 'bare_v3', + migrated: false, + unresolvedZones: 0, + unresolvedFindings: 0, + archive: null, + }) + }) + + it('migrates a bare v2 with the counts of the migration', () => { + const outcome = readArchiveDocument(fullV2, map) + expect(outcome.origin).toBe('v2') + expect(outcome.migrated).toBe(true) + expect(outcome.archive).toBeNull() + expect(outcome.report).toEqual(report) + expect(outcome.snapshotRejected).toBeUndefined() + + const leaves = leavesAsV2Report(legacyLeaves(loadLegacyBaseline())) + const expected = migrateReportV2ToV3(leaves, map) + const migrated = readArchiveDocument(leaves, map) + expect(expected.unresolvedFindings).toBeGreaterThan(0) + expect(migrated.unresolvedFindings).toBe(expected.unresolvedFindings) + expect(migrated.unresolvedZones).toBe(expected.unresolvedZones) + expect(migrated.report).toEqual(expected.report) + }) + + it('throws for a report version it cannot read, or a non-object', () => { + expect(() => readArchiveDocument({ ...report, version: 1 }, map)).toThrow( + UnsupportedReportVersionError, + ) + for (const data of [null, undefined, 'report', 42, [report]]) { + expect(() => readArchiveDocument(data, map)).toThrow( + UnsupportedReportVersionError, + ) + } + }) +}) + +describe('readArchiveDocument: envelopes', () => { + it('accepts a valid v1 envelope whole', () => { + const env = envelope() + const outcome = readArchiveDocument(env, map) + expect(outcome.origin).toBe('envelope_v1') + expect(outcome.migrated).toBe(false) + expect(outcome.unresolvedZones).toBe(0) + expect(outcome.snapshotRejected).toBeUndefined() + expect(outcome.report).toEqual(report) + expect(outcome.archive).toEqual(env) + expect(ReportArchiveEnvelopeSchema.parse(env)).toEqual(env) + }) + + it('keeps the report of an envelope version it does not know', () => { + const outcome = readArchiveDocument( + { ...envelope(), envelopeVersion: 2 }, + map, + ) + expect(outcome.report).toEqual(report) + expect(outcome.origin).toBe('bare_v3') + expect(outcome.archive).toBeNull() + expect(outcome.snapshotRejected).toBe('unsupported_envelope') + }) + + it('names the report version when the wrapped report is unknown', () => { + const env = raw(envelope()) + env.report = { ...report, version: 4 } + let thrown: unknown + try { + readArchiveDocument(env, map) + } catch (error) { + thrown = error + } + expect(thrown).toBeInstanceOf(UnsupportedReportVersionError) + expect((thrown as UnsupportedReportVersionError).foundVersion).toBe(4) + }) + + it('ignores unknown metadata keys, __proto__ included, within v1', () => { + const env = raw(envelope()) + env.futureField = { anything: true } + const outcome = readArchiveDocument(env, map) + expect(outcome.archive).not.toBeNull() + expect('futureField' in outcome.archive!).toBe(false) + + const text = JSON.stringify(envelope()).replace( + '"format"', + '"__proto__":{"polluted":true},"format"', + ) + const polluted = readArchiveDocument(JSON.parse(text), map) + expect(polluted.archive).not.toBeNull() + expect(({} as { polluted?: boolean }).polluted).toBeUndefined() + expect(Object.hasOwn(polluted.archive!, '__proto__')).toBe(false) + }) + + it('drops the envelope on a wrapper fault (schema): branding, labels, metadata', () => { + const branding = raw(envelope()) + branding.branding = { ...sampleBranding(), siteUrl: 'javascript:alert(1)' } + expect(readArchiveDocument(branding, map)).toMatchObject({ + report, + origin: 'envelope_v1', + archive: null, + snapshotRejected: 'schema', + }) + + const labels = raw(envelope()) + labels.labels = { fr: sampleLabels() } + expect(readArchiveDocument(labels, map).snapshotRejected).toBe('schema') + + const locale = raw(envelope()) + locale.locale = 'de' + expect(readArchiveDocument(locale, map).snapshotRejected).toBe('schema') + + const format = raw(envelope()) + format.format = 'other' + expect(readArchiveDocument(format, map).snapshotRejected).toBe('schema') + }) + + it('drops a snapshot over the caps or failing its own schema', () => { + const caps = envelope() + caps.sheetSnapshot.document.name.fr = 'x'.repeat(513) + expect(readArchiveDocument(caps, map)).toMatchObject({ + report, + archive: null, + snapshotRejected: 'caps', + }) + + const schema = raw(envelope()) + schema.sheetSnapshot = { ...envelope().sheetSnapshot, extra: 1 } + expect(readArchiveDocument(schema, map).snapshotRejected).toBe('schema') + + const missing = raw(envelope()) + delete missing.sheetSnapshot + expect(readArchiveDocument(missing, map).snapshotRejected).toBe('schema') + + const integrity = envelope() + integrity.sheetSnapshot.assets = [] + expect(readArchiveDocument(integrity, map).snapshotRejected).toBe( + 'integrity', + ) + }) + + it('drops a snapshot of another sheet than the report (sheet_mismatch)', () => { + const sha = envelope() + sha.sheetSnapshot.ref.documentSha256 = 'f'.repeat(64) + expect(readArchiveDocument(sha, map)).toMatchObject({ + report, + origin: 'envelope_v1', + archive: null, + snapshotRejected: 'sheet_mismatch', + }) + + const id = envelope() + id.sheetSnapshot.ref.sheetId = 'another-sheet' + expect(readArchiveDocument(id, map).snapshotRejected).toBe('sheet_mismatch') + }) + + it('migrates a v2 report found inside an envelope and still checks the snapshot', () => { + const env = raw(envelope()) + env.report = fullV2 + const outcome = readArchiveDocument(env, map) + expect(outcome.origin).toBe('envelope_v1') + expect(outcome.migrated).toBe(true) + expect(outcome.report).toEqual(report) + expect(outcome.archive?.report).toEqual(report) + }) +}) diff --git a/packages/domain/tests/archive.snapshot.test.ts b/packages/domain/tests/archive.snapshot.test.ts new file mode 100644 index 00000000..14f59a4c --- /dev/null +++ b/packages/domain/tests/archive.snapshot.test.ts @@ -0,0 +1,366 @@ +import { describe, expect, it } from 'vitest' +import { + AnatomicalSheetDocumentSchema, + REPORT_VERSION, + SNAPSHOT_CAPS, + SnapshotError, + assertSnapshot, + buildSheetIndex, + buildSheetSnapshot, + readReportDocument, + snapshotIndexSource, + validateSheetDocument, + type Report, + type SheetSnapshot, + type SnapshotRejection, + type SnapshotSource, +} from '../src' +import { HORSE_MAIN_ASSET_ID, horseSlice } from './fixtures/horse-slice' +import fullV2 from './fixtures/report-v2.full.json' +import { loadDraftSheet } from './helpers/draft-sheet' +import { + leavesAsV2Report, + legacyLeaves, + loadLegacyBaseline, +} from './helpers/legacy-leaves' + +const SHA = 'b'.repeat(64) +const HASH = 'c'.repeat(64) +const SVG = '<svg xmlns="http://www.w3.org/2000/svg"></svg>' + +function sliceSource(): SnapshotSource { + return { + status: 'draft', + ref: { sheetId: 'sheet-1', versionId: null, documentSha256: SHA }, + speciesId: 'equine', + schemaVersion: 2, + document: horseSlice(), + assets: { [HORSE_MAIN_ASSET_ID]: SVG }, + assetHashes: { [HORSE_MAIN_ASSET_ID]: HASH }, + } +} + +function sliceReport(): Report { + return { + version: REPORT_VERSION, + id: 'r1', + createdAt: '2026-10-10T10:00:00Z', + date: '2026-10-10', + practitioner: { name: 'Dr. Dupont' }, + animal: { speciesId: 'equine', name: 'Mistral' }, + owner: { name: 'Jean Martin' }, + sheet: { sheetId: 'sheet-1', versionId: null, documentSha256: SHA }, + observations: [ + { + id: 'obs-1', + zones: [{ annotationId: 'hip', viewId: 'view-main' }], + findings: [ + { + findingZoneId: 'hip', + path: ['hip-dysfunctions', 'articular', 'restriction-flexion'], + labelFrSnapshot: 'Restriction en flexion', + labelEnSnapshot: 'Flexion restriction', + }, + { + findingZoneId: 'hip', + path: ['hip-dysfunctions', 'articular', 'ghost-leaf'], + labelFrSnapshot: 'Disparu', + labelEnSnapshot: 'Gone', + unresolved: true, + }, + { + findingZoneId: 'sphenoid', + path: ['ssb-dysfunctions', 'physiological', 'torsion-right'], + labelFrSnapshot: 'Torsion droite', + labelEnSnapshot: 'Right torsion', + }, + ], + freeTextFindings: [], + comment: '', + }, + ], + conclusion: '', + recommendations: '', + localAnnotations: [], + } +} + +function sliceSnapshot(): SheetSnapshot { + return buildSheetSnapshot(sliceSource(), sliceReport()) +} + +function rejection(input: unknown): SnapshotRejection | 'accepted' { + try { + assertSnapshot(input) + return 'accepted' + } catch (error) { + if (error instanceof SnapshotError) return error.reason + throw error + } +} + +describe('buildSheetSnapshot on the equine draft', () => { + const draft = loadDraftSheet() + const { report } = readReportDocument(fullV2, draft.migrationMap) + const snapshot = buildSheetSnapshot(draft, report) + + it('keeps every view, annotation, category and region, empties the bibliography', () => { + expect(snapshot.document.views).toEqual(draft.document.views) + expect(snapshot.document.annotations).toEqual(draft.document.annotations) + expect(snapshot.document.categories).toEqual(draft.document.categories) + expect(snapshot.document.vertebral_config).toEqual( + draft.document.vertebral_config, + ) + expect(snapshot.document.references).toEqual([]) + expect(snapshot.document.name).toEqual(draft.document.name) + expect(snapshot.document.scope_disclaimer).toEqual( + draft.document.scope_disclaimer, + ) + expect(snapshot.document.attribution).toEqual(draft.document.attribution) + expect(snapshot.document.species_id).toBe('equine') + expect(snapshot.document.schema_version).toBe(2) + }) + + it('prunes finding trees to the paths the report uses, every zone kept', () => { + expect(snapshot.document.finding_zones.map((z) => z.id)).toEqual( + draft.document.finding_zones.map((z) => z.id), + ) + const c7 = snapshot.document.finding_zones.find((z) => z.id === 'c7-t1')! + expect(c7.categories).toHaveLength(1) + expect(c7.categories[0]).toMatchObject({ + id: 'c7-t1-dysfunctions', + kind: 'dysfunction', + description: {}, + reference_ids: [], + }) + expect(c7.categories[0]!.children.map((n) => n.id)).toEqual(['segmental']) + expect(c7.categories[0]!.children[0]!.children).toMatchObject([ + { id: 'fixation', description: {}, reference_ids: [], children: [] }, + ]) + const used = new Set( + report.observations.flatMap((o) => + o.findings.map((f) => f.findingZoneId), + ), + ) + for (const zone of snapshot.document.finding_zones) { + if (!used.has(zone.id)) expect(zone.categories, zone.id).toEqual([]) + else expect(zone.categories.length, zone.id).toBeGreaterThan(0) + } + }) + + it('carries the reachable asset with its manifest hash and the full ref', () => { + const [assetId] = Object.keys(draft.assets) + expect(snapshot.assets).toEqual([ + { + svgAssetId: assetId, + sha256: draft.assetHashes[assetId!], + svg: draft.assets[assetId!], + }, + ]) + expect(snapshot.ref).toEqual({ + ...draft.ref, + schemaVersion: 2, + speciesId: 'equine', + }) + expect(snapshot.status).toBe('draft') + }) + + it('is a valid document with no integrity error, under 250,000 bytes pretty-printed', () => { + expect(() => + AnatomicalSheetDocumentSchema.parse(snapshot.document), + ).not.toThrow() + const errors = validateSheetDocument(snapshot.document).filter( + (i) => i.severity === 'error', + ) + expect(errors).toEqual([]) + const bytes = Buffer.byteLength(JSON.stringify(snapshot, null, 2), 'utf8') + console.log( + `snapshot (report-v2.full on the draft, pretty JSON): ${bytes} bytes`, + ) + expect(bytes).toBeLessThan(250_000) + expect(assertSnapshot(snapshot)).toEqual(snapshot) + }) + + it('is pure and deterministic', () => { + const before = JSON.stringify(draft.document) + const again = buildSheetSnapshot(draft, report) + expect(JSON.stringify(draft.document)).toBe(before) + expect(again).toEqual(snapshot) + expect(again.document.views).not.toBe(draft.document.views) + }) + + it('keeps what exists of an unresolved path and nothing else (legacy leaves)', () => { + const v2 = leavesAsV2Report(legacyLeaves(loadLegacyBaseline())) + const migrated = readReportDocument(v2, draft.migrationMap) + expect(migrated.unresolvedFindings).toBeGreaterThan(0) + const snap = buildSheetSnapshot(draft, migrated.report) + expect(assertSnapshot(snap)).toEqual(snap) + const index = buildSheetIndex(snapshotIndexSource(snap)) + const findings = migrated.report.observations.flatMap((o) => o.findings) + for (const finding of findings) { + const node = index.nodeAt(finding.findingZoneId, finding.path) + if (finding.unresolved) + expect(node, finding.path.join('/')).toBeUndefined() + else expect(node, finding.path.join('/')).toBeDefined() + } + expect(index.sheet.ref.sheetId).toBe(draft.ref.sheetId) + expect(index.sheet.assets[snap.assets[0]!.svgAssetId]).toBe( + snap.assets[0]!.svg, + ) + }) +}) + +describe('buildSheetSnapshot on the slice', () => { + it('copies review_status and requires_vet_referral, skips an asset it has no text for', () => { + const snapshot = sliceSnapshot() + const hip = snapshot.document.finding_zones.find((z) => z.id === 'hip')! + expect(hip.categories.map((c) => c.id)).toEqual(['hip-dysfunctions']) + expect(hip.categories[0]!.review_status).toBe('inherited') + expect(hip.categories[0]!.children[0]!.children.map((n) => n.id)).toEqual([ + 'restriction-flexion', + ]) + const sphenoid = snapshot.document.finding_zones.find( + (z) => z.id === 'sphenoid', + )! + expect(sphenoid.categories[0]!.children[0]!.children[0]).toMatchObject({ + id: 'torsion-right', + requires_vet_referral: false, + }) + expect(snapshot.assets).toEqual([ + { svgAssetId: HORSE_MAIN_ASSET_ID, sha256: HASH, svg: SVG }, + ]) + const noHash = { ...sliceSource(), assetHashes: undefined } + expect( + buildSheetSnapshot(noHash, sliceReport()).assets[0]!.sha256, + ).toBeNull() + const noSvg = { ...sliceSource(), assets: {} } + expect(buildSheetSnapshot(noSvg, sliceReport()).assets).toEqual([]) + }) +}) + +describe('assertSnapshot', () => { + it('accepts the slice snapshot and returns the parsed copy', () => { + const snapshot = sliceSnapshot() + const parsed = assertSnapshot(JSON.parse(JSON.stringify(snapshot))) + expect(parsed).toEqual(snapshot) + }) + + it('rejects a finding tree deeper than the cap before parsing anything (caps)', () => { + let node: unknown = { id: 'leaf' } + for (let depth = 0; depth < SNAPSHOT_CAPS.findingDepth; depth += 1) { + node = { id: `n${depth}`, children: [node] } + } + const raw = { + garbage: true, + document: { finding_zones: [{ categories: [node] }] }, + } + expect(rejection(raw)).toBe('caps') + const shallow = { + document: { finding_zones: [{ categories: [{ id: 'c' }] }] }, + } + expect(rejection(shallow)).toBe('schema') + expect(rejection({ document: { finding_zones: 'x' } })).toBe('schema') + }) + + it('rejects shape faults (schema): unknown key, missing field, too many assets, non-object', () => { + expect(rejection({ ...sliceSnapshot(), extra: 1 })).toBe('schema') + const noStatus: Partial<SheetSnapshot> = sliceSnapshot() + delete noStatus.status + expect(rejection(noStatus)).toBe('schema') + const many = sliceSnapshot() + many.assets = Array.from({ length: 5 }, (_, i) => ({ + svgAssetId: `00000000-0000-4000-8000-00000000000${i}`, + sha256: null, + svg: SVG, + })) + expect(rejection(many)).toBe('schema') + expect(rejection(null)).toBe('schema') + expect(rejection('snapshot')).toBe('schema') + expect(rejection([sliceSnapshot()])).toBe('schema') + }) + + it('rejects a __proto__ key without polluting anything', () => { + const raw = JSON.parse( + JSON.stringify(sliceSnapshot()).replace( + '"status"', + '"__proto__":{"polluted":1},"status"', + ), + ) + expect(rejection(raw)).toBe('schema') + expect(({} as { polluted?: number }).polluted).toBeUndefined() + }) + + it('rejects counts over the caps (caps)', () => { + const views = sliceSnapshot() + views.document.views.push( + ...Array.from({ length: SNAPSHOT_CAPS.views }, (_, i) => ({ + ...views.document.views[1]!, + id: `extra-${i}`, + })), + ) + expect(rejection(views)).toBe('caps') + + const annotations = sliceSnapshot() + annotations.document.annotations.push( + ...Array.from({ length: SNAPSHOT_CAPS.annotations }, (_, i) => ({ + ...annotations.document.annotations[0]!, + id: `extra-${i}`, + })), + ) + expect(rejection(annotations)).toBe('caps') + + const nodes = sliceSnapshot() + const category = nodes.document.finding_zones[0]!.categories[0]! + category.children = Array.from( + { length: SNAPSHOT_CAPS.findingNodes }, + (_, i) => ({ + id: `leaf-${i}`, + name: { fr: 'x', en: 'x' }, + description: {}, + requires_vet_referral: false, + reference_ids: [], + review_status: 'inherited', + children: [], + }), + ) + expect(rejection(nodes)).toBe('caps') + + const label = sliceSnapshot() + label.document.name.fr = 'x'.repeat(SNAPSHOT_CAPS.labelChars + 1) + expect(rejection(label)).toBe('caps') + }) + + it('rejects oversize assets in bytes, single and total (caps)', () => { + const big = sliceSnapshot() + // 1.1M two-byte code points: under the schema's char cap, over 2 MiB. + big.assets[0]!.svg = 'é'.repeat(1_100_000) + expect(rejection(big)).toBe('caps') + + const total = sliceSnapshot() + total.assets = Array.from({ length: 4 }, (_, i) => ({ + svgAssetId: + i === 0 + ? HORSE_MAIN_ASSET_ID + : `00000000-0000-4000-8000-00000000000${i}`, + sha256: null, + svg: 'a'.repeat(1_600_000), + })) + expect(rejection(total)).toBe('caps') + }) + + it('rejects integrity faults: a sheet rule error, a view reaching no carried asset', () => { + const rule = sliceSnapshot() + rule.document.finding_zones = rule.document.finding_zones.filter( + (z) => z.id !== 'atm', + ) + expect(rejection(rule)).toBe('integrity') + + const noAsset = sliceSnapshot() + noAsset.assets = [] + expect(rejection(noAsset)).toBe('integrity') + + const otherAsset = sliceSnapshot() + otherAsset.assets[0]!.svgAssetId = '00000000-0000-4000-8000-000000000009' + expect(rejection(otherAsset)).toBe('integrity') + }) +}) diff --git a/packages/domain/tests/helpers/draft-sheet.ts b/packages/domain/tests/helpers/draft-sheet.ts new file mode 100644 index 00000000..98b7eed3 --- /dev/null +++ b/packages/domain/tests/helpers/draft-sheet.ts @@ -0,0 +1,73 @@ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { join, resolve } from 'node:path' +import { + AnatomicalSheetDocumentSchema, + ReportMigrationMapSchema, + type ReportMigrationMap, + type SnapshotSource, +} from '../../src' + +/** + * The committed equine draft (`pnpm import:equine`) as the application + * bundles it: document, reference, SVG assets and their manifest hashes, + * plus the v2 → v3 migration map. Read from the seed, never copied. + */ + +export const DRAFT_DIR = resolve( + fileURLToPath(import.meta.url), + '../../../../../supabase/seed/anatomical-sheets/equine/draft', +) + +interface SeedRef { + sheet_id: string + version_id: string | null + document_sha256: string + schema_version: number + species_id: string +} + +interface SeedAsset { + file: string + sha256: string + svg_asset_id: string +} + +function json<T>(name: string): T { + return JSON.parse(readFileSync(join(DRAFT_DIR, name), 'utf8')) as T +} + +export interface DraftSheet extends SnapshotSource { + assetHashes: Readonly<Record<string, string>> + migrationMap: ReportMigrationMap +} + +export function loadDraftSheet(): DraftSheet { + const ref = json<SeedRef>('sheet-ref.json') + const manifest = json<SeedAsset[]>('assets.json') + const assets: Record<string, string> = {} + const assetHashes: Record<string, string> = {} + for (const asset of manifest) { + assets[asset.svg_asset_id] = readFileSync( + join(DRAFT_DIR, 'assets', asset.file), + 'utf8', + ) + assetHashes[asset.svg_asset_id] = asset.sha256 + } + return { + status: 'draft', + ref: { + sheetId: ref.sheet_id, + versionId: ref.version_id, + documentSha256: ref.document_sha256, + }, + speciesId: ref.species_id, + schemaVersion: ref.schema_version, + document: AnatomicalSheetDocumentSchema.parse(json('document.json')), + assets, + assetHashes, + migrationMap: ReportMigrationMapSchema.parse( + json('report-migration-map.json'), + ), + } +} diff --git a/packages/domain/tests/helpers/legacy-leaves.ts b/packages/domain/tests/helpers/legacy-leaves.ts new file mode 100644 index 00000000..27608dce --- /dev/null +++ b/packages/domain/tests/helpers/legacy-leaves.ts @@ -0,0 +1,95 @@ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { resolve } from 'node:path' +import { + AnatomicalSheetDocumentSchema, + ReportV2Schema, + type AnatomicalSheetDocument, + type FindingCategory, + type FindingNode, + type ObservationV2, + type ReportV2, +} from '../../src' + +/** + * The legacy catalog as the application's archive knew it: every leaf of the + * generated baseline (`legacy-import/document.json`) becomes a Report v2 + * finding, grouped in one observation per zone. Same recipe as the app and + * anatomy helpers; migrated through the draft map it yields the unresolved + * items (sphenoid / ssb leaves) a Phase 0 golden was frozen with. + */ + +const BASELINE = resolve( + fileURLToPath(import.meta.url), + '../../../../../supabase/seed/anatomical-sheets/equine/legacy-import/document.json', +) + +export interface LegacyLeaf { + zoneId: string + path: string[] + name: { fr: string; en: string } + vet: boolean +} + +export function loadLegacyBaseline(): AnatomicalSheetDocument { + return AnatomicalSheetDocumentSchema.parse( + JSON.parse(readFileSync(BASELINE, 'utf8')), + ) +} + +export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] { + const out: LegacyLeaf[] = [] + const walk = ( + zoneId: string, + nodes: readonly (FindingCategory | FindingNode)[], + prefix: string[], + ) => { + for (const node of nodes) { + const path = [...prefix, node.id] + if (node.children.length > 0) walk(zoneId, node.children, path) + else { + const vet = + 'requires_vet_referral' in node && node.requires_vet_referral + out.push({ zoneId, path, name: node.name, vet }) + } + } + } + for (const zone of doc.finding_zones) walk(zone.id, zone.categories, []) + return out +} + +export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 { + const byZone = new Map<string, ObservationV2>() + for (const leaf of leaves) { + let obs = byZone.get(leaf.zoneId) + if (!obs) { + obs = { + id: `obs-${leaf.zoneId}`, + zones: [], + findings: [], + freeTextFindings: [], + comment: '', + } + byZone.set(leaf.zoneId, obs) + } + obs.findings.push({ + zoneId: leaf.zoneId, + path: leaf.path, + labelFrSnapshot: leaf.name.fr, + labelEnSnapshot: leaf.name.en || leaf.name.fr, + ...(leaf.vet ? { requiresVetReferral: true } : {}), + }) + } + return ReportV2Schema.parse({ + version: 2, + id: 'all-leaves', + createdAt: '2026-10-10T00:00:00Z', + date: '2026-10-10', + practitioner: { name: 'Synthetic' }, + animal: { speciesId: 'equine', name: 'Synthetic' }, + owner: { name: 'Synthetic' }, + observations: [...byZone.values()], + conclusion: '', + recommendations: '', + }) +} diff --git a/packages/domain/tests/report.rebase.test.ts b/packages/domain/tests/report.rebase.test.ts new file mode 100644 index 00000000..1d7860fd --- /dev/null +++ b/packages/domain/tests/report.rebase.test.ts @@ -0,0 +1,208 @@ +import { describe, expect, it } from 'vitest' +import { + REPORT_VERSION, + ReportSchema, + buildSheetIndex, + buildSheetSnapshot, + rebaseReportOnSheet, + type AnatomicalSheetDocument, + type Report, + type SheetRef, + type SnapshotSource, +} from '../src' +import { HORSE_MAIN_ASSET_ID, horseSlice } from './fixtures/horse-slice' + +const SHA_A = 'a'.repeat(64) +const SHA_B = 'b'.repeat(64) +const REF_A: SheetRef = { + sheetId: 'sheet-1', + versionId: null, + documentSha256: SHA_A, +} +const REF_B: SheetRef = { + sheetId: 'sheet-1', + versionId: 'v2', + documentSha256: SHA_B, +} + +function source( + ref: SheetRef, + document: AnatomicalSheetDocument, +): SnapshotSource { + return { + status: 'draft', + ref, + speciesId: 'equine', + schemaVersion: 2, + document, + assets: { [HORSE_MAIN_ASSET_ID]: '<svg/>' }, + } +} + +/** Revision B: the TMJ marker and the head trigger are gone, hip lost its articular node. */ +function revisionB(): AnatomicalSheetDocument { + const doc = horseSlice() + doc.annotations = doc.annotations.filter( + (a) => a.id !== 'atm' && a.id !== 'head-trigger', + ) + const hip = doc.finding_zones.find((z) => z.id === 'hip')! + hip.categories[0]!.children = hip.categories[0]!.children.filter( + (n) => n.id !== 'articular', + ) + return doc +} + +function reportOnA(): Report { + return { + version: REPORT_VERSION, + id: 'r1', + createdAt: '2026-10-10T10:00:00Z', + date: '2026-10-10', + practitioner: { name: 'Dr. Dupont' }, + animal: { speciesId: 'equine', name: 'Mistral' }, + owner: { name: 'Jean Martin' }, + sheet: REF_A, + observations: [ + { + id: 'obs-1', + zones: [ + { + annotationId: 'hip', + viewId: 'view-main', + side: 'left', + labelFrSnapshot: 'Hanche (coxo-fémorale)', + labelEnSnapshot: 'Hip joint', + }, + { annotationId: 'atm', viewId: 'view-head' }, + { annotationId: 'head-trigger', viewId: 'view-main' }, + { + annotationId: 'hip', + viewId: 'ghost-view', + labelFrSnapshot: 'Gardé', + }, + { + annotationId: 'gone-long-ago', + viewId: 'view-main', + labelFrSnapshot: 'Ancien', + unresolved: true, + }, + ], + findings: [ + { + findingZoneId: 'hip', + path: ['hip-dysfunctions', 'articular', 'restriction-flexion'], + labelFrSnapshot: 'Restriction en flexion', + labelEnSnapshot: 'Flexion restriction', + }, + { + findingZoneId: 'cervical', + path: ['cervical-observations', 'stumbling-proprioceptive'], + labelFrSnapshot: 'Trébuchements', + labelEnSnapshot: 'Stumbling', + requiresVetReferral: true, + }, + { + findingZoneId: 'atm', + path: ['atm-observations', 'headshaking'], + labelFrSnapshot: 'Headshaking', + labelEnSnapshot: 'Headshaking', + unresolved: true, + }, + ], + freeTextFindings: ['note'], + severity: 'moderate', + comment: '', + }, + ], + conclusion: 'c', + recommendations: 'r', + localAnnotations: [], + } +} + +const indexA = buildSheetIndex(source(REF_A, horseSlice())) +const indexB = buildSheetIndex(source(REF_B, revisionB())) + +describe('rebaseReportOnSheet', () => { + it('returns the report untouched when it already sits on the loaded sheet', () => { + const report = reportOnA() + const outcome = rebaseReportOnSheet(report, indexA, null) + expect(outcome).toEqual({ + report, + unresolvedZones: 0, + unresolvedFindings: 0, + rebased: false, + }) + expect(outcome.report).toBe(report) + }) + + it('flags what the new sheet lost, labels it from the archive, keeps the rest', () => { + const report = reportOnA() + const archived = buildSheetSnapshot(source(REF_A, horseSlice()), report) + const outcome = rebaseReportOnSheet(report, indexB, archived) + expect(outcome.rebased).toBe(true) + expect(outcome.unresolvedZones).toBe(3) + expect(outcome.unresolvedFindings).toBe(1) + expect(outcome.report.sheet).toEqual(REF_B) + expect(() => ReportSchema.parse(outcome.report)).not.toThrow() + + const [hip, atm, trigger, ghostView, old] = + outcome.report.observations[0]!.zones + expect(hip).toEqual(report.observations[0]!.zones[0]) + expect(atm).toEqual({ + annotationId: 'atm', + viewId: 'view-head', + unresolved: true, + labelFrSnapshot: 'Articulation Temporo-Mandibulaire (ATM)', + labelEnSnapshot: 'Temporomandibular Joint (TMJ)', + }) + expect(trigger).toEqual({ + annotationId: 'head-trigger', + viewId: 'view-main', + unresolved: true, + labelFrSnapshot: 'Tête', + labelEnSnapshot: 'Head', + }) + expect(ghostView).toEqual({ + annotationId: 'hip', + viewId: 'ghost-view', + unresolved: true, + labelFrSnapshot: 'Gardé', + labelEnSnapshot: 'Hip joint', + }) + expect(old).toEqual(report.observations[0]!.zones[4]) + + const [flexion, stumbling, headshaking] = + outcome.report.observations[0]!.findings + expect(flexion).toEqual({ + ...report.observations[0]!.findings[0], + unresolved: true, + }) + expect(stumbling).toEqual(report.observations[0]!.findings[1]) + expect(headshaking).toEqual(report.observations[0]!.findings[2]) + expect(outcome.report.observations[0]!.freeTextFindings).toEqual(['note']) + expect(report).toEqual(reportOnA()) + }) + + it('fills no label without an archived snapshot', () => { + const outcome = rebaseReportOnSheet(reportOnA(), indexB, null) + expect(outcome.report.observations[0]!.zones[1]).toEqual({ + annotationId: 'atm', + viewId: 'view-head', + unresolved: true, + }) + expect(outcome.unresolvedZones).toBe(3) + }) + + it('counts nothing twice: a rebased report rebased again onto the same sheet is stable', () => { + const first = rebaseReportOnSheet(reportOnA(), indexB, null) + const second = rebaseReportOnSheet( + { ...first.report, sheet: REF_A }, + indexB, + null, + ) + expect(second.unresolvedZones).toBe(0) + expect(second.unresolvedFindings).toBe(0) + expect(second.report).toEqual(first.report) + }) +}) diff --git a/packages/domain/tests/sheet-index.test.ts b/packages/domain/tests/sheet-index.test.ts new file mode 100644 index 00000000..13203d21 --- /dev/null +++ b/packages/domain/tests/sheet-index.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it } from 'vitest' +import { + buildSheetIndex, + isObservable, + pickLabel, + type SheetIndexSource, +} from '../src' +import { HORSE_MAIN_ASSET_ID, horseSlice } from './fixtures/horse-slice' + +const SHA = 'a'.repeat(64) + +function source() { + return { + ref: { documentSha256: SHA }, + document: horseSlice(), + assets: { [HORSE_MAIN_ASSET_ID]: '<svg/>' }, + extra: 'kept by the index', + } satisfies SheetIndexSource & { extra: string } +} + +describe('buildSheetIndex', () => { + it('keeps the source as given, typed as the caller passed it', () => { + const index = buildSheetIndex(source()) + expect(index.sheet.extra).toBe('kept by the index') + expect(index.sheet.ref.documentSha256).toBe(SHA) + expect(index.mainView.id).toBe('view-main') + expect(index.view('view-head')?.kind).toBe('detail') + expect(index.view('nowhere')).toBeUndefined() + }) + + it('looks up annotations, zones, regions and spine markers by id', () => { + const index = buildSheetIndex(source()) + expect(index.annotation('hip')?.kind).toBe('point') + expect(index.annotationsOfView('view-head').map((a) => a.id)).toContain( + 'atm', + ) + expect(index.findingZone('cervical')?.name.en).toBe('Cervical Vertebrae') + expect(index.regions().map((r) => r.code)).toEqual([ + 'C', + 'T', + 'L', + 'S', + 'Cd', + ]) + expect(index.region('Cd')?.count_range).toEqual({ min: 15, max: 21 }) + expect(index.spineAnnotation('C', 'view-main')?.id).toBe( + 'cervical-vertebrae', + ) + expect(index.spineAnnotation('C', 'view-head')).toBeUndefined() + expect(index.isSpine('cervical-vertebrae')).toBe(true) + expect(index.isSpine('hip')).toBe(false) + expect(index.isSpine('head-trigger')).toBe(false) + }) + + it('resolves finding paths and reports absent ones', () => { + const index = buildSheetIndex(source()) + expect( + index.nodeAt('hip', [ + 'hip-dysfunctions', + 'articular', + 'restriction-flexion', + ])?.name.fr, + ).toBe('Restriction en flexion') + expect(index.nodeAt('hip', ['hip-dysfunctions'])?.name.fr).toBe( + 'Dysfonctions ostéopathiques', + ) + expect(index.nodeAt('hip', ['hip-dysfunctions', 'ghost'])).toBeUndefined() + expect(index.nodeAt('nowhere', ['x'])).toBeUndefined() + expect(index.nodeAt('hip', [])).toBeUndefined() + }) + + it('names a nameless trigger after the view it opens', () => { + const index = buildSheetIndex(source()) + expect(index.name(index.annotation('head-trigger')!)).toEqual({ + fr: 'Tête', + en: 'Head', + }) + expect(index.name(index.annotation('hip')!).en).toBe('Hip joint') + }) + + it('refuses a document without a main view', () => { + const src = source() + src.document.views = src.document.views.filter((v) => v.kind !== 'main') + expect(() => buildSheetIndex(src)).toThrow('no main view') + }) +}) + +describe('pickLabel / isObservable', () => { + it('falls back to the other locale and to the empty string', () => { + expect(pickLabel({ fr: 'Hanche', en: 'Hip' }, 'fr')).toBe('Hanche') + expect(pickLabel({ fr: 'Hanche', en: 'Hip' }, 'en')).toBe('Hip') + expect(pickLabel({ fr: 'Hanche', en: '' }, 'en')).toBe('Hanche') + expect(pickLabel({ fr: '', en: 'Hip' }, 'fr')).toBe('Hip') + expect(pickLabel(null, 'fr')).toBe('') + expect(pickLabel(undefined, 'en')).toBe('') + }) + + it('tells observable annotations from triggers', () => { + const index = buildSheetIndex(source()) + expect(isObservable(index.annotation('hip'))).toBe(true) + expect(isObservable(index.annotation('head-trigger'))).toBe(false) + expect(isObservable(undefined)).toBe(false) + }) +}) diff --git a/packages/pdf/eslint.config.js b/packages/pdf/eslint.config.js new file mode 100644 index 00000000..f3859bf0 --- /dev/null +++ b/packages/pdf/eslint.config.js @@ -0,0 +1,48 @@ +import globals from 'globals' +import tseslint from 'typescript-eslint' + +/** + * The engine must run without a browser and without Node-only APIs + * (STEP6 §3.3): the restricted globals and imports apply to `src/**` only, + * tests may read fixtures with node:fs. + */ +const BROWSER_OR_NODE_GLOBALS = [ + 'fetch', + 'window', + 'document', + 'Image', + 'DOMParser', + 'XMLSerializer', + 'navigator', + 'Buffer', + 'process', + 'require', +] + +export default tseslint.config( + { ignores: ['node_modules/**'] }, + { + files: ['**/*.ts'], + extends: [...tseslint.configs.recommended], + languageOptions: { + globals: { ...globals.node, ...globals.es2022 }, + }, + rules: { + '@typescript-eslint/no-explicit-any': 'warn', + '@typescript-eslint/no-unused-vars': [ + 'error', + { argsIgnorePattern: '^_' }, + ], + }, + }, + { + files: ['src/**/*.ts'], + rules: { + 'no-restricted-globals': ['error', ...BROWSER_OR_NODE_GLOBALS], + 'no-restricted-imports': [ + 'error', + { patterns: ['@/*', 'react*', 'node:*'] }, + ], + }, + }, +) diff --git a/packages/pdf/package.json b/packages/pdf/package.json new file mode 100644 index 00000000..f44abaee --- /dev/null +++ b/packages/pdf/package.json @@ -0,0 +1,37 @@ +{ + "name": "@faunosteo/pdf", + "version": "0.1.0", + "private": true, + "description": "Faunosteo PDF engine: exports a report archive (pages + envelope attachment) from explicit inputs and reads an archive back, without a browser", + "license": "MIT", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest", + "test:run": "vitest run", + "lint": "eslint . --max-warnings 0", + "build": "tsc -p tsconfig.json --noEmit" + }, + "dependencies": { + "@faunosteo/anatomy": "workspace:*", + "@faunosteo/domain": "workspace:*", + "@pdf-lib/standard-fonts": "^1.0.0", + "@xmldom/xmldom": "^0.9.8", + "pdf-lib": "^1.17.1" + }, + "devDependencies": { + "@pdf-lib/upng": "^1.0.1", + "@resvg/resvg-js": "^2.6.2", + "@types/node": "^20.19.41", + "eslint": "^9.17.0", + "globals": "^15.14.0", + "typescript": "^5.7.2", + "typescript-eslint": "^8.19.0", + "vitest": "^3.2.7" + } +} diff --git a/packages/pdf/src/attachment/inflate.ts b/packages/pdf/src/attachment/inflate.ts new file mode 100644 index 00000000..59521f56 --- /dev/null +++ b/packages/pdf/src/attachment/inflate.ts @@ -0,0 +1,83 @@ +/** + * Hard ceiling on an attachment, inflated or not: a report archive weighs a + * few hundred KB; anything bigger is a decompression bomb or corruption. + */ +export const MAX_ATTACHMENT_BYTES = 16 * 1024 * 1024 + +/** + * Compressed bytes handed to the inflater per write. Chromium's + * `DecompressionStream` inflates everything it has been given before the + * consumer reads it, so a stream written whole lets a bomb inflate gigabytes + * before `reader.cancel()` lands (measured: +2.2 GB RSS on a 4 MB / 4 GiB + * bomb). One awaited slice at a time keeps that read-ahead to what 16 KiB + * can inflate (about 16 MiB). + */ +const WRITE_SLICE_BYTES = 16 * 1024 + +type Writer = WritableStreamDefaultWriter<Uint8Array<ArrayBuffer>> +type Reader = ReadableStreamDefaultReader<Uint8Array> + +function concat(chunks: Uint8Array[], total: number): Uint8Array { + const out = new Uint8Array(total) + let offset = 0 + for (const chunk of chunks) { + out.set(chunk, offset) + offset += chunk.byteLength + } + return out +} + +/** Feeds the inflater one slice per awaited write, then closes it. */ +async function feedSlices(writer: Writer, bytes: Uint8Array): Promise<void> { + // The cast compiles under both the engine (node) and the app (DOM) libs. + const source = bytes as Uint8Array<ArrayBuffer> + for (let at = 0; at < source.byteLength; at += WRITE_SLICE_BYTES) { + await writer.write(source.subarray(at, at + WRITE_SLICE_BYTES)) + } + await writer.close() +} + +/** Collects the inflated chunks; null as soon as their total exceeds `limit`. */ +async function drainUnder( + reader: Reader, + limit: number, +): Promise<Uint8Array | null> { + const chunks: Uint8Array[] = [] + let total = 0 + for (;;) { + const { done, value } = await reader.read() + if (done) return concat(chunks, total) + total += value.byteLength + if (total > limit) return null + chunks.push(value) + } +} + +/** + * FlateDecode (zlib framing) under `limit`, the attachment cap by default. + * Null on any failure (truncated or corrupt stream, trailing junk, bad + * checksum) or as soon as the output exceeds the limit. The feed and the + * drain run concurrently; over the limit both sides are torn down, which + * also rejects the feed's pending write. + */ +export async function inflateFlate( + bytes: Uint8Array, + limit: number = MAX_ATTACHMENT_BYTES, +): Promise<Uint8Array | null> { + if (typeof DecompressionStream === 'undefined') return null + const inflater = new DecompressionStream('deflate') + const writer = inflater.writable.getWriter() + const reader = inflater.readable.getReader() + // A stream error surfaces on the drain; the feed's own rejection is noise. + const fed = feedSlices(writer, bytes) + fed.catch(() => undefined) + try { + const out = await drainUnder(reader, limit) + if (out === null) { + await Promise.allSettled([reader.cancel(), writer.abort()]) + } + return out + } catch { + return null + } +} diff --git a/packages/pdf/src/attachment/read.ts b/packages/pdf/src/attachment/read.ts new file mode 100644 index 00000000..c4c17c0e --- /dev/null +++ b/packages/pdf/src/attachment/read.ts @@ -0,0 +1,36 @@ +import { ArchiveReadError } from '../errors' +import { + ARCHIVE_STAMP, + hasPdfHeader, + locateAttachment, + MAX_PDF_BYTES, +} from './scan' + +/** + * The raw JSON a Faunosteo PDF carries, read from the bytes alone (BLK-009): + * no PDF object graph is parsed, so no object stream is ever inflated. pdf-lib + * stays on the export side. + */ + +export { ATTACHMENT_NAME_PREFIX } from './scan' +export const PDF_KEYWORD = `${ARCHIVE_STAMP}/1` + +/** Size cap first, then the `%PDF-` header: anything else is `invalid_pdf`. */ +function assertPdfBytes(bytes: Uint8Array): void { + if (bytes.byteLength > MAX_PDF_BYTES || !hasPdfHeader(bytes)) { + throw new ArchiveReadError('invalid_pdf') + } +} + +/** + * The raw JSON carried by the PDF, whatever its shape (bare report of any + * version or archive envelope), before any validation: what the archive + * check tool shows next to the read result. Throws ArchiveReadError + * (`invalid_pdf`, `no_attachment`, `attachment_stripped`). + */ +export async function readAttachedDocument( + bytes: Uint8Array, +): Promise<unknown> { + assertPdfBytes(bytes) + return (await locateAttachment(bytes)).data +} diff --git a/packages/pdf/src/attachment/scan.ts b/packages/pdf/src/attachment/scan.ts new file mode 100644 index 00000000..4e124dc8 --- /dev/null +++ b/packages/pdf/src/attachment/scan.ts @@ -0,0 +1,549 @@ +import { ArchiveReadError } from '../errors' +import { inflateFlate, MAX_ATTACHMENT_BYTES } from './inflate' + +/** + * Locates the Faunosteo attachment by scanning the PDF bytes (BLK-009): a + * stream object can never live inside an object stream, so every + * `/Type /EmbeddedFile` dictionary and its data are in clear in the file. + * Nothing here parses the object graph, the xref or an `/ObjStm`, so the + * only inflation on the import path is the capped one of `inflateFlate`. + * The scanner never throws on garbage: it returns fewer candidates. + */ + +/** A Faunosteo PDF weighs a few hundred KB; anything larger is not one. */ +export const MAX_PDF_BYTES = 50 * 1024 * 1024 + +export const ATTACHMENT_NAME_PREFIX = 'osteo-report' +/** The keyword stamp every archive carries (`faunosteo-archive/<n>`). */ +export const ARCHIVE_STAMP = 'faunosteo-archive' + +/** Candidates beyond this count are ignored: a crafted file cannot make the reader loop. */ +const MAX_CANDIDATES = 32 +/** A stream or Filespec dictionary is small; a longer one is skipped. */ +const MAX_DICT_BYTES = 4096 +/** Window read before a dictionary for its `n 0 obj` header. */ +const HEADER_WINDOW = 48 + +export interface EmbeddedFileCandidate { + /** First byte of the stream data. */ + offset: number + /** Byte count of the stream data (declared, or measured to `endstream`). */ + length: number + filter: 'FlateDecode' | null + /** From a visible `/Filespec` whose `/EF /F` points at this stream. */ + name: string | null +} + +const encode = (text: string): Uint8Array => + Uint8Array.from(text, (c) => c.charCodeAt(0)) + +const TYPE = encode('/Type') +const EMBEDDED_FILE = encode('/EmbeddedFile') +const FILESPEC = encode('/Filespec') +const KEYWORDS = encode('/Keywords') +const STREAM = encode('stream') +const ENDSTREAM = encode('endstream') +const PDF_HEADER = encode('%PDF-') + +// --------------------------------------------------------------------------- +// Byte helpers: every loop is bounded by `end` (at most MAX_PDF_BYTES) + +function isWhitespace(byte: number): boolean { + return ( + byte === 0x20 || + byte === 0x0a || + byte === 0x0d || + byte === 0x09 || + byte === 0x0c || + byte === 0x00 + ) +} + +/** PDF delimiters and whitespace end a name token. */ +function isDelimiter(byte: number): boolean { + return isWhitespace(byte) || '()<>[]{}/%'.includes(String.fromCharCode(byte)) +} + +/** Naive forward search; the needle's first byte is the fast reject. */ +function indexOf( + bytes: Uint8Array, + needle: Uint8Array, + from: number, + end: number, +): number { + const last = end - needle.length + const first = needle[0]! + for (let i = Math.max(from, 0); i <= last; i += 1) { + if (bytes[i] !== first) continue + let j = 1 + while (j < needle.length && bytes[i + j] === needle[j]) j += 1 + if (j === needle.length) return i + } + return -1 +} + +function skipWhitespace(bytes: Uint8Array, from: number, end: number): number { + let i = from + while (i < end && isWhitespace(bytes[i]!)) i += 1 + return i +} + +/** Latin-1 view of a small window (never the whole file). */ +function latin1(bytes: Uint8Array, start: number, end: number): string { + let out = '' + for (let i = start; i < end; i += 1) out += String.fromCharCode(bytes[i]!) + return out +} + +/** UTF-16BE with BOM (how pdf-lib writes text strings) or Latin-1 bytes. */ +function decodeTextBytes(raw: number[]): string { + if (raw.length >= 2 && raw[0] === 0xfe && raw[1] === 0xff) { + let out = '' + for (let i = 2; i + 1 < raw.length; i += 2) { + out += String.fromCharCode((raw[i]! << 8) | raw[i + 1]!) + } + return out + } + return String.fromCharCode(...raw) +} + +/** A `(literal)` or `<hex>` string token as text; null for anything else. */ +export function decodePdfString(token: string): string | null { + if (token.startsWith('<') && token.endsWith('>')) { + const hex = token.slice(1, -1).replace(/[^0-9a-fA-F]/g, '') + const raw: number[] = [] + for (let i = 0; i + 1 < hex.length; i += 2) { + raw.push(parseInt(hex.slice(i, i + 2), 16)) + } + return decodeTextBytes(raw) + } + if (token.startsWith('(') && token.endsWith(')')) { + const body = token.slice(1, -1).replace(/\\([()\\])/g, '$1') + return decodeTextBytes(Array.from(body, (c) => c.charCodeAt(0) & 0xff)) + } + return null +} + +// --------------------------------------------------------------------------- +// Dictionaries: `/Type /Name` matches and their `<< … >>` bounds + +/** Every `/Type /<name>` (space optional) whose name ends on a delimiter. */ +function findTypedDicts( + bytes: Uint8Array, + name: Uint8Array, + end: number, +): number[] { + const hits: number[] = [] + let from = 0 + while (hits.length < MAX_CANDIDATES) { + const at = indexOf(bytes, name, from, end) + if (at < 0) break + from = at + name.length + const after = at + name.length + if (after < end && !isDelimiter(bytes[after]!)) continue + let before = at + while (before > 0 && isWhitespace(bytes[before - 1]!)) before -= 1 + const typeAt = before - TYPE.length + if (typeAt >= 0 && indexOf(bytes, TYPE, typeAt, before) === typeAt) { + hits.push(typeAt) + } + } + return hits +} + +/** Index of the `<<` opening the dictionary holding `pos` (nested dicts skipped); -1 when none. */ +function dictStart(bytes: Uint8Array, pos: number): number { + const floor = Math.max(0, pos - MAX_DICT_BYTES) + let depth = 0 + let i = pos + while (i - 2 >= floor) { + const pair = (bytes[i - 2]! << 8) | bytes[i - 1]! + if (pair === 0x3e3e) + depth += 1 // >> + else if (pair === 0x3c3c) { + if (depth === 0) return i - 2 + depth -= 1 + } + i -= pair === 0x3e3e || pair === 0x3c3c ? 2 : 1 + } + return -1 +} + +/** Index just past the `>>` closing the dictionary opened at `start`; -1 when none. */ +function dictEnd(bytes: Uint8Array, start: number, end: number): number { + const limit = Math.min(end, start + MAX_DICT_BYTES) + let depth = 0 + let i = start + while (i + 1 < limit) { + const pair = (bytes[i]! << 8) | bytes[i + 1]! + if (pair === 0x3c3c) depth += 1 + else if (pair === 0x3e3e) { + depth -= 1 + if (depth === 0) return i + 2 + } + i += pair === 0x3c3c || pair === 0x3e3e ? 2 : 1 + } + return -1 +} + +interface DictSpan { + start: number + end: number + text: string + objectNumber: number | null +} + +/** The dictionary around a `/Type` match, its text and the `n 0 obj` header before it. */ +function dictAround( + bytes: Uint8Array, + pos: number, + end: number, +): DictSpan | null { + const start = dictStart(bytes, pos) + if (start < 0) return null + const close = dictEnd(bytes, start, end) + if (close < 0) return null + const header = latin1(bytes, Math.max(0, start - HEADER_WINDOW), start) + const match = /(\d{1,10})\s+\d{1,10}\s+obj\s*$/.exec(header) + return { + start, + end: close, + text: latin1(bytes, start, close), + objectNumber: match ? Number(match[1]) : null, + } +} + +// --------------------------------------------------------------------------- +// Stream data bounds + +/** Data offset after `stream` + `\r\n` or `\n`; -1 when the keyword is missing. */ +function streamDataOffset( + bytes: Uint8Array, + dictClose: number, + end: number, +): number { + const at = skipWhitespace(bytes, dictClose, end) + if (indexOf(bytes, STREAM, at, Math.min(end, at + STREAM.length)) !== at) { + return -1 + } + let i = at + STREAM.length + if (bytes[i] === 0x0d) i += 1 + if (bytes[i] !== 0x0a) return -1 + return i + 1 +} + +/** A direct `/Length N` (never an `N 0 R` reference), when it lands on `endstream`. */ +function declaredLength( + bytes: Uint8Array, + dict: string, + offset: number, + end: number, +): number | null { + const match = /\/Length\s+(\d{1,10})(?!\d)(?!\s+\d+\s+R)/.exec(dict) + if (!match) return null + const length = Number(match[1]) + if (offset + length > end) return null + const tail = skipWhitespace(bytes, offset + length, end) + const found = indexOf( + bytes, + ENDSTREAM, + tail, + Math.min(end, tail + ENDSTREAM.length), + ) + return found === tail ? length : null +} + +/** Farthest `endstream` worth finding: a longer candidate is refused anyway. */ +const MEASURE_WINDOW = MAX_ATTACHMENT_BYTES + 16 + +/** Index of the first `endstream` at or after `offset`, within MEASURE_WINDOW; -1 when none. */ +type EndstreamFinder = (offset: number) => number + +/** + * Searches `endstream` once over the file instead of once per candidate: + * candidates come in offset order (`embeddedStreamHeads` sorts them), so the + * last hit serves every offset before it and a miss clears the bytes it + * covered for the next search. An offset out of order (never produced since + * the sort) restarts the search: a defensive fallback, never the normal path. + */ +function endstreamFinder(bytes: Uint8Array, end: number): EndstreamFinder { + let lastHit = -1 + let clearedTo = 0 + let lastOffset = 0 + return (offset) => { + if (offset < lastOffset) { + lastHit = -1 + clearedTo = 0 + } + lastOffset = offset + if (lastHit >= offset) return lastHit + const limit = Math.min(end, offset + MEASURE_WINDOW) + const at = indexOf(bytes, ENDSTREAM, Math.max(offset, clearedTo), limit) + if (at >= 0) lastHit = at + else clearedTo = Math.max(clearedTo, limit - ENDSTREAM.length + 1) + return at + } +} + +/** Fallback for an indirect or wrong `/Length`: up to `endstream`, the EOL before it dropped. */ +function measuredLength( + bytes: Uint8Array, + offset: number, + findEndstream: EndstreamFinder, +): number | null { + const at = findEndstream(offset) + if (at < 0) return null + let stop = at + if (stop > offset && bytes[stop - 1] === 0x0a) stop -= 1 + if (stop > offset && bytes[stop - 1] === 0x0d) stop -= 1 + return stop - offset +} + +function filterOf(dict: string): EmbeddedFileCandidate['filter'] { + return /\/Filter\s*(\[\s*)?\/FlateDecode\b/.test(dict) ? 'FlateDecode' : null +} + +/** An `EmbeddedFile` dictionary followed by `stream`, before its data is measured. */ +interface StreamHead { + dict: DictSpan + offset: number +} + +/** + * Every `/Type /EmbeddedFile` dictionary followed by `stream`, sorted by data + * offset (stable). Nested dictionaries list outermost first, so their offsets + * come out descending and each one would reset the `endstream` finder: 32 of + * them rescanned 16 MiB each (audit of 3a6e926, finding 1). Sorted, the + * finder never restarts. + */ +function embeddedStreamHeads(bytes: Uint8Array, end: number): StreamHead[] { + const heads: StreamHead[] = [] + for (const pos of findTypedDicts(bytes, EMBEDDED_FILE, end)) { + const dict = dictAround(bytes, pos, end) + if (!dict) continue + const offset = streamDataOffset(bytes, dict.end, end) + if (offset < 0) continue + heads.push({ dict, offset }) + } + return heads.sort((a, b) => a.offset - b.offset) +} + +function candidateOf( + bytes: Uint8Array, + { dict, offset }: StreamHead, + end: number, + findEndstream: EndstreamFinder, +): Omit<EmbeddedFileCandidate, 'name'> | null { + const length = + declaredLength(bytes, dict.text, offset, end) ?? + measuredLength(bytes, offset, findEndstream) + if (length === null) return null + return { offset, length, filter: filterOf(dict.text) } +} + +// --------------------------------------------------------------------------- +// Filespec names and the keyword stamp + +const STRING_TOKEN = String.raw`\((?:\\.|[^\\)])*\)|<[0-9a-fA-F\s]*>` + +/** `/F` (else `/UF`) of a Filespec dictionary, the `/EF` sub-dictionary set aside. */ +function filespecName(dict: string): string | null { + const withoutEf = dict.replace(/\/EF\s*<<[\s\S]*?>>/, '') + const f = new RegExp(String.raw`/F\s*(${STRING_TOKEN})`).exec(withoutEf) + const uf = new RegExp(String.raw`/UF\s*(${STRING_TOKEN})`).exec(withoutEf) + const token = f?.[1] ?? uf?.[1] + return token ? decodePdfString(token) : null +} + +/** Object number of the stream a Filespec's `/EF << /F n 0 R >>` points at. */ +function filespecStreamObject(dict: string): number | null { + const ef = /\/EF\s*<<([\s\S]*?)>>/.exec(dict) + const ref = ef ? /\/F\s+(\d{1,10})\s+\d{1,10}\s+R/.exec(ef[1]!) : null + return ref ? Number(ref[1]) : null +} + +/** Stream object number → file name, from every Filespec dictionary in clear. */ +function filespecNames(bytes: Uint8Array, end: number): Map<number, string> { + const names = new Map<number, string>() + for (const pos of findTypedDicts(bytes, FILESPEC, end)) { + const dict = dictAround(bytes, pos, end) + if (!dict) continue + const target = filespecStreamObject(dict.text) + const name = filespecName(dict.text) + if (target !== null && name !== null && !names.has(target)) { + names.set(target, name) + } + } + return names +} + +/** The string token right after a `/Keywords` key, as text. */ +function keywordsAt( + bytes: Uint8Array, + keyAt: number, + end: number, +): string | null { + const start = skipWhitespace(bytes, keyAt + KEYWORDS.length, end) + const limit = Math.min(end, start + MAX_DICT_BYTES) + const window = latin1(bytes, start, limit) + const token = new RegExp(`^(?:${STRING_TOKEN})`).exec(window) + return token ? decodePdfString(token[0]) : null +} + +/** True when a visible `/Keywords` string carries the archive stamp. */ +export function hasArchiveStamp(bytes: Uint8Array): boolean { + const end = Math.min(bytes.byteLength, MAX_PDF_BYTES) + let from = 0 + for (let n = 0; n < MAX_CANDIDATES; n += 1) { + const at = indexOf(bytes, KEYWORDS, from, end) + if (at < 0) return false + from = at + KEYWORDS.length + if (isDelimiter(bytes[from] ?? 0x20)) { + if (keywordsAt(bytes, at, end)?.includes(ARCHIVE_STAMP)) return true + } + } + return false +} + +/** `%PDF-` within the first KiB, as viewers accept it. */ +export function hasPdfHeader(bytes: Uint8Array): boolean { + return indexOf(bytes, PDF_HEADER, 0, Math.min(bytes.byteLength, 1024)) >= 0 +} + +// --------------------------------------------------------------------------- +// Public scan + +/** + * Every `/Type /EmbeddedFile` stream of the file, named when its Filespec + * is in clear (export without object streams); `osteo-report*` names first, + * then data offset order. At most MAX_CANDIDATES, within MAX_PDF_BYTES. + */ +export function findEmbeddedFiles(bytes: Uint8Array): EmbeddedFileCandidate[] { + const end = Math.min(bytes.byteLength, MAX_PDF_BYTES) + const names = filespecNames(bytes, end) + const findEndstream = endstreamFinder(bytes, end) + const found: EmbeddedFileCandidate[] = [] + for (const head of embeddedStreamHeads(bytes, end)) { + const candidate = candidateOf(bytes, head, end, findEndstream) + if (!candidate) continue + const { objectNumber } = head.dict + const name = + objectNumber === null ? null : (names.get(objectNumber) ?? null) + found.push({ ...candidate, name }) + } + const named = (c: EmbeddedFileCandidate) => + c.name?.startsWith(ATTACHMENT_NAME_PREFIX) ? 0 : 1 + return found.sort((a, b) => named(a) - named(b)) +} + +/** Raw or inflated stream data under `budget`; null when unusable or inflating past it. */ +async function candidateBytes( + bytes: Uint8Array, + candidate: EmbeddedFileCandidate, + budget: number, +): Promise<Uint8Array | null> { + const data = bytes.subarray( + candidate.offset, + candidate.offset + candidate.length, + ) + if (candidate.filter === null) return data + return inflateFlate(data, budget) +} + +/** `{` first, past an optional UTF-8 BOM and JSON whitespace: the only shape a version lives in. */ +function startsJsonObject(data: Uint8Array): boolean { + let i = 0 + if (data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) i = 3 + while ( + i < data.byteLength && + ' \t\n\r'.includes(String.fromCharCode(data[i]!)) + ) { + i += 1 + } + return data[i] === 0x7b +} + +/** The report and its envelope nest under 16 levels; deeper is not ours. */ +const MAX_JSON_DEPTH = 64 + +/** + * Linear bracket-depth count over the raw bytes before `JSON.parse`: a 16 MiB + * document nested thousands deep costs the parser a second and a gigabyte + * (audit of 3a6e926, finding 3). String literals are skipped, their escapes + * honoured; UTF-8 continuation bytes never collide with the ASCII tokens. + */ +function withinJsonDepth(data: Uint8Array): boolean { + let depth = 0 + let inString = false + for (let i = 0; i < data.byteLength; i += 1) { + const byte = data[i]! + if (inString) { + if (byte === 0x5c) i += 1 // backslash: the escaped byte is skipped + else if (byte === 0x22) inString = false + continue + } + if (byte === 0x22) inString = true + else if (byte === 0x7b || byte === 0x5b) { + depth += 1 + if (depth > MAX_JSON_DEPTH) return false + } else if (byte === 0x7d || byte === 0x5d) depth -= 1 + } + return true +} + +/** JSON with a numeric `envelopeVersion` or `version`; undefined otherwise. */ +function parseVersioned(data: Uint8Array): unknown { + let parsed: unknown + try { + parsed = JSON.parse(new TextDecoder().decode(data)) + } catch { + return undefined + } + if (typeof parsed !== 'object' || parsed === null) return undefined + const record = parsed as Record<string, unknown> + const versioned = + typeof record['envelopeVersion'] === 'number' || + typeof record['version'] === 'number' + return versioned ? parsed : undefined +} + +export interface LocatedAttachment { + bytes: Uint8Array + data: unknown +} + +/** + * The first candidate whose data is a versioned JSON document, decoded once. + * None: `attachment_stripped` when the stamp is visible, else `no_attachment`. + * One MAX_ATTACHMENT_BYTES budget of content (raw or inflated) is shared by + * every candidate: a candidate that does not fit what is left ends the + * search, so at most 16 MiB of candidate content is retained and parsed. A + * cancelled inflation is not charged (audit of 3a6e926, finding 2), so up to + * MAX_CANDIDATES oversized streams may each cost one capped inflation of CPU + * (bounded, no memory retained); charging them would let bombs starve a real + * unnamed attachment placed after them. + */ +export async function locateAttachment( + bytes: Uint8Array, +): Promise<LocatedAttachment> { + let budget = MAX_ATTACHMENT_BYTES + for (const candidate of findEmbeddedFiles(bytes)) { + if (candidate.length > budget) break + const data = await candidateBytes(bytes, candidate, budget) + if (!data) continue + budget -= data.byteLength + if (!startsJsonObject(data) || !withinJsonDepth(data)) continue + const parsed = parseVersioned(data) + if (parsed !== undefined) return { bytes: data, data: parsed } + } + throw new ArchiveReadError( + hasArchiveStamp(bytes) ? 'attachment_stripped' : 'no_attachment', + ) +} + +/** The attachment's decoded bytes (BLK-009 reader). Throws ArchiveReadError. */ +export async function readAttachmentBytes( + bytes: Uint8Array, +): Promise<Uint8Array> { + return (await locateAttachment(bytes)).bytes +} diff --git a/packages/pdf/src/attachment/write.ts b/packages/pdf/src/attachment/write.ts new file mode 100644 index 00000000..b328ac51 --- /dev/null +++ b/packages/pdf/src/attachment/write.ts @@ -0,0 +1,19 @@ +import { AFRelationship, type PDFDocument } from 'pdf-lib' + +export const ATTACHMENT_FILENAME = 'osteo-report.json' +export const ATTACHMENT_DESCRIPTION = 'Faunosteo report archive v1' + +/** The envelope bytes as a native embedded file; every date is `exportedAt`. */ +export async function attachEnvelope( + pdfDoc: PDFDocument, + bytes: Uint8Array, + exportedAt: Date, +): Promise<void> { + await pdfDoc.attach(bytes, ATTACHMENT_FILENAME, { + mimeType: 'application/json', + description: ATTACHMENT_DESCRIPTION, + creationDate: exportedAt, + modificationDate: exportedAt, + afRelationship: AFRelationship.Data, + }) +} diff --git a/packages/pdf/src/branding.ts b/packages/pdf/src/branding.ts new file mode 100644 index 00000000..c112142f --- /dev/null +++ b/packages/pdf/src/branding.ts @@ -0,0 +1,291 @@ +import type { PDFDocument, PDFImage } from 'pdf-lib' +import type { Branding, Credit, ImageAsset } from '@faunosteo/domain' +import { inflateFlate, MAX_ATTACHMENT_BYTES } from './attachment/inflate' +import type { ExportWarning, Rasterizer } from './types' +import { renderBrandingSvg } from './svg/view' + +/** + * The branding images embedded once per document. A PNG is decoded from + * its base64 once its header, chunk list and IDAT stream pass `pngIssue`; + * an SVG is sanitised and rasterised at the view width. Each slot fails + * alone: the page prints the credit's fallback text instead and the export + * reports a `logo_failed` warning. + */ + +/** + * A logo PNG is at most 4096² pixels and 8192 px a side (STEP6 §15), and + * its raw (filtered, uncompressed) scanlines fit the attachment cap, the + * most the native inflater is allowed to produce. + */ +export const PNG_CAPS = { + side: 8192, + pixels: 4096 * 4096, + rawBytes: MAX_ATTACHMENT_BYTES, +} as const + +const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] +/** A chunk is length (4), type (4), data (length), CRC (4). */ +const CHUNK_HEAD = 8 +const CHUNK_OVERHEAD = 12 +const IHDR_LENGTH = 13 +const IHDR_END = PNG_SIGNATURE.length + CHUNK_OVERHEAD + IHDR_LENGTH + +/** The big-endian uint32 a four-letter chunk type reads as. */ +const chunkType = (name: string): number => + [...name].reduce((acc, char) => acc * 256 + char.charCodeAt(0), 0) + +const IHDR_TYPE = chunkType('IHDR') +const IDAT_TYPE = chunkType('IDAT') +const IEND_TYPE = chunkType('IEND') +/** + * The chunk types UPNG reads by fixed offsets or by declared length. A + * second IHDR resizes the decoder's buffer, APNG frames are not a logo, and + * every text or profile chunk (`tEXt`, `iTXt`, `zTXt`, `iCCP`) is read with + * `_bin.nextZero` (`while (data[p] != 0) p++`), which never stops when no + * NUL byte follows in the buffer: all of them stay out of the list. + */ +const ALLOWED_CHUNKS = new Set( + [ + 'PLTE', + 'tRNS', + 'IDAT', + 'IEND', + 'gAMA', + 'cHRM', + 'sRGB', + 'sBIT', + 'pHYs', + 'bKGD', + ].map(chunkType), +) + +/** Samples per pixel and the bit depths the PNG spec allows, by colour type. */ +const CHANNELS: Record<number, number> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 } +const DEPTHS: Record<number, readonly number[]> = { + 0: [1, 2, 4, 8, 16], + 2: [8, 16], + 3: [1, 2, 4, 8], + 4: [8, 16], + 6: [8, 16], +} + +export type PngIssue = 'signature' | 'dimensions' | 'ihdr' | 'chunks' | 'idat' + +/** The 13 IHDR fields, read as announced. */ +interface PngHeader { + width: number + height: number + depth: number + colourType: number + compression: number + filter: number + interlace: number +} + +export type LogoSlot = Extract<ExportWarning, { kind: 'logo_failed' }>['slot'] + +export interface CreditAsset { + image: PDFImage | null + url: string + fallbackText: string +} + +export interface BrandingImages { + siteUrl: string + header: PDFImage | null + footer: PDFImage | null + poweredBy: CreditAsset | null + partner: CreditAsset | null +} + +/** + * Why a PNG is refused before UPNG sees it, or null when it may be decoded. + * In order: the signature and a first 13-byte IHDR (`signature`); the + * announced size under `PNG_CAPS` (`dimensions`); IHDR fields the spec + * allows, non-interlaced (`ihdr`); an allowlisted chunk list closed by an + * empty `IEND` (`chunks`); an IDAT stream the native inflater accepts and + * that yields exactly the raw scanline size (`idat`). UPNG's `inflateRaw` + * never checks its input bound, so a truncated or crafted stream makes it + * read past the buffer and never return; its bitmap is sized from whatever + * IHDR claims; and `nextZero` scans text chunks for a NUL that may be + * missing. Each check closes one of those paths. + */ +export async function pngIssue(bytes: Uint8Array): Promise<PngIssue | null> { + if (bytes.byteLength < IHDR_END) return 'signature' + if (PNG_SIGNATURE.some((byte, i) => bytes[i] !== byte)) return 'signature' + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength) + if (view.getUint32(8) !== IHDR_LENGTH) return 'signature' + if (view.getUint32(12) !== IHDR_TYPE) return 'signature' + const header = readHeader(view) + const headerProblem = headerIssue(header) + if (headerProblem) return headerProblem + const rawSize = expectedRawSize(header) + if (rawSize > PNG_CAPS.rawBytes) return 'dimensions' + return chunkListIssue(view) ?? idatIssue(view, rawSize) +} + +function readHeader(view: DataView): PngHeader { + return { + width: view.getUint32(16), + height: view.getUint32(20), + depth: view.getUint8(24), + colourType: view.getUint8(25), + compression: view.getUint8(26), + filter: view.getUint8(27), + interlace: view.getUint8(28), + } +} + +/** + * The size budget, then the IHDR fields: a side of 0 would give the page + * stream an Infinity scale, an unknown colour type or depth (255 at 4096² + * costs seconds of CPU in UPNG) has no raw size to check against, and an + * interlaced image is refused outright: no archived logo is interlaced and + * the Adam7 pass sizes are not worth computing here. + */ +function headerIssue(header: PngHeader): PngIssue | null { + const { width, height, depth, colourType } = header + if (width < 1 || height < 1) return 'dimensions' + if (width > PNG_CAPS.side || height > PNG_CAPS.side) return 'dimensions' + if (width * height > PNG_CAPS.pixels) return 'dimensions' + if (!DEPTHS[colourType]?.includes(depth)) return 'ihdr' + if (header.compression !== 0 || header.filter !== 0) return 'ihdr' + if (header.interlace !== 0) return 'ihdr' + return null +} + +/** Non-interlaced raw size: each scanline is a filter byte plus its packed samples. */ +function expectedRawSize(header: PngHeader): number { + const bitsPerPixel = CHANNELS[header.colourType]! * header.depth + const rowBytes = Math.ceil((header.width * bitsPerPixel) / 8) + 1 + return rowBytes * header.height +} + +/** + * Walks the chunks after the first IHDR to an `IEND` of length 0 that ends + * the buffer exactly. Any type outside `ALLOWED_CHUNKS` (a second IHDR, an + * APNG chunk, a `tEXt`/`iTXt` whose missing NUL would spin UPNG's + * `nextZero` forever, an unknown type), a declared length past the buffer, + * a truncated chunk head, a missing IEND or bytes after it are refused. + */ +function chunkListIssue(view: DataView): PngIssue | null { + let offset = IHDR_END + while (offset + CHUNK_HEAD <= view.byteLength) { + const length = view.getUint32(offset) + const type = view.getUint32(offset + 4) + const next = offset + CHUNK_OVERHEAD + length + if (next > view.byteLength) return 'chunks' + if (!ALLOWED_CHUNKS.has(type)) return 'chunks' + if (type === IEND_TYPE) { + return length === 0 && next === view.byteLength ? null : 'chunks' + } + offset = next + } + return 'chunks' +} + +/** The IDAT payloads in file order, one zlib stream; the chunk list is already known sound. */ +function idatPayload(view: DataView): Uint8Array { + const parts: Uint8Array[] = [] + let total = 0 + let offset = IHDR_END + while (offset + CHUNK_HEAD <= view.byteLength) { + const length = view.getUint32(offset) + if (view.getUint32(offset + 4) === IDAT_TYPE) { + const start = view.byteOffset + offset + CHUNK_HEAD + parts.push(new Uint8Array(view.buffer, start, length)) + total += length + } + offset += CHUNK_OVERHEAD + length + } + const payload = new Uint8Array(total) + let at = 0 + for (const part of parts) { + payload.set(part, at) + at += part.byteLength + } + return payload +} + +/** + * Inflates the IDAT stream with the native, bounded inflater before UPNG's + * unbounded `inflateRaw` does: a truncated, corrupt or oversized stream, or + * one that does not yield exactly the raw scanline size, is refused. + */ +async function idatIssue( + view: DataView, + rawSize: number, +): Promise<PngIssue | null> { + const raw = await inflateFlate(idatPayload(view), rawSize) + if (!raw || raw.byteLength !== rawSize) return 'idat' + return null +} + +function base64ToBytes(base64: string): Uint8Array { + const binary = atob(base64) + const bytes = new Uint8Array(binary.length) + for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i) + return bytes +} + +async function embedImage( + pdfDoc: PDFDocument, + asset: ImageAsset, + rasterizer: Rasterizer, +): Promise<PDFImage> { + if (asset.kind === 'png') { + const bytes = base64ToBytes(asset.base64) + const issue = await pngIssue(bytes) + if (issue) throw new Error(`png refused: ${issue}`) + return pdfDoc.embedPng(bytes) + } + const { svg, size } = renderBrandingSvg(asset.svg) + return pdfDoc.embedPng(await rasterizer(svg, size)) +} + +interface Embedder { + pdfDoc: PDFDocument + rasterizer: Rasterizer + warnings: ExportWarning[] +} + +async function embedSlot( + embedder: Embedder, + slot: LogoSlot, + asset: ImageAsset | null, +): Promise<PDFImage | null> { + if (!asset) return null + try { + return await embedImage(embedder.pdfDoc, asset, embedder.rasterizer) + } catch { + embedder.warnings.push({ kind: 'logo_failed', slot }) + return null + } +} + +async function embedCredit( + embedder: Embedder, + slot: LogoSlot, + credit: Credit | null, +): Promise<CreditAsset | null> { + if (!credit) return null + return { + image: await embedSlot(embedder, slot, credit.logo), + url: credit.url, + fallbackText: credit.fallbackText, + } +} + +/** Embeds the four slots in a fixed order: header, footer, powered-by, partner. */ +export async function embedBranding( + embedder: Embedder, + branding: Branding, +): Promise<BrandingImages> { + return { + siteUrl: branding.siteUrl, + header: await embedSlot(embedder, 'headerLogo', branding.headerLogo), + footer: await embedSlot(embedder, 'footerLogo', branding.footerLogo), + poweredBy: await embedCredit(embedder, 'poweredBy', branding.poweredBy), + partner: await embedCredit(embedder, 'partner', branding.partner), + } +} diff --git a/packages/pdf/src/errors.ts b/packages/pdf/src/errors.ts new file mode 100644 index 00000000..9480f15c --- /dev/null +++ b/packages/pdf/src/errors.ts @@ -0,0 +1,55 @@ +/** + * Typed failures of the engine. The app maps the kinds to its messages; no + * message here echoes untrusted input. + */ + +export type ArchiveReadErrorKind = + | 'invalid_pdf' + | 'no_attachment' + | 'attachment_stripped' + | 'incompatible_version' + +export class ArchiveReadError extends Error { + constructor( + public readonly kind: ArchiveReadErrorKind, + /** The report version found, for `incompatible_version`. */ + public readonly foundVersion?: number | null, + ) { + super(kind) + this.name = 'ArchiveReadError' + } +} + +export type ArchiveExportErrorKind = + | 'snapshot_invalid' + | 'snapshot_too_large' + | 'sheet_mismatch' + | 'too_many_pages' + /** The branding or the label set fails its schema (URLs included). */ + | 'branding_invalid' + +export class ArchiveExportError extends Error { + constructor( + public readonly kind: ArchiveExportErrorKind, + detail = '', + ) { + super(detail ? `${kind}: ${detail}` : kind) + this.name = 'ArchiveExportError' + } +} + +export type SvgRejection = + | 'doctype' + | 'malformed' + | 'not_svg' + | 'too_many_elements' + | 'too_deep' + | 'too_many_uses' + +/** An SVG text the sanitiser refuses outright (STEP6 §15). */ +export class SvgRejectedError extends Error { + constructor(public readonly reason: SvgRejection) { + super(`svg rejected: ${reason}`) + this.name = 'SvgRejectedError' + } +} diff --git a/packages/pdf/src/export.ts b/packages/pdf/src/export.ts new file mode 100644 index 00000000..a74194c0 --- /dev/null +++ b/packages/pdf/src/export.ts @@ -0,0 +1,228 @@ +import { PDFDocument } from 'pdf-lib' +import { + assertSnapshot, + BrandingSchema, + buildSheetIndex, + ENVELOPE_FORMAT, + ENVELOPE_VERSION, + PdfLabelSetSchema, + snapshotIndexSource, + SnapshotError, + type Report, + type ReportArchiveEnvelope, + type SheetIndex, + type SheetSnapshot, +} from '@faunosteo/domain' +import { attachEnvelope } from './attachment/write' +import { MAX_ATTACHMENT_BYTES } from './attachment/inflate' +import { PDF_KEYWORD } from './attachment/read' +import { embedBranding, type BrandingImages } from './branding' +import { ArchiveExportError, SvgRejectedError } from './errors' +import { addConclusionPage } from './render/conclusionPage' +import type { RenderContext } from './render/context' +import { embedFonts } from './render/fonts' +import { drawFooter } from './render/footer' +import { addObservationPage } from './render/observationPage' +import { cleanSvgRoot } from './svg/view' +import type { + ExportInput, + ExportResult, + ExportWarning, + PdfLocale, + Rasterizer, +} from './types' + +/** + * Exports a report archive from explicit inputs and nothing else: the + * report, the sheet snapshot it was written on, the branding, the labels, + * the locale, a rasterizer and the export time (STEP6 §14 "Export"). The + * attachment embeds exactly what the pages were rendered from, so the file + * re-exports without the current catalog, assets or configuration. + */ + +export const PAGE_CAPS = { + observations: 500, + viewsPerObservation: 8, +} as const + +/** + * Step 0: the branding and the labels pass their schemas again. They reach + * the engine from an archive or from the application and end up in link + * URIs and drawn text, so a caller cannot be trusted to have validated them. + */ +function assertBrandingAndLabels(input: ExportInput): void { + if (!BrandingSchema.safeParse(input.branding).success) { + throw new ArchiveExportError('branding_invalid', 'branding') + } + if (!PdfLabelSetSchema.safeParse(input.labels).success) { + throw new ArchiveExportError('branding_invalid', 'labels') + } +} + +/** Step 1: the snapshot gate, with every asset accepted by the sanitiser. */ +function checkedSnapshot(sheet: SheetSnapshot): SheetSnapshot { + let parsed: SheetSnapshot + try { + parsed = assertSnapshot(sheet) + } catch (error) { + if (!(error instanceof SnapshotError)) throw error + const kind = + error.reason === 'caps' ? 'snapshot_too_large' : 'snapshot_invalid' + throw new ArchiveExportError(kind, error.reason) + } + for (const asset of parsed.assets) { + try { + cleanSvgRoot(asset.svg) + } catch (error) { + if (!(error instanceof SvgRejectedError)) throw error + throw new ArchiveExportError('snapshot_invalid', `asset ${error.reason}`) + } + } + return parsed +} + +/** Steps 2 and 3: the report belongs to this sheet and fits the page budget. */ +function assertExportable(report: Report, sheet: SheetSnapshot): void { + if ( + report.sheet.sheetId !== sheet.ref.sheetId || + report.sheet.documentSha256 !== sheet.ref.documentSha256 + ) { + throw new ArchiveExportError('sheet_mismatch') + } + if (report.observations.length > PAGE_CAPS.observations) { + throw new ArchiveExportError('too_many_pages', 'observations') + } + const tooManyViews = report.observations.some( + (o) => + new Set(o.zones.map((z) => z.viewId)).size > + PAGE_CAPS.viewsPerObservation, + ) + if (tooManyViews) throw new ArchiveExportError('too_many_pages', 'views') +} + +function buildEnvelope( + input: ExportInput, + sheet: SheetSnapshot, +): ReportArchiveEnvelope { + return { + format: ENVELOPE_FORMAT, + envelopeVersion: ENVELOPE_VERSION, + exportedAt: input.exportedAt.toISOString(), + locale: input.locale, + report: input.report, + sheetSnapshot: sheet, + branding: input.branding, + labels: input.labels, + } +} + +/** Step 4: pretty JSON under the attachment cap. */ +function encodeEnvelope(envelope: ReportArchiveEnvelope): Uint8Array { + const bytes = new TextEncoder().encode(JSON.stringify(envelope, null, 2)) + if (bytes.byteLength > MAX_ATTACHMENT_BYTES) { + throw new ArchiveExportError('snapshot_too_large', 'attachment') + } + return bytes +} + +/** Step 5: document information, every date the export time. */ +function setMetadata(pdfDoc: PDFDocument, input: ExportInput): void { + const labels = input.labels[input.locale] + pdfDoc.setTitle( + `${labels['pdf.title.suffix.bilan']}${input.report.animal.name}`, + ) + pdfDoc.setAuthor(input.report.practitioner.name) + pdfDoc.setSubject(labels['pdf.subject']) + pdfDoc.setKeywords([PDF_KEYWORD]) + pdfDoc.setCreationDate(input.exportedAt) + pdfDoc.setModificationDate(input.exportedAt) +} + +interface Pages { + pdfDoc: PDFDocument + input: ExportInput + sheet: SheetSnapshot + index: SheetIndex + ctx: RenderContext + branding: BrandingImages + warnings: ExportWarning[] +} + +/** Steps 8 and 9: one page per observation, the conclusion, footers everywhere. */ +async function drawPages(pages: Pages): Promise<void> { + const { pdfDoc, input, ctx, branding } = pages + const headerAssets = { logo: branding.header, siteUrl: branding.siteUrl } + for (let i = 0; i < input.report.observations.length; i += 1) { + await addObservationPage({ + pdfDoc, + report: input.report, + observation: input.report.observations[i]!, + obsIndex: i, + sheet: pages.index, + snapshot: pages.sheet, + ctx, + headerAssets, + rasterizer: input.rasterizer, + warnings: pages.warnings, + }) + } + await addConclusionPage(pdfDoc, input.report, ctx, headerAssets) + const all = pdfDoc.getPages() + all.forEach((page, idx) => { + const pagination = { pageNumber: idx + 1, totalPages: all.length } + drawFooter(page, pagination, ctx, branding) + }) +} + +export async function exportReportArchive( + input: ExportInput, +): Promise<ExportResult> { + assertBrandingAndLabels(input) + const sheet = checkedSnapshot(input.sheet) + assertExportable(input.report, sheet) + const envelope = buildEnvelope(input, sheet) + const attachment = encodeEnvelope(envelope) + + const pdfDoc = await PDFDocument.create() + setMetadata(pdfDoc, input) + const fonts = await embedFonts(pdfDoc) + const warnings: ExportWarning[] = [] + const branding = await embedBranding( + { pdfDoc, rasterizer: input.rasterizer, warnings }, + input.branding, + ) + await drawPages({ + pdfDoc, + input, + sheet, + index: buildSheetIndex(snapshotIndexSource(sheet)), + ctx: { fonts, locale: input.locale, labels: input.labels[input.locale] }, + branding, + warnings, + }) + await attachEnvelope(pdfDoc, attachment, input.exportedAt) + // No object streams (BLK-009): the Filespec name and the keyword stamp stay + // in clear for the byte-scan reader; the file grows by a few KB. + const pdf = await pdfDoc.save({ useObjectStreams: false }) + return { pdf, envelope, warnings } +} + +export interface ReexportOptions { + locale: PdfLocale + rasterizer: Rasterizer + exportedAt: Date +} + +/** Re-export from an archive alone: no sheet, no network, no configuration. */ +export function exportFromEnvelope( + env: ReportArchiveEnvelope, + opts: ReexportOptions, +): Promise<ExportResult> { + return exportReportArchive({ + report: env.report, + sheet: env.sheetSnapshot, + branding: env.branding, + labels: env.labels, + ...opts, + }) +} diff --git a/packages/pdf/src/i18n/en.ts b/packages/pdf/src/i18n/en.ts new file mode 100644 index 00000000..2ea2aaae --- /dev/null +++ b/packages/pdf/src/i18n/en.ts @@ -0,0 +1,30 @@ +import type { PdfLabels } from '@faunosteo/domain' + +/** Verbatim copy of the app's EN strings the PDF read when Step 6 started. */ +export const en: PdfLabels = { + 'pdf.eyebrow.observation': 'OBSERVATION', + 'pdf.eyebrow.synthesis': 'SYNTHESIS', + 'pdf.title.conclusion': 'Conclusion', + 'pdf.section.zones': 'ZONES', + 'pdf.section.findings_prefix': 'FINDINGS — ', + 'pdf.section.free_findings': 'FREE FINDINGS', + 'pdf.section.severity': 'SEVERITY', + 'pdf.section.comment': 'COMMENT', + 'pdf.section.conclusion': 'CONCLUSION', + 'pdf.section.recommendations': 'RECOMMENDATIONS', + 'pdf.section.next_appointment': 'NEXT APPOINTMENT', + 'pdf.view.general': 'GENERAL VIEW', + 'pdf.view.detail_prefix': 'DETAIL VIEW — ', + 'pdf.empty': '—', + 'pdf.owner_prefix': 'Owner: ', + 'pdf.siret_prefix': 'SIRET ', + 'pdf.title.suffix.bilan': 'Osteo report — ', + 'pdf.subject': 'Animal osteopathic report', + 'severity.mild': 'mild', + 'severity.moderate': 'moderate', + 'severity.severe': 'severe', + 'lateral.left': 'Left', + 'lateral.right': 'Right', + 'footer.powered_by': 'Powered by', + 'footer.in_partnership': 'In partnership with', +} diff --git a/packages/pdf/src/i18n/fr.ts b/packages/pdf/src/i18n/fr.ts new file mode 100644 index 00000000..b4bfdb72 --- /dev/null +++ b/packages/pdf/src/i18n/fr.ts @@ -0,0 +1,30 @@ +import type { PdfLabels } from '@faunosteo/domain' + +/** Verbatim copy of the app's FR strings the PDF read when Step 6 started. */ +export const fr: PdfLabels = { + 'pdf.eyebrow.observation': 'OBSERVATION', + 'pdf.eyebrow.synthesis': 'SYNTHÈSE', + 'pdf.title.conclusion': 'Conclusion', + 'pdf.section.zones': 'ZONES', + 'pdf.section.findings_prefix': 'CONSTATS — ', + 'pdf.section.free_findings': 'CONSTATS LIBRES', + 'pdf.section.severity': 'SÉVÉRITÉ', + 'pdf.section.comment': 'COMMENTAIRE', + 'pdf.section.conclusion': 'CONCLUSION', + 'pdf.section.recommendations': 'RECOMMANDATIONS', + 'pdf.section.next_appointment': 'PROCHAIN RENDEZ-VOUS', + 'pdf.view.general': 'VUE GÉNÉRALE', + 'pdf.view.detail_prefix': 'VUE DÉTAIL — ', + 'pdf.empty': '—', + 'pdf.owner_prefix': 'Propriétaire : ', + 'pdf.siret_prefix': 'SIRET ', + 'pdf.title.suffix.bilan': 'Bilan ostéo — ', + 'pdf.subject': "Bilan d'ostéopathie animalière", + 'severity.mild': 'légère', + 'severity.moderate': 'modérée', + 'severity.severe': 'sévère', + 'lateral.left': 'Gauche', + 'lateral.right': 'Droite', + 'footer.powered_by': 'Propulsé par', + 'footer.in_partnership': 'En partenariat avec', +} diff --git a/packages/pdf/src/i18n/index.ts b/packages/pdf/src/i18n/index.ts new file mode 100644 index 00000000..79edc00f --- /dev/null +++ b/packages/pdf/src/i18n/index.ts @@ -0,0 +1,6 @@ +import type { PdfLabelSet } from '@faunosteo/domain' +import { en } from './en' +import { fr } from './fr' + +/** The wording of the day, frozen into every archive the engine writes. */ +export const defaultPdfLabels: PdfLabelSet = { fr, en } diff --git a/packages/pdf/src/index.ts b/packages/pdf/src/index.ts new file mode 100644 index 00000000..45b327b4 --- /dev/null +++ b/packages/pdf/src/index.ts @@ -0,0 +1,27 @@ +/** + * @faunosteo/pdf — the browser-free PDF engine (STEP6 §13). + */ +export { exportReportArchive, exportFromEnvelope } from './export' +export { readReportArchive, MAX_PDF_BYTES } from './read' +export { readAttachedDocument, PDF_KEYWORD } from './attachment/read' +export { + findEmbeddedFiles, + readAttachmentBytes, + type EmbeddedFileCandidate, +} from './attachment/scan' +export { MAX_ATTACHMENT_BYTES } from './attachment/inflate' +export { + ArchiveReadError, + ArchiveExportError, + type ArchiveReadErrorKind, + type ArchiveExportErrorKind, +} from './errors' +export type { + Rasterizer, + ExportInput, + ExportResult, + ExportWarning, + PdfLocale, +} from './types' +export { defaultPdfLabels } from './i18n' +export { composeHighlightedViewSvg } from './svg/view' diff --git a/packages/pdf/src/read.ts b/packages/pdf/src/read.ts new file mode 100644 index 00000000..56451746 --- /dev/null +++ b/packages/pdf/src/read.ts @@ -0,0 +1,38 @@ +import { + readArchiveDocument, + UnsupportedReportVersionError, + type ArchiveReadOutcome, + type ReportMigrationMap, +} from '@faunosteo/domain' +import { readAttachedDocument } from './attachment/read' +import { ArchiveReadError } from './errors' + +export { MAX_PDF_BYTES } from './attachment/scan' + +/** + * Reads a Faunosteo PDF back: size cap and `%PDF-` header (`invalid_pdf`), + * attachment located by a byte scan (filename first, never a PDF parse: + * BLK-009), JSON, then the layered reading of the domain (report first, then + * the envelope accepted whole or dropped with a reason). An unknown report + * version is `incompatible_version` with that version; any other content + * failure is `no_attachment`, as today. + */ +export async function readReportArchive( + pdfBytes: Uint8Array, + map: ReportMigrationMap, +): Promise<ArchiveReadOutcome> { + const data = await readAttachedDocument(pdfBytes) + try { + return readArchiveDocument(data, map) + } catch (error) { + // A numeric but unknown version is an incompatible Faunosteo report; no + // version at all is not a Faunosteo attachment (today's message). + if ( + error instanceof UnsupportedReportVersionError && + error.foundVersion !== null + ) { + throw new ArchiveReadError('incompatible_version', error.foundVersion) + } + throw new ArchiveReadError('no_attachment') + } +} diff --git a/apps/app/src/pdf/render/conclusionPage.ts b/packages/pdf/src/render/conclusionPage.ts similarity index 58% rename from apps/app/src/pdf/render/conclusionPage.ts rename to packages/pdf/src/render/conclusionPage.ts index b8af4415..84572512 100644 --- a/apps/app/src/pdf/render/conclusionPage.ts +++ b/packages/pdf/src/render/conclusionPage.ts @@ -1,51 +1,84 @@ import { PageSizes, type PDFDocument } from 'pdf-lib' -import type { EmbeddedFonts } from '@/pdf/fonts' import type { Report } from '@faunosteo/domain' -import type { Locale } from '@/i18n/types' -import { getDict } from '@/i18n' -import { drawHeader, type HeaderAssets } from './header' -import { wrapLines } from './text' -import { formatDate } from '@/lib/dates' import { - MARGIN_X, - EYEBROW_Y_OFFSET, - TITLE_Y_OFFSET, - TITLE_RULE_OFFSET, - TITLE_RULE_WIDTH, - SECTION_LABEL_GAP, + COLOR_ACCENT, COLOR_INK, COLOR_MUTED, - COLOR_ACCENT, + EYEBROW_Y_OFFSET, + MARGIN_X, + SECTION_LABEL_GAP, + TITLE_RULE_OFFSET, + TITLE_RULE_WIDTH, + TITLE_Y_OFFSET, } from './constants' +import type { RenderContext } from './context' +import { formatDate } from './dates' +import { drawHeader, type HeaderAssets } from './header' +import { drawText, wrapLines } from './text' const SECTION_TOP_GAP = 28 const SECTION_BLOCK_GAP = 18 const TEXT_LINE_HEIGHT = 14 +interface ConclusionSection { + label: string + body: string + color?: typeof COLOR_INK +} + +function nextAppointmentText(report: Report, ctx: RenderContext): string { + const next = report.nextAppointment! + return next.kind === 'date' ? formatDate(next.date, ctx.locale) : next.text +} + +function conclusionSections( + report: Report, + ctx: RenderContext, +): ConclusionSection[] { + const { labels } = ctx + const sections: ConclusionSection[] = [ + { + label: labels['pdf.section.conclusion'], + body: report.conclusion || labels['pdf.empty'], + }, + { + label: labels['pdf.section.recommendations'], + body: report.recommendations || labels['pdf.empty'], + }, + ] + if (report.nextAppointment) { + sections.push({ + label: labels['pdf.section.next_appointment'], + body: nextAppointmentText(report, ctx) || labels['pdf.empty'], + color: COLOR_MUTED, + }) + } + return sections +} + export async function addConclusionPage( pdfDoc: PDFDocument, report: Report, - fonts: EmbeddedFonts, - locale: Locale, + ctx: RenderContext, headerAssets: HeaderAssets, ): Promise<void> { - const dict = getDict(locale) + const { fonts, labels } = ctx const page = pdfDoc.addPage(PageSizes.A4) const { width, height } = page.getSize() const max = width - MARGIN_X * 2 - drawHeader(page, report, fonts, locale, headerAssets) + drawHeader(page, report, ctx, headerAssets) const eyebrowY = height - EYEBROW_Y_OFFSET const titleY = height - TITLE_Y_OFFSET - page.drawText(dict['pdf.eyebrow.synthesis'], { + drawText(page, labels['pdf.eyebrow.synthesis'], { x: MARGIN_X, y: eyebrowY, size: 9, font: fonts.bodyBold, color: COLOR_ACCENT, }) - page.drawText(dict['pdf.title.conclusion'], { + drawText(page, labels['pdf.title.conclusion'], { x: MARGIN_X, y: titleY, size: 22, @@ -60,35 +93,8 @@ export async function addConclusionPage( }) let cursorY = titleY - SECTION_TOP_GAP - - const sections: Array<{ - label: string - body: string - color?: typeof COLOR_INK - }> = [ - { - label: dict['pdf.section.conclusion'], - body: report.conclusion || dict['pdf.empty'], - }, - { - label: dict['pdf.section.recommendations'], - body: report.recommendations || dict['pdf.empty'], - }, - ] - if (report.nextAppointment) { - const txt = - report.nextAppointment.kind === 'date' - ? formatDate(report.nextAppointment.date, locale) - : report.nextAppointment.text - sections.push({ - label: dict['pdf.section.next_appointment'], - body: txt || dict['pdf.empty'], - color: COLOR_MUTED, - }) - } - - for (const { label, body, color } of sections) { - page.drawText(label, { + for (const { label, body, color } of conclusionSections(report, ctx)) { + drawText(page, label, { x: MARGIN_X, y: cursorY, size: 9, @@ -97,7 +103,7 @@ export async function addConclusionPage( }) cursorY -= SECTION_LABEL_GAP + 10 wrapLines(body, fonts.bodyRegular, 11, max).forEach((line) => { - page.drawText(line, { + drawText(page, line, { x: MARGIN_X, y: cursorY, size: 11, diff --git a/apps/app/src/pdf/render/constants.ts b/packages/pdf/src/render/constants.ts similarity index 58% rename from apps/app/src/pdf/render/constants.ts rename to packages/pdf/src/render/constants.ts index ab9b1c94..c12effbd 100644 --- a/apps/app/src/pdf/render/constants.ts +++ b/packages/pdf/src/render/constants.ts @@ -1,10 +1,9 @@ import { rgb } from 'pdf-lib' /** - * Layout and color constants shared across PDF page renderers (header, - * footer, observation page, conclusion page). Only values that are - * byte-identical across all callers live here — a same-named constant - * with a different value per file stays local to that file. + * Layout and colour constants shared across page renderers (header, footer, + * observation page, conclusion page). Only values identical across callers + * live here; a same-named constant with another value stays local. */ export const MARGIN_X = 36 diff --git a/packages/pdf/src/render/context.ts b/packages/pdf/src/render/context.ts new file mode 100644 index 00000000..a4d013a6 --- /dev/null +++ b/packages/pdf/src/render/context.ts @@ -0,0 +1,11 @@ +import type { PdfLabels } from '@faunosteo/domain' +import type { EmbeddedFonts } from './fonts' + +export type PdfLocale = 'fr' | 'en' + +/** What every page renderer needs besides the page: fonts, locale, labels. */ +export interface RenderContext { + fonts: EmbeddedFonts + locale: PdfLocale + labels: PdfLabels +} diff --git a/packages/pdf/src/render/dates.ts b/packages/pdf/src/render/dates.ts new file mode 100644 index 00000000..f5c5af36 --- /dev/null +++ b/packages/pdf/src/render/dates.ts @@ -0,0 +1,26 @@ +import type { PdfLocale } from './context' + +const LOCALE_TAG: Record<PdfLocale, string> = { + fr: 'fr-FR', + en: 'en-US', +} + +/** + * Long date in the locale for a `YYYY-MM-DD` value. Anything else is + * printed unchanged: a report is user data and never fails the export. + */ +export function formatDate(isoDate: string, locale: PdfLocale): string { + const match = isoDate.match(/^(\d{4})-(\d{2})-(\d{2})$/) + if (!match) return isoDate + const [, y, mo, d] = match + const date = new Date(Date.UTC(Number(y), Number(mo) - 1, Number(d))) + const rolledOver = + date.getUTCMonth() !== Number(mo) - 1 || date.getUTCDate() !== Number(d) + if (Number.isNaN(date.getTime()) || rolledOver) return isoDate + return new Intl.DateTimeFormat(LOCALE_TAG[locale], { + day: 'numeric', + month: 'long', + year: 'numeric', + timeZone: 'UTC', + }).format(date) +} diff --git a/apps/app/src/pdf/fonts.ts b/packages/pdf/src/render/fonts.ts similarity index 87% rename from apps/app/src/pdf/fonts.ts rename to packages/pdf/src/render/fonts.ts index b6465872..c36d7bd6 100644 --- a/apps/app/src/pdf/fonts.ts +++ b/packages/pdf/src/render/fonts.ts @@ -1,5 +1,6 @@ import { PDFDocument, StandardFonts, type PDFFont } from 'pdf-lib' +/** Helvetica body, Times heading: WinAnsi standard fonts (TTF planned). */ export interface EmbeddedFonts { bodyRegular: PDFFont bodyBold: PDFFont diff --git a/packages/pdf/src/render/footer.ts b/packages/pdf/src/render/footer.ts new file mode 100644 index 00000000..1ce317f5 --- /dev/null +++ b/packages/pdf/src/render/footer.ts @@ -0,0 +1,170 @@ +import { rgb, type PDFPage } from 'pdf-lib' +import type { BrandingImages, CreditAsset } from '../branding' +import { COLOR_MUTED, MARGIN_X } from './constants' +import type { RenderContext } from './context' +import { addLinkAnnotation } from './linkAnnotation' +import { drawText, measure } from './text' + +const FOOTER_BASE_Y = 20 +const FONT_SIZE = 8 +const LOGO_W = 80 +const LOGO_H = 30 +const ROW_Y = FOOTER_BASE_Y + 14 +const TEXT_BASE_Y = ROW_Y + 6 +const CREDIT_LOGO_H = 16 +const POWERED_LOGO_W = 70 +const COLOR_RULE = rgb(0.85, 0.83, 0.8) +const COLOR_CREDIT = rgb(0.28, 0.56, 0.42) + +function drawRule(page: PDFPage): void { + const { width } = page.getSize() + const separatorY = ROW_Y + LOGO_H + 6 + page.drawLine({ + start: { x: MARGIN_X, y: separatorY }, + end: { x: width - MARGIN_X, y: separatorY }, + thickness: 0.5, + color: COLOR_RULE, + }) +} + +function drawSiteLogo(page: PDFPage, assets: BrandingImages): void { + if (!assets.footer) return + const rect = { x: MARGIN_X, y: ROW_Y, width: LOGO_W, height: LOGO_H } + page.drawImage(assets.footer, rect) + addLinkAnnotation(page, { ...rect, url: assets.siteUrl }) +} + +function drawMutedLabel( + page: PDFPage, + text: string, + x: number, + ctx: RenderContext, +): void { + drawText(page, text, { + x, + y: TEXT_BASE_Y, + size: FONT_SIZE, + font: ctx.fonts.bodyRegular, + color: COLOR_MUTED, + }) +} + +/** The credit's fallback text in the accent colour, linked. */ +function drawCreditText( + page: PDFPage, + credit: CreditAsset, + x: number, + ctx: RenderContext, +): void { + const font = ctx.fonts.bodyRegular + drawText(page, credit.fallbackText, { + x, + y: TEXT_BASE_Y, + size: FONT_SIZE, + font, + color: COLOR_CREDIT, + }) + addLinkAnnotation(page, { + x, + y: TEXT_BASE_Y - 2, + width: measure(font, credit.fallbackText, FONT_SIZE), + height: FONT_SIZE + 4, + url: credit.url, + }) +} + +function drawCreditLogo( + page: PDFPage, + credit: CreditAsset & { image: NonNullable<CreditAsset['image']> }, + x: number, + width: number, +): void { + const rect = { x, y: ROW_Y + 2, width, height: CREDIT_LOGO_H } + page.drawImage(credit.image, rect) + addLinkAnnotation(page, { ...rect, url: credit.url }) +} + +/** Centred block: label then the fixed-width logo or the fallback text. */ +function drawPoweredBy( + page: PDFPage, + credit: CreditAsset, + ctx: RenderContext, +): void { + const { width } = page.getSize() + const font = ctx.fonts.bodyRegular + const label = `${ctx.labels['footer.powered_by']} ` + const labelW = measure(font, label, FONT_SIZE) + const creditW = credit.image + ? POWERED_LOGO_W + : measure(font, credit.fallbackText, FONT_SIZE) + const x = (width - labelW - creditW) / 2 + drawMutedLabel(page, label, x, ctx) + if (credit.image) { + drawCreditLogo( + page, + { ...credit, image: credit.image }, + x + labelW, + POWERED_LOGO_W, + ) + } else { + drawCreditText(page, credit, x + labelW, ctx) + } +} + +/** Right-aligned block: label then the aspect-sized logo or the handle. */ +function drawPartner( + page: PDFPage, + credit: CreditAsset, + ctx: RenderContext, +): void { + const { width } = page.getSize() + const font = ctx.fonts.bodyRegular + const label = `${ctx.labels['footer.in_partnership']} ` + const labelW = measure(font, label, FONT_SIZE) + const creditW = credit.image + ? CREDIT_LOGO_H * (credit.image.width / credit.image.height) + : measure(font, credit.fallbackText, FONT_SIZE) + const x = width - MARGIN_X - labelW - creditW + drawMutedLabel(page, label, x, ctx) + if (credit.image) { + drawCreditLogo( + page, + { ...credit, image: credit.image }, + x + labelW, + creditW, + ) + } else { + drawCreditText(page, credit, x + labelW, ctx) + } +} + +function drawPageNumber( + page: PDFPage, + pageNumber: number, + totalPages: number, + ctx: RenderContext, +): void { + const { width } = page.getSize() + const text = `${pageNumber} / ${totalPages}` + drawText(page, text, { + x: (width - measure(ctx.fonts.bodyRegular, text, FONT_SIZE)) / 2, + y: FOOTER_BASE_Y + 2, + size: FONT_SIZE, + font: ctx.fonts.bodyRegular, + color: COLOR_MUTED, + }) +} + +/** Rule, site logo, powered-by credit, partner credit, page number. */ +export function drawFooter( + page: PDFPage, + pagination: { pageNumber: number; totalPages: number }, + ctx: RenderContext, + assets: BrandingImages, +): void { + drawRule(page) + drawSiteLogo(page, assets) + if (assets.poweredBy) drawPoweredBy(page, assets.poweredBy, ctx) + if (assets.partner) drawPartner(page, assets.partner, ctx) + drawPageNumber(page, pagination.pageNumber, pagination.totalPages, ctx) +} diff --git a/packages/pdf/src/render/header.ts b/packages/pdf/src/render/header.ts new file mode 100644 index 00000000..58e1c867 --- /dev/null +++ b/packages/pdf/src/render/header.ts @@ -0,0 +1,112 @@ +import type { PDFImage, PDFPage } from 'pdf-lib' +import type { Report } from '@faunosteo/domain' +import { COLOR_INK, COLOR_MUTED, MARGIN_X } from './constants' +import type { RenderContext } from './context' +import { formatDate } from './dates' +import { addLinkAnnotation } from './linkAnnotation' +import { drawText, measure } from './text' + +const TOP_Y = 800 +const LOGO_WIDTH = 100 +const LOGO_HEIGHT = 38 + +export interface HeaderAssets { + logo: PDFImage | null + siteUrl: string +} + +function practitionerLines(report: Report, ctx: RenderContext): string[] { + const { practitioner } = report + return [ + practitioner.name, + practitioner.cabinet, + practitioner.contact, + practitioner.siret + ? `${ctx.labels['pdf.siret_prefix']}${practitioner.siret}` + : undefined, + ].filter((line): line is string => Boolean(line)) +} + +function animalLines(report: Report, ctx: RenderContext): string[] { + const animalLine = [ + report.animal.name, + report.animal.breed ? `(${report.animal.breed})` : '', + report.animal.age ? `· ${report.animal.age}` : '', + ] + .filter(Boolean) + .join(' ') + return [ + animalLine, + `${ctx.labels['pdf.owner_prefix']}${report.owner.name}`, + formatDate(report.date, ctx.locale), + ] +} + +function drawLeftColumn( + page: PDFPage, + lines: string[], + ctx: RenderContext, +): void { + lines.forEach((line, i) => { + drawText(page, line, { + x: MARGIN_X, + y: TOP_Y - i * 12, + size: i === 0 ? 11 : 9, + font: i === 0 ? ctx.fonts.bodyBold : ctx.fonts.bodyRegular, + color: i === 0 ? COLOR_INK : COLOR_MUTED, + }) + }) +} + +function drawRightColumn( + page: PDFPage, + lines: string[], + ctx: RenderContext, +): void { + const { width } = page.getSize() + lines.forEach((line, i) => { + const size = i === 0 ? 11 : 9 + const font = i === 0 ? ctx.fonts.bodyBold : ctx.fonts.bodyRegular + drawText(page, line, { + x: width - MARGIN_X - measure(font, line, size), + y: TOP_Y - i * 12, + size, + font, + color: i === 0 ? COLOR_INK : COLOR_MUTED, + }) + }) +} + +function drawLogo(page: PDFPage, assets: HeaderAssets): void { + if (!assets.logo) return + const { width } = page.getSize() + const rect = { + x: (width - LOGO_WIDTH) / 2, + y: TOP_Y - LOGO_HEIGHT + 10, + width: LOGO_WIDTH, + height: LOGO_HEIGHT, + } + page.drawImage(assets.logo, rect) + addLinkAnnotation(page, { ...rect, url: assets.siteUrl }) +} + +/** Practitioner block left, logo centred, animal block right, then a rule. */ +export function drawHeader( + page: PDFPage, + report: Report, + ctx: RenderContext, + assets: HeaderAssets, +): void { + const { width } = page.getSize() + const left = practitionerLines(report, ctx) + drawLeftColumn(page, left, ctx) + drawLogo(page, assets) + drawRightColumn(page, animalLines(report, ctx), ctx) + const separatorY = TOP_Y - Math.max(left.length * 12, LOGO_HEIGHT) - 8 + page.drawLine({ + start: { x: MARGIN_X, y: separatorY }, + end: { x: width - MARGIN_X, y: separatorY }, + thickness: 0.5, + color: COLOR_MUTED, + }) +} diff --git a/packages/pdf/src/render/linkAnnotation.ts b/packages/pdf/src/render/linkAnnotation.ts new file mode 100644 index 00000000..d3c53da3 --- /dev/null +++ b/packages/pdf/src/render/linkAnnotation.ts @@ -0,0 +1,65 @@ +import { PDFName, PDFHexString, type PDFPage } from 'pdf-lib' +import { ArchiveExportError } from '../errors' + +export interface LinkRect { + x: number + y: number + width: number + height: number + url: string +} + +/** Printable ASCII without the space: what the branding URL schema allows. */ +const ASCII_MIN = 0x21 +const ASCII_MAX = 0x7e + +/** + * The URL as the hex form of its ASCII bytes, one byte per character. + * `PDFHexString.fromText` would write UTF-16BE with a BOM, which readers + * that take `/URI` as raw bytes (poppler) turn into a dead link. A code + * point outside printable ASCII cannot reach the sink: the schema refuses + * it upstream, so it means the branding bypassed validation. + */ +function asciiHexOf(url: string): string { + let hex = '' + for (const char of url) { + const code = char.codePointAt(0) ?? 0 + if (code < ASCII_MIN || code > ASCII_MAX) { + throw new ArchiveExportError('branding_invalid', 'url') + } + hex += code.toString(16).padStart(2, '0') + } + return hex +} + +/** + * A clickable `/Link` annotation opening `url`, appended to the page's + * Annots. The URI is written as a hex string: pdf-lib does not escape `(`, + * `)` or `\` in a literal string, so a hostile URL could otherwise close + * the literal and inject objects (a `/Next` JavaScript action, for one). + */ +export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void { + const context = page.doc.context + + const actionDict = context.obj({ + Type: 'Action', + S: 'URI', + URI: PDFHexString.of(asciiHexOf(rect.url)), + }) + + const annotDict = context.obj({ + Type: 'Annot', + Subtype: 'Link', + Rect: [rect.x, rect.y, rect.x + rect.width, rect.y + rect.height], + Border: [0, 0, 0], + A: actionDict, + }) + + const annots = page.node.Annots() + if (annots) { + annots.push(context.register(annotDict)) + } else { + const arr = context.obj([context.register(annotDict)]) + page.node.set(PDFName.of('Annots'), arr) + } +} diff --git a/packages/pdf/src/render/observationPage.ts b/packages/pdf/src/render/observationPage.ts new file mode 100644 index 00000000..d2054a3a --- /dev/null +++ b/packages/pdf/src/render/observationPage.ts @@ -0,0 +1,634 @@ +import { + PageSizes, + rgb, + type PDFDocument, + type PDFImage, + type PDFPage, +} from 'pdf-lib' +import { + pickLabel, + type Finding, + type Observation, + type PdfLabels, + type Report, + type ReportZone, + type Severity, + type SheetIndex, + type SheetSnapshot, +} from '@faunosteo/domain' +import { renderHighlightedView } from '../svg/view' +import type { ExportWarning, Rasterizer } from '../types' +import { + COLOR_ACCENT, + COLOR_INK, + EYEBROW_Y_OFFSET, + MARGIN_X, + SECTION_LABEL_GAP, + TITLE_RULE_OFFSET, + TITLE_RULE_WIDTH, + TITLE_Y_OFFSET, +} from './constants' +import type { PdfLocale, RenderContext } from './context' +import type { EmbeddedFonts } from './fonts' +import { drawHeader, type HeaderAssets } from './header' +import { drawText, measure, wrapLines } from './text' + +const MARGIN_BOTTOM = 48 +const IMAGE_TOP_GAP = 32 +const IMAGE_LABEL_GAP = 14 +const IMAGE_BOTTOM_GAP = 14 +const IMAGE_COL_GAP = 16 +const IMAGE_ROW_GAP = 12 +const IMAGE_MIN_CELL_H = 60 +const TEXT_TOP_GAP = 10 +const TEXT_LINE_HEIGHT = 13 +const SECTION_BLOCK_GAP = 10 + +const COLOR_WHITE = rgb(1, 1, 1) + +const SEVERITY_BG: Record<Severity, ReturnType<typeof rgb>> = { + mild: rgb(0.55, 0.65, 0.45), + moderate: rgb(0.85, 0.55, 0.18), + severe: rgb(0.78, 0.2, 0.2), +} + +const SECTION_TEXT_SIZE = 10 +const SEPARATOR_GLYPH = '•' +const SEPARATOR_SIZE = 14 +const SEPARATOR_SIDE_GAP = 5 +/** Items of a section joined by this print as a segmented line. */ +const ITEM_JOIN = ' · ' + +/** Width of the visible separator block including the empty space on each side. */ +function separatorWidth(fonts: EmbeddedFonts): number { + return ( + measure(fonts.bodyBold, SEPARATOR_GLYPH, SEPARATOR_SIZE) + + SEPARATOR_SIDE_GAP * 2 + ) +} + +/** Counts the line breaks a list of items would consume when laid out on a maxWidth line. */ +function countSegmentedLines( + items: string[], + fonts: EmbeddedFonts, + maxWidth: number, +): number { + if (items.length === 0) return 1 + const sepW = separatorWidth(fonts) + let lines = 1 + let x = 0 + for (let i = 0; i < items.length; i += 1) { + const itemW = measure(fonts.bodyRegular, items[i]!, SECTION_TEXT_SIZE) + if (x + itemW > maxWidth && x > 0) { + lines += 1 + x = 0 + } + x += itemW + if (i < items.length - 1) { + if (x + sepW > maxWidth) { + lines += 1 + x = 0 + } else { + x += sepW + } + } + } + return lines +} + +interface SegmentCursor { + x: number + y: number +} + +function drawSeparator( + page: PDFPage, + cursor: SegmentCursor, + fonts: EmbeddedFonts, +): void { + const baselineOffset = (SEPARATOR_SIZE - SECTION_TEXT_SIZE) * 0.3 + drawText(page, SEPARATOR_GLYPH, { + x: cursor.x + SEPARATOR_SIDE_GAP, + y: cursor.y - baselineOffset, + size: SEPARATOR_SIZE, + font: fonts.bodyBold, + color: COLOR_ACCENT, + }) +} + +/** + * Renders a list of items separated by a visibly larger accent-coloured + * bullet. Returns the cursor y *below* the last line drawn. + */ +function drawSegmentedText( + page: PDFPage, + items: string[], + start: SegmentCursor, + maxWidth: number, + fonts: EmbeddedFonts, +): number { + if (items.length === 0) return start.y - TEXT_LINE_HEIGHT + const sepW = separatorWidth(fonts) + const cursor = { ...start } + for (let i = 0; i < items.length; i += 1) { + const item = items[i]! + const itemW = measure(fonts.bodyRegular, item, SECTION_TEXT_SIZE) + if (cursor.x + itemW > start.x + maxWidth && cursor.x > start.x) { + cursor.x = start.x + cursor.y -= TEXT_LINE_HEIGHT + } + drawText(page, item, { + x: cursor.x, + y: cursor.y, + size: SECTION_TEXT_SIZE, + font: fonts.bodyRegular, + color: COLOR_INK, + }) + cursor.x += itemW + if (i === items.length - 1) continue + if (cursor.x + sepW > start.x + maxWidth) { + cursor.x = start.x + cursor.y -= TEXT_LINE_HEIGHT + } else { + drawSeparator(page, cursor, fonts) + cursor.x += sepW + } + } + return cursor.y - TEXT_LINE_HEIGHT +} + +/** Parameters needed to render one observation page. */ +export interface ObservationPageContext { + pdfDoc: PDFDocument + report: Report + observation: Observation + obsIndex: number + sheet: SheetIndex + snapshot: SheetSnapshot + ctx: RenderContext + headerAssets: HeaderAssets + rasterizer: Rasterizer + warnings: ExportWarning[] +} + +interface PageDrawContext { + page: PDFPage + fonts: EmbeddedFonts + width: number +} + +interface RenderedImage { + label: string + img: PDFImage + aspect: number +} + +interface ObservationSection { + label: string + value: string +} + +function drawSeverityPill( + draw: PageDrawContext, + severity: Severity, + labels: PdfLabels, + anchor: { numW: number; titleY: number }, +): void { + const { page, fonts } = draw + const sevText = labels[`severity.${severity}`].toUpperCase() + const sevSize = 9 + const padX = 8 + const padY = 4 + const pillW = measure(fonts.bodyBold, sevText, sevSize) + padX * 2 + const pillH = sevSize + padY * 2 + const pillX = MARGIN_X + anchor.numW + 14 + const pillY = anchor.titleY + 4 + page.drawRectangle({ + x: pillX, + y: pillY, + width: pillW, + height: pillH, + color: SEVERITY_BG[severity], + }) + drawText(page, sevText, { + x: pillX + padX, + y: pillY + padY, + size: sevSize, + font: fonts.bodyBold, + color: COLOR_WHITE, + }) +} + +function drawObservationTitleBlock( + draw: PageDrawContext, + labels: PdfLabels, + obsIndex: number, + severity: Severity | undefined, +): number { + const { page, fonts } = draw + const { height } = page.getSize() + const eyebrowY = height - EYEBROW_Y_OFFSET + const titleY = height - TITLE_Y_OFFSET + const obsLabel = String(obsIndex + 1).padStart(2, '0') + drawText(page, labels['pdf.eyebrow.observation'], { + x: MARGIN_X, + y: eyebrowY, + size: 9, + font: fonts.bodyBold, + color: COLOR_ACCENT, + }) + drawText(page, obsLabel, { + x: MARGIN_X, + y: titleY, + size: 22, + font: fonts.headingRegular, + color: COLOR_INK, + }) + if (severity) { + const numW = measure(fonts.headingRegular, obsLabel, 22) + drawSeverityPill(draw, severity, labels, { numW, titleY }) + } + page.drawLine({ + start: { x: MARGIN_X, y: titleY - TITLE_RULE_OFFSET }, + end: { x: MARGIN_X + TITLE_RULE_WIDTH, y: titleY - TITLE_RULE_OFFSET }, + thickness: 2, + color: COLOR_ACCENT, + }) + return titleY +} + +/** Unique views the observation touches and the snapshot holds, main first. */ +export function observationViewIds( + sheet: SheetIndex, + observation: Observation, +): string[] { + return [...new Set(observation.zones.map((z) => z.viewId))] + .filter((id) => sheet.view(id)) + .sort( + (a, b) => + Number(b === sheet.mainView.id) - Number(a === sheet.mainView.id), + ) +} + +function viewLabel( + sheet: SheetIndex, + viewId: string, + ctx: RenderContext, +): string { + const view = sheet.view(viewId)! + if (view.kind === 'main') return ctx.labels['pdf.view.general'] + const name = pickLabel(view.name, ctx.locale).toUpperCase() + return `${ctx.labels['pdf.view.detail_prefix']}${name}` +} + +interface RasterisedView { + viewId: string + png: Uint8Array | null +} + +/** One view rasterised; a failure yields null and a warning, never a throw. */ +async function rasteriseView( + page: ObservationPageContext, + viewId: string, +): Promise<RasterisedView> { + try { + const { svg, size } = renderHighlightedView( + page.snapshot, + viewId, + page.observation, + ) + return { viewId, png: await page.rasterizer(svg, size) } + } catch { + page.warnings.push({ + kind: 'view_raster_failed', + observationId: page.observation.id, + viewId, + }) + return { viewId, png: null } + } +} + +/** Rasterisation in parallel, embedding in view order so bytes stay stable. */ +async function buildObservationImages( + page: ObservationPageContext, +): Promise<RenderedImage[]> { + const viewIds = observationViewIds(page.sheet, page.observation) + const rasters = await Promise.all( + viewIds.map((viewId) => rasteriseView(page, viewId)), + ) + const rendered: RenderedImage[] = [] + for (const { viewId, png } of rasters) { + if (!png) continue + try { + const img = await page.pdfDoc.embedPng(png) + rendered.push({ + label: viewLabel(page.sheet, viewId, page.ctx), + img, + aspect: img.width > 0 ? img.height / img.width : 0.6, + }) + } catch { + page.warnings.push({ + kind: 'view_raster_failed', + observationId: page.observation.id, + viewId, + }) + } + } + return rendered +} + +/** Zone name: snapshot annotation, else the report's label snapshot, else the id. */ +function zoneText(z: ReportZone, sheet: SheetIndex, locale: PdfLocale): string { + const annotation = sheet.annotation(z.annotationId) + if (annotation) return pickLabel(sheet.name(annotation), locale) + const snapshot = + locale === 'en' + ? z.labelEnSnapshot || z.labelFrSnapshot + : z.labelFrSnapshot || z.labelEnSnapshot + return snapshot || z.annotationId +} + +function sideLabel(side: 'left' | 'right', labels: PdfLabels): string { + return labels[side === 'left' ? 'lateral.left' : 'lateral.right'] +} + +function describeObservationZones( + zones: ReportZone[], + sheet: SheetIndex, + ctx: RenderContext, +): string { + return zones + .map((z) => { + const v = z.vertebrae?.length + ? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})` + : '' + const side = z.side ? ` (${sideLabel(z.side, ctx.labels)})` : '' + return `${zoneText(z, sheet, ctx.locale)}${v}${side}` + }) + .join(ITEM_JOIN) +} + +/** Finding group heading: snapshot finding-zone name, else the id as is. */ +function findingZoneName( + zoneId: string, + sheet: SheetIndex, + locale: PdfLocale, +): string { + const zone = sheet.findingZone(zoneId) + return zone ? pickLabel(zone.name, locale) : zoneId +} + +function findingText(f: Finding, locale: PdfLocale): string { + const label = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot + return f.requiresVetReferral ? `(!) ${label}` : label +} + +/** Groups findings by zone+side, one section per group; snapshots give the text. */ +function buildFindingsSections( + findings: Finding[], + sheet: SheetIndex, + ctx: RenderContext, +): ObservationSection[] { + const byZoneSide = new Map<string, Finding[]>() + for (const f of findings) { + const key = f.side ? `${f.findingZoneId}:${f.side}` : f.findingZoneId + byZoneSide.set(key, [...(byZoneSide.get(key) ?? []), f]) + } + const sections: ObservationSection[] = [] + for (const [key, group] of byZoneSide) { + const zoneId = key.split(':')[0]! + const side = group[0]?.side + let zoneName = findingZoneName(zoneId, sheet, ctx.locale) + if (side) zoneName = `${zoneName} (${sideLabel(side, ctx.labels)})` + sections.push({ + label: `${ctx.labels['pdf.section.findings_prefix']}${zoneName.toUpperCase()}`, + value: group.map((f) => findingText(f, ctx.locale)).join(ITEM_JOIN), + }) + } + return sections +} + +function buildObservationSections( + observation: Observation, + sheet: SheetIndex, + ctx: RenderContext, +): ObservationSection[] { + const { labels } = ctx + const zonesText = describeObservationZones(observation.zones, sheet, ctx) + const sections: ObservationSection[] = [ + { + label: labels['pdf.section.zones'], + value: zonesText || labels['pdf.empty'], + }, + ...buildFindingsSections(observation.findings, sheet, ctx), + ] + if (observation.freeTextFindings.length) { + sections.push({ + label: labels['pdf.section.free_findings'], + value: observation.freeTextFindings.join(ITEM_JOIN), + }) + } + if (observation.severity) { + sections.push({ + label: labels['pdf.section.severity'], + value: labels[`severity.${observation.severity}`], + }) + } + if (observation.comment.trim()) { + sections.push({ + label: labels['pdf.section.comment'], + value: observation.comment.trim(), + }) + } + return sections +} + +function estimateSectionsHeight( + sections: ObservationSection[], + fonts: EmbeddedFonts, + maxTextW: number, +): number { + let h = TEXT_TOP_GAP + for (const { value } of sections) { + const lineCount = value.includes(ITEM_JOIN) + ? countSegmentedLines(value.split(ITEM_JOIN), fonts, maxTextW) + : wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW).length + h += + SECTION_LABEL_GAP + 9 + lineCount * TEXT_LINE_HEIGHT + SECTION_BLOCK_GAP + } + return h +} + +interface ImageGrid { + cols: number + rows: number + cellW: number + offsetX: number + rowBudget: number +} + +function imageGridOf( + rendered: RenderedImage[], + width: number, + availH: number, +): ImageGrid { + const isSingle = rendered.length === 1 + const cols = isSingle ? 1 : 2 + const rows = Math.ceil(rendered.length / cols) + const fullCellW = (width - MARGIN_X * 2 - IMAGE_COL_GAP * (cols - 1)) / cols + const cellW = isSingle ? fullCellW / 2 : fullCellW + return { + cols, + rows, + cellW, + offsetX: isSingle ? (fullCellW - cellW) / 2 : 0, + rowBudget: Math.max( + IMAGE_MIN_CELL_H, + (availH - rows * IMAGE_LABEL_GAP - (rows - 1) * IMAGE_ROW_GAP) / rows, + ), + } +} + +/** One row of the grid: labels above, then the images; returns the row height. */ +function drawImageRow( + draw: PageDrawContext, + rowItems: RenderedImage[], + grid: ImageGrid, + topY: number, +): number { + const { page, fonts } = draw + const cellHs = rowItems.map((it) => + Math.min(grid.cellW * it.aspect, grid.rowBudget), + ) + const cellX = (c: number) => + MARGIN_X + grid.offsetX + c * (grid.cellW + IMAGE_COL_GAP) + rowItems.forEach((it, c) => { + drawText(page, it.label, { + x: cellX(c), + y: topY, + size: 8, + font: fonts.bodyBold, + color: COLOR_ACCENT, + }) + }) + const imagesY = topY - IMAGE_LABEL_GAP + rowItems.forEach((it, c) => { + page.drawImage(it.img, { + x: cellX(c), + y: imagesY - cellHs[c]!, + width: grid.cellW, + height: cellHs[c]!, + }) + }) + return Math.max(0, ...cellHs) +} + +/** Lays out the (up to 2-column) image grid; returns the cursor y below it. */ +function drawObservationImageGrid( + draw: PageDrawContext, + rendered: RenderedImage[], + startY: number, + reservedBottom: number, +): number { + if (rendered.length === 0) return startY + const availH = Math.max(IMAGE_MIN_CELL_H, startY - reservedBottom) + const grid = imageGridOf(rendered, draw.width, availH) + let cursorY = startY + for (let r = 0; r < grid.rows; r += 1) { + const rowItems = rendered.slice(r * grid.cols, r * grid.cols + grid.cols) + const rowH = drawImageRow(draw, rowItems, grid, cursorY) + cursorY -= IMAGE_LABEL_GAP + rowH + if (r < grid.rows - 1) cursorY -= IMAGE_ROW_GAP + } + return cursorY - IMAGE_BOTTOM_GAP +} + +function drawSectionValue( + draw: PageDrawContext, + value: string, + startY: number, + maxTextW: number, +): number { + const { page, fonts } = draw + if (value.includes(ITEM_JOIN)) { + return drawSegmentedText( + page, + value.split(ITEM_JOIN), + { x: MARGIN_X, y: startY }, + maxTextW, + fonts, + ) + } + let cursorY = startY + for (const line of wrapLines( + value, + fonts.bodyRegular, + SECTION_TEXT_SIZE, + maxTextW, + )) { + drawText(page, line, { + x: MARGIN_X, + y: cursorY, + size: SECTION_TEXT_SIZE, + font: fonts.bodyRegular, + color: COLOR_INK, + }) + cursorY -= TEXT_LINE_HEIGHT + } + return cursorY +} + +function drawObservationSections( + draw: PageDrawContext, + sections: ObservationSection[], + startY: number, + maxTextW: number, +): number { + let cursorY = startY + for (const { label, value } of sections) { + drawText(draw.page, label, { + x: MARGIN_X, + y: cursorY, + size: 8, + font: draw.fonts.bodyBold, + color: COLOR_ACCENT, + }) + cursorY -= SECTION_LABEL_GAP + 9 + cursorY = drawSectionValue(draw, value, cursorY, maxTextW) + cursorY -= SECTION_BLOCK_GAP + } + return cursorY +} + +export async function addObservationPage( + input: ObservationPageContext, +): Promise<void> { + const { pdfDoc, report, observation, obsIndex, sheet, ctx, headerAssets } = + input + const page = pdfDoc.addPage(PageSizes.A4) + const { width } = page.getSize() + drawHeader(page, report, ctx, headerAssets) + + const draw: PageDrawContext = { page, fonts: ctx.fonts, width } + const titleY = drawObservationTitleBlock( + draw, + ctx.labels, + obsIndex, + observation.severity, + ) + const rendered = await buildObservationImages(input) + const maxTextW = width - MARGIN_X * 2 + const sections = buildObservationSections(observation, sheet, ctx) + const reservedBottom = + MARGIN_BOTTOM + + estimateSectionsHeight(sections, ctx.fonts, maxTextW) + + IMAGE_BOTTOM_GAP + let cursorY = drawObservationImageGrid( + draw, + rendered, + titleY - IMAGE_TOP_GAP, + reservedBottom, + ) + cursorY -= TEXT_TOP_GAP + drawObservationSections(draw, sections, cursorY, maxTextW) +} diff --git a/packages/pdf/src/render/text.ts b/packages/pdf/src/render/text.ts new file mode 100644 index 00000000..35801f41 --- /dev/null +++ b/packages/pdf/src/render/text.ts @@ -0,0 +1,46 @@ +import type { PDFFont, PDFPage, PDFPageDrawTextOptions } from 'pdf-lib' +import { safeText } from '../text' + +/** + * Every string reaches pdf-lib through these three helpers, so a glyph the + * standard fonts cannot encode never throws at draw or measure time. + */ + +export function measure(font: PDFFont, text: string, size: number): number { + return font.widthOfTextAtSize(safeText(text), size) +} + +export function drawText( + page: PDFPage, + text: string, + options: PDFPageDrawTextOptions, +): void { + page.drawText(safeText(text), options) +} + +/** + * Greedy word-wrap: splits `text` into lines whose rendered width at + * `size` points stays within `max` for the given font. Whitespace of any + * kind separates words first, then each word is made safe. + */ +export function wrapLines( + text: string, + font: PDFFont, + size: number, + max: number, +): string[] { + const words = text.split(/\s+/).map(safeText) + const lines: string[] = [] + let line = '' + for (const w of words) { + const test = line ? `${line} ${w}` : w + if (measure(font, test, size) > max && line) { + lines.push(line) + line = w + } else { + line = test + } + } + if (line) lines.push(line) + return lines +} diff --git a/packages/pdf/src/svg/parse.ts b/packages/pdf/src/svg/parse.ts new file mode 100644 index 00000000..06d08245 --- /dev/null +++ b/packages/pdf/src/svg/parse.ts @@ -0,0 +1,37 @@ +import { DOMParser, XMLSerializer, type Element } from '@xmldom/xmldom' +import { SvgRejectedError } from '../errors' + +/** + * SVG text in, DOM root out, with xmldom (one code path in Node and in the + * browser). Entity declarations are refused before parsing; a parse error + * is reported as a typed rejection and its message, which may echo the + * input, is never logged. + */ + +const ENTITY_MARKUP = /<!(DOCTYPE|ENTITY)/i +const SVG_NS = 'http://www.w3.org/2000/svg' + +function rejectOnError(level: 'warning' | 'error' | 'fatalError'): void { + if (level !== 'warning') throw new SvgRejectedError('malformed') +} + +export function parseSvg(text: string): Element { + if (ENTITY_MARKUP.test(text)) throw new SvgRejectedError('doctype') + let root: Element | null + try { + const parser = new DOMParser({ onError: rejectOnError }) + root = parser.parseFromString(text, 'image/svg+xml').documentElement + } catch (error) { + if (error instanceof SvgRejectedError) throw error + throw new SvgRejectedError('malformed') + } + if (!root || root.localName !== 'svg' || root.namespaceURI !== SVG_NS) { + throw new SvgRejectedError('not_svg') + } + return root +} + +/** The root element alone: no XML declaration, as the app serialised it. */ +export function serializeSvg(root: Element): string { + return new XMLSerializer().serializeToString(root) +} diff --git a/packages/pdf/src/svg/sanitize.ts b/packages/pdf/src/svg/sanitize.ts new file mode 100644 index 00000000..9c3bc6db --- /dev/null +++ b/packages/pdf/src/svg/sanitize.ts @@ -0,0 +1,281 @@ +import type { Attr, Element, Node } from '@xmldom/xmldom' +import { SvgRejectedError } from '../errors' + +/** + * Allowlist sanitiser for the sheet drawings and the branding SVGs + * (STEP6 §15), on DOM Level 2 only. Elements and attributes outside the + * inventory of the real assets plus structural needs are removed with + * their subtree; `href` and `url(…)` must stay inside the document; no + * value carries a backslash (a CSS escape such as `u\72l(` would hide a + * reference from the rules below); a `style` or presentation attribute may + * call no function but `url(#…)`; the halo filters are clamped. Element, + * nesting and `<use>` counters refuse an oversized tree. The caller learns + * what was removed (names only, never values). + */ + +export const SANITIZER_CAPS = { + elements: 20_000, + depth: 64, + uses: 256, + stdDeviation: 100, +} as const + +const ALLOWED_ELEMENTS = new Set([ + '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 = new Set([ + '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', +]) + +/** Attributes whose value is CSS-like: a function call there is a reference or an exploit. */ +const PRESENTATION_ATTRIBUTES = new Set([ + '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', +]) + +const LOCAL_REFERENCE = /^#[A-Za-z_][\w.:-]*$/ +const URL_FUNCTION = /url\(\s*['"]?\s*(.?)/gi +const LOCAL_URL_OPEN = /url\(\s*['"]?\s*#/gi +const STYLE_FORBIDDEN = + /expression\(|image-set\(|@import|javascript:|behavior:/i + +export interface SanitizeOutcome { + /** Removed element names and `element@attribute` pairs, in document order. */ + removed: string[] +} + +const ELEMENT_NODE = 1 + +function isElement(node: Node): node is Element { + return node.nodeType === ELEMENT_NODE +} + +function elementChildren(node: Node): Element[] { + return Array.from(node.childNodes).filter(isElement) +} + +/** Every `url(` in the value must point inside the document (`url(#…)`). */ +function urlsAreLocal(value: string): boolean { + for (const match of value.matchAll(URL_FUNCTION)) { + if (match[1] !== '#') return false + } + return true +} + +function hrefIsLocal(value: string): boolean { + return LOCAL_REFERENCE.test(value.trim()) +} + +/** Any `(` left once the `url(#` openings are gone is a function we never allow. */ +function callsOnlyLocalUrl(value: string): boolean { + return !value.replace(LOCAL_URL_OPEN, '').includes('(') +} + +/** Whether an allowed attribute keeps its value, by name-specific rule. */ +function attributeAcceptable(name: string, value: string): boolean { + if (value.includes('\\')) return false + if (!urlsAreLocal(value)) return false + if (name === 'href' || name === 'xlink:href') return hrefIsLocal(value) + if (name === 'style') { + return !STYLE_FORBIDDEN.test(value) && callsOnlyLocalUrl(value) + } + if (PRESENTATION_ATTRIBUTES.has(name)) return callsOnlyLocalUrl(value) + return true +} + +/** Clamps every number of a `stdDeviation` list; rewrites only when needed. */ +function clampStdDeviation(element: Element): void { + const raw = element.getAttribute('stdDeviation') + if (raw === null) return + const numbers = raw + .trim() + .split(/[\s,]+/) + .map(Number) + if (numbers.some(Number.isNaN)) { + element.removeAttribute('stdDeviation') + return + } + if (numbers.every((n) => n <= SANITIZER_CAPS.stdDeviation)) return + const clamped = numbers.map((n) => Math.min(n, SANITIZER_CAPS.stdDeviation)) + element.setAttribute('stdDeviation', clamped.join(' ')) +} + +function sanitizeAttributes(element: Element, removed: string[]): void { + const attributes: Attr[] = Array.from(element.attributes) + for (const attribute of attributes) { + const { name, value } = attribute + const keep = + ALLOWED_ATTRIBUTES.has(name) && attributeAcceptable(name, value) + if (keep) continue + element.removeAttribute(name) + removed.push(`${element.tagName}@${name}`) + } + clampStdDeviation(element) +} + +interface Walk { + removed: string[] + elements: number + uses: number +} + +function visit(element: Element, depth: number, walk: Walk): void { + walk.elements += 1 + if (walk.elements > SANITIZER_CAPS.elements) { + throw new SvgRejectedError('too_many_elements') + } + if (depth > SANITIZER_CAPS.depth) throw new SvgRejectedError('too_deep') + if (element.tagName === 'use') { + walk.uses += 1 + if (walk.uses > SANITIZER_CAPS.uses) { + throw new SvgRejectedError('too_many_uses') + } + } + sanitizeAttributes(element, walk.removed) + for (const child of elementChildren(element)) { + if (ALLOWED_ELEMENTS.has(child.tagName)) { + visit(child, depth + 1, walk) + } else { + element.removeChild(child) + walk.removed.push(child.tagName) + } + } +} + +/** + * Sanitises the tree under `root` in place. Throws SvgRejectedError when a + * counter cap is exceeded; the tree is then unusable and the caller drops + * it. Returns the names of what was removed (empty on the real assets). + */ +export function sanitizeSvgRoot(root: Element): SanitizeOutcome { + if (root.tagName !== 'svg') throw new SvgRejectedError('not_svg') + const walk: Walk = { removed: [], elements: 0, uses: 0 } + visit(root, 1, walk) + return { removed: walk.removed } +} diff --git a/packages/pdf/src/svg/view.ts b/packages/pdf/src/svg/view.ts new file mode 100644 index 00000000..5a0f7140 --- /dev/null +++ b/packages/pdf/src/svg/view.ts @@ -0,0 +1,132 @@ +import type { Element } from '@xmldom/xmldom' +import { composeViewSvg } from '@faunosteo/anatomy/render' +import type { Observation, SheetSnapshot, SheetView } from '@faunosteo/domain' +import { parseSvg, serializeSvg } from './parse' +import { sanitizeSvgRoot } from './sanitize' + +/** + * The picture of one view of an observation: the snapshot's drawing, + * sanitised, framed on the view and overlaid with the observation's zones + * highlighted (accent fill, halo on the main view). The raster size follows + * today's rule, width 1200 px and the view box aspect, with the aspect + * clamped so an untrusted `viewBox` cannot request a huge canvas. + */ + +export const RASTER_WIDTH_PX = 1200 +const ASPECT_MIN = 0.2 +const ASPECT_MAX = 2.0 +const ASPECT_FALLBACK = 0.6 + +export interface RasterSize { + widthPx: number + heightPx: number +} + +export interface RenderedSvg { + svg: string + size: RasterSize +} + +/** A usable dimension: finite and strictly positive (`1e999` parses to Infinity). */ +function isPositiveFinite(value: number | undefined): value is number { + return value !== undefined && Number.isFinite(value) && value > 0 +} + +/** Height over width of a `viewBox` value, or the fallback when unusable. */ +function aspectOf(viewBox: string | null): number { + const parts = (viewBox ?? '') + .trim() + .split(/[\s,]+/) + .map(Number) + const [, , width, height] = parts + if ( + parts.length !== 4 || + !isPositiveFinite(width) || + !isPositiveFinite(height) + ) { + return ASPECT_FALLBACK + } + return height / width +} + +export function rasterSizeOf(viewBox: string | null): RasterSize { + const aspect = Math.min(ASPECT_MAX, Math.max(ASPECT_MIN, aspectOf(viewBox))) + return { + widthPx: RASTER_WIDTH_PX, + heightPx: Math.max(1, Math.round(RASTER_WIDTH_PX * aspect)), + } +} + +/** The asset a view draws: its own, else the first up its parent chain. */ +export function assetIdOfView( + view: SheetView, + views: ReadonlyMap<string, SheetView>, +): string | null { + const visited = new Set<string>() + let current: SheetView | undefined = view + while (current && !visited.has(current.id)) { + if (current.svg_asset_id !== null) return current.svg_asset_id + visited.add(current.id) + current = + current.kind === 'detail' ? views.get(current.parent_view_id) : undefined + } + return null +} + +function assetText(sheet: SheetSnapshot, view: SheetView): string { + const views = new Map(sheet.document.views.map((v) => [v.id, v])) + const assetId = assetIdOfView(view, views) + const asset = sheet.assets.find((a) => a.svgAssetId === assetId) + if (!asset) throw new Error(`view "${view.id}" reaches no asset`) + return asset.svg +} + +/** Parse, sanitise: the only way an asset text becomes a tree here. */ +export function cleanSvgRoot(text: string): Element { + const root = parseSvg(text) + sanitizeSvgRoot(root) + return root +} + +/** The view's drawing with the observation's zones of that view highlighted. */ +export function renderHighlightedView( + sheet: SheetSnapshot, + viewId: string, + observation: Observation, +): RenderedSvg { + const view = sheet.document.views.find((v) => v.id === viewId) + if (!view) throw new Error(`unknown view "${viewId}"`) + const annotationIds = new Set( + observation.zones + .filter((zone) => zone.viewId === viewId) + .map((zone) => zone.annotationId), + ) + const root = cleanSvgRoot(assetText(sheet, view)) + composeViewSvg({ + root, + document: sheet.document, + viewId, + highlight: { annotationIds, halo: view.kind === 'main' }, + }) + return { + svg: serializeSvg(root), + size: rasterSizeOf(root.getAttribute('viewBox')), + } +} + +export function composeHighlightedViewSvg( + sheet: SheetSnapshot, + viewId: string, + observation: Observation, +): string { + return renderHighlightedView(sheet, viewId, observation).svg +} + +/** A branding SVG made safe, with the raster size its own viewBox gives. */ +export function renderBrandingSvg(text: string): RenderedSvg { + const root = cleanSvgRoot(text) + return { + svg: serializeSvg(root), + size: rasterSizeOf(root.getAttribute('viewBox')), + } +} diff --git a/packages/pdf/src/text.ts b/packages/pdf/src/text.ts new file mode 100644 index 00000000..f34e0fae --- /dev/null +++ b/packages/pdf/src/text.ts @@ -0,0 +1,21 @@ +import { Encodings } from '@pdf-lib/standard-fonts' + +/** + * The single text ingress of the engine (STEP6 §15). The standard fonts are + * WinAnsi-encoded: a glyph outside that table makes pdf-lib throw at draw + * or measure time. Control, format and line/paragraph separator characters + * are dropped; every other unencodable code point prints as `?`. En and em + * dashes, bullets, accents and the euro sign are WinAnsi and survive. + */ + +const DROPPED = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu + +function encodable(char: string): string { + const codePoint = char.codePointAt(0) + if (codePoint === undefined) return '' + return Encodings.WinAnsi.canEncodeUnicodeCodePoint(codePoint) ? char : '?' +} + +export function safeText(text: string): string { + return Array.from(text.replace(DROPPED, ''), encodable).join('') +} diff --git a/packages/pdf/src/types.ts b/packages/pdf/src/types.ts new file mode 100644 index 00000000..f4d05b7d --- /dev/null +++ b/packages/pdf/src/types.ts @@ -0,0 +1,43 @@ +import type { + Branding, + PdfLabelSet, + Report, + ReportArchiveEnvelope, + SheetSnapshot, +} from '@faunosteo/domain' +import type { PdfLocale } from './render/context' + +export type { PdfLocale } + +/** + * Rasterisation is an adapter (STEP6 §3.3): the engine computes the size + * and the caller renders (browser Image/canvas, resvg in Node). + */ +export type Rasterizer = ( + svg: string, + size: { widthPx: number; heightPx: number }, +) => Promise<Uint8Array> + +export interface ExportInput { + report: Report + sheet: SheetSnapshot + branding: Branding + labels: PdfLabelSet + locale: PdfLocale + rasterizer: Rasterizer + /** Drives every date in the file: metadata, attachment, envelope. */ + exportedAt: Date +} + +export type ExportWarning = + | { kind: 'view_raster_failed'; observationId: string; viewId: string } + | { + kind: 'logo_failed' + slot: 'headerLogo' | 'footerLogo' | 'poweredBy' | 'partner' + } + +export interface ExportResult { + pdf: Uint8Array + envelope: ReportArchiveEnvelope + warnings: ExportWarning[] +} diff --git a/packages/pdf/tests/goldens.test.ts b/packages/pdf/tests/goldens.test.ts new file mode 100644 index 00000000..89f65dcc --- /dev/null +++ b/packages/pdf/tests/goldens.test.ts @@ -0,0 +1,137 @@ +/** + * T3 (STEP6 §7, §17): the engine reproduces every Phase 0 golden, per + * report × locale × logo mode. A mismatch is a visible change: the golden + * is never edited here. + */ +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { PDFDocument } from 'pdf-lib' +import { defaultPdfLabels, exportReportArchive } from '../src' +import type { PdfLocale } from '../src' +import { + brandingOf, + checkGolden, + FIXED_EXPORTED_AT, + ONE_PX_PNG, + rasterizerOf, + readGolden, + readLinks, + recordDrawing, + snapshotViews, + TWO_BY_ONE_PNG, + type ImageEntry, + type LinkEntry, + type LogoMode, + type TextEntry, + type ViewSnapshot, +} from './helpers/goldens' +import { + loadGoldenReports, + REPORT_NAMES, + type GoldenReports, + type ReportName, +} from './helpers/reports' + +const MODES: readonly LogoMode[] = ['nologos', 'logos'] + +let golden: GoldenReports + +beforeAll(() => { + golden = loadGoldenReports() +}) +afterAll(() => vi.restoreAllMocks()) + +interface Exported { + bytes: Uint8Array + texts: TextEntry[] + images: ImageEntry[] + links: LinkEntry[] +} + +async function exportWith( + name: ReportName, + mode: LogoMode, + locale: PdfLocale, +): Promise<Exported> { + const recording = recordDrawing() + try { + const { pdf, warnings } = await exportReportArchive({ + report: golden.reports[name], + sheet: golden.snapshots[name], + branding: brandingOf(mode), + labels: defaultPdfLabels, + locale, + rasterizer: rasterizerOf(mode), + exportedAt: FIXED_EXPORTED_AT, + }) + expect(warnings).toEqual([]) + const { texts, images } = recording + return { bytes: pdf, texts, images, links: await readLinks(pdf) } + } finally { + recording.stop() + } +} + +const pagesOf = (entries: readonly { page: number }[]) => + entries.map((e) => e.page) + +describe('golden inputs', () => { + it('the 2×1 PNG decodes as 2×1 and the 1×1 as 1×1', async () => { + const doc = await PDFDocument.create() + const two = await doc.embedPng(TWO_BY_ONE_PNG) + expect([two.width, two.height]).toEqual([2, 1]) + const one = await doc.embedPng(ONE_PX_PNG) + expect([one.width, one.height]).toEqual([1, 1]) + }) + + it('the v2unresolved report carries the unresolved findings of the freeze', () => { + expect(golden.unresolvedOfV2Unresolved).toBeGreaterThan(0) + const findings = golden.reports.v2unresolved.observations.flatMap( + (o) => o.findings, + ) + expect(findings.filter((f) => f.unresolved)).toHaveLength( + golden.unresolvedOfV2Unresolved, + ) + }) +}) + +describe.each(REPORT_NAMES)('goldens of %s', (name) => { + describe.each(MODES)('%s', (mode) => { + it('text, images and links per locale; same pagination across locales', async () => { + const fr = await exportWith(name, mode, 'fr') + const en = await exportWith(name, mode, 'en') + for (const [locale, out] of [ + ['fr', fr], + ['en', en], + ] as const) { + checkGolden(`text.${name}.${locale}.${mode}.json`, out.texts) + checkGolden(`images.${name}.${locale}.${mode}.json`, out.images) + checkGolden(`links.${name}.${locale}.${mode}.json`, out.links) + } + expect(pagesOf(en.images)).toEqual(pagesOf(fr.images)) + expect(pagesOf(en.links)).toEqual(pagesOf(fr.links)) + }, 30_000) + }) + + // Hidden markers are absent in the engine (the browser hid them with + // display="none") and the layer <g> carries no data-* any more: `titles` + // shrinks to the highlighted markers plus the asset's own, and + // `dataAttributes` drops from 2 to 0. Everything else must match. + it('highlighted views: same facts but titles and data attributes', () => { + const actual = snapshotViews(golden.snapshots[name], golden.reports[name]) + const expected = readGolden<ViewSnapshot[]>(`views.${name}.json`) + const comparable = (v: ViewSnapshot) => ({ + observationId: v.observationId, + viewId: v.viewId, + viewBox: v.viewBox, + halo: v.halo, + highlighted: v.highlighted, + nonHighlightedVisible: v.nonHighlightedVisible, + }) + expect(actual.map(comparable)).toEqual(expected.map(comparable)) + for (const view of actual) { + expect(view.dataAttributes).toBe(0) + expect(view.titles).toBeGreaterThanOrEqual(view.highlighted.length) + } + for (const view of expected) expect(view.dataAttributes).toBe(2) + }) +}) diff --git a/packages/pdf/tests/helpers/draft.ts b/packages/pdf/tests/helpers/draft.ts new file mode 100644 index 00000000..e273f08c --- /dev/null +++ b/packages/pdf/tests/helpers/draft.ts @@ -0,0 +1,92 @@ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { join, resolve } from 'node:path' +import { + AnatomicalSheetDocumentSchema, + ReportMigrationMapSchema, + type ReportMigrationMap, + type SnapshotSource, +} from '@faunosteo/domain' + +/** + * Paths and loaders shared by the engine tests. The committed equine draft + * is read from the seed as the application bundles it; the Phase 0 goldens + * and fixtures are read from the app's test folder, never copied. + */ + +const HERE = resolve(fileURLToPath(import.meta.url), '..') +export const REPO_ROOT = resolve(HERE, '../../../..') +export const DRAFT_DIR = resolve( + REPO_ROOT, + 'supabase/seed/anatomical-sheets/equine/draft', +) +export const LEGACY_BASELINE = resolve( + REPO_ROOT, + 'supabase/seed/anatomical-sheets/equine/legacy-import/document.json', +) +export const FIXTURES_DIR = resolve(REPO_ROOT, 'apps/app/tests/fixtures') +export const GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/step6') +export const PUBLIC_DIR = resolve(REPO_ROOT, 'apps/app/public') +/** The logo files the app bundles into its export branding. */ +export const BRAND_ASSETS_DIR = resolve(REPO_ROOT, 'apps/app/src/assets/brand') + +export function readJson<T = unknown>(path: string): T { + return JSON.parse(readFileSync(path, 'utf8')) as T +} + +export function readFixtureJson<T = unknown>(name: string): T { + return readJson<T>(resolve(FIXTURES_DIR, name)) +} + +export function readFixtureBytes(name: string): Uint8Array { + return new Uint8Array(readFileSync(resolve(FIXTURES_DIR, name))) +} + +interface SeedRef { + sheet_id: string + version_id: string | null + document_sha256: string + schema_version: number + species_id: string +} + +interface SeedAsset { + file: string + sha256: string + svg_asset_id: string +} + +export interface DraftSheet extends SnapshotSource { + assetHashes: Readonly<Record<string, string>> + migrationMap: ReportMigrationMap +} + +export function loadDraftSheet(): DraftSheet { + const json = <T>(name: string) => readJson<T>(join(DRAFT_DIR, name)) + const ref = json<SeedRef>('sheet-ref.json') + const assets: Record<string, string> = {} + const assetHashes: Record<string, string> = {} + for (const asset of json<SeedAsset[]>('assets.json')) { + assets[asset.svg_asset_id] = readFileSync( + join(DRAFT_DIR, 'assets', asset.file), + 'utf8', + ) + assetHashes[asset.svg_asset_id] = asset.sha256 + } + return { + status: 'draft', + ref: { + sheetId: ref.sheet_id, + versionId: ref.version_id, + documentSha256: ref.document_sha256, + }, + speciesId: ref.species_id, + schemaVersion: ref.schema_version, + document: AnatomicalSheetDocumentSchema.parse(json('document.json')), + assets, + assetHashes, + migrationMap: ReportMigrationMapSchema.parse( + json('report-migration-map.json'), + ), + } +} diff --git a/packages/pdf/tests/helpers/goldens.ts b/packages/pdf/tests/helpers/goldens.ts new file mode 100644 index 00000000..3ae96650 --- /dev/null +++ b/packages/pdf/tests/helpers/goldens.ts @@ -0,0 +1,359 @@ +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { DOMParser, type Element, type Node } from '@xmldom/xmldom' +import { expect, vi } from 'vitest' +import { + PDFArray, + PDFDict, + PDFDocument, + PDFHexString, + PDFName, + PDFNumber, + PDFPage, + PDFString, +} from 'pdf-lib' +import type { + Branding, + Observation, + Report, + SheetSnapshot, +} from '@faunosteo/domain' +import { composeHighlightedViewSvg, type Rasterizer } from '../../src' +import { BRAND_ASSETS_DIR, GOLDEN_DIR } from './draft' + +/** + * Step 6 Phase 0 goldens, replayed on the engine: the same recorder on + * pdf-lib, the same link reader, the same view facts (computed with xmldom + * instead of the browser DOM) and the same fixed PNG rasters. + */ + +export const FIXED_EXPORTED_AT = new Date('2026-10-11T12:00:00.000Z') + +/** 1×1 PNG (nologos: the legacy stub) and 2×1 PNG (logos: deterministic partner logo width). */ +export const ONE_PX_PNG = Uint8Array.from( + Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', + 'base64', + ), +) +export const TWO_BY_ONE_PNG = Uint8Array.from( + Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7QOjdAAAAD0lEQVR4nGPYEWX///9/AA0PBE/1T7nxAAAAAElFTkSuQmCC', + 'base64', + ), +) + +/** A rasterizer returning the same PNG whatever the SVG, like the Phase 0 mock. */ +export function fixedRasterizer(png: Uint8Array): Rasterizer { + return async () => png +} + +export type LogoMode = 'nologos' | 'logos' + +const SITE_URL = 'https://faunosteo.com' +const POWERED_BY = { + url: 'https://zenquality.fr', + fallbackText: 'zenquality.fr', +} +const PARTNER = { + url: 'https://www.instagram.com/paws.iin.harmony', + fallbackText: '@paws.iin.harmony', +} + +function brandPng(file: string): { kind: 'png'; base64: string } { + const bytes = readFileSync(resolve(BRAND_ASSETS_DIR, file)) + return { kind: 'png', base64: Buffer.from(bytes).toString('base64') } +} + +/** Every logo null, credits with their fallback texts (fetch 404 in Phase 0). */ +export function nologosBranding(): Branding { + return { + siteUrl: SITE_URL, + headerLogo: null, + footerLogo: null, + poweredBy: { logo: null, ...POWERED_BY }, + partner: { logo: null, ...PARTNER }, + } +} + +/** The four real logo files the app bundles (served by a fetch stub in Phase 0). */ +export function logosBranding(): Branding { + return { + siteUrl: SITE_URL, + headerLogo: brandPng('faunosteo-logo-horizontal-512.png'), + footerLogo: brandPng('faunosteo-horizontal-com-512.png'), + poweredBy: { logo: brandPng('zenquality-logo-fr.png'), ...POWERED_BY }, + partner: { + logo: { + kind: 'svg', + svg: readFileSync( + resolve(BRAND_ASSETS_DIR, 'paws-in-harmony.svg'), + 'utf8', + ), + }, + ...PARTNER, + }, + } +} + +export function brandingOf(mode: LogoMode): Branding { + return mode === 'logos' ? logosBranding() : nologosBranding() +} + +export function rasterizerOf(mode: LogoMode): Rasterizer { + return fixedRasterizer(mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG) +} + +export interface TextEntry { + page: number + text: string + x: number | null + y: number | null + size: number | null + font: string | null +} + +export interface ImageEntry { + page: number + x: number | null + y: number | null + width: number | null + height: number | null +} + +export interface LinkEntry { + page: number + rect: number[] + uri: string +} + +export function round2(value: unknown): number | null { + return typeof value === 'number' ? Math.round(value * 100) / 100 : null +} + +/** Pages are appended in order and never moved: the index at draw time is final. */ +function pageIndex(page: PDFPage): number { + return page.doc.getPages().indexOf(page) +} + +export interface DrawRecording { + texts: TextEntry[] + images: ImageEntry[] + stop(): void +} + +/** Records every drawText / drawImage while letting pdf-lib draw for real. */ +export function recordDrawing(): DrawRecording { + const texts: TextEntry[] = [] + const images: ImageEntry[] = [] + const drawText = PDFPage.prototype.drawText + const drawImage = PDFPage.prototype.drawImage + const textSpy = vi + .spyOn(PDFPage.prototype, 'drawText') + .mockImplementation(function (this: PDFPage, text, options) { + texts.push({ + page: pageIndex(this), + text, + x: round2(options?.x), + y: round2(options?.y), + size: round2(options?.size), + font: options?.font?.name ?? null, + }) + return drawText.call(this, text, options) + }) + const imageSpy = vi + .spyOn(PDFPage.prototype, 'drawImage') + .mockImplementation(function (this: PDFPage, image, options) { + images.push({ + page: pageIndex(this), + x: round2(options?.x), + y: round2(options?.y), + width: round2(options?.width), + height: round2(options?.height), + }) + return drawImage.call(this, image, options) + }) + return { + texts, + images, + stop: () => { + textSpy.mockRestore() + imageSpy.mockRestore() + }, + } +} + +function linkOf(dict: PDFDict, page: number): LinkEntry | null { + if (dict.get(PDFName.of('Subtype')) !== PDFName.of('Link')) return null + const rect = dict + .lookup(PDFName.of('Rect'), PDFArray) + .asArray() + .map((n) => round2((n as PDFNumber).asNumber()) ?? 0) + const uri = dict.lookup(PDFName.of('A'), PDFDict).lookup(PDFName.of('URI')) + const text = + uri instanceof PDFString || uri instanceof PDFHexString + ? uri.decodeText() + : String(uri) + return { page, rect, uri: text } +} + +/** Every `/Annot /Link` of the saved PDF, page by page, in annotation order. */ +export async function readLinks(bytes: Uint8Array): Promise<LinkEntry[]> { + const doc = await PDFDocument.load(bytes) + const out: LinkEntry[] = [] + doc.getPages().forEach((page, index) => { + const annots = page.node.Annots() + if (!annots) return + for (let i = 0; i < annots.size(); i += 1) { + const link = linkOf(annots.lookup(i, PDFDict), index) + if (link) out.push(link) + } + }) + return out +} + +// --------------------------------------------------------------------------- +// View facts (G2), computed with xmldom on the engine's SVG + +export const HIGHLIGHT_FILL = '#b85a3f' + +export interface HighlightedElement { + tag: string + cx: string | null + cy: string | null + r: string | null + points: string | null + d: string | null + fill: string | null + fillOpacity: string | null + filter: string | null +} + +export interface ViewSnapshot { + observationId: string + viewId: string + viewBox: string | null + halo: boolean + highlighted: HighlightedElement[] + nonHighlightedVisible: number + dataAttributes: number + titles: number +} + +function isElement(node: Node): node is Element { + return node.nodeType === 1 +} + +/** Every element under `root` (root included), document order. */ +export function allElements(root: Element): Element[] { + const out: Element[] = [] + const stack: Element[] = [root] + while (stack.length) { + const el = stack.pop()! + out.push(el) + const children = Array.from(el.childNodes).filter(isElement) + for (let i = children.length - 1; i >= 0; i -= 1) stack.push(children[i]!) + } + return out +} + +export function elementChildren(el: Element): Element[] { + return Array.from(el.childNodes).filter(isElement) +} + +function highlightedOf(el: Element): HighlightedElement { + const attr = (name: string) => el.getAttribute(name) + return { + tag: el.tagName, + cx: attr('cx'), + cy: attr('cy'), + r: attr('r'), + points: attr('points'), + d: attr('d'), + fill: attr('fill'), + fillOpacity: attr('fill-opacity'), + filter: attr('filter'), + } +} + +/** Children of the annotation layer (last `<g>` of the root) still visible and not highlighted. */ +function countVisibleNonHighlighted(root: Element): number { + const layer = elementChildren(root) + .filter((c) => c.tagName === 'g') + .at(-1) + if (!layer) return 0 + return elementChildren(layer).filter( + (el) => + el.getAttribute('fill') !== HIGHLIGHT_FILL && + el.getAttribute('display') !== 'none', + ).length +} + +function countDataAttributes(root: Element): number { + return allElements(root).reduce( + (count, el) => + count + + Array.from(el.attributes).filter((a) => a.name.startsWith('data-')) + .length, + 0, + ) +} + +export function parseXml(svg: string): Element { + return new DOMParser().parseFromString(svg, 'image/svg+xml').documentElement! +} + +export function snapshotView( + sheet: SheetSnapshot, + observation: Observation, + viewId: string, +): ViewSnapshot { + const root = parseXml(composeHighlightedViewSvg(sheet, viewId, observation)) + const elements = allElements(root) + return { + observationId: observation.id, + viewId, + viewBox: root.getAttribute('viewBox'), + halo: elements.some( + (el) => el.tagName === 'filter' && el.getAttribute('id') === 'osteo-halo', + ), + highlighted: elements + .filter((el) => el.getAttribute('fill') === HIGHLIGHT_FILL) + .map(highlightedOf), + nonHighlightedVisible: countVisibleNonHighlighted(root), + dataAttributes: countDataAttributes(root), + titles: elements.filter((el) => el.tagName === 'title').length, + } +} + +/** The views an observation draws, in the pipeline's order: main first, then first appearance. */ +export function viewIdsOf( + sheet: SheetSnapshot, + observation: Observation, +): string[] { + const views = new Set(sheet.document.views.map((v) => v.id)) + const main = sheet.document.views.find((v) => v.kind === 'main')!.id + return [...new Set(observation.zones.map((z) => z.viewId))] + .filter((id) => views.has(id)) + .sort((a, b) => Number(b === main) - Number(a === main)) +} + +export function snapshotViews( + sheet: SheetSnapshot, + report: Report, +): ViewSnapshot[] { + return report.observations.flatMap((observation) => + viewIdsOf(sheet, observation).map((viewId) => + snapshotView(sheet, observation, viewId), + ), + ) +} + +export function readGolden<T = unknown>(name: string): T { + return JSON.parse(readFileSync(resolve(GOLDEN_DIR, name), 'utf8')) as T +} + +/** Asserts deep equality with a Phase 0 golden (never regenerated here). */ +export function checkGolden(name: string, actual: unknown): void { + expect(actual, name).toEqual(readGolden(name)) +} diff --git a/packages/pdf/tests/helpers/legacy-leaves.ts b/packages/pdf/tests/helpers/legacy-leaves.ts new file mode 100644 index 00000000..508a4752 --- /dev/null +++ b/packages/pdf/tests/helpers/legacy-leaves.ts @@ -0,0 +1,84 @@ +import { + AnatomicalSheetDocumentSchema, + ReportV2Schema, + type AnatomicalSheetDocument, + type FindingCategory, + type FindingNode, + type ObservationV2, + type ReportV2, +} from '@faunosteo/domain' +import { LEGACY_BASELINE, readJson } from './draft' + +/** + * The legacy catalog as the application's archive knew it: every leaf of the + * generated baseline becomes a Report v2 finding, one observation per zone. + * Same recipe as the app and domain helpers (Phase 0 `v2unresolved`). + */ + +export interface LegacyLeaf { + zoneId: string + path: string[] + name: { fr: string; en: string } + vet: boolean +} + +export function loadLegacyBaseline(): AnatomicalSheetDocument { + return AnatomicalSheetDocumentSchema.parse(readJson(LEGACY_BASELINE)) +} + +export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] { + const out: LegacyLeaf[] = [] + const walk = ( + zoneId: string, + nodes: readonly (FindingCategory | FindingNode)[], + prefix: string[], + ) => { + for (const node of nodes) { + const path = [...prefix, node.id] + if (node.children.length > 0) walk(zoneId, node.children, path) + else { + const vet = + 'requires_vet_referral' in node && node.requires_vet_referral + out.push({ zoneId, path, name: node.name, vet }) + } + } + } + for (const zone of doc.finding_zones) walk(zone.id, zone.categories, []) + return out +} + +export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 { + const byZone = new Map<string, ObservationV2>() + for (const leaf of leaves) { + let obs = byZone.get(leaf.zoneId) + if (!obs) { + obs = { + id: `obs-${leaf.zoneId}`, + zones: [], + findings: [], + freeTextFindings: [], + comment: '', + } + byZone.set(leaf.zoneId, obs) + } + obs.findings.push({ + zoneId: leaf.zoneId, + path: leaf.path, + labelFrSnapshot: leaf.name.fr, + labelEnSnapshot: leaf.name.en || leaf.name.fr, + ...(leaf.vet ? { requiresVetReferral: true } : {}), + }) + } + return ReportV2Schema.parse({ + version: 2, + id: 'all-leaves', + createdAt: '2026-10-10T00:00:00Z', + date: '2026-10-10', + practitioner: { name: 'Synthetic' }, + animal: { speciesId: 'equine', name: 'Synthetic' }, + owner: { name: 'Synthetic' }, + observations: [...byZone.values()], + conclusion: '', + recommendations: '', + }) +} diff --git a/packages/pdf/tests/helpers/pdf.ts b/packages/pdf/tests/helpers/pdf.ts new file mode 100644 index 00000000..cfbd3257 --- /dev/null +++ b/packages/pdf/tests/helpers/pdf.ts @@ -0,0 +1,55 @@ +import { AFRelationship, PDFDocument } from 'pdf-lib' +import { findEmbeddedFiles } from '../../src' + +/** + * Crafted PDFs for the read tests, built with pdf-lib's own attach. Saved + * without object streams by default, like the export since BLK-009; pass + * `objectStreams: true` for the pre-BLK-009 layout (Filespec and Info + * packed into an `/ObjStm`, invisible to the byte scan). + */ +export interface CraftOptions { + keywords?: string[] + before?: [string, unknown] + objectStreams?: boolean +} + +export async function pdfWithAttachment( + name: string, + payload: unknown, + extra: CraftOptions = {}, +): Promise<Uint8Array> { + const doc = await PDFDocument.create() + doc.addPage() + if (extra.keywords) doc.setKeywords(extra.keywords) + if (extra.before) await attachJson(doc, extra.before[0], extra.before[1]) + await attachJson(doc, name, payload) + return doc.save({ useObjectStreams: extra.objectStreams ?? false }) +} + +async function attachJson( + doc: PDFDocument, + name: string, + payload: unknown, +): Promise<void> { + await doc.attach(new TextEncoder().encode(JSON.stringify(payload)), name, { + mimeType: 'application/json', + afRelationship: AFRelationship.Data, + }) +} + +export async function pdfWithoutAttachment( + keywords?: string[], + objectStreams = false, +): Promise<Uint8Array> { + const doc = await PDFDocument.create() + doc.addPage() + if (keywords) doc.setKeywords(keywords) + return doc.save({ useObjectStreams: objectStreams }) +} + +/** Stored (Flate) size of the first `/EmbeddedFile` stream of a saved PDF, by the byte scan. */ +export function storedAttachmentSize(bytes: Uint8Array): number { + const [first] = findEmbeddedFiles(bytes) + if (!first) throw new Error('no EmbeddedFile stream') + return first.length +} diff --git a/packages/pdf/tests/helpers/reports.ts b/packages/pdf/tests/helpers/reports.ts new file mode 100644 index 00000000..1091b53d --- /dev/null +++ b/packages/pdf/tests/helpers/reports.ts @@ -0,0 +1,71 @@ +import { + buildSheetSnapshot, + readReportDocument, + ReportSchema, + type Report, + type SheetSnapshot, +} from '@faunosteo/domain' +import { loadDraftSheet, readFixtureJson, type DraftSheet } from './draft' +import { + leavesAsV2Report, + legacyLeaves, + loadLegacyBaseline, +} from './legacy-leaves' + +/** The three Phase 0 reports, built with the Phase 0 recipe. */ +export const REPORT_NAMES = ['v2full', 'demo', 'v2unresolved'] as const +export type ReportName = (typeof REPORT_NAMES)[number] + +export interface GoldenReports { + draft: DraftSheet + reports: Record<ReportName, Report> + snapshots: Record<ReportName, SheetSnapshot> + /** Unresolved findings of `v2unresolved` as the migration counted them. */ + unresolvedOfV2Unresolved: number +} + +/** sphenoid + ssb (the families the migration cannot place) plus one leaf that resolves. */ +function buildV2Unresolved(draft: DraftSheet) { + const leaves = legacyLeaves(loadLegacyBaseline()) + const unresolvedFamilies = leaves.filter( + (l) => l.zoneId === 'sphenoid' || l.zoneId === 'ssb', + ) + const resolved = leaves.find((l) => l.zoneId === 'frontal')! + return readReportDocument( + leavesAsV2Report([...unresolvedFamilies, resolved]), + draft.migrationMap, + ) +} + +export function loadGoldenReports(): GoldenReports { + const draft = loadDraftSheet() + const unresolved = buildV2Unresolved(draft) + const reports: Record<ReportName, Report> = { + v2full: readReportDocument( + readFixtureJson('report-v2.full.json'), + draft.migrationMap, + ).report, + demo: ReportSchema.parse(readFixtureJson('report-v3.demo.json')), + v2unresolved: unresolved.report, + } + const snapshots = Object.fromEntries( + REPORT_NAMES.map((name) => [ + name, + buildSheetSnapshot(draft, reports[name]), + ]), + ) as Record<ReportName, SheetSnapshot> + return { + draft, + reports, + snapshots, + unresolvedOfV2Unresolved: unresolved.unresolvedFindings, + } +} + +/** The 612-leaf legacy report migrated through the draft map (T5). */ +export function allLeavesMigrated(draft: DraftSheet) { + return readReportDocument( + leavesAsV2Report(legacyLeaves(loadLegacyBaseline())), + draft.migrationMap, + ) +} diff --git a/packages/pdf/tests/helpers/resvg.ts b/packages/pdf/tests/helpers/resvg.ts new file mode 100644 index 00000000..6dcd2e92 --- /dev/null +++ b/packages/pdf/tests/helpers/resvg.ts @@ -0,0 +1,88 @@ +import { Resvg } from '@resvg/resvg-js' +import type { Rasterizer } from '../../src' + +/** + * A real Node rasterizer for T10. resvg 0.40 (resvg-js 2.6.2) panics + * (`geom.rs:27`, `Option::unwrap() on None`) when gradient-filled elements + * are culled by a cropped root `viewBox` such as the head view's + * `60 100 500 380` on the equine drawing, aborting the process. The + * adapter therefore renders the box covering the whole content at the + * same scale and crops the pixels to the requested view: identical output + * for a view that already covers its content (main view). + */ + +export interface Raster { + requested: { widthPx: number; heightPx: number } + png: Uint8Array +} + +interface Box { + x: number + y: number + width: number + height: number +} + +const FONT = { loadSystemFonts: false } + +function rootViewBox(svg: string): Box | null { + const tag = svg.match(/<svg\b[^>]*>/)?.[0] ?? '' + const raw = tag.match(/\sviewBox="([^"]+)"/)?.[1] + if (!raw) return null + const [x, y, width, height] = raw + .trim() + .split(/[\s,]+/) + .map(Number) + if (!(width! > 0) || !(height! > 0)) return null + return { x: x!, y: y!, width: width!, height: height! } +} + +function withViewBox(svg: string, box: Box): string { + const value = `${box.x} ${box.y} ${box.width} ${box.height}` + return svg.replace(/(<svg\b[^>]*?\sviewBox=")[^"]+(")/, `$1${value}$2`) +} + +function union(a: Box, b: Box): Box { + const x = Math.min(a.x, b.x) + const y = Math.min(a.y, b.y) + return { + x, + y, + width: Math.max(a.x + a.width, b.x + b.width) - x, + height: Math.max(a.y + a.height, b.y + b.height) - y, + } +} + +function contentBox(svg: string): Box | null { + const bbox = new Resvg(svg, { font: FONT }).getBBox() + if (!bbox || !(bbox.width > 0) || !(bbox.height > 0)) return null + return { x: bbox.x, y: bbox.y, width: bbox.width, height: bbox.height } +} + +export function resvgRasterizer(record: Raster[] = []): Rasterizer { + return async (svg, size) => { + const crop = rootViewBox(svg) + const content = crop ? contentBox(svg) : null + const full = crop && content ? union(crop, content) : crop + const scale = crop ? size.widthPx / crop.width : 1 + const left = Math.round(((crop?.x ?? 0) - (full?.x ?? 0)) * scale) + const top = Math.round(((crop?.y ?? 0) - (full?.y ?? 0)) * scale) + const resvg = new Resvg(full ? withViewBox(svg, full) : svg, { + fitTo: { + mode: 'width', + value: full ? Math.round(full.width * scale) : size.widthPx, + }, + background: 'white', + font: FONT, + crop: { + left, + top, + right: left + size.widthPx, + bottom: top + size.heightPx, + }, + }) + const png = new Uint8Array(resvg.render().asPng()) + record.push({ requested: size, png }) + return png + } +} diff --git a/packages/pdf/tests/inflate.test.ts b/packages/pdf/tests/inflate.test.ts new file mode 100644 index 00000000..c8a95ee7 --- /dev/null +++ b/packages/pdf/tests/inflate.test.ts @@ -0,0 +1,77 @@ +/** + * The capped inflater: round trips, the exact limit, every failure mode as + * null, the bomb cancelled early, and the compressed bytes fed to the + * platform inflater in slices (the Chromium read-ahead bound; Node cannot + * show the memory effect, only the feeding shape). + */ +import { deflateSync } from 'node:zlib' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { inflateFlate, MAX_ATTACHMENT_BYTES } from '../src/attachment/inflate' + +const KiB = 1024 +const MiB = 1024 * KiB + +/** Incompressible bytes: the compressed stream is about as long as the input. */ +function noise(length: number): Uint8Array { + let seed = 0x9e3779b9 + return Uint8Array.from({ length }, () => { + seed = (seed * 1664525 + 1013904223) >>> 0 + return seed >>> 24 + }) +} + +const deflate = (data: Uint8Array) => new Uint8Array(deflateSync(data)) + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('inflateFlate', () => { + it('round-trips a payload spanning several slices', async () => { + const payload = noise(200 * KiB) + const compressed = deflate(payload) + expect(compressed.byteLength).toBeGreaterThan(10 * 16 * KiB) + expect(await inflateFlate(compressed)).toEqual(payload) + }) + + it('feeds the inflater in 16 KiB slices, each awaited', async () => { + const compressed = deflate(noise(100 * KiB)) + const write = vi.spyOn(WritableStreamDefaultWriter.prototype, 'write') + await inflateFlate(compressed) + const slices = Math.ceil(compressed.byteLength / (16 * KiB)) + expect(write).toHaveBeenCalledTimes(slices) + const sizes = write.mock.calls.map((c) => (c[0] as Uint8Array).byteLength) + expect(Math.max(...sizes)).toBe(16 * KiB) + }) + + it('an output exactly at the limit passes, one byte more is null', async () => { + const payload = noise(64 * KiB) + const compressed = deflate(payload) + expect(await inflateFlate(compressed, payload.byteLength)).toEqual(payload) + expect(await inflateFlate(compressed, payload.byteLength - 1)).toBeNull() + }) + + it.each([ + ['empty input', new Uint8Array(0)], + ['truncated stream', deflate(noise(4 * KiB)).subarray(0, 2 * KiB)], + ['trailing junk', Uint8Array.from([...deflate(noise(KiB)), 1, 2, 3])], + [ + 'corrupt body', + Uint8Array.from(deflate(noise(KiB)), (b, i) => (i > 8 ? b ^ 0xff : b)), + ], + ['not deflate at all', new TextEncoder().encode('{"version":3}')], + ])('%s: null', async (_name, bytes) => { + expect(await inflateFlate(bytes)).toBeNull() + }) + + it('a 64 MiB bomb past the default cap is cancelled in well under a second', async () => { + const bomb = deflate(new Uint8Array(64 * MiB)) + expect(bomb.byteLength).toBeLessThan(MiB) + const started = performance.now() + expect(await inflateFlate(bomb)).toBeNull() + const elapsed = performance.now() - started + console.log(`[inflate] 64 MiB bomb: ${elapsed.toFixed(0)} ms`) + expect(elapsed).toBeLessThan(1000) + expect(MAX_ATTACHMENT_BYTES).toBe(16 * MiB) + }) +}) diff --git a/packages/pdf/tests/raster.test.ts b/packages/pdf/tests/raster.test.ts new file mode 100644 index 00000000..01103405 --- /dev/null +++ b/packages/pdf/tests/raster.test.ts @@ -0,0 +1,122 @@ +/** + * T10 (STEP6 §7): a real rasterizer (resvg) renders the demo report's main + * and head views: 1200 px wide, height from the view box, highlight colour + * present, sane non-white ratio. A failing rasterizer degrades to a page + * without the image and one warning. + */ +import { beforeAll, describe, expect, it } from 'vitest' +import * as UPNG from '@pdf-lib/upng' +import { PDFDocument } from 'pdf-lib' +import { buildSheetSnapshot } from '@faunosteo/domain' +import { + defaultPdfLabels, + exportReportArchive, + type ExportInput, + type Rasterizer, +} from '../src' +import { + FIXED_EXPORTED_AT, + nologosBranding, + recordDrawing, +} from './helpers/goldens' +import { loadGoldenReports, type GoldenReports } from './helpers/reports' +import { resvgRasterizer, type Raster } from './helpers/resvg' + +const HIGHLIGHT = { r: 0xb8, g: 0x5a, b: 0x3f } +const TOLERANCE = 24 + +interface PixelFacts { + width: number + height: number + highlightPixels: number + nonWhiteRatio: number +} + +function pixelFacts(png: Uint8Array): PixelFacts { + const buffer = new ArrayBuffer(png.byteLength) + new Uint8Array(buffer).set(png) + const image = UPNG.decode(buffer) + const rgba = new Uint8Array(UPNG.toRGBA8(image)[0]!) + let highlightPixels = 0 + let nonWhite = 0 + for (let i = 0; i < rgba.length; i += 4) { + const [r, g, b] = [rgba[i]!, rgba[i + 1]!, rgba[i + 2]!] + if (r < 250 || g < 250 || b < 250) nonWhite += 1 + if ( + Math.abs(r - HIGHLIGHT.r) <= TOLERANCE && + Math.abs(g - HIGHLIGHT.g) <= TOLERANCE && + Math.abs(b - HIGHLIGHT.b) <= TOLERANCE + ) { + highlightPixels += 1 + } + } + const total = rgba.length / 4 + return { + width: image.width, + height: image.height, + highlightPixels, + nonWhiteRatio: nonWhite / total, + } +} + +let golden: GoldenReports +beforeAll(() => { + golden = loadGoldenReports() +}) + +function inputFor( + observations: GoldenReports['reports']['demo']['observations'], + rasterizer: Rasterizer, +): ExportInput { + const report = { ...golden.reports.demo, observations } + return { + report, + sheet: buildSheetSnapshot(golden.draft, report), + branding: nologosBranding(), + labels: defaultPdfLabels, + locale: 'fr', + rasterizer, + exportedAt: FIXED_EXPORTED_AT, + } +} + +describe('resvg rasterisation of the demo views', () => { + it('main (haloed) and head views: 1200 px wide, highlight present, sane coverage', async () => { + const rasters: Raster[] = [] + const [main, , , head] = golden.reports.demo.observations + const { pdf, warnings } = await exportReportArchive( + inputFor([main!, head!], resvgRasterizer(rasters)), + ) + expect(warnings).toEqual([]) + expect(rasters).toHaveLength(2) + for (const { requested, png } of rasters) { + const facts = pixelFacts(png) + expect(facts.width).toBe(1200) + expect(Math.abs(facts.height - requested.heightPx)).toBeLessThanOrEqual(1) + expect(facts.highlightPixels).toBeGreaterThan(0) + expect(facts.nonWhiteRatio).toBeGreaterThanOrEqual(0.01) + expect(facts.nonWhiteRatio).toBeLessThanOrEqual(0.9) + } + // main: 2073.4 × 1629.4 → 943 px; head: 500 × 380 → 912 px + expect(rasters.map((r) => r.requested.heightPx)).toEqual([943, 912]) + expect((await PDFDocument.load(pdf)).getPageCount()).toBe(3) + }, 60_000) + + it('a rasterizer that throws: page without image, one view_raster_failed warning', async () => { + const [main] = golden.reports.demo.observations + const failing: Rasterizer = async () => { + throw new Error('no renderer here') + } + const recording = recordDrawing() + try { + const { warnings } = await exportReportArchive(inputFor([main!], failing)) + expect(warnings).toEqual([ + { kind: 'view_raster_failed', observationId: main!.id, viewId: 'main' }, + ]) + expect(recording.images).toEqual([]) + expect(recording.texts.some((t) => t.text === 'VUE GÉNÉRALE')).toBe(false) + } finally { + recording.stop() + } + }) +}) diff --git a/packages/pdf/tests/read.test.ts b/packages/pdf/tests/read.test.ts new file mode 100644 index 00000000..7a41f2e3 --- /dev/null +++ b/packages/pdf/tests/read.test.ts @@ -0,0 +1,183 @@ +/** + * T4 T5 T6 (STEP6 §4, §7, §14 "Read"): roundtrip, the frozen v2 PDFs and + * the 612-leaf legacy report, the bare v3 fixture, wrapper and report + * versions, stripped attachments, attachment selection, size cap. + */ +import { beforeAll, describe, expect, it } from 'vitest' +import { + buildSheetSnapshot, + type Report, + type ReportArchiveEnvelope, +} from '@faunosteo/domain' +import { + ArchiveReadError, + defaultPdfLabels, + exportReportArchive, + MAX_PDF_BYTES, + readReportArchive, + type ExportResult, +} from '../src' +import { readFixtureBytes } from './helpers/draft' +import { + FIXED_EXPORTED_AT, + nologosBranding, + rasterizerOf, +} from './helpers/goldens' +import { pdfWithAttachment, pdfWithoutAttachment } from './helpers/pdf' +import { + allLeavesMigrated, + loadGoldenReports, + type GoldenReports, +} from './helpers/reports' + +let golden: GoldenReports +const map = () => golden.draft.migrationMap + +beforeAll(() => { + golden = loadGoldenReports() +}) + +function exportOnDraft(report: Report): Promise<ExportResult> { + return exportReportArchive({ + report, + sheet: buildSheetSnapshot(golden.draft, report), + branding: nologosBranding(), + labels: defaultPdfLabels, + locale: 'fr', + rasterizer: rasterizerOf('nologos'), + exportedAt: FIXED_EXPORTED_AT, + }) +} + +const unresolvedFindings = (report: Report) => + report.observations.flatMap((o) => o.findings).filter((f) => f.unresolved) + .length + +async function rejects( + bytes: Uint8Array, + expected: Partial<ArchiveReadError>, +): Promise<void> { + const promise = readReportArchive(bytes, map()) + await expect(promise).rejects.toBeInstanceOf(ArchiveReadError) + await expect(promise).rejects.toMatchObject(expected) +} + +describe('T4 roundtrip', () => { + it('reads back the exported envelope whole', async () => { + const { pdf, envelope } = await exportOnDraft(golden.reports.demo) + const outcome = await readReportArchive(pdf, map()) + expect(outcome.origin).toBe('envelope_v1') + expect(outcome.migrated).toBe(false) + expect(outcome.snapshotRejected).toBeUndefined() + expect(outcome.report).toEqual(golden.reports.demo) + expect(outcome.archive).toEqual(envelope) + }) +}) + +describe('T5 v2 archives and the bare v3 fixture', () => { + it.each(['report-v2.full.pdf', 'report-v2.minimal.pdf'])( + '%s: migrated, re-exported, imported again equal', + async (name) => { + const first = await readReportArchive(readFixtureBytes(name), map()) + expect(first.origin).toBe('v2') + expect(first.migrated).toBe(true) + expect(first.archive).toBeNull() + expect(first.report.version).toBe(3) + const { pdf } = await exportOnDraft(first.report) + const again = await readReportArchive(pdf, map()) + expect(again.origin).toBe('envelope_v1') + expect(again.report).toEqual(first.report) + }, + ) + + it('keeps the 29 unresolved findings of the 612-leaf report through export and import', async () => { + const migrated = allLeavesMigrated(golden.draft) + expect(migrated.unresolvedFindings).toBe(29) + expect(unresolvedFindings(migrated.report)).toBe(29) + const { pdf } = await exportOnDraft(migrated.report) + const again = await readReportArchive(pdf, map()) + expect(unresolvedFindings(again.report)).toBe(29) + expect(again.report).toEqual(migrated.report) + }) + + it('reads report-v3.bare.pdf as a bare v3 with no archive', async () => { + const outcome = await readReportArchive( + readFixtureBytes('report-v3.bare.pdf'), + map(), + ) + expect(outcome.origin).toBe('bare_v3') + expect(outcome.archive).toBeNull() + expect(outcome.snapshotRejected).toBeUndefined() + expect(outcome.report).toEqual(golden.reports.demo) + }) +}) + +describe('T6 versions', () => { + let envelope: ReportArchiveEnvelope + beforeAll(async () => { + envelope = (await exportOnDraft(golden.reports.demo)).envelope + }) + + it('envelope v2 wrapper: report kept, snapshot rejected as unsupported_envelope', async () => { + const bytes = await pdfWithAttachment('osteo-report.json', { + ...envelope, + envelopeVersion: 2, + }) + const outcome = await readReportArchive(bytes, map()) + expect(outcome.report).toEqual(golden.reports.demo) + expect(outcome.archive).toBeNull() + expect(outcome.snapshotRejected).toBe('unsupported_envelope') + }) + + it('envelope v1 with a report v4: incompatible_version 4', async () => { + const bytes = await pdfWithAttachment('osteo-report.json', { + ...envelope, + report: { ...envelope.report, version: 4 }, + }) + await rejects(bytes, { kind: 'incompatible_version', foundVersion: 4 }) + }) + + it('bare report version 7: incompatible_version 7', async () => { + const bytes = await pdfWithAttachment('osteo-report.json', { version: 7 }) + await rejects(bytes, { kind: 'incompatible_version', foundVersion: 7 }) + }) +}) + +describe('attachment presence and selection', () => { + it('a stamped PDF without attachment: attachment_stripped', async () => { + const bytes = await pdfWithoutAttachment(['faunosteo-archive/1']) + await rejects(bytes, { kind: 'attachment_stripped' }) + }) + + it('a stamped PDF saved with object streams (pre-BLK-009 layout): the stamp is invisible, no_attachment', async () => { + const bytes = await pdfWithoutAttachment(['faunosteo-archive/1'], true) + await rejects(bytes, { kind: 'no_attachment' }) + }) + + it('a foreign PDF: no_attachment', async () => { + await rejects(await pdfWithoutAttachment(), { kind: 'no_attachment' }) + const foreign = await pdfWithAttachment('other.json', { hello: 'world' }) + await rejects(foreign, { kind: 'no_attachment' }) + }) + + it('the Filespec named osteo-report.json wins over an earlier EmbeddedFile', async () => { + const bytes = await pdfWithAttachment( + 'osteo-report.json', + golden.reports.demo, + { before: ['other.json', { hello: 'world', version: 2 }] }, + ) + const outcome = await readReportArchive(bytes, map()) + expect(outcome.origin).toBe('bare_v3') + expect(outcome.report).toEqual(golden.reports.demo) + }) + + it('refuses an oversized file or one without a %PDF- header as invalid_pdf', async () => { + await rejects(new Uint8Array(MAX_PDF_BYTES + 1), { kind: 'invalid_pdf' }) + await rejects(new TextEncoder().encode('not a pdf at all'), { + kind: 'invalid_pdf', + }) + const late = new Uint8Array(2048) + late.set(new TextEncoder().encode('%PDF-1.7'), 1024) + await rejects(late, { kind: 'invalid_pdf' }) + }) +}) diff --git a/packages/pdf/tests/reexport.test.ts b/packages/pdf/tests/reexport.test.ts new file mode 100644 index 00000000..69f29dcd --- /dev/null +++ b/packages/pdf/tests/reexport.test.ts @@ -0,0 +1,83 @@ +/** + * T1 (STEP6 §5, §7): an archive re-exports from its own envelope, with no + * sheet, no network and no configuration: same drawn text, same images, + * same view facts, same envelope but the export time. + */ +import { afterAll, describe, expect, it, vi } from 'vitest' +import { + buildSheetSnapshot, + ReportSchema, + type ReportArchiveEnvelope, +} from '@faunosteo/domain' +import { + defaultPdfLabels, + exportFromEnvelope, + exportReportArchive, + readReportArchive, + type ExportResult, +} from '../src' +import { loadDraftSheet, readFixtureJson } from './helpers/draft' +import { + FIXED_EXPORTED_AT, + logosBranding, + rasterizerOf, + recordDrawing, + snapshotViews, + type DrawRecording, +} from './helpers/goldens' + +afterAll(() => vi.restoreAllMocks()) + +type Recorded = ExportResult & Pick<DrawRecording, 'texts' | 'images'> + +async function recorded(run: () => Promise<ExportResult>): Promise<Recorded> { + const recording = recordDrawing() + try { + const result = await run() + return { ...result, texts: recording.texts, images: recording.images } + } finally { + recording.stop() + } +} + +const withoutDate = ({ exportedAt: _e, ...rest }: ReportArchiveEnvelope) => rest + +describe('re-export from the envelope alone', () => { + it('reproduces text, images, views and the envelope minus exportedAt', async () => { + // The draft is known here only, for the first export. + const draft = loadDraftSheet() + const report = ReportSchema.parse(readFixtureJson('report-v3.demo.json')) + const first = await recorded(() => + exportReportArchive({ + report, + sheet: buildSheetSnapshot(draft, report), + branding: logosBranding(), + labels: defaultPdfLabels, + locale: 'fr', + rasterizer: rasterizerOf('logos'), + exportedAt: FIXED_EXPORTED_AT, + }), + ) + const outcome = await readReportArchive(first.pdf, draft.migrationMap) + expect(outcome.origin).toBe('envelope_v1') + const archive = outcome.archive! + + // From here on, only the archive is used. + const later = new Date('2027-01-01T00:00:00.000Z') + const second = await recorded(() => + exportFromEnvelope(archive, { + locale: 'fr', + rasterizer: rasterizerOf('logos'), + exportedAt: later, + }), + ) + expect(second.warnings).toEqual([]) + expect(second.texts).toEqual(first.texts) + expect(second.images).toEqual(first.images) + expect( + snapshotViews(second.envelope.sheetSnapshot, second.envelope.report), + ).toEqual(snapshotViews(first.envelope.sheetSnapshot, report)) + expect(second.envelope.exportedAt).toBe(later.toISOString()) + expect(withoutDate(second.envelope)).toEqual(withoutDate(first.envelope)) + }) +}) diff --git a/packages/pdf/tests/scan.test.ts b/packages/pdf/tests/scan.test.ts new file mode 100644 index 00000000..a33e881e --- /dev/null +++ b/packages/pdf/tests/scan.test.ts @@ -0,0 +1,608 @@ +/** + * BLK-009: the byte-scan attachment reader. Candidates on a fresh export and + * on the frozen fixtures (object-stream layout), crafted layouts (two files, + * indirect `/Length`, `\r\n`, no space after `/Type`), garbage, the keyword + * stamp, the object-stream bomb the reader never inflates, and the candidate + * cost bounds (monotonic `endstream` search over offset-sorted candidates, + * shared 16 MiB budget, `{` check, bracket-depth pre-scan before JSON.parse). + */ +import { deflateSync } from 'node:zlib' +import { beforeAll, describe, expect, it, vi } from 'vitest' +import { buildSheetSnapshot, type Report } from '@faunosteo/domain' +import { + ArchiveReadError, + defaultPdfLabels, + exportReportArchive, + findEmbeddedFiles, + readAttachedDocument, + readAttachmentBytes, + readReportArchive, + type EmbeddedFileCandidate, +} from '../src' +import { inflateFlate } from '../src/attachment/inflate' +import { + decodePdfString, + hasArchiveStamp, + locateAttachment, +} from '../src/attachment/scan' +import { readFixtureBytes } from './helpers/draft' +import { + FIXED_EXPORTED_AT, + nologosBranding, + rasterizerOf, +} from './helpers/goldens' +import { pdfWithAttachment, pdfWithoutAttachment } from './helpers/pdf' +import { loadGoldenReports, type GoldenReports } from './helpers/reports' + +let golden: GoldenReports +let exported: Uint8Array +const map = () => golden.draft.migrationMap + +beforeAll(async () => { + golden = loadGoldenReports() + exported = (await exportDemo()).pdf +}) + +async function exportDemo() { + const report: Report = golden.reports.demo + return exportReportArchive({ + report, + sheet: buildSheetSnapshot(golden.draft, report), + branding: nologosBranding(), + labels: defaultPdfLabels, + locale: 'fr', + rasterizer: rasterizerOf('nologos'), + exportedAt: FIXED_EXPORTED_AT, + }) +} + +// --------------------------------------------------------------------------- +// Hand-built PDFs: the scanner never reads the xref, so none is written + +const latin1 = (bytes: Uint8Array) => Buffer.from(bytes).toString('latin1') +const ascii = (text: string) => new Uint8Array(Buffer.from(text, 'latin1')) + +function concat(parts: Uint8Array[]): Uint8Array { + const out = new Uint8Array(parts.reduce((n, p) => n + p.byteLength, 0)) + let at = 0 + for (const part of parts) { + out.set(part, at) + at += part.byteLength + } + return out +} + +interface StreamSpec { + num: number + dict: string + data: Uint8Array + eol?: string +} + +function streamObject({ num, dict, data, eol = '\n' }: StreamSpec): Uint8Array { + return concat([ + ascii(`${num} 0 obj\n<<${dict}>>\nstream${eol}`), + data, + ascii('\nendstream\nendobj\n'), + ]) +} + +function craftPdf(objects: Uint8Array[]): Uint8Array { + return concat([ + ascii('%PDF-1.7\n'), + ...objects, + ascii('trailer\n<< /Root 1 0 R >>\n%%EOF\n'), + ]) +} + +/** The `n 0 obj … endobj` bytes of the object whose dictionary holds `marker`. */ +function objectHolding(pdf: Uint8Array, marker: string): Uint8Array { + const text = latin1(pdf) + const at = text.indexOf(marker) + expect(at).toBeGreaterThan(0) + const start = text.lastIndexOf(' 0 obj', at) + const headerStart = text.lastIndexOf('\n', start) + 1 + const end = text.indexOf('endobj', at) + 'endobj'.length + return pdf.slice(headerStart, end) +} + +const BOMB_RAW = 64 * 1024 * 1024 +const bomb = () => new Uint8Array(deflateSync(new Uint8Array(BOMB_RAW))) + +async function rejects( + bytes: Uint8Array, + kind: ArchiveReadError['kind'], +): Promise<void> { + const promise = readReportArchive(bytes, map()) + await expect(promise).rejects.toBeInstanceOf(ArchiveReadError) + await expect(promise).rejects.toMatchObject({ kind }) +} + +// --------------------------------------------------------------------------- + +describe('findEmbeddedFiles on a fresh export (no object streams)', () => { + let candidates: EmbeddedFileCandidate[] + beforeAll(() => { + candidates = findEmbeddedFiles(exported) + }) + + it('finds the one Flate stream, named through its visible Filespec', async () => { + expect(candidates).toHaveLength(1) + const [c] = candidates + expect(c!.filter).toBe('FlateDecode') + expect(c!.name).toBe('osteo-report.json') + const inflated = await inflateFlate( + exported.subarray(c!.offset, c!.offset + c!.length), + ) + const json = JSON.parse(new TextDecoder().decode(inflated!)) as { + envelopeVersion: number + } + expect(json.envelopeVersion).toBe(1) + }) + + it('the length is the declared /Length and the data ends on endstream', () => { + const [c] = candidates + const text = latin1(exported) + expect(text).toContain(`/Length ${c!.length}\n>>\nstream\n`) + expect(text.slice(c!.offset + c!.length)).toMatch(/^\r?\nendstream/) + }) + + it('the export keeps the Filespec, its name and the stamp in clear, no object stream', () => { + const text = latin1(exported) + expect(text).toContain('/Type /Filespec') + expect(text).toContain('/F (osteo-report.json)') + expect(text).not.toContain('/Type /ObjStm') + expect(hasArchiveStamp(exported)).toBe(true) + }) + + it('readAttachmentBytes returns the inflated envelope bytes', async () => { + const bytes = await readAttachmentBytes(exported) + const json = JSON.parse(new TextDecoder().decode(bytes)) as { + report: Report + } + expect(json.report).toEqual(golden.reports.demo) + }) +}) + +describe('compatibility: frozen fixtures written with object streams', () => { + it.each([ + ['report-v2.full.pdf', 'v2'], + ['report-v2.minimal.pdf', 'v2'], + ['report-v3.bare.pdf', 'bare_v3'], + ] as const)('%s → origin %s', async (name, origin) => { + const bytes = readFixtureBytes(name) + expect(latin1(bytes)).toContain('/Type /ObjStm') + const candidates = findEmbeddedFiles(bytes) + expect(candidates).toHaveLength(1) + // The Filespec is packed into the object stream: no name, the JSON decides. + expect(candidates[0]!.name).toBeNull() + expect(candidates[0]!.filter).toBe('FlateDecode') + const outcome = await readReportArchive(bytes, map()) + expect(outcome.origin).toBe(origin) + }) + + it('a stamped PDF with object streams hides its stamp: no_attachment (documented)', async () => { + const bytes = await pdfWithoutAttachment(['faunosteo-archive/1'], true) + expect(hasArchiveStamp(bytes)).toBe(false) + await rejects(bytes, 'no_attachment') + }) +}) + +describe('selection between several embedded files', () => { + it('a decoy EmbeddedFile first, the named Faunosteo one second: the name wins', async () => { + const bytes = await pdfWithAttachment( + 'osteo-report.json', + golden.reports.demo, + { + before: ['other.json', { hello: 'world', version: 2 }], + }, + ) + const names = findEmbeddedFiles(bytes).map((c) => c.name) + expect(names).toEqual(['osteo-report.json', 'other.json']) + const outcome = await readReportArchive(bytes, map()) + expect(outcome.origin).toBe('bare_v3') + expect(outcome.report).toEqual(golden.reports.demo) + }) + + it('an unnamed decoy without a version is skipped for the versioned JSON after it', async () => { + const decoy = streamObject({ + num: 2, + dict: '/Type /EmbeddedFile /Length 17', + data: ascii('{"hello":"world"}'), + }) + const real = objectHolding(exported, '/Type /EmbeddedFile') + const outcome = await readReportArchive(craftPdf([decoy, real]), map()) + expect(outcome.origin).toBe('envelope_v1') + expect(outcome.report).toEqual(golden.reports.demo) + }) + + it('a foreign PDF, with or without attachments: no_attachment', async () => { + await rejects(await pdfWithoutAttachment(), 'no_attachment') + await rejects( + await pdfWithAttachment('other.json', { hello: 'world' }), + 'no_attachment', + ) + }) +}) + +describe('crafted stream layouts', () => { + // UTF-8: the demo report holds an en dash that Latin-1 cannot carry. + const demoJson = () => + new TextEncoder().encode(JSON.stringify(golden.reports.demo)) + + it('/Length as an indirect reference: read up to endstream', async () => { + const pdf = craftPdf([ + streamObject({ + num: 2, + dict: '/Type /EmbeddedFile /Length 7 0 R', + data: demoJson(), + }), + ascii('7 0 obj\n123456\nendobj\n'), + ]) + const [c] = findEmbeddedFiles(pdf) + expect(c!.filter).toBeNull() + expect(c!.length).toBe(demoJson().byteLength) + expect((await readReportArchive(pdf, map())).origin).toBe('bare_v3') + }) + + it('a wrong direct /Length that does not land on endstream: measured instead', async () => { + const pdf = craftPdf([ + streamObject({ + num: 2, + dict: '/Type /EmbeddedFile /Length 5', + data: demoJson(), + }), + ]) + expect(findEmbeddedFiles(pdf)[0]!.length).toBe(demoJson().byteLength) + expect((await readReportArchive(pdf, map())).origin).toBe('bare_v3') + }) + + it('CRLF after stream, /Type/EmbeddedFile unspaced, a leading /Params dict', async () => { + const data = demoJson() + const pdf = craftPdf([ + streamObject({ + num: 2, + dict: `/Params << /Size ${data.byteLength} >> /Type/EmbeddedFile/Length ${data.byteLength}`, + data, + eol: '\r\n', + }), + ]) + const [c] = findEmbeddedFiles(pdf) + expect(c!.length).toBe(data.byteLength) + expect(await readAttachmentBytes(pdf)).toEqual(data) + }) + + it('a Filespec with a hex /F name and an /EF listing /UF too names its stream', () => { + const name = Buffer.from('osteo-report.json', 'utf16le') + .swap16() + .toString('hex') + const pdf = craftPdf([ + ascii( + `3 0 obj\n<< /Type /Filespec /F <${name}> /EF << /F 2 0 R /UF 2 0 R >> >>\nendobj\n`, + ), + streamObject({ + num: 2, + dict: '/Type /EmbeddedFile /Length 13', + data: ascii('{"version":3}'), + }), + ]) + expect(findEmbeddedFiles(pdf)[0]!.name).toBe('osteo-report.json') + }) + + it('decodePdfString: literal with escapes, hex ASCII, hex UTF-16BE with BOM', () => { + expect(decodePdfString('(a\\(b\\)c)')).toBe('a(b)c') + expect(decodePdfString('<6F7374656F>')).toBe('osteo') + expect(decodePdfString('<FEFF006F0073>')).toBe('os') + expect(decodePdfString('/Name')).toBeNull() + }) +}) + +describe('the keyword stamp', () => { + it('hex (pdf-lib) and literal /Keywords strings are both read', async () => { + expect( + hasArchiveStamp(await pdfWithoutAttachment(['faunosteo-archive/1'])), + ).toBe(true) + expect(hasArchiveStamp(await pdfWithoutAttachment(['other']))).toBe(false) + const literal = craftPdf([ + ascii('3 0 obj\n<< /Keywords (faunosteo-archive/1) >>\nendobj\n'), + ]) + expect(hasArchiveStamp(literal)).toBe(true) + await rejects(literal, 'attachment_stripped') + }) +}) + +describe('garbage never throws', () => { + const cases: [string, Uint8Array][] = [ + ['empty', new Uint8Array(0)], + [ + 'random bytes', + Uint8Array.from({ length: 4096 }, (_, i) => (i * 7919) % 256), + ], + ['the type alone', ascii('%PDF-1.7\n/Type /EmbeddedFile')], + [ + 'dict without stream', + ascii('%PDF-1.7\n<< /Type /EmbeddedFile /Length 3 >>\nendobj'), + ], + [ + 'stream without endstream', + ascii('%PDF-1.7\n<< /Type /EmbeddedFile >>\nstream\n{"version":3}'), + ], + [ + 'only the /EmbeddedFiles name tree key', + ascii('%PDF-1.7\n<< /Type /EmbeddedFiles >>\nstream\nx\nendstream'), + ], + [ + 'unterminated dictionary', + ascii( + '%PDF-1.7\n<< /Type /EmbeddedFile /Length 1 << >>\nstream\nx\nendstream', + ), + ], + [ + 'hex /Keywords without a closing bracket', + ascii('%PDF-1.7\n<< /Keywords <FEFF0066'), + ], + ] + + it.each(cases)( + '%s: no candidate, no stamp, no_attachment or invalid_pdf', + async (_name, bytes) => { + expect(findEmbeddedFiles(bytes)).toEqual([]) + expect(hasArchiveStamp(bytes)).toBe(false) + await expect(readAttachedDocument(bytes)).rejects.toBeInstanceOf( + ArchiveReadError, + ) + }, + ) + + it('caps the candidates at 32', () => { + const objects = Array.from({ length: 40 }, (_, i) => + streamObject({ + num: i + 2, + dict: '/Type /EmbeddedFile /Length 1', + data: ascii('x'), + }), + ) + expect(findEmbeddedFiles(craftPdf(objects))).toHaveLength(32) + }) +}) + +describe('object-stream bomb (BLK-009)', () => { + const MiB = 1024 * 1024 + const objStmBomb = () => { + const data = bomb() + return streamObject({ + num: 9, + dict: `/Type /ObjStm /N 1 /First 4 /Filter /FlateDecode /Length ${data.byteLength}`, + data, + }) + } + const embeddedBomb = () => { + const data = bomb() + return streamObject({ + num: 8, + dict: `/Type /EmbeddedFile /Filter /FlateDecode /Length ${data.byteLength}`, + data, + }) + } + + it('64 MiB ObjStm bomb beside the attachment: report in ms, bomb never inflated', async () => { + const pdf = craftPdf([ + objStmBomb(), + objectHolding(exported, '/Type /Filespec'), + objectHolding(exported, '/Type /EmbeddedFile'), + ]) + expect(pdf.byteLength).toBeLessThan(512 * 1024) + const rssBefore = process.memoryUsage().rss + const started = performance.now() + const outcome = await readReportArchive(pdf, map()) + const elapsed = performance.now() - started + const rssDelta = process.memoryUsage().rss - rssBefore + console.log( + `[bomb] objstm: ${elapsed.toFixed(0)} ms, rss +${(rssDelta / MiB).toFixed(1)} MiB`, + ) + expect(outcome.origin).toBe('envelope_v1') + expect(outcome.report).toEqual(golden.reports.demo) + expect(elapsed).toBeLessThan(2000) + expect(rssDelta).toBeLessThan(64 * MiB) + }) + + it('EmbeddedFile bomb past 16 MiB: inflation cancelled, no_attachment, no hang', async () => { + const pdf = craftPdf([objStmBomb(), embeddedBomb()]) + const started = performance.now() + await rejects(pdf, 'no_attachment') + const elapsed = performance.now() - started + console.log(`[bomb] embedded: ${elapsed.toFixed(0)} ms`) + expect(elapsed).toBeLessThan(2000) + }) + + it('both bombs before an unnamed real attachment: bomb skipped, report read', async () => { + const pdf = craftPdf([ + objStmBomb(), + embeddedBomb(), + objectHolding(exported, '/Type /EmbeddedFile'), + ]) + const started = performance.now() + const outcome = await readReportArchive(pdf, map()) + const elapsed = performance.now() - started + console.log(`[bomb] both + unnamed attachment: ${elapsed.toFixed(0)} ms`) + expect(outcome.report).toEqual(golden.reports.demo) + expect(elapsed).toBeLessThan(2000) + }) +}) + +describe('candidate cost bounds (audit M2)', () => { + const MiB = 1024 * 1024 + /** `n 0 obj << /Type /EmbeddedFile >> stream` with no `/Length`: the data runs to `endstream`. */ + const openStream = (num: number) => + ascii(`${num} 0 obj\n<< /Type /EmbeddedFile >>\nstream\n`) + const filled = (byte: string, length: number) => ascii(byte.repeat(length)) + const timed = async <T>(label: string, run: () => Promise<T> | T) => { + const started = performance.now() + const result = await run() + const elapsed = performance.now() - started + console.log(`[cost] ${label}: ${elapsed.toFixed(0)} ms`) + return { result, elapsed } + } + + it('32 candidates without any endstream on a 20 MiB file: no candidate, well under a second', async () => { + const heads = Array.from({ length: 32 }, (_, i) => openStream(i + 2)) + const pdf = craftPdf([...heads, filled('x', 20 * MiB)]) + const { result, elapsed } = await timed('32 × no endstream', () => + findEmbeddedFiles(pdf), + ) + expect(result).toEqual([]) + expect(elapsed).toBeLessThan(1000) + }) + + it('32 nested EmbeddedFile dicts (descending offsets) without endstream on a 20 MiB file: no candidate, no finder reset', async () => { + // Outermost `/Type` first in the file, its `stream` last: offsets come out + // reversed; the sort by offset keeps the endstream search to one pass. + let nested: Uint8Array = ascii('<< /Type /EmbeddedFile >>\nstream\n') + for (let level = 1; level < 32; level += 1) { + nested = concat([ + ascii('<< /Type /EmbeddedFile /A '), + nested, + ascii(' >>\nstream\n'), + ]) + } + const pdf = craftPdf([ascii('2 0 obj\n'), nested, filled('x', 20 * MiB)]) + const { result, elapsed } = await timed('32 nested, no endstream', () => + findEmbeddedFiles(pdf), + ) + expect(result).toEqual([]) + expect(elapsed).toBeLessThan(500) + }) + + it('several indirect /Length streams in a row: each measured to its own endstream', () => { + const payloads = ['{"version":3}', '{"version":4,"x":1}', '{"v":5}'] + const pdf = craftPdf( + payloads.map((text, i) => + streamObject({ + num: i + 2, + dict: `/Type /EmbeddedFile /Length ${i + 20} 0 R`, + data: ascii(text), + }), + ), + ) + const lengths = findEmbeddedFiles(pdf).map((c) => c.length) + expect(lengths).toEqual(payloads.map((p) => p.length)) + }) + + it('a measured stream running past the cap window is not a candidate, the next one is', () => { + const pdf = craftPdf([ + openStream(2), + filled('x', 16 * MiB + 64), + ascii('\nendstream\nendobj\n'), + streamObject({ + num: 3, + dict: '/Type /EmbeddedFile /Length 13', + data: ascii('{"version":3}'), + }), + ]) + const candidates = findEmbeddedFiles(pdf) + expect(candidates).toHaveLength(1) + expect(candidates[0]!.length).toBe(13) + }) + + it('32 raw candidates of 1 MiB of "[": no_attachment under a second, JSON.parse never called', async () => { + const objects = Array.from({ length: 32 }, (_, i) => + streamObject({ + num: i + 2, + dict: `/Type /EmbeddedFile /Length ${MiB}`, + data: filled('[', MiB), + }), + ) + const pdf = craftPdf(objects) + const parse = vi.spyOn(JSON, 'parse') + try { + const { elapsed } = await timed('32 × 1 MiB "["', () => + rejects(pdf, 'no_attachment'), + ) + expect(elapsed).toBeLessThan(1000) + expect(parse).not.toHaveBeenCalled() + } finally { + parse.mockRestore() + } + }) + + describe('bracket-depth pre-scan before JSON.parse (audit finding 3)', () => { + const flateObject = (num: number, raw: Uint8Array) => { + const data = new Uint8Array(deflateSync(raw)) + return streamObject({ + num, + dict: `/Type /EmbeddedFile /Filter /FlateDecode /Length ${data.byteLength}`, + data, + }) + } + const withSpy = async (run: () => Promise<void>) => { + const parse = vi.spyOn(JSON, 'parse') + try { + await run() + return parse.mock.calls.length + } finally { + parse.mockRestore() + } + } + + it('a 16 KB Flate candidate opening 8 million "[" deep: skipped unparsed, no_attachment fast', async () => { + const raw = concat([ascii('{"version":3,"x":'), filled('[', 8_000_000)]) + const object = flateObject(2, raw) + expect(object.byteLength).toBeLessThan(16 * 1024) + const calls = await withSpy(async () => { + const { elapsed } = await timed('8M-deep candidate', () => + rejects(craftPdf([object]), 'no_attachment'), + ) + expect(elapsed).toBeLessThan(100) + }) + expect(calls).toBe(0) + }) + + it('2000 "[" inside a string with escaped quotes and backslashes: not rejected, parsed once', async () => { + const text = `{"version":3,"note":"\\"${'['.repeat(2000)}\\\\ \\" [[[["}` + const pdf = craftPdf([ + streamObject({ + num: 2, + dict: `/Type /EmbeddedFile /Length ${text.length}`, + data: ascii(text), + }), + ]) + const calls = await withSpy(async () => { + const located = await locateAttachment(pdf) + expect(located.data).toMatchObject({ version: 3 }) + }) + expect(calls).toBe(1) + }) + + it('the real envelope passes the pre-scan and is parsed once', async () => { + const calls = await withSpy(async () => { + const located = await locateAttachment(exported) + expect(located.data).toMatchObject({ envelopeVersion: 1 }) + }) + expect(calls).toBe(1) + }) + }) + + describe('one 16 MiB budget shared by every candidate', () => { + const garbageObject = (num: number) => + streamObject({ + num, + dict: `/Type /EmbeddedFile /Length ${10 * MiB}`, + data: concat([ascii('{'), filled('x', 10 * MiB - 1)]), + }) + const real = () => objectHolding(exported, '/Type /EmbeddedFile') + + it('one 10 MiB garbage object before the attachment: 6 MiB left, the report is read', async () => { + const pdf = craftPdf([garbageObject(2), real()]) + const outcome = await readReportArchive(pdf, map()) + expect(outcome.report).toEqual(golden.reports.demo) + }) + + it('two 10 MiB garbage objects before the attachment: budget exhausted, no_attachment', async () => { + const pdf = craftPdf([garbageObject(2), garbageObject(3), real()]) + const { elapsed } = await timed('2 × 10 MiB "{" + attachment', () => + rejects(pdf, 'no_attachment'), + ) + expect(elapsed).toBeLessThan(2000) + }) + }) +}) diff --git a/packages/pdf/tests/security.test.ts b/packages/pdf/tests/security.test.ts new file mode 100644 index 00000000..1b33da62 --- /dev/null +++ b/packages/pdf/tests/security.test.ts @@ -0,0 +1,987 @@ +/** + * T8 (STEP6 §6, §15): a hostile or oversized snapshot never sinks the + * report on import and never produces an unreadable file on export; hostile + * SVG content is removed, refused or clamped; the real assets pass the + * sanitiser untouched; the inflate bomb guard stays. + */ +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { deflateSync } from 'node:zlib' +import { beforeAll, describe, expect, it, vi } from 'vitest' +import { PDFDict, PDFDocument, PDFName } from 'pdf-lib' +import { + assertSnapshot, + SnapshotError, + type Branding, + type Report, + type ReportArchiveEnvelope, + type SheetSnapshot, +} from '@faunosteo/domain' +import { + ArchiveExportError, + defaultPdfLabels, + exportFromEnvelope, + exportReportArchive, + readReportArchive, + type ExportInput, + type Rasterizer, +} from '../src' +import { inflateFlate } from '../src/attachment/inflate' +import { pngIssue } from '../src/branding' +import { SvgRejectedError } from '../src/errors' +import { addLinkAnnotation } from '../src/render/linkAnnotation' +import { parseSvg, serializeSvg } from '../src/svg/parse' +import { sanitizeSvgRoot } from '../src/svg/sanitize' +import { rasterSizeOf } from '../src/svg/view' +import { BRAND_ASSETS_DIR, DRAFT_DIR, PUBLIC_DIR } from './helpers/draft' +import { + FIXED_EXPORTED_AT, + logosBranding, + nologosBranding, + ONE_PX_PNG, + rasterizerOf, + readLinks, + recordDrawing, + TWO_BY_ONE_PNG, +} from './helpers/goldens' +import { pdfWithAttachment } from './helpers/pdf' +import { loadGoldenReports, type GoldenReports } from './helpers/reports' + +let golden: GoldenReports +let envelope: ReportArchiveEnvelope + +const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T + +function baseInput(report: Report, sheet: SheetSnapshot): ExportInput { + return { + report, + sheet, + branding: nologosBranding(), + labels: defaultPdfLabels, + locale: 'fr', + rasterizer: rasterizerOf('nologos'), + exportedAt: FIXED_EXPORTED_AT, + } +} + +beforeAll(async () => { + golden = loadGoldenReports() + envelope = ( + await exportReportArchive( + baseInput(golden.reports.demo, golden.snapshots.demo), + ) + ).envelope +}) + +/** The reason the domain gate gives: the oracle the engine must surface. */ +function domainReason(snapshot: unknown): string { + try { + assertSnapshot(snapshot) + return 'accepted' + } catch (error) { + if (error instanceof SnapshotError) return error.reason + throw error + } +} + +type Mutation = (snapshot: SheetSnapshot) => void + +const UUID = (i: number) => `00000000-0000-4000-8000-00000000000${i}` + +const MUTATIONS: Array<[string, string, Mutation]> = [ + [ + '5 assets', + 'schema', + (s) => { + s.assets = Array.from({ length: 5 }, (_, i) => ({ + ...s.assets[0]!, + svgAssetId: i === 0 ? s.assets[0]!.svgAssetId : UUID(i), + })) + }, + ], + [ + 'a 3 MiB asset', + 'caps', + (s) => { + s.assets[0]!.svg = 'é'.repeat(1_100_000) + }, + ], + [ + 'finding depth 9', + 'caps', + (s) => { + const leaf = { + id: 'deep', + name: { fr: 'x', en: 'x' }, + description: {}, + requires_vet_referral: false, + reference_ids: [], + review_status: 'inherited' as const, + children: [] as never[], + } + let node: typeof leaf = leaf + for (let depth = 0; depth < 9; depth += 1) { + node = { ...leaf, id: `n${depth}`, children: [node] as never[] } + } + const zone = s.document.finding_zones.find((z) => z.categories.length)! + zone.categories[0]!.children.push(node) + }, + ], + [ + '1,025 annotations', + 'caps', + (s) => { + s.document.annotations.push( + ...Array.from({ length: 1025 }, (_, i) => ({ + ...s.document.annotations[0]!, + id: `extra-${i}`, + })), + ) + }, + ], + [ + 'a view chain cycle', + 'integrity', + (s) => { + const head = s.document.views.find((v) => v.id === 'head')! + if (head.kind === 'detail') head.parent_view_id = 'head' + }, + ], + [ + 'a dangling svg_asset_id', + 'integrity', + (s) => { + s.document.views.find((v) => v.kind === 'main')!.svg_asset_id = UUID(9) + }, + ], + [ + 'another sheet (sheet_mismatch)', + 'sheet_mismatch', + (s) => { + s.ref.documentSha256 = 'f'.repeat(64) + }, + ], +] + +describe('import: the report survives a rejected snapshot', () => { + it.each(MUTATIONS)( + '%s → %s', + async (_name, reason, mutate) => { + const hostile = clone(envelope) + mutate(hostile.sheetSnapshot) + if (reason !== 'sheet_mismatch') { + expect(domainReason(hostile.sheetSnapshot)).toBe(reason) + } + const bytes = await pdfWithAttachment('osteo-report.json', hostile) + const outcome = await readReportArchive(bytes, golden.draft.migrationMap) + expect(outcome.report).toEqual(golden.reports.demo) + expect(outcome.origin).toBe('envelope_v1') + expect(outcome.archive).toBeNull() + expect(outcome.snapshotRejected).toBe(reason) + }, + 20_000, + ) +}) + +describe('export: a snapshot over the caps fails with a typed error and no file', () => { + it.each([ + ['1,025 annotations', 'snapshot_too_large', MUTATIONS[3]![2]], + ['a 3 MiB asset', 'snapshot_too_large', MUTATIONS[1]![2]], + ['5 assets', 'snapshot_invalid', MUTATIONS[0]![2]], + ['a dangling svg_asset_id', 'snapshot_invalid', MUTATIONS[5]![2]], + ['another sheet', 'sheet_mismatch', MUTATIONS[6]![2]], + ] as const)('%s → %s', async (_name, kind, mutate) => { + const sheet = clone(golden.snapshots.demo) + mutate(sheet) + const promise = exportReportArchive(baseInput(golden.reports.demo, sheet)) + await expect(promise).rejects.toBeInstanceOf(ArchiveExportError) + await expect(promise).rejects.toMatchObject({ kind }) + }) + + it('too many observations or views per observation → too_many_pages', async () => { + const demo = golden.reports.demo + const many = { + ...demo, + observations: Array.from({ length: 501 }, (_, i) => ({ + ...demo.observations[0]!, + id: `o${i}`, + })), + } + await expect( + exportReportArchive(baseInput(many, golden.snapshots.demo)), + ).rejects.toMatchObject({ kind: 'too_many_pages' }) + const views = { + ...demo, + observations: [ + { + ...demo.observations[0]!, + zones: Array.from({ length: 9 }, (_, i) => ({ + annotationId: 'c7-t1', + viewId: `v${i}`, + })), + }, + ], + } + await expect( + exportReportArchive(baseInput(views, golden.snapshots.demo)), + ).rejects.toMatchObject({ kind: 'too_many_pages' }) + }) +}) + +// --------------------------------------------------------------------------- +// Hostile SVG + +const SVG_OPEN = + '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 2073.4 1629.4">' +const wrap = (inner: string) => `${SVG_OPEN}${inner}</svg>` + +/** Exports the demo first observation on a snapshot whose drawing is `svg`; returns what the rasterizer saw. */ +async function exportWithAsset(svg: string): Promise<string[]> { + const sheet = clone(golden.snapshots.demo) + sheet.assets[0]!.svg = svg + const seen: string[] = [] + const rasterizer: Rasterizer = async (text) => { + seen.push(text) + return ONE_PX_PNG + } + const report = { + ...golden.reports.demo, + observations: [golden.reports.demo.observations[0]!], + } + const { warnings } = await exportReportArchive({ + ...baseInput(report, sheet), + rasterizer, + }) + expect(warnings).toEqual([]) + return seen +} + +describe('hostile SVG assets', () => { + it('<script>, on*, javascript: href, external <image>, <style> are gone from what is rasterised', async () => { + const [seen] = await exportWithAsset( + wrap( + '<script>alert(1)</script>' + + '<style>path{fill:url(http://evil.test/a)}</style>' + + '<defs><path id="p" d="M0 0h10v10z"/></defs>' + + '<path d="M0 0h1" onload="steal()" style="fill:url(http://evil.test/b)"/>' + + '<use xlink:href="javascript:alert(1)"/><use href="#p"/>' + + '<image href="https://evil.test/x.png" width="10" height="10"/>' + + '<path d="M1 1h1" fill="url(http://evil.test/c)"/>', + ), + ) + expect(seen).toBeDefined() + for (const forbidden of [ + '<script', + '<style', + 'onload', + 'javascript:', + '<image', + 'evil.test', + ]) { + expect(seen).not.toContain(forbidden) + } + expect(seen).toContain('<use href="#p"/>') + expect(seen).toContain('<path id="p" d="M0 0h10v10z"/>') + expect(seen).toContain('fill="#b85a3f"') + }) + + it('the sanitiser names what it removed and clamps stdDeviation', () => { + const root = parseSvg( + wrap( + '<script>x</script><g onclick="y()" data-x="1"><path d="M0 0" style="fill:url(http://e)"/></g>' + + '<filter id="f"><feGaussianBlur stdDeviation="500,3"/><feTurbulence/></filter>' + + '<use xlink:href="javascript:z"/><a href="#ok"/>', + ), + ) + const { removed } = sanitizeSvgRoot(root) + expect(removed).toEqual([ + 'script', + 'g@onclick', + 'g@data-x', + 'path@style', + 'feTurbulence', + 'use@xlink:href', + 'a', + ]) + expect(serializeSvg(root)).toContain('stdDeviation="100 3"') + }) + + it('CSS escapes, image-set and function calls in style or presentation attributes are removed', () => { + const root = parseSvg( + wrap( + '<path d="M0 0" style="fill:u\\72l(http://evil/x)"/>' + + `<path d="M0 0" style='fill:image-set("http://evil/y")'/>` + + '<path d="M0 0" fill="u\\72l(http://evil/x)"/>' + + '<path d="M0 0" fill="rgb(1,2,3)"/>' + + '<path d="M0 0" id="a\b"/>' + + '<path d="M0 0" fill="url(#ok)" transform="translate(1 2)"/>', + ), + ) + const { removed } = sanitizeSvgRoot(root) + expect(removed).toEqual([ + 'path@style', + 'path@style', + 'path@fill', + 'path@fill', + 'path@id', + ]) + const out = serializeSvg(root) + expect(out).not.toContain('evil') + expect(out).not.toContain('rgb(') + expect(out).toContain('fill="url(#ok)" transform="translate(1 2)"') + }) + + it('a non-finite or empty viewBox falls back to the 0.6 ratio, never NaN', () => { + for (const viewBox of [ + '0 0 1e999 1e999', + '0 0 Infinity 10', + '0 0 NaN 10', + '0 0 0 10', + '0 0 -5 10', + '', + ]) { + const size = rasterSizeOf(viewBox) + expect(size, viewBox).toEqual({ widthPx: 1200, heightPx: 720 }) + expect(Number.isFinite(size.heightPx)).toBe(true) + } + }) + + it('<!ENTITY> and 257 <use> are refused: the export fails as snapshot_invalid', async () => { + const entity = + '<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY x "y">]>' + wrap('&x;') + await expect(exportWithAsset(entity)).rejects.toMatchObject({ + kind: 'snapshot_invalid', + }) + const uses = (count: number) => + wrap( + '<defs><path id="p" d="M0 0h1"/></defs>' + + '<use href="#p"/>'.repeat(count), + ) + await expect(exportWithAsset(uses(257))).rejects.toMatchObject({ + kind: 'snapshot_invalid', + }) + expect(() => sanitizeSvgRoot(parseSvg(uses(257)))).toThrow(SvgRejectedError) + await expect(exportWithAsset(uses(256))).resolves.toHaveLength(1) + }) + + it('a huge root viewBox is clamped to a 1200×2400 raster', async () => { + expect(rasterSizeOf('0 0 1 100000')).toEqual({ + widthPx: 1200, + heightPx: 2400, + }) + expect(rasterSizeOf('0 0 100000 1')).toEqual({ + widthPx: 1200, + heightPx: 240, + }) + expect(rasterSizeOf(null)).toEqual({ widthPx: 1200, heightPx: 720 }) + const sizes: Array<{ widthPx: number; heightPx: number }> = [] + const branding = nologosBranding() + branding.partner!.logo = { + kind: 'svg', + svg: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 100000"><rect width="1" height="1"/></svg>', + } + await exportReportArchive({ + ...baseInput(golden.reports.demo, golden.snapshots.demo), + branding, + rasterizer: async (_svg, size) => { + sizes.push(size) + return ONE_PX_PNG + }, + }) + expect(sizes[0]).toEqual({ widthPx: 1200, heightPx: 2400 }) + }) + + it('horse.svg and paws-in-harmony.svg pass with nothing removed and an identical serialisation', () => { + for (const file of [ + resolve(DRAFT_DIR, 'assets/horse.svg'), + resolve(BRAND_ASSETS_DIR, 'paws-in-harmony.svg'), + ]) { + const text = readFileSync(file, 'utf8') + const pristine = serializeSvg(parseSvg(text)) + const root = parseSvg(text) + expect(sanitizeSvgRoot(root)).toEqual({ removed: [] }) + expect(serializeSvg(root)).toBe(pristine) + } + }) +}) + +describe('__proto__ ids and the inflate bomb', () => { + it('report ids named __proto__ print raw and pollute nothing', async () => { + const demo = golden.reports.demo + const report: Report = { + ...demo, + observations: [ + { + ...demo.observations[0]!, + zones: [{ annotationId: '__proto__', viewId: 'main' }], + findings: [ + { + findingZoneId: '__proto__', + path: ['__proto__'], + labelFrSnapshot: 'proto fr', + labelEnSnapshot: 'proto en', + }, + ], + }, + ], + } + const recording = recordDrawing() + try { + const { warnings } = await exportReportArchive( + baseInput(report, golden.snapshots.demo), + ) + expect(warnings).toEqual([]) + const drawn = recording.texts.map((t) => t.text) + expect(drawn).toContain('__proto__') + expect(drawn).toContain('CONSTATS — __PROTO__') + expect(drawn).toContain('proto fr') + } finally { + recording.stop() + } + expect(Object.keys(Object.prototype)).toEqual([]) + expect(({} as Record<string, unknown>).polluted).toBeUndefined() + }) + + async function deflate(data: Uint8Array): Promise<Uint8Array> { + const stream = new Blob([data]) + .stream() + .pipeThrough(new CompressionStream('deflate')) + return new Uint8Array(await new Response(stream).arrayBuffer()) + } + + it('inflates a normal payload and returns null for a 24 MB bomb', async () => { + const payload = new TextEncoder().encode(JSON.stringify({ version: 2 })) + const out = await inflateFlate(await deflate(payload)) + expect(new TextDecoder().decode(out!)).toContain('version') + const bomb = await deflate(new Uint8Array(24 * 1024 * 1024)) + expect(bomb.byteLength).toBeLessThan(1024 * 1024) + expect(await inflateFlate(bomb)).toBeNull() + }) +}) + +// --------------------------------------------------------------------------- +// Branding: URL injection at the link sink, PNG budget + +/** Closes the `/URI (` literal and chains a JavaScript action when written unescaped. */ +const INJECTION_URL = + 'https://a.example/) /Next << /S /JavaScript /JS (app.alert\\(1\\)) >> /Z (' + +/** Every dictionary of the loaded file whose `/S` is `JavaScript`. */ +function javaScriptActions(doc: PDFDocument): PDFDict[] { + return doc.context + .enumerateIndirectObjects() + .map(([, object]) => object) + .filter((object): object is PDFDict => object instanceof PDFDict) + .filter((dict) => dict.get(PDFName.of('S')) === PDFName.of('JavaScript')) +} + +function reexportOptions() { + return { + locale: 'fr' as const, + rasterizer: rasterizerOf('nologos'), + exportedAt: FIXED_EXPORTED_AT, + } +} + +/** The same payload without spaces: PDF syntax needs none, and the sink lets it through to the hex string. */ +const TIGHT_INJECTION_URL = INJECTION_URL.replaceAll(' ', '') + +/** The saved bytes of a one-page PDF holding one link to `url`, objects uncompressed so the bytes can be read. */ +async function savedLink(url: string): Promise<Uint8Array> { + const doc = await PDFDocument.create() + addLinkAnnotation(doc.addPage(), { x: 0, y: 0, width: 10, height: 10, url }) + return doc.save({ useObjectStreams: false }) +} + +/** `<hex>` of the URL's ASCII bytes, as the sink must write `/URI`. */ +const asciiHex = (url: string): string => + Array.from(url, (c) => c.charCodeAt(0).toString(16).padStart(2, '0')).join('') + +describe('branding URL injection (HIGH)', () => { + it('writes /URI as the hex of the ASCII bytes, no UTF-16 BOM, and reloads to the URL', async () => { + const url = 'https://faunosteo.com' + const bytes = await savedLink(url) + const raw = Buffer.from(bytes).toString('latin1') + const uriMatch = /\/URI\s*<([0-9A-Fa-f]+)>/.exec(raw) + expect(uriMatch?.[1]?.toLowerCase()).toBe(asciiHex(url)) + expect(uriMatch?.[1]?.toUpperCase().startsWith('FEFF')).toBe(false) + expect(Buffer.from(uriMatch![1]!, 'hex').toString('latin1')).toBe(url) + const [link] = await readLinks(bytes) + expect(link?.uri).toBe(url) + }) + + it('a URL with a code point above 0x7e or below 0x21 throws branding_invalid at the sink', async () => { + for (const url of [ + 'https://faunosté.com', + 'https://a.example/ b', + INJECTION_URL, + 'https://a.example/\u00ff', + ]) { + await expect(savedLink(url), url).rejects.toMatchObject({ + kind: 'branding_invalid', + }) + await expect(savedLink(url), url).rejects.toBeInstanceOf( + ArchiveExportError, + ) + } + }) + + it('the link sink alone keeps the whole URL inside the /URI string', async () => { + const bytes = await savedLink(TIGHT_INJECTION_URL) + const raw = Buffer.from(bytes).toString('latin1') + expect(raw).not.toContain('/JavaScript') + expect(raw).not.toContain('/Next') + expect(raw).not.toContain('/JS') + const reloaded = await PDFDocument.load(bytes) + expect(javaScriptActions(reloaded)).toEqual([]) + const action = reloaded + .getPage(0) + .node.Annots()! + .lookup(0, PDFDict) + .lookup(PDFName.of('A'), PDFDict) + expect(action.has(PDFName.of('Next'))).toBe(false) + expect(action.get(PDFName.of('S'))).toBe(PDFName.of('URI')) + const [link] = await readLinks(bytes) + expect(link?.uri).toBe(TIGHT_INJECTION_URL) + }) + + it('exportFromEnvelope refuses the URL before drawing anything: branding_invalid', async () => { + const hostile = clone(envelope) + hostile.branding = { + ...hostile.branding, + siteUrl: INJECTION_URL, + } as unknown as Branding + const recording = recordDrawing() + try { + const promise = exportFromEnvelope(hostile, reexportOptions()) + await expect(promise).rejects.toBeInstanceOf(ArchiveExportError) + await expect(promise).rejects.toMatchObject({ kind: 'branding_invalid' }) + expect(recording.texts).toEqual([]) + expect(recording.images).toEqual([]) + } finally { + recording.stop() + } + }) + + it('a credit URL with a parenthesis and a broken label set are refused the same way', async () => { + const credit = clone(envelope) + credit.branding.partner!.url = 'https://a.example/)' + await expect( + exportFromEnvelope(credit, reexportOptions()), + ).rejects.toMatchObject({ kind: 'branding_invalid' }) + const labels = clone(envelope) + delete (labels.labels.fr as Record<string, string>)['pdf.subject'] + await expect( + exportFromEnvelope(labels, reexportOptions()), + ).rejects.toMatchObject({ kind: 'branding_invalid' }) + await expect( + exportFromEnvelope(clone(envelope), reexportOptions()), + ).resolves.toMatchObject({ warnings: [] }) + }) +}) + +interface IhdrFields { + depth?: number + colourType?: number + compression?: number + filter?: number + interlace?: number +} + +const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] + +/** + * A PNG signature and an IHDR chunk announcing `width` × `height`, 8-bit + * greyscale non-interlaced unless `fields` says otherwise, nothing after. + */ +function pngHeader( + width: number, + height: number, + fields: IhdrFields = {}, + signature = true, +): Uint8Array { + const bytes = new Uint8Array(33) + bytes.set(PNG_SIGNATURE) + if (!signature) bytes[3] = 0x48 + const view = new DataView(bytes.buffer) + view.setUint32(8, 13) + bytes.set([0x49, 0x48, 0x44, 0x52], 12) + view.setUint32(16, width) + view.setUint32(20, height) + const { depth = 8, colourType = 0, compression = 0 } = fields + const { filter = 0, interlace = 0 } = fields + bytes.set([depth, colourType, compression, filter, interlace], 24) + return bytes +} + +/** One chunk: length, four-letter type, `data`, a zero CRC. */ +function pngChunk(type: string, data: Uint8Array): Uint8Array { + const bytes = new Uint8Array(12 + data.byteLength) + new DataView(bytes.buffer).setUint32(0, data.byteLength) + bytes.set( + Array.from(type, (c) => c.charCodeAt(0)), + 4, + ) + bytes.set(data, 8) + return bytes +} + +const concat = (...parts: Uint8Array[]): Uint8Array => + Uint8Array.from(Buffer.concat(parts.map((p) => Buffer.from(p)))) + +const CHANNELS: Record<number, number> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 } + +/** Raw scanlines of a non-interlaced image: a filter byte then the packed samples, per row. */ +function rawSize( + width: number, + height: number, + fields: IhdrFields = {}, +): number { + const { depth = 8, colourType = 0 } = fields + const bitsPerPixel = CHANNELS[colourType]! * depth + return (Math.ceil((width * bitsPerPixel) / 8) + 1) * height +} + +/** An IDAT chunk holding the zlib stream of `raw`. */ +const idatOf = (raw: Uint8Array): Uint8Array => + pngChunk('IDAT', deflateSync(raw)) + +const IEND = pngChunk('IEND', new Uint8Array(0)) +/** The IDAT of a 1×1 8-bit greyscale image (2 raw bytes), what `pngHeader(1, 1)` announces. */ +const IDAT = idatOf(new Uint8Array(2)) + +/** A complete valid PNG of zero pixels: header, one IDAT of the exact raw size, IEND. */ +function validPng( + width: number, + height: number, + fields: IhdrFields = {}, +): Uint8Array { + const raw = new Uint8Array(rawSize(width, height, fields)) + return concat(pngHeader(width, height, fields), idatOf(raw), IEND) +} + +/** A 1×1 header followed by a second IHDR announcing 10000 × 10000, then IEND. */ +function doubledIhdrPng(): Uint8Array { + const second = pngHeader(10_000, 10_000).subarray(8) + return concat(pngHeader(1, 1), second, IEND) +} + +/** + * The auditor's PoC: a valid 1×1 PNG whose IEND is replaced by a `tEXt` + * chunk "AAAA" with a non-zero CRC and no NUL byte, so UPNG's `nextZero` + * never stops (`ONE_PX_PNG` minus its 12-byte IEND). + */ +function textWithoutNulPng(): Uint8Array { + const text = pngChunk('tEXt', new TextEncoder().encode('AAAA')) + text.fill(0xff, text.byteLength - 4) + return concat(ONE_PX_PNG.subarray(0, ONE_PX_PNG.byteLength - 12), text) +} + +/** The second PoC: an `iTXt` chunk, then an IEND of length 0x010101 with a non-zero payload. */ +function itxtThenFatIendPng(): Uint8Array { + const itxt = pngChunk('iTXt', new TextEncoder().encode('kw')) + const fatIend = pngChunk('IEND', new Uint8Array(0x010101).fill(1)) + return concat(pngHeader(1, 1), IDAT, itxt, fatIend) +} + +/** + * The third PoC, 77 bytes: 16×16 RGBA, a zlib IDAT cut to 20 bytes, IEND. + * Signature and chunk list are sound; UPNG's `inflateRaw` reads past the + * end of the stream and never returns. + */ +function truncatedIdatPng(): Uint8Array { + const raw = Uint8Array.from( + { length: rawSize(16, 16, { colourType: 6 }) }, + (_, i) => i & 0xff, + ) + const stream = deflateSync(raw).subarray(0, 20) + const header = pngHeader(16, 16, { colourType: 6 }) + return concat(header, pngChunk('IDAT', stream), IEND) +} + +interface Chunk { + type: string + data: Uint8Array +} + +/** The chunks of a well-formed PNG, in file order, CRCs dropped. */ +function chunksOf(png: Uint8Array): Chunk[] { + const view = new DataView(png.buffer, png.byteOffset, png.byteLength) + const chunks: Chunk[] = [] + let offset = 8 + while (offset < png.byteLength) { + const length = view.getUint32(offset) + const type = String.fromCharCode(...png.subarray(offset + 4, offset + 8)) + chunks.push({ type, data: png.subarray(offset + 8, offset + 8 + length) }) + offset += 12 + length + } + return chunks +} + +const pngOf = (chunks: Chunk[]): Uint8Array => + concat( + Uint8Array.from(PNG_SIGNATURE), + ...chunks.map((c) => pngChunk(c.type, c.data)), + ) + +function headerLogoBytes(): Uint8Array { + const asset = logosBranding().headerLogo + if (asset?.kind !== 'png') throw new Error('png expected') + return Uint8Array.from(Buffer.from(asset.base64, 'base64')) +} + +/** The real header logo with the last 5 bytes of its IDAT stream removed: the chunk list stays sound. */ +function cutLogoPng(): Uint8Array { + const chunks = chunksOf(headerLogoBytes()) + const last = chunks.filter((c) => c.type === 'IDAT').at(-1)! + last.data = last.data.subarray(0, last.data.byteLength - 5) + return pngOf(chunks) +} + +describe('PNG budget (MEDIUM)', () => { + it.each([ + ['8193 × 1', 8193, 1], + ['1 × 8193', 1, 8193], + ['4097 × 4096 (over 4096²)', 4097, 4096], + ['12000 × 12000 (144 Mpx)', 12_000, 12_000], + ['0 × 0', 0, 0], + ['1 × 0', 1, 0], + ['8192 × 0', 8192, 0], + ])('%s → dimensions', async (_name, width, height) => { + const png = concat(pngHeader(width, height), IEND) + expect(await pngIssue(png)).toBe('dimensions') + }) + + it('the raw-size budget: 16 MiB of scanlines at most, whatever the pixel count', async () => { + // 1-bit grey: 513 bytes a row. + expect(await pngIssue(validPng(4096, 4096, { depth: 1 }))).toBeNull() + expect(await pngIssue(validPng(8192, 2048, { depth: 1 }))).toBeNull() + // 8-bit grey: (4095 + 1) × 4096 is exactly 16 MiB, one more row byte is over. + expect(await pngIssue(validPng(4095, 4096))).toBeNull() + const overByARow = concat(pngHeader(4096, 4096), IEND) + expect(await pngIssue(overByARow)).toBe('dimensions') + // 8-bit RGBA at 4096²: 67 MB of scanlines, refused before any inflation. + const rgba = concat(pngHeader(4096, 4096, { colourType: 6 }), IEND) + expect(await pngIssue(rgba)).toBe('dimensions') + expect(rawSize(4096, 4096, { colourType: 6 })).toBeGreaterThan( + 16 * 1024 * 1024, + ) + }) + + it.each([ + ['depth 255', { depth: 255 }], + ['colour type 5', { colourType: 5 }], + ['interlace 1 (Adam7)', { interlace: 1 }], + ['filter method 1', { filter: 1 }], + ['compression method 1', { compression: 1 }], + ['depth 4 for RGBA', { depth: 4, colourType: 6 }], + ['depth 16 for a palette', { depth: 16, colourType: 3 }], + ])('%s → ihdr', async (_name, fields: IhdrFields) => { + expect(await pngIssue(validPng(4, 3, fields))).toBe('ihdr') + const atTheCap = concat(pngHeader(4096, 4096, fields), IEND) + expect(await pngIssue(atTheCap)).toBe('ihdr') + }) + + it('every colour type and depth the spec allows passes with a matching IDAT', async () => { + const allowed: Array<[number, number[]]> = [ + [0, [1, 2, 4, 8, 16]], + [2, [8, 16]], + [3, [1, 2, 4, 8]], + [4, [8, 16]], + [6, [8, 16]], + ] + for (const [colourType, depths] of allowed) { + for (const depth of depths) { + const png = validPng(5, 3, { depth, colourType }) + expect( + await pngIssue(png), + `type ${colourType} depth ${depth}`, + ).toBeNull() + } + } + }) + + it('an IDAT stream that is truncated, empty, not zlib or off by one raw byte → idat', async () => { + const poc = truncatedIdatPng() + expect(poc.byteLength).toBe(77) + expect(await pngIssue(poc)).toBe('idat') + expect(await pngIssue(cutLogoPng())).toBe('idat') + expect(await pngIssue(concat(pngHeader(1, 1), IEND))).toBe('idat') + const notZlib = pngChunk('IDAT', new Uint8Array(16)) + expect(await pngIssue(concat(pngHeader(1, 1), notZlib, IEND))).toBe('idat') + for (const delta of [1, -1]) { + const raw = new Uint8Array(rawSize(4, 3) + delta) + const png = concat(pngHeader(4, 3), idatOf(raw), IEND) + expect(await pngIssue(png), `off by ${delta}`).toBe('idat') + } + expect(await pngIssue(validPng(4, 3))).toBeNull() + }) + + it('the IDAT stream may span several chunks', async () => { + const stream = deflateSync(new Uint8Array(rawSize(4, 3))) + const split = Math.floor(stream.byteLength / 2) + const png = concat( + pngHeader(4, 3), + pngChunk('IDAT', stream.subarray(0, split)), + pngChunk('IDAT', stream.subarray(split)), + IEND, + ) + expect(await pngIssue(png)).toBeNull() + }) + + it('a wrong signature or a truncated header is refused; the real logos pass', async () => { + expect(await pngIssue(pngHeader(1, 1, {}, false))).toBe('signature') + expect(await pngIssue(pngHeader(1, 1).subarray(0, 20))).toBe('signature') + const svg = new TextEncoder().encode('<svg/>') + expect(await pngIssue(svg)).toBe('signature') + expect(await pngIssue(ONE_PX_PNG)).toBeNull() + expect(await pngIssue(TWO_BY_ONE_PNG)).toBeNull() + const logos = logosBranding() + for (const asset of [ + logos.headerLogo, + logos.footerLogo, + logos.poweredBy!.logo, + ]) { + if (asset?.kind !== 'png') throw new Error('png expected') + expect(await pngIssue(Buffer.from(asset.base64, 'base64'))).toBeNull() + } + const touchIcon = readFileSync(resolve(PUBLIC_DIR, 'apple-touch-icon.png')) + expect(await pngIssue(new Uint8Array(touchIcon))).toBeNull() + }) + + it('the chunk walk refuses a second IHDR, an APNG acTL and a length past the buffer', async () => { + expect(await pngIssue(doubledIhdrPng())).toBe('chunks') + const apng = concat( + pngHeader(1, 1), + pngChunk('acTL', new Uint8Array(8)), + IEND, + ) + expect(await pngIssue(apng)).toBe('chunks') + for (const type of ['fcTL', 'fdAT']) { + const frame = concat( + pngHeader(1, 1), + pngChunk(type, new Uint8Array(4)), + IEND, + ) + expect(await pngIssue(frame), type).toBe('chunks') + } + const idat = pngChunk('IDAT', new Uint8Array(16)) + new DataView(idat.buffer).setUint32(0, 1_000_000) + expect(await pngIssue(concat(pngHeader(1, 1), idat))).toBe('chunks') + const partialHead = concat(pngHeader(1, 1), new Uint8Array(5)) + expect(await pngIssue(partialHead)).toBe('chunks') + expect(await pngIssue(concat(pngHeader(1, 1), IDAT, IEND))).toBeNull() + const shortIhdr = pngHeader(1, 1) + new DataView(shortIhdr.buffer).setUint32(8, 12) + expect(await pngIssue(shortIhdr)).toBe('signature') + }) + + it('a chunk UPNG reads with nextZero, or any type outside the allowlist, is refused', async () => { + expect(await pngIssue(textWithoutNulPng())).toBe('chunks') + expect(await pngIssue(itxtThenFatIendPng())).toBe('chunks') + for (const type of ['tIME', 'zTXt', 'iCCP', 'abCD']) { + const png = concat( + pngHeader(1, 1), + IDAT, + pngChunk(type, new Uint8Array(7)), + IEND, + ) + expect(await pngIssue(png), type).toBe('chunks') + } + }) + + it('the list must end on an empty IEND that closes the buffer; ancillary chunks pass', async () => { + const valid = concat(pngHeader(1, 1), IDAT, IEND) + expect(await pngIssue(concat(valid, new Uint8Array([0])))).toBe('chunks') + expect(await pngIssue(concat(pngHeader(1, 1), IDAT))).toBe('chunks') + const fatIend = pngChunk('IEND', new Uint8Array(1)) + expect(await pngIssue(concat(pngHeader(1, 1), IDAT, fatIend))).toBe( + 'chunks', + ) + const ancillary = concat( + pngHeader(1, 1), + pngChunk('gAMA', new Uint8Array(4)), + pngChunk('pHYs', new Uint8Array(9)), + pngChunk('sRGB', new Uint8Array(1)), + IDAT, + IEND, + ) + expect(await pngIssue(ancillary)).toBeNull() + }) + + it.each([ + ['an oversized header logo', () => concat(pngHeader(16_384, 16_384), IEND)], + ['a doubled-IHDR header logo', doubledIhdrPng], + ['a tEXt-without-NUL header logo (UPNG would spin)', textWithoutNulPng], + [ + 'a truncated-IDAT header logo (UPNG inflateRaw would read past the buffer)', + truncatedIdatPng, + ], + ['a 1 × 0 header logo', () => concat(pngHeader(1, 0), IDAT, IEND)], + ])( + '%s fails alone with logo_failed and never reaches embedPng', + async (_name, make) => { + const branding = nologosBranding() + const huge = make() + branding.headerLogo = { + kind: 'png', + base64: Buffer.from(huge).toString('base64'), + } + branding.footerLogo = { + kind: 'png', + base64: Buffer.from(ONE_PX_PNG).toString('base64'), + } + // The spy refuses the hostile bytes itself: a regression that lets + // them through fails on the assertion below instead of spinning the + // worker in UPNG's nextZero or inflateRaw, which no vitest timeout + // can interrupt. + const realEmbedPng = PDFDocument.prototype.embedPng + const embedPng = vi + .spyOn(PDFDocument.prototype, 'embedPng') + .mockImplementation(function (this: PDFDocument, png) { + if (Buffer.from(png as Uint8Array).equals(Buffer.from(huge))) { + throw new Error('hostile png reached embedPng') + } + return realEmbedPng.call(this, png) + }) + try { + const { warnings } = await exportReportArchive({ + ...baseInput(golden.reports.demo, golden.snapshots.demo), + branding, + }) + expect(warnings).toEqual([{ kind: 'logo_failed', slot: 'headerLogo' }]) + const base64 = (png: Uint8Array) => Buffer.from(png).toString('base64') + const embedded = embedPng.mock.calls.map(([png]) => + base64(png as Uint8Array), + ) + expect(embedded).not.toContain(base64(huge)) + expect(embedded).toContain(base64(ONE_PX_PNG)) + } finally { + embedPng.mockRestore() + } + }, + 10_000, + ) + + it('the real logos reach embedPng when the gate passes them', async () => { + const embedPng = vi.spyOn(PDFDocument.prototype, 'embedPng') + try { + const { warnings } = await exportReportArchive({ + ...baseInput(golden.reports.demo, golden.snapshots.demo), + branding: logosBranding(), + rasterizer: rasterizerOf('logos'), + }) + expect(warnings).toEqual([]) + const embedded = embedPng.mock.calls.map(([png]) => + Buffer.from(png as Uint8Array).toString('base64'), + ) + const logos = logosBranding() + for (const asset of [logos.headerLogo, logos.footerLogo]) { + if (asset?.kind !== 'png') throw new Error('png expected') + expect(embedded).toContain(asset.base64) + } + } finally { + embedPng.mockRestore() + } + }) +}) diff --git a/packages/pdf/tests/size.test.ts b/packages/pdf/tests/size.test.ts new file mode 100644 index 00000000..85482282 --- /dev/null +++ b/packages/pdf/tests/size.test.ts @@ -0,0 +1,47 @@ +/** + * T7 (STEP6 §7): the demo envelope stays well under the attachment cap; + * stored (Flate) and raw sizes are printed for both brandings. + */ +import { beforeAll, describe, expect, it } from 'vitest' +import { defaultPdfLabels, exportReportArchive } from '../src' +import { + brandingOf, + FIXED_EXPORTED_AT, + rasterizerOf, + type LogoMode, +} from './helpers/goldens' +import { storedAttachmentSize } from './helpers/pdf' +import { loadGoldenReports, type GoldenReports } from './helpers/reports' + +const MAX_STORED = 250_000 + +let golden: GoldenReports +beforeAll(() => { + golden = loadGoldenReports() +}) + +describe('demo envelope size', () => { + it.each<LogoMode>(['nologos', 'logos'])( + '%s: stored attachment under 250,000 bytes', + async (mode) => { + const { pdf, envelope } = await exportReportArchive({ + report: golden.reports.demo, + sheet: golden.snapshots.demo, + branding: brandingOf(mode), + labels: defaultPdfLabels, + locale: 'fr', + rasterizer: rasterizerOf(mode), + exportedAt: FIXED_EXPORTED_AT, + }) + const raw = new TextEncoder().encode( + JSON.stringify(envelope, null, 2), + ).byteLength + const stored = storedAttachmentSize(pdf) + console.log( + `[size] demo ${mode}: stored ${stored} B, raw ${raw} B, pdf ${pdf.byteLength} B`, + ) + expect(stored).toBeLessThan(MAX_STORED) + expect(stored).toBeLessThan(raw) + }, + ) +}) diff --git a/packages/pdf/tests/text.test.ts b/packages/pdf/tests/text.test.ts new file mode 100644 index 00000000..38c5332b --- /dev/null +++ b/packages/pdf/tests/text.test.ts @@ -0,0 +1,90 @@ +/** + * T9 (STEP6 §15): the WinAnsi canary. One text ingress, so a glyph the + * standard fonts cannot encode never reaches pdf-lib; `formatDate` never + * throws on user data. + */ +import { beforeAll, describe, expect, it } from 'vitest' +import { PDFDocument, StandardFonts } from 'pdf-lib' +import { buildSheetSnapshot } from '@faunosteo/domain' +import { defaultPdfLabels, exportReportArchive } from '../src' +import { formatDate } from '../src/render/dates' +import { wrapLines } from '../src/render/text' +import { safeText } from '../src/text' +import { + FIXED_EXPORTED_AT, + nologosBranding, + rasterizerOf, + recordDrawing, +} from './helpers/goldens' +import { loadGoldenReports, type GoldenReports } from './helpers/reports' + +let golden: GoldenReports +beforeAll(() => { + golden = loadGoldenReports() +}) + +describe('safeText', () => { + it('keeps the WinAnsi glyphs the pages use', () => { + const kept = 'Fixation (C2–C7) — bilan • zone · Sévérité à l’écu €' + expect(safeText(kept)).toBe(kept) + }) + + it('replaces unencodable glyphs by ? and strips control characters', () => { + expect(safeText('⚠ alerte')).toBe('? alerte') + expect(safeText('a → b')).toBe('a ? b') + expect(safeText('ok 😀')).toBe('ok ?') + expect(safeText('a\tb')).toBe('ab') + expect(safeText('a
b')).toBe('ab') + expect(safeText('a\x1bb')).toBe('ab') + }) + + it('wrapLines splits on any whitespace first, then makes each word safe', async () => { + const doc = await PDFDocument.create() + const font = await doc.embedFont(StandardFonts.Helvetica) + expect(wrapLines('un\tdeux\ntrois ⚠', font, 10, 1000)).toEqual([ + 'un deux trois ?', + ]) + }) +}) + +describe('export with hostile text', () => { + it('a report with ⚠ in a comment exports; the glyph prints as ?', async () => { + const demo = golden.reports.demo + const report = { + ...demo, + observations: [ + { ...demo.observations[0]!, comment: 'Attention ⚠ tab\tici → fin' }, + ], + conclusion: 'Conclusion ⚠', + } + const recording = recordDrawing() + try { + const { warnings } = await exportReportArchive({ + report, + sheet: buildSheetSnapshot(golden.draft, report), + branding: nologosBranding(), + labels: defaultPdfLabels, + locale: 'fr', + rasterizer: rasterizerOf('nologos'), + exportedAt: FIXED_EXPORTED_AT, + }) + expect(warnings).toEqual([]) + const drawn = recording.texts.map((t) => t.text) + expect(drawn).toContain('Attention ? tab ici ? fin') + expect(drawn).toContain('Conclusion ?') + expect(drawn.every((t) => safeText(t) === t)).toBe(true) + } finally { + recording.stop() + } + }) +}) + +describe('formatDate', () => { + it('formats an ISO date per locale and returns anything else unchanged', () => { + expect(formatDate('2026-11-20', 'fr')).toBe('20 novembre 2026') + expect(formatDate('2026-11-20', 'en')).toBe('November 20, 2026') + expect(formatDate('n/a', 'fr')).toBe('n/a') + expect(formatDate('2026-13-45', 'en')).toBe('2026-13-45') + expect(formatDate('2026-02-30', 'en')).toBe('2026-02-30') + }) +}) diff --git a/packages/pdf/tsconfig.json b/packages/pdf/tsconfig.json new file mode 100644 index 00000000..99d2ea87 --- /dev/null +++ b/packages/pdf/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022"], + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "noImplicitReturns": true, + "skipLibCheck": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "isolatedModules": true, + "types": ["node", "vitest/globals"], + "noEmit": true + }, + "include": ["src", "tests"], + "exclude": ["node_modules"] +} diff --git a/packages/pdf/vitest.config.ts b/packages/pdf/vitest.config.ts new file mode 100644 index 00000000..f6374039 --- /dev/null +++ b/packages/pdf/vitest.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + environment: 'node', + globals: true, + include: ['tests/**/*.test.ts'], + }, +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 11574827..8a6927e4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -26,6 +26,9 @@ importers: '@faunosteo/domain': specifier: workspace:* version: link:../../packages/domain + '@faunosteo/pdf': + specifier: workspace:* + version: link:../../packages/pdf '@faunosteo/supabase': specifier: workspace:* version: link:../../packages/supabase @@ -168,6 +171,49 @@ importers: specifier: ^3.2.7 version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0)(tsx@4.23.15) + packages/pdf: + dependencies: + '@faunosteo/anatomy': + specifier: workspace:* + version: link:../anatomy + '@faunosteo/domain': + specifier: workspace:* + version: link:../domain + '@pdf-lib/standard-fonts': + specifier: ^1.0.0 + version: 1.0.0 + '@xmldom/xmldom': + specifier: ^0.9.8 + version: 0.9.12 + pdf-lib: + specifier: ^1.17.1 + version: 1.17.1 + devDependencies: + '@pdf-lib/upng': + specifier: ^1.0.1 + version: 1.0.1 + '@resvg/resvg-js': + specifier: ^2.6.2 + version: 2.6.2 + '@types/node': + specifier: ^20.19.41 + version: 20.19.41 + eslint: + specifier: ^9.17.0 + version: 9.39.4(jiti@2.7.0) + globals: + specifier: ^15.14.0 + version: 15.15.0 + typescript: + specifier: ^5.7.2 + version: 5.9.3 + typescript-eslint: + specifier: ^8.19.0 + version: 8.59.3(eslint@9.39.4(jiti@2.7.0))(typescript@5.9.3) + vitest: + specifier: ^3.2.7 + version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0)(tsx@4.23.15) + packages/supabase: dependencies: '@faunosteo/domain': @@ -473,6 +519,82 @@ packages: '@pdf-lib/upng@1.0.1': resolution: {integrity: sha512-dQK2FUMQtowVP00mtIksrlZhdFXQZPC+taih1q4CvPZ5vqdxR/LKBaFg0oAfzd1GlHZXXSPdQfzQnt+ViGvEIQ==} + '@resvg/resvg-js-android-arm-eabi@2.6.2': + resolution: {integrity: sha512-FrJibrAk6v29eabIPgcTUMPXiEz8ssrAk7TXxsiZzww9UTQ1Z5KAbFJs+Z0Ez+VZTYgnE5IQJqBcoSiMebtPHA==} + engines: {node: '>= 10'} + cpu: [arm] + os: [android] + + '@resvg/resvg-js-android-arm64@2.6.2': + resolution: {integrity: sha512-VcOKezEhm2VqzXpcIJoITuvUS/fcjIw5NA/w3tjzWyzmvoCdd+QXIqy3FBGulWdClvp4g+IfUemigrkLThSjAQ==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [android] + + '@resvg/resvg-js-darwin-arm64@2.6.2': + resolution: {integrity: sha512-nmok2LnAd6nLUKI16aEB9ydMC6Lidiiq2m1nEBDR1LaaP7FGs4AJ90qDraxX+CWlVuRlvNjyYJTNv8qFjtL9+A==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [darwin] + + '@resvg/resvg-js-darwin-x64@2.6.2': + resolution: {integrity: sha512-GInyZLjgWDfsVT6+SHxQVRwNzV0AuA1uqGsOAW+0th56J7Nh6bHHKXHBWzUrihxMetcFDmQMAX1tZ1fZDYSRsw==} + engines: {node: '>= 10'} + cpu: [x64] + os: [darwin] + + '@resvg/resvg-js-linux-arm-gnueabihf@2.6.2': + resolution: {integrity: sha512-YIV3u/R9zJbpqTTNwTZM5/ocWetDKGsro0SWp70eGEM9eV2MerWyBRZnQIgzU3YBnSBQ1RcxRZvY/UxwESfZIw==} + engines: {node: '>= 10'} + cpu: [arm] + os: [linux] + + '@resvg/resvg-js-linux-arm64-gnu@2.6.2': + resolution: {integrity: sha512-zc2BlJSim7YR4FZDQ8OUoJg5holYzdiYMeobb9pJuGDidGL9KZUv7SbiD4E8oZogtYY42UZEap7dqkkYuA91pg==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + + '@resvg/resvg-js-linux-arm64-musl@2.6.2': + resolution: {integrity: sha512-3h3dLPWNgSsD4lQBJPb4f+kvdOSJHa5PjTYVsWHxLUzH4IFTJUAnmuWpw4KqyQ3NA5QCyhw4TWgxk3jRkQxEKg==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + + '@resvg/resvg-js-linux-x64-gnu@2.6.2': + resolution: {integrity: sha512-IVUe+ckIerA7xMZ50duAZzwf1U7khQe2E0QpUxu5MBJNao5RqC0zwV/Zm965vw6D3gGFUl7j4m+oJjubBVoftw==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + + '@resvg/resvg-js-linux-x64-musl@2.6.2': + resolution: {integrity: sha512-UOf83vqTzoYQO9SZ0fPl2ZIFtNIz/Rr/y+7X8XRX1ZnBYsQ/tTb+cj9TE+KHOdmlTFBxhYzVkP2lRByCzqi4jQ==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + + '@resvg/resvg-js-win32-arm64-msvc@2.6.2': + resolution: {integrity: sha512-7C/RSgCa+7vqZ7qAbItfiaAWhyRSoD4l4BQAbVDqRRsRgY+S+hgS3in0Rxr7IorKUpGE69X48q6/nOAuTJQxeQ==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [win32] + + '@resvg/resvg-js-win32-ia32-msvc@2.6.2': + resolution: {integrity: sha512-har4aPAlvjnLcil40AC77YDIk6loMawuJwFINEM7n0pZviwMkMvjb2W5ZirsNOZY4aDbo5tLx0wNMREp5Brk+w==} + engines: {node: '>= 10'} + cpu: [ia32] + os: [win32] + + '@resvg/resvg-js-win32-x64-msvc@2.6.2': + resolution: {integrity: sha512-ZXtYhtUr5SSaBrUDq7DiyjOFJqBVL/dOBN7N/qmi/pO0IgiWW/f/ue3nbvu9joWE5aAKDoIzy/CxsY0suwGosQ==} + engines: {node: '>= 10'} + cpu: [x64] + os: [win32] + + '@resvg/resvg-js@2.6.2': + resolution: {integrity: sha512-xBaJish5OeGmniDj9cW5PRa/PtmuVU3ziqrbr5xJj901ZDN4TosrVaNZpEiLZAxdfnhAe7uQ7QFWfjPe9d9K2Q==} + engines: {node: '>= 10'} + '@rolldown/pluginutils@1.0.0-beta.27': resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==} @@ -2507,6 +2629,57 @@ snapshots: dependencies: pako: 1.0.11 + '@resvg/resvg-js-android-arm-eabi@2.6.2': + optional: true + + '@resvg/resvg-js-android-arm64@2.6.2': + optional: true + + '@resvg/resvg-js-darwin-arm64@2.6.2': + optional: true + + '@resvg/resvg-js-darwin-x64@2.6.2': + optional: true + + '@resvg/resvg-js-linux-arm-gnueabihf@2.6.2': + optional: true + + '@resvg/resvg-js-linux-arm64-gnu@2.6.2': + optional: true + + '@resvg/resvg-js-linux-arm64-musl@2.6.2': + optional: true + + '@resvg/resvg-js-linux-x64-gnu@2.6.2': + optional: true + + '@resvg/resvg-js-linux-x64-musl@2.6.2': + optional: true + + '@resvg/resvg-js-win32-arm64-msvc@2.6.2': + optional: true + + '@resvg/resvg-js-win32-ia32-msvc@2.6.2': + optional: true + + '@resvg/resvg-js-win32-x64-msvc@2.6.2': + optional: true + + '@resvg/resvg-js@2.6.2': + optionalDependencies: + '@resvg/resvg-js-android-arm-eabi': 2.6.2 + '@resvg/resvg-js-android-arm64': 2.6.2 + '@resvg/resvg-js-darwin-arm64': 2.6.2 + '@resvg/resvg-js-darwin-x64': 2.6.2 + '@resvg/resvg-js-linux-arm-gnueabihf': 2.6.2 + '@resvg/resvg-js-linux-arm64-gnu': 2.6.2 + '@resvg/resvg-js-linux-arm64-musl': 2.6.2 + '@resvg/resvg-js-linux-x64-gnu': 2.6.2 + '@resvg/resvg-js-linux-x64-musl': 2.6.2 + '@resvg/resvg-js-win32-arm64-msvc': 2.6.2 + '@resvg/resvg-js-win32-ia32-msvc': 2.6.2 + '@resvg/resvg-js-win32-x64-msvc': 2.6.2 + '@rolldown/pluginutils@1.0.0-beta.27': {} '@rollup/rollup-android-arm-eabi@4.60.4':