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

+5 -4
View File
@@ -153,10 +153,11 @@ pnpm format # Prettier write
```
faunosteo/
├─ apps/app/ ← @faunosteo/app (everything below until packages/)
├─ public/ ← logos only (no anatomy asset: the sheet is bundled)
├─ public/ ← favicons, env.js, site header logo only (PDF logos live in src/assets/brand; no anatomy asset)
├─ vite/sheet-bundle.ts ← Vite plugin: `virtual:faunosteo-sheet` (SHEET_BUNDLE=draft|none)
├─ scripts/compare-reports.ts ← `pnpm report:compare`: archive PDF vs v3 reading (pure part in scripts/compare/report.ts)
├─ src/
│ ├─ assets/brand/ ← the four PDF branding logos, bundled by Vite (?inline / ?raw / ?url), never fetched
│ ├─ app/
│ │ ├─ App.tsx ← root router
│ │ ├─ routes/{Home,NewReport,Editor,NotFound}Route.tsx
@@ -187,7 +188,7 @@ faunosteo/
│ │ └─ brand/{Brand,AppHeader,Footer,LanguageSwitcher}.tsx
│ ├─ pdf/ ← app side of @faunosteo/pdf (engine in packages/pdf)
│ │ ├─ export.ts + import.ts ← exportReportToPdf (sheet snapshot + branding + browser rasterizer → engine), importReportFromPdf (ArchiveReadOutcome, ImportError kinds)
│ │ └─ branding.ts + browserRasterizer.ts ← public/ logos → Branding; Image/canvas Rasterizer adapter
│ │ └─ branding.ts + browserRasterizer.ts ← bundled src/assets/brand logos (?inline / ?raw) → Branding; Image/canvas Rasterizer adapter
│ ├─ lib/{dates,id,assert,supabase}.ts ← supabase.ts: getSupabaseClient() | null
│ ├─ styles/{index,tokens}.css ← Tailwind v4 CSS-first
│ └─ main.tsx
@@ -258,12 +259,12 @@ SVG interaction
PDF export (app side: apps/app/src/pdf, engine: packages/pdf)
→ exportReportToPdf(report, index, { locale })
→ buildSheetSnapshot(index.sheet, report) + loadBranding() (4 public/ files, each may fail alone) + defaultPdfLabels
→ buildSheetSnapshot(index.sheet, report) + loadBranding() (4 logos bundled at build time, no network) + defaultPdfLabels
→ exportReportArchive({ report, sheet, branding, labels, locale, rasterizer: browserRasterizer, exportedAt })
assertSnapshot (caps, integrity, sheet invariant) → fonts (WinAnsi StandardFonts, safeText guard)
→ per observation: composeHighlightedViewSvg (xmldom: sanitise allowlist → composeViewSvg highlight) → rasterizer → page
→ conclusion page, footer, envelope v1 attached as osteo-report.json, Keywords faunosteo-archive/1
→ { pdf, envelope, warnings } → browser download
→ { pdf, envelope, warnings } → { pdf, warnings } to EditorRoute → browser download, alert naming failed logo slots / views
→ exportFromEnvelope(envelope, …) re-exports an archive from its own snapshot, branding and labels (no sheet)
PDF import
+16 -2
View File
@@ -28,11 +28,17 @@ import {
} from '@/services/zoneInteraction'
import type { ViewStates } from '@/anatomy/drawing'
import { exportReportToPdf } from '@/pdf/export'
import type { ExportWarning } from '@faunosteo/pdf'
import { useT } from '@/i18n/useT'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
/** What the PDF lacks, named for the practitioner: logo slots and view ids. */
function missingItemsOf(warnings: readonly ExportWarning[]): string[] {
return warnings.map((w) => (w.kind === 'logo_failed' ? w.slot : w.viewId))
}
/** Editor on the reference sheet: wires the canvas, the pickers and the store. */
export default function EditorRoute() {
const navigate = useNavigate()
@@ -144,14 +150,22 @@ export default function EditorRoute() {
if (!report) return
setExporting(true)
try {
const bytes = await exportReportToPdf(report, index, { locale })
const blob = new Blob([bytes as BlobPart], { type: 'application/pdf' })
const { pdf, warnings } = await exportReportToPdf(report, index, {
locale,
})
const blob = new Blob([pdf as BlobPart], { type: 'application/pdf' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `bilan-${report.animal.name}-${report.date}.pdf`
a.click()
URL.revokeObjectURL(url)
const missing = missingItemsOf(warnings)
if (missing.length) {
window.alert(
t('editor.export_warnings').replace('{items}', missing.join(', ')),
)
}
} catch (err) {
console.error('PDF export failed', err)
window.alert(t('editor.export_failed'))
+2 -1
View File
@@ -1,5 +1,6 @@
import { useConfig } from '@/app/providers/ConfigProvider'
import { useT } from '@/i18n/useT'
import pawsInHarmonyUrl from '@/assets/brand/paws-in-harmony.svg?url'
export default function Footer() {
const cfg = useConfig()
@@ -37,7 +38,7 @@ export default function Footer() {
className="text-[var(--color-accent)] hover:text-[var(--color-accent-strong)] transition-colors font-medium"
>
<img
src="/Paws_in_harmony.svg"
src={pawsInHarmonyUrl}
alt="Paws in Harmony"
className="h-6 w-auto inline-block align-middle"
/>
+2
View File
@@ -66,6 +66,8 @@ export const en: Dict = {
'editor.export': 'Export as PDF',
'editor.exporting': 'Generating…',
'editor.export_failed': 'PDF generation failed. Retry or contact support.',
'editor.export_warnings':
'PDF exported with missing elements: {items}. Check the browser console.',
'editor.edit_infos': 'Edit info',
'editor.edit_dialog_title': 'Edit information',
'editor.disclaimer_title': 'Legal scope of animal osteopathy',
+2
View File
@@ -72,6 +72,8 @@ export const fr: Dict = {
'editor.exporting': 'Génération…',
'editor.export_failed':
'Échec de la génération du PDF. Réessayez ou contactez le support.',
'editor.export_warnings':
'PDF exporté avec des éléments manquants : {items}. Vérifiez la console du navigateur.',
'editor.edit_infos': 'Modifier les infos',
'editor.edit_dialog_title': 'Modifier les informations',
'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale",
+17 -54
View File
@@ -1,11 +1,14 @@
import type { Branding, ImageAsset } from '@faunosteo/domain'
import headerLogoDataUrl from '@/assets/brand/faunosteo-logo-horizontal-512.png?inline'
import footerLogoDataUrl from '@/assets/brand/faunosteo-horizontal-com-512.png?inline'
import poweredByLogoDataUrl from '@/assets/brand/zenquality-logo-fr.png?inline'
import partnerLogoSvg from '@/assets/brand/paws-in-harmony.svg?raw'
/**
* The visual identity the export embeds (STEP6 §14 "Branding in the app"):
* the four `public/` files fetched by their current URLs, each failure
* leaving its slot empty with a warning (the page then prints the credit's
* fallback text), plus the credit URLs. The result travels inside the
* archive, so a re-export never needs these files again.
* the four logo files bundled with the application (`src/assets/brand`), so
* an export needs no network and no deployed file, plus the credit URLs. The
* result travels inside the archive, so a re-export never needs them again.
*/
// shortcut: the site URL and the credit constants belong to the runtime
@@ -20,62 +23,22 @@ const PARTNER = {
fallbackText: '@paws.iin.harmony',
}
const HEADER_LOGO_URL = '/assets/faunosteo_logo_horizontal-512.png'
const FOOTER_LOGO_URL = '/assets/faunosteo-horizontal-com-512.png'
const POWERED_BY_LOGO_URL = '/brand/zenquality-logo-fr.png'
const PARTNER_LOGO_URL = '/Paws_in_harmony.svg'
const PNG_DATA_URL_PREFIX = 'data:image/png;base64,'
/** btoa takes a binary string; chunking keeps the argument list small. */
function bytesToBase64(bytes: Uint8Array): string {
const CHUNK = 0x8000
let binary = ''
for (let i = 0; i < bytes.length; i += CHUNK) {
binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK))
}
return btoa(binary)
}
async function fetchOk(url: string): Promise<Response> {
const resp = await fetch(url)
if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
return resp
}
async function pngAsset(url: string): Promise<ImageAsset> {
const bytes = new Uint8Array(await (await fetchOk(url)).arrayBuffer())
return { kind: 'png', base64: bytesToBase64(bytes) }
}
async function svgAsset(url: string): Promise<ImageAsset> {
return { kind: 'svg', svg: await (await fetchOk(url)).text() }
}
/** A slot fails alone: the export goes on without that logo. */
async function slot(
load: Promise<ImageAsset>,
url: string,
): Promise<ImageAsset | null> {
try {
return await load
} catch (err) {
console.warn(`Branding asset ${url} skipped:`, err)
return null
/** A `?inline` PNG import is a base64 data URL; the engine wants the base64 alone. */
function pngAsset(dataUrl: string): ImageAsset {
if (!dataUrl.startsWith(PNG_DATA_URL_PREFIX)) {
throw new Error('bundled logo is not a base64 PNG data URL')
}
return { kind: 'png', base64: dataUrl.slice(PNG_DATA_URL_PREFIX.length) }
}
export async function loadBranding(): Promise<Branding> {
const [headerLogo, footerLogo, poweredByLogo, partnerLogo] =
await Promise.all([
slot(pngAsset(HEADER_LOGO_URL), HEADER_LOGO_URL),
slot(pngAsset(FOOTER_LOGO_URL), FOOTER_LOGO_URL),
slot(pngAsset(POWERED_BY_LOGO_URL), POWERED_BY_LOGO_URL),
slot(svgAsset(PARTNER_LOGO_URL), PARTNER_LOGO_URL),
])
return {
siteUrl: SITE_URL,
headerLogo,
footerLogo,
poweredBy: { logo: poweredByLogo, ...POWERED_BY },
partner: { logo: partnerLogo, ...PARTNER },
headerLogo: pngAsset(headerLogoDataUrl),
footerLogo: pngAsset(footerLogoDataUrl),
poweredBy: { logo: pngAsset(poweredByLogoDataUrl), ...POWERED_BY },
partner: { logo: { kind: 'svg', svg: partnerLogoSvg }, ...PARTNER },
}
}
+15 -5
View File
@@ -1,5 +1,9 @@
import { buildSheetSnapshot, type Report } from '@faunosteo/domain'
import { defaultPdfLabels, exportReportArchive } from '@faunosteo/pdf'
import {
defaultPdfLabels,
exportReportArchive,
type ExportWarning,
} from '@faunosteo/pdf'
import type { Locale } from '@/i18n/types'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadBranding } from './branding'
@@ -9,17 +13,23 @@ export interface PdfExportOptions {
locale: Locale
}
export interface PdfExportResult {
pdf: Uint8Array
/** Non-fatal engine warnings: a logo or a view that failed to embed. */
warnings: ExportWarning[]
}
/**
* Exports the report as an archive PDF through the engine: the loaded sheet
* becomes the snapshot the pages are drawn from and the attachment carries,
* the branding is fetched once from `public/`, the browser rasterises the
* views. Non-fatal engine warnings (a logo or a view that failed) are logged.
* the branding comes from the bundled logos, the browser rasterises the
* views. Warnings are logged and returned for the caller to surface.
*/
export async function exportReportToPdf(
report: Report,
index: SheetIndex,
opts: PdfExportOptions,
): Promise<Uint8Array> {
): Promise<PdfExportResult> {
const result = await exportReportArchive({
report,
sheet: buildSheetSnapshot(index.sheet, report),
@@ -32,5 +42,5 @@ export async function exportReportToPdf(
for (const warning of result.warnings) {
console.warn('PDF export warning', warning)
}
return result.pdf
return { pdf: result.pdf, warnings: result.warnings }
}
+2 -2
View File
@@ -30,8 +30,8 @@ What the PDF pipeline produced right before the Step 6 refactor, recorded by
Reports: `v2full` (`report-v2.full.json` migrated), `demo` (`report-v3.demo.json`),
`v2unresolved` (legacy `sphenoid` and `ssb` leaves plus one `frontal` leaf, migrated;
zone-less, so its `images` and `views` goldens are empty). Logo modes: `nologos`
(fetch 404, 1×1 rasteriser) and `logos` (fetch serves the four `public/` logo files,
rasteriser stubbed to a 2×1 PNG).
(every branding slot empty, 1×1 rasteriser) and `logos` (the four logo files bundled
under `apps/app/src/assets/brand`, rasteriser stubbed to a 2×1 PNG).
Never regenerate these files without a user decision; the Step 6 engine must
reproduce them. Generation, once: `MAKE_GOLDEN=1 corepack pnpm vitest run
+18 -39
View File
@@ -1,4 +1,4 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { expect, vi } from 'vitest'
@@ -12,8 +12,14 @@ import {
PDFPage,
PDFString,
} from 'pdf-lib'
import type { Observation, Report, SheetSnapshot } from '@faunosteo/domain'
import type {
Branding,
Observation,
Report,
SheetSnapshot,
} from '@faunosteo/domain'
import { composeHighlightedViewSvg } from '@faunosteo/pdf'
import { nologosBranding } from './sheet'
/**
* Step 6 Phase 0 freeze: what the PDF pipeline drew before the engine,
@@ -41,7 +47,6 @@ export const TWO_BY_ONE_PNG = Uint8Array.from(
const HERE = dirname(fileURLToPath(import.meta.url))
export const FIXTURES_DIR = resolve(HERE, '../fixtures')
export const GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/step6')
const PUBLIC_DIR = resolve(HERE, '../../public')
/** `MAKE_GOLDEN=1` writes the goldens instead of asserting them. */
export const MAKE_GOLDEN = process.env.MAKE_GOLDEN === '1'
@@ -179,42 +184,16 @@ export async function readLinks(bytes: Uint8Array): Promise<LinkEntry[]> {
return out
}
const LOGO_FILES: Readonly<Record<string, string>> = {
'/assets/faunosteo_logo_horizontal-512.png':
'assets/faunosteo_logo_horizontal-512.png',
'/assets/faunosteo-horizontal-com-512.png':
'assets/faunosteo-horizontal-com-512.png',
'/brand/zenquality-logo-fr.png': 'brand/zenquality-logo-fr.png',
'/Paws_in_harmony.svg': 'Paws_in_harmony.svg',
}
function serveLogo(path: string): Response {
const relative = LOGO_FILES[path]
const file = relative ? resolve(PUBLIC_DIR, relative) : null
if (!file || !existsSync(file))
return new Response('not found', { status: 404 })
return new Response(new Uint8Array(readFileSync(file)), { status: 200 })
}
/** 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) =>
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 }),
)
/**
* The branding of one logo mode, for a test that mocks `@/pdf/branding`:
* `logos` is the real module (the bundled files), `nologos` every slot
* empty with the credits' fallback texts (the Phase 0 fetch 404).
*/
export async function brandingOf(mode: LogoMode): Promise<Branding> {
if (mode === 'nologos') return nologosBranding()
const real =
await vi.importActual<typeof import('@/pdf/branding')>('@/pdf/branding')
return real.loadBranding()
}
const HIGHLIGHT_FILL = '#b85a3f'
+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'))
+2
View File
@@ -84,6 +84,8 @@ rules as the catalog):
| `assets` | the SVG text of every asset a view reaches, with the catalog's content hash when known |
`branding` is the exact set of images, URLs and credit texts used at export;
the application builds it from logos bundled at build time
(`apps/app/src/assets/brand`), so the export makes no network request.
`labels` is the engine dictionary in both languages. A re-export of the
archive uses these three blocks and nothing from the current application, so
a new logo, a reworded heading or a curated sheet never changes how an old
+2
View File
@@ -27,6 +27,8 @@ export const LEGACY_BASELINE = resolve(
export const FIXTURES_DIR = resolve(REPO_ROOT, 'apps/app/tests/fixtures')
export const GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/step6')
export const PUBLIC_DIR = resolve(REPO_ROOT, 'apps/app/public')
/** The logo files the app bundles into its export branding. */
export const BRAND_ASSETS_DIR = resolve(REPO_ROOT, 'apps/app/src/assets/brand')
export function readJson<T = unknown>(path: string): T {
return JSON.parse(readFileSync(path, 'utf8')) as T
+11 -11
View File
@@ -19,7 +19,7 @@ import type {
SheetSnapshot,
} from '@faunosteo/domain'
import { composeHighlightedViewSvg, type Rasterizer } from '../../src'
import { GOLDEN_DIR, PUBLIC_DIR } from './draft'
import { BRAND_ASSETS_DIR, GOLDEN_DIR } from './draft'
/**
* Step 6 Phase 0 goldens, replayed on the engine: the same recorder on
@@ -60,8 +60,8 @@ const PARTNER = {
fallbackText: '@paws.iin.harmony',
}
function publicPng(relative: string): { kind: 'png'; base64: string } {
const bytes = readFileSync(resolve(PUBLIC_DIR, relative))
function brandPng(file: string): { kind: 'png'; base64: string } {
const bytes = readFileSync(resolve(BRAND_ASSETS_DIR, file))
return { kind: 'png', base64: Buffer.from(bytes).toString('base64') }
}
@@ -76,20 +76,20 @@ export function nologosBranding(): Branding {
}
}
/** The four real `public/` files (Phase 0 fetch stub). */
/** The four real logo files the app bundles (served by a fetch stub in Phase 0). */
export function logosBranding(): Branding {
return {
siteUrl: SITE_URL,
headerLogo: publicPng('assets/faunosteo_logo_horizontal-512.png'),
footerLogo: publicPng('assets/faunosteo-horizontal-com-512.png'),
poweredBy: {
logo: publicPng('brand/zenquality-logo-fr.png'),
...POWERED_BY,
},
headerLogo: brandPng('faunosteo-logo-horizontal-512.png'),
footerLogo: brandPng('faunosteo-horizontal-com-512.png'),
poweredBy: { logo: brandPng('zenquality-logo-fr.png'), ...POWERED_BY },
partner: {
logo: {
kind: 'svg',
svg: readFileSync(resolve(PUBLIC_DIR, 'Paws_in_harmony.svg'), 'utf8'),
svg: readFileSync(
resolve(BRAND_ASSETS_DIR, 'paws-in-harmony.svg'),
'utf8',
),
},
...PARTNER,
},
+3 -3
View File
@@ -33,7 +33,7 @@ import { addLinkAnnotation } from '../src/render/linkAnnotation'
import { parseSvg, serializeSvg } from '../src/svg/parse'
import { sanitizeSvgRoot } from '../src/svg/sanitize'
import { rasterSizeOf } from '../src/svg/view'
import { DRAFT_DIR, PUBLIC_DIR } from './helpers/draft'
import { BRAND_ASSETS_DIR, DRAFT_DIR, PUBLIC_DIR } from './helpers/draft'
import {
FIXED_EXPORTED_AT,
logosBranding,
@@ -391,10 +391,10 @@ describe('hostile SVG assets', () => {
expect(sizes[0]).toEqual({ widthPx: 1200, heightPx: 2400 })
})
it('horse.svg and Paws_in_harmony.svg pass with nothing removed and an identical serialisation', () => {
it('horse.svg and paws-in-harmony.svg pass with nothing removed and an identical serialisation', () => {
for (const file of [
resolve(DRAFT_DIR, 'assets/horse.svg'),
resolve(PUBLIC_DIR, 'Paws_in_harmony.svg'),
resolve(BRAND_ASSETS_DIR, 'paws-in-harmony.svg'),
]) {
const text = readFileSync(file, 'utf8')
const pristine = serializeSvg(parseSvg(text))