Consumers now fed by the core (crates/core through @faunosteo/core-wasm):
- the sheet: the bundled payload is parsed and indexed by the core
(SheetHandle, SheetIndexData); SheetIndex reads precomputed tables only;
- the store: new report, add / remove / move observation, draft restore
(v2 migration + rebase) through the core, actions answering { ok };
- the editor click chain (zone.click), laterality and vertebra pickers
(zone.add_sides, vertebra.initial / sync / select), the findings picker
(finding.toggle by clicked leaf position), zone removal;
- the import: engine byte scan (TypeScript until R4), then the core's
layered reading and rebase in one call; the export: the core builds the
sheet snapshot, the frozen TypeScript engine writes the PDF (R4).
Lazy core: Home and the new-report form read the sheet availability from
the bundle and load the module on import / submit only; the auth shell
never references it. Degraded states (core_unavailable, invalid_sheet)
show the validated notice with a retry and never redirect or touch the
draft; an unreadable draft or archive is set aside under
osteo:quarantine:* (only content kinds; a failed write keeps it in place
and the editor stays), a rebase that flags items keeps the raw pre-rebase
draft. Four strings, wording validated by the owner.
Deleted: services/zoneInteraction.ts and its suite (13 cases ported to
cargo), the TypeScript Finding builder and vertebra selection rules of the
pickers, store rules, persistence parsing, hydrateReport. ESLint forbids
@faunosteo/domain in apps/app/src; the report:compare CLI keeps the frozen
domain until R4 (scripts/compare/sheet.ts). App suite 313/313 on the real
core (24 new tests: quarantine, degraded editor, core failures, N-1
reader); step6 goldens and the frozen envelopes unchanged.
159 lines
5.4 KiB
TypeScript
159 lines
5.4 KiB
TypeScript
/**
|
|
* Archive check: reads the report attached to one or more Faunosteo PDFs and
|
|
* prints it next to its v3 reading on the bundled reference sheet.
|
|
*
|
|
* pnpm report:compare <file.pdf | folder>... [--summary] [--full]
|
|
* [--locale fr|en] [--diff a.pdf b.pdf]
|
|
*
|
|
* A v2 archive PDF is shown legacy id → canonical id, line by line; a v3 PDF
|
|
* is checked against the sheet. Items the sheet cannot place are marked
|
|
* `!! UNRESOLVED` with the reason. `--diff` compares the v3 content of two
|
|
* PDFs (an archive and its re-export after import, typically). By default
|
|
* only identifiers, catalog labels, counts and placeholders are printed and
|
|
* compared (a text shows as `conclusion (present)`); names and free texts,
|
|
* printed and compared, need `--full`.
|
|
* Untrusted strings are printed with control characters escaped. It writes
|
|
* no output file.
|
|
*/
|
|
import { readFileSync, readdirSync, statSync } from 'node:fs'
|
|
import { basename, join, resolve } from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
import {
|
|
readArchiveDocument,
|
|
UnsupportedReportVersionError,
|
|
} from '@faunosteo/domain'
|
|
import {
|
|
ArchiveReadError,
|
|
MAX_PDF_BYTES,
|
|
readAttachedDocument,
|
|
} from '@faunosteo/pdf'
|
|
import { compareSheetIndex, type CompareSheetIndex } from './compare/sheet'
|
|
import {
|
|
compareReport,
|
|
diffLines,
|
|
esc,
|
|
parseArgs,
|
|
renderComparison,
|
|
renderSummary,
|
|
type CliArgs,
|
|
type Comparison,
|
|
} from './compare/report'
|
|
|
|
const SEED_DIR = resolve(
|
|
fileURLToPath(import.meta.url),
|
|
'../../../../supabase/seed/anatomical-sheets/equine/draft',
|
|
)
|
|
/** pnpm runs the script from apps/app; paths are typed from the caller's folder. */
|
|
const CWD = process.env.INIT_CWD ?? process.cwd()
|
|
|
|
function loadSheet(): CompareSheetIndex {
|
|
const json = (name: string) =>
|
|
JSON.parse(readFileSync(join(SEED_DIR, name), 'utf8')) as never
|
|
// The comparison needs the document and the map, not the drawings.
|
|
return compareSheetIndex({
|
|
ref: json('sheet-ref.json'),
|
|
document: json('document.json'),
|
|
migrationMap: json('report-migration-map.json'),
|
|
})
|
|
}
|
|
|
|
/** A folder stands for its PDFs; any other argument stays one entry. */
|
|
function expandArg(arg: string): string[] {
|
|
const path = resolve(CWD, arg)
|
|
try {
|
|
if (!statSync(path).isDirectory()) return [path]
|
|
} catch {
|
|
return [path] // reported as a failed entry by compareFile
|
|
}
|
|
return readdirSync(path)
|
|
.filter((f) => f.toLowerCase().endsWith('.pdf'))
|
|
.sort()
|
|
.map((f) => join(path, f))
|
|
}
|
|
|
|
async function compareFile(
|
|
path: string,
|
|
sheet: CompareSheetIndex,
|
|
args: CliArgs,
|
|
): Promise<Comparison> {
|
|
const st = statSync(path)
|
|
if (!st.isFile()) throw new Error('not a regular file')
|
|
if (st.size > MAX_PDF_BYTES) throw new Error('file too large')
|
|
const bytes = new Uint8Array(readFileSync(path))
|
|
// Byte-scan reader (BLK-009): the PDF object graph is never parsed here.
|
|
const raw = await readAttachedDocument(bytes)
|
|
try {
|
|
const outcome = readArchiveDocument(raw, sheet.sheet.migrationMap)
|
|
return compareReport(raw, outcome, sheet, args)
|
|
} catch (err) {
|
|
if (err instanceof UnsupportedReportVersionError) {
|
|
// The version is a number or null: nothing of the attachment is echoed.
|
|
throw new Error(`report version ${err.foundVersion} cannot be read`)
|
|
}
|
|
throw err
|
|
}
|
|
}
|
|
|
|
/** The engine's typed read failures, worded without echoing the file. */
|
|
const READ_FAILURES: Record<ArchiveReadError['kind'], string> = {
|
|
invalid_pdf: 'not a readable PDF',
|
|
no_attachment: 'no Faunosteo attachment found',
|
|
attachment_stripped:
|
|
'attachment stripped (the PDF is stamped as a Faunosteo archive)',
|
|
incompatible_version: 'report version cannot be read',
|
|
}
|
|
|
|
/** A missing or unreadable file is a failed entry, not a crash. */
|
|
function failureReason(err: unknown): string {
|
|
const code = (err as NodeJS.ErrnoException | undefined)?.code
|
|
if (code === 'ENOENT') return 'file not found'
|
|
if (code === 'EACCES') return 'file not readable'
|
|
if (err instanceof ArchiveReadError) return READ_FAILURES[err.kind]
|
|
// JSON.parse messages echo a fragment of the attachment.
|
|
if (err instanceof SyntaxError) return 'attachment is not valid JSON'
|
|
return err instanceof Error ? err.message : String(err)
|
|
}
|
|
|
|
async function main(argv: string[]): Promise<number> {
|
|
const args = parseArgs(argv)
|
|
const files = args.files.flatMap(expandArg)
|
|
if (files.length === 0 || (args.diff && files.length !== 2)) {
|
|
console.error(
|
|
'usage: pnpm report:compare <file.pdf | folder>... [--summary] [--full] [--locale fr|en] [--diff a.pdf b.pdf]',
|
|
)
|
|
return 1
|
|
}
|
|
const sheet = loadSheet()
|
|
const results: Comparison[] = []
|
|
let failures = 0
|
|
for (const file of files) {
|
|
const name = esc(basename(file))
|
|
try {
|
|
const c = await compareFile(file, sheet, args)
|
|
results.push(c)
|
|
if (!args.diff) {
|
|
const lines = args.summary
|
|
? [renderSummary(name, c)]
|
|
: [...renderComparison(name, c), '']
|
|
console.log(lines.join('\n'))
|
|
}
|
|
} catch (err) {
|
|
failures += 1
|
|
console.log(`!! ${name}: ${esc(failureReason(err))}`)
|
|
}
|
|
}
|
|
if (args.diff && results.length === 2) {
|
|
const diff = diffLines(results[0]!.normalized, results[1]!.normalized)
|
|
console.log(diff.length ? diff.join('\n') : 'identical v3 content')
|
|
}
|
|
return failures ? 2 : 0
|
|
}
|
|
|
|
main(process.argv.slice(2)).then(
|
|
(code) => process.exit(code),
|
|
(err) => {
|
|
console.error(esc(err instanceof Error ? err.message : String(err)))
|
|
process.exit(1)
|
|
},
|
|
)
|