@inditextech/weave-store-websockets 0.1.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.
@@ -0,0 +1,453 @@
1
+ import * as I from "yjs";
2
+ const At = "store-websockets", Et = {
3
+ CONNECTING: "connecting",
4
+ CONNECTED: "connected",
5
+ DISCONNECTED: "disconnected"
6
+ }, p = () => /* @__PURE__ */ new Map(), T = (t, e, s) => {
7
+ let n = t.get(e);
8
+ return n === void 0 && t.set(e, n = s()), n;
9
+ }, N = () => /* @__PURE__ */ new Set(), x = Array.from, It = String.fromCharCode, Y = (t) => t.toLowerCase(), $ = /^\s*/g, q = (t) => t.replace($, ""), F = /([A-Z])/g, Ct = (t, e) => q(t.replace(F, (s) => `${e}${Y(s)}`)), G = (t) => {
10
+ const e = unescape(encodeURIComponent(t)), s = e.length, n = new Uint8Array(s);
11
+ for (let o = 0; o < s; o++)
12
+ n[o] = /** @type {number} */
13
+ e.codePointAt(o);
14
+ return n;
15
+ }, S = (
16
+ /** @type {TextEncoder} */
17
+ typeof TextEncoder < "u" ? new TextEncoder() : null
18
+ ), J = (t) => S.encode(t), K = S ? J : G;
19
+ let g = typeof TextDecoder > "u" ? null : new TextDecoder("utf-8", { fatal: !0, ignoreBOM: !0 });
20
+ g && g.decode(new Uint8Array()).length === 1 && (g = null);
21
+ const X = Object.keys, kt = (t, e) => {
22
+ const s = [];
23
+ for (const n in t)
24
+ s.push(e(t[n], n));
25
+ return s;
26
+ }, O = (t) => X(t).length, Z = (t, e) => Object.prototype.hasOwnProperty.call(t, e), H = (t, e) => t === e, y = (t, e) => {
27
+ if (t == null || e == null)
28
+ return H(t, e);
29
+ if (t.constructor !== e.constructor)
30
+ return !1;
31
+ if (t === e)
32
+ return !0;
33
+ switch (t.constructor) {
34
+ case ArrayBuffer:
35
+ t = new Uint8Array(t), e = new Uint8Array(e);
36
+ case Uint8Array: {
37
+ if (t.byteLength !== e.byteLength)
38
+ return !1;
39
+ for (let s = 0; s < t.length; s++)
40
+ if (t[s] !== e[s])
41
+ return !1;
42
+ break;
43
+ }
44
+ case Set: {
45
+ if (t.size !== e.size)
46
+ return !1;
47
+ for (const s of t)
48
+ if (!e.has(s))
49
+ return !1;
50
+ break;
51
+ }
52
+ case Map: {
53
+ if (t.size !== e.size)
54
+ return !1;
55
+ for (const s of t.keys())
56
+ if (!e.has(s) || !y(t.get(s), e.get(s)))
57
+ return !1;
58
+ break;
59
+ }
60
+ case Object:
61
+ if (O(t) !== O(e))
62
+ return !1;
63
+ for (const s in t)
64
+ if (!Z(t, s) || !y(t[s], e[s]))
65
+ return !1;
66
+ break;
67
+ case Array:
68
+ if (t.length !== e.length)
69
+ return !1;
70
+ for (let s = 0; s < t.length; s++)
71
+ if (!y(t[s], e[s]))
72
+ return !1;
73
+ break;
74
+ default:
75
+ return !1;
76
+ }
77
+ return !0;
78
+ }, Lt = (t, e) => e.includes(t), V = Math.floor, Q = (t, e) => t < e ? t : e, tt = (t, e) => t > e ? t : e, Ot = Math.pow, M = 128, b = 127, et = Number.MAX_SAFE_INTEGER, Dt = Number.parseInt;
79
+ class st {
80
+ constructor() {
81
+ this.cpos = 0, this.cbuf = new Uint8Array(100), this.bufs = [];
82
+ }
83
+ }
84
+ const nt = () => new st(), ot = (t) => {
85
+ let e = t.cpos;
86
+ for (let s = 0; s < t.bufs.length; s++)
87
+ e += t.bufs[s].length;
88
+ return e;
89
+ }, rt = (t) => {
90
+ const e = new Uint8Array(ot(t));
91
+ let s = 0;
92
+ for (let n = 0; n < t.bufs.length; n++) {
93
+ const o = t.bufs[n];
94
+ e.set(o, s), s += o.length;
95
+ }
96
+ return e.set(new Uint8Array(t.cbuf.buffer, 0, t.cpos), s), e;
97
+ }, w = (t, e) => {
98
+ const s = t.cbuf.length;
99
+ t.cpos === s && (t.bufs.push(t.cbuf), t.cbuf = new Uint8Array(s * 2), t.cpos = 0), t.cbuf[t.cpos++] = e;
100
+ }, l = (t, e) => {
101
+ for (; e > b; )
102
+ w(t, M | b & e), e = V(e / 128);
103
+ w(t, b & e);
104
+ }, E = new Uint8Array(3e4), ct = E.length / 3, at = (t, e) => {
105
+ if (e.length < ct) {
106
+ const s = S.encodeInto(e, E).written || 0;
107
+ l(t, s);
108
+ for (let n = 0; n < s; n++)
109
+ w(t, E[n]);
110
+ } else
111
+ _(t, K(e));
112
+ }, it = (t, e) => {
113
+ const s = unescape(encodeURIComponent(e)), n = s.length;
114
+ l(t, n);
115
+ for (let o = 0; o < n; o++)
116
+ w(
117
+ t,
118
+ /** @type {number} */
119
+ s.codePointAt(o)
120
+ );
121
+ }, lt = S && /** @type {any} */
122
+ S.encodeInto ? at : it, ft = (t, e) => {
123
+ const s = t.cbuf.length, n = t.cpos, o = Q(s - n, e.length), r = e.length - o;
124
+ t.cbuf.set(e.subarray(0, o), n), t.cpos += o, r > 0 && (t.bufs.push(t.cbuf), t.cbuf = new Uint8Array(tt(s * 2, r)), t.cbuf.set(e.subarray(o)), t.cpos = r);
125
+ }, _ = (t, e) => {
126
+ l(t, e.byteLength), ft(t, e);
127
+ }, P = (t) => new Error(t), ut = P("Unexpected end of array"), ht = P("Integer out of Range");
128
+ class pt {
129
+ /**
130
+ * @param {Uint8Array} uint8Array Binary data to decode
131
+ */
132
+ constructor(e) {
133
+ this.arr = e, this.pos = 0;
134
+ }
135
+ }
136
+ const dt = (t) => new pt(t), gt = (t, e) => {
137
+ const s = new Uint8Array(t.arr.buffer, t.pos + t.arr.byteOffset, e);
138
+ return t.pos += e, s;
139
+ }, C = (t) => gt(t, d(t)), D = (t) => t.arr[t.pos++], d = (t) => {
140
+ let e = 0, s = 1;
141
+ const n = t.arr.length;
142
+ for (; t.pos < n; ) {
143
+ const o = t.arr[t.pos++];
144
+ if (e = e + (o & b) * s, s *= 128, o < M)
145
+ return e;
146
+ if (e > et)
147
+ throw ht;
148
+ }
149
+ throw ut;
150
+ }, yt = (t) => {
151
+ let e = d(t);
152
+ if (e === 0)
153
+ return "";
154
+ {
155
+ let s = String.fromCodePoint(D(t));
156
+ if (--e < 100)
157
+ for (; e--; )
158
+ s += String.fromCodePoint(D(t));
159
+ else
160
+ for (; e > 0; ) {
161
+ const n = e < 1e4 ? e : 1e4, o = t.arr.subarray(t.pos, t.pos + n);
162
+ t.pos += n, s += String.fromCodePoint.apply(
163
+ null,
164
+ /** @type {any} */
165
+ o
166
+ ), e -= n;
167
+ }
168
+ return decodeURIComponent(escape(s));
169
+ }
170
+ }, St = (t) => (
171
+ /** @type any */
172
+ g.decode(C(t))
173
+ ), mt = g ? St : yt, v = Date.now, R = 0, B = 1, z = 2, Tt = (t, e) => {
174
+ l(t, R);
175
+ const s = I.encodeStateVector(e);
176
+ _(t, s);
177
+ }, Ut = (t, e, s) => {
178
+ l(t, B), _(t, I.encodeStateAsUpdate(e, s));
179
+ }, bt = (t, e, s) => Ut(e, s, C(t)), j = (t, e, s) => {
180
+ try {
181
+ I.applyUpdate(e, C(t), s);
182
+ } catch (n) {
183
+ console.error("Caught error while handling a Yjs update", n);
184
+ }
185
+ }, Nt = (t, e) => {
186
+ l(t, z), _(t, e);
187
+ }, wt = j, xt = (t, e, s, n) => {
188
+ const o = d(t);
189
+ switch (o) {
190
+ case R:
191
+ bt(t, e, s);
192
+ break;
193
+ case B:
194
+ j(t, s, n);
195
+ break;
196
+ case z:
197
+ wt(t, s, n);
198
+ break;
199
+ default:
200
+ throw new Error("Unknown message type");
201
+ }
202
+ return o;
203
+ };
204
+ class Vt {
205
+ constructor() {
206
+ this._observers = p();
207
+ }
208
+ /**
209
+ * @template {keyof EVENTS & string} NAME
210
+ * @param {NAME} name
211
+ * @param {EVENTS[NAME]} f
212
+ */
213
+ on(e, s) {
214
+ return T(
215
+ this._observers,
216
+ /** @type {string} */
217
+ e,
218
+ N
219
+ ).add(s), s;
220
+ }
221
+ /**
222
+ * @template {keyof EVENTS & string} NAME
223
+ * @param {NAME} name
224
+ * @param {EVENTS[NAME]} f
225
+ */
226
+ once(e, s) {
227
+ const n = (...o) => {
228
+ this.off(
229
+ e,
230
+ /** @type {any} */
231
+ n
232
+ ), s(...o);
233
+ };
234
+ this.on(
235
+ e,
236
+ /** @type {any} */
237
+ n
238
+ );
239
+ }
240
+ /**
241
+ * @template {keyof EVENTS & string} NAME
242
+ * @param {NAME} name
243
+ * @param {EVENTS[NAME]} f
244
+ */
245
+ off(e, s) {
246
+ const n = this._observers.get(e);
247
+ n !== void 0 && (n.delete(s), n.size === 0 && this._observers.delete(e));
248
+ }
249
+ /**
250
+ * Emit a named event. All registered event listeners that listen to the
251
+ * specified name will receive the event.
252
+ *
253
+ * @todo This should catch exceptions
254
+ *
255
+ * @template {keyof EVENTS & string} NAME
256
+ * @param {NAME} name The event name.
257
+ * @param {Parameters<EVENTS[NAME]>} args The arguments that are applied to the event listener.
258
+ */
259
+ emit(e, s) {
260
+ return x((this._observers.get(e) || p()).values()).forEach((n) => n(...s));
261
+ }
262
+ destroy() {
263
+ this._observers = p();
264
+ }
265
+ }
266
+ class vt {
267
+ constructor() {
268
+ this._observers = p();
269
+ }
270
+ /**
271
+ * @param {N} name
272
+ * @param {function} f
273
+ */
274
+ on(e, s) {
275
+ T(this._observers, e, N).add(s);
276
+ }
277
+ /**
278
+ * @param {N} name
279
+ * @param {function} f
280
+ */
281
+ once(e, s) {
282
+ const n = (...o) => {
283
+ this.off(e, n), s(...o);
284
+ };
285
+ this.on(e, n);
286
+ }
287
+ /**
288
+ * @param {N} name
289
+ * @param {function} f
290
+ */
291
+ off(e, s) {
292
+ const n = this._observers.get(e);
293
+ n !== void 0 && (n.delete(s), n.size === 0 && this._observers.delete(e));
294
+ }
295
+ /**
296
+ * Emit a named event. All registered event listeners that listen to the
297
+ * specified name will receive the event.
298
+ *
299
+ * @todo This should catch exceptions
300
+ *
301
+ * @param {N} name The event name.
302
+ * @param {Array<any>} args The arguments that are applied to the event listener.
303
+ */
304
+ emit(e, s) {
305
+ return x((this._observers.get(e) || p()).values()).forEach((n) => n(...s));
306
+ }
307
+ destroy() {
308
+ this._observers = p();
309
+ }
310
+ }
311
+ const A = 3e4;
312
+ class Mt extends vt {
313
+ /**
314
+ * @param {Y.Doc} doc
315
+ */
316
+ constructor(e) {
317
+ super(), this.doc = e, this.clientID = e.clientID, this.states = /* @__PURE__ */ new Map(), this.meta = /* @__PURE__ */ new Map(), this._checkInterval = /** @type {any} */
318
+ setInterval(() => {
319
+ const s = v();
320
+ this.getLocalState() !== null && A / 2 <= s - /** @type {{lastUpdated:number}} */
321
+ this.meta.get(this.clientID).lastUpdated && this.setLocalState(this.getLocalState());
322
+ const n = [];
323
+ this.meta.forEach((o, r) => {
324
+ r !== this.clientID && A <= s - o.lastUpdated && this.states.has(r) && n.push(r);
325
+ }), n.length > 0 && _t(this, n, "timeout");
326
+ }, V(A / 10)), e.on("destroy", () => {
327
+ this.destroy();
328
+ }), this.setLocalState({});
329
+ }
330
+ destroy() {
331
+ this.emit("destroy", [this]), this.setLocalState(null), super.destroy(), clearInterval(this._checkInterval);
332
+ }
333
+ /**
334
+ * @return {Object<string,any>|null}
335
+ */
336
+ getLocalState() {
337
+ return this.states.get(this.clientID) || null;
338
+ }
339
+ /**
340
+ * @param {Object<string,any>|null} state
341
+ */
342
+ setLocalState(e) {
343
+ const s = this.clientID, n = this.meta.get(s), o = n === void 0 ? 0 : n.clock + 1, r = this.states.get(s);
344
+ e === null ? this.states.delete(s) : this.states.set(s, e), this.meta.set(s, {
345
+ clock: o,
346
+ lastUpdated: v()
347
+ });
348
+ const c = [], f = [], a = [], h = [];
349
+ e === null ? h.push(s) : r == null ? e != null && c.push(s) : (f.push(s), y(r, e) || a.push(s)), (c.length > 0 || a.length > 0 || h.length > 0) && this.emit("change", [{ added: c, updated: a, removed: h }, "local"]), this.emit("update", [{ added: c, updated: f, removed: h }, "local"]);
350
+ }
351
+ /**
352
+ * @param {string} field
353
+ * @param {any} value
354
+ */
355
+ setLocalStateField(e, s) {
356
+ const n = this.getLocalState();
357
+ n !== null && this.setLocalState({
358
+ ...n,
359
+ [e]: s
360
+ });
361
+ }
362
+ /**
363
+ * @return {Map<number,Object<string,any>>}
364
+ */
365
+ getStates() {
366
+ return this.states;
367
+ }
368
+ }
369
+ const _t = (t, e, s) => {
370
+ const n = [];
371
+ for (let o = 0; o < e.length; o++) {
372
+ const r = e[o];
373
+ if (t.states.has(r)) {
374
+ if (t.states.delete(r), r === t.clientID) {
375
+ const c = (
376
+ /** @type {MetaClientState} */
377
+ t.meta.get(r)
378
+ );
379
+ t.meta.set(r, {
380
+ clock: c.clock + 1,
381
+ lastUpdated: v()
382
+ });
383
+ }
384
+ n.push(r);
385
+ }
386
+ }
387
+ n.length > 0 && (t.emit("change", [{ added: [], updated: [], removed: n }, s]), t.emit("update", [{ added: [], updated: [], removed: n }, s]));
388
+ }, Pt = (t, e, s = t.states) => {
389
+ const n = e.length, o = nt();
390
+ l(o, n);
391
+ for (let r = 0; r < n; r++) {
392
+ const c = e[r], f = s.get(c) || null, a = (
393
+ /** @type {MetaClientState} */
394
+ t.meta.get(c).clock
395
+ );
396
+ l(o, c), l(o, a), lt(o, JSON.stringify(f));
397
+ }
398
+ return rt(o);
399
+ }, Rt = (t, e, s) => {
400
+ const n = dt(e), o = v(), r = [], c = [], f = [], a = [], h = d(n);
401
+ for (let k = 0; k < h; k++) {
402
+ const i = d(n);
403
+ let m = d(n);
404
+ const u = JSON.parse(mt(n)), U = t.meta.get(i), W = t.states.get(i), L = U === void 0 ? 0 : U.clock;
405
+ (L < m || L === m && u === null && t.states.has(i)) && (u === null ? i === t.clientID && t.getLocalState() != null ? m++ : t.states.delete(i) : t.states.set(i, u), t.meta.set(i, {
406
+ clock: m,
407
+ lastUpdated: o
408
+ }), U === void 0 && u !== null ? r.push(i) : U !== void 0 && u === null ? a.push(i) : u !== null && (y(u, W) || f.push(i), c.push(i)));
409
+ }
410
+ (r.length > 0 || f.length > 0 || a.length > 0) && t.emit("change", [{
411
+ added: r,
412
+ updated: f,
413
+ removed: a
414
+ }, s]), (r.length > 0 || c.length > 0 || a.length > 0) && t.emit("update", [{
415
+ added: r,
416
+ updated: c,
417
+ removed: a
418
+ }, s]);
419
+ };
420
+ export {
421
+ Mt as A,
422
+ C as B,
423
+ Et as C,
424
+ Dt as D,
425
+ Vt as O,
426
+ At as W,
427
+ It as a,
428
+ N as b,
429
+ p as c,
430
+ mt as d,
431
+ Tt as e,
432
+ Ct as f,
433
+ Nt as g,
434
+ _ as h,
435
+ Lt as i,
436
+ Pt as j,
437
+ _t as k,
438
+ ot as l,
439
+ kt as m,
440
+ v as n,
441
+ Ut as o,
442
+ nt as p,
443
+ dt as q,
444
+ d as r,
445
+ T as s,
446
+ rt as t,
447
+ Q as u,
448
+ Ot as v,
449
+ l as w,
450
+ xt as x,
451
+ B as y,
452
+ Rt as z
453
+ };
Binary file
@@ -0,0 +1,2 @@
1
+ "use strict";var j=Object.defineProperty;var F=(e,s,t)=>s in e?j(e,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[s]=t;var f=(e,s,t)=>(F(e,typeof s!="symbol"?s+"":s,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const K=require("@inditextech/weave-sdk"),n=require("./awareness-BgEfnEJw.cjs");require("yjs");const T=e=>e===void 0?null:e;class ${constructor(){this.map=new Map}setItem(s,t){this.map.set(s,t)}getItem(s){return this.map.get(s)}}let V=new $,_=!0;try{typeof localStorage<"u"&&localStorage&&(V=localStorage,_=!1)}catch{}const B=V,q=e=>_||addEventListener("storage",e),Q=e=>_||removeEventListener("storage",e),h=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",I=typeof window<"u"&&typeof document<"u"&&!h;let r;const Y=()=>{if(r===void 0)if(h){r=n.create();const e=process.argv;let s=null;for(let t=0;t<e.length;t++){const c=e[t];c[0]==="-"?(s!==null&&r.set(s,""),s=c):s!==null&&(r.set(s,c),s=null)}s!==null&&r.set(s,"")}else typeof location=="object"?(r=n.create(),(location.search||"?").slice(1).split("&").forEach(e=>{if(e.length!==0){const[s,t]=e.split("=");r.set(`--${n.fromCamelCase(s,"-")}`,t),r.set(`-${n.fromCamelCase(s,"-")}`,t)}})):r=n.create();return r},U=e=>Y().has(e),A=e=>T(h?process.env[e.toUpperCase().replaceAll("-","_")]:B.getItem(e)),W=e=>U("--"+e)||A(e)!==null;W("production");const z=h&&n.isOneOf(process.env.FORCE_COLOR,["true","1","2"]);z||!U("--no-colors")&&!W("no-color")&&(!h||process.stdout.isTTY)&&(!h||U("--color")||A("COLORTERM")!==null||(A("TERM")||"").includes("color"));const G=e=>new Uint8Array(e),J=(e,s,t)=>new Uint8Array(e,s,t),X=e=>new Uint8Array(e),Z=e=>{let s="";for(let t=0;t<e.byteLength;t++)s+=n.fromCharCode(e[t]);return btoa(s)},v=e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),ee=e=>{const s=atob(e),t=G(s.length);for(let c=0;c<s.length;c++)t[c]=s.charCodeAt(c);return t},se=e=>{const s=Buffer.from(e,"base64");return J(s.buffer,s.byteOffset,s.byteLength)},te=I?Z:v,ne=I?ee:se,R=new Map;class ce{constructor(s){this.room=s,this.onmessage=null,this._onChange=t=>t.key===s&&this.onmessage!==null&&this.onmessage({data:ne(t.newValue||"")}),q(this._onChange)}postMessage(s){B.setItem(this.room,te(X(s)))}close(){Q(this._onChange)}}const ae=typeof BroadcastChannel>"u"?ce:BroadcastChannel,C=e=>n.setIfUndefined(R,e,()=>{const s=n.create$1(),t=new ae(e);return t.onmessage=c=>s.forEach(a=>a(c.data,"broadcastchannel")),{bc:t,subs:s}}),oe=(e,s)=>(C(e).subs.add(s),s),re=(e,s)=>{const t=C(e),c=t.subs.delete(s);return c&&t.subs.size===0&&(t.bc.close(),R.delete(e)),c},w=(e,s,t=null)=>{const c=C(e);c.bc.postMessage(s),c.subs.forEach(a=>a(s,t))},ie=0,le=(e,s,t)=>{switch(n.readVarUint(e)){case ie:t(s,n.readVarString(e))}},he=e=>n.map(e,(s,t)=>`${encodeURIComponent(t)}=${encodeURIComponent(s)}`).join("&"),d=0,k=3,y=1,de=2,m=[];m[d]=(e,s,t,c,a)=>{n.writeVarUint(e,d);const o=n.readSyncMessage(s,e,t.doc,t);c&&o===n.messageYjsSyncStep2&&!t.synced&&(t.synced=!0)};m[k]=(e,s,t,c,a)=>{n.writeVarUint(e,y),n.writeVarUint8Array(e,n.encodeAwarenessUpdate(t.awareness,Array.from(t.awareness.getStates().keys())))};m[y]=(e,s,t,c,a)=>{n.applyAwarenessUpdate(t.awareness,n.readVarUint8Array(s),t)};m[de]=(e,s,t,c,a)=>{le(s,t.doc,(o,u)=>ue(t,u))};const O=3e4,ue=(e,s)=>console.warn(`Permission denied to access ${e.url}.
2
+ ${s}`),M=(e,s,t)=>{const c=n.createDecoder(s),a=n.createEncoder(),o=n.readVarUint(c),u=e.messageHandlers[o];return u?u(a,c,e,t,o):console.error("Unable to compute message"),a},p=(e,s,t)=>{s===e.ws&&(e.emit("connection-close",[t,e]),e.ws=null,s.close(),e.wsconnecting=!1,e.wsconnected?(e.wsconnected=!1,e.synced=!1,n.removeAwarenessStates(e.awareness,Array.from(e.awareness.getStates().keys()).filter(c=>c!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])):e.wsUnsuccessfulReconnects++,setTimeout(L,n.min(n.pow(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e))},L=e=>{if(e.shouldConnect&&e.ws===null){const s=new e._WS(e.url,e.protocols);s.binaryType="arraybuffer",e.ws=s,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,s.onmessage=t=>{e.wsLastMessageReceived=n.getUnixTime();const c=M(e,new Uint8Array(t.data),!0);n.length(c)>1&&s.send(n.toUint8Array(c))},s.onerror=t=>{e.emit("connection-error",[t,e])},s.onclose=t=>{p(e,s,t)},s.onopen=()=>{e.wsLastMessageReceived=n.getUnixTime(),e.wsconnecting=!1,e.wsconnected=!0,e.wsUnsuccessfulReconnects=0,e.emit("status",[{status:"connected"}]);const t=n.createEncoder();if(n.writeVarUint(t,d),n.writeSyncStep1(t,e.doc),s.send(n.toUint8Array(t)),e.awareness.getLocalState()!==null){const c=n.createEncoder();n.writeVarUint(c,y),n.writeVarUint8Array(c,n.encodeAwarenessUpdate(e.awareness,[e.doc.clientID])),s.send(n.toUint8Array(c))}},e.emit("status",[{status:"connecting"}])}},S=(e,s)=>{const t=e.ws;e.wsconnected&&t&&t.readyState===t.OPEN&&t.send(s),e.bcconnected&&w(e.bcChannel,s,e)};class fe extends n.ObservableV2{constructor(s,t,c,{connect:a=!0,awareness:o=new n.Awareness(c),params:u={},protocols:H=[],WebSocketPolyfill:P=WebSocket,resyncInterval:E=-1,maxBackoffTime:N=2500,disableBc:x=!1}={}){for(super();s[s.length-1]==="/";)s=s.slice(0,s.length-1);this.serverUrl=s,this.bcChannel=s+"/"+t,this.maxBackoffTime=N,this.params=u,this.protocols=H,this.roomname=t,this.doc=c,this._WS=P,this.awareness=o,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=x,this.wsUnsuccessfulReconnects=0,this.messageHandlers=m.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=a,this._resyncInterval=0,E>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const i=n.createEncoder();n.writeVarUint(i,d),n.writeSyncStep1(i,c),this.ws.send(n.toUint8Array(i))}},E)),this._bcSubscriber=(i,g)=>{if(g!==this){const l=M(this,new Uint8Array(i),!1);n.length(l)>1&&w(this.bcChannel,n.toUint8Array(l),this)}},this._updateHandler=(i,g)=>{if(g!==this){const l=n.createEncoder();n.writeVarUint(l,d),n.writeUpdate(l,i),S(this,n.toUint8Array(l))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:i,updated:g,removed:l},ye)=>{const D=i.concat(g).concat(l),b=n.createEncoder();n.writeVarUint(b,y),n.writeVarUint8Array(b,n.encodeAwarenessUpdate(o,D)),S(this,n.toUint8Array(b))},this._exitHandler=()=>{n.removeAwarenessStates(this.awareness,[c.clientID],"app closed")},h&&typeof process<"u"&&process.on("exit",this._exitHandler),o.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&O<n.getUnixTime()-this.wsLastMessageReceived&&p(this,this.ws,null)},O/10),a&&this.connect()}get url(){const s=he(this.params);return this.serverUrl+"/"+this.roomname+(s.length===0?"":"?"+s)}get synced(){return this._synced}set synced(s){this._synced!==s&&(this._synced=s,this.emit("synced",[s]),this.emit("sync",[s]))}destroy(){this._resyncInterval!==0&&clearInterval(this._resyncInterval),clearInterval(this._checkInterval),this.disconnect(),h&&typeof process<"u"&&process.off("exit",this._exitHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.doc.off("update",this._updateHandler),super.destroy()}connectBc(){if(this.disableBc)return;this.bcconnected||(oe(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);const s=n.createEncoder();n.writeVarUint(s,d),n.writeSyncStep1(s,this.doc),w(this.bcChannel,n.toUint8Array(s),this);const t=n.createEncoder();n.writeVarUint(t,d),n.writeSyncStep2(t,this.doc),w(this.bcChannel,n.toUint8Array(t),this);const c=n.createEncoder();n.writeVarUint(c,k),w(this.bcChannel,n.toUint8Array(c),this);const a=n.createEncoder();n.writeVarUint(a,y),n.writeVarUint8Array(a,n.encodeAwarenessUpdate(this.awareness,[this.doc.clientID])),w(this.bcChannel,n.toUint8Array(a),this)}disconnectBc(){const s=n.createEncoder();n.writeVarUint(s,y),n.writeVarUint8Array(s,n.encodeAwarenessUpdate(this.awareness,[this.doc.clientID],new Map)),S(this,n.toUint8Array(s)),this.bcconnected&&(re(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&p(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(L(this),this.connectBc())}}class we extends K.WeaveStore{constructor(t,c){super(t);f(this,"websocketOptions");f(this,"roomId");f(this,"provider");f(this,"name",n.WEAVE_STORE_WEBSOCKETS);f(this,"supportsUndoManager",!0);const{roomId:a}=c;this.websocketOptions=c,this.roomId=a,this.init()}init(){const{wsOptions:{serverUrl:t}}=this.websocketOptions;this.provider=new fe(t,this.roomId,this.getDocument(),{connect:!1,disableBc:!0}),this.provider.on("status",({status:c})=>{var a,o;(o=(a=this.websocketOptions.callbacks)==null?void 0:a.onConnectionStatusChange)==null||o.call(a,c),this.instance.emitEvent("onConnectionStatusChange",c)})}connect(){this.provider.connect()}disconnect(){this.provider.connect()}setAwarenessInfo(t,c){this.provider.awareness.setLocalStateField(t,c)}onAwarenessChange(t){const c=this.provider.awareness;c.on("change",()=>{const a=Array.from(c.getStates().values());a.splice(c.clientID,1),t(a)})}}exports.WEAVE_STORE_WEBSOCKETS=n.WEAVE_STORE_WEBSOCKETS;exports.WEAVE_STORE_WEBSOCKETS_CONNECTION_STATUS=n.WEAVE_STORE_WEBSOCKETS_CONNECTION_STATUS;exports.WeaveStoreWebsockets=we;
Binary file
@@ -0,0 +1,56 @@
1
+ import { IncomingMessage } from 'http';
2
+ import { WeaveAwarenessChange } from '@inditextech/weave-types';
3
+ import { WeaveStore } from '@inditextech/weave-sdk';
4
+ import { WeaveStoreOptions } from '@inditextech/weave-types';
5
+ import { WebsocketProvider } from 'y-websocket';
6
+ import * as Y from 'yjs';
7
+
8
+ export declare type ExtractRoomId = (req: IncomingMessage) => string | undefined;
9
+
10
+ export declare type FetchInitialState = (doc: Y.Doc) => void;
11
+
12
+ export declare type FetchRoom = (roomId: string) => Promise<Uint8Array | null>;
13
+
14
+ export declare type PerformUpgrade = (req: IncomingMessage) => Promise<boolean>;
15
+
16
+ export declare type PersistRoom = (roomId: string, actualState: Uint8Array<ArrayBufferLike>) => Promise<void>;
17
+
18
+ export declare const WEAVE_STORE_WEBSOCKETS = "store-websockets";
19
+
20
+ export declare const WEAVE_STORE_WEBSOCKETS_CONNECTION_STATUS: {
21
+ readonly CONNECTING: "connecting";
22
+ readonly CONNECTED: "connected";
23
+ readonly DISCONNECTED: "disconnected";
24
+ };
25
+
26
+ export declare class WeaveStoreWebsockets extends WeaveStore {
27
+ private websocketOptions;
28
+ private roomId;
29
+ protected provider: WebsocketProvider;
30
+ protected name: string;
31
+ protected supportsUndoManager: boolean;
32
+ constructor(storeOptions: WeaveStoreOptions, websocketOptions: WeaveStoreWebsocketsOptions);
33
+ private init;
34
+ connect(): void;
35
+ disconnect(): void;
36
+ setAwarenessInfo(field: string, value: unknown): void;
37
+ onAwarenessChange<K extends string, T>(callback: (changes: WeaveAwarenessChange<K, T>[]) => void): void;
38
+ }
39
+
40
+ export declare type WeaveStoreWebsocketsCallbacks = {
41
+ onConnectionStatusChange?: (status: WeaveStoreWebsocketsConnectionStatus) => void;
42
+ };
43
+
44
+ export declare type WeaveStoreWebsocketsConnectionStatus = (typeof WEAVE_STORE_WEBSOCKETS_CONNECTION_STATUS)[WeaveStoreWebsocketsConnectionStatusKeys];
45
+
46
+ export declare type WeaveStoreWebsocketsConnectionStatusKeys = keyof typeof WEAVE_STORE_WEBSOCKETS_CONNECTION_STATUS;
47
+
48
+ export declare type WeaveStoreWebsocketsOptions = {
49
+ roomId: string;
50
+ wsOptions: {
51
+ serverUrl: string;
52
+ };
53
+ callbacks?: WeaveStoreWebsocketsCallbacks;
54
+ };
55
+
56
+ export { }