@nichoth/simple-sync 0.0.0-stage → 0.0.5

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.
Files changed (67) hide show
  1. package/README.md +469 -2
  2. package/dist/client/db.d.ts +67 -0
  3. package/dist/client/db.d.ts.map +1 -0
  4. package/dist/client/db.js +1 -0
  5. package/dist/client/db.js.map +7 -0
  6. package/dist/client/idb.d.ts +12 -0
  7. package/dist/client/idb.d.ts.map +1 -0
  8. package/dist/client/idb.js +72 -0
  9. package/dist/client/idb.js.map +7 -0
  10. package/dist/client/index.d.ts +143 -0
  11. package/dist/client/index.d.ts.map +1 -0
  12. package/dist/client/index.js +362 -0
  13. package/dist/client/index.js.map +7 -0
  14. package/dist/client/sqlite-opfs-rpc.d.ts +21 -0
  15. package/dist/client/sqlite-opfs-rpc.d.ts.map +1 -0
  16. package/dist/client/sqlite-opfs-rpc.js +55 -0
  17. package/dist/client/sqlite-opfs-rpc.js.map +7 -0
  18. package/dist/client/sqlite-opfs.d.ts +15 -0
  19. package/dist/client/sqlite-opfs.d.ts.map +1 -0
  20. package/dist/client/sqlite-opfs.js +31 -0
  21. package/dist/client/sqlite-opfs.js.map +7 -0
  22. package/dist/client/sqlite-opfs.worker.d.ts +6 -0
  23. package/dist/client/sqlite-opfs.worker.d.ts.map +1 -0
  24. package/dist/client/sqlite-opfs.worker.js +47 -0
  25. package/dist/client/sqlite-opfs.worker.js.map +7 -0
  26. package/dist/client/sqlite.d.ts +25 -0
  27. package/dist/client/sqlite.d.ts.map +1 -0
  28. package/dist/client/sqlite.js +117 -0
  29. package/dist/client/sqlite.js.map +7 -0
  30. package/dist/client.d.ts +6 -0
  31. package/dist/client.d.ts.map +1 -0
  32. package/dist/client.js +11 -0
  33. package/dist/client.js.map +7 -0
  34. package/dist/hash.d.ts +23 -0
  35. package/dist/hash.d.ts.map +1 -0
  36. package/dist/hash.js +29 -0
  37. package/dist/hash.js.map +7 -0
  38. package/dist/index.d.ts +10 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +18 -0
  41. package/dist/index.js.map +7 -0
  42. package/dist/meta.json +511 -0
  43. package/dist/op.d.ts +41 -0
  44. package/dist/op.d.ts.map +1 -0
  45. package/dist/op.js +46 -0
  46. package/dist/op.js.map +7 -0
  47. package/dist/reduce.d.ts +55 -0
  48. package/dist/reduce.d.ts.map +1 -0
  49. package/dist/reduce.js +173 -0
  50. package/dist/reduce.js.map +7 -0
  51. package/dist/server/errors.d.ts +16 -0
  52. package/dist/server/errors.d.ts.map +1 -0
  53. package/dist/server/errors.js +14 -0
  54. package/dist/server/errors.js.map +7 -0
  55. package/dist/server/index.d.ts +75 -0
  56. package/dist/server/index.d.ts.map +1 -0
  57. package/dist/server/index.js +324 -0
  58. package/dist/server/index.js.map +7 -0
  59. package/dist/server.d.ts +2 -0
  60. package/dist/server.d.ts.map +1 -0
  61. package/dist/server.js +5 -0
  62. package/dist/server.js.map +7 -0
  63. package/dist/types.d.ts +105 -0
  64. package/dist/types.d.ts.map +1 -0
  65. package/dist/types.js +1 -0
  66. package/dist/types.js.map +7 -0
  67. package/package.json +118 -4
