diff --git a/src/core/links.ts b/src/core/links.ts new file mode 100644 index 0000000..62c48f8 --- /dev/null +++ b/src/core/links.ts @@ -0,0 +1,236 @@ +/** + * Links between nodes, and from nodes to Wikipedia and the web: the backlinks index, finding a + * node target again when its id is gone, and applying a batch of links through the op API. + * + * A link is a note with a target and no body, so it is anchored, orphaned, healed, merged, undone + * and versioned like any note. Nothing here is stored except through ops; the index is derived. + */ +import { Doc, docOf, findDoc, notesOf, sections, type Actor, type NodeId, type NodeSnap, type Op, type Snap } from "./model"; +import { sameTarget, wikiKey, type Ref } from "./ref"; +import { clip, type Range } from "./text"; + +// ---- finding a node target ---- + +/** The nearest section at or above a node: the place a note's text is read in. */ +export function ownerSection(snap: Snap, id: NodeId): NodeId { + let n = snap.nodes[id]; + while (n && n.kind === "note" && n.parent) n = snap.nodes[n.parent]; + return n?.id ?? id; +} + +/** A target naming a node, with the hint that finds it again: its document's slug and the titles down to it. */ +export function nodeRef(snap: Snap, id: NodeId): Ref & { kind: "node" } { + const n = snap.nodes[id]; + const d = docOf(snap, id); + const sec = ownerSection(snap, id); + const path: string[] = []; + for (let x = snap.nodes[sec]; x && x.id !== d && x.parent; x = snap.nodes[x.parent]) path.unshift(x.title); + const out: Ref & { kind: "node" } = { kind: "node", id }; + const slug = d ? snap.nodes[d].slug : undefined; + if (slug) out.doc = slug; + out.path = path; + if (n.kind === "note") out.quote = n.anchors[0]?.text || n.anchors[0]?.quote || ""; + return out; +} + +/** + * The node a target names: by id while it exists, else by its hint (document, section titles, + * and a note's quote). `here` is the document a relative path is read from. Null if neither finds it. + */ +export function resolveNode(snap: Snap, ref: Ref & { kind: "node" }, here?: NodeId): NodeId | null { + if (ref.id && snap.nodes[ref.id]) return ref.id; + if (!ref.path && !ref.doc) return null; + let at = ref.doc ? findDoc(snap, ref.doc) : here; + if (!at || !snap.nodes[at]) return null; + for (const title of ref.path ?? []) { + const kids = sections(snap, at); + const next = kids.find((c) => snap.nodes[c].title === title) ?? kids.find((c) => snap.nodes[c].title.toLowerCase() === title.toLowerCase()); + if (!next) return null; + at = next; + } + if (ref.quote !== undefined) { + const note = notesOf(snap, at).find((c) => snap.nodes[c].anchors.some((a) => a.text === ref.quote || a.quote === ref.quote)); + return note ?? null; + } + return at; +} + +// ---- the backlinks index ---- + +/** + * For each node, the nodes that link to it; for each Wikipedia article, the nodes that link to it. + * Kept current from the snapshot's patches (Doc.onPatch), so a change costs what it touched, and + * built whole only when the snapshot is read whole (boot, checkout). + */ +export class LinkIndex { + private byNode = new Map>(); + private byWiki = new Map>(); + /** Node targets with no id yet (written from a file, waiting for their target to be imported). */ + private unresolved = new Set(); + + constructor(private doc: Doc) { + doc.onPatch((was, nodes) => { + if (!was) return this.rebuild(nodes); + for (const [id, before] of was) { + if (before?.ref) this.file(id, before.ref, false); + const after = nodes[id]; + if (after?.ref) this.file(id, after.ref, true); + } + }); + this.rebuild(doc.snap().nodes); + } + + private rebuild(nodes: Record) { + this.byNode.clear(); + this.byWiki.clear(); + this.unresolved.clear(); + for (const id in nodes) { + const r = nodes[id as NodeId].ref; + if (r) this.file(id as NodeId, r, true); + } + } + + private file(id: NodeId, r: Ref, add: boolean) { + if (r.kind === "url") return; + if (r.kind === "node" && !r.id) { + if (add) this.unresolved.add(id); + else this.unresolved.delete(id); + return; + } + const map = r.kind === "node" ? this.byNode : this.byWiki; + const key = r.kind === "node" ? r.id! : wikiKey(r.lang, r.title); + let set = map.get(key); + if (add) { + if (!set) map.set(key, (set = new Set())); + set.add(id); + } else if (set) { + set.delete(id); + if (!set.size) map.delete(key); + } + } + + /** The nodes whose target is this node. */ + linksTo(id: NodeId): NodeId[] { + this.doc.snap(); + return [...(this.byNode.get(id) ?? [])]; + } + + /** The nodes whose target is this article. */ + mentions(lang: string, title: string): NodeId[] { + this.doc.snap(); + return [...(this.byWiki.get(wikiKey(lang, title)) ?? [])]; + } + + /** Nodes whose node target is gone or was never found: what healing tries to find again. */ + broken(): NodeId[] { + const snap = this.doc.snap(); + const out = [...this.unresolved]; + for (const [target, from] of this.byNode) if (!snap.nodes[target]) out.push(...from); + return out; + } + + /** Every Wikipedia article linked from the library, with how many nodes link to it. */ + articles(): { key: string; count: number }[] { + this.doc.snap(); + return [...this.byWiki].map(([key, s]) => ({ key, count: s.size })); + } +} + +const indexes = new WeakMap(); +/** The backlinks index of a library, made on first use and kept current from then on. */ +export function linkIndex(doc: Doc): LinkIndex { + let ix = indexes.get(doc); + if (!ix) indexes.set(doc, (ix = new LinkIndex(doc))); + return ix; +} + +// ---- healing ---- + +/** + * Find node targets again whose node is gone (undoing a delete brings nodes back under new ids) + * or was never found (a file linking to a document imported later), from the hint each carries. + * One system commit, which undo steps over. Returns how many were found. + */ +export function healLinks(doc: Doc): number { + const snap = doc.snap(); + const ops: Op[] = []; + for (const id of linkIndex(doc).broken()) { + const n = snap.nodes[id]; + if (!n || n.ref?.kind !== "node") continue; + const found = resolveNode(snap, n.ref, docOf(snap, id) ?? undefined); + if (found && found !== n.ref.id) ops.push({ op: "update", id, ref: nodeRef(snap, found) }); + } + if (ops.length) doc.apply(ops, `Find ${ops.length} link target${ops.length > 1 ? "s" : ""} again`, { actor: "llm", tag: "regen" }); + return ops.length; +} + +// ---- applying links ---- + +export interface LinkSpec { + /** The node whose text is linked. */ + node: NodeId; + /** The linked words: the first occurrence of this text in the node's body… */ + quote?: string; + /** …or these offsets into it. */ + range?: Range; + target: Ref; +} + +export interface LinkResult { + created: NodeId[]; + /** Existing notes on the same span that took the target. */ + merged: NodeId[]; + /** Spans that already had this target. */ + same: number; + /** Spans that already had a different target: left alone, so a person's link is never replaced. */ + occupied: number; + /** Specs whose node or words could not be found. */ + missing: number; +} + +/** + * Link spans of text to targets, as one commit through the op API: a span that already carries + * the target is skipped, a span that carries a note without a target gives that note the target + * (one node, not two stacked on the same words), and a span that already links elsewhere is left + * alone. Running the same batch twice changes nothing the second time. Made for bulk use: link + * discovery calls this with whatever it found. + */ +export function applyLinks(doc: Doc, specs: LinkSpec[], meta: { message?: string; actor?: Actor; author?: string; tag?: string } = {}): LinkResult { + const snap = doc.snap(); + const out: LinkResult = { created: [], merged: [], same: 0, occupied: 0, missing: 0 }; + const ops: Op[] = []; + const claimed = new Map(); + for (const s of specs) { + const n = snap.nodes[s.node]; + let range = s.range; + if (n && !range && s.quote) { + const at = n.body.indexOf(s.quote); + if (at >= 0) range = [at, at + s.quote.length]; + } + if (!n || !range || range[1] <= range[0] || range[1] > n.body.length) { + out.missing++; + continue; + } + const key = `${s.node}:${range[0]}:${range[1]}`; + const earlier = claimed.get(key); + const onSpan = notesOf(snap, s.node).filter((c) => snap.nodes[c].anchors.some((a) => a.start === range![0] && a.end === range![1])); + const current = earlier ?? onSpan.map((c) => snap.nodes[c].ref).find(Boolean); + if (current) { + if (sameTarget(current, s.target)) out.same++; + else out.occupied++; + continue; + } + claimed.set(key, s.target); + const plain = onSpan.find((c) => !snap.nodes[c].ref); + if (plain) { + ops.push({ op: "update", id: plain, ref: s.target }); + out.merged.push(plain); + } else ops.push({ op: "create", parent: s.node, kind: "note", anchors: [range], ref: s.target }); + } + if (!ops.length) return out; + const first = specs.find((s) => s.target)?.target; + const message = meta.message ?? (ops.length === 1 && first ? `Link to ${clip(first.kind === "wiki" ? first.title : first.kind === "url" ? first.url : (first.path ?? []).join(" › ") || "a node", 50)}` : `Add ${ops.length} links`); + out.created = doc.as(meta.author ?? doc.author, () => doc.apply(ops, message, { actor: meta.actor ?? "human", tag: meta.tag ?? "link" }).created); + return out; +} + diff --git a/src/core/marks.ts b/src/core/marks.ts new file mode 100644 index 0000000..7ee96a6 --- /dev/null +++ b/src/core/marks.ts @@ -0,0 +1,51 @@ +/** + * Link marks: `[[phrase]]` asks for the phrase to be linked to whatever it names (a library node + * or a Wikipedia article, verified before a link is made); `[[phrase|handle]]` names a library node + * by its handle (its id, as given to a model in the "nearby" list). A writer, human or model, types + * them; they are never stored. On save the brackets are taken out and each mark becomes a forced + * candidate for the scanner (server/links). While a model streams, the reader sees the text + * without them. + */ + +export interface Mark { + /** Offsets of the phrase in the text with the marks taken out. */ + start: number; + end: number; + phrase: string; + handle?: string; +} + +const MARK = /\[\[([^\[\]|\n]{1,200}?)(?:\|([^\[\]|\n]{1,100}))?\]\]/g; + +/** The text without its marks, and where each marked phrase now sits. */ +export function stripMarks(raw: string): { text: string; marks: Mark[] } { + const marks: Mark[] = []; + let text = ""; + let last = 0; + MARK.lastIndex = 0; + for (let m; (m = MARK.exec(raw)); ) { + text += raw.slice(last, m.index); + const phrase = m[1].trim(); + const lead = m[1].length - m[1].trimStart().length; + const start = text.length + lead; + text += m[1]; + if (phrase) marks.push({ start, end: start + phrase.length, phrase, ...(m[2]?.trim() ? { handle: m[2].trim() } : {}) }); + last = m.index + m[0].length; + } + text += raw.slice(last); + return { text, marks }; +} + +/** + * What a reader sees of text still arriving: complete marks taken out, and an unfinished one at + * the end shown as its phrase so far (its brackets and handle hidden), so nothing flickers. + */ +export function streamView(raw: string): string { + const { text } = stripMarks(raw); + const open = text.lastIndexOf("[["); + if (open < 0) return text.endsWith("[") ? text.slice(0, -1) : text; + const tail = text.slice(open + 2); + if (tail.includes("]]") || tail.includes("\n")) return text; + const bar = tail.indexOf("|"); + return text.slice(0, open) + (bar < 0 ? tail.replace(/\]$/, "") : tail.slice(0, bar)); +} diff --git a/src/core/model.ts b/src/core/model.ts new file mode 100644 index 0000000..157b573 --- /dev/null +++ b/src/core/model.ts @@ -0,0 +1,1083 @@ +/** + * The document model: a tree of nodes in a Loro CRDT, one op API for every writer, and + * staleness that is computed from content hashes rather than stored. + * + * A node is a title and a body. Its kind says how it hangs off its parent: + * section — a structural child, listed in the parent's outline + * note — an expansion anchored to one or more spans of the parent's body + * Anchors are pairs of CRDT cursors, so they keep pointing at the same words while the + * text around them is edited. + * + * The whole library is one such tree. Its root is the library itself (flagged `library` in its + * data); the root's sections are the documents, each with a slug for its address. Everything + * else (notes, anchors, ops, staleness, history, merge) is the same wherever a node sits, except + * that the root and the documents are not reconciled with each other: a document is not a + * summary of the library, nor the library of its documents. + */ +import { Cursor, LoroDoc, LoroText, type LoroEventBatch, type LoroMap, type LoroTreeNode, type TreeID } from "loro-crdt"; +import { RefError, canonRef, validateRef, type Ref } from "./ref"; +import { digest, sha256, slugify, words, type Form, type Range } from "./text"; + +export type { Ref } from "./ref"; + +export type NodeId = TreeID; +export type Kind = "section" | "note"; +export type Actor = "human" | "llm"; + +export interface Anchor { + start: number; + end: number; + /** The anchored text when the anchor was made. */ + quote: string; + /** The anchored text now. */ + text: string; +} + +export interface NodeSnap { + id: NodeId; + parent: NodeId | null; + kind: Kind; + title: string; + body: string; + by: Actor; + /** Pinned nodes are flagged when stale but never rewritten by a model. Human edits pin. */ + pinned: boolean; + form?: Form; + lens?: string; + /** A document's address (only meaningful on the library root's sections). */ + slug?: string; + /** What the node is about, elsewhere (see ref.ts). A note with a target and no body is a link. */ + ref?: Ref; + /** + * Phrases in this node's text that a writer declined to link (normalised, see links/extract). + * Kept in the library, so a rejection syncs between replicas and survives edits elsewhere in + * the node; each phrase is a key of its own in the node's map ("nolink:"), so two + * replicas declining at once both keep theirs. + */ + nolink?: string[]; + anchors: Anchor[]; + seenUp: string; + seenDown: string; + children: NodeId[]; + depth: number; +} + +/** + * A snapshot is immutable. Successive snapshots of one Doc share the NodeSnap objects of nodes + * that did not change, and a changed node's ancestors are copied, so anything computed from a + * NodeSnap and its subtree can be remembered against that object. + */ +export interface Snap { + root: NodeId; + nodes: Record; + /** The root is a library, and its sections are documents. */ + library: boolean; +} + +export type Op = + | { + op: "create"; + parent: NodeId; + index?: number; + kind?: Kind; + title?: string; + body?: string; + /** Spans of the parent's body, as offsets. */ + anchors?: Range[]; + /** Alternative to anchors: anchor to the first occurrence of this text in the parent's body. */ + quote?: string; + form?: Form; + lens?: string; + /** For a new document (a section of the library root): its address. Made from the title if left out. */ + slug?: string; + /** What the node is about, elsewhere. A note with a target and no body is a link. */ + ref?: Ref; + } + /** `ref: null` removes the target. Changing a target is not a change of content: it leaves authorship and staleness alone. */ + /** `nolink` adds phrases the writer declined to link; like a target, it is not a change of content. */ + | { op: "update"; id: NodeId; title?: string; body?: string; pinned?: boolean; form?: Form; lens?: string; anchors?: Range[]; slug?: string; ref?: Ref | null; nolink?: string[] } + /** Swap in new content and drop everything beneath the node. */ + | { op: "replace"; id: NodeId; title: string; body: string } + | { op: "delete"; id: NodeId } + | { op: "move"; id: NodeId; parent: NodeId; index?: number } + /** Copy a node and everything beneath it, as it stands, to a new place; optionally under a new title. */ + | { op: "copy"; id: NodeId; parent: NodeId; index?: number; title?: string } + /** Declare the node consistent with its children (up), its parent (down), or both. */ + | { op: "bless"; id: NodeId; dir?: "up" | "down" | "both" }; + +export interface CommitMeta { + /** Identifies the commit. One commit can be stored as several Loro changes; they share this. */ + n: string; + /** Message. */ + m: string; + /** Author name. */ + by: string; + /** human | llm */ + a: Actor; + /** SHA-256 of the canonical tree state after this commit. Carried by the commit's last change. */ + h?: string; + /** Optional tag: merge, revert, regen, resolve… */ + t?: string; +} + +export class OpError extends Error {} + +export type PatchListener = (was: Map | null, nodes: Record) => void; + +/** A document's slug: also a path segment, so nothing that could leave its directory. */ +export const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/; +/** Slugs that are words in the URL scheme rather than documents. */ +const RESERVED = new Set(["import"]); +export const LIBRARY_TITLE = "Library"; + +/** + * Commits the system makes on its own account (reconciling after an edit, recording or settling a + * conflict, marking a merge) are labelled so that a person's undo steps over them: `u` after a + * delete should bring the node back, not undo the bookkeeping that followed the delete. + */ +export const SYSTEM_ORIGIN = "sys"; +const originOf = (m: CommitMeta) => + m.t === "merge" || m.t === "conflict" || (m.a === "llm" && (m.t === "regen" || m.t === "resolve")) ? SYSTEM_ORIGIN : "user"; + +const b64 = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)); +const unb64 = (s: string) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0)); + +let peerSource: (() => bigint) | null = null; +/** Replace the source of peer ids. Fixtures use this to get the same node ids on every run. */ +export function setPeerSource(fn: (() => bigint) | null) { + peerSource = fn; +} + +export function randomPeer(): bigint { + if (peerSource) return peerSource(); + const a = new Uint32Array(2); + crypto.getRandomValues(a); + return (BigInt(a[0] & 0x1fffff) << 32n) | BigInt(a[1]); +} + +interface StoredAnchor { + s: string; + e: string; + q: string; +} + +/** Write the fields every root has. */ +export function initRoot(n: LoroTreeNode, title: string, body: string, actor: Actor) { + n.data.set("kind", "section"); + n.data.set("title", title); + (n.data.setContainer("body", new LoroText()) as LoroText).insert(0, body); + n.data.set("by", actor); + n.data.set("pinned", actor === "human"); + n.data.set("up", ""); + n.data.set("down", ""); +} + +export class Doc { + readonly loro: LoroDoc; + author: string; + private cache: Snap | null = null; + /** Nodes written since `cache` was read. Only they (and what hangs off them) are read again. */ + private dirty = new Set(); + /** Something changed that a partial read cannot follow (a new root, a checkout): read it all. */ + private stale = true; + /** + * Nodes by the text their anchors' cursors live in. That is the parent's body, except for a + * note that has been moved to another parent: its cursors still point into the old one's text, + * and an edit there moves them. + */ + private anchoredIn = new Map>(); + private conflictCache: Conflict[] | null = null; + /** The commit being assembled, if any. */ + private txn: CommitMeta | null = null; + /** Called around each commit, so an undo manager can treat its parts as one step. */ + group: { start(): void; end(): void } | null = null; + private listeners = new Set<() => void>(); + private patchListeners = new Set(); + + constructor(loro: LoroDoc, author = "anon") { + this.loro = loro; + this.author = author; + loro.setRecordTimestamp(true); + loro.setChangeMergeInterval(-1); + loro.subscribe((e) => { + this.noteEvents(e); + this.touch(); + }); + } + + /** A single tree, not a library: what documents were before there was one (and what tests build). */ + static create(author: string, title: string, body: string, actor: Actor = "human"): Doc { + const loro = new LoroDoc(); + loro.setPeerId(randomPeer()); + const doc = new Doc(loro, author); + doc.begin("Create document", actor); + initRoot(loro.getTree("tree").createNode(), title, body, actor); + doc.commit("Create document", actor); + return doc; + } + + /** An empty library. Its id is kept in the database, so a replica of another library is never mistaken for it. */ + static library(author: string, id = randomPeer().toString(36)): Doc { + const loro = new LoroDoc(); + loro.setPeerId(randomPeer()); + const doc = new Doc(loro, author); + doc.begin("Create the library", "human"); + const root = loro.getTree("tree").createNode(); + initRoot(root, LIBRARY_TITLE, "", "human"); + root.data.set("library", true); + loro.getMap("meta").set("library", id); + doc.commit("Create the library", "human"); + return doc; + } + + static load(bytes: Uint8Array, author: string): Doc { + const loro = new LoroDoc(); + loro.setPeerId(randomPeer()); + loro.import(bytes); + return new Doc(loro, author); + } + + /** An independent replica with its own peer id (a branch, or an agent's workspace). */ + fork(author = this.author): Doc { + const loro = this.loro.fork(); + loro.setPeerId(randomPeer()); + return new Doc(loro, author); + } + + /** Run some writes under another author's name. */ + as(author: string, fn: () => T): T { + const was = this.author; + this.author = author; + try { + return fn(); + } finally { + this.author = was; + } + } + + /** The library's id, if this is a library. */ + get libraryId(): string | undefined { + return this.loro.getMap("meta").get("library") as string | undefined; + } + + snapshotBytes(): Uint8Array { + return this.loro.export({ mode: "snapshot" }); + } + + onChange(fn: () => void): () => void { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + /** + * Follow the snapshot as it is patched: called with the entries a patch replaced (as they were; + * undefined for a new node) and the new record, or with null when the snapshot was read whole. + * What is derived from many nodes (the backlinks index) is kept current this way at the cost of + * what changed. + */ + onPatch(fn: PatchListener): () => void { + this.patchListeners.add(fn); + return () => this.patchListeners.delete(fn); + } + + /** Tell listeners the document changed. What changed is already known from Loro's events. */ + touch() { + this.conflictCache = null; + for (const fn of this.listeners) fn(); + } + + /** A node was written directly (not through apply): read it again before the next snapshot. */ + mark(id: NodeId) { + this.dirty.add(id); + } + + /** Forget the snapshot entirely, after a write too broad to follow node by node. */ + reread() { + this.stale = true; + } + + private noteEvents(e: LoroEventBatch) { + if (e.by === "checkout") this.stale = true; + for (const ev of e.events) { + if (ev.path[0] !== "tree") continue; + if (ev.diff.type === "tree") { + for (const it of ev.diff.diff) { + this.dirty.add(it.target); + const to = it.action === "delete" ? undefined : it.parent; + const from = it.action === "create" ? undefined : it.oldParent; + if (to) this.dirty.add(to); + if (from) this.dirty.add(from); + // A node becoming a root, or ceasing to be one, changes what the snapshot is rooted at. + if ((it.action !== "delete" && !to) || (it.action !== "create" && !from)) this.stale = true; + } + } else if (typeof ev.path[1] === "string") { + this.dirty.add(ev.path[1] as NodeId); + if (ev.diff.type === "text") this.markAnchoredIn(ev.target); + } + } + } + + /** A text was written directly: read again the nodes anchored in it. */ + markAnchoredIn(text: string) { + for (const id of this.anchoredIn.get(text) ?? []) this.dirty.add(id); + } + + // ---- reading ---- + + get tree() { + return this.loro.getTree("tree"); + } + + snap(): Snap { + if (this.cache && !this.stale && !this.dirty.size) return this.cache; + // Resolving a cursor whose character has been deleted makes Loro commit whatever is pending. + // Naming the commit first means that early part is still recognisably part of it. + this.arm(); + let snap = this.cache && !this.stale ? this.patch(this.cache) : null; + if (!snap) { + this.stale = false; + this.dirty.clear(); + snap = this.read(); + } + this.arm(); + return (this.cache = snap); + } + + private arm() { + if (this.txn) this.loro.setNextCommitOptions({ message: JSON.stringify(this.txn), origin: originOf(this.txn) }); + } + + /** One node's own fields. Its children are filled in by the caller. */ + private readNode(n: LoroTreeNode, parent: NodeId | null, parentBody: string, depth: number): NodeSnap { + const d = (n.data as LoroMap).toJSON() as Record; + const snap: NodeSnap = { + id: n.id, + parent, + kind: (d.kind as Kind) ?? "section", + title: (d.title as string) ?? "", + body: (d.body as string) ?? "", + by: (d.by as Actor) ?? "llm", + pinned: !!d.pinned, + anchors: parent ? this.resolveAnchors(d.anchors as StoredAnchor[] | undefined, parentBody, n.id) : [], + seenUp: (d.up as string) ?? "", + seenDown: (d.down as string) ?? "", + children: [], + depth, + }; + if (d.form) snap.form = d.form as Form; + if (d.lens) snap.lens = d.lens as string; + if (d.slug) snap.slug = d.slug as string; + if (d.ref && typeof d.ref === "object") snap.ref = d.ref as Ref; + const declined = Object.keys(d).filter((k) => k.startsWith(NOLINK)).map((k) => k.slice(NOLINK.length)).sort(); + if (declined.length) snap.nolink = declined; + return snap; + } + + /** Read a subtree whole, handing each node to `put`. */ + private readTree(n: LoroTreeNode, parent: NodeSnap | null, depth: number, put: (n: NodeSnap) => void) { + const snap = this.readNode(n, parent?.id ?? null, parent?.body ?? "", depth); + put(snap); + for (const c of n.children() ?? []) { + snap.children.push(c.id); + this.readTree(c, snap, depth + 1, put); + } + } + + private read(): Snap { + const roots = this.tree.roots(); + if (!roots.length) throw new Error("document has no root"); + const nodes: Record = {}; + this.readTree(roots[0], null, 0, (n) => (nodes[n.id] = n)); + this.older = null; + for (const fn of this.patchListeners) fn(null, nodes); + return { root: roots[0].id, nodes, library: !!roots[0].data.get("library") }; + } + + /** + * The previous snapshot's view, whose prototype is the record the newest snapshot owns. + * See `patch`. + */ + private older: Record | null = null; + + /** + * The previous snapshot with the dirty nodes read again. A node is read with its children's + * ids; children that are new are read whole, children that moved in are read again, and + * children anchored to its body have their anchors resolved again. Every node + * whose entry was replaced has its ancestors copied, so a NodeSnap never changes. + * + * Copying a record of every node on each change would cost the size of the library, so the + * newest snapshot owns the record and the patch writes into it. The snapshot it replaces is + * handed a small view instead: the entries that changed, as they were, over the record (and + * the view before that is re-pointed at this one, so each older snapshot still reads what it + * read). An old snapshot answers lookups exactly; enumerating one (Object.keys and the like) + * sees only its own changed entries, so anything that enumerates a snapshot it took before a + * write must copy it first, as `mergeUpdate` does. + */ + private patch(prev: Snap): Snap | null { + const dirty = this.dirty; + this.dirty = new Set(); + const roots = this.tree.roots(); + if (roots.length !== 1 || roots[0].id !== prev.root) return null; + const nodes = prev.nodes; + const was = new Map(); + const replaced = new Set(); + const put = (n: NodeSnap) => { + if (!was.has(n.id)) was.set(n.id, nodes[n.id]); + nodes[n.id] = n; + replaced.add(n.id); + }; + const gone = (id: NodeId) => !this.tree.getNodeByID(id) || this.tree.isNodeDeleted(id); + // A deleted node's children went with it, unless they had moved away first (then they are read where they are now). + const drop = (id: NodeId) => { + const n = nodes[id]; + if (!n) return; + if (!was.has(id)) was.set(id, n); + delete nodes[id]; + replaced.delete(id); + for (const c of n.children) if (gone(c)) drop(c); + }; + const depthOf = (n: LoroTreeNode) => { + let d = 0; + for (let p = n.parent(); p; p = p.parent()) d++; + return d; + }; + const done = new Set(); + const later: NodeId[] = []; + + const reread = (n: LoroTreeNode, depth: number) => { + if (done.has(n.id)) return; + done.add(n.id); + const p = n.parent(); + const before = nodes[n.id]; + const parentBody = p ? (nodes[p.id] && done.has(p.id) ? nodes[p.id].body : ((p.data.get("body") as LoroText | undefined)?.toString() ?? "")) : ""; + const snap = this.readNode(n, p?.id ?? null, parentBody, depth); + const kids = n.children() ?? []; + snap.children = kids.map((c) => c.id); + // Nodes are often marked more than once for one write (by the op, then by Loro's event); + // an entry that reads back the same is kept, so nothing computed from it is thrown away. + if (!before || !sameNode(before, snap)) put(snap); + for (const c of kids) { + const cur = nodes[c.id]; + if (!cur) this.readTree(c, snap, depth + 1, put); + else if (cur.parent !== snap.id || cur.depth !== depth + 1) reread(c, depth + 1); + // Anchors are resolved against the text's history, not its string: a merge can move them + // while the body reads the same, so they are resolved again whenever the parent is read. + else if (!done.has(c.id)) { + const anchors = this.resolveAnchors(c.data.get("anchors") as StoredAnchor[] | undefined, snap.body, c.id); + if (JSON.stringify(anchors) !== JSON.stringify(cur.anchors)) put({ ...cur, anchors }); + } + } + // A child that left was deleted (drop it) or moved (make sure its new place is read). + for (const c of before?.children ?? []) { + if (snap.children.includes(c)) continue; + if (gone(c)) drop(c); + else later.push(c, this.tree.getNodeByID(c)!.parent()?.id ?? c); + } + }; + + const live: [LoroTreeNode, number][] = []; + for (const id of dirty) { + if (gone(id)) drop(id); + else { + const n = this.tree.getNodeByID(id)!; + live.push([n, depthOf(n)]); + } + } + live.sort((a, b) => a[1] - b[1]); + for (const [n, depth] of live) reread(n, depth); + for (const id of later) { + if (done.has(id) || gone(id)) continue; + const n = this.tree.getNodeByID(id)!; + reread(n, depthOf(n)); + } + + const copied = new Set(); + for (const id of [...replaced]) { + for (let p = nodes[id]?.parent; p && !copied.has(p); p = nodes[p]?.parent ?? null) { + if (!replaced.has(p)) put({ ...nodes[p] }); + copied.add(p); + } + } + if (!was.size) return prev; + for (const fn of this.patchListeners) fn(was, nodes); + // The snapshot being replaced keeps what it saw: a view of the changed entries over the record. + const view = Object.create(nodes) as Record; + for (const [id, n] of was) view[id] = n!; + if (this.older) Object.setPrototypeOf(this.older, view); + this.older = view; + prev.nodes = view; + return { root: prev.root, nodes, library: prev.library }; + } + + private resolveAnchors(stored: StoredAnchor[] | undefined, parentBody: string, id: NodeId): Anchor[] { + if (!stored?.length) return []; + const out: Anchor[] = []; + for (const a of stored) { + const sc = Cursor.decode(unb64(a.s)); + const text = sc.containerId(); + let ids = this.anchoredIn.get(text); + if (!ids) this.anchoredIn.set(text, (ids = new Set())); + ids.add(id); + const s = this.loro.getCursorPos(sc); + const e = this.loro.getCursorPos(Cursor.decode(unb64(a.e))); + if (!s || !e) continue; + const start = Math.min(s.offset, parentBody.length); + // The end cursor sits on the last anchored character. If that character has been deleted + // the cursor reports where it used to be, which is already the exclusive end. + const end = Math.min(e.update ? e.offset : e.offset + 1, parentBody.length); + out.push({ start, end: Math.max(start, end), quote: a.q, text: parentBody.slice(start, Math.max(start, end)) }); + } + return out.sort((x, y) => x.start - y.start); + } + + /** + * Canonical serialisation: the same tree always produces the same string. A single tree is + * written out row by row, as it always was, so commits made before the library still verify. + * A library is hashed node by node (a Merkle tree), so a commit costs the path to what changed + * rather than the whole library. + */ + canonical(snap = this.snap()): string { + if (snap.library) return JSON.stringify(["library", subtreeHash(snap, snap.root)]); + const rows: unknown[] = []; + const visit = (id: NodeId) => { + rows.push(row(snap.nodes[id])); + snap.nodes[id].children.forEach(visit); + }; + visit(snap.root); + return JSON.stringify(rows); + } + + stateHash(): string { + return sha256(this.canonical()); + } + + /** A subtree's content with node identity factored out (ids replaced by position). */ + shape(snap = this.snap(), from = snap.root): string { + const visit = (id: NodeId): unknown => { + const n = snap.nodes[id]; + const row: unknown[] = [n.kind, n.title, n.body, n.by, n.pinned, n.form ?? null, n.lens ?? null, n.anchors.map((a) => [a.start, a.end]), n.children.map(visit)]; + // A node target is compared by where its target sits, since ids differ between copies. + if (n.ref) row.push(n.ref.kind === "node" ? ["node", n.ref.id && snap.nodes[n.ref.id] ? position(snap, n.ref.id) : [n.ref.doc ?? null, n.ref.path ?? null], n.ref.quote ?? null] : canonRef(n.ref)); + return row; + }; + return JSON.stringify(visit(from)); + } + + // ---- writing ---- + + /** Name the commit that the following writes belong to. */ + begin(message: string, actor: Actor = "human", tag?: string) { + this.txn = { n: Math.random().toString(36).slice(2, 10), m: message, by: this.author, a: actor }; + if (tag) this.txn.t = tag; + this.group?.start(); + this.arm(); + } + + commit(message: string, actor: Actor = "human", tag?: string) { + if (!this.txn) this.begin(message, actor, tag); + const meta = this.txn!; + this.arm(); + const h = this.stateHash(); + // A write of its own, so the closing change is never empty and always carries the hash. + this.loro.getMap("meta").set("n", meta.n); + this.txn = null; + this.loro.commit({ message: JSON.stringify({ ...meta, h }), origin: originOf(meta) }); + this.group?.end(); + this.touch(); + } + + private node(id: NodeId): LoroTreeNode { + const n = this.tree.getNodeByID(id); + if (!n || this.tree.isNodeDeleted(id)) throw new OpError(`no such node: ${id}`); + return n; + } + + private bodyOf(n: LoroTreeNode): LoroText { + return (n.data.get("body") as LoroText | undefined) ?? (n.data.setContainer("body", new LoroText()) as LoroText); + } + + /** Encode spans of a node's body as stored cursor pairs. */ + makeAnchors(parent: LoroTreeNode, ranges: Range[], quotes?: string[]): StoredAnchor[] { + const text = this.bodyOf(parent); + const body = text.toString(); + const out: StoredAnchor[] = []; + ranges.forEach(([start, end], i) => { + start = Math.max(0, Math.min(start, body.length)); + end = Math.max(start, Math.min(end, body.length)); + if (end <= start) throw new OpError("anchor is empty"); + const s = text.getCursor(start, 0); + const e = text.getCursor(end - 1, 0); + if (!s || !e) throw new OpError("could not anchor"); + out.push({ s: b64(s.encode()), e: b64(e.encode()), q: quotes?.[i] ?? body.slice(start, end) }); + }); + return out; + } + + /** + * The slug a node may take as a document: the one asked for if free, else one made from the + * hint. None if the node is not a section of the library root. Read from Loro, not a snapshot, + * because it runs for every op. + */ + private slugFor(n: LoroTreeNode, asked: string | undefined, hint: string): string | undefined { + const lib = n.parent(); + if (!lib || lib.parent() || !lib.data.get("library")) { + if (asked !== undefined) throw new OpError("only a document (a section of the library) has a slug"); + return undefined; + } + const taken = new Set((lib.children() ?? []).filter((c) => c.id !== n.id).map((c) => c.data.get("slug") as string | undefined)); + if (asked !== undefined) { + if (!SLUG.test(asked) || RESERVED.has(asked)) throw new OpError(`not a valid slug: ${asked}`); + if (taken.has(asked)) throw new OpError(`another document has the slug ${asked}`); + return asked; + } + return freeSlug(hint, taken); + } + + /** + * Write a copy of a subtree (from this document or another) under `parent`, as it stands: + * content, authorship, pins and the hashes it was last reconciled with. Must run inside a commit. + */ + graft(src: Snap, from: NodeId, parent: NodeId, opts: { index?: number; slug?: string; title?: string } = {}): NodeId { + const { index, slug, title } = opts; + const into = this.node(parent); + const visit = (id: NodeId, under: LoroTreeNode, at?: number): NodeId => { + const s = src.nodes[id]; + const n = at === undefined ? under.createNode() : under.createNode(at); + n.data.set("kind", s.kind); + n.data.set("title", id === from && title !== undefined ? title : s.title); + (n.data.setContainer("body", new LoroText()) as LoroText).insert(0, s.body); + n.data.set("by", s.by); + n.data.set("pinned", s.pinned); + if (s.form) n.data.set("form", s.form); + if (s.lens) n.data.set("lens", s.lens); + if (s.ref) n.data.set("ref", s.ref as never); + if (s.nolink?.length) setNolink(n, s.nolink); + n.data.set("up", s.seenUp); + n.data.set("down", s.seenDown); + // The copy's anchors are offsets into its parent's body, which is a copy too; except at the + // top, where they would be offsets into a different text unless it lands beside the original. + const kept = id !== from || parent === s.parent ? s.anchors.filter((a) => a.end > a.start) : []; + if (kept.length) n.data.set("anchors", this.makeAnchors(under, kept.map((a) => [a.start, a.end]), kept.map((a) => a.quote)) as never); + this.mark(n.id); + for (const c of s.children) visit(c, n); + return n.id; + }; + const count = into.children()?.length ?? 0; + const top = visit(from, into, Math.max(0, Math.min(index ?? count, count))); + this.mark(parent); + const n = this.node(top); + const free = this.slugFor(n, slug, (title ?? src.nodes[from].title) || "untitled"); + if (free) n.data.set("slug", free); + return top; + } + + /** + * Apply a batch of ops as one commit. This is the only write path: the keyboard, the editor + * agent and the HTTP endpoint all come through here. + */ + apply(ops: Op[], message: string, opts: { actor?: Actor; tag?: string } = {}): { created: NodeId[] } { + const actor = opts.actor ?? "human"; + this.begin(message, actor, opts.tag); + const created: NodeId[] = []; + const authored = new Set(); + const blessings: { id: NodeId; dir: "up" | "down" | "both" }[] = []; + let failure: unknown; + // "$n" names the nth node created earlier in the same batch. + const r = (x: NodeId) => (x.startsWith("$") ? (created[+x.slice(1)] ?? x) : x); + try { + for (const raw of ops) { + const op = { ...raw } as Op; + if ("id" in op) op.id = r(op.id); + if ("parent" in op) op.parent = r(op.parent); + switch (op.op) { + case "create": { + const parent = this.node(op.parent); + const kind: Kind = op.kind ?? (op.anchors || op.quote ? "note" : "section"); + let ranges = op.anchors; + if (!ranges && op.quote) { + const at = this.bodyOf(parent).toString().indexOf(op.quote); + if (at < 0) throw new OpError(`quote not found in parent body: "${op.quote}"`); + ranges = [[at, at + op.quote.length]]; + } + if (kind === "note" && !ranges?.length) throw new OpError("a note needs an anchor or a quote"); + const count = parent.children()?.length ?? 0; + const n = parent.createNode(Math.max(0, Math.min(op.index ?? count, count))); + this.mark(parent.id); + this.mark(n.id); + n.data.set("kind", kind); + n.data.set("title", op.title ?? ""); + (n.data.setContainer("body", new LoroText()) as LoroText).insert(0, op.body ?? ""); + n.data.set("by", actor); + n.data.set("pinned", actor === "human"); + if (op.form) n.data.set("form", op.form); + if (op.lens) n.data.set("lens", op.lens); + if (op.ref) n.data.set("ref", checkRef(op.ref) as never); + if (ranges?.length) n.data.set("anchors", this.makeAnchors(parent, ranges) as never); + const slug = kind === "section" ? this.slugFor(n, op.slug, op.title || "untitled") : undefined; + if (op.slug && kind !== "section") throw new OpError("only a document (a section of the library) has a slug"); + if (slug) n.data.set("slug", slug); + created.push(n.id); + authored.add(n.id); + break; + } + case "update": { + const n = this.node(op.id); + this.mark(n.id); + if (op.title !== undefined && op.title !== n.data.get("title")) n.data.set("title", op.title); + if (op.body !== undefined) { + this.bodyOf(n).update(op.body); + this.markAnchoredIn(this.bodyOf(n).id); + } + if (op.form) n.data.set("form", op.form); + if (op.lens) n.data.set("lens", op.lens); + if (op.ref === null) n.data.get("ref") !== undefined && n.data.delete("ref"); + else if (op.ref) n.data.set("ref", checkRef(op.ref) as never); + if (op.nolink?.length) { + if (!op.nolink.every((p) => typeof p === "string" && p.length > 0 && p.length <= 200)) throw new OpError("nolink takes phrases of 1 to 200 characters"); + setNolink(n, op.nolink); + } + if (op.anchors) { + const parent = n.parent(); + if (!parent) throw new OpError("the root has nothing to anchor to"); + n.data.set("anchors", this.makeAnchors(parent, op.anchors) as never); + } + if (op.slug !== undefined && op.slug !== n.data.get("slug")) n.data.set("slug", this.slugFor(n, op.slug, "")!); + if (op.title !== undefined || op.body !== undefined) { + n.data.set("by", actor); + n.data.set("pinned", actor === "human"); + authored.add(n.id); + } + if (op.pinned !== undefined) n.data.set("pinned", op.pinned); + break; + } + case "replace": { + const n = this.node(op.id); + this.mark(n.id); + n.data.set("title", op.title); + this.bodyOf(n).update(op.body); + this.markAnchoredIn(this.bodyOf(n).id); + n.data.set("by", actor); + n.data.set("pinned", actor === "human"); + for (const c of n.children() ?? []) this.tree.delete(c.id); + authored.add(n.id); + break; + } + case "delete": { + const n = this.node(op.id); + if (!n.parent()) throw new OpError("the root cannot be deleted"); + this.mark(n.parent()!.id); + this.mark(n.id); + this.tree.delete(op.id); + break; + } + case "move": { + const n = this.node(op.id); + const parent = this.node(op.parent); + if (!n.parent()) throw new OpError("the root cannot be moved"); + for (let p: LoroTreeNode | undefined = parent; p; p = p.parent()) { + if (p.id === op.id) throw new OpError("a node cannot be moved inside itself"); + } + const sameParent = n.parent()!.id === parent.id; + const count = (parent.children()?.length ?? 0) - (sameParent ? 1 : 0); + this.mark(n.parent()!.id); + this.mark(parent.id); + this.mark(n.id); + this.tree.move(op.id, op.parent, Math.max(0, Math.min(op.index ?? count, count))); + // A section that becomes a document needs an address; one it had before is kept if still free. + if (!sameParent && n.data.get("kind") !== "note") { + const had = n.data.get("slug") as string | undefined; + let slug: string | undefined; + try { + slug = this.slugFor(n, had, (n.data.get("title") as string) || "untitled"); + } catch { + slug = this.slugFor(n, undefined, (n.data.get("title") as string) || "untitled"); + } + if (slug && slug !== had) n.data.set("slug", slug); + } + break; + } + case "copy": { + this.node(op.id); + const top = this.graft(this.snap(), op.id, op.parent, { index: op.index, title: op.title }); + created.push(top); + // A new name is not new content: as with a rename, the sections stay consistent with it. + if (op.title !== undefined) for (const c of sections(this.snap(), top)) blessings.push({ id: c, dir: "down" }); + break; + } + case "bless": + this.node(op.id); + blessings.push({ id: op.id, dir: op.dir ?? "both" }); + break; + } + } + } catch (err) { + failure = err; + } + // Writing a node is a statement that it is consistent with its surroundings as they now stand. + const snap = this.snap(); + for (const id of authored) if (snap.nodes[id]) blessings.push({ id, dir: "both" }); + for (const { id, dir } of blessings) { + const n = this.tree.getNodeByID(id); + if (!n || !snap.nodes[id]) continue; + this.mark(id); + if (dir !== "down") n.data.set("up", upInput(snap, id)); + if (dir !== "up") n.data.set("down", downInput(snap, id)); + } + this.commit(message, actor, opts.tag); + if (failure) throw failure; + return { created }; + } + + // ---- conflict records (kept in the document so they replicate and version like everything else) ---- + + get conflictMap() { + return this.loro.getMap("conflicts"); + } + + conflicts(): Conflict[] { + if (this.conflictCache) return this.conflictCache; + const out: Conflict[] = []; + for (const v of Object.values(this.conflictMap.toJSON() as Record)) { + try { + out.push(JSON.parse(v)); + } catch { + /* ignore a malformed record rather than break the reader */ + } + } + return (this.conflictCache = out.sort((a, b) => (a.id < b.id ? -1 : 1))); + } +} + +export interface Conflict { + id: string; + type: "edit-edit" | "edit-delete" | "contradiction"; + /** The node in question (for a contradiction, the first of the pair). */ + node: NodeId; + /** For a contradiction: the other node. */ + other?: NodeId; + /** For edit-edit: which field both sides changed. For "ref", the sides are targets in their text form. */ + field?: "title" | "body" | "ref"; + title: string; + base: string; + /** The two sides, in a replica-independent order. */ + a: string; + b: string; + /** What the CRDT produced on its own. */ + merged: string; + status: "open" | "resolved"; + resolved?: string; + rationale?: string; + resolvedBy?: string; + /** For edit-delete: where the deleted node lived. */ + parent?: NodeId; +} + +const refString = (r: Ref | undefined) => (r ? JSON.stringify(canonRef(r)) : ""); + +/** Declined phrases are keys of the node's own map: a key each, so concurrent additions all survive. */ +export const NOLINK = "nolink:"; +export function setNolink(n: LoroTreeNode, phrases: string[]) { + for (const p of phrases) if (n.data.get(NOLINK + p) === undefined) n.data.set(NOLINK + p, 1); +} +const sameNode = (a: NodeSnap, b: NodeSnap) => + refString(a.ref) === refString(b.ref) && (a.nolink ?? []).join("\u0000") === (b.nolink ?? []).join("\u0000") && a.parent === b.parent && a.kind === b.kind && a.title === b.title && a.body === b.body && a.by === b.by && a.pinned === b.pinned && + a.form === b.form && a.lens === b.lens && a.slug === b.slug && a.seenUp === b.seenUp && a.seenDown === b.seenDown && a.depth === b.depth && + a.children.length === b.children.length && a.children.every((c, i) => c === b.children[i]) && + a.anchors.length === b.anchors.length && a.anchors.every((x, i) => x.start === b.anchors[i].start && x.end === b.anchors[i].end && x.quote === b.anchors[i].quote && x.text === b.anchors[i].text); + +// ---- hashing ---- + +const row = (n: NodeSnap) => { + const r: unknown[] = [n.id, n.parent, n.kind, n.title, n.body, n.by, n.pinned, n.form ?? null, n.lens ?? null, n.anchors.map((a) => [a.start, a.end]), n.seenUp, n.seenDown]; + // Optional fields go last, and only when set, so commits made before they existed still verify. + if (n.slug || n.ref || n.nolink) r.push(n.slug ?? null); + if (n.ref || n.nolink) r.push(n.ref ? canonRef(n.ref) : null); + if (n.nolink) r.push(n.nolink); + return r; +}; + +const hashes = new WeakMap(); +/** A node's row and its children's hashes, hashed: remembered per NodeSnap, which never changes. */ +function subtreeHash(snap: Snap, id: NodeId): string { + const n = snap.nodes[id]; + let h = hashes.get(n); + if (!h) hashes.set(n, (h = sha256(JSON.stringify([row(n), n.children.map((c) => subtreeHash(snap, c))])))); + return h; +} + +// ---- the library ---- + +/** The library's documents: the root's sections. In a single tree, the root is the one document. */ +export function documents(snap: Snap): NodeId[] { + return snap.library ? sections(snap, snap.root) : [snap.root]; +} + +export const isLibraryRoot = (snap: Snap, id: NodeId) => snap.library && id === snap.root; + +/** The document a node belongs to: its ancestor among the library's sections. None for the library root itself. */ +export function docOf(snap: Snap, id: NodeId): NodeId | null { + let n = snap.nodes[id]; + if (!n) return null; + if (!snap.library) return snap.root; + if (!n.parent) return null; + while (n.parent !== snap.root) n = snap.nodes[n.parent!]; + return n.id; +} + +/** The document with this slug. If two replicas gave the same slug at once, the first in the library wins. */ +export function findDoc(snap: Snap, slug: string): NodeId | undefined { + return documents(snap).find((d) => snap.nodes[d].slug === slug); +} + +/** A free slug made from a hint, numbered if it is taken. */ +export function freeSlug(hint: string, taken: Set): string { + const base = slugify(hint); + const free = (s: string) => !RESERVED.has(s) && !taken.has(s); + if (free(base)) return base; + for (let n = 2; ; n++) { + const s = `${base.slice(0, 58)}-${n}`; + if (free(s)) return s; + } +} + +// ---- staleness: computed, never stored ---- + +export const sections = (snap: Snap, id: NodeId) => snap.nodes[id].children.filter((c) => snap.nodes[c].kind === "section"); + +/** + * Hash of what a node's body should be a summary of: its section children, in order. The + * library's body is not a summary of its documents, so it has nothing to be stale against. + */ +function upInput(snap: Snap, id: NodeId): string { + if (isLibraryRoot(snap, id)) return ""; + const kids = sections(snap, id); + if (!kids.length) return ""; + return digest(JSON.stringify(kids.map((c) => [snap.nodes[c].title, snap.nodes[c].body]))); +} + +/** + * Hash of what a node elaborates: its anchored text, or failing that its parent's title and body. + * A document does not elaborate the library, so, like a root, it elaborates nothing. + */ +function downInput(snap: Snap, id: NodeId): string { + const n = snap.nodes[id]; + if (!n.parent) return ""; + if (n.anchors.length) return digest(JSON.stringify(n.anchors.map((a) => a.text))); + if (n.kind === "section" && isLibraryRoot(snap, n.parent)) return ""; + const p = snap.nodes[n.parent]; + return digest(JSON.stringify([p.title, p.body])); +} + +export interface Staleness { + /** The children changed since this node was last reconciled with them. */ + up: boolean; + /** The parent text (or anchored quote) changed since this node was last reconciled with it. */ + down: boolean; + /** A note whose anchored text has been deleted. */ + orphan: boolean; +} + +/** + * Whether an anchor no longer points at what it was made for. Cursors survive on single + * characters, so after a heavy rewrite an anchor can still span *something*; if under half the + * quoted words are left in it, the text it was about is gone. + */ +export function anchorLost(a: Anchor): boolean { + if (a.end <= a.start) return true; + if (a.text === a.quote) return false; + const lower = (t: string) => words(t).map(([s, e]) => t.slice(s, e).toLowerCase()); + const quoted = lower(a.quote); + if (!quoted.length) return true; + const now = new Set(lower(a.text)); + return quoted.filter((w) => now.has(w)).length * 2 < quoted.length; +} + +/** + * A node's staleness depends on its own entry, its children's and its parent's. A NodeSnap is + * replaced whenever anything beneath it changes, so the answer can be remembered against the + * node's entry (and its parent's): it carries over from one snapshot to the next for every node + * an edit did not reach, which in a large library is nearly all of them. + */ +const memo = new WeakMap(); + +export function staleness(snap: Snap, id: NodeId): Staleness { + const n = snap.nodes[id]; + const parent = n.parent ? snap.nodes[n.parent] : undefined; + const seen = memo.get(n); + if (seen && seen.parent === parent) return seen.s; + const orphan = n.kind === "note" && (!n.anchors.length || n.anchors.every(anchorLost)); + // A link has no text of its own to fall out of date: it is never stale, so it never asks a model + // to rewrite it, and nothing else looks at it (a parent summarises its sections, not its notes). + const s = isLink(n) ? { up: false, down: false, orphan } : { up: n.seenUp !== upInput(snap, id), down: n.seenDown !== downInput(snap, id), orphan }; + memo.set(n, { parent, s }); + return s; +} + +export const isStale = (snap: Snap, id: NodeId) => { + const s = staleness(snap, id); + return s.up || s.down || s.orphan; +}; + +// ---- small tree helpers ---- + +/** A link: a note with a target and no text of its own. */ +export const isLink = (n: NodeSnap) => n.kind === "note" && !!n.ref && !n.body.trim(); + +/** A node's position as child indices from the root: what identifies it across copies of a tree. */ +function position(snap: Snap, id: NodeId): number[] { + const out: number[] = []; + for (let n = snap.nodes[id]; n?.parent; n = snap.nodes[n.parent]) out.unshift(snap.nodes[n.parent].children.indexOf(n.id)); + return out; +} + +/** An op's target, checked: a bad one is refused like any other bad op. */ +function checkRef(r: unknown): Ref { + try { + return validateRef(r); + } catch (err) { + if (err instanceof RefError) throw new OpError(err.message); + throw err; + } +} + +export const notesOf = (snap: Snap, id: NodeId) => snap.nodes[id].children.filter((c) => snap.nodes[c].kind === "note"); + +export function ancestors(snap: Snap, id: NodeId): NodeId[] { + const out: NodeId[] = []; + for (let p = snap.nodes[id]?.parent; p; p = snap.nodes[p].parent) out.push(p); + return out; +} + +/** Ancestors up to and including the node's document: never the library root. */ +export function ancestorsInDoc(snap: Snap, id: NodeId): NodeId[] { + const out = ancestors(snap, id); + return snap.library ? out.filter((a) => a !== snap.root) : out; +} + +export function descendants(snap: Snap, id: NodeId): NodeId[] { + const out: NodeId[] = []; + const visit = (x: NodeId) => snap.nodes[x].children.forEach((c) => (out.push(c), visit(c))); + visit(id); + return out; +} + +/** A note's display title: its own, or the text it is anchored to. */ +export function label(snap: Snap, id: NodeId): string { + const n = snap.nodes[id]; + if (n.title) return n.title; + if (n.anchors.length) return `“${n.anchors[0].text || n.anchors[0].quote}”`; + return "(untitled)"; +} + +/** + * Ops that rename a document (the library's section, or a single tree's root). A new name is not + * new content: the sections under it are declared still consistent with it, and it keeps the pin it had. + */ +export function retitleOps(snap: Snap, id: NodeId, title: string): Op[] { + const n = snap.nodes[id]; + return [ + { op: "update", id, title }, + { op: "update", id, pinned: n.pinned }, + ...sections(snap, id).map((c): Op => ({ op: "bless", id: c, dir: "down" })), + ]; +} diff --git a/src/core/ref.ts b/src/core/ref.ts new file mode 100644 index 0000000..133e033 --- /dev/null +++ b/src/core/ref.ts @@ -0,0 +1,290 @@ +/** + * A node's target: what it is about, elsewhere. A Wikipedia article, another node in the library, + * or a web page. A note with a target and no body is a link; with a body it is a commentary on + * something that also has an article. Targets are plain data in the node, so they replicate, + * version, merge and undo like a title does. + * + * Also the one text form of a target, shared by the .md format, the command bar and the editor + * agent's tools: + * + * w:Fixed-point combinator English Wikipedia (w.fr:Point fixe for another language) + * /fixed-points/Recursion/How Y works a node, by document slug and section titles + * ./How Y works the same, inside the document it is written in + * /fixed-points/The idea ^"one repels them" a note, by its section and its quote + * https://example.org/page "Title" a web page, with an optional title + * "w:Star Wars: Episode IV" any of them in quotes, when it contains ": " + * + * In a path, `\/`, `\^` and `\\` stand for a slash, a caret and a backslash inside a title. + */ +import type { NodeId } from "./model"; + +export type Ref = + | { kind: "wiki"; title: string; lang: string; pageId?: number } + /** + * A node in the library. `id` is what counts; `doc` (a document's slug) and `path` (section + * titles below the document, and a note's quote) let the link be found again when the id has + * gone: undoing a delete re-creates nodes under new ids. A path with no `doc` is relative to the + * document it is written in (only in a parsed file, before it is written into the library). + */ + | { kind: "node"; id?: NodeId; doc?: string; path?: string[]; quote?: string } + | { kind: "url"; url: string; title?: string }; + +const DEFAULT_LANG = "en"; +const LANG = /^[a-z][a-z0-9-]{1,15}$/; +const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/; +/** Characters MediaWiki never allows in a title. */ +const ILLEGAL = /[#<>[\]|{}\u0000-\u001f\u007f]/; + +export class RefError extends Error {} + +/** How MediaWiki would spell a main-namespace title: spaces for underscores, first letter capital. */ +export function wikiTitle(s: string): string { + const t = s.replace(/_/g, " ").replace(/\s+/g, " ").trim(); + if (!t) return t; + const first = String.fromCodePoint(t.codePointAt(0)!); + return first.toUpperCase() + t.slice(first.length); +} + +/** Check a target from outside (an op, a file, a model) and return a clean copy. Throws RefError. */ +export function validateRef(input: unknown): Ref { + if (!input || typeof input !== "object") throw new RefError("a target must be an object"); + const r = input as Record; + const str = (v: unknown, name: string, max: number) => { + if (typeof v !== "string") throw new RefError(`a target's ${name} must be a string`); + if (v.length > max) throw new RefError(`a target's ${name} is longer than ${max} characters`); + return v; + }; + switch (r.kind) { + case "wiki": { + const title = wikiTitle(str(r.title, "title", 255)); + if (!title || ILLEGAL.test(title)) throw new RefError(`not a Wikipedia title: “${r.title}”`); + const lang = r.lang === undefined ? DEFAULT_LANG : str(r.lang, "lang", 16); + if (!LANG.test(lang)) throw new RefError(`not a Wikipedia language: ${lang}`); + const out: Ref = { kind: "wiki", title, lang }; + if (r.pageId !== undefined) { + if (!Number.isInteger(r.pageId) || (r.pageId as number) <= 0) throw new RefError("a page id must be a positive integer"); + out.pageId = r.pageId as number; + } + return out; + } + case "node": { + const out: Ref = { kind: "node" }; + if (r.id !== undefined && r.id !== "") out.id = str(r.id, "id", 64) as NodeId; + if (r.doc !== undefined) { + const d = str(r.doc, "document", 64); + if (!SLUG.test(d)) throw new RefError(`not a document slug: ${d}`); + out.doc = d; + } + if (r.path !== undefined) { + if (!Array.isArray(r.path) || r.path.length > 64) throw new RefError("a target's path must be a list of titles"); + out.path = r.path.map((t) => str(t, "path", 500)); + } + if (r.quote !== undefined) out.quote = str(r.quote, "quote", 2000); + if (!out.id && !out.path && !out.doc) throw new RefError("a node target needs an id or a path"); + return out; + } + case "url": { + const url = str(r.url, "url", 2000).trim(); + let ok = false; + try { + ok = /^https?:$/.test(new URL(url).protocol) && /^https?:\/\//i.test(url); + } catch { + ok = false; + } + if (!ok) throw new RefError(`only http and https addresses can be linked: ${url}`); + const out: Ref = { kind: "url", url }; + if (r.title !== undefined && r.title !== "") out.title = str(r.title, "title", 300).replace(/\s+/g, " ").trim(); + return out; + } + default: + throw new RefError(`unknown kind of target: ${String(r.kind)}`); + } +} + +/** A canonical form, for hashing and comparing: the same target always gives the same value. */ +export function canonRef(r: Ref): unknown[] { + switch (r.kind) { + case "wiki": + return ["wiki", r.lang, r.title, r.pageId ?? null]; + case "node": + return ["node", r.id ?? null, r.doc ?? null, r.path ?? null, r.quote ?? null]; + case "url": + return ["url", r.url, r.title ?? null]; + } +} + +/** Whether two targets name the same thing (a node by its id when both have one; a fallback hint does not count). */ +export function sameTarget(a: Ref | undefined, b: Ref | undefined): boolean { + if (!a || !b || a.kind !== b.kind) return !a && !b; + if (a.kind === "wiki" && b.kind === "wiki") return a.lang === b.lang && a.title === b.title; + if (a.kind === "url" && b.kind === "url") return a.url === b.url; + if (a.kind === "node" && b.kind === "node") { + if (a.id || b.id) return a.id === b.id; + return a.doc === b.doc && JSON.stringify(a.path ?? []) === JSON.stringify(b.path ?? []) && (a.quote ?? "") === (b.quote ?? ""); + } + return false; +} + +/** The key a Wikipedia target is filed under. */ +export const wikiKey = (lang: string, title: string) => `${lang}:${wikiTitle(title)}`; + +// ---- the text form ---- + +const escapeSeg = (s: string) => s.replace(/[\\/^]/g, (c) => "\\" + c); + +/** A string in quotes, with `\\`, `\"` and `\n` escaped: how the text form writes quotes, titles and lenses. */ +export const quoteStr = (s: string) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`; + +/** Read a "quoted" string at s[i] === '"': the text and the index after the closing quote. */ +export function readQuoted(s: string, i: number): [string, number] | null { + let out = ""; + for (let j = i + 1; j < s.length; j++) { + const c = s[j]; + if (c === '"') return [out, j + 1]; + if (c === "\\" && j + 1 < s.length) { + const n = s[j + 1]; + if (n === '"' || n === "\\") (out += n), j++; + else if (n === "n") (out += "\n"), j++; + else out += c; + } else out += c; + } + return null; +} + +/** + * A target in the text form. A node target is written from its `doc` and `path`, so refresh them + * first (`nodeRef` in links.ts); `here` is the slug of the document it is written in, which makes + * a path inside that document relative. + */ +export function formatTarget(r: Ref, here?: string): string { + let s: string; + if (r.kind === "wiki") s = `${r.lang === DEFAULT_LANG ? "w" : `w.${r.lang}`}:${r.title}`; + else if (r.kind === "url") return r.url + (r.title ? " " + quoteStr(r.title) : ""); + else { + const segs = (r.path ?? []).map(escapeSeg).join("/"); + const head = !r.doc || r.doc === here ? "." : `/${r.doc}`; + s = `${head}${segs || head === "." ? "/" : ""}${segs}`; + if (r.quote !== undefined) s += ` ^${quoteStr(r.quote)}`; + } + // Unquoted, a target ends at ": " (where a note's text begins), so one that contains that is quoted. + return /:(\s|$)/.test(s) || s.startsWith('"') ? quoteStr(s) : s; +} + +const PREFIX = /^(w(?:\.[a-z][a-z0-9-]{1,15})?:|\.?\/|https?:\/\/)/i; + +/** Whether text at this point would be read as a target (used to tell `-> target` from prose). */ +export const looksLikeTarget = (s: string) => PREFIX.test(s) || (s.startsWith('"') && PREFIX.test(s.slice(1))); + +/** Where an unquoted wiki title or path ends: at ": ", or a ":" that ends the text. Inside quotes, at the end. */ +function stopAt(s: string, i: number, whole: boolean): number { + if (whole) return s.length; + for (let j = i; j < s.length; j++) if (s[j] === ":" && (j + 1 === s.length || /\s/.test(s[j + 1]))) return j; + return s.length; +} + +function parsePath(text: string): Ref | string { + let rest = text; + let quote: string | undefined; + const caret = /(?:^|[^\\])\s\^"/.exec(rest); + if (caret) { + const at = rest.indexOf('^"', caret.index); + const q = readQuoted(rest, at + 1); + if (!q || rest.slice(q[1]).trim()) return "the quote after ^ is not closed"; + quote = q[0]; + rest = rest.slice(0, at).trimEnd(); + } + const relative = rest.startsWith("./") || rest === "."; + const body = relative ? rest.slice(2) : rest.slice(1); + const segs: string[] = []; + let cur = ""; + for (let i = 0; i < body.length; i++) { + const c = body[i]; + if (c === "\\" && i + 1 < body.length) cur += body[++i]; + else if (c === "/") segs.push(cur), (cur = ""); + else cur += c; + } + if (cur || body.endsWith("/")) segs.push(cur); + if (relative) return { kind: "node", path: segs, ...(quote !== undefined ? { quote } : {}) }; + const [doc, ...path] = segs; + if (!doc || !SLUG.test(doc)) return `not a document slug: “${doc ?? ""}”`; + return { kind: "node", doc, path, ...(quote !== undefined ? { quote } : {}) }; +} + +/** Read the target that starts at s[i]. Returns it and where it ended, or why it is not one. */ +export function readTarget(s: string, i: number, whole = false): { ref: Ref; end: number } | string { + if (s[i] === '"' && !whole) { + const q = readQuoted(s, i); + if (!q) return "the target's quote is not closed"; + const inner = readTarget(q[0], 0, true); + if (typeof inner === "string") return inner; + if (inner.end !== q[0].length) return `unexpected text in the target: “${q[0].slice(inner.end)}”`; + return { ref: inner.ref, end: q[1] }; + } + const tail = s.slice(i); + const wiki = /^w(?:\.([a-z][a-z0-9-]{1,15}))?:/i.exec(tail); + try { + if (wiki) { + const end = stopAt(s, i + wiki[0].length, whole); + return { ref: validateRef({ kind: "wiki", lang: wiki[1]?.toLowerCase() ?? DEFAULT_LANG, title: s.slice(i + wiki[0].length, end) }), end }; + } + if (/^https?:\/\//i.test(tail)) { + let end = i + (/^\S+/.exec(tail)?.[0].length ?? 0); + if (s[end - 1] === ":" && (end === s.length || /\s/.test(s[end]))) end--; + const url = s.slice(i, end); + const t = /^\s+"/.exec(s.slice(end)); + if (t) { + const q = readQuoted(s, end + t[0].length - 1); + if (!q) return "the link's title is not closed"; + return { ref: validateRef({ kind: "url", url, title: q[0] }), end: q[1] }; + } + return { ref: validateRef({ kind: "url", url }), end }; + } + if (tail.startsWith("/") || tail.startsWith("./") || tail === ".") { + const end = stopAt(s, i, whole); + const ref = parsePath(s.slice(i, end).trimEnd()); + if (typeof ref === "string") return ref; + return { ref: validateRef(ref), end }; + } + } catch (err) { + if (err instanceof RefError) return err.message; + throw err; + } + return "a target is w:Title, /document/Section, ./Section or an http(s) address"; +} + +/** A whole string as a target, or why it is not one. */ +export function parseTarget(text: string): Ref | string { + const s = text.trim(); + const r = readTarget(s, 0); + if (typeof r === "string") return r; + if (s.slice(r.end).trim()) return `unexpected text after the target: “${s.slice(r.end).trim()}”`; + return r.ref; +} + +/** What a person types: a target in the text form, or else a Wikipedia title. */ +export function parseTargetLoose(text: string): Ref | string { + const s = text.trim(); + if (!s) return "give a target: w:Title, /document/Section or an address"; + if (looksLikeTarget(s)) return parseTarget(s); + try { + return validateRef({ kind: "wiki", title: s, lang: DEFAULT_LANG }); + } catch (err) { + return (err as Error).message; + } +} + +/** A one-line description, for lists and messages. */ +export function describeTarget(r: Ref): string { + if (r.kind === "wiki") return `Wikipedia: ${r.title}${r.lang === DEFAULT_LANG ? "" : ` (${r.lang})`}`; + if (r.kind === "url") return r.title ? `${r.title} (${hostOf(r.url)})` : r.url; + return [r.doc, ...(r.path ?? [])].filter(Boolean).join(" › ") || "a node"; +} + +/** A page's site, for showing: its host without "www.". */ +export function hostOf(url: string): string { + try { + return new URL(url).host.replace(/^www\./, ""); + } catch { + return url; + } +} diff --git a/src/core/repo.ts b/src/core/repo.ts new file mode 100644 index 0000000..7a6b764 --- /dev/null +++ b/src/core/repo.ts @@ -0,0 +1,563 @@ +/** + * Git-shaped operations over the CRDT: history, verified checkout, revert, branches, and a merge + * that is structural first (the CRDT, deterministic) and semantic second (three-way comparison + * against the merge base, producing conflict records for a model or a person to resolve). + */ +import { VersionVector, type LoroText, type OpId, type PeerID } from "loro-crdt"; +import { healLinks } from "./links"; +import { Doc, NOLINK, OpError, anchorLost, label, setNolink, type CommitMeta, type Conflict, type NodeId, type NodeSnap, type Op, type Snap, descendants } from "./model"; +import { canonRef, formatTarget, parseTarget, validateRef, type Ref } from "./ref"; +import { clip, digest } from "./text"; + +/** A run of one peer's ops. */ +export interface Span { + peer: PeerID; + counter: number; + length: number; +} + +export interface Commit { + /** `${counter}@${peer}` of the commit's last op: a stable name for this point in history. */ + id: string; + peer: PeerID; + lamport: number; + /** Unix seconds. */ + time: number; + message: string; + by: string; + actor: string; + tag?: string; + /** Recorded SHA-256 of the tree state at this commit, if the commit carries one. */ + hash?: string; + parents: string[]; + frontiers: OpId[]; + /** The ops the commit is made of. */ + spans: Span[]; +} + +const opName = (o: OpId) => `${o.counter}@${o.peer}`; + +export function history(doc: Doc): Commit[] { + const out: Commit[] = []; + const parse = (message: string | undefined): Partial => { + if (!message) return {}; + try { + return JSON.parse(message); + } catch { + return { m: message }; + } + }; + for (const changes of doc.loro.getAllChanges().values()) { + for (let i = 0; i < changes.length; i++) { + const first = changes[i]; + // One commit can be stored as several consecutive changes: Loro splits large ones, and + // commits early when a deleted cursor is resolved mid-transaction. They carry the same + // commit id; the commit starts at the first and its state is the state after the last. + let c = first; + let meta = parse(c.message); + for (let next = changes[i + 1]; next && meta.n; next = changes[i + 1]) { + const follows = next.deps.length === 1 && next.deps[0].peer === c.peer && next.deps[0].counter === c.counter + c.length - 1; + const nextMeta = parse(next.message); + if (!follows || nextMeta.n !== meta.n) break; + c = next; + meta = { ...meta, ...nextMeta }; + i++; + } + const last = { peer: c.peer, counter: c.counter + c.length - 1 }; + out.push({ + id: opName(last), + peer: c.peer, + lamport: c.lamport + c.length - 1, + time: c.timestamp, + message: meta.m ?? "(undo/redo)", + by: meta.by ?? "?", + actor: meta.a ?? "human", + tag: meta.t, + hash: meta.h, + parents: first.deps.map(opName), + frontiers: [last], + spans: [{ peer: c.peer, counter: first.counter, length: c.counter + c.length - first.counter }], + }); + } + } + // Newest first. Lamport order is consistent with causality; peer breaks ties deterministically. + return out.sort((a, b) => b.lamport - a.lamport || (a.peer < b.peer ? 1 : -1)); +} + +/** A read-only replica of the document as it stood at a commit. */ +export function at(doc: Doc, commit: Pick): Doc { + return new Doc(doc.loro.forkAt(commit.frontiers), doc.author); +} + +/** + * The nodes some ops wrote to, read from the containers they changed: a node's data map shares + * the node's id, and its body sits under it. Tree ops are read for what they created, moved or + * deleted. Nodes that have since been deleted are still named (by id). + */ +export function touched(doc: Doc, spans: Span[]): { nodes: Set; deleted: Set; unknown: boolean } { + const nodes = new Set(); + const deleted = new Set(); + let unknown = false; + for (const s of spans) { + if (s.length <= 0) continue; + let tree = false; + for (const cid of doc.loro.getChangedContainersIn({ peer: s.peer, counter: s.counter }, s.length)) { + if (cid === "cid:root-tree:Tree") tree = true; + if (cid.startsWith("cid:root-")) continue; + const m = /^cid:(\d+@\d+):(\w+)$/.exec(cid); + if (!m) continue; + if (m[2] === "Map") nodes.add(m[1] as NodeId); + else { + const path = doc.loro.getPathToContainer(cid); + if (path?.[0] === "tree" && typeof path[1] === "string") nodes.add(path[1] as NodeId); + else unknown = true; + } + } + if (!tree) continue; + for (const change of doc.loro.exportJsonInIdSpan(s)) { + for (const op of change.ops) { + const c = op.content as { type?: string; target?: string; parent?: string }; + if (!op.container.endsWith(":Tree") || !c.target) continue; + if (c.type === "delete") deleted.add(c.target as NodeId); + else { + nodes.add(c.target as NodeId); + if (c.parent) nodes.add(c.parent as NodeId); + } + } + } + } + return { nodes, deleted, unknown }; +} + +export interface Verification { + checked: number; + unhashed: number; + mismatches: { id: string; message: string; recorded: string; actual: string }[]; +} + +/** + * Check out every commit and confirm the tree hashes to what the commit recorded. One detached + * replica walks the commits oldest first: a checkout moves it from one state to the next, where + * forking a fresh replica for each would replay the library's history every time. A detached + * replica can resolve an anchor whose characters were deleted later differently from the replica + * that made the commit, so a mismatch is checked again in a fresh fork before it is reported. + */ +export function verifyHistory(doc: Doc): Verification { + const result: Verification = { checked: 0, unhashed: 0, mismatches: [] }; + const walker = doc.fork(); + for (const c of history(doc).reverse()) { + if (!c.hash) { + result.unhashed++; + continue; + } + walker.loro.checkout(c.frontiers); + walker.reread(); + let actual = walker.stateHash(); + if (actual !== c.hash) actual = at(doc, c).stateHash(); + result.checked++; + if (actual !== c.hash) result.mismatches.push({ id: c.id, message: c.message, recorded: c.hash, actual }); + } + return result; +} + +/** Point a node's anchors back at the spans they had in `was`, if they have moved since. */ +function reanchor(doc: Doc, id: NodeId, was: NodeSnap, now: NodeSnap) { + const same = was.anchors.length === now.anchors.length && was.anchors.every((a, i) => a.start === now.anchors[i].start && a.end === now.anchors[i].end); + const node = doc.tree.getNodeByID(id); + const parent = node?.parent(); + if (same || !was.anchors.length || !node || !parent) return; + node.data.set("anchors", doc.makeAnchors(parent, was.anchors.map((a) => [a.start, a.end])) as never); + doc.mark(id); +} + +/** Roll the whole tree back to a commit by writing the inverse as a new commit. History is kept. */ +export function revertTo(doc: Doc, commit: Commit) { + const target = at(doc, commit).snap(); + if (doc.snap().library && !target.library) throw new OpError("that commit is from before the library existed; revert one document to it instead"); + doc.begin(`Revert to “${clip(commit.message, 60)}”`, "human", "revert"); + doc.loro.revertTo(commit.frontiers); + doc.reread(); + // A reverted deletion comes back as new characters and new nodes, which old cursors do not + // point at. The two trees have the same shape, so walk them together and re-anchor. + const now = doc.snap(); + const fix = (was: NodeId, is: NodeId) => { + const w = target.nodes[was]; + const n = now.nodes[is]; + if (!w || !n) return; + reanchor(doc, is, w, n); + w.children.forEach((c, i) => n.children[i] && fix(c, n.children[i])); + }; + fix(target.root, now.root); + doc.commit(`Revert to “${clip(commit.message, 60)}”`, "human", "revert"); +} + +/** + * Roll one subtree (a document) back to how it stood at a commit, leaving the rest of the library + * as it is now. Nodes that still exist keep their ids and are moved, rewritten and re-anchored to + * match; nodes deleted since come back as copies under new ids; nodes added since are deleted. + * The document node itself stays where it is now. + */ +export function revertDocTo(doc: Doc, commit: Commit, id: NodeId) { + const target = at(doc, commit).snap(); + const now = doc.snap(); + if (!target.nodes[id]) throw new OpError(`“${clip(label(now, id), 40)}” did not exist yet at “${clip(commit.message, 40)}”`); + if (!now.nodes[id]) throw new OpError("that node no longer exists"); + const message = `Revert “${clip(label(now, id), 40)}” to “${clip(commit.message, 50)}”`; + const tree = doc.tree; + const alive = (x: NodeId) => !!tree.getNodeByID(x) && !tree.isNodeDeleted(x); + const wanted = new Set([id, ...descendants(target, id)]); + doc.begin(message, "human", "revert"); + const place = (tid: NodeId, parent: NodeId | null, index: number) => { + const t = target.nodes[tid]; + if (!alive(tid)) { + doc.graft(target, tid, parent!, { index }); + return; + } + const n = tree.getNodeByID(tid)!; + if (parent) { + const from = n.parent()!; + const at = (from.children() ?? []).findIndex((c) => c.id === tid); + if (from.id !== parent || at !== index) { + tree.move(tid, parent, index); + doc.mark(from.id); + doc.mark(parent); + } + } + doc.mark(tid); + const d = n.data; + for (const [key, value] of [["kind", t.kind], ["title", t.title], ["by", t.by], ["pinned", t.pinned], ["up", t.seenUp], ["down", t.seenDown]] as const) { + if (d.get(key) !== value) d.set(key, value); + } + for (const [key, value] of [["form", t.form], ["lens", t.lens]] as const) { + if (value === undefined) d.get(key) !== undefined && d.delete(key); + else if (d.get(key) !== value) d.set(key, value); + } + if (!t.ref) d.get("ref") !== undefined && d.delete("ref"); + else if (JSON.stringify(canonRef(t.ref)) !== JSON.stringify(d.get("ref") ? canonRef(d.get("ref") as Ref) : null)) d.set("ref", t.ref as never); + // Declined phrases only ever grow; going back to a commit forgets the ones added since. + for (const k of d.keys()) if (k.startsWith(NOLINK) && !t.nolink?.includes(k.slice(NOLINK.length))) d.delete(k); + if (t.nolink?.length) setNolink(n, t.nolink); + const body = d.get("body") as LoroText | undefined; + if (body && body.toString() !== t.body) { + body.update(t.body); + doc.markAnchoredIn(body.id); + } + t.children.forEach((c, i) => place(c, tid, i)); + }; + place(id, null, 0); + // What was added since goes; then a second pass puts the survivors back in order. + for (const x of descendants(doc.snap(), id)) { + if (!wanted.has(x) && alive(x)) { + doc.mark(tree.getNodeByID(x)!.parent()!.id); + tree.delete(x); + } + } + place(id, null, 0); + // Re-anchor what no longer points where it pointed then. + const snap = doc.snap(); + for (const x of wanted) if (snap.nodes[x] && x !== id) reanchor(doc, x, target.nodes[x], snap.nodes[x]); + doc.commit(message, "human", "revert"); +} + +/** + * Re-attach notes whose anchor was lost but whose quoted text is back in the parent's body, as + * happens when a deletion is undone: the text returns as new characters that old cursors do not + * point at. Returns how many were re-anchored. + */ +export function healAnchors(doc: Doc): number { + const snap = doc.snap(); + const ops: Op[] = []; + for (const n of Object.values(snap.nodes)) { + if (n.kind !== "note" || !n.parent || !n.anchors.length || !n.anchors.every(anchorLost)) continue; + const quote = n.anchors[0].quote; + const at = quote ? snap.nodes[n.parent].body.indexOf(quote) : -1; + if (at >= 0) ops.push({ op: "update", id: n.id, anchors: [[at, at + quote.length]] }, { op: "bless", id: n.id, dir: "down" }); + } + if (ops.length) doc.apply(ops, `Re-anchor ${ops.length / 2} note${ops.length > 2 ? "s" : ""} to restored text`, { actor: "llm", tag: "regen" }); + // Links to nodes that came back under new ids are found again the same way, from what they recorded. + healLinks(doc); + return ops.length / 2; +} + +// ---- version-vector arithmetic ---- + +type VV = Map; +const vvOf = (doc: Doc): VV => doc.loro.version().toJSON(); + +function vvMin(a: VV, b: VV): VV { + const out: VV = new Map(); + for (const [peer, n] of a) { + const m = Math.min(n, b.get(peer) ?? 0); + if (m > 0) out.set(peer, m); + } + return out; +} + +export const vvIncludes = (a: VV, b: VV) => [...b].every(([peer, n]) => (a.get(peer) ?? 0) >= n); + +/** The ops in `to` that `from` lacks. */ +function spansBetween(from: VV, to: VV): Span[] { + const out: Span[] = []; + for (const [peer, n] of to) { + const m = from.get(peer) ?? 0; + if (n > m) out.push({ peer, counter: m, length: n - m }); + } + return out; +} + +export const encodeVV = (vv: VV) => JSON.stringify([...vv]); +export const decodeVV = (s: string): VV => new Map(JSON.parse(s)); + +// ---- merge ---- + +export interface MergeReport { + /** nothing: already contained. forward: the other side was strictly ahead. merge: histories had diverged. */ + kind: "nothing" | "forward" | "merge"; + conflicts: Conflict[]; + /** For a real merge: the three states it was computed from, for anything that wants to look further. */ + base?: Snap; + ours?: Snap; + theirs?: Snap; +} + +/** + * Bring another replica's changes in. `bytes` is its update, `theirVV` its version. + * The CRDT does the structural merge; what it cannot see is then looked for by comparing + * base, ours and theirs node by node. + * + * Comparing whole states costs the size of the library, so unless `full` is asked for, it is + * done only when the two sides could disagree: when they wrote to a node in common, or one side + * deleted something. Sync rounds take the short way; explicit merges ask for the states. + */ +export function mergeUpdate(doc: Doc, bytes: Uint8Array, theirVV: VV, opts: { full?: boolean } = {}): MergeReport { + const ourVV = vvOf(doc); + if (vvIncludes(ourVV, theirVV)) return { kind: "nothing", conflicts: [] }; + if (vvIncludes(theirVV, ourVV)) { + doc.loro.import(bytes); + doc.touch(); + return { kind: "forward", conflicts: [] }; + } + const mine = opts.full ? null : touched(doc, spansBetween(theirVV, ourVV)); + // A copy: a snapshot taken before a write answers lookups but cannot be enumerated (see Doc.patch). + const oursNow = opts.full ? { ...doc.snap(), nodes: { ...doc.snap().nodes } } : null; + doc.loro.import(bytes); + doc.touch(); + if (mine) { + const theirs = touched(doc, spansBetween(ourVV, theirVV)); + const overlap = [...mine.nodes].some((id) => theirs.nodes.has(id)); + const deletes = (mine.deleted.size && theirs.nodes.size + theirs.deleted.size) || (theirs.deleted.size && mine.nodes.size); + if (!overlap && !deletes && !mine.unknown && !theirs.unknown) return { kind: "merge", conflicts: [] }; + } + const merged = doc.snap(); + const stateAt = (vv: VV) => new Doc(doc.loro.forkAt(doc.loro.vvToFrontiers(new VersionVector(vv)))).snap(); + const ours = oursNow ?? stateAt(ourVV); + const base = stateAt(vvMin(ourVV, theirVV)); + const theirs = stateAt(theirVV); + const found = detectConflicts(base, ours, theirs, merged); + const known = new Set(doc.conflicts().map((c) => c.id)); + const fresh = found.filter((c) => !known.has(c.id)); + if (fresh.length) { + for (const c of fresh) doc.conflictMap.set(c.id, JSON.stringify(c)); + doc.touch(); + doc.commit(`Detected ${fresh.length} semantic conflict${fresh.length > 1 ? "s" : ""}`, "llm", "conflict"); + } + return { kind: "merge", conflicts: fresh, base, ours, theirs }; +} + +/** Merge a branch (another Doc) into this one, leaving a merge commit that names it. */ +export function mergeBranch(doc: Doc, other: Doc, name: string): MergeReport { + const report = mergeUpdate(doc, other.loro.export({ mode: "update", from: doc.loro.version() }), vvOf(other), { full: true }); + if (report.kind === "merge") { + const n = report.conflicts.length; + doc.loro.getMap("meta").set("merges", ((doc.loro.getMap("meta").get("merges") as number) ?? 0) + 1); + doc.commit(`Merge ${name}${n ? ` (${n} conflict${n > 1 ? "s" : ""} to review)` : ""}`, "human", "merge"); + } + return report; +} + +/** The semantic conflicts a structural merge leaves behind. Pure: same inputs, same records. */ +export function detectConflicts(base: Snap, ours: Snap, theirs: Snap, merged: Snap): Conflict[] { + const out: Conflict[] = []; + const ids = new Set([...Object.keys(ours.nodes), ...Object.keys(theirs.nodes)] as NodeId[]); + const order = (x: string, y: string): [string, string] => (x <= y ? [x, y] : [y, x]); + + for (const id of ids) { + const b = base.nodes[id]; + const o = ours.nodes[id]; + const t = theirs.nodes[id]; + if (!b) continue; // created on one side only: nothing to disagree with + if (o && t) { + // Both sides changed the same field to different things. The CRDT's interleaving is + // well-formed text that neither author wrote. + for (const field of ["title", "body"] as const) { + if (o[field] !== b[field] && t[field] !== b[field] && o[field] !== t[field]) { + const [a, bb] = order(o[field], t[field]); + out.push({ + id: digest(["edit-edit", id, field, a, bb].join("\u0000")), + type: "edit-edit", + node: id, + field, + title: merged.nodes[id]?.title ?? b.title, + base: b[field], + a, + b: bb, + merged: merged.nodes[id]?.[field] ?? "", + status: "open", + }); + } + } + // Both sides pointed the same node at different targets: the CRDT keeps one; say which was lost. + const [rb, ro, rt] = [b, o, t].map((n) => refText(n.ref)); + if (ro !== rb && rt !== rb && ro !== rt) { + const [a, bb] = order(ro, rt); + out.push({ + id: digest(["edit-edit", id, "ref", a, bb].join("\u0000")), + type: "edit-edit", + node: id, + field: "ref", + title: merged.nodes[id] ? label(merged, id) : b.title, + base: rb, + a, + b: bb, + merged: refText(merged.nodes[id]?.ref), + status: "open", + }); + } + } else if (!!o !== !!t) { + // One side deleted the node (or an ancestor); the other kept working in it. + const kept = (o ? ours : theirs) as Snap; + const k = kept.nodes[id]; + const parentGone = b.parent && !(o ? theirs : ours).nodes[b.parent]; + if (parentGone) continue; // reported once, at the top of the deleted subtree + const touchedHere = [id, ...descendants(kept, id)].filter((x) => { + const was = base.nodes[x]; + const now = kept.nodes[x]; + return !was || was.title !== now.title || was.body !== now.body || refText(was.ref) !== refText(now.ref); + }); + if (!touchedHere.length) continue; + out.push({ + id: digest(["edit-delete", id, k.title, k.body].join("\u0000")), + type: "edit-delete", + node: id, + field: "body", + title: k.title || b.title, + base: b.body, + a: k.body, + b: "", + merged: "", + status: "open", + parent: b.parent ?? undefined, + }); + } + } + return out.sort((x, y) => (x.id < y.id ? -1 : 1)); +} + +/** + * Settle a conflict by writing a chosen text as an ordinary commit. The record keeps what was + * there before, so the decision can be reopened. + */ +export function resolveConflict( + doc: Doc, + id: string, + text: string, + how: { by: string; rationale?: string; actor?: "human" | "llm" }, +) { + const c = doc.conflicts().find((x) => x.id === id); + if (!c) throw new Error(`no such conflict: ${id}`); + const snap = doc.snap(); + const actor = how.actor ?? "human"; + const record: Conflict = { ...c, status: "resolved", resolved: text, rationale: how.rationale, resolvedBy: how.by }; + doc.conflictMap.set(id, JSON.stringify(record)); + doc.touch(); + const message = `Resolve conflict in “${clip(c.title, 40)}” (${how.by})`; + if (c.type === "edit-edit" && c.field === "ref" && snap.nodes[c.node]) { + const ref = readRefText(text); + if (typeof ref === "string") throw new OpError(`not a target: ${ref}`); + doc.apply([{ op: "update", id: c.node, ref }], message, { actor, tag: "resolve" }); + } else if (c.type === "edit-edit" && snap.nodes[c.node]) { + doc.apply([{ op: "update", id: c.node, [c.field!]: text }], message, { actor, tag: "resolve" }); + } else if (c.type === "edit-delete" && text && c.parent && snap.nodes[c.parent] && !snap.nodes[c.node]) { + // Restoring: tree nodes cannot be undeleted, so the kept text comes back as a new node. + doc.apply([{ op: "create", parent: c.parent, title: c.title, body: text }], message, { actor, tag: "resolve" }); + } else if (c.type === "contradiction" && snap.nodes[c.node] && text !== snap.nodes[c.node].body) { + doc.apply([{ op: "update", id: c.node, body: text }], message, { actor, tag: "resolve" }); + } else { + doc.commit(message, actor, "resolve"); + } +} + +/** Undo a resolution: put back what the merge produced and mark the conflict open again. */ +export function reopenConflict(doc: Doc, id: string) { + const c = doc.conflicts().find((x) => x.id === id); + if (!c || c.status !== "resolved") return; + const { resolved: _r, rationale: _why, resolvedBy: _by, ...rest } = c; + doc.conflictMap.set(id, JSON.stringify({ ...rest, status: "open" })); + doc.touch(); + const snap = doc.snap(); + if (c.field === "ref" && snap.nodes[c.node]) { + const ref = readRefText(c.merged); + doc.apply([{ op: "update", id: c.node, ref: typeof ref === "string" ? null : ref }], `Reopen conflict in “${clip(c.title, 40)}”`, { actor: "llm", tag: "resolve" }); + } else if ((c.type === "edit-edit" || c.type === "contradiction") && snap.nodes[c.node]) { + doc.apply([{ op: "update", id: c.node, [c.field ?? "body"]: c.merged }], `Reopen conflict in “${clip(c.title, 40)}”`, { + actor: "llm", + tag: "resolve", + }); + } else { + doc.commit(`Reopen conflict in “${clip(c.title, 40)}”`, "human", "resolve"); + } +} + +// ---- branches ---- + +/** A set of named replicas of one library. */ +export class Repo { + branches = new Map(); + current = "main"; + + constructor(main: Doc) { + this.branches.set("main", main); + } + + get doc(): Doc { + return this.branches.get(this.current)!; + } + + /** Create a branch from the current one, optionally from an earlier commit. */ + branch(name: string, from?: Commit): Doc { + if (this.branches.has(name)) throw new Error(`branch exists: ${name}`); + const doc = from ? at(this.doc, from).fork() : this.doc.fork(); + doc.author = this.doc.author; + this.branches.set(name, doc); + return doc; + } + + switch(name: string) { + if (!this.branches.has(name)) throw new Error(`no such branch: ${name}`); + this.current = name; + } + + merge(from: string): MergeReport { + const other = this.branches.get(from); + if (!other) throw new Error(`no such branch: ${from}`); + return mergeBranch(this.doc, other, from); + } +} + +/** A target as text for a conflict record ("" for none): what a person reads and what resolving it parses back. */ +function refText(r: Ref | undefined): string { + // A node target is kept whole (its id is what counts), the others in their text form. + return !r ? "" : r.kind === "node" ? JSON.stringify(r) : formatTarget(r); +} + +function readRefText(text: string): Ref | null | string { + if (!text) return null; + if (text.startsWith("{")) { + try { + return validateRef(JSON.parse(text)); + } catch (err) { + return (err as Error).message; + } + } + return parseTarget(text); +} diff --git a/src/core/text.ts b/src/core/text.ts new file mode 100644 index 0000000..214448e --- /dev/null +++ b/src/core/text.ts @@ -0,0 +1,151 @@ +/** Text utilities: hashing, sentence/word segmentation, and the size → display-form rule. */ + +export type Range = [start: number, end: number]; +export type Form = "gloss" | "note" | "passage"; + +// ---- SHA-256 (synchronous; needed inside commits, where WebCrypto's async API can't be used) ---- + +const K = new Uint32Array(64); +{ + let n = 0; + for (let c = 2; n < 64; c++) { + let prime = true; + for (let d = 2; d * d <= c; d++) if (c % d === 0) { prime = false; break; } + if (prime) K[n++] = (Math.cbrt(c) * 2 ** 32) >>> 0; + } +} +const encoder = new TextEncoder(); + +export function sha256(input: string): string { + const data = encoder.encode(input); + const bitLen = data.length * 8; + const padded = new Uint8Array((((data.length + 8) >> 6) + 1) << 6); + padded.set(data); + padded[data.length] = 0x80; + const view = new DataView(padded.buffer); + view.setUint32(padded.length - 8, Math.floor(bitLen / 2 ** 32)); + view.setUint32(padded.length - 4, bitLen >>> 0); + const h = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, + ]); + const w = new Uint32Array(64); + const rotr = (x: number, n: number) => (x >>> n) | (x << (32 - n)); + for (let off = 0; off < padded.length; off += 64) { + for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4); + for (let i = 16; i < 64; i++) { + const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3); + const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10); + w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0; + } + let [a, b, c, d, e, f, g, hh] = h; + for (let i = 0; i < 64; i++) { + const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); + const ch = (e & f) ^ (~e & g); + const t1 = (hh + S1 + ch + K[i] + w[i]) >>> 0; + const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); + const maj = (a & b) ^ (a & c) ^ (b & c); + const t2 = (S0 + maj) >>> 0; + hh = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0; + } + h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh; + } + return Array.from(h, (x) => x.toString(16).padStart(8, "0")).join(""); +} + +/** Short content hash used for staleness bookkeeping. */ +export const digest = (s: string) => sha256(s).slice(0, 16); + +// ---- Segmentation ---- + +/** Paragraph ranges: runs of text separated by one or more blank lines. */ +export function paragraphs(body: string): Range[] { + const out: Range[] = []; + const re = /\n\s*\n/g; + let start = 0; + for (let m; (m = re.exec(body)); ) { + if (m.index > start) out.push([start, m.index]); + start = m.index + m[0].length; + } + if (start < body.length) out.push([start, body.length]); + return out.filter(([s, e]) => body.slice(s, e).trim().length > 0); +} + +/** + * Sentence ranges. A sentence ends at . ! or ? (plus any closing quote or bracket) followed by + * whitespace and something that looks like a sentence start, or at the end of its paragraph. + */ +export function sentences(body: string): Range[] { + const out: Range[] = []; + for (const [ps, pe] of paragraphs(body)) { + const para = body.slice(ps, pe); + const re = /[.!?]["”’)\]*`]*\s+(?=["“‘(\[*`]*[A-Z0-9])/g; + let start = 0; + const push = (s: number, e: number) => { + while (s < e && /\s/.test(para[s])) s++; + while (e > s && /\s/.test(para[e - 1])) e--; + if (e > s) out.push([ps + s, ps + e]); + }; + for (let m; (m = re.exec(para)); ) { + const end = m.index + m[0].length; + push(start, end); + start = end; + } + push(start, para.length); + } + return out; +} + +/** Word ranges (letters, digits, inner apostrophes and hyphens). */ +export function words(body: string, within?: Range): Range[] { + const [s, e] = within ?? [0, body.length]; + const out: Range[] = []; + const re = /[\p{L}\p{N}]+(?:['’\-.][\p{L}\p{N}]+)*/gu; + re.lastIndex = s; + for (let m; (m = re.exec(body)) && m.index < e; ) { + out.push([m.index, Math.min(e, m.index + m[0].length)]); + } + return out; +} + +export const wordCount = (s: string) => words(s).length; + +/** + * The display form follows the size of what is being expanded, so it is known before the first + * token arrives and nothing reflows while text streams in. + */ +export function formFor(selection: string): Form { + const n = wordCount(selection); + if (n <= 3) return "gloss"; + if (n <= 45 && sentences(selection).length <= 2) return "note"; + return "passage"; +} + +/** Index of the range containing offset, or the nearest one after it. */ +export function rangeAt(ranges: Range[], offset: number): number { + for (let i = 0; i < ranges.length; i++) if (offset < ranges[i][1]) return i; + return ranges.length - 1; +} + +export const overlaps = (a: Range, b: Range) => a[0] < b[1] && b[0] < a[1]; + +/** Strip the two inline markers so text can be shown or sent as plain prose. */ +export const plain = (s: string) => s.replace(/[*`]/g, ""); + +export function clip(s: string, n: number): string { + s = s.replace(/\s+/g, " ").trim(); + return s.length <= n ? s : s.slice(0, n - 1).trimEnd() + "…"; +} + +/** A file name or title as a document's slug: lowercase letters, digits and single hyphens. */ +export function slugify(s: string): string { + return ( + s + .normalize("NFKD") + .replace(/[̀-ͯ]/g, "") + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 60) + .replace(/-+$/, "") || "untitled" + ); +}