| 1 | // fixtures/import-interop.mjs — reads an imported document's update, as |
| 2 | // the server's import path (internal/docs/import.go) wrote it, on stdin, |
| 3 | // and checks the editor can take it as it is: |
| 4 | // |
| 5 | // - Yjs decodes it at all. lib0 refuses a client id past |
| 6 | // Number.MAX_SAFE_INTEGER, which yrs writes without complaint; an |
| 7 | // import written under one applied on the server and in no browser. |
| 8 | // - y-prosemirror builds the editor's own schema's document from it |
| 9 | // without changing the Yjs document. y-prosemirror deletes, and then |
| 10 | // saves the deletion of, any node the schema refuses; an import it |
| 11 | // had to clean up would lose text the first time it was opened. |
| 12 | // - That document passes the schema's full check, attribute validators |
| 13 | // included (a heading level must be a number). |
| 14 | // |
| 15 | // Prints {"clients": [...], "doc": <ProseMirror JSON>} for the Go side |
| 16 | // (internal/docs/import_interop_test.go) to compare with what the |
| 17 | // reader meant. Exits non-zero, saying why, on any failure. |
| 18 | import * as Y from 'yjs' |
| 19 | import { yXmlFragmentToProseMirrorRootNode } from 'y-prosemirror' |
| 20 | import { schema } from './schema.mjs' |
| 21 | |
| 22 | const chunks = [] |
| 23 | for await (const chunk of process.stdin) chunks.push(chunk) |
| 24 | const update = new Uint8Array(Buffer.concat(chunks)) |
| 25 | |
| 26 | function fail (why) { |
| 27 | console.error('import-interop: ' + why) |
| 28 | process.exit(1) |
| 29 | } |
| 30 | |
| 31 | if (update.length === 0) fail('empty update on stdin') |
| 32 | |
| 33 | const doc = new Y.Doc() |
| 34 | try { |
| 35 | Y.applyUpdate(doc, update) |
| 36 | } catch (err) { |
| 37 | fail('Yjs cannot decode the update: ' + err.message) |
| 38 | } |
| 39 | const clients = [...Y.decodeStateVector(Y.encodeStateVector(doc)).keys()] |
| 40 | for (const c of clients) { |
| 41 | if (!Number.isSafeInteger(c)) fail('a client id is not a safe integer') |
| 42 | } |
| 43 | |
| 44 | let changed = false |
| 45 | doc.on('update', () => { changed = true }) |
| 46 | let root |
| 47 | try { |
| 48 | root = yXmlFragmentToProseMirrorRootNode(doc.getXmlFragment('prosemirror'), schema) |
| 49 | } catch (err) { |
| 50 | fail('y-prosemirror cannot build the document: ' + err.message) |
| 51 | } |
| 52 | if (changed) fail('y-prosemirror changed the document while reading it (schema clean-up)') |
| 53 | try { |
| 54 | root.check() |
| 55 | } catch (err) { |
| 56 | fail('the editor schema refuses the document: ' + err.message) |
| 57 | } |
| 58 | |
| 59 | process.stdout.write(JSON.stringify({ clients, doc: root.toJSON() })) |
| 60 | |