Files
faunosteo/apps/app/tests/unit/pdf.goldens.test.ts
T
bchanot 74fcb37564 feat(app): R2 switch — the application runs its domain rules in the Rust core
Consumers now fed by the core (crates/core through @faunosteo/core-wasm):
- the sheet: the bundled payload is parsed and indexed by the core
  (SheetHandle, SheetIndexData); SheetIndex reads precomputed tables only;
- the store: new report, add / remove / move observation, draft restore
  (v2 migration + rebase) through the core, actions answering { ok };
- the editor click chain (zone.click), laterality and vertebra pickers
  (zone.add_sides, vertebra.initial / sync / select), the findings picker
  (finding.toggle by clicked leaf position), zone removal;
- the import: engine byte scan (TypeScript until R4), then the core's
  layered reading and rebase in one call; the export: the core builds the
  sheet snapshot, the frozen TypeScript engine writes the PDF (R4).
Lazy core: Home and the new-report form read the sheet availability from
the bundle and load the module on import / submit only; the auth shell
never references it. Degraded states (core_unavailable, invalid_sheet)
show the validated notice with a retry and never redirect or touch the
draft; an unreadable draft or archive is set aside under
osteo:quarantine:* (only content kinds; a failed write keeps it in place
and the editor stays), a rebase that flags items keeps the raw pre-rebase
draft. Four strings, wording validated by the owner.
Deleted: services/zoneInteraction.ts and its suite (13 cases ported to
cargo), the TypeScript Finding builder and vertebra selection rules of the
pickers, store rules, persistence parsing, hydrateReport. ESLint forbids
@faunosteo/domain in apps/app/src; the report:compare CLI keeps the frozen
domain until R4 (scripts/compare/sheet.ts). App suite 313/313 on the real
core (24 new tests: quarantine, degraded editor, core failures, N-1
reader); step6 goldens and the frozen envelopes unchanged.
2026-10-14 00:41:34 +02:00

188 lines
7.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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 type { Report } from '@faunosteo/core-wasm/types'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf } from '@/pdf/import'
import type { SheetIndex } from '@/services/sheetIndex'
import type { Locale } from '@/i18n/types'
import { loadTestSheet, sheetSnapshot } from '../helpers/sheet'
import {
buildGoldenReports,
GOLDEN_REPORTS,
type GoldenReportName,
} from '../helpers/goldenReports'
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 = GOLDEN_REPORTS
const MODES: readonly LogoMode[] = ['nologos', 'logos']
const BARE_PDF = resolve(FIXTURES_DIR, 'report-v3.bare.pdf')
let sheet: SheetIndex
let reports: Record<GoldenReportName, Report>
let unresolvedOfV2Unresolved = 0
beforeAll(async () => {
sheet = await loadTestSheet()
;({ reports, unresolvedOfV2Unresolved } = buildGoldenReports(sheet))
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 = sheetSnapshot(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 { read: outcome } = await importReportFromPdf(bytes, sheet)
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)
})
})