oficina / mapa Public

Editor fidelity: serialiser, side table, settle plugin, clipboard

Level-up spec §6.4 and §6.6, in the editor bundle (not loaded yet):

- serialize.mjs writes the document as Mapa Markdown. An untouched block
  (first holder of its origin, eq its entry's node, same context)
  re-emits its source; seams between recorded neighbours are kept;
  Join's rule elsewhere; leading and trailing bytes while their blocks
  are first and last; cleanBody's rule. Edited blocks are written from
  their kept attributes, marks per §6.3 (em outside strong, bold
  reopened around italics, edge whitespace outside, marks closed around
  code, links and atoms). Empty blocks, and a trailing hard break, are
  written as nothing. The structure check puts Join's seams, then
  node-written blocks, where the body would not reload as the document.
- fidelity.mjs: opaque monotonic origins, the never-forgetting table,
  mount, rebuild against a body (addToHistory false, origins only),
  applyBody and prepareSave (adopting the parse as the last resort), and
  the settle plugin: the reparse rule (in place, or adopting the parse,
  deferred while composing, idempotent), the marker rule, item indents
  following depth, and the trailing paragraph.
- clipboard.mjs: Mapa Markdown and an application/x-mapa slice on copy
  and cut; paste prefers the slice, rebuilds its blocks with the parser
  and records them with fresh origins, sources and seams; a pasted ^id
  is dropped only when the document already has it.

The bundle is 26.5KB gzipped (L12 budget 120KB).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5a499ddcfc33da99a406319eae3afa720b8bf560 parent 94b6260
8 files changed, +1,547 −5
  • editor/clipboard.mjs +189 −0
  • editor/editor-entry.js +18 −3
  • editor/fidelity.mjs +541 −0
  • editor/serialize.mjs +484 −0
  • editor/serialize.test.mjs +215 −0
  • editor/testkit.mjs +70 −0
  • internal/mapa/static/editor.191a361976920a15.js +0 −2
  • internal/mapa/static/editor.e67effa70bb31619.js +30 −0
diff --git a/editor/clipboard.mjs b/editor/clipboard.mjs
new file mode 100644
index 0000000..bf37a3e
--- /dev/null
+++ b/editor/clipboard.mjs
@@ -0,0 +1,189 @@
+// clipboard.mjs — copy, cut and paste (spec §6.6).
+//
+// Copy and cut put Mapa Markdown in text/plain, ProseMirror's HTML in
+// text/html, and a private application/x-mapa slice: each copied block's
+// Markdown (its source, when it is untouched) and the exact bytes between
+// them. Paste prefers that slice. Its blocks are built by markup.mjs's
+// parser, never taken on trust, and get fresh origins recorded with their
+// sources and seams, so a cut and paste re-emits the bytes it cut.
+// text/plain from outside is parsed as Mapa Markdown; text/html goes
+// through the schema's parseDOM. A pasted block's ^id is removed only
+// when that id is already in the document (outside what the paste
+// replaces), so a cut and paste keeps the links to its block.
+
+import { Plugin, PluginKey, TextSelection } from 'prosemirror-state'
+import { Fragment, Slice } from 'prosemirror-model'
+import { parse } from './markup.mjs'
+import { fromMarkdown } from './fromMarkdown.mjs'
+import { serialiseDetailed } from './serialize.mjs'
+import { recordBody } from './fidelity.mjs'
+
+export const mapaType = 'application/x-mapa'
+
+// copyData is what copy puts on the clipboard for from..to: Markdown for
+// text/plain, and the x-mapa slice.
+export function copyData (state, fidelity, from = state.selection.from,
+ to = state.selection.to) {
+ const whole = state.doc.slice(from, to, true)
+ const doc = state.schema.topNodeType.create(null, whole.content)
+ const { body, emitted } = serialiseDetailed(doc, fidelity, { edges: false, raw: true })
+ const mapa = JSON.stringify({
+ v: 1,
+ sources: emitted.map(block => block.text),
+ seams: emitted.slice(1).map(block => block.seam)
+ })
+ return { text: body, mapa }
+}
+
+// slicePayload reads an x-mapa slice: the Markdown it carries, or null
+// when it is not one this editor wrote.
+function slicePayload (data) {
+ let payload
+ try {
+ payload = JSON.parse(data)
+ } catch {
+ return null
+ }
+ const { sources, seams } = payload ?? {}
+ if (payload?.v !== 1 || !Array.isArray(sources) || !Array.isArray(seams) ||
+ sources.length === 0 || seams.length !== sources.length - 1 ||
+ ![...sources, ...seams].every(text => typeof text === 'string') ||
+ !seams.every(text => /^\n(?:[^\n]*\n)*$/u.test(text))) {
+ return null
+ }
+ const body = sources.map((source, index) => (index ? seams[index - 1] : '') + source).join('')
+ const blocks = parse(body)
+ if (blocks.length !== sources.length ||
+ blocks.some((block, index) => block.source !== sources[index])) return null
+ return body
+}
+
+// takenMarkers is every ^id in the document outside the selection. An
+// empty block (the one a cut leaves) writes nothing, so its ^id is not in
+// the document.
+export function takenMarkers (state, fidelity) {
+ const { from, to } = state.selection
+ const taken = new Set()
+ for (const block of serialiseDetailed(state.doc, fidelity).emitted) {
+ const marker = block.holder.attrs.marker
+ const inside = block.holderPos >= from &&
+ block.holderPos + block.holder.nodeSize <= to
+ if (marker && !inside) taken.add(marker)
+ }
+ return taken
+}
+
+function stripMarkers (fragment, taken) {
+ const out = []
+ fragment.forEach(node => {
+ let next = node
+ if (!node.isTextblock && !node.isLeaf) next = node.copy(stripMarkers(node.content, taken))
+ if (next.attrs.marker && taken.has(next.attrs.marker)) {
+ next = next.type.create({ ...next.attrs, marker: null }, next.content, next.marks)
+ }
+ out.push(next)
+ })
+ return Fragment.from(out)
+}
+
+export function stripTakenMarkers (slice, state, fidelity) {
+ const taken = takenMarkers(state, fidelity)
+ if (taken.size === 0) return slice
+ return new Slice(stripMarkers(slice.content, taken), slice.openStart, slice.openEnd)
+}
+
+// pasteTransaction is a paste of an x-mapa slice over the selection, or
+// null when data is not one. Its blocks get fresh origins recorded with
+// their sources and the seams between them.
+export function pasteTransaction (state, fidelity, data) {
+ const body = slicePayload(data)
+ if (body === null) return null
+ const { doc } = recordBody(state.schema, fidelity, body, { trailing: false, edges: false })
+ const slice = stripTakenMarkers(Slice.maxOpen(doc.content), state, fidelity)
+ // Into an empty paragraph of its own (where a cut leaves the caret),
+ // the blocks replace it whole rather than merging into it, so every
+ // pasted block keeps its source and the seams between them.
+ const { $from, empty } = state.selection
+ if (empty && $from.depth === 1 && $from.parent.type.name === 'paragraph' &&
+ $from.parent.content.size === 0) {
+ const tr = state.tr.replaceWith($from.before(), $from.after(), slice.content)
+ const end = $from.before() + slice.content.size
+ return tr.setSelection(TextSelection.near(tr.doc.resolve(end), -1))
+ }
+ return state.tr.replaceSelection(slice)
+}
+
+// textSlice is text/plain from outside, read as Mapa Markdown.
+export function textSlice (schema, text) {
+ const doc = fromMarkdown(schema, text, { trailing: false })
+ return doc.childCount ? Slice.maxOpen(doc.content) : Slice.empty
+}
+
+// sliceText is a slice's Markdown, written from its nodes, for a slice
+// that is not the selection.
+function sliceText (schema, slice) {
+ let content = slice.content
+ const first = content.firstChild
+ if (!first) return ''
+ if (first.isInline) content = Fragment.from(schema.nodes.paragraph.create(null, content))
+ else if (first.type.name === 'list_item') {
+ content = Fragment.from(schema.nodes.bullet_list.create(null, content))
+ }
+ try {
+ return serialiseDetailed(schema.topNodeType.create(null, content), null,
+ { edges: false, raw: true }).body
+ } catch {
+ return slice.content.textBetween(0, slice.content.size, '\n\n')
+ }
+}
+
+const clipboardKey = new PluginKey('mapa-clipboard')
+
+// clipboardPlugin wires the handlers above into the view.
+export function clipboardPlugin (fidelity) {
+ const copy = (view, event, cut) => {
+ const data = event.clipboardData
+ if (!data || view.state.selection.empty) return false
+ const { text, mapa } = copyData(view.state, fidelity)
+ const { dom } = view.serializeForClipboard(view.state.selection.content())
+ event.preventDefault()
+ data.clearData()
+ data.setData('text/html', dom.innerHTML)
+ data.setData('text/plain', text)
+ data.setData(mapaType, mapa)
+ if (cut) {
+ view.dispatch(view.state.tr.deleteSelection().scrollIntoView()
+ .setMeta('uiEvent', 'cut'))
+ }
+ return true
+ }
+ return new Plugin({
+ key: clipboardKey,
+ props: {
+ handleDOMEvents: {
+ copy: (view, event) => copy(view, event, false),
+ cut: (view, event) => copy(view, event, true)
+ },
+ handlePaste (view, event) {
+ const data = event.clipboardData?.getData(mapaType)
+ if (!data) return false
+ const tr = pasteTransaction(view.state, fidelity, data)
+ if (!tr) return false
+ view.dispatch(tr.scrollIntoView().setMeta('paste', true).setMeta('uiEvent', 'paste'))
+ return true
+ },
+ clipboardTextSerializer (slice, view) {
+ if (view.state.selection.content().eq(slice)) {
+ return copyData(view.state, fidelity).text
+ }
+ return sliceText(view.state.schema, slice)
+ },
+ clipboardTextParser (text, $context, plain, view) {
+ return textSlice(view.state.schema, text)
+ },
+ transformPasted (slice, view) {
+ return stripTakenMarkers(slice, view.state, fidelity)
+ }
+ }
+ })
+}
diff --git a/editor/editor-entry.js b/editor/editor-entry.js
index 92e267c..6a139f3 100644
--- a/editor/editor-entry.js
+++ b/editor/editor-entry.js
@@ -1,6 +1,21 @@
-// editor-entry.js — the editor bundle's entry. Phase 1 (spec §12, step 0)
-// builds the bundle with the schema in it and mounts nothing: no template
-// loads it yet. Phase 2 mounts the editor on the page's <article> here.
+// editor-entry.js — the editor bundle's entry. Phase 2's first step
+// (spec §12) builds the fidelity layer into it: the schema, the
+// serialiser and its side table, the settle and clipboard plugins. No
+// template loads the bundle yet; the editor is mounted on the page's
+// <article> here once the view and saving land.
import { createSchema } from './schema.mjs'
+export { createSchema }
+export { fromMarkdown } from './fromMarkdown.mjs'
+export {
+ serialise, serialiseDetailed, structureCheck, docBlocks
+} from './serialize.mjs'
+export {
+ Fidelity, mount, recordBody, rebuild, applyBody, prepareSave, reparse,
+ settle, fidelityPlugin, fidelityKey
+} from './fidelity.mjs'
+export {
+ clipboardPlugin, copyData, pasteTransaction, textSlice, mapaType
+} from './clipboard.mjs'
+
export const schema = createSchema()
diff --git a/editor/fidelity.mjs b/editor/fidelity.mjs
new file mode 100644
index 0000000..702301a
--- /dev/null
+++ b/editor/fidelity.mjs
@@ -0,0 +1,541 @@
+// fidelity.mjs — origins, the side table, and the rules that keep the
+// editor's document and its Markdown saying the same thing (spec §6.4).
+//
+// - Origins are opaque, monotonic and never reused: a Fidelity issues
+// them from 1 for each page load.
+// - The table never forgets: each origin is recorded once, with the node
+// read for it, its source, its context, its neighbours and its seams.
+// - Origins enter the document only where a document is built from a
+// body: at mount (the document is made with them), on paste from
+// Mapa's own clipboard (the pasted nodes carry them), when the parse is
+// adopted, and when the table is rebuilt against a body after a rebase,
+// which is the one transaction that changes origins alone, marked
+// addToHistory false. Nothing re-stamps origins after an ordinary edit:
+// a later holder of an origin (a split's second half, a copy-drag's
+// copy) is treated as new where it is written (serialize.mjs), so no
+// table update ever follows an edit, an undo or a redo.
+// - The settle plugin runs after every edit: the reparse rule (step 6),
+// then the marker rule, the list rules and the trailing paragraph.
+
+import { Plugin, PluginKey, TextSelection } from 'prosemirror-state'
+import { Fragment } from 'prosemirror-model'
+import { parse, normalise, cleanBody, Item, Quote, Code, Rule } from './markup.mjs'
+import { fromBlocks } from './fromMarkdown.mjs'
+import {
+ docBlocks, contextKey, bareNode, sameNode, serialise, serialiseBlock,
+ serialiseDetailed, structureCheck, docShapes
+} from './serialize.mjs'
+
+export class Fidelity {
+ constructor () {
+ this.issued = 0
+ this.table = new Map()
+ }
+
+ // mint is a fresh origin: never issued before on this page load.
+ mint () { return ++this.issued }
+
+ get (origin) { return this.table.get(origin) }
+
+ // record enters an origin once. An entry is never changed or removed.
+ record (origin, entry) {
+ if (this.table.has(origin)) throw new Error(`origin ${origin} is already recorded`)
+ this.table.set(origin, Object.freeze(entry))
+ }
+}
+
+export const fidelityKey = new PluginKey('mapa-fidelity')
+
+// recordBody gives every block of body a fresh origin and records it:
+// the node that block reads as, its source, its context, and its
+// neighbours and seams within body. It returns the document built with
+// those origins, its blocks (in body order) and the origins.
+export function recordBody (schema, fidelity, body, options = {}) {
+ const text = normalise(body)
+ const blocks = parse(text)
+ const origins = blocks.map(() => fidelity.mint())
+ const doc = fromBlocks(schema, blocks, { origin: index => origins[index], ...options })
+ const nodes = docBlocks(doc).slice(0, blocks.length)
+ const edges = options.edges !== false
+ blocks.forEach((block, index) => {
+ const before = blocks[index - 1]
+ const after = blocks[index + 1]
+ fidelity.record(origins[index], {
+ node: nodes[index].node,
+ source: block.source,
+ context: contextKey(nodes[index]),
+ prev: before ? origins[index - 1] : null,
+ next: after ? origins[index + 1] : null,
+ before: before ? text.slice(before.to, block.from) : null,
+ after: after ? text.slice(block.to, after.from) : null,
+ leading: edges && !before ? text.slice(0, block.from) : null,
+ trailing: edges && !after ? text.slice(block.to) : null
+ })
+ })
+ return { doc, nodes, origins }
+}
+
+// mount is the editor's document for a body, with a new table. Its
+// origins are made with it, so mounting puts nothing in undo history.
+export function mount (schema, body) {
+ const fidelity = new Fidelity()
+ const { doc } = recordBody(schema, fidelity, body)
+ return { doc, fidelity }
+}
+
+// sameBlock is whether a document's block says what a parsed block says:
+// the same node, origins aside and tail aside, in the same context.
+function sameBlock (block, parsed) {
+ return contextKey(block) === contextKey(parsed) &&
+ sameNode(bareNode(block), parsed.node)
+}
+
+// align pairs a's items with b's by a longest common subsequence under
+// same, in order.
+function align (a, b, same) {
+ const rows = a.length
+ const columns = b.length
+ const lengths = Array.from({ length: rows + 1 }, () => new Int32Array(columns + 1))
+ for (let row = rows - 1; row >= 0; row--) {
+ for (let column = columns - 1; column >= 0; column--) {
+ lengths[row][column] = same(a[row], b[column])
+ ? lengths[row + 1][column + 1] + 1
+ : Math.max(lengths[row + 1][column], lengths[row][column + 1])
+ }
+ }
+ const pairs = []
+ for (let row = 0, column = 0; row < rows && column < columns;) {
+ if (same(a[row], b[column])) {
+ pairs.push([row, column])
+ row++
+ column++
+ } else if (lengths[row + 1][column] >= lengths[row][column + 1]) {
+ row++
+ } else {
+ column++
+ }
+ }
+ return pairs
+}
+
+// rebuild is §6.5 step 3: the table rebuilt against body. Every block of
+// parse(body) gets a fresh origin, recorded with its source, context,
+// neighbours and seams from body, and each block of the document that
+// says what one of them says takes that origin. One transaction, marked
+// addToHistory false, changes origin attributes and nothing else.
+// ok is step 4: serialising the document now gives exactly body.
+export function rebuild (view, fidelity, body) {
+ const state = view.state
+ const { nodes, origins } = recordBody(state.schema, fidelity, body)
+ const parsed = nodes.slice(0, origins.length)
+ const current = serialiseDetailed(state.doc, fidelity).emitted
+ const tr = state.tr
+ for (const [mine, theirs] of align(current, parsed, sameBlock)) {
+ tr.setNodeAttribute(current[mine].pos, 'origin', origins[theirs])
+ }
+ tr.setMeta('addToHistory', false).setMeta(fidelityKey, { rebuilt: true })
+ view.dispatch(tr)
+ return { ok: serialise(view.state.doc, fidelity) === cleanBody(body) }
+}
+
+// childKey is what a top-level node says: the shape and Markdown of each
+// block it writes, from its nodes. Empty blocks write nothing, so a node
+// that holds only empty blocks has the key '[]'.
+function childKey (node, schema) {
+ const doc = schema.topNodeType.create(null, node)
+ const { emitted } = serialiseDetailed(doc, null, { raw: true })
+ const shapes = docShapes(emitted)
+ return JSON.stringify(emitted.map((block, index) => [shapes[index], block.text]))
+}
+
+// adoptInto makes tr's document what body says, by top-level node: each
+// node whose key (its shape and Markdown) body still has is kept as it
+// is, origins and all, and so is every node that writes nothing (the
+// empty block you are typing in); the rest are replaced by body's, with
+// fresh origins recorded from body. The selection, when it was in a
+// replaced run, keeps its distance from the end of that run.
+export function adoptInto (tr, fidelity, body) {
+ const schema = tr.doc.type.schema
+ const { doc: target } = recordBody(schema, fidelity, body)
+ const old = []
+ tr.doc.forEach((node, offset) => {
+ const key = childKey(node, schema)
+ if (key !== '[]') old.push({ node, offset, key })
+ })
+ const neu = []
+ target.forEach(node => {
+ const key = childKey(node, schema)
+ if (key !== '[]') neu.push({ node, key })
+ })
+ const pairs = align(old, neu, (a, b) => a.key === b.key)
+ // gaps: [old from, old to), and the new nodes for them, last first.
+ const gaps = []
+ let previous = [-1, -1]
+ for (const pair of [...pairs, [old.length, neu.length]]) {
+ const [oldStart, neuStart] = [previous[0] + 1, previous[1] + 1]
+ if (pair[0] > oldStart || pair[1] > neuStart) {
+ const from = oldStart < old.length
+ ? old[oldStart].offset
+ : (old[old.length - 1] ? old[old.length - 1].offset + old[old.length - 1].node.nodeSize : 0)
+ const to = pair[0] > oldStart
+ ? old[pair[0] - 1].offset + old[pair[0] - 1].node.nodeSize
+ : from
+ gaps.push({ from, to, nodes: neu.slice(neuStart, pair[1]).map(item => item.node) })
+ }
+ previous = pair
+ }
+ const head = tr.selection.head
+ let caret = null
+ for (const gap of gaps.reverse()) {
+ if (caret === null && head >= gap.from && head <= gap.to) {
+ caret = { left: inlineLength(tr.doc, head, gap.to), gap }
+ }
+ // The empty nodes inside a replaced run stay, after the new nodes.
+ const kept = []
+ tr.doc.nodesBetween(gap.from, gap.to, (node, pos) => {
+ if (pos >= gap.from && childKey(node, schema) === '[]') kept.push(node)
+ return false
+ })
+ tr.replaceWith(gap.from, gap.to, Fragment.from([...gap.nodes, ...kept]))
+ gap.size = [...gap.nodes, ...kept].reduce((size, node) => size + node.nodeSize, 0)
+ }
+ if (caret) {
+ const from = tr.mapping.map(caret.gap.from, -1)
+ const at = posBeforeEnd(tr.doc, from, from + caret.gap.size, caret.left)
+ tr.setSelection(TextSelection.near(tr.doc.resolve(at), -1))
+ }
+ return tr
+}
+
+// inlineLength counts the inline units (characters, breaks, atoms)
+// between from and to.
+function inlineLength (doc, from, to) {
+ let count = 0
+ doc.nodesBetween(from, to, (node, pos) => {
+ if (node.isText) {
+ count += Math.min(pos + node.nodeSize, to) - Math.max(pos, from)
+ } else if (node.isInline) {
+ count += 1
+ }
+ })
+ return count
+}
+
+// posBeforeEnd is the position left inline units before to, inside
+// [from, to).
+function posBeforeEnd (doc, from, to, left) {
+ let found = null
+ const textblocks = []
+ doc.nodesBetween(from, to, (node, pos) => {
+ if (node.isTextblock) {
+ textblocks.push({ node, pos })
+ return false
+ }
+ })
+ for (const { node, pos } of textblocks.reverse()) {
+ const size = node.content.size
+ if (left <= size) {
+ found = pos + 1 + size - left
+ break
+ }
+ left -= size
+ }
+ if (found === null) found = textblocks.length ? textblocks[textblocks.length - 1].pos + 1 : from
+ return Math.min(Math.max(found, 0), doc.content.size)
+}
+
+// applyBody makes the document say body, and rebuilds the table against
+// it: adopting the parse (step 5's last resort), and applying a clean
+// merge (§6.5's "Apply" and "Rebuild"). The content change is one
+// ordinary transaction, so undo brings back the person's own text; the
+// rebuild is not in history.
+export function applyBody (view, fidelity, body) {
+ const tr = adoptInto(view.state.tr, fidelity, body)
+ if (tr.docChanged) view.dispatch(tr.scrollIntoView())
+ return rebuild(view, fidelity, body)
+}
+
+// prepareSave is what autosave sends (step 5): the structure check, and,
+// when even writing every block from its node cannot give a body that
+// reloads as this document, the parse adopted as the document. Nothing
+// is sent that would reload as a different document.
+export function prepareSave (view, fidelity) {
+ const check = structureCheck(view.state.doc, fidelity)
+ if (check.ok) return { body: check.body, shapes: check.shapes, adopted: false }
+ applyBody(view, fidelity, check.body)
+ const again = structureCheck(view.state.doc, fidelity)
+ return { body: again.body, shapes: again.shapes, adopted: true }
+}
+
+// The reparse rule (step 6). A block is written from its node and parsed
+// again; when that is not exactly the block, the block becomes what the
+// parse says. One block of the same kind is updated in place, so the
+// caret stays where it was; anything else adopts the parse.
+const kept = {
+ paragraph: ['marker'],
+ heading: ['level', 'marker'],
+ code_block: ['fence', 'info', 'closed', 'close'],
+ list_item: ['indent', 'bullet', 'number', 'delim', 'task', 'checked', 'marker'],
+ blockquote: ['prefix', 'marker']
+}
+
+function attrsOf (block) {
+ return block.kind === Item || block.kind === Quote ? block.holder : block.node
+}
+
+export function reparseBlock (block, schema) {
+ if (block.kind === Rule) return null
+ const text = serialiseBlock(block)
+ if (text === '') return null
+ const parsed = parse(text)
+ if (parsed.length !== 1 || parsed[0].kind !== block.kind) return 'structural'
+ const ref = docBlocks(fromBlocks(schema, parsed, { trailing: false }))[0]
+ if (block.kind === Item && ref.list !== block.list) return 'structural'
+ const mine = attrsOf(block)
+ const theirs = attrsOf(ref)
+ const attrs = []
+ for (const name of kept[mine.type.name] ?? []) {
+ if (JSON.stringify(mine.attrs[name]) !== JSON.stringify(theirs.attrs[name])) {
+ attrs.push([name, theirs.attrs[name]])
+ }
+ }
+ const have = bareNode(block).content
+ const want = ref.node.content
+ const start = have.findDiffStart(want)
+ if (start === null && attrs.length === 0) return null
+ let diff = null
+ if (start !== null) {
+ let { a: endA, b: endB } = have.findDiffEnd(want)
+ const overlap = start - Math.min(endA, endB)
+ if (overlap > 0) {
+ endA += overlap
+ endB += overlap
+ }
+ diff = { from: start, to: endA, content: want.cut(start, endB) }
+ }
+ return { block, attrs, diff, text, node: ref.node }
+}
+
+function applyReparse (tr, { block, attrs, diff }, origin) {
+ if (diff) {
+ const at = block.pos + 1
+ tr.replaceWith(at + diff.from, at + diff.to, diff.content)
+ }
+ const pos = block.kind === Item || block.kind === Quote ? block.holderPos : block.pos
+ for (const [name, value] of attrs) tr.setNodeAttribute(pos, name, value)
+ tr.setNodeAttribute(block.pos, 'origin', origin)
+}
+
+// reparse checks the blocks of state's document that are not in oldDoc
+// (every block, without it) and returns the transaction that settles
+// them, or null.
+export function reparse (state, fidelity, oldDoc = null) {
+ const tr = state.tr
+ reparseInto(tr, fidelity, oldDoc)
+ return tr.docChanged ? tr : null
+}
+
+// changedBlocks is the blocks of doc that oldDoc did not hold, in the
+// same context (all of them without it), less the untouched ones: an
+// untouched block re-emits its source, which is what the Markdown says by
+// definition. Undo bringing a block back is not an edit to it; an item
+// carried into a list of the other kind is.
+function changedBlocks (detail, oldDoc) {
+ const blocks = detail.blocks.filter(block => !block.untouched)
+ if (!oldDoc) return blocks
+ const before = new Map(docBlocks(oldDoc).map(block => [block.node, contextKey(block)]))
+ return blocks.filter(block => before.get(block.node) !== contextKey(block))
+}
+
+// reparseInto settles the changed blocks of tr's document. A block the
+// reparse replaces takes a fresh origin, recorded with the Markdown it was
+// written as (which is what it now is), its neighbours and the seams
+// written beside it: so it re-emits those bytes, and a second reparse
+// finds nothing to do, even where writing the parse back would not give
+// the same parse (text holding a "*" inside a mark).
+function reparseInto (tr, fidelity, oldDoc) {
+ const schema = tr.doc.type.schema
+ const detail = serialiseDetailed(tr.doc, fidelity)
+ const updates = []
+ for (const block of changedBlocks(detail, oldDoc)) {
+ const update = reparseBlock(block, schema)
+ if (update === 'structural') {
+ adoptInto(tr, fidelity, detail.body)
+ return
+ }
+ if (update) updates.push(update)
+ }
+ if (updates.length === 0) return
+ const fresh = new Map(updates.map(update => [update.block, fidelity.mint()]))
+ const originOf = block => fresh.get(block) ?? (block.first ? block.origin : null)
+ const { emitted } = detail
+ const entries = updates.map(({ block, text, node }) => {
+ const at = emitted.indexOf(block)
+ const before = emitted[at - 1]
+ const after = emitted[at + 1]
+ const origin = fresh.get(block)
+ return {
+ origin,
+ source: text,
+ node: node.type.create({ ...node.attrs, origin }, node.content, node.marks),
+ prev: before ? originOf(before) : null,
+ next: after ? originOf(after) : null,
+ before: before ? block.seam : null,
+ after: after ? after.seam : null,
+ leading: at === 0 ? block.entry?.leading ?? null : null,
+ trailing: at >= 0 && !after ? block.entry?.trailing ?? null : null
+ }
+ })
+ for (const update of [...updates].reverse()) applyReparse(tr, update, fresh.get(update.block))
+ const placed = new Map(docBlocks(tr.doc).map(block => [block.node.attrs.origin, block]))
+ for (const { origin, ...entry } of entries) {
+ fidelity.record(origin, { ...entry, context: contextKey(placed.get(origin)) })
+ }
+}
+
+// markerRule is step 1's: only the first holder keeps a marker. A marker
+// held more often than before the edit (or than once) is taken from its
+// newest holders, last first; markers a stored body already repeats are
+// left as the body has them.
+function markerRule (tr, oldDoc) {
+ const count = 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
+ }
+ const before = oldDoc ? count(oldDoc) : new Map()
+ const oldHolders = new Set(oldDoc ? docBlocks(oldDoc).map(block => block.holder) : [])
+ const blocks = docBlocks(tr.doc)
+ for (const [marker, held] of count(tr.doc)) {
+ let extra = held - Math.max(before.get(marker) ?? 0, 1)
+ if (extra <= 0) continue
+ const [, ...later] = blocks.filter(block => block.holder.attrs.marker === marker)
+ const order = [...later.filter(block => !oldHolders.has(block.holder)).reverse(),
+ ...later.filter(block => oldHolders.has(block.holder)).reverse()]
+ for (const block of order.slice(0, extra)) {
+ tr.setNodeAttribute(block.holderPos, 'marker', null)
+ }
+
+ }
+}
+
+// indentLevel is markup's item level for an indent.
+function indentLevel (indent) {
+ return Math.floor(String(indent ?? '').replaceAll('\t', ' ').length / 2)
+}
+
+// listRule keeps each item's indent saying the depth it is drawn at
+// (§6.3: a moved item's indent is two spaces per depth), so the body
+// nests the way the document does; and joins two lists of one kind that
+// have come to sit side by side, which the body would read as one.
+function listRule (tr, fidelity) {
+ let previous = -1
+ for (const block of serialiseDetailed(tr.doc, fidelity).emitted) {
+ if (block.kind !== Item) {
+ previous = -1
+ continue
+ }
+ const level = indentLevel(block.holder.attrs.indent)
+ const indent = ' '.repeat(block.depth)
+ // An indent can say any depth up to one under the item above; an
+ // item drawn deeper (under an empty item, which is not written) is
+ // left to the structure check.
+ if (Math.min(level, previous + 1) !== block.depth && block.depth <= previous + 1 &&
+ block.holder.attrs.indent !== indent) {
+ tr.setNodeAttribute(block.holderPos, 'indent', indent)
+ }
+ previous = block.depth
+ }
+ const joins = []
+ const siblings = (node, start) => {
+ let offset = start
+ let last = null
+ node.forEach(child => {
+ if (last && last.type === child.type && (child.type.name === 'bullet_list' ||
+ child.type.name === 'ordered_list')) joins.push(offset)
+ last = child
+ offset += child.nodeSize
+ })
+ }
+ siblings(tr.doc, 0)
+ tr.doc.descendants((node, pos) => {
+ if (node.isTextblock) return false
+ siblings(node, pos + 1)
+ })
+ for (const pos of joins.sort((a, b) => b - a)) tr.join(pos)
+}
+
+// The document always ends in a paragraph (§6.2).
+function trailingRule (tr) {
+ const last = tr.doc.lastChild
+ if (!last || last.type.name !== 'paragraph') {
+ tr.insert(tr.doc.content.size, tr.doc.type.schema.nodes.paragraph.create())
+ }
+}
+
+// settle is what follows an edit: the reparse, then the marker, list and
+// trailing paragraph rules, repeated over what they changed until nothing
+// changes (ProseMirror never shows a plugin its own appended transaction,
+// so one call must finish the job). It returns a transaction, or null
+// when the document already says what its Markdown says.
+export function settle (state, fidelity, oldDoc = null) {
+ const tr = state.tr
+ for (let round = 0; round < 4; round++) {
+ const start = tr.doc
+ // Each round looks at every block the edit changed: a block a round
+ // has settled is untouched (or already says its parse) by then.
+ reparseInto(tr, fidelity, oldDoc)
+ markerRule(tr, oldDoc)
+ listRule(tr, fidelity)
+ trailingRule(tr)
+ if (tr.doc === start) break
+ }
+ return tr.docChanged ? tr : null
+}
+
+// fidelityPlugin runs settle after each transaction that changes the
+// document, and holds it while an IME is composing (the reparse waits
+// for compositionend, §6.11). options.composing replaces the view's
+// flag, for tests.
+export function fidelityPlugin (fidelity, options = {}) {
+ let editorView = null
+ let pending = null
+ const composing = () => options.composing ? options.composing() : editorView?.composing ?? false
+ return new Plugin({
+ key: fidelityKey,
+ state: { init: () => fidelity, apply: (tr, value) => value },
+ view (view) {
+ editorView = view
+ return { destroy () { editorView = null } }
+ },
+ props: {
+ handleDOMEvents: {
+ compositionend (view) {
+ setTimeout(() => {
+ if (editorView === view && pending) {
+ view.dispatch(view.state.tr.setMeta(fidelityKey, { composed: true }))
+ }
+ }, 50)
+ return false
+ }
+ }
+ },
+ appendTransaction (trs, oldState, newState) {
+ const changed = trs.some(tr => tr.docChanged && !tr.getMeta(fidelityKey)?.rebuilt)
+ if (!changed && !pending) return null
+ if (composing()) {
+ pending = pending ?? oldState.doc
+ return null
+ }
+ const since = pending ?? oldState.doc
+ pending = null
+ const tr = settle(newState, fidelity, since)
+ return tr ? tr.setMeta(fidelityKey, { settled: true }) : null
+ }
+ })
+}
+
+export { serialise, structureCheck }
diff --git a/editor/serialize.mjs b/editor/serialize.mjs
new file mode 100644
index 0000000..8274aee
--- /dev/null
+++ b/editor/serialize.mjs
@@ -0,0 +1,484 @@
+// serialize.mjs — the editor's document as Mapa Markdown (spec §6.4).
+//
+// A block nobody touched is written back from the source it was read
+// from, byte for byte, and the bytes between two blocks that were
+// neighbours when they were read are kept. Everything else is written
+// from its node, with the syntax its kept attributes record. The side
+// table that holds sources and seams is fidelity.mjs's; this file only
+// reads it, through table.get(origin).
+//
+// A Mapa block is one textblock, or one rule (§6.3). docBlocks lists
+// them in document order, which is the order markup.parse gives them.
+
+import {
+ parse, cleanBody, normalise, goTrimSpace, spans, isDate, isRuleLine,
+ isFenceLine, fenceOf, closesFence,
+ Paragraph, Heading, Item, Code, Quote, Rule, WikiLink, Embed
+} from './markup.mjs'
+import { fromBlocks } from './fromMarkdown.mjs'
+
+const lists = new Set(['bullet_list', 'ordered_list'])
+
+// docBlocks is a document's Mapa blocks, each with:
+// - kind, as markup names it, and node, the textblock (or rule) that
+// holds its origin, at pos;
+// - holder, the node that holds its ^id (the list_item or blockquote
+// around an item's or quote's paragraph), at holderPos;
+// - for an item: depth, list (its list's type), listPos and listStart.
+export function docBlocks (doc) {
+ const out = []
+ doc.forEach((child, offset) => topBlock(child, offset, out))
+ return out
+}
+
+function push (out, block) {
+ block.index = out.length
+ out.push(block)
+}
+
+function topBlock (node, pos, out) {
+ switch (node.type.name) {
+ case 'paragraph':
+ return push(out, { kind: Paragraph, node, pos, holder: node, holderPos: pos })
+ case 'heading':
+ return push(out, { kind: Heading, node, pos, holder: node, holderPos: pos })
+ case 'code_block':
+ return push(out, { kind: Code, node, pos, holder: node, holderPos: pos })
+ case 'horizontal_rule':
+ return push(out, { kind: Rule, node, pos, holder: node, holderPos: pos })
+ case 'blockquote':
+ if (node.firstChild?.type.name === 'paragraph') {
+ push(out, {
+ kind: Quote, node: node.firstChild, pos: pos + 1, holder: node, holderPos: pos
+ })
+ }
+ return
+ }
+ if (lists.has(node.type.name)) listBlocks(node, pos, 0, out)
+}
+
+function listBlocks (list, pos, depth, out) {
+ list.forEach((item, offset, index) => {
+ const itemPos = pos + 1 + offset
+ item.forEach((child, childOffset, childIndex) => {
+ const childPos = itemPos + 1 + childOffset
+ if (childIndex === 0 && child.type.name === 'paragraph') {
+ push(out, {
+ kind: Item, node: child, pos: childPos, holder: item, holderPos: itemPos,
+ depth, list: list.type.name, listPos: pos, listStart: index === 0
+ })
+ } else if (lists.has(child.type.name)) {
+ listBlocks(child, childPos, depth + 1, out)
+ }
+ })
+ })
+}
+
+// contextKey is what, besides its own node, decides how a block is
+// written: its kind, and an item's list attributes, depth and list kind,
+// or a quote's prefixes and ^id (§6.4 step 1).
+export function contextKey (block) {
+ const attrs = block.holder.attrs
+ switch (block.kind) {
+ case Item:
+ return JSON.stringify([Item, block.depth, block.list, attrs.indent,
+ attrs.bullet, attrs.number, attrs.delim, attrs.task, attrs.checked,
+ attrs.marker])
+ case Quote:
+ return JSON.stringify([Quote, attrs.prefix, attrs.marker])
+ }
+ return block.kind
+}
+
+// The tail: a textblock's trailing hard breaks, and the blank text after
+// them, have no Markdown form outside a quote (a blank line ends a
+// block). Like an empty block, the editor keeps them on screen while you
+// type and writes nothing for them.
+function tailStart (node) {
+ let pos = node.content.size
+ let start = null
+ for (let index = node.childCount - 1; index >= 0; index--) {
+ const child = node.child(index)
+ if (child.type.name === 'hard_break') start = pos - child.nodeSize
+ else if (!(child.isText && goTrimSpace(child.text) === '')) break
+ pos -= child.nodeSize
+ }
+ return start
+}
+
+// bareNode is a block's node without its tail.
+export function bareNode (block) {
+ if (block.kind === Quote || block.kind === Code || block.kind === Rule) {
+ return block.node
+ }
+ const start = tailStart(block.node)
+ if (start === null) return block.node
+ return block.node.copy(block.node.content.cut(0, start))
+}
+
+// isUntouched is §6.4 step 2: the first holder of its origin (decided by
+// the caller), equal to the node its entry recorded, in the same context.
+// A tail added since does not count as a change: it is written as
+// nothing either way. Nor does a heading's source attribute, which
+// records the line it was read from and is never drawn or reparsed.
+export function isUntouched (block, entry) {
+ if (!entry) return false
+ const node = block.node
+ if (node !== entry.node && !node.eq(entry.node) &&
+ !sameNode(bareNode(block), entry.node)) return false
+ return contextKey(block) === entry.context
+}
+
+// sameNode is eq, except that origins and a heading's source are not
+// compared (the caller has already matched origins, or is assigning one).
+export function sameNode (node, other) {
+ if (node.type !== other.type || !node.content.eq(other.content)) return false
+ for (const name of Object.keys(node.attrs)) {
+ if (name === 'origin') continue
+ if (name === 'source' && node.type.name === 'heading') continue
+ if (JSON.stringify(node.attrs[name]) !== JSON.stringify(other.attrs[name])) {
+ return false
+ }
+ }
+ return true
+}
+
+// serialiseBlock writes one block from its node (§6.4 step 4). last says
+// whether nothing follows it: a fence that is not last must be closed.
+// An empty block is written as nothing ('').
+export function serialiseBlock (block, { last = true } = {}) {
+ const node = block.node
+ switch (block.kind) {
+ case Paragraph: {
+ const text = inline(bareNode(block))
+ return blank(text) ? '' : text + markerTail(block)
+ }
+ case Heading: {
+ const text = inline(bareNode(block))
+ return blank(text) ? '' : headingPrefix(node.attrs) + text + markerTail(block)
+ }
+ case Item:
+ return itemText(block)
+ case Quote:
+ return quoteText(block)
+ case Code:
+ return codeText(node, last)
+ case Rule:
+ return isRuleLine(node.attrs.source ?? '') ? node.attrs.source : '---'
+ }
+ return ''
+}
+
+function blank (text) { return goTrimSpace(text) === '' }
+
+function markerTail (block) {
+ const marker = block.holder.attrs.marker
+ return marker && /^[A-Za-z0-9-]{1,40}$/u.test(marker) ? ` ^${marker}` : ''
+}
+
+function headingPrefix (attrs) {
+ const level = Math.min(Math.max(attrs.level ?? 1, 1), 6)
+ const kept = /^(#{1,6})([ \t]+)/u.exec(attrs.source ?? '')
+ if (kept && kept[1].length === level) return kept[0]
+ return '#'.repeat(level) + ' '
+}
+
+function itemText (block) {
+ const attrs = block.holder.attrs
+ const text = inline(bareNode(block))
+ if (blank(text)) return ''
+ const indent = /^[ \t]*$/u.test(attrs.indent ?? '') ? attrs.indent ?? '' : ''
+ let mark
+ if (block.list === 'ordered_list') {
+ const number = /^[0-9]{1,9}$/u.test(attrs.number ?? '') ? attrs.number : '1'
+ mark = number + (attrs.delim === ')' ? ')' : '.')
+ } else {
+ mark = ['-', '*', '+'].includes(attrs.bullet) ? attrs.bullet : '-'
+ }
+ const box = attrs.task
+ ? `[${[' ', 'x', 'X'].includes(attrs.checked) ? attrs.checked : ' '}] `
+ : ''
+ return `${indent}${mark} ${box}${text}${markerTail(block)}`
+}
+
+// quoteText puts each line's own prefix back. A quote keeps its tail: a
+// line of only ">" is a line of the quote.
+function quoteText (block) {
+ const text = inline(block.node)
+ if (text === '') return ''
+ const prefixes = Array.isArray(block.holder.attrs.prefix)
+ ? block.holder.attrs.prefix
+ : []
+ return (text + markerTail(block)).split('\n').map((line, index) => {
+ let prefix = prefixes[index] ?? prefixes[0] ?? '> '
+ if (!/^ *> ?$/u.test(prefix)) prefix = '> '
+ // quoteText drops one space after the ">": a line that starts with
+ // a space needs that space written.
+ if (!prefix.endsWith(' ') && line.startsWith(' ')) prefix += ' '
+ return prefix + line
+ }).join('\n')
+}
+
+function codeText (node, last) {
+ const attrs = node.attrs
+ const open = /^ {0,3}(?:`{3,}|~{3,})$/u.test(attrs.fence ?? '') ? attrs.fence : '```'
+ let out = open + String(attrs.info ?? '').split('\n')[0]
+ if (node.textContent !== '') out += '\n' + node.textContent
+ if (attrs.close != null && isFenceLine(attrs.close)) out += '\n' + attrs.close
+ if (!last && !fenceClosed(out)) out += '\n' + open.trimStart()
+ return out
+}
+
+// fenceClosed is whether a fence's source ends with its closing line.
+export function fenceClosed (source) {
+ const lines = source.split('\n')
+ return lines.length > 1 && closesFence(lines[lines.length - 1], fenceOf(lines[0]))
+}
+
+// inline writes a textblock's content. Marks follow §6.3: a mark never
+// spans code, a link or an atom, so each run of plain text between them
+// takes its emphasis on its own; em goes outside strong; whitespace at a
+// mark's edge goes outside its delimiters.
+export function inline (node) {
+ const pieces = []
+ node.forEach(child => {
+ const has = name => child.marks.some(mark => mark.type.name === name)
+ if (child.isText) {
+ const link = child.marks.find(mark => mark.type.name === 'link')
+ const last = pieces[pieces.length - 1]
+ if (has('code')) {
+ if (last?.kind === 'code') last.text += child.text
+ else pieces.push({ kind: 'code', text: child.text })
+ } else if (link) {
+ if (last?.kind === 'link' && last.mark.eq(link)) last.text += child.text
+ else pieces.push({ kind: 'link', text: child.text, mark: link })
+ } else {
+ pieces.push({ kind: 'text', text: child.text, em: has('em'), strong: has('strong') })
+ }
+ } else if (child.type.name === 'hard_break') {
+ const indent = /^[ \t]*/u.exec(child.attrs.indent ?? '')[0]
+ pieces.push({ kind: 'text', text: '\n' + indent, em: has('em'), strong: has('strong') })
+ } else {
+ pieces.push({ kind: 'atom', text: atomSource(child) })
+ }
+ })
+ let out = ''
+ for (let index = 0; index < pieces.length;) {
+ const piece = pieces[index]
+ if (piece.kind === 'text') {
+ let end = index
+ while (end < pieces.length && pieces[end].kind === 'text') end++
+ out += emphasis(pieces.slice(index, end))
+ index = end
+ continue
+ }
+ if (piece.kind === 'code') out += '`' + piece.text + '`'
+ else if (piece.kind === 'link') out += linkText(piece)
+ else out += piece.text
+ index++
+ }
+ return normalise(out)
+}
+
+function linkText ({ text, mark }) {
+ if (mark.attrs.bare && text === mark.attrs.href) return text
+ return `[${text}](${mark.attrs.href})`
+}
+
+function emphasis (run) {
+ return groups(run, 'em', part => strongs(part), '*')
+}
+
+function strongs (run) {
+ return groups(run, 'strong', part => part.map(piece => piece.text).join(''), '**')
+}
+
+// groups wraps each stretch of run that has the mark in delim.
+function groups (run, mark, inner, delim) {
+ let out = ''
+ for (let index = 0; index < run.length;) {
+ let end = index
+ while (end < run.length && run[end][mark] === run[index][mark]) end++
+ const text = inner(run.slice(index, end))
+ out += run[index][mark] ? wrap(text, delim) : text
+ index = end
+ }
+ return out
+}
+
+// wrap puts text in delim with its edge whitespace (Go's ASCII \s)
+// outside, because a delimiter needs a non-space beside it.
+function wrap (text, delim) {
+ const parts = /^([\t\n\f\r ]*)([^]*?)([\t\n\f\r ]*)$/u.exec(text)
+ if (parts[2] === '') return text
+ return parts[1] + delim + parts[2] + delim + parts[3]
+}
+
+// atomSource is an atom's Markdown: its source while that still says
+// exactly what the atom holds, otherwise written from its attributes.
+export function atomSource (node) {
+ const attrs = node.attrs
+ if (attrs.source != null && atomSays(node, attrs.source)) return attrs.source
+ if (node.type.name === 'embed') return `![[${attrs.ref}]]`
+ const target = node.type.name === 'datelink' ? attrs.date : attrs.target
+ return `[[${target}${attrs.anchor ? '#^' + attrs.anchor : ''}` +
+ `${attrs.shown ? '|' + attrs.shown : ''}]]`
+}
+
+function atomSays (node, source) {
+ const found = spans(source)
+ if (found.length !== 1 || found[0].source !== source) return false
+ const span = found[0]
+ if (node.type.name === 'embed') {
+ return span.kind === Embed && span.text.slice(3, -2) === node.attrs.ref
+ }
+ if (span.kind !== WikiLink) return false
+ const date = node.type.name === 'datelink'
+ return isDate(span.target) === date &&
+ span.target === (date ? node.attrs.date : node.attrs.target) &&
+ span.anchor === (node.attrs.anchor ?? '') &&
+ span.text === (node.attrs.shown ?? '')
+}
+
+// serialiseDetailed is serialise with its working: every block, with
+// first (first holder of its origin), entry, untouched and text, and for
+// each written block after the first, the seam written before it.
+//
+// options:
+// - fresh: block indexes written from their nodes whatever the table says;
+// - joins: block indexes whose seam before them follows Join;
+// - edges: false leaves out the leading and trailing bytes (a copied slice);
+// - raw: true skips cleanBody's rule.
+export function serialiseDetailed (doc, table, options = {}) {
+ const fresh = options.fresh ?? new Set()
+ const joins = options.joins ?? new Set()
+ const blocks = docBlocks(doc)
+ const holders = new Set()
+ for (const block of blocks) {
+ const origin = block.node.attrs.origin
+ block.origin = origin
+ block.first = origin != null && !holders.has(origin)
+ if (origin != null) holders.add(origin)
+ block.entry = block.first ? table?.get(origin) : undefined
+ block.untouched = !fresh.has(block.index) && isUntouched(block, block.entry)
+ block.text = block.untouched ? block.entry.source : serialiseBlock(block)
+ }
+ // A fence that is no longer last is closed: an untouched one whose
+ // source runs to the end is written from its node instead (step 5).
+ let last = -1
+ blocks.forEach((block, index) => { if (block.text !== '') last = index })
+ for (const block of blocks.slice(0, Math.max(last, 0))) {
+ if (block.kind !== Code) continue
+ if (block.untouched && fenceClosed(block.text)) continue
+ block.untouched = false
+ block.text = serialiseBlock(block, { last: false })
+ }
+ const emitted = blocks.filter(block => block.text !== '')
+ let out = ''
+ emitted.forEach((block, index) => {
+ if (index === 0) {
+ if (options.edges !== false && block.entry?.leading != null) {
+ out += block.entry.leading
+ }
+ } else {
+ block.seam = seam(emitted[index - 1], block, joins.has(block.index))
+ out += block.seam
+ }
+ out += block.text
+ })
+ const end = emitted[emitted.length - 1]
+ if (options.edges !== false && end?.entry?.trailing != null) {
+ out += end.entry.trailing
+ }
+ return { body: options.raw ? normalise(out) : cleanBody(out), blocks, emitted }
+}
+
+// serialise is the document's Mapa Markdown (§6.4).
+export function serialise (doc, table, options) {
+ return serialiseDetailed(doc, table, options).body
+}
+
+// seam is step 3: the bytes recorded between two blocks the table says
+// were neighbours, else Join's rule.
+function seam (before, after, forced) {
+ if (!forced && before.first && after.first) {
+ if (before.entry && before.entry.next === after.origin &&
+ before.entry.after != null) return before.entry.after
+ if (after.entry && after.entry.prev === before.origin &&
+ after.entry.before != null) return after.entry.before
+ }
+ return joinSeam(before.kind, after.kind)
+}
+
+// joinSeam is markup.Join's: one blank line, or one newline between two
+// list items.
+export function joinSeam (before, after) {
+ return before === Item && after === Item ? '\n' : '\n\n'
+}
+
+// shape is what the structure check compares (step 5): kind, a heading's
+// level, and where an item sits: its list kind, its depth, and whether it
+// opens a list. listStart counts only blocks that are written.
+function shapes (emitted) {
+ const seenLists = new Set()
+ return emitted.map(block => {
+ if (block.kind === Heading) {
+ return `${Heading}:${Math.min(Math.max(block.node.attrs.level, 1), 6)}`
+ }
+ if (block.kind !== Item) return block.kind
+ const start = !seenLists.has(block.listPos)
+ seenLists.add(block.listPos)
+ return `${Item}:${block.list}:${block.depth}:${start}`
+ })
+}
+
+// bodyShapes is the shape of the document a body would reload as.
+export function bodyShapes (schema, body) {
+ return shapes(docBlocks(fromBlocks(schema, parse(body), { trailing: false })))
+}
+
+export function docShapes (emitted) { return shapes(emitted) }
+
+function firstMismatch (want, got) {
+ const length = Math.min(want.length, got.length)
+ for (let index = 0; index < length; index++) {
+ if (want[index] !== got[index]) return index
+ }
+ return want.length === got.length ? -1 : length
+}
+
+// structureCheck is step 5, before every autosave: parse(serialise(doc))
+// must give the document's blocks (empty blocks and the trailing
+// paragraph, which are written as nothing, left out). Failing that, the
+// offending blocks' seams follow Join, then those blocks are written from
+// their nodes, then every block is. ok false means even that failed and
+// the caller adopts the parse (fidelity.prepareSave). shapes are the
+// document's blocks as checked: what the body must parse as.
+export function structureCheck (doc, table) {
+ const schema = doc.type.schema
+ const attempt = options => {
+ const result = serialiseDetailed(doc, table, options)
+ result.shapes = shapes(result.emitted)
+ result.mismatch = firstMismatch(result.shapes, bodyShapes(schema, result.body))
+ return result
+ }
+ const fresh = new Set()
+ const joins = new Set()
+ let result = attempt({})
+ for (let round = 0; result.mismatch >= 0 && round < 4; round++) {
+ const near = [-1, 0, 1, 2].map(step => result.emitted[result.mismatch + step])
+ for (const block of near) {
+ if (!block) continue
+ joins.add(block.index)
+ if (round >= 2) fresh.add(block.index)
+ }
+ result = attempt({ fresh, joins })
+ }
+ if (result.mismatch >= 0) {
+ const every = new Set(result.blocks.map(block => block.index))
+ result = attempt({ fresh: every, joins: every })
+ }
+ return {
+ ok: result.mismatch < 0, body: result.body, shapes: result.shapes, fixed: joins.size > 0
+ }
+}
diff --git a/editor/serialize.test.mjs b/editor/serialize.test.mjs
new file mode 100644
index 0000000..6d96d13
--- /dev/null
+++ b/editor/serialize.test.mjs
@@ -0,0 +1,215 @@
+// serialize.test.mjs — the serialiser's and the fidelity rules' cases,
+// one at a time (spec §6.3, §6.4, §6.6). The corpus-wide gates are in
+// fidelity.test.mjs.
+
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { TextSelection } from 'prosemirror-state'
+import { undo, undoDepth } from 'prosemirror-history'
+import { liftListItem } from 'prosemirror-schema-list'
+import { schema, editor } from './testkit.mjs'
+import { serialise, structureCheck } from './serialize.mjs'
+import { fromMarkdown } from './fromMarkdown.mjs'
+import { mount, settle, rebuild, applyBody, prepareSave } from './fidelity.mjs'
+import { copyData, pasteTransaction, textSlice } from './clipboard.mjs'
+import { EditorState } from 'prosemirror-state'
+
+const text = (words, ...marks) =>
+ schema.text(words, marks.map(name => schema.marks[name].create()))
+const paragraph = (...content) =>
+ schema.nodes.doc.create(null, [schema.nodes.paragraph.create(null, content)])
+const write = doc => serialise(doc, null)
+
+// position of the end of the first textblock whose text is words.
+function at (doc, words, offset = words.length) {
+ let found = null
+ doc.descendants((node, pos) => {
+ if (found === null && node.isTextblock && node.textContent === words) found = pos + 1 + offset
+ })
+ assert.notEqual(found, null, `no block reads ${words}`)
+ return found
+}
+
+test('marks: em outside strong, bold reopened around italics, edges outside', () => {
+ const cases = [
+ [paragraph(text('a ', 'strong'), text('b', 'em', 'strong'), text(' c', 'strong')),
+ '**a** ***b*** **c**'],
+ [paragraph(text('a ', 'em'), text('b', 'em', 'strong'), text(' c', 'em')), '*a **b** c*'],
+ [paragraph(text('x', 'em', 'strong')), '***x***'],
+ [paragraph(text('x'), text(' a ', 'em'), text('y')), 'x *a* y'],
+ [paragraph(text('one '), text('two three', 'strong'), text('.')), 'one **two three**.']
+ ]
+ for (const [doc, want] of cases) {
+ assert.equal(write(doc), want)
+ // Read back, the marks are the same, give or take a space's.
+ assert.equal(write(fromMarkdown(schema, want)), want, `${want} reads back`)
+ assert.equal(fromMarkdown(schema, want).textContent, doc.textContent)
+ }
+})
+
+test('marks close before code, links and atoms, and reopen after', () => {
+ const link = schema.marks.link.create({ href: 'https://x.y' })
+ const chip = schema.nodes.wikilink.create({ target: 'Acme' })
+ assert.equal(write(paragraph(text('a ', 'em'), text('c', 'code'), text(' b', 'em'))),
+ '*a* `c` *b*')
+ assert.equal(write(paragraph(text('a ', 'em'), schema.text('l', [link]), text(' b', 'em'))),
+ '*a* [l](https://x.y) *b*')
+ assert.equal(write(paragraph(text('a ', 'em'), chip, text(' b', 'em'))), '*a* [[Acme]] *b*')
+})
+
+test('untouched blocks and atoms re-emit their source; edited atoms are written from attributes', () => {
+ const body = '[[ Acme |the firm]] and ![[fichas:c1]]\n\n- wide\n\n##\tTabbed ^h1'
+ const { view, fidelity } = editor(body)
+ assert.equal(serialise(view.state.doc, fidelity), body)
+ view.dispatch(view.state.tr.insertText('!', at(view.state.doc, 'wide')))
+ assert.equal(serialise(view.state.doc, fidelity),
+ '[[ Acme |the firm]] and ![[fichas:c1]]\n\n- wide!\n\n##\tTabbed ^h1')
+ view.dispatch(view.state.tr.insertText('?', at(view.state.doc, 'Tabbed')))
+ assert.equal(serialise(view.state.doc, fidelity),
+ '[[ Acme |the firm]] and ![[fichas:c1]]\n\n- wide!\n\n##\tTabbed? ^h1')
+})
+
+test('empty blocks are written as nothing', () => {
+ const { view, fidelity } = editor('# Title\n\n- a\n\npara\n\n## b')
+ for (const words of ['a', 'para', 'b']) {
+ const end = at(view.state.doc, words)
+ view.dispatch(view.state.tr.delete(end - words.length, end))
+ }
+ assert.equal(serialise(view.state.doc, fidelity), '# Title')
+ assert.deepEqual(view.state.doc.content.content.map(node => node.content.size === 0),
+ [false, false, true, true, true], 'the empty blocks stay on screen')
+})
+
+test('an unclosed fence that is no longer last gets its closing fence', () => {
+ const { view, fidelity } = editor('```js\nlet a = 1')
+ const end = view.state.doc.content.size
+ view.dispatch(view.state.tr.insertText('after', end - 1))
+ assert.equal(serialise(view.state.doc, fidelity), '```js\nlet a = 1\n```\n\nafter')
+ assert.equal(structureCheck(view.state.doc, fidelity).ok, true)
+})
+
+test('the structure check puts Join\'s seam where a kept one would merge two blocks', () => {
+ const { view, fidelity } = editor('- a\n- b')
+ view.dispatch(view.state.tr.setSelection(
+ TextSelection.create(view.state.doc, at(view.state.doc, 'b'))))
+ view.run(liftListItem(schema.nodes.list_item))
+ assert.equal(view.state.doc.child(1).type.name, 'paragraph')
+ const check = structureCheck(view.state.doc, fidelity)
+ assert.equal(check.ok, true)
+ assert.equal(check.body, '- a\n\nb')
+})
+
+test('prepareSave adopts the parse when no seam or rewrite can save the document', () => {
+ // No settle plugin: a paragraph that says "- a" is left as it is.
+ const { doc, fidelity } = mount(schema, 'x')
+ const view = {
+ state: EditorState.create({ doc }),
+ dispatch (tr) { this.state = this.state.apply(tr) }
+ }
+ view.dispatch(view.state.tr.insertText('- a', 1, 2))
+ assert.equal(structureCheck(view.state.doc, fidelity).ok, false)
+ const { body, adopted } = prepareSave(view, fidelity)
+ assert.equal(adopted, true)
+ assert.equal(body, '- a')
+ assert.equal(view.state.doc.firstChild.type.name, 'bullet_list')
+ assert.equal(serialise(view.state.doc, fidelity), body)
+})
+
+test('reparse: typed emphasis becomes a mark, "- " after a break becomes an item', () => {
+ const { view, fidelity } = editor('hello')
+ view.dispatch(view.state.tr.insertText(' *word*', at(view.state.doc, 'hello')))
+ const marks = []
+ view.state.doc.firstChild.forEach(node => marks.push([node.text, node.marks.map(m => m.type.name)]))
+ assert.deepEqual(marks, [['hello ', []], ['word', ['em']]])
+ view.dispatch(view.state.tr.insert(view.state.doc.firstChild.nodeSize - 1,
+ schema.nodes.hard_break.create()))
+ view.dispatch(view.state.tr.insertText('- item', view.state.doc.firstChild.nodeSize - 1))
+ assert.deepEqual(view.state.doc.content.content.map(node => node.type.name),
+ ['paragraph', 'bullet_list', 'paragraph'])
+ // The line typed is kept as typed: a list right under a paragraph.
+ assert.equal(serialise(view.state.doc, fidelity), 'hello *word*\n- item')
+ assert.ok(settle(view.state, fidelity) === null, 'reparse is idempotent')
+})
+
+test('a trailing hard break stays on screen and is written as nothing', () => {
+ const { view, fidelity } = editor('- item\n\nnext')
+ view.dispatch(view.state.tr.insert(at(view.state.doc, 'item'), schema.nodes.hard_break.create()))
+ let breaks = 0
+ view.state.doc.descendants(node => { if (node.type.name === 'hard_break') breaks++ })
+ assert.equal(breaks, 1)
+ assert.equal(serialise(view.state.doc, fidelity), '- item\n\nnext', 'still untouched')
+})
+
+test('the reparse waits while an IME is composing', () => {
+ let composing = true
+ const { view } = editor('hello', { composing: () => composing })
+ view.dispatch(view.state.tr.insertText(' *x*', at(view.state.doc, 'hello')))
+ assert.equal(view.state.doc.firstChild.textContent, 'hello *x*')
+ composing = false
+ view.dispatch(view.state.tr.setMeta('composed', true))
+ assert.equal(view.state.doc.firstChild.textContent, 'hello x')
+})
+
+test('copied blocks paste with their bytes and seams; a cut and paste gives the body back', () => {
+ const body = 'x\n\na ^m1\n\n\n\n- b\n- c\n\n# d'
+ const { view, fidelity } = editor(body)
+ const from = at(view.state.doc, 'a', 0)
+ const to = at(view.state.doc, 'c')
+ const { text, mapa } = copyData(view.state, fidelity, from, to)
+ assert.equal(text, 'a ^m1\n\n\n\n- b\n- c')
+ // Paste into the empty paragraph after the heading: the marker is
+ // already in the document, so the copy loses it.
+ const end = view.state.doc.content.size - 1
+ view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, end)))
+ view.dispatch(pasteTransaction(view.state, fidelity, mapa))
+ assert.equal(serialise(view.state.doc, fidelity), body + '\n\na\n\n\n\n- b\n- c')
+ // Cut the originals and paste them back: the same bytes, marker and all.
+ const again = editor(body)
+ const cutFrom = at(again.view.state.doc, 'a', 0)
+ const cutTo = at(again.view.state.doc, 'c')
+ const cut = copyData(again.view.state, again.fidelity, cutFrom, cutTo)
+ again.view.dispatch(again.view.state.tr.setSelection(
+ TextSelection.create(again.view.state.doc, cutFrom, cutTo)).deleteSelection())
+ assert.equal(serialise(again.view.state.doc, again.fidelity), 'x\n\n# d')
+ again.view.dispatch(pasteTransaction(again.view.state, again.fidelity, cut.mapa))
+ assert.equal(serialise(again.view.state.doc, again.fidelity), body)
+})
+
+test('a forged x-mapa slice is refused, and text from outside is read as Markdown', () => {
+ const { view, fidelity } = editor('a')
+ for (const forged of ['{', '{"v":1,"sources":["a\\n\\nb"],"seams":[]}',
+ '{"v":1,"sources":["a","b"],"seams":["\\nx\\n"]}', '{"v":2,"sources":["a"],"seams":[]}']) {
+ assert.equal(pasteTransaction(view.state, fidelity, forged), null, forged)
+ }
+ const slice = textSlice(schema, '- one\n- [two](javascript:alert(1))')
+ let links = 0
+ slice.content.descendants(node => { if (node.marks.some(m => m.type.name === 'link')) links++ })
+ assert.equal(links, 0, 'an unsafe address is not a link')
+})
+
+test('rebuild changes origins only, outside undo history', () => {
+ const { view, fidelity } = editor('a\n\nb')
+ view.dispatch(view.state.tr.insertText('!', at(view.state.doc, 'b')))
+ const depth = undoDepth(view.state)
+ const body = serialise(view.state.doc, fidelity)
+ const before = view.state.doc
+ assert.equal(rebuild(view, fidelity, body).ok, true)
+ assert.equal(undoDepth(view.state), depth)
+ assert.ok(view.state.doc.content.size === before.content.size)
+ view.run(undo)
+ assert.equal(serialise(view.state.doc, fidelity), 'a\n\nb', 'undo undoes the edit, not the rebuild')
+})
+
+test('applyBody takes a teammate\'s block, keeps the caret, and ends untouched', () => {
+ const { view, fidelity } = editor('one\n\ntwo\n\nthree')
+ view.dispatch(view.state.tr.insertText('!', at(view.state.doc, 'three')))
+ view.dispatch(view.state.tr.setSelection(
+ TextSelection.create(view.state.doc, at(view.state.doc, 'three!'))))
+ const caret = view.state.selection.head
+ const merged = 'one\n\n\ntwo, said Bo\n\nthree!'
+ assert.equal(applyBody(view, fidelity, merged).ok, true)
+ assert.equal(serialise(view.state.doc, fidelity), merged)
+ assert.equal(view.state.selection.head, caret + ', said Bo'.length)
+ view.run(undo)
+ assert.equal(serialise(view.state.doc, fidelity), 'one\n\ntwo\n\nthree!')
+})
diff --git a/editor/testkit.mjs b/editor/testkit.mjs
new file mode 100644
index 0000000..f3b460a
--- /dev/null
+++ b/editor/testkit.mjs
@@ -0,0 +1,70 @@
+// testkit.mjs — what the fidelity gates share: the corpus from Go's
+// golden file, a seeded generator, and an editor without a DOM. The
+// gates drive EditorState transactions directly, with the same plugins
+// the page will run; no view is needed, so none is made. Not bundled.
+
+import { readFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { EditorState } from 'prosemirror-state'
+import { history } from 'prosemirror-history'
+import { createSchema } from './schema.mjs'
+import { mount, fidelityPlugin } from './fidelity.mjs'
+
+const here = dirname(fileURLToPath(import.meta.url))
+export const goldenPath = process.env.MAPA_GOLDEN ||
+ join(here, '..', 'internal', 'mapa', 'markup', 'testdata', 'golden.json')
+export const localCorpus = Boolean(process.env.MAPA_GOLDEN)
+
+// corpus is every golden body, read a line at a time (parity.test.mjs).
+export function corpus () {
+ const bytes = readFileSync(goldenPath)
+ const bodies = []
+ for (let start = 0; start < bytes.length;) {
+ let end = bytes.indexOf(10, start)
+ if (end < 0) end = bytes.length
+ const line = bytes.toString('utf8', start, end).replace(/,$/u, '')
+ start = end + 1
+ if (line !== '[' && line !== ']' && line !== '') {
+ const { name, body } = JSON.parse(line)
+ bodies.push({ name, body })
+ }
+ }
+ return bodies
+}
+
+// random is mulberry32, seeded from a string, so each body has its own
+// fixed sequence.
+export function random (seedText) {
+ let seed = 2166136261
+ for (const char of seedText) seed = Math.imul(seed ^ char.codePointAt(0), 16777619)
+ const next = () => {
+ seed = (seed + 0x6d2b79f5) | 0
+ let value = Math.imul(seed ^ (seed >>> 15), 1 | seed)
+ value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value
+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296
+ }
+ next.int = n => Math.floor(next() * n)
+ next.pick = list => list[next.int(list.length)]
+ return next
+}
+
+export const schema = createSchema()
+
+// editor is a mounted body in an EditorState with history and the
+// fidelity plugin, behind the small part of EditorView's interface the
+// fidelity functions use (state and dispatch).
+export function editor (body, options = {}) {
+ const { doc, fidelity } = mount(schema, body)
+ const state = EditorState.create({
+ doc,
+ plugins: [history(), fidelityPlugin(fidelity, { composing: options.composing ?? (() => false) })]
+ })
+ const view = {
+ state,
+ dispatch (tr) { this.state = this.state.apply(tr) },
+ // run is a prosemirror command against this view.
+ run (command) { return command(this.state, tr => this.dispatch(tr)) }
+ }
+ return { view, fidelity }
+}
diff --git a/internal/mapa/static/editor.191a361976920a15.js b/internal/mapa/static/editor.191a361976920a15.js
deleted file mode 100644
index 6216f60..0000000
--- a/internal/mapa/static/editor.191a361976920a15.js
+++ /dev/null
@@ -1,2 +0,0 @@
-function p(i){this.content=i}p.prototype={constructor:p,find:function(i){for(var t=0;t<this.content.length;t+=2)if(this.content[t]===i)return t;return-1},get:function(i){var t=this.find(i);return t==-1?void 0:this.content[t+1]},update:function(i,t,e){var n=e&&e!=i?this.remove(e):this,r=n.find(i),s=n.content.slice();return r==-1?s.push(e||i,t):(s[r+1]=t,e&&(s[r]=e)),new p(s)},remove:function(i){var t=this.find(i);if(t==-1)return this;var e=this.content.slice();return e.splice(t,2),new p(e)},addToStart:function(i,t){return new p([i,t].concat(this.remove(i).content))},addToEnd:function(i,t){var e=this.remove(i).content.slice();return e.push(i,t),new p(e)},addBefore:function(i,t,e){var n=this.remove(t),r=n.content.slice(),s=n.find(i);return r.splice(s==-1?r.length:s,0,t,e),new p(r)},forEach:function(i){for(var t=0;t<this.content.length;t+=2)i(this.content[t],this.content[t+1])},prepend:function(i){return i=p.from(i),i.size?new p(i.content.concat(this.subtract(i).content)):this},append:function(i){return i=p.from(i),i.size?new p(this.subtract(i).content.concat(i.content)):this},subtract:function(i){var t=this;i=p.from(i);for(var e=0;e<i.content.length;e+=2)t=t.remove(i.content[e]);return t},toObject:function(){var i={};return this.forEach(function(t,e){i[t]=e}),i},get size(){return this.content.length>>1}};p.from=function(i){if(i instanceof p)return i;var t=[];if(i)for(var e in i)t.push(e,i[e]);return new p(t)};var D=p;function Q(i,t,e){for(let n=0;;n++){if(n==i.childCount||n==t.childCount)return i.childCount==t.childCount?null:e;let r=i.child(n),s=t.child(n);if(r==s){e+=r.nodeSize;continue}if(!r.sameMarkup(s))return e;if(r.isText&&r.text!=s.text){let l=r.text,o=s.text,a=0;for(;l[a]==o[a];a++)e++;return a&&a<l.length&&a<o.length&&K(l.charCodeAt(a-1))&&Y(l.charCodeAt(a))&&e--,e}if(r.content.size||s.content.size){let l=Q(r.content,s.content,e+1);if(l!=null)return l}e+=r.nodeSize}}function X(i,t,e,n){for(let r=i.childCount,s=t.childCount;;){if(r==0||s==0)return r==s?null:{a:e,b:n};let l=i.child(--r),o=t.child(--s),a=l.nodeSize;if(l==o){e-=a,n-=a;continue}if(!l.sameMarkup(o))return{a:e,b:n};if(l.isText&&l.text!=o.text){let h=l.text,c=o.text,d=h.length,m=c.length;for(;d>0&&m>0&&h[d-1]==c[m-1];)d--,m--,e--,n--;return d&&m&&d<h.length&&K(h.charCodeAt(d-1))&&Y(h.charCodeAt(d))&&(e++,n++),{a:e,b:n}}if(l.content.size||o.content.size){let h=X(l.content,o.content,e-1,n-1);if(h)return h}e-=a,n-=a}}function Y(i){return i>=56320&&i<57344}function K(i){return i>=55296&&i<56320}var f=class i{constructor(t,e){if(this.content=t,this.size=e||0,e==null)for(let n=0;n<t.length;n++)this.size+=t[n].nodeSize}nodesBetween(t,e,n,r=0,s){for(let l=0,o=0;o<e;l++){let a=this.content[l],h=o+a.nodeSize;if(h>t&&n(a,r+o,s||null,l)!==!1&&a.content.size){let c=o+1;a.nodesBetween(Math.max(0,t-c),Math.min(a.content.size,e-c),n,r+c)}o=h}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,e,n,r){let s="",l=!0;return this.nodesBetween(t,e,(o,a)=>{let h=o.isText?o.text.slice(Math.max(t,a)-a,e-a):o.isLeaf?r?typeof r=="function"?r(o):r:o.type.spec.leafText?o.type.spec.leafText(o):"":"";o.isBlock&&(o.isLeaf&&h||o.isTextblock)&&n&&(l?l=!1:s+=n),s+=h},0),s}append(t){if(!t.size)return this;if(!this.size)return t;let e=this.lastChild,n=t.firstChild,r=this.content.slice(),s=0;for(e.isText&&e.sameMarkup(n)&&(r[r.length-1]=e.withText(e.text+n.text),s=1);s<t.content.length;s++)r.push(t.content[s]);return new i(r,this.size+t.size)}cut(t,e=this.size){if(t==0&&e==this.size)return this;let n=[],r=0;if(e>t)for(let s=0,l=0;l<e;s++){let o=this.content[s],a=l+o.nodeSize;a>t&&((l<t||a>e)&&(o.isText?o=o.cut(Math.max(0,t-l),Math.min(o.text.length,e-l)):o=o.cut(Math.max(0,t-l-1),Math.min(o.content.size,e-l-1))),n.push(o),r+=o.nodeSize),l=a}return new i(n,r)}cutByIndex(t,e){return t==e?i.empty:t==0&&e==this.content.length?this:new i(this.content.slice(t,e))}replaceChild(t,e){let n=this.content[t];if(n==e)return this;let r=this.content.slice(),s=this.size+e.nodeSize-n.nodeSize;return r[t]=e,new i(r,s)}addToStart(t){return new i([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new i(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let e=0;e<this.content.length;e++)if(!this.content[e].eq(t.content[e]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(t){let e=this.content[t];if(!e)throw new RangeError("Index "+t+" out of range for "+this);return e}maybeChild(t){return this.content[t]||null}forEach(t){for(let e=0,n=0;e<this.content.length;e++){let r=this.content[e];t(r,n,e),n+=r.nodeSize}}findDiffStart(t,e=0){return Q(this,t,e)}findDiffEnd(t,e=this.size,n=t.size){return X(this,t,e,n)}findIndex(t){if(t==0)return M(0,t);if(t==this.size)return M(this.content.length,t);if(t>this.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let e=0,n=0;;e++){let r=this.child(e),s=n+r.nodeSize;if(s>=t)return s==t?M(e+1,s):M(e,n);n=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(t=>t.toJSON()):null}static fromJSON(t,e){if(!e)return i.empty;if(!Array.isArray(e))throw new RangeError("Invalid input for Fragment.fromJSON");return i.fromArray(e.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return i.empty;let e,n=0;for(let r=0;r<t.length;r++){let s=t[r];n+=s.nodeSize,r&&s.isText&&t[r-1].sameMarkup(s)?(e||(e=t.slice(0,r)),e[e.length-1]=s.withText(e[e.length-1].text+s.text)):e&&e.push(s)}return new i(e||t,n)}static from(t){if(!t)return i.empty;if(t instanceof i)return t;if(Array.isArray(t))return this.fromArray(t);if(t.attrs)return new i([t],t.nodeSize);throw new RangeError("Can not convert "+t+" to a Fragment"+(t.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}};f.empty=new f([],0);var N={index:0,offset:0};function M(i,t){return N.index=i,N.offset=t,N}function E(i,t){if(i===t)return!0;if(!(i&&typeof i=="object")||!(t&&typeof t=="object"))return!1;let e=Array.isArray(i);if(Array.isArray(t)!=e)return!1;if(e){if(i.length!=t.length)return!1;for(let n=0;n<i.length;n++)if(!E(i[n],t[n]))return!1}else{for(let n in i)if(!(n in t)||!E(i[n],t[n]))return!1;for(let n in t)if(!(n in i))return!1}return!0}var u=class i{constructor(t,e){this.type=t,this.attrs=e}addToSet(t){let e,n=!1;for(let r=0;r<t.length;r++){let s=t[r];if(this.eq(s))return t;if(this.type.excludes(s.type))e||(e=t.slice(0,r));else{if(s.type.excludes(this.type))return t;!n&&s.type.rank>this.type.rank&&(e||(e=t.slice(0,r)),e.push(this),n=!0),e&&e.push(s)}}return e||(e=t.slice()),n||e.push(this),e}removeFromSet(t){for(let e=0;e<t.length;e++)if(this.eq(t[e]))return t.slice(0,e).concat(t.slice(e+1));return t}isInSet(t){for(let e=0;e<t.length;e++)if(this.eq(t[e]))return!0;return!1}eq(t){return this==t||this.type==t.type&&E(this.attrs,t.attrs)}toJSON(){let t={type:this.type.name};for(let e in this.attrs){t.attrs=this.attrs;break}return t}static fromJSON(t,e){if(!e)throw new RangeError("Invalid input for Mark.fromJSON");let n=t.marks[e.type];if(!n)throw new RangeError(`There is no mark type ${e.type} in this schema`);let r=n.create(e.attrs);return n.checkAttrs(r.attrs),r}static sameSet(t,e){if(t==e)return!0;if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].eq(e[n]))return!1;return!0}static setFrom(t){if(!t||Array.isArray(t)&&t.length==0)return i.none;if(t instanceof i)return[t];let e=t.slice();return e.sort((n,r)=>n.type.rank-r.type.rank),e}};u.none=[];var b=class extends Error{},S=class i{constructor(t,e,n){this.content=t,this.openStart=e,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,e){let n=tt(this.content,t+this.openStart,e,this.openStart+1,this.openEnd+1);return n&&new i(n,this.openStart,this.openEnd)}removeBetween(t,e){return new i(_(this.content,t+this.openStart,e+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(t,e){if(!e)return i.empty;let n=e.openStart||0,r=e.openEnd||0;if(typeof n!="number"||typeof r!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new i(f.fromJSON(t,e.content),n,r)}static maxOpen(t,e=!0){let n=0,r=0;for(let s=t.firstChild;s&&!s.isLeaf&&(e||!s.type.spec.isolating);s=s.firstChild)n++;for(let s=t.lastChild;s&&!s.isLeaf&&(e||!s.type.spec.isolating);s=s.lastChild)r++;return new i(t,n,r)}};S.empty=new S(f.empty,0,0);function _(i,t,e){let{index:n,offset:r}=i.findIndex(t),s=i.maybeChild(n),{index:l,offset:o}=i.findIndex(e);if(r==t||s.isText){if(o!=e&&!i.child(l).isText)throw new RangeError("Removing non-flat range");return i.cut(0,t).append(i.cut(e))}if(n!=l)throw new RangeError("Removing non-flat range");return i.replaceChild(n,s.copy(_(s.content,t-r-1,e-r-1)))}function tt(i,t,e,n,r,s){let{index:l,offset:o}=i.findIndex(t),a=i.maybeChild(l);if(o==t||a.isText)return s&&n<=0&&r<=0&&!s.canReplace(l,l,e)?null:i.cut(0,t).append(e).append(i.cut(t));let h=tt(a.content,t-o-1,e,l==0?n-1:0,l==i.childCount-1?r-1:0,a);return h&&i.replaceChild(l,a.copy(h))}function kt(i,t,e){if(e.openStart>i.depth)throw new b("Inserted content deeper than insertion position");if(i.depth-e.openStart!=t.depth-e.openEnd)throw new b("Inconsistent open depths");return et(i,t,e,0)}function et(i,t,e,n){let r=i.index(n),s=i.node(n);if(r==t.index(n)&&n<i.depth-e.openStart){let l=et(i,t,e,n+1);return s.copy(s.content.replaceChild(r,l))}else if(e.content.size)if(!e.openStart&&!e.openEnd&&i.depth==n&&t.depth==n){let l=i.parent,o=l.content;return y(l,o.cut(0,i.parentOffset).append(e.content).append(o.cut(t.parentOffset)))}else{let{start:l,end:o}=wt(e,i);return y(s,it(i,l,o,t,n))}else return y(s,C(i,t,n))}function nt(i,t){if(!t.type.compatibleContent(i.type))throw new b("Cannot join "+t.type.name+" onto "+i.type.name)}function I(i,t,e){let n=i.node(e);return nt(n,t.node(e)),n}function x(i,t){let e=t.length-1;e>=0&&i.isText&&i.sameMarkup(t[e])?t[e]=i.withText(t[e].text+i.text):t.push(i)}function O(i,t,e,n){let r=(t||i).node(e),s=0,l=t?t.index(e):r.childCount;i&&(s=i.index(e),i.depth>e?s++:i.textOffset&&(x(i.nodeAfter,n),s++));for(let o=s;o<l;o++)x(r.child(o),n);t&&t.depth==e&&t.textOffset&&x(t.nodeBefore,n)}function y(i,t){if(!i.type.validContent(t))throw new b("Invalid content for node "+i.type.name);return i.copy(t)}function it(i,t,e,n,r){let s=i.depth>r&&I(i,t,r+1),l=n.depth>r&&I(e,n,r+1),o=[];return O(null,i,r,o),s&&l&&t.index(r)==e.index(r)?(nt(s,l),x(y(s,it(i,t,e,n,r+1)),o)):(s&&x(y(s,C(i,t,r+1)),o),O(t,e,r,o),l&&x(y(l,C(e,n,r+1)),o)),O(n,null,r,o),new f(o)}function C(i,t,e){let n=[];if(O(null,i,e,n),i.depth>e){let r=I(i,t,e+1);x(y(r,C(i,t,e+1)),n)}return O(t,null,e,n),new f(n)}function wt(i,t){let e=t.depth-i.openStart,r=t.node(e).copy(i.content);for(let s=e-1;s>=0;s--)r=t.node(s).copy(f.from(r));return{start:r.resolveNoCache(i.openStart+e),end:r.resolveNoCache(r.content.size-i.openEnd-e)}}var v=class i{constructor(t,e,n){this.pos=t,this.path=e,this.parentOffset=n,this.depth=e.length/3-1}resolveDepth(t){return t==null?this.depth:t<0?this.depth+t:t}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(t){return this.path[this.resolveDepth(t)*3]}index(t){return this.path[this.resolveDepth(t)*3+1]}indexAfter(t){return t=this.resolveDepth(t),this.index(t)+(t==this.depth&&!this.textOffset?0:1)}start(t){return t=this.resolveDepth(t),t==0?0:this.path[t*3-1]+1}end(t){return t=this.resolveDepth(t),this.start(t)+this.node(t).content.size}before(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position before the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]}after(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position after the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]+this.path[t*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let t=this.parent,e=this.index(this.depth);if(e==t.childCount)return null;let n=this.pos-this.path[this.path.length-1],r=t.child(e);return n?t.child(e).cut(n):r}get nodeBefore(){let t=this.index(this.depth),e=this.pos-this.path[this.path.length-1];return e?this.parent.child(t).cut(0,e):t==0?null:this.parent.child(t-1)}posAtIndex(t,e){e=this.resolveDepth(e);let n=this.path[e*3],r=e==0?0:this.path[e*3-1]+1;for(let s=0;s<t;s++)r+=n.child(s).nodeSize;return r}marks(){let t=this.parent,e=this.index();if(t.content.size==0)return u.none;if(this.textOffset)return t.child(e).marks;let n=t.maybeChild(e-1),r=t.maybeChild(e);if(!n){let o=n;n=r,r=o}let s=n.marks;for(var l=0;l<s.length;l++)s[l].type.spec.inclusive===!1&&(!r||!s[l].isInSet(r.marks))&&(s=s[l--].removeFromSet(s));return s}marksAcross(t){let e=this.parent.maybeChild(this.index());if(!e||!e.isInline)return null;let n=e.marks,r=t.parent.maybeChild(t.index());for(var s=0;s<n.length;s++)n[s].type.spec.inclusive===!1&&(!r||!n[s].isInSet(r.marks))&&(n=n[s--].removeFromSet(n));return n}sharedDepth(t){for(let e=this.depth;e>0;e--)if(this.start(e)<=t&&this.end(e)>=t)return e;return 0}blockRange(t=this,e){if(t.pos<this.pos)return t.blockRange(this);for(let n=this.depth-(this.parent.inlineContent||this.pos==t.pos?1:0);n>=0;n--)if(t.pos<=this.end(n)&&(!e||e(this.node(n))))return new B(this,t,n);return null}sameParent(t){return this.pos-this.parentOffset==t.pos-t.parentOffset}max(t){return t.pos>this.pos?t:this}min(t){return t.pos<this.pos?t:this}toString(){let t="";for(let e=1;e<=this.depth;e++)t+=(t?"/":"")+this.node(e).type.name+"_"+this.index(e-1);return t+":"+this.parentOffset}static resolve(t,e){if(!(e>=0&&e<=t.content.size))throw new RangeError("Position "+e+" out of range");let n=[],r=0,s=e;for(let l=t;;){let{index:o,offset:a}=l.content.findIndex(s),h=s-a;if(n.push(l,o,r+a),!h||(l=l.child(o),l.isText))break;s=h-1,r+=a+1}return new i(e,n,s)}static resolveCached(t,e){let n=H.get(t);if(n)for(let s=0;s<n.elts.length;s++){let l=n.elts[s];if(l.pos==e)return l}else H.set(t,n=new F);let r=n.elts[n.i]=i.resolve(t,e);return n.i=(n.i+1)%bt,r}},F=class{constructor(){this.elts=[],this.i=0}},bt=12,H=new WeakMap,B=class{constructor(t,e,n){this.$from=t,this.$to=e,this.depth=n}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}},St=Object.create(null),g=class i{constructor(t,e,n,r=u.none){this.type=t,this.attrs=e,this.marks=r,this.content=n||f.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(t){return this.content.child(t)}maybeChild(t){return this.content.maybeChild(t)}forEach(t){this.content.forEach(t)}nodesBetween(t,e,n,r=0){this.content.nodesBetween(t,e,n,r,this)}descendants(t){this.nodesBetween(0,this.content.size,t)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,"")}textBetween(t,e,n,r){return this.content.textBetween(t,e,n,r)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(t){return this==t||this.sameMarkup(t)&&this.content.eq(t.content)}sameMarkup(t){return this.hasMarkup(t.type,t.attrs,t.marks)}hasMarkup(t,e,n){return this.type==t&&E(this.attrs,e||t.defaultAttrs||St)&&u.sameSet(this.marks,n||u.none)}copy(t=null){return t==this.content?this:new i(this.type,this.attrs,t,this.marks)}mark(t){return t==this.marks?this:new i(this.type,this.attrs,this.content,t)}cut(t,e=this.content.size){return t==0&&e==this.content.size?this:this.copy(this.content.cut(t,e))}slice(t,e=this.content.size,n=!1){if(t==e)return S.empty;let r=this.resolve(t),s=this.resolve(e),l=n?0:r.sharedDepth(e),o=r.start(l),h=r.node(l).content.cut(r.pos-o,s.pos-o);return new S(h,r.depth-l,s.depth-l)}replace(t,e,n){return kt(this.resolve(t),this.resolve(e),n)}nodeAt(t){for(let e=this;;){let{index:n,offset:r}=e.content.findIndex(t);if(e=e.maybeChild(n),!e)return null;if(r==t||e.isText)return e;t-=r+1}}childAfter(t){let{index:e,offset:n}=this.content.findIndex(t);return{node:this.content.maybeChild(e),index:e,offset:n}}childBefore(t){if(t==0)return{node:null,index:0,offset:0};let{index:e,offset:n}=this.content.findIndex(t);if(n<t)return{node:this.content.child(e),index:e,offset:n};let r=this.content.child(e-1);return{node:r,index:e-1,offset:n-r.nodeSize}}resolve(t){return v.resolveCached(this,t)}resolveNoCache(t){return v.resolve(this,t)}rangeHasMark(t,e,n){let r=!1;return e>t&&this.nodesBetween(t,e,s=>(n.isInSet(s.marks)&&(r=!0),!r)),r}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let t=this.type.name;return this.content.size&&(t+="("+this.content.toStringInner()+")"),rt(this.marks,t)}contentMatchAt(t){let e=this.type.contentMatch.matchFragment(this.content,0,t);if(!e)throw new Error("Called contentMatchAt on a node with invalid content");return e}canReplace(t,e,n=f.empty,r=0,s=n.childCount){let l=this.contentMatchAt(t).matchFragment(n,r,s),o=l&&l.matchFragment(this.content,e);if(!o||!o.validEnd)return!1;for(let a=r;a<s;a++)if(!this.type.allowsMarks(n.child(a).marks))return!1;return!0}canReplaceWith(t,e,n,r){if(r&&!this.type.allowsMarks(r))return!1;let s=this.contentMatchAt(t).matchType(n),l=s&&s.matchFragment(this.content,e);return l?l.validEnd:!1}canAppend(t){return t.content.size?this.canReplace(this.childCount,this.childCount,t.content):this.type.compatibleContent(t.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let t=u.none;for(let e=0;e<this.marks.length;e++){let n=this.marks[e];n.type.checkAttrs(n.attrs),t=n.addToSet(t)}if(!u.sameSet(t,this.marks))throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(e=>e.type.name)}`);this.content.forEach(e=>e.check())}toJSON(){let t={type:this.type.name};for(let e in this.attrs){t.attrs=this.attrs;break}return this.content.size&&(t.content=this.content.toJSON()),this.marks.length&&(t.marks=this.marks.map(e=>e.toJSON())),t}static fromJSON(t,e){if(!e)throw new RangeError("Invalid input for Node.fromJSON");let n;if(e.marks){if(!Array.isArray(e.marks))throw new RangeError("Invalid mark data for Node.fromJSON");n=e.marks.map(t.markFromJSON)}if(e.type=="text"){if(typeof e.text!="string")throw new RangeError("Invalid text node in JSON");return t.text(e.text,n)}let r=f.fromJSON(t,e.content),s=t.nodeType(e.type).create(e.attrs,r,n);return s.type.checkAttrs(s.attrs),s}};g.prototype.text=void 0;var L=class i extends g{constructor(t,e,n,r){if(super(t,e,null,r),!n)throw new RangeError("Empty text nodes are not allowed");this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):rt(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,e){return this.text.slice(t,e)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new i(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new i(this.type,this.attrs,t,this.marks)}cut(t=0,e=this.text.length){return t==0&&e==this.text.length?this:this.withText(this.text.slice(t,e))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}};function rt(i,t){for(let e=i.length-1;e>=0;e--)t=i[e].type.name+"("+t+")";return t}var k=class i{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,e){let n=new P(t,e);if(n.next==null)return i.empty;let r=st(n);n.next&&n.err("Unexpected trailing text");let s=Tt(At(r));return zt(s,n),s}matchType(t){for(let e=0;e<this.next.length;e++)if(this.next[e].type==t)return this.next[e].next;return null}matchFragment(t,e=0,n=t.childCount){let r=this;for(let s=e;r&&s<n;s++)r=r.matchType(t.child(s).type);return r}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let t=0;t<this.next.length;t++){let{type:e}=this.next[t];if(!(e.isText||e.hasRequiredAttrs()))return e}return null}compatible(t){for(let e=0;e<this.next.length;e++)for(let n=0;n<t.next.length;n++)if(this.next[e].type==t.next[n].type)return!0;return!1}fillBefore(t,e=!1,n=0){let r=[this];function s(l,o){let a=l.matchFragment(t,n);if(a&&(!e||a.validEnd))return f.from(o.map(h=>h.createAndFill()));for(let h=0;h<l.next.length;h++){let{type:c,next:d}=l.next[h];if(!(c.isText||c.hasRequiredAttrs())&&r.indexOf(d)==-1){r.push(d);let m=s(d,o.concat(c));if(m)return m}}return null}return s(this,[])}findWrapping(t){for(let n=0;n<this.wrapCache.length;n+=2)if(this.wrapCache[n]==t)return this.wrapCache[n+1];let e=this.computeWrapping(t);return this.wrapCache.push(t,e),e}computeWrapping(t){let e=Object.create(null),n=[{match:this,type:null,via:null}];for(;n.length;){let r=n.shift(),s=r.match;if(s.matchType(t)){let l=[];for(let o=r;o.type;o=o.via)l.push(o.type);return l.reverse()}for(let l=0;l<s.next.length;l++){let{type:o,next:a}=s.next[l];!o.isLeaf&&!o.hasRequiredAttrs()&&!(o.name in e)&&(!r.type||a.validEnd)&&(n.push({match:o.contentMatch,type:o,via:r}),e[o.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(t){if(t>=this.next.length)throw new RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];function e(n){t.push(n);for(let r=0;r<n.next.length;r++)t.indexOf(n.next[r].next)==-1&&e(n.next[r].next)}return e(this),t.map((n,r)=>{let s=r+(n.validEnd?"*":" ")+" ";for(let l=0;l<n.next.length;l++)s+=(l?", ":"")+n.next[l].type.name+"->"+t.indexOf(n.next[l].next);return s}).join(`
-`)}};k.empty=new k(!0);var P=class{constructor(t,e){this.string=t,this.nodeTypes=e,this.inline=null,this.pos=0,this.tokens=t.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(t){return this.next==t&&(this.pos++||!0)}err(t){throw new SyntaxError(t+" (in content expression '"+this.string+"')")}};function st(i){let t=[];do t.push(Ot(i));while(i.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function Ot(i){let t=[];do t.push(Mt(i));while(i.next&&i.next!=")"&&i.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function Mt(i){let t=vt(i);for(;;)if(i.eat("+"))t={type:"plus",expr:t};else if(i.eat("*"))t={type:"star",expr:t};else if(i.eat("?"))t={type:"opt",expr:t};else if(i.eat("{"))t=Et(i,t);else break;return t}function V(i){/\D/.test(i.next)&&i.err("Expected number, got '"+i.next+"'");let t=Number(i.next);return i.pos++,t}function Et(i,t){let e=V(i),n=e;return i.eat(",")&&(i.next!="}"?n=V(i):n=-1),i.eat("}")||i.err("Unclosed braced range"),{type:"range",min:e,max:n,expr:t}}function Ct(i,t){let e=i.nodeTypes,n=e[t];if(n)return[n];let r=[];for(let s in e){let l=e[s];l.isInGroup(t)&&r.push(l)}return r.length==0&&i.err("No node type or group '"+t+"' found"),r}function vt(i){if(i.eat("(")){let t=st(i);return i.eat(")")||i.err("Missing closing paren"),t}else if(/\W/.test(i.next))i.err("Unexpected token '"+i.next+"'");else{let t=Ct(i,i.next).map(e=>(i.inline==null?i.inline=e.isInline:i.inline!=e.isInline&&i.err("Mixing inline and block content"),{type:"name",value:e}));return i.pos++,t.length==1?t[0]:{type:"choice",exprs:t}}}function At(i){let t=[[]];return r(s(i,0),e()),t;function e(){return t.push([])-1}function n(l,o,a){let h={term:a,to:o};return t[l].push(h),h}function r(l,o){l.forEach(a=>a.to=o)}function s(l,o){if(l.type=="choice")return l.exprs.reduce((a,h)=>a.concat(s(h,o)),[]);if(l.type=="seq")for(let a=0;;a++){let h=s(l.exprs[a],o);if(a==l.exprs.length-1)return h;r(h,o=e())}else if(l.type=="star"){let a=e();return n(o,a),r(s(l.expr,a),a),[n(a)]}else if(l.type=="plus"){let a=e();return r(s(l.expr,o),a),r(s(l.expr,a),a),[n(a)]}else{if(l.type=="opt")return[n(o)].concat(s(l.expr,o));if(l.type=="range"){let a=o;for(let h=0;h<l.min;h++){let c=e();r(s(l.expr,a),c),a=c}if(l.max==-1)r(s(l.expr,a),a);else for(let h=l.min;h<l.max;h++){let c=e();n(a,c),r(s(l.expr,a),c),a=c}return[n(a)]}else{if(l.type=="name")return[n(o,void 0,l.value)];throw new Error("Unknown expr type")}}}}function lt(i,t){return t-i}function Z(i,t){let e=[];return n(t),e.sort(lt);function n(r){let s=i[r];if(s.length==1&&!s[0].term)return n(s[0].to);e.push(r);for(let l=0;l<s.length;l++){let{term:o,to:a}=s[l];!o&&e.indexOf(a)==-1&&n(a)}}}function Tt(i){let t=Object.create(null);return e(Z(i,0));function e(n){let r=[];n.forEach(l=>{i[l].forEach(({term:o,to:a})=>{if(!o)return;let h;for(let c=0;c<r.length;c++)r[c][0]==o&&(h=r[c][1]);Z(i,a).forEach(c=>{h||r.push([o,h=[]]),h.indexOf(c)==-1&&h.push(c)})})});let s=t[n.join(",")]=new k(n.indexOf(i.length-1)>-1);for(let l=0;l<r.length;l++){let o=r[l][1].sort(lt);s.next.push({type:r[l][0],next:t[o.join(",")]||e(o)})}return s}}function zt(i,t){for(let e=0,n=[i];e<n.length;e++){let r=n[e],s=!r.validEnd,l=[];for(let o=0;o<r.next.length;o++){let{type:a,next:h}=r.next[o];l.push(a.name),s&&!(a.isText||a.hasRequiredAttrs())&&(s=!1),n.indexOf(h)==-1&&n.push(h)}s&&t.err("Only non-generatable nodes ("+l.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}function ot(i){let t=Object.create(null);for(let e in i){let n=i[e];if(!n.hasDefault)return null;t[e]=n.default}return t}function at(i,t){let e=Object.create(null);for(let n in i){let r=t&&t[n];if(r===void 0){let s=i[n];if(s.hasDefault)r=s.default;else throw new RangeError("No value supplied for attribute "+n)}e[n]=r}return e}function ht(i,t,e,n){for(let r in t)if(!(r in i))throw new RangeError(`Unsupported attribute ${r} for ${e} of type ${n}`);for(let r in i)i[r].validate&&i[r].validate(t[r])}function ct(i,t){let e=Object.create(null);if(t)for(let n in t)e[n]=new W(i,n,t[n]);return e}var A=class i{constructor(t,e,n){this.name=t,this.schema=e,this.spec=n,this.markSet=null,this.groups=n.group?n.group.split(" "):[],this.attrs=ct(t,n.attrs),this.defaultAttrs=ot(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(n.inline||t=="text"),this.isText=t=="text"}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==k.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(t){return this.groups.indexOf(t)>-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let t in this.attrs)if(this.attrs[t].isRequired)return!0;return!1}compatibleContent(t){return this==t||this.contentMatch.compatible(t.contentMatch)}computeAttrs(t){return!t&&this.defaultAttrs?this.defaultAttrs:at(this.attrs,t)}create(t=null,e,n){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new g(this,this.computeAttrs(t),f.from(e),u.setFrom(n))}createChecked(t=null,e,n){return e=f.from(e),this.checkContent(e),new g(this,this.computeAttrs(t),e,u.setFrom(n))}createAndFill(t=null,e,n){if(t=this.computeAttrs(t),e=f.from(e),e.size){let l=this.contentMatch.fillBefore(e);if(!l)return null;e=l.append(e)}let r=this.contentMatch.matchFragment(e),s=r&&r.fillBefore(f.empty,!0);return s?new g(this,t,e.append(s),u.setFrom(n)):null}validContent(t){let e=this.contentMatch.matchFragment(t);if(!e||!e.validEnd)return!1;for(let n=0;n<t.childCount;n++)if(!this.allowsMarks(t.child(n).marks))return!1;return!0}checkContent(t){if(!this.validContent(t))throw new RangeError(`Invalid content for node ${this.name}: ${t.toString().slice(0,50)}`)}checkAttrs(t){ht(this.attrs,t,"node",this.name)}allowsMarkType(t){return this.markSet==null||this.markSet.indexOf(t)>-1}allowsMarks(t){if(this.markSet==null)return!0;for(let e=0;e<t.length;e++)if(!this.allowsMarkType(t[e].type))return!1;return!0}allowedMarks(t){if(this.markSet==null)return t;let e;for(let n=0;n<t.length;n++)this.allowsMarkType(t[n].type)?e&&e.push(t[n]):e||(e=t.slice(0,n));return e?e.length?e:u.none:t}static compile(t,e){let n=Object.create(null);t.forEach((s,l)=>n[s]=new i(s,e,l));let r=e.spec.topNode||"doc";if(!n[r])throw new RangeError("Schema is missing its top node type ('"+r+"')");if(!n.text)throw new RangeError("Every schema needs a 'text' type");for(let s in n.text.attrs)throw new RangeError("The text node type should not have attributes");return n}};function Rt(i,t,e){let n=e.split("|");return r=>{let s=r===null?"null":typeof r;if(n.indexOf(s)<0)throw new RangeError(`Expected value of type ${n} for attribute ${t} on type ${i}, got ${s}`)}}var W=class{constructor(t,e,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,"default"),this.default=n.default,this.validate=typeof n.validate=="string"?Rt(t,e,n.validate):n.validate}get isRequired(){return!this.hasDefault}},q=class i{constructor(t,e,n,r){this.name=t,this.rank=e,this.schema=n,this.spec=r,this.attrs=ct(t,r.attrs),this.excluded=null;let s=ot(this.attrs);this.instance=s?new u(this,s):null}create(t=null){return!t&&this.instance?this.instance:new u(this,at(this.attrs,t))}static compile(t,e){let n=Object.create(null),r=0;return t.forEach((s,l)=>n[s]=new i(s,r++,e,l)),n}removeFromSet(t){for(var e=0;e<t.length;e++)t[e].type==this&&(t=t.slice(0,e).concat(t.slice(e+1)),e--);return t}isInSet(t){for(let e=0;e<t.length;e++)if(t[e].type==this)return t[e]}checkAttrs(t){ht(this.attrs,t,"mark",this.name)}excludes(t){return this.excluded.indexOf(t)>-1}},T=class{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let e=this.spec={};for(let r in t)e[r]=t[r];e.nodes=D.from(t.nodes),e.marks=D.from(t.marks||{}),this.nodes=A.compile(this.spec.nodes,this),this.marks=q.compile(this.spec.marks,this);let n=Object.create(null);for(let r in this.nodes){if(r in this.marks)throw new RangeError(r+" can not be both a node and a mark");let s=this.nodes[r],l=s.spec.content||"",o=s.spec.marks;if(s.contentMatch=n[l]||(n[l]=k.parse(l,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=o=="_"?null:o?G(this,o.split(" ")):o==""||!s.inlineContent?[]:null}for(let r in this.marks){let s=this.marks[r],l=s.spec.excludes;s.excluded=l==null?[s]:l==""?[]:G(this,l.split(" "))}this.nodeFromJSON=r=>g.fromJSON(this,r),this.markFromJSON=r=>u.fromJSON(this,r),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,e=null,n,r){if(typeof t=="string")t=this.nodeType(t);else if(t instanceof A){if(t.schema!=this)throw new RangeError("Node type from different schema used ("+t.name+")")}else throw new RangeError("Invalid node type: "+t);return t.createChecked(e,n,r)}text(t,e){let n=this.nodes.text;return new L(n,n.defaultAttrs,t,u.setFrom(e))}mark(t,e){return typeof t=="string"&&(t=this.marks[t]),t.create(e)}nodeType(t){let e=this.nodes[t];if(!e)throw new RangeError("Unknown node type: "+t);return e}};function G(i,t){let e=[];for(let n=0;n<t.length;n++){let r=t[n],s=i.marks[r],l=s;if(s)e.push(s);else for(let o in i.marks){let a=i.marks[o];(r=="_"||a.spec.group&&a.spec.group.split(" ").indexOf(r)>-1)&&e.push(l=a)}if(!l)throw new SyntaxError("Unknown mark type: '"+t[n]+"'")}return e}var ut="http://www.w3.org/2000/svg",Dt={page:["M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z","M14 2v4a2 2 0 0 0 2 2h4","M9 13h6","M9 17h4"],"page-plus":["M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z","M14 2v4a2 2 0 0 0 2 2h4","M9 15h6","M12 12v6"],calendar:["M8 2v4","M16 2v4","M5 4h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z","M3 10h18"],block:["M13 4v16","M17 4v16","M19 4H9.5a4.5 4.5 0 0 0 0 9H13"],embed:["M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z","m3.3 7 8.7 5 8.7-5","M12 22V12"]};function ft(i){return[`${ut} svg`,{"mapa-i":"",viewBox:"0 0 24 24","aria-hidden":"true"},...Dt[i].map(t=>[`${ut} path`,{d:t}])]}function z({href:i,kind:t,title:e,label:n,icon:r,shown:s,note:l}){let o={href:i,"mapa-chip":t};e&&(o.title=e),o["aria-label"]=n;let a=["a",o,ft(r),s];return l&&a.push(["span",{"mapa-chip-note":""},l]),a}function J({target:i,anchor:t,shown:e},n){let r=e||i;if(n.broken)return["span",{"mapa-chip":"broken"},r];if(n.day)return Nt(e,n);if(n.pending)return z({href:n.href,kind:"pending",icon:"page-plus",shown:r,label:`${r}, page not written yet`});let s=n.title||i,l={href:n.href,kind:"team",icon:"page",shown:r,label:`${r}, team page`};return n.alias&&(l.title=`Now called ${s}`,l.label=`${r}, now called ${s}`),t&&(l.kind=l.icon="block",l.label=`${r}, a block in ${s}`),t&&n.blockGone&&(l.kind="block gone",l.label=`${r}, block removed from ${s}`,l.note="block removed"),z(l)}function Nt(i,t){return z(i?{href:t.href,kind:"date",icon:"calendar",shown:i,label:`${i}, your note for ${t.day}`}:{href:t.href,kind:"date",icon:"calendar",shown:t.day,label:`${t.day}, your note`})}function pt(i){return["span",{"mapa-chip":"embed",role:"img","aria-label":`${i}, embedded item, not shown yet`},ft("embed"),i]}var It=/^[A-Za-z0-9\-_.~!$&'()*+,;=:[\]<>"]$/u,Ft=/^[A-Za-z0-9\-._:~!$&'()*+,;=%@]$/u,dt=/^[0-9A-Fa-f]$/u;function j(i){let t=Bt(i);if(t===null)return!1;switch(t.scheme){case"http":case"https":return t.host!==""&&!t.host.startsWith("[");case"mailto":return t.opaque!==""}return!1}function Bt(i){let t=i.indexOf("#"),e=t<0?i:i.slice(0,t),n=t<0?"":i.slice(t+1),r=Lt(e);return r===null||n!==""&&!$(n)?null:r}function Lt(i){if(/[\x00-\x1f\x7f]/u.test(i))return null;if(i==="*")return{scheme:"",host:"",opaque:""};let t=Pt(i);if(t===null)return null;let e=t.rest,n={scheme:t.name.toLowerCase(),host:"",opaque:""};if(e.endsWith("?")&&e.split("?").length===2?e=e.slice(0,-1):e.includes("?")&&(e=e.slice(0,e.indexOf("?"))),!e.startsWith("/")){if(n.scheme!=="")return n.opaque=e,n;if(e.split("/")[0].includes(":"))return null}if((n.scheme!==""||!e.startsWith("///"))&&e.startsWith("//")){let r=e.slice(2);e="";let s=r.indexOf("/");s>=0&&(e=r.slice(s),r=r.slice(0,s));let l=Wt(n.scheme,r);if(l===null)return null;n.host=l}return $(e)?n:null}function Pt(i){for(let t=0;t<i.length;t++){let e=i[t];if(!/^[A-Za-z]$/u.test(e)){if(/^[0-9+\-.]$/u.test(e)){if(t===0)return{name:"",rest:i};continue}return e===":"?t===0?null:{name:i.slice(0,t),rest:i.slice(t+1)}:{name:"",rest:i}}}return{name:"",rest:i}}function Wt(i,t){let e=t.lastIndexOf("@"),n=qt(i,e<0?t:t.slice(e+1));if(n===null||e<0)return n;let r=t.slice(0,e);for(let s of r)if(!Ft.test(s))return null;return $(r)?n:null}function qt(i,t){let e=t.lastIndexOf("[");if(e>0)return null;if(e===0)return"[";let n=t.indexOf(":");if(n!==-1){let r=t.lastIndexOf(":");if(r!==n&&i!=="http"&&i!=="https"&&(n=r),!/^:[0-9]*$/u.test(t.slice(n)))return null}return Jt(t)?t:null}function Jt(i){for(let t=0;t<i.length;t++){let e=i[t];if(e==="%"){if(!gt(i,t)||parseInt(i[t+1],16)<8&&i.slice(t,t+3)!=="%25")return!1;t+=2}else if(e.charCodeAt(0)<128&&!It.test(e))return!1}return!0}function $(i){for(let t=0;t<i.length;t++)if(i[t]==="%"){if(!gt(i,t))return!1;t+=2}return!0}function gt(i,t){return t+2<i.length&&dt.test(i[t+1])&&dt.test(i[t+2])}var w="[^\\t\\n\\f\\r ]",te=new RegExp(`^(#{1,6})[ \\t]+${w}`,"u");var jt=/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/u;function $t(i){return jt.test(i)}function mt(i){if(!$t(i))return!1;let[t,e,n]=i.split("-").map(Number);if(e<1||e>12||n<1)return!1;let s=[31,t%4===0&&(t%100!==0||t%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return n<=s[e-1]}var ee=new RegExp(`\\*\\*\\*(${w}(?:[^*]*?${w})?)\\*\\*\\*`,"gu"),ne=new RegExp(`\\*\\*(${w}(?:[^*]*?${w})?)\\*\\*`,"gu"),ie=new RegExp(`\\*(${w}(?:[^*]*?${w})?)\\*`,"gu");function R(i){return i.attrs.marker?{id:`b-${i.attrs.marker}`}:{}}var xt={origin:{default:null},marker:{default:null}},Ut={doc:{content:"block+"},paragraph:{group:"block",content:"inline*",attrs:{...xt},parseDOM:[{tag:"p"}],toDOM:i=>["p",R(i),0]},heading:{group:"block",content:"inline*",defining:!0,attrs:{...xt,level:{default:1},source:{default:null}},parseDOM:[1,2,3,4,5,6].map(i=>({tag:`h${i}`,attrs:{level:Math.max(i-1,1)}})),toDOM:i=>[`h${Math.min(i.attrs.level+1,6)}`,R(i),0]},bullet_list:{group:"block",content:"list_item+",parseDOM:[{tag:"ul"}],toDOM:()=>["ul",0]},ordered_list:{group:"block",content:"list_item+",parseDOM:[{tag:"ol"}],toDOM:()=>["ol",0]},list_item:{content:"paragraph (bullet_list | ordered_list)*",defining:!0,attrs:{marker:{default:null},indent:{default:""},bullet:{default:"-"},number:{default:null},delim:{default:null},task:{default:!1},checked:{default:null}},parseDOM:[{tag:"li",getAttrs:i=>{let t=i.getAttribute("mapa-task");return t==="open"?{task:!0,checked:" "}:t==="done"?{task:!0,checked:"x"}:{}}}],toDOM:i=>{let t=R(i);return i.attrs.task&&(t["mapa-task"]=i.attrs.checked===" "?"open":"done"),["li",t,0]}},blockquote:{group:"block",content:"paragraph",defining:!0,attrs:{marker:{default:null},prefix:{default:null}},parseDOM:[{tag:"blockquote"}],toDOM:i=>["blockquote",R(i),0]},code_block:{group:"block",content:"text*",marks:"",code:!0,defining:!0,attrs:{origin:{default:null},fence:{default:"```"},info:{default:""},closed:{default:!0},close:{default:"```"}},parseDOM:[{tag:"pre",preserveWhitespace:"full"}],toDOM:()=>["pre",["code",0]]},horizontal_rule:{group:"block",attrs:{origin:{default:null},source:{default:"---"}},parseDOM:[{tag:"hr"}],toDOM:()=>["hr"]},text:{group:"inline"},hard_break:{inline:!0,group:"inline",selectable:!1,attrs:{indent:{default:""}},parseDOM:[{tag:"br"}],toDOM:()=>["br"]}},Ht={link:{attrs:{href:{},bare:{default:!1}},inclusive:!1,excludes:"em strong code",parseDOM:[{tag:"a[href]",getAttrs:i=>j(i.getAttribute("href"))?{href:i.getAttribute("href")}:!1}],toDOM:i=>["a",{href:i.attrs.href,rel:"noopener noreferrer"},0]},em:{parseDOM:[{tag:"em"},{tag:"i"},{style:"font-style=italic"}],toDOM:()=>["em",0]},strong:{parseDOM:[{tag:"strong"},{tag:"b",getAttrs:i=>i.style?.fontWeight!=="normal"&&null},{style:"font-weight",getAttrs:i=>/^(bold(er)?|[6-9]\d{2,})$/u.test(i)&&null}],toDOM:()=>["strong",0]},code:{excludes:"_",parseDOM:[{tag:"code"}],toDOM:()=>["code",0]}};function U(i){let t="";for(let e of i.childNodes)e.nodeType===3&&(t+=e.nodeValue);return t.trim()}function Vt(i){let t={inline:!0,group:"inline",atom:!0,selectable:!0};return{wikilink:{...t,attrs:{target:{},anchor:{default:""},shown:{default:""},source:{default:null},origin:{default:null}},parseDOM:[{tag:"a[mapa-chip]",priority:60,getAttrs:e=>{if(/^\/d\/([0-9]{4}-[0-9]{2}-[0-9]{2})$/u.exec(e.getAttribute("href")??""))return!1;let r=U(e);return r===""?!1:{target:r}}}],toDOM:e=>J(e.attrs,i(e.attrs.target,e.attrs.anchor))},datelink:{...t,attrs:{date:{},anchor:{default:""},shown:{default:""},source:{default:null},origin:{default:null}},parseDOM:[{tag:"a[mapa-chip]",priority:61,getAttrs:e=>{let n=/^\/d\/([0-9]{4}-[0-9]{2}-[0-9]{2})$/u.exec(e.getAttribute("href")??"");return n&&mt(n[1])?{date:n[1]}:!1}}],toDOM:e=>J({...e.attrs,target:e.attrs.date},i(e.attrs.date,e.attrs.anchor))},embed:{...t,attrs:{ref:{},source:{default:null},origin:{default:null}},parseDOM:[{tag:'span[mapa-chip="embed"]',priority:60,getAttrs:e=>U(e)===""?!1:{ref:U(e)}}],toDOM:e=>pt(e.attrs.ref)}}}var Zt=i=>({href:`/new?title=${encodeURIComponent(i)}`,pending:!0});function yt(i=Zt){return new T({nodes:{...Ut,...Vt(i)},marks:Ht})}var ce=yt();export{ce as schema};
diff --git a/internal/mapa/static/editor.e67effa70bb31619.js b/internal/mapa/static/editor.e67effa70bb31619.js
new file mode 100644
index 0000000..f0382e2
--- /dev/null
+++ b/internal/mapa/static/editor.e67effa70bb31619.js
@@ -0,0 +1,30 @@
+function M(n){this.content=n}M.prototype={constructor:M,find:function(n){for(var e=0;e<this.content.length;e+=2)if(this.content[e]===n)return e;return-1},get:function(n){var e=this.find(n);return e==-1?void 0:this.content[e+1]},update:function(n,e,t){var r=t&&t!=n?this.remove(t):this,i=r.find(n),s=r.content.slice();return i==-1?s.push(t||n,e):(s[i+1]=e,t&&(s[i]=t)),new M(s)},remove:function(n){var e=this.find(n);if(e==-1)return this;var t=this.content.slice();return t.splice(e,2),new M(t)},addToStart:function(n,e){return new M([n,e].concat(this.remove(n).content))},addToEnd:function(n,e){var t=this.remove(n).content.slice();return t.push(n,e),new M(t)},addBefore:function(n,e,t){var r=this.remove(e),i=r.content.slice(),s=r.find(n);return i.splice(s==-1?i.length:s,0,e,t),new M(i)},forEach:function(n){for(var e=0;e<this.content.length;e+=2)n(this.content[e],this.content[e+1])},prepend:function(n){return n=M.from(n),n.size?new M(n.content.concat(this.subtract(n).content)):this},append:function(n){return n=M.from(n),n.size?new M(this.subtract(n).content.concat(n.content)):this},subtract:function(n){var e=this;n=M.from(n);for(var t=0;t<n.content.length;t+=2)e=e.remove(n.content[t]);return e},toObject:function(){var n={};return this.forEach(function(e,t){n[e]=t}),n},get size(){return this.content.length>>1}};M.from=function(n){if(n instanceof M)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new M(e)};var Ue=M;function Ot(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a<o.length&&a<l.length&&Tt(o.charCodeAt(a-1))&&Ct(o.charCodeAt(a))&&t--,t}if(i.content.size||s.content.size){let o=Ot(i.content,s.content,t+1);if(o!=null)return o}t+=i.nodeSize}}function Et(n,e,t,r){for(let i=n.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a:t,b:r};let o=n.child(--i),l=e.child(--s),a=o.nodeSize;if(o==l){t-=a,r-=a;continue}if(!o.sameMarkup(l))return{a:t,b:r};if(o.isText&&o.text!=l.text){let c=o.text,u=l.text,h=c.length,f=u.length;for(;h>0&&f>0&&c[h-1]==u[f-1];)h--,f--,t--,r--;return h&&f&&h<c.length&&Tt(c.charCodeAt(h-1))&&Ct(c.charCodeAt(h))&&(t++,r++),{a:t,b:r}}if(o.content.size||l.content.size){let c=Et(o.content,l.content,t-1,r-1);if(c)return c}t-=a,r-=a}}function Ct(n){return n>=56320&&n<57344}function Tt(n){return n>=55296&&n<56320}var m=class n{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;r<e.length;r++)this.size+=e[r].nodeSize}nodesBetween(e,t,r,i=0,s){for(let o=0,l=0;l<t;o++){let a=this.content[o],c=l+a.nodeSize;if(c>e&&r(a,i+l,s||null,o)!==!1&&a.content.size){let u=l+1;a.nodesBetween(Math.max(0,e-u),Math.min(a.content.size,t-u),r,i+u)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);s<e.content.length;s++)i.push(e.content[s]);return new n(i,this.size+e.size)}cut(e,t=this.size){if(e==0&&t==this.size)return this;let r=[],i=0;if(t>e)for(let s=0,o=0;o<t;s++){let l=this.content[s],a=o+l.nodeSize;a>e&&((o<e||a>t)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new n(r,i)}cutByIndex(e,t){return e==t?n.empty:e==0&&t==this.content.length?this:new n(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new n(i,s)}addToStart(e){return new n([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new n(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;t<this.content.length;t++)if(!this.content[t].eq(e.content[t]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(e){let t=this.content[e];if(!t)throw new RangeError("Index "+e+" out of range for "+this);return t}maybeChild(e){return this.content[e]||null}forEach(e){for(let t=0,r=0;t<this.content.length;t++){let i=this.content[t];e(i,r,t),r+=i.nodeSize}}findDiffStart(e,t=0){return Ot(this,e,t)}findDiffEnd(e,t=this.size,r=e.size){return Et(this,e,t,r)}findIndex(e){if(e==0)return pe(0,e);if(e==this.size)return pe(this.content.length,e);if(e>this.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?pe(t+1,s):pe(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return n.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return n.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return n.empty;let t,r=0;for(let i=0;i<e.length;i++){let s=e[i];r+=s.nodeSize,i&&s.isText&&e[i-1].sameMarkup(s)?(t||(t=e.slice(0,i)),t[t.length-1]=s.withText(t[t.length-1].text+s.text)):t&&t.push(s)}return new n(t||e,r)}static from(e){if(!e)return n.empty;if(e instanceof n)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new n([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}};m.empty=new m([],0);var He={index:0,offset:0};function pe(n,e){return He.index=n,He.offset=e,He}function de(n,e){if(n===e)return!0;if(!(n&&typeof n=="object")||!(e&&typeof e=="object"))return!1;let t=Array.isArray(n);if(Array.isArray(e)!=t)return!1;if(t){if(n.length!=e.length)return!1;for(let r=0;r<n.length;r++)if(!de(n[r],e[r]))return!1}else{for(let r in n)if(!(r in e)||!de(n[r],e[r]))return!1;for(let r in e)if(!(r in n))return!1}return!0}var y=class n{constructor(e,t){this.type=e,this.attrs=t}addToSet(e){let t,r=!1;for(let i=0;i<e.length;i++){let s=e[i];if(this.eq(s))return e;if(this.type.excludes(s.type))t||(t=e.slice(0,i));else{if(s.type.excludes(this.type))return e;!r&&s.type.rank>this.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;t<e.length;t++)if(this.eq(e[t]))return e.slice(0,t).concat(e.slice(t+1));return e}isInSet(e){for(let t=0;t<e.length;t++)if(this.eq(e[t]))return!0;return!1}eq(e){return this==e||this.type==e.type&&de(this.attrs,e.attrs)}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Mark.fromJSON");let r=e.marks[t.type];if(!r)throw new RangeError(`There is no mark type ${t.type} in this schema`);let i=r.create(t.attrs);return r.checkAttrs(i.attrs),i}static sameSet(e,t){if(e==t)return!0;if(e.length!=t.length)return!1;for(let r=0;r<e.length;r++)if(!e[r].eq(t[r]))return!1;return!0}static setFrom(e){if(!e||Array.isArray(e)&&e.length==0)return n.none;if(e instanceof n)return[e];let t=e.slice();return t.sort((r,i)=>r.type.rank-i.type.rank),t}};y.none=[];var D=class extends Error{},d=class n{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=At(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new n(r,this.openStart,this.openEnd)}removeBetween(e,t){return new n(Nt(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return n.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new n(m.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new n(e,r,i)}};d.empty=new d(m.empty,0,0);function Nt(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Nt(s.content,e-i-1,t-i-1)))}function At(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=At(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function Pn(n,e,t){if(t.openStart>n.depth)throw new D("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new D("Inconsistent open depths");return Rt(n,e,t,0)}function Rt(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r<n.depth-t.openStart){let o=Rt(n,e,t,r+1);return s.copy(s.content.replaceChild(i,o))}else if(t.content.size)if(!t.openStart&&!t.openEnd&&n.depth==r&&e.depth==r){let o=n.parent,l=o.content;return L(o,l.cut(0,n.parentOffset).append(t.content).append(l.cut(e.parentOffset)))}else{let{start:o,end:l}=Wn(t,n);return L(s,zt(n,o,l,e,r))}else return L(s,me(n,e,r))}function It(n,e){if(!e.type.compatibleContent(n.type))throw new D("Cannot join "+e.type.name+" onto "+n.type.name)}function Ve(n,e,t){let r=n.node(t);return It(r,e.node(t)),r}function W(n,e){let t=e.length-1;t>=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function ie(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(W(n.nodeAfter,r),s++));for(let l=s;l<o;l++)W(i.child(l),r);e&&e.depth==t&&e.textOffset&&W(e.nodeBefore,r)}function L(n,e){if(!n.type.validContent(e))throw new D("Invalid content for node "+n.type.name);return n.copy(e)}function zt(n,e,t,r,i){let s=n.depth>i&&Ve(n,e,i+1),o=r.depth>i&&Ve(t,r,i+1),l=[];return ie(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(It(s,o),W(L(s,zt(n,e,t,r,i+1)),l)):(s&&W(L(s,me(n,e,i+1)),l),ie(e,t,i,l),o&&W(L(o,me(t,r,i+1)),l)),ie(r,null,i,l),new m(l)}function me(n,e,t){let r=[];if(ie(null,n,t,r),n.depth>t){let i=Ve(n,e,t+1);W(L(i,me(n,e,t+1)),r)}return ie(e,null,t,r),new m(r)}function Wn(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(m.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}var ge=class n{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s<e;s++)i+=r.child(s).nodeSize;return i}marks(){let e=this.parent,t=this.index();if(e.content.size==0)return y.none;if(this.textOffset)return e.child(t).marks;let r=e.maybeChild(t-1),i=e.maybeChild(t);if(!r){let l=r;r=i,i=l}let s=r.marks;for(var o=0;o<s.length;o++)s[o].type.spec.inclusive===!1&&(!i||!s[o].isInSet(i.marks))&&(s=s[o--].removeFromSet(s));return s}marksAcross(e){let t=this.parent.maybeChild(this.index());if(!t||!t.isInline)return null;let r=t.marks,i=e.parent.maybeChild(e.index());for(var s=0;s<r.length;s++)r[s].type.spec.inclusive===!1&&(!i||!r[s].isInSet(i.marks))&&(r=r[s--].removeFromSet(r));return r}sharedDepth(e){for(let t=this.depth;t>0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos<this.pos)return e.blockRange(this);for(let r=this.depth-(this.parent.inlineContent||this.pos==e.pos?1:0);r>=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new Ze(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos<this.pos?e:this}toString(){let e="";for(let t=1;t<=this.depth;t++)e+=(e?"/":"")+this.node(t).type.name+"_"+this.index(t-1);return e+":"+this.parentOffset}static resolve(e,t){if(!(t>=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new n(t,r,s)}static resolveCached(e,t){let r=St.get(e);if(r)for(let s=0;s<r.elts.length;s++){let o=r.elts[s];if(o.pos==t)return o}else St.set(e,r=new je);let i=r.elts[r.i]=n.resolve(e,t);return r.i=(r.i+1)%Ln,i}},je=class{constructor(){this.elts=[],this.i=0}},Ln=12,St=new WeakMap,Ze=class{constructor(e,t,r){this.$from=e,this.$to=t,this.depth=r}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}},$n=Object.create(null),A=class n{constructor(e,t,r,i=y.none){this.type=e,this.attrs=t,this.marks=i,this.content=r||m.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(e){return this.content.child(e)}maybeChild(e){return this.content.maybeChild(e)}forEach(e){this.content.forEach(e)}nodesBetween(e,t,r,i=0){this.content.nodesBetween(e,t,r,i,this)}descendants(e){this.nodesBetween(0,this.content.size,e)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,"")}textBetween(e,t,r,i){return this.content.textBetween(e,t,r,i)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(e){return this==e||this.sameMarkup(e)&&this.content.eq(e.content)}sameMarkup(e){return this.hasMarkup(e.type,e.attrs,e.marks)}hasMarkup(e,t,r){return this.type==e&&de(this.attrs,t||e.defaultAttrs||$n)&&y.sameSet(this.marks,r||y.none)}copy(e=null){return e==this.content?this:new n(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new n(this.type,this.attrs,this.content,e)}cut(e,t=this.content.size){return e==0&&t==this.content.size?this:this.copy(this.content.cut(e,t))}slice(e,t=this.content.size,r=!1){if(e==t)return d.empty;let i=this.resolve(e),s=this.resolve(t),o=r?0:i.sharedDepth(t),l=i.start(o),c=i.node(o).content.cut(i.pos-l,s.pos-l);return new d(c,i.depth-o,s.depth-o)}replace(e,t,r){return Pn(this.resolve(e),this.resolve(t),r)}nodeAt(e){for(let t=this;;){let{index:r,offset:i}=t.content.findIndex(e);if(t=t.maybeChild(r),!t)return null;if(i==e||t.isText)return t;e-=i+1}}childAfter(e){let{index:t,offset:r}=this.content.findIndex(e);return{node:this.content.maybeChild(t),index:t,offset:r}}childBefore(e){if(e==0)return{node:null,index:0,offset:0};let{index:t,offset:r}=this.content.findIndex(e);if(r<e)return{node:this.content.child(t),index:t,offset:r};let i=this.content.child(t-1);return{node:i,index:t-1,offset:r-i.nodeSize}}resolve(e){return ge.resolveCached(this,e)}resolveNoCache(e){return ge.resolve(this,e)}rangeHasMark(e,t,r){let i=!1;return t>e&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Dt(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=m.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;a<s;a++)if(!this.type.allowsMarks(r.child(a).marks))return!1;return!0}canReplaceWith(e,t,r,i){if(i&&!this.type.allowsMarks(i))return!1;let s=this.contentMatchAt(e).matchType(r),o=s&&s.matchFragment(this.content,t);return o?o.validEnd:!1}canAppend(e){return e.content.size?this.canReplace(this.childCount,this.childCount,e.content):this.type.compatibleContent(e.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let e=y.none;for(let t=0;t<this.marks.length;t++){let r=this.marks[t];r.type.checkAttrs(r.attrs),e=r.addToSet(e)}if(!y.sameSet(e,this.marks))throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(t=>t.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=m.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};A.prototype.text=void 0;var Ke=class n extends A{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Dt(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new n(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new n(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}};function Dt(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}var $=class n{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new Ge(e,t);if(r.next==null)return n.empty;let i=Ft(r);r.next&&r.err("Unexpected trailing text");let s=Kn(Zn(i));return Gn(s,r),s}matchType(e){for(let t=0;t<this.next.length;t++)if(this.next[t].type==e)return this.next[t].next;return null}matchFragment(e,t=0,r=e.childCount){let i=this;for(let s=t;i&&s<r;s++)i=i.matchType(e.child(s).type);return i}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let e=0;e<this.next.length;e++){let{type:t}=this.next[e];if(!(t.isText||t.hasRequiredAttrs()))return t}return null}compatible(e){for(let t=0;t<this.next.length;t++)for(let r=0;r<e.next.length;r++)if(this.next[t].type==e.next[r].type)return!0;return!1}fillBefore(e,t=!1,r=0){let i=[this];function s(o,l){let a=o.matchFragment(e,r);if(a&&(!t||a.validEnd))return m.from(l.map(c=>c.createAndFill()));for(let c=0;c<o.next.length;c++){let{type:u,next:h}=o.next[c];if(!(u.isText||u.hasRequiredAttrs())&&i.indexOf(h)==-1){i.push(h);let f=s(h,l.concat(u));if(f)return f}}return null}return s(this,[])}findWrapping(e){for(let r=0;r<this.wrapCache.length;r+=2)if(this.wrapCache[r]==e)return this.wrapCache[r+1];let t=this.computeWrapping(e);return this.wrapCache.push(e,t),t}computeWrapping(e){let t=Object.create(null),r=[{match:this,type:null,via:null}];for(;r.length;){let i=r.shift(),s=i.match;if(s.matchType(e)){let o=[];for(let l=i;l.type;l=l.via)o.push(l.type);return o.reverse()}for(let o=0;o<s.next.length;o++){let{type:l,next:a}=s.next[o];!l.isLeaf&&!l.hasRequiredAttrs()&&!(l.name in t)&&(!i.type||a.validEnd)&&(r.push({match:l.contentMatch,type:l,via:i}),t[l.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(e){if(e>=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i<r.next.length;i++)e.indexOf(r.next[i].next)==-1&&t(r.next[i].next)}return t(this),e.map((r,i)=>{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o<r.next.length;o++)s+=(o?", ":"")+r.next[o].type.name+"->"+e.indexOf(r.next[o].next);return s}).join(`
+`)}};$.empty=new $(!0);var Ge=class{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}};function Ft(n){let e=[];do e.push(qn(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function qn(n){let e=[];do e.push(Un(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function Un(n){let e=jn(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=Hn(n,e);else break;return e}function Mt(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function Hn(n,e){let t=Mt(n),r=t;return n.eat(",")&&(n.next!="}"?r=Mt(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function Vn(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function jn(n){if(n.eat("(")){let e=Ft(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=Vn(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function Zn(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c<o.min;c++){let u=t();i(s(o.expr,a),u),a=u}if(o.max==-1)i(s(o.expr,a),a);else for(let c=o.min;c<o.max;c++){let u=t();r(a,u),i(s(o.expr,a),u),a=u}return[r(a)]}else{if(o.type=="name")return[r(l,void 0,o.value)];throw new Error("Unknown expr type")}}}}function Bt(n,e){return e-n}function bt(n,e){let t=[];return r(e),t.sort(Bt);function r(i){let s=n[i];if(s.length==1&&!s[0].term)return r(s[0].to);t.push(i);for(let o=0;o<s.length;o++){let{term:l,to:a}=s[o];!l&&t.indexOf(a)==-1&&r(a)}}}function Kn(n){let e=Object.create(null);return t(bt(n,0));function t(r){let i=[];r.forEach(o=>{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let u=0;u<i.length;u++)i[u][0]==l&&(c=i[u][1]);bt(n,a).forEach(u=>{c||i.push([l,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let s=e[r.join(",")]=new $(r.indexOf(n.length-1)>-1);for(let o=0;o<i.length;o++){let l=i[o][1].sort(Bt);s.next.push({type:i[o][0],next:e[l.join(",")]||t(l)})}return s}}function Gn(n,e){for(let t=0,r=[n];t<r.length;t++){let i=r[t],s=!i.validEnd,o=[];for(let l=0;l<i.next.length;l++){let{type:a,next:c}=i.next[l];o.push(a.name),s&&!(a.isText||a.hasRequiredAttrs())&&(s=!1),r.indexOf(c)==-1&&r.push(c)}s&&e.err("Only non-generatable nodes ("+o.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}function Jt(n){let e=Object.create(null);for(let t in n){let r=n[t];if(!r.hasDefault)return null;e[t]=r.default}return e}function Pt(n,e){let t=Object.create(null);for(let r in n){let i=e&&e[r];if(i===void 0){let s=n[r];if(s.hasDefault)i=s.default;else throw new RangeError("No value supplied for attribute "+r)}t[r]=i}return t}function Wt(n,e,t,r){for(let i in e)if(!(i in n))throw new RangeError(`Unsupported attribute ${i} for ${t} of type ${r}`);for(let i in n)n[i].validate&&n[i].validate(e[i])}function Lt(n,e){let t=Object.create(null);if(e)for(let r in e)t[r]=new Qe(n,r,e[r]);return t}var ye=class n{constructor(e,t,r){this.name=e,this.schema=t,this.spec=r,this.markSet=null,this.groups=r.group?r.group.split(" "):[],this.attrs=Lt(e,r.attrs),this.defaultAttrs=Jt(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(r.inline||e=="text"),this.isText=e=="text"}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==$.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(e){return this.groups.indexOf(e)>-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Pt(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new A(this,this.computeAttrs(e),m.from(t),y.setFrom(r))}createChecked(e=null,t,r){return t=m.from(t),this.checkContent(t),new A(this,this.computeAttrs(e),t,y.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=m.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(m.empty,!0);return s?new A(this,e,t.append(s),y.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r<e.childCount;r++)if(!this.allowsMarks(e.child(r).marks))return!1;return!0}checkContent(e){if(!this.validContent(e))throw new RangeError(`Invalid content for node ${this.name}: ${e.toString().slice(0,50)}`)}checkAttrs(e){Wt(this.attrs,e,"node",this.name)}allowsMarkType(e){return this.markSet==null||this.markSet.indexOf(e)>-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;t<e.length;t++)if(!this.allowsMarkType(e[t].type))return!1;return!0}allowedMarks(e){if(this.markSet==null)return e;let t;for(let r=0;r<e.length;r++)this.allowsMarkType(e[r].type)?t&&t.push(e[r]):t||(t=e.slice(0,r));return t?t.length?t:y.none:e}static compile(e,t){let r=Object.create(null);e.forEach((s,o)=>r[s]=new n(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Qn(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}var Qe=class{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Qn(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}},xe=class n{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Lt(e,i.attrs),this.excluded=null;let s=Jt(this.attrs);this.instance=s?new y(this,s):null}create(e=null){return!e&&this.instance?this.instance:new y(this,Pt(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new n(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t<e.length;t++)e[t].type==this&&(e=e.slice(0,t).concat(e.slice(t+1)),t--);return e}isInSet(e){for(let t=0;t<e.length;t++)if(e[t].type==this)return e[t]}checkAttrs(e){Wt(this.attrs,e,"mark",this.name)}excludes(e){return this.excluded.indexOf(e)>-1}},ke=class{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=Ue.from(e.nodes),t.marks=Ue.from(e.marks||{}),this.nodes=ye.compile(this.spec.nodes,this),this.marks=xe.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=$.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?vt(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:vt(this,o.split(" "))}this.nodeFromJSON=i=>A.fromJSON(this,i),this.markFromJSON=i=>y.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof ye){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new Ke(r,r.defaultAttrs,e,y.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}};function vt(n,e){let t=[];for(let r=0;r<e.length;r++){let i=e[r],s=n.marks[i],o=s;if(s)t.push(s);else for(let l in n.marks){let a=n.marks[l];(i=="_"||a.spec.group&&a.spec.group.split(" ").indexOf(i)>-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}var $t="http://www.w3.org/2000/svg",Xn={page:["M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z","M14 2v4a2 2 0 0 0 2 2h4","M9 13h6","M9 17h4"],"page-plus":["M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z","M14 2v4a2 2 0 0 0 2 2h4","M9 15h6","M12 12v6"],calendar:["M8 2v4","M16 2v4","M5 4h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z","M3 10h18"],block:["M13 4v16","M17 4v16","M19 4H9.5a4.5 4.5 0 0 0 0 9H13"],embed:["M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z","m3.3 7 8.7 5 8.7-5","M12 22V12"]};function qt(n){return[`${$t} svg`,{"mapa-i":"",viewBox:"0 0 24 24","aria-hidden":"true"},...Xn[n].map(e=>[`${$t} path`,{d:e}])]}function we({href:n,kind:e,title:t,label:r,icon:i,shown:s,note:o}){let l={href:n,"mapa-chip":e};t&&(l.title=t),l["aria-label"]=r;let a=["a",l,qt(i),s];return o&&a.push(["span",{"mapa-chip-note":""},o]),a}function Xe({target:n,anchor:e,shown:t},r){let i=t||n;if(r.broken)return["span",{"mapa-chip":"broken"},i];if(r.day)return Yn(t,r);if(r.pending)return we({href:r.href,kind:"pending",icon:"page-plus",shown:i,label:`${i}, page not written yet`});let s=r.title||n,o={href:r.href,kind:"team",icon:"page",shown:i,label:`${i}, team page`};return r.alias&&(o.title=`Now called ${s}`,o.label=`${i}, now called ${s}`),e&&(o.kind=o.icon="block",o.label=`${i}, a block in ${s}`),e&&r.blockGone&&(o.kind="block gone",o.label=`${i}, block removed from ${s}`,o.note="block removed"),we(o)}function Yn(n,e){return we(n?{href:e.href,kind:"date",icon:"calendar",shown:n,label:`${n}, your note for ${e.day}`}:{href:e.href,kind:"date",icon:"calendar",shown:e.day,label:`${e.day}, your note`})}function Ut(n){return["span",{"mapa-chip":"embed",role:"img","aria-label":`${n}, embedded item, not shown yet`},qt("embed"),n]}var _n=/^[A-Za-z0-9\-_.~!$&'()*+,;=:[\]<>"]$/u,er=/^[A-Za-z0-9\-._:~!$&'()*+,;=%@]$/u,Ht=/^[0-9A-Fa-f]$/u;function Se(n){let e=tr(n);if(e===null)return!1;switch(e.scheme){case"http":case"https":return e.host!==""&&!e.host.startsWith("[");case"mailto":return e.opaque!==""}return!1}function tr(n){let e=n.indexOf("#"),t=e<0?n:n.slice(0,e),r=e<0?"":n.slice(e+1),i=nr(t);return i===null||r!==""&&!Ye(r)?null:i}function nr(n){if(/[\x00-\x1f\x7f]/u.test(n))return null;if(n==="*")return{scheme:"",host:"",opaque:""};let e=rr(n);if(e===null)return null;let t=e.rest,r={scheme:e.name.toLowerCase(),host:"",opaque:""};if(t.endsWith("?")&&t.split("?").length===2?t=t.slice(0,-1):t.includes("?")&&(t=t.slice(0,t.indexOf("?"))),!t.startsWith("/")){if(r.scheme!=="")return r.opaque=t,r;if(t.split("/")[0].includes(":"))return null}if((r.scheme!==""||!t.startsWith("///"))&&t.startsWith("//")){let i=t.slice(2);t="";let s=i.indexOf("/");s>=0&&(t=i.slice(s),i=i.slice(0,s));let o=ir(r.scheme,i);if(o===null)return null;r.host=o}return Ye(t)?r:null}function rr(n){for(let e=0;e<n.length;e++){let t=n[e];if(!/^[A-Za-z]$/u.test(t)){if(/^[0-9+\-.]$/u.test(t)){if(e===0)return{name:"",rest:n};continue}return t===":"?e===0?null:{name:n.slice(0,e),rest:n.slice(e+1)}:{name:"",rest:n}}}return{name:"",rest:n}}function ir(n,e){let t=e.lastIndexOf("@"),r=sr(n,t<0?e:e.slice(t+1));if(r===null||t<0)return r;let i=e.slice(0,t);for(let s of i)if(!er.test(s))return null;return Ye(i)?r:null}function sr(n,e){let t=e.lastIndexOf("[");if(t>0)return null;if(t===0)return"[";let r=e.indexOf(":");if(r!==-1){let i=e.lastIndexOf(":");if(i!==r&&n!=="http"&&n!=="https"&&(r=i),!/^:[0-9]*$/u.test(e.slice(r)))return null}return or(e)?e:null}function or(n){for(let e=0;e<n.length;e++){let t=n[e];if(t==="%"){if(!Vt(n,e)||parseInt(n[e+1],16)<8&&n.slice(e,e+3)!=="%25")return!1;e+=2}else if(t.charCodeAt(0)<128&&!_n.test(t))return!1}return!0}function Ye(n){for(let e=0;e<n.length;e++)if(n[e]==="%"){if(!Vt(n,e))return!1;e+=2}return!0}function Vt(n,e){return e+2<n.length&&Ht.test(n[e+1])&&Ht.test(n[e+2])}var be="paragraph",R="heading",k="item",T="code",v="quote",N="rule",lr="text",et="code",oe="wiki",Me="web",le="embed",q="[^\\t\\n\\f\\r ]",Yt=new RegExp(`^(#{1,6})[ \\t]+${q}`,"u"),ae=/^([ \t]*)([-*+]|[0-9]{1,9}[.)])[ \t]+/u,Z=/^ {0,3}(```|~~~)/u,tt=/^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})$/u,_t=/[ \t]\^([A-Za-z0-9-]{1,40})[ \t]*$/u,ar=/^\[([^\]\n]+)\]\(([^)\t\n\f\r ]+)\)/u,cr=/^https?:\/\/[^\t\n\f\r <>()[\]]+[^\t\n\f\r <>()[\].,;:!?'"]/u,hr=/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/u,ur=/^\[([ xX])\][ \t]+/u,jt=/[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/u;function F(n){let e=0,t=n.length;for(;e<t&&jt.test(n[e]);)e++;for(;t>e&&jt.test(n[t-1]);)t--;return n.slice(e,t)}function ce(n,e){let t=0;for(;t<n.length&&e.includes(n[t]);)t++;return n.slice(t)}function Zt(n){let e=0;for(let t of n){let r=t.codePointAt(0);e+=r<128?1:r<2048?2:r<65536?3:4}return e}function ve(n){return U(n).replace(/[ \t\n]+$/u,"")}function U(n){return n.replaceAll(`\r
+`,`
+`).replaceAll("\r",`
+`)}function I(n){let e=U(n).split(`
+`),t=[0],r=[0];for(let s of e)t.push(t[t.length-1]+Zt(s)+1),r.push(r[r.length-1]+s.length+1);let i=[];for(let s=0;s<e.length;){if(F(e[s])===""){s++;continue}let[o,l]=fr(e,s);o.marker=gr(o),o.start=t[s],o.end=o.start+Zt(o.source),o.from=r[s],o.to=o.from+o.source.length,i.push(o),s=l}return i}function se(n,e,t={}){return{kind:n,source:e,level:0,ordered:!1,marker:"",...t}}function fr(n,e){let t=n[e];if(Z.test(t))return pr(n,e);let r=Yt.exec(t);return r?[se(R,t,{level:r[1].length}),e+1]:tt.test(t)?[se(N,t),e+1]:ae.test(t)?dr(n,e):_e(t)?Kt(n,e,v,_e):Kt(n,e,be,en)}function pr(n,e){let t=Z.exec(n[e])[1],r=e+1;for(;r<n.length&&!ce(n[r]," ").startsWith(t);)r++;return r<n.length&&r++,[se(T,n.slice(e,r).join(`
+`)),r]}function dr(n,e){let t=ae.exec(n[e]),r=t[1].replaceAll(" "," "),i=e+1;for(;i<n.length&&en(n[i]);)i++;return[se(k,n.slice(e,i).join(`
+`),{level:Math.floor(r.length/2),ordered:!/[-*+]/u.test(t[2])}),i]}function Kt(n,e,t,r){let i=e+1;for(;i<n.length&&r(n[i]);)i++;return[se(t,n.slice(e,i).join(`
+`)),i]}function _e(n){return ce(n," ").startsWith(">")}function en(n){return F(n)!==""&&!mr(n)}function mr(n){return Z.test(n)||Yt.test(n)||tt.test(n)||ae.test(n)||_e(n)}function gr(n){if(n.kind===T||n.kind===N)return"";let e=n.source.slice(n.source.lastIndexOf(`
+`)+1),t=_t.exec(e);return t?t[1]:""}function nt(n){let e=n.source;switch(n.kind){case T:return yr(e);case R:e=ce(e,"# ");break;case k:e=e.replace(ae,"");break;case v:e=xr(e);break}return n.marker!==""&&(e=e.replace(_t,"")),e}function yr(n){let e=n.split(`
+`);return e.length<=1?"":(Z.test(e[e.length-1])&&(e=e.slice(0,-1)),e.slice(1).join(`
+`))}function xr(n){return n.split(`
+`).map(e=>(e=ce(e," "),e.startsWith(">")&&(e=e.slice(1)),e.startsWith(" ")?e.slice(1):e)).join(`
+`)}function tn(n){let e=ae.exec(n.source),t={indent:e[1],bullet:null,number:null,delim:null};return n.ordered?(t.number=e[2].slice(0,-1),t.delim=e[2].slice(-1)):t.bullet=e[2],t}function nn(n){let e=ur.exec(n);return e?[n.slice(e[0].length),e[1]]:[n,null]}function Oe(n){let e=[],t="",r=()=>{t!==""&&e.push(j(lr,{text:t,source:t})),t=""};for(let i=0;i<n.length;){let[s,o]=kr(n,i);if(o===0){t+=n[i],i++;continue}r(),s.source=n.slice(i,i+o),e.push(s),i+=o}return r(),e}function j(n,e){return{kind:n,text:"",target:"",anchor:"",url:"",source:"",...e}}function kr(n,e){let t=n.slice(e);if(t[0]==="`")return wr(t);if(t.startsWith("![[")){let r=rn(t.slice(3));if(r>=0)return[j(le,{text:t.slice(0,r+5)}),r+5]}else{if(t.startsWith("[["))return Sr(t);if(t[0]==="["){let r=ar.exec(t);if(r&&Se(r[2]))return[j(Me,{text:r[1],url:r[2]}),r[0].length]}else if(t[0]==="h"&&Mr(n,e)){let r=cr.exec(t);if(r)return[j(Me,{text:r[0],url:r[0]}),r[0].length]}}return[null,0]}function wr(n){let e=n.slice(1).indexOf("`");return e<=0?[null,0]:[j(et,{text:n.slice(1,e+1)}),e+2]}function Gt(n,e){let t=n.indexOf(e);return t<0?[n,""]:[n.slice(0,t),n.slice(t+1)]}function Sr(n){let e=rn(n.slice(2));if(e<0)return[null,0];let t=n.slice(2,e+2),[r,i]=Gt(t,"|"),s;if([r,s]=Gt(r,"#"),r=F(r),r==="")return[null,0];let o=j(oe,{target:r,text:F(i)});return s.startsWith("^")&&(o.anchor=F(s.slice(1))),[o,e+4]}function rn(n){let e=n.indexOf("]]");return e<0||/[\n[]/u.test(n.slice(0,e))?-1:e}function Mr(n,e){return e===0||`
+(`.includes(n[e-1])}function br(n){return hr.test(n)}function Ee(n){return Z.test(n)}function sn(n){return tt.test(n)}function Ce(n){return Z.exec(n)?.[1]??null}function Te(n,e){return ce(n," ").startsWith(e)}function K(n){if(!br(n))return!1;let[e,t,r]=n.split("-").map(Number);if(t<1||t>12||r<1)return!1;let s=[31,e%4===0&&(e%100!==0||e%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return r<=s[t-1]}var vr=new RegExp(`\\*\\*\\*(${q}(?:[^*]*?${q})?)\\*\\*\\*`,"gu"),Or=new RegExp(`\\*\\*(${q}(?:[^*]*?${q})?)\\*\\*`,"gu"),Er=new RegExp(`\\*(${q}(?:[^*]*?${q})?)\\*`,"gu"),Cr=/<\/?(?:em|strong)>/gu,Tr=/\n[ \t]*/gu;function Nr(n){return n.replace(/[&'<>"]/gu,e=>({"&":"&amp;","'":"&#39;","<":"&lt;",">":"&gt;",'"':"&#34;"})[e])}function Ar(n){return n.replace(/&(?:amp|#39|lt|gt|#34);/gu,e=>({"&amp;":"&","&#39;":"'","&lt;":"<","&gt;":">","&#34;":'"'})[e])}function on(n){let e=Nr(n);e=e.replace(vr,"<em><strong>$1</strong></em>"),e=e.replace(Or,"<strong>$1</strong>"),e=e.replace(Er,"<em>$1</em>");let t=[],r=0,i=0,s=0;for(let o of e.matchAll(Cr)){Qt(t,e.slice(s,o.index),r>0,i>0);let l=o[0][1]==="/"?-1:1;o[0].endsWith("em>")?r+=l:i+=l,s=o.index+o[0].length}return Qt(t,e.slice(s),r>0,i>0),t}function Qt(n,e,t,r){let i=0;for(let s of e.matchAll(Tr))Xt(n,e.slice(i,s.index),t,r),n.push({kind:"break",indent:s[0].slice(1),em:t,strong:r}),i=s.index+s[0].length;Xt(n,e.slice(i),t,r)}function Xt(n,e,t,r){e!==""&&n.push({kind:"text",text:Ar(e),em:t,strong:r})}function Ne(n){return n.attrs.marker?{id:`b-${n.attrs.marker}`}:{}}var ln={origin:{default:null},marker:{default:null}},Rr={doc:{content:"block+"},paragraph:{group:"block",content:"inline*",attrs:{...ln},parseDOM:[{tag:"p"}],toDOM:n=>["p",Ne(n),0]},heading:{group:"block",content:"inline*",defining:!0,attrs:{...ln,level:{default:1},source:{default:null}},parseDOM:[1,2,3,4,5,6].map(n=>({tag:`h${n}`,attrs:{level:Math.max(n-1,1)}})),toDOM:n=>[`h${Math.min(n.attrs.level+1,6)}`,Ne(n),0]},bullet_list:{group:"block",content:"list_item+",parseDOM:[{tag:"ul"}],toDOM:()=>["ul",0]},ordered_list:{group:"block",content:"list_item+",parseDOM:[{tag:"ol"}],toDOM:()=>["ol",0]},list_item:{content:"paragraph (bullet_list | ordered_list)*",defining:!0,attrs:{marker:{default:null},indent:{default:""},bullet:{default:"-"},number:{default:null},delim:{default:null},task:{default:!1},checked:{default:null}},parseDOM:[{tag:"li",getAttrs:n=>{let e=n.getAttribute("mapa-task");return e==="open"?{task:!0,checked:" "}:e==="done"?{task:!0,checked:"x"}:{}}}],toDOM:n=>{let e=Ne(n);return n.attrs.task&&(e["mapa-task"]=n.attrs.checked===" "?"open":"done"),["li",e,0]}},blockquote:{group:"block",content:"paragraph",defining:!0,attrs:{marker:{default:null},prefix:{default:null}},parseDOM:[{tag:"blockquote"}],toDOM:n=>["blockquote",Ne(n),0]},code_block:{group:"block",content:"text*",marks:"",code:!0,defining:!0,attrs:{origin:{default:null},fence:{default:"```"},info:{default:""},closed:{default:!0},close:{default:"```"}},parseDOM:[{tag:"pre",preserveWhitespace:"full"}],toDOM:()=>["pre",["code",0]]},horizontal_rule:{group:"block",attrs:{origin:{default:null},source:{default:"---"}},parseDOM:[{tag:"hr"}],toDOM:()=>["hr"]},text:{group:"inline"},hard_break:{inline:!0,group:"inline",selectable:!1,attrs:{indent:{default:""}},parseDOM:[{tag:"br"}],toDOM:()=>["br"]}},Ir={link:{attrs:{href:{},bare:{default:!1}},inclusive:!1,excludes:"em strong code",parseDOM:[{tag:"a[href]",getAttrs:n=>Se(n.getAttribute("href"))?{href:n.getAttribute("href")}:!1}],toDOM:n=>["a",{href:n.attrs.href,rel:"noopener noreferrer"},0]},em:{parseDOM:[{tag:"em"},{tag:"i"},{style:"font-style=italic"}],toDOM:()=>["em",0]},strong:{parseDOM:[{tag:"strong"},{tag:"b",getAttrs:n=>n.style?.fontWeight!=="normal"&&null},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[6-9]\d{2,})$/u.test(n)&&null}],toDOM:()=>["strong",0]},code:{excludes:"_",parseDOM:[{tag:"code"}],toDOM:()=>["code",0]}};function rt(n){let e="";for(let t of n.childNodes)t.nodeType===3&&(e+=t.nodeValue);return e.trim()}function zr(n){let e={inline:!0,group:"inline",atom:!0,selectable:!0};return{wikilink:{...e,attrs:{target:{},anchor:{default:""},shown:{default:""},source:{default:null},origin:{default:null}},parseDOM:[{tag:"a[mapa-chip]",priority:60,getAttrs:t=>{if(/^\/d\/([0-9]{4}-[0-9]{2}-[0-9]{2})$/u.exec(t.getAttribute("href")??""))return!1;let i=rt(t);return i===""?!1:{target:i}}}],toDOM:t=>Xe(t.attrs,n(t.attrs.target,t.attrs.anchor))},datelink:{...e,attrs:{date:{},anchor:{default:""},shown:{default:""},source:{default:null},origin:{default:null}},parseDOM:[{tag:"a[mapa-chip]",priority:61,getAttrs:t=>{let r=/^\/d\/([0-9]{4}-[0-9]{2}-[0-9]{2})$/u.exec(t.getAttribute("href")??"");return r&&K(r[1])?{date:r[1]}:!1}}],toDOM:t=>Xe({...t.attrs,target:t.attrs.date},n(t.attrs.date,t.attrs.anchor))},embed:{...e,attrs:{ref:{},source:{default:null},origin:{default:null}},parseDOM:[{tag:'span[mapa-chip="embed"]',priority:60,getAttrs:t=>rt(t)===""?!1:{ref:rt(t)}}],toDOM:t=>Ut(t.attrs.ref)}}}var Dr=n=>({href:`/new?title=${encodeURIComponent(n)}`,pending:!0});function an(n=Dr){return new ke({nodes:{...Rr,...zr(n)},marks:Ir})}function it(n,e,t){return G(n,I(e),t)}function G(n,e,t={}){let r=t.origin??(()=>null),i=[];for(let o=0;o<e.length;){if(e[o].kind===k){let[l,a]=Pr(n,e,o,r);i.push(...l),o=a;continue}i.push(Fr(n,e[o],r(o))),o++}let s=i[i.length-1];return t.trailing!==!1&&(!s||s.type!==n.nodes.paragraph)&&i.push(n.nodes.paragraph.create()),n.nodes.doc.create(null,i)}function Fr(n,e,t){let r=e.marker||null,i=nt(e);switch(e.kind){case R:return n.nodes.heading.create({origin:t,marker:r,level:e.level,source:e.source},Ae(n,i));case T:return Br(n,e,i,t);case N:return n.nodes.horizontal_rule.create({origin:t,source:e.source});case v:return n.nodes.blockquote.create({marker:r,prefix:Jr(e.source)},n.nodes.paragraph.create({origin:t},Ae(n,i)))}return n.nodes.paragraph.create({origin:t,marker:r},Ae(n,i))}function Br(n,e,t,r){let i=e.source.split(`
+`),s=/^( {0,3}(?:`{3,}|~{3,}))(.*)$/u.exec(i[0]),o=i[i.length-1];return n.nodes.code_block.create({origin:r,fence:s[1],info:s[2],closed:i.length>1&&Te(o,Ce(i[0])),close:i.length>1&&Ee(o)?o:null},t===""?null:n.text(t))}function Jr(n){return n.split(`
+`).map(e=>/^ *> ?/u.exec(e)?.[0]??"")}function Pr(n,e,t,r){let i=[],s=[],o=t;for(;o<e.length&&e[o].kind===k;o++){let l=e[o],a=Math.min(l.level,s.length);s.length=Math.min(s.length,a+1);let c=l.ordered?"ordered_list":"bullet_list";if(s.length===a+1&&s[a].kind!==c&&(s.length=a),s.length!==a+1){let u={kind:c,items:[]};a===0?i.push(u):s[a-1].items.at(-1).lists.push(u),s.push(u)}s[a].items.push({block:l,lists:[],origin:r(o)})}return[i.map(l=>cn(n,l)),o]}function cn(n,e){return n.nodes[e.kind].create(null,e.items.map(t=>Wr(n,t)))}function Wr(n,{block:e,lists:t,origin:r}){let[i,s]=nn(nt(e)),o={marker:e.marker||null,...tn(e),task:s!==null,checked:s},l=n.nodes.paragraph.create({origin:r},Ae(n,i));return n.nodes.list_item.create(o,[l,...t.map(a=>cn(n,a))])}function Ae(n,e){let t=[];for(let r of Oe(e))switch(r.kind){case et:t.push(n.text(r.text,[n.marks.code.create()]));break;case Me:t.push(n.text(r.text,[n.marks.link.create({href:r.url,bare:!r.source.startsWith("[")})]));break;case oe:t.push(Lr(n,r));break;case le:t.push(n.nodes.embed.create({ref:r.text.slice(3,-2),source:r.source}));break;default:t.push(...$r(n,r.text))}return t}function Lr(n,e){let t={anchor:e.anchor,shown:e.text,source:e.source};return K(e.target)?n.nodes.datelink.create({...t,date:e.target}):n.nodes.wikilink.create({...t,target:e.target})}function $r(n,e){return on(e).map(t=>{let r=y.setFrom([...t.em?[n.marks.em.create()]:[],...t.strong?[n.marks.strong.create()]:[]]);return t.kind==="break"?n.nodes.hard_break.create({indent:t.indent},null,r):n.text(t.text,r)})}var hn=new Set(["bullet_list","ordered_list"]);function E(n){let e=[];return n.forEach((t,r)=>qr(t,r,e)),e}function Q(n,e){e.index=n.length,n.push(e)}function qr(n,e,t){switch(n.type.name){case"paragraph":return Q(t,{kind:be,node:n,pos:e,holder:n,holderPos:e});case"heading":return Q(t,{kind:R,node:n,pos:e,holder:n,holderPos:e});case"code_block":return Q(t,{kind:T,node:n,pos:e,holder:n,holderPos:e});case"horizontal_rule":return Q(t,{kind:N,node:n,pos:e,holder:n,holderPos:e});case"blockquote":n.firstChild?.type.name==="paragraph"&&Q(t,{kind:v,node:n.firstChild,pos:e+1,holder:n,holderPos:e});return}hn.has(n.type.name)&&un(n,e,0,t)}function un(n,e,t,r){n.forEach((i,s,o)=>{let l=e+1+s;i.forEach((a,c,u)=>{let h=l+1+c;u===0&&a.type.name==="paragraph"?Q(r,{kind:k,node:a,pos:h,holder:i,holderPos:l,depth:t,list:n.type.name,listPos:e,listStart:o===0}):hn.has(a.type.name)&&un(a,h,t+1,r)})})}function B(n){let e=n.holder.attrs;switch(n.kind){case k:return JSON.stringify([k,n.depth,n.list,e.indent,e.bullet,e.number,e.delim,e.task,e.checked,e.marker]);case v:return JSON.stringify([v,e.prefix,e.marker])}return n.kind}function Ur(n){let e=n.content.size,t=null;for(let r=n.childCount-1;r>=0;r--){let i=n.child(r);if(i.type.name==="hard_break")t=e-i.nodeSize;else if(!(i.isText&&F(i.text)===""))break;e-=i.nodeSize}return t}function H(n){if(n.kind===v||n.kind===T||n.kind===N)return n.node;let e=Ur(n.node);return e===null?n.node:n.node.copy(n.node.content.cut(0,e))}function Hr(n,e){if(!e)return!1;let t=n.node;return t!==e.node&&!t.eq(e.node)&&!ot(H(n),e.node)?!1:B(n)===e.context}function ot(n,e){if(n.type!==e.type||!n.content.eq(e.content))return!1;for(let t of Object.keys(n.attrs))if(t!=="origin"&&!(t==="source"&&n.type.name==="heading")&&JSON.stringify(n.attrs[t])!==JSON.stringify(e.attrs[t]))return!1;return!0}function Re(n,{last:e=!0}={}){let t=n.node;switch(n.kind){case be:{let r=ze(H(n));return st(r)?"":r+Ie(n)}case R:{let r=ze(H(n));return st(r)?"":Vr(t.attrs)+r+Ie(n)}case k:return jr(n);case v:return Zr(n);case T:return Kr(t,e);case N:return sn(t.attrs.source??"")?t.attrs.source:"---"}return""}function st(n){return F(n)===""}function Ie(n){let e=n.holder.attrs.marker;return e&&/^[A-Za-z0-9-]{1,40}$/u.test(e)?` ^${e}`:""}function Vr(n){let e=Math.min(Math.max(n.level??1,1),6),t=/^(#{1,6})([ \t]+)/u.exec(n.source??"");return t&&t[1].length===e?t[0]:"#".repeat(e)+" "}function jr(n){let e=n.holder.attrs,t=ze(H(n));if(st(t))return"";let r=/^[ \t]*$/u.test(e.indent??"")?e.indent??"":"",i;n.list==="ordered_list"?i=(/^[0-9]{1,9}$/u.test(e.number??"")?e.number:"1")+(e.delim===")"?")":"."):i=["-","*","+"].includes(e.bullet)?e.bullet:"-";let s=e.task?`[${[" ","x","X"].includes(e.checked)?e.checked:" "}] `:"";return`${r}${i} ${s}${t}${Ie(n)}`}function Zr(n){let e=ze(n.node);if(e==="")return"";let t=Array.isArray(n.holder.attrs.prefix)?n.holder.attrs.prefix:[];return(e+Ie(n)).split(`
+`).map((r,i)=>{let s=t[i]??t[0]??"> ";return/^ *> ?$/u.test(s)||(s="> "),!s.endsWith(" ")&&r.startsWith(" ")&&(s+=" "),s+r}).join(`
+`)}function Kr(n,e){let t=n.attrs,r=/^ {0,3}(?:`{3,}|~{3,})$/u.test(t.fence??"")?t.fence:"```",i=r+String(t.info??"").split(`
+`)[0];return n.textContent!==""&&(i+=`
+`+n.textContent),t.close!=null&&Ee(t.close)&&(i+=`
+`+t.close),!e&&!fn(i)&&(i+=`
+`+r.trimStart()),i}function fn(n){let e=n.split(`
+`);return e.length>1&&Te(e[e.length-1],Ce(e[0]))}function ze(n){let e=[];n.forEach(r=>{let i=s=>r.marks.some(o=>o.type.name===s);if(r.isText){let s=r.marks.find(l=>l.type.name==="link"),o=e[e.length-1];i("code")?o?.kind==="code"?o.text+=r.text:e.push({kind:"code",text:r.text}):s?o?.kind==="link"&&o.mark.eq(s)?o.text+=r.text:e.push({kind:"link",text:r.text,mark:s}):e.push({kind:"text",text:r.text,em:i("em"),strong:i("strong")})}else if(r.type.name==="hard_break"){let s=/^[ \t]*/u.exec(r.attrs.indent??"")[0];e.push({kind:"text",text:`
+`+s,em:i("em"),strong:i("strong")})}else e.push({kind:"atom",text:_r(r)})});let t="";for(let r=0;r<e.length;){let i=e[r];if(i.kind==="text"){let s=r;for(;s<e.length&&e[s].kind==="text";)s++;t+=Qr(e.slice(r,s)),r=s;continue}i.kind==="code"?t+="`"+i.text+"`":i.kind==="link"?t+=Gr(i):t+=i.text,r++}return U(t)}function Gr({text:n,mark:e}){return e.attrs.bare&&n===e.attrs.href?n:`[${n}](${e.attrs.href})`}function Qr(n){return pn(n,"em",e=>Xr(e),"*")}function Xr(n){return pn(n,"strong",e=>e.map(t=>t.text).join(""),"**")}function pn(n,e,t,r){let i="";for(let s=0;s<n.length;){let o=s;for(;o<n.length&&n[o][e]===n[s][e];)o++;let l=t(n.slice(s,o));i+=n[s][e]?Yr(l,r):l,s=o}return i}function Yr(n,e){let t=/^([\t\n\f\r ]*)([^]*?)([\t\n\f\r ]*)$/u.exec(n);return t[2]===""?n:t[1]+e+t[2]+e+t[3]}function _r(n){let e=n.attrs;return e.source!=null&&ei(n,e.source)?e.source:n.type.name==="embed"?`![[${e.ref}]]`:`[[${n.type.name==="datelink"?e.date:e.target}${e.anchor?"#^"+e.anchor:""}${e.shown?"|"+e.shown:""}]]`}function ei(n,e){let t=Oe(e);if(t.length!==1||t[0].source!==e)return!1;let r=t[0];if(n.type.name==="embed")return r.kind===le&&r.text.slice(3,-2)===n.attrs.ref;if(r.kind!==oe)return!1;let i=n.type.name==="datelink";return K(r.target)===i&&r.target===(i?n.attrs.date:n.attrs.target)&&r.anchor===(n.attrs.anchor??"")&&r.text===(n.attrs.shown??"")}function O(n,e,t={}){let r=t.fresh??new Set,i=t.joins??new Set,s=E(n),o=new Set;for(let h of s){let f=h.node.attrs.origin;h.origin=f,h.first=f!=null&&!o.has(f),f!=null&&o.add(f),h.entry=h.first?e?.get(f):void 0,h.untouched=!r.has(h.index)&&Hr(h,h.entry),h.text=h.untouched?h.entry.source:Re(h)}let l=-1;s.forEach((h,f)=>{h.text!==""&&(l=f)});for(let h of s.slice(0,Math.max(l,0)))h.kind===T&&(h.untouched&&fn(h.text)||(h.untouched=!1,h.text=Re(h,{last:!1})));let a=s.filter(h=>h.text!==""),c="";a.forEach((h,f)=>{f===0?t.edges!==!1&&h.entry?.leading!=null&&(c+=h.entry.leading):(h.seam=ti(a[f-1],h,i.has(h.index)),c+=h.seam),c+=h.text});let u=a[a.length-1];return t.edges!==!1&&u?.entry?.trailing!=null&&(c+=u.entry.trailing),{body:t.raw?U(c):ve(c),blocks:s,emitted:a}}function lt(n,e,t){return O(n,e,t).body}function ti(n,e,t){if(!t&&n.first&&e.first){if(n.entry&&n.entry.next===e.origin&&n.entry.after!=null)return n.entry.after;if(e.entry&&e.entry.prev===n.origin&&e.entry.before!=null)return e.entry.before}return ni(n.kind,e.kind)}function ni(n,e){return n===k&&e===k?`
+`:`
+
+`}function at(n){let e=new Set;return n.map(t=>{if(t.kind===R)return`${R}:${Math.min(Math.max(t.node.attrs.level,1),6)}`;if(t.kind!==k)return t.kind;let r=!e.has(t.listPos);return e.add(t.listPos),`${k}:${t.list}:${t.depth}:${r}`})}function ri(n,e){return at(E(G(n,I(e),{trailing:!1})))}function dn(n){return at(n)}function ii(n,e){let t=Math.min(n.length,e.length);for(let r=0;r<t;r++)if(n[r]!==e[r])return r;return n.length===e.length?-1:t}function De(n,e){let t=n.type.schema,r=l=>{let a=O(n,e,l);return a.shapes=at(a.emitted),a.mismatch=ii(a.shapes,ri(t,a.body)),a},i=new Set,s=new Set,o=r({});for(let l=0;o.mismatch>=0&&l<4;l++){let a=[-1,0,1,2].map(c=>o.emitted[o.mismatch+c]);for(let c of a)c&&(s.add(c.index),l>=2&&i.add(c.index));o=r({fresh:i,joins:s})}if(o.mismatch>=0){let l=new Set(o.blocks.map(a=>a.index));o=r({fresh:l,joins:l})}return{ok:o.mismatch<0,body:o.body,shapes:o.shapes,fixed:s.size>0}}var gn=65535,yn=Math.pow(2,16);function si(n,e){return n+e*yn}function mn(n){return n&gn}function oi(n){return(n-(n&gn))/yn}var xn=1,kn=2,Fe=4,wn=8,Be=class{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&wn)>0}get deletedBefore(){return(this.delInfo&(xn|Fe))>0}get deletedAfter(){return(this.delInfo&(kn|Fe))>0}get deletedAcross(){return(this.delInfo&Fe)>0}},z=class n{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&n.empty)return n.empty}recover(e){let t=0,r=mn(e);if(!this.inverted)for(let i=0;i<r;i++)t+=this.ranges[i*3+2]-this.ranges[i*3+1];return this.ranges[r*3]+t+oi(e)}mapResult(e,t=1){return this._map(e,t,!1)}map(e,t=1){return this._map(e,t,!0)}_map(e,t,r){let i=0,s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;l<this.ranges.length;l+=3){let a=this.ranges[l]-(this.inverted?i:0);if(a>e)break;let c=this.ranges[l+s],u=this.ranges[l+o],h=a+c;if(e<=h){let f=c?e==a?-1:e==h?1:t:t,p=a+i+(f<0?0:u);if(r)return p;let g=e==(t<0?a:h)?null:si(l/3,e-a),b=e==a?kn:e==h?xn:Fe;return(t<0?e!=a:e!=h)&&(b|=wn),new Be(p,b,g)}i+=u-c}return r?e+i:new Be(e+i,0,null)}touches(e,t){let r=0,i=mn(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;l<this.ranges.length;l+=3){let a=this.ranges[l]-(this.inverted?r:0);if(a>e)break;let c=this.ranges[l+s],u=a+c;if(e<=u&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i<this.ranges.length;i+=3){let o=this.ranges[i],l=o-(this.inverted?s:0),a=o+(this.inverted?0:s),c=this.ranges[i+t],u=this.ranges[i+r];e(l,l+c,a,a+u),s+=u-c}}invert(){return new n(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?n.empty:new n(e<0?[0,-e,0]:[0,0,e])}};z.empty=new z([]);var ct=Object.create(null),w=class{getMap(){return z.empty}merge(e){return null}static fromJSON(e,t){if(!t||!t.stepType)throw new RangeError("Invalid input for Step.fromJSON");let r=ct[t.stepType];if(!r)throw new RangeError(`No step type ${t.stepType} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in ct)throw new RangeError("Duplicate use of step JSON ID "+e);return ct[e]=t,t.prototype.jsonID=e,t}},S=class n{constructor(e,t){this.doc=e,this.failed=t}static ok(e){return new n(e,null)}static fail(e){return new n(null,e)}static fromReplace(e,t,r,i){try{return n.ok(e.replace(t,r,i))}catch(s){if(s instanceof D)return n.fail(s.message);throw s}}};function pt(n,e,t){let r=[];for(let i=0;i<n.childCount;i++){let s=n.child(i);s.content.size&&(s=s.copy(pt(s.content,e,s))),s.isInline&&(s=e(s,t,i)),r.push(s)}return m.fromArray(r)}var Je=class n extends w{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=e.resolve(this.from),i=r.node(r.sharedDepth(this.to)),s=new d(pt(t.content,(o,l)=>!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return S.fromReplace(e,this.from,this.to,s)}invert(){return new Pe(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new n(t.pos,r.pos,this.mark)}merge(e){return e instanceof n&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new n(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new n(t.from,t.to,e.markFromJSON(t.mark))}};w.jsonID("addMark",Je);var Pe=class n extends w{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new d(pt(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return S.fromReplace(e,this.from,this.to,r)}invert(){return new Je(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new n(t.pos,r.pos,this.mark)}merge(e){return e instanceof n&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new n(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new n(t.from,t.to,e.markFromJSON(t.mark))}};w.jsonID("removeMark",Pe);var We=class n extends w{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return S.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return S.fromReplace(e,this.pos,this.pos+1,new d(m.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;i<t.marks.length;i++)if(!t.marks[i].isInSet(r))return new n(this.pos,t.marks[i]);return new n(this.pos,this.mark)}}return new Le(this.pos,this.mark)}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new n(t.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new n(t.pos,e.markFromJSON(t.mark))}};w.jsonID("addNodeMark",We);var Le=class n extends w{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return S.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.removeFromSet(t.marks));return S.fromReplace(e,this.pos,this.pos+1,new d(m.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);return!t||!this.mark.isInSet(t.marks)?this:new We(this.pos,this.mark)}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new n(t.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new n(t.pos,e.markFromJSON(t.mark))}};w.jsonID("removeNodeMark",Le);var X=class n extends w{constructor(e,t,r,i=!1){super(),this.from=e,this.to=t,this.slice=r,this.structure=i}apply(e){return this.structure&&ht(e,this.from,this.to)?S.fail("Structure replace would overwrite content"):S.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new z([this.from,this.to-this.from,this.slice.size])}invert(e){return new n(this.from,this.from+this.slice.size,e.slice(this.from,this.to))}map(e){let t=e.mapResult(this.to,-1),r=this.from==this.to&&n.MAP_BIAS<0?t:e.mapResult(this.from,1);return r.deletedAcross&&t.deletedAcross?null:new n(r.pos,Math.max(r.pos,t.pos),this.slice,this.structure)}merge(e){if(!(e instanceof n)||e.structure||this.structure)return null;if(this.from+this.slice.size==e.from&&!this.slice.openEnd&&!e.slice.openStart){let t=this.slice.size+e.slice.size==0?d.empty:new d(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new n(this.from,this.to+(e.to-e.from),t,this.structure)}else if(e.to==this.from&&!this.slice.openStart&&!e.slice.openEnd){let t=this.slice.size+e.slice.size==0?d.empty:new d(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new n(e.from,this.to,t,this.structure)}else return null}toJSON(){let e={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new n(t.from,t.to,d.fromJSON(e,t.slice),!!t.structure)}};X.MAP_BIAS=1;w.jsonID("replace",X);var he=class n extends w{constructor(e,t,r,i,s,o,l=!1){super(),this.from=e,this.to=t,this.gapFrom=r,this.gapTo=i,this.slice=s,this.insert=o,this.structure=l}apply(e){if(this.structure&&(ht(e,this.from,this.gapFrom)||ht(e,this.gapTo,this.to)))return S.fail("Structure gap-replace would overwrite content");let t=e.slice(this.gapFrom,this.gapTo);if(t.openStart||t.openEnd)return S.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,t.content);return r?S.fromReplace(e,this.from,this.to,r):S.fail("Content does not fit in gap")}getMap(){return new z([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(e){let t=this.gapTo-this.gapFrom;return new n(this.from,this.from+this.slice.size+t,this.from+this.insert,this.from+this.insert+t,e.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1),i=this.from==this.gapFrom?t.pos:e.map(this.gapFrom,-1),s=this.to==this.gapTo?r.pos:e.map(this.gapTo,1);return t.deletedAcross&&r.deletedAcross||i<t.pos||s>r.pos?null:new n(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new n(t.from,t.to,t.gapFrom,t.gapTo,d.fromJSON(e,t.slice),t.insert,!!t.structure)}};w.jsonID("replaceAround",he);function ht(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}var ut=class n extends w{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return S.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return S.fromReplace(e,this.pos,this.pos+1,new d(m.from(i),0,t.isLeaf?0:1))}getMap(){return z.empty}invert(e){return new n(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new n(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new n(t.pos,t.attr,t.value)}};w.jsonID("attr",ut);var ft=class n extends w{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return S.ok(r)}getMap(){return z.empty}invert(e){return new n(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new n(t.attr,t.value)}};w.jsonID("docAttr",ft);var ue=class extends Error{};ue=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t};ue.prototype=Object.create(Error.prototype);ue.prototype.constructor=ue;ue.prototype.name="TransformError";var dt=Object.create(null),x=class{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new gt(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t<e.length;t++)if(e[t].$from.pos!=e[t].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(e,t=d.empty){let r=t.content.lastChild,i=null;for(let l=0;l<t.openEnd;l++)i=r,r=r.lastChild;let s=e.steps.length,o=this.ranges;for(let l=0;l<o.length;l++){let{$from:a,$to:c}=o[l],u=e.mapping.slice(s);e.replaceRange(u.map(a.pos),u.map(c.pos),l?d.empty:t),l==0&&bn(e,s,(r?r.isInline:i&&i.isTextblock)?-1:1)}}replaceWith(e,t){let r=e.steps.length,i=this.ranges;for(let s=0;s<i.length;s++){let{$from:o,$to:l}=i[s],a=e.mapping.slice(r),c=a.map(o.pos),u=a.map(l.pos);s?e.deleteRange(c,u):(e.replaceRangeWith(c,u,t),bn(e,r,t.isInline?-1:1))}}static findFrom(e,t,r=!1){let i=e.parent.inlineContent?new C(e):Y(e.node(0),e.parent,e.pos,e.index(),t,r);if(i)return i;for(let s=e.depth-1;s>=0;s--){let o=t<0?Y(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):Y(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new V(e.node(0))}static atStart(e){return Y(e,e,0,0,1)||new V(e)}static atEnd(e){return Y(e,e,e.content.size,e.childCount,-1)||new V(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=dt[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in dt)throw new RangeError("Duplicate use of selection JSON ID "+e);return dt[e]=t,t.prototype.jsonID=e,t}getBookmark(){return C.between(this.$anchor,this.$head).getBookmark()}};x.prototype.visible=!0;var gt=class{constructor(e,t){this.$from=e,this.$to=t}},Sn=!1;function Mn(n){!Sn&&!n.parent.inlineContent&&(Sn=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}var C=class n extends x{constructor(e,t=e){Mn(e),Mn(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return x.near(r);let i=e.resolve(t.map(this.anchor));return new n(i.parent.inlineContent?i:r,r)}replace(e,t=d.empty){if(super.replace(e,t),t==d.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof n&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new $e(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new n(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=x.findFrom(t,r,!0)||x.findFrom(t,-r,!0);if(s)t=s.$head;else return x.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(x.findFrom(e,-r,!0)||x.findFrom(e,r,!0)).$anchor,e.pos<t.pos!=i<0&&(e=t))),new n(e,t)}};x.jsonID("text",C);var $e=class n{constructor(e,t){this.anchor=e,this.head=t}map(e){return new n(e.map(this.anchor),e.map(this.head))}resolve(e){return C.between(e.resolve(this.anchor),e.resolve(this.head))}},J=class n extends x{constructor(e){let t=e.nodeAfter,r=e.node(0).resolve(e.pos+t.nodeSize);super(e,r),this.node=t}map(e,t){let{deleted:r,pos:i}=t.mapResult(this.anchor),s=e.resolve(i);return r?x.near(s):new n(s)}content(){return new d(m.from(this.node),0,0)}eq(e){return e instanceof n&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new yt(this.anchor)}static fromJSON(e,t){if(typeof t.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new n(e.resolve(t.anchor))}static create(e,t){return new n(e.resolve(t))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}};J.prototype.visible=!1;x.jsonID("node",J);var yt=class n{constructor(e){this.anchor=e}map(e){let{deleted:t,pos:r}=e.mapResult(this.anchor);return t?new $e(r,r):new n(r)}resolve(e){let t=e.resolve(this.anchor),r=t.nodeAfter;return r&&J.isSelectable(r)?new J(t):x.near(t)}},V=class n extends x{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,t=d.empty){if(t==d.empty){e.delete(0,e.doc.content.size);let r=x.atStart(e.doc);r.eq(e.selection)||e.setSelection(r)}else super.replace(e,t)}toJSON(){return{type:"all"}}static fromJSON(e){return new n(e)}map(e){return new n(e)}eq(e){return e instanceof n}getBookmark(){return li}};x.jsonID("all",V);var li={map(){return this},resolve(n){return new V(n)}};function Y(n,e,t,r,i,s=!1){if(e.inlineContent)return C.create(n,t);for(let o=r-(i>0?0:1);i>0?o<e.childCount:o>=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&J.isSelectable(l))return J.create(n,t-(i<0?l.nodeSize:0))}else{let a=Y(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function bn(n,e,t){let r=n.steps.length-1;if(r<e)return;let i=n.steps[r];if(!(i instanceof X||i instanceof he))return;let s=n.mapping.maps[r],o;s.forEach((l,a,c,u)=>{o==null&&(o=u)}),n.setSelection(x.near(n.doc.resolve(o),t))}function vn(n,e){return!e||!n?n:n.bind(e)}var _=class{constructor(e,t,r){this.name=e,this.init=vn(t.init,r),this.apply=vn(t.apply,r)}},Yi=[new _("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new _("selection",{init(n,e){return n.selection||x.atStart(e.doc)},apply(n){return n.selection}}),new _("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new _("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];function On(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=On(i,e,{})),t[r]=i}return t}var ee=class{constructor(e){this.spec=e,this.props={},e.props&&On(e.props,this,this.props),this.key=e.key?e.key.key:En("plugin")}getState(e){return e[this.key]}},mt=Object.create(null);function En(n){return n in mt?n+"$"+ ++mt[n]:(mt[n]=0,n+"$")}var te=class{constructor(e="key"){this.key=En(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}};var qe=class{constructor(){this.issued=0,this.table=new Map}mint(){return++this.issued}get(e){return this.table.get(e)}record(e,t){if(this.table.has(e))throw new Error(`origin ${e} is already recorded`);this.table.set(e,Object.freeze(t))}},ne=new te("mapa-fidelity");function re(n,e,t,r={}){let i=U(t),s=I(i),o=s.map(()=>e.mint()),l=G(n,s,{origin:u=>o[u],...r}),a=E(l).slice(0,s.length),c=r.edges!==!1;return s.forEach((u,h)=>{let f=s[h-1],p=s[h+1];e.record(o[h],{node:a[h].node,source:u.source,context:B(a[h]),prev:f?o[h-1]:null,next:p?o[h+1]:null,before:f?i.slice(f.to,u.from):null,after:p?i.slice(u.to,p.from):null,leading:c&&!f?i.slice(0,u.from):null,trailing:c&&!p?i.slice(u.to):null})}),{doc:l,nodes:a,origins:o}}function ai(n,e){let t=new qe,{doc:r}=re(n,t,e);return{doc:r,fidelity:t}}function ci(n,e){return B(n)===B(e)&&ot(H(n),e.node)}function Tn(n,e,t){let r=n.length,i=e.length,s=Array.from({length:r+1},()=>new Int32Array(i+1));for(let l=r-1;l>=0;l--)for(let a=i-1;a>=0;a--)s[l][a]=t(n[l],e[a])?s[l+1][a+1]+1:Math.max(s[l+1][a],s[l][a+1]);let o=[];for(let l=0,a=0;l<r&&a<i;)t(n[l],e[a])?(o.push([l,a]),l++,a++):s[l+1][a]>=s[l][a+1]?l++:a++;return o}function Nn(n,e,t){let r=n.state,{nodes:i,origins:s}=re(r.schema,e,t),o=i.slice(0,s.length),l=O(r.doc,e).emitted,a=r.tr;for(let[c,u]of Tn(l,o,ci))a.setNodeAttribute(l[c].pos,"origin",s[u]);return a.setMeta("addToHistory",!1).setMeta(ne,{rebuilt:!0}),n.dispatch(a),{ok:lt(n.state.doc,e)===ve(t)}}function xt(n,e){let t=e.topNodeType.create(null,n),{emitted:r}=O(t,null,{raw:!0}),i=dn(r);return JSON.stringify(r.map((s,o)=>[i[o],s.text]))}function An(n,e,t){let r=n.doc.type.schema,{doc:i}=re(r,e,t),s=[];n.doc.forEach((f,p)=>{let g=xt(f,r);g!=="[]"&&s.push({node:f,offset:p,key:g})});let o=[];i.forEach(f=>{let p=xt(f,r);p!=="[]"&&o.push({node:f,key:p})});let l=Tn(s,o,(f,p)=>f.key===p.key),a=[],c=[-1,-1];for(let f of[...l,[s.length,o.length]]){let[p,g]=[c[0]+1,c[1]+1];if(f[0]>p||f[1]>g){let b=p<s.length?s[p].offset:s[s.length-1]?s[s.length-1].offset+s[s.length-1].node.nodeSize:0,P=f[0]>p?s[f[0]-1].offset+s[f[0]-1].node.nodeSize:b;a.push({from:b,to:P,nodes:o.slice(g,f[1]).map(fe=>fe.node)})}c=f}let u=n.selection.head,h=null;for(let f of a.reverse()){h===null&&u>=f.from&&u<=f.to&&(h={left:hi(n.doc,u,f.to),gap:f});let p=[];n.doc.nodesBetween(f.from,f.to,(g,b)=>(b>=f.from&&xt(g,r)==="[]"&&p.push(g),!1)),n.replaceWith(f.from,f.to,m.from([...f.nodes,...p])),f.size=[...f.nodes,...p].reduce((g,b)=>g+b.nodeSize,0)}if(h){let f=n.mapping.map(h.gap.from,-1),p=ui(n.doc,f,f+h.gap.size,h.left);n.setSelection(C.near(n.doc.resolve(p),-1))}return n}function hi(n,e,t){let r=0;return n.nodesBetween(e,t,(i,s)=>{i.isText?r+=Math.min(s+i.nodeSize,t)-Math.max(s,e):i.isInline&&(r+=1)}),r}function ui(n,e,t,r){let i=null,s=[];n.nodesBetween(e,t,(o,l)=>{if(o.isTextblock)return s.push({node:o,pos:l}),!1});for(let{node:o,pos:l}of s.reverse()){let a=o.content.size;if(r<=a){i=l+1+a-r;break}r-=a}return i===null&&(i=s.length?s[s.length-1].pos+1:e),Math.min(Math.max(i,0),n.content.size)}function Rn(n,e,t){let r=An(n.state.tr,e,t);return r.docChanged&&n.dispatch(r.scrollIntoView()),Nn(n,e,t)}function fi(n,e){let t=De(n.state.doc,e);if(t.ok)return{body:t.body,shapes:t.shapes,adopted:!1};Rn(n,e,t.body);let r=De(n.state.doc,e);return{body:r.body,shapes:r.shapes,adopted:!0}}var pi={paragraph:["marker"],heading:["level","marker"],code_block:["fence","info","closed","close"],list_item:["indent","bullet","number","delim","task","checked","marker"],blockquote:["prefix","marker"]};function Cn(n){return n.kind===k||n.kind===v?n.holder:n.node}function di(n,e){if(n.kind===N)return null;let t=Re(n);if(t==="")return null;let r=I(t);if(r.length!==1||r[0].kind!==n.kind)return"structural";let i=E(G(e,r,{trailing:!1}))[0];if(n.kind===k&&i.list!==n.list)return"structural";let s=Cn(n),o=Cn(i),l=[];for(let f of pi[s.type.name]??[])JSON.stringify(s.attrs[f])!==JSON.stringify(o.attrs[f])&&l.push([f,o.attrs[f]]);let a=H(n).content,c=i.node.content,u=a.findDiffStart(c);if(u===null&&l.length===0)return null;let h=null;if(u!==null){let{a:f,b:p}=a.findDiffEnd(c),g=u-Math.min(f,p);g>0&&(f+=g,p+=g),h={from:u,to:f,content:c.cut(u,p)}}return{block:n,attrs:l,diff:h,text:t,node:i.node}}function mi(n,{block:e,attrs:t,diff:r},i){if(r){let o=e.pos+1;n.replaceWith(o+r.from,o+r.to,r.content)}let s=e.kind===k||e.kind===v?e.holderPos:e.pos;for(let[o,l]of t)n.setNodeAttribute(s,o,l);n.setNodeAttribute(e.pos,"origin",i)}function gi(n,e,t=null){let r=n.tr;return In(r,e,t),r.docChanged?r:null}function yi(n,e){let t=n.blocks.filter(i=>!i.untouched);if(!e)return t;let r=new Map(E(e).map(i=>[i.node,B(i)]));return t.filter(i=>r.get(i.node)!==B(i))}function In(n,e,t){let r=n.doc.type.schema,i=O(n.doc,e),s=[];for(let h of yi(i,t)){let f=di(h,r);if(f==="structural"){An(n,e,i.body);return}f&&s.push(f)}if(s.length===0)return;let o=new Map(s.map(h=>[h.block,e.mint()])),l=h=>o.get(h)??(h.first?h.origin:null),{emitted:a}=i,c=s.map(({block:h,text:f,node:p})=>{let g=a.indexOf(h),b=a[g-1],P=a[g+1],fe=o.get(h);return{origin:fe,source:f,node:p.type.create({...p.attrs,origin:fe},p.content,p.marks),prev:b?l(b):null,next:P?l(P):null,before:b?h.seam:null,after:P?P.seam:null,leading:g===0?h.entry?.leading??null:null,trailing:g>=0&&!P?h.entry?.trailing??null:null}});for(let h of[...s].reverse())mi(n,h,o.get(h.block));let u=new Map(E(n.doc).map(h=>[h.node.attrs.origin,h]));for(let{origin:h,...f}of c)e.record(h,{...f,context:B(u.get(h))})}function xi(n,e){let t=o=>{let l=new Map;for(let a of E(o)){let c=a.holder.attrs.marker;c&&l.set(c,(l.get(c)??0)+1)}return l},r=e?t(e):new Map,i=new Set(e?E(e).map(o=>o.holder):[]),s=E(n.doc);for(let[o,l]of t(n.doc)){let a=l-Math.max(r.get(o)??0,1);if(a<=0)continue;let[,...c]=s.filter(h=>h.holder.attrs.marker===o),u=[...c.filter(h=>!i.has(h.holder)).reverse(),...c.filter(h=>i.has(h.holder)).reverse()];for(let h of u.slice(0,a))n.setNodeAttribute(h.holderPos,"marker",null)}}function ki(n){return Math.floor(String(n??"").replaceAll(" "," ").length/2)}function wi(n,e){let t=-1;for(let s of O(n.doc,e).emitted){if(s.kind!==k){t=-1;continue}let o=ki(s.holder.attrs.indent),l=" ".repeat(s.depth);Math.min(o,t+1)!==s.depth&&s.depth<=t+1&&s.holder.attrs.indent!==l&&n.setNodeAttribute(s.holderPos,"indent",l),t=s.depth}let r=[],i=(s,o)=>{let l=o,a=null;s.forEach(c=>{a&&a.type===c.type&&(c.type.name==="bullet_list"||c.type.name==="ordered_list")&&r.push(l),a=c,l+=c.nodeSize})};i(n.doc,0),n.doc.descendants((s,o)=>{if(s.isTextblock)return!1;i(s,o+1)});for(let s of r.sort((o,l)=>l-o))n.join(s)}function Si(n){let e=n.doc.lastChild;(!e||e.type.name!=="paragraph")&&n.insert(n.doc.content.size,n.doc.type.schema.nodes.paragraph.create())}function zn(n,e,t=null){let r=n.tr;for(let i=0;i<4;i++){let s=r.doc;if(In(r,e,t),xi(r,t),wi(r,e),Si(r),r.doc===s)break}return r.docChanged?r:null}function Mi(n,e={}){let t=null,r=null,i=()=>e.composing?e.composing():t?.composing??!1;return new ee({key:ne,state:{init:()=>n,apply:(s,o)=>o},view(s){return t=s,{destroy(){t=null}}},props:{handleDOMEvents:{compositionend(s){return setTimeout(()=>{t===s&&r&&s.dispatch(s.state.tr.setMeta(ne,{composed:!0}))},50),!1}}},appendTransaction(s,o,l){if(!s.some(h=>h.docChanged&&!h.getMeta(ne)?.rebuilt)&&!r)return null;if(i())return r=r??o.doc,null;let c=r??o.doc;r=null;let u=zn(l,n,c);return u?u.setMeta(ne,{settled:!0}):null}})}var kt="application/x-mapa";function wt(n,e,t=n.selection.from,r=n.selection.to){let i=n.doc.slice(t,r,!0),s=n.schema.topNodeType.create(null,i.content),{body:o,emitted:l}=O(s,e,{edges:!1,raw:!0}),a=JSON.stringify({v:1,sources:l.map(c=>c.text),seams:l.slice(1).map(c=>c.seam)});return{text:o,mapa:a}}function bi(n){let e;try{e=JSON.parse(n)}catch{return null}let{sources:t,seams:r}=e??{};if(e?.v!==1||!Array.isArray(t)||!Array.isArray(r)||t.length===0||r.length!==t.length-1||![...t,...r].every(o=>typeof o=="string")||!r.every(o=>/^\n(?:[^\n]*\n)*$/u.test(o)))return null;let i=t.map((o,l)=>(l?r[l-1]:"")+o).join(""),s=I(i);return s.length!==t.length||s.some((o,l)=>o.source!==t[l])?null:i}function vi(n,e){let{from:t,to:r}=n.selection,i=new Set;for(let s of O(n.doc,e).emitted){let o=s.holder.attrs.marker,l=s.holderPos>=t&&s.holderPos+s.holder.nodeSize<=r;o&&!l&&i.add(o)}return i}function Dn(n,e){let t=[];return n.forEach(r=>{let i=r;!r.isTextblock&&!r.isLeaf&&(i=r.copy(Dn(r.content,e))),i.attrs.marker&&e.has(i.attrs.marker)&&(i=i.type.create({...i.attrs,marker:null},i.content,i.marks)),t.push(i)}),m.from(t)}function Fn(n,e,t){let r=vi(e,t);return r.size===0?n:new d(Dn(n.content,r),n.openStart,n.openEnd)}function Bn(n,e,t){let r=bi(t);if(r===null)return null;let{doc:i}=re(n.schema,e,r,{trailing:!1,edges:!1}),s=Fn(d.maxOpen(i.content),n,e),{$from:o,empty:l}=n.selection;if(l&&o.depth===1&&o.parent.type.name==="paragraph"&&o.parent.content.size===0){let a=n.tr.replaceWith(o.before(),o.after(),s.content),c=o.before()+s.content.size;return a.setSelection(C.near(a.doc.resolve(c),-1))}return n.tr.replaceSelection(s)}function Jn(n,e){let t=it(n,e,{trailing:!1});return t.childCount?d.maxOpen(t.content):d.empty}function Oi(n,e){let t=e.content,r=t.firstChild;if(!r)return"";r.isInline?t=m.from(n.nodes.paragraph.create(null,t)):r.type.name==="list_item"&&(t=m.from(n.nodes.bullet_list.create(null,t)));try{return O(n.topNodeType.create(null,t),null,{edges:!1,raw:!0}).body}catch{return e.content.textBetween(0,e.content.size,`
+
+`)}}var Ei=new te("mapa-clipboard");function Ci(n){let e=(t,r,i)=>{let s=r.clipboardData;if(!s||t.state.selection.empty)return!1;let{text:o,mapa:l}=wt(t.state,n),{dom:a}=t.serializeForClipboard(t.state.selection.content());return r.preventDefault(),s.clearData(),s.setData("text/html",a.innerHTML),s.setData("text/plain",o),s.setData(kt,l),i&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut")),!0};return new ee({key:Ei,props:{handleDOMEvents:{copy:(t,r)=>e(t,r,!1),cut:(t,r)=>e(t,r,!0)},handlePaste(t,r){let i=r.clipboardData?.getData(kt);if(!i)return!1;let s=Bn(t.state,n,i);return s?(t.dispatch(s.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0):!1},clipboardTextSerializer(t,r){return r.state.selection.content().eq(t)?wt(r.state,n).text:Oi(r.state.schema,t)},clipboardTextParser(t,r,i,s){return Jn(s.state.schema,t)},transformPasted(t,r){return Fn(t,r.state,n)}}})}var ms=an();export{qe as Fidelity,Rn as applyBody,Ci as clipboardPlugin,wt as copyData,an as createSchema,E as docBlocks,ne as fidelityKey,Mi as fidelityPlugin,it as fromMarkdown,kt as mapaType,ai as mount,Bn as pasteTransaction,fi as prepareSave,Nn as rebuild,re as recordBody,gi as reparse,ms as schema,lt as serialise,O as serialiseDetailed,zn as settle,De as structureCheck,Jn as textSlice};