@johnhenry/browsermesh-sync 0.0.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/src/collab.mjs ADDED
@@ -0,0 +1,363 @@
1
+ /**
2
+ // STATUS: EXPERIMENTAL — complete implementation, not yet integrated into main application
3
+ * clawser-peer-collab.js -- Real-time collaborative editing via Yjs CRDT.
4
+ *
5
+ * YjsAdapter: wraps Yjs Doc with shared types and sync primitives.
6
+ * AwarenessState: cursor/selection presence (custom, no Yjs awareness dep).
7
+ * CollabSession: ties YjsAdapter + AwarenessState to a PeerSession.
8
+ *
9
+ * Yjs loaded via CDN: https://cdn.jsdelivr.net/npm/yjs@13.6.30/+esm
10
+ *
11
+ * No browser-only imports at module level.
12
+ *
13
+ * Run tests:
14
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-collab.test.mjs
15
+ */
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Wire constants
19
+ // ---------------------------------------------------------------------------
20
+
21
+ export const COLLAB_UPDATE = 0xF0
22
+ export const COLLAB_AWARENESS = 0xF1
23
+ export const COLLAB_SYNC = 0xF2
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // YjsAdapter
27
+ // ---------------------------------------------------------------------------
28
+
29
+ /**
30
+ * Wraps a Yjs Doc for collaborative editing.
31
+ * Accepts an injected Y module for testability (CDN loaded in browser).
32
+ */
33
+ export class YjsAdapter {
34
+ #doc
35
+ #Y
36
+ #updateCallbacks = []
37
+ #destroyed = false
38
+
39
+ /**
40
+ * @param {string} docId - Document identifier
41
+ * @param {object} [opts]
42
+ * @param {object} [opts.Y] - Yjs module (injected for testing)
43
+ */
44
+ constructor(docId, opts = {}) {
45
+ if (!docId || typeof docId !== 'string') {
46
+ throw new Error('docId is required and must be a non-empty string')
47
+ }
48
+ this.docId = docId
49
+ this.#Y = opts.Y || null
50
+
51
+ if (this.#Y) {
52
+ this.#doc = new this.#Y.Doc()
53
+ } else {
54
+ // Stub doc for when Y is not available
55
+ this.#doc = this.#createStubDoc()
56
+ }
57
+ }
58
+
59
+ get doc() { return this.#doc }
60
+ get destroyed() { return this.#destroyed }
61
+
62
+ /**
63
+ * Get or create a shared Y.Text type.
64
+ * @param {string} name
65
+ * @returns {*} Y.Text or stub
66
+ */
67
+ getText(name) {
68
+ if (this.#Y) return this.#doc.getText(name)
69
+ return this.#doc._texts.get(name) || this.#doc._createText(name)
70
+ }
71
+
72
+ /**
73
+ * Get or create a shared Y.Map type.
74
+ * @param {string} name
75
+ * @returns {*} Y.Map or stub
76
+ */
77
+ getMap(name) {
78
+ if (this.#Y) return this.#doc.getMap(name)
79
+ return this.#doc._maps.get(name) || this.#doc._createMap(name)
80
+ }
81
+
82
+ /**
83
+ * Apply a binary update from a remote peer.
84
+ * @param {Uint8Array} update
85
+ */
86
+ applyUpdate(update) {
87
+ if (this.#destroyed) throw new Error('Adapter is destroyed')
88
+ if (this.#Y) {
89
+ this.#Y.applyUpdate(this.#doc, update)
90
+ } else {
91
+ // Stub: store raw update
92
+ this.#doc._updates.push(update)
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Encode the full document state as a binary snapshot.
98
+ * @returns {Uint8Array}
99
+ */
100
+ encodeState() {
101
+ if (this.#Y) {
102
+ return this.#Y.encodeStateAsUpdate(this.#doc)
103
+ }
104
+ return new Uint8Array(this.#doc._updates.flat())
105
+ }
106
+
107
+ /**
108
+ * Register a callback for document updates.
109
+ * @param {Function} callback - (update: Uint8Array, origin: any) => void
110
+ */
111
+ onUpdate(callback) {
112
+ this.#updateCallbacks.push(callback)
113
+ if (this.#Y) {
114
+ this.#doc.on('update', callback)
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Destroy the adapter and release resources.
120
+ */
121
+ destroy() {
122
+ if (this.#destroyed) return
123
+ this.#destroyed = true
124
+ if (this.#Y) {
125
+ this.#doc.destroy()
126
+ }
127
+ this.#updateCallbacks = []
128
+ }
129
+
130
+ // -- Internal -------------------------------------------------------------
131
+
132
+ /**
133
+ * Create a stub doc for testing without Yjs.
134
+ * @returns {object}
135
+ */
136
+ #createStubDoc() {
137
+ const texts = new Map()
138
+ const maps = new Map()
139
+ const updates = []
140
+ return {
141
+ _texts: texts,
142
+ _maps: maps,
143
+ _updates: updates,
144
+ _createText(name) {
145
+ const t = {
146
+ _content: '',
147
+ insert(pos, str) {
148
+ this._content = this._content.slice(0, pos) + str + this._content.slice(pos)
149
+ },
150
+ toString() { return this._content },
151
+ delete(pos, len) {
152
+ this._content = this._content.slice(0, pos) + this._content.slice(pos + len)
153
+ },
154
+ get length() { return this._content.length },
155
+ }
156
+ texts.set(name, t)
157
+ return t
158
+ },
159
+ _createMap(name) {
160
+ const m = {
161
+ _data: new Map(),
162
+ set(k, v) { this._data.set(k, v) },
163
+ get(k) { return this._data.get(k) },
164
+ delete(k) { this._data.delete(k) },
165
+ has(k) { return this._data.has(k) },
166
+ toJSON() { return Object.fromEntries(this._data) },
167
+ get size() { return this._data.size },
168
+ }
169
+ maps.set(name, m)
170
+ return m
171
+ },
172
+ }
173
+ }
174
+ }
175
+
176
+ // ---------------------------------------------------------------------------
177
+ // AwarenessState
178
+ // ---------------------------------------------------------------------------
179
+
180
+ /**
181
+ * Lightweight awareness/presence state for collaborative sessions.
182
+ * Tracks cursor positions, selections, and user metadata without
183
+ * depending on Yjs awareness protocol.
184
+ */
185
+ export class AwarenessState {
186
+ #localState = null
187
+ #states = new Map() // peerId -> state
188
+ #callbacks = []
189
+
190
+ /**
191
+ * Set the local user's awareness state.
192
+ * @param {object} state - { cursor, selection, user, color, ... }
193
+ */
194
+ setLocal(state) {
195
+ this.#localState = { ...state, updatedAt: Date.now() }
196
+ }
197
+
198
+ /**
199
+ * Get the local state.
200
+ * @returns {object|null}
201
+ */
202
+ getLocal() {
203
+ return this.#localState ? { ...this.#localState } : null
204
+ }
205
+
206
+ /**
207
+ * Update a remote peer's awareness state.
208
+ * @param {string} peerId
209
+ * @param {object} state
210
+ */
211
+ setRemote(peerId, state) {
212
+ this.#states.set(peerId, { ...state, updatedAt: Date.now() })
213
+ for (const cb of this.#callbacks) cb(peerId, state)
214
+ }
215
+
216
+ /**
217
+ * Remove a peer's awareness state.
218
+ * @param {string} peerId
219
+ */
220
+ removeRemote(peerId) {
221
+ this.#states.delete(peerId)
222
+ }
223
+
224
+ /**
225
+ * Get all awareness states (local + remote).
226
+ * @returns {Map<string, object>}
227
+ */
228
+ getStates() {
229
+ const result = new Map(this.#states)
230
+ if (this.#localState) {
231
+ result.set('local', this.#localState)
232
+ }
233
+ return result
234
+ }
235
+
236
+ /**
237
+ * Register a callback for awareness updates.
238
+ * @param {Function} cb - (peerId, state) => void
239
+ */
240
+ onUpdate(cb) {
241
+ this.#callbacks.push(cb)
242
+ }
243
+
244
+ /**
245
+ * Clear all remote states.
246
+ */
247
+ clear() {
248
+ this.#states.clear()
249
+ }
250
+ }
251
+
252
+ // ---------------------------------------------------------------------------
253
+ // CollabSession
254
+ // ---------------------------------------------------------------------------
255
+
256
+ /**
257
+ * Ties a YjsAdapter + AwarenessState to a PeerSession for
258
+ * real-time collaborative editing over the mesh network.
259
+ */
260
+ export class CollabSession {
261
+ #adapter
262
+ #awareness
263
+ #session
264
+ #docId
265
+ #active = false
266
+
267
+ /**
268
+ * @param {object} opts
269
+ * @param {object} opts.session - PeerSession (or mock with send/onMessage)
270
+ * @param {string} opts.docId - Document identifier
271
+ * @param {object} [opts.Y] - Yjs module
272
+ */
273
+ constructor({ session, docId, Y }) {
274
+ if (!session) throw new Error('session is required')
275
+ if (!docId || typeof docId !== 'string') throw new Error('docId is required')
276
+
277
+ this.#session = session
278
+ this.#docId = docId
279
+ this.#adapter = new YjsAdapter(docId, { Y })
280
+ this.#awareness = new AwarenessState()
281
+ }
282
+
283
+ get adapter() { return this.#adapter }
284
+ get awareness() { return this.#awareness }
285
+ get docId() { return this.#docId }
286
+ get active() { return this.#active }
287
+
288
+ /**
289
+ * Start the collab session -- register message handlers and
290
+ * listen for doc updates to broadcast to peer.
291
+ */
292
+ start() {
293
+ if (this.#active) return
294
+ this.#active = true
295
+
296
+ // Forward local doc updates to peer
297
+ this.#adapter.onUpdate((update) => {
298
+ if (this.#active && this.#session.send) {
299
+ this.#session.send({
300
+ type: COLLAB_UPDATE,
301
+ docId: this.#docId,
302
+ update: Array.from(update),
303
+ })
304
+ }
305
+ })
306
+
307
+ // Handle incoming messages
308
+ if (this.#session.onMessage) {
309
+ this.#session.onMessage((msg) => {
310
+ if (!msg || msg.docId !== this.#docId) return
311
+
312
+ if (msg.type === COLLAB_UPDATE && msg.update) {
313
+ this.#adapter.applyUpdate(new Uint8Array(msg.update))
314
+ } else if (msg.type === COLLAB_AWARENESS && msg.state) {
315
+ this.#awareness.setRemote(msg.peerId || 'remote', msg.state)
316
+ } else if (msg.type === COLLAB_SYNC) {
317
+ // Full state sync request/response
318
+ if (msg.state) {
319
+ this.#adapter.applyUpdate(new Uint8Array(msg.state))
320
+ }
321
+ }
322
+ })
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Sync full state with peer (initial exchange).
328
+ */
329
+ syncWithPeer() {
330
+ const state = this.#adapter.encodeState()
331
+ if (this.#session.send) {
332
+ this.#session.send({
333
+ type: COLLAB_SYNC,
334
+ docId: this.#docId,
335
+ state: Array.from(state),
336
+ })
337
+ }
338
+ }
339
+
340
+ /**
341
+ * Broadcast local awareness state to peer.
342
+ * @param {object} state - Awareness data to share
343
+ */
344
+ broadcastAwareness(state) {
345
+ this.#awareness.setLocal(state)
346
+ if (this.#session.send) {
347
+ this.#session.send({
348
+ type: COLLAB_AWARENESS,
349
+ docId: this.#docId,
350
+ state,
351
+ })
352
+ }
353
+ }
354
+
355
+ /**
356
+ * Close the collab session and clean up.
357
+ */
358
+ close() {
359
+ this.#active = false
360
+ this.#adapter.destroy()
361
+ this.#awareness.clear()
362
+ }
363
+ }