fix(pdf): bundle the branding assets into the app (no fetch at export), export returns its warnings and the editor reports missing elements

This commit is contained in:
bchanot committed 2026-10-11 16:09:39 +02:00
1 parent 80e95ca61d
commit 293a6e0b36
22 files changed
+199 -185

No files matched your search

+3 -4
View File
@@ -31,9 +31,6 @@ 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,7 +57,9 @@ describe('the 612 legacy leaves in the application', () => {
})
it('keeps every finding, resolved or not, through an archive PDF export and import', async () => {
const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' })
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')
+30 -24
View File
@@ -19,6 +19,7 @@ import {
buildSheetIndex,
buildSheetSnapshot,
ReportSchema,
type Branding,
type FindingCategory,
type FindingNode,
type Report,
@@ -33,8 +34,6 @@ import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
import {
FIXTURES_DIR,
installFetch,
installLogoFetch,
ONE_PX_PNG,
readLinks,
recordDrawing,
@@ -50,10 +49,17 @@ 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
let restoreFetch: () => void = () => undefined
beforeAll(async () => {
sheet = await loadTestSheet()
@@ -65,8 +71,8 @@ beforeAll(async () => {
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterEach(() => {
restoreFetch()
restoreFetch = () => undefined
branding.current = null
vi.unstubAllGlobals()
})
afterAll(() => vi.restoreAllMocks())
@@ -96,18 +102,9 @@ const facts = ({ texts, images, links }: Facts): Facts => ({
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()
}
/** 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> {
@@ -181,18 +178,27 @@ describe('the archive survives its resources', () => {
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>'
const fetchSpy = vi.fn((path: string) =>
path.endsWith('.svg')
? new Response(otherSvg, { status: 200 })
: new Response(ONE_PX_PNG, { status: 200 }),
)
restoreFetch = installFetch(fetchSpy)
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)
fetchSpy.mockClear()
const fetchSpy = vi.fn()
vi.stubGlobal('fetch', fetchSpy)
const again = await recorded(() => exportFromEnvelope(archive, REEXPORT))
expect(fetchSpy).not.toHaveBeenCalled()
+10 -6
View File
@@ -1,8 +1,9 @@
/**
* 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,
* 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.
@@ -30,7 +31,6 @@ import {
import {
checkGolden,
FIXTURES_DIR,
installLogoFetch,
ONE_PX_PNG,
readGolden,
readLinks,
@@ -48,6 +48,11 @@ 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]
@@ -103,15 +108,14 @@ async function exportWith(
locale: Locale,
): Promise<Exported> {
raster.png = mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG
const restoreFetch = installLogoFetch(mode)
logoMode.current = mode
const recording = recordDrawing()
try {
const bytes = await exportReportToPdf(report, sheet, { locale })
const { pdf: bytes } = await exportReportToPdf(report, sheet, { locale })
const { texts, images } = recording
return { bytes, texts, images, links: await readLinks(bytes) }
} finally {
recording.stop()
restoreFetch()
}
}
+37 -25
View File
@@ -17,11 +17,16 @@ import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { buildSheetSnapshot, 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 { formatDate } from '@/lib/dates'
import type { Locale } from '@/i18n/types'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
@@ -34,29 +39,25 @@ vi.mock('@/pdf/browserRasterizer', async () => {
/** 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) =>
new Uint8Array(readFileSync(resolve(HERE, '../fixtures', name)))
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,
@@ -118,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,7 +146,7 @@ describe('export on a full v3 report (FR)', () => {
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')
@@ -242,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')
@@ -260,7 +261,7 @@ describe('PDF content on a two-observation report', () => {
})
it('sets the PDF metadata and the archive keyword', async () => {
const bytes = await exportReportToPdf(fullReport(), sheet, { locale: 'fr' })
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')
@@ -268,17 +269,28 @@ describe('PDF content on a two-observation report', () => {
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 report archive v1"', async () => {
const bytes = await exportReportToPdf(fullReport(), sheet, { locale: 'fr' })
const bytes = await exportPdf(fullReport(), 'fr')
const doc = await PDFDocument.load(bytes)
const objects = [...doc.context.enumerateIndirectObjects()].map(([, o]) =>
String(o),
@@ -368,7 +380,7 @@ 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)
@@ -440,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)
@@ -1,8 +1,8 @@
/**
* 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 and the failure alert. Phase 4 adapts
* only the mocked module path and the call-shape assertion.
* index, locale), the download name, the failure alert and the alert that
* names what the exported PDF lacks when the engine warned.
*/
import {
describe,
@@ -27,6 +27,7 @@ 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[] = []
@@ -74,7 +75,7 @@ async function mountAndExport(label: string): Promise<void> {
describe('EditorRoute export', () => {
it('calls exportReportToPdf with the store report, the loaded index and the FR locale', async () => {
exportMock.mockResolvedValue(new Uint8Array([37, 80, 68, 70]))
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]!
@@ -85,14 +86,14 @@ describe('EditorRoute export', () => {
it('passes the active locale (EN)', async () => {
useLocaleStore.setState({ locale: 'en' })
exportMock.mockResolvedValue(new Uint8Array([37, 80, 68, 70]))
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(new Uint8Array([37, 80, 68, 70]))
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')
@@ -103,6 +104,22 @@ describe('EditorRoute export', () => {
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'))