Developers · version 0.8.0
Build with Heddle
Start in the framework you use, mount the history component, then read how the five rules behave with real inputs. After that: the multiplayer sync pattern, the git mapping and the API reference. The last section is for apps whose core is not JavaScript.
Quick start UI kit Multiplayer sync New in 0.5 to 0.8 Reference
Quick start
The same small app five ways: one title field with undo, redo, a scrubber and autosave. Heddle has no framework code in it, so every version makes the same five moves.
bun run pack # in the heddle repo: writes dist/heddle-0.8.0.tgz
bun add /path/to/heddle/dist/heddle-0.8.0.tgz # in your appimport { autosave, loadHistory } from "heddle";
import { mountHistory } from "heddle/ui";
type Doc = { title: string };
const input = document.querySelector<HTMLInputElement>("#title")!;
// 1. One history per document. Load it, or start it.
const history = loadHistory<Doc>(localStorage, "title-doc", { model: "linear" });
if (!history.length()) history.commit({ title: "Untitled" }, { message: "Start" });
// 2. Commit the whole state when it changes.
input.addEventListener("change", () => history.commit({ title: input.value }, { message: "Rename" }));
// 3. Draw from the history, now and after every change.
const draw = () => void (input.value = history.state().title);
const off = history.subscribe(draw);
draw();
// 4. Undo, Redo and a scrubber, in an element you own.
const view = mountHistory(document.querySelector<HTMLElement>("#history")!, history);
// 5. Save after every change. On teardown: stop(), off(), view.destroy().
const stop = autosave(history, localStorage, "title-doc");import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
import { autosave, loadHistory } from "heddle";
import { mountHistory } from "heddle/ui";
type Doc = { title: string };
// One history per document, created outside the component.
const history = loadHistory<Doc>(localStorage, "title-doc", { model: "linear" });
if (!history.length()) history.commit({ title: "Untitled" }, { message: "Start" });
autosave(history, localStorage, "title-doc");
// The current commit id is the snapshot: a string that changes exactly when the position does.
const subscribe = (notify: () => void) => history.subscribe(notify);
const position = () => history.get().id;
export function Editor() {
const id = useSyncExternalStore(subscribe, position);
const doc = useMemo(() => history.state(), [id]);
const host = useRef<HTMLDivElement>(null);
useEffect(() => {
const view = mountHistory(host.current!, history);
return () => view.destroy();
}, []);
const rename = (title: string) => history.commit({ ...doc, title }, { message: "Rename" });
return (
<>
<input value={doc.title} onChange={(e) => rename(e.target.value)} />
<div ref={host} />
</>
);
}import { createSignal, onCleanup, onMount } from "solid-js";
import { autosave, loadHistory } from "heddle";
import { mountHistory } from "heddle/ui";
type Doc = { title: string };
// One history per document, created outside the component.
const history = loadHistory<Doc>(localStorage, "title-doc", { model: "linear" });
if (!history.length()) history.commit({ title: "Untitled" }, { message: "Start" });
autosave(history, localStorage, "title-doc");
export function Editor() {
const [doc, setDoc] = createSignal(history.state());
onCleanup(history.subscribe(() => setDoc(history.state())));
let host!: HTMLDivElement;
onMount(() => {
const view = mountHistory(host, history);
onCleanup(() => view.destroy());
});
const rename = (title: string) => history.commit({ ...doc(), title }, { message: "Rename" });
return (
<>
<input value={doc().title} onChange={(e) => rename(e.currentTarget.value)} />
<div ref={host} />
</>
);
}<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, shallowRef } from "vue";
import { autosave, loadHistory } from "heddle";
import { mountHistory } from "heddle/ui";
type Doc = { title: string };
// One history per document. Module scope would also do; here it lives as long as the component.
const history = loadHistory<Doc>(localStorage, "title-doc", { model: "linear" });
if (!history.length()) history.commit({ title: "Untitled" }, { message: "Start" });
const stop = autosave(history, localStorage, "title-doc");
const doc = shallowRef(history.state());
const off = history.subscribe(() => (doc.value = history.state()));
const host = ref<HTMLDivElement>();
let view: ReturnType<typeof mountHistory> | undefined;
onMounted(() => (view = mountHistory(host.value!, history)));
onBeforeUnmount(() => {
view?.destroy();
off();
stop();
});
const rename = (e: Event) =>
history.commit({ ...doc.value, title: (e.target as HTMLInputElement).value }, { message: "Rename" });
</script>
<template>
<input :value="doc.title" @change="rename" />
<div ref="host" />
</template><script lang="ts">
import { onMount } from "svelte";
import { autosave, loadHistory } from "heddle";
import { mountHistory } from "heddle/ui";
type Doc = { title: string };
// One history per document.
const history = loadHistory<Doc>(localStorage, "title-doc", { model: "linear" });
if (!history.length()) history.commit({ title: "Untitled" }, { message: "Start" });
let doc = $state.raw(history.state());
let host: HTMLDivElement;
onMount(() => {
const stop = autosave(history, localStorage, "title-doc");
const off = history.subscribe(() => (doc = history.state()));
const view = mountHistory(host, history);
return () => {
view.destroy();
off();
stop();
};
});
const rename = (title: string) => history.commit({ ...doc, title }, { message: "Rename" });
</script>
<input value={doc.title} onchange={(e) => rename(e.currentTarget.value)} />
<div bind:this={host}></div>All five are run by the test suite as written. The four framework files are compiled with each framework's own compiler and mounted in a DOM: the test renames the title, presses Undo in the mounted component, checks what was saved and unmounts. Tested against React 19, SolidJS 1, Vue 3, Svelte 5. They are development dependencies of this repository only: the library has 0 runtime dependencies.
The five moves
- Create or load one history per document. Outside any component, so a re-render never makes a second one. loadHistory returns an empty history the first time.
- Commit the whole state when it changes. Pass the full state object. Heddle diffs it against the last commit and stores only the nodes that changed.
- Subscribe and draw from history.state(). subscribe(fn) runs after every change (a commit, an undo, a move from the component) and returns the function that stops it.
- Mount the component in an element you own. mountHistory returns { destroy() }. Call it when the element goes away. The component is plain DOM, so every framework hosts it the same way.
- Save. autosave(history, store, key) writes after every change and returns stop(). Any object with getItem and setItem works.
Want branches? Change model: "linear" to model: "graph". Nothing else in these files changes: the component reads history.capabilities and shows the branch and merge controls by itself.
UI kit
mountHistory is the one component most apps need. It takes a history of either model and renders from its capabilities. The lower-level pieces it is built from are exported too. No framework. Every component re-renders when the history changes, works from the keyboard and fits a 320 px wide host.
This figure is live. It needs JavaScript, which has not run.
History: Undo, Redo, drag to preview, release to move, Escape cancels a preview. Details has the capability-gated controls. Timeline and graph are the graph-model pieces on their own: arrow keys, Home and End move between commits, Enter selects, double-click checks out.
mountHistory(host, history, options)
Two tabs. Timeline (the default) is Undo, Redo, one scrubber, the position and the current message, in both models. Details lists the commits for a history without the graph capability. With graph capabilities it shows a branch list, Branch here, Merge from, Check out, Revert, Restore part and the commit graph, each behind its own flag. It returns { element, update(), destroy(), tab(), show(tab) }. The samples in step two and under Pick a model are complete.
| Option | Meaning |
|---|---|
onPreview(state, commit) | Called while dragging the scrubber. Nothing has moved and nothing is committed. |
onChange(state, commit) | Called after the component moved the position or made a commit: undo, redo, drag released, row click, check out, merge, revert, restore. |
onAction(action, preview) | Called before every action (undo, redo, seek, checkout, branch, merge, revert, restore) with a dry-run preview: status, state, changes, conflicts, removesPart. Return "deny" to veto it, "handled" when your app performed it itself, or nothing to let it proceed. { verdict, message } adds a status line. |
onSelect(commit), onTab(tab) | The commit shown changed. The visitor switched tab. |
onDetailsSelect(commit) | The commit the Details actions act on changed: the one selected in the graph, else the current one. |
actions | Your own buttons in Details: { id, label, hint?, enabled?(commit), run(commit) }[]. They act on that commit. |
onError(error), onConflict(conflicts) | An action failed, or a merge stopped on conflicts. Both are also written to the status line in Details. |
tab | "simple" (Timeline, the default) or "details". |
parts, part | Part selectors offered by Restore part (a string, or { value, label?, hint? }), and the one selected at mount. Used only when the history has partialRestore. Change them later with setParts(). |
partLabel(selector, from) | How a part is named in status text. Default: the label of the matching parts entry, else the selector. |
branchName(commit), branchInput, mergeOptions | Default name for Branch here. Whether a name field is shown beside it (default true). Options passed to merge and revert, such as strategies. |
graph | { rowHeight, laneWidth, maxHeight, checkoutOnSelect, showDetached } for the embedded commit graph. |
maxTicks, maxRows | Above 200 commits only checkpoint ticks are drawn. Details lists the newest 200 commits. |
formatTime(ms), theme, label | Time format in Details. "light" or "dark". Accessible name, default "History". |
It returns { element, update(), destroy(), tab(), show(tab), selection(), select(target), setParts(parts, selected?), part(), selectPart(selector) }. The parts and the selection can change while it is mounted.
Host hook and dry runs
An app whose real source of truth is elsewhere (an engine, a server, a document model) should not have a component commit behind its back. onAction is called before every action with a preview computed by a dry run. Return "deny" and nothing happens. Return "handled" and the component performs nothing: your app did it, and the component re-renders from the history. The dry runs are on the history too: previewRestore, previewRevert and previewMerge return the state the real call would commit and write nothing.
Restoring a part that does not exist in the source commit removes it. The button then reads Remove part, the preview carries removesPart: true, and restore(from, part, { ifMissing: "error" }) refuses instead.
import { createHistory } from "heddle";
import { mountHistory } from "heddle/ui";
type Doc = { title: string; layers: Record<string, { fill: string }> };
const repo = createHistory<Doc>({ model: "graph", parts: { layer: (id) => `/layers/${id}` } });
const first = repo.commit({ title: "Poster", layers: { sky: { fill: "blue" } } }, { message: "Start" });
repo.commit({ title: "Poster", layers: { sky: { fill: "navy" }, sun: { fill: "gold" } } }, { message: "Add sun" });
// A dry run: what restore would commit. Nothing is written and nothing moves.
const dry = repo.previewRestore(first.id, "layer:sun");
dry.missing; // true: "sun" is not in the first commit, so restoring it removes it
dry.state; // { title: "Poster", layers: { sky: { fill: "navy" } } }
const locked = new Set(["revert"]);
const view = mountHistory(document.querySelector<HTMLElement>("#history-panel")!, repo, {
parts: [{ value: "layer:sky", label: "Sky", hint: "background" }],
partLabel: (selector) => `layer “${selector.slice(6)}”`,
// Asked before every action, with a preview. "deny" vetoes it; "handled" means your app did it itself.
onAction: (action, preview) => {
if (locked.has(action.type)) return { verdict: "deny", message: "This board is read-only" };
if (action.type === "restore" && preview.removesPart) return "deny";
},
onDetailsSelect: (commit) => console.log("Details acts on", commit?.message),
});
// Layers changed in your app: update the restore choices in place. No remount.
view.setParts([{ value: "layer:sky", label: "Sky" }, { value: "layer:sun", label: "Sun" }], "layer:sun");
view.select(first.id); // select a commit in the Details graph
const selected = view.selection(); // the commit the Details actions act onThe dropdowns inside it are createListbox(document, { label, options, value, onChange, side?, align? }): a button and a role="listbox" list, exported for your own controls. An option is { value, label?, hint? }. The open list flips above the button or lines up with its end edge when it would leave the viewport. Heddle renders no native select, so the open list follows the host theme too.
Commits made on a detached HEAD do not vanish when you switch back to a branch. The graph keeps drawing them with a detached chip until a branch points at them, and Branch here names them.
Lower-level pieces (graph model)
mountTimeline(host, repo, options)
| Option | Meaning |
|---|---|
onPreview(state, commit) | Called while dragging. HEAD has not moved. |
onCheckout(state, commit) | Called after HEAD moved: drag released, step, undo, branch here. |
onSelect(commit) | The commit shown in the header changed. |
onBranch(name, commit) | "Branch here" created and checked out a branch. |
branchName(commit) | Name for that branch. Default: branch-<short id>. |
theme | "light" or "dark". Default: follow the page. |
label | Accessible name. Default: "History timeline". |
maxTicks | Above this many commits only checkpoint ticks are drawn. Default: 200. |
mountGraph(host, repo, options)
| Option | Meaning |
|---|---|
onSelect(commit) | Click, or Enter on a row. |
onCheckout(state, commit) | After a checkout made from the graph. |
checkoutOnSelect | Check out on a single click. Default: false (double-click checks out). |
rowHeight | Row height in px. Default: 32. |
laneWidth | Maximum lane width in px. Default: 16. |
maxHeight | CSS max-height of the scrolling list. Default: unlimited. |
showDetached | Draw commits made on a detached HEAD that no branch reaches, with a detached chip. Default: true. |
onError(error) | A checkout made from the graph failed. Without it the error is thrown from the event handler. |
performCheckout(commit, target) | Do the checkout yourself. The graph then calls neither repo.checkout nor onCheckout. |
theme, label | As for the timeline. Default label: "History graph". |
Both return { element, update(), destroy() }; the graph adds selected() and select(id). For your own UI, createScrubber(repo) gives positions, checkpoints, preview(index) and seek(index), and layoutGraph(repo.graph()) gives rows, edges and lanes.
import { createRepo } from "heddle";
import { createScrubber, layoutGraph, mountGraph } from "heddle/ui";
const repo = createRepo<{ n: number }>();
repo.commit({ n: 1 }, { message: "One", labels: ["v1"] });
repo.commit({ n: 2 }, { message: "Two" });
const graph = mountGraph(document.querySelector<HTMLElement>("#graph")!, repo, {
checkoutOnSelect: true, // one click checks out; the default is double-click
onCheckout: (state) => console.log(state.n),
maxHeight: "320px",
});
// The models behind the components, for your own UI:
const scrubber = createScrubber(repo);
const preview = scrubber.preview(0).state.n; // 1: look at a position; HEAD stays put
const layout = layoutGraph(repo.graph()); // { rows, edges, lanes } for drawing
graph.destroy();Styling: --heddle-* custom properties
The components take their colours, radius and fonts from custom properties, set on the host or any ancestor. This site maps them to its brand tokens with one rule, which is why the components above match the page in every palette of the theme selector, light and dark. --primary-ink and --on-primary-ink are this site's own tokens: the primary colour, adjusted in a palette whose primary is too faint to draw lines with (Boots light), and the text colour on it. The accent uses them because it draws the scrubber thumb, the outline chips and the selected tab.
The mapping is the whole theme. This site has no rule that targets a .heddle-* class: the listbox button, its popup, the popup shadow, the control height and the active option each have a property. A property marked “follows” takes another property's value until you set it. The root element carries data-heddle-model and, when a theme is forced, data-heddle-theme; the classes and other attributes inside a component are not a styling contract.
:root {
--heddle-bg: var(--surface);
--heddle-fg: var(--ink);
--heddle-muted: var(--muted);
--heddle-border: var(--line);
--heddle-accent: var(--primary-ink);
--heddle-accent-fg: var(--on-primary-ink);
--heddle-track: var(--line-strong);
--heddle-tick: var(--muted);
--heddle-checkpoint: var(--warning);
--heddle-hover: color-mix(in oklab, var(--ink) 8%, transparent);
--heddle-focus: var(--focus);
--heddle-lane-1: var(--primary-ink);
--heddle-lane-2: var(--secondary);
--heddle-lane-3: var(--lane);
--heddle-lane-4: var(--warning);
--heddle-lane-5: color-mix(in oklab, var(--secondary) 55%, var(--primary));
--heddle-lane-6: var(--success);
--heddle-radius: var(--r-card);
--heddle-font: var(--font-body);
--heddle-font-mono: var(--font-mono);
--heddle-control-height: 36px;
--heddle-control-bg: var(--bg);
--heddle-control-border: var(--line-strong);
--heddle-control-radius: var(--r-control);
--heddle-popup-bg: var(--surface);
--heddle-popup-radius: calc(var(--r-control) + 2px);
--heddle-popup-shadow: var(--shadow);
--heddle-popup-z: 30;
--heddle-active: color-mix(in oklab, var(--primary) 14%, var(--surface));
}| Property | Light default | Dark default | Used for | This site sets |
|---|---|---|---|---|
--heddle-bg | #fbf8f1 | #1c1917 | component background | var(--surface) |
--heddle-fg | #1a1714 | #f3eee4 | text | var(--ink) |
--heddle-muted | #6b6259 | #a89f93 | secondary text, ids | var(--muted) |
--heddle-border | #ddd5c6 | #3a3530 | borders and dividers | var(--line) |
--heddle-accent | #b4442a | #e8795c | thumb, current commit, primary lane | var(--primary-ink) |
--heddle-accent-fg | #ffffff | #1c1917 | text on accent | var(--on-primary-ink) |
--heddle-track | #ddd5c6 | #3a3530 | scrubber track | var(--line-strong) |
--heddle-tick | #8a8076 | #7d756b | commit tick marks | var(--muted) |
--heddle-checkpoint | #c98a0c | #e0a526 | labelled (checkpoint) ticks and badges | var(--warning) |
--heddle-hover | rgba(26,23,20,.06) | rgba(243,238,228,.08) | hover and selected row background | color-mix(in oklab, var(--ink) 8%, transparent) |
--heddle-focus | #33505c | #9cc3d3 | focus ring | var(--focus) |
--heddle-lane-1 | #b4442a | #e8795c | graph lane colour 1 | var(--primary-ink) |
--heddle-lane-2 | #33505c | #8fb8c9 | graph lane colour 2 | var(--secondary) |
--heddle-lane-3 | #6e8b5e | #9dbb8c | graph lane colour 3 | var(--lane) |
--heddle-lane-4 | #a86a12 | #e0a526 | graph lane colour 4 | var(--warning) |
--heddle-lane-5 | #7a4f8a | #c39ad3 | graph lane colour 5 | color-mix(in oklab, var(--secondary) 55%, var(--primary)) |
--heddle-lane-6 | #3f7350 | #7fc095 | graph lane colour 6 | var(--success) |
--heddle-radius | 8px | same | corner radius | var(--r-card) |
--heddle-font | system-ui, -apple-system, 'Segoe UI', sans-serif | same | font family | var(--font-body) |
--heddle-font-mono | ui-monospace, 'SF Mono', Menlo, Consolas, monospace | same | font for ids | var(--font-mono) |
--heddle-font-size | 14px | same | base font size | default |
--heddle-padding | 12px | same | inner padding | default |
--heddle-control-height | 32px | same | minimum height of buttons, listbox buttons and inputs | 36px |
--heddle-control-bg | follows --heddle-bg | same | listbox button and input background | var(--bg) |
--heddle-control-border | follows --heddle-border | same | border of buttons, listbox buttons and inputs | var(--line-strong) |
--heddle-control-radius | follows calc(--heddle-radius * .75) | same | corner radius of buttons, listbox buttons and inputs | var(--r-control) |
--heddle-popup-bg | follows --heddle-bg | same | listbox popup background | var(--surface) |
--heddle-popup-border | follows --heddle-control-border | same | listbox popup border | default |
--heddle-popup-radius | follows --heddle-control-radius | same | listbox popup corner radius | calc(var(--r-control) + 2px) |
--heddle-popup-shadow | 0 6px 20px rgba(26,23,20,.16) | 0 6px 20px rgba(0,0,0,.5) | listbox popup shadow | var(--shadow) |
--heddle-popup-z | 10 | same | listbox popup z-index | 30 |
--heddle-active | follows --heddle-hover | same | background of the active (keyboard or hovered) listbox option | color-mix(in oklab, var(--primary) 14%, var(--surface)) |
The five rules, with real inputs
Each tab runs the library. Change the inputs and watch the ids, counts and results move. Rules 1, 2 and 5 hold in both models. Rules 3 and 4 need the graph model.
A commit's id is a hash of its content
The id is the hash of the state tree, the ordered parents, the op log and the provenance. The message, labels and time are kept outside it. Two repositories that never met give the same content the same id. Edit either side: the ids are recomputed on every keystroke.
This figure is live. It needs JavaScript, which has not run.
Show the code
import { createRepo } from "heddle";
const a = createRepo<{ n: number }>();
const b = createRepo<{ n: number }>();
const x = a.commit({ n: 1 }, { message: "First", labels: ["v1"], time: 1 });
const y = b.commit({ n: 1 }, { message: "Other words", time: 2 });
const sameId = x.id === y.id; // true: message, labels and time are outside the id
const z = b.commit({ n: 2 });
const w = a.commit({ n: 3 });
const differs = z.id !== w.id; // true: different content, different idUnchanged parts are stored once
The state is stored as a tree of nodes, each named by its hash. A commit that changes one value writes new nodes only on the path from that value up to the root. Press an edit: new nodes are marked, and the counts come from the store.
This figure is live. It needs JavaScript, which has not run.
Show the code
import { createRepo } from "heddle";
const repo = createRepo();
const doc = {
title: "Plan",
layers: {
sky: { colour: "blue", shapes: ["cloud"] },
sea: { colour: "teal", shapes: ["boat"] },
},
};
repo.commit(doc);
const before = repo.objectCount(); // 9
doc.layers.sky.colour = "black"; // one value, three levels down
repo.commit(doc);
const added = repo.objectCount() - before; // 4: root, layers, sky and the commit. The sea is reused.Lift only the threads you choose
restore(from, part) brings one part back from any commit, as a new commit. Nothing outside the part changes, and the new commit records where the part came from. Pick an earlier commit and a part: the list shows which paths changed and which did not.
This figure is live. It needs JavaScript, which has not run.
Show the code
import { createRepo } from "heddle";
type Doc = { title: string; style: { font: string }; layers: Record<string, { colour: string }> };
const repo = createRepo<Doc>({
parts: {
style: "/style", // a fixed part
layer: (id) => `/layers/${id}`, // a parameterised part: "layer:sky"
},
});
const old = repo.commit({ title: "A", style: { font: "serif" }, layers: { sky: { colour: "blue" } } });
repo.commit({ title: "B", style: { font: "mono" }, layers: { sky: { colour: "black" } } });
const c = repo.restore(old.id, "layer:sky"); // or "style", or a JSON Pointer such as "/layers/sky"
const kind = c.kind; // "restore", with c.from and c.part recorded
const now = repo.state();
// { layers: { sky: { colour: "blue" } }, style: { font: "mono" }, title: "B" }Merges are explicit about conflicts
Objects merge key by key. If both branches changed the same path to different values, merge returns the conflicts and commits nothing. A strategy per path ("ours", "theirs" or a function) settles them, and the choice is recorded in the merge commit.
This figure is live. It needs JavaScript, which has not run.
Show the code
import { createRepo } from "heddle";
type Doc = { title: string; sky: string };
const repo = createRepo<Doc>();
repo.commit({ title: "Poster", sky: "blue" });
repo.branch("idea", { checkout: true });
repo.commit({ title: "Poster", sky: "black" });
repo.checkout("main");
repo.commit({ title: "Poster", sky: "gold" });
const first = repo.merge("idea");
// { status: "conflict", conflicts: [{ pointer: "/sky", base: "blue", ours: "gold", theirs: "black" }] }
// Nothing was committed. Settle it per path:
const second = repo.merge("idea", { strategies: { "/sky": "theirs" } });
const sky = repo.state().sky; // "black"; the resolution is recorded in the merge commitHistory can be replayed and checked
A commit can carry the ops that produced it. verify() rehashes the stored objects, replays each op log from the parent state and compares the result with what was committed. Add a commit whose log is false, or edit a stored log, and run it again.
This figure is live. It needs JavaScript, which has not run.
Show the code
import { createRepo } from "heddle";
type Ledger = { total: number };
const repo = createRepo<Ledger>({
ops: { add: (s, a: { by: number }) => ({ total: s.total + a.by }) },
});
repo.commit({ total: 0 }); // a snapshot: no log to replay
repo.apply([{ op: "add", args: { by: 2 } }]); // the op computes the state
const good = repo.verify(); // { ok: true, checked: 1, skipped: 1 }
// A commit whose log does not explain its state:
const lie = repo.commit({ total: 9 }, { ops: [{ op: "add", args: { by: 1 } }] });
const bad = repo.verify();
// { ok: false, commit: lie.id, reason: "tree-mismatch", ... }Multiplayer sync
heddle/sync is a small entry with no transport in it: a last-writer-wins register, edit and join. On state keyed by id, that is a state-based CRDT kept in a Heddle history. The whiteboard on the home page makes these calls.
A CRDT's parts, on a Heddle history
| CRDT part | On a Heddle history | Why it works |
|---|---|---|
| Add-wins map | An object keyed by ids no two peers can both mint, such as "ann7". | Objects merge key by key, so two people adding different things never conflict. |
| Last-writer-wins register | Register<T> from heddle/sync: the array [clock, peer, value]. | An array merges as one value. Two writes to it are one conflict, handed to your strategy with both arrays. |
| Logical clock | edit() stamps every write with one more than clockOf(state). | No wall clock is involved. A later write always carries a higher number than the writes it saw. |
| Merge function | join(), which merges with lastWriterWins: the higher [clock, peer] is kept. | The same inputs give the same answer on every device, in either order. The choice is recorded in the merge commit. |
| Tombstone | A register such as gone: write(true). Never delete the key. | A deleted key and an edited key would be a conflict with nothing to compare. A register is one more last-writer-wins field. |
| Delta | exportBundle({ have: [lastAgreedCommit] }) | Objects reachable from the commits in have are left out. An edit to one shape sends the nodes it changed and the path above them, not the board. |
| Causal history | The commit graph. | merge finds the common ancestor itself, so no version vector is kept in the state. |
| Convergence check | Compare commit ids. | An id is a hash of the content. Two copies with the same id hold the same state and the same history. |
| Presence | A stream from heddle/stream, beside the history. | Cursors, selections and who is typing are ticks: pushed, read by time, sent as chunks and never committed. |
The whole pattern
Two things are yours: the state shape and the transport. The run at the end has two people drag the same shape before either syncs. Nothing is lost, and all three copies end on one commit id.
| Export | Does |
|---|---|
Register<T> | The type of a last-writer-wins register: [clock, peer, value], stored as a plain JSON array. |
edit(repo, peer, change, options?) | Calls change(state, write, clock) and commits the result with provenance { by: peer }. write(value) makes a register stamped with the peer and a clock one past every clock in the state. |
join(repo, bundle, from, options?) | Imports the bundle. A branch that diverged is merged with lastWriterWins, after any strategies in options. Returns { objects, changed, merges, settled, conflicts, parked }. |
lastWriterWins | The merge strategy join uses: the higher clock wins and the peer name breaks a tie. A conflict that is not between two registers is left unresolved. |
clockOf(value), isRegister(value), compareRegisters(a, b) | The highest register clock in a value. Whether a value has the register shape. Which of two registers was written later. |
import { type Repo, createRepo } from "heddle";
import { type Register, edit, join } from "heddle/sync";
// 1. Shape the state so it merges by itself. Things live in a map, under ids no two peers can both
// mint. A field two people may change at once is a register: [clock, peer, value].
type Shape = { kind: string; at: Register<[x: number, y: number]>; colour: Register<string> };
type Board = { shapes: Record<string, Shape> };
// 2. Carry the bundles. Here the transport is a function call and the relay is a history in the same
// process. Push what the room lacks, pull what we lack: `have` keeps both bundles small.
// Only the room ever merges, so every copy ends on the same commit id.
function sync(peer: Repo<Board>, name: string, room: Repo<Board>, agreed: string): string {
join(room, peer.exportBundle({ have: [agreed] }), name); // diverged? merged, last writer wins
join(peer, room.exportBundle({ have: [peer.head().commit!] }), "room"); // always a fast-forward
return peer.head().commit!; // what both sides hold now: pass it as `agreed` next time
}
const room = createRepo<Board>();
room.commit({ shapes: {} }, { message: "Open the board" });
const [ann, ben] = [createRepo<Board>(), createRepo<Board>()];
for (const peer of [ann, ben]) peer.importBundle(room.exportBundle({ reflog: true }), { restore: true });
const start = room.head().commit!;
// 3. An edit is a commit. `write` stamps a value with the peer and a clock one past every clock this copy has seen.
edit(ann, "ann", (board, write) => void (board.shapes.a1 = { kind: "circle", at: write([40, 40]), colour: write("pink") }));
let annAt = sync(ann, "ann", room, start);
let benAt = sync(ben, "ben", room, start);
// Both drag a1 before either syncs. Ben's is the later write: he also recoloured it first.
edit(ann, "ann", (board, write) => void (board.shapes.a1!.at = write([200, 60])));
edit(ben, "ben", (board, write) => void (board.shapes.a1!.colour = write("cyan")));
edit(ben, "ben", (board, write) => void (board.shapes.a1!.at = write([90, 150])));
annAt = sync(ann, "ann", room, annAt);
benAt = sync(ben, "ben", room, benAt); // the room merges here: /shapes/a1/at goes to Ben
annAt = sync(ann, "ann", room, annAt);
const a1 = room.state().shapes.a1!; // at [3, "ben", [90, 150]], colour [2, "ben", "cyan"]: nothing was dropped
const same = annAt === benAt && benAt === room.head().commit; // true: three copies, one commit idTwo ways to wire it
Through a relay
Each device pushes to one room and pulls from it. Only the room merges, so every device fast-forwards to the room's line and all copies share one commit id. The room is a Heddle history on your server, or on whichever player is the host. This is what the sample and the whiteboard do.
Peer to peer
Every device takes bundles from every other and merges for itself. The rule is the same in either order, so all copies reach the same state and the same tree id. Their commit ids differ until one peer's merge commit has reached the others, because each merge commit names its own parents.
have is what keeps a bundle small: pass the commit both sides held after the last exchange. A commit id the sender does not know is ignored, so a stale value costs bytes and never correctness. importBundle rehashes every object it is given, so a relay cannot hand a device a commit that does not match its id.
Where it stops
- No transport. heddle/sync has no sockets and no timers. The relay is yours: a WebSocket server, WebRTC, or a file both sides can reach. Decide there who may push.
- One shape of register array. clockOf scans the state for arrays shaped [non-negative integer, string, x]. Keep no other arrays of that shape in synced state, or they are read as clocks.
- Other conflicts are still yours. Two writes to a plain value that is not a register are a normal conflict. join commits nothing for that branch, returns the conflicts and leaves the tip parked for a merge with your own strategies.
- Commit per gesture, not per pointer move. Every commit hashes the whole state. Commit when a drag ends, a shape lands or a field loses focus. What happens during the gesture is a tick: push it to a stream.
- Text needs a sequence type. Last writer wins replaces a whole value, which is right for a position or a colour and wrong for two people typing in one paragraph. Use a sequence CRDT for that text and commit its snapshots.
- History grows with every edit. Nothing is dropped, which is what makes a session replayable. A long-lived room needs a policy: start a new history from a snapshot, or keep the full one on the server only.
- Game ticks are not commits. Sixty updates a second go in a stream, or in your netcode. A history fits the layer above: the level, the inventory, the things players build and expect to keep.
Stream: ticks by time
heddle/stream is the third model. linear and graph version a state, one commit per decision. A stream keeps values that arrive many times a second: cursors, selections, samples, prices.
import { createStream } from "heddle/stream";
// Ticks, not decisions: values that arrive many times a second and are read by time.
// A stream hashes nothing and commits nothing. Each channel keeps its newest `capacity` ticks.
const presence = createStream<{ x: number; y: number }>({ capacity: 2000 });
presence.push("ann", { x: 40, y: 12 }, 1000); // channel, value, time in ms (default: the clock)
presence.push("ann", { x: 48, y: 15 }, 1016);
presence.push("ben", { x: 300, y: 90 }, 1020);
const then = presence.at("ann", 1010)!.v; // { x: 40, y: 12 }: where Ann's cursor was at that time
const delta = presence.exportChunk({ since: { ann: 1000 } }); // plain JSON for your transport, later ticks only
// { format: "heddle-stream", version: 1, channels: { ann: [[1016, { x: 48, y: 15 }]], ben: [[1020, { x: 300, y: 90 }]] } }
// The same model for a price feed: buckets() turns ticks into candles.
const feed = createStream<number>();
for (const [t, price] of [[0, 10], [200, 14], [900, 9], [1000, 11], [1999, 12]]) feed.push("btc", price!, t);
const candles = feed.buckets("btc", 1000).map((c) => [c.open, c.high, c.low, c.close]);
// [[10, 14, 9, 9], [11, 12, 11, 12]]| Call | Does |
|---|---|
createStream<T>({ capacity?, now? }) | A stream of ticks in named channels. capacity is the ticks kept per channel (default 10,000). now is the clock for a push with no time (default Date.now). |
push(channel, value, t?) | Add a tick. No hash and no commit. A tick at a time the channel already has replaces it, and an earlier time is put in order. |
at(channel, t), latest(channel) | The newest tick at or before a time: the value that was current then. The newest tick of all. |
range(channel, from?, to?) | Ticks between two times, both included, oldest first. |
buckets(channel, ms, { from?, to?, value? }) | Ticks grouped into spans of ms, each with n, first, last and open, high, low, close taken through value. Empty spans are left out. |
exportChunk({ since?, channels? }), importChunk(chunk), cursor() | Plain JSON for your transport. since is a time for all channels or a time per channel, and cursor() returns the newest time per channel to pass back as since. Importing a chunk twice changes nothing. |
channels(), length(channel?), dropped(channel?), clear(channel?), subscribe(fn) | Channel names. Ticks held. Ticks dropped for being over capacity. Drop ticks. fn gets { type, channel, tick } after every change. |
What it is not
A stream is not a history. Nothing is hashed, so there is no commit id, no branch, no merge and no verify(). Ticks past a channel's capacity are gone. If a span of ticks has to last, read it with range() and commit it to a history as one value.
Sync
exportChunk({ since }) and importChunk are the stream's bundles: plain JSON, sent by your app. A tick is identified by its channel and time, so importing a chunk twice changes nothing. Give each writer its own channel (a peer's name, a feed's symbol) and any two streams that have seen the same chunks are equal.
New in 0.5 to 0.8
Remotes, array-aware merges, async storage and chunked arrays. Each is opt-in: a history that uses none of them behaves and stores exactly as in 0.4. The upgrade notes are docs/UPGRADE-0.5.md to docs/UPGRADE-0.8.md in the Heddle repository.
Remotes: fetch, pull and push graph model · 0.5
A remote is a name and a transport your app supplies. Heddle does no networking. serveRepo(repo) turns a repository into a transport, answerRequest answers one transport request as plain JSON on your server, and requestTransport(send) is the client side over any channel. fetch brings only the objects you lack and moves only origin/* refs. pull is fetch plus merge. push is a compare-and-set fast-forward: if someone pushed first it answers stale, and you pull, then push again. There is no force push.
import { answerRequest, createRepo, requestTransport, serveRepo, type TransportRequest } from "heddle";
type Board = { title: string; notes: Record<string, string> };
// Server: one hub repository and one route. answerRequest never throws: errors become JSON.
const hub = createRepo<Board>();
const served = serveRepo(hub);
const route = async (body: string) => JSON.stringify(await answerRequest(served, JSON.parse(body)));
// Client: a transport whose calls go through that route. Swap `route` for fetch("/heddle", ...).
const send = async (r: TransportRequest) => JSON.parse(await route(JSON.stringify(r)));
const ann = createRepo<Board>();
const ben = createRepo<Board>();
ann.remote.add("origin", requestTransport(send));
ben.remote.add("origin", requestTransport(send));
ann.commit({ title: "Plan", notes: {} });
await ann.push("origin"); // { status: "pushed", branch: "main", ... }
await ben.pull("origin"); // an empty history takes the hub's branch as it is
ben.commit({ title: "Plan", notes: { b1: "Fix the shuttle" } });
await ben.push("origin");
ann.commit({ title: "Plan", notes: { a1: "Buy thread" } });
const late = await ann.push("origin"); // { status: "rejected", reason: "stale" }: Ben pushed first
const pulled = await ann.pull("origin"); // fetch, then merge: different notes merge cleanly
const again = await ann.push("origin"); // { status: "pushed" }Pass merge options to pull as you would to merge: strategies, arrays, or strategy: lastWriterWins from heddle/sync. serveRepo(repo, { readOnly, accept }) refuses every push, or one ref move at a time. The remote names are stored with the history; call remote.add again each time the app opens it.
Array rules graph model · 0.6
Without a rule an array is one value, so two different edits to it are one conflict. arrays names JSON Pointer patterns, on createRepo for every merge, pull and revert, or per call. "sequence" is for lists without ids (tags, points, text runs): edits in different places merge, and insertions at the same place keep both. { key: "id" } is for lists of records: each record merges field by field, adds and removes merge, and a conflict names the record, as in /shapes/s1/colour.
import { createRepo } from "heddle";
type Shape = { id: string; colour: string };
type Board = { tags: string[]; shapes: Shape[] };
// Opt in per JSON Pointer pattern. Without a rule an array is one value: two edits, one conflict.
const repo = createRepo<Board>({ arrays: { "/tags": "sequence", "/shapes": { key: "id" } } });
repo.commit({ tags: ["draft"], shapes: [{ id: "s1", colour: "red" }, { id: "s2", colour: "blue" }] });
repo.branch("ben", { checkout: true });
repo.commit({ tags: ["draft", "night"], shapes: [{ id: "s1", colour: "red" }, { id: "s2", colour: "navy" }] });
repo.checkout("main");
repo.commit({ tags: ["urgent", "draft"], shapes: [{ id: "s1", colour: "gold" }, { id: "s2", colour: "blue" }, { id: "s3", colour: "green" }] });
const result = repo.merge("ben"); // "merged": no conflict
const state = repo.state();
// tags: ["urgent", "draft", "night"] both insertions kept, in place
// shapes: s1 gold, s2 navy, s3 green records merged field by field, by idThe rules used are recorded in the merge or revert commit, so verify() replays them whatever the history is opened with. Keep heddle/sync registers out of rules: they must merge as one value.
Async storage both models · 0.7
The core reads and writes synchronously. cachedStore(adapter) puts an async backend behind it: it loads the history once, answers reads from memory and writes each change back in the background, batched and in order. indexedDbAdapter(name) from heddle/indexeddb writes each batch in one transaction. keyValueAdapter(kv, { prefix }) wraps any { get, set, delete, list } service. Unlike autosave, only new objects and moved refs are written, and the 5 MB localStorage limit does not apply.
import { cachedStore, createRepo, keyValueAdapter } from "heddle";
import { indexedDbAdapter } from "heddle/indexeddb";
type Board = { title: string };
// In a browser: IndexedDB, one transaction per batch of writes.
const store = await cachedStore(indexedDbAdapter("board-42"), { delay: 50 });
const repo = createRepo<Board>({ store }); // or createHistory({ model: "linear", store })
repo.commit({ title: "Draft" }); // returns at once; the write follows in the background
repo.commit({ title: "Final" });
await store.flush(); // before the page goes away, or to surface a write error
await store.close();
// Opened again later: the history, its branches and HEAD are there.
const again = createRepo<Board>({ store: await cachedStore(indexedDbAdapter("board-42")) });
const title = again.state().title; // "Final"
// Any { get, set, delete, list(prefix) } service works the same way: Cloudflare KV, localForage, Redis.
const map = new Map<string, string>();
const kv = {
get: async (k: string) => map.get(k),
set: async (k: string, v: string) => void map.set(k, v),
delete: async (k: string) => void map.delete(k),
list: async (prefix: string) => [...map.keys()].filter((k) => k.startsWith(prefix)),
};
const remote = await cachedStore(keyValueAdapter(kv, { prefix: "board-42:" }));
createRepo<Board>({ store: remote }).commit({ title: "On the server" });
await remote.flush();A failed write stays queued: store.error holds it and flush() rejects until the backend takes it. Flush on pagehide. One history should have one writer, so two tabs share a document through remotes, not through one database.
Long arrays: chunkArrays both models · 0.8
By default an array is one stored node, so one changed point in a 50,000-point stroke writes the whole list again. With chunkArrays: true, arrays longer than 256 entries are stored as content-defined chunks of about 64 entries. An append or a mid-list edit writes a chunk or two and the nodes above them. The same array always gets the same chunks, so one value still has one id.
import { createRepo, memoryStore } from "heddle";
type Track = { points: number[] };
const points = Array.from({ length: 50_000 }, (_, i) => i);
// Count the bytes a commit writes, with and without chunking.
function written(chunkArrays: boolean): number {
const store = memoryStore();
let bytes = 0;
const set = store.set.bind(store);
store.set = (ns, key, value) => { bytes += value.length; set(ns, key, value); };
const repo = createRepo<Track>({ store, chunkArrays });
repo.commit({ points });
bytes = 0;
const next = [...points, 50_000]; // one append
next[25_000] = -1; // and one edit in the middle
repo.commit({ points: next });
return bytes;
}
const flat = written(false); // hundreds of kilobytes: the whole list again
const chunked = written(true); // a few kilobytes: two chunks and the nodes above them
// Reading, diffs, merges and restores still see one ordinary array.It is safe on an existing store: old commits keep their flat arrays and still verify. Stores and bundles that hold chunks can be read only by Heddle 0.8.0 or later, and such bundles are version: 2, so move every device to 0.8.0 before turning it on. It combines with array rules: { chunkArrays: true, arrays: { "/rows": { key: "id" } } }.
The graph model is git's model, for your app
This table is about model: "graph" only. If you know git, you know the graph model: the files are your state, and the working tree is what your app shows. createRepo() is the same call as createHistory({ model: "graph" }). The linear model needs none of this.
| git | Heddle, graph model | What your user sees |
|---|---|---|
git init | createHistory({ model: "graph" }) | Nothing yet. History starts empty. |
git commit | repo.commit(state, { message }) | A new tick on the timeline. |
git log | repo.log(), repo.graph() | The commit list and the history graph. |
git checkout <commit> | repo.checkout(id) | The app shows that earlier state. The scrubber thumb moves. |
git reflog, then go back | repo.undoCheckout() | They are back where they were before the checkout. |
git switch -c <name> | repo.branch(name, { checkout: true }) | A new lane in the graph. Main is untouched. |
git tag | repo.label(target, "v1") | A taller checkpoint tick and a label chip. |
git diff | repo.diff(from, to) | A list of changed paths with old and new values. |
git revert | repo.revert(id) | A new commit that undoes one earlier change. |
git checkout <commit> -- <path> | repo.restore(id, part) | One part goes back. Everything else stays. |
git merge | repo.merge(branch, { strategies }) | Two lanes join. Conflicts are listed, never guessed. |
git fsck | repo.verify() | A pass, or the first commit that fails. |
git bundle | repo.exportBundle(), repo.importBundle(bundle) | The same history on another device or peer. |
git remote add | repo.remote.add("origin", transport) | Nothing yet. The app chooses the transport. |
git fetch, git pull | await repo.fetch("origin"), await repo.pull("origin") | Other people's commits arrive and merge in. |
git push | await repo.push("origin") | Their commits reach the shared copy, or a pull comes first. |
git gc | repo.gc() | Nothing. Unreachable objects are dropped. |
Reference
Install
Heddle 0.8.0 is not on a registry. Build the tarball in the Heddle repository and add it to your app. The package ships TypeScript sources, and your bundler (Bun, Vite, esbuild) compiles them.
bun run pack # in the heddle repo: writes dist/heddle-0.8.0.tgz
bun add /path/to/heddle/dist/heddle-0.8.0.tgz # in your app| Import | Contents | Runs in |
|---|---|---|
heddle | createHistory, createRepo, CAPABILITIES, errors, canonical JSON, sha256, memory store, saveHistory, loadHistory, autosave, cachedStore, keyValueAdapter, serveRepo, answerRequest, requestTransport | browser, Bun, Node |
heddle/ui | mountHistory, createListbox, layoutGraph, createScrubber, mountTimeline, mountGraph | browser (the models run anywhere) |
heddle/sync | edit, join, lastWriterWins, Register, clockOf: live sync over bundles | browser, Bun, Node |
heddle/stream | createStream: ticks by time, candles and chunks | browser, Bun, Node |
heddle/lab | Script, replay, compareTurns, runAll, buildCheckin, bench: the test lab | browser, Bun, Node |
heddle/sqlite | sqliteStore | Bun only |
heddle/indexeddb | indexedDbAdapter: an async backend for cachedStore | browser (any IndexedDB) |
heddle/testing | stubHost, StubDocument, StubElement: the DOM stand-in the component tests use, for testing your own code that mounts them | any test runner |
Linear API
createHistory<S>({ model: "linear", store?, ops?, hash?, now?, chunkArrays? }) returns a LinearHistory<S>. A target is an index (0 is the oldest commit), a commit id or a unique id prefix on the line. The first commit is the baseline, so canUndo is false there. This is the whole API.
| Method | Does |
|---|---|
commit(state, options?), apply(ops, options?) | New commit at the current position. After an undo, the commits that were ahead leave the line and are parked under undone/<n>. |
undo(steps?), redo(steps?), canUndo, canRedo | Move the position back or forward and return that state. No commit is written. Throws E_NOTHING_TO_UNDO or E_NOTHING_TO_REDO at the ends. |
goto(target) | Move to any point: an index (0 is the oldest commit), a commit id or a unique id prefix. |
state(target?), get(target?), index(), length(), log() | Read without moving. log() is oldest first, so log()[i] is index i. |
diff(from, to?) | JSON-path changes between two points. |
label(target, ...labels) | Named checkpoints. The commit id does not change. |
verify(), exportBundle(), subscribe(fn) | Check hashes and replay op logs (parked tails included). Export everything as plain JSON. fn gets { type, index, commit } after every change. |
Graph API
createHistory<S>({ model: "graph", ...options }), or createRepo<S>(options?), returns a repository. Options: store, parts, ops, hash, defaultBranch, now, arrays, chunkArrays. A target is a branch name, a commit id, a unique id prefix of four or more hex characters, or "HEAD".
| Method | Does |
|---|---|
commit(state, { ops?, provenance?, message?, labels?, time? }) | New commit on HEAD. ops and provenance are part of the id. message, labels and time are not. |
apply(ops, options?) | Runs registered ops on the HEAD state and commits the result with those ops as its log. |
state(target?) | The state at a target (default HEAD), as a fresh copy you may mutate. |
head() | { branch, commit, detached }. |
get(target?) | One commit: id, tree, parents, ops, provenance, message, labels, time, kind, plus from and part on a restore. |
log({ from?, firstParent?, limit? }) | Newest first. The first-parent path by default. Every ancestor with firstParent: false. |
graph({ detached? }) | Every commit reachable from any branch or HEAD, children before parents, in a deterministic order. With detached: true, also the commits made on a detached HEAD that no branch reaches. |
detachedTips() | Tips of commits made on a detached HEAD that no branch and not HEAD reaches. They stay in the store. branch(name, { at }) gives one a name again. |
branch(name, { at?, checkout? }), branches(), renameBranch(from, to), deleteBranch(name) | Branch management. |
checkout(target) | A branch name attaches HEAD. A commit detaches it. Returns the state. Recorded in the reflog. |
undoCheckout(), canUndoCheckout() | Undo the latest checkout not yet undone. Repeat to walk further back. |
label(target, ...labels) | Add labels (checkpoints) to a commit without changing its id. |
diff(from, to?) | { op: "add" | "remove" | "replace", path, pointer, value?, oldValue? }[]. |
revert(target, options?) | New commit undoing one commit's changes (3-way). Throws E_CONFLICT if later edits overlap, unless a strategy settles them. |
restore(from, part, { ifMissing?, message? }) | Partial restore as a new commit. Nothing outside the part changes. A part that does not exist in the source commit is removed, or with ifMissing: "error" the call throws E_PART_MISSING. |
previewRestore(from, part), previewRevert(target, options?), previewMerge(theirs, options?) | Dry runs: the state the real call would commit, the changes from the current state, and for restore whether the part is missing in the source. They throw what the real call throws. Nothing is written and nothing moves. |
merge(theirs, { strategies?, strategy?, arrays?, fastForward?, message? }) | Returns up-to-date, fast-forward, merged (with commit, state, resolutions) or conflict (with conflicts; nothing is committed). arrays adds array rules for this call, overriding the repository's per pattern. |
mergeBase(a, b) | Best common ancestor id, or null. |
verify({ strict? }) | Rehashes commit objects and replays op logs. { ok: true, checked, skipped }, or the first failing commit with a reason. |
exportBundle({ reflog?, have?, want? }), importBundle(bundle, { restore?, remote? }) | Plain-JSON object bundles for persistence and peer sync. want limits a bundle to what those branches or commits reach. Incoming labels join existing ones. |
remote.add(name, transport), remote.list(), remote.remove(name) | Named remotes. The names are stored, the transports are not: call remote.add each time the app opens the history. Until then list() shows the remote with attached: false. |
fetch(remote), pull(remote, branch?, mergeOptions?), push(remote, branch?) | Async. fetch brings only the objects you lack and moves only <remote>/* refs, which are read-only. pull is fetch plus merge. push is a compare-and-set fast-forward: rejected with reason stale means pull, then push again. |
reflog(), gc(), objectCount() | Reflog entries. Delete unreachable objects. Count stored objects. |
subscribe(fn) | Calls fn({ type, head }) after every change. Returns an unsubscribe function. |
Errors are HeddleError with a stable code, such as E_CONFLICT, E_NO_CHANGE, E_NOT_FOUND, E_NOTHING_TO_UNDO, E_MODEL, E_BAD_BUNDLE, E_REMOTE or E_READ_ONLY.
Limits in 0.8.0
- The model is fixed when the history is created. A linear history has no branch, checkout or merge methods at all. To get them, open the same data as graph. Going back to linear works only while the history is still one line.
- Array rules are opt-in. Without a rule an array merges as one value, so two different edits to it are one conflict. Name the arrays that need more with arrays: "sequence" for lists without ids, { key: "id" } for lists of records. A keyed list with a missing or repeated key falls back to one value.
- One writer per async store. cachedStore loads the whole history into memory when it opens and writes back in the background. Two tabs over one IndexedDB database do not see each other's writes. Share a history between writers with remotes, and flush() before the page goes away.
- autosave writes the whole repository. saveHistory and autosave serialise every object, branch and the reflog as one JSON string on each change. That suits small documents. For long histories use cachedStore over IndexedDB or a key-value service, bundles with have, or SQLite on Bun.
- Each commit hashes the full state. commit takes the whole state and hashes every node of it. Only nodes that are new get written, so storage grows with the change, but the time per commit grows with the state.
- A wide object is rewritten whole. An object is one stored node listing all its keys. One changed entry in an object of thousands of keys writes that list again, and a long history of such edits can take more room than snapshots. Group entries so a change rewrites one small object.
- A stream is not a history. heddle/stream keeps ticks in memory, up to a capacity per channel. It has no persistence helper, no undo and no verify. Commit a span to a history if it has to last.
- Long arrays need chunkArrays. By default an array is one stored node, so changing one item of a very large array writes it again. With chunkArrays: true, arrays over 256 entries are stored in chunks. Stores and bundles that hold chunks are read only by Heddle 0.8.0 or later.
- State must be plain JSON. Finite numbers, plain objects, no undefined inside arrays. Object keys come back in sorted order.
- No transport, and one kind of live merge. Heddle sends nothing: your app carries the bundles or the transport requests. heddle/sync has last-writer-wins registers in maps keyed by id and nothing else: no text sequences, no counters. The Multiplayer sync section has the code.
- Components are tested on a DOM stub, checked in one browser. The component test suite runs against a small DOM stand-in, shipped as heddle/testing for your own tests. This page is where the components run in a real browser. They were checked in Chromium only.
- Remotes bring no network. fetch, pull and push run over a transport your app supplies: serveRepo in memory, or answerRequest and requestTransport over your own route. There is no force push, linear histories have no remotes, and transports are re-attached each time a history is opened.
- Not on a registry. The package is private and ships TypeScript sources. Install it from the local tarball. Your bundler compiles it.
Sizes
Measured by this site's build script on the sources in this repository. Nothing here is estimated.
| What | Minified | Minified + gzip |
|---|---|---|
heddle entry, bundled for the browser | 42,019 bytes | 16,071 bytes |
heddle/ui entry, bundled for the browser | 39,127 bytes | 12,897 bytes |
This page's script (site.js: library, components and all demos) | 242,935 bytes | 86,047 bytes |
This page's stylesheet (site.css) | 99,515 bytes | 19,026 bytes |
dist/heddle-0.8.0.tgz (41 files, TypeScript sources) | n/a | 128,463 bytes |
Library source under src/ | 6,447 lines | n/a |
Other languages: Rust and C++
Heddle 0.8.0 ships one implementation, in TypeScript. There is no Rust or C++ port yet. This section shows why one is small, what it would look like, and how it compares with the history engines those languages already have.
The contract is a file format, not an API
Everything Heddle keeps is JSON named by its hash. An implementation in any language that writes the same bytes for the same state gets the same commit ids, so a history saved by one opens in the other. That is the whole of what a port has to match:
| Part | What it is | SPEC section |
|---|---|---|
| Canonical JSON | Object keys in UTF-8 order, no insignificant whitespace, finite numbers only. | 1, 4.1 |
| One hash function | SHA-256, hex, over the canonical body. An id is the hash of the body it names. | 1 |
| Six object kinds | Object node, array node, blob, commit, op log, provenance: each a two-item JSON array [tag, data]. | 4.1 |
| Five namespaces | obj, meta, ref, head, reflog over any string key-value store. | 4.1 |
| The bundle | One JSON document: format, version 1, objects, meta, refs, head, model. It is the file on disk and the message between peers. | 4.2 |
| Two rules | undone/<n> for a cut tail, and when a history opens as linear or as graph. | 5, 6 |
One detail needs care: numbers are written the way ECMAScript writes them (JSON.stringify), with -0 as 0. A port has to print numbers identically or its ids will differ. The test for a port is simple: load a bundle the TypeScript library wrote, check every hash, write it back, compare the bytes.
{
"format": "heddle-bundle",
"version": 1,
"objects": { "<id>": "<canonical JSON body>" },
"meta": { "<commit id>": { "message": "", "labels": [], "time": 0 } },
"refs": { "<branch>": "<commit id>" },
"head": { "branch": "main", "commit": "<id>", "detached": false },
"model": "linear"
}What works today, without a port
- Exchange bundles. A native core can read a bundle with a JSON parser and SHA-256 alone: follow
refsto a commit, the commit to its tree, the tree to its values. No Heddle code is needed to read a state out of a history. - Keep history where the JavaScript is. The
heddleentry has no DOM and no dependencies, and runs in a browser, Bun and Node. An app with a native core and a web or webview front end can keep history on the front-end side and send the core whole states. - Port it. The model is small because storage, hashing and saving are shared by both history models. The specification is in the repository at
docs/SPEC.md.
What a port would look like
The same calls as the TypeScript API, in each language's idiom. These are sketches to show the shape. They are not shipped and have not been compiled.
// A sketch of a port's surface. Nothing here is shipped.
use heddle::{History, Model};
use serde_json::json;
let mut doc = History::new(Model::Linear);
doc.commit(json!({ "body": "madder", "sleeves": "undyed" }), "Cast on")?;
doc.commit(json!({ "body": "madder", "sleeves": "indigo" }), "Dye the sleeves")?;
doc.undo()?;
// The same JSON the TypeScript library writes and reads.
let bundle: String = doc.export_bundle()?;
let repo = History::import_bundle(&bundle, Model::Graph)?; // a linear history always opens as graph// A sketch of a port's surface. Nothing here is shipped.
#include <heddle/history.hpp>
#include <nlohmann/json.hpp>
auto doc = heddle::history::create(heddle::model::linear);
doc.commit({{"body", "madder"}, {"sleeves", "undyed"}}, "Cast on");
doc.commit({{"body", "madder"}, {"sleeves", "indigo"}}, "Dye the sleeves");
doc.undo();
// The same JSON the TypeScript library writes and reads.
std::string bundle = doc.export_bundle();
auto repo = heddle::history::import_bundle(bundle, heddle::model::graph); // linear always opens as graphNext to the engines Rust and C++ already have
Four well-known ones, by what you hand them and what shape of history you get back.
| Engine | Language | You hand it | History is | How Heddle differs |
|---|---|---|---|---|
| undo (crate) | Rust | An edit that knows how to apply itself and how to undo itself (the command pattern). | Record is one line. History is a tree: editing after an undo starts a branch. | Heddle takes the state, not an edit, so there is no inverse to write. Its line and its graph are the same two shapes, plus content ids, merge and a stored format. |
| QUndoStack | C++ (Qt) | A QUndoCommand with undo() and redo(), pushed on a stack. QUndoView lists the stack. | One stack. Pushing after an undo discards the commands that were undone. | Heddle's linear model is the same shape for the user, but the cut tail is kept under undone/<n> and the history is saved with the document. |
| lager with immer | C++ | Actions through a reducer. The model is an immutable value, shared structurally by immer. | Snapshots of the model. A time-travel debugger steps through them. | The closest in spirit: state as values, unchanged parts shared. Heddle adds ids from content, branches and merge, partial restore and a format another language can read. |
| Automerge | Rust core, C API | Edits to a CRDT document. | A graph of changes, each named by its SHA-256 hash, in a binary format every binding reads. | Automerge merges concurrent edits by itself. Heddle keeps plain JSON, reports a conflict and lets the app choose. Use Automerge for live co-editing of text. Heddle is for versions a person steps through, and it syncs whole values with a rule you write. |
Read from each project's own documentation in November 2026. None of them is a dependency of Heddle, and Heddle has not been benchmarked against them.