Files
faunosteo/apps/app/tests/unit/pdf.export.app.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

231 lines
7.1 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.
/**
* 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 type {
Branding,
LocalizedText,
Report,
} from '@faunosteo/core-wasm/types'
import { exportFromEnvelope } from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { importAttachment, importReportFromPdf } from '@/pdf/import'
import { browserRasterizer } from '@/pdf/browserRasterizer'
import { loadBranding } from '@/pdf/branding'
import type { BundledSheetData } from '@/sheets/provider'
import type { SheetIndex } from '@/services/sheetIndex'
import {
bundledSheet,
loadTestSheet,
sheetFromBundle,
sheetSnapshot,
} 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 = importAttachment(
JSON.parse(
readFileSync(resolve(FIXTURES_DIR, 'report-v3.demo.json'), 'utf8'),
),
sheet,
).read.report
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' }))
}
/** The envelope the app reads back from its own export, as the engine takes it. */
type EngineEnvelope = Parameters<typeof exportFromEnvelope>[0]
async function archiveOf(pdf: Uint8Array): Promise<EngineEnvelope> {
const { read: outcome } = await importReportFromPdf(pdf, sheet)
expect(outcome.origin).toBe('envelope_v1')
return outcome.archive! as EngineEnvelope
}
const REEXPORT = {
locale: 'fr' as const,
rasterizer: browserRasterizer,
exportedAt: new Date('2027-01-01T00:00:00.000Z'),
}
/** A category or node of the bundled payload (authoring form: leaves have no children). */
interface PayloadNode {
name: LocalizedText
children?: PayloadNode[]
}
interface PayloadDocument {
annotations: {
id: string
name: LocalizedText | null
geometry: { type: string; cx?: number } | null
}[]
finding_zones: { name: LocalizedText; categories: PayloadNode[] }[]
}
function renameNodes(nodes: PayloadNode[]): 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: BundledSheetData): BundledSheetData {
const next = structuredClone(source)
const document = next.document as PayloadDocument
for (const a of 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 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 = sheetFromBundle(revisedSheet(await bundledSheet()))
const onRevised = await appExport(revised)
expect(onRevised.texts).not.toEqual(first.texts)
const revisedViews = snapshotViews(sheetSnapshot(revised, demo), demo)
const archivedViews = snapshotViews(
archive.sheetSnapshot as Parameters<typeof snapshotViews>[0],
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)
})