@dovetail-ts/crdt-yjs 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-yjs
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,65 @@
1
- # Temporary Holding Version
1
+ # @dovetail-ts/crdt-yjs
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 Yjs `DocEngine` of Dovetail. Yjs is the reference engine. It has all the capabilities:
4
+ the Tiptap binding, remote cursors, per-user undo, version history and comment anchors.
5
+
6
+ Part of [Dovetail](https://joegaudet.com/dovetail/). Not released yet.
7
+
8
+ ## Make a document
9
+
10
+ ```ts
11
+ import { yjsEngine } from '@dovetail-ts/crdt-yjs'
12
+
13
+ const engine = yjsEngine()
14
+ const handle = engine.create()
15
+ const copy = engine.load(handle.snapshot())
16
+ ```
17
+
18
+ `handle.doc` is the `Y.Doc`. `handle.yAwareness` is the y-protocols `Awareness` of that document.
19
+ Use them only for Yjs bindings. All other code uses the `DocHandle` interface of
20
+ `@dovetail-ts/crdt`.
21
+
22
+ ## Sync
23
+
24
+ The `doc-sync` and `doc-update` messages of the protocol carry the bytes of these calls:
25
+
26
+ ```ts
27
+ import { applySyncStep, syncStep1 } from '@dovetail-ts/crdt'
28
+
29
+ send(syncStep1(handle)) // step 1: the state vector
30
+ const answer = applySyncStep(handle, received, 'remote') // step 1 gives step 2; step 2 merges
31
+ handle.onUpdate((update, origin) => {
32
+ if (origin !== 'remote') send({ update }) // doc-update
33
+ })
34
+ ```
35
+
36
+ Give each update from a peer a remote origin. Then `onUpdate` does not send it back.
37
+
38
+ ## Offline edits
39
+
40
+ While the client is offline, append each local update to a `DocStorage`. When the client is
41
+ online again, send the stored updates, run the sync steps, and clear the storage.
42
+
43
+ ## Awareness
44
+
45
+ `handle.awareness` uses the ids and the JSON states of the `awareness` message:
46
+
47
+ - `setLocalStateField('user', { id, name, color })` changes the local state.
48
+ - `onChange(change => …)` tells you about each change. When `change.local` is true, send
49
+ `getLocalState()`.
50
+ - `applyRemoteState(clientId, state)` applies a received state. A null state removes the client.
51
+
52
+ Remote clients get negative ids in `yAwareness`, so they never match the local Yjs client id.
53
+
54
+ ## Undo, positions and versions
55
+
56
+ - `undoScope(origin)` undoes only the changes that have that origin.
57
+ - `relativePosition(field, index)` gives a position in a root type that follows edits.
58
+ `absolutePosition(position)` gives its index now.
59
+ - `versions.create({ name, by })` keeps a copy of the content in the `dovetail:versions` map, so
60
+ the versions sync. `versions.open(id)` gives a document for a preview. Destroy it after use.
61
+ `versions.restore(id, origin)` makes the content equal to the version, as a new change.
62
+
63
+ A version keeps a copy of the content root types only. The root types with a name that starts
64
+ with `dovetail:` (the comment threads and the versions) are not in the copy, and a restore does
65
+ not change them. Each version adds the size of the content to the document.
@@ -0,0 +1,37 @@
1
+ import * as Y from 'yjs';
2
+ import { Awareness } from 'y-protocols/awareness';
3
+ import type { DocAwareness, DocEngine, DocHandle, DocVersions, EngineCapabilities, SharedMap, UndoScope } from '@dovetail-ts/crdt';
4
+ export interface YjsEngineOptions {
5
+ /** The clock of the version dates. The default is `Date.now`. */
6
+ now?: () => number;
7
+ }
8
+ /** Makes the Yjs engine. */
9
+ export declare function yjsEngine(options?: YjsEngineOptions): YjsEngine;
10
+ export declare class YjsEngine implements DocEngine {
11
+ readonly now: () => number;
12
+ readonly name = "yjs";
13
+ readonly capabilities: EngineCapabilities;
14
+ constructor(now: () => number);
15
+ create(): YjsDocHandle;
16
+ load(snapshot: Uint8Array): YjsDocHandle;
17
+ }
18
+ /** A Yjs document. `doc` and `yAwareness` are for the Yjs bindings (Tiptap carets). */
19
+ export declare class YjsDocHandle implements DocHandle {
20
+ readonly engine: YjsEngine;
21
+ readonly doc: Y.Doc;
22
+ readonly awareness: DocAwareness;
23
+ readonly versions: DocVersions;
24
+ /** The y-protocols awareness of `doc`. Remote clients have negative ids. */
25
+ readonly yAwareness: Awareness;
26
+ constructor(engine: YjsEngine, doc: Y.Doc);
27
+ applyUpdate(update: Uint8Array, origin?: unknown): void;
28
+ encodeStateVector(): Uint8Array;
29
+ encodeUpdate(stateVector?: Uint8Array): Uint8Array;
30
+ snapshot(): Uint8Array;
31
+ onUpdate(listener: (update: Uint8Array, origin: unknown) => void): () => void;
32
+ map(name: string): SharedMap;
33
+ undoScope(origin: unknown): UndoScope;
34
+ relativePosition(field: string, index: number): Uint8Array;
35
+ absolutePosition(position: Uint8Array): number | null;
36
+ destroy(): void;
37
+ }
package/dist/index.js ADDED
@@ -0,0 +1,254 @@
1
+ import * as Y from 'yjs';
2
+ import { Awareness } from 'y-protocols/awareness';
3
+
4
+ // src/index.ts
5
+ function yjsEngine(options = {}) {
6
+ return new YjsEngine(options.now ?? Date.now);
7
+ }
8
+ var YjsEngine = class {
9
+ constructor(now) {
10
+ this.now = now;
11
+ }
12
+ now;
13
+ name = "yjs";
14
+ capabilities = {
15
+ tiptap: true,
16
+ cursors: true,
17
+ undo: true,
18
+ history: true,
19
+ commentAnchors: true
20
+ };
21
+ create() {
22
+ return new YjsDocHandle(this, new Y.Doc());
23
+ }
24
+ load(snapshot) {
25
+ const handle = this.create();
26
+ Y.applyUpdate(handle.doc, snapshot);
27
+ return handle;
28
+ }
29
+ };
30
+ var YjsDocHandle = class {
31
+ constructor(engine, doc) {
32
+ this.engine = engine;
33
+ this.doc = doc;
34
+ this.yAwareness = new Awareness(doc);
35
+ this.awareness = new YjsAwareness(this.yAwareness);
36
+ this.versions = new YjsVersions(this);
37
+ }
38
+ engine;
39
+ doc;
40
+ awareness;
41
+ versions;
42
+ /** The y-protocols awareness of `doc`. Remote clients have negative ids. */
43
+ yAwareness;
44
+ applyUpdate(update, origin) {
45
+ Y.applyUpdate(this.doc, update, origin);
46
+ }
47
+ encodeStateVector() {
48
+ return Y.encodeStateVector(this.doc);
49
+ }
50
+ encodeUpdate(stateVector) {
51
+ return Y.encodeStateAsUpdate(this.doc, stateVector);
52
+ }
53
+ snapshot() {
54
+ return Y.encodeStateAsUpdate(this.doc);
55
+ }
56
+ onUpdate(listener) {
57
+ this.doc.on("update", listener);
58
+ return () => this.doc.off("update", listener);
59
+ }
60
+ map(name) {
61
+ const map = this.doc.getMap(name);
62
+ const doc = this.doc;
63
+ return {
64
+ get: (key) => map.get(key),
65
+ set: (key, value, origin) => doc.transact(() => map.set(key, value), origin),
66
+ delete: (key, origin) => doc.transact(() => map.delete(key), origin),
67
+ entries: () => [...map.entries()],
68
+ onChange(listener) {
69
+ const observer = (event) => listener([...event.keysChanged], event.transaction.origin);
70
+ map.observe(observer);
71
+ return () => map.unobserve(observer);
72
+ }
73
+ };
74
+ }
75
+ undoScope(origin) {
76
+ const manager = new Y.UndoManager(this.doc, { trackedOrigins: /* @__PURE__ */ new Set([origin]) });
77
+ return {
78
+ undo: () => manager.undo() !== null,
79
+ redo: () => manager.redo() !== null,
80
+ get canUndo() {
81
+ return manager.canUndo();
82
+ },
83
+ get canRedo() {
84
+ return manager.canRedo();
85
+ },
86
+ destroy: () => manager.destroy()
87
+ };
88
+ }
89
+ relativePosition(field, index) {
90
+ return Y.encodeRelativePosition(
91
+ Y.createRelativePositionFromTypeIndex(this.doc.get(field), index)
92
+ );
93
+ }
94
+ absolutePosition(position) {
95
+ const absolute = Y.createAbsolutePositionFromRelativePosition(
96
+ Y.decodeRelativePosition(position),
97
+ this.doc
98
+ );
99
+ return absolute?.index ?? null;
100
+ }
101
+ destroy() {
102
+ this.yAwareness.destroy();
103
+ this.doc.destroy();
104
+ }
105
+ };
106
+ var REMOTE = "remote";
107
+ var YjsAwareness = class {
108
+ constructor(y) {
109
+ this.y = y;
110
+ this.clientId = String(y.clientID);
111
+ }
112
+ y;
113
+ clientId;
114
+ #numbers = /* @__PURE__ */ new Map();
115
+ #names = /* @__PURE__ */ new Map();
116
+ getLocalState() {
117
+ return this.y.getLocalState();
118
+ }
119
+ setLocalState(state) {
120
+ this.y.setLocalState(state);
121
+ }
122
+ setLocalStateField(field, value) {
123
+ this.y.setLocalStateField(field, value);
124
+ }
125
+ getStates() {
126
+ return new Map([...this.y.getStates()].map(([id, state]) => [this.#name(id), state]));
127
+ }
128
+ applyRemoteState(clientId, state) {
129
+ let id = this.#numbers.get(clientId);
130
+ if (id === void 0) {
131
+ id = -(this.#numbers.size + 1);
132
+ this.#numbers.set(clientId, id);
133
+ this.#names.set(id, clientId);
134
+ }
135
+ const had = this.y.states.has(id);
136
+ const change = { added: [], updated: [], removed: [] };
137
+ if (state === null) {
138
+ if (!had) return;
139
+ this.y.states.delete(id);
140
+ change.removed.push(id);
141
+ } else {
142
+ this.y.states.set(id, state);
143
+ (had ? change.updated : change.added).push(id);
144
+ }
145
+ this.y.emit("change", [change, REMOTE]);
146
+ this.y.emit("update", [change, REMOTE]);
147
+ }
148
+ onChange(listener) {
149
+ const observer = (change, origin) => listener({
150
+ added: change.added.map((id) => this.#name(id)),
151
+ updated: change.updated.map((id) => this.#name(id)),
152
+ removed: change.removed.map((id) => this.#name(id)),
153
+ local: origin === "local"
154
+ });
155
+ this.y.on("change", observer);
156
+ return () => this.y.off("change", observer);
157
+ }
158
+ #name(id) {
159
+ return this.#names.get(id) ?? String(id);
160
+ }
161
+ };
162
+ var YjsVersions = class {
163
+ constructor(handle) {
164
+ this.handle = handle;
165
+ }
166
+ handle;
167
+ get #map() {
168
+ return this.handle.doc.getMap("dovetail:versions");
169
+ }
170
+ list() {
171
+ return [...this.#map.values()].map(({ id, name, createdAt, by }) => ({ id, name, createdAt, by })).sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
172
+ }
173
+ create(options = {}) {
174
+ const { doc, engine } = this.handle;
175
+ const copy = new Y.Doc();
176
+ for (const [name, kind] of contentTypes(doc))
177
+ replace(get(copy, name, kind), get(doc, name, kind));
178
+ const version = {
179
+ id: `${doc.clientID}-${this.#map.size}`,
180
+ name: options.name ?? `Version ${this.#map.size + 1}`,
181
+ createdAt: new Date(engine.now()).toISOString(),
182
+ by: options.by ?? null
183
+ };
184
+ this.#map.set(version.id, { ...version, content: Y.encodeStateAsUpdate(copy) });
185
+ copy.destroy();
186
+ return version;
187
+ }
188
+ open(id) {
189
+ return this.handle.engine.load(this.#content(id));
190
+ }
191
+ restore(id, origin) {
192
+ const old = new Y.Doc();
193
+ Y.applyUpdate(old, this.#content(id));
194
+ const { doc } = this.handle;
195
+ doc.transact(() => {
196
+ for (const [name, kind] of contentTypes(doc))
197
+ replace(get(doc, name, kind), get(old, name, kind));
198
+ }, origin);
199
+ old.destroy();
200
+ }
201
+ onChange(listener) {
202
+ const observer = () => listener();
203
+ this.#map.observe(observer);
204
+ return () => this.#map.unobserve(observer);
205
+ }
206
+ #content(id) {
207
+ const stored = this.#map.get(id);
208
+ if (!stored) throw new Error(`No version "${id}" in this document.`);
209
+ return stored.content;
210
+ }
211
+ };
212
+ function contentTypes(doc) {
213
+ return [...doc.share].filter(([name]) => !name.startsWith("dovetail:")).map(([name, type]) => {
214
+ if (type instanceof Y.XmlFragment) return [name, "xml"];
215
+ if (type instanceof Y.Text) return [name, "text"];
216
+ if (type instanceof Y.Array) return [name, "array"];
217
+ if (type instanceof Y.Map) return [name, "map"];
218
+ throw new Error(
219
+ `The root type "${name}" has no kind yet. Get it with getText, getXmlFragment, getArray or getMap before you use versions.`
220
+ );
221
+ });
222
+ }
223
+ function get(doc, name, kind) {
224
+ if (kind === "xml") return doc.getXmlFragment(name);
225
+ if (kind === "text") return doc.getText(name);
226
+ if (kind === "array") return doc.getArray(name);
227
+ return doc.getMap(name);
228
+ }
229
+ var clone = (value) => value instanceof Y.AbstractType ? value.clone() : value;
230
+ function replace(target, source) {
231
+ if (target instanceof Y.XmlFragment && source instanceof Y.XmlFragment) {
232
+ target.delete(0, target.length);
233
+ target.insert(
234
+ 0,
235
+ source.toArray().map((child) => {
236
+ if (child instanceof Y.XmlHook) throw new Error("Versions do not support Y.XmlHook.");
237
+ return child.clone();
238
+ })
239
+ );
240
+ } else if (target instanceof Y.Text && source instanceof Y.Text) {
241
+ target.delete(0, target.length);
242
+ target.applyDelta(source.toDelta());
243
+ } else if (target instanceof Y.Array && source instanceof Y.Array) {
244
+ target.delete(0, target.length);
245
+ target.insert(0, source.toArray().map(clone));
246
+ } else if (target instanceof Y.Map && source instanceof Y.Map) {
247
+ for (const key of [...target.keys()]) if (!source.has(key)) target.delete(key);
248
+ for (const [key, value] of source.entries()) target.set(key, clone(value));
249
+ }
250
+ }
251
+
252
+ export { YjsDocHandle, YjsEngine, yjsEngine };
253
+ //# sourceMappingURL=index.js.map
254
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;;AAuBO,SAAS,SAAA,CAAU,OAAA,GAA4B,EAAC,EAAc;AACnE,EAAA,OAAO,IAAI,SAAA,CAAU,OAAA,CAAQ,GAAA,IAAO,KAAK,GAAG,CAAA;AAC9C;AAEO,IAAM,YAAN,MAAqC;AAAA,EAU1C,YAAqB,GAAA,EAAmB;AAAnB,IAAA,IAAA,CAAA,GAAA,GAAA,GAAA;AAAA,EAAoB;AAAA,EAApB,GAAA;AAAA,EATZ,IAAA,GAAO,KAAA;AAAA,EACP,YAAA,GAAmC;AAAA,IAC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AA;AAC9B,IAAA,MAAA,CAAO,UAAA,CAAW,MAAA,CAAO,OAAA,EAAS,CAAA;AAAA,EACpC,CAAA,MAAA,IAAW,MAAA,YAAoB,CAAA,CAAA,KAAA,IAAS,MAAA,YAAoB,CAAA,CAAA,KAAA,EAAO;AACjE,IAAA,MAAA,CAAO,MAAA,CAAO,CAAA,EAAG,MAAA,CAAO,MAAM,CAAA;AAC9B,IAAA,MAAA,CAAO,OAAO,CAAA,EAAG,MAAA,CAAO,SAAQ,CAAE,GAAA,CAAI,KAAK,CAAC,CAAA;AAAA,EAC9C,CAAA,MAAA,IAAW,MAAA,YAAoB,CAAA,CAAA,GAAA,IAAO,MAAA,YAAoB,CAAA,CAAA,GAAA,EAAK;AAC7D,IAAA,KAAA,MAAW,GAAA,IAAO,CAAC,GAAG,MAAA,CAAO,MAAM,CAAA,EAAG,IAAI,CAAC,OAAO,GAAA,CAAI,GAAG,CAAA,EAAG,MAAA,CAAO,OAAO,GAAG,CAAA;AAC7E,IAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,CAAA,IAAK,MAAA,CAAO,OAAA,EAAQ,EAAG,MAAA,CAAO,GAAA,CAAI,GAAA,EAAK,KAAA,CAAM,KAAK,CAAC,CAAA;AAAA,EAC3E;AACF","file":"index.js","sourcesContent":["// The Yjs DocEngine, the reference engine (ADR 0002). It has every capability.\nimport * as Y from 'yjs'\nimport { Awareness } from 'y-protocols/awareness'\nimport type {\n AwarenessChange,\n DocAwareness,\n DocEngine,\n DocHandle,\n DocVersions,\n EngineCapabilities,\n JsonObject,\n JsonValue,\n SharedMap,\n UndoScope,\n Version,\n} from '@dovetail-ts/crdt'\n\nexport interface YjsEngineOptions {\n /** The clock of the version dates. The default is `Date.now`. */\n now?: () => number\n}\n\n/** Makes the Yjs engine. */\nexport function yjsEngine(options: YjsEngineOptions = {}): YjsEngine {\n return new YjsEngine(options.now ?? Date.now)\n}\n\nexport class YjsEngine implements DocEngine {\n readonly name = 'yjs'\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(): YjsDocHandle {\n return new YjsDocHandle(this, new Y.Doc())\n }\n\n load(snapshot: Uint8Array): YjsDocHandle {\n const handle = this.create()\n Y.applyUpdate(handle.doc, snapshot)\n return handle\n }\n}\n\n/** A Yjs document. `doc` and `yAwareness` are for the Yjs bindings (Tiptap carets). */\nexport class YjsDocHandle implements DocHandle {\n readonly awareness: DocAwareness\n readonly versions: DocVersions\n /** The y-protocols awareness of `doc`. Remote clients have negative ids. */\n readonly yAwareness: Awareness\n\n constructor(\n readonly engine: YjsEngine,\n readonly doc: Y.Doc,\n ) {\n this.yAwareness = new Awareness(doc)\n this.awareness = new YjsAwareness(this.yAwareness)\n this.versions = new YjsVersions(this)\n }\n\n applyUpdate(update: Uint8Array, origin?: unknown): void {\n Y.applyUpdate(this.doc, update, origin)\n }\n\n encodeStateVector(): Uint8Array {\n return Y.encodeStateVector(this.doc)\n }\n\n encodeUpdate(stateVector?: Uint8Array): Uint8Array {\n return Y.encodeStateAsUpdate(this.doc, stateVector)\n }\n\n snapshot(): Uint8Array {\n return Y.encodeStateAsUpdate(this.doc)\n }\n\n onUpdate(listener: (update: Uint8Array, origin: unknown) => void): () => void {\n this.doc.on('update', listener)\n return () => this.doc.off('update', listener)\n }\n\n map(name: string): SharedMap {\n const map = this.doc.getMap<JsonValue>(name)\n const doc = this.doc\n return {\n get: key => map.get(key),\n set: (key, value, origin) => doc.transact(() => map.set(key, value), origin),\n delete: (key, origin) => doc.transact(() => map.delete(key), origin),\n entries: () => [...map.entries()],\n onChange(listener) {\n const observer = (event: Y.YMapEvent<JsonValue>) =>\n listener([...event.keysChanged], event.transaction.origin)\n map.observe(observer)\n return () => map.unobserve(observer)\n },\n }\n }\n\n undoScope(origin: unknown): UndoScope {\n const manager = new Y.UndoManager(this.doc, { trackedOrigins: new Set([origin]) })\n return {\n undo: () => manager.undo() !== null,\n redo: () => manager.redo() !== null,\n get canUndo() {\n return manager.canUndo()\n },\n get canRedo() {\n return manager.canRedo()\n },\n destroy: () => manager.destroy(),\n }\n }\n\n relativePosition(field: string, index: number): Uint8Array {\n return Y.encodeRelativePosition(\n Y.createRelativePositionFromTypeIndex(this.doc.get(field), index),\n )\n }\n\n absolutePosition(position: Uint8Array): number | null {\n const absolute = Y.createAbsolutePositionFromRelativePosition(\n Y.decodeRelativePosition(position),\n this.doc,\n )\n return absolute?.index ?? null\n }\n\n destroy(): void {\n this.yAwareness.destroy()\n this.doc.destroy()\n }\n}\n\nconst REMOTE = 'remote'\n\n/** The protocol awareness (string ids, JSON states) on a y-protocols awareness (number ids). */\nclass YjsAwareness implements DocAwareness {\n readonly clientId: string\n #numbers = new Map<string, number>()\n #names = new Map<number, string>()\n\n constructor(readonly y: Awareness) {\n this.clientId = String(y.clientID)\n }\n\n getLocalState(): JsonObject | null {\n return this.y.getLocalState()\n }\n\n setLocalState(state: JsonObject | null): void {\n this.y.setLocalState(state)\n }\n\n setLocalStateField(field: string, value: JsonValue): void {\n this.y.setLocalStateField(field, value)\n }\n\n getStates(): Map<string, JsonObject> {\n return new Map([...this.y.getStates()].map(([id, state]) => [this.#name(id), state]))\n }\n\n applyRemoteState(clientId: string, state: JsonObject | null): void {\n let id = this.#numbers.get(clientId)\n if (id === undefined) {\n // Negative ids never match a Yjs client id, which is a positive number.\n id = -(this.#numbers.size + 1)\n this.#numbers.set(clientId, id)\n this.#names.set(id, clientId)\n }\n const had = this.y.states.has(id)\n const change = { added: [] as number[], updated: [] as number[], removed: [] as number[] }\n if (state === null) {\n if (!had) return\n this.y.states.delete(id)\n change.removed.push(id)\n } else {\n this.y.states.set(id, state)\n ;(had ? change.updated : change.added).push(id)\n }\n this.y.emit('change', [change, REMOTE])\n this.y.emit('update', [change, REMOTE])\n }\n\n onChange(listener: (change: AwarenessChange) => void): () => void {\n const observer = (\n change: { added: number[]; updated: number[]; removed: number[] },\n origin: unknown,\n ) =>\n listener({\n added: change.added.map(id => this.#name(id)),\n updated: change.updated.map(id => this.#name(id)),\n removed: change.removed.map(id => this.#name(id)),\n local: origin === 'local',\n })\n this.y.on('change', observer)\n return () => this.y.off('change', observer)\n }\n\n #name(id: number): string {\n return this.#names.get(id) ?? String(id)\n }\n}\n\ntype Kind = 'xml' | 'text' | 'array' | 'map'\ntype Stored = Version & { content: Uint8Array }\n\n/**\n * The versions of a Yjs document, in its `dovetail:versions` map. A version keeps a copy of\n * the content types only, so it does not hold the versions or the comment threads.\n */\nclass YjsVersions implements DocVersions {\n constructor(readonly handle: YjsDocHandle) {}\n\n get #map(): Y.Map<Stored> {\n return this.handle.doc.getMap<Stored>('dovetail:versions')\n }\n\n list(): Version[] {\n return [...this.#map.values()]\n .map(({ id, name, createdAt, by }) => ({ id, name, createdAt, by }))\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 const copy = new Y.Doc()\n for (const [name, kind] of contentTypes(doc))\n replace(get(copy, name, kind), get(doc, name, kind))\n const version: Version = {\n id: `${doc.clientID}-${this.#map.size}`,\n name: options.name ?? `Version ${this.#map.size + 1}`,\n createdAt: new Date(engine.now()).toISOString(),\n by: options.by ?? null,\n }\n this.#map.set(version.id, { ...version, content: Y.encodeStateAsUpdate(copy) })\n copy.destroy()\n return version\n }\n\n open(id: string): DocHandle {\n return this.handle.engine.load(this.#content(id))\n }\n\n restore(id: string, origin?: unknown): void {\n const old = new Y.Doc()\n Y.applyUpdate(old, this.#content(id))\n const { doc } = this.handle\n doc.transact(() => {\n for (const [name, kind] of contentTypes(doc))\n replace(get(doc, name, kind), get(old, name, kind))\n }, origin)\n old.destroy()\n }\n\n onChange(listener: () => void): () => void {\n const observer = () => listener()\n this.#map.observe(observer)\n return () => this.#map.unobserve(observer)\n }\n\n #content(id: string): Uint8Array {\n const stored = this.#map.get(id)\n if (!stored) throw new Error(`No version \"${id}\" in this document.`)\n return stored.content\n }\n}\n\n/** The root types of the content: all the root types but the `dovetail:` ones. */\nfunction contentTypes(doc: Y.Doc): [string, Kind][] {\n return [...doc.share]\n .filter(([name]) => !name.startsWith('dovetail:'))\n .map(([name, type]) => {\n if (type instanceof Y.XmlFragment) return [name, 'xml']\n if (type instanceof Y.Text) return [name, 'text']\n if (type instanceof Y.Array) return [name, 'array']\n if (type instanceof Y.Map) return [name, 'map']\n throw new Error(\n `The root type \"${name}\" has no kind yet. Get it with getText, getXmlFragment, ` +\n 'getArray or getMap before you use versions.',\n )\n })\n}\n\ntype Root = Y.XmlFragment | Y.Text | Y.Array<unknown> | Y.Map<unknown>\n\nfunction get(doc: Y.Doc, name: string, kind: Kind): Root {\n if (kind === 'xml') return doc.getXmlFragment(name)\n if (kind === 'text') return doc.getText(name)\n if (kind === 'array') return doc.getArray(name)\n return doc.getMap(name)\n}\n\nconst clone = (value: unknown) => (value instanceof Y.AbstractType ? value.clone() : value)\n\n/** Makes `target` equal to `source`, a root type of the same kind in another document. */\nfunction replace(target: Root, source: Root): void {\n if (target instanceof Y.XmlFragment && source instanceof Y.XmlFragment) {\n target.delete(0, target.length)\n target.insert(\n 0,\n source.toArray().map(child => {\n if (child instanceof Y.XmlHook) throw new Error('Versions do not support Y.XmlHook.')\n return child.clone()\n }),\n )\n } else if (target instanceof Y.Text && source instanceof Y.Text) {\n target.delete(0, target.length)\n target.applyDelta(source.toDelta())\n } else if (target instanceof Y.Array && source instanceof Y.Array) {\n target.delete(0, target.length)\n target.insert(0, source.toArray().map(clone))\n } else if (target instanceof Y.Map && source instanceof Y.Map) {\n for (const key of [...target.keys()]) if (!source.has(key)) target.delete(key)\n for (const [key, value] of source.entries()) target.set(key, clone(value))\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@dovetail-ts/crdt-yjs",
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 Yjs DocEngine. This is the reference engine.",
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-yjs"
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
+ "y-protocols": "^1.0.7",
39
+ "yjs": "^13.6.33"
40
+ },
41
+ "devDependencies": {
42
+ "tsup": "^8.5.1"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "engines": {
48
+ "node": ">=22.12.0"
49
+ },
50
+ "scripts": {
51
+ "build": "tsc --build --force && tsup"
52
+ }
6
53
  }