@crdt-sync/core 0.1.2 → 0.2.1

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.
@@ -1,115 +0,0 @@
1
- import { CrdtStateProxy } from './CrdtStateProxy.js';
2
- import type { WasmStateStore } from './CrdtStateProxy.js';
3
- /**
4
- * Minimal subset of the browser `WebSocket` API used by `WebSocketManager`.
5
- *
6
- * The real browser `WebSocket` satisfies this interface out-of-the-box.
7
- * In tests, a plain mock object can be used instead.
8
- */
9
- export interface WebSocketLike {
10
- /** Current connection state (0 = CONNECTING, 1 = OPEN, 2 = CLOSING, 3 = CLOSED). */
11
- readonly readyState: number;
12
- /** Send a UTF-8 string frame to the server. */
13
- send(data: string): void;
14
- /** Initiate the closing handshake. */
15
- close(): void;
16
- /** Fired when a message frame is received. */
17
- onmessage: ((event: {
18
- data: string;
19
- }) => void) | null;
20
- /** Fired when the connection is established. */
21
- onopen: ((event: unknown) => void) | null;
22
- /** Fired when the connection is closed. */
23
- onclose: ((event: unknown) => void) | null;
24
- /** Fired when an error occurs. */
25
- onerror: ((event: unknown) => void) | null;
26
- }
27
- /**
28
- * Bridges a `CrdtStateProxy` to a WebSocket connection so that every CRDT
29
- * operation produced locally is broadcast to peers, and every envelope
30
- * received from a peer is applied to the local store.
31
- *
32
- * ## Data flow
33
- *
34
- * ```
35
- * Local write
36
- * → CrdtStateProxy.onUpdate (envelope collected in _pendingEnvelopes)
37
- * → requestAnimationFrame / setTimeout schedules a batch flush
38
- * → WebSocket.send(JSON.stringify(envelopes)) // one payload per frame
39
- *
40
- * Incoming message (single envelope or JSON array of envelopes)
41
- * → WebSocket.onmessage
42
- * → WasmStateStore.apply_envelope() // merge into local store
43
- * ```
44
- *
45
- * ## Throttling / batching
46
- *
47
- * Multiple proxy writes that occur within the same JavaScript task (e.g. a
48
- * 60 FPS game loop) are collected in `_pendingEnvelopes` and sent as a single
49
- * JSON array payload on the next animation frame (browser) or the next
50
- * `setTimeout(fn, 0)` tick (Node.js / non-browser environments). This keeps
51
- * network traffic proportional to frame rate rather than to the raw mutation
52
- * rate.
53
- *
54
- * ## Usage
55
- *
56
- * ```ts
57
- * import init, { WasmStateStore } from './crdt_sync.js';
58
- * import { CrdtStateProxy, WebSocketManager } from './index.js';
59
- *
60
- * await init();
61
- * const store = new WasmStateStore('node-1');
62
- * const proxy = new CrdtStateProxy(store);
63
- * const manager = new WebSocketManager(store, proxy, new WebSocket('wss://example.com/sync'));
64
- *
65
- * // Writes are automatically batched and broadcast to peers.
66
- * proxy.state.robot = { x: 10, y: 20 };
67
- *
68
- * // Clean up.
69
- * manager.disconnect();
70
- * ```
71
- */
72
- export declare class WebSocketManager {
73
- private readonly _store;
74
- private readonly _proxy;
75
- private readonly _ws;
76
- private _unsubscribe;
77
- /** Envelopes collected in the current frame, waiting for the batch flush. */
78
- private _pendingEnvelopes;
79
- /** Cancels the currently scheduled batch flush (rAF or setTimeout handle). */
80
- private _cancelFlush;
81
- /** Envelopes queued while the socket is not open, flushed on reconnection. */
82
- private _offlineQueue;
83
- /**
84
- * Create a `WebSocketManager` and attach it to the given WebSocket.
85
- *
86
- * @param store - The Wasm state store. Incoming peer envelopes will be
87
- * applied to this store via `apply_envelope`.
88
- * @param proxy - The CRDT state proxy. Outgoing envelopes produced by
89
- * `set_register` calls will be read from the proxy's `onUpdate` events.
90
- * @param ws - An open or connecting WebSocket (or any `WebSocketLike` object).
91
- */
92
- constructor(store: WasmStateStore, proxy: CrdtStateProxy, ws: WebSocketLike);
93
- private _attach;
94
- /**
95
- * Schedule a single batch flush for the current frame. Subsequent calls
96
- * before the flush fires are no-ops (only one flush is ever outstanding).
97
- *
98
- * Uses `requestAnimationFrame` when available (browser, ~60 FPS cadence),
99
- * falling back to `setTimeout(fn, 0)` in non-browser environments.
100
- */
101
- private _scheduleBatchFlush;
102
- /**
103
- * Send all pending envelopes as a single JSON-array payload, or move them
104
- * to the offline queue if the socket is not currently open.
105
- */
106
- private _flushBatch;
107
- /**
108
- * Unsubscribe from proxy updates, discard any buffered envelopes, and close
109
- * the WebSocket connection.
110
- *
111
- * Safe to call more than once.
112
- */
113
- disconnect(): void;
114
- }
115
- //# sourceMappingURL=WebSocketManager.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"WebSocketManager.d.ts","sourceRoot":"","sources":["../src/WebSocketManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D;;;;;GAKG;AACH,MAAM,WAAW,aAAa;IAC5B,oFAAoF;IACpF,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,+CAA+C;IAC/C,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,sCAAsC;IACtC,KAAK,IAAI,IAAI,CAAC;IACd,8CAA8C;IAC9C,SAAS,EAAE,CAAC,CAAC,KAAK,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;IACtD,gDAAgD;IAChD,MAAM,EAAE,CAAC,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;IAC1C,2CAA2C;IAC3C,OAAO,EAAE,CAAC,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;IAC3C,kCAAkC;IAClC,OAAO,EAAE,CAAC,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;CAC5C;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiB;IACxC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiB;IACxC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAgB;IACpC,OAAO,CAAC,YAAY,CAA6B;IACjD,6EAA6E;IAC7E,OAAO,CAAC,iBAAiB,CAAgB;IACzC,8EAA8E;IAC9E,OAAO,CAAC,YAAY,CAA6B;IACjD,8EAA8E;IAC9E,OAAO,CAAC,aAAa,CAAgB;IAErC;;;;;;;;OAQG;gBACS,KAAK,EAAE,cAAc,EAAE,KAAK,EAAE,cAAc,EAAE,EAAE,EAAE,aAAa;IAS3E,OAAO,CAAC,OAAO;IAoDf;;;;;;OAMG;IACH,OAAO,CAAC,mBAAmB;IAiB3B;;;OAGG;IACH,OAAO,CAAC,WAAW;IAcnB;;;;;OAKG;IACH,UAAU,IAAI,IAAI;CASnB"}
@@ -1,179 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WebSocketManager = void 0;
4
- /**
5
- * Bridges a `CrdtStateProxy` to a WebSocket connection so that every CRDT
6
- * operation produced locally is broadcast to peers, and every envelope
7
- * received from a peer is applied to the local store.
8
- *
9
- * ## Data flow
10
- *
11
- * ```
12
- * Local write
13
- * → CrdtStateProxy.onUpdate (envelope collected in _pendingEnvelopes)
14
- * → requestAnimationFrame / setTimeout schedules a batch flush
15
- * → WebSocket.send(JSON.stringify(envelopes)) // one payload per frame
16
- *
17
- * Incoming message (single envelope or JSON array of envelopes)
18
- * → WebSocket.onmessage
19
- * → WasmStateStore.apply_envelope() // merge into local store
20
- * ```
21
- *
22
- * ## Throttling / batching
23
- *
24
- * Multiple proxy writes that occur within the same JavaScript task (e.g. a
25
- * 60 FPS game loop) are collected in `_pendingEnvelopes` and sent as a single
26
- * JSON array payload on the next animation frame (browser) or the next
27
- * `setTimeout(fn, 0)` tick (Node.js / non-browser environments). This keeps
28
- * network traffic proportional to frame rate rather than to the raw mutation
29
- * rate.
30
- *
31
- * ## Usage
32
- *
33
- * ```ts
34
- * import init, { WasmStateStore } from './crdt_sync.js';
35
- * import { CrdtStateProxy, WebSocketManager } from './index.js';
36
- *
37
- * await init();
38
- * const store = new WasmStateStore('node-1');
39
- * const proxy = new CrdtStateProxy(store);
40
- * const manager = new WebSocketManager(store, proxy, new WebSocket('wss://example.com/sync'));
41
- *
42
- * // Writes are automatically batched and broadcast to peers.
43
- * proxy.state.robot = { x: 10, y: 20 };
44
- *
45
- * // Clean up.
46
- * manager.disconnect();
47
- * ```
48
- */
49
- class WebSocketManager {
50
- /**
51
- * Create a `WebSocketManager` and attach it to the given WebSocket.
52
- *
53
- * @param store - The Wasm state store. Incoming peer envelopes will be
54
- * applied to this store via `apply_envelope`.
55
- * @param proxy - The CRDT state proxy. Outgoing envelopes produced by
56
- * `set_register` calls will be read from the proxy's `onUpdate` events.
57
- * @param ws - An open or connecting WebSocket (or any `WebSocketLike` object).
58
- */
59
- constructor(store, proxy, ws) {
60
- this._unsubscribe = null;
61
- /** Envelopes collected in the current frame, waiting for the batch flush. */
62
- this._pendingEnvelopes = [];
63
- /** Cancels the currently scheduled batch flush (rAF or setTimeout handle). */
64
- this._cancelFlush = null;
65
- /** Envelopes queued while the socket is not open, flushed on reconnection. */
66
- this._offlineQueue = [];
67
- this._store = store;
68
- this._proxy = proxy;
69
- this._ws = ws;
70
- this._attach();
71
- }
72
- // ── Internal setup ────────────────────────────────────────────────────
73
- _attach() {
74
- const ws = this._ws;
75
- // Collect envelopes and schedule a batch flush once per frame so that
76
- // multiple synchronous writes (e.g. a 60 FPS game loop) are coalesced
77
- // into a single network payload instead of one message per mutation.
78
- this._unsubscribe = this._proxy.onUpdate(({ envelope }) => {
79
- this._pendingEnvelopes.push(envelope);
80
- this._scheduleBatchFlush();
81
- });
82
- // On (re)connection, immediately flush pending envelopes together with any
83
- // envelopes that were queued while the socket was offline.
84
- ws.onopen = () => {
85
- // Cancel any scheduled flush — we will drain everything right now.
86
- this._cancelFlush?.();
87
- this._cancelFlush = null;
88
- const offline = this._offlineQueue;
89
- const pending = this._pendingEnvelopes;
90
- this._offlineQueue = [];
91
- this._pendingEnvelopes = [];
92
- const batch = [...offline, ...pending];
93
- if (batch.length > 0) {
94
- ws.send(JSON.stringify(batch));
95
- }
96
- };
97
- // Apply envelopes received from peers. Peers may send either a single
98
- // envelope JSON string or a JSON array of envelope strings (batch format).
99
- ws.onmessage = (event) => {
100
- let parsed;
101
- try {
102
- parsed = JSON.parse(event.data);
103
- }
104
- catch {
105
- parsed = null;
106
- }
107
- if (Array.isArray(parsed)) {
108
- for (const env of parsed) {
109
- this._store.apply_envelope(env);
110
- }
111
- }
112
- else {
113
- // Fallback: treat the raw frame data as a single envelope string.
114
- this._store.apply_envelope(event.data);
115
- }
116
- };
117
- // On close or error the subscription stays active so that writes made
118
- // while offline are buffered and flushed when the socket reconnects.
119
- ws.onclose = () => { };
120
- ws.onerror = () => { };
121
- }
122
- /**
123
- * Schedule a single batch flush for the current frame. Subsequent calls
124
- * before the flush fires are no-ops (only one flush is ever outstanding).
125
- *
126
- * Uses `requestAnimationFrame` when available (browser, ~60 FPS cadence),
127
- * falling back to `setTimeout(fn, 0)` in non-browser environments.
128
- */
129
- _scheduleBatchFlush() {
130
- if (this._cancelFlush !== null)
131
- return; // already scheduled
132
- const doFlush = () => {
133
- this._cancelFlush = null;
134
- this._flushBatch();
135
- };
136
- if (typeof requestAnimationFrame === 'function') {
137
- const id = requestAnimationFrame(doFlush);
138
- this._cancelFlush = () => cancelAnimationFrame(id);
139
- }
140
- else {
141
- const id = setTimeout(doFlush, 0);
142
- this._cancelFlush = () => clearTimeout(id);
143
- }
144
- }
145
- /**
146
- * Send all pending envelopes as a single JSON-array payload, or move them
147
- * to the offline queue if the socket is not currently open.
148
- */
149
- _flushBatch() {
150
- const envelopes = this._pendingEnvelopes.splice(0);
151
- if (envelopes.length === 0)
152
- return;
153
- const ws = this._ws;
154
- if (ws.readyState === 1 /* OPEN */) {
155
- ws.send(JSON.stringify(envelopes));
156
- }
157
- else {
158
- this._offlineQueue.push(...envelopes);
159
- }
160
- }
161
- // ── Public API ────────────────────────────────────────────────────────
162
- /**
163
- * Unsubscribe from proxy updates, discard any buffered envelopes, and close
164
- * the WebSocket connection.
165
- *
166
- * Safe to call more than once.
167
- */
168
- disconnect() {
169
- this._unsubscribe?.();
170
- this._unsubscribe = null;
171
- this._cancelFlush?.();
172
- this._cancelFlush = null;
173
- this._pendingEnvelopes = [];
174
- this._offlineQueue = [];
175
- this._ws.close();
176
- }
177
- }
178
- exports.WebSocketManager = WebSocketManager;
179
- //# sourceMappingURL=WebSocketManager.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"WebSocketManager.js","sourceRoot":"","sources":["../src/WebSocketManager.ts"],"names":[],"mappings":";;;AA0BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,MAAa,gBAAgB;IAY3B;;;;;;;;OAQG;IACH,YAAY,KAAqB,EAAE,KAAqB,EAAE,EAAiB;QAjBnE,iBAAY,GAAwB,IAAI,CAAC;QACjD,6EAA6E;QACrE,sBAAiB,GAAa,EAAE,CAAC;QACzC,8EAA8E;QACtE,iBAAY,GAAwB,IAAI,CAAC;QACjD,8EAA8E;QACtE,kBAAa,GAAa,EAAE,CAAC;QAYnC,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QACpB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QACpB,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;QACd,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IAED,yEAAyE;IAEjE,OAAO;QACb,MAAM,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC;QAEpB,sEAAsE;QACtE,sEAAsE;QACtE,qEAAqE;QACrE,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;YACxD,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YACtC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC7B,CAAC,CAAC,CAAC;QAEH,2EAA2E;QAC3E,2DAA2D;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