refactor(pdf): R4.8 the TypeScript PDF engine leaves: packages/pdf, pdf-lib, the TS CLI and import path, the oracle generators deleted; test read-back on an own reader of the writer's files (pdfFile.ts), view goldens from the session's SVGs, import helper on the module's reader, N-1 scanner exported by core-wasm/n-1; app no longer depends on @faunosteo/domain; r4.census suite
This commit is contained in:
1 parent
77e11a53e4
commit
0dc1ba27c7
96 files changed
+743
-15769
No files matched your search
@@ -21,7 +21,6 @@
|
||||
"build": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@faunosteo/pdf": "workspace:*",
|
||||
"@types/node": "^20.19.41",
|
||||
"eslint": "^9.17.0",
|
||||
"globals": "^15.14.0",
|
||||
|
||||
@@ -50,6 +50,9 @@ export interface GlueSheetHandle {
|
||||
import_pdf_bytes(bytes: GlueFileBytes): string
|
||||
/** R4.3: a rescue copy streamed into the module's memory (consumed): `draft.restore`'s kinds. */
|
||||
restore_copy_bytes(bytes: GlueFileBytes): string
|
||||
/** wasm-bindgen's: the page's session keeps its handle for the instance's life, a worker
|
||||
* dies with its own; the tests' throwaway handles free theirs. */
|
||||
free(): void
|
||||
}
|
||||
|
||||
/** A file gathered chunk by chunk in the module's memory (crates/wasm `FileBytes`). */
|
||||
|
||||
@@ -19,3 +19,16 @@ export {
|
||||
type ReportArchiveEnvelope,
|
||||
type ReportMigrationMap,
|
||||
} from './domain'
|
||||
|
||||
/**
|
||||
* The N-1 PDF reader (R4 plan B.2.2, O11): the byte-scan attachment reader of the R3 build
|
||||
* and release 0.2.0, copied verbatim under `./scanner` (never edited). Since R4.8 it is the
|
||||
* only TypeScript reader left: the application suites that compare an attachment's text with
|
||||
* a frozen envelope read it here, as a rollback to that build would.
|
||||
*/
|
||||
export {
|
||||
readAttachedDocument,
|
||||
readAttachmentBytes,
|
||||
ArchiveReadError,
|
||||
type ArchiveReadErrorKind,
|
||||
} from './scanner'
|
||||
@@ -0,0 +1,4 @@
|
||||
/** The frozen scanner's surface (see README.md): the copies are never edited, this index only re-exports them. */
|
||||
export { readAttachedDocument } from './attachment/read'
|
||||
export { readAttachmentBytes } from './attachment/scan'
|
||||
export { ArchiveReadError, type ArchiveReadErrorKind } from './errors'
|
||||
@@ -3,8 +3,10 @@
|
||||
* (`CoreExportSession`): driven request by request on the O2 runs it writes the native
|
||||
* bytes (`goldens/r4/pdf.*.sha256`), which the module's own reader imports back onto the
|
||||
* bundled sheet as the report they carry (export Rust → import Rust, no loss); every view
|
||||
* it asks for is the SVG the TypeScript engine composes (`composeHighlightedViewSvg`)
|
||||
* and, on the real-raster run, the digests and sizes the R4.1 rasteriser recorded
|
||||
* it asks for is composed on the view's own frame with the observation's markers
|
||||
* highlighted (the text itself is pinned in cargo: `pdf_session` against `compose_highlight`,
|
||||
* `anatomy_compose` against the frozen R3 trees of the TypeScript engine) and, on the
|
||||
* real-raster run, the digests and sizes the R4.1 rasteriser recorded
|
||||
* (`pdf/r3/real/manifest.json`); the refusals are closed kinds; a trap mid-session
|
||||
* poisons the instance and the session answers `core_unavailable` from then on, `free()`
|
||||
* included; the memory held by a fresh instance after an export is printed against the
|
||||
@@ -14,7 +16,6 @@ import { createHash } from 'node:crypto'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { composeHighlightedViewSvg } from '@faunosteo/pdf'
|
||||
|
||||
import {
|
||||
CoreRuntime,
|
||||
@@ -221,22 +222,24 @@ describe('R4.6 export session through the shipped module', () => {
|
||||
expect(outcome.value!.read.origin, run.name).toBe('envelope_v1')
|
||||
expect(outcome.value!.read.snapshotRejected, run.name).toBeUndefined()
|
||||
expect(outcome.value!.rebase.report, run.name).toEqual(report)
|
||||
// Every view request is the TypeScript composition of that view for that observation.
|
||||
// Every view request is a composition on that view's frame with the observation's
|
||||
// markers highlighted and nothing of the editor's attributes (the exact text is the
|
||||
// cargo suites' business).
|
||||
let views = 0
|
||||
const snapshotViews = (
|
||||
envelope.sheetSnapshot as { document: { views: Array<{ id: string }> } }
|
||||
).document.views
|
||||
for (const request of driven.requests) {
|
||||
if (!request.key.startsWith('view:')) continue
|
||||
const [, observationId, viewId] = request.key.split(':')
|
||||
const observation = report.observations.find((o) => o.id === observationId)!
|
||||
expect(
|
||||
request.svg,
|
||||
`${run.name} ${request.key}`,
|
||||
).toBe(
|
||||
composeHighlightedViewSvg(
|
||||
envelope.sheetSnapshot as never,
|
||||
viewId!,
|
||||
observation as never,
|
||||
),
|
||||
)
|
||||
const where = `${run.name} ${request.key}`
|
||||
expect(snapshotViews.some((v) => v.id === viewId), where).toBe(true)
|
||||
expect(request.svg, where).toMatch(/^<svg /)
|
||||
expect(request.svg, where).not.toContain('data-anno-id')
|
||||
expect(request.svg, where).not.toContain('display="none"')
|
||||
const highlighted = observation.zones.some((z) => z.viewId === viewId)
|
||||
expect(request.svg.includes('fill="#b85a3f"'), where).toBe(highlighted)
|
||||
views += 1
|
||||
}
|
||||
// Every (observation, view) the snapshot holds was asked for, once.
|
||||
|
||||
@@ -1,170 +0,0 @@
|
||||
/**
|
||||
* R4.5: the Rust writer's output under the TypeScript engine's own reader (plan §B.2.2: the
|
||||
* R3 build reads R4 PDFs) and against that engine's export on the same inputs and
|
||||
* conditions: the demo, L and CAP reports with the stub rasteriser, in Node, time, process
|
||||
* RSS growth and file size (E2: ≤ R3 + 5 % on the O2 runs). The Rust side runs through the
|
||||
* proofs build; the TypeScript side is `@faunosteo/pdf`'s `exportReportArchive`. Numbers
|
||||
* printed for RUST.md §10.7. The engine and this test leave with R4.8.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import {
|
||||
exportReportArchive,
|
||||
readAttachedDocument,
|
||||
readReportArchive,
|
||||
type ExportInput,
|
||||
} from '@faunosteo/pdf'
|
||||
|
||||
import { loadProofModule } from '../src/node'
|
||||
import { ReportMigrationMapSchema } from './n-1/domain'
|
||||
|
||||
const ROOT = fileURLToPath(new URL('../../../', import.meta.url))
|
||||
const FIXTURES = join(ROOT, 'apps/app/tests/fixtures')
|
||||
const ONE_PX_PNG = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
|
||||
'base64',
|
||||
)
|
||||
const TWO_BY_ONE_PNG = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7QOjdAAAAD0lEQVR4nGPYEWX///9/AA0PBE/1T7nxAAAAAElFTkSuQmCC',
|
||||
'base64',
|
||||
)
|
||||
const FIXED_EXPORTED_AT = new Date('2026-10-11T12:00:00.000Z')
|
||||
|
||||
type Report = ExportInput['report']
|
||||
|
||||
interface Envelope {
|
||||
report: Report
|
||||
sheetSnapshot: ExportInput['sheet']
|
||||
branding: ExportInput['branding']
|
||||
labels: ExportInput['labels']
|
||||
locale: 'fr' | 'en'
|
||||
exportedAt: string
|
||||
}
|
||||
|
||||
function rastersFor(report: Report, png: Buffer): string {
|
||||
const seen = new Set<string>()
|
||||
const views: Array<{ observationId: string; viewId: string; png: string }> =
|
||||
[]
|
||||
for (const observation of report.observations) {
|
||||
for (const zone of observation.zones) {
|
||||
const key = `${observation.id}\u0000${zone.viewId}`
|
||||
if (seen.has(key)) continue
|
||||
seen.add(key)
|
||||
views.push({
|
||||
observationId: observation.id,
|
||||
viewId: zone.viewId,
|
||||
png: png.toString('base64'),
|
||||
})
|
||||
}
|
||||
}
|
||||
const logo = png.toString('base64')
|
||||
return JSON.stringify({
|
||||
headerLogo: logo,
|
||||
footerLogo: logo,
|
||||
poweredBy: logo,
|
||||
partner: logo,
|
||||
views,
|
||||
})
|
||||
}
|
||||
|
||||
function migrationMap() {
|
||||
return ReportMigrationMapSchema.parse(
|
||||
JSON.parse(
|
||||
readFileSync(
|
||||
join(
|
||||
ROOT,
|
||||
'supabase/seed/anatomical-sheets/equine/draft/report-migration-map.json',
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
describe('R4 writer under the TypeScript engine (same inputs, Node)', () => {
|
||||
it('the engine reads every R4 PDF of the O2 runs back as it reads the R3 one; E2 size', async () => {
|
||||
const proofs = await loadProofModule()
|
||||
const map = migrationMap()
|
||||
for (const report of ['demo', 'v2full', 'v2unresolved']) {
|
||||
for (const locale of ['fr', 'en']) {
|
||||
for (const mode of ['nologos', 'logos']) {
|
||||
const name = `${report}.${locale}.${mode}`
|
||||
const r3 = new Uint8Array(
|
||||
readFileSync(join(FIXTURES, `pdf/r3/${name}.pdf`)),
|
||||
)
|
||||
const envelope = (await readAttachedDocument(r3)) as Envelope
|
||||
const png = mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG
|
||||
const pdf = proofs.export_pdf_for_test(
|
||||
JSON.stringify(envelope),
|
||||
rastersFor(envelope.report, png),
|
||||
)
|
||||
expect(await readReportArchive(pdf, map), name).toEqual(
|
||||
await readReportArchive(r3, map),
|
||||
)
|
||||
expect(pdf.byteLength, `${name}: size`).toBeLessThanOrEqual(
|
||||
Math.ceil(r3.byteLength * 1.05),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('costs less than the engine on demo, L and CAP with the stub rasters (printed)', async () => {
|
||||
const proofs = await loadProofModule()
|
||||
const map = migrationMap()
|
||||
const demo = (await readAttachedDocument(
|
||||
new Uint8Array(readFileSync(join(FIXTURES, 'pdf/r3/demo.fr.logos.pdf'))),
|
||||
)) as Envelope
|
||||
const rows = [
|
||||
'| Report | TS ms | TS RSS MiB | TS bytes | Rust ms | Rust RSS MiB | Rust bytes |',
|
||||
'|---|---|---|---|---|---|---|',
|
||||
]
|
||||
for (const name of ['demo', 'L', 'CAP']) {
|
||||
const report: Report =
|
||||
name === 'demo'
|
||||
? demo.report
|
||||
: JSON.parse(
|
||||
readFileSync(join(FIXTURES, `r4/reports/${name}.json`), 'utf8'),
|
||||
)
|
||||
if (name !== 'demo') report.sheet = demo.report.sheet
|
||||
let rss = process.memoryUsage().rss
|
||||
let started = performance.now()
|
||||
const ts = await exportReportArchive({
|
||||
report,
|
||||
sheet: demo.sheetSnapshot,
|
||||
branding: demo.branding,
|
||||
labels: demo.labels,
|
||||
locale: 'fr',
|
||||
rasterizer: async () => new Uint8Array(TWO_BY_ONE_PNG),
|
||||
exportedAt: FIXED_EXPORTED_AT,
|
||||
})
|
||||
const tsMs = performance.now() - started
|
||||
const tsRss = (process.memoryUsage().rss - rss) / 1024 / 1024
|
||||
const input = JSON.stringify({
|
||||
...demo,
|
||||
report,
|
||||
locale: 'fr',
|
||||
exportedAt: FIXED_EXPORTED_AT.toISOString(),
|
||||
})
|
||||
rss = process.memoryUsage().rss
|
||||
started = performance.now()
|
||||
const rust = proofs.export_pdf_for_test(
|
||||
input,
|
||||
rastersFor(report, TWO_BY_ONE_PNG),
|
||||
)
|
||||
const rustMs = performance.now() - started
|
||||
const rustRss = (process.memoryUsage().rss - rss) / 1024 / 1024
|
||||
rows.push(
|
||||
`| ${name} | ${tsMs.toFixed(0)} | ${tsRss.toFixed(1)} | ${ts.pdf.byteLength} | ${rustMs.toFixed(0)} | ${rustRss.toFixed(1)} | ${rust.byteLength} |`,
|
||||
)
|
||||
expect(
|
||||
(await readReportArchive(rust, map)).report.observations.length,
|
||||
).toBe(report.observations.length)
|
||||
expect(rustMs).toBeLessThan(tsMs)
|
||||
}
|
||||
console.info(
|
||||
`[core-wasm] R4 writer vs TS engine (Node, stub rasters)\n${rows.join('\n')}`,
|
||||
)
|
||||
}, 300_000)
|
||||
})
|
||||
@@ -1,48 +0,0 @@
|
||||
import globals from 'globals'
|
||||
import tseslint from 'typescript-eslint'
|
||||
|
||||
/**
|
||||
* The engine must run without a browser and without Node-only APIs
|
||||
* (STEP6 §3.3): the restricted globals and imports apply to `src/**` only,
|
||||
* tests may read fixtures with node:fs.
|
||||
*/
|
||||
const BROWSER_OR_NODE_GLOBALS = [
|
||||
'fetch',
|
||||
'window',
|
||||
'document',
|
||||
'Image',
|
||||
'DOMParser',
|
||||
'XMLSerializer',
|
||||
'navigator',
|
||||
'Buffer',
|
||||
'process',
|
||||
'require',
|
||||
]
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['node_modules/**'] },
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
extends: [...tseslint.configs.recommended],
|
||||
languageOptions: {
|
||||
globals: { ...globals.node, ...globals.es2022 },
|
||||
},
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'warn',
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'error',
|
||||
{ argsIgnorePattern: '^_' },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['src/**/*.ts'],
|
||||
rules: {
|
||||
'no-restricted-globals': ['error', ...BROWSER_OR_NODE_GLOBALS],
|
||||
'no-restricted-imports': [
|
||||
'error',
|
||||
{ patterns: ['@/*', 'react*', 'node:*'] },
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -1,37 +0,0 @@
|
||||
{
|
||||
"name": "@faunosteo/pdf",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Faunosteo PDF engine: exports a report archive (pages + envelope attachment) from explicit inputs and reads an archive back, without a browser",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "vitest",
|
||||
"test:run": "vitest run",
|
||||
"lint": "eslint . --max-warnings 0",
|
||||
"build": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@faunosteo/anatomy": "workspace:*",
|
||||
"@faunosteo/domain": "workspace:*",
|
||||
"@pdf-lib/standard-fonts": "^1.0.0",
|
||||
"@xmldom/xmldom": "^0.9.8",
|
||||
"pdf-lib": "^1.17.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@pdf-lib/upng": "^1.0.1",
|
||||
"@resvg/resvg-js": "^2.6.2",
|
||||
"@types/node": "^20.19.41",
|
||||
"eslint": "^9.17.0",
|
||||
"globals": "^15.14.0",
|
||||
"typescript": "^5.7.2",
|
||||
"typescript-eslint": "^8.19.0",
|
||||
"vitest": "^3.2.7"
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
/**
|
||||
* Hard ceiling on an attachment, inflated or not: a report archive weighs a
|
||||
* few hundred KB; anything bigger is a decompression bomb or corruption.
|
||||
*/
|
||||
export const MAX_ATTACHMENT_BYTES = 16 * 1024 * 1024
|
||||
|
||||
/**
|
||||
* Compressed bytes handed to the inflater per write. Chromium's
|
||||
* `DecompressionStream` inflates everything it has been given before the
|
||||
* consumer reads it, so a stream written whole lets a bomb inflate gigabytes
|
||||
* before `reader.cancel()` lands (measured: +2.2 GB RSS on a 4 MB / 4 GiB
|
||||
* bomb). One awaited slice at a time keeps that read-ahead to what 16 KiB
|
||||
* can inflate (about 16 MiB).
|
||||
*/
|
||||
const WRITE_SLICE_BYTES = 16 * 1024
|
||||
|
||||
type Writer = WritableStreamDefaultWriter<Uint8Array<ArrayBuffer>>
|
||||
type Reader = ReadableStreamDefaultReader<Uint8Array>
|
||||
|
||||
function concat(chunks: Uint8Array[], total: number): Uint8Array {
|
||||
const out = new Uint8Array(total)
|
||||
let offset = 0
|
||||
for (const chunk of chunks) {
|
||||
out.set(chunk, offset)
|
||||
offset += chunk.byteLength
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Feeds the inflater one slice per awaited write, then closes it. */
|
||||
async function feedSlices(writer: Writer, bytes: Uint8Array): Promise<void> {
|
||||
// The cast compiles under both the engine (node) and the app (DOM) libs.
|
||||
const source = bytes as Uint8Array<ArrayBuffer>
|
||||
for (let at = 0; at < source.byteLength; at += WRITE_SLICE_BYTES) {
|
||||
await writer.write(source.subarray(at, at + WRITE_SLICE_BYTES))
|
||||
}
|
||||
await writer.close()
|
||||
}
|
||||
|
||||
/** Collects the inflated chunks; null as soon as their total exceeds `limit`. */
|
||||
async function drainUnder(
|
||||
reader: Reader,
|
||||
limit: number,
|
||||
): Promise<Uint8Array | null> {
|
||||
const chunks: Uint8Array[] = []
|
||||
let total = 0
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) return concat(chunks, total)
|
||||
total += value.byteLength
|
||||
if (total > limit) return null
|
||||
chunks.push(value)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* FlateDecode (zlib framing) under `limit`, the attachment cap by default.
|
||||
* Null on any failure (truncated or corrupt stream, trailing junk, bad
|
||||
* checksum) or as soon as the output exceeds the limit. The feed and the
|
||||
* drain run concurrently; over the limit both sides are torn down, which
|
||||
* also rejects the feed's pending write.
|
||||
*/
|
||||
export async function inflateFlate(
|
||||
bytes: Uint8Array,
|
||||
limit: number = MAX_ATTACHMENT_BYTES,
|
||||
): Promise<Uint8Array | null> {
|
||||
if (typeof DecompressionStream === 'undefined') return null
|
||||
const inflater = new DecompressionStream('deflate')
|
||||
const writer = inflater.writable.getWriter()
|
||||
const reader = inflater.readable.getReader()
|
||||
// A stream error surfaces on the drain; the feed's own rejection is noise.
|
||||
const fed = feedSlices(writer, bytes)
|
||||
fed.catch(() => undefined)
|
||||
try {
|
||||
const out = await drainUnder(reader, limit)
|
||||
if (out === null) {
|
||||
await Promise.allSettled([reader.cancel(), writer.abort()])
|
||||
}
|
||||
return out
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { ArchiveReadError } from '../errors'
|
||||
import {
|
||||
ARCHIVE_STAMP,
|
||||
hasPdfHeader,
|
||||
locateAttachment,
|
||||
MAX_PDF_BYTES,
|
||||
} from './scan'
|
||||
|
||||
/**
|
||||
* The raw JSON a Faunosteo PDF carries, read from the bytes alone (BLK-009):
|
||||
* no PDF object graph is parsed, so no object stream is ever inflated. pdf-lib
|
||||
* stays on the export side.
|
||||
*/
|
||||
|
||||
export { ATTACHMENT_NAME_PREFIX } from './scan'
|
||||
export const PDF_KEYWORD = `${ARCHIVE_STAMP}/1`
|
||||
|
||||
/** Size cap first, then the `%PDF-` header: anything else is `invalid_pdf`. */
|
||||
function assertPdfBytes(bytes: Uint8Array): void {
|
||||
if (bytes.byteLength > MAX_PDF_BYTES || !hasPdfHeader(bytes)) {
|
||||
throw new ArchiveReadError('invalid_pdf')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The raw JSON carried by the PDF, whatever its shape (bare report of any
|
||||
* version or archive envelope), before any validation: what the archive
|
||||
* check tool shows next to the read result. Throws ArchiveReadError
|
||||
* (`invalid_pdf`, `no_attachment`, `attachment_stripped`).
|
||||
*/
|
||||
export async function readAttachedDocument(
|
||||
bytes: Uint8Array,
|
||||
): Promise<unknown> {
|
||||
assertPdfBytes(bytes)
|
||||
return (await locateAttachment(bytes)).data
|
||||
}
|
||||
@@ -1,549 +0,0 @@
|
||||
import { ArchiveReadError } from '../errors'
|
||||
import { inflateFlate, MAX_ATTACHMENT_BYTES } from './inflate'
|
||||
|
||||
/**
|
||||
* Locates the Faunosteo attachment by scanning the PDF bytes (BLK-009): a
|
||||
* stream object can never live inside an object stream, so every
|
||||
* `/Type /EmbeddedFile` dictionary and its data are in clear in the file.
|
||||
* Nothing here parses the object graph, the xref or an `/ObjStm`, so the
|
||||
* only inflation on the import path is the capped one of `inflateFlate`.
|
||||
* The scanner never throws on garbage: it returns fewer candidates.
|
||||
*/
|
||||
|
||||
/** A Faunosteo PDF weighs a few hundred KB; anything larger is not one. */
|
||||
export const MAX_PDF_BYTES = 50 * 1024 * 1024
|
||||
|
||||
export const ATTACHMENT_NAME_PREFIX = 'osteo-report'
|
||||
/** The keyword stamp every archive carries (`faunosteo-archive/<n>`). */
|
||||
export const ARCHIVE_STAMP = 'faunosteo-archive'
|
||||
|
||||
/** Candidates beyond this count are ignored: a crafted file cannot make the reader loop. */
|
||||
const MAX_CANDIDATES = 32
|
||||
/** A stream or Filespec dictionary is small; a longer one is skipped. */
|
||||
const MAX_DICT_BYTES = 4096
|
||||
/** Window read before a dictionary for its `n 0 obj` header. */
|
||||
const HEADER_WINDOW = 48
|
||||
|
||||
export interface EmbeddedFileCandidate {
|
||||
/** First byte of the stream data. */
|
||||
offset: number
|
||||
/** Byte count of the stream data (declared, or measured to `endstream`). */
|
||||
length: number
|
||||
filter: 'FlateDecode' | null
|
||||
/** From a visible `/Filespec` whose `/EF /F` points at this stream. */
|
||||
name: string | null
|
||||
}
|
||||
|
||||
const encode = (text: string): Uint8Array =>
|
||||
Uint8Array.from(text, (c) => c.charCodeAt(0))
|
||||
|
||||
const TYPE = encode('/Type')
|
||||
const EMBEDDED_FILE = encode('/EmbeddedFile')
|
||||
const FILESPEC = encode('/Filespec')
|
||||
const KEYWORDS = encode('/Keywords')
|
||||
const STREAM = encode('stream')
|
||||
const ENDSTREAM = encode('endstream')
|
||||
const PDF_HEADER = encode('%PDF-')
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Byte helpers: every loop is bounded by `end` (at most MAX_PDF_BYTES)
|
||||
|
||||
function isWhitespace(byte: number): boolean {
|
||||
return (
|
||||
byte === 0x20 ||
|
||||
byte === 0x0a ||
|
||||
byte === 0x0d ||
|
||||
byte === 0x09 ||
|
||||
byte === 0x0c ||
|
||||
byte === 0x00
|
||||
)
|
||||
}
|
||||
|
||||
/** PDF delimiters and whitespace end a name token. */
|
||||
function isDelimiter(byte: number): boolean {
|
||||
return isWhitespace(byte) || '()<>[]{}/%'.includes(String.fromCharCode(byte))
|
||||
}
|
||||
|
||||
/** Naive forward search; the needle's first byte is the fast reject. */
|
||||
function indexOf(
|
||||
bytes: Uint8Array,
|
||||
needle: Uint8Array,
|
||||
from: number,
|
||||
end: number,
|
||||
): number {
|
||||
const last = end - needle.length
|
||||
const first = needle[0]!
|
||||
for (let i = Math.max(from, 0); i <= last; i += 1) {
|
||||
if (bytes[i] !== first) continue
|
||||
let j = 1
|
||||
while (j < needle.length && bytes[i + j] === needle[j]) j += 1
|
||||
if (j === needle.length) return i
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
function skipWhitespace(bytes: Uint8Array, from: number, end: number): number {
|
||||
let i = from
|
||||
while (i < end && isWhitespace(bytes[i]!)) i += 1
|
||||
return i
|
||||
}
|
||||
|
||||
/** Latin-1 view of a small window (never the whole file). */
|
||||
function latin1(bytes: Uint8Array, start: number, end: number): string {
|
||||
let out = ''
|
||||
for (let i = start; i < end; i += 1) out += String.fromCharCode(bytes[i]!)
|
||||
return out
|
||||
}
|
||||
|
||||
/** UTF-16BE with BOM (how pdf-lib writes text strings) or Latin-1 bytes. */
|
||||
function decodeTextBytes(raw: number[]): string {
|
||||
if (raw.length >= 2 && raw[0] === 0xfe && raw[1] === 0xff) {
|
||||
let out = ''
|
||||
for (let i = 2; i + 1 < raw.length; i += 2) {
|
||||
out += String.fromCharCode((raw[i]! << 8) | raw[i + 1]!)
|
||||
}
|
||||
return out
|
||||
}
|
||||
return String.fromCharCode(...raw)
|
||||
}
|
||||
|
||||
/** A `(literal)` or `<hex>` string token as text; null for anything else. */
|
||||
export function decodePdfString(token: string): string | null {
|
||||
if (token.startsWith('<') && token.endsWith('>')) {
|
||||
const hex = token.slice(1, -1).replace(/[^0-9a-fA-F]/g, '')
|
||||
const raw: number[] = []
|
||||
for (let i = 0; i + 1 < hex.length; i += 2) {
|
||||
raw.push(parseInt(hex.slice(i, i + 2), 16))
|
||||
}
|
||||
return decodeTextBytes(raw)
|
||||
}
|
||||
if (token.startsWith('(') && token.endsWith(')')) {
|
||||
const body = token.slice(1, -1).replace(/\\([()\\])/g, '$1')
|
||||
return decodeTextBytes(Array.from(body, (c) => c.charCodeAt(0) & 0xff))
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Dictionaries: `/Type /Name` matches and their `<< … >>` bounds
|
||||
|
||||
/** Every `/Type /<name>` (space optional) whose name ends on a delimiter. */
|
||||
function findTypedDicts(
|
||||
bytes: Uint8Array,
|
||||
name: Uint8Array,
|
||||
end: number,
|
||||
): number[] {
|
||||
const hits: number[] = []
|
||||
let from = 0
|
||||
while (hits.length < MAX_CANDIDATES) {
|
||||
const at = indexOf(bytes, name, from, end)
|
||||
if (at < 0) break
|
||||
from = at + name.length
|
||||
const after = at + name.length
|
||||
if (after < end && !isDelimiter(bytes[after]!)) continue
|
||||
let before = at
|
||||
while (before > 0 && isWhitespace(bytes[before - 1]!)) before -= 1
|
||||
const typeAt = before - TYPE.length
|
||||
if (typeAt >= 0 && indexOf(bytes, TYPE, typeAt, before) === typeAt) {
|
||||
hits.push(typeAt)
|
||||
}
|
||||
}
|
||||
return hits
|
||||
}
|
||||
|
||||
/** Index of the `<<` opening the dictionary holding `pos` (nested dicts skipped); -1 when none. */
|
||||
function dictStart(bytes: Uint8Array, pos: number): number {
|
||||
const floor = Math.max(0, pos - MAX_DICT_BYTES)
|
||||
let depth = 0
|
||||
let i = pos
|
||||
while (i - 2 >= floor) {
|
||||
const pair = (bytes[i - 2]! << 8) | bytes[i - 1]!
|
||||
if (pair === 0x3e3e)
|
||||
depth += 1 // >>
|
||||
else if (pair === 0x3c3c) {
|
||||
if (depth === 0) return i - 2
|
||||
depth -= 1
|
||||
}
|
||||
i -= pair === 0x3e3e || pair === 0x3c3c ? 2 : 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
/** Index just past the `>>` closing the dictionary opened at `start`; -1 when none. */
|
||||
function dictEnd(bytes: Uint8Array, start: number, end: number): number {
|
||||
const limit = Math.min(end, start + MAX_DICT_BYTES)
|
||||
let depth = 0
|
||||
let i = start
|
||||
while (i + 1 < limit) {
|
||||
const pair = (bytes[i]! << 8) | bytes[i + 1]!
|
||||
if (pair === 0x3c3c) depth += 1
|
||||
else if (pair === 0x3e3e) {
|
||||
depth -= 1
|
||||
if (depth === 0) return i + 2
|
||||
}
|
||||
i += pair === 0x3c3c || pair === 0x3e3e ? 2 : 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
interface DictSpan {
|
||||
start: number
|
||||
end: number
|
||||
text: string
|
||||
objectNumber: number | null
|
||||
}
|
||||
|
||||
/** The dictionary around a `/Type` match, its text and the `n 0 obj` header before it. */
|
||||
function dictAround(
|
||||
bytes: Uint8Array,
|
||||
pos: number,
|
||||
end: number,
|
||||
): DictSpan | null {
|
||||
const start = dictStart(bytes, pos)
|
||||
if (start < 0) return null
|
||||
const close = dictEnd(bytes, start, end)
|
||||
if (close < 0) return null
|
||||
const header = latin1(bytes, Math.max(0, start - HEADER_WINDOW), start)
|
||||
const match = /(\d{1,10})\s+\d{1,10}\s+obj\s*$/.exec(header)
|
||||
return {
|
||||
start,
|
||||
end: close,
|
||||
text: latin1(bytes, start, close),
|
||||
objectNumber: match ? Number(match[1]) : null,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Stream data bounds
|
||||
|
||||
/** Data offset after `stream` + `\r\n` or `\n`; -1 when the keyword is missing. */
|
||||
function streamDataOffset(
|
||||
bytes: Uint8Array,
|
||||
dictClose: number,
|
||||
end: number,
|
||||
): number {
|
||||
const at = skipWhitespace(bytes, dictClose, end)
|
||||
if (indexOf(bytes, STREAM, at, Math.min(end, at + STREAM.length)) !== at) {
|
||||
return -1
|
||||
}
|
||||
let i = at + STREAM.length
|
||||
if (bytes[i] === 0x0d) i += 1
|
||||
if (bytes[i] !== 0x0a) return -1
|
||||
return i + 1
|
||||
}
|
||||
|
||||
/** A direct `/Length N` (never an `N 0 R` reference), when it lands on `endstream`. */
|
||||
function declaredLength(
|
||||
bytes: Uint8Array,
|
||||
dict: string,
|
||||
offset: number,
|
||||
end: number,
|
||||
): number | null {
|
||||
const match = /\/Length\s+(\d{1,10})(?!\d)(?!\s+\d+\s+R)/.exec(dict)
|
||||
if (!match) return null
|
||||
const length = Number(match[1])
|
||||
if (offset + length > end) return null
|
||||
const tail = skipWhitespace(bytes, offset + length, end)
|
||||
const found = indexOf(
|
||||
bytes,
|
||||
ENDSTREAM,
|
||||
tail,
|
||||
Math.min(end, tail + ENDSTREAM.length),
|
||||
)
|
||||
return found === tail ? length : null
|
||||
}
|
||||
|
||||
/** Farthest `endstream` worth finding: a longer candidate is refused anyway. */
|
||||
const MEASURE_WINDOW = MAX_ATTACHMENT_BYTES + 16
|
||||
|
||||
/** Index of the first `endstream` at or after `offset`, within MEASURE_WINDOW; -1 when none. */
|
||||
type EndstreamFinder = (offset: number) => number
|
||||
|
||||
/**
|
||||
* Searches `endstream` once over the file instead of once per candidate:
|
||||
* candidates come in offset order (`embeddedStreamHeads` sorts them), so the
|
||||
* last hit serves every offset before it and a miss clears the bytes it
|
||||
* covered for the next search. An offset out of order (never produced since
|
||||
* the sort) restarts the search: a defensive fallback, never the normal path.
|
||||
*/
|
||||
function endstreamFinder(bytes: Uint8Array, end: number): EndstreamFinder {
|
||||
let lastHit = -1
|
||||
let clearedTo = 0
|
||||
let lastOffset = 0
|
||||
return (offset) => {
|
||||
if (offset < lastOffset) {
|
||||
lastHit = -1
|
||||
clearedTo = 0
|
||||
}
|
||||
lastOffset = offset
|
||||
if (lastHit >= offset) return lastHit
|
||||
const limit = Math.min(end, offset + MEASURE_WINDOW)
|
||||
const at = indexOf(bytes, ENDSTREAM, Math.max(offset, clearedTo), limit)
|
||||
if (at >= 0) lastHit = at
|
||||
else clearedTo = Math.max(clearedTo, limit - ENDSTREAM.length + 1)
|
||||
return at
|
||||
}
|
||||
}
|
||||
|
||||
/** Fallback for an indirect or wrong `/Length`: up to `endstream`, the EOL before it dropped. */
|
||||
function measuredLength(
|
||||
bytes: Uint8Array,
|
||||
offset: number,
|
||||
findEndstream: EndstreamFinder,
|
||||
): number | null {
|
||||
const at = findEndstream(offset)
|
||||
if (at < 0) return null
|
||||
let stop = at
|
||||
if (stop > offset && bytes[stop - 1] === 0x0a) stop -= 1
|
||||
if (stop > offset && bytes[stop - 1] === 0x0d) stop -= 1
|
||||
return stop - offset
|
||||
}
|
||||
|
||||
function filterOf(dict: string): EmbeddedFileCandidate['filter'] {
|
||||
return /\/Filter\s*(\[\s*)?\/FlateDecode\b/.test(dict) ? 'FlateDecode' : null
|
||||
}
|
||||
|
||||
/** An `EmbeddedFile` dictionary followed by `stream`, before its data is measured. */
|
||||
interface StreamHead {
|
||||
dict: DictSpan
|
||||
offset: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Every `/Type /EmbeddedFile` dictionary followed by `stream`, sorted by data
|
||||
* offset (stable). Nested dictionaries list outermost first, so their offsets
|
||||
* come out descending and each one would reset the `endstream` finder: 32 of
|
||||
* them rescanned 16 MiB each (audit of 3a6e926, finding 1). Sorted, the
|
||||
* finder never restarts.
|
||||
*/
|
||||
function embeddedStreamHeads(bytes: Uint8Array, end: number): StreamHead[] {
|
||||
const heads: StreamHead[] = []
|
||||
for (const pos of findTypedDicts(bytes, EMBEDDED_FILE, end)) {
|
||||
const dict = dictAround(bytes, pos, end)
|
||||
if (!dict) continue
|
||||
const offset = streamDataOffset(bytes, dict.end, end)
|
||||
if (offset < 0) continue
|
||||
heads.push({ dict, offset })
|
||||
}
|
||||
return heads.sort((a, b) => a.offset - b.offset)
|
||||
}
|
||||
|
||||
function candidateOf(
|
||||
bytes: Uint8Array,
|
||||
{ dict, offset }: StreamHead,
|
||||
end: number,
|
||||
findEndstream: EndstreamFinder,
|
||||
): Omit<EmbeddedFileCandidate, 'name'> | null {
|
||||
const length =
|
||||
declaredLength(bytes, dict.text, offset, end) ??
|
||||
measuredLength(bytes, offset, findEndstream)
|
||||
if (length === null) return null
|
||||
return { offset, length, filter: filterOf(dict.text) }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Filespec names and the keyword stamp
|
||||
|
||||
const STRING_TOKEN = String.raw`\((?:\\.|[^\\)])*\)|<[0-9a-fA-F\s]*>`
|
||||
|
||||
/** `/F` (else `/UF`) of a Filespec dictionary, the `/EF` sub-dictionary set aside. */
|
||||
function filespecName(dict: string): string | null {
|
||||
const withoutEf = dict.replace(/\/EF\s*<<[\s\S]*?>>/, '')
|
||||
const f = new RegExp(String.raw`/F\s*(${STRING_TOKEN})`).exec(withoutEf)
|
||||
const uf = new RegExp(String.raw`/UF\s*(${STRING_TOKEN})`).exec(withoutEf)
|
||||
const token = f?.[1] ?? uf?.[1]
|
||||
return token ? decodePdfString(token) : null
|
||||
}
|
||||
|
||||
/** Object number of the stream a Filespec's `/EF << /F n 0 R >>` points at. */
|
||||
function filespecStreamObject(dict: string): number | null {
|
||||
const ef = /\/EF\s*<<([\s\S]*?)>>/.exec(dict)
|
||||
const ref = ef ? /\/F\s+(\d{1,10})\s+\d{1,10}\s+R/.exec(ef[1]!) : null
|
||||
return ref ? Number(ref[1]) : null
|
||||
}
|
||||
|
||||
/** Stream object number → file name, from every Filespec dictionary in clear. */
|
||||
function filespecNames(bytes: Uint8Array, end: number): Map<number, string> {
|
||||
const names = new Map<number, string>()
|
||||
for (const pos of findTypedDicts(bytes, FILESPEC, end)) {
|
||||
const dict = dictAround(bytes, pos, end)
|
||||
if (!dict) continue
|
||||
const target = filespecStreamObject(dict.text)
|
||||
const name = filespecName(dict.text)
|
||||
if (target !== null && name !== null && !names.has(target)) {
|
||||
names.set(target, name)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
/** The string token right after a `/Keywords` key, as text. */
|
||||
function keywordsAt(
|
||||
bytes: Uint8Array,
|
||||
keyAt: number,
|
||||
end: number,
|
||||
): string | null {
|
||||
const start = skipWhitespace(bytes, keyAt + KEYWORDS.length, end)
|
||||
const limit = Math.min(end, start + MAX_DICT_BYTES)
|
||||
const window = latin1(bytes, start, limit)
|
||||
const token = new RegExp(`^(?:${STRING_TOKEN})`).exec(window)
|
||||
return token ? decodePdfString(token[0]) : null
|
||||
}
|
||||
|
||||
/** True when a visible `/Keywords` string carries the archive stamp. */
|
||||
export function hasArchiveStamp(bytes: Uint8Array): boolean {
|
||||
const end = Math.min(bytes.byteLength, MAX_PDF_BYTES)
|
||||
let from = 0
|
||||
for (let n = 0; n < MAX_CANDIDATES; n += 1) {
|
||||
const at = indexOf(bytes, KEYWORDS, from, end)
|
||||
if (at < 0) return false
|
||||
from = at + KEYWORDS.length
|
||||
if (isDelimiter(bytes[from] ?? 0x20)) {
|
||||
if (keywordsAt(bytes, at, end)?.includes(ARCHIVE_STAMP)) return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** `%PDF-` within the first KiB, as viewers accept it. */
|
||||
export function hasPdfHeader(bytes: Uint8Array): boolean {
|
||||
return indexOf(bytes, PDF_HEADER, 0, Math.min(bytes.byteLength, 1024)) >= 0
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public scan
|
||||
|
||||
/**
|
||||
* Every `/Type /EmbeddedFile` stream of the file, named when its Filespec
|
||||
* is in clear (export without object streams); `osteo-report*` names first,
|
||||
* then data offset order. At most MAX_CANDIDATES, within MAX_PDF_BYTES.
|
||||
*/
|
||||
export function findEmbeddedFiles(bytes: Uint8Array): EmbeddedFileCandidate[] {
|
||||
const end = Math.min(bytes.byteLength, MAX_PDF_BYTES)
|
||||
const names = filespecNames(bytes, end)
|
||||
const findEndstream = endstreamFinder(bytes, end)
|
||||
const found: EmbeddedFileCandidate[] = []
|
||||
for (const head of embeddedStreamHeads(bytes, end)) {
|
||||
const candidate = candidateOf(bytes, head, end, findEndstream)
|
||||
if (!candidate) continue
|
||||
const { objectNumber } = head.dict
|
||||
const name =
|
||||
objectNumber === null ? null : (names.get(objectNumber) ?? null)
|
||||
found.push({ ...candidate, name })
|
||||
}
|
||||
const named = (c: EmbeddedFileCandidate) =>
|
||||
c.name?.startsWith(ATTACHMENT_NAME_PREFIX) ? 0 : 1
|
||||
return found.sort((a, b) => named(a) - named(b))
|
||||
}
|
||||
|
||||
/** Raw or inflated stream data under `budget`; null when unusable or inflating past it. */
|
||||
async function candidateBytes(
|
||||
bytes: Uint8Array,
|
||||
candidate: EmbeddedFileCandidate,
|
||||
budget: number,
|
||||
): Promise<Uint8Array | null> {
|
||||
const data = bytes.subarray(
|
||||
candidate.offset,
|
||||
candidate.offset + candidate.length,
|
||||
)
|
||||
if (candidate.filter === null) return data
|
||||
return inflateFlate(data, budget)
|
||||
}
|
||||
|
||||
/** `{` first, past an optional UTF-8 BOM and JSON whitespace: the only shape a version lives in. */
|
||||
function startsJsonObject(data: Uint8Array): boolean {
|
||||
let i = 0
|
||||
if (data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) i = 3
|
||||
while (
|
||||
i < data.byteLength &&
|
||||
' \t\n\r'.includes(String.fromCharCode(data[i]!))
|
||||
) {
|
||||
i += 1
|
||||
}
|
||||
return data[i] === 0x7b
|
||||
}
|
||||
|
||||
/** The report and its envelope nest under 16 levels; deeper is not ours. */
|
||||
const MAX_JSON_DEPTH = 64
|
||||
|
||||
/**
|
||||
* Linear bracket-depth count over the raw bytes before `JSON.parse`: a 16 MiB
|
||||
* document nested thousands deep costs the parser a second and a gigabyte
|
||||
* (audit of 3a6e926, finding 3). String literals are skipped, their escapes
|
||||
* honoured; UTF-8 continuation bytes never collide with the ASCII tokens.
|
||||
*/
|
||||
function withinJsonDepth(data: Uint8Array): boolean {
|
||||
let depth = 0
|
||||
let inString = false
|
||||
for (let i = 0; i < data.byteLength; i += 1) {
|
||||
const byte = data[i]!
|
||||
if (inString) {
|
||||
if (byte === 0x5c) i += 1 // backslash: the escaped byte is skipped
|
||||
else if (byte === 0x22) inString = false
|
||||
continue
|
||||
}
|
||||
if (byte === 0x22) inString = true
|
||||
else if (byte === 0x7b || byte === 0x5b) {
|
||||
depth += 1
|
||||
if (depth > MAX_JSON_DEPTH) return false
|
||||
} else if (byte === 0x7d || byte === 0x5d) depth -= 1
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** JSON with a numeric `envelopeVersion` or `version`; undefined otherwise. */
|
||||
function parseVersioned(data: Uint8Array): unknown {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(new TextDecoder().decode(data))
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
if (typeof parsed !== 'object' || parsed === null) return undefined
|
||||
const record = parsed as Record<string, unknown>
|
||||
const versioned =
|
||||
typeof record['envelopeVersion'] === 'number' ||
|
||||
typeof record['version'] === 'number'
|
||||
return versioned ? parsed : undefined
|
||||
}
|
||||
|
||||
export interface LocatedAttachment {
|
||||
bytes: Uint8Array
|
||||
data: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* The first candidate whose data is a versioned JSON document, decoded once.
|
||||
* None: `attachment_stripped` when the stamp is visible, else `no_attachment`.
|
||||
* One MAX_ATTACHMENT_BYTES budget of content (raw or inflated) is shared by
|
||||
* every candidate: a candidate that does not fit what is left ends the
|
||||
* search, so at most 16 MiB of candidate content is retained and parsed. A
|
||||
* cancelled inflation is not charged (audit of 3a6e926, finding 2), so up to
|
||||
* MAX_CANDIDATES oversized streams may each cost one capped inflation of CPU
|
||||
* (bounded, no memory retained); charging them would let bombs starve a real
|
||||
* unnamed attachment placed after them.
|
||||
*/
|
||||
export async function locateAttachment(
|
||||
bytes: Uint8Array,
|
||||
): Promise<LocatedAttachment> {
|
||||
let budget = MAX_ATTACHMENT_BYTES
|
||||
for (const candidate of findEmbeddedFiles(bytes)) {
|
||||
if (candidate.length > budget) break
|
||||
const data = await candidateBytes(bytes, candidate, budget)
|
||||
if (!data) continue
|
||||
budget -= data.byteLength
|
||||
if (!startsJsonObject(data) || !withinJsonDepth(data)) continue
|
||||
const parsed = parseVersioned(data)
|
||||
if (parsed !== undefined) return { bytes: data, data: parsed }
|
||||
}
|
||||
throw new ArchiveReadError(
|
||||
hasArchiveStamp(bytes) ? 'attachment_stripped' : 'no_attachment',
|
||||
)
|
||||
}
|
||||
|
||||
/** The attachment's decoded bytes (BLK-009 reader). Throws ArchiveReadError. */
|
||||
export async function readAttachmentBytes(
|
||||
bytes: Uint8Array,
|
||||
): Promise<Uint8Array> {
|
||||
return (await locateAttachment(bytes)).bytes
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import { AFRelationship, type PDFDocument } from 'pdf-lib'
|
||||
|
||||
export const ATTACHMENT_FILENAME = 'osteo-report.json'
|
||||
export const ATTACHMENT_DESCRIPTION = 'Faunosteo report archive v1'
|
||||
|
||||
/** The envelope bytes as a native embedded file; every date is `exportedAt`. */
|
||||
export async function attachEnvelope(
|
||||
pdfDoc: PDFDocument,
|
||||
bytes: Uint8Array,
|
||||
exportedAt: Date,
|
||||
): Promise<void> {
|
||||
await pdfDoc.attach(bytes, ATTACHMENT_FILENAME, {
|
||||
mimeType: 'application/json',
|
||||
description: ATTACHMENT_DESCRIPTION,
|
||||
creationDate: exportedAt,
|
||||
modificationDate: exportedAt,
|
||||
afRelationship: AFRelationship.Data,
|
||||
})
|
||||
}
|
||||
@@ -1,291 +0,0 @@
|
||||
import type { PDFDocument, PDFImage } from 'pdf-lib'
|
||||
import type { Branding, Credit, ImageAsset } from '@faunosteo/domain'
|
||||
import { inflateFlate, MAX_ATTACHMENT_BYTES } from './attachment/inflate'
|
||||
import type { ExportWarning, Rasterizer } from './types'
|
||||
import { renderBrandingSvg } from './svg/view'
|
||||
|
||||
/**
|
||||
* The branding images embedded once per document. A PNG is decoded from
|
||||
* its base64 once its header, chunk list and IDAT stream pass `pngIssue`;
|
||||
* an SVG is sanitised and rasterised at the view width. Each slot fails
|
||||
* alone: the page prints the credit's fallback text instead and the export
|
||||
* reports a `logo_failed` warning.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A logo PNG is at most 4096² pixels and 8192 px a side (STEP6 §15), and
|
||||
* its raw (filtered, uncompressed) scanlines fit the attachment cap, the
|
||||
* most the native inflater is allowed to produce.
|
||||
*/
|
||||
export const PNG_CAPS = {
|
||||
side: 8192,
|
||||
pixels: 4096 * 4096,
|
||||
rawBytes: MAX_ATTACHMENT_BYTES,
|
||||
} as const
|
||||
|
||||
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
|
||||
/** A chunk is length (4), type (4), data (length), CRC (4). */
|
||||
const CHUNK_HEAD = 8
|
||||
const CHUNK_OVERHEAD = 12
|
||||
const IHDR_LENGTH = 13
|
||||
const IHDR_END = PNG_SIGNATURE.length + CHUNK_OVERHEAD + IHDR_LENGTH
|
||||
|
||||
/** The big-endian uint32 a four-letter chunk type reads as. */
|
||||
const chunkType = (name: string): number =>
|
||||
[...name].reduce((acc, char) => acc * 256 + char.charCodeAt(0), 0)
|
||||
|
||||
const IHDR_TYPE = chunkType('IHDR')
|
||||
const IDAT_TYPE = chunkType('IDAT')
|
||||
const IEND_TYPE = chunkType('IEND')
|
||||
/**
|
||||
* The chunk types UPNG reads by fixed offsets or by declared length. A
|
||||
* second IHDR resizes the decoder's buffer, APNG frames are not a logo, and
|
||||
* every text or profile chunk (`tEXt`, `iTXt`, `zTXt`, `iCCP`) is read with
|
||||
* `_bin.nextZero` (`while (data[p] != 0) p++`), which never stops when no
|
||||
* NUL byte follows in the buffer: all of them stay out of the list.
|
||||
*/
|
||||
const ALLOWED_CHUNKS = new Set(
|
||||
[
|
||||
'PLTE',
|
||||
'tRNS',
|
||||
'IDAT',
|
||||
'IEND',
|
||||
'gAMA',
|
||||
'cHRM',
|
||||
'sRGB',
|
||||
'sBIT',
|
||||
'pHYs',
|
||||
'bKGD',
|
||||
].map(chunkType),
|
||||
)
|
||||
|
||||
/** Samples per pixel and the bit depths the PNG spec allows, by colour type. */
|
||||
const CHANNELS: Record<number, number> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }
|
||||
const DEPTHS: Record<number, readonly number[]> = {
|
||||
0: [1, 2, 4, 8, 16],
|
||||
2: [8, 16],
|
||||
3: [1, 2, 4, 8],
|
||||
4: [8, 16],
|
||||
6: [8, 16],
|
||||
}
|
||||
|
||||
export type PngIssue = 'signature' | 'dimensions' | 'ihdr' | 'chunks' | 'idat'
|
||||
|
||||
/** The 13 IHDR fields, read as announced. */
|
||||
interface PngHeader {
|
||||
width: number
|
||||
height: number
|
||||
depth: number
|
||||
colourType: number
|
||||
compression: number
|
||||
filter: number
|
||||
interlace: number
|
||||
}
|
||||
|
||||
export type LogoSlot = Extract<ExportWarning, { kind: 'logo_failed' }>['slot']
|
||||
|
||||
export interface CreditAsset {
|
||||
image: PDFImage | null
|
||||
url: string
|
||||
fallbackText: string
|
||||
}
|
||||
|
||||
export interface BrandingImages {
|
||||
siteUrl: string
|
||||
header: PDFImage | null
|
||||
footer: PDFImage | null
|
||||
poweredBy: CreditAsset | null
|
||||
partner: CreditAsset | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a PNG is refused before UPNG sees it, or null when it may be decoded.
|
||||
* In order: the signature and a first 13-byte IHDR (`signature`); the
|
||||
* announced size under `PNG_CAPS` (`dimensions`); IHDR fields the spec
|
||||
* allows, non-interlaced (`ihdr`); an allowlisted chunk list closed by an
|
||||
* empty `IEND` (`chunks`); an IDAT stream the native inflater accepts and
|
||||
* that yields exactly the raw scanline size (`idat`). UPNG's `inflateRaw`
|
||||
* never checks its input bound, so a truncated or crafted stream makes it
|
||||
* read past the buffer and never return; its bitmap is sized from whatever
|
||||
* IHDR claims; and `nextZero` scans text chunks for a NUL that may be
|
||||
* missing. Each check closes one of those paths.
|
||||
*/
|
||||
export async function pngIssue(bytes: Uint8Array): Promise<PngIssue | null> {
|
||||
if (bytes.byteLength < IHDR_END) return 'signature'
|
||||
if (PNG_SIGNATURE.some((byte, i) => bytes[i] !== byte)) return 'signature'
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
||||
if (view.getUint32(8) !== IHDR_LENGTH) return 'signature'
|
||||
if (view.getUint32(12) !== IHDR_TYPE) return 'signature'
|
||||
const header = readHeader(view)
|
||||
const headerProblem = headerIssue(header)
|
||||
if (headerProblem) return headerProblem
|
||||
const rawSize = expectedRawSize(header)
|
||||
if (rawSize > PNG_CAPS.rawBytes) return 'dimensions'
|
||||
return chunkListIssue(view) ?? idatIssue(view, rawSize)
|
||||
}
|
||||
|
||||
function readHeader(view: DataView): PngHeader {
|
||||
return {
|
||||
width: view.getUint32(16),
|
||||
height: view.getUint32(20),
|
||||
depth: view.getUint8(24),
|
||||
colourType: view.getUint8(25),
|
||||
compression: view.getUint8(26),
|
||||
filter: view.getUint8(27),
|
||||
interlace: view.getUint8(28),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The size budget, then the IHDR fields: a side of 0 would give the page
|
||||
* stream an Infinity scale, an unknown colour type or depth (255 at 4096²
|
||||
* costs seconds of CPU in UPNG) has no raw size to check against, and an
|
||||
* interlaced image is refused outright: no archived logo is interlaced and
|
||||
* the Adam7 pass sizes are not worth computing here.
|
||||
*/
|
||||
function headerIssue(header: PngHeader): PngIssue | null {
|
||||
const { width, height, depth, colourType } = header
|
||||
if (width < 1 || height < 1) return 'dimensions'
|
||||
if (width > PNG_CAPS.side || height > PNG_CAPS.side) return 'dimensions'
|
||||
if (width * height > PNG_CAPS.pixels) return 'dimensions'
|
||||
if (!DEPTHS[colourType]?.includes(depth)) return 'ihdr'
|
||||
if (header.compression !== 0 || header.filter !== 0) return 'ihdr'
|
||||
if (header.interlace !== 0) return 'ihdr'
|
||||
return null
|
||||
}
|
||||
|
||||
/** Non-interlaced raw size: each scanline is a filter byte plus its packed samples. */
|
||||
function expectedRawSize(header: PngHeader): number {
|
||||
const bitsPerPixel = CHANNELS[header.colourType]! * header.depth
|
||||
const rowBytes = Math.ceil((header.width * bitsPerPixel) / 8) + 1
|
||||
return rowBytes * header.height
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks the chunks after the first IHDR to an `IEND` of length 0 that ends
|
||||
* the buffer exactly. Any type outside `ALLOWED_CHUNKS` (a second IHDR, an
|
||||
* APNG chunk, a `tEXt`/`iTXt` whose missing NUL would spin UPNG's
|
||||
* `nextZero` forever, an unknown type), a declared length past the buffer,
|
||||
* a truncated chunk head, a missing IEND or bytes after it are refused.
|
||||
*/
|
||||
function chunkListIssue(view: DataView): PngIssue | null {
|
||||
let offset = IHDR_END
|
||||
while (offset + CHUNK_HEAD <= view.byteLength) {
|
||||
const length = view.getUint32(offset)
|
||||
const type = view.getUint32(offset + 4)
|
||||
const next = offset + CHUNK_OVERHEAD + length
|
||||
if (next > view.byteLength) return 'chunks'
|
||||
if (!ALLOWED_CHUNKS.has(type)) return 'chunks'
|
||||
if (type === IEND_TYPE) {
|
||||
return length === 0 && next === view.byteLength ? null : 'chunks'
|
||||
}
|
||||
offset = next
|
||||
}
|
||||
return 'chunks'
|
||||
}
|
||||
|
||||
/** The IDAT payloads in file order, one zlib stream; the chunk list is already known sound. */
|
||||
function idatPayload(view: DataView): Uint8Array {
|
||||
const parts: Uint8Array[] = []
|
||||
let total = 0
|
||||
let offset = IHDR_END
|
||||
while (offset + CHUNK_HEAD <= view.byteLength) {
|
||||
const length = view.getUint32(offset)
|
||||
if (view.getUint32(offset + 4) === IDAT_TYPE) {
|
||||
const start = view.byteOffset + offset + CHUNK_HEAD
|
||||
parts.push(new Uint8Array(view.buffer, start, length))
|
||||
total += length
|
||||
}
|
||||
offset += CHUNK_OVERHEAD + length
|
||||
}
|
||||
const payload = new Uint8Array(total)
|
||||
let at = 0
|
||||
for (const part of parts) {
|
||||
payload.set(part, at)
|
||||
at += part.byteLength
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
/**
|
||||
* Inflates the IDAT stream with the native, bounded inflater before UPNG's
|
||||
* unbounded `inflateRaw` does: a truncated, corrupt or oversized stream, or
|
||||
* one that does not yield exactly the raw scanline size, is refused.
|
||||
*/
|
||||
async function idatIssue(
|
||||
view: DataView,
|
||||
rawSize: number,
|
||||
): Promise<PngIssue | null> {
|
||||
const raw = await inflateFlate(idatPayload(view), rawSize)
|
||||
if (!raw || raw.byteLength !== rawSize) return 'idat'
|
||||
return null
|
||||
}
|
||||
|
||||
function base64ToBytes(base64: string): Uint8Array {
|
||||
const binary = atob(base64)
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)
|
||||
return bytes
|
||||
}
|
||||
|
||||
async function embedImage(
|
||||
pdfDoc: PDFDocument,
|
||||
asset: ImageAsset,
|
||||
rasterizer: Rasterizer,
|
||||
): Promise<PDFImage> {
|
||||
if (asset.kind === 'png') {
|
||||
const bytes = base64ToBytes(asset.base64)
|
||||
const issue = await pngIssue(bytes)
|
||||
if (issue) throw new Error(`png refused: ${issue}`)
|
||||
return pdfDoc.embedPng(bytes)
|
||||
}
|
||||
const { svg, size } = renderBrandingSvg(asset.svg)
|
||||
return pdfDoc.embedPng(await rasterizer(svg, size))
|
||||
}
|
||||
|
||||
interface Embedder {
|
||||
pdfDoc: PDFDocument
|
||||
rasterizer: Rasterizer
|
||||
warnings: ExportWarning[]
|
||||
}
|
||||
|
||||
async function embedSlot(
|
||||
embedder: Embedder,
|
||||
slot: LogoSlot,
|
||||
asset: ImageAsset | null,
|
||||
): Promise<PDFImage | null> {
|
||||
if (!asset) return null
|
||||
try {
|
||||
return await embedImage(embedder.pdfDoc, asset, embedder.rasterizer)
|
||||
} catch {
|
||||
embedder.warnings.push({ kind: 'logo_failed', slot })
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function embedCredit(
|
||||
embedder: Embedder,
|
||||
slot: LogoSlot,
|
||||
credit: Credit | null,
|
||||
): Promise<CreditAsset | null> {
|
||||
if (!credit) return null
|
||||
return {
|
||||
image: await embedSlot(embedder, slot, credit.logo),
|
||||
url: credit.url,
|
||||
fallbackText: credit.fallbackText,
|
||||
}
|
||||
}
|
||||
|
||||
/** Embeds the four slots in a fixed order: header, footer, powered-by, partner. */
|
||||
export async function embedBranding(
|
||||
embedder: Embedder,
|
||||
branding: Branding,
|
||||
): Promise<BrandingImages> {
|
||||
return {
|
||||
siteUrl: branding.siteUrl,
|
||||
header: await embedSlot(embedder, 'headerLogo', branding.headerLogo),
|
||||
footer: await embedSlot(embedder, 'footerLogo', branding.footerLogo),
|
||||
poweredBy: await embedCredit(embedder, 'poweredBy', branding.poweredBy),
|
||||
partner: await embedCredit(embedder, 'partner', branding.partner),
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
/**
|
||||
* Typed failures of the engine. The app maps the kinds to its messages; no
|
||||
* message here echoes untrusted input.
|
||||
*/
|
||||
|
||||
export type ArchiveReadErrorKind =
|
||||
| 'invalid_pdf'
|
||||
| 'no_attachment'
|
||||
| 'attachment_stripped'
|
||||
| 'incompatible_version'
|
||||
|
||||
export class ArchiveReadError extends Error {
|
||||
constructor(
|
||||
public readonly kind: ArchiveReadErrorKind,
|
||||
/** The report version found, for `incompatible_version`. */
|
||||
public readonly foundVersion?: number | null,
|
||||
) {
|
||||
super(kind)
|
||||
this.name = 'ArchiveReadError'
|
||||
}
|
||||
}
|
||||
|
||||
export type ArchiveExportErrorKind =
|
||||
| 'snapshot_invalid'
|
||||
| 'snapshot_too_large'
|
||||
| 'sheet_mismatch'
|
||||
| 'too_many_pages'
|
||||
/** The branding or the label set fails its schema (URLs included). */
|
||||
| 'branding_invalid'
|
||||
|
||||
export class ArchiveExportError extends Error {
|
||||
constructor(
|
||||
public readonly kind: ArchiveExportErrorKind,
|
||||
detail = '',
|
||||
) {
|
||||
super(detail ? `${kind}: ${detail}` : kind)
|
||||
this.name = 'ArchiveExportError'
|
||||
}
|
||||
}
|
||||
|
||||
export type SvgRejection =
|
||||
| 'doctype'
|
||||
| 'malformed'
|
||||
| 'not_svg'
|
||||
| 'too_many_elements'
|
||||
| 'too_deep'
|
||||
| 'too_many_uses'
|
||||
|
||||
/** An SVG text the sanitiser refuses outright (STEP6 §15). */
|
||||
export class SvgRejectedError extends Error {
|
||||
constructor(public readonly reason: SvgRejection) {
|
||||
super(`svg rejected: ${reason}`)
|
||||
this.name = 'SvgRejectedError'
|
||||
}
|
||||
}
|
||||
@@ -1,228 +0,0 @@
|
||||
import { PDFDocument } from 'pdf-lib'
|
||||
import {
|
||||
assertSnapshot,
|
||||
BrandingSchema,
|
||||
buildSheetIndex,
|
||||
ENVELOPE_FORMAT,
|
||||
ENVELOPE_VERSION,
|
||||
PdfLabelSetSchema,
|
||||
snapshotIndexSource,
|
||||
SnapshotError,
|
||||
type Report,
|
||||
type ReportArchiveEnvelope,
|
||||
type SheetIndex,
|
||||
type SheetSnapshot,
|
||||
} from '@faunosteo/domain'
|
||||
import { attachEnvelope } from './attachment/write'
|
||||
import { MAX_ATTACHMENT_BYTES } from './attachment/inflate'
|
||||
import { PDF_KEYWORD } from './attachment/read'
|
||||
import { embedBranding, type BrandingImages } from './branding'
|
||||
import { ArchiveExportError, SvgRejectedError } from './errors'
|
||||
import { addConclusionPage } from './render/conclusionPage'
|
||||
import type { RenderContext } from './render/context'
|
||||
import { embedFonts } from './render/fonts'
|
||||
import { drawFooter } from './render/footer'
|
||||
import { addObservationPage } from './render/observationPage'
|
||||
import { cleanSvgRoot } from './svg/view'
|
||||
import type {
|
||||
ExportInput,
|
||||
ExportResult,
|
||||
ExportWarning,
|
||||
PdfLocale,
|
||||
Rasterizer,
|
||||
} from './types'
|
||||
|
||||
/**
|
||||
* Exports a report archive from explicit inputs and nothing else: the
|
||||
* report, the sheet snapshot it was written on, the branding, the labels,
|
||||
* the locale, a rasterizer and the export time (STEP6 §14 "Export"). The
|
||||
* attachment embeds exactly what the pages were rendered from, so the file
|
||||
* re-exports without the current catalog, assets or configuration.
|
||||
*/
|
||||
|
||||
export const PAGE_CAPS = {
|
||||
observations: 500,
|
||||
viewsPerObservation: 8,
|
||||
} as const
|
||||
|
||||
/**
|
||||
* Step 0: the branding and the labels pass their schemas again. They reach
|
||||
* the engine from an archive or from the application and end up in link
|
||||
* URIs and drawn text, so a caller cannot be trusted to have validated them.
|
||||
*/
|
||||
function assertBrandingAndLabels(input: ExportInput): void {
|
||||
if (!BrandingSchema.safeParse(input.branding).success) {
|
||||
throw new ArchiveExportError('branding_invalid', 'branding')
|
||||
}
|
||||
if (!PdfLabelSetSchema.safeParse(input.labels).success) {
|
||||
throw new ArchiveExportError('branding_invalid', 'labels')
|
||||
}
|
||||
}
|
||||
|
||||
/** Step 1: the snapshot gate, with every asset accepted by the sanitiser. */
|
||||
function checkedSnapshot(sheet: SheetSnapshot): SheetSnapshot {
|
||||
let parsed: SheetSnapshot
|
||||
try {
|
||||
parsed = assertSnapshot(sheet)
|
||||
} catch (error) {
|
||||
if (!(error instanceof SnapshotError)) throw error
|
||||
const kind =
|
||||
error.reason === 'caps' ? 'snapshot_too_large' : 'snapshot_invalid'
|
||||
throw new ArchiveExportError(kind, error.reason)
|
||||
}
|
||||
for (const asset of parsed.assets) {
|
||||
try {
|
||||
cleanSvgRoot(asset.svg)
|
||||
} catch (error) {
|
||||
if (!(error instanceof SvgRejectedError)) throw error
|
||||
throw new ArchiveExportError('snapshot_invalid', `asset ${error.reason}`)
|
||||
}
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
/** Steps 2 and 3: the report belongs to this sheet and fits the page budget. */
|
||||
function assertExportable(report: Report, sheet: SheetSnapshot): void {
|
||||
if (
|
||||
report.sheet.sheetId !== sheet.ref.sheetId ||
|
||||
report.sheet.documentSha256 !== sheet.ref.documentSha256
|
||||
) {
|
||||
throw new ArchiveExportError('sheet_mismatch')
|
||||
}
|
||||
if (report.observations.length > PAGE_CAPS.observations) {
|
||||
throw new ArchiveExportError('too_many_pages', 'observations')
|
||||
}
|
||||
const tooManyViews = report.observations.some(
|
||||
(o) =>
|
||||
new Set(o.zones.map((z) => z.viewId)).size >
|
||||
PAGE_CAPS.viewsPerObservation,
|
||||
)
|
||||
if (tooManyViews) throw new ArchiveExportError('too_many_pages', 'views')
|
||||
}
|
||||
|
||||
function buildEnvelope(
|
||||
input: ExportInput,
|
||||
sheet: SheetSnapshot,
|
||||
): ReportArchiveEnvelope {
|
||||
return {
|
||||
format: ENVELOPE_FORMAT,
|
||||
envelopeVersion: ENVELOPE_VERSION,
|
||||
exportedAt: input.exportedAt.toISOString(),
|
||||
locale: input.locale,
|
||||
report: input.report,
|
||||
sheetSnapshot: sheet,
|
||||
branding: input.branding,
|
||||
labels: input.labels,
|
||||
}
|
||||
}
|
||||
|
||||
/** Step 4: pretty JSON under the attachment cap. */
|
||||
function encodeEnvelope(envelope: ReportArchiveEnvelope): Uint8Array {
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(envelope, null, 2))
|
||||
if (bytes.byteLength > MAX_ATTACHMENT_BYTES) {
|
||||
throw new ArchiveExportError('snapshot_too_large', 'attachment')
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
/** Step 5: document information, every date the export time. */
|
||||
function setMetadata(pdfDoc: PDFDocument, input: ExportInput): void {
|
||||
const labels = input.labels[input.locale]
|
||||
pdfDoc.setTitle(
|
||||
`${labels['pdf.title.suffix.bilan']}${input.report.animal.name}`,
|
||||
)
|
||||
pdfDoc.setAuthor(input.report.practitioner.name)
|
||||
pdfDoc.setSubject(labels['pdf.subject'])
|
||||
pdfDoc.setKeywords([PDF_KEYWORD])
|
||||
pdfDoc.setCreationDate(input.exportedAt)
|
||||
pdfDoc.setModificationDate(input.exportedAt)
|
||||
}
|
||||
|
||||
interface Pages {
|
||||
pdfDoc: PDFDocument
|
||||
input: ExportInput
|
||||
sheet: SheetSnapshot
|
||||
index: SheetIndex
|
||||
ctx: RenderContext
|
||||
branding: BrandingImages
|
||||
warnings: ExportWarning[]
|
||||
}
|
||||
|
||||
/** Steps 8 and 9: one page per observation, the conclusion, footers everywhere. */
|
||||
async function drawPages(pages: Pages): Promise<void> {
|
||||
const { pdfDoc, input, ctx, branding } = pages
|
||||
const headerAssets = { logo: branding.header, siteUrl: branding.siteUrl }
|
||||
for (let i = 0; i < input.report.observations.length; i += 1) {
|
||||
await addObservationPage({
|
||||
pdfDoc,
|
||||
report: input.report,
|
||||
observation: input.report.observations[i]!,
|
||||
obsIndex: i,
|
||||
sheet: pages.index,
|
||||
snapshot: pages.sheet,
|
||||
ctx,
|
||||
headerAssets,
|
||||
rasterizer: input.rasterizer,
|
||||
warnings: pages.warnings,
|
||||
})
|
||||
}
|
||||
await addConclusionPage(pdfDoc, input.report, ctx, headerAssets)
|
||||
const all = pdfDoc.getPages()
|
||||
all.forEach((page, idx) => {
|
||||
const pagination = { pageNumber: idx + 1, totalPages: all.length }
|
||||
drawFooter(page, pagination, ctx, branding)
|
||||
})
|
||||
}
|
||||
|
||||
export async function exportReportArchive(
|
||||
input: ExportInput,
|
||||
): Promise<ExportResult> {
|
||||
assertBrandingAndLabels(input)
|
||||
const sheet = checkedSnapshot(input.sheet)
|
||||
assertExportable(input.report, sheet)
|
||||
const envelope = buildEnvelope(input, sheet)
|
||||
const attachment = encodeEnvelope(envelope)
|
||||
|
||||
const pdfDoc = await PDFDocument.create()
|
||||
setMetadata(pdfDoc, input)
|
||||
const fonts = await embedFonts(pdfDoc)
|
||||
const warnings: ExportWarning[] = []
|
||||
const branding = await embedBranding(
|
||||
{ pdfDoc, rasterizer: input.rasterizer, warnings },
|
||||
input.branding,
|
||||
)
|
||||
await drawPages({
|
||||
pdfDoc,
|
||||
input,
|
||||
sheet,
|
||||
index: buildSheetIndex(snapshotIndexSource(sheet)),
|
||||
ctx: { fonts, locale: input.locale, labels: input.labels[input.locale] },
|
||||
branding,
|
||||
warnings,
|
||||
})
|
||||
await attachEnvelope(pdfDoc, attachment, input.exportedAt)
|
||||
// No object streams (BLK-009): the Filespec name and the keyword stamp stay
|
||||
// in clear for the byte-scan reader; the file grows by a few KB.
|
||||
const pdf = await pdfDoc.save({ useObjectStreams: false })
|
||||
return { pdf, envelope, warnings }
|
||||
}
|
||||
|
||||
export interface ReexportOptions {
|
||||
locale: PdfLocale
|
||||
rasterizer: Rasterizer
|
||||
exportedAt: Date
|
||||
}
|
||||
|
||||
/** Re-export from an archive alone: no sheet, no network, no configuration. */
|
||||
export function exportFromEnvelope(
|
||||
env: ReportArchiveEnvelope,
|
||||
opts: ReexportOptions,
|
||||
): Promise<ExportResult> {
|
||||
return exportReportArchive({
|
||||
report: env.report,
|
||||
sheet: env.sheetSnapshot,
|
||||
branding: env.branding,
|
||||
labels: env.labels,
|
||||
...opts,
|
||||
})
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import type { PdfLabels } from '@faunosteo/domain'
|
||||
|
||||
/** Verbatim copy of the app's EN strings the PDF read when Step 6 started. */
|
||||
export const en: PdfLabels = {
|
||||
'pdf.eyebrow.observation': 'OBSERVATION',
|
||||
'pdf.eyebrow.synthesis': 'SYNTHESIS',
|
||||
'pdf.title.conclusion': 'Conclusion',
|
||||
'pdf.section.zones': 'ZONES',
|
||||
'pdf.section.findings_prefix': 'FINDINGS — ',
|
||||
'pdf.section.free_findings': 'FREE FINDINGS',
|
||||
'pdf.section.severity': 'SEVERITY',
|
||||
'pdf.section.comment': 'COMMENT',
|
||||
'pdf.section.conclusion': 'CONCLUSION',
|
||||
'pdf.section.recommendations': 'RECOMMENDATIONS',
|
||||
'pdf.section.next_appointment': 'NEXT APPOINTMENT',
|
||||
'pdf.view.general': 'GENERAL VIEW',
|
||||
'pdf.view.detail_prefix': 'DETAIL VIEW — ',
|
||||
'pdf.empty': '—',
|
||||
'pdf.owner_prefix': 'Owner: ',
|
||||
'pdf.siret_prefix': 'SIRET ',
|
||||
'pdf.title.suffix.bilan': 'Osteo report — ',
|
||||
'pdf.subject': 'Animal osteopathic report',
|
||||
'severity.mild': 'mild',
|
||||
'severity.moderate': 'moderate',
|
||||
'severity.severe': 'severe',
|
||||
'lateral.left': 'Left',
|
||||
'lateral.right': 'Right',
|
||||
'footer.powered_by': 'Powered by',
|
||||
'footer.in_partnership': 'In partnership with',
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import type { PdfLabels } from '@faunosteo/domain'
|
||||
|
||||
/** Verbatim copy of the app's FR strings the PDF read when Step 6 started. */
|
||||
export const fr: PdfLabels = {
|
||||
'pdf.eyebrow.observation': 'OBSERVATION',
|
||||
'pdf.eyebrow.synthesis': 'SYNTHÈSE',
|
||||
'pdf.title.conclusion': 'Conclusion',
|
||||
'pdf.section.zones': 'ZONES',
|
||||
'pdf.section.findings_prefix': 'CONSTATS — ',
|
||||
'pdf.section.free_findings': 'CONSTATS LIBRES',
|
||||
'pdf.section.severity': 'SÉVÉRITÉ',
|
||||
'pdf.section.comment': 'COMMENTAIRE',
|
||||
'pdf.section.conclusion': 'CONCLUSION',
|
||||
'pdf.section.recommendations': 'RECOMMANDATIONS',
|
||||
'pdf.section.next_appointment': 'PROCHAIN RENDEZ-VOUS',
|
||||
'pdf.view.general': 'VUE GÉNÉRALE',
|
||||
'pdf.view.detail_prefix': 'VUE DÉTAIL — ',
|
||||
'pdf.empty': '—',
|
||||
'pdf.owner_prefix': 'Propriétaire : ',
|
||||
'pdf.siret_prefix': 'SIRET ',
|
||||
'pdf.title.suffix.bilan': 'Bilan ostéo — ',
|
||||
'pdf.subject': "Bilan d'ostéopathie animalière",
|
||||
'severity.mild': 'légère',
|
||||
'severity.moderate': 'modérée',
|
||||
'severity.severe': 'sévère',
|
||||
'lateral.left': 'Gauche',
|
||||
'lateral.right': 'Droite',
|
||||
'footer.powered_by': 'Propulsé par',
|
||||
'footer.in_partnership': 'En partenariat avec',
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import type { PdfLabelSet } from '@faunosteo/domain'
|
||||
import { en } from './en'
|
||||
import { fr } from './fr'
|
||||
|
||||
/** The wording of the day, frozen into every archive the engine writes. */
|
||||
export const defaultPdfLabels: PdfLabelSet = { fr, en }
|
||||
@@ -1,27 +0,0 @@
|
||||
/**
|
||||
* @faunosteo/pdf — the browser-free PDF engine (STEP6 §13).
|
||||
*/
|
||||
export { exportReportArchive, exportFromEnvelope } from './export'
|
||||
export { readReportArchive, MAX_PDF_BYTES } from './read'
|
||||
export { readAttachedDocument, PDF_KEYWORD } from './attachment/read'
|
||||
export {
|
||||
findEmbeddedFiles,
|
||||
readAttachmentBytes,
|
||||
type EmbeddedFileCandidate,
|
||||
} from './attachment/scan'
|
||||
export { MAX_ATTACHMENT_BYTES } from './attachment/inflate'
|
||||
export {
|
||||
ArchiveReadError,
|
||||
ArchiveExportError,
|
||||
type ArchiveReadErrorKind,
|
||||
type ArchiveExportErrorKind,
|
||||
} from './errors'
|
||||
export type {
|
||||
Rasterizer,
|
||||
ExportInput,
|
||||
ExportResult,
|
||||
ExportWarning,
|
||||
PdfLocale,
|
||||
} from './types'
|
||||
export { defaultPdfLabels } from './i18n'
|
||||
export { composeHighlightedViewSvg } from './svg/view'
|
||||
@@ -1,38 +0,0 @@
|
||||
import {
|
||||
readArchiveDocument,
|
||||
UnsupportedReportVersionError,
|
||||
type ArchiveReadOutcome,
|
||||
type ReportMigrationMap,
|
||||
} from '@faunosteo/domain'
|
||||
import { readAttachedDocument } from './attachment/read'
|
||||
import { ArchiveReadError } from './errors'
|
||||
|
||||
export { MAX_PDF_BYTES } from './attachment/scan'
|
||||
|
||||
/**
|
||||
* Reads a Faunosteo PDF back: size cap and `%PDF-` header (`invalid_pdf`),
|
||||
* attachment located by a byte scan (filename first, never a PDF parse:
|
||||
* BLK-009), JSON, then the layered reading of the domain (report first, then
|
||||
* the envelope accepted whole or dropped with a reason). An unknown report
|
||||
* version is `incompatible_version` with that version; any other content
|
||||
* failure is `no_attachment`, as today.
|
||||
*/
|
||||
export async function readReportArchive(
|
||||
pdfBytes: Uint8Array,
|
||||
map: ReportMigrationMap,
|
||||
): Promise<ArchiveReadOutcome> {
|
||||
const data = await readAttachedDocument(pdfBytes)
|
||||
try {
|
||||
return readArchiveDocument(data, map)
|
||||
} catch (error) {
|
||||
// A numeric but unknown version is an incompatible Faunosteo report; no
|
||||
// version at all is not a Faunosteo attachment (today's message).
|
||||
if (
|
||||
error instanceof UnsupportedReportVersionError &&
|
||||
error.foundVersion !== null
|
||||
) {
|
||||
throw new ArchiveReadError('incompatible_version', error.foundVersion)
|
||||
}
|
||||
throw new ArchiveReadError('no_attachment')
|
||||
}
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
import { PageSizes, type PDFDocument } from 'pdf-lib'
|
||||
import type { Report } from '@faunosteo/domain'
|
||||
import {
|
||||
COLOR_ACCENT,
|
||||
COLOR_INK,
|
||||
COLOR_MUTED,
|
||||
EYEBROW_Y_OFFSET,
|
||||
MARGIN_X,
|
||||
SECTION_LABEL_GAP,
|
||||
TITLE_RULE_OFFSET,
|
||||
TITLE_RULE_WIDTH,
|
||||
TITLE_Y_OFFSET,
|
||||
} from './constants'
|
||||
import type { RenderContext } from './context'
|
||||
import { formatDate } from './dates'
|
||||
import { drawHeader, type HeaderAssets } from './header'
|
||||
import { drawText, wrapLines } from './text'
|
||||
|
||||
const SECTION_TOP_GAP = 28
|
||||
const SECTION_BLOCK_GAP = 18
|
||||
const TEXT_LINE_HEIGHT = 14
|
||||
|
||||
interface ConclusionSection {
|
||||
label: string
|
||||
body: string
|
||||
color?: typeof COLOR_INK
|
||||
}
|
||||
|
||||
function nextAppointmentText(report: Report, ctx: RenderContext): string {
|
||||
const next = report.nextAppointment!
|
||||
return next.kind === 'date' ? formatDate(next.date, ctx.locale) : next.text
|
||||
}
|
||||
|
||||
function conclusionSections(
|
||||
report: Report,
|
||||
ctx: RenderContext,
|
||||
): ConclusionSection[] {
|
||||
const { labels } = ctx
|
||||
const sections: ConclusionSection[] = [
|
||||
{
|
||||
label: labels['pdf.section.conclusion'],
|
||||
body: report.conclusion || labels['pdf.empty'],
|
||||
},
|
||||
{
|
||||
label: labels['pdf.section.recommendations'],
|
||||
body: report.recommendations || labels['pdf.empty'],
|
||||
},
|
||||
]
|
||||
if (report.nextAppointment) {
|
||||
sections.push({
|
||||
label: labels['pdf.section.next_appointment'],
|
||||
body: nextAppointmentText(report, ctx) || labels['pdf.empty'],
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
}
|
||||
return sections
|
||||
}
|
||||
|
||||
export async function addConclusionPage(
|
||||
pdfDoc: PDFDocument,
|
||||
report: Report,
|
||||
ctx: RenderContext,
|
||||
headerAssets: HeaderAssets,
|
||||
): Promise<void> {
|
||||
const { fonts, labels } = ctx
|
||||
const page = pdfDoc.addPage(PageSizes.A4)
|
||||
const { width, height } = page.getSize()
|
||||
const max = width - MARGIN_X * 2
|
||||
|
||||
drawHeader(page, report, ctx, headerAssets)
|
||||
|
||||
const eyebrowY = height - EYEBROW_Y_OFFSET
|
||||
const titleY = height - TITLE_Y_OFFSET
|
||||
drawText(page, labels['pdf.eyebrow.synthesis'], {
|
||||
x: MARGIN_X,
|
||||
y: eyebrowY,
|
||||
size: 9,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
drawText(page, labels['pdf.title.conclusion'], {
|
||||
x: MARGIN_X,
|
||||
y: titleY,
|
||||
size: 22,
|
||||
font: fonts.headingRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
page.drawLine({
|
||||
start: { x: MARGIN_X, y: titleY - TITLE_RULE_OFFSET },
|
||||
end: { x: MARGIN_X + TITLE_RULE_WIDTH, y: titleY - TITLE_RULE_OFFSET },
|
||||
thickness: 2,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
|
||||
let cursorY = titleY - SECTION_TOP_GAP
|
||||
for (const { label, body, color } of conclusionSections(report, ctx)) {
|
||||
drawText(page, label, {
|
||||
x: MARGIN_X,
|
||||
y: cursorY,
|
||||
size: 9,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
cursorY -= SECTION_LABEL_GAP + 10
|
||||
wrapLines(body, fonts.bodyRegular, 11, max).forEach((line) => {
|
||||
drawText(page, line, {
|
||||
x: MARGIN_X,
|
||||
y: cursorY,
|
||||
size: 11,
|
||||
font: fonts.bodyRegular,
|
||||
color: color ?? COLOR_INK,
|
||||
})
|
||||
cursorY -= TEXT_LINE_HEIGHT
|
||||
})
|
||||
cursorY -= SECTION_BLOCK_GAP
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { rgb } from 'pdf-lib'
|
||||
|
||||
/**
|
||||
* Layout and colour constants shared across page renderers (header, footer,
|
||||
* observation page, conclusion page). Only values identical across callers
|
||||
* live here; a same-named constant with another value stays local.
|
||||
*/
|
||||
|
||||
export const MARGIN_X = 36
|
||||
export const EYEBROW_Y_OFFSET = 95
|
||||
export const TITLE_Y_OFFSET = 122
|
||||
export const TITLE_RULE_OFFSET = 12
|
||||
export const TITLE_RULE_WIDTH = 48
|
||||
export const SECTION_LABEL_GAP = 4
|
||||
|
||||
export const COLOR_INK = rgb(0.12, 0.11, 0.09)
|
||||
export const COLOR_MUTED = rgb(0.42, 0.39, 0.35)
|
||||
export const COLOR_ACCENT = rgb(0.72, 0.35, 0.25)
|
||||
@@ -1,11 +0,0 @@
|
||||
import type { PdfLabels } from '@faunosteo/domain'
|
||||
import type { EmbeddedFonts } from './fonts'
|
||||
|
||||
export type PdfLocale = 'fr' | 'en'
|
||||
|
||||
/** What every page renderer needs besides the page: fonts, locale, labels. */
|
||||
export interface RenderContext {
|
||||
fonts: EmbeddedFonts
|
||||
locale: PdfLocale
|
||||
labels: PdfLabels
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import type { PdfLocale } from './context'
|
||||
|
||||
const LOCALE_TAG: Record<PdfLocale, string> = {
|
||||
fr: 'fr-FR',
|
||||
en: 'en-US',
|
||||
}
|
||||
|
||||
/**
|
||||
* Long date in the locale for a `YYYY-MM-DD` value. Anything else is
|
||||
* printed unchanged: a report is user data and never fails the export.
|
||||
*/
|
||||
export function formatDate(isoDate: string, locale: PdfLocale): string {
|
||||
const match = isoDate.match(/^(\d{4})-(\d{2})-(\d{2})$/)
|
||||
if (!match) return isoDate
|
||||
const [, y, mo, d] = match
|
||||
const date = new Date(Date.UTC(Number(y), Number(mo) - 1, Number(d)))
|
||||
const rolledOver =
|
||||
date.getUTCMonth() !== Number(mo) - 1 || date.getUTCDate() !== Number(d)
|
||||
if (Number.isNaN(date.getTime()) || rolledOver) return isoDate
|
||||
return new Intl.DateTimeFormat(LOCALE_TAG[locale], {
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
timeZone: 'UTC',
|
||||
}).format(date)
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import { PDFDocument, StandardFonts, type PDFFont } from 'pdf-lib'
|
||||
|
||||
/** Helvetica body, Times heading: WinAnsi standard fonts (TTF planned). */
|
||||
export interface EmbeddedFonts {
|
||||
bodyRegular: PDFFont
|
||||
bodyBold: PDFFont
|
||||
headingRegular: PDFFont
|
||||
}
|
||||
|
||||
export async function embedFonts(pdfDoc: PDFDocument): Promise<EmbeddedFonts> {
|
||||
const [bodyRegular, bodyBold, headingRegular] = await Promise.all([
|
||||
pdfDoc.embedFont(StandardFonts.Helvetica),
|
||||
pdfDoc.embedFont(StandardFonts.HelveticaBold),
|
||||
pdfDoc.embedFont(StandardFonts.TimesRoman),
|
||||
])
|
||||
return { bodyRegular, bodyBold, headingRegular }
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
import { rgb, type PDFPage } from 'pdf-lib'
|
||||
import type { BrandingImages, CreditAsset } from '../branding'
|
||||
import { COLOR_MUTED, MARGIN_X } from './constants'
|
||||
import type { RenderContext } from './context'
|
||||
import { addLinkAnnotation } from './linkAnnotation'
|
||||
import { drawText, measure } from './text'
|
||||
|
||||
const FOOTER_BASE_Y = 20
|
||||
const FONT_SIZE = 8
|
||||
const LOGO_W = 80
|
||||
const LOGO_H = 30
|
||||
const ROW_Y = FOOTER_BASE_Y + 14
|
||||
const TEXT_BASE_Y = ROW_Y + 6
|
||||
const CREDIT_LOGO_H = 16
|
||||
const POWERED_LOGO_W = 70
|
||||
const COLOR_RULE = rgb(0.85, 0.83, 0.8)
|
||||
const COLOR_CREDIT = rgb(0.28, 0.56, 0.42)
|
||||
|
||||
function drawRule(page: PDFPage): void {
|
||||
const { width } = page.getSize()
|
||||
const separatorY = ROW_Y + LOGO_H + 6
|
||||
page.drawLine({
|
||||
start: { x: MARGIN_X, y: separatorY },
|
||||
end: { x: width - MARGIN_X, y: separatorY },
|
||||
thickness: 0.5,
|
||||
color: COLOR_RULE,
|
||||
})
|
||||
}
|
||||
|
||||
function drawSiteLogo(page: PDFPage, assets: BrandingImages): void {
|
||||
if (!assets.footer) return
|
||||
const rect = { x: MARGIN_X, y: ROW_Y, width: LOGO_W, height: LOGO_H }
|
||||
page.drawImage(assets.footer, rect)
|
||||
addLinkAnnotation(page, { ...rect, url: assets.siteUrl })
|
||||
}
|
||||
|
||||
function drawMutedLabel(
|
||||
page: PDFPage,
|
||||
text: string,
|
||||
x: number,
|
||||
ctx: RenderContext,
|
||||
): void {
|
||||
drawText(page, text, {
|
||||
x,
|
||||
y: TEXT_BASE_Y,
|
||||
size: FONT_SIZE,
|
||||
font: ctx.fonts.bodyRegular,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
}
|
||||
|
||||
/** The credit's fallback text in the accent colour, linked. */
|
||||
function drawCreditText(
|
||||
page: PDFPage,
|
||||
credit: CreditAsset,
|
||||
x: number,
|
||||
ctx: RenderContext,
|
||||
): void {
|
||||
const font = ctx.fonts.bodyRegular
|
||||
drawText(page, credit.fallbackText, {
|
||||
x,
|
||||
y: TEXT_BASE_Y,
|
||||
size: FONT_SIZE,
|
||||
font,
|
||||
color: COLOR_CREDIT,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x,
|
||||
y: TEXT_BASE_Y - 2,
|
||||
width: measure(font, credit.fallbackText, FONT_SIZE),
|
||||
height: FONT_SIZE + 4,
|
||||
url: credit.url,
|
||||
})
|
||||
}
|
||||
|
||||
function drawCreditLogo(
|
||||
page: PDFPage,
|
||||
credit: CreditAsset & { image: NonNullable<CreditAsset['image']> },
|
||||
x: number,
|
||||
width: number,
|
||||
): void {
|
||||
const rect = { x, y: ROW_Y + 2, width, height: CREDIT_LOGO_H }
|
||||
page.drawImage(credit.image, rect)
|
||||
addLinkAnnotation(page, { ...rect, url: credit.url })
|
||||
}
|
||||
|
||||
/** Centred block: label then the fixed-width logo or the fallback text. */
|
||||
function drawPoweredBy(
|
||||
page: PDFPage,
|
||||
credit: CreditAsset,
|
||||
ctx: RenderContext,
|
||||
): void {
|
||||
const { width } = page.getSize()
|
||||
const font = ctx.fonts.bodyRegular
|
||||
const label = `${ctx.labels['footer.powered_by']} `
|
||||
const labelW = measure(font, label, FONT_SIZE)
|
||||
const creditW = credit.image
|
||||
? POWERED_LOGO_W
|
||||
: measure(font, credit.fallbackText, FONT_SIZE)
|
||||
const x = (width - labelW - creditW) / 2
|
||||
drawMutedLabel(page, label, x, ctx)
|
||||
if (credit.image) {
|
||||
drawCreditLogo(
|
||||
page,
|
||||
{ ...credit, image: credit.image },
|
||||
x + labelW,
|
||||
POWERED_LOGO_W,
|
||||
)
|
||||
} else {
|
||||
drawCreditText(page, credit, x + labelW, ctx)
|
||||
}
|
||||
}
|
||||
|
||||
/** Right-aligned block: label then the aspect-sized logo or the handle. */
|
||||
function drawPartner(
|
||||
page: PDFPage,
|
||||
credit: CreditAsset,
|
||||
ctx: RenderContext,
|
||||
): void {
|
||||
const { width } = page.getSize()
|
||||
const font = ctx.fonts.bodyRegular
|
||||
const label = `${ctx.labels['footer.in_partnership']} `
|
||||
const labelW = measure(font, label, FONT_SIZE)
|
||||
const creditW = credit.image
|
||||
? CREDIT_LOGO_H * (credit.image.width / credit.image.height)
|
||||
: measure(font, credit.fallbackText, FONT_SIZE)
|
||||
const x = width - MARGIN_X - labelW - creditW
|
||||
drawMutedLabel(page, label, x, ctx)
|
||||
if (credit.image) {
|
||||
drawCreditLogo(
|
||||
page,
|
||||
{ ...credit, image: credit.image },
|
||||
x + labelW,
|
||||
creditW,
|
||||
)
|
||||
} else {
|
||||
drawCreditText(page, credit, x + labelW, ctx)
|
||||
}
|
||||
}
|
||||
|
||||
function drawPageNumber(
|
||||
page: PDFPage,
|
||||
pageNumber: number,
|
||||
totalPages: number,
|
||||
ctx: RenderContext,
|
||||
): void {
|
||||
const { width } = page.getSize()
|
||||
const text = `${pageNumber} / ${totalPages}`
|
||||
drawText(page, text, {
|
||||
x: (width - measure(ctx.fonts.bodyRegular, text, FONT_SIZE)) / 2,
|
||||
y: FOOTER_BASE_Y + 2,
|
||||
size: FONT_SIZE,
|
||||
font: ctx.fonts.bodyRegular,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
}
|
||||
|
||||
/** Rule, site logo, powered-by credit, partner credit, page number. */
|
||||
export function drawFooter(
|
||||
page: PDFPage,
|
||||
pagination: { pageNumber: number; totalPages: number },
|
||||
ctx: RenderContext,
|
||||
assets: BrandingImages,
|
||||
): void {
|
||||
drawRule(page)
|
||||
drawSiteLogo(page, assets)
|
||||
if (assets.poweredBy) drawPoweredBy(page, assets.poweredBy, ctx)
|
||||
if (assets.partner) drawPartner(page, assets.partner, ctx)
|
||||
drawPageNumber(page, pagination.pageNumber, pagination.totalPages, ctx)
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
import type { PDFImage, PDFPage } from 'pdf-lib'
|
||||
import type { Report } from '@faunosteo/domain'
|
||||
import { COLOR_INK, COLOR_MUTED, MARGIN_X } from './constants'
|
||||
import type { RenderContext } from './context'
|
||||
import { formatDate } from './dates'
|
||||
import { addLinkAnnotation } from './linkAnnotation'
|
||||
import { drawText, measure } from './text'
|
||||
|
||||
const TOP_Y = 800
|
||||
const LOGO_WIDTH = 100
|
||||
const LOGO_HEIGHT = 38
|
||||
|
||||
export interface HeaderAssets {
|
||||
logo: PDFImage | null
|
||||
siteUrl: string
|
||||
}
|
||||
|
||||
function practitionerLines(report: Report, ctx: RenderContext): string[] {
|
||||
const { practitioner } = report
|
||||
return [
|
||||
practitioner.name,
|
||||
practitioner.cabinet,
|
||||
practitioner.contact,
|
||||
practitioner.siret
|
||||
? `${ctx.labels['pdf.siret_prefix']}${practitioner.siret}`
|
||||
: undefined,
|
||||
].filter((line): line is string => Boolean(line))
|
||||
}
|
||||
|
||||
function animalLines(report: Report, ctx: RenderContext): string[] {
|
||||
const animalLine = [
|
||||
report.animal.name,
|
||||
report.animal.breed ? `(${report.animal.breed})` : '',
|
||||
report.animal.age ? `· ${report.animal.age}` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
return [
|
||||
animalLine,
|
||||
`${ctx.labels['pdf.owner_prefix']}${report.owner.name}`,
|
||||
formatDate(report.date, ctx.locale),
|
||||
]
|
||||
}
|
||||
|
||||
function drawLeftColumn(
|
||||
page: PDFPage,
|
||||
lines: string[],
|
||||
ctx: RenderContext,
|
||||
): void {
|
||||
lines.forEach((line, i) => {
|
||||
drawText(page, line, {
|
||||
x: MARGIN_X,
|
||||
y: TOP_Y - i * 12,
|
||||
size: i === 0 ? 11 : 9,
|
||||
font: i === 0 ? ctx.fonts.bodyBold : ctx.fonts.bodyRegular,
|
||||
color: i === 0 ? COLOR_INK : COLOR_MUTED,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function drawRightColumn(
|
||||
page: PDFPage,
|
||||
lines: string[],
|
||||
ctx: RenderContext,
|
||||
): void {
|
||||
const { width } = page.getSize()
|
||||
lines.forEach((line, i) => {
|
||||
const size = i === 0 ? 11 : 9
|
||||
const font = i === 0 ? ctx.fonts.bodyBold : ctx.fonts.bodyRegular
|
||||
drawText(page, line, {
|
||||
x: width - MARGIN_X - measure(font, line, size),
|
||||
y: TOP_Y - i * 12,
|
||||
size,
|
||||
font,
|
||||
color: i === 0 ? COLOR_INK : COLOR_MUTED,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function drawLogo(page: PDFPage, assets: HeaderAssets): void {
|
||||
if (!assets.logo) return
|
||||
const { width } = page.getSize()
|
||||
const rect = {
|
||||
x: (width - LOGO_WIDTH) / 2,
|
||||
y: TOP_Y - LOGO_HEIGHT + 10,
|
||||
width: LOGO_WIDTH,
|
||||
height: LOGO_HEIGHT,
|
||||
}
|
||||
page.drawImage(assets.logo, rect)
|
||||
addLinkAnnotation(page, { ...rect, url: assets.siteUrl })
|
||||
}
|
||||
|
||||
/** Practitioner block left, logo centred, animal block right, then a rule. */
|
||||
export function drawHeader(
|
||||
page: PDFPage,
|
||||
report: Report,
|
||||
ctx: RenderContext,
|
||||
assets: HeaderAssets,
|
||||
): void {
|
||||
const { width } = page.getSize()
|
||||
const left = practitionerLines(report, ctx)
|
||||
drawLeftColumn(page, left, ctx)
|
||||
drawLogo(page, assets)
|
||||
drawRightColumn(page, animalLines(report, ctx), ctx)
|
||||
const separatorY = TOP_Y - Math.max(left.length * 12, LOGO_HEIGHT) - 8
|
||||
page.drawLine({
|
||||
start: { x: MARGIN_X, y: separatorY },
|
||||
end: { x: width - MARGIN_X, y: separatorY },
|
||||
thickness: 0.5,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
import { PDFName, PDFHexString, type PDFPage } from 'pdf-lib'
|
||||
import { ArchiveExportError } from '../errors'
|
||||
|
||||
export interface LinkRect {
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
url: string
|
||||
}
|
||||
|
||||
/** Printable ASCII without the space: what the branding URL schema allows. */
|
||||
const ASCII_MIN = 0x21
|
||||
const ASCII_MAX = 0x7e
|
||||
|
||||
/**
|
||||
* The URL as the hex form of its ASCII bytes, one byte per character.
|
||||
* `PDFHexString.fromText` would write UTF-16BE with a BOM, which readers
|
||||
* that take `/URI` as raw bytes (poppler) turn into a dead link. A code
|
||||
* point outside printable ASCII cannot reach the sink: the schema refuses
|
||||
* it upstream, so it means the branding bypassed validation.
|
||||
*/
|
||||
function asciiHexOf(url: string): string {
|
||||
let hex = ''
|
||||
for (const char of url) {
|
||||
const code = char.codePointAt(0) ?? 0
|
||||
if (code < ASCII_MIN || code > ASCII_MAX) {
|
||||
throw new ArchiveExportError('branding_invalid', 'url')
|
||||
}
|
||||
hex += code.toString(16).padStart(2, '0')
|
||||
}
|
||||
return hex
|
||||
}
|
||||
|
||||
/**
|
||||
* A clickable `/Link` annotation opening `url`, appended to the page's
|
||||
* Annots. The URI is written as a hex string: pdf-lib does not escape `(`,
|
||||
* `)` or `\` in a literal string, so a hostile URL could otherwise close
|
||||
* the literal and inject objects (a `/Next` JavaScript action, for one).
|
||||
*/
|
||||
export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void {
|
||||
const context = page.doc.context
|
||||
|
||||
const actionDict = context.obj({
|
||||
Type: 'Action',
|
||||
S: 'URI',
|
||||
URI: PDFHexString.of(asciiHexOf(rect.url)),
|
||||
})
|
||||
|
||||
const annotDict = context.obj({
|
||||
Type: 'Annot',
|
||||
Subtype: 'Link',
|
||||
Rect: [rect.x, rect.y, rect.x + rect.width, rect.y + rect.height],
|
||||
Border: [0, 0, 0],
|
||||
A: actionDict,
|
||||
})
|
||||
|
||||
const annots = page.node.Annots()
|
||||
if (annots) {
|
||||
annots.push(context.register(annotDict))
|
||||
} else {
|
||||
const arr = context.obj([context.register(annotDict)])
|
||||
page.node.set(PDFName.of('Annots'), arr)
|
||||
}
|
||||
}
|
||||
@@ -1,634 +0,0 @@
|
||||
import {
|
||||
PageSizes,
|
||||
rgb,
|
||||
type PDFDocument,
|
||||
type PDFImage,
|
||||
type PDFPage,
|
||||
} from 'pdf-lib'
|
||||
import {
|
||||
pickLabel,
|
||||
type Finding,
|
||||
type Observation,
|
||||
type PdfLabels,
|
||||
type Report,
|
||||
type ReportZone,
|
||||
type Severity,
|
||||
type SheetIndex,
|
||||
type SheetSnapshot,
|
||||
} from '@faunosteo/domain'
|
||||
import { renderHighlightedView } from '../svg/view'
|
||||
import type { ExportWarning, Rasterizer } from '../types'
|
||||
import {
|
||||
COLOR_ACCENT,
|
||||
COLOR_INK,
|
||||
EYEBROW_Y_OFFSET,
|
||||
MARGIN_X,
|
||||
SECTION_LABEL_GAP,
|
||||
TITLE_RULE_OFFSET,
|
||||
TITLE_RULE_WIDTH,
|
||||
TITLE_Y_OFFSET,
|
||||
} from './constants'
|
||||
import type { PdfLocale, RenderContext } from './context'
|
||||
import type { EmbeddedFonts } from './fonts'
|
||||
import { drawHeader, type HeaderAssets } from './header'
|
||||
import { drawText, measure, wrapLines } from './text'
|
||||
|
||||
const MARGIN_BOTTOM = 48
|
||||
const IMAGE_TOP_GAP = 32
|
||||
const IMAGE_LABEL_GAP = 14
|
||||
const IMAGE_BOTTOM_GAP = 14
|
||||
const IMAGE_COL_GAP = 16
|
||||
const IMAGE_ROW_GAP = 12
|
||||
const IMAGE_MIN_CELL_H = 60
|
||||
const TEXT_TOP_GAP = 10
|
||||
const TEXT_LINE_HEIGHT = 13
|
||||
const SECTION_BLOCK_GAP = 10
|
||||
|
||||
const COLOR_WHITE = rgb(1, 1, 1)
|
||||
|
||||
const SEVERITY_BG: Record<Severity, ReturnType<typeof rgb>> = {
|
||||
mild: rgb(0.55, 0.65, 0.45),
|
||||
moderate: rgb(0.85, 0.55, 0.18),
|
||||
severe: rgb(0.78, 0.2, 0.2),
|
||||
}
|
||||
|
||||
const SECTION_TEXT_SIZE = 10
|
||||
const SEPARATOR_GLYPH = '•'
|
||||
const SEPARATOR_SIZE = 14
|
||||
const SEPARATOR_SIDE_GAP = 5
|
||||
/** Items of a section joined by this print as a segmented line. */
|
||||
const ITEM_JOIN = ' · '
|
||||
|
||||
/** Width of the visible separator block including the empty space on each side. */
|
||||
function separatorWidth(fonts: EmbeddedFonts): number {
|
||||
return (
|
||||
measure(fonts.bodyBold, SEPARATOR_GLYPH, SEPARATOR_SIZE) +
|
||||
SEPARATOR_SIDE_GAP * 2
|
||||
)
|
||||
}
|
||||
|
||||
/** Counts the line breaks a list of items would consume when laid out on a maxWidth line. */
|
||||
function countSegmentedLines(
|
||||
items: string[],
|
||||
fonts: EmbeddedFonts,
|
||||
maxWidth: number,
|
||||
): number {
|
||||
if (items.length === 0) return 1
|
||||
const sepW = separatorWidth(fonts)
|
||||
let lines = 1
|
||||
let x = 0
|
||||
for (let i = 0; i < items.length; i += 1) {
|
||||
const itemW = measure(fonts.bodyRegular, items[i]!, SECTION_TEXT_SIZE)
|
||||
if (x + itemW > maxWidth && x > 0) {
|
||||
lines += 1
|
||||
x = 0
|
||||
}
|
||||
x += itemW
|
||||
if (i < items.length - 1) {
|
||||
if (x + sepW > maxWidth) {
|
||||
lines += 1
|
||||
x = 0
|
||||
} else {
|
||||
x += sepW
|
||||
}
|
||||
}
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
interface SegmentCursor {
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
function drawSeparator(
|
||||
page: PDFPage,
|
||||
cursor: SegmentCursor,
|
||||
fonts: EmbeddedFonts,
|
||||
): void {
|
||||
const baselineOffset = (SEPARATOR_SIZE - SECTION_TEXT_SIZE) * 0.3
|
||||
drawText(page, SEPARATOR_GLYPH, {
|
||||
x: cursor.x + SEPARATOR_SIDE_GAP,
|
||||
y: cursor.y - baselineOffset,
|
||||
size: SEPARATOR_SIZE,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a list of items separated by a visibly larger accent-coloured
|
||||
* bullet. Returns the cursor y *below* the last line drawn.
|
||||
*/
|
||||
function drawSegmentedText(
|
||||
page: PDFPage,
|
||||
items: string[],
|
||||
start: SegmentCursor,
|
||||
maxWidth: number,
|
||||
fonts: EmbeddedFonts,
|
||||
): number {
|
||||
if (items.length === 0) return start.y - TEXT_LINE_HEIGHT
|
||||
const sepW = separatorWidth(fonts)
|
||||
const cursor = { ...start }
|
||||
for (let i = 0; i < items.length; i += 1) {
|
||||
const item = items[i]!
|
||||
const itemW = measure(fonts.bodyRegular, item, SECTION_TEXT_SIZE)
|
||||
if (cursor.x + itemW > start.x + maxWidth && cursor.x > start.x) {
|
||||
cursor.x = start.x
|
||||
cursor.y -= TEXT_LINE_HEIGHT
|
||||
}
|
||||
drawText(page, item, {
|
||||
x: cursor.x,
|
||||
y: cursor.y,
|
||||
size: SECTION_TEXT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
cursor.x += itemW
|
||||
if (i === items.length - 1) continue
|
||||
if (cursor.x + sepW > start.x + maxWidth) {
|
||||
cursor.x = start.x
|
||||
cursor.y -= TEXT_LINE_HEIGHT
|
||||
} else {
|
||||
drawSeparator(page, cursor, fonts)
|
||||
cursor.x += sepW
|
||||
}
|
||||
}
|
||||
return cursor.y - TEXT_LINE_HEIGHT
|
||||
}
|
||||
|
||||
/** Parameters needed to render one observation page. */
|
||||
export interface ObservationPageContext {
|
||||
pdfDoc: PDFDocument
|
||||
report: Report
|
||||
observation: Observation
|
||||
obsIndex: number
|
||||
sheet: SheetIndex
|
||||
snapshot: SheetSnapshot
|
||||
ctx: RenderContext
|
||||
headerAssets: HeaderAssets
|
||||
rasterizer: Rasterizer
|
||||
warnings: ExportWarning[]
|
||||
}
|
||||
|
||||
interface PageDrawContext {
|
||||
page: PDFPage
|
||||
fonts: EmbeddedFonts
|
||||
width: number
|
||||
}
|
||||
|
||||
interface RenderedImage {
|
||||
label: string
|
||||
img: PDFImage
|
||||
aspect: number
|
||||
}
|
||||
|
||||
interface ObservationSection {
|
||||
label: string
|
||||
value: string
|
||||
}
|
||||
|
||||
function drawSeverityPill(
|
||||
draw: PageDrawContext,
|
||||
severity: Severity,
|
||||
labels: PdfLabels,
|
||||
anchor: { numW: number; titleY: number },
|
||||
): void {
|
||||
const { page, fonts } = draw
|
||||
const sevText = labels[`severity.${severity}`].toUpperCase()
|
||||
const sevSize = 9
|
||||
const padX = 8
|
||||
const padY = 4
|
||||
const pillW = measure(fonts.bodyBold, sevText, sevSize) + padX * 2
|
||||
const pillH = sevSize + padY * 2
|
||||
const pillX = MARGIN_X + anchor.numW + 14
|
||||
const pillY = anchor.titleY + 4
|
||||
page.drawRectangle({
|
||||
x: pillX,
|
||||
y: pillY,
|
||||
width: pillW,
|
||||
height: pillH,
|
||||
color: SEVERITY_BG[severity],
|
||||
})
|
||||
drawText(page, sevText, {
|
||||
x: pillX + padX,
|
||||
y: pillY + padY,
|
||||
size: sevSize,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_WHITE,
|
||||
})
|
||||
}
|
||||
|
||||
function drawObservationTitleBlock(
|
||||
draw: PageDrawContext,
|
||||
labels: PdfLabels,
|
||||
obsIndex: number,
|
||||
severity: Severity | undefined,
|
||||
): number {
|
||||
const { page, fonts } = draw
|
||||
const { height } = page.getSize()
|
||||
const eyebrowY = height - EYEBROW_Y_OFFSET
|
||||
const titleY = height - TITLE_Y_OFFSET
|
||||
const obsLabel = String(obsIndex + 1).padStart(2, '0')
|
||||
drawText(page, labels['pdf.eyebrow.observation'], {
|
||||
x: MARGIN_X,
|
||||
y: eyebrowY,
|
||||
size: 9,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
drawText(page, obsLabel, {
|
||||
x: MARGIN_X,
|
||||
y: titleY,
|
||||
size: 22,
|
||||
font: fonts.headingRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
if (severity) {
|
||||
const numW = measure(fonts.headingRegular, obsLabel, 22)
|
||||
drawSeverityPill(draw, severity, labels, { numW, titleY })
|
||||
}
|
||||
page.drawLine({
|
||||
start: { x: MARGIN_X, y: titleY - TITLE_RULE_OFFSET },
|
||||
end: { x: MARGIN_X + TITLE_RULE_WIDTH, y: titleY - TITLE_RULE_OFFSET },
|
||||
thickness: 2,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
return titleY
|
||||
}
|
||||
|
||||
/** Unique views the observation touches and the snapshot holds, main first. */
|
||||
export function observationViewIds(
|
||||
sheet: SheetIndex,
|
||||
observation: Observation,
|
||||
): string[] {
|
||||
return [...new Set(observation.zones.map((z) => z.viewId))]
|
||||
.filter((id) => sheet.view(id))
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Number(b === sheet.mainView.id) - Number(a === sheet.mainView.id),
|
||||
)
|
||||
}
|
||||
|
||||
function viewLabel(
|
||||
sheet: SheetIndex,
|
||||
viewId: string,
|
||||
ctx: RenderContext,
|
||||
): string {
|
||||
const view = sheet.view(viewId)!
|
||||
if (view.kind === 'main') return ctx.labels['pdf.view.general']
|
||||
const name = pickLabel(view.name, ctx.locale).toUpperCase()
|
||||
return `${ctx.labels['pdf.view.detail_prefix']}${name}`
|
||||
}
|
||||
|
||||
interface RasterisedView {
|
||||
viewId: string
|
||||
png: Uint8Array | null
|
||||
}
|
||||
|
||||
/** One view rasterised; a failure yields null and a warning, never a throw. */
|
||||
async function rasteriseView(
|
||||
page: ObservationPageContext,
|
||||
viewId: string,
|
||||
): Promise<RasterisedView> {
|
||||
try {
|
||||
const { svg, size } = renderHighlightedView(
|
||||
page.snapshot,
|
||||
viewId,
|
||||
page.observation,
|
||||
)
|
||||
return { viewId, png: await page.rasterizer(svg, size) }
|
||||
} catch {
|
||||
page.warnings.push({
|
||||
kind: 'view_raster_failed',
|
||||
observationId: page.observation.id,
|
||||
viewId,
|
||||
})
|
||||
return { viewId, png: null }
|
||||
}
|
||||
}
|
||||
|
||||
/** Rasterisation in parallel, embedding in view order so bytes stay stable. */
|
||||
async function buildObservationImages(
|
||||
page: ObservationPageContext,
|
||||
): Promise<RenderedImage[]> {
|
||||
const viewIds = observationViewIds(page.sheet, page.observation)
|
||||
const rasters = await Promise.all(
|
||||
viewIds.map((viewId) => rasteriseView(page, viewId)),
|
||||
)
|
||||
const rendered: RenderedImage[] = []
|
||||
for (const { viewId, png } of rasters) {
|
||||
if (!png) continue
|
||||
try {
|
||||
const img = await page.pdfDoc.embedPng(png)
|
||||
rendered.push({
|
||||
label: viewLabel(page.sheet, viewId, page.ctx),
|
||||
img,
|
||||
aspect: img.width > 0 ? img.height / img.width : 0.6,
|
||||
})
|
||||
} catch {
|
||||
page.warnings.push({
|
||||
kind: 'view_raster_failed',
|
||||
observationId: page.observation.id,
|
||||
viewId,
|
||||
})
|
||||
}
|
||||
}
|
||||
return rendered
|
||||
}
|
||||
|
||||
/** Zone name: snapshot annotation, else the report's label snapshot, else the id. */
|
||||
function zoneText(z: ReportZone, sheet: SheetIndex, locale: PdfLocale): string {
|
||||
const annotation = sheet.annotation(z.annotationId)
|
||||
if (annotation) return pickLabel(sheet.name(annotation), locale)
|
||||
const snapshot =
|
||||
locale === 'en'
|
||||
? z.labelEnSnapshot || z.labelFrSnapshot
|
||||
: z.labelFrSnapshot || z.labelEnSnapshot
|
||||
return snapshot || z.annotationId
|
||||
}
|
||||
|
||||
function sideLabel(side: 'left' | 'right', labels: PdfLabels): string {
|
||||
return labels[side === 'left' ? 'lateral.left' : 'lateral.right']
|
||||
}
|
||||
|
||||
function describeObservationZones(
|
||||
zones: ReportZone[],
|
||||
sheet: SheetIndex,
|
||||
ctx: RenderContext,
|
||||
): string {
|
||||
return zones
|
||||
.map((z) => {
|
||||
const v = z.vertebrae?.length
|
||||
? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})`
|
||||
: ''
|
||||
const side = z.side ? ` (${sideLabel(z.side, ctx.labels)})` : ''
|
||||
return `${zoneText(z, sheet, ctx.locale)}${v}${side}`
|
||||
})
|
||||
.join(ITEM_JOIN)
|
||||
}
|
||||
|
||||
/** Finding group heading: snapshot finding-zone name, else the id as is. */
|
||||
function findingZoneName(
|
||||
zoneId: string,
|
||||
sheet: SheetIndex,
|
||||
locale: PdfLocale,
|
||||
): string {
|
||||
const zone = sheet.findingZone(zoneId)
|
||||
return zone ? pickLabel(zone.name, locale) : zoneId
|
||||
}
|
||||
|
||||
function findingText(f: Finding, locale: PdfLocale): string {
|
||||
const label = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot
|
||||
return f.requiresVetReferral ? `(!) ${label}` : label
|
||||
}
|
||||
|
||||
/** Groups findings by zone+side, one section per group; snapshots give the text. */
|
||||
function buildFindingsSections(
|
||||
findings: Finding[],
|
||||
sheet: SheetIndex,
|
||||
ctx: RenderContext,
|
||||
): ObservationSection[] {
|
||||
const byZoneSide = new Map<string, Finding[]>()
|
||||
for (const f of findings) {
|
||||
const key = f.side ? `${f.findingZoneId}:${f.side}` : f.findingZoneId
|
||||
byZoneSide.set(key, [...(byZoneSide.get(key) ?? []), f])
|
||||
}
|
||||
const sections: ObservationSection[] = []
|
||||
for (const [key, group] of byZoneSide) {
|
||||
const zoneId = key.split(':')[0]!
|
||||
const side = group[0]?.side
|
||||
let zoneName = findingZoneName(zoneId, sheet, ctx.locale)
|
||||
if (side) zoneName = `${zoneName} (${sideLabel(side, ctx.labels)})`
|
||||
sections.push({
|
||||
label: `${ctx.labels['pdf.section.findings_prefix']}${zoneName.toUpperCase()}`,
|
||||
value: group.map((f) => findingText(f, ctx.locale)).join(ITEM_JOIN),
|
||||
})
|
||||
}
|
||||
return sections
|
||||
}
|
||||
|
||||
function buildObservationSections(
|
||||
observation: Observation,
|
||||
sheet: SheetIndex,
|
||||
ctx: RenderContext,
|
||||
): ObservationSection[] {
|
||||
const { labels } = ctx
|
||||
const zonesText = describeObservationZones(observation.zones, sheet, ctx)
|
||||
const sections: ObservationSection[] = [
|
||||
{
|
||||
label: labels['pdf.section.zones'],
|
||||
value: zonesText || labels['pdf.empty'],
|
||||
},
|
||||
...buildFindingsSections(observation.findings, sheet, ctx),
|
||||
]
|
||||
if (observation.freeTextFindings.length) {
|
||||
sections.push({
|
||||
label: labels['pdf.section.free_findings'],
|
||||
value: observation.freeTextFindings.join(ITEM_JOIN),
|
||||
})
|
||||
}
|
||||
if (observation.severity) {
|
||||
sections.push({
|
||||
label: labels['pdf.section.severity'],
|
||||
value: labels[`severity.${observation.severity}`],
|
||||
})
|
||||
}
|
||||
if (observation.comment.trim()) {
|
||||
sections.push({
|
||||
label: labels['pdf.section.comment'],
|
||||
value: observation.comment.trim(),
|
||||
})
|
||||
}
|
||||
return sections
|
||||
}
|
||||
|
||||
function estimateSectionsHeight(
|
||||
sections: ObservationSection[],
|
||||
fonts: EmbeddedFonts,
|
||||
maxTextW: number,
|
||||
): number {
|
||||
let h = TEXT_TOP_GAP
|
||||
for (const { value } of sections) {
|
||||
const lineCount = value.includes(ITEM_JOIN)
|
||||
? countSegmentedLines(value.split(ITEM_JOIN), fonts, maxTextW)
|
||||
: wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW).length
|
||||
h +=
|
||||
SECTION_LABEL_GAP + 9 + lineCount * TEXT_LINE_HEIGHT + SECTION_BLOCK_GAP
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
interface ImageGrid {
|
||||
cols: number
|
||||
rows: number
|
||||
cellW: number
|
||||
offsetX: number
|
||||
rowBudget: number
|
||||
}
|
||||
|
||||
function imageGridOf(
|
||||
rendered: RenderedImage[],
|
||||
width: number,
|
||||
availH: number,
|
||||
): ImageGrid {
|
||||
const isSingle = rendered.length === 1
|
||||
const cols = isSingle ? 1 : 2
|
||||
const rows = Math.ceil(rendered.length / cols)
|
||||
const fullCellW = (width - MARGIN_X * 2 - IMAGE_COL_GAP * (cols - 1)) / cols
|
||||
const cellW = isSingle ? fullCellW / 2 : fullCellW
|
||||
return {
|
||||
cols,
|
||||
rows,
|
||||
cellW,
|
||||
offsetX: isSingle ? (fullCellW - cellW) / 2 : 0,
|
||||
rowBudget: Math.max(
|
||||
IMAGE_MIN_CELL_H,
|
||||
(availH - rows * IMAGE_LABEL_GAP - (rows - 1) * IMAGE_ROW_GAP) / rows,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/** One row of the grid: labels above, then the images; returns the row height. */
|
||||
function drawImageRow(
|
||||
draw: PageDrawContext,
|
||||
rowItems: RenderedImage[],
|
||||
grid: ImageGrid,
|
||||
topY: number,
|
||||
): number {
|
||||
const { page, fonts } = draw
|
||||
const cellHs = rowItems.map((it) =>
|
||||
Math.min(grid.cellW * it.aspect, grid.rowBudget),
|
||||
)
|
||||
const cellX = (c: number) =>
|
||||
MARGIN_X + grid.offsetX + c * (grid.cellW + IMAGE_COL_GAP)
|
||||
rowItems.forEach((it, c) => {
|
||||
drawText(page, it.label, {
|
||||
x: cellX(c),
|
||||
y: topY,
|
||||
size: 8,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
})
|
||||
const imagesY = topY - IMAGE_LABEL_GAP
|
||||
rowItems.forEach((it, c) => {
|
||||
page.drawImage(it.img, {
|
||||
x: cellX(c),
|
||||
y: imagesY - cellHs[c]!,
|
||||
width: grid.cellW,
|
||||
height: cellHs[c]!,
|
||||
})
|
||||
})
|
||||
return Math.max(0, ...cellHs)
|
||||
}
|
||||
|
||||
/** Lays out the (up to 2-column) image grid; returns the cursor y below it. */
|
||||
function drawObservationImageGrid(
|
||||
draw: PageDrawContext,
|
||||
rendered: RenderedImage[],
|
||||
startY: number,
|
||||
reservedBottom: number,
|
||||
): number {
|
||||
if (rendered.length === 0) return startY
|
||||
const availH = Math.max(IMAGE_MIN_CELL_H, startY - reservedBottom)
|
||||
const grid = imageGridOf(rendered, draw.width, availH)
|
||||
let cursorY = startY
|
||||
for (let r = 0; r < grid.rows; r += 1) {
|
||||
const rowItems = rendered.slice(r * grid.cols, r * grid.cols + grid.cols)
|
||||
const rowH = drawImageRow(draw, rowItems, grid, cursorY)
|
||||
cursorY -= IMAGE_LABEL_GAP + rowH
|
||||
if (r < grid.rows - 1) cursorY -= IMAGE_ROW_GAP
|
||||
}
|
||||
return cursorY - IMAGE_BOTTOM_GAP
|
||||
}
|
||||
|
||||
function drawSectionValue(
|
||||
draw: PageDrawContext,
|
||||
value: string,
|
||||
startY: number,
|
||||
maxTextW: number,
|
||||
): number {
|
||||
const { page, fonts } = draw
|
||||
if (value.includes(ITEM_JOIN)) {
|
||||
return drawSegmentedText(
|
||||
page,
|
||||
value.split(ITEM_JOIN),
|
||||
{ x: MARGIN_X, y: startY },
|
||||
maxTextW,
|
||||
fonts,
|
||||
)
|
||||
}
|
||||
let cursorY = startY
|
||||
for (const line of wrapLines(
|
||||
value,
|
||||
fonts.bodyRegular,
|
||||
SECTION_TEXT_SIZE,
|
||||
maxTextW,
|
||||
)) {
|
||||
drawText(page, line, {
|
||||
x: MARGIN_X,
|
||||
y: cursorY,
|
||||
size: SECTION_TEXT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
cursorY -= TEXT_LINE_HEIGHT
|
||||
}
|
||||
return cursorY
|
||||
}
|
||||
|
||||
function drawObservationSections(
|
||||
draw: PageDrawContext,
|
||||
sections: ObservationSection[],
|
||||
startY: number,
|
||||
maxTextW: number,
|
||||
): number {
|
||||
let cursorY = startY
|
||||
for (const { label, value } of sections) {
|
||||
drawText(draw.page, label, {
|
||||
x: MARGIN_X,
|
||||
y: cursorY,
|
||||
size: 8,
|
||||
font: draw.fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
cursorY -= SECTION_LABEL_GAP + 9
|
||||
cursorY = drawSectionValue(draw, value, cursorY, maxTextW)
|
||||
cursorY -= SECTION_BLOCK_GAP
|
||||
}
|
||||
return cursorY
|
||||
}
|
||||
|
||||
export async function addObservationPage(
|
||||
input: ObservationPageContext,
|
||||
): Promise<void> {
|
||||
const { pdfDoc, report, observation, obsIndex, sheet, ctx, headerAssets } =
|
||||
input
|
||||
const page = pdfDoc.addPage(PageSizes.A4)
|
||||
const { width } = page.getSize()
|
||||
drawHeader(page, report, ctx, headerAssets)
|
||||
|
||||
const draw: PageDrawContext = { page, fonts: ctx.fonts, width }
|
||||
const titleY = drawObservationTitleBlock(
|
||||
draw,
|
||||
ctx.labels,
|
||||
obsIndex,
|
||||
observation.severity,
|
||||
)
|
||||
const rendered = await buildObservationImages(input)
|
||||
const maxTextW = width - MARGIN_X * 2
|
||||
const sections = buildObservationSections(observation, sheet, ctx)
|
||||
const reservedBottom =
|
||||
MARGIN_BOTTOM +
|
||||
estimateSectionsHeight(sections, ctx.fonts, maxTextW) +
|
||||
IMAGE_BOTTOM_GAP
|
||||
let cursorY = drawObservationImageGrid(
|
||||
draw,
|
||||
rendered,
|
||||
titleY - IMAGE_TOP_GAP,
|
||||
reservedBottom,
|
||||
)
|
||||
cursorY -= TEXT_TOP_GAP
|
||||
drawObservationSections(draw, sections, cursorY, maxTextW)
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import type { PDFFont, PDFPage, PDFPageDrawTextOptions } from 'pdf-lib'
|
||||
import { safeText } from '../text'
|
||||
|
||||
/**
|
||||
* Every string reaches pdf-lib through these three helpers, so a glyph the
|
||||
* standard fonts cannot encode never throws at draw or measure time.
|
||||
*/
|
||||
|
||||
export function measure(font: PDFFont, text: string, size: number): number {
|
||||
return font.widthOfTextAtSize(safeText(text), size)
|
||||
}
|
||||
|
||||
export function drawText(
|
||||
page: PDFPage,
|
||||
text: string,
|
||||
options: PDFPageDrawTextOptions,
|
||||
): void {
|
||||
page.drawText(safeText(text), options)
|
||||
}
|
||||
|
||||
/**
|
||||
* Greedy word-wrap: splits `text` into lines whose rendered width at
|
||||
* `size` points stays within `max` for the given font. Whitespace of any
|
||||
* kind separates words first, then each word is made safe.
|
||||
*/
|
||||
export function wrapLines(
|
||||
text: string,
|
||||
font: PDFFont,
|
||||
size: number,
|
||||
max: number,
|
||||
): string[] {
|
||||
const words = text.split(/\s+/).map(safeText)
|
||||
const lines: string[] = []
|
||||
let line = ''
|
||||
for (const w of words) {
|
||||
const test = line ? `${line} ${w}` : w
|
||||
if (measure(font, test, size) > max && line) {
|
||||
lines.push(line)
|
||||
line = w
|
||||
} else {
|
||||
line = test
|
||||
}
|
||||
}
|
||||
if (line) lines.push(line)
|
||||
return lines
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { DOMParser, XMLSerializer, type Element } from '@xmldom/xmldom'
|
||||
import { SvgRejectedError } from '../errors'
|
||||
|
||||
/**
|
||||
* SVG text in, DOM root out, with xmldom (one code path in Node and in the
|
||||
* browser). Entity declarations are refused before parsing; a parse error
|
||||
* is reported as a typed rejection and its message, which may echo the
|
||||
* input, is never logged.
|
||||
*/
|
||||
|
||||
const ENTITY_MARKUP = /<!(DOCTYPE|ENTITY)/i
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg'
|
||||
|
||||
function rejectOnError(level: 'warning' | 'error' | 'fatalError'): void {
|
||||
if (level !== 'warning') throw new SvgRejectedError('malformed')
|
||||
}
|
||||
|
||||
export function parseSvg(text: string): Element {
|
||||
if (ENTITY_MARKUP.test(text)) throw new SvgRejectedError('doctype')
|
||||
let root: Element | null
|
||||
try {
|
||||
const parser = new DOMParser({ onError: rejectOnError })
|
||||
root = parser.parseFromString(text, 'image/svg+xml').documentElement
|
||||
} catch (error) {
|
||||
if (error instanceof SvgRejectedError) throw error
|
||||
throw new SvgRejectedError('malformed')
|
||||
}
|
||||
if (!root || root.localName !== 'svg' || root.namespaceURI !== SVG_NS) {
|
||||
throw new SvgRejectedError('not_svg')
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
/** The root element alone: no XML declaration, as the app serialised it. */
|
||||
export function serializeSvg(root: Element): string {
|
||||
return new XMLSerializer().serializeToString(root)
|
||||
}
|
||||
@@ -1,281 +0,0 @@
|
||||
import type { Attr, Element, Node } from '@xmldom/xmldom'
|
||||
import { SvgRejectedError } from '../errors'
|
||||
|
||||
/**
|
||||
* Allowlist sanitiser for the sheet drawings and the branding SVGs
|
||||
* (STEP6 §15), on DOM Level 2 only. Elements and attributes outside the
|
||||
* inventory of the real assets plus structural needs are removed with
|
||||
* their subtree; `href` and `url(…)` must stay inside the document; no
|
||||
* value carries a backslash (a CSS escape such as `u\72l(` would hide a
|
||||
* reference from the rules below); a `style` or presentation attribute may
|
||||
* call no function but `url(#…)`; the halo filters are clamped. Element,
|
||||
* nesting and `<use>` counters refuse an oversized tree. The caller learns
|
||||
* what was removed (names only, never values).
|
||||
*/
|
||||
|
||||
export const SANITIZER_CAPS = {
|
||||
elements: 20_000,
|
||||
depth: 64,
|
||||
uses: 256,
|
||||
stdDeviation: 100,
|
||||
} as const
|
||||
|
||||
const ALLOWED_ELEMENTS = new Set([
|
||||
'svg',
|
||||
'g',
|
||||
'path',
|
||||
'circle',
|
||||
'ellipse',
|
||||
'rect',
|
||||
'line',
|
||||
'polyline',
|
||||
'polygon',
|
||||
'defs',
|
||||
'linearGradient',
|
||||
'radialGradient',
|
||||
'stop',
|
||||
'filter',
|
||||
'feGaussianBlur',
|
||||
'feMerge',
|
||||
'feMergeNode',
|
||||
'feOffset',
|
||||
'feFlood',
|
||||
'feComposite',
|
||||
'feBlend',
|
||||
'feColorMatrix',
|
||||
'clipPath',
|
||||
'mask',
|
||||
'title',
|
||||
'desc',
|
||||
'switch',
|
||||
'use',
|
||||
])
|
||||
|
||||
const ALLOWED_ATTRIBUTES = new Set([
|
||||
'id',
|
||||
'class',
|
||||
'd',
|
||||
'cx',
|
||||
'cy',
|
||||
'r',
|
||||
'rx',
|
||||
'ry',
|
||||
'x',
|
||||
'y',
|
||||
'x1',
|
||||
'y1',
|
||||
'x2',
|
||||
'y2',
|
||||
'dx',
|
||||
'dy',
|
||||
'width',
|
||||
'height',
|
||||
'points',
|
||||
'transform',
|
||||
'viewBox',
|
||||
'version',
|
||||
'preserveAspectRatio',
|
||||
'fill',
|
||||
'fill-opacity',
|
||||
'fill-rule',
|
||||
'stroke',
|
||||
'stroke-width',
|
||||
'stroke-linecap',
|
||||
'stroke-linejoin',
|
||||
'stroke-opacity',
|
||||
'stroke-dasharray',
|
||||
'stroke-dashoffset',
|
||||
'stroke-miterlimit',
|
||||
'opacity',
|
||||
'filter',
|
||||
'clip-path',
|
||||
'clip-rule',
|
||||
'mask',
|
||||
'display',
|
||||
'visibility',
|
||||
'color',
|
||||
'gradientUnits',
|
||||
'gradientTransform',
|
||||
'spreadMethod',
|
||||
'offset',
|
||||
'stop-color',
|
||||
'stop-opacity',
|
||||
'stdDeviation',
|
||||
'in',
|
||||
'in2',
|
||||
'result',
|
||||
'mode',
|
||||
'operator',
|
||||
'k1',
|
||||
'k2',
|
||||
'k3',
|
||||
'k4',
|
||||
'flood-color',
|
||||
'flood-opacity',
|
||||
'type',
|
||||
'values',
|
||||
'color-interpolation-filters',
|
||||
'filterUnits',
|
||||
'primitiveUnits',
|
||||
'systemLanguage',
|
||||
'font-family',
|
||||
'font-size',
|
||||
'font-weight',
|
||||
'xmlns',
|
||||
'xmlns:xlink',
|
||||
'xlink:href',
|
||||
'href',
|
||||
'style',
|
||||
])
|
||||
|
||||
/** Attributes whose value is CSS-like: a function call there is a reference or an exploit. */
|
||||
const PRESENTATION_ATTRIBUTES = new Set([
|
||||
'fill',
|
||||
'fill-opacity',
|
||||
'fill-rule',
|
||||
'stroke',
|
||||
'stroke-width',
|
||||
'stroke-linecap',
|
||||
'stroke-linejoin',
|
||||
'stroke-opacity',
|
||||
'stroke-dasharray',
|
||||
'stroke-dashoffset',
|
||||
'stroke-miterlimit',
|
||||
'opacity',
|
||||
'filter',
|
||||
'clip-path',
|
||||
'clip-rule',
|
||||
'mask',
|
||||
'display',
|
||||
'visibility',
|
||||
'color',
|
||||
'stop-color',
|
||||
'stop-opacity',
|
||||
'flood-color',
|
||||
'flood-opacity',
|
||||
'color-interpolation-filters',
|
||||
'font-family',
|
||||
'font-size',
|
||||
'font-weight',
|
||||
])
|
||||
|
||||
const LOCAL_REFERENCE = /^#[A-Za-z_][\w.:-]*$/
|
||||
const URL_FUNCTION = /url\(\s*['"]?\s*(.?)/gi
|
||||
const LOCAL_URL_OPEN = /url\(\s*['"]?\s*#/gi
|
||||
const STYLE_FORBIDDEN =
|
||||
/expression\(|image-set\(|@import|javascript:|behavior:/i
|
||||
|
||||
export interface SanitizeOutcome {
|
||||
/** Removed element names and `element@attribute` pairs, in document order. */
|
||||
removed: string[]
|
||||
}
|
||||
|
||||
const ELEMENT_NODE = 1
|
||||
|
||||
function isElement(node: Node): node is Element {
|
||||
return node.nodeType === ELEMENT_NODE
|
||||
}
|
||||
|
||||
function elementChildren(node: Node): Element[] {
|
||||
return Array.from(node.childNodes).filter(isElement)
|
||||
}
|
||||
|
||||
/** Every `url(` in the value must point inside the document (`url(#…)`). */
|
||||
function urlsAreLocal(value: string): boolean {
|
||||
for (const match of value.matchAll(URL_FUNCTION)) {
|
||||
if (match[1] !== '#') return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function hrefIsLocal(value: string): boolean {
|
||||
return LOCAL_REFERENCE.test(value.trim())
|
||||
}
|
||||
|
||||
/** Any `(` left once the `url(#` openings are gone is a function we never allow. */
|
||||
function callsOnlyLocalUrl(value: string): boolean {
|
||||
return !value.replace(LOCAL_URL_OPEN, '').includes('(')
|
||||
}
|
||||
|
||||
/** Whether an allowed attribute keeps its value, by name-specific rule. */
|
||||
function attributeAcceptable(name: string, value: string): boolean {
|
||||
if (value.includes('\\')) return false
|
||||
if (!urlsAreLocal(value)) return false
|
||||
if (name === 'href' || name === 'xlink:href') return hrefIsLocal(value)
|
||||
if (name === 'style') {
|
||||
return !STYLE_FORBIDDEN.test(value) && callsOnlyLocalUrl(value)
|
||||
}
|
||||
if (PRESENTATION_ATTRIBUTES.has(name)) return callsOnlyLocalUrl(value)
|
||||
return true
|
||||
}
|
||||
|
||||
/** Clamps every number of a `stdDeviation` list; rewrites only when needed. */
|
||||
function clampStdDeviation(element: Element): void {
|
||||
const raw = element.getAttribute('stdDeviation')
|
||||
if (raw === null) return
|
||||
const numbers = raw
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.map(Number)
|
||||
if (numbers.some(Number.isNaN)) {
|
||||
element.removeAttribute('stdDeviation')
|
||||
return
|
||||
}
|
||||
if (numbers.every((n) => n <= SANITIZER_CAPS.stdDeviation)) return
|
||||
const clamped = numbers.map((n) => Math.min(n, SANITIZER_CAPS.stdDeviation))
|
||||
element.setAttribute('stdDeviation', clamped.join(' '))
|
||||
}
|
||||
|
||||
function sanitizeAttributes(element: Element, removed: string[]): void {
|
||||
const attributes: Attr[] = Array.from(element.attributes)
|
||||
for (const attribute of attributes) {
|
||||
const { name, value } = attribute
|
||||
const keep =
|
||||
ALLOWED_ATTRIBUTES.has(name) && attributeAcceptable(name, value)
|
||||
if (keep) continue
|
||||
element.removeAttribute(name)
|
||||
removed.push(`${element.tagName}@${name}`)
|
||||
}
|
||||
clampStdDeviation(element)
|
||||
}
|
||||
|
||||
interface Walk {
|
||||
removed: string[]
|
||||
elements: number
|
||||
uses: number
|
||||
}
|
||||
|
||||
function visit(element: Element, depth: number, walk: Walk): void {
|
||||
walk.elements += 1
|
||||
if (walk.elements > SANITIZER_CAPS.elements) {
|
||||
throw new SvgRejectedError('too_many_elements')
|
||||
}
|
||||
if (depth > SANITIZER_CAPS.depth) throw new SvgRejectedError('too_deep')
|
||||
if (element.tagName === 'use') {
|
||||
walk.uses += 1
|
||||
if (walk.uses > SANITIZER_CAPS.uses) {
|
||||
throw new SvgRejectedError('too_many_uses')
|
||||
}
|
||||
}
|
||||
sanitizeAttributes(element, walk.removed)
|
||||
for (const child of elementChildren(element)) {
|
||||
if (ALLOWED_ELEMENTS.has(child.tagName)) {
|
||||
visit(child, depth + 1, walk)
|
||||
} else {
|
||||
element.removeChild(child)
|
||||
walk.removed.push(child.tagName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitises the tree under `root` in place. Throws SvgRejectedError when a
|
||||
* counter cap is exceeded; the tree is then unusable and the caller drops
|
||||
* it. Returns the names of what was removed (empty on the real assets).
|
||||
*/
|
||||
export function sanitizeSvgRoot(root: Element): SanitizeOutcome {
|
||||
if (root.tagName !== 'svg') throw new SvgRejectedError('not_svg')
|
||||
const walk: Walk = { removed: [], elements: 0, uses: 0 }
|
||||
visit(root, 1, walk)
|
||||
return { removed: walk.removed }
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
import type { Element } from '@xmldom/xmldom'
|
||||
import { composeViewSvg } from '@faunosteo/anatomy/render'
|
||||
import type { Observation, SheetSnapshot, SheetView } from '@faunosteo/domain'
|
||||
import { parseSvg, serializeSvg } from './parse'
|
||||
import { sanitizeSvgRoot } from './sanitize'
|
||||
|
||||
/**
|
||||
* The picture of one view of an observation: the snapshot's drawing,
|
||||
* sanitised, framed on the view and overlaid with the observation's zones
|
||||
* highlighted (accent fill, halo on the main view). The raster size follows
|
||||
* today's rule, width 1200 px and the view box aspect, with the aspect
|
||||
* clamped so an untrusted `viewBox` cannot request a huge canvas.
|
||||
*/
|
||||
|
||||
export const RASTER_WIDTH_PX = 1200
|
||||
const ASPECT_MIN = 0.2
|
||||
const ASPECT_MAX = 2.0
|
||||
const ASPECT_FALLBACK = 0.6
|
||||
|
||||
export interface RasterSize {
|
||||
widthPx: number
|
||||
heightPx: number
|
||||
}
|
||||
|
||||
export interface RenderedSvg {
|
||||
svg: string
|
||||
size: RasterSize
|
||||
}
|
||||
|
||||
/** A usable dimension: finite and strictly positive (`1e999` parses to Infinity). */
|
||||
function isPositiveFinite(value: number | undefined): value is number {
|
||||
return value !== undefined && Number.isFinite(value) && value > 0
|
||||
}
|
||||
|
||||
/** Height over width of a `viewBox` value, or the fallback when unusable. */
|
||||
function aspectOf(viewBox: string | null): number {
|
||||
const parts = (viewBox ?? '')
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.map(Number)
|
||||
const [, , width, height] = parts
|
||||
if (
|
||||
parts.length !== 4 ||
|
||||
!isPositiveFinite(width) ||
|
||||
!isPositiveFinite(height)
|
||||
) {
|
||||
return ASPECT_FALLBACK
|
||||
}
|
||||
return height / width
|
||||
}
|
||||
|
||||
export function rasterSizeOf(viewBox: string | null): RasterSize {
|
||||
const aspect = Math.min(ASPECT_MAX, Math.max(ASPECT_MIN, aspectOf(viewBox)))
|
||||
return {
|
||||
widthPx: RASTER_WIDTH_PX,
|
||||
heightPx: Math.max(1, Math.round(RASTER_WIDTH_PX * aspect)),
|
||||
}
|
||||
}
|
||||
|
||||
/** The asset a view draws: its own, else the first up its parent chain. */
|
||||
export function assetIdOfView(
|
||||
view: SheetView,
|
||||
views: ReadonlyMap<string, SheetView>,
|
||||
): string | null {
|
||||
const visited = new Set<string>()
|
||||
let current: SheetView | undefined = view
|
||||
while (current && !visited.has(current.id)) {
|
||||
if (current.svg_asset_id !== null) return current.svg_asset_id
|
||||
visited.add(current.id)
|
||||
current =
|
||||
current.kind === 'detail' ? views.get(current.parent_view_id) : undefined
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function assetText(sheet: SheetSnapshot, view: SheetView): string {
|
||||
const views = new Map(sheet.document.views.map((v) => [v.id, v]))
|
||||
const assetId = assetIdOfView(view, views)
|
||||
const asset = sheet.assets.find((a) => a.svgAssetId === assetId)
|
||||
if (!asset) throw new Error(`view "${view.id}" reaches no asset`)
|
||||
return asset.svg
|
||||
}
|
||||
|
||||
/** Parse, sanitise: the only way an asset text becomes a tree here. */
|
||||
export function cleanSvgRoot(text: string): Element {
|
||||
const root = parseSvg(text)
|
||||
sanitizeSvgRoot(root)
|
||||
return root
|
||||
}
|
||||
|
||||
/** The view's drawing with the observation's zones of that view highlighted. */
|
||||
export function renderHighlightedView(
|
||||
sheet: SheetSnapshot,
|
||||
viewId: string,
|
||||
observation: Observation,
|
||||
): RenderedSvg {
|
||||
const view = sheet.document.views.find((v) => v.id === viewId)
|
||||
if (!view) throw new Error(`unknown view "${viewId}"`)
|
||||
const annotationIds = new Set(
|
||||
observation.zones
|
||||
.filter((zone) => zone.viewId === viewId)
|
||||
.map((zone) => zone.annotationId),
|
||||
)
|
||||
const root = cleanSvgRoot(assetText(sheet, view))
|
||||
composeViewSvg({
|
||||
root,
|
||||
document: sheet.document,
|
||||
viewId,
|
||||
highlight: { annotationIds, halo: view.kind === 'main' },
|
||||
})
|
||||
return {
|
||||
svg: serializeSvg(root),
|
||||
size: rasterSizeOf(root.getAttribute('viewBox')),
|
||||
}
|
||||
}
|
||||
|
||||
export function composeHighlightedViewSvg(
|
||||
sheet: SheetSnapshot,
|
||||
viewId: string,
|
||||
observation: Observation,
|
||||
): string {
|
||||
return renderHighlightedView(sheet, viewId, observation).svg
|
||||
}
|
||||
|
||||
/** A branding SVG made safe, with the raster size its own viewBox gives. */
|
||||
export function renderBrandingSvg(text: string): RenderedSvg {
|
||||
const root = cleanSvgRoot(text)
|
||||
return {
|
||||
svg: serializeSvg(root),
|
||||
size: rasterSizeOf(root.getAttribute('viewBox')),
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import { Encodings } from '@pdf-lib/standard-fonts'
|
||||
|
||||
/**
|
||||
* The single text ingress of the engine (STEP6 §15). The standard fonts are
|
||||
* WinAnsi-encoded: a glyph outside that table makes pdf-lib throw at draw
|
||||
* or measure time. Control, format and line/paragraph separator characters
|
||||
* are dropped; every other unencodable code point prints as `?`. En and em
|
||||
* dashes, bullets, accents and the euro sign are WinAnsi and survive.
|
||||
*/
|
||||
|
||||
const DROPPED = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu
|
||||
|
||||
function encodable(char: string): string {
|
||||
const codePoint = char.codePointAt(0)
|
||||
if (codePoint === undefined) return ''
|
||||
return Encodings.WinAnsi.canEncodeUnicodeCodePoint(codePoint) ? char : '?'
|
||||
}
|
||||
|
||||
export function safeText(text: string): string {
|
||||
return Array.from(text.replace(DROPPED, ''), encodable).join('')
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import type {
|
||||
Branding,
|
||||
PdfLabelSet,
|
||||
Report,
|
||||
ReportArchiveEnvelope,
|
||||
SheetSnapshot,
|
||||
} from '@faunosteo/domain'
|
||||
import type { PdfLocale } from './render/context'
|
||||
|
||||
export type { PdfLocale }
|
||||
|
||||
/**
|
||||
* Rasterisation is an adapter (STEP6 §3.3): the engine computes the size
|
||||
* and the caller renders (browser Image/canvas, resvg in Node).
|
||||
*/
|
||||
export type Rasterizer = (
|
||||
svg: string,
|
||||
size: { widthPx: number; heightPx: number },
|
||||
) => Promise<Uint8Array>
|
||||
|
||||
export interface ExportInput {
|
||||
report: Report
|
||||
sheet: SheetSnapshot
|
||||
branding: Branding
|
||||
labels: PdfLabelSet
|
||||
locale: PdfLocale
|
||||
rasterizer: Rasterizer
|
||||
/** Drives every date in the file: metadata, attachment, envelope. */
|
||||
exportedAt: Date
|
||||
}
|
||||
|
||||
export type ExportWarning =
|
||||
| { kind: 'view_raster_failed'; observationId: string; viewId: string }
|
||||
| {
|
||||
kind: 'logo_failed'
|
||||
slot: 'headerLogo' | 'footerLogo' | 'poweredBy' | 'partner'
|
||||
}
|
||||
|
||||
export interface ExportResult {
|
||||
pdf: Uint8Array
|
||||
envelope: ReportArchiveEnvelope
|
||||
warnings: ExportWarning[]
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
/**
|
||||
* T3 (STEP6 §7, §17): the engine reproduces every Phase 0 golden, per
|
||||
* report × locale × logo mode. A mismatch is a visible change: the golden
|
||||
* is never edited here.
|
||||
*/
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { PDFDocument } from 'pdf-lib'
|
||||
import { defaultPdfLabels, exportReportArchive } from '../src'
|
||||
import type { PdfLocale } from '../src'
|
||||
import {
|
||||
brandingOf,
|
||||
checkGolden,
|
||||
FIXED_EXPORTED_AT,
|
||||
ONE_PX_PNG,
|
||||
rasterizerOf,
|
||||
readGolden,
|
||||
readLinks,
|
||||
recordDrawing,
|
||||
snapshotViews,
|
||||
TWO_BY_ONE_PNG,
|
||||
type ImageEntry,
|
||||
type LinkEntry,
|
||||
type LogoMode,
|
||||
type TextEntry,
|
||||
type ViewSnapshot,
|
||||
} from './helpers/goldens'
|
||||
import {
|
||||
loadGoldenReports,
|
||||
REPORT_NAMES,
|
||||
type GoldenReports,
|
||||
type ReportName,
|
||||
} from './helpers/reports'
|
||||
|
||||
const MODES: readonly LogoMode[] = ['nologos', 'logos']
|
||||
|
||||
let golden: GoldenReports
|
||||
|
||||
beforeAll(() => {
|
||||
golden = loadGoldenReports()
|
||||
})
|
||||
afterAll(() => vi.restoreAllMocks())
|
||||
|
||||
interface Exported {
|
||||
bytes: Uint8Array
|
||||
texts: TextEntry[]
|
||||
images: ImageEntry[]
|
||||
links: LinkEntry[]
|
||||
}
|
||||
|
||||
async function exportWith(
|
||||
name: ReportName,
|
||||
mode: LogoMode,
|
||||
locale: PdfLocale,
|
||||
): Promise<Exported> {
|
||||
const recording = recordDrawing()
|
||||
try {
|
||||
const { pdf, warnings } = await exportReportArchive({
|
||||
report: golden.reports[name],
|
||||
sheet: golden.snapshots[name],
|
||||
branding: brandingOf(mode),
|
||||
labels: defaultPdfLabels,
|
||||
locale,
|
||||
rasterizer: rasterizerOf(mode),
|
||||
exportedAt: FIXED_EXPORTED_AT,
|
||||
})
|
||||
expect(warnings).toEqual([])
|
||||
const { texts, images } = recording
|
||||
return { bytes: pdf, texts, images, links: await readLinks(pdf) }
|
||||
} finally {
|
||||
recording.stop()
|
||||
}
|
||||
}
|
||||
|
||||
const pagesOf = (entries: readonly { page: number }[]) =>
|
||||
entries.map((e) => e.page)
|
||||
|
||||
describe('golden inputs', () => {
|
||||
it('the 2×1 PNG decodes as 2×1 and the 1×1 as 1×1', async () => {
|
||||
const doc = await PDFDocument.create()
|
||||
const two = await doc.embedPng(TWO_BY_ONE_PNG)
|
||||
expect([two.width, two.height]).toEqual([2, 1])
|
||||
const one = await doc.embedPng(ONE_PX_PNG)
|
||||
expect([one.width, one.height]).toEqual([1, 1])
|
||||
})
|
||||
|
||||
it('the v2unresolved report carries the unresolved findings of the freeze', () => {
|
||||
expect(golden.unresolvedOfV2Unresolved).toBeGreaterThan(0)
|
||||
const findings = golden.reports.v2unresolved.observations.flatMap(
|
||||
(o) => o.findings,
|
||||
)
|
||||
expect(findings.filter((f) => f.unresolved)).toHaveLength(
|
||||
golden.unresolvedOfV2Unresolved,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe.each(REPORT_NAMES)('goldens of %s', (name) => {
|
||||
describe.each(MODES)('%s', (mode) => {
|
||||
it('text, images and links per locale; same pagination across locales', async () => {
|
||||
const fr = await exportWith(name, mode, 'fr')
|
||||
const en = await exportWith(name, mode, 'en')
|
||||
for (const [locale, out] of [
|
||||
['fr', fr],
|
||||
['en', en],
|
||||
] as const) {
|
||||
checkGolden(`text.${name}.${locale}.${mode}.json`, out.texts)
|
||||
checkGolden(`images.${name}.${locale}.${mode}.json`, out.images)
|
||||
checkGolden(`links.${name}.${locale}.${mode}.json`, out.links)
|
||||
}
|
||||
expect(pagesOf(en.images)).toEqual(pagesOf(fr.images))
|
||||
expect(pagesOf(en.links)).toEqual(pagesOf(fr.links))
|
||||
}, 30_000)
|
||||
})
|
||||
|
||||
// Hidden markers are absent in the engine (the browser hid them with
|
||||
// display="none") and the layer <g> carries no data-* any more: `titles`
|
||||
// shrinks to the highlighted markers plus the asset's own, and
|
||||
// `dataAttributes` drops from 2 to 0. Everything else must match.
|
||||
it('highlighted views: same facts but titles and data attributes', () => {
|
||||
const actual = snapshotViews(golden.snapshots[name], golden.reports[name])
|
||||
const expected = readGolden<ViewSnapshot[]>(`views.${name}.json`)
|
||||
const comparable = (v: ViewSnapshot) => ({
|
||||
observationId: v.observationId,
|
||||
viewId: v.viewId,
|
||||
viewBox: v.viewBox,
|
||||
halo: v.halo,
|
||||
highlighted: v.highlighted,
|
||||
nonHighlightedVisible: v.nonHighlightedVisible,
|
||||
})
|
||||
expect(actual.map(comparable)).toEqual(expected.map(comparable))
|
||||
for (const view of actual) {
|
||||
expect(view.dataAttributes).toBe(0)
|
||||
expect(view.titles).toBeGreaterThanOrEqual(view.highlighted.length)
|
||||
}
|
||||
for (const view of expected) expect(view.dataAttributes).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -1,92 +0,0 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { join, resolve } from 'node:path'
|
||||
import {
|
||||
AnatomicalSheetDocumentSchema,
|
||||
ReportMigrationMapSchema,
|
||||
type ReportMigrationMap,
|
||||
type SnapshotSource,
|
||||
} from '@faunosteo/domain'
|
||||
|
||||
/**
|
||||
* Paths and loaders shared by the engine tests. The committed equine draft
|
||||
* is read from the seed as the application bundles it; the Phase 0 goldens
|
||||
* and fixtures are read from the app's test folder, never copied.
|
||||
*/
|
||||
|
||||
const HERE = resolve(fileURLToPath(import.meta.url), '..')
|
||||
export const REPO_ROOT = resolve(HERE, '../../../..')
|
||||
export const DRAFT_DIR = resolve(
|
||||
REPO_ROOT,
|
||||
'supabase/seed/anatomical-sheets/equine/draft',
|
||||
)
|
||||
export const LEGACY_BASELINE = resolve(
|
||||
REPO_ROOT,
|
||||
'supabase/seed/anatomical-sheets/equine/legacy-import/document.json',
|
||||
)
|
||||
export const FIXTURES_DIR = resolve(REPO_ROOT, 'apps/app/tests/fixtures')
|
||||
export const GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/step6')
|
||||
export const PUBLIC_DIR = resolve(REPO_ROOT, 'apps/app/public')
|
||||
/** The logo files the app bundles into its export branding. */
|
||||
export const BRAND_ASSETS_DIR = resolve(REPO_ROOT, 'apps/app/src/assets/brand')
|
||||
|
||||
export function readJson<T = unknown>(path: string): T {
|
||||
return JSON.parse(readFileSync(path, 'utf8')) as T
|
||||
}
|
||||
|
||||
export function readFixtureJson<T = unknown>(name: string): T {
|
||||
return readJson<T>(resolve(FIXTURES_DIR, name))
|
||||
}
|
||||
|
||||
export function readFixtureBytes(name: string): Uint8Array {
|
||||
return new Uint8Array(readFileSync(resolve(FIXTURES_DIR, name)))
|
||||
}
|
||||
|
||||
interface SeedRef {
|
||||
sheet_id: string
|
||||
version_id: string | null
|
||||
document_sha256: string
|
||||
schema_version: number
|
||||
species_id: string
|
||||
}
|
||||
|
||||
interface SeedAsset {
|
||||
file: string
|
||||
sha256: string
|
||||
svg_asset_id: string
|
||||
}
|
||||
|
||||
export interface DraftSheet extends SnapshotSource {
|
||||
assetHashes: Readonly<Record<string, string>>
|
||||
migrationMap: ReportMigrationMap
|
||||
}
|
||||
|
||||
export function loadDraftSheet(): DraftSheet {
|
||||
const json = <T>(name: string) => readJson<T>(join(DRAFT_DIR, name))
|
||||
const ref = json<SeedRef>('sheet-ref.json')
|
||||
const assets: Record<string, string> = {}
|
||||
const assetHashes: Record<string, string> = {}
|
||||
for (const asset of json<SeedAsset[]>('assets.json')) {
|
||||
assets[asset.svg_asset_id] = readFileSync(
|
||||
join(DRAFT_DIR, 'assets', asset.file),
|
||||
'utf8',
|
||||
)
|
||||
assetHashes[asset.svg_asset_id] = asset.sha256
|
||||
}
|
||||
return {
|
||||
status: 'draft',
|
||||
ref: {
|
||||
sheetId: ref.sheet_id,
|
||||
versionId: ref.version_id,
|
||||
documentSha256: ref.document_sha256,
|
||||
},
|
||||
speciesId: ref.species_id,
|
||||
schemaVersion: ref.schema_version,
|
||||
document: AnatomicalSheetDocumentSchema.parse(json('document.json')),
|
||||
assets,
|
||||
assetHashes,
|
||||
migrationMap: ReportMigrationMapSchema.parse(
|
||||
json('report-migration-map.json'),
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -1,359 +0,0 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { DOMParser, type Element, type Node } from '@xmldom/xmldom'
|
||||
import { expect, vi } from 'vitest'
|
||||
import {
|
||||
PDFArray,
|
||||
PDFDict,
|
||||
PDFDocument,
|
||||
PDFHexString,
|
||||
PDFName,
|
||||
PDFNumber,
|
||||
PDFPage,
|
||||
PDFString,
|
||||
} from 'pdf-lib'
|
||||
import type {
|
||||
Branding,
|
||||
Observation,
|
||||
Report,
|
||||
SheetSnapshot,
|
||||
} from '@faunosteo/domain'
|
||||
import { composeHighlightedViewSvg, type Rasterizer } from '../../src'
|
||||
import { BRAND_ASSETS_DIR, GOLDEN_DIR } from './draft'
|
||||
|
||||
/**
|
||||
* Step 6 Phase 0 goldens, replayed on the engine: the same recorder on
|
||||
* pdf-lib, the same link reader, the same view facts (computed with xmldom
|
||||
* instead of the browser DOM) and the same fixed PNG rasters.
|
||||
*/
|
||||
|
||||
export const FIXED_EXPORTED_AT = new Date('2026-10-11T12:00:00.000Z')
|
||||
|
||||
/** 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',
|
||||
),
|
||||
)
|
||||
|
||||
/** A rasterizer returning the same PNG whatever the SVG, like the Phase 0 mock. */
|
||||
export function fixedRasterizer(png: Uint8Array): Rasterizer {
|
||||
return async () => png
|
||||
}
|
||||
|
||||
export type LogoMode = 'nologos' | 'logos'
|
||||
|
||||
const SITE_URL = 'https://faunosteo.com'
|
||||
const POWERED_BY = {
|
||||
url: 'https://zenquality.fr',
|
||||
fallbackText: 'zenquality.fr',
|
||||
}
|
||||
const PARTNER = {
|
||||
url: 'https://www.instagram.com/paws.iin.harmony',
|
||||
fallbackText: '@paws.iin.harmony',
|
||||
}
|
||||
|
||||
function brandPng(file: string): { kind: 'png'; base64: string } {
|
||||
const bytes = readFileSync(resolve(BRAND_ASSETS_DIR, file))
|
||||
return { kind: 'png', base64: Buffer.from(bytes).toString('base64') }
|
||||
}
|
||||
|
||||
/** Every logo null, credits with their fallback texts (fetch 404 in Phase 0). */
|
||||
export function nologosBranding(): Branding {
|
||||
return {
|
||||
siteUrl: SITE_URL,
|
||||
headerLogo: null,
|
||||
footerLogo: null,
|
||||
poweredBy: { logo: null, ...POWERED_BY },
|
||||
partner: { logo: null, ...PARTNER },
|
||||
}
|
||||
}
|
||||
|
||||
/** The four real logo files the app bundles (served by a fetch stub in Phase 0). */
|
||||
export function logosBranding(): Branding {
|
||||
return {
|
||||
siteUrl: SITE_URL,
|
||||
headerLogo: brandPng('faunosteo-logo-horizontal-512.png'),
|
||||
footerLogo: brandPng('faunosteo-horizontal-com-512.png'),
|
||||
poweredBy: { logo: brandPng('zenquality-logo-fr.png'), ...POWERED_BY },
|
||||
partner: {
|
||||
logo: {
|
||||
kind: 'svg',
|
||||
svg: readFileSync(
|
||||
resolve(BRAND_ASSETS_DIR, 'paws-in-harmony.svg'),
|
||||
'utf8',
|
||||
),
|
||||
},
|
||||
...PARTNER,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function brandingOf(mode: LogoMode): Branding {
|
||||
return mode === 'logos' ? logosBranding() : nologosBranding()
|
||||
}
|
||||
|
||||
export function rasterizerOf(mode: LogoMode): Rasterizer {
|
||||
return fixedRasterizer(mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG)
|
||||
}
|
||||
|
||||
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 function round2(value: unknown): number | null {
|
||||
return typeof value === 'number' ? Math.round(value * 100) / 100 : null
|
||||
}
|
||||
|
||||
/** 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)
|
||||
}
|
||||
|
||||
export interface DrawRecording {
|
||||
texts: TextEntry[]
|
||||
images: ImageEntry[]
|
||||
stop(): void
|
||||
}
|
||||
|
||||
/** Records every drawText / drawImage while letting pdf-lib draw for real. */
|
||||
export function recordDrawing(): DrawRecording {
|
||||
const texts: TextEntry[] = []
|
||||
const images: ImageEntry[] = []
|
||||
const drawText = PDFPage.prototype.drawText
|
||||
const drawImage = PDFPage.prototype.drawImage
|
||||
const textSpy = vi
|
||||
.spyOn(PDFPage.prototype, 'drawText')
|
||||
.mockImplementation(function (this: PDFPage, text, options) {
|
||||
texts.push({
|
||||
page: pageIndex(this),
|
||||
text,
|
||||
x: round2(options?.x),
|
||||
y: round2(options?.y),
|
||||
size: round2(options?.size),
|
||||
font: options?.font?.name ?? null,
|
||||
})
|
||||
return drawText.call(this, text, options)
|
||||
})
|
||||
const imageSpy = vi
|
||||
.spyOn(PDFPage.prototype, 'drawImage')
|
||||
.mockImplementation(function (this: PDFPage, image, options) {
|
||||
images.push({
|
||||
page: pageIndex(this),
|
||||
x: round2(options?.x),
|
||||
y: round2(options?.y),
|
||||
width: round2(options?.width),
|
||||
height: round2(options?.height),
|
||||
})
|
||||
return drawImage.call(this, image, options)
|
||||
})
|
||||
return {
|
||||
texts,
|
||||
images,
|
||||
stop: () => {
|
||||
textSpy.mockRestore()
|
||||
imageSpy.mockRestore()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function linkOf(dict: PDFDict, page: number): LinkEntry | null {
|
||||
if (dict.get(PDFName.of('Subtype')) !== PDFName.of('Link')) return null
|
||||
const rect = dict
|
||||
.lookup(PDFName.of('Rect'), PDFArray)
|
||||
.asArray()
|
||||
.map((n) => round2((n as PDFNumber).asNumber()) ?? 0)
|
||||
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 }
|
||||
}
|
||||
|
||||
/** Every `/Annot /Link` of the saved PDF, page by page, in annotation order. */
|
||||
export async function readLinks(bytes: Uint8Array): Promise<LinkEntry[]> {
|
||||
const doc = await PDFDocument.load(bytes)
|
||||
const out: LinkEntry[] = []
|
||||
doc.getPages().forEach((page, index) => {
|
||||
const annots = page.node.Annots()
|
||||
if (!annots) return
|
||||
for (let i = 0; i < annots.size(); i += 1) {
|
||||
const link = linkOf(annots.lookup(i, PDFDict), index)
|
||||
if (link) out.push(link)
|
||||
}
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// View facts (G2), computed with xmldom on the engine's SVG
|
||||
|
||||
export const HIGHLIGHT_FILL = '#b85a3f'
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
function isElement(node: Node): node is Element {
|
||||
return node.nodeType === 1
|
||||
}
|
||||
|
||||
/** Every element under `root` (root included), document order. */
|
||||
export function allElements(root: Element): Element[] {
|
||||
const out: Element[] = []
|
||||
const stack: Element[] = [root]
|
||||
while (stack.length) {
|
||||
const el = stack.pop()!
|
||||
out.push(el)
|
||||
const children = Array.from(el.childNodes).filter(isElement)
|
||||
for (let i = children.length - 1; i >= 0; i -= 1) stack.push(children[i]!)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function elementChildren(el: Element): Element[] {
|
||||
return Array.from(el.childNodes).filter(isElement)
|
||||
}
|
||||
|
||||
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 = elementChildren(root)
|
||||
.filter((c) => c.tagName === 'g')
|
||||
.at(-1)
|
||||
if (!layer) return 0
|
||||
return elementChildren(layer).filter(
|
||||
(el) =>
|
||||
el.getAttribute('fill') !== HIGHLIGHT_FILL &&
|
||||
el.getAttribute('display') !== 'none',
|
||||
).length
|
||||
}
|
||||
|
||||
function countDataAttributes(root: Element): number {
|
||||
return allElements(root).reduce(
|
||||
(count, el) =>
|
||||
count +
|
||||
Array.from(el.attributes).filter((a) => a.name.startsWith('data-'))
|
||||
.length,
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
export function parseXml(svg: string): Element {
|
||||
return new DOMParser().parseFromString(svg, 'image/svg+xml').documentElement!
|
||||
}
|
||||
|
||||
export function snapshotView(
|
||||
sheet: SheetSnapshot,
|
||||
observation: Observation,
|
||||
viewId: string,
|
||||
): ViewSnapshot {
|
||||
const root = parseXml(composeHighlightedViewSvg(sheet, viewId, observation))
|
||||
const elements = allElements(root)
|
||||
return {
|
||||
observationId: observation.id,
|
||||
viewId,
|
||||
viewBox: root.getAttribute('viewBox'),
|
||||
halo: elements.some(
|
||||
(el) => el.tagName === 'filter' && el.getAttribute('id') === 'osteo-halo',
|
||||
),
|
||||
highlighted: elements
|
||||
.filter((el) => el.getAttribute('fill') === HIGHLIGHT_FILL)
|
||||
.map(highlightedOf),
|
||||
nonHighlightedVisible: countVisibleNonHighlighted(root),
|
||||
dataAttributes: countDataAttributes(root),
|
||||
titles: elements.filter((el) => el.tagName === '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))
|
||||
}
|
||||
|
||||
export function snapshotViews(
|
||||
sheet: SheetSnapshot,
|
||||
report: Report,
|
||||
): ViewSnapshot[] {
|
||||
return report.observations.flatMap((observation) =>
|
||||
viewIdsOf(sheet, observation).map((viewId) =>
|
||||
snapshotView(sheet, observation, viewId),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
export function readGolden<T = unknown>(name: string): T {
|
||||
return JSON.parse(readFileSync(resolve(GOLDEN_DIR, name), 'utf8')) as T
|
||||
}
|
||||
|
||||
/** Asserts deep equality with a Phase 0 golden (never regenerated here). */
|
||||
export function checkGolden(name: string, actual: unknown): void {
|
||||
expect(actual, name).toEqual(readGolden(name))
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
import {
|
||||
AnatomicalSheetDocumentSchema,
|
||||
ReportV2Schema,
|
||||
type AnatomicalSheetDocument,
|
||||
type FindingCategory,
|
||||
type FindingNode,
|
||||
type ObservationV2,
|
||||
type ReportV2,
|
||||
} from '@faunosteo/domain'
|
||||
import { LEGACY_BASELINE, readJson } from './draft'
|
||||
|
||||
/**
|
||||
* The legacy catalog as the application's archive knew it: every leaf of the
|
||||
* generated baseline becomes a Report v2 finding, one observation per zone.
|
||||
* Same recipe as the app and domain helpers (Phase 0 `v2unresolved`).
|
||||
*/
|
||||
|
||||
export interface LegacyLeaf {
|
||||
zoneId: string
|
||||
path: string[]
|
||||
name: { fr: string; en: string }
|
||||
vet: boolean
|
||||
}
|
||||
|
||||
export function loadLegacyBaseline(): AnatomicalSheetDocument {
|
||||
return AnatomicalSheetDocumentSchema.parse(readJson(LEGACY_BASELINE))
|
||||
}
|
||||
|
||||
export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] {
|
||||
const out: LegacyLeaf[] = []
|
||||
const walk = (
|
||||
zoneId: string,
|
||||
nodes: readonly (FindingCategory | FindingNode)[],
|
||||
prefix: string[],
|
||||
) => {
|
||||
for (const node of nodes) {
|
||||
const path = [...prefix, node.id]
|
||||
if (node.children.length > 0) walk(zoneId, node.children, path)
|
||||
else {
|
||||
const vet =
|
||||
'requires_vet_referral' in node && node.requires_vet_referral
|
||||
out.push({ zoneId, path, name: node.name, vet })
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const zone of doc.finding_zones) walk(zone.id, zone.categories, [])
|
||||
return out
|
||||
}
|
||||
|
||||
export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
|
||||
const byZone = new Map<string, ObservationV2>()
|
||||
for (const leaf of leaves) {
|
||||
let obs = byZone.get(leaf.zoneId)
|
||||
if (!obs) {
|
||||
obs = {
|
||||
id: `obs-${leaf.zoneId}`,
|
||||
zones: [],
|
||||
findings: [],
|
||||
freeTextFindings: [],
|
||||
comment: '',
|
||||
}
|
||||
byZone.set(leaf.zoneId, obs)
|
||||
}
|
||||
obs.findings.push({
|
||||
zoneId: leaf.zoneId,
|
||||
path: leaf.path,
|
||||
labelFrSnapshot: leaf.name.fr,
|
||||
labelEnSnapshot: leaf.name.en || leaf.name.fr,
|
||||
...(leaf.vet ? { requiresVetReferral: true } : {}),
|
||||
})
|
||||
}
|
||||
return ReportV2Schema.parse({
|
||||
version: 2,
|
||||
id: 'all-leaves',
|
||||
createdAt: '2026-10-10T00:00:00Z',
|
||||
date: '2026-10-10',
|
||||
practitioner: { name: 'Synthetic' },
|
||||
animal: { speciesId: 'equine', name: 'Synthetic' },
|
||||
owner: { name: 'Synthetic' },
|
||||
observations: [...byZone.values()],
|
||||
conclusion: '',
|
||||
recommendations: '',
|
||||
})
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
import { AFRelationship, PDFDocument } from 'pdf-lib'
|
||||
import { findEmbeddedFiles } from '../../src'
|
||||
|
||||
/**
|
||||
* Crafted PDFs for the read tests, built with pdf-lib's own attach. Saved
|
||||
* without object streams by default, like the export since BLK-009; pass
|
||||
* `objectStreams: true` for the pre-BLK-009 layout (Filespec and Info
|
||||
* packed into an `/ObjStm`, invisible to the byte scan).
|
||||
*/
|
||||
export interface CraftOptions {
|
||||
keywords?: string[]
|
||||
before?: [string, unknown]
|
||||
objectStreams?: boolean
|
||||
}
|
||||
|
||||
export async function pdfWithAttachment(
|
||||
name: string,
|
||||
payload: unknown,
|
||||
extra: CraftOptions = {},
|
||||
): Promise<Uint8Array> {
|
||||
const doc = await PDFDocument.create()
|
||||
doc.addPage()
|
||||
if (extra.keywords) doc.setKeywords(extra.keywords)
|
||||
if (extra.before) await attachJson(doc, extra.before[0], extra.before[1])
|
||||
await attachJson(doc, name, payload)
|
||||
return doc.save({ useObjectStreams: extra.objectStreams ?? false })
|
||||
}
|
||||
|
||||
async function attachJson(
|
||||
doc: PDFDocument,
|
||||
name: string,
|
||||
payload: unknown,
|
||||
): Promise<void> {
|
||||
await doc.attach(new TextEncoder().encode(JSON.stringify(payload)), name, {
|
||||
mimeType: 'application/json',
|
||||
afRelationship: AFRelationship.Data,
|
||||
})
|
||||
}
|
||||
|
||||
export async function pdfWithoutAttachment(
|
||||
keywords?: string[],
|
||||
objectStreams = false,
|
||||
): Promise<Uint8Array> {
|
||||
const doc = await PDFDocument.create()
|
||||
doc.addPage()
|
||||
if (keywords) doc.setKeywords(keywords)
|
||||
return doc.save({ useObjectStreams: objectStreams })
|
||||
}
|
||||
|
||||
/** Stored (Flate) size of the first `/EmbeddedFile` stream of a saved PDF, by the byte scan. */
|
||||
export function storedAttachmentSize(bytes: Uint8Array): number {
|
||||
const [first] = findEmbeddedFiles(bytes)
|
||||
if (!first) throw new Error('no EmbeddedFile stream')
|
||||
return first.length
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { expect } from 'vitest'
|
||||
import { REPO_ROOT } from './draft'
|
||||
|
||||
/**
|
||||
* Shared plumbing of the R4.1 freeze generators (plan 2026-10-17 §B.5.1,
|
||||
* O4 to O6). `MAKE_R4_ORACLES=1` writes the files; without it the
|
||||
* generator recomputes and compares with the committed ones.
|
||||
*/
|
||||
|
||||
export const R4_ORACLES = resolve(REPO_ROOT, 'crates/core/tests/oracles/r4')
|
||||
export const MAKE_R4 = process.env.MAKE_R4_ORACLES === '1'
|
||||
|
||||
/** Where the oracle was computed; informative, left out of the comparison. */
|
||||
export interface OracleEnvironment {
|
||||
node: string
|
||||
v8: string
|
||||
icu: string | null
|
||||
unicode: string | null
|
||||
}
|
||||
|
||||
export function environment(): OracleEnvironment {
|
||||
return {
|
||||
node: process.version,
|
||||
v8: process.versions.v8,
|
||||
icu: process.versions.icu ?? null,
|
||||
unicode: process.versions.unicode ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/** B.5.2: no generator writes while the field corpus is reachable. */
|
||||
function assertNoFieldCorpus(): void {
|
||||
if (process.env.FAUNOSTEO_FIELD_CORPUS) {
|
||||
throw new Error(
|
||||
'FAUNOSTEO_FIELD_CORPUS is set: R4 oracle generators refuse to write',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export function writeOracleFile(
|
||||
path: string,
|
||||
bytes: string | Uint8Array,
|
||||
): void {
|
||||
assertNoFieldCorpus()
|
||||
mkdirSync(dirname(path), { recursive: true })
|
||||
writeFileSync(path, bytes)
|
||||
}
|
||||
|
||||
/** The JSON value as the file holds it: `-0` becomes `0`, `undefined` fields vanish. */
|
||||
const asJson = (value: unknown): unknown => JSON.parse(JSON.stringify(value))
|
||||
|
||||
/**
|
||||
* Writes `value` as `JSON.stringify(value, null, 2)` (MAKE), or asserts
|
||||
* deep equality with the committed file, `environment` excepted.
|
||||
*/
|
||||
export function freezeJson(
|
||||
name: string,
|
||||
value: { environment: OracleEnvironment },
|
||||
): void {
|
||||
const path = resolve(R4_ORACLES, name)
|
||||
if (MAKE_R4) {
|
||||
writeOracleFile(path, `${JSON.stringify(value, null, 2)}\n`)
|
||||
return
|
||||
}
|
||||
const expected = JSON.parse(readFileSync(path, 'utf8')) as Record<
|
||||
string,
|
||||
unknown
|
||||
>
|
||||
const computed = asJson(value) as Record<string, unknown>
|
||||
delete expected.environment
|
||||
delete computed.environment
|
||||
expect(computed).toEqual(expected)
|
||||
}
|
||||
|
||||
/** A number as JavaScript prints it, `-0` kept apart from `0`. */
|
||||
export const jsNumber = (value: number): string =>
|
||||
Object.is(value, -0) ? '-0' : String(value)
|
||||
|
||||
/** mulberry32: a small seeded PRNG, [0, 1). */
|
||||
export function mulberry32(seed: number): () => number {
|
||||
let state = seed >>> 0
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0
|
||||
let t = state
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1)
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
|
||||
}
|
||||
}
|
||||
|
||||
export const MAX_CODE_POINT = 0x10ffff
|
||||
|
||||
/** Every code point from 0 to 0x10FFFF run-length encoded as `[start, end, class]` (end inclusive). */
|
||||
export function classRanges<T extends string>(
|
||||
classOf: (cp: number) => T,
|
||||
): Array<[number, number, T]> {
|
||||
const out: Array<[number, number, T]> = []
|
||||
for (let cp = 0; cp <= MAX_CODE_POINT; cp += 1) {
|
||||
const cls = classOf(cp)
|
||||
const last = out.at(-1)
|
||||
if (last && last[2] === cls && last[1] === cp - 1) last[1] = cp
|
||||
else out.push([cp, cp, cls])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** The code points where `test` holds, as `[start, end]` ranges (end inclusive). */
|
||||
export function codePointRanges(
|
||||
test: (cp: number) => boolean,
|
||||
): Array<[number, number]> {
|
||||
return classRanges((cp) => (test(cp) ? 'in' : 'out'))
|
||||
.filter(([, , cls]) => cls === 'in')
|
||||
.map(([start, end]) => [start, end])
|
||||
}
|
||||
|
||||
export const isSurrogate = (cp: number): boolean => cp >= 0xd800 && cp <= 0xdfff
|
||||
|
||||
/** A one-code-point string; a surrogate stays a lone single-unit string. */
|
||||
export const charOf = (cp: number): string =>
|
||||
isSurrogate(cp) ? String.fromCharCode(cp) : String.fromCodePoint(cp)
|
||||
@@ -1,105 +0,0 @@
|
||||
import { deflateSync } from 'node:zlib'
|
||||
|
||||
/**
|
||||
* Byte builders of the R4 reader oracles, copied from scan.test.ts and
|
||||
* inflate.test.ts: a test file cannot be imported without registering its
|
||||
* cases, and those files stay untouched. Same output for the same arguments.
|
||||
*/
|
||||
|
||||
export const KiB = 1024
|
||||
export const MiB = 1024 * KiB
|
||||
|
||||
export const latin1 = (bytes: Uint8Array) =>
|
||||
Buffer.from(bytes).toString('latin1')
|
||||
/** One byte per character: every string given here stays at or below U+00FF. */
|
||||
export const ascii = (text: string) =>
|
||||
new Uint8Array(Buffer.from(text, 'latin1'))
|
||||
|
||||
export function concat(parts: Uint8Array[]): Uint8Array {
|
||||
const out = new Uint8Array(parts.reduce((n, p) => n + p.byteLength, 0))
|
||||
let at = 0
|
||||
for (const part of parts) {
|
||||
out.set(part, at)
|
||||
at += part.byteLength
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export interface StreamSpec {
|
||||
num: number
|
||||
dict: string
|
||||
data: Uint8Array
|
||||
eol?: string
|
||||
}
|
||||
|
||||
export function streamObject({
|
||||
num,
|
||||
dict,
|
||||
data,
|
||||
eol = '\n',
|
||||
}: StreamSpec): Uint8Array {
|
||||
return concat([
|
||||
ascii(`${num} 0 obj\n<<${dict}>>\nstream${eol}`),
|
||||
data,
|
||||
ascii('\nendstream\nendobj\n'),
|
||||
])
|
||||
}
|
||||
|
||||
/** The scanner never reads the xref, so none is written. */
|
||||
export function craftPdf(objects: Uint8Array[]): Uint8Array {
|
||||
return concat([
|
||||
ascii('%PDF-1.7\n'),
|
||||
...objects,
|
||||
ascii('trailer\n<< /Root 1 0 R >>\n%%EOF\n'),
|
||||
])
|
||||
}
|
||||
|
||||
/** `craftPdf` over Latin-1 texts and byte parts. */
|
||||
export function pdfOf(...objects: Array<string | Uint8Array>): Uint8Array {
|
||||
return craftPdf(objects.map((o) => (typeof o === 'string' ? ascii(o) : o)))
|
||||
}
|
||||
|
||||
export interface Span {
|
||||
start: number
|
||||
end: number
|
||||
}
|
||||
|
||||
/** Bounds of the `n 0 obj … endobj` object whose dictionary holds `marker` (scan.test.ts `objectHolding`). */
|
||||
export function objectSpan(pdf: Uint8Array, marker: string): Span {
|
||||
const text = latin1(pdf)
|
||||
const at = text.indexOf(marker)
|
||||
if (at <= 0) throw new Error(`marker not found: ${marker}`)
|
||||
const start = text.lastIndexOf(' 0 obj', at)
|
||||
const headerStart = text.lastIndexOf('\n', start) + 1
|
||||
const end = text.indexOf('endobj', at) + 'endobj'.length
|
||||
return { start: headerStart, end }
|
||||
}
|
||||
|
||||
export function objectHolding(pdf: Uint8Array, marker: string): Uint8Array {
|
||||
const { start, end } = objectSpan(pdf, marker)
|
||||
return pdf.slice(start, end)
|
||||
}
|
||||
|
||||
export const filled = (byte: string, length: number) =>
|
||||
ascii(byte.repeat(length))
|
||||
|
||||
export const deflate = (data: Uint8Array) => new Uint8Array(deflateSync(data))
|
||||
|
||||
/** Incompressible bytes: the compressed stream is about as long as the input. */
|
||||
export function noise(length: number): Uint8Array {
|
||||
let seed = 0x9e3779b9
|
||||
return Uint8Array.from({ length }, () => {
|
||||
seed = (seed * 1664525 + 1013904223) >>> 0
|
||||
return seed >>> 24
|
||||
})
|
||||
}
|
||||
|
||||
/** CompressionStream('deflate') output, as security.test.ts builds its inputs. */
|
||||
export async function compressionStreamDeflate(
|
||||
data: Uint8Array,
|
||||
): Promise<Uint8Array> {
|
||||
const stream = new Blob([data])
|
||||
.stream()
|
||||
.pipeThrough(new CompressionStream('deflate'))
|
||||
return new Uint8Array(await new Response(stream).arrayBuffer())
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,215 +0,0 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { expect } from 'vitest'
|
||||
import { inflateFlate } from '../../src/attachment/inflate'
|
||||
import { FIXTURES_DIR, REPO_ROOT } from './draft'
|
||||
import { ascii, concat, latin1, MiB } from './r4-reader-craft'
|
||||
|
||||
/**
|
||||
* Write-or-check plumbing of the R4.1 reader oracles (O7, O9). With
|
||||
* `MAKE_R4_ORACLES=1` the generators write their inputs and oracles; without
|
||||
* it they rebuild everything and require the committed files to be the same
|
||||
* (bytes for inputs, deep equality for JSON).
|
||||
*/
|
||||
|
||||
export const MAKE = process.env.MAKE_R4_ORACLES === '1'
|
||||
export const R4_INPUTS_DIR = resolve(FIXTURES_DIR, 'pdf/r4')
|
||||
export const R4_ORACLES_DIR = resolve(REPO_ROOT, 'crates/core/tests/oracles/r4')
|
||||
|
||||
/** Inputs above this size are committed as a generator description, never as bytes. */
|
||||
export const MAX_STORED_BYTES = 2 * MiB
|
||||
|
||||
export const sha256 = (data: Uint8Array | string): string =>
|
||||
createHash('sha256').update(data).digest('hex')
|
||||
|
||||
export const jsonText = (value: unknown): string =>
|
||||
`${JSON.stringify(value, null, 2)}\n`
|
||||
|
||||
export function relativeToRepo(path: string): string {
|
||||
return path.slice(REPO_ROOT.length + 1)
|
||||
}
|
||||
|
||||
export function storeFile(path: string, bytes: Uint8Array): void {
|
||||
if (MAKE) {
|
||||
mkdirSync(dirname(path), { recursive: true })
|
||||
writeFileSync(path, bytes)
|
||||
return
|
||||
}
|
||||
expect(existsSync(path), `missing ${relativeToRepo(path)}`).toBe(true)
|
||||
expect(sha256(readFileSync(path)), relativeToRepo(path)).toBe(sha256(bytes))
|
||||
}
|
||||
|
||||
export function readJsonFile<T>(path: string): T {
|
||||
return JSON.parse(readFileSync(path, 'utf8')) as T
|
||||
}
|
||||
|
||||
/**
|
||||
* `normalise` maps the committed JSON before the comparison, for the parts
|
||||
* this generator does not own (the Node version that wrote it, the browser
|
||||
* columns of O9).
|
||||
*/
|
||||
export function storeJson(
|
||||
path: string,
|
||||
value: unknown,
|
||||
normalise: (committed: unknown) => unknown = (committed) => committed,
|
||||
): void {
|
||||
if (MAKE) {
|
||||
storeFile(path, new TextEncoder().encode(jsonText(value)))
|
||||
return
|
||||
}
|
||||
expect(existsSync(path), `missing ${relativeToRepo(path)}`).toBe(true)
|
||||
expect(normalise(readJsonFile(path)), relativeToRepo(path)).toEqual(
|
||||
JSON.parse(jsonText(value)),
|
||||
)
|
||||
}
|
||||
|
||||
/** The Node build that produced an oracle: recorded, never compared (inputs are compared byte for byte). */
|
||||
export const generatedWith = () => ({
|
||||
node: process.version,
|
||||
zlib: process.versions.zlib,
|
||||
})
|
||||
|
||||
/** The input directory holds exactly the listed files: no stale input survives a rename. */
|
||||
export function expectOnlyFiles(dir: string, files: string[]): void {
|
||||
expect(readdirSync(dir).sort(), relativeToRepo(dir)).toEqual(
|
||||
[...new Set(files)].sort(),
|
||||
)
|
||||
}
|
||||
|
||||
/** inflateFlate's verdict as the oracles record it: null, or the output length and digest. */
|
||||
export async function inflateVerdict(input: Uint8Array, limit: number) {
|
||||
const out = await inflateFlate(input, limit)
|
||||
return out === null ? null : { length: out.byteLength, sha256: sha256(out) }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Generator descriptions (`<slug>.gen.json`) for the inputs over 2 MiB
|
||||
|
||||
/**
|
||||
* Concatenated in order: `latin1` one byte per character, `fill` the byte
|
||||
* value repeated `count` times, `slice` the bytes [start, end) of another
|
||||
* input file of the same directory.
|
||||
*/
|
||||
export type Part =
|
||||
| { latin1: string }
|
||||
| { fill: number; count: number }
|
||||
| { slice: string; start: number; end: number }
|
||||
|
||||
export interface GeneratorDescription {
|
||||
generator: 'concat/1'
|
||||
length: number
|
||||
sha256: string
|
||||
parts: Part[]
|
||||
}
|
||||
|
||||
/** Bytes a description may reference instead of spelling them out. */
|
||||
export interface SliceRef {
|
||||
file: string
|
||||
start: number
|
||||
end: number
|
||||
bytes: Uint8Array
|
||||
}
|
||||
|
||||
export function expandParts(parts: Part[], dir: string): Uint8Array {
|
||||
return concat(
|
||||
parts.map((part) => {
|
||||
if ('latin1' in part) return ascii(part.latin1)
|
||||
if ('fill' in part) return new Uint8Array(part.count).fill(part.fill)
|
||||
const source = new Uint8Array(readFileSync(resolve(dir, part.slice)))
|
||||
return source.subarray(part.start, part.end)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/** Runs this long or longer of one byte value become a `fill` part. */
|
||||
const MIN_RUN = 4096
|
||||
|
||||
function runParts(bytes: Uint8Array, start: number, end: number): Part[] {
|
||||
const parts: Part[] = []
|
||||
let textFrom = start
|
||||
let i = start
|
||||
while (i < end) {
|
||||
let j = i + 1
|
||||
while (j < end && bytes[j] === bytes[i]) j += 1
|
||||
if (j - i >= MIN_RUN) {
|
||||
if (textFrom < i) {
|
||||
parts.push({ latin1: latin1(bytes.subarray(textFrom, i)) })
|
||||
}
|
||||
parts.push({ fill: bytes[i]!, count: j - i })
|
||||
textFrom = j
|
||||
}
|
||||
i = j
|
||||
}
|
||||
if (textFrom < end)
|
||||
parts.push({ latin1: latin1(bytes.subarray(textFrom, end)) })
|
||||
return parts
|
||||
}
|
||||
|
||||
interface RefHit {
|
||||
at: number
|
||||
ref: SliceRef
|
||||
}
|
||||
|
||||
function refHits(bytes: Uint8Array, refs: SliceRef[]): RefHit[] {
|
||||
const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
||||
const hits: RefHit[] = []
|
||||
for (const ref of refs) {
|
||||
let at = buffer.indexOf(ref.bytes)
|
||||
while (at >= 0) {
|
||||
hits.push({ at, ref })
|
||||
at = buffer.indexOf(ref.bytes, at + ref.bytes.byteLength)
|
||||
}
|
||||
}
|
||||
return hits.sort((a, b) => a.at - b.at)
|
||||
}
|
||||
|
||||
/** Derives the description from the bytes the original test builds, so both stay the same input. */
|
||||
export function partsOf(bytes: Uint8Array, refs: SliceRef[]): Part[] {
|
||||
const parts: Part[] = []
|
||||
let at = 0
|
||||
for (const hit of refHits(bytes, refs)) {
|
||||
parts.push(...runParts(bytes, at, hit.at))
|
||||
parts.push({ slice: hit.ref.file, start: hit.ref.start, end: hit.ref.end })
|
||||
at = hit.at + hit.ref.bytes.byteLength
|
||||
}
|
||||
parts.push(...runParts(bytes, at, bytes.byteLength))
|
||||
return parts
|
||||
}
|
||||
|
||||
export interface StoredInput {
|
||||
file: string
|
||||
stored: 'bytes' | 'generator'
|
||||
length: number
|
||||
sha256: string
|
||||
}
|
||||
|
||||
/** Commits an input as bytes, or above MAX_STORED_BYTES as a description checked to expand to the same bytes. */
|
||||
export function storeInput(
|
||||
dir: string,
|
||||
name: { slug: string; ext: string },
|
||||
bytes: Uint8Array,
|
||||
refs: SliceRef[] = [],
|
||||
): StoredInput {
|
||||
const digest = { length: bytes.byteLength, sha256: sha256(bytes) }
|
||||
if (bytes.byteLength <= MAX_STORED_BYTES) {
|
||||
const file = `${name.slug}${name.ext}`
|
||||
storeFile(resolve(dir, file), bytes)
|
||||
return { file, stored: 'bytes', ...digest }
|
||||
}
|
||||
const file = `${name.slug}.gen.json`
|
||||
const description: GeneratorDescription = {
|
||||
generator: 'concat/1',
|
||||
...digest,
|
||||
parts: partsOf(bytes, refs),
|
||||
}
|
||||
storeJson(resolve(dir, file), description)
|
||||
expect(sha256(expandParts(description.parts, dir)), file).toBe(digest.sha256)
|
||||
return { file, stored: 'generator', ...digest }
|
||||
}
|
||||
@@ -1,618 +0,0 @@
|
||||
import { MAX_ATTACHMENT_BYTES, MAX_PDF_BYTES } from '../../src'
|
||||
import {
|
||||
ascii,
|
||||
concat,
|
||||
craftPdf,
|
||||
deflate,
|
||||
pdfOf,
|
||||
streamObject,
|
||||
} from './r4-reader-craft'
|
||||
import type { InputSpec, ReaderFunction } from './r4-reader-inputs'
|
||||
|
||||
/**
|
||||
* Plan §B.1.2 "JS regex semantics reproduced explicitly", one minimal PDF
|
||||
* per variant, plus the boundaries of the scanner's other rules (dictionary
|
||||
* and keyword windows, candidate and occurrence caps, header position, the
|
||||
* shared budget). Each pair differs only where the rule decides: `\s` (VT,
|
||||
* FF, NBSP yes; NUL, NEL no) against `isWhitespace` (NUL yes; VT, NBSP no),
|
||||
* `.` against CR and LF in the string token, the lazy `/EF` removal, the
|
||||
* `break` on a candidate over the remaining budget. The outcomes are what
|
||||
* the TypeScript does, recorded by the O7 driver, never what a PDF parser
|
||||
* would do.
|
||||
*/
|
||||
|
||||
const J = '{"version":3}'
|
||||
const FLATE_J = deflate(ascii(J))
|
||||
|
||||
const EF2 = `2 0 obj\n<< /Type /EmbeddedFile /Length 13 >>\nstream\n${J}\nendstream\nendobj\n`
|
||||
|
||||
type Build = InputSpec['build']
|
||||
|
||||
const rule =
|
||||
(group: string, exercises: ReaderFunction[]) =>
|
||||
(slug: string, title: string, build: Build): InputSpec => ({
|
||||
slug: `semantics.${slug}`,
|
||||
kind: 'pdf',
|
||||
cases: [{ suite: 'semantics', case: `${group} > ${title}`, exercises }],
|
||||
build,
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// `n 0 obj` header: /(\d{1,10})\s+\d{1,10}\s+obj\s*$/ on a 48-byte window
|
||||
|
||||
const header = rule('object header regex (\\s, 48-byte window)', [
|
||||
'findEmbeddedFiles',
|
||||
])
|
||||
|
||||
const namedStream = (head: string, target = 2) =>
|
||||
pdfOf(
|
||||
`3 0 obj\n<< /Type /Filespec /F (osteo-report.json) /EF << /F ${target} 0 R >> >>\nendobj\n`,
|
||||
`${head}<< /Type /EmbeddedFile /Length 13 >>\nstream\n${J}\nendstream\nendobj\n`,
|
||||
)
|
||||
|
||||
const HEADER: InputSpec[] = [
|
||||
header('header-vt', 'VT (0x0B) separators', () =>
|
||||
namedStream('2\x0B0\x0Bobj\x0B'),
|
||||
),
|
||||
header('header-ff', 'FF (0x0C) separators', () =>
|
||||
namedStream('2\x0C0\x0Cobj\x0C'),
|
||||
),
|
||||
header('header-nbsp', 'NBSP (0xA0) separators', () =>
|
||||
namedStream('2\xA00\xA0obj\xA0'),
|
||||
),
|
||||
header('header-nel', 'NEL (0x85) between the numbers', () =>
|
||||
namedStream('2\x850\x85obj\n'),
|
||||
),
|
||||
header('header-nul', 'NUL between the numbers', () =>
|
||||
namedStream('2\x000 obj\n'),
|
||||
),
|
||||
header('header-nul-before-dict', 'NUL between obj and <<', () =>
|
||||
namedStream('2 0 obj\x00'),
|
||||
),
|
||||
header(
|
||||
'header-window-40-spaces',
|
||||
'12 0 obj then 40 spaces: the number fits the window',
|
||||
() => namedStream(`12 0 obj${' '.repeat(40)}`, 12),
|
||||
),
|
||||
header(
|
||||
'header-window-41-spaces',
|
||||
'12 0 obj then 41 spaces: the window cuts the 1',
|
||||
() => namedStream(`12 0 obj${' '.repeat(41)}`, 12),
|
||||
),
|
||||
]
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// /Length: /\/Length\s+(\d{1,10})(?!\d)(?!\s+\d+\s+R)/, then isWhitespace before endstream
|
||||
|
||||
const length = rule('/Length regex and endstream landing', [
|
||||
'findEmbeddedFiles',
|
||||
'readAttachedDocument',
|
||||
])
|
||||
|
||||
/** Three spaces after the data: a direct /Length gives 13, the measured length 16. */
|
||||
const lengthStream = (dict: string, tail = ' \n') =>
|
||||
pdfOf(
|
||||
`2 0 obj\n<< /Type /EmbeddedFile ${dict} >>\nstream\n${J}${tail}endstream\nendobj\n`,
|
||||
)
|
||||
|
||||
const LENGTH: InputSpec[] = [
|
||||
length('length-space', 'space after /Length (control)', () =>
|
||||
lengthStream('/Length 13'),
|
||||
),
|
||||
length('length-vt', 'VT after /Length', () => lengthStream('/Length\x0B13')),
|
||||
length('length-nbsp', 'NBSP after /Length', () =>
|
||||
lengthStream('/Length\xA013'),
|
||||
),
|
||||
length('length-nel', 'NEL after /Length', () =>
|
||||
lengthStream('/Length\x8513'),
|
||||
),
|
||||
length('length-nul', 'NUL after /Length', () =>
|
||||
lengthStream('/Length\x0013'),
|
||||
),
|
||||
length('length-indirect-space', '13 0 R with spaces (indirect)', () =>
|
||||
lengthStream('/Length 13 0 R'),
|
||||
),
|
||||
length('length-indirect-vt', '13 0 R with VT separators', () =>
|
||||
lengthStream('/Length 13\x0B0\x0BR'),
|
||||
),
|
||||
length('length-indirect-nul', '13 0 R with NUL separators', () =>
|
||||
lengthStream('/Length 13\x000\x00R'),
|
||||
),
|
||||
length('length-10-digits', 'ten digits 0000000013', () =>
|
||||
lengthStream('/Length 0000000013'),
|
||||
),
|
||||
length('length-11-digits', 'eleven digits 00000000013', () =>
|
||||
lengthStream('/Length 00000000013'),
|
||||
),
|
||||
length('length-past-end', 'a direct length past the end of the file', () =>
|
||||
lengthStream('/Length 99999'),
|
||||
),
|
||||
length('length-tail-nul', 'NUL between the data and endstream', () =>
|
||||
lengthStream('/Length 13', '\x00\n'),
|
||||
),
|
||||
length('length-tail-vt', 'VT between the data and endstream', () =>
|
||||
lengthStream('/Length 13', '\x0B\n'),
|
||||
),
|
||||
length('measured-lf', 'no /Length, LF before endstream', () =>
|
||||
lengthStream('', '\n'),
|
||||
),
|
||||
length('measured-crlf', 'no /Length, CRLF before endstream', () =>
|
||||
lengthStream('', '\r\n'),
|
||||
),
|
||||
length('measured-lfcr', 'no /Length, LF CR before endstream', () =>
|
||||
lengthStream('', '\n\r'),
|
||||
),
|
||||
length('measured-cr', 'no /Length, CR before endstream', () =>
|
||||
lengthStream('', '\r'),
|
||||
),
|
||||
]
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// /Filter: /\/Filter\s*(\[\s*)?\/FlateDecode\b/
|
||||
|
||||
const filter = rule('/Filter regex', [
|
||||
'findEmbeddedFiles',
|
||||
'readAttachedDocument',
|
||||
])
|
||||
|
||||
const filterStream = (dict: string, data: Uint8Array = FLATE_J) =>
|
||||
craftPdf([
|
||||
streamObject({
|
||||
num: 2,
|
||||
dict: ` /Type /EmbeddedFile ${dict} /Length ${data.byteLength} `,
|
||||
data,
|
||||
}),
|
||||
])
|
||||
|
||||
const HEX_J = ascii(
|
||||
`${Buffer.from(J, 'latin1').toString('hex').toUpperCase()}>`,
|
||||
)
|
||||
|
||||
const FILTER: InputSpec[] = [
|
||||
filter('filter-name', '/Filter /FlateDecode (control)', () =>
|
||||
filterStream('/Filter /FlateDecode'),
|
||||
),
|
||||
filter('filter-unspaced', '/Filter/FlateDecode', () =>
|
||||
filterStream('/Filter/FlateDecode'),
|
||||
),
|
||||
filter('filter-array', '/Filter [/FlateDecode]', () =>
|
||||
filterStream('/Filter [/FlateDecode]'),
|
||||
),
|
||||
filter('filter-array-spaced', '/Filter [ /FlateDecode ]', () =>
|
||||
filterStream('/Filter [ /FlateDecode ]'),
|
||||
),
|
||||
filter(
|
||||
'filter-array-second',
|
||||
'/Filter [/ASCIIHexDecode /FlateDecode] on Flate data',
|
||||
() => filterStream('/Filter [/ASCIIHexDecode /FlateDecode]'),
|
||||
),
|
||||
filter('filter-asciihex', '/Filter /ASCIIHexDecode on hex data', () =>
|
||||
filterStream('/Filter /ASCIIHexDecode', HEX_J),
|
||||
),
|
||||
filter(
|
||||
'filter-asciihex-on-json',
|
||||
'/Filter /ASCIIHexDecode on plain JSON',
|
||||
() => filterStream('/Filter /ASCIIHexDecode', ascii(J)),
|
||||
),
|
||||
filter('filter-vt', 'VT after /Filter', () =>
|
||||
filterStream('/Filter\x0B/FlateDecode'),
|
||||
),
|
||||
filter('filter-nbsp', 'NBSP after /Filter', () =>
|
||||
filterStream('/Filter\xA0/FlateDecode'),
|
||||
),
|
||||
filter('filter-nul', 'NUL after /Filter', () =>
|
||||
filterStream('/Filter\x00/FlateDecode'),
|
||||
),
|
||||
filter('filter-array-nul', 'NUL inside the array', () =>
|
||||
filterStream('/Filter [\x00/FlateDecode]'),
|
||||
),
|
||||
filter('filter-name-continues', '/Filter /FlateDecodeX', () =>
|
||||
filterStream('/Filter /FlateDecodeX'),
|
||||
),
|
||||
]
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Filespec: /EF removal (lazy), /F then /UF string token, /EF << /F n 0 R >>
|
||||
|
||||
const filespecRule = rule('Filespec /EF and /F regexes, string token', [
|
||||
'findEmbeddedFiles',
|
||||
])
|
||||
|
||||
const filespec = (...dicts: string[]) =>
|
||||
pdfOf(...dicts.map((d, i) => `${i + 3} 0 obj\n<<${d}>>\nendobj\n`), EF2)
|
||||
|
||||
const FILESPEC: InputSpec[] = [
|
||||
filespecRule('filespec-ef-vt', 'VT around /EF and the reference', () =>
|
||||
filespec(
|
||||
' /Type /Filespec /F (osteo-report.json) /EF\x0B<< /F\x0B2\x0B0\x0BR >> ',
|
||||
),
|
||||
),
|
||||
filespecRule('filespec-ef-nbsp', 'NBSP around /EF and the reference', () =>
|
||||
filespec(
|
||||
' /Type /Filespec /F (osteo-report.json) /EF\xA0<< /F\xA02\xA00\xA0R >> ',
|
||||
),
|
||||
),
|
||||
filespecRule('filespec-ef-nul', 'NUL between /EF and <<', () =>
|
||||
filespec(' /Type /Filespec /F (osteo-report.json) /EF\x00<< /F 2 0 R >> '),
|
||||
),
|
||||
filespecRule('filespec-ref-nul', 'NUL between /F and the reference', () =>
|
||||
filespec(' /Type /Filespec /F (osteo-report.json) /EF << /F\x002 0 R >> '),
|
||||
),
|
||||
filespecRule('filespec-ref-nel', 'NEL between /F and the reference', () =>
|
||||
filespec(' /Type /Filespec /F (osteo-report.json) /EF << /F\x852 0 R >> '),
|
||||
),
|
||||
filespecRule(
|
||||
'filespec-f-vt',
|
||||
'VT between /F and its string, /UF fallback present',
|
||||
() =>
|
||||
filespec(
|
||||
' /Type /Filespec /F\x0B(osteo-report.json) /UF (fallback.json) /EF << /F 2 0 R >> ',
|
||||
),
|
||||
),
|
||||
filespecRule(
|
||||
'filespec-f-nul',
|
||||
'NUL between /F and its string, /UF fallback present',
|
||||
() =>
|
||||
filespec(
|
||||
' /Type /Filespec /F\x00(osteo-report.json) /UF (fallback.json) /EF << /F 2 0 R >> ',
|
||||
),
|
||||
),
|
||||
filespecRule('filespec-uf-only', '/UF only', () =>
|
||||
filespec(' /Type /Filespec /UF (osteo-report.json) /EF << /F 2 0 R >> '),
|
||||
),
|
||||
filespecRule(
|
||||
'filespec-lazy-ef',
|
||||
'/EF holding a nested dictionary: removal stops at the first >>',
|
||||
() =>
|
||||
filespec(
|
||||
' /Type /Filespec /EF << /F 2 0 R /Sub << >> /F (inner.json) >> /UF (outer.json) ',
|
||||
),
|
||||
),
|
||||
filespecRule(
|
||||
'filespec-tight',
|
||||
'no spaces, /EF closing right before the Filespec >>',
|
||||
() => filespec('/Type/Filespec/F(osteo-report.json)/EF<</F 2 0 R>>'),
|
||||
),
|
||||
filespecRule(
|
||||
'filespec-two-for-one-stream',
|
||||
'two Filespecs for one stream: the first wins',
|
||||
() =>
|
||||
filespec(
|
||||
' /Type /Filespec /F (decoy.json) /EF << /F 2 0 R >> ',
|
||||
' /Type /Filespec /F (osteo-report.json) /EF << /F 2 0 R >> ',
|
||||
),
|
||||
),
|
||||
filespecRule(
|
||||
'filespec-backslash-cr',
|
||||
'backslash then CR inside the /F string',
|
||||
() =>
|
||||
filespec(
|
||||
' /Type /Filespec /F (osteo-report\\\r.json) /UF (fallback.json) /EF << /F 2 0 R >> ',
|
||||
),
|
||||
),
|
||||
filespecRule(
|
||||
'filespec-backslash-lf',
|
||||
'backslash then LF inside the /F string',
|
||||
() =>
|
||||
filespec(
|
||||
' /Type /Filespec /F (osteo-report\\\n.json) /UF (fallback.json) /EF << /F 2 0 R >> ',
|
||||
),
|
||||
),
|
||||
filespecRule('filespec-plain-cr', 'a bare CR inside the /F string', () =>
|
||||
filespec(' /Type /Filespec /F (osteo-report\r.json) /EF << /F 2 0 R >> '),
|
||||
),
|
||||
filespecRule(
|
||||
'filespec-escaped-paren',
|
||||
'an escaped parenthesis inside the /F string',
|
||||
() =>
|
||||
filespec(
|
||||
' /Type /Filespec /F (osteo-report\\).json) /EF << /F 2 0 R >> ',
|
||||
),
|
||||
),
|
||||
filespecRule('filespec-hex-latin1', 'hex /F name without BOM', () =>
|
||||
filespec(
|
||||
` /Type /Filespec /F <${Buffer.from('osteo-report.json').toString('hex')}> /EF << /F 2 0 R >> `,
|
||||
),
|
||||
),
|
||||
]
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// /Keywords: isDelimiter after the key, string token, 4,096-byte window, 32 occurrences
|
||||
|
||||
const keywordsRule = rule('/Keywords stamp', [
|
||||
'hasArchiveStamp',
|
||||
'readAttachedDocument',
|
||||
])
|
||||
|
||||
const STAMP = 'faunosteo-archive/1'
|
||||
const keywords = (body: string) => pdfOf(`3 0 obj\n<< ${body} >>\nendobj\n`)
|
||||
const hexWith = (text: string, insert: string) => {
|
||||
const hex = Buffer.from(text, 'latin1').toString('hex')
|
||||
return `<${hex.slice(0, 8)}${insert}${hex.slice(8)}>`
|
||||
}
|
||||
const utf16Literal = (text: string) =>
|
||||
`(\xFE\xFF${Array.from(text, (c) => `\x00${c}`).join('')})`
|
||||
/** A literal token of exactly `total` bytes ending with the stamp. */
|
||||
const literalOfLength = (total: number) =>
|
||||
`(${'x'.repeat(total - STAMP.length - 2)}${STAMP})`
|
||||
|
||||
const KEYWORDS: InputSpec[] = [
|
||||
keywordsRule('keywords-literal', 'literal string (control)', () =>
|
||||
keywords(`/Keywords (${STAMP})`),
|
||||
),
|
||||
keywordsRule('keywords-key-vt', 'VT after the key', () =>
|
||||
keywords(`/Keywords\x0B(${STAMP})`),
|
||||
),
|
||||
keywordsRule('keywords-key-nbsp', 'NBSP after the key', () =>
|
||||
keywords(`/Keywords\xA0(${STAMP})`),
|
||||
),
|
||||
keywordsRule('keywords-key-nul', 'NUL after the key', () =>
|
||||
keywords(`/Keywords\x00(${STAMP})`),
|
||||
),
|
||||
keywordsRule('keywords-key-unspaced', 'the string right after the key', () =>
|
||||
keywords(`/Keywords(${STAMP})`),
|
||||
),
|
||||
keywordsRule('keywords-key-continues', '/KeywordsX', () =>
|
||||
keywords(`/KeywordsX (${STAMP})`),
|
||||
),
|
||||
keywordsRule('keywords-hex-vt', 'VT inside a hex string', () =>
|
||||
keywords(`/Keywords ${hexWith(STAMP, '\x0B')}`),
|
||||
),
|
||||
keywordsRule('keywords-hex-nul', 'NUL inside a hex string', () =>
|
||||
keywords(`/Keywords ${hexWith(STAMP, '\x00')}`),
|
||||
),
|
||||
keywordsRule(
|
||||
'keywords-backslash-cr',
|
||||
'backslash then CR inside the literal',
|
||||
() => keywords(`/Keywords (${STAMP}\\\r)`),
|
||||
),
|
||||
keywordsRule('keywords-plain-cr', 'a bare CR inside the literal', () =>
|
||||
keywords(`/Keywords (x\r${STAMP})`),
|
||||
),
|
||||
keywordsRule('keywords-literal-utf16', 'UTF-16BE literal with BOM', () =>
|
||||
keywords(`/Keywords ${utf16Literal(STAMP)}`),
|
||||
),
|
||||
keywordsRule('keywords-token-4096', 'a 4,096-byte token', () =>
|
||||
keywords(`/Keywords ${literalOfLength(4096)}`),
|
||||
),
|
||||
keywordsRule('keywords-token-4097', 'a 4,097-byte token', () =>
|
||||
keywords(`/Keywords ${literalOfLength(4097)}`),
|
||||
),
|
||||
keywordsRule(
|
||||
'keywords-32nd-occurrence',
|
||||
'the stamp on the 32nd /Keywords',
|
||||
() => keywords(`${'/Keywords (x) '.repeat(31)}/Keywords (${STAMP})`),
|
||||
),
|
||||
keywordsRule(
|
||||
'keywords-33rd-occurrence',
|
||||
'the stamp on the 33rd /Keywords',
|
||||
() => keywords(`${'/Keywords (x) '.repeat(32)}/Keywords (${STAMP})`),
|
||||
),
|
||||
]
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// isWhitespace / isDelimiter around /Type /EmbeddedFile and `stream`; dictionary bounds; caps
|
||||
|
||||
const scanRule = rule('isWhitespace and isDelimiter, dictionary bounds, caps', [
|
||||
'findEmbeddedFiles',
|
||||
'readAttachedDocument',
|
||||
])
|
||||
|
||||
const efObject = (dict: string, between = '\n', eol = '\n') =>
|
||||
`2 0 obj\n<<${dict}>>${between}stream${eol}${J}\nendstream\nendobj\n`
|
||||
|
||||
/** An `EmbeddedFile` dictionary of exactly `total` bytes from `<<` to `>>`. */
|
||||
const efOfLength = (total: number) => {
|
||||
const frame = '<< /Type /EmbeddedFile /Length 13 /Pad () >>'
|
||||
const dict = `/Type /EmbeddedFile /Length 13 /Pad (${'x'.repeat(total - frame.length)}) `
|
||||
return pdfOf(efObject(` ${dict}`))
|
||||
}
|
||||
|
||||
const streamless = (count: number, type = '/Type /EmbeddedFile') =>
|
||||
Array.from(
|
||||
{ length: count },
|
||||
(_, i) => `${i + 10} 0 obj\n<< ${type} >>\nendobj\n`,
|
||||
).join('')
|
||||
|
||||
const SCAN_RULES: InputSpec[] = [
|
||||
scanRule('type-nul-gap', 'NUL between /Type and /EmbeddedFile', () =>
|
||||
pdfOf(efObject(' /Type\x00/EmbeddedFile /Length 13 ')),
|
||||
),
|
||||
scanRule('type-vt-gap', 'VT between /Type and /EmbeddedFile', () =>
|
||||
pdfOf(efObject(' /Type\x0B/EmbeddedFile /Length 13 ')),
|
||||
),
|
||||
scanRule('type-nbsp-gap', 'NBSP between /Type and /EmbeddedFile', () =>
|
||||
pdfOf(efObject(' /Type\xA0/EmbeddedFile /Length 13 ')),
|
||||
),
|
||||
scanRule('type-name-end-vt', 'VT right after /EmbeddedFile', () =>
|
||||
pdfOf(efObject(' /Type /EmbeddedFile\x0B/Length 13 ')),
|
||||
),
|
||||
scanRule('type-name-end-nul', 'NUL right after /EmbeddedFile', () =>
|
||||
pdfOf(efObject(' /Type /EmbeddedFile\x00/Length 13 ')),
|
||||
),
|
||||
scanRule('type-name-continues', '/EmbeddedFileX', () =>
|
||||
pdfOf(efObject(' /Type /EmbeddedFileX /Length 13 ')),
|
||||
),
|
||||
scanRule('stream-after-nul', 'NUL between >> and stream', () =>
|
||||
pdfOf(efObject(' /Type /EmbeddedFile /Length 13 ', '\x00')),
|
||||
),
|
||||
scanRule('stream-after-vt', 'VT between >> and stream', () =>
|
||||
pdfOf(efObject(' /Type /EmbeddedFile /Length 13 ', '\x0B')),
|
||||
),
|
||||
scanRule('stream-cr-only', 'stream then CR alone', () =>
|
||||
pdfOf(efObject(' /Type /EmbeddedFile /Length 13 ', '\n', '\r')),
|
||||
),
|
||||
scanRule('stream-space-lf', 'stream then space LF', () =>
|
||||
pdfOf(efObject(' /Type /EmbeddedFile /Length 13 ', '\n', ' \n')),
|
||||
),
|
||||
scanRule(
|
||||
'dict-length-4096',
|
||||
'an EmbeddedFile dictionary of 4,096 bytes',
|
||||
() => efOfLength(4096),
|
||||
),
|
||||
scanRule(
|
||||
'dict-length-4097',
|
||||
'an EmbeddedFile dictionary of 4,097 bytes',
|
||||
() => efOfLength(4097),
|
||||
),
|
||||
scanRule(
|
||||
'cap-32nd-dict-valid',
|
||||
'31 streamless EmbeddedFile dictionaries, then a valid one',
|
||||
() => pdfOf(streamless(31), EF2),
|
||||
),
|
||||
scanRule(
|
||||
'cap-33rd-dict-valid',
|
||||
'32 streamless EmbeddedFile dictionaries, then a valid one',
|
||||
() => pdfOf(streamless(32), EF2),
|
||||
),
|
||||
scanRule(
|
||||
'cap-ignores-non-names',
|
||||
'40 /Type /EmbeddedFileX dictionaries, then a valid one',
|
||||
() => pdfOf(streamless(40, '/Type /EmbeddedFileX'), EF2),
|
||||
),
|
||||
]
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// One 16 MiB budget: a stored length over what is left ends the search
|
||||
|
||||
const budgetRule = rule('shared candidate budget', ['readAttachedDocument'])
|
||||
|
||||
/** A Flate candidate inflating to `output` bytes of `x`: charged, never JSON. */
|
||||
const charged = (output: number) => {
|
||||
const data = deflate(new Uint8Array(output).fill(0x78))
|
||||
return streamObject({
|
||||
num: 2,
|
||||
dict: `/Type /EmbeddedFile /Filter /FlateDecode /Length ${data.byteLength}`,
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
const raw = (num: number, text: string) =>
|
||||
streamObject({
|
||||
num,
|
||||
dict: `/Type /EmbeddedFile /Length ${text.length}`,
|
||||
data: ascii(text),
|
||||
})
|
||||
|
||||
const flate = (num: number, data: Uint8Array) =>
|
||||
streamObject({
|
||||
num,
|
||||
dict: `/Type /EmbeddedFile /Filter /FlateDecode /Length ${data.byteLength}`,
|
||||
data,
|
||||
})
|
||||
|
||||
const PAD_40 = `{"version":3,"pad":"${'a'.repeat(18)}"}`
|
||||
const PAD_222 = `{"version":3,"pad":"${'a'.repeat(200)}"}`
|
||||
const corrupt = Uint8Array.from(FLATE_J, (b, i) => (i > 2 ? b ^ 0x55 : b))
|
||||
|
||||
const BUDGET: InputSpec[] = [
|
||||
budgetRule(
|
||||
'budget-break-before-valid',
|
||||
'20 bytes left, a 40-byte candidate, then a 13-byte one',
|
||||
() =>
|
||||
craftPdf([charged(MAX_ATTACHMENT_BYTES - 20), raw(3, PAD_40), raw(4, J)]),
|
||||
),
|
||||
budgetRule(
|
||||
'budget-skip-control',
|
||||
'20 bytes left, then a 13-byte candidate',
|
||||
() => craftPdf([charged(MAX_ATTACHMENT_BYTES - 20), raw(4, J)]),
|
||||
),
|
||||
budgetRule(
|
||||
'budget-exact-fit',
|
||||
'13 bytes left, then a 13-byte candidate',
|
||||
() => craftPdf([charged(MAX_ATTACHMENT_BYTES - 13), raw(4, J)]),
|
||||
),
|
||||
budgetRule(
|
||||
'budget-one-short',
|
||||
'12 bytes left, then a 13-byte candidate',
|
||||
() => craftPdf([charged(MAX_ATTACHMENT_BYTES - 12), raw(4, J)]),
|
||||
),
|
||||
budgetRule(
|
||||
'budget-inflate-limited-by-remaining',
|
||||
'100 bytes left, a small Flate candidate inflating to 222 bytes, then a 13-byte one',
|
||||
() =>
|
||||
craftPdf([
|
||||
charged(MAX_ATTACHMENT_BYTES - 100),
|
||||
flate(3, deflate(ascii(PAD_222))),
|
||||
raw(4, J),
|
||||
]),
|
||||
),
|
||||
budgetRule(
|
||||
'flate-corrupt-then-valid',
|
||||
'a corrupt Flate candidate, then a raw one',
|
||||
() => craftPdf([flate(2, corrupt), raw(3, J)]),
|
||||
),
|
||||
]
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// `%PDF-` within the first 1,024 bytes; the 50 MiB file cap
|
||||
|
||||
const headerRule = rule('file header and size', ['readAttachedDocument'])
|
||||
|
||||
const headerAt = (offset: number) => {
|
||||
const bytes = new Uint8Array(offset + 8)
|
||||
bytes.set(ascii('%PDF-1.7'), offset)
|
||||
return bytes
|
||||
}
|
||||
|
||||
const FILE: InputSpec[] = [
|
||||
headerRule('header-at-1019', '%PDF- at offset 1,019', () => headerAt(1019)),
|
||||
headerRule('header-at-1020', '%PDF- at offset 1,020', () => headerAt(1020)),
|
||||
headerRule('size-exactly-50mib', 'a file of exactly 50 MiB', () =>
|
||||
concat([ascii('%PDF-1.7\n'), new Uint8Array(MAX_PDF_BYTES - 9)]),
|
||||
),
|
||||
]
|
||||
|
||||
export const SEMANTIC_INPUTS: InputSpec[] = [
|
||||
...HEADER,
|
||||
...LENGTH,
|
||||
...FILTER,
|
||||
...FILESPEC,
|
||||
...KEYWORDS,
|
||||
...SCAN_RULES,
|
||||
...BUDGET,
|
||||
...FILE,
|
||||
]
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// decodePdfString tokens (Latin-1 strings, one character per byte)
|
||||
|
||||
export interface TokenCase {
|
||||
suite: string
|
||||
case: string
|
||||
token: string
|
||||
}
|
||||
|
||||
const SCAN_TOKENS =
|
||||
'crafted stream layouts > decodePdfString: literal with escapes, hex ASCII, hex UTF-16BE with BOM'
|
||||
|
||||
export const TOKEN_CASES: TokenCase[] = [
|
||||
...['(a\\(b\\)c)', '<6F7374656F>', '<FEFF006F0073>', '/Name'].map(
|
||||
(token) => ({
|
||||
suite: 'scan',
|
||||
case: SCAN_TOKENS,
|
||||
token,
|
||||
}),
|
||||
),
|
||||
...[
|
||||
'(a\\nb)',
|
||||
'(a\\\\b)',
|
||||
'(\\157)',
|
||||
'()',
|
||||
'<>',
|
||||
'<6F7>',
|
||||
'<6F 73\x0B74>',
|
||||
'<zz6F>',
|
||||
'<FEFF>',
|
||||
'<FEFF00>',
|
||||
'<FEFF006F00>',
|
||||
'(\xFE\xFF\x00o\x00s)',
|
||||
'(\xE9t\xE9)',
|
||||
'(abc',
|
||||
'abc)',
|
||||
].map((token) => ({
|
||||
suite: 'semantics',
|
||||
case: 'decodePdfString > literal unescape, hex digits, UTF-16BE BOM, Latin-1',
|
||||
token,
|
||||
})),
|
||||
]
|
||||
@@ -1,71 +0,0 @@
|
||||
import {
|
||||
buildSheetSnapshot,
|
||||
readReportDocument,
|
||||
ReportSchema,
|
||||
type Report,
|
||||
type SheetSnapshot,
|
||||
} from '@faunosteo/domain'
|
||||
import { loadDraftSheet, readFixtureJson, type DraftSheet } from './draft'
|
||||
import {
|
||||
leavesAsV2Report,
|
||||
legacyLeaves,
|
||||
loadLegacyBaseline,
|
||||
} from './legacy-leaves'
|
||||
|
||||
/** The three Phase 0 reports, built with the Phase 0 recipe. */
|
||||
export const REPORT_NAMES = ['v2full', 'demo', 'v2unresolved'] as const
|
||||
export type ReportName = (typeof REPORT_NAMES)[number]
|
||||
|
||||
export interface GoldenReports {
|
||||
draft: DraftSheet
|
||||
reports: Record<ReportName, Report>
|
||||
snapshots: Record<ReportName, SheetSnapshot>
|
||||
/** Unresolved findings of `v2unresolved` as the migration counted them. */
|
||||
unresolvedOfV2Unresolved: number
|
||||
}
|
||||
|
||||
/** sphenoid + ssb (the families the migration cannot place) plus one leaf that resolves. */
|
||||
function buildV2Unresolved(draft: DraftSheet) {
|
||||
const leaves = legacyLeaves(loadLegacyBaseline())
|
||||
const unresolvedFamilies = leaves.filter(
|
||||
(l) => l.zoneId === 'sphenoid' || l.zoneId === 'ssb',
|
||||
)
|
||||
const resolved = leaves.find((l) => l.zoneId === 'frontal')!
|
||||
return readReportDocument(
|
||||
leavesAsV2Report([...unresolvedFamilies, resolved]),
|
||||
draft.migrationMap,
|
||||
)
|
||||
}
|
||||
|
||||
export function loadGoldenReports(): GoldenReports {
|
||||
const draft = loadDraftSheet()
|
||||
const unresolved = buildV2Unresolved(draft)
|
||||
const reports: Record<ReportName, Report> = {
|
||||
v2full: readReportDocument(
|
||||
readFixtureJson('report-v2.full.json'),
|
||||
draft.migrationMap,
|
||||
).report,
|
||||
demo: ReportSchema.parse(readFixtureJson('report-v3.demo.json')),
|
||||
v2unresolved: unresolved.report,
|
||||
}
|
||||
const snapshots = Object.fromEntries(
|
||||
REPORT_NAMES.map((name) => [
|
||||
name,
|
||||
buildSheetSnapshot(draft, reports[name]),
|
||||
]),
|
||||
) as Record<ReportName, SheetSnapshot>
|
||||
return {
|
||||
draft,
|
||||
reports,
|
||||
snapshots,
|
||||
unresolvedOfV2Unresolved: unresolved.unresolvedFindings,
|
||||
}
|
||||
}
|
||||
|
||||
/** The 612-leaf legacy report migrated through the draft map (T5). */
|
||||
export function allLeavesMigrated(draft: DraftSheet) {
|
||||
return readReportDocument(
|
||||
leavesAsV2Report(legacyLeaves(loadLegacyBaseline())),
|
||||
draft.migrationMap,
|
||||
)
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import { Resvg } from '@resvg/resvg-js'
|
||||
import type { Rasterizer } from '../../src'
|
||||
|
||||
/**
|
||||
* A real Node rasterizer for T10. resvg 0.40 (resvg-js 2.6.2) panics
|
||||
* (`geom.rs:27`, `Option::unwrap() on None`) when gradient-filled elements
|
||||
* are culled by a cropped root `viewBox` such as the head view's
|
||||
* `60 100 500 380` on the equine drawing, aborting the process. The
|
||||
* adapter therefore renders the box covering the whole content at the
|
||||
* same scale and crops the pixels to the requested view: identical output
|
||||
* for a view that already covers its content (main view).
|
||||
*/
|
||||
|
||||
export interface Raster {
|
||||
requested: { widthPx: number; heightPx: number }
|
||||
png: Uint8Array
|
||||
}
|
||||
|
||||
interface Box {
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
const FONT = { loadSystemFonts: false }
|
||||
|
||||
function rootViewBox(svg: string): Box | null {
|
||||
const tag = svg.match(/<svg\b[^>]*>/)?.[0] ?? ''
|
||||
const raw = tag.match(/\sviewBox="([^"]+)"/)?.[1]
|
||||
if (!raw) return null
|
||||
const [x, y, width, height] = raw
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.map(Number)
|
||||
if (!(width! > 0) || !(height! > 0)) return null
|
||||
return { x: x!, y: y!, width: width!, height: height! }
|
||||
}
|
||||
|
||||
function withViewBox(svg: string, box: Box): string {
|
||||
const value = `${box.x} ${box.y} ${box.width} ${box.height}`
|
||||
return svg.replace(/(<svg\b[^>]*?\sviewBox=")[^"]+(")/, `$1${value}$2`)
|
||||
}
|
||||
|
||||
function union(a: Box, b: Box): Box {
|
||||
const x = Math.min(a.x, b.x)
|
||||
const y = Math.min(a.y, b.y)
|
||||
return {
|
||||
x,
|
||||
y,
|
||||
width: Math.max(a.x + a.width, b.x + b.width) - x,
|
||||
height: Math.max(a.y + a.height, b.y + b.height) - y,
|
||||
}
|
||||
}
|
||||
|
||||
function contentBox(svg: string): Box | null {
|
||||
const bbox = new Resvg(svg, { font: FONT }).getBBox()
|
||||
if (!bbox || !(bbox.width > 0) || !(bbox.height > 0)) return null
|
||||
return { x: bbox.x, y: bbox.y, width: bbox.width, height: bbox.height }
|
||||
}
|
||||
|
||||
export function resvgRasterizer(record: Raster[] = []): Rasterizer {
|
||||
return async (svg, size) => {
|
||||
const crop = rootViewBox(svg)
|
||||
const content = crop ? contentBox(svg) : null
|
||||
const full = crop && content ? union(crop, content) : crop
|
||||
const scale = crop ? size.widthPx / crop.width : 1
|
||||
const left = Math.round(((crop?.x ?? 0) - (full?.x ?? 0)) * scale)
|
||||
const top = Math.round(((crop?.y ?? 0) - (full?.y ?? 0)) * scale)
|
||||
const resvg = new Resvg(full ? withViewBox(svg, full) : svg, {
|
||||
fitTo: {
|
||||
mode: 'width',
|
||||
value: full ? Math.round(full.width * scale) : size.widthPx,
|
||||
},
|
||||
background: 'white',
|
||||
font: FONT,
|
||||
crop: {
|
||||
left,
|
||||
top,
|
||||
right: left + size.widthPx,
|
||||
bottom: top + size.heightPx,
|
||||
},
|
||||
})
|
||||
const png = new Uint8Array(resvg.render().asPng())
|
||||
record.push({ requested: size, png })
|
||||
return png
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
/**
|
||||
* The capped inflater: round trips, the exact limit, every failure mode as
|
||||
* null, the bomb cancelled early, and the compressed bytes fed to the
|
||||
* platform inflater in slices (the Chromium read-ahead bound; Node cannot
|
||||
* show the memory effect, only the feeding shape).
|
||||
*/
|
||||
import { deflateSync } from 'node:zlib'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { inflateFlate, MAX_ATTACHMENT_BYTES } from '../src/attachment/inflate'
|
||||
|
||||
const KiB = 1024
|
||||
const MiB = 1024 * KiB
|
||||
|
||||
/** Incompressible bytes: the compressed stream is about as long as the input. */
|
||||
function noise(length: number): Uint8Array {
|
||||
let seed = 0x9e3779b9
|
||||
return Uint8Array.from({ length }, () => {
|
||||
seed = (seed * 1664525 + 1013904223) >>> 0
|
||||
return seed >>> 24
|
||||
})
|
||||
}
|
||||
|
||||
const deflate = (data: Uint8Array) => new Uint8Array(deflateSync(data))
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('inflateFlate', () => {
|
||||
it('round-trips a payload spanning several slices', async () => {
|
||||
const payload = noise(200 * KiB)
|
||||
const compressed = deflate(payload)
|
||||
expect(compressed.byteLength).toBeGreaterThan(10 * 16 * KiB)
|
||||
expect(await inflateFlate(compressed)).toEqual(payload)
|
||||
})
|
||||
|
||||
it('feeds the inflater in 16 KiB slices, each awaited', async () => {
|
||||
const compressed = deflate(noise(100 * KiB))
|
||||
const write = vi.spyOn(WritableStreamDefaultWriter.prototype, 'write')
|
||||
await inflateFlate(compressed)
|
||||
const slices = Math.ceil(compressed.byteLength / (16 * KiB))
|
||||
expect(write).toHaveBeenCalledTimes(slices)
|
||||
const sizes = write.mock.calls.map((c) => (c[0] as Uint8Array).byteLength)
|
||||
expect(Math.max(...sizes)).toBe(16 * KiB)
|
||||
})
|
||||
|
||||
it('an output exactly at the limit passes, one byte more is null', async () => {
|
||||
const payload = noise(64 * KiB)
|
||||
const compressed = deflate(payload)
|
||||
expect(await inflateFlate(compressed, payload.byteLength)).toEqual(payload)
|
||||
expect(await inflateFlate(compressed, payload.byteLength - 1)).toBeNull()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['empty input', new Uint8Array(0)],
|
||||
['truncated stream', deflate(noise(4 * KiB)).subarray(0, 2 * KiB)],
|
||||
['trailing junk', Uint8Array.from([...deflate(noise(KiB)), 1, 2, 3])],
|
||||
[
|
||||
'corrupt body',
|
||||
Uint8Array.from(deflate(noise(KiB)), (b, i) => (i > 8 ? b ^ 0xff : b)),
|
||||
],
|
||||
['not deflate at all', new TextEncoder().encode('{"version":3}')],
|
||||
])('%s: null', async (_name, bytes) => {
|
||||
expect(await inflateFlate(bytes)).toBeNull()
|
||||
})
|
||||
|
||||
it('a 64 MiB bomb past the default cap is cancelled in well under a second', async () => {
|
||||
const bomb = deflate(new Uint8Array(64 * MiB))
|
||||
expect(bomb.byteLength).toBeLessThan(MiB)
|
||||
const started = performance.now()
|
||||
expect(await inflateFlate(bomb)).toBeNull()
|
||||
const elapsed = performance.now() - started
|
||||
console.log(`[inflate] 64 MiB bomb: ${elapsed.toFixed(0)} ms`)
|
||||
expect(elapsed).toBeLessThan(1000)
|
||||
expect(MAX_ATTACHMENT_BYTES).toBe(16 * MiB)
|
||||
})
|
||||
})
|
||||
@@ -1,203 +0,0 @@
|
||||
/**
|
||||
* R3 freeze O3 (plan 2026-10-14 §3): the engine's highlighted views as the
|
||||
* TypeScript composes them (parse, allowlist, `composeViewSvg` with the halo
|
||||
* on main views), for the Rust highlight to reproduce at tree level. Every
|
||||
* (report, observation, view) of the three reference reports, plus an edge
|
||||
* sheet: a `<defs>` already present (nested), a detail view with its own
|
||||
* asset and no viewBox, highlighted triggers, path geometry, an empty
|
||||
* selection. Trees as structure (namespace, local name, attributes by
|
||||
* qualified name, children with text), never bytes. When a composed root
|
||||
* holds the sanitised asset unchanged, the case points at that tree instead
|
||||
* of repeating it. `MAKE_R3_ORACLES=1` writes
|
||||
* `crates/core/tests/oracles/r3/highlight.json`.
|
||||
*/
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { DOMParser, type Element as XmlElement, type Node as XmlNode } from '@xmldom/xmldom'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { Observation, SheetSnapshot } from '@faunosteo/domain'
|
||||
import { cleanSvgRoot, renderHighlightedView } from '../src/svg/view'
|
||||
import { serializeSvg } from '../src/svg/parse'
|
||||
import { loadGoldenReports, REPORT_NAMES } from './helpers/reports'
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||
const R3 = resolve(HERE, '../../../crates/core/tests/oracles/r3')
|
||||
const OUT = resolve(R3, 'highlight.json')
|
||||
const MAKE = process.env.MAKE_R3_ORACLES === '1'
|
||||
|
||||
type TreeNode =
|
||||
| { ns: string | null; name: string; attrs: Record<string, string>; children: TreeNode[] }
|
||||
| { text: string }
|
||||
| { comment: string }
|
||||
| { pi: string }
|
||||
|
||||
function treeOf(node: XmlNode): TreeNode {
|
||||
if (node.nodeType === 3 || node.nodeType === 4) return { text: node.nodeValue ?? '' }
|
||||
if (node.nodeType === 8) return { comment: node.nodeValue ?? '' }
|
||||
if (node.nodeType === 7) return { pi: node.nodeName }
|
||||
const el = node as unknown as XmlElement
|
||||
const attrs: Record<string, string> = {}
|
||||
const names = Array.from({ length: el.attributes.length }, (_, i) => el.attributes[i]!.name)
|
||||
for (const name of names.sort()) attrs[name] = el.getAttribute(name) ?? ''
|
||||
const children = Array.from({ length: node.childNodes.length }, (_, i) => node.childNodes[i]!)
|
||||
return { ns: el.namespaceURI, name: el.localName ?? el.nodeName, attrs, children: children.map(treeOf) }
|
||||
}
|
||||
|
||||
const parsedTree = (svg: string) =>
|
||||
treeOf(new DOMParser().parseFromString(svg, 'image/svg+xml').documentElement!)
|
||||
|
||||
const EDGE_MAIN = [
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"',
|
||||
' viewBox="0 0 100 80" width="100" height="80">',
|
||||
'<g id="g1"><defs id="d1"><linearGradient id="lg"><stop offset="0" stop-color="#000"/>',
|
||||
'</linearGradient></defs><path d="M0 0h10" fill="url(#lg)"/></g>\n',
|
||||
'<rect x="1" y="1" width="5" height="5"/></svg>',
|
||||
].join('')
|
||||
const EDGE_OWN = '<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50"><circle cx="5" cy="5" r="2"/></svg>'
|
||||
const OWN_ASSET = '9d0e5f3a-1b2c-4d5e-8f90-a1b2c3d4e5f6'
|
||||
|
||||
function edgeSnapshot(): SheetSnapshot {
|
||||
const layer = JSON.parse(readFileSync(resolve(R3, 'layer.json'), 'utf8'))
|
||||
const document = structuredClone(layer.edge)
|
||||
const main = document.views.find((v: { id: string }) => v.id === 'main')
|
||||
document.views.push({
|
||||
id: 'detail-own',
|
||||
kind: 'detail',
|
||||
parent_view_id: 'main',
|
||||
name: { fr: 'Détail', en: 'Detail' },
|
||||
svg_asset_id: OWN_ASSET,
|
||||
view_box: null,
|
||||
})
|
||||
document.annotations.push({
|
||||
id: 'own-point',
|
||||
kind: 'point',
|
||||
view_id: 'detail-own',
|
||||
category_id: 'joints',
|
||||
laterality: 'unpaired',
|
||||
geometry: { type: 'circle', cx: 5, cy: 5, r: 20 },
|
||||
review_status: 'inherited',
|
||||
color: null,
|
||||
name: { fr: 'Point', en: 'Point' },
|
||||
finding_zone_id: 'hip',
|
||||
vertebral_region_code: null,
|
||||
})
|
||||
return {
|
||||
status: 'draft',
|
||||
ref: { sheetId: 'edge', versionId: null, documentSha256: 'e'.repeat(64) },
|
||||
document,
|
||||
assets: [
|
||||
{ svgAssetId: main.svg_asset_id, sha256: 'a'.repeat(64), svg: EDGE_MAIN },
|
||||
{ svgAssetId: OWN_ASSET, sha256: 'b'.repeat(64), svg: EDGE_OWN },
|
||||
],
|
||||
} as unknown as SheetSnapshot
|
||||
}
|
||||
|
||||
const zone = (annotationId: string, viewId: string) => ({ annotationId, viewId })
|
||||
const observation = (id: string, zones: Array<{ annotationId: string; viewId: string }>) =>
|
||||
({ id, zones, findings: [], freeTextFindings: [], comment: '' }) as unknown as Observation
|
||||
|
||||
const EDGE_OBSERVATIONS = [
|
||||
observation('edge-1', [
|
||||
zone('point-polygon', 'main'),
|
||||
zone('zone-path', 'main'),
|
||||
zone('trigger-named', 'main'),
|
||||
zone('zone-circle', 'main'),
|
||||
zone('trigger-circle', 'main'),
|
||||
]),
|
||||
observation('edge-2', [zone('head-point', 'head'), zone('hip', 'main')]),
|
||||
observation('edge-3', [zone('own-point', 'detail-own')]),
|
||||
observation('edge-4', []),
|
||||
]
|
||||
|
||||
interface HighlightCase {
|
||||
sheet: string
|
||||
observation: Observation
|
||||
viewId: string
|
||||
size: { widthPx: number; heightPx: number }
|
||||
root: { ns: string | null; name: string; attrs: Record<string, string> }
|
||||
/** Children before the asset's, the asset's (or `asset:<id>` when unchanged), the layer. */
|
||||
before: TreeNode[]
|
||||
asset: TreeNode[] | string
|
||||
layer: TreeNode
|
||||
}
|
||||
|
||||
function assetIdOf(sheet: SheetSnapshot, viewId: string): string {
|
||||
const views = new Map(sheet.document.views.map((v) => [v.id, v]))
|
||||
let view = views.get(viewId)
|
||||
while (view && view.svg_asset_id === null && view.kind === 'detail') {
|
||||
view = views.get(view.parent_view_id)
|
||||
}
|
||||
return view!.svg_asset_id!
|
||||
}
|
||||
|
||||
function highlightCase(
|
||||
name: string,
|
||||
sheet: SheetSnapshot,
|
||||
obs: Observation,
|
||||
viewId: string,
|
||||
sanitized: Record<string, TreeNode>,
|
||||
): HighlightCase {
|
||||
const rendered = renderHighlightedView(sheet, viewId, obs)
|
||||
const tree = parsedTree(rendered.svg)
|
||||
if (!('children' in tree)) throw new Error('no root')
|
||||
const assetId = assetIdOf(sheet, viewId)
|
||||
const assetTree = sanitized[assetId]!
|
||||
const assetChildren = 'children' in assetTree ? assetTree.children : []
|
||||
const before = tree.children.slice(0, tree.children.length - 1 - assetChildren.length)
|
||||
const middle = tree.children.slice(before.length, -1)
|
||||
const same = JSON.stringify(middle) === JSON.stringify(assetChildren)
|
||||
return {
|
||||
sheet: name,
|
||||
observation: obs,
|
||||
viewId,
|
||||
size: rendered.size,
|
||||
root: { ns: tree.ns, name: tree.name, attrs: tree.attrs },
|
||||
before: same ? before : [],
|
||||
asset: same ? `asset:${assetId}` : tree.children.slice(0, -1),
|
||||
layer: tree.children.at(-1)!,
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizedTrees(sheet: SheetSnapshot): Record<string, TreeNode> {
|
||||
return Object.fromEntries(
|
||||
sheet.assets.map((a) => [a.svgAssetId, parsedTree(serializeSvg(cleanSvgRoot(a.svg)))]),
|
||||
)
|
||||
}
|
||||
|
||||
function build() {
|
||||
const golden = loadGoldenReports()
|
||||
const edge = edgeSnapshot()
|
||||
const sanitized = { ...sanitizedTrees(golden.snapshots.demo), ...sanitizedTrees(edge) }
|
||||
const cases: HighlightCase[] = []
|
||||
for (const name of REPORT_NAMES) {
|
||||
for (const obs of golden.reports[name].observations) {
|
||||
for (const viewId of ['main', 'head']) {
|
||||
cases.push(highlightCase(name, golden.snapshots[name], obs, viewId, sanitized))
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const obs of EDGE_OBSERVATIONS) {
|
||||
for (const viewId of ['main', 'head', 'detail-own']) {
|
||||
cases.push(highlightCase('edge', edge, obs, viewId, sanitized))
|
||||
}
|
||||
}
|
||||
return {
|
||||
edgeAssets: { main: EDGE_MAIN, own: EDGE_OWN, ownAssetId: OWN_ASSET },
|
||||
edgeDocument: edge.document,
|
||||
sanitized,
|
||||
cases,
|
||||
}
|
||||
}
|
||||
|
||||
describe('R3 highlight oracles (TypeScript freeze)', () => {
|
||||
it('matches the frozen highlighted trees', () => {
|
||||
const actual = build()
|
||||
if (MAKE) {
|
||||
mkdirSync(R3, { recursive: true })
|
||||
writeFileSync(OUT, `${JSON.stringify(actual, null, 1)}\n`)
|
||||
return
|
||||
}
|
||||
expect(actual).toEqual(JSON.parse(readFileSync(OUT, 'utf8')))
|
||||
})
|
||||
})
|
||||
@@ -1,169 +0,0 @@
|
||||
/**
|
||||
* R3 freeze O4 + O5 (plan 2026-10-14 §3): what the TypeScript sanitiser does
|
||||
* with every case of the hostile corpus (`crates/core/tests/fixtures/svg/
|
||||
* hostile/*.svg`, plus generated cases defined by a small spec both sides
|
||||
* build the same way) and with the legitimate SVGs of the product (the sheet
|
||||
* drawing, the partner logo, the public SVGs): rejected with a reason, or
|
||||
* kept with the list of removed names and the sanitised tree. The Rust
|
||||
* sanitiser must give the same verdict where both apply the same rule; where
|
||||
* the plan declares Rust stricter, the Rust test states its own verdict next
|
||||
* to this one. `MAKE_R3_ORACLES=1` writes
|
||||
* `crates/core/tests/oracles/r3/sanitiser.json`.
|
||||
*/
|
||||
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { DOMParser, type Element as XmlElement, type Node as XmlNode } from '@xmldom/xmldom'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseSvg, serializeSvg } from '../src/svg/parse'
|
||||
import { sanitizeSvgRoot } from '../src/svg/sanitize'
|
||||
import { SvgRejectedError } from '../src/errors'
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = resolve(HERE, '../../..')
|
||||
const HOSTILE = resolve(ROOT, 'crates/core/tests/fixtures/svg/hostile')
|
||||
const OUT = resolve(ROOT, 'crates/core/tests/oracles/r3/sanitiser.json')
|
||||
const MAKE = process.env.MAKE_R3_ORACLES === '1'
|
||||
|
||||
/** The legitimate SVGs that must come out untouched (zero removal, same tree). */
|
||||
const LEGITIMATE = [
|
||||
'supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg',
|
||||
'apps/app/src/assets/brand/paws-in-harmony.svg',
|
||||
'apps/app/public/favicon.svg',
|
||||
'apps/app/public/logo-horizontal.svg',
|
||||
]
|
||||
|
||||
/**
|
||||
* Generated cases: `uses` = a path then N `<use href="#p"/>`; `chain` = L levels of
|
||||
* groups each holding W uses of the previous level; `depth` = N nested `<g>` under
|
||||
* the root (root depth 1); `elements` = the root plus N-1 `<path/>`; `bytes` = a root
|
||||
* whose comment pads the text to N bytes; `attributes` = one path with N attributes.
|
||||
*/
|
||||
type Spec =
|
||||
| { kind: 'uses'; n: number }
|
||||
| { kind: 'chain'; levels: number; width: number }
|
||||
| { kind: 'depth'; n: number }
|
||||
| { kind: 'elements'; n: number }
|
||||
| { kind: 'bytes'; n: number }
|
||||
| { kind: 'attributes'; n: number }
|
||||
|
||||
const SPECS: Spec[] = [
|
||||
{ kind: 'uses', n: 256 },
|
||||
{ kind: 'uses', n: 257 },
|
||||
{ kind: 'chain', levels: 8, width: 30 },
|
||||
{ kind: 'depth', n: 64 },
|
||||
{ kind: 'depth', n: 65 },
|
||||
{ kind: 'elements', n: 20000 },
|
||||
{ kind: 'elements', n: 20001 },
|
||||
{ kind: 'bytes', n: 2 * 1024 * 1024 },
|
||||
{ kind: 'bytes', n: 2 * 1024 * 1024 + 1 },
|
||||
{ kind: 'attributes', n: 2000 },
|
||||
]
|
||||
|
||||
const OPEN = '<svg xmlns="http://www.w3.org/2000/svg">'
|
||||
|
||||
export function generated(spec: Spec): string {
|
||||
switch (spec.kind) {
|
||||
case 'uses':
|
||||
return `${OPEN}<path id="p" d="M0 0h1"/>${'<use href="#p"/>'.repeat(spec.n)}</svg>`
|
||||
case 'chain': {
|
||||
let body = '<path id="l0" d="M0 0h1"/>'
|
||||
for (let level = 1; level <= spec.levels; level++) {
|
||||
body += `<g id="l${level}">${`<use href="#l${level - 1}"/>`.repeat(spec.width)}</g>`
|
||||
}
|
||||
return `${OPEN}${body}</svg>`
|
||||
}
|
||||
case 'depth':
|
||||
return `${OPEN}${'<g>'.repeat(spec.n - 1)}${'</g>'.repeat(spec.n - 1)}</svg>`
|
||||
case 'elements':
|
||||
return `${OPEN}${'<path/>'.repeat(spec.n - 1)}</svg>`
|
||||
case 'bytes': {
|
||||
const frame = `${OPEN}<!---->` + '</svg>'
|
||||
return `${OPEN}<!--${'x'.repeat(spec.n - frame.length)}--></svg>`
|
||||
}
|
||||
case 'attributes': {
|
||||
const attrs = Array.from({ length: spec.n }, (_, i) => ` data-a${i}="${i}"`).join('')
|
||||
return `${OPEN}<path d="M0 0h1"${attrs}/></svg>`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type TreeNode =
|
||||
| { ns: string | null; name: string; attrs: Record<string, string>; children: TreeNode[] }
|
||||
| { text: string }
|
||||
| { comment: string }
|
||||
| { pi: string }
|
||||
|
||||
function treeOf(node: XmlNode): TreeNode {
|
||||
if (node.nodeType === 3 || node.nodeType === 4) return { text: node.nodeValue ?? '' }
|
||||
if (node.nodeType === 8) return { comment: node.nodeValue ?? '' }
|
||||
if (node.nodeType === 7) return { pi: node.nodeName }
|
||||
const el = node as unknown as XmlElement
|
||||
const attrs: Record<string, string> = {}
|
||||
const names = Array.from({ length: el.attributes.length }, (_, i) => el.attributes[i]!.name)
|
||||
for (const name of names.sort()) attrs[name] = el.getAttribute(name) ?? ''
|
||||
const children = Array.from({ length: node.childNodes.length }, (_, i) => node.childNodes[i]!)
|
||||
return { ns: el.namespaceURI, name: el.localName ?? el.nodeName, attrs, children: children.map(treeOf) }
|
||||
}
|
||||
|
||||
type Verdict =
|
||||
| { rejected: string }
|
||||
| { removed: string[]; tree?: TreeNode; bytes?: number }
|
||||
|
||||
/** Big generated outcomes keep the removed list and the output size, not the tree. */
|
||||
function verdictOf(text: string, keepTree: boolean): Verdict {
|
||||
try {
|
||||
const root = parseSvg(text)
|
||||
const { removed } = sanitizeSvgRoot(root)
|
||||
const svg = serializeSvg(root)
|
||||
if (!keepTree) return { removed: [...new Set(removed)].sort(), bytes: svg.length }
|
||||
const tree = treeOf(new DOMParser().parseFromString(svg, 'image/svg+xml').documentElement!)
|
||||
return { removed, tree }
|
||||
} catch (error) {
|
||||
if (error instanceof SvgRejectedError) return { rejected: error.reason }
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/** The tree xmldom gives the source itself: what a zero-removal sanitiser must keep. */
|
||||
function sourceTree(text: string): TreeNode {
|
||||
return treeOf(new DOMParser().parseFromString(text, 'image/svg+xml').documentElement!)
|
||||
}
|
||||
|
||||
function build() {
|
||||
const hostile = Object.fromEntries(
|
||||
readdirSync(HOSTILE)
|
||||
.filter((f) => f.endsWith('.svg'))
|
||||
.sort()
|
||||
.map((f) => [f, verdictOf(readFileSync(resolve(HOSTILE, f), 'utf8'), true)]),
|
||||
)
|
||||
const specs = SPECS.map((spec) => ({ spec, verdict: verdictOf(generated(spec), false) }))
|
||||
const legitimate = LEGITIMATE.map((path) => {
|
||||
const text = readFileSync(resolve(ROOT, path), 'utf8')
|
||||
const verdict = verdictOf(text, true)
|
||||
const unchanged =
|
||||
'removed' in verdict &&
|
||||
JSON.stringify(verdict.tree) === JSON.stringify(sourceTree(text))
|
||||
const tree = 'removed' in verdict ? verdict.tree : null
|
||||
return { path, removed: 'removed' in verdict ? verdict.removed : null, unchanged, tree }
|
||||
})
|
||||
return { hostile, specs, legitimate }
|
||||
}
|
||||
|
||||
describe('R3 sanitiser oracles (TypeScript freeze)', () => {
|
||||
it('keeps every legitimate SVG untouched', () => {
|
||||
for (const entry of build().legitimate) {
|
||||
expect(entry, entry.path).toMatchObject({ removed: [], unchanged: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('matches the frozen verdicts', () => {
|
||||
const actual = build()
|
||||
if (MAKE) {
|
||||
mkdirSync(dirname(OUT), { recursive: true })
|
||||
writeFileSync(OUT, `${JSON.stringify(actual, null, 1)}\n`)
|
||||
return
|
||||
}
|
||||
expect(actual).toEqual(JSON.parse(readFileSync(OUT, 'utf8')))
|
||||
})
|
||||
})
|
||||
@@ -1,95 +0,0 @@
|
||||
/**
|
||||
* R4.1 freeze O5 (plan 2026-10-17 §B.5.1): `formatDate` (render/dates.ts)
|
||||
* as the TypeScript engine prints it with Node's ICU, for fr and en, over a
|
||||
* grid of `YYYY-MM-DD` inputs (years 0000 to 9999 with the `Date.UTC`
|
||||
* 0-99 → 1900-1999 mapping, months 00 to 13, days 00 to 32, so rolled-over
|
||||
* dates come back unchanged) and strings the pattern refuses.
|
||||
* `MAKE_R4_ORACLES=1` writes `crates/core/tests/oracles/r4/dates.json`.
|
||||
*/
|
||||
import { describe, it } from 'vitest'
|
||||
import { formatDate } from '../src/render/dates'
|
||||
import { environment, freezeJson } from './helpers/r4-oracle-io'
|
||||
|
||||
const YEARS = [
|
||||
'0000',
|
||||
'0001',
|
||||
'0050',
|
||||
'0099',
|
||||
'0100',
|
||||
'0999',
|
||||
'1000',
|
||||
'1900',
|
||||
'1904',
|
||||
'1999',
|
||||
'2000',
|
||||
'2024',
|
||||
'2026',
|
||||
'9999',
|
||||
]
|
||||
const pad2 = (n: number): string => String(n).padStart(2, '0')
|
||||
const MONTHS = Array.from({ length: 14 }, (_, i) => pad2(i))
|
||||
const DAYS = Array.from({ length: 33 }, (_, i) => pad2(i))
|
||||
|
||||
/** Inputs `^\d{4}-\d{2}-\d{2}$` refuses (printed unchanged), plus near misses it accepts. */
|
||||
const OTHER_INPUTS = [
|
||||
'2026-1-5',
|
||||
'26-01-05',
|
||||
'',
|
||||
'2026-01-05T00:00',
|
||||
' 2026-01-05',
|
||||
'2026-01-05 ',
|
||||
'2026 -01-05',
|
||||
'\u00a02026-01-05',
|
||||
'2026-01-05',
|
||||
'+2026-01-05',
|
||||
'-2026-01-05',
|
||||
'+002026-01-05',
|
||||
'2026/01/05',
|
||||
'2026-01-05\n',
|
||||
'\n2026-01-05',
|
||||
'20260105',
|
||||
'2026-001-05',
|
||||
'abcd-ef-gh',
|
||||
'١٢٣٤-٠١-٠٥',
|
||||
'2026-01-05Z',
|
||||
'10000-01-05',
|
||||
'0000-00-00',
|
||||
]
|
||||
|
||||
function buildGrid() {
|
||||
const results: Record<string, { fr: string[]; en: string[] }> = {}
|
||||
for (const year of YEARS) {
|
||||
for (const month of MONTHS) {
|
||||
const inputs = DAYS.map((day) => `${year}-${month}-${day}`)
|
||||
results[`${year}-${month}`] = {
|
||||
fr: inputs.map((input) => formatDate(input, 'fr')),
|
||||
en: inputs.map((input) => formatDate(input, 'en')),
|
||||
}
|
||||
}
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
function buildDates() {
|
||||
return {
|
||||
comment: [
|
||||
'formatDate(input, locale) (packages/pdf/src/render/dates.ts), Intl.DateTimeFormat fr-FR and',
|
||||
'en-US, day numeric, month long, year numeric, UTC. grid.results["YYYY-MM"].fr[d] is the',
|
||||
'output for input "YYYY-MM-" + days[d] (d = 0..32); an output equal to its input means the',
|
||||
'date was refused (rolled over or out of range). others: [input, fr, en].',
|
||||
],
|
||||
environment: environment(),
|
||||
grid: { years: YEARS, months: MONTHS, days: DAYS, results: buildGrid() },
|
||||
others: OTHER_INPUTS.map((input) => [
|
||||
input,
|
||||
formatDate(input, 'fr'),
|
||||
formatDate(input, 'en'),
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
describe('R4 date oracles (TypeScript freeze)', () => {
|
||||
it('matches the frozen formatDate outputs', () => {
|
||||
freezeJson('dates.json', buildDates())
|
||||
})
|
||||
})
|
||||
@@ -1,333 +0,0 @@
|
||||
/**
|
||||
* R4.1 freeze O9, Node part (plan 2026-10-17 §B.1.2 "Inflation", §B.5.1):
|
||||
* the verdict of `inflateFlate(bytes, limit)` (DecompressionStream('deflate')
|
||||
* fed in 16 KiB awaited slices, null on any failure or past the limit) on
|
||||
* the zlib framing cases, inputs under `apps/app/tests/fixtures/pdf/r4/
|
||||
* inflate/`, rows in `crates/core/tests/oracles/r4/inflate.json`. Each row
|
||||
* holds the Node verdict; the browser harness (`scripts/browser/
|
||||
* inflate-verdicts.mjs`) runs the same function on the same files in each
|
||||
* engine and writes its columns next to Node's in `inflate.browsers.json`.
|
||||
* `MAKE_R4_ORACLES=1` writes the inputs and this file.
|
||||
*/
|
||||
import { resolve } from 'node:path'
|
||||
import {
|
||||
constants,
|
||||
createDeflate,
|
||||
deflateRawSync,
|
||||
deflateSync,
|
||||
gzipSync,
|
||||
} from 'node:zlib'
|
||||
import { describe, it } from 'vitest'
|
||||
import { MAX_ATTACHMENT_BYTES } from '../src'
|
||||
import { ascii, concat, deflate, KiB, noise } from './helpers/r4-reader-craft'
|
||||
import {
|
||||
expectOnlyFiles,
|
||||
inflateVerdict,
|
||||
R4_INPUTS_DIR,
|
||||
R4_ORACLES_DIR,
|
||||
sha256,
|
||||
storeFile,
|
||||
storeJson,
|
||||
} from './helpers/r4-reader-io'
|
||||
|
||||
const INPUTS_DIR = resolve(R4_INPUTS_DIR, 'inflate')
|
||||
/** The engine column this generator owns: recorded, never compared. */
|
||||
const nodeEngine = () => ({
|
||||
version: process.version,
|
||||
zlib: process.versions.zlib,
|
||||
})
|
||||
const OUT = resolve(R4_ORACLES_DIR, 'inflate.json')
|
||||
const CAP = MAX_ATTACHMENT_BYTES
|
||||
|
||||
const TEXT = ascii('{"version":3,"note":"inflate oracle"}')
|
||||
const STREAM = deflate(TEXT)
|
||||
const EXACT = 64 * KiB
|
||||
|
||||
function adler32(data: Uint8Array): number {
|
||||
let a = 1
|
||||
let b = 0
|
||||
for (const byte of data) {
|
||||
a = (a + byte) % 65521
|
||||
b = (b + a) % 65521
|
||||
}
|
||||
return ((b << 16) | a) >>> 0
|
||||
}
|
||||
|
||||
/** A stored deflate block; `nlen` defaults to the one's complement of the length. */
|
||||
function storedBlock(
|
||||
data: Uint8Array,
|
||||
final: boolean,
|
||||
nlen = ~data.length,
|
||||
): Uint8Array {
|
||||
const len = data.length
|
||||
return concat([
|
||||
Uint8Array.from([
|
||||
final ? 1 : 0,
|
||||
len & 0xff,
|
||||
len >> 8,
|
||||
nlen & 0xff,
|
||||
(nlen >> 8) & 0xff,
|
||||
]),
|
||||
data,
|
||||
])
|
||||
}
|
||||
|
||||
/** zlib framing (CMF 0x78, FLG 0x01) around raw deflate blocks. */
|
||||
function zlibOf(blocks: Uint8Array[], payload: Uint8Array): Uint8Array {
|
||||
const check = adler32(payload)
|
||||
const trailer = [
|
||||
check >>> 24,
|
||||
(check >> 16) & 0xff,
|
||||
(check >> 8) & 0xff,
|
||||
check & 0xff,
|
||||
]
|
||||
return concat([
|
||||
Uint8Array.from([0x78, 0x01]),
|
||||
...blocks,
|
||||
Uint8Array.from(trailer),
|
||||
])
|
||||
}
|
||||
|
||||
function storedBlocks(): Uint8Array {
|
||||
const parts = [ascii('abc'), ascii(''), ascii('defgh')]
|
||||
const blocks = parts.map((part, i) =>
|
||||
storedBlock(part, i === parts.length - 1),
|
||||
)
|
||||
return zlibOf(blocks, concat(parts))
|
||||
}
|
||||
|
||||
function storedBadNlen(): Uint8Array {
|
||||
const data = ascii('abcdefgh')
|
||||
return zlibOf([storedBlock(data, true, ~data.length ^ 1)], data)
|
||||
}
|
||||
|
||||
/** One zlib stream, a full flush after each chunk: several compressed blocks. */
|
||||
async function flushedBlocks(chunks: Uint8Array[]): Promise<Uint8Array> {
|
||||
const deflater = createDeflate()
|
||||
const out: Buffer[] = []
|
||||
deflater.on('data', (chunk: Buffer) => out.push(chunk))
|
||||
const ended = new Promise((done) => deflater.on('end', done))
|
||||
for (const chunk of chunks) {
|
||||
deflater.write(chunk)
|
||||
await new Promise<void>((done) =>
|
||||
deflater.flush(constants.Z_FULL_FLUSH, () => done()),
|
||||
)
|
||||
}
|
||||
deflater.end()
|
||||
await ended
|
||||
return new Uint8Array(Buffer.concat(out))
|
||||
}
|
||||
|
||||
const MULTI_BLOCK_TEXT = [
|
||||
'{"version":3,',
|
||||
`"note":"${'abc'.repeat(100)}",`,
|
||||
'"end":true}',
|
||||
].map(ascii)
|
||||
|
||||
const flipped = (bytes: Uint8Array, index: number, mask: number) =>
|
||||
Uint8Array.from(bytes, (b, i) => (i === index ? b ^ mask : b))
|
||||
|
||||
interface InflateCase {
|
||||
file: string
|
||||
title: string
|
||||
build: () => Uint8Array | Promise<Uint8Array>
|
||||
/** [limit, row title]; absent = the default 16 MiB cap only. */
|
||||
limits?: Array<[number, string]>
|
||||
}
|
||||
|
||||
const CASES: InflateCase[] = [
|
||||
{
|
||||
file: 'valid-noise-64kib.bin',
|
||||
title: 'valid zlib stream, 64 KiB of noise over several 16 KiB slices',
|
||||
build: () => deflate(noise(EXACT)),
|
||||
limits: [
|
||||
[CAP, 'valid zlib stream, default cap'],
|
||||
[EXACT, 'output exactly at the limit'],
|
||||
[EXACT - 1, 'output one byte over the limit'],
|
||||
],
|
||||
},
|
||||
{
|
||||
file: 'valid-json.bin',
|
||||
title: 'valid zlib stream, small JSON',
|
||||
build: () => STREAM,
|
||||
},
|
||||
{
|
||||
file: 'empty-input.bin',
|
||||
title: 'empty input (0 bytes)',
|
||||
build: () => new Uint8Array(0),
|
||||
},
|
||||
{
|
||||
file: 'empty-zlib-stream.bin',
|
||||
title: 'empty zlib stream (no output)',
|
||||
build: () => deflate(new Uint8Array(0)),
|
||||
},
|
||||
{
|
||||
file: 'truncated.bin',
|
||||
title: 'truncated stream (first 2 KiB of a 4 KiB noise stream)',
|
||||
build: () => deflate(noise(4 * KiB)).subarray(0, 2 * KiB),
|
||||
},
|
||||
{
|
||||
file: 'truncated-header-only.bin',
|
||||
title: 'the 2-byte zlib header alone',
|
||||
build: () => STREAM.subarray(0, 2),
|
||||
},
|
||||
{
|
||||
file: 'missing-adler.bin',
|
||||
title: 'complete deflate data, Adler-32 missing',
|
||||
build: () => STREAM.subarray(0, -4),
|
||||
},
|
||||
{
|
||||
file: 'partial-adler.bin',
|
||||
title: 'complete deflate data, 2 of the 4 Adler-32 bytes',
|
||||
build: () => STREAM.subarray(0, -2),
|
||||
},
|
||||
{
|
||||
file: 'bad-adler.bin',
|
||||
title: 'bad Adler-32 (last byte flipped)',
|
||||
build: () => flipped(STREAM, STREAM.length - 1, 0xff),
|
||||
},
|
||||
{
|
||||
file: 'trailing-bytes.bin',
|
||||
title: 'trailing bytes after the stream end',
|
||||
build: () => Uint8Array.from([...deflate(noise(KiB)), 1, 2, 3]),
|
||||
},
|
||||
{
|
||||
file: 'trailing-zero-byte.bin',
|
||||
title: 'one 0x00 byte after the stream end',
|
||||
build: () => concat([STREAM, new Uint8Array(1)]),
|
||||
},
|
||||
{
|
||||
file: 'two-streams.bin',
|
||||
title: 'two complete zlib streams back to back',
|
||||
build: () => concat([STREAM, STREAM]),
|
||||
},
|
||||
{
|
||||
file: 'raw-deflate.bin',
|
||||
title: 'raw deflate without zlib header',
|
||||
build: () => new Uint8Array(deflateRawSync(TEXT)),
|
||||
},
|
||||
{
|
||||
file: 'gzip.bin',
|
||||
title: 'gzip header and trailer',
|
||||
build: () => new Uint8Array(gzipSync(TEXT)),
|
||||
},
|
||||
{
|
||||
file: 'preset-dictionary.bin',
|
||||
title: 'preset dictionary flag (FDICT) set',
|
||||
build: () =>
|
||||
new Uint8Array(deflateSync(TEXT, { dictionary: ascii('{"version":') })),
|
||||
},
|
||||
{
|
||||
file: 'bad-header-check.bin',
|
||||
title: 'zlib header whose FCHECK fails',
|
||||
build: () => flipped(STREAM, 1, 0x01),
|
||||
},
|
||||
{
|
||||
file: 'small-window.bin',
|
||||
title: 'window size below 32 KiB (CINFO 1, windowBits 9)',
|
||||
build: () => new Uint8Array(deflateSync(TEXT, { windowBits: 9 })),
|
||||
},
|
||||
{
|
||||
file: 'stored-blocks.bin',
|
||||
title: 'stored blocks: two non-final ones (one empty), then a final one',
|
||||
build: storedBlocks,
|
||||
},
|
||||
{
|
||||
file: 'stored-bad-nlen.bin',
|
||||
title: 'stored block whose NLEN is not the complement of LEN',
|
||||
build: storedBadNlen,
|
||||
},
|
||||
{
|
||||
file: 'multiple-blocks.bin',
|
||||
title: 'several compressed blocks separated by full flushes',
|
||||
build: () => flushedBlocks(MULTI_BLOCK_TEXT),
|
||||
},
|
||||
{
|
||||
file: 'corrupt-body.bin',
|
||||
title: 'corrupt body (every byte after the ninth flipped)',
|
||||
build: () =>
|
||||
Uint8Array.from(deflate(noise(KiB)), (b, i) => (i > 8 ? b ^ 0xff : b)),
|
||||
},
|
||||
{
|
||||
file: 'not-deflate.bin',
|
||||
title: 'not deflate at all (JSON text)',
|
||||
build: () => ascii('{"version":3}'),
|
||||
},
|
||||
{
|
||||
file: 'output-exactly-16mib.bin',
|
||||
title: 'output of exactly 16 MiB (the default cap)',
|
||||
build: () => deflate(new Uint8Array(CAP)),
|
||||
},
|
||||
{
|
||||
file: 'bomb-16mib-plus-1.bin',
|
||||
title: 'output of 16 MiB + 1 (one byte over the default cap)',
|
||||
build: () => deflate(new Uint8Array(CAP + 1)),
|
||||
},
|
||||
]
|
||||
|
||||
interface Row {
|
||||
file: string
|
||||
case: string
|
||||
limit: number
|
||||
verdicts: Record<string, unknown>
|
||||
}
|
||||
|
||||
interface InflateOracle {
|
||||
engines: Record<string, unknown>
|
||||
inputs: Array<{ file: string; length: number; sha256: string }>
|
||||
rows: Row[]
|
||||
}
|
||||
|
||||
async function build() {
|
||||
const inputs: InflateOracle['inputs'] = []
|
||||
const rows: Row[] = []
|
||||
for (const spec of CASES) {
|
||||
const bytes = await spec.build()
|
||||
storeFile(resolve(INPUTS_DIR, spec.file), bytes)
|
||||
inputs.push({
|
||||
file: spec.file,
|
||||
length: bytes.byteLength,
|
||||
sha256: sha256(bytes),
|
||||
})
|
||||
for (const [limit, title] of spec.limits ?? [[CAP, spec.title]]) {
|
||||
const node = await inflateVerdict(bytes, limit)
|
||||
rows.push({ file: spec.file, case: title, limit, verdicts: { node } })
|
||||
}
|
||||
}
|
||||
return {
|
||||
oracle: 'O9',
|
||||
plan: '.claude/tasks/plans/2026-10-17-rust-r4-pdf-core.md §B.1.2, §B.5.1',
|
||||
generator: 'packages/pdf/tests/r4.inflate-oracles.test.ts',
|
||||
function:
|
||||
'inflateFlate(bytes, limit) of packages/pdf/src/attachment/inflate.ts, run in each engine on the file bytes',
|
||||
verdict: 'null, or { length, sha256 } of the output',
|
||||
inputsDir: 'apps/app/tests/fixtures/pdf/r4/inflate',
|
||||
engines: { node: nodeEngine() },
|
||||
inputs,
|
||||
rows,
|
||||
}
|
||||
}
|
||||
|
||||
/** The committed file restricted to what this generator owns, with the running Node recorded. */
|
||||
function nodeColumn(committed: unknown): unknown {
|
||||
const oracle = committed as InflateOracle
|
||||
return {
|
||||
...oracle,
|
||||
engines: { node: nodeEngine() },
|
||||
rows: oracle.rows.map((row) => ({
|
||||
...row,
|
||||
verdicts: { node: row.verdicts.node },
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
describe('R4 inflate oracles O9 (TypeScript freeze, Node)', () => {
|
||||
it('matches the frozen inputs and Node verdicts', async () => {
|
||||
const oracle = await build()
|
||||
storeJson(OUT, oracle, nodeColumn)
|
||||
expectOnlyFiles(
|
||||
INPUTS_DIR,
|
||||
CASES.map((c) => c.file),
|
||||
)
|
||||
}, 120_000)
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,322 +0,0 @@
|
||||
/**
|
||||
* R4.1 freeze O7 (plan 2026-10-17 §B.1.2, §B.5.1): what the TypeScript
|
||||
* reader answers on every input of scan.test.ts, inflate.test.ts,
|
||||
* read.test.ts and the reader cases of security.test.ts, rebuilt with the
|
||||
* same code, and on the §B.1.2 semantics rows. Inputs go under
|
||||
* `apps/app/tests/fixtures/pdf/r4/read/` (bytes, or a generator description
|
||||
* above 2 MiB), outcomes to `crates/core/tests/oracles/r4/read.json`: the
|
||||
* Rust reader reproduces them at R4.2. `MAKE_R4_ORACLES=1` writes both;
|
||||
* without it the test rebuilds everything and requires the same files.
|
||||
* pdf-lib stamps the current date into the PDFs it creates, so the clock is
|
||||
* frozen at FIXED_EXPORTED_AT while the inputs are built.
|
||||
*/
|
||||
import { resolve } from 'node:path'
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import type { ArchiveReadOutcome } from '@faunosteo/domain'
|
||||
import {
|
||||
ArchiveReadError,
|
||||
findEmbeddedFiles,
|
||||
MAX_ATTACHMENT_BYTES,
|
||||
MAX_PDF_BYTES,
|
||||
readAttachedDocument,
|
||||
readAttachmentBytes,
|
||||
readReportArchive,
|
||||
type EmbeddedFileCandidate,
|
||||
} from '../src'
|
||||
import { inflateFlate } from '../src/attachment/inflate'
|
||||
import {
|
||||
decodePdfString,
|
||||
hasArchiveStamp,
|
||||
hasPdfHeader,
|
||||
locateAttachment,
|
||||
type LocatedAttachment,
|
||||
} from '../src/attachment/scan'
|
||||
import { FIXED_EXPORTED_AT } from './helpers/goldens'
|
||||
import { objectSpan } from './helpers/r4-reader-craft'
|
||||
import {
|
||||
expectOnlyFiles,
|
||||
generatedWith,
|
||||
inflateVerdict,
|
||||
MAKE,
|
||||
R4_INPUTS_DIR,
|
||||
R4_ORACLES_DIR,
|
||||
readJsonFile,
|
||||
sha256,
|
||||
storeInput,
|
||||
storeJson,
|
||||
type SliceRef,
|
||||
type StoredInput,
|
||||
} from './helpers/r4-reader-io'
|
||||
import {
|
||||
readerContext,
|
||||
SUITE_INPUTS,
|
||||
type CaseRef,
|
||||
type InputSpec,
|
||||
type ReaderContext,
|
||||
} from './helpers/r4-reader-inputs'
|
||||
import { SEMANTIC_INPUTS, TOKEN_CASES } from './helpers/r4-reader-semantics'
|
||||
|
||||
const INPUTS_DIR = resolve(R4_INPUTS_DIR, 'read')
|
||||
const OUT = resolve(R4_ORACLES_DIR, 'read.json')
|
||||
const DEMO_EXPORT_FILE = 'scan.demo-export.pdf'
|
||||
|
||||
type Outcome = Record<string, unknown>
|
||||
|
||||
interface Entry extends StoredInput {
|
||||
kind: InputSpec['kind']
|
||||
cases: CaseRef[]
|
||||
outcomes: Record<string, unknown>
|
||||
}
|
||||
|
||||
const objectSha = (value: unknown) => sha256(JSON.stringify(value))
|
||||
|
||||
function failure(error: unknown): Outcome {
|
||||
if (!(error instanceof ArchiveReadError)) throw error
|
||||
const found =
|
||||
error.foundVersion === undefined ? {} : { foundVersion: error.foundVersion }
|
||||
return { ok: false, kind: error.kind, ...found }
|
||||
}
|
||||
|
||||
/** The success description of `run`, or the ArchiveReadError kind it throws. */
|
||||
async function outcomeOf<T>(
|
||||
run: () => Promise<T>,
|
||||
success: (value: T) => Promise<Outcome> | Outcome,
|
||||
): Promise<Outcome> {
|
||||
let value: T
|
||||
try {
|
||||
value = await run()
|
||||
} catch (error) {
|
||||
return failure(error)
|
||||
}
|
||||
return success(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* The candidate `locateAttachment` kept: a raw one is a view on the input,
|
||||
* a Flate one is the first whose inflation gives the same bytes (an earlier
|
||||
* twin would have been accepted first).
|
||||
*/
|
||||
async function chosenIndex(
|
||||
input: Uint8Array,
|
||||
candidates: EmbeddedFileCandidate[],
|
||||
kept: Uint8Array,
|
||||
): Promise<number> {
|
||||
if (kept.buffer === input.buffer) {
|
||||
const offset = kept.byteOffset - input.byteOffset
|
||||
return candidates.findIndex(
|
||||
(c) =>
|
||||
c.filter === null &&
|
||||
c.offset === offset &&
|
||||
c.length === kept.byteLength,
|
||||
)
|
||||
}
|
||||
const keptSha = sha256(kept)
|
||||
for (const [index, c] of candidates.entries()) {
|
||||
if (c.filter === null) continue
|
||||
const out = await inflateFlate(
|
||||
input.subarray(c.offset, c.offset + c.length),
|
||||
)
|
||||
if (out !== null && sha256(out) === keptSha) return index
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
async function locatedOutcome(
|
||||
input: Uint8Array,
|
||||
candidates: EmbeddedFileCandidate[],
|
||||
located: LocatedAttachment,
|
||||
): Promise<Outcome> {
|
||||
const index = await chosenIndex(input, candidates, located.bytes)
|
||||
expect(index, 'chosen candidate').toBeGreaterThanOrEqual(0)
|
||||
const chosen = candidates[index]!
|
||||
return {
|
||||
ok: true,
|
||||
candidate: index,
|
||||
name: chosen.name,
|
||||
dataOffset: chosen.offset,
|
||||
bytesLength: located.bytes.byteLength,
|
||||
bytesSha256: sha256(located.bytes),
|
||||
objectSha256: objectSha(located.data),
|
||||
}
|
||||
}
|
||||
|
||||
const archiveOutcome = (outcome: ArchiveReadOutcome): Outcome => ({
|
||||
ok: true,
|
||||
origin: outcome.origin,
|
||||
migrated: outcome.migrated,
|
||||
unresolvedZones: outcome.unresolvedZones,
|
||||
unresolvedFindings: outcome.unresolvedFindings,
|
||||
snapshotRejected: outcome.snapshotRejected ?? null,
|
||||
reportSha256: objectSha(outcome.report),
|
||||
archiveSha256: outcome.archive === null ? null : objectSha(outcome.archive),
|
||||
})
|
||||
|
||||
const exercised = (spec: InputSpec, name: string) =>
|
||||
spec.cases.some((c) => c.exercises.some((f) => f === name))
|
||||
|
||||
async function readerOutcomes(
|
||||
ctx: ReaderContext,
|
||||
spec: InputSpec,
|
||||
input: Uint8Array,
|
||||
): Promise<Outcome> {
|
||||
const candidates = findEmbeddedFiles(input)
|
||||
const located = (l: LocatedAttachment) => locatedOutcome(input, candidates, l)
|
||||
const outcomes: Outcome = {
|
||||
findEmbeddedFiles: candidates.map(({ name, offset, length, filter }) => ({
|
||||
name,
|
||||
offset,
|
||||
length,
|
||||
filter,
|
||||
})),
|
||||
hasArchiveStamp: hasArchiveStamp(input),
|
||||
locateAttachment: await outcomeOf(() => locateAttachment(input), located),
|
||||
readAttachedDocument: await outcomeOf(
|
||||
() => readAttachedDocument(input),
|
||||
async (data) => {
|
||||
const again = await locateAttachment(input)
|
||||
expect(objectSha(again.data)).toBe(objectSha(data))
|
||||
return located(again)
|
||||
},
|
||||
),
|
||||
}
|
||||
if (exercised(spec, 'readAttachmentBytes')) {
|
||||
outcomes.readAttachmentBytes = await outcomeOf(
|
||||
() => readAttachmentBytes(input),
|
||||
(bytes) => ({
|
||||
ok: true,
|
||||
bytesLength: bytes.byteLength,
|
||||
bytesSha256: sha256(bytes),
|
||||
}),
|
||||
)
|
||||
}
|
||||
outcomes.readReportArchive = await outcomeOf(
|
||||
() => readReportArchive(input, ctx.golden.draft.migrationMap),
|
||||
archiveOutcome,
|
||||
)
|
||||
return outcomes
|
||||
}
|
||||
|
||||
async function flateOutcomes(spec: InputSpec, input: Uint8Array) {
|
||||
const runs = []
|
||||
for (const limit of spec.limits ?? [MAX_ATTACHMENT_BYTES]) {
|
||||
runs.push({ limit, verdict: await inflateVerdict(input, limit) })
|
||||
}
|
||||
return { inflateFlate: runs }
|
||||
}
|
||||
|
||||
/** The demo attachment object, referenced by the descriptions that embed it. */
|
||||
function sliceRefs(ctx: ReaderContext): SliceRef[] {
|
||||
const pdf = ctx.exported.pdf
|
||||
const span = objectSpan(pdf, '/Type /EmbeddedFile')
|
||||
const bytes = pdf.slice(span.start, span.end)
|
||||
return [{ file: DEMO_EXPORT_FILE, ...span, bytes }]
|
||||
}
|
||||
|
||||
const extensionOf = (spec: InputSpec, bytes: Uint8Array) =>
|
||||
spec.kind === 'pdf' && hasPdfHeader(bytes) ? '.pdf' : '.bin'
|
||||
|
||||
/** Builds, stores and reads every input; identical inputs of the same kind are stored once. */
|
||||
async function buildEntries(ctx: ReaderContext): Promise<Entry[]> {
|
||||
const entries = new Map<string, Entry>()
|
||||
const refs = sliceRefs(ctx)
|
||||
for (const spec of [...SUITE_INPUTS, ...SEMANTIC_INPUTS]) {
|
||||
const bytes = await spec.build(ctx)
|
||||
const key = `${spec.kind}:${sha256(bytes)}`
|
||||
const known = entries.get(key)
|
||||
if (known) {
|
||||
expect(spec.limits, spec.slug).toBeUndefined()
|
||||
known.cases.push(...spec.cases)
|
||||
continue
|
||||
}
|
||||
const name = { slug: spec.slug, ext: extensionOf(spec, bytes) }
|
||||
const stored = storeInput(INPUTS_DIR, name, bytes, refs)
|
||||
const outcomes =
|
||||
spec.kind === 'pdf'
|
||||
? await readerOutcomes(ctx, spec, bytes)
|
||||
: await flateOutcomes(spec, bytes)
|
||||
entries.set(key, {
|
||||
...stored,
|
||||
kind: spec.kind,
|
||||
cases: [...spec.cases],
|
||||
outcomes,
|
||||
})
|
||||
}
|
||||
return [...entries.values()]
|
||||
}
|
||||
|
||||
const CONVENTIONS = {
|
||||
inputs:
|
||||
'file under inputsDir; stored "bytes" as is, "generator" as <slug>.gen.json whose parts concatenate in order (latin1: one byte per character; fill: the byte value repeated count times; slice: bytes [start, end) of another file of inputsDir) into length bytes of digest sha256',
|
||||
kind: 'pdf: every reader function below is run on the file; flate: inflateFlate only',
|
||||
cases:
|
||||
'the TypeScript cases (vitest full title) that build this input and the reader functions they call on it; identical inputs are stored once',
|
||||
findEmbeddedFiles:
|
||||
'candidates in returned order: name, offset (first data byte), length (stored bytes), filter',
|
||||
locateAttachment:
|
||||
'{ ok: true, candidate (index in findEmbeddedFiles), name, dataOffset, bytesLength, bytesSha256 (stored or inflated bytes), objectSha256 (sha256 of JSON.stringify of the parsed value) } or { ok: false, kind }',
|
||||
readAttachedDocument:
|
||||
'the same shapes, after the size cap and the %PDF- header check',
|
||||
readAttachmentBytes:
|
||||
'only where a case calls it: { ok: true, bytesLength, bytesSha256 } or { ok: false, kind }',
|
||||
readReportArchive:
|
||||
'on the draft migration map: { ok: true, origin, migrated, unresolvedZones, unresolvedFindings, snapshotRejected, reportSha256, archiveSha256 } (sha256 of JSON.stringify) or { ok: false, kind, foundVersion when present }',
|
||||
inflateFlate: 'per limit: verdict null, or { length, sha256 } of the output',
|
||||
decodePdfString:
|
||||
'token as a Latin-1 string (one character per byte); result string or null',
|
||||
}
|
||||
|
||||
function oracleOf(entries: Entry[]) {
|
||||
return {
|
||||
oracle: 'O7',
|
||||
plan: '.claude/tasks/plans/2026-10-17-rust-r4-pdf-core.md §B.1.2, §B.5.1',
|
||||
generator: 'packages/pdf/tests/r4.reader-oracles.test.ts',
|
||||
generatedWith: generatedWith(),
|
||||
inputsDir: 'apps/app/tests/fixtures/pdf/r4/read',
|
||||
constants: { MAX_PDF_BYTES, MAX_ATTACHMENT_BYTES },
|
||||
conventions: CONVENTIONS,
|
||||
inputs: entries,
|
||||
decodePdfString: TOKEN_CASES.map((t) => ({
|
||||
...t,
|
||||
result: decodePdfString(t.token),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
type Oracle = ReturnType<typeof oracleOf>
|
||||
|
||||
/** Per-input comparison first: a failure names the input instead of diffing the whole oracle. */
|
||||
function expectSameEntries(entries: Entry[]): void {
|
||||
const committed = readJsonFile<Oracle>(OUT)
|
||||
const byFile = new Map(committed.inputs.map((e) => [e.file, e]))
|
||||
for (const entry of entries) {
|
||||
expect(byFile.get(entry.file), entry.file).toEqual(
|
||||
JSON.parse(JSON.stringify(entry)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] })
|
||||
vi.setSystemTime(FIXED_EXPORTED_AT)
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('R4 reader oracles O7 (TypeScript freeze)', () => {
|
||||
it('matches the frozen inputs and reader outcomes', async () => {
|
||||
const entries = await buildEntries(await readerContext())
|
||||
const bytes = entries.reduce((n, e) => n + e.length, 0)
|
||||
console.log(`[O7] ${entries.length} inputs, ${bytes} bytes expanded`)
|
||||
if (!MAKE) expectSameEntries(entries)
|
||||
storeJson(OUT, oracleOf(entries), (committed) => ({
|
||||
...(committed as Oracle),
|
||||
generatedWith: generatedWith(),
|
||||
}))
|
||||
expectOnlyFiles(
|
||||
INPUTS_DIR,
|
||||
entries.map((e) => e.file),
|
||||
)
|
||||
}, 600_000)
|
||||
})
|
||||
@@ -1,875 +0,0 @@
|
||||
/**
|
||||
* R4.1 freeze O4 (plan 2026-10-17 §B.5.1): the text and number rules the
|
||||
* Rust writer reproduces, computed with the TypeScript engine and pdf-lib
|
||||
* 1.17.1. `afm.json`: the metrics and the WinAnsi table pdf-lib measures
|
||||
* with (`@pdf-lib/standard-fonts`). `text.json`: `measure` over a corpus ×
|
||||
* the three fonts × eight sizes, `wrapLines`, `safeText` over every code
|
||||
* point, `toUpperCase`, JS `\s` and `trim`, `Math.round`, pdf-lib's
|
||||
* `numberToString` and `rasterSizeOf`. `MAKE_R4_ORACLES=1` writes
|
||||
* `crates/core/tests/oracles/r4/{afm,text}.json`.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { beforeAll, describe, expect, it } from 'vitest'
|
||||
import { Encodings, Font, FontNames } from '@pdf-lib/standard-fonts'
|
||||
import {
|
||||
numberToString,
|
||||
PageSizes,
|
||||
PDFDocument,
|
||||
StandardFontEmbedder,
|
||||
type PDFFont,
|
||||
} from 'pdf-lib'
|
||||
import type { Observation } from '@faunosteo/domain'
|
||||
import { defaultPdfLabels } from '../src'
|
||||
import { embedFonts } from '../src/render/fonts'
|
||||
import { measure, wrapLines } from '../src/render/text'
|
||||
import { rasterSizeOf, renderHighlightedView } from '../src/svg/view'
|
||||
import { safeText } from '../src/text'
|
||||
import { DRAFT_DIR, loadDraftSheet } from './helpers/draft'
|
||||
import {
|
||||
charOf,
|
||||
classRanges,
|
||||
codePointRanges,
|
||||
environment,
|
||||
freezeJson,
|
||||
isSurrogate,
|
||||
jsNumber,
|
||||
MAX_CODE_POINT,
|
||||
mulberry32,
|
||||
} from './helpers/r4-oracle-io'
|
||||
import {
|
||||
loadGoldenReports,
|
||||
REPORT_NAMES,
|
||||
type GoldenReports,
|
||||
} from './helpers/reports'
|
||||
|
||||
/** The fonts `embedFonts` embeds, in its order: bodyRegular, bodyBold, headingRegular. */
|
||||
const FONT_NAMES = [
|
||||
FontNames.Helvetica,
|
||||
FontNames.HelveticaBold,
|
||||
FontNames.TimesRoman,
|
||||
]
|
||||
const SIZES = [8, 9, 10, 11, 14, 22, 9.5, 13.333333333333334]
|
||||
const SEED = 0x52344f34
|
||||
const RANDOM_WINANSI = 500
|
||||
const RANDOM_UNICODE = 200
|
||||
|
||||
let fonts: PDFFont[]
|
||||
let golden: GoldenReports
|
||||
beforeAll(async () => {
|
||||
const embedded = await embedFonts(await PDFDocument.create())
|
||||
fonts = [embedded.bodyRegular, embedded.bodyBold, embedded.headingRegular]
|
||||
golden = loadGoldenReports()
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// afm.json
|
||||
|
||||
/**
|
||||
* StandardFontEmbedder of pdf-lib 1.17.1 (es build; the cjs build vitest loads
|
||||
* differs only by the `utils_1.` prefix), quoted for the port.
|
||||
*/
|
||||
const EMBEDDER_SOURCE = [
|
||||
'StandardFontEmbedder.prototype.widthOfTextAtSize = function (text, size) {',
|
||||
' var glyphs = this.encodeTextAsGlyphs(text);',
|
||||
' var totalWidth = 0;',
|
||||
' for (var idx = 0, len = glyphs.length; idx < len; idx++) {',
|
||||
' var left = glyphs[idx].name;',
|
||||
' var right = (glyphs[idx + 1] || {}).name;',
|
||||
' var kernAmount = this.font.getXAxisKerningForPair(left, right) || 0;',
|
||||
' totalWidth += this.widthOfGlyph(left) + kernAmount;',
|
||||
' }',
|
||||
' var scale = size / 1000;',
|
||||
' return totalWidth * scale;',
|
||||
'};',
|
||||
'StandardFontEmbedder.prototype.widthOfGlyph = function (glyphName) {',
|
||||
" // Default to 250 if font doesn't specify a width",
|
||||
' return this.font.getWidthOfGlyph(glyphName) || 250;',
|
||||
'};',
|
||||
'StandardFontEmbedder.prototype.encodeTextAsGlyphs = function (text) {',
|
||||
' var codePoints = Array.from(text);',
|
||||
' var glyphs = new Array(codePoints.length);',
|
||||
' for (var idx = 0, len = codePoints.length; idx < len; idx++) {',
|
||||
' var codePoint = toCodePoint(codePoints[idx]);',
|
||||
' glyphs[idx] = this.encoding.encodeUnicodeCodePoint(codePoint);',
|
||||
' }',
|
||||
' return glyphs;',
|
||||
'};',
|
||||
]
|
||||
|
||||
/** @pdf-lib/standard-fonts 1.0.0 Font.js, the two lookups the embedder calls. */
|
||||
const FONT_SOURCE = [
|
||||
'this.getWidthOfGlyph = function (glyphName) {',
|
||||
' return _this.CharWidths[glyphName];',
|
||||
'};',
|
||||
'this.getXAxisKerningForPair = function (leftGlyphName, rightGlyphName) {',
|
||||
' return (_this.KernPairXAmounts[leftGlyphName] || {})[rightGlyphName];',
|
||||
'};',
|
||||
'// CharWidths: CharMetrics reduced name -> WX; KernPairXAmounts: KernPairs reduced',
|
||||
'// left -> right -> amount (a later duplicate would win; the three fonts have none).',
|
||||
]
|
||||
|
||||
const normalised = (code: string): string =>
|
||||
code.replace(/\b\w+_\d+\./g, '').replace(/\s+/g, ' ')
|
||||
|
||||
/** Every quoted body line, whitespace-normalised, is in the installed code. */
|
||||
function assertQuoted(quote: string[], installed: string): void {
|
||||
const code = normalised(installed)
|
||||
for (const line of quote.filter(
|
||||
(l) => l.startsWith(' ') && !l.includes('//'),
|
||||
)) {
|
||||
expect(code, line).toContain(normalised(line.trim()))
|
||||
}
|
||||
}
|
||||
|
||||
function assertQuoteMatchesInstalled(): void {
|
||||
const proto = StandardFontEmbedder.prototype as unknown as Record<
|
||||
string,
|
||||
() => void
|
||||
>
|
||||
const methods = ['widthOfTextAtSize', 'widthOfGlyph', 'encodeTextAsGlyphs']
|
||||
assertQuoted(
|
||||
EMBEDDER_SOURCE,
|
||||
methods.map((name) => proto[name]!.toString()).join('\n'),
|
||||
)
|
||||
const font = Font.load(FontNames.Helvetica)
|
||||
const lookups = [font.getWidthOfGlyph, font.getXAxisKerningForPair]
|
||||
assertQuoted(FONT_SOURCE, lookups.map((fn) => fn.toString()).join('\n'))
|
||||
}
|
||||
|
||||
type WinAnsiRow = [number, number, string]
|
||||
|
||||
/** `Encodings.WinAnsi`: code point → [byte code, glyph name], code point order. */
|
||||
function winAnsiTable(): WinAnsiRow[] {
|
||||
const encoding = Encodings.WinAnsi
|
||||
return encoding.supportedCodePoints.map((cp) => {
|
||||
const { code, name } = encoding.encodeUnicodeCodePoint(cp)
|
||||
return [cp, code, name]
|
||||
})
|
||||
}
|
||||
|
||||
function fontMetrics(fontName: FontNames, table: WinAnsiRow[]) {
|
||||
const font = Font.load(fontName)
|
||||
const glyphs: Record<string, [number, number[]]> = {}
|
||||
for (const { N, WX } of font.CharMetrics) {
|
||||
const codes = table
|
||||
.filter(([, , name]) => name === N)
|
||||
.map(([, code]) => code)
|
||||
glyphs[N] = [WX, [...new Set(codes)].sort((a, b) => a - b)]
|
||||
}
|
||||
const kerning: Record<string, Record<string, number>> = {}
|
||||
for (const [left, right, amount] of font.KernPairs) {
|
||||
kerning[left] = { ...kerning[left], [right]: amount }
|
||||
}
|
||||
/** The AFM header fields: every own value that is neither a table nor a method. */
|
||||
const scalars = Object.fromEntries(
|
||||
Object.entries(font).filter(
|
||||
([, value]) => typeof value !== 'function' && typeof value !== 'object',
|
||||
),
|
||||
)
|
||||
return {
|
||||
...scalars,
|
||||
FontBBox: font.FontBBox,
|
||||
charMetricsCount: font.CharMetrics.length,
|
||||
kernPairsCount: font.KernPairs.length,
|
||||
winAnsiGlyphsWithoutWidth: [
|
||||
...new Set(table.map(([, , name]) => name)),
|
||||
].filter((name) => font.getWidthOfGlyph(name) === undefined),
|
||||
glyphs,
|
||||
kerning,
|
||||
}
|
||||
}
|
||||
|
||||
function buildAfm() {
|
||||
assertQuoteMatchesInstalled()
|
||||
const table = winAnsiTable()
|
||||
return {
|
||||
comment: [
|
||||
'O4 metrics: what pdf-lib 1.17.1 measures with (@pdf-lib/standard-fonts 1.0.0, Font.load).',
|
||||
'glyphs: name -> [WX, WinAnsi byte codes that print this glyph]; no AFM C field is kept by',
|
||||
'the package. kerning: left -> right -> KPX amount, every pair of the font. winAnsi: code',
|
||||
'point -> [byte code, glyph name] for every code point Encodings.WinAnsi can encode (note',
|
||||
'376 U+0178 -> [159, "ydieresis"], 160 -> "space", 173 -> "hyphen", as pdf-lib has them).',
|
||||
'Width of a string: sum over its glyphs of (WX || 250) + (KPX(left, next) || 0), times',
|
||||
'size / 1000 (measuredWith below). The fonts carry no APAFML notice in this package:',
|
||||
'Notice/Comment are the AFM header fields as pdf-lib stores them.',
|
||||
],
|
||||
measuredWith: [...EMBEDDER_SOURCE, ...FONT_SOURCE],
|
||||
environment: environment(),
|
||||
fonts: Object.fromEntries(
|
||||
FONT_NAMES.map((name) => [name, fontMetrics(name, table)]),
|
||||
),
|
||||
winAnsi: table,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// text.json: measure
|
||||
|
||||
/** Every `{ fr, en }` label found under a `name` key of the draft document. */
|
||||
function sheetNames(): string[] {
|
||||
const out: string[] = []
|
||||
const walk = (value: unknown, key: string): void => {
|
||||
if (Array.isArray(value)) return value.forEach((item) => walk(item, key))
|
||||
if (!value || typeof value !== 'object') return
|
||||
const record = value as Record<string, unknown>
|
||||
if (
|
||||
key === 'name' &&
|
||||
typeof record.fr === 'string' &&
|
||||
typeof record.en === 'string'
|
||||
) {
|
||||
out.push(record.fr, record.en)
|
||||
return
|
||||
}
|
||||
for (const [k, v] of Object.entries(record)) walk(v, k)
|
||||
}
|
||||
walk(loadDraftSheet().document, '')
|
||||
return out
|
||||
}
|
||||
|
||||
function stringLeaves(value: unknown): string[] {
|
||||
if (typeof value === 'string') return [value]
|
||||
if (Array.isArray(value)) return value.flatMap(stringLeaves)
|
||||
if (value && typeof value === 'object')
|
||||
return Object.values(value).flatMap(stringLeaves)
|
||||
return []
|
||||
}
|
||||
|
||||
const pdfLabelTexts = (): string[] => [
|
||||
...Object.values(defaultPdfLabels.fr),
|
||||
...Object.values(defaultPdfLabels.en),
|
||||
]
|
||||
|
||||
function randomText(
|
||||
rng: () => number,
|
||||
alphabet: number[],
|
||||
maxLength: number,
|
||||
): string {
|
||||
const length = 1 + Math.floor(rng() * maxLength)
|
||||
return Array.from({ length }, () =>
|
||||
String.fromCodePoint(alphabet[Math.floor(rng() * alphabet.length)]!),
|
||||
).join('')
|
||||
}
|
||||
|
||||
/** A scalar value (never a surrogate) from one of four bands: ASCII, 2-byte, BMP, astral. */
|
||||
function randomScalar(rng: () => number): number {
|
||||
const bands: Array<[number, number]> = [
|
||||
[0, 0x7f],
|
||||
[0x80, 0x7ff],
|
||||
[0x800, 0xffff],
|
||||
[0x10000, MAX_CODE_POINT],
|
||||
]
|
||||
const [low, high] = bands[Math.floor(rng() * bands.length)]!
|
||||
for (;;) {
|
||||
const cp = low + Math.floor(rng() * (high - low + 1))
|
||||
if (!isSurrogate(cp)) return cp
|
||||
}
|
||||
}
|
||||
|
||||
function randomUnicodeText(rng: () => number): string {
|
||||
const length = 1 + Math.floor(rng() * 16)
|
||||
return Array.from({ length }, () =>
|
||||
String.fromCodePoint(randomScalar(rng)),
|
||||
).join('')
|
||||
}
|
||||
|
||||
interface CorpusGroups {
|
||||
sheetNames: string[]
|
||||
pdfLabels: string[]
|
||||
reports: string[]
|
||||
randomWinAnsi: string[]
|
||||
randomUnicode: string[]
|
||||
}
|
||||
|
||||
/** Each fixed text and its upper-case form; a text already seen in an earlier group is not repeated. */
|
||||
function corpus(): CorpusGroups {
|
||||
const seen = new Set<string>()
|
||||
const fresh = (texts: string[]) =>
|
||||
texts.filter((text) => !seen.has(text) && seen.add(text))
|
||||
const withUpper = (texts: string[]) =>
|
||||
fresh(texts.flatMap((text) => [text, text.toUpperCase()]))
|
||||
const rng = mulberry32(SEED)
|
||||
const winAnsi = Encodings.WinAnsi.supportedCodePoints
|
||||
return {
|
||||
sheetNames: withUpper(sheetNames()),
|
||||
pdfLabels: withUpper(pdfLabelTexts()),
|
||||
reports: withUpper(
|
||||
REPORT_NAMES.flatMap((name) => stringLeaves(golden.reports[name])),
|
||||
),
|
||||
randomWinAnsi: Array.from({ length: RANDOM_WINANSI }, () =>
|
||||
randomText(rng, winAnsi, 40),
|
||||
),
|
||||
randomUnicode: Array.from({ length: RANDOM_UNICODE }, () =>
|
||||
randomUnicodeText(rng),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/** The width rule of StandardFontEmbedder, as the Rust port must write it. */
|
||||
const WIDTH_FORMULA = 'units * (size / 1000)'
|
||||
const SAMPLE_HEAD = 100
|
||||
const SAMPLE_DRAWN = 100
|
||||
const SAMPLE_SEED = SEED + 2
|
||||
|
||||
/** Flat row indices that keep their widths: the first 100, then 100 distinct others drawn by the PRNG. */
|
||||
function widthSample(total: number): number[] {
|
||||
const rng = mulberry32(SAMPLE_SEED)
|
||||
const head = Math.min(SAMPLE_HEAD, total)
|
||||
const picked = new Set(Array.from({ length: head }, (_, i) => i))
|
||||
const target = Math.min(total, SAMPLE_HEAD + SAMPLE_DRAWN)
|
||||
while (picked.size < target) {
|
||||
picked.add(SAMPLE_HEAD + Math.floor(rng() * (total - SAMPLE_HEAD)))
|
||||
}
|
||||
return [...picked].sort((a, b) => a - b)
|
||||
}
|
||||
|
||||
interface MeasureRow {
|
||||
text: string
|
||||
safe: string
|
||||
units: number[]
|
||||
widths?: number[][]
|
||||
}
|
||||
|
||||
/**
|
||||
* One text: its safeText form and the raw unit sum per font (size 1000).
|
||||
* Every font × size is checked against the formula; the widths are kept
|
||||
* for sampled rows only.
|
||||
*/
|
||||
function measureRow(text: string, keepWidths: boolean): MeasureRow {
|
||||
const safe = safeText(text)
|
||||
const units = fonts.map((font) => font.widthOfTextAtSize(safe, 1000))
|
||||
const widths = fonts.map((font, f) =>
|
||||
SIZES.map((size) => {
|
||||
const width = measure(font, text, size)
|
||||
expect(width).toBe(units[f]! * (size / 1000))
|
||||
expect(width).toBe(font.widthOfTextAtSize(safe, size))
|
||||
return width
|
||||
}),
|
||||
)
|
||||
return keepWidths ? { text, safe, units, widths } : { text, safe, units }
|
||||
}
|
||||
|
||||
function measureGroups(groups: CorpusGroups, sample: Set<number>) {
|
||||
const rows: Record<string, MeasureRow[]> = {}
|
||||
let offset = 0
|
||||
for (const [name, texts] of Object.entries(groups) as Array<
|
||||
[string, string[]]
|
||||
>) {
|
||||
rows[name] = texts.map((text, i) =>
|
||||
measureRow(text, sample.has(offset + i)),
|
||||
)
|
||||
offset += texts.length
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
function buildMeasure() {
|
||||
const groups = corpus()
|
||||
const total = Object.values(groups).reduce((n, texts) => n + texts.length, 0)
|
||||
const sample = widthSample(total)
|
||||
return {
|
||||
comment: [
|
||||
'measure(font, text, size) = font.widthOfTextAtSize(safeText(text), size) (render/text.ts).',
|
||||
'units[f] = widthOfTextAtSize(safe, 1000): the raw sum of glyph widths and kerning for',
|
||||
'fonts[f]. The generator asserts, for every row, font and size, measure === widthFormula',
|
||||
'evaluated in JavaScript (f64, this exact expression and order); widths[f][s] (sizes[s]) is',
|
||||
'kept only on the widthSample rows. Fixed groups hold each text and its toUpperCase(); a',
|
||||
'text is listed once, in the first group that has it. Random groups use mulberry32(seed):',
|
||||
'randomWinAnsi draws 1-40 code points of Encodings.WinAnsi, randomUnicode 1-16 scalar',
|
||||
'values from four bands (ASCII, 2-byte, rest of the BMP, astral), no surrogate.',
|
||||
],
|
||||
fonts: fonts.map((font) => font.name),
|
||||
sizes: SIZES,
|
||||
widthFormula: WIDTH_FORMULA,
|
||||
seed: SEED,
|
||||
counts: Object.fromEntries(
|
||||
Object.entries(groups).map(([k, v]) => [k, (v as string[]).length]),
|
||||
),
|
||||
widthSample: {
|
||||
rule: [
|
||||
'Rows indexed in file order across the groups (sheetNames, pdfLabels, reports,',
|
||||
`randomWinAnsi, randomUnicode), from 0. Kept: indices 0..${SAMPLE_HEAD - 1}, then`,
|
||||
`${SAMPLE_DRAWN} distinct indices drawn as ${SAMPLE_HEAD} + floor(rng() * (total - ${SAMPLE_HEAD}))`,
|
||||
'with rng = mulberry32(seed), a repeat drawn again; listed ascending.',
|
||||
],
|
||||
seed: SAMPLE_SEED,
|
||||
total,
|
||||
indices: sample,
|
||||
},
|
||||
groups: measureGroups(groups, new Set(sample)),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// text.json: wrapLines
|
||||
|
||||
/** `width - MARGIN_X * 2` on A4, the only maxWidth the observation and conclusion pages pass. */
|
||||
const LAYOUT_MAX_WIDTH = PageSizes.A4[0] - 36 * 2
|
||||
const WRAP_WIDTHS = [LAYOUT_MAX_WIDTH, 0, 1, 50, 100, 200, 300, 1000]
|
||||
/** wrapLines is only called with bodyRegular: size 10 (observation sections), 11 (conclusion). */
|
||||
const WRAP_SIZES = [10, 11]
|
||||
|
||||
function reportLongTexts(): string[] {
|
||||
return REPORT_NAMES.flatMap((name) => {
|
||||
const report = golden.reports[name]
|
||||
const next = report.nextAppointment
|
||||
return [
|
||||
report.conclusion,
|
||||
report.recommendations,
|
||||
next && next.kind === 'period' ? next.text : '',
|
||||
...report.observations.flatMap((o) => [
|
||||
o.comment,
|
||||
o.comment.trim(),
|
||||
...o.freeTextFindings,
|
||||
]),
|
||||
...report.observations.map((o) => o.freeTextFindings.join(' · ')),
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
function edgeWrapTexts(): string[] {
|
||||
const document = loadDraftSheet().document
|
||||
const vocabulary = sheetNames()
|
||||
.filter((_, i) => i % 2 === 0)
|
||||
.slice(0, 60)
|
||||
return [
|
||||
document.scope_disclaimer.fr ?? '',
|
||||
document.scope_disclaimer.en ?? '',
|
||||
vocabulary.join(' '),
|
||||
'',
|
||||
' ',
|
||||
'\t\n',
|
||||
' leading and trailing ',
|
||||
'a\u00a0b\u2028c\ufeffd\u3000e\u1680f\u205fg',
|
||||
'word\u200bjoined by a zero width space',
|
||||
'x\u0007y z',
|
||||
'\u0007 \u0007 word \u0007',
|
||||
'Supercalifragilisticexpialidocious'.repeat(3),
|
||||
'short Supercalifragilisticexpialidociouscalifragilistic tail',
|
||||
'emoji 😀 and CJK 漢字 and ☃ and → arrows',
|
||||
'Œuvre « guillemets » – tiret — long … points € ‰ ™',
|
||||
]
|
||||
}
|
||||
|
||||
function buildWrap() {
|
||||
const seen = new Set<string>()
|
||||
const texts = [
|
||||
...reportLongTexts(),
|
||||
...pdfLabelTexts(),
|
||||
...edgeWrapTexts(),
|
||||
].filter((text) => !seen.has(text) && seen.add(text))
|
||||
const font = fonts[0]!
|
||||
return {
|
||||
comment: [
|
||||
'wrapLines(text, font, size, maxWidth) (render/text.ts): split on JS /\\s+/, safeText per',
|
||||
'word, greedy join with one space. lines[s][w] for sizes[s] and maxWidths[w]; maxWidths[0]',
|
||||
'is the layout value A4 width - 36 * 2 as JavaScript computes it.',
|
||||
],
|
||||
font: font.name,
|
||||
sizes: WRAP_SIZES,
|
||||
maxWidths: WRAP_WIDTHS,
|
||||
cases: texts.map((text) => ({
|
||||
text,
|
||||
lines: WRAP_SIZES.map((size) =>
|
||||
WRAP_WIDTHS.map((max) => wrapLines(text, font, size, max)),
|
||||
),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// text.json: code point tables
|
||||
|
||||
type SafeClass = 'kept' | 'dropped' | 'question'
|
||||
|
||||
function safeClassOf(cp: number): SafeClass {
|
||||
const char = charOf(cp)
|
||||
const out = safeText(char)
|
||||
if (out === char) return 'kept'
|
||||
if (out === '') return 'dropped'
|
||||
if (out === '?') return 'question'
|
||||
throw new Error(`safeText(${cp}) gave ${JSON.stringify(out)}`)
|
||||
}
|
||||
|
||||
type UpperRun = [number, number, number, number]
|
||||
|
||||
/** Single-code-point mappings as runs [start, end, step, delta]: start, start + step, … end map to cp + delta. */
|
||||
function upperRuns(single: Array<[number, number]>): UpperRun[] {
|
||||
const runs: UpperRun[] = []
|
||||
for (const [cp, mapped] of single) {
|
||||
const delta = mapped - cp
|
||||
const last = runs.at(-1)
|
||||
const step = last ? cp - last[1] : 0
|
||||
const joins =
|
||||
last &&
|
||||
last[3] === delta &&
|
||||
(last[0] === last[1] ? step <= 2 : step === last[2])
|
||||
if (last && joins) {
|
||||
last[2] = step
|
||||
last[1] = cp
|
||||
} else runs.push([cp, cp, 1, delta])
|
||||
}
|
||||
return runs
|
||||
}
|
||||
|
||||
function expandRuns(runs: UpperRun[]): Array<[number, number]> {
|
||||
return runs.flatMap(([start, end, step, delta]) => {
|
||||
const out: Array<[number, number]> = []
|
||||
for (let cp = start; cp <= end; cp += step) out.push([cp, cp + delta])
|
||||
return out
|
||||
})
|
||||
}
|
||||
|
||||
function buildUpper() {
|
||||
const single: Array<[number, number]> = []
|
||||
const special: Array<[number, number[]]> = []
|
||||
for (let cp = 0; cp <= MAX_CODE_POINT; cp += 1) {
|
||||
if (isSurrogate(cp)) continue
|
||||
const char = String.fromCodePoint(cp)
|
||||
const upper = char.toUpperCase()
|
||||
if (upper === char) continue
|
||||
const mapped = Array.from(upper, (c) => c.codePointAt(0)!)
|
||||
if (mapped.length === 1) single.push([cp, mapped[0]!])
|
||||
else special.push([cp, mapped])
|
||||
}
|
||||
const runs = upperRuns(single)
|
||||
expect(expandRuns(runs)).toEqual(single)
|
||||
return {
|
||||
comment: [
|
||||
'String.fromCodePoint(cp).toUpperCase() for every non-surrogate code point where it differs.',
|
||||
'runs: [start, end, step, delta]: start, start + step, ... end each map to cp + delta (one',
|
||||
'code point). special: [cp, result code points] when the result is not one code point.',
|
||||
'Any other code point maps to itself.',
|
||||
],
|
||||
singleCount: single.length,
|
||||
runs,
|
||||
special,
|
||||
}
|
||||
}
|
||||
|
||||
const isJsWhitespace = (cp: number): boolean =>
|
||||
!isSurrogate(cp) && /\s/.test(String.fromCodePoint(cp))
|
||||
const isJsTrimmed = (cp: number): boolean =>
|
||||
!isSurrogate(cp) && `${String.fromCodePoint(cp)}a`.trim() === 'a'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// text.json: numbers
|
||||
|
||||
const HALF_TIES = [
|
||||
0.5, -0.5, 1.5, -1.5, 2.5, -2.5, 3.5, -3.5, 4.5, 99.5, 1199.5, 2399.5,
|
||||
]
|
||||
const ROUND_EDGES = [
|
||||
0.49999999999999994,
|
||||
-0.49999999999999994,
|
||||
0.5000000000000001,
|
||||
1.4999999999999998,
|
||||
2 ** 52 + 0.5,
|
||||
2 ** 52 - 0.5,
|
||||
-(2 ** 52) + 0.5,
|
||||
2 ** 53,
|
||||
2 ** 53 + 2,
|
||||
1e21,
|
||||
1.7976931348623157e308,
|
||||
5e-324,
|
||||
-5e-324,
|
||||
1e-300,
|
||||
0,
|
||||
-0,
|
||||
0.4,
|
||||
-0.4,
|
||||
0.6,
|
||||
-0.6,
|
||||
100.49999999999999,
|
||||
Infinity,
|
||||
-Infinity,
|
||||
NaN,
|
||||
1200 * 0.2,
|
||||
1200 * 0.6,
|
||||
1200 * 1.2345,
|
||||
1200 * (943 / 1200),
|
||||
1200 * (942.5 / 1200),
|
||||
]
|
||||
|
||||
function mathRoundInputs(rng: () => number): number[] {
|
||||
const random = Array.from({ length: 50 }, () => (rng() - 0.5) * 6000)
|
||||
const halves = Array.from(
|
||||
{ length: 50 },
|
||||
() => Math.floor((rng() - 0.5) * 2e6) + 0.5,
|
||||
)
|
||||
const raster = Array.from({ length: 30 }, () => 1200 * (0.2 + rng() * 1.8))
|
||||
return [...HALF_TIES, ...ROUND_EDGES, ...random, ...halves, ...raster]
|
||||
}
|
||||
|
||||
const LAYOUT_SUMS = [
|
||||
36 + 523.28 / 2,
|
||||
595.28 - 36,
|
||||
841.89 - 95,
|
||||
841.89 - 122,
|
||||
841.89 - 122 - 12,
|
||||
(595.28 - 72 - 16) / 2,
|
||||
(595.28 - 72 - 16) / 2 / 2,
|
||||
595.28 - 36 - 50.5,
|
||||
800 - 12 * 3,
|
||||
(14 - 10) * 0.3,
|
||||
1 - 0.9,
|
||||
0.1 + 0.2,
|
||||
0.1 * 3,
|
||||
523.28 * 0.6,
|
||||
253.64 * 0.7876,
|
||||
841.89 - 48,
|
||||
36 + 253.64 + 16,
|
||||
595.28 / 2 - 50,
|
||||
]
|
||||
const COLOUR_COMPONENTS = [
|
||||
0.12, 0.11, 0.09, 0.42, 0.39, 0.35, 0.72, 0.25, 0.55, 0.65, 0.45, 0.85, 0.18,
|
||||
0.78, 0.2,
|
||||
]
|
||||
const INTEGERS = [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
36,
|
||||
72,
|
||||
595,
|
||||
842,
|
||||
1000,
|
||||
2 ** 31,
|
||||
2 ** 32,
|
||||
2 ** 53,
|
||||
1e15,
|
||||
1e20,
|
||||
123456789,
|
||||
-1,
|
||||
-842,
|
||||
]
|
||||
const TINY_RESIDUES = [
|
||||
0.1 + 0.2 - 0.3,
|
||||
1.0000000000001 - 1,
|
||||
3 * 0.1 - 0.3,
|
||||
523.28 - 523.2799999999999,
|
||||
1e-13,
|
||||
1.5e-13,
|
||||
9.999999999999999e-14,
|
||||
0.30000000000000004 - 0.3,
|
||||
0.000001,
|
||||
0.0000009999999,
|
||||
5e-324,
|
||||
1e-300,
|
||||
2.2250738585072014e-308,
|
||||
-1e-7,
|
||||
-1.5e-13,
|
||||
-(0.1 + 0.2 - 0.3),
|
||||
]
|
||||
const LARGE = [
|
||||
1e21,
|
||||
1.5e21,
|
||||
9.999999999999999e21,
|
||||
1e22,
|
||||
1.2345678901234567e25,
|
||||
2 ** 70,
|
||||
2 ** 100,
|
||||
1e100,
|
||||
1.7976931348623157e308,
|
||||
-1e21,
|
||||
-3.3e25,
|
||||
999999999999999900000,
|
||||
1e21 - 65536,
|
||||
]
|
||||
const SPECIAL_NUMBERS = [NaN, Infinity, -Infinity, -0]
|
||||
|
||||
function numberInputs(rng: () => number): number[] {
|
||||
const n = (count: number, make: () => number) =>
|
||||
Array.from({ length: count }, make)
|
||||
const widths = fonts.map((font) =>
|
||||
measure(font, 'Restriction en flexion', 10),
|
||||
)
|
||||
return [
|
||||
...n(300, () => rng() * 842),
|
||||
...n(150, () => rng()),
|
||||
...n(50, () => -rng() * 842),
|
||||
...n(50, () => -rng()),
|
||||
...INTEGERS,
|
||||
...LAYOUT_SUMS,
|
||||
...COLOUR_COMPONENTS,
|
||||
...widths.flatMap((w) => [595.28 - 36 - w, (595.28 - w) / 2, w + 10]),
|
||||
...n(14, () => 0).map((_, i) => 10 ** -(i + 7)),
|
||||
...n(28, () => (1 + rng() * 9) * 10 ** -(7 + Math.floor(rng() * 14))),
|
||||
...TINY_RESIDUES,
|
||||
...LARGE,
|
||||
...n(20, () => (1 + rng() * 9) * 10 ** (21 + Math.floor(rng() * 280))),
|
||||
...SPECIAL_NUMBERS,
|
||||
]
|
||||
}
|
||||
|
||||
function buildNumbers() {
|
||||
const rng = mulberry32(SEED + 1)
|
||||
return {
|
||||
mathRound: {
|
||||
comment:
|
||||
'Math.round(input): [input, output] as JavaScript prints them, "-0" kept, NaN/Infinity by name.',
|
||||
seed: SEED + 1,
|
||||
cases: mathRoundInputs(rng).map((x) => [
|
||||
jsNumber(x),
|
||||
jsNumber(Math.round(x)),
|
||||
]),
|
||||
},
|
||||
numberToString: {
|
||||
comment: [
|
||||
'pdf-lib 1.17.1 numberToString (utils/numbers.js, as loaded), the operand printer of every',
|
||||
'content stream operator and PDFNumber: [String(input) ("-0" for -0), output]. Source below.',
|
||||
],
|
||||
source: numberToString.toString().split('\n'),
|
||||
seed: SEED + 1,
|
||||
cases: numberInputs(rng).map((x) => [jsNumber(x), numberToString(x)]),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// text.json: rasterSizeOf
|
||||
|
||||
const VIEW_BOXES: Array<string | null> = [
|
||||
null,
|
||||
'',
|
||||
'0 0 100 50',
|
||||
'0 0 1200 943',
|
||||
'0,0,100,50',
|
||||
'0, 0, 100, 50',
|
||||
' 0 0 100 50 ',
|
||||
'\t0\n0\r100\u00a050\ufeff',
|
||||
'0\u20280\u3000100\u205f50',
|
||||
'0 0 0x10 0x20',
|
||||
'0 0 Infinity 50',
|
||||
'0 0 100 Infinity',
|
||||
'0 0 -Infinity 50',
|
||||
'0 0 NaN 50',
|
||||
'0 0 -100 50',
|
||||
'0 0 100 -50',
|
||||
'0 0 0 50',
|
||||
'0 0 100 0',
|
||||
'0 0 -0 50',
|
||||
'0 0 100',
|
||||
'0 0',
|
||||
'0',
|
||||
'0 0 100 50 7',
|
||||
'0 0 100 1000',
|
||||
'0 0 1000 1',
|
||||
'0 0 1e2 5e1',
|
||||
'0 0 1E2 5E1',
|
||||
'0 0 1e999 50',
|
||||
'0 0 100 1e-400',
|
||||
'0 0 5e-324 1',
|
||||
'0 0 .5 .25',
|
||||
'0 0 5. 2.',
|
||||
'0 0 +100 +50',
|
||||
'0 0 0b11 0o7',
|
||||
'0 0 1_000 500',
|
||||
'0 0 100px 50px',
|
||||
',0 0 100 50',
|
||||
'0 0 100 50,',
|
||||
'0 0 100,,50',
|
||||
'a b c d',
|
||||
'-50 -50 100 50',
|
||||
'0 0 100 50.5',
|
||||
'0 0 1200 942.5',
|
||||
'0 0 3 2',
|
||||
'0 0 7 3',
|
||||
'0 0 2400 1885',
|
||||
'0 0 100 20',
|
||||
'0 0 100 200',
|
||||
'0 0 100 19.999',
|
||||
'0 0 100 200.001',
|
||||
'0 0 1 0.6000000000000001',
|
||||
'0 0 100 0x',
|
||||
'0 0 ١٠٠ ٥٠',
|
||||
'0 0 100 50',
|
||||
]
|
||||
|
||||
const VIEW_BOX_ATTRIBUTE = /<svg\b[^>]*\sviewBox="([^"]*)"/
|
||||
|
||||
/** The viewBox of every drawing the draft sheet bundles, as its asset text declares it. */
|
||||
function draftViewBoxes(): string[] {
|
||||
const assets = JSON.parse(
|
||||
readFileSync(resolve(DRAFT_DIR, 'assets.json'), 'utf8'),
|
||||
) as Array<{ file: string }>
|
||||
return assets.flatMap(({ file }) => {
|
||||
const match = VIEW_BOX_ATTRIBUTE.exec(
|
||||
readFileSync(resolve(DRAFT_DIR, 'assets', file), 'utf8'),
|
||||
)
|
||||
return match ? [match[1]!] : []
|
||||
})
|
||||
}
|
||||
|
||||
/** The viewBox `rasterSizeOf` reads for each view of the draft: the composed root's, view framing applied. */
|
||||
function composedViewBoxes(): string[] {
|
||||
const sheet = golden.snapshots.demo
|
||||
const none = {
|
||||
id: 'none',
|
||||
zones: [],
|
||||
findings: [],
|
||||
freeTextFindings: [],
|
||||
comment: '',
|
||||
} as unknown as Observation
|
||||
return sheet.document.views.map((view) => {
|
||||
const { svg } = renderHighlightedView(sheet, view.id, none)
|
||||
return VIEW_BOX_ATTRIBUTE.exec(svg)?.[1] ?? ''
|
||||
})
|
||||
}
|
||||
|
||||
function buildRasterSizes() {
|
||||
return {
|
||||
comment: [
|
||||
'rasterSizeOf(viewBox) (svg/view.ts): [input (null = attribute absent), widthPx, heightPx].',
|
||||
'The last rows are the draft drawing viewBoxes, then the composed view roots (main, head).',
|
||||
],
|
||||
cases: [...VIEW_BOXES, ...draftViewBoxes(), ...composedViewBoxes()].map(
|
||||
(viewBox) => {
|
||||
const { widthPx, heightPx } = rasterSizeOf(viewBox)
|
||||
return [viewBox, widthPx, heightPx]
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
function buildText() {
|
||||
return {
|
||||
comment: [
|
||||
'O4 text and numbers, frozen from the TypeScript engine (packages/pdf) and pdf-lib 1.17.1.',
|
||||
'Code point tables depend on the V8 / ICU / Unicode versions in environment.',
|
||||
],
|
||||
environment: environment(),
|
||||
measure: buildMeasure(),
|
||||
wrapLines: buildWrap(),
|
||||
safeText: {
|
||||
comment: [
|
||||
'safeText(one code point) over 0..0x10FFFF, surrogates as lone single-unit strings:',
|
||||
'[start, end, class]; kept = unchanged, dropped = removed (\\p{Cc}, \\p{Cf}, \\p{Zl}, \\p{Zp}),',
|
||||
'question = replaced by "?" (not WinAnsi-encodable). Ranges are contiguous and cover all.',
|
||||
],
|
||||
ranges: classRanges(safeClassOf),
|
||||
},
|
||||
upper: buildUpper(),
|
||||
jsWhitespace: {
|
||||
comment:
|
||||
'Code points JS /\\s/ matches (non-surrogates), [start, end] ranges.',
|
||||
ranges: codePointRanges(isJsWhitespace),
|
||||
},
|
||||
jsTrim: {
|
||||
comment:
|
||||
'Code points String.prototype.trim removes (non-surrogates), [start, end] ranges.',
|
||||
ranges: codePointRanges(isJsTrimmed),
|
||||
},
|
||||
...buildNumbers(),
|
||||
rasterSizeOf: buildRasterSizes(),
|
||||
}
|
||||
}
|
||||
|
||||
describe('R4 text oracles (TypeScript freeze)', () => {
|
||||
it('matches the frozen AFM metrics and WinAnsi table', () => {
|
||||
freezeJson('afm.json', buildAfm())
|
||||
})
|
||||
|
||||
it('matches the frozen text and number rules', () => {
|
||||
freezeJson('text.json', buildText())
|
||||
}, 120_000)
|
||||
})
|
||||
@@ -1,122 +0,0 @@
|
||||
/**
|
||||
* T10 (STEP6 §7): a real rasterizer (resvg) renders the demo report's main
|
||||
* and head views: 1200 px wide, height from the view box, highlight colour
|
||||
* present, sane non-white ratio. A failing rasterizer degrades to a page
|
||||
* without the image and one warning.
|
||||
*/
|
||||
import { beforeAll, describe, expect, it } from 'vitest'
|
||||
import * as UPNG from '@pdf-lib/upng'
|
||||
import { PDFDocument } from 'pdf-lib'
|
||||
import { buildSheetSnapshot } from '@faunosteo/domain'
|
||||
import {
|
||||
defaultPdfLabels,
|
||||
exportReportArchive,
|
||||
type ExportInput,
|
||||
type Rasterizer,
|
||||
} from '../src'
|
||||
import {
|
||||
FIXED_EXPORTED_AT,
|
||||
nologosBranding,
|
||||
recordDrawing,
|
||||
} from './helpers/goldens'
|
||||
import { loadGoldenReports, type GoldenReports } from './helpers/reports'
|
||||
import { resvgRasterizer, type Raster } from './helpers/resvg'
|
||||
|
||||
const HIGHLIGHT = { r: 0xb8, g: 0x5a, b: 0x3f }
|
||||
const TOLERANCE = 24
|
||||
|
||||
interface PixelFacts {
|
||||
width: number
|
||||
height: number
|
||||
highlightPixels: number
|
||||
nonWhiteRatio: number
|
||||
}
|
||||
|
||||
function pixelFacts(png: Uint8Array): PixelFacts {
|
||||
const buffer = new ArrayBuffer(png.byteLength)
|
||||
new Uint8Array(buffer).set(png)
|
||||
const image = UPNG.decode(buffer)
|
||||
const rgba = new Uint8Array(UPNG.toRGBA8(image)[0]!)
|
||||
let highlightPixels = 0
|
||||
let nonWhite = 0
|
||||
for (let i = 0; i < rgba.length; i += 4) {
|
||||
const [r, g, b] = [rgba[i]!, rgba[i + 1]!, rgba[i + 2]!]
|
||||
if (r < 250 || g < 250 || b < 250) nonWhite += 1
|
||||
if (
|
||||
Math.abs(r - HIGHLIGHT.r) <= TOLERANCE &&
|
||||
Math.abs(g - HIGHLIGHT.g) <= TOLERANCE &&
|
||||
Math.abs(b - HIGHLIGHT.b) <= TOLERANCE
|
||||
) {
|
||||
highlightPixels += 1
|
||||
}
|
||||
}
|
||||
const total = rgba.length / 4
|
||||
return {
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
highlightPixels,
|
||||
nonWhiteRatio: nonWhite / total,
|
||||
}
|
||||
}
|
||||
|
||||
let golden: GoldenReports
|
||||
beforeAll(() => {
|
||||
golden = loadGoldenReports()
|
||||
})
|
||||
|
||||
function inputFor(
|
||||
observations: GoldenReports['reports']['demo']['observations'],
|
||||
rasterizer: Rasterizer,
|
||||
): ExportInput {
|
||||
const report = { ...golden.reports.demo, observations }
|
||||
return {
|
||||
report,
|
||||
sheet: buildSheetSnapshot(golden.draft, report),
|
||||
branding: nologosBranding(),
|
||||
labels: defaultPdfLabels,
|
||||
locale: 'fr',
|
||||
rasterizer,
|
||||
exportedAt: FIXED_EXPORTED_AT,
|
||||
}
|
||||
}
|
||||
|
||||
describe('resvg rasterisation of the demo views', () => {
|
||||
it('main (haloed) and head views: 1200 px wide, highlight present, sane coverage', async () => {
|
||||
const rasters: Raster[] = []
|
||||
const [main, , , head] = golden.reports.demo.observations
|
||||
const { pdf, warnings } = await exportReportArchive(
|
||||
inputFor([main!, head!], resvgRasterizer(rasters)),
|
||||
)
|
||||
expect(warnings).toEqual([])
|
||||
expect(rasters).toHaveLength(2)
|
||||
for (const { requested, png } of rasters) {
|
||||
const facts = pixelFacts(png)
|
||||
expect(facts.width).toBe(1200)
|
||||
expect(Math.abs(facts.height - requested.heightPx)).toBeLessThanOrEqual(1)
|
||||
expect(facts.highlightPixels).toBeGreaterThan(0)
|
||||
expect(facts.nonWhiteRatio).toBeGreaterThanOrEqual(0.01)
|
||||
expect(facts.nonWhiteRatio).toBeLessThanOrEqual(0.9)
|
||||
}
|
||||
// main: 2073.4 × 1629.4 → 943 px; head: 500 × 380 → 912 px
|
||||
expect(rasters.map((r) => r.requested.heightPx)).toEqual([943, 912])
|
||||
expect((await PDFDocument.load(pdf)).getPageCount()).toBe(3)
|
||||
}, 60_000)
|
||||
|
||||
it('a rasterizer that throws: page without image, one view_raster_failed warning', async () => {
|
||||
const [main] = golden.reports.demo.observations
|
||||
const failing: Rasterizer = async () => {
|
||||
throw new Error('no renderer here')
|
||||
}
|
||||
const recording = recordDrawing()
|
||||
try {
|
||||
const { warnings } = await exportReportArchive(inputFor([main!], failing))
|
||||
expect(warnings).toEqual([
|
||||
{ kind: 'view_raster_failed', observationId: main!.id, viewId: 'main' },
|
||||
])
|
||||
expect(recording.images).toEqual([])
|
||||
expect(recording.texts.some((t) => t.text === 'VUE GÉNÉRALE')).toBe(false)
|
||||
} finally {
|
||||
recording.stop()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,183 +0,0 @@
|
||||
/**
|
||||
* T4 T5 T6 (STEP6 §4, §7, §14 "Read"): roundtrip, the frozen v2 PDFs and
|
||||
* the 612-leaf legacy report, the bare v3 fixture, wrapper and report
|
||||
* versions, stripped attachments, attachment selection, size cap.
|
||||
*/
|
||||
import { beforeAll, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildSheetSnapshot,
|
||||
type Report,
|
||||
type ReportArchiveEnvelope,
|
||||
} from '@faunosteo/domain'
|
||||
import {
|
||||
ArchiveReadError,
|
||||
defaultPdfLabels,
|
||||
exportReportArchive,
|
||||
MAX_PDF_BYTES,
|
||||
readReportArchive,
|
||||
type ExportResult,
|
||||
} from '../src'
|
||||
import { readFixtureBytes } from './helpers/draft'
|
||||
import {
|
||||
FIXED_EXPORTED_AT,
|
||||
nologosBranding,
|
||||
rasterizerOf,
|
||||
} from './helpers/goldens'
|
||||
import { pdfWithAttachment, pdfWithoutAttachment } from './helpers/pdf'
|
||||
import {
|
||||
allLeavesMigrated,
|
||||
loadGoldenReports,
|
||||
type GoldenReports,
|
||||
} from './helpers/reports'
|
||||
|
||||
let golden: GoldenReports
|
||||
const map = () => golden.draft.migrationMap
|
||||
|
||||
beforeAll(() => {
|
||||
golden = loadGoldenReports()
|
||||
})
|
||||
|
||||
function exportOnDraft(report: Report): Promise<ExportResult> {
|
||||
return exportReportArchive({
|
||||
report,
|
||||
sheet: buildSheetSnapshot(golden.draft, report),
|
||||
branding: nologosBranding(),
|
||||
labels: defaultPdfLabels,
|
||||
locale: 'fr',
|
||||
rasterizer: rasterizerOf('nologos'),
|
||||
exportedAt: FIXED_EXPORTED_AT,
|
||||
})
|
||||
}
|
||||
|
||||
const unresolvedFindings = (report: Report) =>
|
||||
report.observations.flatMap((o) => o.findings).filter((f) => f.unresolved)
|
||||
.length
|
||||
|
||||
async function rejects(
|
||||
bytes: Uint8Array,
|
||||
expected: Partial<ArchiveReadError>,
|
||||
): Promise<void> {
|
||||
const promise = readReportArchive(bytes, map())
|
||||
await expect(promise).rejects.toBeInstanceOf(ArchiveReadError)
|
||||
await expect(promise).rejects.toMatchObject(expected)
|
||||
}
|
||||
|
||||
describe('T4 roundtrip', () => {
|
||||
it('reads back the exported envelope whole', async () => {
|
||||
const { pdf, envelope } = await exportOnDraft(golden.reports.demo)
|
||||
const outcome = await readReportArchive(pdf, map())
|
||||
expect(outcome.origin).toBe('envelope_v1')
|
||||
expect(outcome.migrated).toBe(false)
|
||||
expect(outcome.snapshotRejected).toBeUndefined()
|
||||
expect(outcome.report).toEqual(golden.reports.demo)
|
||||
expect(outcome.archive).toEqual(envelope)
|
||||
})
|
||||
})
|
||||
|
||||
describe('T5 v2 archives and the bare v3 fixture', () => {
|
||||
it.each(['report-v2.full.pdf', 'report-v2.minimal.pdf'])(
|
||||
'%s: migrated, re-exported, imported again equal',
|
||||
async (name) => {
|
||||
const first = await readReportArchive(readFixtureBytes(name), map())
|
||||
expect(first.origin).toBe('v2')
|
||||
expect(first.migrated).toBe(true)
|
||||
expect(first.archive).toBeNull()
|
||||
expect(first.report.version).toBe(3)
|
||||
const { pdf } = await exportOnDraft(first.report)
|
||||
const again = await readReportArchive(pdf, map())
|
||||
expect(again.origin).toBe('envelope_v1')
|
||||
expect(again.report).toEqual(first.report)
|
||||
},
|
||||
)
|
||||
|
||||
it('keeps the 29 unresolved findings of the 612-leaf report through export and import', async () => {
|
||||
const migrated = allLeavesMigrated(golden.draft)
|
||||
expect(migrated.unresolvedFindings).toBe(29)
|
||||
expect(unresolvedFindings(migrated.report)).toBe(29)
|
||||
const { pdf } = await exportOnDraft(migrated.report)
|
||||
const again = await readReportArchive(pdf, map())
|
||||
expect(unresolvedFindings(again.report)).toBe(29)
|
||||
expect(again.report).toEqual(migrated.report)
|
||||
})
|
||||
|
||||
it('reads report-v3.bare.pdf as a bare v3 with no archive', async () => {
|
||||
const outcome = await readReportArchive(
|
||||
readFixtureBytes('report-v3.bare.pdf'),
|
||||
map(),
|
||||
)
|
||||
expect(outcome.origin).toBe('bare_v3')
|
||||
expect(outcome.archive).toBeNull()
|
||||
expect(outcome.snapshotRejected).toBeUndefined()
|
||||
expect(outcome.report).toEqual(golden.reports.demo)
|
||||
})
|
||||
})
|
||||
|
||||
describe('T6 versions', () => {
|
||||
let envelope: ReportArchiveEnvelope
|
||||
beforeAll(async () => {
|
||||
envelope = (await exportOnDraft(golden.reports.demo)).envelope
|
||||
})
|
||||
|
||||
it('envelope v2 wrapper: report kept, snapshot rejected as unsupported_envelope', async () => {
|
||||
const bytes = await pdfWithAttachment('osteo-report.json', {
|
||||
...envelope,
|
||||
envelopeVersion: 2,
|
||||
})
|
||||
const outcome = await readReportArchive(bytes, map())
|
||||
expect(outcome.report).toEqual(golden.reports.demo)
|
||||
expect(outcome.archive).toBeNull()
|
||||
expect(outcome.snapshotRejected).toBe('unsupported_envelope')
|
||||
})
|
||||
|
||||
it('envelope v1 with a report v4: incompatible_version 4', async () => {
|
||||
const bytes = await pdfWithAttachment('osteo-report.json', {
|
||||
...envelope,
|
||||
report: { ...envelope.report, version: 4 },
|
||||
})
|
||||
await rejects(bytes, { kind: 'incompatible_version', foundVersion: 4 })
|
||||
})
|
||||
|
||||
it('bare report version 7: incompatible_version 7', async () => {
|
||||
const bytes = await pdfWithAttachment('osteo-report.json', { version: 7 })
|
||||
await rejects(bytes, { kind: 'incompatible_version', foundVersion: 7 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('attachment presence and selection', () => {
|
||||
it('a stamped PDF without attachment: attachment_stripped', async () => {
|
||||
const bytes = await pdfWithoutAttachment(['faunosteo-archive/1'])
|
||||
await rejects(bytes, { kind: 'attachment_stripped' })
|
||||
})
|
||||
|
||||
it('a stamped PDF saved with object streams (pre-BLK-009 layout): the stamp is invisible, no_attachment', async () => {
|
||||
const bytes = await pdfWithoutAttachment(['faunosteo-archive/1'], true)
|
||||
await rejects(bytes, { kind: 'no_attachment' })
|
||||
})
|
||||
|
||||
it('a foreign PDF: no_attachment', async () => {
|
||||
await rejects(await pdfWithoutAttachment(), { kind: 'no_attachment' })
|
||||
const foreign = await pdfWithAttachment('other.json', { hello: 'world' })
|
||||
await rejects(foreign, { kind: 'no_attachment' })
|
||||
})
|
||||
|
||||
it('the Filespec named osteo-report.json wins over an earlier EmbeddedFile', async () => {
|
||||
const bytes = await pdfWithAttachment(
|
||||
'osteo-report.json',
|
||||
golden.reports.demo,
|
||||
{ before: ['other.json', { hello: 'world', version: 2 }] },
|
||||
)
|
||||
const outcome = await readReportArchive(bytes, map())
|
||||
expect(outcome.origin).toBe('bare_v3')
|
||||
expect(outcome.report).toEqual(golden.reports.demo)
|
||||
})
|
||||
|
||||
it('refuses an oversized file or one without a %PDF- header as invalid_pdf', async () => {
|
||||
await rejects(new Uint8Array(MAX_PDF_BYTES + 1), { kind: 'invalid_pdf' })
|
||||
await rejects(new TextEncoder().encode('not a pdf at all'), {
|
||||
kind: 'invalid_pdf',
|
||||
})
|
||||
const late = new Uint8Array(2048)
|
||||
late.set(new TextEncoder().encode('%PDF-1.7'), 1024)
|
||||
await rejects(late, { kind: 'invalid_pdf' })
|
||||
})
|
||||
})
|
||||
@@ -1,83 +0,0 @@
|
||||
/**
|
||||
* T1 (STEP6 §5, §7): an archive re-exports from its own envelope, with no
|
||||
* sheet, no network and no configuration: same drawn text, same images,
|
||||
* same view facts, same envelope but the export time.
|
||||
*/
|
||||
import { afterAll, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
buildSheetSnapshot,
|
||||
ReportSchema,
|
||||
type ReportArchiveEnvelope,
|
||||
} from '@faunosteo/domain'
|
||||
import {
|
||||
defaultPdfLabels,
|
||||
exportFromEnvelope,
|
||||
exportReportArchive,
|
||||
readReportArchive,
|
||||
type ExportResult,
|
||||
} from '../src'
|
||||
import { loadDraftSheet, readFixtureJson } from './helpers/draft'
|
||||
import {
|
||||
FIXED_EXPORTED_AT,
|
||||
logosBranding,
|
||||
rasterizerOf,
|
||||
recordDrawing,
|
||||
snapshotViews,
|
||||
type DrawRecording,
|
||||
} from './helpers/goldens'
|
||||
|
||||
afterAll(() => vi.restoreAllMocks())
|
||||
|
||||
type Recorded = ExportResult & Pick<DrawRecording, 'texts' | 'images'>
|
||||
|
||||
async function recorded(run: () => Promise<ExportResult>): Promise<Recorded> {
|
||||
const recording = recordDrawing()
|
||||
try {
|
||||
const result = await run()
|
||||
return { ...result, texts: recording.texts, images: recording.images }
|
||||
} finally {
|
||||
recording.stop()
|
||||
}
|
||||
}
|
||||
|
||||
const withoutDate = ({ exportedAt: _e, ...rest }: ReportArchiveEnvelope) => rest
|
||||
|
||||
describe('re-export from the envelope alone', () => {
|
||||
it('reproduces text, images, views and the envelope minus exportedAt', async () => {
|
||||
// The draft is known here only, for the first export.
|
||||
const draft = loadDraftSheet()
|
||||
const report = ReportSchema.parse(readFixtureJson('report-v3.demo.json'))
|
||||
const first = await recorded(() =>
|
||||
exportReportArchive({
|
||||
report,
|
||||
sheet: buildSheetSnapshot(draft, report),
|
||||
branding: logosBranding(),
|
||||
labels: defaultPdfLabels,
|
||||
locale: 'fr',
|
||||
rasterizer: rasterizerOf('logos'),
|
||||
exportedAt: FIXED_EXPORTED_AT,
|
||||
}),
|
||||
)
|
||||
const outcome = await readReportArchive(first.pdf, draft.migrationMap)
|
||||
expect(outcome.origin).toBe('envelope_v1')
|
||||
const archive = outcome.archive!
|
||||
|
||||
// From here on, only the archive is used.
|
||||
const later = new Date('2027-01-01T00:00:00.000Z')
|
||||
const second = await recorded(() =>
|
||||
exportFromEnvelope(archive, {
|
||||
locale: 'fr',
|
||||
rasterizer: rasterizerOf('logos'),
|
||||
exportedAt: later,
|
||||
}),
|
||||
)
|
||||
expect(second.warnings).toEqual([])
|
||||
expect(second.texts).toEqual(first.texts)
|
||||
expect(second.images).toEqual(first.images)
|
||||
expect(
|
||||
snapshotViews(second.envelope.sheetSnapshot, second.envelope.report),
|
||||
).toEqual(snapshotViews(first.envelope.sheetSnapshot, report))
|
||||
expect(second.envelope.exportedAt).toBe(later.toISOString())
|
||||
expect(withoutDate(second.envelope)).toEqual(withoutDate(first.envelope))
|
||||
})
|
||||
})
|
||||
@@ -1,608 +0,0 @@
|
||||
/**
|
||||
* BLK-009: the byte-scan attachment reader. Candidates on a fresh export and
|
||||
* on the frozen fixtures (object-stream layout), crafted layouts (two files,
|
||||
* indirect `/Length`, `\r\n`, no space after `/Type`), garbage, the keyword
|
||||
* stamp, the object-stream bomb the reader never inflates, and the candidate
|
||||
* cost bounds (monotonic `endstream` search over offset-sorted candidates,
|
||||
* shared 16 MiB budget, `{` check, bracket-depth pre-scan before JSON.parse).
|
||||
*/
|
||||
import { deflateSync } from 'node:zlib'
|
||||
import { beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { buildSheetSnapshot, type Report } from '@faunosteo/domain'
|
||||
import {
|
||||
ArchiveReadError,
|
||||
defaultPdfLabels,
|
||||
exportReportArchive,
|
||||
findEmbeddedFiles,
|
||||
readAttachedDocument,
|
||||
readAttachmentBytes,
|
||||
readReportArchive,
|
||||
type EmbeddedFileCandidate,
|
||||
} from '../src'
|
||||
import { inflateFlate } from '../src/attachment/inflate'
|
||||
import {
|
||||
decodePdfString,
|
||||
hasArchiveStamp,
|
||||
locateAttachment,
|
||||
} from '../src/attachment/scan'
|
||||
import { readFixtureBytes } from './helpers/draft'
|
||||
import {
|
||||
FIXED_EXPORTED_AT,
|
||||
nologosBranding,
|
||||
rasterizerOf,
|
||||
} from './helpers/goldens'
|
||||
import { pdfWithAttachment, pdfWithoutAttachment } from './helpers/pdf'
|
||||
import { loadGoldenReports, type GoldenReports } from './helpers/reports'
|
||||
|
||||
let golden: GoldenReports
|
||||
let exported: Uint8Array
|
||||
const map = () => golden.draft.migrationMap
|
||||
|
||||
beforeAll(async () => {
|
||||
golden = loadGoldenReports()
|
||||
exported = (await exportDemo()).pdf
|
||||
})
|
||||
|
||||
async function exportDemo() {
|
||||
const report: Report = golden.reports.demo
|
||||
return exportReportArchive({
|
||||
report,
|
||||
sheet: buildSheetSnapshot(golden.draft, report),
|
||||
branding: nologosBranding(),
|
||||
labels: defaultPdfLabels,
|
||||
locale: 'fr',
|
||||
rasterizer: rasterizerOf('nologos'),
|
||||
exportedAt: FIXED_EXPORTED_AT,
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hand-built PDFs: the scanner never reads the xref, so none is written
|
||||
|
||||
const latin1 = (bytes: Uint8Array) => Buffer.from(bytes).toString('latin1')
|
||||
const ascii = (text: string) => new Uint8Array(Buffer.from(text, 'latin1'))
|
||||
|
||||
function concat(parts: Uint8Array[]): Uint8Array {
|
||||
const out = new Uint8Array(parts.reduce((n, p) => n + p.byteLength, 0))
|
||||
let at = 0
|
||||
for (const part of parts) {
|
||||
out.set(part, at)
|
||||
at += part.byteLength
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
interface StreamSpec {
|
||||
num: number
|
||||
dict: string
|
||||
data: Uint8Array
|
||||
eol?: string
|
||||
}
|
||||
|
||||
function streamObject({ num, dict, data, eol = '\n' }: StreamSpec): Uint8Array {
|
||||
return concat([
|
||||
ascii(`${num} 0 obj\n<<${dict}>>\nstream${eol}`),
|
||||
data,
|
||||
ascii('\nendstream\nendobj\n'),
|
||||
])
|
||||
}
|
||||
|
||||
function craftPdf(objects: Uint8Array[]): Uint8Array {
|
||||
return concat([
|
||||
ascii('%PDF-1.7\n'),
|
||||
...objects,
|
||||
ascii('trailer\n<< /Root 1 0 R >>\n%%EOF\n'),
|
||||
])
|
||||
}
|
||||
|
||||
/** The `n 0 obj … endobj` bytes of the object whose dictionary holds `marker`. */
|
||||
function objectHolding(pdf: Uint8Array, marker: string): Uint8Array {
|
||||
const text = latin1(pdf)
|
||||
const at = text.indexOf(marker)
|
||||
expect(at).toBeGreaterThan(0)
|
||||
const start = text.lastIndexOf(' 0 obj', at)
|
||||
const headerStart = text.lastIndexOf('\n', start) + 1
|
||||
const end = text.indexOf('endobj', at) + 'endobj'.length
|
||||
return pdf.slice(headerStart, end)
|
||||
}
|
||||
|
||||
const BOMB_RAW = 64 * 1024 * 1024
|
||||
const bomb = () => new Uint8Array(deflateSync(new Uint8Array(BOMB_RAW)))
|
||||
|
||||
async function rejects(
|
||||
bytes: Uint8Array,
|
||||
kind: ArchiveReadError['kind'],
|
||||
): Promise<void> {
|
||||
const promise = readReportArchive(bytes, map())
|
||||
await expect(promise).rejects.toBeInstanceOf(ArchiveReadError)
|
||||
await expect(promise).rejects.toMatchObject({ kind })
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('findEmbeddedFiles on a fresh export (no object streams)', () => {
|
||||
let candidates: EmbeddedFileCandidate[]
|
||||
beforeAll(() => {
|
||||
candidates = findEmbeddedFiles(exported)
|
||||
})
|
||||
|
||||
it('finds the one Flate stream, named through its visible Filespec', async () => {
|
||||
expect(candidates).toHaveLength(1)
|
||||
const [c] = candidates
|
||||
expect(c!.filter).toBe('FlateDecode')
|
||||
expect(c!.name).toBe('osteo-report.json')
|
||||
const inflated = await inflateFlate(
|
||||
exported.subarray(c!.offset, c!.offset + c!.length),
|
||||
)
|
||||
const json = JSON.parse(new TextDecoder().decode(inflated!)) as {
|
||||
envelopeVersion: number
|
||||
}
|
||||
expect(json.envelopeVersion).toBe(1)
|
||||
})
|
||||
|
||||
it('the length is the declared /Length and the data ends on endstream', () => {
|
||||
const [c] = candidates
|
||||
const text = latin1(exported)
|
||||
expect(text).toContain(`/Length ${c!.length}\n>>\nstream\n`)
|
||||
expect(text.slice(c!.offset + c!.length)).toMatch(/^\r?\nendstream/)
|
||||
})
|
||||
|
||||
it('the export keeps the Filespec, its name and the stamp in clear, no object stream', () => {
|
||||
const text = latin1(exported)
|
||||
expect(text).toContain('/Type /Filespec')
|
||||
expect(text).toContain('/F (osteo-report.json)')
|
||||
expect(text).not.toContain('/Type /ObjStm')
|
||||
expect(hasArchiveStamp(exported)).toBe(true)
|
||||
})
|
||||
|
||||
it('readAttachmentBytes returns the inflated envelope bytes', async () => {
|
||||
const bytes = await readAttachmentBytes(exported)
|
||||
const json = JSON.parse(new TextDecoder().decode(bytes)) as {
|
||||
report: Report
|
||||
}
|
||||
expect(json.report).toEqual(golden.reports.demo)
|
||||
})
|
||||
})
|
||||
|
||||
describe('compatibility: frozen fixtures written with object streams', () => {
|
||||
it.each([
|
||||
['report-v2.full.pdf', 'v2'],
|
||||
['report-v2.minimal.pdf', 'v2'],
|
||||
['report-v3.bare.pdf', 'bare_v3'],
|
||||
] as const)('%s → origin %s', async (name, origin) => {
|
||||
const bytes = readFixtureBytes(name)
|
||||
expect(latin1(bytes)).toContain('/Type /ObjStm')
|
||||
const candidates = findEmbeddedFiles(bytes)
|
||||
expect(candidates).toHaveLength(1)
|
||||
// The Filespec is packed into the object stream: no name, the JSON decides.
|
||||
expect(candidates[0]!.name).toBeNull()
|
||||
expect(candidates[0]!.filter).toBe('FlateDecode')
|
||||
const outcome = await readReportArchive(bytes, map())
|
||||
expect(outcome.origin).toBe(origin)
|
||||
})
|
||||
|
||||
it('a stamped PDF with object streams hides its stamp: no_attachment (documented)', async () => {
|
||||
const bytes = await pdfWithoutAttachment(['faunosteo-archive/1'], true)
|
||||
expect(hasArchiveStamp(bytes)).toBe(false)
|
||||
await rejects(bytes, 'no_attachment')
|
||||
})
|
||||
})
|
||||
|
||||
describe('selection between several embedded files', () => {
|
||||
it('a decoy EmbeddedFile first, the named Faunosteo one second: the name wins', async () => {
|
||||
const bytes = await pdfWithAttachment(
|
||||
'osteo-report.json',
|
||||
golden.reports.demo,
|
||||
{
|
||||
before: ['other.json', { hello: 'world', version: 2 }],
|
||||
},
|
||||
)
|
||||
const names = findEmbeddedFiles(bytes).map((c) => c.name)
|
||||
expect(names).toEqual(['osteo-report.json', 'other.json'])
|
||||
const outcome = await readReportArchive(bytes, map())
|
||||
expect(outcome.origin).toBe('bare_v3')
|
||||
expect(outcome.report).toEqual(golden.reports.demo)
|
||||
})
|
||||
|
||||
it('an unnamed decoy without a version is skipped for the versioned JSON after it', async () => {
|
||||
const decoy = streamObject({
|
||||
num: 2,
|
||||
dict: '/Type /EmbeddedFile /Length 17',
|
||||
data: ascii('{"hello":"world"}'),
|
||||
})
|
||||
const real = objectHolding(exported, '/Type /EmbeddedFile')
|
||||
const outcome = await readReportArchive(craftPdf([decoy, real]), map())
|
||||
expect(outcome.origin).toBe('envelope_v1')
|
||||
expect(outcome.report).toEqual(golden.reports.demo)
|
||||
})
|
||||
|
||||
it('a foreign PDF, with or without attachments: no_attachment', async () => {
|
||||
await rejects(await pdfWithoutAttachment(), 'no_attachment')
|
||||
await rejects(
|
||||
await pdfWithAttachment('other.json', { hello: 'world' }),
|
||||
'no_attachment',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('crafted stream layouts', () => {
|
||||
// UTF-8: the demo report holds an en dash that Latin-1 cannot carry.
|
||||
const demoJson = () =>
|
||||
new TextEncoder().encode(JSON.stringify(golden.reports.demo))
|
||||
|
||||
it('/Length as an indirect reference: read up to endstream', async () => {
|
||||
const pdf = craftPdf([
|
||||
streamObject({
|
||||
num: 2,
|
||||
dict: '/Type /EmbeddedFile /Length 7 0 R',
|
||||
data: demoJson(),
|
||||
}),
|
||||
ascii('7 0 obj\n123456\nendobj\n'),
|
||||
])
|
||||
const [c] = findEmbeddedFiles(pdf)
|
||||
expect(c!.filter).toBeNull()
|
||||
expect(c!.length).toBe(demoJson().byteLength)
|
||||
expect((await readReportArchive(pdf, map())).origin).toBe('bare_v3')
|
||||
})
|
||||
|
||||
it('a wrong direct /Length that does not land on endstream: measured instead', async () => {
|
||||
const pdf = craftPdf([
|
||||
streamObject({
|
||||
num: 2,
|
||||
dict: '/Type /EmbeddedFile /Length 5',
|
||||
data: demoJson(),
|
||||
}),
|
||||
])
|
||||
expect(findEmbeddedFiles(pdf)[0]!.length).toBe(demoJson().byteLength)
|
||||
expect((await readReportArchive(pdf, map())).origin).toBe('bare_v3')
|
||||
})
|
||||
|
||||
it('CRLF after stream, /Type/EmbeddedFile unspaced, a leading /Params dict', async () => {
|
||||
const data = demoJson()
|
||||
const pdf = craftPdf([
|
||||
streamObject({
|
||||
num: 2,
|
||||
dict: `/Params << /Size ${data.byteLength} >> /Type/EmbeddedFile/Length ${data.byteLength}`,
|
||||
data,
|
||||
eol: '\r\n',
|
||||
}),
|
||||
])
|
||||
const [c] = findEmbeddedFiles(pdf)
|
||||
expect(c!.length).toBe(data.byteLength)
|
||||
expect(await readAttachmentBytes(pdf)).toEqual(data)
|
||||
})
|
||||
|
||||
it('a Filespec with a hex /F name and an /EF listing /UF too names its stream', () => {
|
||||
const name = Buffer.from('osteo-report.json', 'utf16le')
|
||||
.swap16()
|
||||
.toString('hex')
|
||||
const pdf = craftPdf([
|
||||
ascii(
|
||||
`3 0 obj\n<< /Type /Filespec /F <${name}> /EF << /F 2 0 R /UF 2 0 R >> >>\nendobj\n`,
|
||||
),
|
||||
streamObject({
|
||||
num: 2,
|
||||
dict: '/Type /EmbeddedFile /Length 13',
|
||||
data: ascii('{"version":3}'),
|
||||
}),
|
||||
])
|
||||
expect(findEmbeddedFiles(pdf)[0]!.name).toBe('osteo-report.json')
|
||||
})
|
||||
|
||||
it('decodePdfString: literal with escapes, hex ASCII, hex UTF-16BE with BOM', () => {
|
||||
expect(decodePdfString('(a\\(b\\)c)')).toBe('a(b)c')
|
||||
expect(decodePdfString('<6F7374656F>')).toBe('osteo')
|
||||
expect(decodePdfString('<FEFF006F0073>')).toBe('os')
|
||||
expect(decodePdfString('/Name')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the keyword stamp', () => {
|
||||
it('hex (pdf-lib) and literal /Keywords strings are both read', async () => {
|
||||
expect(
|
||||
hasArchiveStamp(await pdfWithoutAttachment(['faunosteo-archive/1'])),
|
||||
).toBe(true)
|
||||
expect(hasArchiveStamp(await pdfWithoutAttachment(['other']))).toBe(false)
|
||||
const literal = craftPdf([
|
||||
ascii('3 0 obj\n<< /Keywords (faunosteo-archive/1) >>\nendobj\n'),
|
||||
])
|
||||
expect(hasArchiveStamp(literal)).toBe(true)
|
||||
await rejects(literal, 'attachment_stripped')
|
||||
})
|
||||
})
|
||||
|
||||
describe('garbage never throws', () => {
|
||||
const cases: [string, Uint8Array][] = [
|
||||
['empty', new Uint8Array(0)],
|
||||
[
|
||||
'random bytes',
|
||||
Uint8Array.from({ length: 4096 }, (_, i) => (i * 7919) % 256),
|
||||
],
|
||||
['the type alone', ascii('%PDF-1.7\n/Type /EmbeddedFile')],
|
||||
[
|
||||
'dict without stream',
|
||||
ascii('%PDF-1.7\n<< /Type /EmbeddedFile /Length 3 >>\nendobj'),
|
||||
],
|
||||
[
|
||||
'stream without endstream',
|
||||
ascii('%PDF-1.7\n<< /Type /EmbeddedFile >>\nstream\n{"version":3}'),
|
||||
],
|
||||
[
|
||||
'only the /EmbeddedFiles name tree key',
|
||||
ascii('%PDF-1.7\n<< /Type /EmbeddedFiles >>\nstream\nx\nendstream'),
|
||||
],
|
||||
[
|
||||
'unterminated dictionary',
|
||||
ascii(
|
||||
'%PDF-1.7\n<< /Type /EmbeddedFile /Length 1 << >>\nstream\nx\nendstream',
|
||||
),
|
||||
],
|
||||
[
|
||||
'hex /Keywords without a closing bracket',
|
||||
ascii('%PDF-1.7\n<< /Keywords <FEFF0066'),
|
||||
],
|
||||
]
|
||||
|
||||
it.each(cases)(
|
||||
'%s: no candidate, no stamp, no_attachment or invalid_pdf',
|
||||
async (_name, bytes) => {
|
||||
expect(findEmbeddedFiles(bytes)).toEqual([])
|
||||
expect(hasArchiveStamp(bytes)).toBe(false)
|
||||
await expect(readAttachedDocument(bytes)).rejects.toBeInstanceOf(
|
||||
ArchiveReadError,
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
it('caps the candidates at 32', () => {
|
||||
const objects = Array.from({ length: 40 }, (_, i) =>
|
||||
streamObject({
|
||||
num: i + 2,
|
||||
dict: '/Type /EmbeddedFile /Length 1',
|
||||
data: ascii('x'),
|
||||
}),
|
||||
)
|
||||
expect(findEmbeddedFiles(craftPdf(objects))).toHaveLength(32)
|
||||
})
|
||||
})
|
||||
|
||||
describe('object-stream bomb (BLK-009)', () => {
|
||||
const MiB = 1024 * 1024
|
||||
const objStmBomb = () => {
|
||||
const data = bomb()
|
||||
return streamObject({
|
||||
num: 9,
|
||||
dict: `/Type /ObjStm /N 1 /First 4 /Filter /FlateDecode /Length ${data.byteLength}`,
|
||||
data,
|
||||
})
|
||||
}
|
||||
const embeddedBomb = () => {
|
||||
const data = bomb()
|
||||
return streamObject({
|
||||
num: 8,
|
||||
dict: `/Type /EmbeddedFile /Filter /FlateDecode /Length ${data.byteLength}`,
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
it('64 MiB ObjStm bomb beside the attachment: report in ms, bomb never inflated', async () => {
|
||||
const pdf = craftPdf([
|
||||
objStmBomb(),
|
||||
objectHolding(exported, '/Type /Filespec'),
|
||||
objectHolding(exported, '/Type /EmbeddedFile'),
|
||||
])
|
||||
expect(pdf.byteLength).toBeLessThan(512 * 1024)
|
||||
const rssBefore = process.memoryUsage().rss
|
||||
const started = performance.now()
|
||||
const outcome = await readReportArchive(pdf, map())
|
||||
const elapsed = performance.now() - started
|
||||
const rssDelta = process.memoryUsage().rss - rssBefore
|
||||
console.log(
|
||||
`[bomb] objstm: ${elapsed.toFixed(0)} ms, rss +${(rssDelta / MiB).toFixed(1)} MiB`,
|
||||
)
|
||||
expect(outcome.origin).toBe('envelope_v1')
|
||||
expect(outcome.report).toEqual(golden.reports.demo)
|
||||
expect(elapsed).toBeLessThan(2000)
|
||||
expect(rssDelta).toBeLessThan(64 * MiB)
|
||||
})
|
||||
|
||||
it('EmbeddedFile bomb past 16 MiB: inflation cancelled, no_attachment, no hang', async () => {
|
||||
const pdf = craftPdf([objStmBomb(), embeddedBomb()])
|
||||
const started = performance.now()
|
||||
await rejects(pdf, 'no_attachment')
|
||||
const elapsed = performance.now() - started
|
||||
console.log(`[bomb] embedded: ${elapsed.toFixed(0)} ms`)
|
||||
expect(elapsed).toBeLessThan(2000)
|
||||
})
|
||||
|
||||
it('both bombs before an unnamed real attachment: bomb skipped, report read', async () => {
|
||||
const pdf = craftPdf([
|
||||
objStmBomb(),
|
||||
embeddedBomb(),
|
||||
objectHolding(exported, '/Type /EmbeddedFile'),
|
||||
])
|
||||
const started = performance.now()
|
||||
const outcome = await readReportArchive(pdf, map())
|
||||
const elapsed = performance.now() - started
|
||||
console.log(`[bomb] both + unnamed attachment: ${elapsed.toFixed(0)} ms`)
|
||||
expect(outcome.report).toEqual(golden.reports.demo)
|
||||
expect(elapsed).toBeLessThan(2000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('candidate cost bounds (audit M2)', () => {
|
||||
const MiB = 1024 * 1024
|
||||
/** `n 0 obj << /Type /EmbeddedFile >> stream` with no `/Length`: the data runs to `endstream`. */
|
||||
const openStream = (num: number) =>
|
||||
ascii(`${num} 0 obj\n<< /Type /EmbeddedFile >>\nstream\n`)
|
||||
const filled = (byte: string, length: number) => ascii(byte.repeat(length))
|
||||
const timed = async <T>(label: string, run: () => Promise<T> | T) => {
|
||||
const started = performance.now()
|
||||
const result = await run()
|
||||
const elapsed = performance.now() - started
|
||||
console.log(`[cost] ${label}: ${elapsed.toFixed(0)} ms`)
|
||||
return { result, elapsed }
|
||||
}
|
||||
|
||||
it('32 candidates without any endstream on a 20 MiB file: no candidate, well under a second', async () => {
|
||||
const heads = Array.from({ length: 32 }, (_, i) => openStream(i + 2))
|
||||
const pdf = craftPdf([...heads, filled('x', 20 * MiB)])
|
||||
const { result, elapsed } = await timed('32 × no endstream', () =>
|
||||
findEmbeddedFiles(pdf),
|
||||
)
|
||||
expect(result).toEqual([])
|
||||
expect(elapsed).toBeLessThan(1000)
|
||||
})
|
||||
|
||||
it('32 nested EmbeddedFile dicts (descending offsets) without endstream on a 20 MiB file: no candidate, no finder reset', async () => {
|
||||
// Outermost `/Type` first in the file, its `stream` last: offsets come out
|
||||
// reversed; the sort by offset keeps the endstream search to one pass.
|
||||
let nested: Uint8Array = ascii('<< /Type /EmbeddedFile >>\nstream\n')
|
||||
for (let level = 1; level < 32; level += 1) {
|
||||
nested = concat([
|
||||
ascii('<< /Type /EmbeddedFile /A '),
|
||||
nested,
|
||||
ascii(' >>\nstream\n'),
|
||||
])
|
||||
}
|
||||
const pdf = craftPdf([ascii('2 0 obj\n'), nested, filled('x', 20 * MiB)])
|
||||
const { result, elapsed } = await timed('32 nested, no endstream', () =>
|
||||
findEmbeddedFiles(pdf),
|
||||
)
|
||||
expect(result).toEqual([])
|
||||
expect(elapsed).toBeLessThan(500)
|
||||
})
|
||||
|
||||
it('several indirect /Length streams in a row: each measured to its own endstream', () => {
|
||||
const payloads = ['{"version":3}', '{"version":4,"x":1}', '{"v":5}']
|
||||
const pdf = craftPdf(
|
||||
payloads.map((text, i) =>
|
||||
streamObject({
|
||||
num: i + 2,
|
||||
dict: `/Type /EmbeddedFile /Length ${i + 20} 0 R`,
|
||||
data: ascii(text),
|
||||
}),
|
||||
),
|
||||
)
|
||||
const lengths = findEmbeddedFiles(pdf).map((c) => c.length)
|
||||
expect(lengths).toEqual(payloads.map((p) => p.length))
|
||||
})
|
||||
|
||||
it('a measured stream running past the cap window is not a candidate, the next one is', () => {
|
||||
const pdf = craftPdf([
|
||||
openStream(2),
|
||||
filled('x', 16 * MiB + 64),
|
||||
ascii('\nendstream\nendobj\n'),
|
||||
streamObject({
|
||||
num: 3,
|
||||
dict: '/Type /EmbeddedFile /Length 13',
|
||||
data: ascii('{"version":3}'),
|
||||
}),
|
||||
])
|
||||
const candidates = findEmbeddedFiles(pdf)
|
||||
expect(candidates).toHaveLength(1)
|
||||
expect(candidates[0]!.length).toBe(13)
|
||||
})
|
||||
|
||||
it('32 raw candidates of 1 MiB of "[": no_attachment under a second, JSON.parse never called', async () => {
|
||||
const objects = Array.from({ length: 32 }, (_, i) =>
|
||||
streamObject({
|
||||
num: i + 2,
|
||||
dict: `/Type /EmbeddedFile /Length ${MiB}`,
|
||||
data: filled('[', MiB),
|
||||
}),
|
||||
)
|
||||
const pdf = craftPdf(objects)
|
||||
const parse = vi.spyOn(JSON, 'parse')
|
||||
try {
|
||||
const { elapsed } = await timed('32 × 1 MiB "["', () =>
|
||||
rejects(pdf, 'no_attachment'),
|
||||
)
|
||||
expect(elapsed).toBeLessThan(1000)
|
||||
expect(parse).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
parse.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
describe('bracket-depth pre-scan before JSON.parse (audit finding 3)', () => {
|
||||
const flateObject = (num: number, raw: Uint8Array) => {
|
||||
const data = new Uint8Array(deflateSync(raw))
|
||||
return streamObject({
|
||||
num,
|
||||
dict: `/Type /EmbeddedFile /Filter /FlateDecode /Length ${data.byteLength}`,
|
||||
data,
|
||||
})
|
||||
}
|
||||
const withSpy = async (run: () => Promise<void>) => {
|
||||
const parse = vi.spyOn(JSON, 'parse')
|
||||
try {
|
||||
await run()
|
||||
return parse.mock.calls.length
|
||||
} finally {
|
||||
parse.mockRestore()
|
||||
}
|
||||
}
|
||||
|
||||
it('a 16 KB Flate candidate opening 8 million "[" deep: skipped unparsed, no_attachment fast', async () => {
|
||||
const raw = concat([ascii('{"version":3,"x":'), filled('[', 8_000_000)])
|
||||
const object = flateObject(2, raw)
|
||||
expect(object.byteLength).toBeLessThan(16 * 1024)
|
||||
const calls = await withSpy(async () => {
|
||||
const { elapsed } = await timed('8M-deep candidate', () =>
|
||||
rejects(craftPdf([object]), 'no_attachment'),
|
||||
)
|
||||
expect(elapsed).toBeLessThan(100)
|
||||
})
|
||||
expect(calls).toBe(0)
|
||||
})
|
||||
|
||||
it('2000 "[" inside a string with escaped quotes and backslashes: not rejected, parsed once', async () => {
|
||||
const text = `{"version":3,"note":"\\"${'['.repeat(2000)}\\\\ \\" [[[["}`
|
||||
const pdf = craftPdf([
|
||||
streamObject({
|
||||
num: 2,
|
||||
dict: `/Type /EmbeddedFile /Length ${text.length}`,
|
||||
data: ascii(text),
|
||||
}),
|
||||
])
|
||||
const calls = await withSpy(async () => {
|
||||
const located = await locateAttachment(pdf)
|
||||
expect(located.data).toMatchObject({ version: 3 })
|
||||
})
|
||||
expect(calls).toBe(1)
|
||||
})
|
||||
|
||||
it('the real envelope passes the pre-scan and is parsed once', async () => {
|
||||
const calls = await withSpy(async () => {
|
||||
const located = await locateAttachment(exported)
|
||||
expect(located.data).toMatchObject({ envelopeVersion: 1 })
|
||||
})
|
||||
expect(calls).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('one 16 MiB budget shared by every candidate', () => {
|
||||
const garbageObject = (num: number) =>
|
||||
streamObject({
|
||||
num,
|
||||
dict: `/Type /EmbeddedFile /Length ${10 * MiB}`,
|
||||
data: concat([ascii('{'), filled('x', 10 * MiB - 1)]),
|
||||
})
|
||||
const real = () => objectHolding(exported, '/Type /EmbeddedFile')
|
||||
|
||||
it('one 10 MiB garbage object before the attachment: 6 MiB left, the report is read', async () => {
|
||||
const pdf = craftPdf([garbageObject(2), real()])
|
||||
const outcome = await readReportArchive(pdf, map())
|
||||
expect(outcome.report).toEqual(golden.reports.demo)
|
||||
})
|
||||
|
||||
it('two 10 MiB garbage objects before the attachment: budget exhausted, no_attachment', async () => {
|
||||
const pdf = craftPdf([garbageObject(2), garbageObject(3), real()])
|
||||
const { elapsed } = await timed('2 × 10 MiB "{" + attachment', () =>
|
||||
rejects(pdf, 'no_attachment'),
|
||||
)
|
||||
expect(elapsed).toBeLessThan(2000)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,987 +0,0 @@
|
||||
/**
|
||||
* T8 (STEP6 §6, §15): a hostile or oversized snapshot never sinks the
|
||||
* report on import and never produces an unreadable file on export; hostile
|
||||
* SVG content is removed, refused or clamped; the real assets pass the
|
||||
* sanitiser untouched; the inflate bomb guard stays.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { deflateSync } from 'node:zlib'
|
||||
import { beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { PDFDict, PDFDocument, PDFName } from 'pdf-lib'
|
||||
import {
|
||||
assertSnapshot,
|
||||
SnapshotError,
|
||||
type Branding,
|
||||
type Report,
|
||||
type ReportArchiveEnvelope,
|
||||
type SheetSnapshot,
|
||||
} from '@faunosteo/domain'
|
||||
import {
|
||||
ArchiveExportError,
|
||||
defaultPdfLabels,
|
||||
exportFromEnvelope,
|
||||
exportReportArchive,
|
||||
readReportArchive,
|
||||
type ExportInput,
|
||||
type Rasterizer,
|
||||
} from '../src'
|
||||
import { inflateFlate } from '../src/attachment/inflate'
|
||||
import { pngIssue } from '../src/branding'
|
||||
import { SvgRejectedError } from '../src/errors'
|
||||
import { addLinkAnnotation } from '../src/render/linkAnnotation'
|
||||
import { parseSvg, serializeSvg } from '../src/svg/parse'
|
||||
import { sanitizeSvgRoot } from '../src/svg/sanitize'
|
||||
import { rasterSizeOf } from '../src/svg/view'
|
||||
import { BRAND_ASSETS_DIR, DRAFT_DIR, PUBLIC_DIR } from './helpers/draft'
|
||||
import {
|
||||
FIXED_EXPORTED_AT,
|
||||
logosBranding,
|
||||
nologosBranding,
|
||||
ONE_PX_PNG,
|
||||
rasterizerOf,
|
||||
readLinks,
|
||||
recordDrawing,
|
||||
TWO_BY_ONE_PNG,
|
||||
} from './helpers/goldens'
|
||||
import { pdfWithAttachment } from './helpers/pdf'
|
||||
import { loadGoldenReports, type GoldenReports } from './helpers/reports'
|
||||
|
||||
let golden: GoldenReports
|
||||
let envelope: ReportArchiveEnvelope
|
||||
|
||||
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T
|
||||
|
||||
function baseInput(report: Report, sheet: SheetSnapshot): ExportInput {
|
||||
return {
|
||||
report,
|
||||
sheet,
|
||||
branding: nologosBranding(),
|
||||
labels: defaultPdfLabels,
|
||||
locale: 'fr',
|
||||
rasterizer: rasterizerOf('nologos'),
|
||||
exportedAt: FIXED_EXPORTED_AT,
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
golden = loadGoldenReports()
|
||||
envelope = (
|
||||
await exportReportArchive(
|
||||
baseInput(golden.reports.demo, golden.snapshots.demo),
|
||||
)
|
||||
).envelope
|
||||
})
|
||||
|
||||
/** The reason the domain gate gives: the oracle the engine must surface. */
|
||||
function domainReason(snapshot: unknown): string {
|
||||
try {
|
||||
assertSnapshot(snapshot)
|
||||
return 'accepted'
|
||||
} catch (error) {
|
||||
if (error instanceof SnapshotError) return error.reason
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
type Mutation = (snapshot: SheetSnapshot) => void
|
||||
|
||||
const UUID = (i: number) => `00000000-0000-4000-8000-00000000000${i}`
|
||||
|
||||
const MUTATIONS: Array<[string, string, Mutation]> = [
|
||||
[
|
||||
'5 assets',
|
||||
'schema',
|
||||
(s) => {
|
||||
s.assets = Array.from({ length: 5 }, (_, i) => ({
|
||||
...s.assets[0]!,
|
||||
svgAssetId: i === 0 ? s.assets[0]!.svgAssetId : UUID(i),
|
||||
}))
|
||||
},
|
||||
],
|
||||
[
|
||||
'a 3 MiB asset',
|
||||
'caps',
|
||||
(s) => {
|
||||
s.assets[0]!.svg = 'é'.repeat(1_100_000)
|
||||
},
|
||||
],
|
||||
[
|
||||
'finding depth 9',
|
||||
'caps',
|
||||
(s) => {
|
||||
const leaf = {
|
||||
id: 'deep',
|
||||
name: { fr: 'x', en: 'x' },
|
||||
description: {},
|
||||
requires_vet_referral: false,
|
||||
reference_ids: [],
|
||||
review_status: 'inherited' as const,
|
||||
children: [] as never[],
|
||||
}
|
||||
let node: typeof leaf = leaf
|
||||
for (let depth = 0; depth < 9; depth += 1) {
|
||||
node = { ...leaf, id: `n${depth}`, children: [node] as never[] }
|
||||
}
|
||||
const zone = s.document.finding_zones.find((z) => z.categories.length)!
|
||||
zone.categories[0]!.children.push(node)
|
||||
},
|
||||
],
|
||||
[
|
||||
'1,025 annotations',
|
||||
'caps',
|
||||
(s) => {
|
||||
s.document.annotations.push(
|
||||
...Array.from({ length: 1025 }, (_, i) => ({
|
||||
...s.document.annotations[0]!,
|
||||
id: `extra-${i}`,
|
||||
})),
|
||||
)
|
||||
},
|
||||
],
|
||||
[
|
||||
'a view chain cycle',
|
||||
'integrity',
|
||||
(s) => {
|
||||
const head = s.document.views.find((v) => v.id === 'head')!
|
||||
if (head.kind === 'detail') head.parent_view_id = 'head'
|
||||
},
|
||||
],
|
||||
[
|
||||
'a dangling svg_asset_id',
|
||||
'integrity',
|
||||
(s) => {
|
||||
s.document.views.find((v) => v.kind === 'main')!.svg_asset_id = UUID(9)
|
||||
},
|
||||
],
|
||||
[
|
||||
'another sheet (sheet_mismatch)',
|
||||
'sheet_mismatch',
|
||||
(s) => {
|
||||
s.ref.documentSha256 = 'f'.repeat(64)
|
||||
},
|
||||
],
|
||||
]
|
||||
|
||||
describe('import: the report survives a rejected snapshot', () => {
|
||||
it.each(MUTATIONS)(
|
||||
'%s → %s',
|
||||
async (_name, reason, mutate) => {
|
||||
const hostile = clone(envelope)
|
||||
mutate(hostile.sheetSnapshot)
|
||||
if (reason !== 'sheet_mismatch') {
|
||||
expect(domainReason(hostile.sheetSnapshot)).toBe(reason)
|
||||
}
|
||||
const bytes = await pdfWithAttachment('osteo-report.json', hostile)
|
||||
const outcome = await readReportArchive(bytes, golden.draft.migrationMap)
|
||||
expect(outcome.report).toEqual(golden.reports.demo)
|
||||
expect(outcome.origin).toBe('envelope_v1')
|
||||
expect(outcome.archive).toBeNull()
|
||||
expect(outcome.snapshotRejected).toBe(reason)
|
||||
},
|
||||
20_000,
|
||||
)
|
||||
})
|
||||
|
||||
describe('export: a snapshot over the caps fails with a typed error and no file', () => {
|
||||
it.each([
|
||||
['1,025 annotations', 'snapshot_too_large', MUTATIONS[3]![2]],
|
||||
['a 3 MiB asset', 'snapshot_too_large', MUTATIONS[1]![2]],
|
||||
['5 assets', 'snapshot_invalid', MUTATIONS[0]![2]],
|
||||
['a dangling svg_asset_id', 'snapshot_invalid', MUTATIONS[5]![2]],
|
||||
['another sheet', 'sheet_mismatch', MUTATIONS[6]![2]],
|
||||
] as const)('%s → %s', async (_name, kind, mutate) => {
|
||||
const sheet = clone(golden.snapshots.demo)
|
||||
mutate(sheet)
|
||||
const promise = exportReportArchive(baseInput(golden.reports.demo, sheet))
|
||||
await expect(promise).rejects.toBeInstanceOf(ArchiveExportError)
|
||||
await expect(promise).rejects.toMatchObject({ kind })
|
||||
})
|
||||
|
||||
it('too many observations or views per observation → too_many_pages', async () => {
|
||||
const demo = golden.reports.demo
|
||||
const many = {
|
||||
...demo,
|
||||
observations: Array.from({ length: 501 }, (_, i) => ({
|
||||
...demo.observations[0]!,
|
||||
id: `o${i}`,
|
||||
})),
|
||||
}
|
||||
await expect(
|
||||
exportReportArchive(baseInput(many, golden.snapshots.demo)),
|
||||
).rejects.toMatchObject({ kind: 'too_many_pages' })
|
||||
const views = {
|
||||
...demo,
|
||||
observations: [
|
||||
{
|
||||
...demo.observations[0]!,
|
||||
zones: Array.from({ length: 9 }, (_, i) => ({
|
||||
annotationId: 'c7-t1',
|
||||
viewId: `v${i}`,
|
||||
})),
|
||||
},
|
||||
],
|
||||
}
|
||||
await expect(
|
||||
exportReportArchive(baseInput(views, golden.snapshots.demo)),
|
||||
).rejects.toMatchObject({ kind: 'too_many_pages' })
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hostile SVG
|
||||
|
||||
const SVG_OPEN =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 2073.4 1629.4">'
|
||||
const wrap = (inner: string) => `${SVG_OPEN}${inner}</svg>`
|
||||
|
||||
/** Exports the demo first observation on a snapshot whose drawing is `svg`; returns what the rasterizer saw. */
|
||||
async function exportWithAsset(svg: string): Promise<string[]> {
|
||||
const sheet = clone(golden.snapshots.demo)
|
||||
sheet.assets[0]!.svg = svg
|
||||
const seen: string[] = []
|
||||
const rasterizer: Rasterizer = async (text) => {
|
||||
seen.push(text)
|
||||
return ONE_PX_PNG
|
||||
}
|
||||
const report = {
|
||||
...golden.reports.demo,
|
||||
observations: [golden.reports.demo.observations[0]!],
|
||||
}
|
||||
const { warnings } = await exportReportArchive({
|
||||
...baseInput(report, sheet),
|
||||
rasterizer,
|
||||
})
|
||||
expect(warnings).toEqual([])
|
||||
return seen
|
||||
}
|
||||
|
||||
describe('hostile SVG assets', () => {
|
||||
it('<script>, on*, javascript: href, external <image>, <style> are gone from what is rasterised', async () => {
|
||||
const [seen] = await exportWithAsset(
|
||||
wrap(
|
||||
'<script>alert(1)</script>' +
|
||||
'<style>path{fill:url(http://evil.test/a)}</style>' +
|
||||
'<defs><path id="p" d="M0 0h10v10z"/></defs>' +
|
||||
'<path d="M0 0h1" onload="steal()" style="fill:url(http://evil.test/b)"/>' +
|
||||
'<use xlink:href="javascript:alert(1)"/><use href="#p"/>' +
|
||||
'<image href="https://evil.test/x.png" width="10" height="10"/>' +
|
||||
'<path d="M1 1h1" fill="url(http://evil.test/c)"/>',
|
||||
),
|
||||
)
|
||||
expect(seen).toBeDefined()
|
||||
for (const forbidden of [
|
||||
'<script',
|
||||
'<style',
|
||||
'onload',
|
||||
'javascript:',
|
||||
'<image',
|
||||
'evil.test',
|
||||
]) {
|
||||
expect(seen).not.toContain(forbidden)
|
||||
}
|
||||
expect(seen).toContain('<use href="#p"/>')
|
||||
expect(seen).toContain('<path id="p" d="M0 0h10v10z"/>')
|
||||
expect(seen).toContain('fill="#b85a3f"')
|
||||
})
|
||||
|
||||
it('the sanitiser names what it removed and clamps stdDeviation', () => {
|
||||
const root = parseSvg(
|
||||
wrap(
|
||||
'<script>x</script><g onclick="y()" data-x="1"><path d="M0 0" style="fill:url(http://e)"/></g>' +
|
||||
'<filter id="f"><feGaussianBlur stdDeviation="500,3"/><feTurbulence/></filter>' +
|
||||
'<use xlink:href="javascript:z"/><a href="#ok"/>',
|
||||
),
|
||||
)
|
||||
const { removed } = sanitizeSvgRoot(root)
|
||||
expect(removed).toEqual([
|
||||
'script',
|
||||
'g@onclick',
|
||||
'g@data-x',
|
||||
'path@style',
|
||||
'feTurbulence',
|
||||
'use@xlink:href',
|
||||
'a',
|
||||
])
|
||||
expect(serializeSvg(root)).toContain('stdDeviation="100 3"')
|
||||
})
|
||||
|
||||
it('CSS escapes, image-set and function calls in style or presentation attributes are removed', () => {
|
||||
const root = parseSvg(
|
||||
wrap(
|
||||
'<path d="M0 0" style="fill:u\\72l(http://evil/x)"/>' +
|
||||
`<path d="M0 0" style='fill:image-set("http://evil/y")'/>` +
|
||||
'<path d="M0 0" fill="u\\72l(http://evil/x)"/>' +
|
||||
'<path d="M0 0" fill="rgb(1,2,3)"/>' +
|
||||
'<path d="M0 0" id="a\b"/>' +
|
||||
'<path d="M0 0" fill="url(#ok)" transform="translate(1 2)"/>',
|
||||
),
|
||||
)
|
||||
const { removed } = sanitizeSvgRoot(root)
|
||||
expect(removed).toEqual([
|
||||
'path@style',
|
||||
'path@style',
|
||||
'path@fill',
|
||||
'path@fill',
|
||||
'path@id',
|
||||
])
|
||||
const out = serializeSvg(root)
|
||||
expect(out).not.toContain('evil')
|
||||
expect(out).not.toContain('rgb(')
|
||||
expect(out).toContain('fill="url(#ok)" transform="translate(1 2)"')
|
||||
})
|
||||
|
||||
it('a non-finite or empty viewBox falls back to the 0.6 ratio, never NaN', () => {
|
||||
for (const viewBox of [
|
||||
'0 0 1e999 1e999',
|
||||
'0 0 Infinity 10',
|
||||
'0 0 NaN 10',
|
||||
'0 0 0 10',
|
||||
'0 0 -5 10',
|
||||
'',
|
||||
]) {
|
||||
const size = rasterSizeOf(viewBox)
|
||||
expect(size, viewBox).toEqual({ widthPx: 1200, heightPx: 720 })
|
||||
expect(Number.isFinite(size.heightPx)).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('<!ENTITY> and 257 <use> are refused: the export fails as snapshot_invalid', async () => {
|
||||
const entity =
|
||||
'<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY x "y">]>' + wrap('&x;')
|
||||
await expect(exportWithAsset(entity)).rejects.toMatchObject({
|
||||
kind: 'snapshot_invalid',
|
||||
})
|
||||
const uses = (count: number) =>
|
||||
wrap(
|
||||
'<defs><path id="p" d="M0 0h1"/></defs>' +
|
||||
'<use href="#p"/>'.repeat(count),
|
||||
)
|
||||
await expect(exportWithAsset(uses(257))).rejects.toMatchObject({
|
||||
kind: 'snapshot_invalid',
|
||||
})
|
||||
expect(() => sanitizeSvgRoot(parseSvg(uses(257)))).toThrow(SvgRejectedError)
|
||||
await expect(exportWithAsset(uses(256))).resolves.toHaveLength(1)
|
||||
})
|
||||
|
||||
it('a huge root viewBox is clamped to a 1200×2400 raster', async () => {
|
||||
expect(rasterSizeOf('0 0 1 100000')).toEqual({
|
||||
widthPx: 1200,
|
||||
heightPx: 2400,
|
||||
})
|
||||
expect(rasterSizeOf('0 0 100000 1')).toEqual({
|
||||
widthPx: 1200,
|
||||
heightPx: 240,
|
||||
})
|
||||
expect(rasterSizeOf(null)).toEqual({ widthPx: 1200, heightPx: 720 })
|
||||
const sizes: Array<{ widthPx: number; heightPx: number }> = []
|
||||
const branding = nologosBranding()
|
||||
branding.partner!.logo = {
|
||||
kind: 'svg',
|
||||
svg: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 100000"><rect width="1" height="1"/></svg>',
|
||||
}
|
||||
await exportReportArchive({
|
||||
...baseInput(golden.reports.demo, golden.snapshots.demo),
|
||||
branding,
|
||||
rasterizer: async (_svg, size) => {
|
||||
sizes.push(size)
|
||||
return ONE_PX_PNG
|
||||
},
|
||||
})
|
||||
expect(sizes[0]).toEqual({ widthPx: 1200, heightPx: 2400 })
|
||||
})
|
||||
|
||||
it('horse.svg and paws-in-harmony.svg pass with nothing removed and an identical serialisation', () => {
|
||||
for (const file of [
|
||||
resolve(DRAFT_DIR, 'assets/horse.svg'),
|
||||
resolve(BRAND_ASSETS_DIR, 'paws-in-harmony.svg'),
|
||||
]) {
|
||||
const text = readFileSync(file, 'utf8')
|
||||
const pristine = serializeSvg(parseSvg(text))
|
||||
const root = parseSvg(text)
|
||||
expect(sanitizeSvgRoot(root)).toEqual({ removed: [] })
|
||||
expect(serializeSvg(root)).toBe(pristine)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('__proto__ ids and the inflate bomb', () => {
|
||||
it('report ids named __proto__ print raw and pollute nothing', async () => {
|
||||
const demo = golden.reports.demo
|
||||
const report: Report = {
|
||||
...demo,
|
||||
observations: [
|
||||
{
|
||||
...demo.observations[0]!,
|
||||
zones: [{ annotationId: '__proto__', viewId: 'main' }],
|
||||
findings: [
|
||||
{
|
||||
findingZoneId: '__proto__',
|
||||
path: ['__proto__'],
|
||||
labelFrSnapshot: 'proto fr',
|
||||
labelEnSnapshot: 'proto en',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
const recording = recordDrawing()
|
||||
try {
|
||||
const { warnings } = await exportReportArchive(
|
||||
baseInput(report, golden.snapshots.demo),
|
||||
)
|
||||
expect(warnings).toEqual([])
|
||||
const drawn = recording.texts.map((t) => t.text)
|
||||
expect(drawn).toContain('__proto__')
|
||||
expect(drawn).toContain('CONSTATS — __PROTO__')
|
||||
expect(drawn).toContain('proto fr')
|
||||
} finally {
|
||||
recording.stop()
|
||||
}
|
||||
expect(Object.keys(Object.prototype)).toEqual([])
|
||||
expect(({} as Record<string, unknown>).polluted).toBeUndefined()
|
||||
})
|
||||
|
||||
async function deflate(data: Uint8Array): Promise<Uint8Array> {
|
||||
const stream = new Blob([data])
|
||||
.stream()
|
||||
.pipeThrough(new CompressionStream('deflate'))
|
||||
return new Uint8Array(await new Response(stream).arrayBuffer())
|
||||
}
|
||||
|
||||
it('inflates a normal payload and returns null for a 24 MB bomb', async () => {
|
||||
const payload = new TextEncoder().encode(JSON.stringify({ version: 2 }))
|
||||
const out = await inflateFlate(await deflate(payload))
|
||||
expect(new TextDecoder().decode(out!)).toContain('version')
|
||||
const bomb = await deflate(new Uint8Array(24 * 1024 * 1024))
|
||||
expect(bomb.byteLength).toBeLessThan(1024 * 1024)
|
||||
expect(await inflateFlate(bomb)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Branding: URL injection at the link sink, PNG budget
|
||||
|
||||
/** Closes the `/URI (` literal and chains a JavaScript action when written unescaped. */
|
||||
const INJECTION_URL =
|
||||
'https://a.example/) /Next << /S /JavaScript /JS (app.alert\\(1\\)) >> /Z ('
|
||||
|
||||
/** Every dictionary of the loaded file whose `/S` is `JavaScript`. */
|
||||
function javaScriptActions(doc: PDFDocument): PDFDict[] {
|
||||
return doc.context
|
||||
.enumerateIndirectObjects()
|
||||
.map(([, object]) => object)
|
||||
.filter((object): object is PDFDict => object instanceof PDFDict)
|
||||
.filter((dict) => dict.get(PDFName.of('S')) === PDFName.of('JavaScript'))
|
||||
}
|
||||
|
||||
function reexportOptions() {
|
||||
return {
|
||||
locale: 'fr' as const,
|
||||
rasterizer: rasterizerOf('nologos'),
|
||||
exportedAt: FIXED_EXPORTED_AT,
|
||||
}
|
||||
}
|
||||
|
||||
/** The same payload without spaces: PDF syntax needs none, and the sink lets it through to the hex string. */
|
||||
const TIGHT_INJECTION_URL = INJECTION_URL.replaceAll(' ', '')
|
||||
|
||||
/** The saved bytes of a one-page PDF holding one link to `url`, objects uncompressed so the bytes can be read. */
|
||||
async function savedLink(url: string): Promise<Uint8Array> {
|
||||
const doc = await PDFDocument.create()
|
||||
addLinkAnnotation(doc.addPage(), { x: 0, y: 0, width: 10, height: 10, url })
|
||||
return doc.save({ useObjectStreams: false })
|
||||
}
|
||||
|
||||
/** `<hex>` of the URL's ASCII bytes, as the sink must write `/URI`. */
|
||||
const asciiHex = (url: string): string =>
|
||||
Array.from(url, (c) => c.charCodeAt(0).toString(16).padStart(2, '0')).join('')
|
||||
|
||||
describe('branding URL injection (HIGH)', () => {
|
||||
it('writes /URI as the hex of the ASCII bytes, no UTF-16 BOM, and reloads to the URL', async () => {
|
||||
const url = 'https://faunosteo.com'
|
||||
const bytes = await savedLink(url)
|
||||
const raw = Buffer.from(bytes).toString('latin1')
|
||||
const uriMatch = /\/URI\s*<([0-9A-Fa-f]+)>/.exec(raw)
|
||||
expect(uriMatch?.[1]?.toLowerCase()).toBe(asciiHex(url))
|
||||
expect(uriMatch?.[1]?.toUpperCase().startsWith('FEFF')).toBe(false)
|
||||
expect(Buffer.from(uriMatch![1]!, 'hex').toString('latin1')).toBe(url)
|
||||
const [link] = await readLinks(bytes)
|
||||
expect(link?.uri).toBe(url)
|
||||
})
|
||||
|
||||
it('a URL with a code point above 0x7e or below 0x21 throws branding_invalid at the sink', async () => {
|
||||
for (const url of [
|
||||
'https://faunosté.com',
|
||||
'https://a.example/ b',
|
||||
INJECTION_URL,
|
||||
'https://a.example/\u00ff',
|
||||
]) {
|
||||
await expect(savedLink(url), url).rejects.toMatchObject({
|
||||
kind: 'branding_invalid',
|
||||
})
|
||||
await expect(savedLink(url), url).rejects.toBeInstanceOf(
|
||||
ArchiveExportError,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('the link sink alone keeps the whole URL inside the /URI string', async () => {
|
||||
const bytes = await savedLink(TIGHT_INJECTION_URL)
|
||||
const raw = Buffer.from(bytes).toString('latin1')
|
||||
expect(raw).not.toContain('/JavaScript')
|
||||
expect(raw).not.toContain('/Next')
|
||||
expect(raw).not.toContain('/JS')
|
||||
const reloaded = await PDFDocument.load(bytes)
|
||||
expect(javaScriptActions(reloaded)).toEqual([])
|
||||
const action = reloaded
|
||||
.getPage(0)
|
||||
.node.Annots()!
|
||||
.lookup(0, PDFDict)
|
||||
.lookup(PDFName.of('A'), PDFDict)
|
||||
expect(action.has(PDFName.of('Next'))).toBe(false)
|
||||
expect(action.get(PDFName.of('S'))).toBe(PDFName.of('URI'))
|
||||
const [link] = await readLinks(bytes)
|
||||
expect(link?.uri).toBe(TIGHT_INJECTION_URL)
|
||||
})
|
||||
|
||||
it('exportFromEnvelope refuses the URL before drawing anything: branding_invalid', async () => {
|
||||
const hostile = clone(envelope)
|
||||
hostile.branding = {
|
||||
...hostile.branding,
|
||||
siteUrl: INJECTION_URL,
|
||||
} as unknown as Branding
|
||||
const recording = recordDrawing()
|
||||
try {
|
||||
const promise = exportFromEnvelope(hostile, reexportOptions())
|
||||
await expect(promise).rejects.toBeInstanceOf(ArchiveExportError)
|
||||
await expect(promise).rejects.toMatchObject({ kind: 'branding_invalid' })
|
||||
expect(recording.texts).toEqual([])
|
||||
expect(recording.images).toEqual([])
|
||||
} finally {
|
||||
recording.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('a credit URL with a parenthesis and a broken label set are refused the same way', async () => {
|
||||
const credit = clone(envelope)
|
||||
credit.branding.partner!.url = 'https://a.example/)'
|
||||
await expect(
|
||||
exportFromEnvelope(credit, reexportOptions()),
|
||||
).rejects.toMatchObject({ kind: 'branding_invalid' })
|
||||
const labels = clone(envelope)
|
||||
delete (labels.labels.fr as Record<string, string>)['pdf.subject']
|
||||
await expect(
|
||||
exportFromEnvelope(labels, reexportOptions()),
|
||||
).rejects.toMatchObject({ kind: 'branding_invalid' })
|
||||
await expect(
|
||||
exportFromEnvelope(clone(envelope), reexportOptions()),
|
||||
).resolves.toMatchObject({ warnings: [] })
|
||||
})
|
||||
})
|
||||
|
||||
interface IhdrFields {
|
||||
depth?: number
|
||||
colourType?: number
|
||||
compression?: number
|
||||
filter?: number
|
||||
interlace?: number
|
||||
}
|
||||
|
||||
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
|
||||
|
||||
/**
|
||||
* A PNG signature and an IHDR chunk announcing `width` × `height`, 8-bit
|
||||
* greyscale non-interlaced unless `fields` says otherwise, nothing after.
|
||||
*/
|
||||
function pngHeader(
|
||||
width: number,
|
||||
height: number,
|
||||
fields: IhdrFields = {},
|
||||
signature = true,
|
||||
): Uint8Array {
|
||||
const bytes = new Uint8Array(33)
|
||||
bytes.set(PNG_SIGNATURE)
|
||||
if (!signature) bytes[3] = 0x48
|
||||
const view = new DataView(bytes.buffer)
|
||||
view.setUint32(8, 13)
|
||||
bytes.set([0x49, 0x48, 0x44, 0x52], 12)
|
||||
view.setUint32(16, width)
|
||||
view.setUint32(20, height)
|
||||
const { depth = 8, colourType = 0, compression = 0 } = fields
|
||||
const { filter = 0, interlace = 0 } = fields
|
||||
bytes.set([depth, colourType, compression, filter, interlace], 24)
|
||||
return bytes
|
||||
}
|
||||
|
||||
/** One chunk: length, four-letter type, `data`, a zero CRC. */
|
||||
function pngChunk(type: string, data: Uint8Array): Uint8Array {
|
||||
const bytes = new Uint8Array(12 + data.byteLength)
|
||||
new DataView(bytes.buffer).setUint32(0, data.byteLength)
|
||||
bytes.set(
|
||||
Array.from(type, (c) => c.charCodeAt(0)),
|
||||
4,
|
||||
)
|
||||
bytes.set(data, 8)
|
||||
return bytes
|
||||
}
|
||||
|
||||
const concat = (...parts: Uint8Array[]): Uint8Array =>
|
||||
Uint8Array.from(Buffer.concat(parts.map((p) => Buffer.from(p))))
|
||||
|
||||
const CHANNELS: Record<number, number> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }
|
||||
|
||||
/** Raw scanlines of a non-interlaced image: a filter byte then the packed samples, per row. */
|
||||
function rawSize(
|
||||
width: number,
|
||||
height: number,
|
||||
fields: IhdrFields = {},
|
||||
): number {
|
||||
const { depth = 8, colourType = 0 } = fields
|
||||
const bitsPerPixel = CHANNELS[colourType]! * depth
|
||||
return (Math.ceil((width * bitsPerPixel) / 8) + 1) * height
|
||||
}
|
||||
|
||||
/** An IDAT chunk holding the zlib stream of `raw`. */
|
||||
const idatOf = (raw: Uint8Array): Uint8Array =>
|
||||
pngChunk('IDAT', deflateSync(raw))
|
||||
|
||||
const IEND = pngChunk('IEND', new Uint8Array(0))
|
||||
/** The IDAT of a 1×1 8-bit greyscale image (2 raw bytes), what `pngHeader(1, 1)` announces. */
|
||||
const IDAT = idatOf(new Uint8Array(2))
|
||||
|
||||
/** A complete valid PNG of zero pixels: header, one IDAT of the exact raw size, IEND. */
|
||||
function validPng(
|
||||
width: number,
|
||||
height: number,
|
||||
fields: IhdrFields = {},
|
||||
): Uint8Array {
|
||||
const raw = new Uint8Array(rawSize(width, height, fields))
|
||||
return concat(pngHeader(width, height, fields), idatOf(raw), IEND)
|
||||
}
|
||||
|
||||
/** A 1×1 header followed by a second IHDR announcing 10000 × 10000, then IEND. */
|
||||
function doubledIhdrPng(): Uint8Array {
|
||||
const second = pngHeader(10_000, 10_000).subarray(8)
|
||||
return concat(pngHeader(1, 1), second, IEND)
|
||||
}
|
||||
|
||||
/**
|
||||
* The auditor's PoC: a valid 1×1 PNG whose IEND is replaced by a `tEXt`
|
||||
* chunk "AAAA" with a non-zero CRC and no NUL byte, so UPNG's `nextZero`
|
||||
* never stops (`ONE_PX_PNG` minus its 12-byte IEND).
|
||||
*/
|
||||
function textWithoutNulPng(): Uint8Array {
|
||||
const text = pngChunk('tEXt', new TextEncoder().encode('AAAA'))
|
||||
text.fill(0xff, text.byteLength - 4)
|
||||
return concat(ONE_PX_PNG.subarray(0, ONE_PX_PNG.byteLength - 12), text)
|
||||
}
|
||||
|
||||
/** The second PoC: an `iTXt` chunk, then an IEND of length 0x010101 with a non-zero payload. */
|
||||
function itxtThenFatIendPng(): Uint8Array {
|
||||
const itxt = pngChunk('iTXt', new TextEncoder().encode('kw'))
|
||||
const fatIend = pngChunk('IEND', new Uint8Array(0x010101).fill(1))
|
||||
return concat(pngHeader(1, 1), IDAT, itxt, fatIend)
|
||||
}
|
||||
|
||||
/**
|
||||
* The third PoC, 77 bytes: 16×16 RGBA, a zlib IDAT cut to 20 bytes, IEND.
|
||||
* Signature and chunk list are sound; UPNG's `inflateRaw` reads past the
|
||||
* end of the stream and never returns.
|
||||
*/
|
||||
function truncatedIdatPng(): Uint8Array {
|
||||
const raw = Uint8Array.from(
|
||||
{ length: rawSize(16, 16, { colourType: 6 }) },
|
||||
(_, i) => i & 0xff,
|
||||
)
|
||||
const stream = deflateSync(raw).subarray(0, 20)
|
||||
const header = pngHeader(16, 16, { colourType: 6 })
|
||||
return concat(header, pngChunk('IDAT', stream), IEND)
|
||||
}
|
||||
|
||||
interface Chunk {
|
||||
type: string
|
||||
data: Uint8Array
|
||||
}
|
||||
|
||||
/** The chunks of a well-formed PNG, in file order, CRCs dropped. */
|
||||
function chunksOf(png: Uint8Array): Chunk[] {
|
||||
const view = new DataView(png.buffer, png.byteOffset, png.byteLength)
|
||||
const chunks: Chunk[] = []
|
||||
let offset = 8
|
||||
while (offset < png.byteLength) {
|
||||
const length = view.getUint32(offset)
|
||||
const type = String.fromCharCode(...png.subarray(offset + 4, offset + 8))
|
||||
chunks.push({ type, data: png.subarray(offset + 8, offset + 8 + length) })
|
||||
offset += 12 + length
|
||||
}
|
||||
return chunks
|
||||
}
|
||||
|
||||
const pngOf = (chunks: Chunk[]): Uint8Array =>
|
||||
concat(
|
||||
Uint8Array.from(PNG_SIGNATURE),
|
||||
...chunks.map((c) => pngChunk(c.type, c.data)),
|
||||
)
|
||||
|
||||
function headerLogoBytes(): Uint8Array {
|
||||
const asset = logosBranding().headerLogo
|
||||
if (asset?.kind !== 'png') throw new Error('png expected')
|
||||
return Uint8Array.from(Buffer.from(asset.base64, 'base64'))
|
||||
}
|
||||
|
||||
/** The real header logo with the last 5 bytes of its IDAT stream removed: the chunk list stays sound. */
|
||||
function cutLogoPng(): Uint8Array {
|
||||
const chunks = chunksOf(headerLogoBytes())
|
||||
const last = chunks.filter((c) => c.type === 'IDAT').at(-1)!
|
||||
last.data = last.data.subarray(0, last.data.byteLength - 5)
|
||||
return pngOf(chunks)
|
||||
}
|
||||
|
||||
describe('PNG budget (MEDIUM)', () => {
|
||||
it.each([
|
||||
['8193 × 1', 8193, 1],
|
||||
['1 × 8193', 1, 8193],
|
||||
['4097 × 4096 (over 4096²)', 4097, 4096],
|
||||
['12000 × 12000 (144 Mpx)', 12_000, 12_000],
|
||||
['0 × 0', 0, 0],
|
||||
['1 × 0', 1, 0],
|
||||
['8192 × 0', 8192, 0],
|
||||
])('%s → dimensions', async (_name, width, height) => {
|
||||
const png = concat(pngHeader(width, height), IEND)
|
||||
expect(await pngIssue(png)).toBe('dimensions')
|
||||
})
|
||||
|
||||
it('the raw-size budget: 16 MiB of scanlines at most, whatever the pixel count', async () => {
|
||||
// 1-bit grey: 513 bytes a row.
|
||||
expect(await pngIssue(validPng(4096, 4096, { depth: 1 }))).toBeNull()
|
||||
expect(await pngIssue(validPng(8192, 2048, { depth: 1 }))).toBeNull()
|
||||
// 8-bit grey: (4095 + 1) × 4096 is exactly 16 MiB, one more row byte is over.
|
||||
expect(await pngIssue(validPng(4095, 4096))).toBeNull()
|
||||
const overByARow = concat(pngHeader(4096, 4096), IEND)
|
||||
expect(await pngIssue(overByARow)).toBe('dimensions')
|
||||
// 8-bit RGBA at 4096²: 67 MB of scanlines, refused before any inflation.
|
||||
const rgba = concat(pngHeader(4096, 4096, { colourType: 6 }), IEND)
|
||||
expect(await pngIssue(rgba)).toBe('dimensions')
|
||||
expect(rawSize(4096, 4096, { colourType: 6 })).toBeGreaterThan(
|
||||
16 * 1024 * 1024,
|
||||
)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['depth 255', { depth: 255 }],
|
||||
['colour type 5', { colourType: 5 }],
|
||||
['interlace 1 (Adam7)', { interlace: 1 }],
|
||||
['filter method 1', { filter: 1 }],
|
||||
['compression method 1', { compression: 1 }],
|
||||
['depth 4 for RGBA', { depth: 4, colourType: 6 }],
|
||||
['depth 16 for a palette', { depth: 16, colourType: 3 }],
|
||||
])('%s → ihdr', async (_name, fields: IhdrFields) => {
|
||||
expect(await pngIssue(validPng(4, 3, fields))).toBe('ihdr')
|
||||
const atTheCap = concat(pngHeader(4096, 4096, fields), IEND)
|
||||
expect(await pngIssue(atTheCap)).toBe('ihdr')
|
||||
})
|
||||
|
||||
it('every colour type and depth the spec allows passes with a matching IDAT', async () => {
|
||||
const allowed: Array<[number, number[]]> = [
|
||||
[0, [1, 2, 4, 8, 16]],
|
||||
[2, [8, 16]],
|
||||
[3, [1, 2, 4, 8]],
|
||||
[4, [8, 16]],
|
||||
[6, [8, 16]],
|
||||
]
|
||||
for (const [colourType, depths] of allowed) {
|
||||
for (const depth of depths) {
|
||||
const png = validPng(5, 3, { depth, colourType })
|
||||
expect(
|
||||
await pngIssue(png),
|
||||
`type ${colourType} depth ${depth}`,
|
||||
).toBeNull()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('an IDAT stream that is truncated, empty, not zlib or off by one raw byte → idat', async () => {
|
||||
const poc = truncatedIdatPng()
|
||||
expect(poc.byteLength).toBe(77)
|
||||
expect(await pngIssue(poc)).toBe('idat')
|
||||
expect(await pngIssue(cutLogoPng())).toBe('idat')
|
||||
expect(await pngIssue(concat(pngHeader(1, 1), IEND))).toBe('idat')
|
||||
const notZlib = pngChunk('IDAT', new Uint8Array(16))
|
||||
expect(await pngIssue(concat(pngHeader(1, 1), notZlib, IEND))).toBe('idat')
|
||||
for (const delta of [1, -1]) {
|
||||
const raw = new Uint8Array(rawSize(4, 3) + delta)
|
||||
const png = concat(pngHeader(4, 3), idatOf(raw), IEND)
|
||||
expect(await pngIssue(png), `off by ${delta}`).toBe('idat')
|
||||
}
|
||||
expect(await pngIssue(validPng(4, 3))).toBeNull()
|
||||
})
|
||||
|
||||
it('the IDAT stream may span several chunks', async () => {
|
||||
const stream = deflateSync(new Uint8Array(rawSize(4, 3)))
|
||||
const split = Math.floor(stream.byteLength / 2)
|
||||
const png = concat(
|
||||
pngHeader(4, 3),
|
||||
pngChunk('IDAT', stream.subarray(0, split)),
|
||||
pngChunk('IDAT', stream.subarray(split)),
|
||||
IEND,
|
||||
)
|
||||
expect(await pngIssue(png)).toBeNull()
|
||||
})
|
||||
|
||||
it('a wrong signature or a truncated header is refused; the real logos pass', async () => {
|
||||
expect(await pngIssue(pngHeader(1, 1, {}, false))).toBe('signature')
|
||||
expect(await pngIssue(pngHeader(1, 1).subarray(0, 20))).toBe('signature')
|
||||
const svg = new TextEncoder().encode('<svg/>')
|
||||
expect(await pngIssue(svg)).toBe('signature')
|
||||
expect(await pngIssue(ONE_PX_PNG)).toBeNull()
|
||||
expect(await pngIssue(TWO_BY_ONE_PNG)).toBeNull()
|
||||
const logos = logosBranding()
|
||||
for (const asset of [
|
||||
logos.headerLogo,
|
||||
logos.footerLogo,
|
||||
logos.poweredBy!.logo,
|
||||
]) {
|
||||
if (asset?.kind !== 'png') throw new Error('png expected')
|
||||
expect(await pngIssue(Buffer.from(asset.base64, 'base64'))).toBeNull()
|
||||
}
|
||||
const touchIcon = readFileSync(resolve(PUBLIC_DIR, 'apple-touch-icon.png'))
|
||||
expect(await pngIssue(new Uint8Array(touchIcon))).toBeNull()
|
||||
})
|
||||
|
||||
it('the chunk walk refuses a second IHDR, an APNG acTL and a length past the buffer', async () => {
|
||||
expect(await pngIssue(doubledIhdrPng())).toBe('chunks')
|
||||
const apng = concat(
|
||||
pngHeader(1, 1),
|
||||
pngChunk('acTL', new Uint8Array(8)),
|
||||
IEND,
|
||||
)
|
||||
expect(await pngIssue(apng)).toBe('chunks')
|
||||
for (const type of ['fcTL', 'fdAT']) {
|
||||
const frame = concat(
|
||||
pngHeader(1, 1),
|
||||
pngChunk(type, new Uint8Array(4)),
|
||||
IEND,
|
||||
)
|
||||
expect(await pngIssue(frame), type).toBe('chunks')
|
||||
}
|
||||
const idat = pngChunk('IDAT', new Uint8Array(16))
|
||||
new DataView(idat.buffer).setUint32(0, 1_000_000)
|
||||
expect(await pngIssue(concat(pngHeader(1, 1), idat))).toBe('chunks')
|
||||
const partialHead = concat(pngHeader(1, 1), new Uint8Array(5))
|
||||
expect(await pngIssue(partialHead)).toBe('chunks')
|
||||
expect(await pngIssue(concat(pngHeader(1, 1), IDAT, IEND))).toBeNull()
|
||||
const shortIhdr = pngHeader(1, 1)
|
||||
new DataView(shortIhdr.buffer).setUint32(8, 12)
|
||||
expect(await pngIssue(shortIhdr)).toBe('signature')
|
||||
})
|
||||
|
||||
it('a chunk UPNG reads with nextZero, or any type outside the allowlist, is refused', async () => {
|
||||
expect(await pngIssue(textWithoutNulPng())).toBe('chunks')
|
||||
expect(await pngIssue(itxtThenFatIendPng())).toBe('chunks')
|
||||
for (const type of ['tIME', 'zTXt', 'iCCP', 'abCD']) {
|
||||
const png = concat(
|
||||
pngHeader(1, 1),
|
||||
IDAT,
|
||||
pngChunk(type, new Uint8Array(7)),
|
||||
IEND,
|
||||
)
|
||||
expect(await pngIssue(png), type).toBe('chunks')
|
||||
}
|
||||
})
|
||||
|
||||
it('the list must end on an empty IEND that closes the buffer; ancillary chunks pass', async () => {
|
||||
const valid = concat(pngHeader(1, 1), IDAT, IEND)
|
||||
expect(await pngIssue(concat(valid, new Uint8Array([0])))).toBe('chunks')
|
||||
expect(await pngIssue(concat(pngHeader(1, 1), IDAT))).toBe('chunks')
|
||||
const fatIend = pngChunk('IEND', new Uint8Array(1))
|
||||
expect(await pngIssue(concat(pngHeader(1, 1), IDAT, fatIend))).toBe(
|
||||
'chunks',
|
||||
)
|
||||
const ancillary = concat(
|
||||
pngHeader(1, 1),
|
||||
pngChunk('gAMA', new Uint8Array(4)),
|
||||
pngChunk('pHYs', new Uint8Array(9)),
|
||||
pngChunk('sRGB', new Uint8Array(1)),
|
||||
IDAT,
|
||||
IEND,
|
||||
)
|
||||
expect(await pngIssue(ancillary)).toBeNull()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['an oversized header logo', () => concat(pngHeader(16_384, 16_384), IEND)],
|
||||
['a doubled-IHDR header logo', doubledIhdrPng],
|
||||
['a tEXt-without-NUL header logo (UPNG would spin)', textWithoutNulPng],
|
||||
[
|
||||
'a truncated-IDAT header logo (UPNG inflateRaw would read past the buffer)',
|
||||
truncatedIdatPng,
|
||||
],
|
||||
['a 1 × 0 header logo', () => concat(pngHeader(1, 0), IDAT, IEND)],
|
||||
])(
|
||||
'%s fails alone with logo_failed and never reaches embedPng',
|
||||
async (_name, make) => {
|
||||
const branding = nologosBranding()
|
||||
const huge = make()
|
||||
branding.headerLogo = {
|
||||
kind: 'png',
|
||||
base64: Buffer.from(huge).toString('base64'),
|
||||
}
|
||||
branding.footerLogo = {
|
||||
kind: 'png',
|
||||
base64: Buffer.from(ONE_PX_PNG).toString('base64'),
|
||||
}
|
||||
// The spy refuses the hostile bytes itself: a regression that lets
|
||||
// them through fails on the assertion below instead of spinning the
|
||||
// worker in UPNG's nextZero or inflateRaw, which no vitest timeout
|
||||
// can interrupt.
|
||||
const realEmbedPng = PDFDocument.prototype.embedPng
|
||||
const embedPng = vi
|
||||
.spyOn(PDFDocument.prototype, 'embedPng')
|
||||
.mockImplementation(function (this: PDFDocument, png) {
|
||||
if (Buffer.from(png as Uint8Array).equals(Buffer.from(huge))) {
|
||||
throw new Error('hostile png reached embedPng')
|
||||
}
|
||||
return realEmbedPng.call(this, png)
|
||||
})
|
||||
try {
|
||||
const { warnings } = await exportReportArchive({
|
||||
...baseInput(golden.reports.demo, golden.snapshots.demo),
|
||||
branding,
|
||||
})
|
||||
expect(warnings).toEqual([{ kind: 'logo_failed', slot: 'headerLogo' }])
|
||||
const base64 = (png: Uint8Array) => Buffer.from(png).toString('base64')
|
||||
const embedded = embedPng.mock.calls.map(([png]) =>
|
||||
base64(png as Uint8Array),
|
||||
)
|
||||
expect(embedded).not.toContain(base64(huge))
|
||||
expect(embedded).toContain(base64(ONE_PX_PNG))
|
||||
} finally {
|
||||
embedPng.mockRestore()
|
||||
}
|
||||
},
|
||||
10_000,
|
||||
)
|
||||
|
||||
it('the real logos reach embedPng when the gate passes them', async () => {
|
||||
const embedPng = vi.spyOn(PDFDocument.prototype, 'embedPng')
|
||||
try {
|
||||
const { warnings } = await exportReportArchive({
|
||||
...baseInput(golden.reports.demo, golden.snapshots.demo),
|
||||
branding: logosBranding(),
|
||||
rasterizer: rasterizerOf('logos'),
|
||||
})
|
||||
expect(warnings).toEqual([])
|
||||
const embedded = embedPng.mock.calls.map(([png]) =>
|
||||
Buffer.from(png as Uint8Array).toString('base64'),
|
||||
)
|
||||
const logos = logosBranding()
|
||||
for (const asset of [logos.headerLogo, logos.footerLogo]) {
|
||||
if (asset?.kind !== 'png') throw new Error('png expected')
|
||||
expect(embedded).toContain(asset.base64)
|
||||
}
|
||||
} finally {
|
||||
embedPng.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,47 +0,0 @@
|
||||
/**
|
||||
* T7 (STEP6 §7): the demo envelope stays well under the attachment cap;
|
||||
* stored (Flate) and raw sizes are printed for both brandings.
|
||||
*/
|
||||
import { beforeAll, describe, expect, it } from 'vitest'
|
||||
import { defaultPdfLabels, exportReportArchive } from '../src'
|
||||
import {
|
||||
brandingOf,
|
||||
FIXED_EXPORTED_AT,
|
||||
rasterizerOf,
|
||||
type LogoMode,
|
||||
} from './helpers/goldens'
|
||||
import { storedAttachmentSize } from './helpers/pdf'
|
||||
import { loadGoldenReports, type GoldenReports } from './helpers/reports'
|
||||
|
||||
const MAX_STORED = 250_000
|
||||
|
||||
let golden: GoldenReports
|
||||
beforeAll(() => {
|
||||
golden = loadGoldenReports()
|
||||
})
|
||||
|
||||
describe('demo envelope size', () => {
|
||||
it.each<LogoMode>(['nologos', 'logos'])(
|
||||
'%s: stored attachment under 250,000 bytes',
|
||||
async (mode) => {
|
||||
const { pdf, envelope } = await exportReportArchive({
|
||||
report: golden.reports.demo,
|
||||
sheet: golden.snapshots.demo,
|
||||
branding: brandingOf(mode),
|
||||
labels: defaultPdfLabels,
|
||||
locale: 'fr',
|
||||
rasterizer: rasterizerOf(mode),
|
||||
exportedAt: FIXED_EXPORTED_AT,
|
||||
})
|
||||
const raw = new TextEncoder().encode(
|
||||
JSON.stringify(envelope, null, 2),
|
||||
).byteLength
|
||||
const stored = storedAttachmentSize(pdf)
|
||||
console.log(
|
||||
`[size] demo ${mode}: stored ${stored} B, raw ${raw} B, pdf ${pdf.byteLength} B`,
|
||||
)
|
||||
expect(stored).toBeLessThan(MAX_STORED)
|
||||
expect(stored).toBeLessThan(raw)
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -1,90 +0,0 @@
|
||||
/**
|
||||
* T9 (STEP6 §15): the WinAnsi canary. One text ingress, so a glyph the
|
||||
* standard fonts cannot encode never reaches pdf-lib; `formatDate` never
|
||||
* throws on user data.
|
||||
*/
|
||||
import { beforeAll, describe, expect, it } from 'vitest'
|
||||
import { PDFDocument, StandardFonts } from 'pdf-lib'
|
||||
import { buildSheetSnapshot } from '@faunosteo/domain'
|
||||
import { defaultPdfLabels, exportReportArchive } from '../src'
|
||||
import { formatDate } from '../src/render/dates'
|
||||
import { wrapLines } from '../src/render/text'
|
||||
import { safeText } from '../src/text'
|
||||
import {
|
||||
FIXED_EXPORTED_AT,
|
||||
nologosBranding,
|
||||
rasterizerOf,
|
||||
recordDrawing,
|
||||
} from './helpers/goldens'
|
||||
import { loadGoldenReports, type GoldenReports } from './helpers/reports'
|
||||
|
||||
let golden: GoldenReports
|
||||
beforeAll(() => {
|
||||
golden = loadGoldenReports()
|
||||
})
|
||||
|
||||
describe('safeText', () => {
|
||||
it('keeps the WinAnsi glyphs the pages use', () => {
|
||||
const kept = 'Fixation (C2–C7) — bilan • zone · Sévérité à l’écu €'
|
||||
expect(safeText(kept)).toBe(kept)
|
||||
})
|
||||
|
||||
it('replaces unencodable glyphs by ? and strips control characters', () => {
|
||||
expect(safeText('⚠ alerte')).toBe('? alerte')
|
||||
expect(safeText('a → b')).toBe('a ? b')
|
||||
expect(safeText('ok 😀')).toBe('ok ?')
|
||||
expect(safeText('a\tb')).toBe('ab')
|
||||
expect(safeText('a
b')).toBe('ab')
|
||||
expect(safeText('a\x1bb')).toBe('ab')
|
||||
})
|
||||
|
||||
it('wrapLines splits on any whitespace first, then makes each word safe', async () => {
|
||||
const doc = await PDFDocument.create()
|
||||
const font = await doc.embedFont(StandardFonts.Helvetica)
|
||||
expect(wrapLines('un\tdeux\ntrois ⚠', font, 10, 1000)).toEqual([
|
||||
'un deux trois ?',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('export with hostile text', () => {
|
||||
it('a report with ⚠ in a comment exports; the glyph prints as ?', async () => {
|
||||
const demo = golden.reports.demo
|
||||
const report = {
|
||||
...demo,
|
||||
observations: [
|
||||
{ ...demo.observations[0]!, comment: 'Attention ⚠ tab\tici → fin' },
|
||||
],
|
||||
conclusion: 'Conclusion ⚠',
|
||||
}
|
||||
const recording = recordDrawing()
|
||||
try {
|
||||
const { warnings } = await exportReportArchive({
|
||||
report,
|
||||
sheet: buildSheetSnapshot(golden.draft, report),
|
||||
branding: nologosBranding(),
|
||||
labels: defaultPdfLabels,
|
||||
locale: 'fr',
|
||||
rasterizer: rasterizerOf('nologos'),
|
||||
exportedAt: FIXED_EXPORTED_AT,
|
||||
})
|
||||
expect(warnings).toEqual([])
|
||||
const drawn = recording.texts.map((t) => t.text)
|
||||
expect(drawn).toContain('Attention ? tab ici ? fin')
|
||||
expect(drawn).toContain('Conclusion ?')
|
||||
expect(drawn.every((t) => safeText(t) === t)).toBe(true)
|
||||
} finally {
|
||||
recording.stop()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatDate', () => {
|
||||
it('formats an ISO date per locale and returns anything else unchanged', () => {
|
||||
expect(formatDate('2026-11-20', 'fr')).toBe('20 novembre 2026')
|
||||
expect(formatDate('2026-11-20', 'en')).toBe('November 20, 2026')
|
||||
expect(formatDate('n/a', 'fr')).toBe('n/a')
|
||||
expect(formatDate('2026-13-45', 'en')).toBe('2026-13-45')
|
||||
expect(formatDate('2026-02-30', 'en')).toBe('2026-02-30')
|
||||
})
|
||||
})
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noImplicitReturns": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"types": ["node", "vitest/globals"],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src", "tests"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: 'node',
|
||||
globals: true,
|
||||
include: ['tests/**/*.test.ts'],
|
||||
},
|
||||
})
|
||||
Reference in new issue
Block a user