oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1// Generates the ProseMirror-shaped Y.XmlFragment fixtures that define the
2// wire contract for core/src/fragment.rs. These are the contract: never
3// edit a fixture to make a test pass. A deliberate rule change regenerates
4// them in the same commit.
5import * as Y from 'yjs'
6import { writeFileSync, mkdirSync, readFileSync } from 'node:fs'
7
8// The client id is pinned so the bytes are reproducible. Options::
9// with_guid_and_client_id on the Rust side pins the same pair; nothing
10// in this pipeline may draw entropy (see the plan's Global Constraints).
11function docWith(build) {
12 const doc = new Y.Doc()
13 doc.clientID = 1
14 build(doc.getXmlFragment('prosemirror'))
15 return Y.encodeStateAsUpdate(doc)
16}
17
18function el(name, attrs, ...children) {
19 const e = new Y.XmlElement(name)
20 for (const [k, v] of Object.entries(attrs ?? {})) e.setAttribute(k, v)
21 if (children.length) e.insert(0, children)
22 return e
23}
24
25function text(s, marks) {
26 const t = new Y.XmlText()
27 t.insert(0, s, marks ?? undefined)
28 return t
29}
30
31mkdirSync('vectors/fragment', { recursive: true })
32
33writeFileSync('vectors/fragment/simple.bin', docWith(f => {
34 f.insert(0, [
35 el('paragraph', null, text('First paragraph.')),
36 el('paragraph', null, text('Second paragraph.')),
37 ])
38}))
39
40writeFileSync('vectors/fragment/marks.bin', docWith(f => {
41 f.insert(0, [
42 el('paragraph', null,
43 text('Plain then '), text('bold', { strong: {} }),
44 text(' then '), text('italic', { em: {} }), text('.')),
45 ])
46}))
47
48writeFileSync('vectors/fragment/nested.bin', docWith(f => {
49 f.insert(0, [
50 el('heading', { level: '2' }, text('A heading')),
51 el('bullet_list', null,
52 el('list_item', null, el('paragraph', null, text('One'))),
53 el('list_item', null, el('paragraph', null, text('Two')))),
54 ])
55}))
56
57// styled.bin covers what the formatting bar can produce that the three
58// fixtures above cannot: the font and size marks (core/src/fragment.rs's
59// MARKS table), a run carrying two marks at once, and the two block
60// shapes — blockquote and ordered_list — that had no fixture before the
61// export paths needed to render them. The marks are attribute-free on
62// purpose; see that table's own comment for why a mark never carries a
63// value.
64writeFileSync('vectors/fragment/styled.bin', docWith(f => {
65 f.insert(0, [
66 el('paragraph', null,
67 text('sans', { font_sans: {} }),
68 text(' mono', { font_mono: {} }),
69 text(' large', { size_lg: {} }),
70 text(' both', { font_sans: {}, strong: {} })),
71 el('blockquote', null, el('paragraph', null, text('Quoted.'))),
72 el('ordered_list', null,
73 el('list_item', null, el('paragraph', null, text('First'))),
74 el('list_item', null, el('paragraph', null, text('Second')))),
75 ])
76}))
77
78// fonts.bin covers the font marks on their own, and exists because
79// serif became sayable. Until sans took the default over, "serif" was
80// spelled as the ABSENCE of a mark — there was no font_serif — so the
81// vocabulary styled.bin pins had no way to express the face most
82// documents were actually in. This fixture pins the whole of it: an
83// unmarked run, which carries no span whatever the default happens to
84// be, and one run per face.
85//
86// A fixture of its own, rather than three more runs inside styled.bin.
87// These vectors are the wire contract, not an output of it: styled.bin's
88// bytes are what a dozen assertions in core/tests/fragment.rs and
89// internal/docs already compare against, and regenerating it would
90// quietly change what every one of them means. Adding a vector changes
91// nothing that already exists.
92writeFileSync('vectors/fragment/fonts.bin', docWith(f => {
93 f.insert(0, [
94 el('paragraph', null,
95 text('Unmarked'),
96 text(' serif', { font_serif: {} }),
97 text(' sans', { font_sans: {} }),
98 text(' mono', { font_mono: {} })),
99 ])
100}))
101
102// families.bin is one run per family in internal/fonts/fonts.json,
103// generated from the manifest, so core/tests/fragment.rs can hold its
104// MARKS table to the same list internal/fonts and the editor read.
105// Regenerated whenever a family is added; nothing else depends on its
106// bytes.
107const manifest = JSON.parse(readFileSync(new URL('../internal/fonts/fonts.json', import.meta.url)))
108writeFileSync('vectors/fragment/families.bin', docWith(f => {
109 f.insert(0, [
110 el('paragraph', null,
111 ...manifest.families.map((fam) => text(fam.name, { ['font_' + fam.key]: {} }))),
112 ])
113}))
114
115// faces.bin is a document set in five faces, for the font gate's test
116// that a page preloads exactly the faces it uses: Carlito regular, bold
117// (a heading and a strong run), italic, Liberation Mono (code) and
118// Caladea regular.
119writeFileSync('vectors/fragment/faces.bin', docWith(f => {
120 f.insert(0, [
121 el('heading', { level: 2 }, text('Heading')),
122 el('paragraph', null,
123 text('Plain '),
124 text('bold', { strong: {} }),
125 text(' and '),
126 text('italic', { em: {} }),
127 text(' and '),
128 text('code', { code: {} }),
129 text(' and '),
130 text('twin', { font_caladea: {} })),
131 ])
132}))
133
134// playfair.bin is a collaborator's change in a family the reader's tab
135// has not loaded: internal/docs's browser test posts it while the tab
136// watches, and holds that the text never paints before Playfair Display
137// has loaded.
138writeFileSync('vectors/fragment/playfair.bin', docWith(f => {
139 f.insert(0, [el('paragraph', null, text('A collaborator wrote this', { font_playfair: {} }))])
140}))
141
142// linebreaks.bin is three long paragraphs, in Carlito (unmarked),
143// Caladea and Inter, set to break where kerning and ligatures decide it,
144// for the browser test that holds the PDF's lines to the screen's.
145const prose = 'AVOWED TOYOTA WAVES: Yolanda typed "Tomorrow, LT. Walton" while Vivian, eyeing the office affidavit, ' +
146 'filed fifty reflective notes. Every Wednesday the Avalon Toy Workshop yields jolly figures, ' +
147 'wavy yarns and quirky boxes; Tycho fixed the kerning, Ava efficiently waffled, and nobody officially ' +
148 'objected to the fluffy waffles that Tom effortlessly offered. Yet Vance, wary of affluent tycoons, ' +
149 'quietly typed a final paragraph for the Wolverhampton Yacht Society.'
150writeFileSync('vectors/fragment/linebreaks.bin', docWith(f => {
151 f.insert(0, [
152 el('paragraph', null, text(prose)),
153 el('paragraph', null, text(prose, { font_caladea: {} })),
154 el('paragraph', null, text(prose, { font_inter: {} })),
155 ])
156}))
157
158// The font gate's remote changes, each an increment on simple.bin from a
159// second client, the way a collaborator's edit reaches a tab: none names
160// a font_* key, so a gate that only scanned for those would let them
161// through. remote-code.bin appends a paragraph of code (Liberation Mono);
162// remote-bold.bin appends a bold one (Carlito Bold).
163function incrementOnSimple(name, build) {
164 const base = new Y.Doc()
165 base.clientID = 1
166 base.getXmlFragment('prosemirror').insert(0, [
167 el('paragraph', null, text('First paragraph.')),
168 el('paragraph', null, text('Second paragraph.')),
169 ])
170 const other = new Y.Doc()
171 other.clientID = 2
172 Y.applyUpdate(other, Y.encodeStateAsUpdate(base))
173 const before = Y.encodeStateVector(other)
174 build(other.getXmlFragment('prosemirror'))
175 writeFileSync(`vectors/fragment/${name}`, Y.encodeStateAsUpdate(other, before))
176}
177incrementOnSimple('remote-code.bin', f => {
178 f.insert(f.length, [el('paragraph', null, text('A collaborator\'s code', { code: {} }))])
179})
180incrementOnSimple('remote-codeblock.bin', f => {
181 f.insert(f.length, [el('code_block', null, text('const fromACollaborator = true'))])
182})
183incrementOnSimple('remote-bold.bin', f => {
184 f.insert(f.length, [el('paragraph', null, text('A collaborator\'s bold', { strong: {} }))])
185})
186// remote-before.bin puts a paragraph before both of simple.bin's, so a
187// selection in them moves (the phone's Format sheet maps its kept
188// selection through it).
189incrementOnSimple('remote-before.bin', f => {
190 f.insert(0, [el('paragraph', null, text('A collaborator\'s first line.'))])
191})
192// remote-edit-second.bin writes into the start of simple.bin's second
193// paragraph, so a selection there no longer reads as it did.
194incrementOnSimple('remote-edit-second.bin', f => {
195 const words = f.get(1).get(0)
196 words.insert(0, 'Edited: ')
197})
198
199// long.bin runs to several pages, for the check that a paged document is
200// first shown already paginated.
201writeFileSync('vectors/fragment/long.bin', docWith(f => {
202 const paras = []
203 for (let i = 0; i < 60; i++) paras.push(el('paragraph', null, text(`Paragraph ${i + 1}. ` + 'The quick brown fox jumps over the lazy dog. '.repeat(6))))
204 f.insert(0, paras)
205}))
206
207// spaces.bin is ordinary Carlito words whose separating spaces alone are
208// in Caveat (branch review 3, finding 1): the gate must wait for Caveat,
209// though not one Caveat glyph is drawn, because Caveat sets the spaces'
210// widths and so where every line breaks.
211writeFileSync('vectors/fragment/spaces.bin', docWith(f => {
212 const paras = []
213 for (let i = 0; i < 30; i++) {
214 const runs = []
215 const words = `Paragraph ${i + 1} of ordinary words whose spaces alone are set in another face entirely`.split(' ')
216 words.forEach((w, j) => {
217 runs.push(text(w))
218 if (j < words.length - 1) runs.push(text(' ', { font_caveat: {} }))
219 })
220 paras.push(el('paragraph', null, ...runs))
221 }
222 f.insert(0, paras)
223}))
224
225// inline.bin is bold Caveat throughout (branch review 4): the glyphs are
226// Caveat Bold, but the <span class="docs-font-caveat"> around each run is
227// Caveat Regular, and that inline box sets the line's height. The gate
228// must wait for the family, every style of it, not for the faces that
229// happen to draw.
230writeFileSync('vectors/fragment/inline.bin', docWith(f => {
231 const paras = []
232 for (let i = 0; i < 30; i++) {
233 paras.push(el('paragraph', null, text('A line of bold Caveat words with ascenders and descenders. '.repeat(3), { font_caveat: {}, strong: {} })))
234 }
235 f.insert(0, paras)
236}))
237
238// aligned.bin covers the first block-level formatting: a paragraph's
239// `align` attribute. Unlike a mark, alignment belongs to the block, so
240// it is a real Yjs XML attribute on the element — which is exactly why
241// it needs a fixture of its own. y-prosemirror stores node attributes
242// this way (createTypeFromElementNode: setAttribute for every non-null
243// attr), so this is what an aligned document ACTUALLY contains on the
244// wire, and core/src/fragment.rs has to read it back from there rather
245// than from anyone's description of it.
246//
247// The first paragraph carries no attribute at all, which is the whole
248// point of left being the default: the editor's schema stores null,
249// y-prosemirror skips null, and an unaligned document is byte-identical
250// to one written before alignment existed. The last one says "left" out
251// loud, which a paste or a future build can produce and which must
252// render as no class rather than as a class of its own.
253// images.bin (Docs images spec §4.1): an image of this document's own
254// (sqid k3m9) with its size as y-prosemirror writes it from the upload's
255// reply, strings; a second whose width arrived as a NUMBER, which
256// y-prosemirror never validates and the core must still read; one with
257// no size at all (a native paste's data: image today); and another
258// document's address, which must draw as missing.
259writeFileSync('vectors/fragment/images.bin', docWith(f => {
260 f.insert(0, [
261 el('paragraph', null,
262 text('A '),
263 el('image', { src: '/d/k3m9/images/0123456789abcdef', alt: 'A cat', width: '640', height: '480' }),
264 text(' and '),
265 el('image', { src: '/d/k3m9/images/fedcba9876543210', alt: '', width: 320, height: 200 }),
266 ),
267 el('paragraph', null,
268 el('image', { src: 'data:image/png;base64,iVBORw0KGgo=', alt: 'Pasted' }),
269 el('image', { src: '/d/other/images/0123456789abcdef', alt: 'Elsewhere' }),
270 ),
271 ])
272}))
273
274writeFileSync('vectors/fragment/aligned.bin', docWith(f => {
275 f.insert(0, [
276 el('paragraph', null, text('Left by default.')),
277 el('paragraph', { align: 'center' }, text('Centred.')),
278 el('paragraph', { align: 'right' }, text('Right.')),
279 el('paragraph', { align: 'left' }, text('Left, said out loud.')),
280 ])
281}))
282
283// indented.bin covers the second block attribute, and it exists as its
284// own vector for a reason aligned.bin did not have: indent's value is a
285// NUMBER, where align's is a string from a closed set of three.
286//
287// That difference is the thing this fixture is here to pin. A string
288// attribute can only be handled one way — look it up in a table, drop
289// anything not in it — so aligned.bin's job was to prove the table is
290// consulted. A number has to be parsed and clamped instead, which is a
291// second mechanism with a second set of ways to be wrong, and the
292// wrong-looking cases are exactly the ones no editor will ever produce:
293// a level past the maximum, a zero, a value that is not a number at
294// all. POST /d/{sqid}/updates takes raw Yjs bytes, so every one of them
295// is reachable by a client that never went through the schema, and the
296// renderer's output goes into the page unescaped.
297//
298// So the last three paragraphs here are not decoration. "99" must
299// render clamped to the deepest level rather than as docs-indent-99;
300// "0" must render as no class at all, the same as no attribute;
301// "3; drop" must fail to parse and render flush left, never reaching
302// attribute position. A build that interpolated the attribute straight
303// into a class name would pass every test written against the first
304// three paragraphs and fail these.
305//
306// The first paragraph carries no attribute, for aligned.bin's own
307// reason: an un-indented document must be byte-identical to one written
308// before indent existed.
309//
310// The heading is here because headings are indentable and are not
311// alignable — a real asymmetry in the schema, and one that a fixture
312// covering only paragraphs would let a renderer get wrong in silence.
313writeFileSync('vectors/fragment/indented.bin', docWith(f => {
314 f.insert(0, [
315 el('paragraph', null, text('Flush left, no attribute.')),
316 el('paragraph', { indent: '1' }, text('One step.')),
317 el('paragraph', { indent: '8' }, text('The deepest step.')),
318 el('heading', { level: '2', indent: '2' }, text('An indented heading.')),
319 el('paragraph', { align: 'center', indent: '3' }, text('Centred and indented.')),
320 el('paragraph', { indent: '99' }, text('Past the maximum; clamps.')),
321 el('paragraph', { indent: '0' }, text('Zero is no indent.')),
322 el('paragraph', { indent: '3; drop' }, text('Not a number at all.')),
323 // The four values JavaScript's Number() accepts and a Rust parse
324 // does not. They are here because the two sides disagreed about
325 // every one of them for a review cycle — the editor rendered them
326 // indented and the read view rendered them flush left — and the
327 // agreement is now the thing being pinned rather than the clamp.
328 el('paragraph', { indent: '400' }, text('Too large for a u8; still clamps.')),
329 el('paragraph', { indent: ' 3' }, text('Leading space is not a number.')),
330 el('paragraph', { indent: '3.0' }, text('Nor is a decimal point.')),
331 el('paragraph', { indent: '0x3' }, text('Nor is hex.')),
332 ])
333}))
334
335// sizes.bin covers the point ladder, and the three legacy marks
336// alongside it.
337//
338// styled.bin already pins size_sm/lg/xl, so this could have been read as
339// redundant. It is not: the legacy marks are pinned there as the sizes
340// this editor WRITES, and here as the sizes it must go on UNDERSTANDING
341// after it stopped writing them. A change that dropped them from MARKS
342// would leave styled.bin's assertions to be "fixed" by regenerating it;
343// this fixture states the property directly, so the same change fails
344// with a message about documents in the wild.
345//
346// The mixed run at the end is the case neither renderer can produce and
347// POST /d/{sqid}/updates can: a run carrying a ladder mark AND a legacy
348// one. Both this build and internal/export/pdf.go resolve it the same
349// way — ladder first, in a fixed order — because a document must not
350// measure one size on screen and another on paper, and an arbitrary but
351// stable answer is what determinism needs.
352writeFileSync('vectors/fragment/sizes.bin', docWith(f => {
353 f.insert(0, [
354 el('paragraph', null,
355 text('Body'),
356 text(' eight', { size_8: {} }),
357 text(' fourteen', { size_14: {} }),
358 text(' seventy-two', { size_72: {} })),
359 el('paragraph', null,
360 text('Small', { size_sm: {} }),
361 text(' Large', { size_lg: {} }),
362 text(' Extra', { size_xl: {} })),
363 el('paragraph', null,
364 text('Both at once', { size_lg: {}, size_24: {} })),
365 ])
366}))
367
368// --- trap-containment vectors ---
369//
370// core/tests/wasm_trap_containment.rs mutation-fuzzes real fixtures and
371// checks a control document's content survives untouched, reading it
372// back through the wasm ABI's docs_core_text_len/docs_core_text_read.
373// Those now read fragment_text (root "prosemirror"), not text_content
374// (root "content") — see core/src/abi.rs's text_string doc comment —
375// so that test needs fragment-shaped fixtures of its own rather than
376// fixtures/data's Y.Text ones (which read back as "" through that ABI
377// now). These four mirror fixtures/data's hello/unicode/formatted/
378// concurrent in content and purpose (plain ASCII, surrogate pairs and
379// combining marks, inline formatting, a concurrent merge) so the same
380// coverage that fuzzing wants — plain text, non-ASCII byte lengths,
381// format-op decoding, CRDT merge structure — survives the move, just
382// wrapped in a single top-level <paragraph> each instead of a bare
383// Y.Text.
384//
385// plainTextOf mirrors core/src/fragment.rs's fragment_text: walk the
386// tree, concatenate each Y.XmlText's own rendering, and join top-level
387// block texts with a blank line.
388//
389// Uses each Y.XmlText's own toString(), not toDelta() — verified
390// against the real Rust output, not assumed: fragment_text calls
391// yrs's XmlTextRef::get_string(txn), and yrs's own get_string embeds
392// formatting as inline pseudo-tags exactly the way Y.XmlText.toString()
393// does in JS ("plain <strong>bold</strong> plain", not "plain bold
394// plain") — this is XmlText's own "plain text" convention in both
395// implementations, not the HTML fragment_html builds via its own MARKS
396// table. A first version of this generator used toDelta() (mark-free)
397// and it disagreed with the real Rust output on the very first run —
398// core/tests/wasm_trap_containment.rs caught it immediately, which is
399// the whole reason this fixture set exists.
400function plainTextOf(doc) {
401 const f = doc.getXmlFragment('prosemirror')
402 const isBlock = (name) =>
403 ['paragraph', 'heading', 'list_item', 'blockquote'].includes(name)
404 const blocks = []
405 let cur = ''
406 function walk(node) {
407 if (node instanceof Y.XmlText) {
408 cur += node.toString()
409 } else if (node instanceof Y.XmlElement) {
410 for (const child of node.toArray()) walk(child)
411 if (isBlock(node.nodeName) && cur.length > 0) {
412 blocks.push(cur)
413 cur = ''
414 }
415 }
416 }
417 for (const child of f.toArray()) walk(child)
418 if (cur.length > 0) blocks.push(cur)
419 return blocks.join('\n\n')
420}
421
422// emitTrap writes both halves a fixture needs: the update bytes, and
423// (unlike docWith's three vectors above, which core/tests/fragment.rs
424// asserts against with hand-written literals) an expected.json next to
425// it, the same shape fixtures/generate.mjs writes for fixtures/data —
426// wasm_trap_containment.rs reads that "text" field the same way
427// wire_compat.rs's fixture() does.
428function emitTrap(name, build) {
429 const doc = new Y.Doc()
430 doc.clientID = 1
431 build(doc)
432 const update = Y.encodeStateAsUpdate(doc)
433 writeFileSync(`vectors/fragment/${name}.update.bin`, Buffer.from(update))
434 writeFileSync(
435 `vectors/fragment/${name}.expected.json`,
436 JSON.stringify({ text: plainTextOf(doc) }, null, 2) + '\n',
437 )
438 console.log(`${name}: ${update.length} bytes`)
439}
440
441emitTrap('hello', (doc) => {
442 doc.getXmlFragment('prosemirror').insert(0, [el('paragraph', null, text('hello world'))])
443})
444
445emitTrap('unicode', (doc) => {
446 // Surrogate pairs and combining marks: Yjs indexes UTF-16 code units and
447 // Rust indexes UTF-8 bytes, same reasoning as fixtures/generate.mjs's
448 // own 'unicode' fixture.
449 doc.getXmlFragment('prosemirror').insert(0, [el('paragraph', null, text('héllo 🌍 café'))])
450})
451
452emitTrap('formatted', (doc) => {
453 // Inline formatting: exercises format-op decoding under mutation
454 // fuzzing, same reasoning as fixtures/generate.mjs's own 'formatted'
455 // fixture. plainTextOf strips marks via toDelta, so the expected text
456 // is just the concatenated runs regardless of the strong attribute.
457 doc.getXmlFragment('prosemirror').insert(0, [
458 el('paragraph', null, text('plain '), text('bold', { strong: {} }), text(' plain')),
459 ])
460})
461
462emitTrap('concurrent', (doc) => {
463 // Two docs each insert their own top-level paragraph before syncing,
464 // then merge — order-independent CRDT merge structure, same
465 // reasoning as fixtures/generate.mjs's own 'concurrent' fixture, at
466 // the block level rather than mid-run since Y.XmlFragment's children
467 // are blocks, not characters.
468 const a = new Y.Doc()
469 a.clientID = 1
470 const b = new Y.Doc()
471 b.clientID = 2
472 // doc.clientID (set to 3 here) overrides the emitTrap assignment
473 // above, same as generate.mjs's own concurrent fixture.
474 doc.clientID = 3
475 a.getXmlFragment('prosemirror').insert(0, [el('paragraph', null, text('AAA'))])
476 b.getXmlFragment('prosemirror').insert(0, [el('paragraph', null, text('BBB'))])
477 Y.applyUpdate(a, Y.encodeStateAsUpdate(b))
478 Y.applyUpdate(b, Y.encodeStateAsUpdate(a))
479 Y.applyUpdate(doc, Y.encodeStateAsUpdate(a))
480})
481
482console.log('wrote 16 fragment vectors + 4 trap-containment vectors')
483