// fidelity.test.mjs — gates L1, L2 and L3 (spec §7), over every body in // Go's golden file (MAPA_GOLDEN points them at another, as make // corpus-local does). // // L3's Go half: the bodies L3 saves, with the blocks the document held, // are written to internal/mapa/markup/testdata/editor.json, which // markup's TestEditorBodies parses with Go's Parse. This test fails when // that file is stale; make editor-golden rewrites it. import { test } from 'node:test' import assert from 'node:assert/strict' import { createHash } from 'node:crypto' import { readFileSync, writeFileSync } from 'node:fs' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { TextSelection } from 'prosemirror-state' import { undo, redo, undoDepth } from 'prosemirror-history' import { splitBlock, joinBackward } from 'prosemirror-commands' import { splitListItem, sinkListItem, liftListItem } from 'prosemirror-schema-list' import { corpus, random, schema, editor, localCorpus } from './testkit.mjs' import { parse, cleanBody, Rule, Item, Code, isFence } from './markup.mjs' import { fromBlocks } from './fromMarkdown.mjs' import { docBlocks, serialise, serialiseDetailed, structureCheck, sameNode, bareNode, fenceClosed, joinSeam } from './serialize.mjs' import { mount, settle, rebuild, prepareSave } from './fidelity.mjs' import { copyData, pasteTransaction } from './clipboard.mjs' import { linkable, linkSelection, pageLinkSource, readsBack } from './pagelink.mjs' import { dateInsertion } from './commands.mjs' const here = dirname(fileURLToPath(import.meta.url)) const editorGolden = join(here, '..', 'internal', 'mapa', 'markup', 'testdata', 'editor.json') // MAPA_L3_ONLY narrows the gates to bodies whose name starts with it, // for working on one case; the editor golden file is then not compared. const only = process.env.MAPA_L3_ONLY const bodies = corpus().filter(({ name }) => !only || name.startsWith(only)) function report (failed, of) { assert.equal(failed.length, 0, `${failed.length} of ${of} differ:\n${failed.slice(0, 5).join('\n\n')}`) } // each runs check on every body and collects the failures by name. function each (check) { const failed = [] for (const body of bodies) { try { check(body) } catch (error) { failed.push(`${body.name}: ${error.stack.split('\n').slice(0, 3).join('\n')}`) } } return failed } test('L1: mounting then serialising gives cleanBody(body), byte for byte', t => { report(each(({ body }) => { const { doc, fidelity } = mount(schema, body) assert.equal(serialise(doc, fidelity), cleanBody(body)) }), bodies.length) t.diagnostic(`${bodies.length} bodies`) }) test('L1: mounting a stored body adds nothing, and saving it writes nothing new', () => { report(each(({ body }) => { const stored = cleanBody(body) const { view, fidelity } = editor(stored) // The rules that run after every edit change nothing on a mounted // document (only edited blocks are reparsed). assert.ok(settle(view.state, fidelity, view.state.doc) === null, 'settle changes nothing') const check = structureCheck(view.state.doc, fidelity) assert.ok(check.ok, 'the structure check passes') assert.equal(check.body, stored) }), bodies.length) }) // childBlocks maps each top-level node to the blocks it holds. function childBlocks (doc) { const blocks = docBlocks(doc) const children = [] doc.forEach((node, offset) => { children.push({ node, offset, blocks: blocks.filter(block => block.pos >= offset && block.pos < offset + node.nodeSize) }) }) // The trailing paragraph mounting adds holds no block of the body. const last = children[children.length - 1] if (last && last.node.content.size === 0 && last.node.type.name === 'paragraph') children.pop() return children } function undoAll (view) { while (undoDepth(view.state) > 0) { if (!view.run(undo)) throw new Error('undo did not apply') } } test('L2: one edited block changes only that block\'s bytes; undo gives the body back', t => { let edits = 0 report(each(({ name, body }) => { const stored = cleanBody(body) const parsed = parse(stored) if (parsed.length === 0) return const rng = random(`L2 ${name}`) const { view, fidelity } = editor(stored) const blocks = docBlocks(view.state.doc) .filter(block => block.kind !== Rule && !isFence(block.kind) && block.index < parsed.length) if (blocks.length === 0) return const block = rng.pick(blocks) const pos = block.pos + 1 + rng.int(block.node.content.size + 1) view.dispatch(view.state.tr.insertText('x', pos)) const after = serialise(view.state.doc, fidelity) const { from, to } = parsed[block.index] // An edit that would make text lines read as a column layout // neutralises them, wherever they are (spec D16): not local. const neutralised = after.split('\u200b').length > stored.split('\u200b').length assert.ok(neutralised || after.startsWith(stored.slice(0, from)), 'the bytes before the block are kept') assert.ok(neutralised || after.endsWith(stored.slice(to)), 'the bytes after the block are kept') assert.notEqual(after, stored) edits++ undoAll(view) assert.equal(serialise(view.state.doc, fidelity), stored, 'undo gives the body back') }), bodies.length) t.diagnostic(`${edits} single-block edits`) }) test('L2: inserting or deleting a block changes bytes only at the new seams, by Join', t => { let inserts = 0 let deletes = 0 report(each(({ name, body }) => { const stored = cleanBody(body) const parsed = parse(stored) const rng = random(`L2 seams ${name}`) const sourceOf = block => parsed[block.index] { const { view, fidelity } = editor(stored) const children = childBlocks(view.state.doc) const gap = rng.int(children.length + 1) const before = children[gap - 1]?.blocks.at(-1) const next = children[gap]?.blocks[0] // A fence that runs to the end is closed when something follows it: // the one case where an insert rewrites a neighbour (step 5). if (!(before?.kind === Code && !fenceClosed(sourceOf(before).source))) { const at = gap < children.length ? children[gap].offset : (children.length ? children[gap - 1].offset + children[gap - 1].node.nodeSize : 0) view.dispatch(view.state.tr.insert(at, schema.nodes.paragraph.create(null, schema.text('new')))) const want = (before ? stored.slice(0, sourceOf(before).to) + '\n\n' : '') + 'new' + (next ? '\n\n' + stored.slice(sourceOf(next).from) : '') assert.equal(serialise(view.state.doc, fidelity), cleanBody(want), 'insert') inserts++ undoAll(view) assert.equal(serialise(view.state.doc, fidelity), stored, 'undo the insert') } } { const { view, fidelity } = editor(stored) const children = childBlocks(view.state.doc) const single = children.map((child, index) => index) .filter(index => children[index].blocks.length === 1 && children[index].blocks[0].kind !== Item) if (single.length === 0) return const index = rng.pick(single) const before = children[index - 1]?.blocks.at(-1) const next = children[index + 1]?.blocks[0] // Two lists brought together nest by indent; an indented item would // move under the list above, so its indent is rewritten (§6.3). if (before?.kind === Item && next?.kind === Item && sourceOf(next).level > 0) return const child = children[index] view.dispatch(view.state.tr.delete(child.offset, child.offset + child.node.nodeSize)) const want = before && next ? stored.slice(0, sourceOf(before).to) + joinSeam(before.kind, next.kind) + stored.slice(sourceOf(next).from) : before ? stored.slice(0, sourceOf(before).to) : next ? stored.slice(sourceOf(next).from) : '' assert.equal(serialise(view.state.doc, fidelity), cleanBody(want), 'delete') deletes++ undoAll(view) assert.equal(serialise(view.state.doc, fidelity), stored, 'undo the delete') } }), bodies.length) t.diagnostic(`${inserts} inserts, ${deletes} deletes`) }) // L3's edits. Each takes the editor and the generator and dispatches at // most a few transactions; a command that does not apply does nothing. function textblocks (doc, { code = true } = {}) { const out = [] doc.descendants((node, pos) => { if (node.isTextblock) { if (code || node.type.name !== 'code_block') out.push({ node, pos }) return false } }) return out } function somewhere (rng, doc, options) { const blocks = textblocks(doc, options) if (blocks.length === 0) return null const { node, pos } = rng.pick(blocks) return { node, pos, at: pos + 1 + rng.int(node.content.size + 1) } } function caret (view, pos, head = pos) { view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, pos, head))) } const typed = ['a', 'word ', ' ', '*', '**', '`', '- ', '# ', '> ', '1. ', '[[Acme]]', '[x](https://x.y)', ' ^ab', '~~~', '```', '---', 'é', '👋', '[ ] ', '|'] function someRange (rng, doc) { const one = somewhere(rng, doc) const two = somewhere(rng, doc) if (!one || !two) return null return [Math.min(one.at, two.at), Math.max(one.at, two.at)] } const edits = { type (view, rng) { const place = somewhere(rng, view.state.doc) if (!place) return if (rng() < 0.2) { if (place.node.type.name === 'code_block') view.dispatch(view.state.tr.insertText('\n', place.at)) else view.dispatch(view.state.tr.insert(place.at, schema.nodes.hard_break.create())) return } view.dispatch(view.state.tr.insertText(rng.pick(typed), place.at)) }, mark (view, rng) { const place = somewhere(rng, view.state.doc, { code: false }) if (!place || place.node.content.size === 0) return const from = place.pos + 1 + rng.int(place.node.content.size) const to = from + 1 + rng.int(place.pos + 1 + place.node.content.size - from) const mark = schema.marks[rng.pick(['em', 'strong', 'code', 'em', 'strong'])].create() view.dispatch(rng() < 0.7 ? view.state.tr.addMark(from, to, mark) : view.state.tr.removeMark(from, to, mark.type)) }, split (view, rng) { const place = somewhere(rng, view.state.doc) if (!place) return caret(view, place.at) view.run(splitListItem(schema.nodes.list_item)) || view.run(splitBlock) }, join (view, rng) { const place = somewhere(rng, view.state.doc) if (!place) return caret(view, place.pos + 1) view.run(joinBackward) }, move (view, rng) { const items = docBlocks(view.state.doc).filter(block => block.kind === Item) if (items.length === 0) return const item = rng.pick(items) caret(view, item.pos + 1) view.run(rng() < 0.5 ? sinkListItem(schema.nodes.list_item) : liftListItem(schema.nodes.list_item)) }, chip (view, rng) { const place = somewhere(rng, view.state.doc, { code: false }) if (!place) return const chip = rng.pick([ () => schema.nodes.wikilink.create({ target: rng.pick(['Acme', 'Halden Robotics']) }), () => schema.nodes.wikilink.create({ target: 'Acme', anchor: 'b1', shown: 'that' }), () => schema.nodes.datelink.create({ date: '2026-11-12' }), () => schema.nodes.embed.create({ ref: 'fichas:c1' }) ])() view.dispatch(view.state.tr.insert(place.at, chip)) }, // Images (images spec §2.3): insert, move and edit the alt text of an // image atom. unchip removes one; paste carries the corpus's images. image (view, rng) { const place = somewhere(rng, view.state.doc, { code: false }) if (!place) return const id = rng.pick(['a1', 'k9', '2kq9xw3m1ab', 'z13']) const alt = rng.pick(['', 'a whiteboard', 'a *b* `c`', 'é'.repeat(20)]) view.dispatch(view.state.tr.insert(place.at, schema.nodes.image.create({ id, alt }))) }, moveImage (view, rng) { const found = images(view.state.doc) if (found.length === 0) return const { node, pos } = rng.pick(found) const tr = view.state.tr.delete(pos, pos + 1) const place = somewhere(rng, tr.doc, { code: false }) if (!place) return view.dispatch(tr.insert(place.at, node)) }, alt (view, rng) { const found = images(view.state.doc) if (found.length === 0) return const { pos } = rng.pick(found) const alt = rng.pick(['', 'changed', 'two words', '**bold** words']) view.dispatch(view.state.tr.setNodeAttribute(pos, 'alt', alt)) }, unchip (view, rng) { const atoms = [] view.state.doc.descendants((node, pos) => { if (node.isAtom && node.isInline) atoms.push(pos) }) if (atoms.length === 0) return const pos = rng.pick(atoms) view.dispatch(view.state.tr.delete(pos, pos + 1)) }, undo (view) { view.run(undo) }, redo (view) { view.run(redo) }, copyDrag (view, rng) { const children = [] view.state.doc.forEach((node, offset) => children.push({ node, offset })) const { node } = rng.pick(children) const target = rng.pick(children) view.dispatch(view.state.tr.insert(rng() < 0.5 ? target.offset : target.offset + target.node.nodeSize, node)) }, paste (view, rng, fidelity) { const range = someRange(rng, view.state.doc) if (!range) return const { mapa } = copyData(view.state, fidelity, ...range) const into = rng() < 0.7 ? somewhere(rng, view.state.doc) : null if (into) caret(view, into.at) else { const other = someRange(rng, view.state.doc) if (other) caret(view, ...other) } const tr = pasteTransaction(view.state, fidelity, mapa) if (tr) view.dispatch(tr) }, cutAndPaste (view, rng, fidelity) { const range = someRange(rng, view.state.doc) if (!range || range[0] === range[1]) return const { mapa } = copyData(view.state, fidelity, ...range) caret(view, ...range) view.dispatch(view.state.tr.deleteSelection()) const into = somewhere(rng, view.state.doc) if (into) caret(view, into.at) const tr = pasteTransaction(view.state, fidelity, mapa) if (tr) view.dispatch(tr) }, rebuild (view, rng, fidelity) { const depth = undoDepth(view.state) const { body } = prepareSave(view, fidelity) const saved = undoDepth(view.state) rebuild(view, fidelity, body) assert.equal(undoDepth(view.state), saved, 'a rebuild is not in undo history') assert.ok(saved >= depth) }, task (view, rng) { const items = docBlocks(view.state.doc).filter(block => block.kind === Item) if (items.length === 0) return const item = rng.pick(items) const on = !item.holder.attrs.task view.dispatch(view.state.tr.setNodeAttribute(item.holderPos, 'task', on) .setNodeAttribute(item.holderPos, 'checked', on ? rng.pick([' ', 'x']) : null)) }, level (view, rng) { const headings = docBlocks(view.state.doc).filter(block => block.node.type.name === 'heading') if (headings.length === 0) return view.dispatch(view.state.tr.setNodeAttribute(rng.pick(headings).pos, 'level', 1 + rng.int(6))) }, remove (view, rng) { const range = someRange(rng, view.state.doc) if (!range) return caret(view, ...range) view.dispatch(view.state.tr.deleteSelection()) } } const weights = Object.entries({ type: 8, mark: 3, split: 3, join: 3, move: 2, chip: 2, unchip: 1, undo: 3, redo: 1, copyDrag: 1, paste: 2, cutAndPaste: 1, rebuild: 1, task: 1, level: 1, remove: 2, image: 1, moveImage: 1, alt: 1 }).flatMap(([name, weight]) => Array(weight).fill(name)) function images (doc) { const found = [] doc.descendants((node, pos) => { if (node.type.name === 'image') found.push({ node, pos }) }) return found } function markerCounts (doc) { const counts = new Map() for (const block of docBlocks(doc)) { const marker = block.holder.attrs.marker if (marker) counts.set(marker, (counts.get(marker) ?? 0) + 1) } return counts } // stable is everything L3 holds after an edit. It returns what was saved. function stable (view, fidelity, before, mounted) { const unsettled = settle(view.state, fidelity, before) if (unsettled) { assert.fail(`the reparse is not idempotent: ${JSON.stringify(serialise(view.state.doc, fidelity))} ` + `settles again to ${JSON.stringify(serialise(unsettled.doc, fidelity))} by ` + JSON.stringify(unsettled.steps.map(step => step.toJSON())).slice(0, 600)) } const { body, shapes } = prepareSave(view, fidelity) const check = structureCheck(view.state.doc, fidelity) assert.ok(check.ok, 'the saved body reloads as this document') assert.equal(check.body, body) const again = mount(schema, body) assert.equal(serialise(again.doc, again.fidelity), body, 'serialise(parse(serialise)) = serialise') for (const [marker, count] of markerCounts(view.state.doc)) { assert.ok(count <= Math.max(1, mounted.get(marker) ?? 0), `^${marker} held ${count} times`) } for (const block of serialiseDetailed(view.state.doc, fidelity).blocks) { // A fence line is no block on its own: its entry is its layout's. if (!block.untouched || isFence(block.kind)) continue const read = docBlocks(fromBlocks(schema, parse(block.entry.source), { trailing: false })) assert.equal(read.length, 1, 'an entry\'s source is one block') assert.ok(sameNode(read[0].node, block.entry.node), `an entry's node is its source's: ${block.kind} ${JSON.stringify(block.entry.source)} ${read[0].kind}`) assert.ok(sameNode(block.node, block.entry.node) || sameNode(bareNode(block), block.entry.node), 'an untouched block is its entry\'s node') } return { body, shapes } } const l3Steps = 24 test('L3: seeded edits keep the document and its Markdown saying the same thing', t => { const saved = [] let steps = 0 report(each(({ name, body }) => { const rng = random(`L3 ${name}`) const { view, fidelity } = editor(cleanBody(body)) const mounted = markerCounts(view.state.doc) let last = null for (let step = 0; step < l3Steps; step++) { const edit = rng.pick(weights) const before = view.state.doc try { edits[edit](view, rng, fidelity) last = stable(view, fidelity, before, mounted) } catch (error) { error.message = `step ${step} (${edit}): ${error.message}` throw error } steps++ } saved.push({ name, body: last.body, blocks: last.shapes }) const before = view.state.doc undoAll(view) stable(view, fidelity, before, mounted) }), bodies.length) t.diagnostic(`${steps} edits over ${bodies.length} bodies`) if (localCorpus || only) return const clean = createHash('sha256') for (const { body } of bodies) clean.update(cleanBody(body) + '\u0000') const encoded = '{"clean":' + JSON.stringify(clean.digest('hex')) + ',"bodies":[\n' + saved.map(entry => JSON.stringify(entry)).join(',\n') + '\n]}\n' if (process.env.MAPA_EDITOR_UPDATE) { writeFileSync(editorGolden, encoded) return } assert.equal(readFileSync(editorGolden, 'utf8') === encoded, true, `${editorGolden} is stale: run make editor-golden and commit it`) }) // Link to a page over the corpus (build note 81): in each body, seeded // selections of words in one block become a chip showing those words. // Everything L3 holds still holds, and per link (review M3) the // document says what it said, less the words, plus exactly one chip // showing them: no embed, no code span, no other link made or lost. // Undo gives the body back byte for byte. function chipsOf (doc) { const out = [] doc.descendants(node => { if (node.type.name === 'wikilink' || node.type.name === 'datelink') { out.push(`${node.attrs.target ?? node.attrs.date}|${node.attrs.shown}`) } if (node.type.name === 'embed') out.push(`embed ${node.attrs.ref}`) }) return out.sort() } test('L3: Link to a page makes exactly one chip, and changes nothing else', t => { let linked = 0 const refused = {} report(each(({ name, body }) => { const rng = random(`link ${name}`) const clean = cleanBody(body) const { view, fidelity } = editor(clean) const mounted = markerCounts(view.state.doc) for (let tries = 0; tries < 8; tries++) { const place = somewhere(rng, view.state.doc, { code: false }) if (!place || place.node.content.size === 0) continue const from = place.pos + 1 + rng.int(place.node.content.size) const to = from + 1 + rng.int(place.pos + 1 + place.node.content.size - from) caret(view, from, to) const found = linkable(view.state) if (!found || found.refuse) { if (found) refused[found.refuse] = (refused[found.refuse] ?? 0) + 1 continue } const target = rng.pick(['Acme', 'Halden Robotics', '2026-11-12', found.words]) const shown = target === found.words ? '' : found.words if (pageLinkSource(target, shown) === null) { // Words holding # or | cannot be a title as typed: no row offers it. assert.equal(view.run(linkSelection(target, found.words)), false) continue } const before = view.state.doc const at = before.textBetween(0, found.from, '', '').length const text = before.textContent assert.equal(view.run(linkSelection(target, found.words)), true) const { body: saved } = stable(view, fidelity, before, mounted) const again = mount(schema, saved).doc for (const doc of [view.state.doc, again]) { // A line that came to read as a fence is neutralised (spec D16). const want = text.slice(0, at) + text.slice(at + found.words.length) const zw = value => doc.textContent === want ? value : value.replaceAll('\u200b', '') assert.equal(zw(doc.textContent), zw(want), `the text is the text less the words: ${JSON.stringify(saved)}`) const chip = `${target}|${shown}` assert.deepEqual(chipsOf(doc), [...chipsOf(before), chip].sort(), `exactly one more chip: ${JSON.stringify(saved)}`) } linked++ view.run(undo) assert.equal(serialise(view.state.doc, fidelity), clean, 'undo gives the body back') } }), bodies.length) t.diagnostic(`${linked} links over ${bodies.length} bodies; refused: ${JSON.stringify(refused)}`) }) // The date picker over the corpus (build note 83, review M1 and M2): in // each body, the picked day goes in at seeded carets outside code, as // dateInsertion puts it. Each insert is refused, or reads back as // exactly one more date chip with the text unchanged (a space before it // when it was spaced). No threshold: where either is not so, or the // insert is refused, a plain letter must fare the same (typing "x" at // the same caret does not read back either), so the chip is never the // only thing the place cannot hold. Everything L3 holds still holds, the // Markdown holds [[date]], and undo gives the body back byte for byte. function textAt (doc, pos) { return doc.textBetween(0, pos, '', '').length } // letterReadsBack is the control: whether typing "x" at pos in body // leaves a document whose text, and whose saved Markdown read again, // is the body's text with the x in it. Where it does not, the body was // already one the Markdown reads differently (an empty "##" heading, // an unclosed fence beside another kind), whatever goes in there. function letterReadsBack (body, pos) { const { view, fidelity } = editor(body) const text = view.state.doc.textContent const at = textAt(view.state.doc, pos) view.dispatch(view.state.tr.insertText('x', pos)) const want = text.slice(0, at) + 'x' + text.slice(at) const again = mount(schema, prepareSave(view, fidelity).body).doc return view.state.doc.textContent === want && again.textContent === want } test('L3: a picked date is one more date chip, or refused where a letter would be too', t => { const tally = { inserted: 0, spaced: 0, refused: 0, unstable: 0 } report(each(({ name, body }) => { const rng = random(`date ${name}`) const clean = cleanBody(body) const { view, fidelity } = editor(clean) const mounted = markerCounts(view.state.doc) for (let tries = 0; tries < 6; tries++) { const place = somewhere(rng, view.state.doc, { code: false }) if (!place) continue caret(view, place.at) const date = rng.pick(['2026-11-20', '2025-02-28', '2028-02-29']) const before = view.state.doc const made = dateInsertion(view.state, date) if (made.refuse) { const control = view.state.tr.insertText('x', place.at) assert.equal(readsBack(control.doc.resolve(place.at).parent), false, `refused where a letter reads back: ${JSON.stringify(clean)} at ${place.at}`) tally.refused++ continue } const at = textAt(before, place.at) const text = before.textContent const want = text.slice(0, at) + (made.spaced ? ' ' : '') + text.slice(at) view.dispatch(made.tr) const { body: saved } = stable(view, fidelity, before, mounted) const again = mount(schema, saved).doc const chips = JSON.stringify([...chipsOf(before), `${date}|`].sort()) const exact = [view.state.doc, again].every(doc => doc.textContent === want && JSON.stringify(chipsOf(doc)) === chips) if (!exact) { assert.equal(letterReadsBack(clean, place.at), false, `the date reads differently where a letter does not: ${JSON.stringify(saved)}`) tally.unstable++ } assert.ok(saved.includes(`[[${date}]]`), `the Markdown holds [[${date}]]: ${JSON.stringify(saved)}`) tally[made.spaced ? 'spaced' : 'inserted']++ view.run(undo) assert.equal(serialise(view.state.doc, fidelity), clean, 'undo gives the body back') } }), bodies.length) t.diagnostic(`over ${bodies.length} bodies: ${JSON.stringify(tally)}`) assert.ok(tally.inserted + tally.spaced > 3000, JSON.stringify(tally)) })