experimental-a2 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +169 -0
- package/dist/ai-B4YhEnfw.d.ts +333 -0
- package/dist/ai-server.d.ts +48 -9
- package/dist/ai-server.js +121 -49
- package/dist/ai.d.ts +2 -303
- package/dist/ai.js +231 -86
- package/dist/cli-B3VuxoDe.js +597 -0
- package/dist/cli-bin.d.ts +1 -0
- package/dist/cli-bin.js +5 -0
- package/dist/cli.d.ts +19 -0
- package/dist/cli.js +2 -0
- package/dist/client-BrfDXQ8A.d.ts +155 -0
- package/dist/client-Bt4tAKi9.js +798 -0
- package/dist/client.d.ts +2 -90
- package/dist/client.js +1 -409
- package/dist/{contract-CG_adnu_.js → contract-48bUMgcL.js} +10 -2
- package/dist/{contract-C_3dIIEU.d.ts → contract-jIfaR085.d.ts} +62 -8
- package/dist/devtools-J_jZ2vQf.d.ts +151 -0
- package/dist/devtools-kJJaORn-.js +338 -0
- package/dist/devtools-server.browser.js +1 -1
- package/dist/devtools-server.d.ts +2 -2
- package/dist/devtools-server.js +224 -43
- package/dist/devtools.d.ts +2 -0
- package/dist/devtools.js +2 -0
- package/dist/{errors-BJRMd-h6.js → errors-BQuJpe82.js} +4 -4
- package/dist/{errors-xL_JTXsY.d.ts → errors-W6nwJ-fm.d.ts} +1 -1
- package/dist/http.d.ts +71 -13
- package/dist/http.js +302 -41
- package/dist/{idempotent-replay-BMyHrP0L.js → idempotent-replay-DuqEkYA7.js} +2 -2
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -2
- package/dist/{inspection-E7qbD0Xj.js → inspection-DaxB5jM2.js} +2 -1
- package/dist/internal-aEotMzu_.js +209 -0
- package/dist/otel.d.ts +1 -1
- package/dist/platform-B4TnJtWu.js +32 -0
- package/dist/react.d.ts +37 -14
- package/dist/react.js +26 -15
- package/dist/scheduler-qstash.d.ts +78 -0
- package/dist/scheduler-qstash.js +499 -0
- package/dist/scheduler-task-BpzhPnRS.js +54 -0
- package/dist/{recovery-vercel.d.ts → scheduler-vercel.d.ts} +17 -24
- package/dist/scheduler-vercel.js +226 -0
- package/dist/server-CcNnFnoW.js +1405 -0
- package/dist/server-YtPq7hjw.d.ts +260 -0
- package/dist/server.d.ts +4 -155
- package/dist/server.js +2 -2
- package/dist/{log-ldf5g8Cx.d.ts → store-C3sNAaBT.d.ts} +111 -35
- package/dist/{log-yJbXUf72.js → store-N8PXxDAS.js} +1 -1
- package/dist/store-codec-DTG0Ftek.js +8 -0
- package/dist/store-memory.d.ts +11 -0
- package/dist/{log-memory.js → store-memory.js} +127 -24
- package/dist/{log-polling-6COoN60V.js → store-polling-DgrrAE3d.js} +7 -6
- package/dist/{log-postgres.d.ts → store-postgres.d.ts} +6 -6
- package/dist/{log-postgres.js → store-postgres.js} +158 -24
- package/dist/{log-redis.js → store-redis-core-DWqx3F47.js} +294 -156
- package/dist/store-redis-http.d.ts +21 -0
- package/dist/store-redis-http.js +70 -0
- package/dist/store-redis.d.ts +37 -0
- package/dist/store-redis.js +298 -0
- package/dist/{log-sqlite.d.ts → store-sqlite.d.ts} +6 -6
- package/dist/{log-sqlite.js → store-sqlite.js} +116 -22
- package/dist/{telemetry-Cso0qyHQ.d.ts → telemetry-BjYHTfh2.d.ts} +1 -1
- package/dist/testing.browser.d.ts +1 -0
- package/dist/testing.browser.js +4 -0
- package/dist/testing.d.ts +31 -0
- package/dist/testing.js +101 -0
- package/dist/wire-DCUZBUlT.js +222 -0
- package/docs/01-quickstart.mdx +4 -5
- package/docs/concepts/01-contracts.mdx +21 -17
- package/docs/concepts/02-handlers.mdx +7 -7
- package/docs/concepts/03-durability.mdx +26 -29
- package/docs/concepts/04-state.mdx +18 -21
- package/docs/guides/01-timers.mdx +154 -54
- package/docs/guides/02-cancellation.mdx +30 -4
- package/docs/guides/03-react.mdx +20 -21
- package/docs/guides/04-local-first.mdx +1 -1
- package/docs/guides/05-production.mdx +321 -60
- package/docs/guides/06-ai-agents.mdx +249 -49
- package/docs/guides/07-devtools.mdx +137 -12
- package/docs/guides/08-application-data.mdx +1 -1
- package/docs/guides/09-presence.mdx +284 -0
- package/docs/guides/10-transports.mdx +131 -0
- package/docs/index.mdx +22 -46
- package/docs/reference/01-api.mdx +751 -102
- package/docs/reference/02-errors.mdx +10 -5
- package/package.json +23 -6
- package/dist/internal-D6wNxTck.js +0 -36
- package/dist/log-memory.d.ts +0 -11
- package/dist/log-redis.d.ts +0 -31
- package/dist/recovery-vercel.js +0 -119
- package/dist/server-DJgD2YWP.js +0 -877
- package/dist/wire-BVsgR8o9.js +0 -62
|
@@ -0,0 +1,798 @@
|
|
|
1
|
+
import { n as validateSync } from "./validate-XKT4FSNn.js";
|
|
2
|
+
import { t as A2Error } from "./errors-BQuJpe82.js";
|
|
3
|
+
import { a as PRESENCE_TIMINGS, c as STREAM_TIMINGS, g as nullProtoRecord } from "./internal-aEotMzu_.js";
|
|
4
|
+
import { a as eventFromWire, c as isWirePresencePatch, d as presencePatchFromWire, l as isWirePresenceSnapshot, n as errorFromWire, p as presenceSnapshotFromWire, s as isWireEvent, u as parseSocketFrame } from "./wire-DCUZBUlT.js";
|
|
5
|
+
//#region src/client.ts
|
|
6
|
+
/**
|
|
7
|
+
* experimental-a2/client — the framework-agnostic session client.
|
|
8
|
+
*
|
|
9
|
+
* Everything the browser needs to read a session live and push
|
|
10
|
+
* optimistically, with no framework attached: the SSE subscription with
|
|
11
|
+
* frontier resume and reconnection, the optimistic push queue with
|
|
12
|
+
* ack/rollback, and the local fold through the same reducer the server
|
|
13
|
+
* uses. `experimental-a2/react`'s `createReact` is a thin binding over it, and the
|
|
14
|
+
* store contract (`subscribe`/`getSnapshot`) is exactly what
|
|
15
|
+
* `useSyncExternalStore` wants.
|
|
16
|
+
*
|
|
17
|
+
* The client is a replica, never an access path — the routes it talks
|
|
18
|
+
* to authorize every read and write.
|
|
19
|
+
*/
|
|
20
|
+
const PUSH_ATTEMPTS = 3;
|
|
21
|
+
const DEFAULT_GC_TIME_MS = 3e5;
|
|
22
|
+
const httpTransport = (routes, fetchImpl, presence) => ({
|
|
23
|
+
async *connect({ sessionId, startAfter, signal }) {
|
|
24
|
+
const sep = routes.stream.includes("?") ? "&" : "?";
|
|
25
|
+
const res = await fetchImpl(`${routes.stream}${sep}sessionId=${encodeURIComponent(sessionId)}&index=${startAfter}`, {
|
|
26
|
+
headers: { accept: "text/event-stream" },
|
|
27
|
+
signal
|
|
28
|
+
});
|
|
29
|
+
if (!res.ok || !res.body) throw new Error(`stream failed with ${res.status}`);
|
|
30
|
+
yield { kind: "ping" };
|
|
31
|
+
const decoder = new TextDecoder();
|
|
32
|
+
const reader = res.body.getReader();
|
|
33
|
+
let buffer = "";
|
|
34
|
+
try {
|
|
35
|
+
for (;;) {
|
|
36
|
+
const { done, value } = await reader.read();
|
|
37
|
+
if (done) return;
|
|
38
|
+
yield { kind: "ping" };
|
|
39
|
+
buffer += decoder.decode(value, { stream: true });
|
|
40
|
+
for (;;) {
|
|
41
|
+
const boundary = buffer.indexOf("\n\n");
|
|
42
|
+
if (boundary === -1) break;
|
|
43
|
+
const frame = buffer.slice(0, boundary);
|
|
44
|
+
buffer = buffer.slice(boundary + 2);
|
|
45
|
+
let eventName;
|
|
46
|
+
const dataLines = [];
|
|
47
|
+
for (const line of frame.split("\n")) if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
|
|
48
|
+
else if (line.startsWith("event:")) eventName = line.slice(6).trim();
|
|
49
|
+
const data = dataLines.join("\n");
|
|
50
|
+
if (!data) continue;
|
|
51
|
+
if (eventName === void 0) {
|
|
52
|
+
const parsed = JSON.parse(data);
|
|
53
|
+
if (isWireEvent(parsed)) yield {
|
|
54
|
+
kind: "event",
|
|
55
|
+
event: parsed
|
|
56
|
+
};
|
|
57
|
+
} else if (presence && eventName === "presence-snapshot") {
|
|
58
|
+
const parsed = JSON.parse(data);
|
|
59
|
+
if (isWirePresenceSnapshot(parsed)) yield {
|
|
60
|
+
kind: "presence-snapshot",
|
|
61
|
+
snapshot: parsed
|
|
62
|
+
};
|
|
63
|
+
} else if (presence && eventName === "presence") {
|
|
64
|
+
const parsed = JSON.parse(data);
|
|
65
|
+
if (isWirePresencePatch(parsed)) yield {
|
|
66
|
+
kind: "presence",
|
|
67
|
+
patch: parsed
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
} finally {
|
|
73
|
+
reader.cancel().catch(() => {});
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
async push(body) {
|
|
77
|
+
const res = await fetchImpl(routes.push, {
|
|
78
|
+
method: "POST",
|
|
79
|
+
headers: { "content-type": "application/json" },
|
|
80
|
+
body: JSON.stringify(body)
|
|
81
|
+
});
|
|
82
|
+
if (res.ok) {
|
|
83
|
+
const rows = await res.json();
|
|
84
|
+
if (!Array.isArray(rows) || !rows.every(isWireEvent)) throw new A2Error("STORE_UNAVAILABLE", "push ack was not a list of events");
|
|
85
|
+
return rows;
|
|
86
|
+
}
|
|
87
|
+
throw errorFromWire(await res.json().catch(() => null)) ?? new A2Error("STORE_UNAVAILABLE", `push failed with ${res.status}`);
|
|
88
|
+
},
|
|
89
|
+
sendPresence(envelope) {
|
|
90
|
+
(async () => {
|
|
91
|
+
try {
|
|
92
|
+
await (await fetchImpl(routes.push, {
|
|
93
|
+
method: "POST",
|
|
94
|
+
headers: { "content-type": "application/json" },
|
|
95
|
+
body: JSON.stringify(envelope)
|
|
96
|
+
})).arrayBuffer();
|
|
97
|
+
} catch {}
|
|
98
|
+
})();
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
/** `WebSocket.OPEN` — fixed by the spec, identical in every runtime. */
|
|
102
|
+
const WS_OPEN = 1;
|
|
103
|
+
const wsTransport = (url, webSocketImpl, presence) => {
|
|
104
|
+
const connections = /* @__PURE__ */ new Map();
|
|
105
|
+
/** Push retries parked in `awaitReady`, flushed on socket open. */
|
|
106
|
+
const readyWaiters = /* @__PURE__ */ new Map();
|
|
107
|
+
let nextReq = 1;
|
|
108
|
+
const flushReadyWaiters = (sessionId) => {
|
|
109
|
+
const waiters = readyWaiters.get(sessionId);
|
|
110
|
+
if (!waiters) return;
|
|
111
|
+
readyWaiters.delete(sessionId);
|
|
112
|
+
for (const waiter of waiters) waiter();
|
|
113
|
+
};
|
|
114
|
+
const socketUrl = (sessionId, startAfter) => {
|
|
115
|
+
let resolved;
|
|
116
|
+
if (/^(https?|wss?):\/\//i.test(url)) resolved = new URL(url);
|
|
117
|
+
else {
|
|
118
|
+
const base = globalThis.location?.href;
|
|
119
|
+
if (base === void 0) throw new TypeError(`cannot resolve the relative ws url '${url}' without a browser location — pass an absolute ws:// or wss:// url`);
|
|
120
|
+
resolved = new URL(url, base);
|
|
121
|
+
}
|
|
122
|
+
if (resolved.protocol === "http:") resolved.protocol = "ws:";
|
|
123
|
+
else if (resolved.protocol === "https:") resolved.protocol = "wss:";
|
|
124
|
+
resolved.searchParams.set("sessionId", sessionId);
|
|
125
|
+
resolved.searchParams.set("index", String(startAfter));
|
|
126
|
+
return resolved.href;
|
|
127
|
+
};
|
|
128
|
+
return {
|
|
129
|
+
async *connect({ sessionId, startAfter, signal }) {
|
|
130
|
+
if (webSocketImpl === void 0) throw new TypeError("no WebSocket implementation available — pass one via createClient({ webSocket }) where the global is missing");
|
|
131
|
+
const socket = new webSocketImpl(socketUrl(sessionId, startAfter));
|
|
132
|
+
const connection = {
|
|
133
|
+
socket,
|
|
134
|
+
pending: /* @__PURE__ */ new Map()
|
|
135
|
+
};
|
|
136
|
+
connections.set(sessionId, connection);
|
|
137
|
+
const queue = [];
|
|
138
|
+
let ended = false;
|
|
139
|
+
let failure = null;
|
|
140
|
+
let wake = null;
|
|
141
|
+
const notify = () => {
|
|
142
|
+
wake?.();
|
|
143
|
+
wake = null;
|
|
144
|
+
};
|
|
145
|
+
const finish = (error) => {
|
|
146
|
+
if (ended) return;
|
|
147
|
+
ended = true;
|
|
148
|
+
failure = error;
|
|
149
|
+
if (connections.get(sessionId) === connection) connections.delete(sessionId);
|
|
150
|
+
const rejection = new A2Error("STORE_UNAVAILABLE", "socket closed with the ack outstanding");
|
|
151
|
+
for (const waiter of connection.pending.values()) waiter.reject(rejection);
|
|
152
|
+
connection.pending.clear();
|
|
153
|
+
notify();
|
|
154
|
+
};
|
|
155
|
+
socket.addEventListener("open", () => {
|
|
156
|
+
queue.push({ kind: "ping" });
|
|
157
|
+
notify();
|
|
158
|
+
flushReadyWaiters(sessionId);
|
|
159
|
+
});
|
|
160
|
+
socket.addEventListener("message", (event) => {
|
|
161
|
+
if (typeof event.data !== "string") return;
|
|
162
|
+
const frame = parseSocketFrame(event.data);
|
|
163
|
+
if (frame === null) return;
|
|
164
|
+
if (frame.kind === "ack") {
|
|
165
|
+
const waiter = connection.pending.get(frame.req);
|
|
166
|
+
if (waiter === void 0) return;
|
|
167
|
+
connection.pending.delete(frame.req);
|
|
168
|
+
if ("events" in frame) waiter.resolve(frame.events);
|
|
169
|
+
else waiter.reject(frame.error);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (!presence && frame.kind !== "event" && frame.kind !== "ping") return;
|
|
173
|
+
queue.push(frame);
|
|
174
|
+
notify();
|
|
175
|
+
});
|
|
176
|
+
socket.addEventListener("close", (event) => {
|
|
177
|
+
finish(event.code === 1e3 ? null : /* @__PURE__ */ new Error(`socket closed (${event.code}${event.reason ? `: ${event.reason}` : ""})`));
|
|
178
|
+
});
|
|
179
|
+
socket.addEventListener("error", () => {
|
|
180
|
+
finish(/* @__PURE__ */ new Error("socket error"));
|
|
181
|
+
});
|
|
182
|
+
const onAbort = () => {
|
|
183
|
+
finish(signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("stream aborted"));
|
|
184
|
+
try {
|
|
185
|
+
socket.close(1e3);
|
|
186
|
+
} catch {}
|
|
187
|
+
};
|
|
188
|
+
if (signal.aborted) onAbort();
|
|
189
|
+
else signal.addEventListener("abort", onAbort, { once: true });
|
|
190
|
+
try {
|
|
191
|
+
for (;;) {
|
|
192
|
+
while (queue.length > 0) yield queue.shift();
|
|
193
|
+
if (ended) {
|
|
194
|
+
if (failure) throw failure;
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
await new Promise((resolve) => {
|
|
198
|
+
wake = resolve;
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
} finally {
|
|
202
|
+
signal.removeEventListener("abort", onAbort);
|
|
203
|
+
finish(null);
|
|
204
|
+
try {
|
|
205
|
+
socket.close(1e3);
|
|
206
|
+
} catch {}
|
|
207
|
+
}
|
|
208
|
+
},
|
|
209
|
+
async push(body) {
|
|
210
|
+
const connection = connections.get(body.sessionId);
|
|
211
|
+
if (connection === void 0 || connection.socket.readyState !== WS_OPEN) throw new A2Error("STORE_UNAVAILABLE", "no open socket for the session");
|
|
212
|
+
const req = nextReq;
|
|
213
|
+
nextReq += 1;
|
|
214
|
+
return await new Promise((resolve, reject) => {
|
|
215
|
+
connection.pending.set(req, {
|
|
216
|
+
resolve,
|
|
217
|
+
reject
|
|
218
|
+
});
|
|
219
|
+
const frame = {
|
|
220
|
+
kind: "push",
|
|
221
|
+
req,
|
|
222
|
+
events: body.events
|
|
223
|
+
};
|
|
224
|
+
try {
|
|
225
|
+
connection.socket.send(JSON.stringify(frame));
|
|
226
|
+
} catch (cause) {
|
|
227
|
+
connection.pending.delete(req);
|
|
228
|
+
reject(new A2Error("STORE_UNAVAILABLE", "socket send failed", { cause }));
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
},
|
|
232
|
+
awaitReady(sessionId, maxWaitMs) {
|
|
233
|
+
const connection = connections.get(sessionId);
|
|
234
|
+
if (connection && connection.socket.readyState === WS_OPEN) return Promise.resolve();
|
|
235
|
+
return new Promise((resolve) => {
|
|
236
|
+
let waiters = readyWaiters.get(sessionId);
|
|
237
|
+
if (!waiters) {
|
|
238
|
+
waiters = /* @__PURE__ */ new Set();
|
|
239
|
+
readyWaiters.set(sessionId, waiters);
|
|
240
|
+
}
|
|
241
|
+
let settled = false;
|
|
242
|
+
const done = () => {
|
|
243
|
+
if (settled) return;
|
|
244
|
+
settled = true;
|
|
245
|
+
clearTimeout(timer);
|
|
246
|
+
waiters.delete(done);
|
|
247
|
+
resolve();
|
|
248
|
+
};
|
|
249
|
+
const timer = setTimeout(done, maxWaitMs);
|
|
250
|
+
timer.unref?.();
|
|
251
|
+
waiters.add(done);
|
|
252
|
+
});
|
|
253
|
+
},
|
|
254
|
+
sendPresence(envelope) {
|
|
255
|
+
const connection = connections.get(envelope.sessionId);
|
|
256
|
+
if (connection === void 0 || connection.socket.readyState !== WS_OPEN) return;
|
|
257
|
+
const frame = {
|
|
258
|
+
kind: "presence",
|
|
259
|
+
...envelope.presence
|
|
260
|
+
};
|
|
261
|
+
try {
|
|
262
|
+
connection.socket.send(JSON.stringify(frame));
|
|
263
|
+
} catch {}
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
};
|
|
267
|
+
const transportFor = (api, fetchImpl, webSocketImpl, presence) => {
|
|
268
|
+
if (typeof api === "string") return httpTransport({
|
|
269
|
+
push: api,
|
|
270
|
+
stream: api
|
|
271
|
+
}, fetchImpl, presence);
|
|
272
|
+
if (api.type === "http") return httpTransport({
|
|
273
|
+
push: api.push,
|
|
274
|
+
stream: api.stream
|
|
275
|
+
}, fetchImpl, presence);
|
|
276
|
+
return wsTransport(api.url, webSocketImpl, presence);
|
|
277
|
+
};
|
|
278
|
+
function createClient(options) {
|
|
279
|
+
const { reducer, api } = options;
|
|
280
|
+
const presenceDefs = reducer.presence;
|
|
281
|
+
const declaresPresence = Object.keys(presenceDefs).length > 0;
|
|
282
|
+
const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
283
|
+
const webSocketImpl = options.webSocket ?? globalThis.WebSocket;
|
|
284
|
+
const transport = transportFor(api, fetchImpl, webSocketImpl, declaresPresence);
|
|
285
|
+
const gcTime = options.gcTime ?? DEFAULT_GC_TIME_MS;
|
|
286
|
+
if (Number.isNaN(gcTime) || gcTime < 0) throw new RangeError("gcTime must be a non-negative number or Infinity");
|
|
287
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
288
|
+
const scheduleGc = (sessionId, delay = gcTime) => {
|
|
289
|
+
const entry = sessions.get(sessionId);
|
|
290
|
+
if (!entry) return;
|
|
291
|
+
clearTimeout(entry.timer);
|
|
292
|
+
if (gcTime === Infinity) return;
|
|
293
|
+
entry.timer = setTimeout(() => {
|
|
294
|
+
if (sessions.get(sessionId) !== entry) return;
|
|
295
|
+
if (entry.runtime.canEvict()) {
|
|
296
|
+
sessions.delete(sessionId);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
scheduleGc(sessionId, Math.max(gcTime, 1e3));
|
|
300
|
+
}, delay);
|
|
301
|
+
entry.timer.unref?.();
|
|
302
|
+
};
|
|
303
|
+
const touch = (sessionId) => {
|
|
304
|
+
scheduleGc(sessionId);
|
|
305
|
+
};
|
|
306
|
+
const makeSession = (sessionId, sessionOptions) => {
|
|
307
|
+
let frontier = sessionOptions?.initialIndex ?? 0;
|
|
308
|
+
let foldedState = sessionOptions?.initialState !== void 0 ? sessionOptions.initialState : reducer.initialState;
|
|
309
|
+
const serverEvents = (sessionOptions?.initialEvents ?? []).filter((event) => event.index <= frontier).toSorted((a, b) => a.index - b.index);
|
|
310
|
+
let pending = [];
|
|
311
|
+
let participant = sessionOptions?.participant;
|
|
312
|
+
let presenceState = nullProtoRecord();
|
|
313
|
+
let presenceLastSentAt = 0;
|
|
314
|
+
/** The last LWW stamp issued — see `nextPresenceAt`. */
|
|
315
|
+
let presenceLastAt = 0;
|
|
316
|
+
/** Values awaiting the trailing send — non-null exactly while
|
|
317
|
+
* `presenceTimer` is armed. */
|
|
318
|
+
let presenceBuffer = null;
|
|
319
|
+
let presenceTimer;
|
|
320
|
+
/** Own fields set while the stream was down — re-sent once on
|
|
321
|
+
* reconnect (their POSTs may have been lost with the network). */
|
|
322
|
+
let presenceResend = null;
|
|
323
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
324
|
+
let snapshot = null;
|
|
325
|
+
let status = "idle";
|
|
326
|
+
let reconnects = 0;
|
|
327
|
+
let lastError = null;
|
|
328
|
+
let inFlightPushes = 0;
|
|
329
|
+
let pushWireTail = Promise.resolve();
|
|
330
|
+
let deferredHydration;
|
|
331
|
+
let hydrationNotification;
|
|
332
|
+
const emit = () => {
|
|
333
|
+
for (const listener of [...listeners]) listener();
|
|
334
|
+
};
|
|
335
|
+
const notify = () => {
|
|
336
|
+
snapshot = null;
|
|
337
|
+
emit();
|
|
338
|
+
};
|
|
339
|
+
const notifyHydrated = () => {
|
|
340
|
+
snapshot = null;
|
|
341
|
+
clearTimeout(hydrationNotification);
|
|
342
|
+
hydrationNotification = setTimeout(emit, 0);
|
|
343
|
+
hydrationNotification.unref?.();
|
|
344
|
+
};
|
|
345
|
+
const mergeServerEvents = (events, throughIndex) => {
|
|
346
|
+
if (!events || events.length === 0) return false;
|
|
347
|
+
const byIndex = new Map(serverEvents.map((event) => [event.index, event]));
|
|
348
|
+
let changed = false;
|
|
349
|
+
for (const event of events) {
|
|
350
|
+
if (event.index > throughIndex) continue;
|
|
351
|
+
if (byIndex.get(event.index)?.id === event.id) continue;
|
|
352
|
+
byIndex.set(event.index, event);
|
|
353
|
+
changed = true;
|
|
354
|
+
}
|
|
355
|
+
if (!changed) return false;
|
|
356
|
+
serverEvents.splice(0, serverEvents.length, ...[...byIndex.values()].toSorted((a, b) => a.index - b.index));
|
|
357
|
+
return true;
|
|
358
|
+
};
|
|
359
|
+
const overlayEvents = () => {
|
|
360
|
+
const acked = pending.filter((p) => p.acked).map((p) => p.acked).toSorted((a, b) => a.index - b.index);
|
|
361
|
+
const maxKnown = acked.at(-1)?.index ?? frontier;
|
|
362
|
+
const unacked = pending.filter((p) => !p.acked).map((p, i) => ({
|
|
363
|
+
id: p.id,
|
|
364
|
+
type: p.type,
|
|
365
|
+
payload: p.payload,
|
|
366
|
+
index: maxKnown + 1 + i,
|
|
367
|
+
sessionId,
|
|
368
|
+
createdAt: p.createdAt
|
|
369
|
+
}));
|
|
370
|
+
return [...acked, ...unacked];
|
|
371
|
+
};
|
|
372
|
+
const connection = () => {
|
|
373
|
+
switch (status) {
|
|
374
|
+
case "idle": return { status: "idle" };
|
|
375
|
+
case "closed": return { status: "closed" };
|
|
376
|
+
case "live": return {
|
|
377
|
+
status: "live",
|
|
378
|
+
reconnects
|
|
379
|
+
};
|
|
380
|
+
case "connecting": return {
|
|
381
|
+
status: "connecting",
|
|
382
|
+
reconnects,
|
|
383
|
+
error: lastError
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
};
|
|
387
|
+
const buildSnapshot = () => {
|
|
388
|
+
const overlay = overlayEvents();
|
|
389
|
+
let state = foldedState;
|
|
390
|
+
for (const event of overlay) state = reducer.fold(state, event);
|
|
391
|
+
return {
|
|
392
|
+
state,
|
|
393
|
+
events: [...serverEvents, ...overlay],
|
|
394
|
+
index: frontier,
|
|
395
|
+
connection: connection(),
|
|
396
|
+
...declaresPresence ? { presence: presenceState } : {}
|
|
397
|
+
};
|
|
398
|
+
};
|
|
399
|
+
/**
|
|
400
|
+
* The per-session monotonic LWW stamp: wall-seeded, guarded
|
|
401
|
+
* `max(now, last + 1)`, so overlapping sends can never invert —
|
|
402
|
+
* the wall clock seeds it because it is the only monotonic state
|
|
403
|
+
* that survives a reload without A2 owning persistence.
|
|
404
|
+
*/
|
|
405
|
+
const nextPresenceAt = () => {
|
|
406
|
+
presenceLastAt = Math.max(Date.now(), presenceLastAt + 1);
|
|
407
|
+
return presenceLastAt;
|
|
408
|
+
};
|
|
409
|
+
const applyPresencePatch = (patch) => {
|
|
410
|
+
if (patch.participant === participant) return;
|
|
411
|
+
const entry = Object.assign(nullProtoRecord(), presenceState[patch.participant]);
|
|
412
|
+
let changed = false;
|
|
413
|
+
for (const [field, value] of Object.entries(patch.values)) {
|
|
414
|
+
if (value === void 0) continue;
|
|
415
|
+
const existing = entry[field];
|
|
416
|
+
if (existing && existing.at.getTime() > patch.at.getTime()) continue;
|
|
417
|
+
if (value === null) {
|
|
418
|
+
if (existing) {
|
|
419
|
+
delete entry[field];
|
|
420
|
+
changed = true;
|
|
421
|
+
}
|
|
422
|
+
} else {
|
|
423
|
+
entry[field] = {
|
|
424
|
+
value,
|
|
425
|
+
seen: patch.seen,
|
|
426
|
+
at: patch.at
|
|
427
|
+
};
|
|
428
|
+
changed = true;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
if (!changed) return;
|
|
432
|
+
const next = Object.assign(nullProtoRecord(), presenceState);
|
|
433
|
+
if (Object.keys(entry).length === 0) delete next[patch.participant];
|
|
434
|
+
else next[patch.participant] = entry;
|
|
435
|
+
presenceState = next;
|
|
436
|
+
notify();
|
|
437
|
+
};
|
|
438
|
+
const applyPresenceSnapshot = (incoming) => {
|
|
439
|
+
const next = nullProtoRecord();
|
|
440
|
+
for (const [id, fields] of Object.entries(incoming)) {
|
|
441
|
+
if (id === participant) continue;
|
|
442
|
+
next[id] = fields;
|
|
443
|
+
}
|
|
444
|
+
const own = participant === void 0 ? void 0 : presenceState[participant];
|
|
445
|
+
if (participant !== void 0 && own !== void 0) next[participant] = own;
|
|
446
|
+
presenceState = next;
|
|
447
|
+
notify();
|
|
448
|
+
};
|
|
449
|
+
const echoPresence = (id, values, atMs) => {
|
|
450
|
+
const entry = Object.assign(nullProtoRecord(), presenceState[id]);
|
|
451
|
+
const at = new Date(atMs);
|
|
452
|
+
for (const [field, value] of Object.entries(values)) if (value === null) delete entry[field];
|
|
453
|
+
else entry[field] = {
|
|
454
|
+
value,
|
|
455
|
+
seen: frontier,
|
|
456
|
+
at
|
|
457
|
+
};
|
|
458
|
+
const next = Object.assign(nullProtoRecord(), presenceState);
|
|
459
|
+
if (Object.keys(entry).length === 0) delete next[id];
|
|
460
|
+
else next[id] = entry;
|
|
461
|
+
presenceState = next;
|
|
462
|
+
notify();
|
|
463
|
+
};
|
|
464
|
+
const sendPresence = (values, at) => {
|
|
465
|
+
presenceLastSentAt = Date.now();
|
|
466
|
+
transport.sendPresence({
|
|
467
|
+
sessionId,
|
|
468
|
+
presence: {
|
|
469
|
+
participant,
|
|
470
|
+
values,
|
|
471
|
+
seen: frontier,
|
|
472
|
+
at
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
touch(sessionId);
|
|
476
|
+
};
|
|
477
|
+
const queuePresenceSend = (values, at) => {
|
|
478
|
+
if (presenceTimer !== void 0) {
|
|
479
|
+
presenceBuffer = {
|
|
480
|
+
...presenceBuffer,
|
|
481
|
+
...values
|
|
482
|
+
};
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
const wait = presenceLastSentAt + PRESENCE_TIMINGS.sendIntervalMs - Date.now();
|
|
486
|
+
if (wait <= 0) {
|
|
487
|
+
sendPresence(values, at ?? nextPresenceAt());
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
presenceBuffer = {
|
|
491
|
+
...presenceBuffer,
|
|
492
|
+
...values
|
|
493
|
+
};
|
|
494
|
+
presenceTimer = setTimeout(() => {
|
|
495
|
+
presenceTimer = void 0;
|
|
496
|
+
const buffered = presenceBuffer;
|
|
497
|
+
presenceBuffer = null;
|
|
498
|
+
if (buffered) sendPresence(buffered, nextPresenceAt());
|
|
499
|
+
}, wait);
|
|
500
|
+
presenceTimer.unref?.();
|
|
501
|
+
};
|
|
502
|
+
const setPresence = (values) => {
|
|
503
|
+
if (participant === void 0) throw new TypeError("setPresence requires a participant — pass one in the session options (the SessionProvider participant prop)");
|
|
504
|
+
const validated = nullProtoRecord();
|
|
505
|
+
for (const [field, value] of Object.entries(values)) {
|
|
506
|
+
if (value === void 0) continue;
|
|
507
|
+
const schema = Object.hasOwn(presenceDefs, field) ? presenceDefs[field] : void 0;
|
|
508
|
+
if (!schema) throw new A2Error("UNKNOWN_PRESENCE_FIELD", `no presence field '${field}' in the reducer's vocabulary`);
|
|
509
|
+
if (value === null) {
|
|
510
|
+
validated[field] = null;
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
const result = validateSync(schema, value, `presence field '${field}'`);
|
|
514
|
+
if (result.issues) throw new A2Error("INVALID_PAYLOAD", `invalid value for presence field '${field}'`, { details: result.issues });
|
|
515
|
+
validated[field] = result.value;
|
|
516
|
+
}
|
|
517
|
+
if (Object.keys(validated).length === 0) return;
|
|
518
|
+
const at = nextPresenceAt();
|
|
519
|
+
echoPresence(participant, validated, at);
|
|
520
|
+
if (status !== "live") presenceResend = {
|
|
521
|
+
...presenceResend,
|
|
522
|
+
...validated
|
|
523
|
+
};
|
|
524
|
+
queuePresenceSend(validated, at);
|
|
525
|
+
touch(sessionId);
|
|
526
|
+
};
|
|
527
|
+
/** Pushes awaiting stream confirmation — resolved by `ingest` the
|
|
528
|
+
* moment the frontier passes their batch. */
|
|
529
|
+
let confirmWatchers = [];
|
|
530
|
+
/** The single ingest point: every server-confirmed event, in log
|
|
531
|
+
* order, from the stream. */
|
|
532
|
+
const ingest = (event) => {
|
|
533
|
+
if (event.index <= frontier) return;
|
|
534
|
+
frontier = event.index;
|
|
535
|
+
serverEvents.push(event);
|
|
536
|
+
foldedState = reducer.fold(foldedState, event);
|
|
537
|
+
pending = pending.filter((p) => p.id !== event.id);
|
|
538
|
+
if (confirmWatchers.some((w) => w.index <= frontier)) {
|
|
539
|
+
const due = confirmWatchers.filter((w) => w.index <= frontier);
|
|
540
|
+
confirmWatchers = confirmWatchers.filter((w) => w.index > frontier);
|
|
541
|
+
for (const watcher of due) watcher.resolve();
|
|
542
|
+
}
|
|
543
|
+
notify();
|
|
544
|
+
touch(sessionId);
|
|
545
|
+
};
|
|
546
|
+
const validated = (events) => events.map((event) => {
|
|
547
|
+
const schema = Object.hasOwn(reducer.events, event.type) ? reducer.events[event.type] : void 0;
|
|
548
|
+
if (!schema) throw new A2Error("UNKNOWN_EVENT_TYPE", `no event type '${String(event.type)}' in the reducer's vocabulary`);
|
|
549
|
+
const result = validateSync(schema, event.payload, `event '${String(event.type)}'`);
|
|
550
|
+
if (result.issues) throw new A2Error("INVALID_PAYLOAD", `invalid payload for event '${String(event.type)}'`, { details: result.issues });
|
|
551
|
+
return {
|
|
552
|
+
id: event.id ?? crypto.randomUUID(),
|
|
553
|
+
type: event.type,
|
|
554
|
+
payload: result.value
|
|
555
|
+
};
|
|
556
|
+
});
|
|
557
|
+
const post = async (body) => {
|
|
558
|
+
let lastPushError = new A2Error("STORE_UNAVAILABLE", "push failed");
|
|
559
|
+
for (let attempt = 1; attempt <= PUSH_ATTEMPTS; attempt += 1) {
|
|
560
|
+
try {
|
|
561
|
+
return (await transport.push(body)).map((row) => eventFromWire(row));
|
|
562
|
+
} catch (err) {
|
|
563
|
+
lastPushError = err instanceof A2Error ? err : new A2Error("STORE_UNAVAILABLE", "push request failed", { cause: err });
|
|
564
|
+
}
|
|
565
|
+
if (lastPushError.code !== "STORE_UNAVAILABLE") throw lastPushError;
|
|
566
|
+
if (attempt < PUSH_ATTEMPTS) {
|
|
567
|
+
const sleepMs = 250 * attempt;
|
|
568
|
+
if (transport.awaitReady) await transport.awaitReady(sessionId, sleepMs + STREAM_TIMINGS.reconnectBaseMs * attempt);
|
|
569
|
+
else await new Promise((resolve) => setTimeout(resolve, sleepMs));
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
throw lastPushError;
|
|
573
|
+
};
|
|
574
|
+
/**
|
|
575
|
+
* Decorate the ack promise into a PushResult. `confirmed` is a
|
|
576
|
+
* lazy getter — materialized on first access, so callers that
|
|
577
|
+
* ignore it can't leak an unhandled rejection.
|
|
578
|
+
*/
|
|
579
|
+
const withConfirmed = (ack) => {
|
|
580
|
+
let confirmed;
|
|
581
|
+
return Object.defineProperty(ack, "confirmed", { get() {
|
|
582
|
+
confirmed ??= ack.then((acked) => new Promise((resolve) => {
|
|
583
|
+
const last = acked.at(-1)?.index ?? 0;
|
|
584
|
+
if (frontier >= last) {
|
|
585
|
+
resolve(acked);
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
confirmWatchers.push({
|
|
589
|
+
index: last,
|
|
590
|
+
resolve: () => resolve(acked)
|
|
591
|
+
});
|
|
592
|
+
}));
|
|
593
|
+
return confirmed;
|
|
594
|
+
} });
|
|
595
|
+
};
|
|
596
|
+
const push = (...events) => {
|
|
597
|
+
touch(sessionId);
|
|
598
|
+
return withConfirmed((async () => {
|
|
599
|
+
if (events.length === 0) throw new TypeError("push requires at least one event");
|
|
600
|
+
const entries = validated(events).map((e) => ({
|
|
601
|
+
id: e.id,
|
|
602
|
+
type: e.type,
|
|
603
|
+
payload: e.payload,
|
|
604
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
605
|
+
}));
|
|
606
|
+
const waitForPriorPush = pushWireTail;
|
|
607
|
+
let releasePush;
|
|
608
|
+
pushWireTail = new Promise((resolve) => {
|
|
609
|
+
releasePush = resolve;
|
|
610
|
+
});
|
|
611
|
+
pending.push(...entries);
|
|
612
|
+
inFlightPushes += 1;
|
|
613
|
+
try {
|
|
614
|
+
notify();
|
|
615
|
+
await waitForPriorPush;
|
|
616
|
+
const acked = await post({
|
|
617
|
+
sessionId,
|
|
618
|
+
events: entries.map(({ id, type, payload }) => ({
|
|
619
|
+
id,
|
|
620
|
+
type,
|
|
621
|
+
payload
|
|
622
|
+
}))
|
|
623
|
+
});
|
|
624
|
+
for (const event of acked) {
|
|
625
|
+
const entry = pending.find((p) => p.id === event.id);
|
|
626
|
+
if (entry) entry.acked = event;
|
|
627
|
+
}
|
|
628
|
+
notify();
|
|
629
|
+
return acked;
|
|
630
|
+
} catch (err) {
|
|
631
|
+
const ids = new Set(entries.map((e) => e.id));
|
|
632
|
+
pending = pending.filter((p) => !ids.has(p.id));
|
|
633
|
+
notify();
|
|
634
|
+
throw err;
|
|
635
|
+
} finally {
|
|
636
|
+
releasePush();
|
|
637
|
+
inFlightPushes -= 1;
|
|
638
|
+
if (inFlightPushes === 0 && deferredHydration) {
|
|
639
|
+
const next = deferredHydration;
|
|
640
|
+
deferredHydration = void 0;
|
|
641
|
+
runtime.hydrate(next);
|
|
642
|
+
}
|
|
643
|
+
touch(sessionId);
|
|
644
|
+
}
|
|
645
|
+
})());
|
|
646
|
+
};
|
|
647
|
+
let generation = 0;
|
|
648
|
+
let active = false;
|
|
649
|
+
let abort = null;
|
|
650
|
+
const runStream = async (run) => {
|
|
651
|
+
let backoff = STREAM_TIMINGS.reconnectBaseMs;
|
|
652
|
+
while (generation === run) {
|
|
653
|
+
const controller = new AbortController();
|
|
654
|
+
abort = controller;
|
|
655
|
+
let stall;
|
|
656
|
+
let stalled = false;
|
|
657
|
+
const armStall = () => {
|
|
658
|
+
clearTimeout(stall);
|
|
659
|
+
stall = setTimeout(() => {
|
|
660
|
+
stalled = true;
|
|
661
|
+
controller.abort();
|
|
662
|
+
}, STREAM_TIMINGS.stallTimeoutMs);
|
|
663
|
+
stall.unref?.();
|
|
664
|
+
};
|
|
665
|
+
let wasLive = false;
|
|
666
|
+
try {
|
|
667
|
+
const frames = transport.connect({
|
|
668
|
+
sessionId,
|
|
669
|
+
startAfter: frontier,
|
|
670
|
+
signal: controller.signal
|
|
671
|
+
});
|
|
672
|
+
for await (const frame of frames) {
|
|
673
|
+
if (generation !== run) break;
|
|
674
|
+
armStall();
|
|
675
|
+
if (!wasLive) {
|
|
676
|
+
backoff = STREAM_TIMINGS.reconnectBaseMs;
|
|
677
|
+
wasLive = true;
|
|
678
|
+
status = "live";
|
|
679
|
+
lastError = null;
|
|
680
|
+
notify();
|
|
681
|
+
if (presenceResend) {
|
|
682
|
+
const values = presenceResend;
|
|
683
|
+
presenceResend = null;
|
|
684
|
+
queuePresenceSend(values);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
if (frame.kind === "event") ingest(eventFromWire(frame.event));
|
|
688
|
+
else if (frame.kind === "presence") applyPresencePatch(presencePatchFromWire(frame.patch));
|
|
689
|
+
else if (frame.kind === "presence-snapshot") applyPresenceSnapshot(presenceSnapshotFromWire(frame.snapshot).snapshot);
|
|
690
|
+
}
|
|
691
|
+
if (generation === run) lastError = null;
|
|
692
|
+
} catch (err) {
|
|
693
|
+
if (generation === run) lastError = stalled ? /* @__PURE__ */ new Error(`stream stalled: no data for ${STREAM_TIMINGS.stallTimeoutMs}ms`) : err instanceof Error ? err : new Error(String(err));
|
|
694
|
+
} finally {
|
|
695
|
+
clearTimeout(stall);
|
|
696
|
+
}
|
|
697
|
+
if (generation !== run) break;
|
|
698
|
+
if (wasLive) reconnects += 1;
|
|
699
|
+
status = "connecting";
|
|
700
|
+
notify();
|
|
701
|
+
await new Promise((resolve) => {
|
|
702
|
+
let settled = false;
|
|
703
|
+
const finish = () => {
|
|
704
|
+
if (settled) return;
|
|
705
|
+
settled = true;
|
|
706
|
+
clearTimeout(timer);
|
|
707
|
+
resolve();
|
|
708
|
+
};
|
|
709
|
+
const timer = setTimeout(finish, backoff);
|
|
710
|
+
timer.unref?.();
|
|
711
|
+
abort?.signal.addEventListener("abort", finish);
|
|
712
|
+
});
|
|
713
|
+
backoff = Math.min(backoff * 2, STREAM_TIMINGS.reconnectMaxMs);
|
|
714
|
+
}
|
|
715
|
+
};
|
|
716
|
+
const runtime = {
|
|
717
|
+
sessionId,
|
|
718
|
+
...declaresPresence ? { setPresence } : {},
|
|
719
|
+
subscribe(listener) {
|
|
720
|
+
touch(sessionId);
|
|
721
|
+
listeners.add(listener);
|
|
722
|
+
return () => {
|
|
723
|
+
listeners.delete(listener);
|
|
724
|
+
touch(sessionId);
|
|
725
|
+
};
|
|
726
|
+
},
|
|
727
|
+
getSnapshot() {
|
|
728
|
+
snapshot ??= buildSnapshot();
|
|
729
|
+
return snapshot;
|
|
730
|
+
},
|
|
731
|
+
push,
|
|
732
|
+
connect() {
|
|
733
|
+
touch(sessionId);
|
|
734
|
+
if (active) return;
|
|
735
|
+
active = true;
|
|
736
|
+
status = "connecting";
|
|
737
|
+
notify();
|
|
738
|
+
runStream(generation);
|
|
739
|
+
},
|
|
740
|
+
close() {
|
|
741
|
+
touch(sessionId);
|
|
742
|
+
if (!active) return;
|
|
743
|
+
active = false;
|
|
744
|
+
generation += 1;
|
|
745
|
+
abort?.abort();
|
|
746
|
+
abort = null;
|
|
747
|
+
clearTimeout(presenceTimer);
|
|
748
|
+
presenceTimer = void 0;
|
|
749
|
+
presenceBuffer = null;
|
|
750
|
+
status = "closed";
|
|
751
|
+
notify();
|
|
752
|
+
},
|
|
753
|
+
hydrate(next) {
|
|
754
|
+
touch(sessionId);
|
|
755
|
+
if (!next) return;
|
|
756
|
+
participant ??= next.participant;
|
|
757
|
+
const nextIndex = next.initialIndex ?? 0;
|
|
758
|
+
if (nextIndex > frontier && inFlightPushes > 0) {
|
|
759
|
+
if (!deferredHydration || nextIndex > (deferredHydration.initialIndex ?? 0)) deferredHydration = next;
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
const historyChanged = mergeServerEvents(next.initialEvents, Math.min(nextIndex, frontier));
|
|
763
|
+
if (next.initialState === void 0 || nextIndex <= frontier) {
|
|
764
|
+
if (historyChanged) notifyHydrated();
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
frontier = nextIndex;
|
|
768
|
+
foldedState = next.initialState;
|
|
769
|
+
mergeServerEvents(next.initialEvents, frontier);
|
|
770
|
+
pending = pending.filter((entry) => !entry.acked || entry.acked.index > frontier);
|
|
771
|
+
if (confirmWatchers.some((watcher) => watcher.index <= frontier)) {
|
|
772
|
+
const due = confirmWatchers.filter((watcher) => watcher.index <= frontier);
|
|
773
|
+
confirmWatchers = confirmWatchers.filter((watcher) => watcher.index > frontier);
|
|
774
|
+
for (const watcher of due) watcher.resolve();
|
|
775
|
+
}
|
|
776
|
+
notifyHydrated();
|
|
777
|
+
},
|
|
778
|
+
canEvict() {
|
|
779
|
+
return listeners.size === 0 && !active && inFlightPushes === 0 && confirmWatchers.length === 0 && presenceTimer === void 0;
|
|
780
|
+
}
|
|
781
|
+
};
|
|
782
|
+
return runtime;
|
|
783
|
+
};
|
|
784
|
+
return { session(sessionId, sessionOptions) {
|
|
785
|
+
const existing = sessions.get(sessionId);
|
|
786
|
+
if (existing) {
|
|
787
|
+
existing.runtime.hydrate(sessionOptions);
|
|
788
|
+
touch(sessionId);
|
|
789
|
+
return existing.runtime;
|
|
790
|
+
}
|
|
791
|
+
const runtime = makeSession(sessionId, sessionOptions);
|
|
792
|
+
sessions.set(sessionId, { runtime });
|
|
793
|
+
touch(sessionId);
|
|
794
|
+
return runtime;
|
|
795
|
+
} };
|
|
796
|
+
}
|
|
797
|
+
//#endregion
|
|
798
|
+
export { createClient as t };
|