foldkit-sync 0.12.4 → 0.13.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 +76 -24
- package/dist/diagnostics.d.ts +71 -0
- package/dist/diagnostics.d.ts.map +1 -0
- package/dist/diagnostics.js +67 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/{do.d.mts → do.d.ts} +12 -2
- package/dist/do.d.ts.map +1 -0
- package/dist/{do.mjs → do.js} +15 -9
- package/dist/do.js.map +1 -0
- package/dist/{entity.d.mts → entity.d.ts} +1 -1
- package/dist/entity.d.ts.map +1 -0
- package/dist/{entity.mjs → entity.js} +1 -1
- package/dist/entity.js.map +1 -0
- package/dist/errors.d.ts +91 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +75 -0
- package/dist/errors.js.map +1 -0
- package/dist/ids.d.ts +30 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +28 -0
- package/dist/ids.js.map +1 -0
- package/dist/index.d.ts +106 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +77 -0
- package/dist/index.js.map +1 -0
- package/dist/indexedDb.d.ts +62 -0
- package/dist/indexedDb.d.ts.map +1 -0
- package/dist/indexedDb.js +128 -0
- package/dist/indexedDb.js.map +1 -0
- package/dist/{journal.d.mts → journal.d.ts} +29 -5
- package/dist/journal.d.ts.map +1 -0
- package/dist/{journal-D5h-jqXE.mjs → journal.js} +43 -32
- package/dist/journal.js.map +1 -0
- package/dist/lww.d.ts +76 -0
- package/dist/lww.d.ts.map +1 -0
- package/dist/lww.js +121 -0
- package/dist/lww.js.map +1 -0
- package/dist/make.d.ts +162 -0
- package/dist/make.d.ts.map +1 -0
- package/dist/make.js +153 -0
- package/dist/make.js.map +1 -0
- package/dist/mount.d.ts +138 -0
- package/dist/mount.d.ts.map +1 -0
- package/dist/mount.js +344 -0
- package/dist/mount.js.map +1 -0
- package/dist/presence.d.ts +116 -0
- package/dist/presence.d.ts.map +1 -0
- package/dist/presence.js +277 -0
- package/dist/presence.js.map +1 -0
- package/dist/{remote.d.mts → remote.d.ts} +2 -2
- package/dist/remote.d.ts.map +1 -0
- package/dist/{remote.mjs → remote.js} +1 -1
- package/dist/remote.js.map +1 -0
- package/dist/revalidate.d.ts +6 -0
- package/dist/revalidate.d.ts.map +1 -0
- package/dist/revalidate.js +10 -0
- package/dist/revalidate.js.map +1 -0
- package/dist/sync.d.ts +276 -0
- package/dist/sync.d.ts.map +1 -0
- package/dist/sync.js +512 -0
- package/dist/sync.js.map +1 -0
- package/dist/transport.d.ts +151 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/{transport-BZ6utYmB.mjs → transport.js} +20 -30
- package/dist/transport.js.map +1 -0
- package/package.json +24 -24
- package/dist/do.d.mts.map +0 -1
- package/dist/do.mjs.map +0 -1
- package/dist/entity.d.mts.map +0 -1
- package/dist/entity.mjs.map +0 -1
- package/dist/index.d.mts +0 -397
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs +0 -1613
- package/dist/index.mjs.map +0 -1
- package/dist/journal-D5h-jqXE.mjs.map +0 -1
- package/dist/journal.d.mts.map +0 -1
- package/dist/journal.mjs +0 -1
- package/dist/make-DJ0Q1SSc.d.mts +0 -702
- package/dist/make-DJ0Q1SSc.d.mts.map +0 -1
- package/dist/remote.d.mts.map +0 -1
- package/dist/remote.mjs.map +0 -1
- package/dist/transport-BZ6utYmB.mjs.map +0 -1
package/dist/presence.js
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { Clock, Duration, Effect, Fiber, PubSub, Ref, Stream, SynchronizedRef } from "effect";
|
|
2
|
+
import { Diagnostics } from "foldkit-surface";
|
|
3
|
+
import { listenerFailed } from "./diagnostics.js";
|
|
4
|
+
// src/presence.ts
|
|
5
|
+
/**
|
|
6
|
+
* Tracks ephemeral peers with a time-to-live.
|
|
7
|
+
*
|
|
8
|
+
* Nothing here touches the durable log: presence is state a peer refreshes, and
|
|
9
|
+
* a peer that stops refreshing is dropped, not replayed. Time comes from the
|
|
10
|
+
* `Clock`, so a `TestClock` drives the TTL deterministically.
|
|
11
|
+
*/
|
|
12
|
+
const createPresence = Effect.fn("Presence.create")(function* (options) {
|
|
13
|
+
const ttl = Duration.toMillis(options.ttl);
|
|
14
|
+
const throttle = options.throttle === void 0 ? 0 : Duration.toMillis(options.throttle);
|
|
15
|
+
const scope = yield* Effect.scope;
|
|
16
|
+
const outbound = yield* SynchronizedRef.make({
|
|
17
|
+
lastSent: void 0,
|
|
18
|
+
held: void 0,
|
|
19
|
+
flusher: void 0
|
|
20
|
+
});
|
|
21
|
+
const peers = yield* Ref.make(/* @__PURE__ */ new Map());
|
|
22
|
+
const closed = yield* Ref.make(false);
|
|
23
|
+
const signals = yield* PubSub.sliding(1);
|
|
24
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
25
|
+
/** A subscriber must never fail an update. */
|
|
26
|
+
const notify = () => Effect.gen(function* () {
|
|
27
|
+
for (const listener of [...listeners]) try {
|
|
28
|
+
listener();
|
|
29
|
+
} catch (thrown) {
|
|
30
|
+
yield* Diagnostics.report(listenerFailed("Presence", thrown));
|
|
31
|
+
}
|
|
32
|
+
yield* PubSub.publish(signals, void 0);
|
|
33
|
+
});
|
|
34
|
+
const expired = (peer, at) => at - peer.updatedAt > ttl;
|
|
35
|
+
const put = (id, value, at) => Ref.update(peers, (map) => {
|
|
36
|
+
const next = new Map(map);
|
|
37
|
+
next.set(id, {
|
|
38
|
+
id,
|
|
39
|
+
value,
|
|
40
|
+
updatedAt: at
|
|
41
|
+
});
|
|
42
|
+
return next;
|
|
43
|
+
});
|
|
44
|
+
const remove = (id) => Ref.modify(peers, (map) => {
|
|
45
|
+
if (!map.has(id)) return [false, map];
|
|
46
|
+
const next = new Map(map);
|
|
47
|
+
next.delete(id);
|
|
48
|
+
return [true, next];
|
|
49
|
+
});
|
|
50
|
+
const receive = Effect.fn("Presence.receive")(function* (update) {
|
|
51
|
+
if (update.id === options.id) return;
|
|
52
|
+
if (update.value === null) {
|
|
53
|
+
if (yield* remove(update.id)) yield* notify();
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
let value;
|
|
57
|
+
try {
|
|
58
|
+
value = options.decodeValue(update.value);
|
|
59
|
+
} catch {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
yield* put(update.id, value, yield* Clock.currentTimeMillis);
|
|
63
|
+
yield* notify();
|
|
64
|
+
});
|
|
65
|
+
const channel = options.channel;
|
|
66
|
+
const consuming = channel === void 0 ? void 0 : yield* Stream.runForEach(Stream.fromPubSub(channel.updates), receive).pipe(Effect.forkScoped);
|
|
67
|
+
const publish = (value) => channel.publish({
|
|
68
|
+
id: options.id,
|
|
69
|
+
value
|
|
70
|
+
});
|
|
71
|
+
/** Drops a value waiting to be sent, so nothing older goes out after what comes next. */
|
|
72
|
+
const cancelHeld = SynchronizedRef.updateEffect(outbound, (state) => (state.flusher === void 0 ? Effect.void : Fiber.interrupt(state.flusher)).pipe(Effect.as({
|
|
73
|
+
...state,
|
|
74
|
+
held: void 0,
|
|
75
|
+
flusher: void 0
|
|
76
|
+
})));
|
|
77
|
+
/** Sends what is held once per interval, until an interval passes with nothing held. */
|
|
78
|
+
const flush = (wait) => Effect.gen(function* () {
|
|
79
|
+
for (let delay = wait;; delay = throttle) {
|
|
80
|
+
yield* Effect.sleep(delay);
|
|
81
|
+
const now = yield* Clock.currentTimeMillis;
|
|
82
|
+
const latest = yield* SynchronizedRef.modify(outbound, (state) => state.held === void 0 ? [void 0, {
|
|
83
|
+
...state,
|
|
84
|
+
flusher: void 0
|
|
85
|
+
}] : [state.held, {
|
|
86
|
+
...state,
|
|
87
|
+
held: void 0,
|
|
88
|
+
lastSent: now
|
|
89
|
+
}]);
|
|
90
|
+
if (latest === void 0) return;
|
|
91
|
+
yield* publish(latest.value);
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
const broadcast = (value, at) => Effect.gen(function* () {
|
|
95
|
+
if (yield* SynchronizedRef.modifyEffect(outbound, (state) => Effect.gen(function* () {
|
|
96
|
+
if (yield* Ref.get(closed)) return [false, state];
|
|
97
|
+
if (state.flusher !== void 0) return [false, {
|
|
98
|
+
...state,
|
|
99
|
+
held: { value }
|
|
100
|
+
}];
|
|
101
|
+
const wait = state.lastSent === void 0 ? 0 : Math.min(throttle, state.lastSent + throttle - at);
|
|
102
|
+
if (wait <= 0) return [true, {
|
|
103
|
+
...state,
|
|
104
|
+
lastSent: at
|
|
105
|
+
}];
|
|
106
|
+
const flusher = yield* Effect.forkIn(flush(wait), scope);
|
|
107
|
+
return [false, {
|
|
108
|
+
...state,
|
|
109
|
+
held: { value },
|
|
110
|
+
flusher
|
|
111
|
+
}];
|
|
112
|
+
}).pipe(Effect.uninterruptible))) yield* publish(value);
|
|
113
|
+
});
|
|
114
|
+
const set = Effect.fn("Presence.set")(function* (value) {
|
|
115
|
+
if (yield* Ref.get(closed)) return;
|
|
116
|
+
const at = yield* Clock.currentTimeMillis;
|
|
117
|
+
yield* put(options.id, value, at);
|
|
118
|
+
if (channel !== void 0) yield* broadcast(value, at);
|
|
119
|
+
yield* notify();
|
|
120
|
+
});
|
|
121
|
+
const leave = Effect.fn("Presence.leave")(function* () {
|
|
122
|
+
if (yield* Ref.get(closed)) return;
|
|
123
|
+
yield* cancelHeld;
|
|
124
|
+
yield* remove(options.id);
|
|
125
|
+
if (channel !== void 0) yield* channel.publish({
|
|
126
|
+
id: options.id,
|
|
127
|
+
value: null
|
|
128
|
+
});
|
|
129
|
+
yield* notify();
|
|
130
|
+
})();
|
|
131
|
+
const peerList = Effect.fn("Presence.peers")(function* () {
|
|
132
|
+
const at = yield* Clock.currentTimeMillis;
|
|
133
|
+
return [...(yield* Ref.get(peers)).values()].filter((peer) => !expired(peer, at)).map((peer) => ({ ...peer }));
|
|
134
|
+
})();
|
|
135
|
+
const prune = Effect.fn("Presence.prune")(function* () {
|
|
136
|
+
if (yield* Ref.get(closed)) return;
|
|
137
|
+
const at = yield* Clock.currentTimeMillis;
|
|
138
|
+
if (yield* Ref.modify(peers, (map) => {
|
|
139
|
+
let removed = false;
|
|
140
|
+
const next = new Map(map);
|
|
141
|
+
for (const [id, peer] of map) if (expired(peer, at)) {
|
|
142
|
+
next.delete(id);
|
|
143
|
+
removed = true;
|
|
144
|
+
}
|
|
145
|
+
return [removed, next];
|
|
146
|
+
})) yield* notify();
|
|
147
|
+
})();
|
|
148
|
+
const close = Effect.fn("Presence.close")(function* () {
|
|
149
|
+
if (yield* Ref.get(closed)) return;
|
|
150
|
+
yield* Ref.set(closed, true);
|
|
151
|
+
yield* cancelHeld;
|
|
152
|
+
if (consuming !== void 0) yield* Fiber.interrupt(consuming);
|
|
153
|
+
yield* Effect.sync(() => listeners.clear());
|
|
154
|
+
yield* PubSub.shutdown(signals);
|
|
155
|
+
})();
|
|
156
|
+
return {
|
|
157
|
+
set,
|
|
158
|
+
leave,
|
|
159
|
+
peers: peerList,
|
|
160
|
+
prune,
|
|
161
|
+
subscribe: (listener) => {
|
|
162
|
+
listeners.add(listener);
|
|
163
|
+
return () => listeners.delete(listener);
|
|
164
|
+
},
|
|
165
|
+
changes: Stream.concat(Stream.fromEffect(peerList), Stream.fromPubSub(signals).pipe(Stream.mapEffect(() => peerList))),
|
|
166
|
+
close
|
|
167
|
+
};
|
|
168
|
+
});
|
|
169
|
+
/** An in-process channel, for tests and single-process demos. */
|
|
170
|
+
const loopbackPresenceChannel = Effect.fn("Presence.loopbackChannel")(function* () {
|
|
171
|
+
const updates = yield* PubSub.unbounded();
|
|
172
|
+
return {
|
|
173
|
+
updates,
|
|
174
|
+
publish: (update) => PubSub.publish(updates, update)
|
|
175
|
+
};
|
|
176
|
+
});
|
|
177
|
+
const createPresenceHub = () => {
|
|
178
|
+
const peers = /* @__PURE__ */ new Set();
|
|
179
|
+
return {
|
|
180
|
+
join: (send) => {
|
|
181
|
+
peers.add(send);
|
|
182
|
+
return () => peers.delete(send);
|
|
183
|
+
},
|
|
184
|
+
publish: (update) => {
|
|
185
|
+
for (const send of [...peers]) try {
|
|
186
|
+
send(update);
|
|
187
|
+
} catch {}
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
};
|
|
191
|
+
const frameType = "presence";
|
|
192
|
+
/** Decodes a presence frame, ignoring anything else a socket may carry. */
|
|
193
|
+
const decodePresence = (data) => {
|
|
194
|
+
let frame;
|
|
195
|
+
try {
|
|
196
|
+
frame = JSON.parse(data);
|
|
197
|
+
} catch {
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (typeof frame !== "object" || frame === null) return void 0;
|
|
201
|
+
const payload = frame[frameType];
|
|
202
|
+
if (typeof payload !== "object" || payload === null) return void 0;
|
|
203
|
+
const { id, value } = payload;
|
|
204
|
+
return {
|
|
205
|
+
id: typeof id === "string" ? id : void 0,
|
|
206
|
+
value: value ?? null
|
|
207
|
+
};
|
|
208
|
+
};
|
|
209
|
+
/**
|
|
210
|
+
* A presence channel fed by stamped frames from the server, sent back without an
|
|
211
|
+
* id: the server owns peer identity, so a client cannot assert another's.
|
|
212
|
+
*/
|
|
213
|
+
const socketPresenceChannel = (socket) => Effect.gen(function* () {
|
|
214
|
+
const updates = yield* PubSub.unbounded();
|
|
215
|
+
yield* Effect.acquireRelease(Effect.sync(() => socket.onMessage((data) => {
|
|
216
|
+
const frame = decodePresence(data);
|
|
217
|
+
if (frame === void 0 || frame.id === void 0) return;
|
|
218
|
+
PubSub.publishUnsafe(updates, {
|
|
219
|
+
id: frame.id,
|
|
220
|
+
value: frame.value
|
|
221
|
+
});
|
|
222
|
+
})), (off) => Effect.sync(off));
|
|
223
|
+
return {
|
|
224
|
+
updates,
|
|
225
|
+
publish: (update) => Effect.sync(() => socket.send(JSON.stringify({ [frameType]: { value: update.value } })))
|
|
226
|
+
};
|
|
227
|
+
});
|
|
228
|
+
/**
|
|
229
|
+
* Serves presence frames on an accepted socket, stamping the connection's
|
|
230
|
+
* identity, until the socket closes or the returned function is called.
|
|
231
|
+
* With `opens`, the connection joins only once it answers that it may open
|
|
232
|
+
* the document the presence accompanies: until then, and for good when it
|
|
233
|
+
* is refused or fails, nothing reaches it and nothing it sends is relayed.
|
|
234
|
+
*/
|
|
235
|
+
const servePresence = (socket, hub, options) => {
|
|
236
|
+
const send = (update) => socket.send(JSON.stringify({ [frameType]: {
|
|
237
|
+
id: update.id,
|
|
238
|
+
value: update.value
|
|
239
|
+
} }));
|
|
240
|
+
let stopped = false;
|
|
241
|
+
let leave = () => {};
|
|
242
|
+
let off = () => {};
|
|
243
|
+
const join = () => {
|
|
244
|
+
leave = hub.join(send);
|
|
245
|
+
off = socket.onMessage((data) => {
|
|
246
|
+
const frame = decodePresence(data);
|
|
247
|
+
if (frame === void 0) return;
|
|
248
|
+
const publish = () => hub.publish({
|
|
249
|
+
id: options.peerId,
|
|
250
|
+
value: frame.value
|
|
251
|
+
});
|
|
252
|
+
if (options.opens === void 0) return publish();
|
|
253
|
+
Effect.runPromise(options.opens).then((open) => {
|
|
254
|
+
if (stopped) return;
|
|
255
|
+
if (open) publish();
|
|
256
|
+
else stop();
|
|
257
|
+
}, () => stop());
|
|
258
|
+
});
|
|
259
|
+
};
|
|
260
|
+
if (options.opens === void 0) join();
|
|
261
|
+
else Effect.runPromise(options.opens).then((open) => {
|
|
262
|
+
if (open && !stopped) join();
|
|
263
|
+
}, () => {});
|
|
264
|
+
const stop = () => {
|
|
265
|
+
stopped = true;
|
|
266
|
+
off();
|
|
267
|
+
leave();
|
|
268
|
+
};
|
|
269
|
+
const stopClose = socket.onClose(stop);
|
|
270
|
+
return () => {
|
|
271
|
+
stop();
|
|
272
|
+
stopClose();
|
|
273
|
+
};
|
|
274
|
+
};
|
|
275
|
+
export { createPresence, createPresenceHub, loopbackPresenceChannel, servePresence, socketPresenceChannel };
|
|
276
|
+
|
|
277
|
+
//# sourceMappingURL=presence.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"presence.js","names":[],"sources":["../src/presence.ts"],"sourcesContent":["import {\n Clock,\n Duration,\n Effect,\n Fiber,\n PubSub,\n Ref,\n Stream,\n SynchronizedRef,\n type Scope,\n} from 'effect'\nimport type { SocketLike } from './transport.js'\nimport { Diagnostics } from 'foldkit-surface'\nimport { listenerFailed } from './diagnostics.js'\n\n/** One peer's presence. A `null` value means the peer left. */\nexport interface PresenceUpdate<Update> {\n readonly id: string\n readonly value: Update | null\n}\n\n/**\n * The ephemeral channel presence travels on.\n *\n * `updates` is the inbound bus a peer consumes; `publish` sends one to the bus.\n * Splitting them keeps an inbound update from being echoed straight back out.\n * This is deliberately not the durable transport: presence is broadcast, never\n * journaled, so a dropped or duplicated update is harmless.\n */\nexport interface PresenceChannel<Update> {\n readonly updates: PubSub.PubSub<PresenceUpdate<Update>>\n readonly publish: (update: PresenceUpdate<Update>) => Effect.Effect<void>\n}\n\nexport interface PresenceOptions<Update> {\n /** This peer's identity on the channel. */\n readonly id: string\n /** How long a peer may go without refreshing before it is dropped. */\n readonly ttl: Duration.Input\n /**\n * Validates the untrusted value a peer sends before it is stored. Presence\n * crosses a wire, so this is required rather than trusting the type\n * parameter; a value it rejects is dropped.\n */\n readonly decodeValue: (value: unknown) => Update\n readonly channel?: PresenceChannel<Update> | undefined\n /**\n * The least time between two values sent on the channel. `set` still takes effect here at\n * once; a value set sooner waits, and only the latest one waiting is sent when the time is\n * up. A departure is never held back. Absent, every `set` is sent at once.\n */\n readonly throttle?: Duration.Input | undefined\n}\n\nexport interface PresencePeer<Update> {\n readonly id: string\n readonly value: Update\n readonly updatedAt: number\n}\n\nexport interface Presence<Update> {\n /** Sets this peer's value and broadcasts it, no sooner than `throttle` allows. */\n readonly set: (value: Update) => Effect.Effect<void>\n /** Removes this peer and broadcasts the departure. */\n readonly leave: Effect.Effect<void>\n /** Live peers, self included, with stale ones excluded. */\n readonly peers: Effect.Effect<ReadonlyArray<PresencePeer<Update>>>\n /** Drops expired peers; notifies if any went. */\n readonly prune: Effect.Effect<void>\n /** Notified when the peer set changes. */\n readonly subscribe: (listener: () => void) => () => void\n /**\n * The live peers, re-emitted whenever the set changes. The `Stream` form of\n * `subscribe`, for a consumer that composes with Effect.\n */\n readonly changes: Stream.Stream<ReadonlyArray<PresencePeer<Update>>>\n /** Stops consuming the channel; the enclosing scope also does this on exit. */\n readonly close: Effect.Effect<void>\n}\n\n/**\n * Tracks ephemeral peers with a time-to-live.\n *\n * Nothing here touches the durable log: presence is state a peer refreshes, and\n * a peer that stops refreshing is dropped, not replayed. Time comes from the\n * `Clock`, so a `TestClock` drives the TTL deterministically.\n */\nexport const createPresence = Effect.fn('Presence.create')(function* <Update>(\n options: PresenceOptions<Update>,\n) {\n const ttl = Duration.toMillis(options.ttl)\n const throttle = options.throttle === undefined ? 0 : Duration.toMillis(options.throttle)\n const scope = yield* Effect.scope\n // What a throttled channel has sent and holds. Every decision about it is made under\n // this one lock, so two `set`s cannot both send in one interval, a value held while a\n // flush finds nothing cannot be stranded, and a flush is never forked and lost.\n const outbound = yield* SynchronizedRef.make<{\n readonly lastSent: number | undefined\n readonly held: { readonly value: Update } | undefined\n readonly flusher: Fiber.Fiber<void> | undefined\n }>({ lastSent: undefined, held: undefined, flusher: undefined })\n const peers = yield* Ref.make(new Map<string, PresencePeer<Update>>())\n const closed = yield* Ref.make(false)\n const signals = yield* PubSub.sliding<void>(1)\n const listeners = new Set<() => void>()\n /** A subscriber must never fail an update. */\n const notify = (): Effect.Effect<void> =>\n Effect.gen(function* () {\n for (const listener of [...listeners]) {\n try {\n listener()\n } catch (thrown) {\n yield* Diagnostics.report(listenerFailed('Presence', thrown))\n }\n }\n yield* PubSub.publish(signals, undefined)\n })\n const expired = (peer: PresencePeer<Update>, at: number): boolean => at - peer.updatedAt > ttl\n\n const put = (id: string, value: Update, at: number): Effect.Effect<void> =>\n Ref.update(peers, map => {\n const next = new Map(map)\n next.set(id, { id, value, updatedAt: at })\n return next\n })\n const remove = (id: string): Effect.Effect<boolean> =>\n Ref.modify(peers, map => {\n if (!map.has(id)) return [false, map] as const\n const next = new Map(map)\n next.delete(id)\n return [true, next] as const\n })\n\n const receive = Effect.fn('Presence.receive')(function* (update: PresenceUpdate<Update>) {\n if (update.id === options.id) return\n if (update.value === null) {\n if (yield* remove(update.id)) yield* notify()\n return\n }\n let value: Update\n try {\n value = options.decodeValue(update.value)\n } catch {\n // A peer's value that fails the contract is dropped, never stored.\n return\n }\n yield* put(update.id, value, yield* Clock.currentTimeMillis)\n yield* notify()\n })\n\n const channel = options.channel\n const consuming =\n channel === undefined\n ? undefined\n : yield* Stream.runForEach(Stream.fromPubSub(channel.updates), receive).pipe(\n Effect.forkScoped,\n )\n\n const publish = (value: Update): Effect.Effect<void> =>\n channel!.publish({ id: options.id, value })\n\n /** Drops a value waiting to be sent, so nothing older goes out after what comes next. */\n const cancelHeld = SynchronizedRef.updateEffect(outbound, state =>\n (state.flusher === undefined ? Effect.void : Fiber.interrupt(state.flusher)).pipe(\n Effect.as({ ...state, held: undefined, flusher: undefined }),\n ),\n )\n\n /** Sends what is held once per interval, until an interval passes with nothing held. */\n const flush = (wait: number): Effect.Effect<void> =>\n Effect.gen(function* () {\n for (let delay = wait; ; delay = throttle) {\n yield* Effect.sleep(delay)\n const now = yield* Clock.currentTimeMillis\n const latest = yield* SynchronizedRef.modify(outbound, state =>\n state.held === undefined\n ? ([undefined, { ...state, flusher: undefined }] as const)\n : ([state.held, { ...state, held: undefined, lastSent: now }] as const),\n )\n if (latest === undefined) return\n yield* publish(latest.value)\n }\n })\n\n const broadcast = (value: Update, at: number): Effect.Effect<void> =>\n Effect.gen(function* () {\n const sends = yield* SynchronizedRef.modifyEffect(outbound, state =>\n Effect.gen(function* () {\n // `set` checked too, but `close` may have run since; a flush forked now would outlive it.\n if (yield* Ref.get(closed)) return [false, state] as const\n if (state.flusher !== undefined) return [false, { ...state, held: { value } }] as const\n // Without a throttle the wait is never positive, so every value goes at once; a\n // clock set back never makes one wait longer than an interval.\n const wait =\n state.lastSent === undefined ? 0 : Math.min(throttle, state.lastSent + throttle - at)\n if (wait <= 0) return [true, { ...state, lastSent: at }] as const\n const flusher = yield* Effect.forkIn(flush(wait), scope)\n return [false, { ...state, held: { value }, flusher }] as const\n }).pipe(Effect.uninterruptible),\n )\n if (sends) yield* publish(value)\n })\n\n const set = Effect.fn('Presence.set')(function* (value: Update) {\n if (yield* Ref.get(closed)) return\n const at = yield* Clock.currentTimeMillis\n yield* put(options.id, value, at)\n if (channel !== undefined) yield* broadcast(value, at)\n yield* notify()\n })\n\n const leave = Effect.fn('Presence.leave')(function* () {\n if (yield* Ref.get(closed)) return\n yield* cancelHeld\n yield* remove(options.id)\n if (channel !== undefined) yield* channel.publish({ id: options.id, value: null })\n yield* notify()\n })()\n\n const peerList = Effect.fn('Presence.peers')(function* () {\n const at = yield* Clock.currentTimeMillis\n const map = yield* Ref.get(peers)\n return [...map.values()].filter(peer => !expired(peer, at)).map(peer => ({ ...peer }))\n })()\n\n const prune = Effect.fn('Presence.prune')(function* () {\n if (yield* Ref.get(closed)) return\n const at = yield* Clock.currentTimeMillis\n const changed = yield* Ref.modify(peers, map => {\n let removed = false\n const next = new Map(map)\n for (const [id, peer] of map) {\n if (expired(peer, at)) {\n next.delete(id)\n removed = true\n }\n }\n return [removed, next] as const\n })\n if (changed) yield* notify()\n })()\n\n const close = Effect.fn('Presence.close')(function* () {\n if (yield* Ref.get(closed)) return\n yield* Ref.set(closed, true)\n yield* cancelHeld\n if (consuming !== undefined) yield* Fiber.interrupt(consuming)\n yield* Effect.sync(() => listeners.clear())\n yield* PubSub.shutdown(signals)\n })()\n\n return {\n set,\n leave,\n peers: peerList,\n prune,\n subscribe: (listener: () => void) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n changes: Stream.concat(\n Stream.fromEffect(peerList),\n Stream.fromPubSub(signals).pipe(Stream.mapEffect(() => peerList)),\n ),\n close,\n }\n})\n\n/** An in-process channel, for tests and single-process demos. */\nexport const loopbackPresenceChannel = Effect.fn('Presence.loopbackChannel')(function* <Update>() {\n const updates = yield* PubSub.unbounded<PresenceUpdate<Update>>()\n return {\n updates,\n publish: (update: PresenceUpdate<Update>) => PubSub.publish(updates, update),\n }\n})\n\n/** Broadcasts presence updates among connected peers. */\nexport interface PresenceHub<Update> {\n /** Registers a peer's send; returns a leave function. */\n join(send: (update: PresenceUpdate<Update>) => void): () => void\n /** Fans an update out to every joined peer. */\n publish(update: PresenceUpdate<Update>): void\n}\n\nexport const createPresenceHub = <Update>(): PresenceHub<Update> => {\n const peers = new Set<(update: PresenceUpdate<Update>) => void>()\n return {\n join: send => {\n peers.add(send)\n return () => peers.delete(send)\n },\n publish: update => {\n for (const send of [...peers]) {\n try {\n send(update)\n } catch {\n // One broken peer must not starve the rest of the fan-out.\n }\n }\n },\n }\n}\n\nconst frameType = 'presence'\n\n/** A presence frame. `id` is set by the server that owns the identity. */\ninterface PresenceFrame<Update> {\n readonly id: string | undefined\n readonly value: Update | null\n}\n\n/** Decodes a presence frame, ignoring anything else a socket may carry. */\nconst decodePresence = <Update>(data: string): PresenceFrame<Update> | undefined => {\n let frame: unknown\n try {\n frame = JSON.parse(data)\n } catch {\n return undefined\n }\n if (typeof frame !== 'object' || frame === null) return undefined\n const payload = (frame as Record<string, unknown>)[frameType]\n if (typeof payload !== 'object' || payload === null) return undefined\n const { id, value } = payload as { id?: unknown; value?: unknown }\n return { id: typeof id === 'string' ? id : undefined, value: (value ?? null) as Update | null }\n}\n\n/**\n * A presence channel fed by stamped frames from the server, sent back without an\n * id: the server owns peer identity, so a client cannot assert another's.\n */\nexport const socketPresenceChannel = <Update>(\n socket: SocketLike,\n): Effect.Effect<PresenceChannel<Update>, never, Scope.Scope> =>\n Effect.gen(function* () {\n const updates = yield* PubSub.unbounded<PresenceUpdate<Update>>()\n yield* Effect.acquireRelease(\n Effect.sync(() =>\n socket.onMessage(data => {\n const frame = decodePresence<Update>(data)\n // An unstamped frame is not from the server and carries no identity.\n if (frame === undefined || frame.id === undefined) return\n PubSub.publishUnsafe(updates, { id: frame.id, value: frame.value })\n }),\n ),\n off => Effect.sync(off),\n )\n return {\n updates,\n publish: update =>\n Effect.sync(() => socket.send(JSON.stringify({ [frameType]: { value: update.value } }))),\n }\n })\n\n/**\n * Serves presence frames on an accepted socket, stamping the connection's\n * identity, until the socket closes or the returned function is called.\n * With `opens`, the connection joins only once it answers that it may open\n * the document the presence accompanies: until then, and for good when it\n * is refused or fails, nothing reaches it and nothing it sends is relayed.\n */\nexport const servePresence = <Update>(\n socket: SocketLike,\n hub: PresenceHub<Update>,\n options: {\n readonly peerId: string\n readonly opens?: Effect.Effect<boolean, unknown> | undefined\n },\n): (() => void) => {\n const send = (update: PresenceUpdate<Update>): void =>\n socket.send(JSON.stringify({ [frameType]: { id: update.id, value: update.value } }))\n let stopped = false\n let leave = (): void => {}\n let off = (): void => {}\n const join = (): void => {\n leave = hub.join(send)\n off = socket.onMessage(data => {\n const frame = decodePresence<Update>(data)\n if (frame === undefined) return\n // The connection owns the identity; a client-supplied id is ignored.\n const publish = () => hub.publish({ id: options.peerId, value: frame.value })\n if (options.opens === undefined) return publish()\n // Asked again with each frame: one no longer let open the document leaves.\n void Effect.runPromise(options.opens).then(\n open => {\n if (stopped) return\n if (open) publish()\n else stop()\n },\n () => stop(),\n )\n })\n }\n if (options.opens === undefined) join()\n else\n void Effect.runPromise(options.opens).then(\n open => {\n if (open && !stopped) join()\n },\n () => {},\n )\n const stop = (): void => {\n stopped = true\n off()\n leave()\n }\n const stopClose = socket.onClose(stop)\n return () => {\n stop()\n stopClose()\n }\n}\n"],"mappings":";;;;;;;;;;;AAuFA,MAAa,iBAAiB,OAAO,GAAG,iBAAiB,CAAC,CAAC,WACzD,SACA;CACA,MAAM,MAAM,SAAS,SAAS,QAAQ,GAAG;CACzC,MAAM,WAAW,QAAQ,aAAa,KAAA,IAAY,IAAI,SAAS,SAAS,QAAQ,QAAQ;CACxF,MAAM,QAAQ,OAAO,OAAO;CAI5B,MAAM,WAAW,OAAO,gBAAgB,KAIrC;EAAE,UAAU,KAAA;EA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AAC;CACzB,IAAI,YAAkB,CAAC;CACvB,MAAM,aAAmB;EACvB,QAAQ,IAAI,KAAK,IAAI;EACrB,MAAM,OAAO,WAAU,SAAQ;GAC7B,MAAM,QAAQ,eAAuB,IAAI;GACzC,IAAI,UAAU,KAAA,GAAW;GAEzB,MAAM,gBAAgB,IAAI,QAAQ;IAAE,IAAI,QAAQ;IAAQ,OAAO,MAAM;GAAM,CAAC;GAC5E,IAAI,QAAQ,UAAU,KAAA,GAAW,OAAO,QAAQ;GAEhD,OAAY,WAAW,QAAQ,KAAK,CAAC,CAAC,MACpC,SAAQ;IACN,IAAI,SAAS;IACb,IAAI,MAAM,QAAQ;SACb,KAAK;GACZ,SACM,KAAK,CACb;EACF,CAAC;CACH;CACA,IAAI,QAAQ,UAAU,KAAA,GAAW,KAAK;MAEpC,OAAY,WAAW,QAAQ,KAAK,CAAC,CAAC,MACpC,SAAQ;EACN,IAAI,QAAQ,CAAC,SAAS,KAAK;CAC7B,SACM,CAAC,CACT;CACF,MAAM,aAAmB;EACvB,UAAU;EACV,IAAI;EACJ,MAAM;CACR;CACA,MAAM,YAAY,OAAO,QAAQ,IAAI;CACrC,aAAa;EACX,KAAK;EACL,UAAU;CACZ;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Author } from "./entity.mjs";
|
|
2
1
|
import { Option, Schema } from "effect";
|
|
3
2
|
import { OptimisticOperation, RemoteModel } from "foldkit-remote";
|
|
3
|
+
import { Author } from "./entity.js";
|
|
4
4
|
/** What `RemoteEdits.make` uses of a Remote domain: `Remote.make`'s value is one. */
|
|
5
5
|
export interface RemoteOverlays<AppModel> {
|
|
6
6
|
readonly store: {
|
|
@@ -90,4 +90,4 @@ export declare const RemoteEdits: {
|
|
|
90
90
|
};
|
|
91
91
|
export type RemoteEdits<AppModel, Edit extends AnyEdit> = ReturnType<typeof make<AppModel, Edit>>;
|
|
92
92
|
export {};
|
|
93
|
-
//# sourceMappingURL=remote.d.
|
|
93
|
+
//# sourceMappingURL=remote.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"remote.d.ts","names":[],"sources":["../src/remote.ts"],"mappings":";;;;iBAyBiB,eAAe;WACrB;IAAS,IAAI,OAAO,WAAW;;EACxC,QAAQ,OAAO,UAAU,YAAY,YAAY,cAAc,uBAAuB;EACtF,KAAK,OAAO,UAAU,aAAa;EACnC,SAAS,OAAO,WAAW;;;iBAIZ,QAAQ;WACd;aAAmB;;WACnB,MAAM,OAAO,MAAM;EAC5B,KAAK,MAAM,MAAM;;;UAIT;WACC;WACA,IAAI,OAAO;WACX,IAAI,OAAO,OAAO;;;iBAWZ,UAAU;WAChB,MAAM;;WAEN;;;iBAIM,WAAW,UAAU;WAC3B,OAAO;;;;;;WAMP,MAAM,cAAc;;;;;;WAMpB,UAAU,cAAc;;cAG7B,OAAQ,UAAU,aAAa,SAAO,MACpC,eAAe,WAAS,OACvB,QAAQ;;;;;;;;;;;;;;;;;EA6Eb,YAAS,OACA,UAAQ,OACR,cAAc,OAAK,oBAEzB,WAAW,UAAU;;;;;;EA8DxB,QAAK,OAAU,aAAW,cAAc,UAAU;;;;;EAWlD,QAAK,OAAU,aAAW;;qBAKjB;;;;;;;;;;;;YAYD,YAAY,UAAU,aAAa,WAAW,kBAAkB,KAAK,UAAU"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"remote.js","names":[],"sources":["../src/remote.ts"],"sourcesContent":["/**\n * `foldkit-sync/remote`: a slice's cell edits shown through Remote, as\n * request-less overlays every read draws, until the row Remote holds has them.\n *\n * ```text\n * cell shown = Remote's row, with each edit over it the row has not reached:\n * one pending, one committed after the row's revision, or one\n * the journal absorbed while the cached row is still below it\n * ```\n *\n * Remote keeps the overlays; the slice stays the only copy of the edits. An\n * overlay is not stored, so after a reload `reconcile` rebuilds them from the\n * slice the replica restored. What an edit absorbed and dropped from the slice\n * still owes a cached row is held as an overlay, not in the application's\n * Model, so every view of the row (a second list, a filter, an undo's reading\n * of the page) sees what the page shows.\n *\n * Pure, like `foldkit-sync/entity`: it reads and writes the Model it is given\n * and sends nothing.\n */\nimport { Equal, Option, Schema } from 'effect'\nimport { entityKey, readField, type OptimisticOperation, type RemoteModel } from 'foldkit-remote'\nimport type { Author } from './entity.js'\n\n/** What `RemoteEdits.make` uses of a Remote domain: `Remote.make`'s value is one. */\nexport interface RemoteOverlays<AppModel> {\n readonly store: { get(model: AppModel): RemoteModel }\n overlay(model: AppModel, id: string, optimistic: ReadonlyArray<OptimisticOperation>): AppModel\n lift(model: AppModel, id: string): AppModel\n overlays(model: AppModel): ReadonlyArray<string>\n}\n\n/** What `RemoteEdits.make` uses of `EditableEntity.make`'s value, over a named Entity. */\nexport interface EditsOf<Edit> {\n readonly entity: { readonly name: string }\n readonly Edit: Schema.Codec<Edit, unknown>\n mine(edit: Edit, replica: string): boolean\n}\n\n/** The fields every cell edit has, as `EditableEntity`'s `Edit` declares them. */\ninterface AnyEdit {\n readonly member: string\n readonly at: Option.Option<number>\n readonly by: Option.Option<Author>\n}\n\n/** An edit as the store holds it: the encoded id, member and value. */\nconst Encoded = Schema.Struct({\n id: Schema.Union([Schema.String, Schema.Number]),\n member: Schema.String,\n value: Schema.Unknown,\n})\n\n/** A cell an overlay draws, and whether its edit is still in the slice or only held. */\nexport interface ShownEdit<Edit> {\n readonly edit: Edit\n /** Absorbed from the slice, and shown until a read of its row has it. */\n readonly held: boolean\n}\n\n/** What `reconcile` did besides the Model. */\nexport interface Reconciled<AppModel, Edit> {\n readonly model: AppModel\n /**\n * Edits the journal absorbed that a cached row has not been read since. The\n * row is out of date until it is: ask for it again, unless a live stream\n * brings it.\n */\n readonly held: ReadonlyArray<Edit>\n /**\n * `replica`'s own edits a read of their row reached with another value: the\n * table applies in commit order, so a later edit replaced them. The slice\n * may say whose later, or may not yet; this is the row saying it.\n */\n readonly replaced: ReadonlyArray<Edit>\n}\n\nconst make = <AppModel, Edit extends AnyEdit>(\n data: RemoteOverlays<AppModel>,\n edits: EditsOf<Edit>,\n) => {\n const entity = edits.entity.name\n const encode = Schema.encodeSync(edits.Edit)\n const decode = Schema.decodeUnknownOption(edits.Edit)\n const decodeEncoded = Schema.decodeUnknownSync(Encoded)\n // Named by the Entity, so a bridge over another one never reads these back.\n const SHOWN = `sync-edit:${entity}:`\n const HELD = `sync-held:${entity}:`\n\n // The overlay's id is the edit itself, encoded: the same edit keeps its\n // overlay, and another edit of the cell is another overlay.\n const keyOf = (edit: Edit) => JSON.stringify(encode(edit))\n const encodedOf = (edit: Edit) => decodeEncoded(encode(edit))\n const rowKey = (edit: Edit) => entityKey(entity, String(encodedOf(edit).id))\n const cellOf = (edit: Edit) => `${rowKey(edit)}\\u0000${edit.member}`\n\n /** The edits this bridge shows, by overlay id, read back from Remote's overlays. */\n const shownIn = (model: AppModel) =>\n data.overlays(model).flatMap(id => {\n const held = id.startsWith(HELD)\n if (!held && !id.startsWith(SHOWN)) return []\n const key = id.slice((held ? HELD : SHOWN).length)\n return Option.match(Option.flatMap(Option.liftThrowable(JSON.parse)(key), decode), {\n onNone: () => [],\n onSome: edit => [{ id, key, edit, held }],\n })\n })\n\n /** The revision Remote holds for the edit's row; none when the row is not cached. */\n const revisionOf = (remote: RemoteModel, edit: Edit): Option.Option<number> =>\n Option.filter(readField(remote.entities, rowKey(edit), 'revision'), Schema.is(Schema.Number))\n const reached = (remote: RemoteModel, edit: Edit) =>\n Option.exists(edit.at, at =>\n Option.exists(revisionOf(remote, edit), revision => at <= revision),\n )\n\n // Reconciling runs after every update; what it depends on rarely changes, so\n // the inputs it last left in line are kept by identity and a repeat is free.\n let settled:\n | {\n readonly entities: RemoteModel['entities']\n readonly optimistic: RemoteModel['optimistic']\n readonly slice: ReadonlyArray<Edit>\n readonly replica: string\n }\n | undefined\n\n /** Whether the row Remote holds has the edit's value in its cell. */\n const holdsValue = (remote: RemoteModel, edit: Edit) =>\n Equal.equals(\n readField(remote.entities, rowKey(edit), edit.member),\n Option.some(encodedOf(edit).value),\n )\n\n const patchOf = (edit: Edit): OptimisticOperation => {\n const { id, member, value } = encodedOf(edit)\n return { entity, id: String(id), values: { [member]: value } }\n }\n\n return {\n /**\n * Brings Remote's overlays in line with `slice`: each edit its row has not\n * reached is shown, and each overlay whose edit has left the slice is\n * lifted, unless its row is cached below it, in which case it is held\n * until a read of the row reaches it. This replica's edit the row has\n * reached with its own value is kept, landed, until the slice drops it, so\n * a later edit reaching the row live is seen replacing it. Call it from\n * `Sync.mount`'s `afterUpdate`: a read can land in any Remote Message, and\n * a replayed durable Message may not touch Remote. With nothing to change,\n * the Model comes back as it was given.\n *\n * Only a committed edit can be held: its `at` says which revision has it.\n * One that leaves the slice straight from pending, committed and absorbed\n * before this page installed the commit, is lifted, and its row shows the\n * cached read until it is read again.\n */\n reconcile: (\n model: AppModel,\n slice: ReadonlyArray<Edit>,\n replica: string,\n ): Reconciled<AppModel, Edit> => {\n const remote = data.store.get(model)\n if (\n settled !== undefined &&\n settled.entities === remote.entities &&\n settled.optimistic === remote.optimistic &&\n settled.slice === slice &&\n settled.replica === replica\n ) {\n return { model, held: [], replaced: [] }\n }\n const inSlice = new Map(slice.map(edit => [keyOf(edit), edit]))\n const edited = new Set(slice.map(cellOf))\n const held: Array<Edit> = []\n const replaced: Array<Edit> = []\n let next = model\n for (const shown of shownIn(model)) {\n const reachedNow = reached(remote, shown.edit)\n const differs = reachedNow && !holdsValue(remote, shown.edit)\n if (!shown.held && inSlice.has(shown.key)) {\n inSlice.delete(shown.key)\n // Kept while the row is below it, and, landed, while it is this\n // replica's and the row still holds it: a later edit that reaches the\n // row live is then seen replacing it, though the slice may never say.\n if (!reachedNow || (!differs && edits.mine(shown.edit, replica))) continue\n next = data.lift(next, shown.id)\n if (differs && edits.mine(shown.edit, replica)) replaced.push(shown.edit)\n continue\n }\n // Held only while nothing in the slice edits the cell and the cached\n // row is below the commit; a later edit of the cell takes its place.\n const holds =\n !edited.has(cellOf(shown.edit)) &&\n Option.isSome(shown.edit.at) &&\n Option.isSome(revisionOf(remote, shown.edit)) &&\n !reached(remote, shown.edit)\n if (holds && shown.held) continue\n next = data.lift(next, shown.id)\n if (holds) {\n next = data.overlay(next, `${HELD}${shown.key}`, [patchOf(shown.edit)])\n held.push(shown.edit)\n } else if (differs && edits.mine(shown.edit, replica)) {\n replaced.push(shown.edit)\n }\n }\n for (const [key, edit] of inSlice) {\n if (!reached(remote, edit)) next = data.overlay(next, `${SHOWN}${key}`, [patchOf(edit)])\n }\n settled = {\n entities: remote.entities,\n optimistic: data.store.get(next).optimistic,\n slice,\n replica,\n }\n return { model: next, held, replaced }\n },\n\n /**\n * The edits the overlays show over their rows now, in the order they are\n * drawn: for a cell's mark. One the row has reached, kept only to see a\n * later edit replace it, is not among them.\n */\n shown: (model: AppModel): ReadonlyArray<ShownEdit<Edit>> => {\n const remote = data.store.get(model)\n return shownIn(model).flatMap(({ edit, held }) =>\n reached(remote, edit) ? [] : [{ edit, held }],\n )\n },\n\n /**\n * Lifts every overlay this bridge shows: for a server reset, after which\n * the rows' revisions count a history that is gone.\n */\n clear: (model: AppModel): AppModel =>\n shownIn(model).reduce((next, shown) => data.lift(next, shown.id), model),\n }\n}\n\nexport const RemoteEdits = {\n /**\n * The bridge between a slice of `EditableEntity` edits and a Remote domain\n * that reads the same Entity, with its `revision`.\n *\n * ```ts\n * const Shown = RemoteEdits.make(Data, ProductEdits)\n * const { model: next } = Shown.reconcile(model, model.edits, model.replica)\n * ```\n */\n make,\n}\nexport type RemoteEdits<AppModel, Edit extends AnyEdit> = ReturnType<typeof make<AppModel, Edit>>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAM,UAAU,OAAO,OAAO;CAC5B,IAAI,OAAO,MAAM,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC;CAC/C,QAAQ,OAAO;CACf,OAAO,OAAO;AAChB,CAAC;AA0BD,MAAM,QACJ,MACA,UACG;CACH,MAAM,SAAS,MAAM,OAAO;CAC5B,MAAM,SAAS,OA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KAC3B,OAAO,OAAO,WAAW,QAAQ,MAAM,IAAI,CAAC,KAC5C,CAAC,QAAQ,QAAQ,MAAM,IAAI;IAC7B,IAAI,SAAS,MAAM,MAAM;IACzB,OAAO,KAAK,KAAK,MAAM,MAAM,EAAE;IAC/B,IAAI,OAAO;KACT,OAAO,KAAK,QAAQ,MAAM,GAAG,OAAO,MAAM,OAAO,CAAC,QAAQ,MAAM,IAAI,CAAC,CAAC;KACtE,KAAK,KAAK,MAAM,IAAI;IACtB,OAAO,IAAI,WAAW,MAAM,KAAK,MAAM,MAAM,OAAO,GAClD,SAAS,KAAK,MAAM,IAAI;GAE5B;GACA,KAAK,MAAM,CAAC,KAAK,SAAS,SACxB,IAAI,CAAC,QAAQ,QAAQ,IAAI,GAAG,OAAO,KAAK,QAAQ,MAAM,GAAG,QAAQ,OAAO,CAAC,QAAQ,IAAI,CAAC,CAAC;GAEzF,UAAU;IACR,UAAU,OAAO;IACjB,YAAY,KAAK,MAAM,IAAI,IAAI,CAAC,CAAC;IACjC;IACA;GACF;GACA,OAAO;IAAE,OAAO;IAAM;IAAM;GAAS;EACvC;;;;;;EAOA,QAAQ,UAAoD;GAC1D,MAAM,SAAS,KAAK,MAAM,IAAI,KAAK;GACnC,OAAO,QAAQ,KAAK,CAAC,CAAC,SAAS,EAAE,MAAM,WACrC,QAAQ,QAAQ,IAAI,IAAI,CAAC,IAAI,CAAC;IAAE;IAAM;GAAK,CAAC,CAC9C;EACF;;;;;EAMA,QAAQ,UACN,QAAQ,KAAK,CAAC,CAAC,QAAQ,MAAM,UAAU,KAAK,KAAK,MAAM,MAAM,EAAE,GAAG,KAAK;CAC3E;AACF;AAEA,MAAa,cAAc;;;;;;;;;;AAUzB,KACF"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { Duration } from "effect";
|
|
2
|
+
/** Refuses a revalidation interval that would ask the session store without pause. */
|
|
3
|
+
export declare const checkRevalidate: (revalidate: {
|
|
4
|
+
readonly every: Duration.Input;
|
|
5
|
+
} | undefined, who: string) => void;
|
|
6
|
+
//# sourceMappingURL=revalidate.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"revalidate.d.ts","names":[],"sources":["../src/revalidate.ts"],"mappings":";;qBAIa,kBAAe;WACH,OAAO,SAAS;eAAmB"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Duration } from "effect";
|
|
2
|
+
// src/revalidate.ts
|
|
3
|
+
/** Shared by `documentHost` and `defineDocumentHost`; not part of either entry's API. */
|
|
4
|
+
/** Refuses a revalidation interval that would ask the session store without pause. */
|
|
5
|
+
const checkRevalidate = (revalidate, who) => {
|
|
6
|
+
if (revalidate !== void 0 && !Duration.isGreaterThan(Duration.fromInputUnsafe(revalidate.every), Duration.zero)) throw new Error(`${who}: revalidate.every must be longer than zero`);
|
|
7
|
+
};
|
|
8
|
+
export { checkRevalidate };
|
|
9
|
+
|
|
10
|
+
//# sourceMappingURL=revalidate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"revalidate.js","names":[],"sources":["../src/revalidate.ts"],"sourcesContent":["/** Shared by `documentHost` and `defineDocumentHost`; not part of either entry's API. */\nimport { Duration } from 'effect'\n\n/** Refuses a revalidation interval that would ask the session store without pause. */\nexport const checkRevalidate = (\n revalidate: { readonly every: Duration.Input } | undefined,\n who: string,\n): void => {\n if (\n revalidate !== undefined &&\n !Duration.isGreaterThan(Duration.fromInputUnsafe(revalidate.every), Duration.zero)\n )\n throw new Error(`${who}: revalidate.every must be longer than zero`)\n}\n"],"mappings":";;;;AAIA,MAAa,mBACX,YACA,QACS;CACT,IACE,eAAe,KAAA,KACf,CAAC,SAAS,cAAc,SAAS,gBAAgB,WAAW,KAAK,GAAG,SAAS,IAAI,GAEjF,MAAM,IAAI,MAAM,GAAG,IAAI,4CAA4C;AACvE"}
|