foldkit-sync 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Patrick Glenn
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 ADDED
@@ -0,0 +1,154 @@
1
+ # `foldkit-sync`
2
+
3
+ A local-first replica of a shared Foldkit projection. The application's Message
4
+ union and `update` stay authoritative; sync wraps them rather than introducing a
5
+ second reducer.
6
+
7
+ ```ts
8
+ import { Effect } from 'effect'
9
+ import { defineSync, indexedDb, layerFromPromise } from 'foldkit-sync'
10
+
11
+ const Sync = defineSync({ ... })
12
+
13
+ const replica = await Effect.runPromise(
14
+ Sync.openReplica('tab-1', await indexedDb('todos-tab-1')),
15
+ )
16
+ await Effect.runPromise(
17
+ replica.submit(Message.CreatedTodo({ id: crypto.randomUUID(), title: 'Milk' })),
18
+ )
19
+ await Effect.runPromise(Effect.provide(replica.synchronize, layerFromPromise(transport)))
20
+
21
+ const shared = Effect.runSync(replica.shared)
22
+ ```
23
+
24
+ ## What it owns
25
+
26
+ - The operation envelope: `replicaId:localSequence` identity, `baseCursor`, and
27
+ protocol/schema versions.
28
+ - A persisted outbox and optimistic projection: a durable Message is visible
29
+ immediately and rebased onto the authoritative order.
30
+ - Reconciliation: committed operations are replayed in order, acknowledged or
31
+ refused pending entries are dropped, and a checkpoint replaces the compacted
32
+ prefix.
33
+ - Strict decoding: an operation is always validated with the application's
34
+ Message schema, and a Message the contract does not call durable is refused.
35
+ - Presence (`createPresence`): an ephemeral, TTL'd peer registry, deliberately
36
+ outside the durable log. A peer that stops refreshing is dropped, not
37
+ replayed. Every value is decoded through the required `decodeValue` before it
38
+ is stored, so a hostile peer cannot inject a value your `Update` type does not
39
+ describe. Presence can travel over a socket — `socketPresenceChannel` on the
40
+ client and `servePresence` fanning through a `createPresenceHub` on the server
41
+ — or in-process via `loopbackPresenceChannel`.
42
+ - The transport seam (`Transport`): an Effect service with a loopback layer, a
43
+ bridge to and from the promise client the replica speaks, and a WebSocket
44
+ client layer. The socket reconnects on an exponential, jittered backoff and
45
+ re-sends queued and in-flight frames with their original ids, so a lost reply
46
+ is answered rather than dropped; retries (`maxRetries`) and the queue
47
+ (`maxQueue`) are bounded, and `serveSocket` is the server side of a
48
+ connection. A refusal is an exchange result; only a wire failure is a
49
+ `TransportError`.
50
+
51
+ ## Limits
52
+
53
+ - IndexedDB is the only storage adapter.
54
+ - It assumes an authoritative, single-writer-per-document server that orders
55
+ operations; there is no peer-to-peer replication. Applications can opt individual
56
+ fields into the specialized merge helper below.
57
+ - Binding the socket transport and presence server to a platform WebSocket
58
+ server is left to the application; the sync example shows a `ws` one for the
59
+ transport (presence over `ws` is not wired there yet).
60
+
61
+ ## Last-writer-wins fields (M8, experimental)
62
+
63
+ Use `lwwRegister` when a field's winner should depend on a write's logical time
64
+ instead of the order offline clients reconnect. It returns a schema and a pure
65
+ `merge` function to call inside the application's existing `update`:
66
+
67
+ ```ts
68
+ import { Schema } from 'effect'
69
+ import { lwwRegister } from 'foldkit-sync'
70
+
71
+ const Title = lwwRegister(Schema.String)
72
+ const Shared = Schema.Struct({ title: Title.schema })
73
+ const Renamed = Schema.Struct({ _tag: Schema.Literal('Renamed'), title: Title.schema })
74
+
75
+ const update = (model: typeof Shared.Type, message: typeof Renamed.Type) => ({
76
+ ...model,
77
+ title: Title.merge(model.title, message.title),
78
+ })
79
+
80
+ const message: typeof Renamed.Type = {
81
+ _tag: 'Renamed',
82
+ title: { stamp: { counter: 1, replicaId: 'tab-a' }, value: 'Milk' },
83
+ }
84
+ ```
85
+
86
+ Higher `counter` wins; equal counters use lexicographic UTF-16 `replicaId`
87
+ order, independent of locale. This is logical ordering, not wall-clock time.
88
+ The rule follows the total-order register model described in
89
+ [Replicated Data Types: Specification, Verification, Optimality](https://www.microsoft.com/en-us/research/publication/replicated-data-types-specification-verification-optimality/).
90
+
91
+ Allocate stamps **before dispatch**, never in `update` or replay. `openLwwClock`
92
+ persists a counter independently of the outbox, so a rejected or unsubmitted
93
+ write cannot cause timestamp reuse after reload:
94
+
95
+ ```ts
96
+ import { Effect } from 'effect'
97
+ import { indexedDb, openLwwClock } from 'foldkit-sync'
98
+
99
+ const clock = await openLwwClock({
100
+ documentId: 'todos',
101
+ replicaId: 'tab-a',
102
+ storage: await indexedDb('todos-tab-a-clock'),
103
+ })
104
+ try {
105
+ const stamp = await clock.next(Effect.runSync(replica.shared).title.stamp.counter)
106
+ await Effect.runPromise(
107
+ replica.submit({ _tag: 'Renamed', title: { stamp, value: 'Milk' } }),
108
+ )
109
+ } finally {
110
+ await clock.close()
111
+ }
112
+ ```
113
+
114
+ Use a **separate database** from the replica's outbox, with one clock per
115
+ document/writer. `next(observedCounter)` returns only after persisting a counter
116
+ greater than both its saved value and the supplied observation. Pass the latest
117
+ observed counter for the field being edited; when causality spans several
118
+ registers, pass their maximum. Calling `next()` without an observation advances
119
+ only the saved local counter. The clock does not inspect application state.
120
+
121
+ Allocations on one handle are serialized. Separate handles use storage's
122
+ compare-and-swap check; a stale handle fails and must be closed and reopened.
123
+ Storage failures reject allocation without returning a stamp. Counter gaps after
124
+ a crash or failed submission are harmless. Counters are nonnegative safe
125
+ integers; exhaustion fails before writing. `close()` waits for accepted
126
+ allocations and refuses new ones. Opening takes ownership of storage and closes
127
+ it on initialization failure too.
128
+
129
+ Keep the clock database across reloads and outbox resets. If it is lost or
130
+ deleted, use a fresh replica id instead of resetting the same writer's counter.
131
+ For applications that allocate stamps themselves, preserve this same durable
132
+ high-water mark, including refused writes.
133
+
134
+ A stamp identifies one immutable write within a register. Repeated delivery of
135
+ the same value is harmless; different values with the same stamp throw. Value
136
+ equality comes from the supplied schema. `merge` takes decoded values, while
137
+ the Message and shared-state schemas perform validation at the normal sync
138
+ boundaries. Transforming value codecs retain both their encoded and decoded
139
+ types.
140
+
141
+ Keep the **whole register**, including the winning stamp, in shared snapshots.
142
+ For deletion, `lwwRegister(Schema.NullOr(Entity))` can retain a `null` tombstone:
143
+ dropping its stamp would allow an old offline write to resurrect the value.
144
+ A newer write may intentionally replace that tombstone.
145
+
146
+ The journal still orders and authorizes every operation, including losing writes.
147
+ Replica ids and counters in Messages are client-authored data, not authenticated
148
+ identity. Applications must enforce writer ownership and clock policy at admission
149
+ where needed. A losing write can still trigger a Command if the application's
150
+ update produces one; this helper only resolves state.
151
+
152
+ These M8 helpers do not change the todo example's persisted schema or claim
153
+ arbitrary Messages commute. Specialized sets, counters and collaborative text
154
+ remain future work.
@@ -0,0 +1,378 @@
1
+ import { Context, Duration, Effect, Layer, Metric, Schema } from "effect";
2
+ //#region src/indexedDb.d.ts
3
+ /** Persists a replica's state with compare-and-swap on its revision. */
4
+ interface Storage<State = unknown> {
5
+ load(): Promise<unknown>;
6
+ save(state: State, expectedRevision: number | null): Promise<void>;
7
+ close(): void;
8
+ }
9
+ /** One database per document/replica; CAS prevents two tabs from sharing a writer identity. */
10
+ export declare const indexedDb: <State = unknown>(name: string, factory?: IDBFactory) => Promise<Storage<State>>;
11
+ //#endregion
12
+ //#region src/errors.d.ts
13
+ declare const StorageError_base: Schema.Class<StorageError, Schema.TaggedStruct<"StorageError", {
14
+ readonly message: Schema.String;
15
+ readonly cause: Schema.optional<Schema.Unknown>;
16
+ }>, import("effect/Cause").YieldableError>;
17
+ /** The persisted storage could not be read or written. */
18
+ export declare class StorageError extends StorageError_base {}
19
+ declare const WrongReplicaStorageError_base: Schema.Class<WrongReplicaStorageError, Schema.TaggedStruct<"WrongReplicaStorageError", {
20
+ readonly documentId: Schema.String;
21
+ readonly replicaId: Schema.String;
22
+ readonly message: Schema.String;
23
+ }>, import("effect/Cause").YieldableError>;
24
+ /** The storage holds a different replica's state. */
25
+ export declare class WrongReplicaStorageError extends WrongReplicaStorageError_base {}
26
+ declare const InvalidReplicaHistoryError_base: Schema.Class<InvalidReplicaHistoryError, Schema.TaggedStruct<"InvalidReplicaHistoryError", {
27
+ readonly message: Schema.String;
28
+ readonly cause: Schema.optional<Schema.Unknown>;
29
+ }>, import("effect/Cause").YieldableError>;
30
+ /** The persisted replica history is internally inconsistent. */
31
+ export declare class InvalidReplicaHistoryError extends InvalidReplicaHistoryError_base {}
32
+ declare const InvalidOutboxError_base: Schema.Class<InvalidOutboxError, Schema.TaggedStruct<"InvalidOutboxError", {
33
+ readonly message: Schema.String;
34
+ }>, import("effect/Cause").YieldableError>;
35
+ /** A persisted pending operation could not have been produced by this replica. */
36
+ export declare class InvalidOutboxError extends InvalidOutboxError_base {}
37
+ declare const CheckpointRegressionError_base: Schema.Class<CheckpointRegressionError, Schema.TaggedStruct<"CheckpointRegressionError", {
38
+ readonly cursor: Schema.Number;
39
+ readonly checkpointCursor: Schema.Number;
40
+ readonly message: Schema.String;
41
+ }>, import("effect/Cause").YieldableError>;
42
+ /** The server sent a checkpoint older than the replica's cursor. */
43
+ export declare class CheckpointRegressionError extends CheckpointRegressionError_base {}
44
+ declare const CommittedOrderError_base: Schema.Class<CommittedOrderError, Schema.TaggedStruct<"CommittedOrderError", {
45
+ readonly expected: Schema.Number;
46
+ readonly actual: Schema.Number;
47
+ readonly message: Schema.String;
48
+ }>, import("effect/Cause").YieldableError>;
49
+ /** Committed operations were not contiguous from the replica's cursor. */
50
+ export declare class CommittedOrderError extends CommittedOrderError_base {}
51
+ declare const ForeignRejectionError_base: Schema.Class<ForeignRejectionError, Schema.TaggedStruct<"ForeignRejectionError", {
52
+ readonly opId: Schema.String;
53
+ readonly message: Schema.String;
54
+ }>, import("effect/Cause").YieldableError>;
55
+ /** The server rejected an operation the replica never sent. */
56
+ export declare class ForeignRejectionError extends ForeignRejectionError_base {}
57
+ declare const ReplicaClosedError_base: Schema.Class<ReplicaClosedError, Schema.TaggedStruct<"ReplicaClosedError", {
58
+ readonly message: Schema.String;
59
+ }>, import("effect/Cause").YieldableError>;
60
+ /** The replica was closed while work was still being submitted. */
61
+ export declare class ReplicaClosedError extends ReplicaClosedError_base {}
62
+ type ReplicaError = StorageError | WrongReplicaStorageError | InvalidReplicaHistoryError | InvalidOutboxError | CheckpointRegressionError | CommittedOrderError | ForeignRejectionError | ReplicaClosedError;
63
+ //#endregion
64
+ //#region src/lww.d.ts
65
+ /** A logical write time; replica ids break concurrent ties using UTF-16 order. */
66
+ declare const Stamp: Schema.Struct<{
67
+ readonly counter: Schema.Number;
68
+ readonly replicaId: Schema.NonEmptyString;
69
+ }>;
70
+ declare const ClockState: Schema.Struct<{
71
+ readonly schemaVersion: Schema.Literal<1>;
72
+ readonly documentId: Schema.NonEmptyString;
73
+ readonly replicaId: Schema.NonEmptyString;
74
+ readonly revision: Schema.Number;
75
+ }>;
76
+ type LwwClockState = typeof ClockState.Type;
77
+ interface LwwClock {
78
+ /** Persists a timestamp beyond the saved counter and supplied observation. */
79
+ next(observedCounter?: number): Promise<typeof Stamp.Type>;
80
+ /** Drains accepted allocations and closes storage; repeated calls share completion. */
81
+ close(): Promise<void>;
82
+ }
83
+ /** Opens a durable clock in its own storage, taking ownership even if opening fails. */
84
+ export declare const openLwwClock: ({ documentId, replicaId, storage }: {
85
+ readonly documentId: string;
86
+ readonly replicaId: string;
87
+ readonly storage: Storage<LwwClockState>;
88
+ }) => Promise<LwwClock>;
89
+ /**
90
+ * A schema and reducer helper for a last-writer-wins register.
91
+ * Allocate a unique stamp per write before dispatch, and retain it in the Message.
92
+ * Merge is for decoded values; the application's schema validates wire input.
93
+ */
94
+ export declare const lwwRegister: <Value, Encoded, RD, RE>(value: Schema.Codec<Value, Encoded, RD, RE>) => {
95
+ schema: Schema.Struct<{
96
+ readonly stamp: Schema.Struct<{
97
+ readonly counter: Schema.Number;
98
+ readonly replicaId: Schema.NonEmptyString;
99
+ }>;
100
+ readonly value: Schema.Codec<Value, Encoded, RD, RE>;
101
+ }>;
102
+ merge: (left: {
103
+ readonly stamp: {
104
+ readonly counter: number;
105
+ readonly replicaId: string;
106
+ };
107
+ readonly value: Value;
108
+ }, right: {
109
+ readonly stamp: {
110
+ readonly counter: number;
111
+ readonly replicaId: string;
112
+ };
113
+ readonly value: Value;
114
+ }) => {
115
+ readonly stamp: {
116
+ readonly counter: number;
117
+ readonly replicaId: string;
118
+ };
119
+ readonly value: Value;
120
+ };
121
+ };
122
+ //#endregion
123
+ //#region src/sync.d.ts
124
+ /** A client-authored operation envelope. `message` is the application's encoded Message. */
125
+ declare const OperationSchema: Schema.Struct<{
126
+ readonly protocolVersion: Schema.Literal<1>;
127
+ readonly schemaVersion: Schema.Literal<1>;
128
+ readonly documentId: Schema.NonEmptyString;
129
+ readonly replicaId: Schema.NonEmptyString;
130
+ readonly localSequence: Schema.Number;
131
+ readonly opId: Schema.NonEmptyString;
132
+ readonly baseCursor: Schema.Number;
133
+ readonly message: Schema.Unknown;
134
+ }>;
135
+ type Operation = typeof OperationSchema.Type;
136
+ /** An operation the server committed, with its authoritative order and actor. */
137
+ declare const CommittedSchema: Schema.Struct<{
138
+ readonly serverSequence: Schema.Number;
139
+ readonly actorId: Schema.NonEmptyString;
140
+ readonly protocolVersion: Schema.Literal<1>;
141
+ readonly schemaVersion: Schema.Literal<1>;
142
+ readonly documentId: Schema.NonEmptyString;
143
+ readonly replicaId: Schema.NonEmptyString;
144
+ readonly localSequence: Schema.Number;
145
+ readonly opId: Schema.NonEmptyString;
146
+ readonly baseCursor: Schema.Number;
147
+ readonly message: Schema.Unknown;
148
+ }>;
149
+ type Committed = typeof CommittedSchema.Type;
150
+ /** Counters and a histogram an application can scrape. */
151
+ export declare const syncMetrics: {
152
+ exchanges: Metric.Counter<number>;
153
+ applied: Metric.Counter<number>;
154
+ checkpoints: Metric.Counter<number>;
155
+ exchangePending: Metric.Histogram<number>;
156
+ };
157
+ interface Checkpoint<Shared> {
158
+ readonly cursor: number;
159
+ readonly model: Shared;
160
+ }
161
+ interface Exchange<Shared> {
162
+ readonly operations: ReadonlyArray<unknown>;
163
+ readonly rejected: ReadonlyArray<string>;
164
+ /** Sends from the request that are durably committed, so the replica can drop them. */
165
+ readonly acknowledged?: ReadonlyArray<string> | undefined;
166
+ /** The snapshot a replica predating compaction adopts in place of the log. */
167
+ readonly checkpoint?: Checkpoint<Shared> | undefined;
168
+ }
169
+ interface ReplicaState<Shared> {
170
+ readonly protocolVersion: 1;
171
+ readonly schemaVersion: 1;
172
+ readonly documentId: string;
173
+ readonly replicaId: string;
174
+ readonly revision: number;
175
+ readonly nextLocalSequence: number;
176
+ readonly cursor: number;
177
+ readonly committed: Shared;
178
+ readonly committedIds: ReadonlyArray<string>;
179
+ readonly pending: ReadonlyArray<Operation>;
180
+ }
181
+ /**
182
+ * What the promise-based edge adapter consumes; the Effect `Transport` service
183
+ * is the primary seam.
184
+ */
185
+ interface TransportClient {
186
+ exchange(cursor: number, pending: ReadonlyArray<Operation>): Promise<unknown>;
187
+ }
188
+ interface Replica<Message, Shared> {
189
+ /** The optimistic projection: committed state with pending operations replayed. */
190
+ readonly shared: Effect.Effect<Shared>;
191
+ readonly pending: Effect.Effect<ReadonlyArray<Operation>>;
192
+ readonly cursor: Effect.Effect<number>;
193
+ readonly submit: (message: Message) => Effect.Effect<void, ReplicaError>;
194
+ /** Reconciles against the server. The `Transport` service must be provided. */
195
+ readonly synchronize: Effect.Effect<void, ReplicaError | TransportError, Transport>;
196
+ readonly close: Effect.Effect<void>;
197
+ }
198
+ interface SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded> {
199
+ readonly documentId: string;
200
+ readonly message: Schema.Codec<Message, MessageEncoded, never, never>;
201
+ readonly shared: Schema.Codec<Shared, SharedEncoded, never, never>;
202
+ readonly empty: Shared;
203
+ readonly durable: (message: Message) => boolean;
204
+ readonly replay: (shared: Shared, message: Message) => Shared;
205
+ }
206
+ interface Sync<Message, Shared> {
207
+ readonly documentId: string;
208
+ readonly normalizeOperation: (input: unknown) => Operation;
209
+ readonly operationFrom: (input: unknown, documentId: string) => Operation;
210
+ readonly committedFrom: (input: unknown, documentId: string) => Committed;
211
+ readonly decodeExchange: (input: unknown) => Exchange<Shared>;
212
+ readonly openReplica: (replicaId: string, storage: Storage<ReplicaState<Shared>>) => Effect.Effect<Replica<Message, Shared>, ReplicaError>;
213
+ }
214
+ /**
215
+ * Binds the replicated-state protocol to one application contract.
216
+ *
217
+ * The returned codecs decide what is a valid operation and what the shared
218
+ * projection means; the replica owns the local outbox, optimistic projection,
219
+ * and reconciliation as Effects, and never runs a second reducer.
220
+ */
221
+ export declare const defineSync: <Message, Shared, MessageEncoded, SharedEncoded>(definition: SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded>) => Sync<Message, Shared>;
222
+ //#endregion
223
+ //#region src/transport.d.ts
224
+ declare const TransportError_base: Schema.Class<TransportError, Schema.TaggedStruct<"SyncTransportError", {
225
+ readonly message: Schema.String;
226
+ }>, import("effect/Cause").YieldableError>;
227
+ /** The wire failure of a transport. A refusal is a result, not an error. */
228
+ export declare class TransportError extends TransportError_base {}
229
+ /** One request/response frame, as it crosses a wire. */
230
+ interface ExchangeFrame {
231
+ readonly id: string;
232
+ readonly cursor: number;
233
+ readonly pending: ReadonlyArray<Operation>;
234
+ }
235
+ interface ExchangeReply {
236
+ readonly id: string;
237
+ readonly result?: unknown;
238
+ readonly error?: string;
239
+ }
240
+ interface TransportShape {
241
+ readonly exchange: (cursor: number, pending: ReadonlyArray<Operation>) => Effect.Effect<unknown, TransportError>;
242
+ }
243
+ declare const Transport_base: Context.ServiceClass<Transport, "foldkit-sync/Transport", TransportShape>;
244
+ /**
245
+ * The seam the replica syncs through.
246
+ *
247
+ * A service, not a concrete client, so an application substitutes an in-process
248
+ * transport, a socket, or a test double without the replica knowing. A refusal
249
+ * arrives in the exchange result; only a wire failure is a `TransportError`.
250
+ */
251
+ export declare class Transport extends Transport_base {}
252
+ /** A transport backed by an in-process handler, for tests and single-process demos. */
253
+ export declare const layerLoopback: (handler: (cursor: number, pending: ReadonlyArray<Operation>) => unknown | Promise<unknown>) => Layer.Layer<Transport>;
254
+ /** Wraps the promise-based client the replica already speaks. */
255
+ export declare const layerFromPromise: (transport: TransportClient) => Layer.Layer<Transport>;
256
+ /** Bridges the service back to the promise client the replica consumes. */
257
+ export declare const toPromise: (transport: TransportShape) => TransportClient;
258
+ /**
259
+ * Serves one accepted socket, answering each exchange frame.
260
+ *
261
+ * The counterpart to `layerSocket`: the handler returns the exchange result, or
262
+ * throws and the failure is written back as an error frame. Returns a function
263
+ * that stops serving.
264
+ */
265
+ export declare const serveSocket: (socket: SocketLike, options: {
266
+ readonly exchange: (cursor: number, pending: ReadonlyArray<Operation>) => unknown | Promise<unknown>;
267
+ }) => (() => void);
268
+ /** The minimal socket the layer needs; the global `WebSocket` satisfies it. */
269
+ interface SocketLike {
270
+ send(data: string): void;
271
+ close(): void;
272
+ onMessage(listener: (data: string) => void): () => void;
273
+ onClose(listener: () => void): () => void;
274
+ /**
275
+ * Optional. When provided, exchanges wait for it before sending, so a
276
+ * transport can connect asynchronously. Absent means already connected.
277
+ */
278
+ onOpen?(listener: () => void): () => void;
279
+ }
280
+ interface SocketOptions {
281
+ readonly url: string;
282
+ /** Injectable for tests; defaults to the platform `WebSocket`. */
283
+ readonly makeSocket?: ((url: string) => SocketLike) | undefined;
284
+ /** Reconnect attempts after a close before queued work fails. Default 5. */
285
+ readonly maxRetries?: number | undefined;
286
+ /** Base delay of the exponential reconnect backoff. Default `50 millis`. */
287
+ readonly retryBase?: Duration.Input | undefined;
288
+ /** Exchanges queued or in flight before new ones fail. Default 64. */
289
+ readonly maxQueue?: number | undefined;
290
+ }
291
+ /** The default socket factory: the platform `WebSocket`, as a `SocketLike`. */
292
+ export declare const nativeSocket: (url: string) => SocketLike;
293
+ /**
294
+ * A WebSocket client transport.
295
+ *
296
+ * One connection is live at a time. While it is connecting, exchanges queue; if
297
+ * it closes, the transport reconnects on an exponential, jittered backoff and
298
+ * re-sends every queued and in-flight frame with its original id, so a lost
299
+ * reply is answered rather than dropped and a late reply cannot resolve a newer
300
+ * frame. Once the retries are exhausted (or the layer closes) queued work fails
301
+ * with a `TransportError`; a queue over `maxQueue` fails new exchanges with
302
+ * backpressure. The socket is released when the layer's scope ends.
303
+ */
304
+ export declare const layerSocket: (options: SocketOptions) => Layer.Layer<Transport, TransportError>;
305
+ //#endregion
306
+ //#region src/presence.d.ts
307
+ /** One peer's presence. A `null` value means the peer left. */
308
+ interface PresenceUpdate<Update> {
309
+ readonly id: string;
310
+ readonly value: Update | null;
311
+ }
312
+ /**
313
+ * The ephemeral channel presence travels on.
314
+ *
315
+ * Deliberately not the durable transport: presence is broadcast, never
316
+ * journaled, so a dropped or duplicated update is harmless.
317
+ */
318
+ interface PresenceChannel<Update> {
319
+ publish(update: PresenceUpdate<Update>): void;
320
+ subscribe(listener: (update: PresenceUpdate<Update>) => void): () => void;
321
+ }
322
+ interface PresenceOptions<Update> {
323
+ /** This peer's identity on the channel. */
324
+ readonly id: string;
325
+ /** Milliseconds without an update before a peer is dropped. */
326
+ readonly ttl: number;
327
+ /**
328
+ * Validates the untrusted value a peer sends before it is stored. Presence
329
+ * crosses a wire, so this is required rather than trusting the type
330
+ * parameter; a value it rejects is dropped.
331
+ */
332
+ readonly decodeValue: (value: unknown) => Update;
333
+ readonly channel?: PresenceChannel<Update> | undefined;
334
+ /** Injectable clock, for tests. */
335
+ readonly now?: (() => number) | undefined;
336
+ }
337
+ interface PresencePeer<Update> {
338
+ readonly id: string;
339
+ readonly value: Update;
340
+ readonly updatedAt: number;
341
+ }
342
+ interface Presence<Update> {
343
+ /** Sets this peer's value and broadcasts it. */
344
+ set(value: Update): void;
345
+ /** Removes this peer and broadcasts the departure. */
346
+ leave(): void;
347
+ /** Live peers, self included, with stale ones excluded. */
348
+ peers(): ReadonlyArray<PresencePeer<Update>>;
349
+ /** Drops expired peers; notifies if any went. */
350
+ prune(): void;
351
+ subscribe(listener: () => void): () => void;
352
+ /** Stops listening to the channel. */
353
+ close(): void;
354
+ }
355
+ /**
356
+ * Tracks ephemeral peers with a time-to-live.
357
+ *
358
+ * Nothing here touches the durable log: presence is state a peer refreshes, and
359
+ * a peer that stops refreshing is dropped, not replayed.
360
+ */
361
+ export declare const createPresence: <Update>(options: PresenceOptions<Update>) => Presence<Update>;
362
+ /** An in-process channel, for tests and single-process demos. */
363
+ export declare const loopbackPresenceChannel: <Update>() => PresenceChannel<Update>;
364
+ /** Broadcasts presence updates among connected peers. */
365
+ interface PresenceHub<Update> {
366
+ /** Registers a peer's send; returns a leave function. */
367
+ join(send: (update: PresenceUpdate<Update>) => void): () => void;
368
+ /** Fans an update out to every joined peer. */
369
+ publish(update: PresenceUpdate<Update>): void;
370
+ }
371
+ export declare const createPresenceHub: <Update>() => PresenceHub<Update>;
372
+ /** A presence channel carried on a socket, alongside exchange frames. */
373
+ export declare const socketPresenceChannel: <Update>(socket: SocketLike) => PresenceChannel<Update>;
374
+ /** Serves presence frames on an accepted socket, fanning them through the hub. */
375
+ export declare const servePresence: <Update>(socket: SocketLike, hub: PresenceHub<Update>) => (() => void);
376
+ //#endregion
377
+ export type { Checkpoint, Committed, Exchange, ExchangeFrame, ExchangeReply, LwwClock, LwwClockState, Operation, Presence, PresenceChannel, PresenceHub, PresenceOptions, PresencePeer, PresenceUpdate, Replica, ReplicaError, ReplicaState, SocketLike, SocketOptions, Storage, Sync, SyncDefinition, TransportClient, TransportShape };
378
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/indexedDb.ts","../src/errors.ts","../src/lww.ts","../src/sync.ts","../src/transport.ts","../src/presence.ts"],"mappings":";;;UACiB,QAAQ;EACvB,QAAQ;EACR,KAAK,OAAO,OAAO,kCAAkC;EACrD;;;qBAIW,YAAmB,iBAC9B,cACA,UAAS,eACR,QAAQ,QAAQ;;;;;;;;qBCRN,qBAAqB;;;;;;;qBAMrB,iCAAiC;;;;;;qBAUjC,mCAAmC;;;;;qBASnC,2BAA2B;;;;;;;qBAQ3B,kCAAkC;;;;;;;qBAUlC,4BAA4B;;;;;;qBAU5B,8BAA8B;;;;;qBAS9B,2BAA2B;KAO5B,eACR,eACA,2BACA,6BACA,qBACA,4BACA,sBACA,wBACA;;;;cC5EE,OAAK,OAAA;;;;cASL,YAAU,OAAA;;;;;;KAOJ,uBAAuB,WAAW;UAE7B;;EAEf,KAAK,2BAA2B,eAAe,MAAM;;EAErD,SAAS;;;qBAOE,iBAAsB,YAAA,WAAA;WAKxB;WACA;WACA,SAAS,QAAQ;MACxB,QAAQ;;;;;;qBAiDC,cAAe,OAAO,SAAS,IAAI,IAC9C,OAAO,OAAO,MAAM,OAAO,SAAS,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cCrEpC,iBAAe,OAAA;;;;;;;;;;KAUT,mBAAmB,gBAAgB;;cAGzC,iBAAe,OAAA;;;;;;;;;;;;KAKT,mBAAmB,gBAAgB;;qBAclC;;;;;;UAgBI,WAAW;WACjB;WACA,OAAO;;UAGD,SAAS;WACf,YAAY;WACZ,UAAU;;WAEV,eAAe;;WAEf,aAAa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