257 lines
7.8 KiB
TypeScript
257 lines
7.8 KiB
TypeScript
import { createHash } from 'node:crypto'
|
||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||
import { fileURLToPath } from 'node:url'
|
||
import { dirname, resolve } from 'node:path'
|
||
import { expect, vi } from 'vitest'
|
||
import type {
|
||
Branding,
|
||
Observation,
|
||
Report,
|
||
SheetSnapshot,
|
||
} from '@faunosteo/core-wasm/types'
|
||
import { PdfFile, nameOf, numbersOf, subDict, textOf } from './pdfFile'
|
||
import { nologosBranding } from './sheet'
|
||
|
||
/**
|
||
* Step 6 Phase 0 freeze: what the PDF pipeline drew before the engine,
|
||
* recorded as JSON goldens (docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md
|
||
* §17) that the app export path must still reproduce. Since R4.8 the text
|
||
* and image facts are read back from the file's content streams
|
||
* (`pdfRead.ts`), the links from its annotations (`pdfFile.ts`), and the
|
||
* view snapshot parses the SVG the core's session asked the rasteriser for,
|
||
* with the browser DOM. Numbers are rounded to 2 decimals; nothing ordered
|
||
* by drawing order is sorted.
|
||
*/
|
||
|
||
/** 1×1 PNG (nologos: the legacy stub) and 2×1 PNG (logos: deterministic partner logo width). */
|
||
export const ONE_PX_PNG = Uint8Array.from(
|
||
Buffer.from(
|
||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
|
||
'base64',
|
||
),
|
||
)
|
||
export const TWO_BY_ONE_PNG = Uint8Array.from(
|
||
Buffer.from(
|
||
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7QOjdAAAAD0lEQVR4nGPYEWX///9/AA0PBE/1T7nxAAAAAElFTkSuQmCC',
|
||
'base64',
|
||
),
|
||
)
|
||
|
||
const HERE = dirname(fileURLToPath(import.meta.url))
|
||
export const FIXTURES_DIR = resolve(HERE, '../fixtures')
|
||
export const GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/step6')
|
||
|
||
/** `MAKE_GOLDEN=1` writes the goldens instead of asserting them. */
|
||
export const MAKE_GOLDEN = process.env.MAKE_GOLDEN === '1'
|
||
/** The R4 digests of the writer's own bytes (`goldens/r4/pdf.*.sha256`), frozen by the cargo suite. */
|
||
export const R4_GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/r4')
|
||
/** The export time of every R4 run (the engine suites' `FIXED_EXPORTED_AT` at the freeze). */
|
||
export const FIXED_EXPORTED_AT = new Date('2026-10-11T12:00:00.000Z')
|
||
|
||
export const sha256 = (data: Uint8Array | string): string =>
|
||
createHash('sha256').update(data).digest('hex')
|
||
|
||
export type LogoMode = 'nologos' | 'logos'
|
||
|
||
export interface TextEntry {
|
||
page: number
|
||
text: string
|
||
x: number | null
|
||
y: number | null
|
||
size: number | null
|
||
font: string | null
|
||
}
|
||
|
||
export interface ImageEntry {
|
||
page: number
|
||
x: number | null
|
||
y: number | null
|
||
width: number | null
|
||
height: number | null
|
||
}
|
||
|
||
export interface LinkEntry {
|
||
page: number
|
||
rect: number[]
|
||
uri: string
|
||
}
|
||
|
||
export interface HighlightedElement {
|
||
tag: string
|
||
cx: string | null
|
||
cy: string | null
|
||
r: string | null
|
||
points: string | null
|
||
d: string | null
|
||
fill: string | null
|
||
fillOpacity: string | null
|
||
filter: string | null
|
||
}
|
||
|
||
export interface ViewSnapshot {
|
||
observationId: string
|
||
viewId: string
|
||
viewBox: string | null
|
||
halo: boolean
|
||
highlighted: HighlightedElement[]
|
||
nonHighlightedVisible: number
|
||
dataAttributes: number
|
||
titles: number
|
||
}
|
||
|
||
export function round2(value: unknown): number | null {
|
||
return typeof value === 'number' ? Math.round(value * 100) / 100 : null
|
||
}
|
||
|
||
/** Every `/Annot /Link` of the saved PDF, page by page, in annotation order. */
|
||
export async function readLinks(bytes: Uint8Array): Promise<LinkEntry[]> {
|
||
const file = PdfFile.parse(bytes)
|
||
const out: LinkEntry[] = []
|
||
file.pages().forEach((page, index) => {
|
||
for (const annot of file.annots(page)) {
|
||
if (nameOf(annot.dict, 'Subtype') !== 'Link') continue
|
||
const action = subDict(annot.dict, 'A') ?? ''
|
||
out.push({
|
||
page: index,
|
||
rect: numbersOf(annot.dict, 'Rect').map((n) => round2(n) ?? 0),
|
||
uri: textOf(action, 'URI') ?? '',
|
||
})
|
||
}
|
||
})
|
||
return out
|
||
}
|
||
|
||
/**
|
||
* 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'
|
||
|
||
function highlightedOf(el: Element): HighlightedElement {
|
||
const attr = (name: string) => el.getAttribute(name)
|
||
return {
|
||
tag: el.tagName,
|
||
cx: attr('cx'),
|
||
cy: attr('cy'),
|
||
r: attr('r'),
|
||
points: attr('points'),
|
||
d: attr('d'),
|
||
fill: attr('fill'),
|
||
fillOpacity: attr('fill-opacity'),
|
||
filter: attr('filter'),
|
||
}
|
||
}
|
||
|
||
/** Children of the annotation layer (last `<g>` of the root) still visible and not highlighted. */
|
||
function countVisibleNonHighlighted(root: Element): number {
|
||
const layer = Array.from(root.children)
|
||
.filter((c) => c.tagName === 'g')
|
||
.at(-1)
|
||
if (!layer) return 0
|
||
return Array.from(layer.children).filter(
|
||
(el) =>
|
||
el.getAttribute('fill') !== HIGHLIGHT_FILL &&
|
||
el.getAttribute('display') !== 'none',
|
||
).length
|
||
}
|
||
|
||
function countDataAttributes(root: Element): number {
|
||
return [root, ...Array.from(root.querySelectorAll('*'))].reduce(
|
||
(count, el) =>
|
||
count +
|
||
Array.from(el.attributes).filter((a) => a.name.startsWith('data-'))
|
||
.length,
|
||
0,
|
||
)
|
||
}
|
||
|
||
/** The facts of one composed view, from the SVG the core's session asked the rasteriser for. */
|
||
export function snapshotView(
|
||
observationId: string,
|
||
viewId: string,
|
||
svg: string,
|
||
): ViewSnapshot {
|
||
const root = new DOMParser().parseFromString(
|
||
svg,
|
||
'image/svg+xml',
|
||
).documentElement
|
||
return {
|
||
observationId,
|
||
viewId,
|
||
viewBox: root.getAttribute('viewBox'),
|
||
halo: root.querySelector('filter#osteo-halo') !== null,
|
||
highlighted: Array.from(
|
||
root.querySelectorAll(`[fill="${HIGHLIGHT_FILL}"]`),
|
||
).map(highlightedOf),
|
||
nonHighlightedVisible: countVisibleNonHighlighted(root),
|
||
dataAttributes: countDataAttributes(root),
|
||
titles: root.getElementsByTagName('title').length,
|
||
}
|
||
}
|
||
|
||
/** The views an observation draws, in the pipeline's order: main first, then first appearance. */
|
||
export function viewIdsOf(
|
||
sheet: SheetSnapshot,
|
||
observation: Observation,
|
||
): string[] {
|
||
const views = new Set(sheet.document.views.map((v) => v.id))
|
||
const main = sheet.document.views.find((v) => v.kind === 'main')!.id
|
||
return [...new Set(observation.zones.map((z) => z.viewId))]
|
||
.filter((id) => views.has(id))
|
||
.sort((a, b) => Number(b === main) - Number(a === main))
|
||
}
|
||
|
||
/** The (observation, view) pairs an export rasterises, in the session's request order. */
|
||
export function viewPairsOf(
|
||
sheet: SheetSnapshot,
|
||
report: Report,
|
||
): { observationId: string; viewId: string }[] {
|
||
return report.observations.flatMap((observation) =>
|
||
viewIdsOf(sheet, observation).map((viewId) => ({
|
||
observationId: observation.id,
|
||
viewId,
|
||
})),
|
||
)
|
||
}
|
||
|
||
/**
|
||
* The view snapshots of an export: `svgs` are the view SVGs the session asked the
|
||
* rasteriser for (every logo raster excluded), in request order, one per pair.
|
||
*/
|
||
export function snapshotViews(
|
||
sheet: SheetSnapshot,
|
||
report: Report,
|
||
svgs: readonly string[],
|
||
): ViewSnapshot[] {
|
||
const pairs = viewPairsOf(sheet, report)
|
||
expect(svgs).toHaveLength(pairs.length)
|
||
return pairs.map((pair, i) =>
|
||
snapshotView(pair.observationId, pair.viewId, svgs[i]!),
|
||
)
|
||
}
|
||
|
||
export function readGolden<T = unknown>(name: string): T {
|
||
return JSON.parse(readFileSync(resolve(GOLDEN_DIR, name), 'utf8')) as T
|
||
}
|
||
|
||
/** Writes the golden under MAKE_GOLDEN, asserts deep equality otherwise. */
|
||
export function checkGolden(name: string, actual: unknown): void {
|
||
if (MAKE_GOLDEN) {
|
||
mkdirSync(GOLDEN_DIR, { recursive: true })
|
||
writeFileSync(
|
||
resolve(GOLDEN_DIR, name),
|
||
`${JSON.stringify(actual, null, 2)}\n`,
|
||
)
|
||
return
|
||
}
|
||
expect(actual, name).toEqual(readGolden(name))
|
||
}
|