test(tests): R4.1b writer oracles: O1 draw logs, O2 R3-build PDFs (real raster, store path), O3 pre-R2 envelope PDFs
This commit is contained in:
1 parent
7a4297933d
commit
87b88739f8
35 files changed
+39810
No files matched your search
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"note": "v2full reduced to its first observation (obs-1, main view), every other field unchanged: the full report weighed 3 MB in real rasters.",
|
||||
"calls": [
|
||||
{
|
||||
"index": 0,
|
||||
"svgSha256": "c342c54fae8e69d90cbe90f4abf233b4aaa388e2d96d54a47fd7c73295b6c89a",
|
||||
"widthPx": 1200,
|
||||
"heightPx": 263,
|
||||
"png": "raster-0.png",
|
||||
"pngSha256": "38f30384e816271f3186ee3f94410d50975176db610ea9d86a3ad0c352fde4fd",
|
||||
"subject": {
|
||||
"kind": "logo",
|
||||
"slot": "partner"
|
||||
}
|
||||
},
|
||||
{
|
||||
"index": 1,
|
||||
"svgSha256": "a9a3155c827838af46edd583452e8d8106c3ce09da272afaaf37c3cb36af2c11",
|
||||
"widthPx": 1200,
|
||||
"heightPx": 943,
|
||||
"png": "raster-1.png",
|
||||
"pngSha256": "c4af684450f54dadf87208560a3ae7f758446f01a5a7f435b6d06c5df59083dd",
|
||||
"subject": {
|
||||
"kind": "view",
|
||||
"observationId": "obs-1",
|
||||
"viewId": "main"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 32 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 522 KiB |
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,266 @@
|
||||
{
|
||||
"version": 3,
|
||||
"id": "fixture-demo-v3",
|
||||
"createdAt": "2026-10-11T09:30:00.000Z",
|
||||
"date": "2026-10-11",
|
||||
"practitioner": {
|
||||
"contact": "secretariat@example.test",
|
||||
"name": "Dr. Claire Dupont-Martin"
|
||||
},
|
||||
"animal": {
|
||||
"speciesId": "equine",
|
||||
"name": "Mistral",
|
||||
"breed": "Selle Français",
|
||||
"age": "9 ans"
|
||||
},
|
||||
"owner": {
|
||||
"name": "Jean Martin"
|
||||
},
|
||||
"sheet": {
|
||||
"sheetId": "503dc301-a8b1-50d4-9e44-0919b2fc2916",
|
||||
"versionId": null,
|
||||
"documentSha256": "27c7383c445c73dc2001ebf4794a3ea63d416910bbbaa0d7848dd720de7c2660"
|
||||
},
|
||||
"observations": [
|
||||
{
|
||||
"id": "obs-demo-1",
|
||||
"zones": [
|
||||
{
|
||||
"annotationId": "c7-t1",
|
||||
"viewId": "main",
|
||||
"labelFrSnapshot": "Charnière C7-T1 (cervico-thoracique)",
|
||||
"labelEnSnapshot": "C7-T1 junction (cervicothoracic)"
|
||||
},
|
||||
{
|
||||
"annotationId": "t18-l1",
|
||||
"viewId": "main",
|
||||
"labelFrSnapshot": "Charnière T18-L1 (thoraco-lombaire)",
|
||||
"labelEnSnapshot": "T18-L1 junction (thoracolumbar)"
|
||||
}
|
||||
],
|
||||
"findings": [
|
||||
{
|
||||
"findingZoneId": "c7-t1",
|
||||
"path": [
|
||||
"c7-t1-dysfunctions",
|
||||
"segmental",
|
||||
"restriction-flexion"
|
||||
],
|
||||
"labelFrSnapshot": "Restriction en flexion",
|
||||
"labelEnSnapshot": "Flexion restriction"
|
||||
},
|
||||
{
|
||||
"findingZoneId": "c7-t1",
|
||||
"path": [
|
||||
"c7-t1-dysfunctions",
|
||||
"segmental",
|
||||
"restriction-extension"
|
||||
],
|
||||
"labelFrSnapshot": "Restriction en extension",
|
||||
"labelEnSnapshot": "Extension restriction"
|
||||
}
|
||||
],
|
||||
"freeTextFindings": [],
|
||||
"severity": "mild",
|
||||
"comment": "Réagit à la palpation de la charnière."
|
||||
},
|
||||
{
|
||||
"id": "obs-demo-2",
|
||||
"zones": [
|
||||
{
|
||||
"annotationId": "hip",
|
||||
"viewId": "main",
|
||||
"side": "left",
|
||||
"labelFrSnapshot": "Hanche (coxo-fémorale)",
|
||||
"labelEnSnapshot": "Hip joint"
|
||||
},
|
||||
{
|
||||
"annotationId": "hip",
|
||||
"viewId": "main",
|
||||
"side": "right",
|
||||
"labelFrSnapshot": "Hanche (coxo-fémorale)",
|
||||
"labelEnSnapshot": "Hip joint"
|
||||
}
|
||||
],
|
||||
"findings": [
|
||||
{
|
||||
"findingZoneId": "hip",
|
||||
"path": [
|
||||
"hip-dysfunctions",
|
||||
"articular",
|
||||
"restriction-flexion"
|
||||
],
|
||||
"labelFrSnapshot": "Restriction en flexion",
|
||||
"labelEnSnapshot": "Flexion restriction",
|
||||
"side": "left"
|
||||
},
|
||||
{
|
||||
"findingZoneId": "hip",
|
||||
"path": [
|
||||
"hip-dysfunctions",
|
||||
"articular",
|
||||
"restriction-abduction-adduction"
|
||||
],
|
||||
"labelFrSnapshot": "Restriction en abduction / adduction",
|
||||
"labelEnSnapshot": "Abduction / adduction restriction",
|
||||
"side": "right"
|
||||
}
|
||||
],
|
||||
"freeTextFindings": [],
|
||||
"severity": "moderate",
|
||||
"comment": ""
|
||||
},
|
||||
{
|
||||
"id": "obs-demo-3",
|
||||
"zones": [
|
||||
{
|
||||
"annotationId": "cervical",
|
||||
"viewId": "main",
|
||||
"vertebrae": [
|
||||
{
|
||||
"region": "C",
|
||||
"index": 3
|
||||
},
|
||||
{
|
||||
"region": "C",
|
||||
"index": 4
|
||||
}
|
||||
],
|
||||
"labelFrSnapshot": "Vertèbres cervicales",
|
||||
"labelEnSnapshot": "Cervical vertebrae"
|
||||
}
|
||||
],
|
||||
"findings": [
|
||||
{
|
||||
"findingZoneId": "cervical",
|
||||
"path": [
|
||||
"cervical-dysfunctions",
|
||||
"segmental",
|
||||
"localized-fixation"
|
||||
],
|
||||
"labelFrSnapshot": "Fixation segmentaire localisée (C2–C7)",
|
||||
"labelEnSnapshot": "Localized segmental fixation (C2–C7)"
|
||||
}
|
||||
],
|
||||
"freeTextFindings": [],
|
||||
"severity": "severe",
|
||||
"comment": "Fixation nette en latéroflexion droite."
|
||||
},
|
||||
{
|
||||
"id": "obs-demo-4",
|
||||
"zones": [
|
||||
{
|
||||
"annotationId": "atm",
|
||||
"viewId": "head",
|
||||
"labelFrSnapshot": "Articulation temporo-mandibulaire (ATM)",
|
||||
"labelEnSnapshot": "Temporomandibular joint (TMJ)"
|
||||
},
|
||||
{
|
||||
"annotationId": "frontal",
|
||||
"viewId": "head",
|
||||
"labelFrSnapshot": "Frontal",
|
||||
"labelEnSnapshot": "Frontal bone"
|
||||
}
|
||||
],
|
||||
"findings": [
|
||||
{
|
||||
"findingZoneId": "frontal",
|
||||
"path": [
|
||||
"frontal-consultation-reasons",
|
||||
"head-rubbing"
|
||||
],
|
||||
"labelFrSnapshot": "Frottements répétés de la tête rapportés",
|
||||
"labelEnSnapshot": "Reported repeated head rubbing",
|
||||
"requiresVetReferral": true
|
||||
},
|
||||
{
|
||||
"findingZoneId": "atm",
|
||||
"path": [
|
||||
"atm-dysfunctions",
|
||||
"articular",
|
||||
"restriction-opening"
|
||||
],
|
||||
"labelFrSnapshot": "Restriction à l'ouverture",
|
||||
"labelEnSnapshot": "Opening restriction"
|
||||
}
|
||||
],
|
||||
"freeTextFindings": [],
|
||||
"comment": ""
|
||||
},
|
||||
{
|
||||
"id": "obs-demo-5",
|
||||
"zones": [
|
||||
{
|
||||
"annotationId": "sacroiliac",
|
||||
"viewId": "main",
|
||||
"side": "right",
|
||||
"labelFrSnapshot": "Articulation sacro-iliaque",
|
||||
"labelEnSnapshot": "Sacroiliac joint"
|
||||
},
|
||||
{
|
||||
"annotationId": "occipital",
|
||||
"viewId": "head",
|
||||
"labelFrSnapshot": "Occipital",
|
||||
"labelEnSnapshot": "Occipital bone"
|
||||
}
|
||||
],
|
||||
"findings": [],
|
||||
"freeTextFindings": [
|
||||
"Sensibilité au garrot",
|
||||
"Tension du ligament nuchal"
|
||||
],
|
||||
"severity": "mild",
|
||||
"comment": "Compensation probable."
|
||||
},
|
||||
{
|
||||
"id": "obs-demo-6",
|
||||
"zones": [
|
||||
{
|
||||
"annotationId": "lumbar",
|
||||
"viewId": "main",
|
||||
"vertebrae": [
|
||||
{
|
||||
"region": "L",
|
||||
"index": 2
|
||||
},
|
||||
{
|
||||
"region": "L",
|
||||
"index": 3
|
||||
}
|
||||
],
|
||||
"labelFrSnapshot": "Vertèbres lombaires",
|
||||
"labelEnSnapshot": "Lumbar vertebrae"
|
||||
},
|
||||
{
|
||||
"annotationId": "l6-s1",
|
||||
"viewId": "main",
|
||||
"labelFrSnapshot": "Charnière L6-S1 (lombo-sacrée)",
|
||||
"labelEnSnapshot": "L6-S1 junction (lumbosacral joint)"
|
||||
}
|
||||
],
|
||||
"findings": [
|
||||
{
|
||||
"findingZoneId": "lumbar",
|
||||
"path": [
|
||||
"lumbar-dysfunctions",
|
||||
"segmental",
|
||||
"restriction-extension"
|
||||
],
|
||||
"labelFrSnapshot": "Restriction en extension",
|
||||
"labelEnSnapshot": "Extension restriction"
|
||||
}
|
||||
],
|
||||
"freeTextFindings": [
|
||||
"Raideur lombaire au pas"
|
||||
],
|
||||
"comment": ""
|
||||
}
|
||||
],
|
||||
"conclusion": "Dysfonction cervico-thoracique avec compensation du bassin et tension crânienne associée.",
|
||||
"recommendations": "Repos 3 jours puis reprise progressive ; contrôle vétérinaire pour les frottements de tête.",
|
||||
"localAnnotations": [],
|
||||
"nextAppointment": {
|
||||
"kind": "date",
|
||||
"date": "2026-11-20"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,389 @@
|
||||
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))
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
/**
|
||||
* R4.1 freeze, writer oracles O1 to O3 (plan 2026-10-17 §B.5.1), recorded on
|
||||
* the application export path with the Step 6 golden inputs (three reports,
|
||||
* fr / en, nologos / logos, fixed 1×1 / 2×1 rasters) at FIXED_EXPORTED_AT:
|
||||
* - O1, the complete draw log of every run, which the Step 6 text, images
|
||||
* and links goldens must equal once rounded;
|
||||
* - O2, the PDFs of those runs, one real-raster PDF (resvg, v2full's first
|
||||
* observation) with every PNG it embedded, one PDF exported through the
|
||||
* store path (D-R11 case);
|
||||
* - O3, the frozen pre-R2 envelopes attached byte for byte by pdf-lib.
|
||||
* `MAKE_R4_ORACLES=1` writes them; never again without an owner decision.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { AFRelationship, PageSizes, PDFDocument, StandardFonts } from 'pdf-lib'
|
||||
import type { Branding, Practitioner, Report } from '@faunosteo/core-wasm/types'
|
||||
import {
|
||||
readAttachedDocument,
|
||||
readAttachmentBytes,
|
||||
type Rasterizer,
|
||||
} from '@faunosteo/pdf'
|
||||
import { exportReportToPdf } from '@/pdf/export'
|
||||
import { importAttachment } from '@/pdf/import'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { resvgRasterizer } from '../../../../packages/pdf/tests/helpers/resvg'
|
||||
import { loadTestSheet, sheetSnapshot } from '../helpers/sheet'
|
||||
import {
|
||||
buildGoldenReports,
|
||||
GOLDEN_REPORTS,
|
||||
type GoldenReportName,
|
||||
} from '../helpers/goldenReports'
|
||||
import {
|
||||
brandingOf,
|
||||
FIXTURES_DIR,
|
||||
ONE_PX_PNG,
|
||||
readGolden,
|
||||
TWO_BY_ONE_PNG,
|
||||
viewIdsOf,
|
||||
type LogoMode,
|
||||
} from '../helpers/goldens'
|
||||
import {
|
||||
checkBytesOracle,
|
||||
checkJsonOracle,
|
||||
drawLogOf,
|
||||
FIXED_EXPORTED_AT,
|
||||
R3_PDF_DIR,
|
||||
R4_GOLDEN_DIR,
|
||||
readPdfFacts,
|
||||
recordFullDrawing,
|
||||
sha256,
|
||||
step6Images,
|
||||
step6Links,
|
||||
step6Texts,
|
||||
STEP6_PDF_DIR,
|
||||
type DrawLog,
|
||||
} from '../helpers/r4-draw'
|
||||
|
||||
const raster = vi.hoisted(() => ({ rasterize: null as Rasterizer | null }))
|
||||
vi.mock('@/pdf/browserRasterizer', () => ({
|
||||
browserRasterizer: vi.fn<Rasterizer>((svg, size) =>
|
||||
raster.rasterize!(svg, size),
|
||||
),
|
||||
}))
|
||||
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 MODES: readonly LogoMode[] = ['nologos', 'logos']
|
||||
const LOCALES: readonly Locale[] = ['fr', 'en']
|
||||
const REAL_DIR = resolve(R3_PDF_DIR, 'real')
|
||||
const R2_DIR = resolve(FIXTURES_DIR, 'goldens/r2')
|
||||
const R2_ENVELOPES = ['demo', 'v2full', 'v2unresolved'].map(
|
||||
(name) => `${name}.fr.nologos`,
|
||||
)
|
||||
const REAL_RASTER_TIMEOUT = 120_000
|
||||
|
||||
let sheet: SheetIndex
|
||||
let reports: Record<GoldenReportName, Report>
|
||||
|
||||
beforeAll(async () => {
|
||||
sheet = await loadTestSheet()
|
||||
reports = buildGoldenReports(sheet).reports
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||
vi.useFakeTimers({ toFake: ['Date'] })
|
||||
vi.setSystemTime(FIXED_EXPORTED_AT)
|
||||
})
|
||||
afterAll(() => {
|
||||
useReportStore.getState().reset()
|
||||
sessionStorage.clear()
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
interface Run {
|
||||
report: Report
|
||||
mode: LogoMode
|
||||
locale: Locale
|
||||
rasterize: Rasterizer
|
||||
}
|
||||
|
||||
interface Exported {
|
||||
pdf: Uint8Array
|
||||
log: DrawLog
|
||||
}
|
||||
|
||||
const fixedRaster =
|
||||
(mode: LogoMode): Rasterizer =>
|
||||
async () =>
|
||||
mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG
|
||||
|
||||
/** One export through `@/pdf/export`, drawn under the full recorder. */
|
||||
async function exportRun(run: Run): Promise<Exported> {
|
||||
raster.rasterize = run.rasterize
|
||||
logoMode.current = run.mode
|
||||
const recorder = recordFullDrawing()
|
||||
try {
|
||||
const { pdf, warnings } = await exportReportToPdf(run.report, sheet, {
|
||||
locale: run.locale,
|
||||
})
|
||||
expect(warnings).toEqual([])
|
||||
expect(recorder.unexpectedCalls()).toEqual([])
|
||||
expect(recorder.state.documents.size).toBe(1)
|
||||
return { pdf, log: drawLogOf(recorder, await readPdfFacts(pdf)) }
|
||||
} finally {
|
||||
recorder.stop()
|
||||
}
|
||||
}
|
||||
|
||||
describe.each(GOLDEN_REPORTS)('writer oracles of %s', (name) => {
|
||||
describe.each(MODES)('%s', (mode) => {
|
||||
it.each(LOCALES)(
|
||||
'%s: O1 draw log, O2 PDF, rounded = step6',
|
||||
async (locale) => {
|
||||
const run = { report: reports[name], mode, locale }
|
||||
const out = await exportRun({ ...run, rasterize: fixedRaster(mode) })
|
||||
const id = `${name}.${locale}.${mode}`
|
||||
checkJsonOracle(resolve(R4_GOLDEN_DIR, `draw.${id}.json`), out.log)
|
||||
checkBytesOracle(resolve(R3_PDF_DIR, `${id}.pdf`), out.pdf)
|
||||
expect(step6Texts(out.log)).toEqual(readGolden(`text.${id}.json`))
|
||||
expect(step6Images(out.log)).toEqual(readGolden(`images.${id}.json`))
|
||||
expect(step6Links(out.log)).toEqual(readGolden(`links.${id}.json`))
|
||||
},
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
type RasterSubject =
|
||||
| { kind: 'logo'; slot: string }
|
||||
| { kind: 'view'; observationId: string; viewId: string }
|
||||
|
||||
interface RasterCall {
|
||||
index: number
|
||||
svgSha256: string
|
||||
widthPx: number
|
||||
heightPx: number
|
||||
png: Uint8Array | null
|
||||
}
|
||||
|
||||
const LOGO_SLOTS = ['headerLogo', 'footerLogo', 'poweredBy', 'partner'] as const
|
||||
|
||||
function logoOf(branding: Branding, slot: (typeof LOGO_SLOTS)[number]) {
|
||||
const value = branding[slot]
|
||||
return value && 'kind' in value ? value : (value?.logo ?? null)
|
||||
}
|
||||
|
||||
/**
|
||||
* The engine's rasteriser calls in order: the SVG logos while embedding the
|
||||
* branding (header, footer, powered-by, partner), then each observation's
|
||||
* views, main first (packages/pdf export and observationPage).
|
||||
*/
|
||||
function rasterSubjects(branding: Branding, report: Report): RasterSubject[] {
|
||||
const logos = LOGO_SLOTS.filter(
|
||||
(slot) => logoOf(branding, slot)?.kind === 'svg',
|
||||
).map((slot): RasterSubject => ({ kind: 'logo', slot }))
|
||||
const snapshot = sheetSnapshot(sheet, report)
|
||||
const views = report.observations.flatMap((o) =>
|
||||
viewIdsOf(snapshot, o).map(
|
||||
(viewId): RasterSubject => ({
|
||||
kind: 'view',
|
||||
observationId: o.id,
|
||||
viewId,
|
||||
}),
|
||||
),
|
||||
)
|
||||
return [...logos, ...views]
|
||||
}
|
||||
|
||||
/** resvg wrapped: each call is numbered when it is made, its PNG kept. */
|
||||
function capturingResvg(calls: RasterCall[]): Rasterizer {
|
||||
const resvg = resvgRasterizer()
|
||||
return async (svg, size) => {
|
||||
const call: RasterCall = {
|
||||
index: calls.length,
|
||||
svgSha256: sha256(svg),
|
||||
widthPx: size.widthPx,
|
||||
heightPx: size.heightPx,
|
||||
png: null,
|
||||
}
|
||||
calls.push(call)
|
||||
call.png = await resvg(svg, size)
|
||||
return call.png
|
||||
}
|
||||
}
|
||||
|
||||
const REAL_NOTE =
|
||||
'v2full reduced to its first observation (obs-1, main view), every other ' +
|
||||
'field unchanged: the full report weighed 3 MB in real rasters.'
|
||||
|
||||
/** v2full with its first observation only: one view keeps the set small. */
|
||||
function firstObservationOf(report: Report): Report {
|
||||
return { ...report, observations: report.observations.slice(0, 1) }
|
||||
}
|
||||
|
||||
describe('O2 real raster: v2full first observation, fr, logos, resvg', () => {
|
||||
it(
|
||||
'freezes the PDF, every PNG returned and the call manifest',
|
||||
async () => {
|
||||
const calls: RasterCall[] = []
|
||||
const report = firstObservationOf(reports.v2full)
|
||||
const { pdf } = await exportRun({
|
||||
report,
|
||||
mode: 'logos',
|
||||
locale: 'fr',
|
||||
rasterize: capturingResvg(calls),
|
||||
})
|
||||
const subjects = rasterSubjects(await brandingOf('logos'), report)
|
||||
expect(subjects).toEqual([
|
||||
{ kind: 'logo', slot: 'partner' },
|
||||
{ kind: 'view', observationId: 'obs-1', viewId: 'main' },
|
||||
])
|
||||
expect(calls).toHaveLength(subjects.length)
|
||||
checkBytesOracle(resolve(REAL_DIR, 'v2full-obs1.fr.logos.pdf'), pdf)
|
||||
const manifest = calls.map(({ png, ...call }) => {
|
||||
const file = `raster-${call.index}.png`
|
||||
checkBytesOracle(resolve(REAL_DIR, file), png!)
|
||||
const pngSha256 = sha256(png!)
|
||||
return { ...call, png: file, pngSha256, subject: subjects[call.index] }
|
||||
})
|
||||
const manifestFile = resolve(REAL_DIR, 'manifest.json')
|
||||
checkJsonOracle(manifestFile, { note: REAL_NOTE, calls: manifest })
|
||||
},
|
||||
REAL_RASTER_TIMEOUT,
|
||||
)
|
||||
})
|
||||
|
||||
type KeyOrder = { path: string; keys: string[] }
|
||||
|
||||
function keyOrders(value: unknown, path = 'report'): KeyOrder[] {
|
||||
if (!value || typeof value !== 'object') return []
|
||||
const entries = Object.entries(value)
|
||||
const own = Array.isArray(value)
|
||||
? []
|
||||
: [{ path, keys: entries.map(([k]) => k) }]
|
||||
return [...own, ...entries.flatMap(([k, v]) => keyOrders(v, `${path}.${k}`))]
|
||||
}
|
||||
|
||||
/** Objects whose key sequence differs between two equal values. */
|
||||
function keyOrderDifferences(a: unknown, b: unknown) {
|
||||
const other = new Map(keyOrders(b).map((o) => [o.path, o.keys]))
|
||||
return keyOrders(a)
|
||||
.map((o) => ({ path: o.path, attachment: o.keys, core: other.get(o.path) }))
|
||||
.filter((d) => JSON.stringify(d.attachment) !== JSON.stringify(d.core))
|
||||
}
|
||||
|
||||
/** A partial practitioner, keys out of the contract order (name, cabinet, contact, siret). */
|
||||
const EDITED_PRACTITIONER: Practitioner = {
|
||||
contact: 'secretariat@example.test',
|
||||
name: 'Dr. Claire Dupont-Martin',
|
||||
}
|
||||
|
||||
describe('O2 store path: demo, next appointment set, practitioner edited', () => {
|
||||
it('freezes the PDF and the store report; attachment order is D-R11', async () => {
|
||||
sessionStorage.clear()
|
||||
const store = useReportStore.getState()
|
||||
expect(
|
||||
store.hydrateImport({ report: reports.demo, archive: null }, sheet),
|
||||
).toEqual({ ok: true })
|
||||
store.setNextAppointment({ kind: 'date', date: '2026-11-20' })
|
||||
store.setPractitioner(EDITED_PRACTITIONER)
|
||||
const report = useReportStore.getState().report!
|
||||
const { pdf } = await exportRun({
|
||||
report,
|
||||
mode: 'nologos',
|
||||
locale: 'fr',
|
||||
rasterize: fixedRaster('nologos'),
|
||||
})
|
||||
checkBytesOracle(resolve(R3_PDF_DIR, 'store-path.fr.nologos.pdf'), pdf)
|
||||
checkJsonOracle(resolve(R3_PDF_DIR, 'store-path.report.json'), report)
|
||||
const attached = (await readAttachedDocument(pdf)) as { report: unknown }
|
||||
expect(keyOrders(attached.report)).toEqual(keyOrders(report))
|
||||
const reread = importAttachment(attached, sheet).read.report
|
||||
expect(reread).toEqual(attached.report)
|
||||
const differences = keyOrderDifferences(attached.report, reread)
|
||||
console.info('D-R11 key order, attachment vs core:', differences)
|
||||
expect(differences.length).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
interface EnvelopeMeta {
|
||||
locale: 'fr' | 'en'
|
||||
labels: Record<string, Record<string, string>>
|
||||
report: { animal: { name: string }; practitioner: { name: string } }
|
||||
}
|
||||
|
||||
/** The engine's file structure around a given attachment (export.ts, attachment/write.ts). */
|
||||
async function envelopePdf(attachment: Uint8Array): Promise<Uint8Array> {
|
||||
const envelope = JSON.parse(
|
||||
new TextDecoder().decode(attachment),
|
||||
) as EnvelopeMeta
|
||||
const labels = envelope.labels[envelope.locale]
|
||||
const title = `${labels['pdf.title.suffix.bilan']}${envelope.report.animal.name}`
|
||||
const doc = await PDFDocument.create()
|
||||
doc.setTitle(title)
|
||||
doc.setAuthor(envelope.report.practitioner.name)
|
||||
doc.setSubject(labels['pdf.subject'])
|
||||
doc.setKeywords(['faunosteo-archive/1'])
|
||||
doc.setCreationDate(FIXED_EXPORTED_AT)
|
||||
doc.setModificationDate(FIXED_EXPORTED_AT)
|
||||
const font = await doc.embedFont(StandardFonts.Helvetica)
|
||||
doc.addPage(PageSizes.A4).drawText(title, { x: 40, y: 790, size: 12, font })
|
||||
await doc.attach(attachment, 'osteo-report.json', {
|
||||
mimeType: 'application/json',
|
||||
description: 'Faunosteo report archive v1',
|
||||
creationDate: FIXED_EXPORTED_AT,
|
||||
modificationDate: FIXED_EXPORTED_AT,
|
||||
afRelationship: AFRelationship.Data,
|
||||
})
|
||||
return doc.save({ useObjectStreams: false })
|
||||
}
|
||||
|
||||
describe.each(R2_ENVELOPES)('O3 pre-R2 envelope PDF %s', (name) => {
|
||||
// The R2 freeze wrote the decoded attachment text as is, and UTF-8
|
||||
// round-trips JSON.stringify output: the file bytes are the attachment.
|
||||
it('carries the frozen bytes, read back as is', async () => {
|
||||
const golden = new Uint8Array(
|
||||
readFileSync(resolve(R2_DIR, `envelope.${name}.json`)),
|
||||
)
|
||||
const pdf = await envelopePdf(golden)
|
||||
checkBytesOracle(resolve(STEP6_PDF_DIR, `envelope.${name}.pdf`), pdf)
|
||||
const read = await readAttachmentBytes(pdf)
|
||||
expect(Buffer.from(read).equals(Buffer.from(golden))).toBe(true)
|
||||
expect(await readAttachedDocument(pdf)).toEqual(
|
||||
JSON.parse(new TextDecoder().decode(golden)),
|
||||
)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user