Files
faunosteo/packages/core-wasm/tests/preview.test.ts
T
bchanot e823655f09 fix(anatomy): V1-2.2 owner arbitrations on SVG references and bytes
Refuse local references to ids a drawing does not define, scope canvas
ids per view, upload every drawing in one stored form checked by the
verdict and the preview, keep strict numeric rgb() colours, and commit
real Inkscape 1.4.3 exports with their generator.
2026-10-29 16:24:07 +01:00

179 lines
8.5 KiB
TypeScript

/**
* V1-2.2 on the shipped module (contract §8.1, §9.2, §10): the equine draft previews with the
* index, the fingerprint and the canvases of the bundled sheet; hash and fingerprint
* mismatches refuse the build with their closed kind; a draft's document is replaced and
* redrawn; the edit commands run through `call`; every hostile SVG and flood gets a closed
* cleaning answer with no trap. The owner's decisions of 2026-10-29 too: canvases scope their
* ids per view, dangling references and removals that leave a dependent are refused, the
* stored form is what a file uploads, cairo's `rgb()` colours are kept. The Rust suites hold
* the rules; this proves the facade.
*/
import { readFileSync, readdirSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import type { GlueModule } from '../src/index'
import { nodeCoreSource } from '../src/node'
const ROOT = '../../../'
const SEED = `${ROOT}supabase/seed/anatomical-sheets/equine/draft/`
const HOSTILE = `${ROOT}crates/core/tests/fixtures/svg/hostile/`
const HORSE_ID = '7f767f74-3b36-51a7-8465-52dd7e2ead4a'
const HORSE_SHA = '0ea5202fa3b95bac167b87c12ee969ab0272e085b60c2d34dbca6202c5f08541'
const EXPORTS = `${ROOT}crates/core/tests/fixtures/svg/exports/`
const PROLOG = '<?xml version="1.0" encoding="UTF-8"?>\n'
const FINGERPRINT = '12d788727c1e532641bd5b3a7ecf39dbdd25e70350f8a76be5ca917b262874e2'
const path = (p: string) => fileURLToPath(new URL(p, import.meta.url))
const text = (p: string) => readFileSync(path(p), 'utf8')
const documentText = text(`${SEED}document.json`)
const horse = new Uint8Array(readFileSync(path(`${SEED}assets/horse.svg`)))
let glue: GlueModule
beforeAll(async () => {
const source = nodeCoreSource('pkg')
glue = await source.importGlue(0)
await glue.default({ module_or_path: await source.compile() })
})
const value = (envelope: string) => {
const outcome = JSON.parse(envelope)
expect(outcome.ok).toBe(true)
return outcome.value
}
function build(status: string, drawing: Uint8Array | null, fingerprint?: string, doc = documentText) {
const builder = new glue.PreviewBuilder()
if (drawing) builder.add_drawing(HORSE_ID, HORSE_SHA, drawing)
return builder.build(JSON.stringify({ status, document: doc, fingerprint }))
}
function refusal(run: () => unknown): string {
try {
run()
} catch (error) {
return (error as Error).message
}
throw new Error('no refusal')
}
describe('PreviewSheet through the shipped module', () => {
it('previews the equine draft as the bundled sheet', () => {
const preview = build('published', horse, FINGERPRINT)
const state = value(preview.call('preview.state', '{}'))
expect(state.fingerprint).toBe(FINGERPRINT)
expect(state.report.groups).toHaveLength(30)
const handle = new glue.SheetHandle(
JSON.stringify({
status: 'draft',
ref: JSON.parse(text(`${SEED}sheet-ref.json`)),
document: JSON.parse(documentText),
migrationMap: JSON.parse(text(`${SEED}report-migration-map.json`)),
assets: { [HORSE_ID]: new TextDecoder().decode(horse) },
assetHashes: { [HORSE_ID]: HORSE_SHA },
}),
)
const index = value(handle.call('index_data', '{}'))
expect(state.index.main_view_id).toBe(index.mainViewId)
expect(state.index.view_by_id).toEqual(index.viewById)
expect(state.index.annotation_by_id).toEqual(index.annotationById)
expect(state.index.finding_zone_by_id).toEqual(index.findingZoneById)
expect(state.index.names).toEqual(index.names)
expect(state.index.node_keys).toEqual(index.nodeKeys)
for (const viewId of ['main', 'head']) {
const input = JSON.stringify({ viewId })
expect(preview.call('view.canvas', input)).toBe(handle.call('view.canvas', input))
const svg: string = value(preview.call('view.canvas', input)).svg
const ids = [...svg.matchAll(/ id="([^"]*)"/g)].map((m) => m[1])
expect(ids.length).toBeGreaterThan(100)
expect(ids.every((id) => id.startsWith(`fv.${viewId}.`))).toBe(true)
const refs = [...svg.matchAll(/(?:href="#|url\(#)([^")]*)/g)].map((m) => m[1])
expect(refs.every((ref) => ids.includes(ref))).toBe(true)
}
handle.free()
preview.free()
})
it('refuses a hash or a fingerprint mismatch with its closed kind', () => {
const altered = horse.slice()
altered[200] ^= 1
expect(refusal(() => build('draft', altered))).toBe(`drawing_hash_mismatch: ${HORSE_ID}`)
expect(refusal(() => build('published', horse, 'a'.repeat(64)))).toBe('fingerprint_mismatch: ')
expect(refusal(() => build('deprecated', null, FINGERPRINT))).toBe(`drawing_missing: ${HORSE_ID}`)
expect(refusal(() => build('draft', horse, undefined, '{'))).toMatch(/^invalid_document: /)
})
it('replaces a draft document and redraws it', () => {
const draft = build('draft', horse)
const before = draft.call('view.canvas', '{"viewId":"main"}')
const edited = JSON.parse(documentText)
edited.annotations = edited.annotations.slice(0, 2)
expect(draft.replace_document(JSON.stringify(edited))).toBe('{"ok":true,"value":null}')
const after = draft.call('view.canvas', '{"viewId":"main"}')
expect(value(after).svg).not.toBe(value(before).svg)
expect(value(draft.call('preview.state', '{}')).document.annotations).toHaveLength(2)
const published = build('published', horse, FINGERPRINT)
expect(JSON.parse(published.replace_document(documentText)).kind).toBe('read_only')
draft.free()
published.free()
})
it('runs the edit commands and lists dependents', () => {
const document = JSON.parse(documentText)
const id = document.annotations[0].id
const command = { op: 'remove', key: { kind: 'annotation', id } }
const edited = value(glue.call('sheet.edit', JSON.stringify({ document, command })))
expect(edited.document.annotations).toHaveLength(document.annotations.length - 1)
const unknown = JSON.parse(
glue.call('sheet.edit', JSON.stringify({ document, command: { op: 'remove', key: { kind: 'annotation', id: 'zz' } } })),
)
expect(unknown.kind).toBe('unknown_key')
const head = value(
glue.call('sheet.dependents', JSON.stringify({ document, key: { kind: 'view', id: 'head' } })),
)
expect(head.dependents.length).toBeGreaterThan(0)
const named = JSON.parse(
glue.call('sheet.edit', JSON.stringify({ document, command: { op: 'remove', key: { kind: 'view', id: 'head' } } })),
)
expect(named.kind).toBe('has_dependents')
})
})
describe('clean_svg through the shipped module', () => {
it('answers every hostile file and flood with a closed outcome, no trap', () => {
const encoder = new TextEncoder()
const files = readdirSync(path(HOSTILE)).filter((f) => f.endsWith('.svg'))
const floods = {
'deep 99,000 levels': `<svg xmlns="http://www.w3.org/2000/svg">${'<g>'.repeat(99_000)}`,
'nodes 20,001': `<svg xmlns="http://www.w3.org/2000/svg">${'<path/>'.repeat(20_000)}</svg>`,
'bytes 2 MiB + 1': `<svg xmlns="http://www.w3.org/2000/svg"><!--${'x'.repeat(2 * 1024 * 1024)}--></svg>`,
}
const inputs: [string, Uint8Array][] = [
...files.map((f): [string, Uint8Array] => [f, new Uint8Array(readFileSync(path(`${HOSTILE}${f}`)))]),
...Object.entries(floods).map(([name, svg]): [string, Uint8Array] => [name, encoder.encode(svg)]),
]
let slowest = 0
for (const [name, bytes] of inputs) {
const started = performance.now()
const cleaning = value(glue.clean_svg(bytes))
slowest = Math.max(slowest, performance.now() - started)
expect(['clean', 'cleanable', 'rejected'], name).toContain(cleaning.outcome)
}
expect(value(glue.clean_svg(new Uint8Array(readFileSync(path(`${HOSTILE}script.svg`))))).reason).toBe(
'svg_active_content',
)
const cleanHorse = value(glue.clean_svg(horse))
expect([cleanHorse.outcome, cleanHorse.sha256]).toEqual(['clean', HORSE_SHA])
expect(cleanHorse.stored).toBe(new TextDecoder().decode(horse))
const dangling = new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"><use href="#nope"/></svg>')
expect(value(glue.clean_svg(dangling)).reason).toBe('dangling_reference')
const cairo = value(
glue.clean_svg(new Uint8Array(readFileSync(path(`${EXPORTS}cairo-1.18.4-pycairo-1.27.0-shapes.svg`)))),
)
expect([cairo.outcome, cairo.removed]).toEqual(['clean', []])
expect(cairo.stored.startsWith(PROLOG) && cairo.stored.includes('fill="rgb(20%, 40%, 70%)"')).toBe(true)
console.info(`[core-wasm] clean_svg: ${inputs.length} inputs, slowest ${slowest.toFixed(1)} ms`)
expect(glue.core_version()).toMatch(/^\d+\.\d+\.\d+$/)
})
})