Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Note SPBoucher AI8 * File : src/lib/canvas/merge.ts9 * Description : three-way merge of canvases by node / edge id (SPEC §3.4,10 * §7), used when `PUT /api/canvases/<id>` answers 409 and11 * when a draft made offline meets a newer server copy. Same12 * algorithm, same outputs as `CanvasDocument.merge` of13 * SPNotesCore (Sources/SPNotesDocument/CanvasMerge.swift):14 * the fixtures in tests/fixtures/canvas/merge-*.json are the15 * shared proof. Edits of different elements combine; an16 * element changed differently on both sides is a conflict17 * that carries every version — nothing is lost. Pure.18 * Module : lib19 * Repository : https://git.spboucher.ai/note-spboucher-ai20 * Project Website : https://note.spboucher.ai21 * Created : 2026-11-1922 * Last Modified : 2026-11-1923 *24 * Author : Simon-Pierre Boucher25 * Position : Professor of Finance26 * Institution : Université du Québec en Outaouais (UQO)27 * Organization : SP Boucher28 * Website : https://spboucher.ai29 * Git : https://git.spboucher.ai30 *31 * Preferred Contact: contact@spboucher.ai32 * Development : dev@spboucher.ai33 * Support : support@spboucher.ai34 * Security/Admin : admin@spboucher.ai35 *36 * Copyright (c) 202637 * Simon-Pierre Boucher38 * All rights reserved where applicable. This file is governed by the39 * applicable project license, copyright notices and relevant law.40 * Existing third-party rights and notices remain unaffected.41 *42 * License : None specified (no license file in this repository)43 *44 * Do not embed credentials, private keys, access tokens,45 * certificates or confidential personal information.46 *47 * =============================================================================48 * END OF SP BOUCHER SOURCE HEADER49 * =============================================================================50 */5152import { CANVAS_FORMAT, type CanvasData, type CanvasEdge, type CanvasNode } from "./format";53import { compareCodePoints, jsonEqual, removeNodes } from "./core";5455export type ConflictKind = "node" | "edge" | "field";56/**57 * bothEdited: changed differently on both sides (or added on both sides with different values) — the merged canvas keeps LOCAL.58 * editedAndDeleted: deleted on one side, edited on the other — the merged canvas keeps the EDITED version (SPEC §7).59 * deletedButReferenced: a node deleted on one side while the other side attached a new or edited edge to it — the node is restored.60 */61export type ConflictReason = "bothEdited" | "editedAndDeleted" | "deletedButReferenced";62/** One element the merge could not settle. `base` / `local` / `remote` are the element in the ancestor, here and on the server; an absent key = absent / deleted. */63export interface CanvasConflict { kind: ConflictKind; id: string; reason: ConflictReason; base?: unknown; local?: unknown; remote?: unknown }64export interface MergeResult { merged: CanvasData; conflicts: CanvasConflict[] }6566type El = { id: string; [k: string]: unknown };67const firstById = <T extends El>(list: readonly T[]) => { const m = new Map<string, T>(); for (const e of list) if (!m.has(e.id)) m.set(e.id, e); return m; };68const conflict = (kind: ConflictKind, id: string, reason: ConflictReason, base: unknown, local: unknown, remote: unknown): CanvasConflict => ({ kind, id, reason, ...(base !== undefined ? { base } : {}), ...(local !== undefined ? { local } : {}), ...(remote !== undefined ? { remote } : {}) });6970/**71 * Three-way merge by element id.72 *73 * 1. Shortcuts on the whole document: `local = remote` or `remote = base` → local, untouched; `local = base` → remote, untouched.74 * 2. Nodes, then edges, id by id (L, R, B = the element on each side; absent counts as a value):75 * L = R → that value · L = B → R · R = B → L ·76 * both present and different → keep L, conflict `bothEdited` ·77 * one absent → keep the present one (the edited version), conflict `editedAndDeleted`.78 * Order of the result: base order, then the ids added by either side sorted by Unicode scalar value — so a clean merge gives the79 * same document whichever side is called local. Stacking is decided by `z`, never by this order.80 * Duplicate ids inside one canvas: the first occurrence counts.81 * 3. Edges left without an end because a side deleted the node (an end that is not in the merged nodes but was in the base):82 * the edge is dropped when it is unchanged since the base (it goes with its node); otherwise (created or edited by the other83 * side) the node is restored from the base, at its base position among the base nodes, with a conflict `deletedButReferenced`.84 * 4. Top-level fields (every key except `nodes` / `edges`), in sorted key order: L = R or R = B → L · L = B → R · else keep L and85 * report a `field` conflict — except `viewport`, a per-device view state: local wins unless only the remote changed, never a conflict.86 * `format` is always "spn-canvas-1".87 */88export function mergeCanvas(base: CanvasData, local: CanvasData, remote: CanvasData): MergeResult {89 if (jsonEqual(local, remote) || jsonEqual(remote, base)) return { merged: local, conflicts: [] };90 if (jsonEqual(local, base)) return { merged: remote, conflicts: [] };91 const conflicts: CanvasConflict[] = [];9293 function mergeElements<T extends El>(kind: ConflictKind, b: readonly T[], l: readonly T[], r: readonly T[]): T[] {94 const bm = firstById(b), lm = firstById(l), rm = firstById(r);95 const resolve = (id: string): T | undefined => {96 const bv = bm.get(id), lv = lm.get(id), rv = rm.get(id);97 if (jsonEqual(lv, rv)) return lv;98 if (jsonEqual(lv, bv)) return rv;99 if (jsonEqual(rv, bv)) return lv;100 if (lv && rv) { conflicts.push(conflict(kind, id, "bothEdited", bv, lv, rv)); return lv; }101 conflicts.push(conflict(kind, id, "editedAndDeleted", bv, lv, rv));102 return lv ?? rv;103 };104 const out: T[] = [];105 for (const id of bm.keys()) { const v = resolve(id); if (v) out.push(v); }106 const added = [...new Set([...lm.keys(), ...rm.keys()])].filter((id) => !bm.has(id)).sort(compareCodePoints);107 for (const id of added) { const v = resolve(id); if (v) out.push(v); }108 return out;109 }110111 let nodes = mergeElements<CanvasNode>("node", base.nodes, local.nodes, remote.nodes);112 let edges = mergeElements<CanvasEdge>("edge", base.edges, local.edges, remote.edges);113114 // edges whose end was deleted by a side115 const baseNodes = firstById(base.nodes), baseEdges = firstById(base.edges);116 const localIds = new Set(local.nodes.map((n) => n.id)), remoteIds = new Set(remote.nodes.map((n) => n.id));117 const present = new Set(nodes.map((n) => n.id)); const restored: string[] = []; const kept: CanvasEdge[] = [];118 for (const e of edges) {119 const ends = [e.from, e.to].filter((x): x is string => typeof x === "string");120 const missing = ends.filter((id) => !present.has(id) && baseNodes.has(id));121 if (!missing.length) { kept.push(e); continue; }122 if (jsonEqual(baseEdges.get(e.id), e)) continue; // untouched edge of a deleted node: goes with it123 for (const id of missing) {124 if (present.has(id)) continue;125 present.add(id); restored.push(id); const b = baseNodes.get(id);126 conflicts.push(conflict("node", id, "deletedButReferenced", b, localIds.has(id) ? b : undefined, remoteIds.has(id) ? b : undefined));127 }128 kept.push(e);129 }130 edges = kept;131 if (restored.length) { // back at their base position among the base elements132 const current = firstById(nodes); const seen = new Set<string>(); const ordered: CanvasNode[] = [];133 for (const n of base.nodes) if (present.has(n.id) && !seen.has(n.id)) { seen.add(n.id); ordered.push(current.get(n.id) ?? n); }134 for (const n of nodes) if (!seen.has(n.id)) { seen.add(n.id); ordered.push(n); }135 nodes = ordered;136 }137138 // top-level fields139 const B = base as Record<string, unknown>, L = local as Record<string, unknown>, R = remote as Record<string, unknown>;140 const keys = [...new Set([...Object.keys(B), ...Object.keys(L), ...Object.keys(R)])].filter((k) => k !== "nodes" && k !== "edges").sort(compareCodePoints);141 const fields: Record<string, unknown> = {};142 for (const key of keys) {143 const bv = B[key], lv = L[key], rv = R[key]; let value: unknown;144 if (jsonEqual(lv, rv) || jsonEqual(rv, bv)) value = lv;145 else if (jsonEqual(lv, bv)) value = rv;146 else { value = lv; if (key !== "viewport") conflicts.push(conflict("field", key, lv === undefined || rv === undefined ? "editedAndDeleted" : "bothEdited", bv, lv, rv)); }147 if (value !== undefined) fields[key] = value;148 }149 return { merged: { ...fields, format: CANVAS_FORMAT, nodes, edges } as CanvasData, conflicts };150}151152/**153 * The canvas with one conflict settled: `takeRemote` replaces the element by (or removes it like) the conflict's `remote` value;154 * otherwise its `local` value is (re)asserted — which is what the merge already kept, except after later edits.155 * Removing a node removes its edges; `format` cannot be changed.156 */157export function resolveConflict(d: CanvasData, c: CanvasConflict, takeRemote: boolean): CanvasData {158 const value = takeRemote ? c.remote : c.local;159 const valid = value && typeof value === "object" && typeof (value as El).id === "string";160 if (c.kind === "node") {161 if (!valid) return removeNodes(d, [c.id]);162 const v = value as CanvasNode; const i = d.nodes.findIndex((n) => n.id === c.id);163 return { ...d, nodes: i >= 0 ? d.nodes.map((n, k) => (k === i ? v : n)) : [...d.nodes, v] };164 }165 if (c.kind === "edge") {166 if (!valid) return { ...d, edges: d.edges.filter((e) => e.id !== c.id) };167 const v = value as CanvasEdge; const i = d.edges.findIndex((e) => e.id === c.id);168 return { ...d, edges: i >= 0 ? d.edges.map((e, k) => (k === i ? v : e)) : [...d.edges, v] };169 }170 if (c.id === "format" || c.id === "nodes" || c.id === "edges") return d;171 const out: Record<string, unknown> = { ...d }; if (value === undefined) delete out[c.id]; else out[c.id] = value;172 return out as CanvasData;173}174