Files
faunosteo/packages/core-wasm/tests/pdf-export.test.ts
T
bchanot 50c8fe0b33 feat(domain): R4.5e wasm proof export, resources per page, N-1 and TS-engine read-back, cost comparison
export_pdf_for_test on the proofs build (ExportInput JSON + base64 rasters): the 14 O2
runs give the native digests through wasm; the frozen O11 scanner reads every R4 PDF and
the N-1 Zod readers accept its envelope; a stripped R4 PDF answers attachment_stripped;
the TypeScript engine reads the R4 PDFs back to the R3 outcome; E2 size ≤ R3 + 5 %. Page
resources list the images the page draws (listing every embed cost 9 MB on CAP). Node,
stub rasters, TS → Rust: demo 198 → 36 ms, L 772 → 57 ms, CAP 5.7 s → 0.22 s; files
236 KB, 386 KB, 1.6 MB against 243 KB, 463 KB, 2.2 MB. Module with the writer linked
(proofs build): 531.6 KB gzip; shipped unchanged at 426 KB until R4.6 links it.
2026-10-18 23:21:05 +02:00

224 lines
7.2 KiB
TypeScript

/**
* R4.5: the Rust writer through the module (proofs build, `export_pdf_for_test`): the wasm
* output is byte-identical to the native one (the digests `goldens/r4/pdf.*.sha256` the
* cargo suite froze), the frozen N-1 scanner (O11) reads every R4 PDF and the N-1 Zod
* readers accept its envelope (plan §B.2.2: what the R3 build and release 0.2.0 read), and
* an R4 PDF with its embedded file removed answers `attachment_stripped` through O11.
* The inputs are the envelopes of the R3 PDFs (read by O11 here), the rasters the stubs of
* the goldens, the real PNGs for the real-raster run.
*/
import { createHash } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { loadProofModule } from '../src/node'
import { readArchiveDocument, ReportArchiveEnvelopeSchema } from './n-1'
import { ReportMigrationMapSchema } from './n-1/domain'
import { ArchiveReadError } from './n-1/scanner/errors'
import { readAttachedDocument } from './n-1/scanner/attachment/read'
const ROOT = fileURLToPath(new URL('../../../', import.meta.url))
const FIXTURES = join(ROOT, 'apps/app/tests/fixtures')
const sha256 = (data: Uint8Array) =>
createHash('sha256').update(data).digest('hex')
const ONE_PX_PNG =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='
const TWO_BY_ONE_PNG =
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7QOjdAAAAD0lEQVR4nGPYEWX///9/AA0PBE/1T7nxAAAAAElFTkSuQmCC'
interface Run {
name: string
r3: string
report?: string
rasters: (envelope: Envelope) => string
}
interface Envelope {
report: {
observations: Array<{ id: string; zones: Array<{ viewId: string }> }>
}
sheetSnapshot: unknown
branding: unknown
labels: unknown
locale: string
exportedAt: string
}
/** The stub rasters of the goldens: every slot and every (observation, view). */
function stubRasters(png: string): (envelope: Envelope) => string {
return (envelope) => {
const views = new Map<
string,
{ observationId: string; viewId: string; png: string }
>()
for (const observation of envelope.report.observations) {
for (const zone of observation.zones) {
const key = `${observation.id}\u0000${zone.viewId}`
if (!views.has(key))
views.set(key, {
observationId: observation.id,
viewId: zone.viewId,
png,
})
}
}
return JSON.stringify({
headerLogo: png,
footerLogo: png,
poweredBy: png,
partner: png,
views: [...views.values()],
})
}
}
function realRasters(envelope: Envelope): string {
const manifest = JSON.parse(
readFileSync(join(FIXTURES, 'pdf/r3/real/manifest.json'), 'utf8'),
) as {
calls: Array<{
png: string
subject: { kind: string; observationId?: string; viewId?: string }
}>
}
const spec = JSON.parse(stubRasters(TWO_BY_ONE_PNG)(envelope)) as Record<
string,
unknown
> & {
views: Array<{ observationId: string; viewId: string; png: string }>
}
for (const call of manifest.calls) {
const png = readFileSync(join(FIXTURES, 'pdf/r3/real', call.png)).toString(
'base64',
)
if (call.subject.kind === 'logo') spec['partner'] = png
else
spec.views = spec.views.map((v) =>
v.observationId === call.subject.observationId &&
v.viewId === call.subject.viewId
? { ...v, png }
: v,
)
}
return JSON.stringify(spec)
}
const RUNS: Run[] = []
for (const report of ['demo', 'v2full', 'v2unresolved']) {
for (const locale of ['fr', 'en']) {
for (const mode of ['nologos', 'logos']) {
RUNS.push({
name: `${report}.${locale}.${mode}`,
r3: `pdf/r3/${report}.${locale}.${mode}.pdf`,
rasters: stubRasters(mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG),
})
}
}
}
RUNS.push({
name: 'real.v2full-obs1.fr.logos',
r3: 'pdf/r3/real/v2full-obs1.fr.logos.pdf',
rasters: realRasters,
})
RUNS.push({
name: 'store-path.fr.nologos',
r3: 'pdf/r3/store-path.fr.nologos.pdf',
report: 'pdf/r3/store-path.report.json',
rasters: stubRasters(ONE_PX_PNG),
})
async function envelopeOf(pdf: Uint8Array): Promise<Envelope> {
return (await readAttachedDocument(pdf)) as Envelope
}
function inputOf(envelope: Envelope, reportOverride?: string): string {
const report = reportOverride
? JSON.parse(readFileSync(join(FIXTURES, reportOverride), 'utf8'))
: envelope.report
return JSON.stringify({
report,
sheetSnapshot: envelope.sheetSnapshot,
branding: envelope.branding,
labels: envelope.labels,
locale: envelope.locale,
exportedAt: envelope.exportedAt,
})
}
/** The R4 PDF with its embedded file hidden from the scanner (the stamp stays). */
function stripped(pdf: Uint8Array): Uint8Array {
const text = Buffer.from(pdf).toString('latin1')
const at = text.indexOf('/Type /EmbeddedFile')
expect(at).toBeGreaterThan(0)
const copy = Buffer.from(pdf)
copy.write('/Type /XmbeddedFile', at, 'latin1')
return new Uint8Array(copy)
}
describe('R4 writer through the module (proofs build)', () => {
it('gives the native bytes on every O2 run, which the N-1 readers accept', async () => {
const proofs = await loadProofModule()
const map = ReportMigrationMapSchema.parse(
JSON.parse(
readFileSync(
join(
ROOT,
'supabase/seed/anatomical-sheets/equine/draft/report-migration-map.json',
),
'utf8',
),
),
)
for (const run of RUNS) {
const r3 = new Uint8Array(readFileSync(join(FIXTURES, run.r3)))
const envelope = await envelopeOf(r3)
const pdf = proofs.export_pdf_for_test(
inputOf(envelope, run.report),
run.rasters(envelope),
)
const expected = readFileSync(
join(FIXTURES, `goldens/r4/pdf.${run.name}.sha256`),
'utf8',
).trim()
expect(sha256(pdf), run.name).toBe(expected)
// O11, the frozen scanner of the R3 build and 0.2.0, reads it; the N-1 Zod readers accept it.
const read = (await readAttachedDocument(pdf)) as Envelope
expect(read.locale, run.name).toBe(envelope.locale)
expect(
ReportArchiveEnvelopeSchema.safeParse(read).success,
run.name,
).toBe(true)
const outcome = readArchiveDocument(read, map)
expect(outcome.report.version, run.name).toBe(3)
if (!run.report) expect(read, run.name).toEqual(envelope)
const failure = await readAttachedDocument(stripped(pdf)).then(
() => null,
(e: unknown) => e,
)
expect(failure, run.name).toBeInstanceOf(ArchiveReadError)
expect((failure as ArchiveReadError).kind, run.name).toBe(
'attachment_stripped',
)
}
}, 60_000)
it('refuses the export errors as closed kinds, never a trap', async () => {
const proofs = await loadProofModule()
const r3 = new Uint8Array(
readFileSync(join(FIXTURES, 'pdf/r3/demo.fr.nologos.pdf')),
)
const envelope = await envelopeOf(r3)
const bad = {
...JSON.parse(inputOf(envelope)),
branding: { siteUrl: 'nope' },
}
expect(() =>
proofs.export_pdf_for_test(
JSON.stringify(bad),
stubRasters(ONE_PX_PNG)(envelope),
),
).toThrow(/branding_invalid: branding/)
})
})