Files
faunosteo/apps/app/tests/helpers/r4-draw.ts
T

390 lines
11 KiB
TypeScript

import { createHash } from 'node:crypto'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { expect, vi } from 'vitest'
import {
PDFArray,
PDFDict,
PDFDocument,
PDFFont,
PDFHexString,
PDFImage,
PDFName,
PDFNumber,
PDFPage,
PDFString,
} from 'pdf-lib'
import {
FIXTURES_DIR,
round2,
type ImageEntry,
type LinkEntry,
type TextEntry,
} from './goldens'
/**
* R4.1 freeze, writer oracles (plan 2026-10-17 §B.5.1 O1 to O3): what the
* TypeScript writer draws, at full precision, for the Rust writer to
* reproduce. The recorder is the Step 6 one made complete: every drawText,
* drawImage, drawLine and drawRectangle call with every option passed, the
* images by embed order and PNG digest, the links read back from the saved
* bytes. `MAKE_R4_ORACLES=1` writes the files; otherwise they are asserted.
*/
export const MAKE_R4_ORACLES = process.env.MAKE_R4_ORACLES === '1'
export const R4_GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/r4')
export const R3_PDF_DIR = resolve(FIXTURES_DIR, 'pdf/r3')
export const STEP6_PDF_DIR = resolve(FIXTURES_DIR, 'pdf/step6')
/** The engine suites' export time (packages/pdf/tests/helpers/goldens.ts). */
export const FIXED_EXPORTED_AT = new Date('2026-10-11T12:00:00.000Z')
export type Json =
| null
| boolean
| number
| string
| Json[]
| { [key: string]: Json }
/** A type alias, not an interface: it must fit the `Json` index signature. */
export type ImageRef = {
embedIndex: number
pngSha256: string
}
export type DrawOpName = 'drawText' | 'drawImage' | 'drawLine' | 'drawRectangle'
export interface DrawOp {
/** Global call order across pages: footers are drawn after every page. */
seq: number
op: DrawOpName
text?: string
image?: ImageRef
options: Json
}
export interface FullLink {
page: number
rect: number[]
uri: string
}
export interface DrawLog {
pages: { index: number; ops: DrawOp[] }[]
/** Every embedPng call in order, drawn or not: each one is an XObject. */
embeds: ImageRef[]
links: FullLink[]
}
export const sha256 = (data: Uint8Array | string): string =>
createHash('sha256').update(data).digest('hex')
interface RecorderState {
ops: { page: number; op: DrawOp }[]
embeds: ImageRef[]
images: Map<PDFImage, ImageRef>
documents: Set<PDFDocument>
}
/** Non-finite numbers and -0 have no JSON form: tagged so none is lost. */
function numberOf(value: number): Json {
if (Number.isFinite(value) && !Object.is(value, -0)) return value
return { $number: Object.is(value, -0) ? '-0' : String(value) }
}
function imageRefOf(state: RecorderState, image: PDFImage): ImageRef {
const ref = state.images.get(image)
if (!ref) throw new Error('drawImage of an image embedPng did not return')
return ref
}
function objectOf(
value: object,
state: RecorderState,
path: Set<object>,
): Json {
if (path.has(value)) throw new Error('cyclic draw argument')
path.add(value)
const out: Json = Array.isArray(value)
? value.map((item) => serialise(item, state, path))
: Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, serialise(v, state, path)]),
)
path.delete(value)
return out
}
/** Generic: whatever a call passes is kept, keys in insertion order. */
function serialise(
value: unknown,
state: RecorderState,
path = new Set<object>(),
): Json {
if (value === undefined) return { $undefined: true }
if (value === null || typeof value === 'string') return value
if (typeof value === 'boolean') return value
if (typeof value === 'number') return numberOf(value)
if (value instanceof PDFFont) return value.name
if (value instanceof PDFImage) return imageRefOf(state, value)
if (typeof value === 'object') return objectOf(value, state, path)
throw new Error(`unexpected draw argument of type ${typeof value}`)
}
/** Pages are appended in order and never moved: the index at draw time is final. */
function pageIndex(page: PDFPage): number {
return page.doc.getPages().indexOf(page)
}
function record(
state: RecorderState,
page: PDFPage,
entry: Omit<DrawOp, 'seq'>,
): void {
state.documents.add(page.doc)
state.ops.push({
page: pageIndex(page),
op: { seq: state.ops.length, ...entry },
})
}
function pngBytes(png: string | Uint8Array | ArrayBuffer): Uint8Array {
if (png instanceof Uint8Array) return png
if (png instanceof ArrayBuffer) return new Uint8Array(png)
throw new Error('embedPng received a string: the engine passes bytes')
}
function spyEmbedPng(state: RecorderState) {
const original = PDFDocument.prototype.embedPng
return vi
.spyOn(PDFDocument.prototype, 'embedPng')
.mockImplementation(async function (this: PDFDocument, png) {
state.documents.add(this)
const ref = {
embedIndex: state.embeds.length,
pngSha256: sha256(pngBytes(png)),
}
state.embeds.push(ref)
const image = await original.call(this, png)
state.images.set(image, ref)
return image
})
}
function spyDrawText(state: RecorderState) {
const original = PDFPage.prototype.drawText
return vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function (
this: PDFPage,
text,
options,
) {
const opts = serialise(options, state)
record(state, this, { op: 'drawText', text, options: opts })
return original.call(this, text, options)
})
}
function spyDrawImage(state: RecorderState) {
const original = PDFPage.prototype.drawImage
return vi.spyOn(PDFPage.prototype, 'drawImage').mockImplementation(function (
this: PDFPage,
image,
options,
) {
const ref = imageRefOf(state, image)
const opts = serialise(options, state)
record(state, this, { op: 'drawImage', image: ref, options: opts })
return original.call(this, image, options)
})
}
function spyDrawLine(state: RecorderState) {
const original = PDFPage.prototype.drawLine
return vi.spyOn(PDFPage.prototype, 'drawLine').mockImplementation(function (
this: PDFPage,
options,
) {
record(state, this, { op: 'drawLine', options: serialise(options, state) })
return original.call(this, options)
})
}
function spyDrawRectangle(state: RecorderState) {
const original = PDFPage.prototype.drawRectangle
return vi
.spyOn(PDFPage.prototype, 'drawRectangle')
.mockImplementation(function (this: PDFPage, options) {
const opts = serialise(options, state)
record(state, this, { op: 'drawRectangle', options: opts })
return original.call(this, options)
})
}
/** Drawing and embedding entry points the engine must not use. */
const UNEXPECTED_PAGE = [
'drawPage',
'drawSvgPath',
'drawSquare',
'drawEllipse',
'drawCircle',
] as const
const UNEXPECTED_DOC = ['embedJpg', 'embedPdf', 'embedPage'] as const
function guardSpies() {
return [
...UNEXPECTED_PAGE.map((name) => ({
name,
spy: vi.spyOn(PDFPage.prototype, name),
})),
...UNEXPECTED_DOC.map((name) => ({
name,
spy: vi.spyOn(PDFDocument.prototype, name),
})),
]
}
export interface DrawRecorder {
state: RecorderState
/** Names of the guarded methods that were called. */
unexpectedCalls(): string[]
stop(): void
}
export function recordFullDrawing(): DrawRecorder {
const state: RecorderState = {
ops: [],
embeds: [],
images: new Map(),
documents: new Set(),
}
const spies = [
spyEmbedPng(state),
spyDrawText(state),
spyDrawImage(state),
spyDrawLine(state),
spyDrawRectangle(state),
]
const guards = guardSpies()
return {
state,
unexpectedCalls: () =>
guards.filter((g) => g.spy.mock.calls.length > 0).map((g) => g.name),
stop: () =>
[...spies, ...guards.map((g) => g.spy)].forEach((s) => s.mockRestore()),
}
}
function linkOf(dict: PDFDict, page: number): FullLink | null {
if (dict.get(PDFName.of('Subtype')) !== PDFName.of('Link')) return null
const rect = dict
.lookup(PDFName.of('Rect'), PDFArray)
.asArray()
.map((n) => (n as PDFNumber).asNumber())
const uri = dict.lookup(PDFName.of('A'), PDFDict).lookup(PDFName.of('URI'))
const text =
uri instanceof PDFString || uri instanceof PDFHexString
? uri.decodeText()
: String(uri)
return { page, rect, uri: text }
}
export interface PdfFacts {
pageCount: number
links: FullLink[]
}
/** Page count and every `/Annot /Link` of the saved bytes, in annotation order. */
export async function readPdfFacts(bytes: Uint8Array): Promise<PdfFacts> {
const doc = await PDFDocument.load(bytes)
const links: FullLink[] = []
doc.getPages().forEach((page, index) => {
const annots = page.node.Annots()
for (let i = 0; i < (annots?.size() ?? 0); i += 1) {
const link = linkOf(annots!.lookup(i, PDFDict), index)
if (link) links.push(link)
}
})
return { pageCount: doc.getPageCount(), links }
}
export function drawLogOf(recorder: DrawRecorder, facts: PdfFacts): DrawLog {
const { ops, embeds } = recorder.state
if (ops.some((o) => o.page < 0 || o.page >= facts.pageCount)) {
throw new Error('a draw call landed on a page the saved PDF lacks')
}
const pages = Array.from({ length: facts.pageCount }, (_, index) => ({
index,
ops: ops.filter((o) => o.page === index).map((o) => o.op),
}))
return { pages, embeds, links: facts.links }
}
function inCallOrder(log: DrawLog, name: DrawOpName) {
return log.pages
.flatMap((p) => p.ops.map((op) => ({ page: p.index, op })))
.filter((entry) => entry.op.op === name)
.sort((a, b) => a.op.seq - b.op.seq)
}
const optionsOf = (op: DrawOp) => op.options as Record<string, Json>
/** The Step 6 text golden's projection: 2 decimals, the same fields. */
export function step6Texts(log: DrawLog): TextEntry[] {
return inCallOrder(log, 'drawText').map(({ page, op }) => {
const o = optionsOf(op)
return {
page,
text: op.text ?? '',
x: round2(o.x),
y: round2(o.y),
size: round2(o.size),
font: typeof o.font === 'string' ? o.font : null,
}
})
}
export function step6Images(log: DrawLog): ImageEntry[] {
return inCallOrder(log, 'drawImage').map(({ page, op }) => {
const o = optionsOf(op)
return {
page,
x: round2(o.x),
y: round2(o.y),
width: round2(o.width),
height: round2(o.height),
}
})
}
export function step6Links(log: DrawLog): LinkEntry[] {
return log.links.map(({ page, rect, uri }) => ({
page,
rect: rect.map((n) => round2(n) ?? 0),
uri,
}))
}
/** Writes under MAKE_R4_ORACLES; otherwise deep equality, then the exact text. */
export function checkJsonOracle(file: string, value: unknown): void {
const text = `${JSON.stringify(value, null, 2)}\n`
if (MAKE_R4_ORACLES) {
mkdirSync(dirname(file), { recursive: true })
writeFileSync(file, text)
return
}
const committed = readFileSync(file, 'utf8')
expect(JSON.parse(text), file).toEqual(JSON.parse(committed))
expect(text, file).toBe(committed)
}
/** Writes under MAKE_R4_ORACLES; otherwise byte equality (by digest). */
export function checkBytesOracle(file: string, bytes: Uint8Array): void {
if (MAKE_R4_ORACLES) {
mkdirSync(dirname(file), { recursive: true })
writeFileSync(file, bytes)
return
}
const committed = new Uint8Array(readFileSync(file))
expect(sha256(bytes), file).toBe(sha256(committed))
}