@dovetail-ts/crdt-loro 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,28 @@
1
+ # @dovetail-ts/crdt-loro
2
+
3
+ ## 1.0.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 21b3dbf: Publish through OIDC trusted publishing only, with the Ember Workbench release kit. Each version from this release on has npm provenance.
8
+ - Updated dependencies [21b3dbf]
9
+ - @dovetail-ts/crdt@1.0.1
10
+
11
+ ## 1.0.0
12
+
13
+ ### Major Changes
14
+
15
+ - 480744b: First release of Dovetail: real-time and offline sync for Ember.
16
+
17
+ - `@dovetail-ts/core`: the connection life cycle, live store subscriptions, the optimistic ledger with rebase and rollback, the offline write queue in IndexedDB with a leader tab and dead letters, `DocSession` and `PresenceRoom`.
18
+ - `@dovetail-ts/warp-drive`: the store feed into WarpDrive.
19
+ - `@dovetail-ts/crdt`, `crdt-yjs`, `crdt-loro` and `crdt-automerge`: one `DocEngine` interface with three engines.
20
+ - `@dovetail-ts/tiptap`: co-editing in Tiptap 3 with carets, per-user undo, versions and comment threads.
21
+ - `@dovetail-ts/ember`, `notifications` and `inspector`: presence and status components, the inbox, toasts and activity feeds, and a dev panel.
22
+ - `@dovetail-ts/server`, the transports (`transport-ws`, `transport-sse`, `transport-cable`) and `conformance`: a Node server and one wire protocol that the Rails gems also pass.
23
+ - Adapters for Hocuspocus, Liveblocks, PartyKit and Supabase, and integrations for Switchyard, Millwork, Benchdog and Lattice. The Neon adapter is not in 1.0: it waits for a stable Neon Realtime client (1.1).
24
+
25
+ ### Patch Changes
26
+
27
+ - Updated dependencies [480744b]
28
+ - @dovetail-ts/crdt@1.0.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Joe Gaudet
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # @dovetail-ts/crdt-loro
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Loro `DocEngine` of Dovetail, on `loro-crdt`.
4
+
5
+ Part of [Dovetail](https://joegaudet.com/dovetail/). Not released yet.
6
+
7
+ ## Use it
8
+
9
+ ```ts
10
+ import { loroEngine } from '@dovetail-ts/crdt-loro'
11
+
12
+ const engine = loroEngine()
13
+ const handle = engine.create()
14
+ ```
15
+
16
+ - `handle.doc` is the `LoroDoc`. Use `handle.transact(doc => …, origin)` to change it and commit
17
+ the change with an origin.
18
+ - Start a new document on one peer only. The other peers load its snapshot
19
+ (`engine.load(bytes)`) or its updates before they start an editor. Two empty documents that
20
+ both start the content of an editor make two roots, and one of them is lost.
21
+ - For Tiptap, use `loroBinding` from `@dovetail-ts/tiptap/loro`.
22
+
23
+ ## Capabilities
24
+
25
+ All five capabilities are true. Tests prove each one.
26
+
27
+ - `history`: a version keeps the frontiers of the document. `open` uses `forkAt`, and
28
+ `restore` applies the diff back to the version. The comment threads and the versions stay.
29
+ - `undo`: the `UndoManager` of Loro. It undoes the local changes of the document and never the
30
+ changes of peers. It cannot filter the local changes by origin, so `undoScope(origin)` does
31
+ not use `origin`. It does not undo the shared maps (threads and versions). The undo of the
32
+ edit that makes the text of a paragraph also removes the text of peers in that paragraph.
33
+ - `commentAnchors`: Loro cursors in a text root container (`relativePosition(field, index)`).
34
+
35
+ ## The capability matrix
36
+
37
+ | Feature | Yjs (`y-prosemirror`) | Loro (`loro-prosemirror`) | Automerge (`@automerge/prosemirror`) |
38
+ | --------------- | -------------------------- | ------------------------------------------------------ | ---------------------------------------------------------------------------- |
39
+ | Tiptap binding | Yes | Yes (`loroBinding`, `@dovetail-ts/tiptap/loro`) | No: `@automerge/prosemirror` 0.2 makes its own schema, not the Tiptap schema |
40
+ | Remote cursors | Yes | Yes (the caret plugin of `loro-prosemirror`) | No: no Tiptap binding |
41
+ | Per-user undo | Yes (`UndoManager` origin) | Yes (Loro `UndoManager`: local changes, not by origin) | No: Automerge has no undo manager |
42
+ | Version history | Yes (snapshots) | Yes (native: frontiers, `forkAt`, diff) | Yes (native: heads, `view`), engine API only |
43
+ | Comment anchors | Yes (relative positions) | Yes (Loro cursors) | Yes (Automerge cursors), engine API only |
@@ -0,0 +1,46 @@
1
+ import { LoroDoc } from 'loro-crdt';
2
+ import type { LoroEventBatch } from 'loro-crdt';
3
+ import type { DocAwareness, DocEngine, DocHandle, DocVersions, EngineCapabilities, SharedMap, UndoScope } from '@dovetail-ts/crdt';
4
+ export interface LoroEngineOptions {
5
+ /** The clock of the version dates. The default is `Date.now`. */
6
+ now?: () => number;
7
+ }
8
+ /** Makes the Loro engine. */
9
+ export declare function loroEngine(options?: LoroEngineOptions): LoroEngine;
10
+ export declare class LoroEngine implements DocEngine {
11
+ readonly now: () => number;
12
+ readonly name = "loro";
13
+ readonly capabilities: EngineCapabilities;
14
+ constructor(now: () => number);
15
+ create(): LoroDocHandle;
16
+ load(snapshot: Uint8Array): LoroDocHandle;
17
+ }
18
+ /** A Loro document. `doc` is for the Loro bindings (Tiptap). */
19
+ export declare class LoroDocHandle implements DocHandle {
20
+ #private;
21
+ readonly engine: LoroEngine;
22
+ readonly doc: LoroDoc;
23
+ readonly awareness: DocAwareness;
24
+ readonly versions: DocVersions;
25
+ constructor(engine: LoroEngine, doc: LoroDoc);
26
+ /** Runs `change` on the document, and commits it as one change with `origin`. */
27
+ transact(change: (doc: LoroDoc) => void, origin?: unknown, loroOrigin?: string): void;
28
+ applyUpdate(update: Uint8Array, origin?: unknown): void;
29
+ encodeStateVector(): Uint8Array;
30
+ encodeUpdate(stateVector?: Uint8Array): Uint8Array;
31
+ snapshot(): Uint8Array;
32
+ onUpdate(listener: (update: Uint8Array, origin: unknown) => void): () => void;
33
+ map(name: string): SharedMap;
34
+ /** The origin of the change of a Loro event: the `origin` of `transact` or `applyUpdate`. */
35
+ originOf(batch: LoroEventBatch): unknown;
36
+ /**
37
+ * Undo of the local changes. Loro tracks all local changes of this peer and never the merged
38
+ * changes of peers, so one document of one user gives per-user undo. It cannot filter the
39
+ * local changes by `origin`. It does not track the shared maps.
40
+ */
41
+ undoScope(_origin: unknown): UndoScope;
42
+ /** A position in the text `field`. */
43
+ relativePosition(field: string, index: number): Uint8Array;
44
+ absolutePosition(position: Uint8Array): number | null;
45
+ destroy(): void;
46
+ }
package/dist/index.js ADDED
@@ -0,0 +1,194 @@
1
+ import { LoroDoc, VersionVector, UndoManager, Cursor } from 'loro-crdt';
2
+ import { JsonAwareness } from '@dovetail-ts/crdt';
3
+
4
+ // src/index.ts
5
+ function loroEngine(options = {}) {
6
+ return new LoroEngine(options.now ?? Date.now);
7
+ }
8
+ var MAP_ORIGIN = "dovetail:";
9
+ var LoroEngine = class {
10
+ constructor(now) {
11
+ this.now = now;
12
+ }
13
+ now;
14
+ name = "loro";
15
+ capabilities = {
16
+ tiptap: true,
17
+ cursors: true,
18
+ undo: true,
19
+ history: true,
20
+ commentAnchors: true
21
+ };
22
+ create() {
23
+ return new LoroDocHandle(this, new LoroDoc());
24
+ }
25
+ load(snapshot) {
26
+ const handle = this.create();
27
+ handle.doc.import(snapshot);
28
+ return handle;
29
+ }
30
+ };
31
+ var LoroDocHandle = class {
32
+ constructor(engine, doc) {
33
+ this.engine = engine;
34
+ this.doc = doc;
35
+ this.awareness = new JsonAwareness(doc.peerIdStr);
36
+ this.versions = new LoroVersions(this);
37
+ this.#stop = doc.subscribeLocalUpdates((update) => this.#emit(update, this.#origin));
38
+ }
39
+ engine;
40
+ doc;
41
+ awareness;
42
+ versions;
43
+ #listeners = /* @__PURE__ */ new Set();
44
+ #origin = void 0;
45
+ // Loro can send the events of a change after the call that made it (an import in the callback
46
+ // of another document). So the events find their origin from the last commit and import.
47
+ #commit = { tag: "", origin: void 0, count: 0 };
48
+ #imported = void 0;
49
+ #stop;
50
+ /** Runs `change` on the document, and commits it as one change with `origin`. */
51
+ transact(change, origin, loroOrigin) {
52
+ const previous = this.#origin;
53
+ this.#origin = origin;
54
+ const tag = `${loroOrigin ?? "change"}#${++this.#commit.count}`;
55
+ this.#commit = { ...this.#commit, tag, origin };
56
+ try {
57
+ change(this.doc);
58
+ this.doc.commit({ origin: tag });
59
+ } finally {
60
+ this.#origin = previous;
61
+ }
62
+ }
63
+ applyUpdate(update, origin) {
64
+ const previous = this.#origin;
65
+ this.#origin = origin;
66
+ this.#imported = origin;
67
+ try {
68
+ this.doc.import(update);
69
+ } finally {
70
+ this.#origin = previous;
71
+ }
72
+ this.#emit(update, origin);
73
+ }
74
+ encodeStateVector() {
75
+ return this.doc.oplogVersion().encode();
76
+ }
77
+ encodeUpdate(stateVector) {
78
+ const from = stateVector ? VersionVector.decode(stateVector) : void 0;
79
+ return this.doc.export({ mode: "update", from });
80
+ }
81
+ snapshot() {
82
+ return this.doc.export({ mode: "snapshot" });
83
+ }
84
+ onUpdate(listener) {
85
+ this.#listeners.add(listener);
86
+ return () => this.#listeners.delete(listener);
87
+ }
88
+ map(name) {
89
+ const map = this.doc.getMap(name);
90
+ const write = (change, origin) => this.transact(change, origin, `${MAP_ORIGIN}${name}`);
91
+ return {
92
+ get: (key) => map.get(key),
93
+ set: (key, value, origin) => write(() => map.set(key, value), origin),
94
+ delete: (key, origin) => write(() => map.delete(key), origin),
95
+ entries: () => map.entries(),
96
+ onChange: (listener) => map.subscribe((batch) => {
97
+ const keys = batch.events.flatMap(
98
+ (event) => event.diff.type === "map" ? Object.keys(event.diff.updated) : []
99
+ );
100
+ listener(keys, this.originOf(batch));
101
+ })
102
+ };
103
+ }
104
+ /** The origin of the change of a Loro event: the `origin` of `transact` or `applyUpdate`. */
105
+ originOf(batch) {
106
+ if (batch.by === "import") return this.#imported;
107
+ return batch.origin === this.#commit.tag ? this.#commit.origin : void 0;
108
+ }
109
+ /**
110
+ * Undo of the local changes. Loro tracks all local changes of this peer and never the merged
111
+ * changes of peers, so one document of one user gives per-user undo. It cannot filter the
112
+ * local changes by `origin`. It does not track the shared maps.
113
+ */
114
+ undoScope(_origin) {
115
+ const manager = new UndoManager(this.doc, { excludeOriginPrefixes: [MAP_ORIGIN] });
116
+ return {
117
+ undo: () => manager.undo(),
118
+ redo: () => manager.redo(),
119
+ get canUndo() {
120
+ return manager.canUndo();
121
+ },
122
+ get canRedo() {
123
+ return manager.canRedo();
124
+ },
125
+ destroy: () => manager.free()
126
+ };
127
+ }
128
+ /** A position in the text `field`. */
129
+ relativePosition(field, index) {
130
+ const cursor = this.doc.getText(field).getCursor(index);
131
+ if (!cursor) throw new Error(`No position ${index} in the text "${field}".`);
132
+ return cursor.encode();
133
+ }
134
+ absolutePosition(position) {
135
+ return this.doc.getCursorPos(Cursor.decode(position))?.offset ?? null;
136
+ }
137
+ destroy() {
138
+ this.#stop();
139
+ this.#listeners.clear();
140
+ this.awareness.setLocalState(null);
141
+ }
142
+ #emit(update, origin) {
143
+ for (const listener of this.#listeners) listener(update, origin);
144
+ }
145
+ };
146
+ var LoroVersions = class {
147
+ constructor(handle) {
148
+ this.handle = handle;
149
+ }
150
+ handle;
151
+ get #map() {
152
+ return this.handle.map("dovetail:versions");
153
+ }
154
+ list() {
155
+ return this.#map.entries().map(([, value]) => {
156
+ const { id, name, createdAt, by } = value;
157
+ return { id, name, createdAt, by };
158
+ }).sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
159
+ }
160
+ create(options = {}) {
161
+ const { doc, engine } = this.handle;
162
+ doc.commit();
163
+ const count = this.#map.entries().length;
164
+ const version = {
165
+ id: `${doc.peerIdStr}-${count}`,
166
+ name: options.name ?? `Version ${count + 1}`,
167
+ createdAt: new Date(engine.now()).toISOString(),
168
+ by: options.by ?? null
169
+ };
170
+ this.#map.set(version.id, { ...version, frontiers: doc.frontiers() });
171
+ return version;
172
+ }
173
+ open(id) {
174
+ return new LoroDocHandle(this.handle.engine, this.handle.doc.forkAt(this.#frontiers(id)));
175
+ }
176
+ restore(id, origin) {
177
+ const { doc } = this.handle;
178
+ doc.commit();
179
+ const diff = doc.diff(doc.frontiers(), this.#frontiers(id), false).filter(([container]) => !container.startsWith(`cid:root-${MAP_ORIGIN}`));
180
+ this.handle.transact(() => doc.applyDiff(diff), origin);
181
+ }
182
+ onChange(listener) {
183
+ return this.#map.onChange(() => listener());
184
+ }
185
+ #frontiers(id) {
186
+ const stored = this.#map.get(id);
187
+ if (!stored) throw new Error(`No version "${id}" in this document.`);
188
+ return stored.frontiers;
189
+ }
190
+ };
191
+
192
+ export { LoroDocHandle, LoroEngine, loroEngine };
193
+ //# sourceMappingURL=index.js.map
194
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;;AAuBO,SAAS,UAAA,CAAW,OAAA,GAA6B,EAAC,EAAe;AACtE,EAAA,OAAO,IAAI,UAAA,CAAW,OAAA,CAAQ,GAAA,IAAO,KAAK,GAAG,CAAA;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AAwB;AAC1C,IAAA,MAAM,EAAE,GAAA,EAAI,GAAI,IAAA,CAAK,MAAA;AACrB,IAAA,GAAA,CAAI,MAAA,EAAO;AAGX,IAAA,MAAM,IAAA,GAAO,IACV,IAAA,CAAK,GAAA,CAAI,WAAU,EAAG,IAAA,CAAK,UAAA,CAAW,EAAE,CAAA,EAAG,KAAK,EAChD,MAAA,CAAO,CAAC,CAAC,SAAS,CAAA,KAAM,CAAC,UAAU,UAAA,CAAW,CAAA,SAAA,EAAY,UAAU,CAAA,CAAE,CAAC,CAAA;AAC1E,IAAA,IAAA,CAAK,OAAO,QAAA,CAAS,MAAM,IAAI,SAAA,CAAU,IAAI,GAAG,MAAM,CAAA;AAAA,EACxD;AAAA,EAEA,SAAS,QAAA,EAAkC;AACzC,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,QAAA,CAAS,MAAM,UAAU,CAAA;AAAA,EAC5C;AAAA,EAEA,WAAW,EAAA,EAAuB;AAChC,IAAA,MAAM,MAAA,GAAS,IAAA,CAAK,IAAA,CAAK,GAAA,CAAI,EAAE,CAAA;AAC/B,IAAA,IAAI,CAAC,MAAA,EAAQ,MAAM,IAAI,KAAA,CAAM,CAAA,YAAA,EAAe,EAAE,CAAA,mBAAA,CAAqB,CAAA;AACnE,IAAA,OAAO,MAAA,CAAO,SAAA;AAAA,EAChB;AACF,CAAA","file":"index.js","sourcesContent":["// The Loro DocEngine (ADR 0002, ADR 0014). Versions use the native history of Loro (frontiers),\n// and comment anchors use Loro cursors.\nimport { Cursor, LoroDoc, UndoManager, VersionVector } from 'loro-crdt'\nimport type { Frontiers, LoroEventBatch } from 'loro-crdt'\nimport type {\n DocAwareness,\n DocEngine,\n DocHandle,\n DocVersions,\n EngineCapabilities,\n JsonValue,\n SharedMap,\n UndoScope,\n Version,\n} from '@dovetail-ts/crdt'\nimport { JsonAwareness } from '@dovetail-ts/crdt'\n\nexport interface LoroEngineOptions {\n /** The clock of the version dates. The default is `Date.now`. */\n now?: () => number\n}\n\n/** Makes the Loro engine. */\nexport function loroEngine(options: LoroEngineOptions = {}): LoroEngine {\n return new LoroEngine(options.now ?? Date.now)\n}\n\n/** The prefix of the commit origins of the shared maps. Undo scopes do not track them. */\nconst MAP_ORIGIN = 'dovetail:'\n\nexport class LoroEngine implements DocEngine {\n readonly name = 'loro'\n readonly capabilities: EngineCapabilities = {\n tiptap: true,\n cursors: true,\n undo: true,\n history: true,\n commentAnchors: true,\n }\n\n constructor(readonly now: () => number) {}\n\n create(): LoroDocHandle {\n return new LoroDocHandle(this, new LoroDoc())\n }\n\n load(snapshot: Uint8Array): LoroDocHandle {\n const handle = this.create()\n handle.doc.import(snapshot)\n return handle\n }\n}\n\n/** A Loro document. `doc` is for the Loro bindings (Tiptap). */\nexport class LoroDocHandle implements DocHandle {\n readonly awareness: DocAwareness\n readonly versions: DocVersions\n #listeners = new Set<(update: Uint8Array, origin: unknown) => void>()\n #origin: unknown = undefined\n // Loro can send the events of a change after the call that made it (an import in the callback\n // of another document). So the events find their origin from the last commit and import.\n #commit = { tag: '', origin: undefined as unknown, count: 0 }\n #imported: unknown = undefined\n #stop: () => void\n\n constructor(\n readonly engine: LoroEngine,\n readonly doc: LoroDoc,\n ) {\n this.awareness = new JsonAwareness(doc.peerIdStr)\n this.versions = new LoroVersions(this)\n this.#stop = doc.subscribeLocalUpdates(update => this.#emit(update, this.#origin))\n }\n\n /** Runs `change` on the document, and commits it as one change with `origin`. */\n transact(change: (doc: LoroDoc) => void, origin?: unknown, loroOrigin?: string): void {\n const previous = this.#origin\n this.#origin = origin\n const tag = `${loroOrigin ?? 'change'}#${++this.#commit.count}`\n this.#commit = { ...this.#commit, tag, origin }\n try {\n change(this.doc)\n this.doc.commit({ origin: tag })\n } finally {\n this.#origin = previous\n }\n }\n\n applyUpdate(update: Uint8Array, origin?: unknown): void {\n const previous = this.#origin\n this.#origin = origin\n this.#imported = origin\n try {\n this.doc.import(update)\n } finally {\n this.#origin = previous\n }\n this.#emit(update, origin)\n }\n\n encodeStateVector(): Uint8Array {\n return this.doc.oplogVersion().encode()\n }\n\n encodeUpdate(stateVector?: Uint8Array): Uint8Array {\n const from = stateVector ? VersionVector.decode(stateVector) : undefined\n return this.doc.export({ mode: 'update', from })\n }\n\n snapshot(): Uint8Array {\n return this.doc.export({ mode: 'snapshot' })\n }\n\n onUpdate(listener: (update: Uint8Array, origin: unknown) => void): () => void {\n this.#listeners.add(listener)\n return () => this.#listeners.delete(listener)\n }\n\n map(name: string): SharedMap {\n const map = this.doc.getMap(name)\n const write = (change: () => void, origin: unknown) =>\n this.transact(change, origin, `${MAP_ORIGIN}${name}`)\n return {\n get: key => map.get(key) as JsonValue | undefined,\n set: (key, value, origin) => write(() => map.set(key, value), origin),\n delete: (key, origin) => write(() => map.delete(key), origin),\n entries: () => map.entries() as [string, JsonValue][],\n onChange: listener =>\n map.subscribe(batch => {\n const keys = batch.events.flatMap(event =>\n event.diff.type === 'map' ? Object.keys(event.diff.updated) : [],\n )\n listener(keys, this.originOf(batch))\n }),\n }\n }\n\n /** The origin of the change of a Loro event: the `origin` of `transact` or `applyUpdate`. */\n originOf(batch: LoroEventBatch): unknown {\n if (batch.by === 'import') return this.#imported\n return batch.origin === this.#commit.tag ? this.#commit.origin : undefined\n }\n\n /**\n * Undo of the local changes. Loro tracks all local changes of this peer and never the merged\n * changes of peers, so one document of one user gives per-user undo. It cannot filter the\n * local changes by `origin`. It does not track the shared maps.\n */\n undoScope(_origin: unknown): UndoScope {\n const manager = new UndoManager(this.doc, { excludeOriginPrefixes: [MAP_ORIGIN] })\n return {\n undo: () => manager.undo(),\n redo: () => manager.redo(),\n get canUndo() {\n return manager.canUndo()\n },\n get canRedo() {\n return manager.canRedo()\n },\n destroy: () => manager.free(),\n }\n }\n\n /** A position in the text `field`. */\n relativePosition(field: string, index: number): Uint8Array {\n const cursor = this.doc.getText(field).getCursor(index)\n if (!cursor) throw new Error(`No position ${index} in the text \"${field}\".`)\n return cursor.encode()\n }\n\n absolutePosition(position: Uint8Array): number | null {\n return this.doc.getCursorPos(Cursor.decode(position))?.offset ?? null\n }\n\n destroy(): void {\n this.#stop()\n this.#listeners.clear()\n this.awareness.setLocalState(null)\n }\n\n #emit(update: Uint8Array, origin: unknown): void {\n for (const listener of this.#listeners) listener(update, origin)\n }\n}\n\ntype Stored = Version & { frontiers: Frontiers }\n\n/** The versions of a Loro document: the frontiers of each version, in `dovetail:versions`. */\nclass LoroVersions implements DocVersions {\n constructor(readonly handle: LoroDocHandle) {}\n\n get #map(): SharedMap {\n return this.handle.map('dovetail:versions')\n }\n\n list(): Version[] {\n return this.#map\n .entries()\n .map(([, value]) => {\n const { id, name, createdAt, by } = value as unknown as Stored\n return { id, name, createdAt, by }\n })\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id))\n }\n\n create(options: { name?: string; by?: string | null } = {}): Version {\n const { doc, engine } = this.handle\n doc.commit()\n const count = this.#map.entries().length\n const version: Version = {\n id: `${doc.peerIdStr}-${count}`,\n name: options.name ?? `Version ${count + 1}`,\n createdAt: new Date(engine.now()).toISOString(),\n by: options.by ?? null,\n }\n this.#map.set(version.id, { ...version, frontiers: doc.frontiers() })\n return version\n }\n\n open(id: string): DocHandle {\n return new LoroDocHandle(this.handle.engine, this.handle.doc.forkAt(this.#frontiers(id)))\n }\n\n restore(id: string, origin?: unknown): void {\n const { doc } = this.handle\n doc.commit()\n // The diff back to the version, without the `dovetail:` maps: threads and versions stay.\n // They hold JSON values only, so no child container of them is in the diff.\n const diff = doc\n .diff(doc.frontiers(), this.#frontiers(id), false)\n .filter(([container]) => !container.startsWith(`cid:root-${MAP_ORIGIN}`))\n this.handle.transact(() => doc.applyDiff(diff), origin)\n }\n\n onChange(listener: () => void): () => void {\n return this.#map.onChange(() => listener())\n }\n\n #frontiers(id: string): Frontiers {\n const stored = this.#map.get(id) as unknown as Stored | undefined\n if (!stored) throw new Error(`No version \"${id}\" in this document.`)\n return stored.frontiers\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@dovetail-ts/crdt-loro",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.1",
4
+ "description": "The Loro DocEngine.",
5
+ "license": "MIT",
6
+ "author": "Joe Gaudet <joe@joegaudet.com>",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/joegaudet/dovetail.git",
10
+ "directory": "packages/crdt-loro"
11
+ },
12
+ "homepage": "https://joegaudet.com/dovetail/",
13
+ "bugs": "https://github.com/joegaudet/dovetail/issues",
14
+ "keywords": [
15
+ "realtime",
16
+ "offline",
17
+ "sync",
18
+ "crdt"
19
+ ],
20
+ "type": "module",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ },
27
+ "./package.json": "./package.json"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "CHANGELOG.md",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "sideEffects": false,
36
+ "dependencies": {
37
+ "@dovetail-ts/crdt": "1.0.1",
38
+ "loro-crdt": "^1.19.1"
39
+ },
40
+ "devDependencies": {
41
+ "tsup": "^8.5.1"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "engines": {
47
+ "node": ">=22.12.0"
48
+ },
49
+ "scripts": {
50
+ "build": "tsc --build --force && tsup"
51
+ }
6
52
  }