Files
faunosteo/apps/app/tests/unit/pdf.export.app.test.ts
T

231 lines
7.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* T2 and user scenario 3 (STEP6 §7): the archive the app exports is
* self-sufficient. Once exported, the catalog may change its labels and
* geometry and the deployment may ship other logos: a re-export from the
* envelope alone reproduces the first export, not the current resources.
*/
import {
describe,
it,
expect,
vi,
beforeAll,
afterAll,
afterEach,
} from 'vitest'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import type {
Branding,
LocalizedText,
Report,
} from '@faunosteo/core-wasm/types'
import { exportFromEnvelope } from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { importAttachment, importReportFromPdf } from '@/pdf/import'
import { browserRasterizer } from '@/pdf/browserRasterizer'
import { loadBranding } from '@/pdf/branding'
import type { BundledSheetData } from '@/sheets/provider'
import type { SheetIndex } from '@/services/sheetIndex'
import {
bundledSheet,
loadTestSheet,
sheetFromBundle,
sheetSnapshot,
} from '../helpers/sheet'
import {
FIXTURES_DIR,
ONE_PX_PNG,
readLinks,
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.
vi.mock('@/pdf/browserRasterizer', async () => {
const { TWO_BY_ONE_PNG } = await import('../helpers/goldens')
return { browserRasterizer: vi.fn(async () => TWO_BY_ONE_PNG) }
})
// The bundled branding, unless a scenario swaps the deployment's logos.
const branding = vi.hoisted(() => ({ current: null as Branding | null }))
vi.mock('@/pdf/branding', async (importOriginal) => {
const real = await importOriginal<typeof import('@/pdf/branding')>()
return {
loadBranding: vi.fn(async () => branding.current ?? real.loadBranding()),
}
})
let sheet: SheetIndex
let demo: Report
beforeAll(async () => {
sheet = await loadTestSheet()
demo = importAttachment(
JSON.parse(
readFileSync(resolve(FIXTURES_DIR, 'report-v3.demo.json'), 'utf8'),
),
sheet,
).read.report
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterEach(() => {
branding.current = null
vi.unstubAllGlobals()
})
afterAll(() => vi.restoreAllMocks())
interface Facts {
texts: TextEntry[]
images: ImageEntry[]
links: LinkEntry[]
}
/**
* Runs an export 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<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 => ({
texts,
images,
links,
})
/** The app export path, bundled logos, under the recorder. */
function appExport(index: SheetIndex): Promise<Facts & { pdf: Uint8Array }> {
return recorded(() => exportReportToPdf(demo, index, { locale: 'fr' }))
}
/** The envelope the app reads back from its own export, as the engine takes it. */
type EngineEnvelope = Parameters<typeof exportFromEnvelope>[0]
async function archiveOf(pdf: Uint8Array): Promise<EngineEnvelope> {
const { read: outcome } = await importReportFromPdf(pdf, sheet)
expect(outcome.origin).toBe('envelope_v1')
return outcome.archive! as EngineEnvelope
}
const REEXPORT = {
locale: 'fr' as const,
rasterizer: browserRasterizer,
exportedAt: new Date('2027-01-01T00:00:00.000Z'),
}
/** A category or node of the bundled payload (authoring form: leaves have no children). */
interface PayloadNode {
name: LocalizedText
children?: PayloadNode[]
}
interface PayloadDocument {
annotations: {
id: string
name: LocalizedText | null
geometry: { type: string; cx?: number } | null
}[]
finding_zones: { name: LocalizedText; categories: PayloadNode[] }[]
}
function renameNodes(nodes: PayloadNode[]): void {
for (const node of nodes) {
node.name = {
fr: `${node.name.fr} (révisé)`,
en: `${node.name.en} (revised)`,
}
renameNodes(node.children ?? [])
}
}
/** The catalog after a revision: every label changed, the hip marker moved. */
function revisedSheet(source: BundledSheetData): BundledSheetData {
const next = structuredClone(source)
const document = next.document as PayloadDocument
for (const a of document.annotations) {
if (a.name) {
a.name = { fr: `${a.name.fr} (révisé)`, en: `${a.name.en} (revised)` }
}
if (a.id === 'hip' && a.geometry?.type === 'circle') a.geometry.cx! += 100
}
for (const zone of document.finding_zones) {
zone.name = {
fr: `${zone.name.fr} (révisé)`,
en: `${zone.name.en} (revised)`,
}
renameNodes(zone.categories)
}
return next
}
describe('the archive survives its resources', () => {
it('T2 catalog changed: the envelope re-exports the archived sheet, not the revised one', async () => {
const first = await appExport(sheet)
const archive = await archiveOf(first.pdf)
// The revision is visible through the app path (labels and geometry)...
const revised = sheetFromBundle(revisedSheet(await bundledSheet()))
const onRevised = await appExport(revised)
expect(onRevised.texts).not.toEqual(first.texts)
const revisedViews = snapshotViews(sheetSnapshot(revised, demo), demo)
const archivedViews = snapshotViews(
archive.sheetSnapshot as Parameters<typeof snapshotViews>[0],
demo,
)
expect(revisedViews).not.toEqual(archivedViews)
// ...and absent from a re-export of the envelope alone.
const again = await recorded(() => exportFromEnvelope(archive, REEXPORT))
expect(again.warnings).toEqual([])
expect(facts(again)).toEqual(facts(first))
expect(
snapshotViews(again.envelope.sheetSnapshot, again.envelope.report),
).toEqual(archivedViews)
}, 60_000)
it('scenario 3 branding changed: the envelope re-exports the archived branding and never fetches', async () => {
const first = await appExport(sheet)
const archive = await archiveOf(first.pdf)
// The deployment now ships other logos: a 1×1 PNG everywhere, another partner SVG.
const onePx = {
kind: 'png' as const,
base64: Buffer.from(ONE_PX_PNG).toString('base64'),
}
const otherSvg =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect width="10" height="10"/></svg>'
branding.current = {
...archive.branding,
headerLogo: onePx,
footerLogo: onePx,
poweredBy: { ...archive.branding.poweredBy!, logo: onePx },
partner: {
...archive.branding.partner!,
logo: { kind: 'svg', svg: otherSvg },
},
}
const current = await loadBranding()
expect(current.headerLogo).not.toBeNull()
expect(current).not.toEqual(archive.branding)
const fetchSpy = vi.fn()
vi.stubGlobal('fetch', fetchSpy)
const again = await recorded(() => exportFromEnvelope(archive, REEXPORT))
expect(fetchSpy).not.toHaveBeenCalled()
expect(again.warnings).toEqual([])
expect(facts(again)).toEqual(facts(first))
expect(again.envelope.branding).toEqual(archive.branding)
}, 60_000)
})