@@ -0,0 +1,143 @@
1
+ import type { Op, Envelope, ReducedState } from '../types.js';
2
+ import type { DraftOp } from '../op.js';
3
+ import type { ClientDB } from './db.js';
4
+ /** Where a state-change event originated. */
5
+ export type StateOrigin = 'cache' | 'local' | 'server';
6
+ /**
7
+ * The subset of `Envelope` kinds a server ever sends to a client.
8
+ * The `message` event only carries these.
9
+ */
10
+ export type ServerEnvelope = Extract<Envelope, {
11
+ kind: 'ready' | 'state' | 'state-deleted';
12
+ }>;
13
+ export type SyncEvents = {
14
+ /**
15
+ * Fires when a single state changes (created or patched). `origin`
16
+ * says where it came from: the IDB cache (hydrate/bootstrap), this
17
+ * device's optimistic write, or the server's authoritative message.
18
+ */
19
+ state: {
20
+ state: ReducedState;
21
+ origin: StateOrigin;
22
+ };
23
+ /**
24
+ * Fires when a state is removed (whole-state delete). `origin` is
25
+ * 'local' (this device's delete) or 'server' (inbound); never
26
+ * 'cache' (bootstrap only emits `state`, never deletions).
27
+ */
28
+ 'state-deleted': {
29
+ id: string;
30
+ origin: StateOrigin;
31
+ };
32
+ /**
33
+ * Fires for every valid inbound server envelope, raw and
34
+ * unprocessed. Every emission of this event is server-originated.
35
+ */
36
+ message: ServerEnvelope;
37
+ /** Fires when the WS opens (true) or closes (false). */
38
+ connected: boolean;
39
+ /**
40
+ * Ops written this session not yet pushed to the socket; returns
41
+ * to 0 after a successful handshake/resend.
42
+ */
43
+ pending: number;
44
+ };
45
+ export interface SyncClientOptions {
46
+ /** Full WS URL, e.g. `ws://localhost:8888/ws/sync/abc`. */
47
+ url: string;
48
+ /** This device's id (derived from EccKeys.getDeviceName()). */
49
+ deviceId: string;
50
+ /** Local persistence. */
51
+ db: ClientDB;
52
+ /**
53
+ * Optional reducer for optimistic local projection. If provided,
54
+ * writes are immediately projected onto the local `states` getter
55
+ * so the UI can render before the server's broadcast arrives.
56
+ *
57
+ * A `null` return signals whole-state delete (the caller's state
58
+ * is removed from the local map).
59
+ */
60
+ reduce?: (state: ReducedState | null, op: Op) => Promise<ReducedState | null>;
61
+ /** Override reconnect backoff. Default: 250ms -> 5s ceiling. */
62
+ backoff?: {
63
+ initialMs: number;
64
+ maxMs: number;
65
+ };
66
+ /**
67
+ * Decouple "online" from "synced". When `true`, `connect()`
68
+ * opens the socket (emitting `connected:true`) but does NOT
69
+ * auto-send `hello`, so no ops are exchanged until the caller
70
+ * invokes `sync()`. Local writes made while online-but-not-synced
71
+ * queue as pending and flush on the next `sync()`.
72
+ *
73
+ * Default `false`: opening the socket immediately sends `hello`
74
+ * (connect implies sync), the historical behavior.
75
+ */
76
+ manualSync?: boolean;
77
+ }
78
+ export declare class SyncClient {
79
+ private readonly opts;
80
+ private readonly emitter;
81
+ private _states;
82
+ private _connected;
83
+ private _pendingOps;
84
+ private _ws;
85
+ private _backoffMs;
86
+ private _reconnectTimer;
87
+ private _bootstrapPromise;
88
+ private _helloSent;
89
+ private _hasConnectedOnce;
90
+ private _syncIntent;
91
+ private _writeChain;
92
+ constructor(opts: SyncClientOptions);
93
+ get states(): ReadonlyMap<string, ReducedState>;
94
+ getState(id: string): ReducedState | undefined;
95
+ get connected(): boolean;
96
+ get pendingOps(): number;
97
+ get deviceId(): string;
98
+ /**
99
+ * @internal Test-only accessor. Returns the underlying ClientDB
100
+ * so test cleanup can explicitly close it before
101
+ * `indexedDB.deleteDatabase()`. Production code must not use.
102
+ */
103
+ get _dbForTest(): ClientDB;
104
+ on<K extends keyof SyncEvents>(type: K, h: (p: SyncEvents[K]) => void): void;
105
+ off<K extends keyof SyncEvents>(type: K, h: (p: SyncEvents[K]) => void): void;
106
+ private _bootstrap;
107
+ private _doBootstrap;
108
+ write(draft: DraftOp): Promise<Op>;
109
+ private _writeOne;
110
+ private _send;
111
+ /**
112
+ * Rehydrate state from IDB without opening the WebSocket and
113
+ * without writing. Idempotent: a second call is a no-op.
114
+ *
115
+ * The notes app calls this from ensureClient() so a reload
116
+ * with cached state shows the notes immediately without
117
+ * requiring a user-initiated write.
118
+ */
119
+ hydrate(): Promise<void>;
120
+ connect(): Promise<void>;
121
+ private _openSocketAwaitable;
122
+ private _awaitFirstEvent;
123
+ private _installHandlers;
124
+ private _setConnected;
125
+ private _scheduleReconnect;
126
+ disconnect(): void;
127
+ /**
128
+ * Run the sync exchange on demand: send `hello` so the server
129
+ * replies with `ready` (flushing any queued ops) and streams back
130
+ * the states this client is missing. Re-callable — each call
131
+ * re-runs the handshake.
132
+ *
133
+ * Only meaningful while the socket is open; a no-op otherwise.
134
+ * Pairs with the `manualSync` option, where opening the socket
135
+ * ("go online") does not auto-sync and the caller decides when to
136
+ * exchange ops. Under the default (auto-sync) the first sync
137
+ * already ran on connect; calling this just re-syncs.
138
+ */
139
+ sync(): Promise<void>;
140
+ private _sendHello;
141
+ private _onMessage;
142
+ }
143
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 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;YAIJ,YAAY;IAoCpB,KAAK,CAAE,KAAK,EAAC,OAAO,GAAE,OAAO,CAAC,EAAE,CAAC;YASzB,SAAS;IAoEvB,OAAO,CAAC,KAAK;IAKb;;;;;;;OAOG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAIxB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAoB9B,OAAO,CAAC,oBAAoB;IAO5B,OAAO,CAAC,gBAAgB;IAyBxB,OAAO,CAAC,gBAAgB;IAwCxB,OAAO,CAAC,aAAa;IAMrB,OAAO,CAAC,kBAAkB;IAsB1B,UAAU,IAAI,IAAI;IAelB;;;;;;;;;;;OAWG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;YAKb,UAAU;YAiBV,UAAU;CAmF3B"}
@@ -0,0 +1,362 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+ import mitt from "mitt";
4
+ import monotonicTimestamp from "monotonic-timestamp";
5
+ import { mergeReducedStates, parseStateId } from "../reduce.js";
6
+ class SyncClient {
7
+ static {
8
+ __name(this, "SyncClient");
9
+ }
10
+ opts;
11
+ emitter = mitt();
12
+ _states = /* @__PURE__ */ new Map();
13
+ _connected = false;
14
+ _pendingOps = 0;
15
+ _ws = null;
16
+ _backoffMs = 0;
17
+ _reconnectTimer = null;
18
+ _bootstrapPromise = null;
19
+ _helloSent = false;
20
+ _hasConnectedOnce = false;
21
+ _syncIntent = false;
22
+ _writeChain = Promise.resolve();
23
+ constructor(opts) {
24
+ this.opts = opts;
25
+ }
26
+ get states() {
27
+ return this._states;
28
+ }
29
+ getState(id) {
30
+ return this._states.get(id);
31
+ }
32
+ get connected() {
33
+ return this._connected;
34
+ }
35
+ get pendingOps() {
36
+ return this._pendingOps;
37
+ }
38
+ get deviceId() {
39
+ return this.opts.deviceId;
40
+ }
41
+ /**
42
+ * @internal Test-only accessor. Returns the underlying ClientDB
43
+ * so test cleanup can explicitly close it before
44
+ * `indexedDB.deleteDatabase()`. Production code must not use.
45
+ */
46
+ get _dbForTest() {
47
+ return this.opts.db;
48
+ }
49
+ on(type, h) {
50
+ this.emitter.on(type, h);
51
+ }
52
+ off(type, h) {
53
+ this.emitter.off(type, h);
54
+ }
55
+ _bootstrap() {
56
+ return this._bootstrapPromise ??= this._doBootstrap();
57
+ }
58
+ async _doBootstrap() {
59
+ const all = await this.opts.db.getAllStates();
60
+ for (const s of all) {
61
+ if (typeof s?.id !== "string" || typeof s?.hash !== "string" || s.id === "" || s.hash === "") {
62
+ continue;
63
+ }
64
+ if (parseStateId(s.id) === null) {
65
+ continue;
66
+ }
67
+ this._states.set(s.id, s);
68
+ }
69
+ for (const s of this._states.values()) {
70
+ this.emitter.emit("state", { state: s, origin: "cache" });
71
+ }
72
+ this._pendingOps = 0;
73
+ this.emitter.emit("pending", 0);
74
+ }
75
+ async write(draft) {
76
+ await this._bootstrap();
77
+ const run = /* @__PURE__ */ __name(() => this._writeOne(draft), "run");
78
+ const result = this._writeChain.then(run, run);
79
+ this._writeChain = result.then(() => {
80
+ }, () => {
81
+ });
82
+ return result;
83
+ }
84
+ async _writeOne(draft) {
85
+ const lastSeq = await this.opts.db.last();
86
+ const seq = lastSeq + 1;
87
+ const op = {
88
+ ...draft,
89
+ seq,
90
+ id: `op:${this.opts.deviceId}:${seq}`,
91
+ ts: monotonicTimestamp()
92
+ };
93
+ await this.opts.db.write(op);
94
+ if (this.opts.reduce) {
95
+ let priorState = null;
96
+ if (op.type === "create") {
97
+ priorState = null;
98
+ } else if (typeof op.target === "string") {
99
+ priorState = this._states.get(op.target) ?? null;
100
+ }
101
+ const next = await this.opts.reduce(priorState, op);
102
+ if (next === null) {
103
+ if (op.type === "delete" && typeof op.target === "string") {
104
+ this._states.delete(op.target);
105
+ try {
106
+ await this.opts.db.deleteState(op.target);
107
+ } catch (err) {
108
+ console.warn(
109
+ "failed to delete state in IDB:",
110
+ err
111
+ );
112
+ }
113
+ this.emitter.emit("state-deleted", {
114
+ id: op.target,
115
+ origin: "local"
116
+ });
117
+ }
118
+ } else {
119
+ this._states.set(next.id, next);
120
+ try {
121
+ await this.opts.db.putState(next);
122
+ } catch (err) {
123
+ console.warn(
124
+ "failed to persist state to IDB:",
125
+ err
126
+ );
127
+ }
128
+ this.emitter.emit("state", { state: next, origin: "local" });
129
+ }
130
+ }
131
+ const canSend = this._connected && this._ws?.readyState === WebSocket.OPEN && this._helloSent;
132
+ if (canSend) {
133
+ this._send({ kind: "write", ops: [op] });
134
+ } else {
135
+ this._pendingOps += 1;
136
+ this.emitter.emit("pending", this._pendingOps);
137
+ }
138
+ return op;
139
+ }
140
+ _send(env) {
141
+ if (!this._ws || this._ws.readyState !== WebSocket.OPEN) return;
142
+ this._ws.send(JSON.stringify(env));
143
+ }
144
+ /**
145
+ * Rehydrate state from IDB without opening the WebSocket and
146
+ * without writing. Idempotent: a second call is a no-op.
147
+ *
148
+ * The notes app calls this from ensureClient() so a reload
149
+ * with cached state shows the notes immediately without
150
+ * requiring a user-initiated write.
151
+ */
152
+ async hydrate() {
153
+ await this._bootstrap();
154
+ }
155
+ async connect() {
156
+ await this._bootstrap();
157
+ if (this._ws && this._ws.readyState === WebSocket.OPEN) {
158
+ return;
159
+ }
160
+ if (this._ws && this._ws.readyState === WebSocket.CONNECTING) {
161
+ return this._awaitFirstEvent(this._ws);
162
+ }
163
+ return this._openSocketAwaitable();
164
+ }
165
+ _openSocketAwaitable() {
166
+ const ws = new WebSocket(this.opts.url);
167
+ this._ws = ws;
168
+ this._installHandlers(ws);
169
+ return this._awaitFirstEvent(ws);
170
+ }
171
+ _awaitFirstEvent(ws) {
172
+ return new Promise((resolve, reject) => {
173
+ const cleanup = /* @__PURE__ */ __name(() => {
174
+ ws.removeEventListener("open", onOpen);
175
+ ws.removeEventListener("error", onError);
176
+ ws.removeEventListener("close", onClose);
177
+ }, "cleanup");
178
+ const onOpen = /* @__PURE__ */ __name(() => {
179
+ cleanup();
180
+ resolve();
181
+ }, "onOpen");
182
+ const onError = /* @__PURE__ */ __name(() => {
183
+ cleanup();
184
+ reject(new Error("WebSocket connect failed: error"));
185
+ }, "onError");
186
+ const onClose = /* @__PURE__ */ __name(() => {
187
+ cleanup();
188
+ reject(new Error("WebSocket connect failed: close"));
189
+ }, "onClose");
190
+ ws.addEventListener("open", onOpen, { once: true });
191
+ ws.addEventListener("error", onError, { once: true });
192
+ ws.addEventListener("close", onClose, { once: true });
193
+ });
194
+ }
195
+ _installHandlers(ws) {
196
+ ws.onopen = () => {
197
+ this._setConnected(true);
198
+ this._hasConnectedOnce = true;
199
+ this._backoffMs = 0;
200
+ if (!this.opts.manualSync || this._syncIntent) {
201
+ this._sendHello().catch(() => {
202
+ });
203
+ }
204
+ };
205
+ ws.onmessage = (evt) => {
206
+ this._onMessage(evt).catch(() => {
207
+ });
208
+ };
209
+ ws.onclose = () => {
210
+ this._setConnected(false);
211
+ this._helloSent = false;
212
+ this._ws = null;
213
+ if (this._hasConnectedOnce) {
214
+ this._scheduleReconnect();
215
+ }
216
+ };
217
+ ws.onerror = () => {
218
+ };
219
+ }
220
+ _setConnected(v) {
221
+ if (this._connected === v) return;
222
+ this._connected = v;
223
+ this.emitter.emit("connected", v);
224
+ }
225
+ _scheduleReconnect() {
226
+ if (this._reconnectTimer) return;
227
+ const initial = this.opts.backoff?.initialMs ?? 250;
228
+ const max = this.opts.backoff?.maxMs ?? 5e3;
229
+ if (this._backoffMs === 0) {
230
+ this._backoffMs = initial;
231
+ } else {
232
+ this._backoffMs = Math.min(this._backoffMs * 2, max);
233
+ }
234
+ this._reconnectTimer = setTimeout(() => {
235
+ this._reconnectTimer = null;
236
+ try {
237
+ const ws = new WebSocket(this.opts.url);
238
+ this._ws = ws;
239
+ this._installHandlers(ws);
240
+ } catch (err) {
241
+ console.warn("failed to open socket:", err);
242
+ this._scheduleReconnect();
243
+ }
244
+ }, this._backoffMs);
245
+ }
246
+ disconnect() {
247
+ if (this._reconnectTimer) {
248
+ clearTimeout(this._reconnectTimer);
249
+ this._reconnectTimer = null;
250
+ }
251
+ if (this._ws) {
252
+ this._ws.onclose = null;
253
+ this._ws.close();
254
+ this._ws = null;
255
+ }
256
+ this._setConnected(false);
257
+ this._helloSent = false;
258
+ this._hasConnectedOnce = false;
259
+ }
260
+ /**
261
+ * Run the sync exchange on demand: send `hello` so the server
262
+ * replies with `ready` (flushing any queued ops) and streams back
263
+ * the states this client is missing. Re-callable — each call
264
+ * re-runs the handshake.
265
+ *
266
+ * Only meaningful while the socket is open; a no-op otherwise.
267
+ * Pairs with the `manualSync` option, where opening the socket
268
+ * ("go online") does not auto-sync and the caller decides when to
269
+ * exchange ops. Under the default (auto-sync) the first sync
270
+ * already ran on connect; calling this just re-syncs.
271
+ */
272
+ async sync() {
273
+ if (!this._ws || this._ws.readyState !== WebSocket.OPEN) return;
274
+ await this._sendHello();
275
+ }
276
+ async _sendHello() {
277
+ const lastSeq = await this.opts.db.last();
278
+ const states = [];
279
+ for (const s of this._states.values()) {
280
+ states.push({ id: s.id, hash: s.hash });
281
+ }
282
+ const env = {
283
+ kind: "hello",
284
+ deviceId: this.opts.deviceId,
285
+ lastSeq,
286
+ ...states.length > 0 ? { states } : {}
287
+ };
288
+ this._send(env);
289
+ this._helloSent = true;
290
+ this._syncIntent = true;
291
+ }
292
+ async _onMessage(evt) {
293
+ let env;
294
+ try {
295
+ env = JSON.parse(String(evt.data));
296
+ } catch {
297
+ return;
298
+ }
299
+ if (!env || typeof env !== "object" || typeof env.kind !== "string") {
300
+ return;
301
+ }
302
+ this.emitter.emit("message", env);
303
+ if (env.kind === "ready") {
304
+ const requestFrom = env.requestFrom;
305
+ if (typeof requestFrom === "number") {
306
+ const ops = await this.opts.db.readFrom(requestFrom);
307
+ if (ops.length > 0) {
308
+ this._send({ kind: "write", ops });
309
+ }
310
+ this._pendingOps = 0;
311
+ this.emitter.emit("pending", 0);
312
+ } else {
313
+ this._pendingOps = 0;
314
+ this.emitter.emit("pending", 0);
315
+ }
316
+ return;
317
+ }
318
+ if (env.kind === "state") {
319
+ const next = env.state;
320
+ if (!next || typeof next.id !== "string" || typeof next.hash !== "string" || typeof next.__ts !== "object" || next.__ts === null || typeof next.value !== "object" || next.value === null) {
321
+ return;
322
+ }
323
+ const local = this._states.get(next.id) ?? null;
324
+ let merged;
325
+ try {
326
+ merged = await mergeReducedStates(local, next);
327
+ } catch (err) {
328
+ console.warn("failed to merge inbound state:", err);
329
+ merged = next;
330
+ }
331
+ this._states.set(merged.id, merged);
332
+ this.emitter.emit("state", { state: merged, origin: "server" });
333
+ try {
334
+ await this.opts.db.putState(merged);
335
+ } catch (err) {
336
+ console.warn(
337
+ "failed to persist state to IDB:",
338
+ err
339
+ );
340
+ }
341
+ return;
342
+ }
343
+ if (env.kind === "state-deleted") {
344
+ const id = env.id;
345
+ if (typeof id !== "string") return;
346
+ this._states.delete(id);
347
+ try {
348
+ await this.opts.db.deleteState(id);
349
+ } catch (err) {
350
+ console.warn(
351
+ "failed to delete state in IDB:",
352
+ err
353
+ );
354
+ }
355
+ this.emitter.emit("state-deleted", { id, origin: "server" });
356
+ }
357
+ }
358
+ }
359
+ export {
360
+ SyncClient
361
+ };
362
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/client/index.ts"],
4
+ "sourcesContent": ["import mitt, { type Emitter } from 'mitt'\nimport monotonicTimestamp from 'monotonic-timestamp'\nimport type { Op, Envelope, ReducedState, StateRef } from '../types.js'\nimport type { DraftOp } from '../op.js'\nimport type { ClientDB } from './db.js'\nimport { mergeReducedStates, parseStateId } from '../reduce.js'\n\n/** Where a state-change event originated. */\nexport type StateOrigin = 'cache' | 'local' | 'server'\n\n/**\n * The subset of `Envelope` kinds a server ever sends to a client.\n * The `message` event only carries these.\n */\nexport type ServerEnvelope =\n Extract<Envelope, { kind:'ready' | 'state' | 'state-deleted' }>\n\nexport type SyncEvents = {\n /**\n * Fires when a single state changes (created or patched). `origin`\n * says where it came from: the IDB cache (hydrate/bootstrap), this\n * device's optimistic write, or the server's authoritative message.\n */\n state:{ state:ReducedState, origin:StateOrigin }\n /**\n * Fires when a state is removed (whole-state delete). `origin` is\n * 'local' (this device's delete) or 'server' (inbound); never\n * 'cache' (bootstrap only emits `state`, never deletions).\n */\n 'state-deleted':{ id:string, origin:StateOrigin }\n /**\n * Fires for every valid inbound server envelope, raw and\n * unprocessed. Every emission of this event is server-originated.\n */\n message:ServerEnvelope\n /** Fires when the WS opens (true) or closes (false). */\n connected:boolean\n /**\n * Ops written this session not yet pushed to the socket; returns\n * to 0 after a successful handshake/resend.\n */\n pending:number\n}\n\nexport interface SyncClientOptions {\n /** Full WS URL, e.g. `ws://localhost:8888/ws/sync/abc`. */\n url:string\n /** This device's id (derived from EccKeys.getDeviceName()). */\n deviceId:string\n /** Local persistence. */\n db:ClientDB\n /**\n * Optional reducer for optimistic local projection. If provided,\n * writes are immediately projected onto the local `states` getter\n * so the UI can render before the server's broadcast arrives.\n *\n * A `null` return signals whole-state delete (the caller's state\n * is removed from the local map).\n */\n reduce?:(state:ReducedState | null, op:Op) =>\n Promise<ReducedState | null>\n /** Override reconnect backoff. Default: 250ms -> 5s ceiling. */\n backoff?:{ initialMs:number, maxMs:number }\n /**\n * Decouple \"online\" from \"synced\". When `true`, `connect()`\n * opens the socket (emitting `connected:true`) but does NOT\n * auto-send `hello`, so no ops are exchanged until the caller\n * invokes `sync()`. Local writes made while online-but-not-synced\n * queue as pending and flush on the next `sync()`.\n *\n * Default `false`: opening the socket immediately sends `hello`\n * (connect implies sync), the historical behavior.\n */\n manualSync?:boolean\n}\n\nexport class SyncClient {\n private readonly opts:SyncClientOptions\n private readonly emitter:Emitter<SyncEvents> = mitt<SyncEvents>()\n private _states:Map<string, ReducedState> = new Map()\n private _connected = false\n private _pendingOps = 0\n private _ws:WebSocket | null = null\n private _backoffMs = 0\n private _reconnectTimer:ReturnType<typeof setTimeout> | null = null\n private _bootstrapPromise:Promise<void> | null = null\n private _helloSent = false\n private _hasConnectedOnce = false\n private _syncIntent = false\n private _writeChain:Promise<unknown> = Promise.resolve()\n\n constructor (opts:SyncClientOptions) {\n this.opts = opts\n }\n\n get states ():ReadonlyMap<string, ReducedState> {\n return this._states\n }\n\n getState (id:string):ReducedState | undefined {\n return this._states.get(id)\n }\n\n get connected ():boolean { return this._connected }\n get pendingOps ():number { return this._pendingOps }\n get deviceId ():string { return this.opts.deviceId }\n\n /**\n * @internal Test-only accessor. Returns the underlying ClientDB\n * so test cleanup can explicitly close it before\n * `indexedDB.deleteDatabase()`. Production code must not use.\n */\n get _dbForTest ():ClientDB { return this.opts.db }\n\n on<K extends keyof SyncEvents> (\n type:K,\n h:(p:SyncEvents[K]) => void\n ):void {\n this.emitter.on(type, h)\n }\n\n off<K extends keyof SyncEvents> (\n type:K,\n h:(p:SyncEvents[K]) => void\n ):void {\n this.emitter.off(type, h)\n }\n\n private _bootstrap ():Promise<void> {\n return (this._bootstrapPromise ??= this._doBootstrap())\n }\n\n private async _doBootstrap ():Promise<void> {\n // Load persisted states from IDB. Skip malformed and\n // stale provisional entries.\n const all = await this.opts.db.getAllStates()\n for (const s of all) {\n // Validate shape\n if (\n typeof s?.id !== 'string' ||\n typeof s?.hash !== 'string' ||\n s.id === '' ||\n s.hash === ''\n ) {\n continue\n }\n\n // Validate id format. The trailing ts segment may be\n // fractional: monotonicTimestamp() returns e.g. 2000.001\n // for sub-millisecond calls, so two states created in the\n // same millisecond carry fractional-ts ids. Rejecting them\n // here silently drops valid states on reload.\n if (parseStateId(s.id) === null) {\n continue\n }\n\n this._states.set(s.id, s)\n }\n\n // Emit one state event per id in the cached states\n for (const s of this._states.values()) {\n this.emitter.emit('state', { state: s, origin: 'cache' })\n }\n\n this._pendingOps = 0\n this.emitter.emit('pending', 0)\n }\n\n async write (draft:DraftOp):Promise<Op> {\n await this._bootstrap()\n const run = ():Promise<Op> => this._writeOne(draft)\n const result = this._writeChain.then(run, run)\n // Keep the chain alive even if this write rejects.\n this._writeChain = result.then(() => {}, () => {})\n return result\n }\n\n private async _writeOne (draft:DraftOp):Promise<Op> {\n const lastSeq = await this.opts.db.last()\n const seq = lastSeq + 1\n const op:Op = {\n ...draft,\n seq,\n id: `op:${this.opts.deviceId}:${seq}`,\n ts: monotonicTimestamp()\n }\n\n await this.opts.db.write(op)\n\n if (this.opts.reduce) {\n let priorState:ReducedState | null = null\n if (op.type === 'create') {\n priorState = null\n } else if (typeof op.target === 'string') {\n priorState = this._states.get(op.target) ?? null\n }\n const next = await this.opts.reduce(priorState, op)\n if (next === null) {\n // Whole-state delete: remove from local map;\n // emit state-deleted.\n if (\n op.type === 'delete' &&\n typeof op.target === 'string'\n ) {\n this._states.delete(op.target)\n try {\n await this.opts.db.deleteState(op.target)\n } catch (err) {\n console.warn(\n 'failed to delete state in IDB:',\n err\n )\n }\n this.emitter.emit('state-deleted', {\n id: op.target,\n origin: 'local'\n })\n }\n } else {\n this._states.set(next.id, next)\n try {\n await this.opts.db.putState(next)\n } catch (err) {\n console.warn(\n 'failed to persist state to IDB:',\n err\n )\n }\n this.emitter.emit('state', { state: next, origin: 'local' })\n }\n }\n\n const canSend = this._connected &&\n this._ws?.readyState === WebSocket.OPEN &&\n this._helloSent\n if (canSend) {\n this._send({ kind: 'write', ops: [op] })\n } else {\n this._pendingOps += 1\n this.emitter.emit('pending', this._pendingOps)\n }\n\n return op\n }\n\n private _send (env:Envelope):void {\n if (!this._ws || this._ws.readyState !== WebSocket.OPEN) return\n this._ws.send(JSON.stringify(env))\n }\n\n /**\n * Rehydrate state from IDB without opening the WebSocket and\n * without writing. Idempotent: a second call is a no-op.\n *\n * The notes app calls this from ensureClient() so a reload\n * with cached state shows the notes immediately without\n * requiring a user-initiated write.\n */\n async hydrate ():Promise<void> {\n await this._bootstrap()\n }\n\n async connect ():Promise<void> {\n await this._bootstrap()\n\n // Already open \u2014 resolve immediately, no new socket.\n if (this._ws && this._ws.readyState === WebSocket.OPEN) {\n return\n }\n\n // Already connecting \u2014 chain onto the existing socket's\n // first event. Do not open a second socket.\n if (\n this._ws &&\n this._ws.readyState === WebSocket.CONNECTING\n ) {\n return this._awaitFirstEvent(this._ws)\n }\n\n return this._openSocketAwaitable()\n }\n\n private _openSocketAwaitable ():Promise<void> {\n const ws = new WebSocket(this.opts.url)\n this._ws = ws\n this._installHandlers(ws)\n return this._awaitFirstEvent(ws)\n }\n\n private _awaitFirstEvent (ws:WebSocket):Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const cleanup = ():void => {\n ws.removeEventListener('open', onOpen)\n ws.removeEventListener('error', onError)\n ws.removeEventListener('close', onClose)\n }\n const onOpen = ():void => {\n cleanup()\n resolve()\n }\n const onError = ():void => {\n cleanup()\n reject(new Error('WebSocket connect failed: error'))\n }\n const onClose = ():void => {\n cleanup()\n reject(new Error('WebSocket connect failed: close'))\n }\n ws.addEventListener('open', onOpen, { once: true })\n ws.addEventListener('error', onError, { once: true })\n ws.addEventListener('close', onClose, { once: true })\n })\n }\n\n private _installHandlers (ws:WebSocket):void {\n ws.onopen = () => {\n this._setConnected(true)\n this._hasConnectedOnce = true\n this._backoffMs = 0\n // manualSync: opening the socket is \"online\" only; the\n // caller drives the op exchange via sync(). Unless an\n // intent to sync has been recorded, in which case replay\n // hello to resume the exchange after an involuntary drop.\n // Otherwise (default mode) connect implies sync \u2014 send\n // hello immediately.\n if (!this.opts.manualSync || this._syncIntent) {\n this._sendHello().catch(() => { /* swallowed */ })\n }\n }\n\n ws.onmessage = (evt:MessageEvent) => {\n this._onMessage(evt).catch(() => { /* logged inside */ })\n }\n\n ws.onclose = () => {\n this._setConnected(false)\n this._helloSent = false\n this._ws = null\n // Background reconnect engages only AFTER the first\n // successful connect. An initial failure surfaces to\n // the caller (their `connect()` promise rejects) and\n // we do not retry silently.\n if (this._hasConnectedOnce) {\n this._scheduleReconnect()\n }\n }\n\n ws.onerror = () => {\n // onerror is followed by onclose; reconnect (if any) is\n // scheduled in onclose. The connect-time promise gets\n // the rejection via _awaitFirstEvent's listener.\n }\n }\n\n private _setConnected (v:boolean):void {\n if (this._connected === v) return\n this._connected = v\n this.emitter.emit('connected', v)\n }\n\n private _scheduleReconnect ():void {\n if (this._reconnectTimer) return\n const initial = this.opts.backoff?.initialMs ?? 250\n const max = this.opts.backoff?.maxMs ?? 5000\n if (this._backoffMs === 0) {\n this._backoffMs = initial\n } else {\n this._backoffMs = Math.min(this._backoffMs * 2, max)\n }\n this._reconnectTimer = setTimeout(() => {\n this._reconnectTimer = null\n try {\n const ws = new WebSocket(this.opts.url)\n this._ws = ws\n this._installHandlers(ws)\n } catch (err) {\n console.warn('failed to open socket:', err)\n this._scheduleReconnect()\n }\n }, this._backoffMs)\n }\n\n disconnect ():void {\n if (this._reconnectTimer) {\n clearTimeout(this._reconnectTimer)\n this._reconnectTimer = null\n }\n if (this._ws) {\n this._ws.onclose = null\n this._ws.close()\n this._ws = null\n }\n this._setConnected(false)\n this._helloSent = false\n this._hasConnectedOnce = false\n }\n\n /**\n * Run the sync exchange on demand: send `hello` so the server\n * replies with `ready` (flushing any queued ops) and streams back\n * the states this client is missing. Re-callable \u2014 each call\n * re-runs the handshake.\n *\n * Only meaningful while the socket is open; a no-op otherwise.\n * Pairs with the `manualSync` option, where opening the socket\n * (\"go online\") does not auto-sync and the caller decides when to\n * exchange ops. Under the default (auto-sync) the first sync\n * already ran on connect; calling this just re-syncs.\n */\n async sync ():Promise<void> {\n if (!this._ws || this._ws.readyState !== WebSocket.OPEN) return\n await this._sendHello()\n }\n\n private async _sendHello ():Promise<void> {\n const lastSeq = await this.opts.db.last()\n const states:StateRef[] = []\n for (const s of this._states.values()) {\n states.push({ id: s.id, hash: s.hash })\n }\n const env:Envelope = {\n kind: 'hello',\n deviceId: this.opts.deviceId,\n lastSeq,\n ...(states.length > 0 ? { states } : {})\n }\n this._send(env)\n this._helloSent = true\n this._syncIntent = true\n }\n\n private async _onMessage (evt:MessageEvent):Promise<void> {\n let env:Envelope\n try {\n env = JSON.parse(String(evt.data)) as Envelope\n } catch {\n return\n }\n if (!env || typeof env !== 'object' || typeof env.kind !== 'string') {\n return\n }\n\n // The server only ever sends ready/state/state-deleted; surface\n // the raw envelope regardless of kind for debugging consumers.\n this.emitter.emit('message', env as ServerEnvelope)\n\n if (env.kind === 'ready') {\n const requestFrom = env.requestFrom\n if (typeof requestFrom === 'number') {\n const ops = await this.opts.db.readFrom(requestFrom)\n if (ops.length > 0) {\n this._send({ kind: 'write', ops })\n }\n this._pendingOps = 0\n this.emitter.emit('pending', 0)\n } else {\n this._pendingOps = 0\n this.emitter.emit('pending', 0)\n }\n return\n }\n\n if (env.kind === 'state') {\n const next = env.state\n if (\n !next ||\n typeof next.id !== 'string' ||\n typeof next.hash !== 'string' ||\n typeof next.__ts !== 'object' ||\n next.__ts === null ||\n typeof next.value !== 'object' ||\n next.value === null\n ) {\n return\n }\n const local = this._states.get(next.id) ?? null\n let merged:ReducedState\n try {\n merged = await mergeReducedStates(local, next)\n } catch (err) {\n console.warn('failed to merge inbound state:', err)\n merged = next\n }\n this._states.set(merged.id, merged)\n this.emitter.emit('state', { state: merged, origin: 'server' })\n try {\n await this.opts.db.putState(merged)\n } catch (err) {\n console.warn(\n 'failed to persist state to IDB:',\n err\n )\n }\n return\n }\n\n if (env.kind === 'state-deleted') {\n const id = env.id\n if (typeof id !== 'string') return\n // AC8.4 / AC6.6: no-op if we never had this state.\n // Deleting from an empty Map is a no-op; same for IDB\n // if the row doesn't exist.\n this._states.delete(id)\n try {\n await this.opts.db.deleteState(id)\n } catch (err) {\n console.warn(\n 'failed to delete state in IDB:',\n err\n )\n }\n this.emitter.emit('state-deleted', { id, origin: 'server' })\n }\n }\n}\n"],
5
+ "mappings": ";;AAAA,OAAO,UAA4B;AACnC,OAAO,wBAAwB;AAI/B,SAAS,oBAAoB,oBAAoB;AAuE1C,MAAM,WAAW;AAAA,EA5ExB,OA4EwB;AAAA;AAAA;AAAA,EACH;AAAA,EACA,UAA8B,KAAiB;AAAA,EACxD,UAAoC,oBAAI,IAAI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SAAS,YACrB,OAAO,KAAK,SAAS,YACrB,KAAK,SAAS,QACd,OAAO,KAAK,UAAU,YACtB,KAAK,UAAU,MACjB;AACE;AAAA,MACJ;AACA,YAAM,QAAQ,KAAK,QAAQ,IAAI,KAAK,EAAE,KAAK;AAC3C,UAAI;AACJ,UAAI;AACA,iBAAS,MAAM,mBAAmB,OAAO,IAAI;AAAA,MACjD,SAAS,KAAK;AACV,gBAAQ,KAAK,kCAAkC,GAAG;AAClD,iBAAS;AAAA,MACb;AACA,WAAK,QAAQ,IAAI,OAAO,IAAI,MAAM;AAClC,WAAK,QAAQ,KAAK,SAAS,EAAE,OAAO,QAAQ,QAAQ,SAAS,CAAC;AAC9D,UAAI;AACA,cAAM,KAAK,KAAK,GAAG,SAAS,MAAM;AAAA,MACtC,SAAS,KAAK;AACV,gBAAQ;AAAA,UACJ;AAAA,UACA;AAAA,QACJ;AAAA,MACJ;AACA;AAAA,IACJ;AAEA,QAAI,IAAI,SAAS,iBAAiB;AAC9B,YAAM,KAAK,IAAI;AACf,UAAI,OAAO,OAAO,SAAU;AAI5B,WAAK,QAAQ,OAAO,EAAE;AACtB,UAAI;AACA,cAAM,KAAK,KAAK,GAAG,YAAY,EAAE;AAAA,MACrC,SAAS,KAAK;AACV,gBAAQ;AAAA,UACJ;AAAA,UACA;AAAA,QACJ;AAAA,MACJ;AACA,WAAK,QAAQ,KAAK,iBAAiB,EAAE,IAAI,QAAQ,SAAS,CAAC;AAAA,IAC/D;AAAA,EACJ;AACJ;",
6
+ "names": []
7
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Dependency-free RPC client for SQLite OPFS worker.
3
+ * Correlates request/response pairs by incrementing reqId.
4
+ */
5
+ import type { SqlExecutor, SqlRow } from './sqlite.js';
6
+ /** Minimal surface shared by a real `Worker` and a `MessagePort`. */
7
+ export interface RpcWorker {
8
+ postMessage(data: unknown): void;
9
+ addEventListener(type: string, cb: (ev: {
10
+ data?: unknown;
11
+ }) => void): void;
12
+ terminate?(): void;
13
+ }
14
+ export interface RpcClient extends SqlExecutor {
15
+ /** Send an arbitrary correlated message (e.g. the `init` handshake). */
16
+ request(msg: Record<string, unknown>): Promise<SqlRow[]>;
17
+ /** Reject + clear all in-flight requests (used on a fatal worker error). */
18
+ failAll(err: Error): void;
19
+ }
20
+ export declare function rpcClient(worker: RpcWorker): RpcClient;
21
+ //# sourceMappingURL=sqlite-opfs-rpc.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-opfs-rpc.d.ts","sourceRoot":"","sources":["../../src/client/sqlite-opfs-rpc.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAEtD,qEAAqE;AACrE,MAAM,WAAW,SAAS;IACtB,WAAW,CAAE,IAAI,EAAC,OAAO,GAAE,IAAI,CAAA;IAC/B,gBAAgB,CACZ,IAAI,EAAC,MAAM,EACX,EAAE,EAAC,CAAC,EAAE,EAAC;QAAE,IAAI,CAAC,EAAC,OAAO,CAAA;KAAE,KAAG,IAAI,GACjC,IAAI,CAAA;IACN,SAAS,CAAC,IAAI,IAAI,CAAA;CACrB;AAcD,MAAM,WAAW,SAAU,SAAQ,WAAW;IAC1C,wEAAwE;IACxE,OAAO,CAAE,GAAG,EAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAA;IACvD,4EAA4E;IAC5E,OAAO,CAAE,GAAG,EAAC,KAAK,GAAE,IAAI,CAAA;CAC3B;AAED,wBAAgB,SAAS,CAAE,MAAM,EAAC,SAAS,GAAE,SAAS,CAiDrD"}
@@ -0,0 +1,55 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+ function rpcClient(worker) {
4
+ let nextId = 1;
5
+ let closed = false;
6
+ const pending = /* @__PURE__ */ new Map();
7
+ worker.addEventListener("message", (ev) => {
8
+ const m = ev.data;
9
+ if (!m || typeof m.reqId !== "number") return;
10
+ const p = pending.get(m.reqId);
11
+ if (!p) return;
12
+ pending.delete(m.reqId);
13
+ if (m.ok) p.resolve(m.rows ?? []);
14
+ else p.reject(new Error(m.error ?? "sqlite worker error"));
15
+ });
16
+ function request(msg) {
17
+ const reqId = nextId++;
18
+ return new Promise((resolve, reject) => {
19
+ pending.set(reqId, { resolve, reject });
20
+ worker.postMessage({ ...msg, reqId });
21
+ });
22
+ }
23
+ __name(request, "request");
24
+ function failAll(err) {
25
+ for (const p of pending.values()) p.reject(err);
26
+ pending.clear();
27
+ }
28
+ __name(failAll, "failAll");
29
+ return {
30
+ request,
31
+ failAll,
32
+ async exec(sql, params) {
33
+ return request({
34
+ kind: "exec",
35
+ sql,
36
+ params: params ? params.slice() : void 0
37
+ });
38
+ },
39
+ async close() {
40
+ if (closed) return;
41
+ closed = true;
42
+ try {
43
+ await request({ kind: "close" });
44
+ } finally {
45
+ failAll(new Error("closed"));
46
+ if (worker.terminate) worker.terminate();
47
+ }
48
+ }
49
+ };
50
+ }
51
+ __name(rpcClient, "rpcClient");
52
+ export {
53
+ rpcClient
54
+ };
55
+ //# sourceMappingURL=sqlite-opfs-rpc.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/client/sqlite-opfs-rpc.ts"],
4
+ "sourcesContent": ["/**\n * Dependency-free RPC client for SQLite OPFS worker.\n * Correlates request/response pairs by incrementing reqId.\n */\n\nimport type { SqlExecutor, SqlRow } from './sqlite.js'\n\n/** Minimal surface shared by a real `Worker` and a `MessagePort`. */\nexport interface RpcWorker {\n postMessage (data:unknown):void\n addEventListener (\n type:string,\n cb:(ev:{ data?:unknown })=>void\n ):void\n terminate? ():void\n}\n\ninterface Pending {\n resolve (rows:SqlRow[]):void\n reject (err:Error):void\n}\n\ninterface Reply {\n reqId:number\n ok:boolean\n rows?:SqlRow[]\n error?:string\n}\n\nexport interface RpcClient extends SqlExecutor {\n /** Send an arbitrary correlated message (e.g. the `init` handshake). */\n request (msg:Record<string, unknown>):Promise<SqlRow[]>\n /** Reject + clear all in-flight requests (used on a fatal worker error). */\n failAll (err:Error):void\n}\n\nexport function rpcClient (worker:RpcWorker):RpcClient {\n let nextId = 1\n let closed = false\n const pending = new Map<number, Pending>()\n\n worker.addEventListener('message', (ev) => {\n const m = ev.data as Reply\n if (!m || typeof m.reqId !== 'number') return\n const p = pending.get(m.reqId)\n if (!p) return\n pending.delete(m.reqId)\n if (m.ok) p.resolve(m.rows ?? [])\n else p.reject(new Error(m.error ?? 'sqlite worker error'))\n })\n\n function request (msg:Record<string, unknown>):Promise<SqlRow[]> {\n const reqId = nextId++\n return new Promise<SqlRow[]>((resolve, reject) => {\n pending.set(reqId, { resolve, reject })\n worker.postMessage({ ...msg, reqId })\n })\n }\n\n function failAll (err:Error):void {\n for (const p of pending.values()) p.reject(err)\n pending.clear()\n }\n\n return {\n request,\n failAll,\n async exec (sql:string, params?:readonly unknown[]):Promise<SqlRow[]> {\n return request({\n kind: 'exec',\n sql,\n params: params ? params.slice() : undefined\n })\n },\n async close ():Promise<void> {\n if (closed) return\n closed = true\n try {\n await request({ kind: 'close' })\n } finally {\n failAll(new Error('closed'))\n if (worker.terminate) worker.terminate()\n }\n }\n }\n}\n"],
5
+ "mappings": ";;AAoCO,SAAS,UAAW,QAA4B;AACnD,MAAI,SAAS;AACb,MAAI,SAAS;AACb,QAAM,UAAU,oBAAI,IAAqB;AAEzC,SAAO,iBAAiB,WAAW,CAAC,OAAO;AACvC,UAAM,IAAI,GAAG;AACb,QAAI,CAAC,KAAK,OAAO,EAAE,UAAU,SAAU;AACvC,UAAM,IAAI,QAAQ,IAAI,EAAE,KAAK;AAC7B,QAAI,CAAC,EAAG;AACR,YAAQ,OAAO,EAAE,KAAK;AACtB,QAAI,EAAE,GAAI,GAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;AAAA,QAC3B,GAAE,OAAO,IAAI,MAAM,EAAE,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