feat(app): export and import through @faunosteo/pdf — snapshot, archived branding and labels, browser rasterizer, imported archive kept in session, explicit rebase with messages; legacy PDF modules removed

This commit is contained in:
bchanot committed 2026-10-11 13:32:14 +02:00
1 parent 20dafc0b00
commit 9bd5173a9c
43 files changed
+1492 -1989

No files matched your search

+54 -28
View File
@@ -12,18 +12,32 @@ import {
PDFPage,
PDFString,
} from 'pdf-lib'
import type { Observation, Report } from '@faunosteo/domain'
import type { SheetIndex } from '@/services/sheetIndex'
import { highlightedViewSvg } from '@/pdf/render/observationPage'
import type { Observation, Report, SheetSnapshot } from '@faunosteo/domain'
import { composeHighlightedViewSvg } from '@faunosteo/pdf'
/**
* Step 6 Phase 0 freeze: what the current PDF pipeline draws, recorded as
* JSON goldens (docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md §17). The
* recorder spies on pdf-lib, the link reader parses the saved bytes, the
* view snapshot parses the highlighted SVG. Numbers are rounded to 2
* decimals; nothing ordered by drawing order is sorted.
* 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')
@@ -174,8 +188,7 @@ const LOGO_FILES: Readonly<Record<string, string>> = {
'/Paws_in_harmony.svg': 'Paws_in_harmony.svg',
}
function serveLogo(input: RequestInfo | URL): Response {
const path = new URL(String(input), 'http://localhost').pathname
function serveLogo(path: string): Response {
const relative = LOGO_FILES[path]
const file = relative ? resolve(PUBLIC_DIR, relative) : null
if (!file || !existsSync(file))
@@ -183,18 +196,27 @@ function serveLogo(input: RequestInfo | URL): Response {
return new Response(new Uint8Array(readFileSync(file)), { status: 200 })
}
/** Stubs fetch for one logo mode; returns the restore function. */
export function installLogoFetch(mode: LogoMode): () => void {
/** Stubs fetch with a path → Response handler; returns the restore function. */
export function installFetch(respond: (path: string) => Response): () => void {
const real = globalThis.fetch
globalThis.fetch = (async (input: RequestInfo | URL) =>
mode === 'logos'
? serveLogo(input)
: new Response('not found', { status: 404 })) as typeof fetch
respond(
new URL(String(input), 'http://localhost').pathname,
)) as typeof fetch
return () => {
globalThis.fetch = real
}
}
/** Stubs fetch for one logo mode; returns the restore function. */
export function installLogoFetch(mode: LogoMode): () => void {
return installFetch((path) =>
mode === 'logos'
? serveLogo(path)
: new Response('not found', { status: 404 }),
)
}
const HIGHLIGHT_FILL = '#b85a3f'
function highlightedOf(el: Element): HighlightedElement {
@@ -236,11 +258,11 @@ function countDataAttributes(root: Element): number {
}
export function snapshotView(
sheet: SheetIndex,
sheet: SheetSnapshot,
observation: Observation,
viewId: string,
): ViewSnapshot {
const svg = highlightedViewSvg(sheet, viewId, observation)
const svg = composeHighlightedViewSvg(sheet, viewId, observation)
const root = new DOMParser().parseFromString(
svg,
'image/svg+xml',
@@ -261,19 +283,18 @@ export function snapshotView(
/** The views an observation draws, in the pipeline's order: main first, then first appearance. */
export function viewIdsOf(
sheet: SheetIndex,
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) => sheet.view(id))
.sort(
(a, b) =>
Number(b === sheet.mainView.id) - Number(a === sheet.mainView.id),
)
.filter((id) => views.has(id))
.sort((a, b) => Number(b === main) - Number(a === main))
}
export function snapshotViews(
sheet: SheetIndex,
sheet: SheetSnapshot,
report: Report,
): ViewSnapshot[] {
return report.observations.flatMap((observation) =>
@@ -283,14 +304,19 @@ export function snapshotViews(
)
}
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 {
const path = resolve(GOLDEN_DIR, name)
if (MAKE_GOLDEN) {
mkdirSync(GOLDEN_DIR, { recursive: true })
writeFileSync(path, `${JSON.stringify(actual, null, 2)}\n`)
writeFileSync(
resolve(GOLDEN_DIR, name),
`${JSON.stringify(actual, null, 2)}\n`,
)
return
}
const golden: unknown = JSON.parse(readFileSync(path, 'utf8'))
expect(actual, name).toEqual(golden)
expect(actual, name).toEqual(readGolden(name))
}
+42
View File
@@ -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,
}
}
+12 -8
View File
@@ -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,13 @@ 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.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 +29,8 @@ 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}',
'vertebra.extend_to': '{max}',
}
+11 -10
View File
@@ -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
@@ -35,6 +31,9 @@ let findings: Finding[]
let unresolvedFindings: number
beforeAll(async () => {
// No logo served: the branding loader leaves every slot empty.
globalThis.fetch = (async () =>
new Response('not found', { status: 404 })) as typeof fetch
sheet = await loadTestSheet()
const leaves = legacyLeaves(loadLegacyBaseline())
const v2 = leavesAsV2Report(leaves)
@@ -60,10 +59,12 @@ describe('the 612 legacy leaves in the application', () => {
}
})
it('keeps every finding, resolved or not, through a v3 PDF export and import', async () => {
it('keeps every finding, resolved or not, through an archive PDF export and import', async () => {
const 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)
@@ -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()
})
})
@@ -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)
})
})
@@ -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)
})
})
+203
View File
@@ -0,0 +1,203 @@
/**
* 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 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,
installFetch,
installLogoFetch,
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) }
})
let sheet: SheetIndex
let demo: Report
let restoreFetch: () => void = () => undefined
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(() => {
restoreFetch()
restoreFetch = () => undefined
})
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, logos served from public/, under the recorder. */
async function appExport(
index: SheetIndex,
): Promise<Facts & { pdf: Uint8Array }> {
const restore = installLogoFetch('logos')
try {
return await recorded(async () => ({
pdf: await exportReportToPdf(demo, index, { locale: 'fr' }),
}))
} finally {
restore()
}
}
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 otherSvg =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect width="10" height="10"/></svg>'
const fetchSpy = vi.fn((path: string) =>
path.endsWith('.svg')
? new Response(otherSvg, { status: 200 })
: new Response(ONE_PX_PNG, { status: 200 }),
)
restoreFetch = installFetch(fetchSpy)
const current = await loadBranding()
expect(current.headerLogo).not.toBeNull()
expect(current).not.toEqual(archive.branding)
fetchSpy.mockClear()
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)
})
+41 -30
View File
@@ -1,15 +1,18 @@
/**
* Step 6 Phase 0 freeze (STEP6_PDF_ARCHIVE_ANALYSIS.md §17): the current PDF
* pipeline recorded as goldens, per report × locale × logo mode. Generated
* once with `MAKE_GOLDEN=1`; without the flag the same file asserts them.
* Never regenerate without a user decision: the Step 6 engine must
* reproduce these files.
* 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 branding fetched from `public/` 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, writeFileSync } from 'node:fs'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
buildSheetSnapshot,
readReportDocument,
ReportSchema,
type Report,
@@ -28,33 +31,22 @@ import {
checkGolden,
FIXTURES_DIR,
installLogoFetch,
MAKE_GOLDEN,
ONE_PX_PNG,
readGolden,
readLinks,
recordDrawing,
snapshotViews,
TWO_BY_ONE_PNG,
type ImageEntry,
type LinkEntry,
type LogoMode,
type TextEntry,
type ViewSnapshot,
} from '../helpers/goldens'
/** 1×1 PNG (nologos: the legacy stub) and 2×1 PNG (logos: deterministic partner logo width). */
const ONE_PX_PNG = Uint8Array.from(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
'base64',
),
)
const TWO_BY_ONE_PNG = Uint8Array.from(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7QOjdAAAAD0lEQVR4nGPYEWX///9/AA0PBE/1T7nxAAAAAElFTkSuQmCC',
'base64',
),
)
const raster = vi.hoisted(() => ({ png: new Uint8Array() }))
vi.mock('@/pdf/render/svgToPng', () => ({
rasterizeSvg: vi.fn(async () => raster.png),
vi.mock('@/pdf/browserRasterizer', () => ({
browserRasterizer: vi.fn(async () => raster.png),
}))
const REPORTS = ['v2full', 'demo', 'v2unresolved'] as const
@@ -184,20 +176,39 @@ describe.each(REPORTS)('goldens of %s', (name) => {
}, 30_000)
})
it('highlighted views', () => {
checkGolden(`views.${name}.json`, snapshotViews(sheet, reports[name]))
// 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 without logos and imports back unchanged', async () => {
if (MAKE_GOLDEN) {
const { bytes } = await exportWith(reports.demo, 'nologos', 'fr')
writeFileSync(BARE_PDF, bytes)
}
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)
})
})
+47
View File
@@ -0,0 +1,47 @@
/**
* 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()
})
async function pdfWithoutAttachment(keywords?: string[]): Promise<Uint8Array> {
const doc = await PDFDocument.create()
doc.addPage()
if (keywords) doc.setKeywords(keywords)
return doc.save()
}
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')
})
})
+34 -25
View File
@@ -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,22 @@ 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 } 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 { 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
const HERE = dirname(fileURLToPath(import.meta.url))
const fixture = (name: string) =>
@@ -145,24 +142,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 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')
})
@@ -252,12 +259,13 @@ describe('PDF content on a two-observation report', () => {
expect(header).toBeGreaterThanOrEqual(pages)
})
it('sets the PDF metadata', async () => {
it('sets the PDF metadata and the archive keyword', async () => {
const bytes = await exportReportToPdf(fullReport(), sheet, { locale: '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 () => {
@@ -269,7 +277,7 @@ describe('PDF content on a two-observation report', () => {
).toBe(true)
})
it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, "Faunosteo state v3"', async () => {
it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, "Faunosteo report archive v1"', async () => {
const bytes = await exportReportToPdf(fullReport(), sheet, { locale: 'fr' })
const doc = await PDFDocument.load(bytes)
const objects = [...doc.context.enumerateIndirectObjects()].map(([, o]) =>
@@ -282,7 +290,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')
})
@@ -365,6 +373,7 @@ describe('import of the frozen v2 archive PDFs', () => {
)
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 () => {
-80
View File
@@ -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)
})
})
@@ -0,0 +1,241 @@
/**
* T15 (STEP6 §7, §16): the home route on Step 6 archives, with
* `importReportFromPdf` mocked. Same sheet: archive kept in the store and
* mirrored, archive_ok alert. Other sheet: the report is rebased on the
* loaded sheet (unresolved flags, labels from the archived snapshot, sheet
* ref updated) and the alert says so with the count. Snapshot rejected: 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)
const alertText = () => alertMock().mock.calls[0]![0] as string
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(alertText()).toBe(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(alertText()).toBe(
[
fr['home.import.archive_ok'],
fr['home.import.rebased']!.replace('{count}', '2'),
].join('\n\n'),
)
})
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(alertText()).toBe(
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()
})
})
@@ -21,6 +21,7 @@ import {
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 } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
@@ -42,7 +43,11 @@ beforeAll(async () => {
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
useReportStore.setState({ report: null, activeObservationIndex: 0 })
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
vi.stubGlobal('alert', vi.fn())
importMock.mockReset()
})
@@ -51,14 +56,16 @@ afterEach(() => {
vi.unstubAllGlobals()
})
/** The outcome shape importReportFromPdf resolves with. */
/** 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,
+40 -7
View File
@@ -1,14 +1,19 @@
/**
* 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 +23,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 +37,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 () => {
@@ -165,6 +169,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) },
+159 -14
View File
@@ -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()
})
})