feat(pdf): R4.6 app export on the core's session: export.ts drives ExportSession (rasters one by one, warnings in the engine's order, abort on unmount), labels moved to the app, EditorRoute downloads the Blob of the parts; suites read the file's content streams (pdfRead helper), app-path bytes = R4 digests, hex strings upper-case as pdf-lib

This commit is contained in:
bchanot committed 2026-10-19 01:26:13 +02:00
1 parent 9e688b6801
commit d492bf7112
29 files changed
+507 -131

No files matched your search

@@ -62,7 +62,8 @@ async function exportedAttachment(
const { pdf } = await exportReportToPdf(golden.reports[name], sheet, {
locale: 'fr',
})
return new TextDecoder().decode(await readAttachmentBytes(pdf))
const bytes = new Uint8Array(await pdf.arrayBuffer())
return new TextDecoder().decode(await readAttachmentBytes(bytes))
}
describe.each(GOLDEN_REPORTS)('archive envelope of %s', (name) => {
+2 -3
View File
@@ -55,9 +55,8 @@ describe('the 612 legacy leaves in the application', () => {
})
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 { pdf } = await exportReportToPdf(report, sheet, { locale: 'fr' })
const bytes = new Uint8Array(await pdf.arrayBuffer())
const { read: back } = await importReportFromPdf(bytes, sheet)
expect(back.migrated).toBe(false)
expect(back.origin).toBe('envelope_v1')
+2 -1
View File
@@ -179,8 +179,9 @@ describe('archives exported from core-built reports', () => {
async (name) => {
const { report } = importAttachment(fixture(name), sheet).read
const { pdf } = await exportReportToPdf(report, sheet, { locale: 'fr' })
const bytes = new Uint8Array(await pdf.arrayBuffer())
const data: unknown = JSON.parse(
new TextDecoder().decode(await readAttachmentBytes(pdf)),
new TextDecoder().decode(await readAttachmentBytes(bytes)),
)
expect(ReportArchiveEnvelopeSchema.safeParse(data).success).toBe(true)
const outcome = readArchiveDocument(data, await bundledMigrationMap())
+12 -12
View File
@@ -37,12 +37,12 @@ import {
FIXTURES_DIR,
ONE_PX_PNG,
readLinks,
recordDrawing,
snapshotViews,
type ImageEntry,
type LinkEntry,
type TextEntry,
} from '../helpers/goldens'
import { bytesOf, readDrawing } from '../helpers/pdfRead'
// Same fixed raster for every view and logo: images then depend on the
// branding and the layout only.
@@ -84,18 +84,18 @@ interface Facts {
links: LinkEntry[]
}
/** Runs an export under the drawing recorder and reads the links back. */
async function recorded<T extends { pdf: Uint8Array }>(
/**
* Runs an export and reads its facts back from the file (R4.6: the app export is the
* core's, the re-export the engine's; both files are read the same way).
*/
async function recorded<T extends { pdf: Uint8Array | Blob }>(
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()
}
): Promise<Omit<T, 'pdf'> & { pdf: Uint8Array } & Facts> {
const result = await run()
const pdf =
result.pdf instanceof Uint8Array ? result.pdf : await bytesOf(result.pdf)
const { texts, images } = await readDrawing(pdf)
return { ...result, pdf, texts, images, links: await readLinks(pdf) }
}
const facts = ({ texts, images, links }: Facts): Facts => ({
+51 -21
View File
@@ -1,12 +1,15 @@
/**
* 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.
* application export path: `exportReportToPdf` runs the core's session (R4.6)
* 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 read back from the file's content streams and
* asserted as frozen; `MAKE_GOLDEN=1` rewrites them, never without a user
* decision. At the fixed export time the file's bytes are the R4 digests the
* cargo suite froze (`goldens/r4/pdf.*.sha256`): the app path writes what the
* native core writes. 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'
@@ -29,7 +32,6 @@ import {
ONE_PX_PNG,
readGolden,
readLinks,
recordDrawing,
snapshotViews,
TWO_BY_ONE_PNG,
type ImageEntry,
@@ -38,6 +40,8 @@ import {
type TextEntry,
type ViewSnapshot,
} from '../helpers/goldens'
import { bytesOf, readDrawing } from '../helpers/pdfRead'
import { FIXED_EXPORTED_AT, R4_GOLDEN_DIR, sha256 } from '../helpers/r4-draw'
const raster = vi.hoisted(() => ({ png: new Uint8Array() }))
vi.mock('@/pdf/browserRasterizer', () => ({
@@ -61,8 +65,13 @@ beforeAll(async () => {
sheet = await loadTestSheet()
;({ reports, unresolvedOfV2Unresolved } = buildGoldenReports(sheet))
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(FIXED_EXPORTED_AT)
})
afterAll(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})
afterAll(() => vi.restoreAllMocks())
interface Exported {
bytes: Uint8Array
@@ -78,14 +87,29 @@ async function exportWith(
): 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 { pdf, warnings } = await exportReportToPdf(report, sheet, { locale })
expect(warnings).toEqual([])
const bytes = await bytesOf(pdf)
const { texts, images } = await readDrawing(bytes)
return { bytes, texts, images, links: await readLinks(bytes) }
}
/**
* The goldens were recorded in call order: every page's content, then the footers of
* every page (the engine drew them last). Read back from the file, the facts come page
* by page, each page's footer after its content: the golden in page order, stably, is
* the same sequence.
*/
function inPageOrder<T extends { page: number }>(name: string): T[] {
return [...readGolden<T[]>(name)].sort((a, b) => a.page - b.page)
}
/** The R4 digest of this run, frozen by the cargo suite from the native writer. */
function r4Digest(name: string, locale: Locale, mode: LogoMode): string {
return readFileSync(
resolve(R4_GOLDEN_DIR, `pdf.${name}.${locale}.${mode}.sha256`),
'utf8',
).trim()
}
const pagesOf = (entries: readonly { page: number }[]) =>
@@ -133,16 +157,22 @@ describe.each(REPORTS)('goldens of %s', (name) => {
// 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 () => {
it('text, images and links per locale; same pagination across locales; app-path bytes = native digest', 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)
const id = `${name}.${locale}.${mode}`
expect(out.texts, `text.${id}`).toEqual(inPageOrder(`text.${id}.json`))
expect(out.images, `images.${id}`).toEqual(
inPageOrder(`images.${id}.json`),
)
checkGolden(`links.${id}.json`, out.links)
expect(sha256(out.bytes), id).toBe(
r4Digest(name, locale, mode),
)
}
expect(pagesOf(en.images)).toEqual(pagesOf(fr.images))
expect(pagesOf(en.links)).toEqual(pagesOf(fr.links))
+23 -30
View File
@@ -1,30 +1,25 @@
/**
* 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.
* export path on the core's session with the bundled sheet (drawn strings
* from the document, read back from the file's content streams since R4.6,
* envelope attachment, roundtrip FR/EN) and the import of the frozen v2
* archive PDFs, migrated without silent loss.
*/
import {
describe,
it,
expect,
vi,
beforeAll,
beforeEach,
afterAll,
} from 'vitest'
import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib'
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
import { AFRelationship, PDFDocument } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import type { Observation, Report } from '@faunosteo/core-wasm/types'
import { composeHighlightedViewSvg, defaultPdfLabels } from '@faunosteo/pdf'
import { composeHighlightedViewSvg } from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { defaultPdfLabels } from '@/pdf/labels'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { formatDate } from '@/lib/dates'
import type { Locale } from '@/i18n/types'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport, sheetSnapshot } from '../helpers/sheet'
import { bytesOf, readDrawing } from '../helpers/pdfRead'
// The factory runs when the engine first loads the adapter: fixed 1×1 PNG.
vi.mock('@/pdf/browserRasterizer', async () => {
@@ -40,12 +35,19 @@ async function readBack(bytes: Uint8Array) {
return (await importReportFromPdf(bytes, sheet)).read
}
/** The static PDF strings now belong to the engine's label set. */
/** The static PDF strings belong to the app's label set. */
const { fr, en } = defaultPdfLabels
/** The bytes of an app export (its warnings are not under test here). */
/**
* The bytes of an app export (its warnings are not under test here); `drawn` holds the
* texts of its content streams, in draw order.
*/
async function exportPdf(report: Report, locale: Locale): Promise<Uint8Array> {
return (await exportReportToPdf(report, sheet, { locale })).pdf
const bytes = await bytesOf(
(await exportReportToPdf(report, sheet, { locale })).pdf,
)
drawn = (await readDrawing(bytes)).texts.map((t) => t.text)
return bytes
}
const HERE = dirname(fileURLToPath(import.meta.url))
@@ -60,15 +62,6 @@ beforeAll(async () => {
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterAll(() => vi.restoreAllMocks())
beforeEach(() => {
drawn = []
vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function (
this: PDFPage,
text: string,
) {
drawn.push(text)
} as never)
})
/** A full v3 observation: plain zone, bilateral both sides, spine with vertebrae, head zone, findings. */
function fullObservation(): Observation {
@@ -208,7 +201,7 @@ function fullReport() {
describe('PDF content on a two-observation report', () => {
it('prints the empty marker for a zoneless observation and keeps its findings', async () => {
await exportReportToPdf(fullReport(), sheet, { locale: 'fr' })
await exportPdf(fullReport(), 'fr')
expect(drawn).toContain(fr['pdf.empty'])
const prefix = fr['pdf.section.findings_prefix']!
const occurrences = drawn.filter(
@@ -231,14 +224,14 @@ describe('PDF content on a two-observation report', () => {
],
}
const report = minimalReport(sheet, { observations: [stale] })
await exportReportToPdf(report, sheet, { locale: 'fr' })
await exportPdf(report, 'fr')
expect(drawn).toContain('point-gone')
expect(drawn).toContain(`${fr['pdf.section.findings_prefix']}ZONE-GONE`)
expect(drawn).toContain('Snapshot FR')
})
it('draws the EN dictionary, annotation names and finding snapshots', async () => {
await exportReportToPdf(fullReport(), sheet, { locale: 'en' })
await exportPdf(fullReport(), 'en')
expect(drawn).toContain(en['pdf.section.zones'])
expect(drawn.some((l) => l.includes('Hip joint'))).toBe(true)
expect(drawn).toContain('Junction fixation')
@@ -282,7 +275,7 @@ describe('PDF content on a two-observation report', () => {
})
expect(fetchSpy).not.toHaveBeenCalled()
expect(warnings).toEqual([])
const out = await readBack(pdf)
const out = await readBack(await bytesOf(pdf))
const branding = out.archive!.branding
expect(branding.headerLogo?.kind).toBe('png')
expect(branding.footerLogo?.kind).toBe('png')
+18 -3
View File
@@ -16,11 +16,14 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import { AFRelationship, PageSizes, PDFDocument, StandardFonts } from 'pdf-lib'
import type { Branding, Practitioner, Report } from '@faunosteo/core-wasm/types'
import {
exportReportArchive,
readAttachedDocument,
readAttachmentBytes,
type ExportInput,
type Rasterizer,
} from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { loadBranding } from '@/pdf/branding'
import { defaultPdfLabels } from '@/pdf/labels'
import { importAttachment } from '@/pdf/import'
import type { SheetIndex } from '@/services/sheetIndex'
import type { Locale } from '@/i18n/types'
@@ -113,14 +116,26 @@ const fixedRaster =
async () =>
mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG
/** One export through `@/pdf/export`, drawn under the full recorder. */
/**
* One export through the TypeScript engine with the application's inputs (the snapshot
* the core builds, the bundled branding of the mode, the app's labels, the fixed export
* time), drawn under the full recorder. R4.6 moved `@/pdf/export` onto the core's
* session: the oracles stay those of the R3 build, so the engine is called directly, as
* the app export called it until then (same inputs, same order).
*/
async function exportRun(run: Run): Promise<Exported> {
raster.rasterize = run.rasterize
logoMode.current = run.mode
const recorder = recordFullDrawing()
try {
const { pdf, warnings } = await exportReportToPdf(run.report, sheet, {
const { pdf, warnings } = await exportReportArchive({
report: run.report as ExportInput['report'],
sheet: sheetSnapshot(sheet, run.report) as ExportInput['sheet'],
branding: await loadBranding(),
labels: defaultPdfLabels,
locale: run.locale,
rasterizer: run.rasterize,
exportedAt: new Date(),
})
expect(warnings).toEqual([])
expect(recorder.unexpectedCalls()).toEqual([])
@@ -27,7 +27,9 @@ 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])
const PDF_BYTES = new Blob([new Uint8Array([37, 80, 68, 70])], {
type: 'application/pdf',
})
let sheet: SheetIndex
const downloads: string[] = []
@@ -69,25 +71,32 @@ afterEach(() => {
URL.revokeObjectURL = realRevokeObjectURL
})
async function mountAndExport(label: string): Promise<void> {
render(
async function mountAndExport(label: string): Promise<() => void> {
const { unmount } = render(
<MemoryRouter initialEntries={['/editor']}>
<EditorRoute />
</MemoryRouter>,
)
const button = await screen.findByRole('button', { name: label })
await userEvent.setup().click(button)
return unmount
}
/** The options the route passes: the locale and the signal it aborts on unmount. */
const options = (locale: 'fr' | 'en') => ({
locale,
signal: expect.any(AbortSignal) as AbortSignal,
})
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]!
const [report, index, passed] = exportMock.mock.calls[0]!
expect(report).toBe(useReportStore.getState().report)
expect(index).toBe(sheet)
expect(options).toEqual({ locale: 'fr' })
expect(passed).toEqual(options('fr'))
})
it('passes the active locale (EN)', async () => {
@@ -95,7 +104,7 @@ describe('EditorRoute export', () => {
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' })
expect(exportMock.mock.calls[0]![2]).toEqual(options('en'))
})
it('downloads bilan-<animal>-<date>.pdf through a blob URL it revokes after a delay', async () => {
@@ -131,6 +140,28 @@ describe('EditorRoute export', () => {
)
})
it('aborts the export when the editor unmounts mid-way: no download, no alert', async () => {
let settle: (() => void) | null = null
exportMock.mockImplementation(
(_report, _index, opts) =>
new Promise((_, reject) => {
settle = () =>
reject(new DOMException('export aborted', 'AbortError'))
opts.signal?.addEventListener('abort', () => settle?.())
}),
)
const unmount = await mountAndExport(fr['editor.export']!)
await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1))
const signal = exportMock.mock.calls[0]![2].signal!
expect(signal.aborted).toBe(false)
unmount()
expect(signal.aborted).toBe(true)
await Promise.resolve()
await Promise.resolve()
expect(downloads).toHaveLength(0)
expect(window.alert).not.toHaveBeenCalled()
})
it('alerts editor.export_failed when the export rejects', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
exportMock.mockRejectedValue(new Error('render exploded'))