@dovetail-ts/core 0.0.0-stage → 1.0.0

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,21 @@
1
+ # @dovetail-ts/core
2
+
3
+ ## 1.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 480744b: First release of Dovetail: real-time and offline sync for Ember.
8
+
9
+ - `@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`.
10
+ - `@dovetail-ts/warp-drive`: the store feed into WarpDrive.
11
+ - `@dovetail-ts/crdt`, `crdt-yjs`, `crdt-loro` and `crdt-automerge`: one `DocEngine` interface with three engines.
12
+ - `@dovetail-ts/tiptap`: co-editing in Tiptap 3 with carets, per-user undo, versions and comment threads.
13
+ - `@dovetail-ts/ember`, `notifications` and `inspector`: presence and status components, the inbox, toasts and activity feeds, and a dev panel.
14
+ - `@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.
15
+ - 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).
16
+
17
+ ### Patch Changes
18
+
19
+ - Updated dependencies [480744b]
20
+ - @dovetail-ts/crdt@1.0.0
21
+ - @dovetail-ts/protocol@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,212 @@
1
- # Temporary Holding Version
1
+ # @dovetail-ts/core
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 client core of Dovetail: the connection, the optimistic ledger, the offline queue, the
4
+ sync of CRDT documents and presence. It has no framework code. The Ember addon wraps the
5
+ `state` and the events of each class to make them reactive.
6
+
7
+ Part of [Dovetail](https://joegaudet.com/dovetail/). Not released yet.
8
+
9
+ ## Connection
10
+
11
+ `Connection` connects to a Dovetail server over a transport. Its life cycle is a statechart
12
+ (`ConnectionMachine`): `idle`, `connecting`, `open`, `reconnecting`, `offline` and `closed`.
13
+
14
+ ```ts
15
+ import { Connection } from '@dovetail-ts/core'
16
+ import { WebSocketTransport } from '@dovetail-ts/transport-ws'
17
+
18
+ const connection = new Connection({
19
+ transport: () => new WebSocketTransport({ url: 'wss://example.com/dovetail' }),
20
+ getToken: () => session.token,
21
+ })
22
+ connection.connect()
23
+ ```
24
+
25
+ | Option | Default | What it does |
26
+ | ------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------- |
27
+ | `transport` | (required) | Makes a new transport for each attempt. |
28
+ | `getToken` | none | The auth hook. The connection calls it before each attempt. |
29
+ | `network` | `browserNetwork()` | The online state of the device. |
30
+ | `clock` | `globalThis` | The timers of the backoff, the ack timeout and the heartbeat. |
31
+ | `backoff` | `{ base: 500, max: 30_000 }` | The steps of the reconnect delay. The jitter makes each delay between half and all of a step. |
32
+ | `ackTimeout` | `15_000` | The time to wait for the answer to a request. After it, the request fails with a `NetworkError`. |
33
+ | `heartbeatInterval` | `30_000` | The time between two pings. A ping with no pong in `ackTimeout` moves the state to `reconnecting`. 0 sends no ping. |
34
+ | `joinUserRoom` | `false` | Joins the per-user room of the user, for notifications. |
35
+ | `client` | none | The name and the version of the client, for the hello. |
36
+ | `onError` | `console.error` | Gets each error that a listener throws. The other listeners still get the message. |
37
+
38
+ The members:
39
+
40
+ - `state`, `isOpen`, `isOnline`, `attempt`, `session`, `version`, `user` and `error`.
41
+ - `connect()` and `close()`.
42
+ - `onStateChange(listener)`, `onMessage(type, listener)`, `onFeed(room, listener)`,
43
+ `onJoin(room, listener)` and `onReset(room, listener)`. Each one returns a function that stops
44
+ it. `onJoin` runs after each join ack, also after a reconnect. `onReset` runs before it when
45
+ the ack has `reset: true`: the server could not send each change after the cursor of the
46
+ client, so the client must load the data of the room again (ADR 0024).
47
+ - `retain(room)` joins a room and gives a release function. The connection leaves the room
48
+ when the last holder releases it. Use it, not `join` and `leave`, when more than one part of
49
+ an app uses a room.
50
+ - `holders(room)` gives the number of holders of a room (the `retain` calls that are not
51
+ released). `onHoldersChange(listener)` runs with the room after each change.
52
+ - `join(room, since?)` and `leave(room)`. After a reconnect, the connection joins each room
53
+ again with the last feed cursor. A join with `since` keeps that cursor until the replay feed
54
+ moves it, so a drop before the replay loses no op. A `reset` ack sets the cursor to the ack
55
+ cursor. A join that the server refuses or that fails rejects its waiters, and the next `join`
56
+ sends it again. A held room (`retain`) whose join gets `rate-limited`, `internal` or no answer
57
+ joins again with backoff while the connection stays open. A `forbidden` join does not.
58
+ - `write(id, room, op)` gives `{ status: 'ack' }` or `{ status: 'reject' }`.
59
+ - `ping()` resolves at the pong. The server handles the messages of a connection in order, so
60
+ at the pong it has each message that was sent before the ping.
61
+ - `send(message)` sends one message. It throws a `NetworkError` when the connection is not
62
+ open.
63
+
64
+ A request fails with a `NetworkError` when the connection is not open, when it closes before
65
+ the answer, when no answer comes in `ackTimeout`, or when the server answers `rate-limited` or
66
+ `internal`. A caller can retry it. A `ProtocolError`
67
+ is an error that a retry cannot fix.
68
+
69
+ ## The sync client: ledger and queue
70
+
71
+ `SyncClient` sends the local changes of the store through the optimistic ledger and the
72
+ offline write queue (ADR 0004, ADR 0005). Each tab has one. The leader tab (Web Locks) sends
73
+ the queue, and tells the other tabs about each answer over a BroadcastChannel. The server does
74
+ not feed a write back to its sender, so each tab applies the ack of a write that another tab
75
+ made (the ack document, or else the op) as a server state. All tabs show each write.
76
+
77
+ ```ts
78
+ import { SyncClient, WriteQueue, openDovetailDB } from '@dovetail-ts/core'
79
+ import { storeSink } from '@dovetail-ts/warp-drive'
80
+
81
+ const sync = new SyncClient({
82
+ connection,
83
+ sink: storeSink(store),
84
+ queue: new WriteQueue(await openDovetailDB()),
85
+ })
86
+ await sync.start()
87
+ const stop = sync.subscribe('note:1')
88
+ await sync.write('note:1', {
89
+ op: 'upsert',
90
+ document: { data: { type: 'note', id: '1', attributes: { title: 'Plan' } } },
91
+ })
92
+ ```
93
+
94
+ - `state` is a `SyncState`: `connection`, `online`, `leader`, `queued`, `deadLetters` and
95
+ `errors`. `onChange(listener)` runs after each change.
96
+ - `write(room, op)` applies the change at once and puts it in the queue.
97
+ - `subscribe(room)` puts the store feed of the room in the store. After a join with
98
+ `reset: true`, the `reload(room)` option of the host loads the room again (see below).
99
+ - `retry(id)` sends a dead letter again. `discard(id)` removes it and the writes that depend on
100
+ it, and their changes roll back.
101
+ - `stop()` waits for the send in flight and for each queue read, then gives the leader lock to
102
+ another tab. After it, the host can close the database.
103
+
104
+ A write that gets no answer in the ack timeout, or a `rate-limited` error, stays in the queue
105
+ and goes again after the backoff, so the queue does not stop. A write that the server rejects goes to the dead letters, and so does a write to a room
106
+ that the server does not let the user join. The leader holds the room of a write only for the
107
+ send. A write to a temporary id that has a server id goes out with the server id.
108
+
109
+ The `reload(room)` option gets a subscribed room after a join with `reset: true`, and gives
110
+ `{ documents, complete? }`, for example from an HTTP request. The documents go through the
111
+ ledger, so the pending local changes stay on top. With `complete: true`, the client removes each
112
+ record of the room feed that the documents do not have, except a record that the feed of another
113
+ subscribed room gave. The feed ops that come during the reload apply after it. Without
114
+ `reload`, a reset changes only the cursor.
115
+
116
+ The parts are also exported: `OptimisticLedger` (on a `StoreSink`), `WriteQueue`,
117
+ `openDovetailDB`, `tempId`, `tempIdMapping`, `remapOp` and `backoffDelay`.
118
+
119
+ ## Documents
120
+
121
+ `DocSession` syncs one CRDT document of a room (a `DocHandle` of `@dovetail-ts/crdt`).
122
+
123
+ ```ts
124
+ import { DocSession, IndexedDBDocStorage, openDovetailDB } from '@dovetail-ts/core'
125
+ import { yjsEngine } from '@dovetail-ts/crdt-yjs'
126
+
127
+ const session = new DocSession({
128
+ connection,
129
+ room: 'note:1',
130
+ doc: 'body',
131
+ handle: yjsEngine().create(),
132
+ storage: new IndexedDBDocStorage(await openDovetailDB()),
133
+ })
134
+ await session.start()
135
+ session.onSyncChange(synced => console.log(synced))
136
+ // Later:
137
+ await session.destroy()
138
+ ```
139
+
140
+ - `start()` applies the stored updates of an earlier page and joins the room. The session
141
+ listens to the document from its constructor, so a local update before `start()` goes to the
142
+ storage, and the first join sends it.
143
+ - After each join, the session sends `doc-sync` step 1 and applies each step 2 answer. It skips
144
+ an empty step 2.
145
+ - Each local update goes to the `DocStorage` and, when the room is joined, to the server as a
146
+ `doc-update`. After each join, the session sends the stored updates again.
147
+ - The session clears the storage only after a ping comes back, because then the server has
148
+ the updates. `synced` is then true.
149
+ - The room awareness goes to `handle.awareness`. The remote ids are the session ids of the
150
+ protocol.
151
+ - `destroy()` stops the sync and releases the room. The updates that the server does not have
152
+ stay in the storage.
153
+
154
+ `IndexedDBDocStorage` keeps the updates in the same database as the write queue. All tabs
155
+ share the rows, so `clear` removes only the rows that the storage loaded or appended. It takes the
156
+ database or a promise of it (`new IndexedDBDocStorage(openDovetailDB())`), so a host can make
157
+ the session before the database opens.
158
+ `MemoryDocStorage` of `@dovetail-ts/crdt` keeps them in memory.
159
+
160
+ ## Presence
161
+
162
+ `PresenceRoom` gives the presence of the clients of a room: the avatar stack, the live
163
+ pointers and the typing indicator use it.
164
+
165
+ ```ts
166
+ import { PresenceRoom } from '@dovetail-ts/core'
167
+
168
+ const presence = new PresenceRoom({
169
+ connection,
170
+ room: 'board:1',
171
+ user: { id: 'u1', name: 'Ann', color: '#cc3333', avatarUrl: 'https://example.com/ann.png' },
172
+ })
173
+ const stop = presence.subscribe(state => render(state.self, state.peers))
174
+ container.addEventListener('pointermove', event => {
175
+ const box = container.getBoundingClientRect()
176
+ presence.setPointer({ x: event.clientX - box.left, y: event.clientY - box.top })
177
+ })
178
+ input.addEventListener('input', () => presence.typing())
179
+ ```
180
+
181
+ | Option | Default | What it does |
182
+ | -------------------- | ------------ | ------------------------------------------------------------------------- |
183
+ | `user` | (required) | `{ id, name, color, avatarUrl? }`. `color` is a hex color. |
184
+ | `connection`, `room` | none | A room without a document. The presence room joins it. |
185
+ | `awareness` | none | The awareness of a document (`docSession.handle.awareness`). |
186
+ | `clock` | `globalThis` | The timers. |
187
+ | `awayAfter` | `60_000` | The idle time after which the status is `away`. |
188
+ | `typingTimeout` | `3_000` | The time after the last `typing()` after which typing stops. |
189
+ | `pointerThrottle` | `50` | The smallest time between two pointer sends. The last one is always sent. |
190
+ | `awarenessRenewal` | `15_000` | The time between two sends of the local state. |
191
+
192
+ - `state` is `{ self, peers }`. Each change makes a new object. Each `Presence` has `user`,
193
+ `status` (`online` or `away`), `typing`, `pointer` (`{ x, y }` or null) and `extra` (the other
194
+ JSON fields). Each peer also has its `clientId`.
195
+ - `subscribe(listener)` runs after each change, and returns a function that stops it.
196
+ - `activity()` marks the user as active. `setPointer` and `typing` also do this.
197
+ - `setPointer(pointer)`, `typing()`, `stopTyping()` and `set(fields)` change the local state.
198
+ - `destroy()` stops the timers and leaves the room. On the awareness of a document, it removes
199
+ the presence fields but keeps `user`, because the editor carets use it.
200
+
201
+ Remote states are not trusted. `readPresence(state)` checks each one: a state with no valid
202
+ user is not a peer, and a field that is not valid gets its default. A color that is not a hex
203
+ color (`isHexColor`: `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`) becomes gray, an `avatarUrl` that is not `https:` is dropped, and `extra` never has
204
+ the keys `__proto__`, `constructor` or `prototype`.
205
+
206
+ `linkAwareness(connection, room, awareness)` is the part that connects the `awareness`
207
+ messages of a room to a `DocAwareness`. `DocSession` and `PresenceRoom` use it.
208
+
209
+ ## Other exports
210
+
211
+ - `browserNetwork()` and `ALWAYS_ONLINE`: network signals.
212
+ - `browserLocks()`, `LOCAL_LOCKS` and `browserChannel(name)`: the tab coordination.
@@ -0,0 +1,23 @@
1
+ import type { DocAwareness } from '@dovetail-ts/crdt';
2
+ import type { Timers } from './backoff';
3
+ import type { Connection } from './connection';
4
+ export interface AwarenessLinkOptions {
5
+ /** The timers of the renewal. The default is the global scope. */
6
+ clock?: Timers;
7
+ /**
8
+ * The time in ms between two sends of the local state. The server removes a state that it
9
+ * does not get again in its awareness timeout (30 s). Default 15 000.
10
+ */
11
+ renewEvery?: number;
12
+ }
13
+ /**
14
+ * Sends the local state of `awareness` to `room` and applies the remote states of the room.
15
+ * The remote ids are the session ids of the protocol. Returns a function that stops it.
16
+ *
17
+ * - After each join, it sends the local state, because the server sends no states at a join.
18
+ * - When a client that it does not know sends a state, it sends the local state again, so the
19
+ * new client gets it.
20
+ * - It sends the local state again before the awareness timeout of the server.
21
+ * - When the connection drops, it removes the remote states. The clients send them again.
22
+ */
23
+ export declare function linkAwareness(connection: Connection, room: string, awareness: DocAwareness, options?: AwarenessLinkOptions): () => void;
@@ -0,0 +1,18 @@
1
+ /** The steps of a backoff: the first delay and the largest delay, in milliseconds. */
2
+ export interface BackoffOptions {
3
+ /** The delay of the first retry. The default is 500. */
4
+ base?: number;
5
+ /** The largest delay. The default is 30 000. */
6
+ max?: number;
7
+ }
8
+ /**
9
+ * The delay before retry number `attempt` (0 is the first retry). The step doubles for each
10
+ * attempt, up to `max`. The jitter makes the delay a value between half the step and the full
11
+ * step, so many clients do not retry at the same time.
12
+ */
13
+ export declare function backoffDelay(attempt: number, { base, max }?: BackoffOptions, random?: () => number): number;
14
+ /** The timer methods that Dovetail uses. A `FakeClock` and the global scope both have them. */
15
+ export interface Timers {
16
+ setTimeout(run: () => void, ms: number): unknown;
17
+ clearTimeout(id: unknown): void;
18
+ }
@@ -0,0 +1,221 @@
1
+ import { Machine, State } from '@switchyard-ts/core';
2
+ import type { AckMessage, ClientMessage, ClientTransport, ErrorCode, FeedMessage, RejectMessage, ServerMessage, StoreOp } from '@dovetail-ts/protocol';
3
+ import type { BackoffOptions, Timers } from './backoff';
4
+ import type { NetworkSignal } from './network';
5
+ /** The states of a connection. */
6
+ export declare class ConnectionState extends State {
7
+ private readonly brand;
8
+ static Idle: ConnectionState & {
9
+ readonly value: "idle";
10
+ };
11
+ static Connecting: ConnectionState & {
12
+ readonly value: "connecting";
13
+ };
14
+ static Open: ConnectionState & {
15
+ readonly value: "open";
16
+ };
17
+ static Reconnecting: ConnectionState & {
18
+ readonly value: "reconnecting";
19
+ };
20
+ static Offline: ConnectionState & {
21
+ readonly value: "offline";
22
+ };
23
+ static Closed: ConnectionState & {
24
+ readonly value: "closed";
25
+ };
26
+ }
27
+ /** The connection cannot send now, or it closed before the answer. The caller can retry. */
28
+ export declare class NetworkError extends Error {
29
+ /** The protocol error code, when the server sent one. */
30
+ readonly code?: ErrorCode | undefined;
31
+ name: string;
32
+ constructor(message: string,
33
+ /** The protocol error code, when the server sent one. */
34
+ code?: ErrorCode | undefined);
35
+ }
36
+ /** The server refused a request with a protocol error. */
37
+ export declare class ProtocolError extends Error {
38
+ readonly code: ErrorCode;
39
+ name: string;
40
+ constructor(code: ErrorCode, message: string);
41
+ }
42
+ /** The answer to a write: an ack, or a reject with a 4xx status. */
43
+ export type WriteResult = {
44
+ status: 'ack';
45
+ ack: AckMessage;
46
+ } | {
47
+ status: 'reject';
48
+ reject: RejectMessage;
49
+ };
50
+ export interface ConnectionOptions {
51
+ /**
52
+ * Makes a new transport for each attempt. A transport cannot open again after it closes, so
53
+ * the connection takes a factory: `() => new WebSocketTransport(url)`.
54
+ */
55
+ transport: () => ClientTransport;
56
+ /** The host auth hook (ADR 0007). The connection calls it before each attempt. */
57
+ getToken?: () => string | undefined | Promise<string | undefined>;
58
+ /** The online state of the device. The default is the browser `online` and `offline` events. */
59
+ network?: NetworkSignal;
60
+ /** The timers of the backoff. The default is the global scope. */
61
+ clock?: Timers;
62
+ /** The source of the jitter. The default is `Math.random`. */
63
+ random?: () => number;
64
+ backoff?: BackoffOptions;
65
+ /** Joins the per-user room (`user:<id>`) of the user of the welcome, for notifications. */
66
+ joinUserRoom?: boolean;
67
+ /** The name and the version of the client, for the hello. */
68
+ client?: {
69
+ name: string;
70
+ version: string;
71
+ };
72
+ /**
73
+ * The time in ms to wait for the answer to a request (a write, a join, a leave or a ping).
74
+ * After it, the request fails with a NetworkError, which the caller can retry. Default 15 000.
75
+ */
76
+ ackTimeout?: number;
77
+ /**
78
+ * The time in ms between two pings while the connection is open. A ping with no pong in
79
+ * `ackTimeout` moves the connection to Reconnecting. 0 sends no ping. Default 30 000.
80
+ */
81
+ heartbeatInterval?: number;
82
+ /**
83
+ * Gets each error that a listener throws. The other listeners still get the message, and the
84
+ * connection stays open. The default is `console.error`.
85
+ */
86
+ onError?: (error: unknown) => void;
87
+ }
88
+ /** The statechart of the connection. The connection does the work in its hooks. */
89
+ export declare class ConnectionMachine extends Machine<ConnectionState> {
90
+ readonly host: ConnectionHost;
91
+ /** The number of failed attempts since the last open. */
92
+ attempt: number;
93
+ constructor(host: ConnectionHost);
94
+ get isOnline(): boolean;
95
+ connect(): void;
96
+ opened(): void;
97
+ dropped(): void;
98
+ /** A fatal error, as no common protocol version. The connection does not retry. */
99
+ failed(): void;
100
+ retry(): void;
101
+ offline(): void;
102
+ online(): void;
103
+ close(): void;
104
+ handshake(signal: AbortSignal): Promise<void>;
105
+ wait(): () => void;
106
+ enterOpen(): void;
107
+ enterReconnecting(): void;
108
+ enterOffline(): void;
109
+ enterClosed(): void;
110
+ }
111
+ /** What the statechart asks of the connection. */
112
+ export interface ConnectionHost {
113
+ readonly isOnline: boolean;
114
+ handshake(signal: AbortSignal): Promise<void>;
115
+ /** Runs `retry` after the backoff delay of `attempt`. Returns a function that cancels it. */
116
+ schedule(retry: () => void, attempt: number): () => void;
117
+ enterOpen(): void;
118
+ teardown(): void;
119
+ }
120
+ type Listener<T extends ServerMessage['type']> = (message: Extract<ServerMessage, {
121
+ type: T;
122
+ }>) => void;
123
+ /**
124
+ * A connection to a Dovetail server over any transport. It sends the hello with the token of
125
+ * the host, negotiates the version, joins rooms again after each reconnect, and gives each
126
+ * message to its subscribers.
127
+ */
128
+ export declare class Connection implements ConnectionHost {
129
+ #private;
130
+ readonly machine: ConnectionMachine;
131
+ /** The session id of the last welcome. */
132
+ session: string | undefined;
133
+ /** The protocol version of the last welcome. */
134
+ version: number | undefined;
135
+ /** The user of the last welcome. */
136
+ user: {
137
+ id: string;
138
+ } | undefined;
139
+ /** The last protocol error from the server. */
140
+ error: {
141
+ code: ErrorCode;
142
+ message: string;
143
+ } | undefined;
144
+ constructor(options: ConnectionOptions);
145
+ /** The current state. */
146
+ get state(): ConnectionState;
147
+ /** The number of failed attempts since the last open. */
148
+ get attempt(): number;
149
+ get isOnline(): boolean;
150
+ /** True when the connection can send. */
151
+ get isOpen(): boolean;
152
+ /** The rooms that the connection joins, also after a reconnect. */
153
+ get rooms(): string[];
154
+ /** The last feed cursor of `room`. */
155
+ cursor(room: string): string | undefined;
156
+ /** Starts the connection. It opens when the network is online. */
157
+ connect(): void;
158
+ /** Closes the connection. It does not reconnect until the next `connect()`. */
159
+ close(): void;
160
+ /** Calls `listener` on each change of the state. Returns a function that stops it. */
161
+ onStateChange(listener: (state: ConnectionState) => void): () => void;
162
+ /** Calls `listener` for each message of the type `type`. Returns a function that stops it. */
163
+ onMessage<T extends ServerMessage['type']>(type: T, listener: Listener<T>): () => void;
164
+ /** Calls `listener` for each store feed message of `room`. Returns a function that stops it. */
165
+ onFeed(room: string, listener: (message: FeedMessage) => void): () => void;
166
+ /**
167
+ * Joins `room`, now and after each reconnect, with the last feed cursor (or `since`). Resolves
168
+ * when the server acks the join.
169
+ */
170
+ join(room: string, since?: string): Promise<void>;
171
+ /**
172
+ * Holds `room`: joins it at the first hold, and leaves it when the last holder calls the
173
+ * function that this returns. The sync client, doc sessions and presence rooms use it, so
174
+ * one of them does not leave a room that another one still uses.
175
+ */
176
+ retain(room: string): () => void;
177
+ /** The number of holders of `room` (`retain` calls that are not released). */
178
+ holders(room: string): number;
179
+ /**
180
+ * Calls `listener` with the room after each change of its holders. A hold does not always
181
+ * send a message, so this is the only signal of the change. Returns a function that stops it.
182
+ */
183
+ onHoldersChange(listener: (room: string) => void): () => void;
184
+ /**
185
+ * Calls `listener` after each join ack of `room`: the first join and each join after a
186
+ * reconnect. When the room is joined now, it also calls it once, in a microtask. Returns a
187
+ * function that stops it.
188
+ */
189
+ onJoin(room: string, listener: () => void): () => void;
190
+ /**
191
+ * Calls `listener` after each join ack of `room` with `reset: true`, before the join
192
+ * listeners. The server could not send each change after the cursor of the client
193
+ * (ADR 0024), so the client must load the data of the room again. Returns a function that
194
+ * stops it.
195
+ */
196
+ onReset(room: string, listener: () => void): () => void;
197
+ /** Leaves `room`. Resolves when the server acks, or at once when the connection is not open. */
198
+ leave(room: string): Promise<void>;
199
+ /** Sends a message. Throws a NetworkError when the connection is not open. */
200
+ send(message: ClientMessage): void;
201
+ /**
202
+ * Sends a write with the id `id`. Resolves with the ack or the reject. Rejects with a
203
+ * NetworkError when the connection is not open, closes before the answer, or the server
204
+ * sends an error that a retry can fix.
205
+ */
206
+ write(id: string, room: string, op: StoreOp): Promise<WriteResult>;
207
+ /**
208
+ * Sends a ping and resolves at the pong. The server handles the messages of a connection in
209
+ * order, so at the pong it has each message that the client sent before the ping.
210
+ */
211
+ ping(): Promise<void>;
212
+ /** @internal */
213
+ handshake(signal: AbortSignal): Promise<void>;
214
+ /** @internal */
215
+ schedule(retry: () => void, attempt: number): () => void;
216
+ /** @internal */
217
+ enterOpen(): void;
218
+ /** @internal */
219
+ teardown(): void;
220
+ }
221
+ export {};
package/dist/db.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ import type { DBSchema, IDBPDatabase } from 'idb';
2
+ import type { JsonApiError, Resource, StoreOp } from '@dovetail-ts/protocol';
3
+ /** A write in the queue. */
4
+ export interface QueuedWrite {
5
+ /** The id of the write. It is also the id of the `write` message, so the server can see a resend. */
6
+ id: string;
7
+ /** The order of the writes. */
8
+ seq: number;
9
+ room: string;
10
+ op: StoreOp;
11
+ /** The ids of the earlier writes that this write waits for. */
12
+ dependsOn: string[];
13
+ /** The number of sends that failed with a network error. */
14
+ attempts: number;
15
+ /**
16
+ * The store state of each record of the write (by `type:id`) before the write, or null when
17
+ * the store did not have it. After a reload, a rollback goes back to it.
18
+ */
19
+ base?: Record<string, Resource | null>;
20
+ }
21
+ /** A write that the server rejected with a 4xx status. The UI can retry or discard it. */
22
+ export interface DeadLetter extends QueuedWrite {
23
+ status: number;
24
+ errors: JsonApiError[];
25
+ }
26
+ /** One update of a CRDT document. */
27
+ export interface StoredDocUpdate {
28
+ room: string;
29
+ doc: string;
30
+ update: Uint8Array;
31
+ }
32
+ export interface DovetailSchema extends DBSchema {
33
+ writes: {
34
+ key: string;
35
+ value: QueuedWrite;
36
+ indexes: {
37
+ seq: number;
38
+ };
39
+ };
40
+ dead: {
41
+ key: string;
42
+ value: DeadLetter;
43
+ indexes: {
44
+ seq: number;
45
+ };
46
+ };
47
+ docs: {
48
+ key: number;
49
+ value: StoredDocUpdate;
50
+ indexes: {
51
+ doc: [string, string];
52
+ };
53
+ };
54
+ }
55
+ export type DovetailDB = IDBPDatabase<DovetailSchema>;
56
+ /** Opens (and makes, the first time) the Dovetail database `name`. */
57
+ export declare function openDovetailDB(name?: string): Promise<DovetailDB>;
@@ -0,0 +1,45 @@
1
+ import type { DocHandle, DocStorage } from '@dovetail-ts/crdt';
2
+ import type { Timers } from './backoff';
3
+ import type { Connection } from './connection';
4
+ export interface DocSessionOptions {
5
+ connection: Connection;
6
+ room: string;
7
+ /** The name of the document in the room. */
8
+ doc: string;
9
+ /** The document: `engine.create()`. */
10
+ handle: DocHandle;
11
+ /** Where the local updates wait until the server has them: `IndexedDBDocStorage` or `MemoryDocStorage`. */
12
+ storage: DocStorage;
13
+ /** The timers of the awareness renewal. The default is the global scope. */
14
+ clock?: Timers;
15
+ /** The time in ms between two sends of the local awareness state. Default 15 000. */
16
+ awarenessRenewal?: number;
17
+ }
18
+ /**
19
+ * Syncs one document of a room with the server. Call `start()` once, and `destroy()` at the
20
+ * end. The room awareness goes to `handle.awareness`.
21
+ *
22
+ * Each local update goes to the storage, and to the server when the room is joined. After each
23
+ * join, the session sends step 1 and each stored update, and then a ping. The server handles
24
+ * the messages of a connection in order, so at the pong it has the updates: the session
25
+ * clears the storage and is `synced`.
26
+ */
27
+ export declare class DocSession {
28
+ #private;
29
+ readonly connection: Connection;
30
+ readonly room: string;
31
+ readonly doc: string;
32
+ readonly handle: DocHandle;
33
+ constructor(options: DocSessionOptions);
34
+ /** True when the server has each local update, and this client has the server updates. */
35
+ get synced(): boolean;
36
+ /** Calls `listener` on each change of `synced`. Returns a function that stops it. */
37
+ onSyncChange(listener: (synced: boolean) => void): () => void;
38
+ /**
39
+ * Applies the stored updates of an earlier page, and joins the room. A local update before
40
+ * it is not lost: it waits in the storage, and the join sends it.
41
+ */
42
+ start(): Promise<void>;
43
+ /** Stops the sync and leaves the room. The updates that the server does not have stay stored. */
44
+ destroy(): Promise<void>;
45
+ }
@@ -0,0 +1,18 @@
1
+ import type { DocKey, DocStorage } from '@dovetail-ts/crdt';
2
+ import type { DovetailDB } from './db';
3
+ /**
4
+ * A DocStorage on IndexedDB, in the same database as the write queue. The doc updates that a
5
+ * client makes offline stay after a reload, until the server has them. It takes the database or
6
+ * a promise of it, so a host can make it (and a `DocSession` on it) before the database opens.
7
+ *
8
+ * All tabs share the rows. So `clear` removes only the rows that this storage loaded or
9
+ * appended: the rows that its doc session sent. A row of another tab that came later stays.
10
+ */
11
+ export declare class IndexedDBDocStorage implements DocStorage {
12
+ #private;
13
+ constructor(db: DovetailDB | Promise<DovetailDB>);
14
+ append(room: string, doc: string, update: Uint8Array): Promise<void>;
15
+ load(room: string, doc: string): Promise<Uint8Array[]>;
16
+ clear(room: string, doc: string): Promise<void>;
17
+ docs(): Promise<DocKey[]>;
18
+ }