Files
faunosteo/packages/anatomy/tests/r5.markdown-sweep-oracles.test.ts
T

307 lines
8.0 KiB
TypeScript

/**
* R5.4 freeze (final gates, 2026-10-23): what Prettier's Markdown printer does to authored text
* in the two draft reports. The port reproduces only the table alignment and refuses the text
* Prettier would rewrite; this sweep, written by the TypeScript, holds it to that: every probe
* (a special character in six positions, whitespace patterns, Markdown constructs) is placed
* in a change title, rationale and question, a cited reference and a changed label, and the
* sha256 of the raw and formatted CHANGELOG and REVIEW-REPORT are frozen (400 of the probes
* come from a seeded generator, so unknown classes surface on their own; eight pairs open a
* construct in one field and close it in the question). `MAKE_R5_ORACLES=1` writes
* crates/core/tests/oracles/r5/markdown-sweep.json.
*/
import { createHash } from 'node:crypto'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import {
applyChangeset,
buildReportMigrationMap,
ChangesetSchema,
documentStats,
renderChangelog,
renderReviewReport,
} from '../src'
import { changeSummary } from '../src/curation/schema'
import { formatMarkdown } from '../src/format'
import { MINI_REFERENCES, miniSheet } from './fixtures/mini-sheet'
const HERE = dirname(fileURLToPath(import.meta.url))
function sha256(text: string): string {
return createHash('sha256').update(text, 'utf8').digest('hex')
}
const OUT = resolve(HERE, '../../../crates/core/tests/oracles/r5')
const MAKE = process.env.MAKE_R5_ORACLES === '1'
const LEGACY_ID_MAP = {
views: { head: 'head' },
annotations: { 'legacy-hip': 'hip', 'legacy-neck': 'neck' },
categories: {},
finding_nodes: {},
assets: {},
}
const CHARACTERS = [...'*_~\\`<>&[]!#$|+=^{}"\'%@:;?/()-.,’‘“”×≤≥±→–—…«»°≠']
function positions(c: string): string[] {
return [c, `${c}x`, `x${c}`, `a ${c} b`, `a${c}b`, `${c}${c}`]
}
const PATTERNS = [
'a b',
'a\tb',
' a',
'a ',
'a\nb',
'a\rb',
'a\n\nb',
'*important*',
'**gras**',
'a **b c** d',
'a**b**c',
'__init__ et _x',
'to_confirm',
'`code`',
'``double``',
'a\\|b',
'a|b',
'<b>gras</b>',
'[lien](https://example.org/x)',
'[a](<b>)',
'[a]( b )',
'[a](b "t")',
'[a](b (t))',
'[a](b&amp;c)',
'[a](b\\)c)',
'[a](https://x.org/a(b)c)',
']( )',
'![img](x.png)',
'[a][b]',
'<http://a&amp;b>',
'<https://example.org/x>',
'<a@b.co>',
'[[ a ]]',
'[[a]]',
'&#42;',
'&ast;',
'&#x2A;',
'&#95;',
'&lowbar;',
'&eacute;',
'doi 10.1/x<0697:toih>2.0',
'中_中',
'ア_ア',
'한_한',
'é_é',
'[a]( https://x.org )',
'**a****b**',
'\\**a**',
'x_**a**',
'**a**_x',
'** **',
'**Total**',
'(**a**)',
'a **b** c',
'Voir_https://example.org/x',
'Voir_www.example.org',
'https://x.org/**a **',
'https://x.org/a_b',
'Lien https://x.org/a_b fin',
'a\u00a0b',
'a\u2003b',
'a\u3000b',
'中文',
'مرحبا',
'e\u0301',
'Mesure a_b `c_`',
'Champ snake_case, voir x_y fin',
'to_do',
'voir [a `](b)` c',
'voir https://x.org/`<a`',
'a &#42 b',
'&#x2A',
'&#95',
'a&#95b',
'&lt x &',
'&#65 x &',
'![a\\"b]',
'![a|b]',
'![&amp]',
'![x]',
'[[ a [[b]]',
'[[a]] [[ b [[c]]',
'a & b',
'A&B',
'x &',
'https://x.org/?a=1&pid=2',
'https://x.org/?a=1&lt=2',
'https://x.org/?a&not=2',
'https://x.org/?a=1&amp=2',
'https://x.org/?a=1&copyx=2',
'&amp;',
'# titre',
'1. item',
'- item',
'> citation',
'Carmalt 2013 (≠ « palpation »), 3 %, 40 °C',
'a = b; c ? d : e',
'{"fr":"x"}',
'é ü ß ø Ω 中',
]
/** A seeded generator (a 32-bit LCG): the random probes are the same on every run. */
function randomProbes(count: number): string[] {
const alphabet = [
...'ab_*\\`[]()<>&#!~ :/.|"é中=;',
'&#',
'&amp',
'&lt',
'![',
'[[',
']]',
'https://',
'www.',
'**',
'\n',
'\u00a0',
]
let state = 20261023
const next = () => {
state = (Math.imul(state, 1664525) + 1013904223) >>> 0
return state
}
const out: string[] = []
for (let i = 0; i < count; i += 1) {
const length = 2 + (next() % 10)
let text = ''
for (let j = 0; j < length; j += 1)
text += alphabet[next() % alphabet.length]
out.push(text)
}
return out
}
function probes(): string[] {
return [...CHARACTERS.flatMap(positions), ...PATTERNS, ...randomProbes(400)]
}
/** Openers in the title, the rationale and every other field, closers in the question. */
const SPLIT = [
['[[', ']]'],
['[[ a', 'b ]]'],
['[[a', 'b]]'],
['{%', '%}'],
['[x', '](y)'],
['*a', 'b*'],
['_a', 'b_'],
['<b', '>'],
]
function changesFile(probe: string, referenceId: string, closer = probe) {
return {
changes: [
{
id: 'CHG-001',
level: 'C',
kind: 'correction',
title: { fr: `Titre ${probe}`, en: 'Title' },
rationale: `Raison ${probe} fin.`,
reference_ids: [],
question: `Question ${closer} ?`,
ops: [
{
op: 'add',
target: 'document',
field: 'references',
value: {
id: referenceId,
type: 'web',
citation: `Citation ${probe}`,
url: null,
doi: null,
},
},
{
op: 'cite',
target: 'finding:hip/hip-dysfunctions/mobility',
reference_ids: [referenceId],
},
{
op: 'set',
target: 'finding:hip/hip-dysfunctions/mobility',
field: 'name.en',
value: `Label ${probe}`,
},
{
op: 'set',
target: 'finding:hip/hip-dysfunctions/mobility/flexion',
field: 'name.fr',
value: probe,
},
],
},
],
}
}
async function run(probe: string, referenceId = 'probe_ref', closer = probe) {
const file = changesFile(probe, referenceId, closer)
const changeset = ChangesetSchema.parse(file)
const baseline = miniSheet()
const result = applyChangeset(baseline, MINI_REFERENCES, changeset)
const before = documentStats(baseline)
const after = documentStats(result.document)
const migration = buildReportMigrationMap({
baseline: miniSheet() as never,
final: result.document as never,
legacyIdMap: LEGACY_ID_MAP,
records: result.records,
sheet: { sheetId: 's', versionId: null, documentSha256: '0'.repeat(64) },
mainViewId: 'main',
})
const changelogRaw = renderChangelog(result, before, after, migration.stats)
const reviewRaw = renderReviewReport({
changes: changeset.changes.map(changeSummary),
records: result.records,
document: result.document,
statsBefore: before,
legacyAnomalies: [],
})
return {
probe: closer === probe ? probe : `${probe}|${closer}`,
reference_id: referenceId,
changes_file: file,
changelog_raw_sha256: sha256(changelogRaw),
changelog_sha256: sha256(await formatMarkdown(changelogRaw)),
review_raw_sha256: sha256(reviewRaw),
review_sha256: sha256(await formatMarkdown(reviewRaw)),
}
}
describe('R5.4 Markdown sweep oracle', () => {
it('markdown-sweep.json', async () => {
const rows = []
for (const probe of probes()) rows.push(await run(probe))
// A cited id ending with `_` puts a closing underscore in a generated code span.
for (const probe of ['to_do', 'a_b c', 'x'])
rows.push(await run(probe, 'probe_ref_'))
// A construct opened in one field and closed in another of the same line.
for (const [opener, closer] of SPLIT)
rows.push(await run(opener, 'probe_ref', closer))
const oracle = {
baseline: miniSheet(),
references: MINI_REFERENCES,
legacy_id_map: LEGACY_ID_MAP,
cases: rows,
}
const text = `${JSON.stringify(oracle)}\n`
const file = resolve(OUT, 'markdown-sweep.json')
if (MAKE) {
mkdirSync(OUT, { recursive: true })
writeFileSync(file, text)
}
expect(text).toBe(readFileSync(file, 'utf8'))
}, 120_000)
})