foldkit-sync 0.8.0 → 0.10.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/README.md +238 -26
- package/dist/do.d.mts +60 -0
- package/dist/do.d.mts.map +1 -0
- package/dist/do.mjs +59 -0
- package/dist/do.mjs.map +1 -0
- package/dist/entity.d.mts +183 -0
- package/dist/entity.d.mts.map +1 -0
- package/dist/entity.mjs +143 -0
- package/dist/entity.mjs.map +1 -0
- package/dist/index.d.mts +45 -622
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +168 -340
- package/dist/index.mjs.map +1 -1
- package/dist/journal.d.mts +142 -0
- package/dist/journal.d.mts.map +1 -0
- package/dist/journal.mjs +212 -0
- package/dist/journal.mjs.map +1 -0
- package/dist/make-h5yD8STj.d.mts +714 -0
- package/dist/make-h5yD8STj.d.mts.map +1 -0
- package/dist/remote.d.mts +123 -0
- package/dist/remote.d.mts.map +1 -0
- package/dist/remote.mjs +163 -0
- package/dist/remote.mjs.map +1 -0
- package/dist/transport-DiKXy5zx.mjs +412 -0
- package/dist/transport-DiKXy5zx.mjs.map +1 -0
- package/package.json +38 -4
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from "effect";
|
|
2
|
+
//#region src/ids.ts
|
|
3
|
+
/** Identifies the replicated document a replica or operation belongs to. */
|
|
4
|
+
const DocumentId = Schema.NonEmptyString.pipe(Schema.brand("@foldkit-sync/DocumentId"));
|
|
5
|
+
/** Identifies one replica (writer identity) within a document. */
|
|
6
|
+
const ReplicaId = Schema.NonEmptyString.pipe(Schema.brand("@foldkit-sync/ReplicaId"));
|
|
7
|
+
/** The stable identity of one operation within a document. */
|
|
8
|
+
const OpId = Schema.NonEmptyString.pipe(Schema.brand("@foldkit-sync/OpId"));
|
|
9
|
+
/**
|
|
10
|
+
* A position in the committed document order. `0` is the start; a committed
|
|
11
|
+
* operation's `serverSequence` and a replica's `cursor` are the same family.
|
|
12
|
+
*/
|
|
13
|
+
const Sequence = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)).pipe(Schema.brand("@foldkit-sync/Sequence"));
|
|
14
|
+
/** A replica's own operation counter within a document; 1-based. */
|
|
15
|
+
const LocalSequence = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)).pipe(Schema.brand("@foldkit-sync/LocalSequence"));
|
|
16
|
+
/**
|
|
17
|
+
* Decode-and-brand helpers. A branded schema constructs the same value with
|
|
18
|
+
* `DocumentId.make('todos')`, which is the spelling to lead with; these stay
|
|
19
|
+
* for callers that already have them.
|
|
20
|
+
*/
|
|
21
|
+
const documentId = (value) => Schema.decodeUnknownSync(DocumentId)(value);
|
|
22
|
+
const replicaId = (value) => Schema.decodeUnknownSync(ReplicaId)(value);
|
|
23
|
+
const opId = (value) => Schema.decodeUnknownSync(OpId)(value);
|
|
24
|
+
const sequence = (value) => Schema.decodeUnknownSync(Sequence)(value);
|
|
25
|
+
const localSequence = (value) => Schema.decodeUnknownSync(LocalSequence)(value);
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/transport.ts
|
|
28
|
+
/** The wire failure of a transport. A refusal is a result, not an error. */
|
|
29
|
+
var TransportError = class extends Schema.TaggedError()("SyncTransportError", { message: Schema.String }) {};
|
|
30
|
+
/**
|
|
31
|
+
* The seam the replica syncs through.
|
|
32
|
+
*
|
|
33
|
+
* A service, not a concrete client, so an application substitutes an in-process
|
|
34
|
+
* transport, a socket, or a test double without the replica knowing. A refusal
|
|
35
|
+
* arrives in the exchange result; only a wire failure is a `TransportError`.
|
|
36
|
+
*/
|
|
37
|
+
var Transport = class extends Context.Service()("foldkit-sync/Transport") {};
|
|
38
|
+
const failure = (error) => new TransportError({ message: error instanceof Error ? error.message : String(error) });
|
|
39
|
+
/** A transport backed by an in-process handler, for tests and single-process demos. */
|
|
40
|
+
const layerLoopback = (handler) => Layer.succeed(Transport, { exchange: (cursor, pending, epoch) => Effect.tryPromise({
|
|
41
|
+
try: () => Promise.resolve(handler(cursor, pending, epoch)),
|
|
42
|
+
catch: failure
|
|
43
|
+
}) });
|
|
44
|
+
/** Wraps the promise-based client the replica already speaks. */
|
|
45
|
+
const layerFromPromise = (transport) => Layer.succeed(Transport, { exchange: (cursor, pending, epoch) => Effect.tryPromise({
|
|
46
|
+
try: () => transport.exchange(sequence(cursor), pending, epoch),
|
|
47
|
+
catch: failure
|
|
48
|
+
}) });
|
|
49
|
+
/** Bridges the service back to the promise client the replica consumes. */
|
|
50
|
+
const toPromise = (transport) => ({ exchange: (cursor, pending, epoch) => Effect.runPromise(transport.exchange(cursor, pending, epoch)) });
|
|
51
|
+
/**
|
|
52
|
+
* Serves one accepted socket, answering each exchange frame.
|
|
53
|
+
*
|
|
54
|
+
* The counterpart to `layerSocket`: the handler returns the exchange result, or
|
|
55
|
+
* throws and the failure is written back as an error frame. With `changes`, a
|
|
56
|
+
* subscription to the document's commits, the socket is also sent a
|
|
57
|
+
* `NotifyFrame` after each, so a client hears of others' edits without polling.
|
|
58
|
+
* Returns a function that stops serving.
|
|
59
|
+
*/
|
|
60
|
+
const serveSocket = (socket, options) => {
|
|
61
|
+
const send = (reply) => {
|
|
62
|
+
try {
|
|
63
|
+
socket.send(JSON.stringify(reply));
|
|
64
|
+
} catch {}
|
|
65
|
+
};
|
|
66
|
+
const stopMessage = socket.onMessage((data) => {
|
|
67
|
+
let parsed;
|
|
68
|
+
try {
|
|
69
|
+
parsed = JSON.parse(data);
|
|
70
|
+
} catch {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (typeof parsed !== "object" || parsed === null) return;
|
|
74
|
+
const { id, cursor, pending, epoch } = parsed;
|
|
75
|
+
if (typeof id !== "string") return;
|
|
76
|
+
if (typeof cursor !== "number" || !Number.isSafeInteger(cursor) || cursor < 0 || !Array.isArray(pending) || epoch !== void 0 && typeof epoch !== "string") {
|
|
77
|
+
send({
|
|
78
|
+
id,
|
|
79
|
+
error: "Invalid exchange frame"
|
|
80
|
+
});
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const frame = {
|
|
84
|
+
id,
|
|
85
|
+
cursor,
|
|
86
|
+
pending,
|
|
87
|
+
epoch: typeof epoch === "string" ? epoch : void 0
|
|
88
|
+
};
|
|
89
|
+
(async () => {
|
|
90
|
+
try {
|
|
91
|
+
const result = await options.exchange(frame.cursor, frame.pending, frame.epoch);
|
|
92
|
+
send({
|
|
93
|
+
id: frame.id,
|
|
94
|
+
result
|
|
95
|
+
});
|
|
96
|
+
} catch (error) {
|
|
97
|
+
send({
|
|
98
|
+
id: frame.id,
|
|
99
|
+
error: error instanceof Error ? error.message : String(error)
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
})();
|
|
103
|
+
});
|
|
104
|
+
const stopChanges = options.changes?.(() => send({ notify: true }));
|
|
105
|
+
const stop = () => {
|
|
106
|
+
stopMessage();
|
|
107
|
+
stopChanges?.();
|
|
108
|
+
};
|
|
109
|
+
const stopClose = socket.onClose(stop);
|
|
110
|
+
return () => {
|
|
111
|
+
stop();
|
|
112
|
+
stopClose();
|
|
113
|
+
};
|
|
114
|
+
};
|
|
115
|
+
/** The default socket factory: the platform `WebSocket`, as a `SocketLike`. */
|
|
116
|
+
const nativeSocket = (url) => {
|
|
117
|
+
const socket = new WebSocket(url);
|
|
118
|
+
return {
|
|
119
|
+
send: (data) => socket.send(data),
|
|
120
|
+
close: () => socket.close(),
|
|
121
|
+
onOpen: (listener) => {
|
|
122
|
+
if (socket.readyState === WebSocket.OPEN) {
|
|
123
|
+
listener();
|
|
124
|
+
return () => {};
|
|
125
|
+
}
|
|
126
|
+
socket.addEventListener("open", listener);
|
|
127
|
+
return () => socket.removeEventListener("open", listener);
|
|
128
|
+
},
|
|
129
|
+
onMessage: (listener) => {
|
|
130
|
+
const handler = (event) => listener(String(event.data));
|
|
131
|
+
socket.addEventListener("message", handler);
|
|
132
|
+
return () => socket.removeEventListener("message", handler);
|
|
133
|
+
},
|
|
134
|
+
onClose: (listener) => {
|
|
135
|
+
const handler = () => listener();
|
|
136
|
+
socket.addEventListener("close", handler);
|
|
137
|
+
return () => socket.removeEventListener("close", handler);
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* A socket over a `MessagePort`, for either end: its frames are the port's
|
|
143
|
+
* string messages, and anything else on the port is ignored. A port tells
|
|
144
|
+
* neither end when the other goes, so `onClose` fires once, on `close()` or
|
|
145
|
+
* when `signal` aborts; a host that serves a pane aborts it when the pane is
|
|
146
|
+
* gone, which stops `serveSocket` and anything else listening.
|
|
147
|
+
*/
|
|
148
|
+
const portSocket = (port, options = {}) => {
|
|
149
|
+
const closeListeners = /* @__PURE__ */ new Set();
|
|
150
|
+
let closed = false;
|
|
151
|
+
const close = () => {
|
|
152
|
+
closed = true;
|
|
153
|
+
port.close();
|
|
154
|
+
for (const listener of [...closeListeners]) listener();
|
|
155
|
+
closeListeners.clear();
|
|
156
|
+
};
|
|
157
|
+
options.signal?.addEventListener("abort", close, { once: true });
|
|
158
|
+
if (options.signal?.aborted === true) close();
|
|
159
|
+
port.start();
|
|
160
|
+
return {
|
|
161
|
+
send: (data) => port.postMessage(data),
|
|
162
|
+
close,
|
|
163
|
+
onMessage: (listener) => {
|
|
164
|
+
const handler = (event) => {
|
|
165
|
+
if (typeof event.data === "string") listener(event.data);
|
|
166
|
+
};
|
|
167
|
+
port.addEventListener("message", handler);
|
|
168
|
+
return () => port.removeEventListener("message", handler);
|
|
169
|
+
},
|
|
170
|
+
onClose: (listener) => {
|
|
171
|
+
if (closed) {
|
|
172
|
+
listener();
|
|
173
|
+
return () => {};
|
|
174
|
+
}
|
|
175
|
+
closeListeners.add(listener);
|
|
176
|
+
return () => closeListeners.delete(listener);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
};
|
|
180
|
+
/**
|
|
181
|
+
* A socket over an existing `WebSocket`: the accepted end of a Cloudflare
|
|
182
|
+
* `WebSocketPair`, or any other socket the platform hands over. Unlike
|
|
183
|
+
* `nativeSocket` it opens nothing — accept the pair first — and unlike
|
|
184
|
+
* `portSocket` there is no signal: the socket closing, erroring, or being
|
|
185
|
+
* closed fires `onClose` once, which is how a host stops serving it.
|
|
186
|
+
*/
|
|
187
|
+
const workerSocket = (socket) => {
|
|
188
|
+
const messageListeners = /* @__PURE__ */ new Set();
|
|
189
|
+
const closeListeners = /* @__PURE__ */ new Set();
|
|
190
|
+
let closed = false;
|
|
191
|
+
const forget = () => {
|
|
192
|
+
socket.removeEventListener("message", onMessageEvent);
|
|
193
|
+
socket.removeEventListener("close", onClosedEvent);
|
|
194
|
+
socket.removeEventListener("error", onClosedEvent);
|
|
195
|
+
};
|
|
196
|
+
const fireClose = () => {
|
|
197
|
+
closed = true;
|
|
198
|
+
forget();
|
|
199
|
+
for (const listener of [...closeListeners]) listener();
|
|
200
|
+
closeListeners.clear();
|
|
201
|
+
};
|
|
202
|
+
const onMessageEvent = (event) => {
|
|
203
|
+
for (const listener of [...messageListeners]) listener(String(event.data));
|
|
204
|
+
};
|
|
205
|
+
const onClosedEvent = () => {
|
|
206
|
+
fireClose();
|
|
207
|
+
};
|
|
208
|
+
socket.addEventListener("message", onMessageEvent);
|
|
209
|
+
socket.addEventListener("close", onClosedEvent);
|
|
210
|
+
socket.addEventListener("error", onClosedEvent);
|
|
211
|
+
return {
|
|
212
|
+
send: (data) => socket.send(data),
|
|
213
|
+
close: () => {
|
|
214
|
+
try {
|
|
215
|
+
socket.close();
|
|
216
|
+
} catch {}
|
|
217
|
+
fireClose();
|
|
218
|
+
},
|
|
219
|
+
onMessage: (listener) => {
|
|
220
|
+
messageListeners.add(listener);
|
|
221
|
+
return () => messageListeners.delete(listener);
|
|
222
|
+
},
|
|
223
|
+
onClose: (listener) => {
|
|
224
|
+
if (closed) {
|
|
225
|
+
listener();
|
|
226
|
+
return () => {};
|
|
227
|
+
}
|
|
228
|
+
closeListeners.add(listener);
|
|
229
|
+
return () => closeListeners.delete(listener);
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
};
|
|
233
|
+
const connector = (options) => {
|
|
234
|
+
if (options.makeSocket !== void 0) return options.makeSocket;
|
|
235
|
+
const { url } = options;
|
|
236
|
+
return () => nativeSocket(url);
|
|
237
|
+
};
|
|
238
|
+
/**
|
|
239
|
+
* A WebSocket client transport.
|
|
240
|
+
*
|
|
241
|
+
* One connection is live at a time. While it is connecting, exchanges queue; if
|
|
242
|
+
* it closes, the transport reconnects on an exponential, jittered backoff and
|
|
243
|
+
* re-sends every queued and in-flight frame with its original id, so a lost
|
|
244
|
+
* reply is answered rather than dropped and a late reply cannot resolve a newer
|
|
245
|
+
* frame. It never stops reconnecting: after `maxRetries` consecutive failures
|
|
246
|
+
* queued work fails with a `TransportError`, and exchanges fail fast while no
|
|
247
|
+
* socket is up, until a socket opens. The count resets only when a connection
|
|
248
|
+
* proves healthy, by answering a frame or by staying open for `maxRetryDelay`:
|
|
249
|
+
* a server that accepts a socket and drops it at once is backed off like one
|
|
250
|
+
* that refuses it. A queue over `maxQueue` fails new
|
|
251
|
+
* exchanges with backpressure. The socket is released when the layer's scope
|
|
252
|
+
* ends.
|
|
253
|
+
*/
|
|
254
|
+
const layerSocket = (options) => Layer.effect(Transport, Effect.fn("Transport.layerSocket")(function* () {
|
|
255
|
+
const makeSocket = connector(options);
|
|
256
|
+
const maxQueue = options.maxQueue ?? 64;
|
|
257
|
+
const maxRetries = options.maxRetries ?? 5;
|
|
258
|
+
const retryBase = Duration.toMillis(Duration.fromInputUnsafe(options.retryBase ?? "50 millis"));
|
|
259
|
+
const maxRetryDelay = Duration.toMillis(Duration.fromInputUnsafe(options.maxRetryDelay ?? "5 seconds"));
|
|
260
|
+
const clock = yield* Clock.Clock;
|
|
261
|
+
const notices = yield* PubSub.sliding(1);
|
|
262
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
263
|
+
const shared = {
|
|
264
|
+
send: (data) => {
|
|
265
|
+
if (ready) socket?.send(data);
|
|
266
|
+
},
|
|
267
|
+
close: () => {},
|
|
268
|
+
onMessage: (listener) => {
|
|
269
|
+
listeners.add(listener);
|
|
270
|
+
return () => listeners.delete(listener);
|
|
271
|
+
},
|
|
272
|
+
onClose: () => () => {}
|
|
273
|
+
};
|
|
274
|
+
const queued = [];
|
|
275
|
+
const inFlight = /* @__PURE__ */ new Map();
|
|
276
|
+
let socket;
|
|
277
|
+
let ready = false;
|
|
278
|
+
let nextId = 0;
|
|
279
|
+
let disposed = false;
|
|
280
|
+
let failures = 0;
|
|
281
|
+
const healthy = () => {
|
|
282
|
+
failures = 0;
|
|
283
|
+
};
|
|
284
|
+
const send = (entry) => {
|
|
285
|
+
inFlight.set(entry.id, entry);
|
|
286
|
+
socket?.send(JSON.stringify({
|
|
287
|
+
id: entry.id,
|
|
288
|
+
cursor: entry.cursor,
|
|
289
|
+
pending: entry.pending,
|
|
290
|
+
...entry.epoch === void 0 ? {} : { epoch: entry.epoch }
|
|
291
|
+
}));
|
|
292
|
+
};
|
|
293
|
+
const flush = () => {
|
|
294
|
+
if (socket === void 0 || !ready) return;
|
|
295
|
+
for (const entry of queued.splice(0)) send(entry);
|
|
296
|
+
};
|
|
297
|
+
const requeue = () => {
|
|
298
|
+
queued.unshift(...inFlight.values());
|
|
299
|
+
inFlight.clear();
|
|
300
|
+
};
|
|
301
|
+
const failAll = (message) => {
|
|
302
|
+
const entries = [...queued.splice(0), ...inFlight.values()];
|
|
303
|
+
inFlight.clear();
|
|
304
|
+
for (const entry of entries) entry.resume(Effect.fail(new TransportError({ message })));
|
|
305
|
+
};
|
|
306
|
+
const connect = Effect.tryPromise({
|
|
307
|
+
try: () => new Promise((resolve, reject) => {
|
|
308
|
+
const next = makeSocket();
|
|
309
|
+
socket = next;
|
|
310
|
+
ready = next.onOpen === void 0;
|
|
311
|
+
let openedAt = ready ? clock.currentTimeMillisUnsafe() : void 0;
|
|
312
|
+
const opened = () => {
|
|
313
|
+
PubSub.publishUnsafe(notices, void 0);
|
|
314
|
+
};
|
|
315
|
+
const offOpen = next.onOpen?.(() => {
|
|
316
|
+
ready = true;
|
|
317
|
+
openedAt = clock.currentTimeMillisUnsafe();
|
|
318
|
+
opened();
|
|
319
|
+
flush();
|
|
320
|
+
});
|
|
321
|
+
const offMessage = next.onMessage((data) => {
|
|
322
|
+
for (const listener of [...listeners]) try {
|
|
323
|
+
listener(data);
|
|
324
|
+
} catch {}
|
|
325
|
+
let reply;
|
|
326
|
+
try {
|
|
327
|
+
reply = JSON.parse(data);
|
|
328
|
+
} catch {
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
if (typeof reply !== "object" || reply === null) return;
|
|
332
|
+
if ("notify" in reply) {
|
|
333
|
+
if (reply.notify === true) PubSub.publishUnsafe(notices, void 0);
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
const entry = inFlight.get(reply.id);
|
|
337
|
+
if (entry === void 0) return;
|
|
338
|
+
healthy();
|
|
339
|
+
inFlight.delete(reply.id);
|
|
340
|
+
entry.resume(reply.error === void 0 ? Effect.succeed(reply.result) : Effect.fail(new TransportError({ message: reply.error })));
|
|
341
|
+
});
|
|
342
|
+
const offClose = next.onClose(() => {
|
|
343
|
+
offOpen?.();
|
|
344
|
+
offMessage();
|
|
345
|
+
offClose();
|
|
346
|
+
socket = void 0;
|
|
347
|
+
ready = false;
|
|
348
|
+
if (openedAt !== void 0 && clock.currentTimeMillisUnsafe() - openedAt >= maxRetryDelay) healthy();
|
|
349
|
+
requeue();
|
|
350
|
+
reject(/* @__PURE__ */ new Error("transport closed"));
|
|
351
|
+
});
|
|
352
|
+
if (ready) {
|
|
353
|
+
opened();
|
|
354
|
+
flush();
|
|
355
|
+
}
|
|
356
|
+
}),
|
|
357
|
+
catch: () => new TransportError({ message: "transport closed" })
|
|
358
|
+
});
|
|
359
|
+
yield* Effect.forkScoped(Effect.gen(function* () {
|
|
360
|
+
while (!disposed) {
|
|
361
|
+
yield* Effect.exit(connect);
|
|
362
|
+
if (disposed) return;
|
|
363
|
+
failures += 1;
|
|
364
|
+
if (failures > maxRetries) failAll("transport closed");
|
|
365
|
+
const backoff = Math.min(maxRetryDelay, retryBase * 2 ** Math.min(failures - 1, 30));
|
|
366
|
+
yield* Effect.sleep(backoff * (.8 + Math.random() * .4));
|
|
367
|
+
}
|
|
368
|
+
}));
|
|
369
|
+
yield* Effect.addFinalizer(() => Effect.sync(() => {
|
|
370
|
+
disposed = true;
|
|
371
|
+
ready = false;
|
|
372
|
+
socket?.close();
|
|
373
|
+
socket = void 0;
|
|
374
|
+
failAll("transport closed");
|
|
375
|
+
}));
|
|
376
|
+
return Transport.of({
|
|
377
|
+
changes: Stream.fromPubSub(notices),
|
|
378
|
+
socket: shared,
|
|
379
|
+
exchange: (cursor, pending, epoch) => Effect.callback((resume) => {
|
|
380
|
+
if (disposed) {
|
|
381
|
+
resume(Effect.fail(new TransportError({ message: "transport closed" })));
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
if (failures > maxRetries && !ready) {
|
|
385
|
+
resume(Effect.fail(new TransportError({ message: "transport closed" })));
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
if (queued.length + inFlight.size >= maxQueue) {
|
|
389
|
+
resume(Effect.fail(new TransportError({ message: "transport queue full" })));
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
const entry = {
|
|
393
|
+
id: String(nextId++),
|
|
394
|
+
cursor,
|
|
395
|
+
pending,
|
|
396
|
+
epoch,
|
|
397
|
+
resume
|
|
398
|
+
};
|
|
399
|
+
if (ready) send(entry);
|
|
400
|
+
else queued.push(entry);
|
|
401
|
+
return Effect.sync(() => {
|
|
402
|
+
const queuedIndex = queued.indexOf(entry);
|
|
403
|
+
if (queuedIndex >= 0) queued.splice(queuedIndex, 1);
|
|
404
|
+
if (inFlight.get(entry.id) === entry) inFlight.delete(entry.id);
|
|
405
|
+
});
|
|
406
|
+
})
|
|
407
|
+
});
|
|
408
|
+
})());
|
|
409
|
+
//#endregion
|
|
410
|
+
export { localSequence as _, layerSocket as a, sequence as b, serveSocket as c, DocumentId as d, LocalSequence as f, documentId as g, Sequence as h, layerLoopback as i, toPromise as l, ReplicaId as m, TransportError as n, nativeSocket as o, OpId as p, layerFromPromise as r, portSocket as s, Transport as t, workerSocket as u, opId as v, replicaId as y };
|
|
411
|
+
|
|
412
|
+
//# sourceMappingURL=transport-DiKXy5zx.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transport-DiKXy5zx.mjs","names":[],"sources":["../src/ids.ts","../src/transport.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** Identifies the replicated document a replica or operation belongs to. */\nexport const DocumentId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/DocumentId'))\nexport type DocumentId = typeof DocumentId.Type\n\n/** Identifies one replica (writer identity) within a document. */\nexport const ReplicaId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/ReplicaId'))\nexport type ReplicaId = typeof ReplicaId.Type\n\n/** The stable identity of one operation within a document. */\nexport const OpId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/OpId'))\nexport type OpId = typeof OpId.Type\n\n/**\n * A position in the committed document order. `0` is the start; a committed\n * operation's `serverSequence` and a replica's `cursor` are the same family.\n */\nexport const Sequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/Sequence'))\nexport type Sequence = typeof Sequence.Type\n\n/** A replica's own operation counter within a document; 1-based. */\nexport const LocalSequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(1),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/LocalSequence'))\nexport type LocalSequence = typeof LocalSequence.Type\n\n/**\n * Decode-and-brand helpers. A branded schema constructs the same value with\n * `DocumentId.make('todos')`, which is the spelling to lead with; these stay\n * for callers that already have them.\n */\nexport const documentId = (value: string): DocumentId => Schema.decodeUnknownSync(DocumentId)(value)\nexport const replicaId = (value: string): ReplicaId => Schema.decodeUnknownSync(ReplicaId)(value)\nexport const opId = (value: string): OpId => Schema.decodeUnknownSync(OpId)(value)\nexport const sequence = (value: number): Sequence => Schema.decodeUnknownSync(Sequence)(value)\nexport const localSequence = (value: number): LocalSequence =>\n Schema.decodeUnknownSync(LocalSequence)(value)\n","import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from 'effect'\nimport { sequence } from './ids.js'\nimport type { Operation, TransportClient } from './sync.js'\n\n/** The wire failure of a transport. A refusal is a result, not an error. */\nexport class TransportError extends Schema.TaggedError<TransportError>()('SyncTransportError', {\n message: Schema.String,\n}) {}\n\n/** One request/response frame, as it crosses a wire. */\nexport interface ExchangeFrame {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\n readonly epoch?: string | undefined\n}\n\nexport interface ExchangeReply {\n readonly id: string\n readonly result?: unknown\n readonly error?: string\n}\n\n/**\n * Sent by a server, unasked, when the document may have changed. It carries no\n * data: the replica exchanges from its own cursor, so a notice that is lost,\n * late, or one of many is harmless.\n */\nexport interface NotifyFrame {\n readonly notify: true\n}\n\nexport interface TransportShape {\n /** `epoch` is the server history the replica's cursor points into, when it knows one. */\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => Effect.Effect<unknown, TransportError>\n /**\n * Emits when the server may have something new, for a transport that can hear\n * it: `Replica.start` exchanges on each. A wake-up, not data.\n */\n readonly changes?: Stream.Stream<void> | undefined\n /**\n * The connection itself, for another protocol to share, such as presence: a send goes to\n * the socket open now and is dropped while none is, and messages from every socket the\n * transport opens arrive here. It is the transport's to close.\n */\n readonly socket?: SocketLike | undefined\n}\n\n/**\n * The seam the replica syncs through.\n *\n * A service, not a concrete client, so an application substitutes an in-process\n * transport, a socket, or a test double without the replica knowing. A refusal\n * arrives in the exchange result; only a wire failure is a `TransportError`.\n */\nexport class Transport extends Context.Service<Transport, TransportShape>()(\n 'foldkit-sync/Transport',\n) {}\n\nconst failure = (error: unknown): TransportError =>\n new TransportError({ message: error instanceof Error ? error.message : String(error) })\n\n/** A transport backed by an in-process handler, for tests and single-process demos. */\nexport const layerLoopback = (\n handler: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>,\n): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => Promise.resolve(handler(cursor, pending, epoch)),\n catch: failure,\n }),\n })\n\n/** Wraps the promise-based client the replica already speaks. */\nexport const layerFromPromise = (transport: TransportClient): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => transport.exchange(sequence(cursor), pending, epoch),\n catch: failure,\n }),\n })\n\n/** Bridges the service back to the promise client the replica consumes. */\nexport const toPromise = (transport: TransportShape): TransportClient => ({\n exchange: (cursor, pending, epoch) =>\n Effect.runPromise(transport.exchange(cursor, pending, epoch)),\n})\n\n/**\n * Serves one accepted socket, answering each exchange frame.\n *\n * The counterpart to `layerSocket`: the handler returns the exchange result, or\n * throws and the failure is written back as an error frame. With `changes`, a\n * subscription to the document's commits, the socket is also sent a\n * `NotifyFrame` after each, so a client hears of others' edits without polling.\n * Returns a function that stops serving.\n */\nexport const serveSocket = (\n socket: SocketLike,\n options: {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>\n /** Subscribes to the document's commits; returns the unsubscribe. */\n readonly changes?: ((listener: () => void) => () => void) | undefined\n },\n): (() => void) => {\n const send = (reply: ExchangeReply | NotifyFrame): void => {\n try {\n socket.send(JSON.stringify(reply))\n } catch {\n // The socket may have closed while the handler was running.\n }\n }\n const stopMessage = socket.onMessage(data => {\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch {\n return\n }\n if (typeof parsed !== 'object' || parsed === null) return\n const { id, cursor, pending, epoch } = parsed as {\n id?: unknown\n cursor?: unknown\n pending?: unknown\n epoch?: unknown\n }\n // Without an id there is nobody to answer, so drop the frame.\n if (typeof id !== 'string') return\n if (\n typeof cursor !== 'number' ||\n !Number.isSafeInteger(cursor) ||\n cursor < 0 ||\n !Array.isArray(pending) ||\n (epoch !== undefined && typeof epoch !== 'string')\n ) {\n send({ id, error: 'Invalid exchange frame' })\n return\n }\n const frame: ExchangeFrame = {\n id,\n cursor,\n pending: pending as ReadonlyArray<Operation>,\n epoch: typeof epoch === 'string' ? epoch : undefined,\n }\n void (async () => {\n try {\n const result = await options.exchange(frame.cursor, frame.pending, frame.epoch)\n send({ id: frame.id, result })\n } catch (error) {\n send({ id: frame.id, error: error instanceof Error ? error.message : String(error) })\n }\n })()\n })\n const stopChanges = options.changes?.(() => send({ notify: true }))\n const stop = (): void => {\n stopMessage()\n stopChanges?.()\n }\n const stopClose = socket.onClose(stop)\n return () => {\n stop()\n stopClose()\n }\n}\n\n/** The minimal socket the layer needs; the global `WebSocket` satisfies it. */\nexport interface SocketLike {\n send(data: string): void\n close(): void\n onMessage(listener: (data: string) => void): () => void\n onClose(listener: () => void): () => void\n /**\n * Optional. When provided, exchanges wait for it before sending, so a\n * transport can connect asynchronously. Absent means already connected.\n */\n onOpen?(listener: () => void): () => void\n}\n\n/**\n * Where `layerSocket` connects: a `url` for the platform `WebSocket`, or a\n * `makeSocket` that opens any other `SocketLike` (a port, a test socket), called\n * again on every reconnect.\n */\nexport type SocketOptions = SocketTuning &\n (\n | { readonly url: string; readonly makeSocket?: undefined }\n | { readonly makeSocket: () => SocketLike; readonly url?: undefined }\n )\n\ninterface SocketTuning {\n /**\n * Consecutive failed connections after which queued work fails and new\n * exchanges fail fast until a connection is healthy again. Reconnecting goes\n * on regardless. Default 5.\n */\n readonly maxRetries?: number | undefined\n /** Base delay of the exponential reconnect backoff. Default `50 millis`. */\n readonly retryBase?: Duration.Input | undefined\n /** Longest wait between reconnect attempts. Default `5 seconds`. */\n readonly maxRetryDelay?: Duration.Input | undefined\n /** Exchanges queued or in flight before new ones fail. Default 64. */\n readonly maxQueue?: number | undefined\n}\n\n/** The default socket factory: the platform `WebSocket`, as a `SocketLike`. */\nexport const nativeSocket = (url: string): SocketLike => {\n const socket = new WebSocket(url)\n return {\n send: data => socket.send(data),\n close: () => socket.close(),\n onOpen: listener => {\n if (socket.readyState === WebSocket.OPEN) {\n listener()\n return () => {}\n }\n socket.addEventListener('open', listener)\n return () => socket.removeEventListener('open', listener)\n },\n onMessage: listener => {\n const handler = (event: MessageEvent): void => listener(String(event.data))\n socket.addEventListener('message', handler)\n return () => socket.removeEventListener('message', handler)\n },\n onClose: listener => {\n const handler = (): void => listener()\n socket.addEventListener('close', handler)\n return () => socket.removeEventListener('close', handler)\n },\n }\n}\n\n/**\n * A socket over a `MessagePort`, for either end: its frames are the port's\n * string messages, and anything else on the port is ignored. A port tells\n * neither end when the other goes, so `onClose` fires once, on `close()` or\n * when `signal` aborts; a host that serves a pane aborts it when the pane is\n * gone, which stops `serveSocket` and anything else listening.\n */\nexport const portSocket = (\n port: MessagePort,\n options: { readonly signal?: AbortSignal | undefined } = {},\n): SocketLike => {\n const closeListeners = new Set<() => void>()\n let closed = false\n const close = (): void => {\n closed = true\n port.close()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n options.signal?.addEventListener('abort', close, { once: true })\n if (options.signal?.aborted === true) close()\n port.start()\n return {\n send: data => port.postMessage(data),\n close,\n onMessage: listener => {\n const handler = (event: MessageEvent): void => {\n if (typeof event.data === 'string') listener(event.data)\n }\n port.addEventListener('message', handler)\n return () => port.removeEventListener('message', handler)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\n/**\n * A socket over an existing `WebSocket`: the accepted end of a Cloudflare\n * `WebSocketPair`, or any other socket the platform hands over. Unlike\n * `nativeSocket` it opens nothing — accept the pair first — and unlike\n * `portSocket` there is no signal: the socket closing, erroring, or being\n * closed fires `onClose` once, which is how a host stops serving it.\n */\nexport const workerSocket = (socket: WebSocket): SocketLike => {\n const messageListeners = new Set<(data: string) => void>()\n const closeListeners = new Set<() => void>()\n let closed = false\n const forget = (): void => {\n socket.removeEventListener('message', onMessageEvent)\n socket.removeEventListener('close', onClosedEvent)\n socket.removeEventListener('error', onClosedEvent)\n }\n const fireClose = (): void => {\n closed = true\n forget()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n const onMessageEvent = (event: MessageEvent): void => {\n for (const listener of [...messageListeners]) listener(String(event.data))\n }\n const onClosedEvent = (): void => {\n fireClose()\n }\n socket.addEventListener('message', onMessageEvent)\n socket.addEventListener('close', onClosedEvent)\n socket.addEventListener('error', onClosedEvent)\n return {\n send: data => socket.send(data),\n close: () => {\n try {\n socket.close()\n } catch {\n // Already gone: still report the close.\n }\n fireClose()\n },\n onMessage: listener => {\n messageListeners.add(listener)\n return () => messageListeners.delete(listener)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\nconst connector = (options: SocketOptions): (() => SocketLike) => {\n if (options.makeSocket !== undefined) return options.makeSocket\n const { url } = options\n return () => nativeSocket(url)\n}\n\n/**\n * A WebSocket client transport.\n *\n * One connection is live at a time. While it is connecting, exchanges queue; if\n * it closes, the transport reconnects on an exponential, jittered backoff and\n * re-sends every queued and in-flight frame with its original id, so a lost\n * reply is answered rather than dropped and a late reply cannot resolve a newer\n * frame. It never stops reconnecting: after `maxRetries` consecutive failures\n * queued work fails with a `TransportError`, and exchanges fail fast while no\n * socket is up, until a socket opens. The count resets only when a connection\n * proves healthy, by answering a frame or by staying open for `maxRetryDelay`:\n * a server that accepts a socket and drops it at once is backed off like one\n * that refuses it. A queue over `maxQueue` fails new\n * exchanges with backpressure. The socket is released when the layer's scope\n * ends.\n */\nexport const layerSocket = (options: SocketOptions): Layer.Layer<Transport, TransportError> =>\n Layer.effect(\n Transport,\n Effect.fn('Transport.layerSocket')(function* () {\n const makeSocket = connector(options)\n const maxQueue = options.maxQueue ?? 64\n const maxRetries = options.maxRetries ?? 5\n const retryBase = Duration.toMillis(\n Duration.fromInputUnsafe(options.retryBase ?? '50 millis'),\n )\n const maxRetryDelay = Duration.toMillis(\n Duration.fromInputUnsafe(options.maxRetryDelay ?? '5 seconds'),\n )\n const clock = yield* Clock.Clock\n\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\n readonly epoch: string | undefined\n readonly resume: (effect: Effect.Effect<unknown, TransportError>) => void\n }\n const notices = yield* PubSub.sliding<void>(1)\n const listeners = new Set<(data: string) => void>()\n const shared: SocketLike = {\n send: data => {\n if (ready) socket?.send(data)\n },\n close: () => {},\n onMessage: listener => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n onClose: () => () => {},\n }\n const queued: Array<Entry> = []\n const inFlight = new Map<string, Entry>()\n let socket: SocketLike | undefined\n let ready = false\n let nextId = 0\n let disposed = false\n // Closes since a connection last proved healthy. Past `maxRetries` the\n // transport is offline: nothing waits for a socket that may be minutes away.\n let failures = 0\n const healthy = (): void => {\n failures = 0\n }\n\n const send = (entry: Entry): void => {\n inFlight.set(entry.id, entry)\n socket?.send(\n JSON.stringify({\n id: entry.id,\n cursor: entry.cursor,\n pending: entry.pending,\n ...(entry.epoch === undefined ? {} : { epoch: entry.epoch }),\n } satisfies ExchangeFrame),\n )\n }\n const flush = (): void => {\n if (socket === undefined || !ready) return\n for (const entry of queued.splice(0)) send(entry)\n }\n const requeue = (): void => {\n queued.unshift(...inFlight.values())\n inFlight.clear()\n }\n const failAll = (message: string): void => {\n const entries = [...queued.splice(0), ...inFlight.values()]\n inFlight.clear()\n for (const entry of entries) entry.resume(Effect.fail(new TransportError({ message })))\n }\n\n const connect = Effect.tryPromise({\n try: () =>\n new Promise<void>((resolve, reject) => {\n const next = makeSocket()\n socket = next\n ready = next.onOpen === undefined\n let openedAt = ready ? clock.currentTimeMillisUnsafe() : undefined\n // A socket that just (re)connected may have missed notices, so opening is one.\n const opened = (): void => {\n PubSub.publishUnsafe(notices, undefined)\n }\n const offOpen = next.onOpen?.(() => {\n ready = true\n openedAt = clock.currentTimeMillisUnsafe()\n opened()\n flush()\n })\n const offMessage = next.onMessage(data => {\n // Another protocol's listener must not cost an exchange its reply.\n for (const listener of [...listeners]) {\n try {\n listener(data)\n } catch {}\n }\n let reply: ExchangeReply | NotifyFrame\n try {\n reply = JSON.parse(data) as ExchangeReply | NotifyFrame\n } catch {\n return\n }\n if (typeof reply !== 'object' || reply === null) return\n if ('notify' in reply) {\n if (reply.notify === true) PubSub.publishUnsafe(notices, undefined)\n return\n }\n const entry = inFlight.get(reply.id)\n if (entry === undefined) return\n healthy()\n inFlight.delete(reply.id)\n entry.resume(\n reply.error === undefined\n ? Effect.succeed(reply.result)\n : Effect.fail(new TransportError({ message: reply.error })),\n )\n })\n const offClose = next.onClose(() => {\n offOpen?.()\n offMessage()\n offClose()\n socket = undefined\n ready = false\n if (\n openedAt !== undefined &&\n clock.currentTimeMillisUnsafe() - openedAt >= maxRetryDelay\n )\n healthy()\n // Keep every unanswered frame for the next connection.\n requeue()\n reject(new Error('transport closed'))\n })\n if (ready) {\n opened()\n flush()\n }\n }),\n catch: () => new TransportError({ message: 'transport closed' }),\n })\n\n yield* Effect.forkScoped(\n Effect.gen(function* () {\n while (!disposed) {\n yield* Effect.exit(connect)\n if (disposed) return\n failures += 1\n if (failures > maxRetries) failAll('transport closed')\n const backoff = Math.min(maxRetryDelay, retryBase * 2 ** Math.min(failures - 1, 30))\n yield* Effect.sleep(backoff * (0.8 + Math.random() * 0.4))\n }\n }),\n )\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n disposed = true\n ready = false\n socket?.close()\n socket = undefined\n failAll('transport closed')\n }),\n )\n\n return Transport.of({\n changes: Stream.fromPubSub(notices),\n socket: shared,\n exchange: (cursor, pending, epoch) =>\n Effect.callback<unknown, TransportError>(resume => {\n if (disposed) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (failures > maxRetries && !ready) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (queued.length + inFlight.size >= maxQueue) {\n resume(Effect.fail(new TransportError({ message: 'transport queue full' })))\n return\n }\n const entry: Entry = { id: String(nextId++), cursor, pending, epoch, resume }\n if (ready) send(entry)\n else queued.push(entry)\n // A caller interrupted before a reply must release its slot, or a\n // socket that never replies can exhaust the queue with abandoned\n // work. The frame may already be on the wire; only the local waiter\n // is forgotten, and a late reply for it is ignored.\n return Effect.sync(() => {\n const queuedIndex = queued.indexOf(entry)\n if (queuedIndex >= 0) queued.splice(queuedIndex, 1)\n if (inFlight.get(entry.id) === entry) inFlight.delete(entry.id)\n })\n }),\n })\n })(),\n )\n"],"mappings":";;;AAGA,MAAa,aAAa,OAAO,eAAe,KAAK,OAAO,MAAM,0BAA0B,CAAC;;AAI7F,MAAa,YAAY,OAAO,eAAe,KAAK,OAAO,MAAM,yBAAyB,CAAC;;AAI3F,MAAa,OAAO,OAAO,eAAe,KAAK,OAAO,MAAM,oBAAoB,CAAC;;;;;AAOjF,MAAa,WAAW,OAAO,OAAO,MACpC,OAAO,MAAM,GACb,OAAO,uBAAuB,CAAC,GAC/B,OAAO,oBAAoB,OAAO,gBAAgB,CACpD,CAAC,CAAC,KAAK,OAAO,MAAM,wBAAwB,CAAC;;AAI7C,MAAa,gBAAgB,OAAO,OAAO,MACzC,OAAO,MAAM,GACb,OAAO,uBAAuB,CAAC,GAC/B,OAAO,oBAAoB,OAAO,gBAAgB,CACpD,CAAC,CAAC,KAAK,O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AAO,QAAQ,KAAK;IACxC,IAAI,eAAe,GAAG,OAAO,OAAO,aAAa,CAAC;IAClD,IAAI,SAAS,IAAI,MAAM,EAAE,MAAM,OAAO,SAAS,OAAO,MAAM,EAAE;GAChE,CAAC;EACH,CAAC;CACL,CAAC;AACH,CAAC,CAAC,CAAC,CACL"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "foldkit-sync",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "A local-first replica of a shared Foldkit projection: offline outbox, optimistic updates, and reconciliation.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"foldkit",
|
|
@@ -31,6 +31,26 @@
|
|
|
31
31
|
"foldkit-plus:source": "./src/index.ts",
|
|
32
32
|
"types": "./dist/index.d.mts",
|
|
33
33
|
"import": "./dist/index.mjs"
|
|
34
|
+
},
|
|
35
|
+
"./journal": {
|
|
36
|
+
"foldkit-plus:source": "./src/journal.ts",
|
|
37
|
+
"types": "./dist/journal.d.mts",
|
|
38
|
+
"import": "./dist/journal.mjs"
|
|
39
|
+
},
|
|
40
|
+
"./entity": {
|
|
41
|
+
"foldkit-plus:source": "./src/entity.ts",
|
|
42
|
+
"types": "./dist/entity.d.mts",
|
|
43
|
+
"import": "./dist/entity.mjs"
|
|
44
|
+
},
|
|
45
|
+
"./do": {
|
|
46
|
+
"foldkit-plus:source": "./src/do.ts",
|
|
47
|
+
"types": "./dist/do.d.mts",
|
|
48
|
+
"import": "./dist/do.mjs"
|
|
49
|
+
},
|
|
50
|
+
"./remote": {
|
|
51
|
+
"foldkit-plus:source": "./src/remote.ts",
|
|
52
|
+
"types": "./dist/remote.d.mts",
|
|
53
|
+
"import": "./dist/remote.mjs"
|
|
34
54
|
}
|
|
35
55
|
},
|
|
36
56
|
"files": [
|
|
@@ -39,20 +59,34 @@
|
|
|
39
59
|
"LICENSE"
|
|
40
60
|
],
|
|
41
61
|
"dependencies": {
|
|
42
|
-
"foldkit-surface": "0.
|
|
62
|
+
"foldkit-surface": "0.8.0"
|
|
43
63
|
},
|
|
44
64
|
"peerDependencies": {
|
|
45
65
|
"effect": "^4.0.0",
|
|
46
|
-
"foldkit": "^0.165.0"
|
|
66
|
+
"foldkit": "^0.165.0",
|
|
67
|
+
"foldkit-durable": "0.8.0",
|
|
68
|
+
"foldkit-remote": "0.14.0"
|
|
69
|
+
},
|
|
70
|
+
"peerDependenciesMeta": {
|
|
71
|
+
"foldkit-durable": {
|
|
72
|
+
"optional": true
|
|
73
|
+
}
|
|
47
74
|
},
|
|
48
75
|
"devDependencies": {
|
|
76
|
+
"@cloudflare/workers-types": "5.20261008.1",
|
|
49
77
|
"@effect/platform-browser": "4.0.0",
|
|
78
|
+
"@effect/sql-d1": "4.0.0",
|
|
50
79
|
"effect": "4.0.0",
|
|
80
|
+
"esbuild": "0.28.2",
|
|
51
81
|
"foldkit": "0.165.0",
|
|
52
82
|
"jsdom": "26.1.0",
|
|
83
|
+
"miniflare": "3.20250718.3",
|
|
53
84
|
"tsdown": "^0.23.0",
|
|
54
85
|
"typescript": "5.9.3",
|
|
55
|
-
"foldkit-agent": "0.
|
|
86
|
+
"foldkit-agent": "0.7.0",
|
|
87
|
+
"foldkit-remote": "0.14.0",
|
|
88
|
+
"foldkit-durable": "0.8.0",
|
|
89
|
+
"foldkit-entity": "0.8.0"
|
|
56
90
|
},
|
|
57
91
|
"scripts": {
|
|
58
92
|
"build": "tsdown",
|