@1kbgz/transports 0.4.0 → 0.7.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,661 @@
1
+ // src/ts/bridge.ts
2
+ function toValue(v) {
3
+ if (v === null || v === void 0) return "Null";
4
+ if (typeof v === "boolean") return { Bool: v };
5
+ if (typeof v === "number")
6
+ return Number.isInteger(v) ? { Int: v } : { Float: v };
7
+ if (typeof v === "string") return { Str: v };
8
+ if (Array.isArray(v)) return { List: v.map(toValue) };
9
+ if (typeof v === "object") {
10
+ const m = {};
11
+ for (const [k, x] of Object.entries(v)) m[k] = toValue(x);
12
+ return { Map: m };
13
+ }
14
+ throw new TypeError(`unsupported value for transports: ${typeof v}`);
15
+ }
16
+ function fromValue(value) {
17
+ if (value === "Null") return null;
18
+ const [tag, inner] = Object.entries(value)[0];
19
+ switch (tag) {
20
+ case "Bool":
21
+ case "Int":
22
+ case "Float":
23
+ case "Str":
24
+ case "Submodel":
25
+ return inner;
26
+ case "List":
27
+ return inner.map(fromValue);
28
+ case "Map": {
29
+ const o = {};
30
+ for (const [k, x] of Object.entries(inner))
31
+ o[k] = fromValue(x);
32
+ return o;
33
+ }
34
+ default:
35
+ throw new Error(`unrecognized tagged value: ${JSON.stringify(value)}`);
36
+ }
37
+ }
38
+
39
+ // src/ts/codecs.ts
40
+ var registry = /* @__PURE__ */ new Map();
41
+ function codecFor(contentType) {
42
+ return registry.get(contentType);
43
+ }
44
+
45
+ // dist/pkg/transports.js
46
+ var Store = class {
47
+ __destroy_into_raw() {
48
+ const ptr = this.__wbg_ptr;
49
+ this.__wbg_ptr = 0;
50
+ StoreFinalization.unregister(this);
51
+ return ptr;
52
+ }
53
+ free() {
54
+ const ptr = this.__destroy_into_raw();
55
+ wasm.__wbg_store_free(ptr, 0);
56
+ }
57
+ /**
58
+ * Apply a JSON patch to a mirrored model; returns whether the id was known.
59
+ * @param {bigint} id
60
+ * @param {string} patch_json
61
+ * @returns {boolean}
62
+ */
63
+ apply(id, patch_json) {
64
+ const ptr0 = passStringToWasm0(patch_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
65
+ const len0 = WASM_VECTOR_LEN;
66
+ const ret = wasm.store_apply(this.__wbg_ptr, id, ptr0, len0);
67
+ if (ret[2]) {
68
+ throw takeFromExternrefTable0(ret[1]);
69
+ }
70
+ return ret[0] !== 0;
71
+ }
72
+ /**
73
+ * Host a model from its JSON; returns the assigned id.
74
+ * @param {string} type_name
75
+ * @param {string} value_json
76
+ * @returns {bigint}
77
+ */
78
+ host(type_name, value_json) {
79
+ const ptr0 = passStringToWasm0(type_name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
80
+ const len0 = WASM_VECTOR_LEN;
81
+ const ptr1 = passStringToWasm0(value_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
82
+ const len1 = WASM_VECTOR_LEN;
83
+ const ret = wasm.store_host(this.__wbg_ptr, ptr0, len0, ptr1, len1);
84
+ if (ret[2]) {
85
+ throw takeFromExternrefTable0(ret[1]);
86
+ }
87
+ return BigInt.asUintN(64, ret[0]);
88
+ }
89
+ /**
90
+ * Replace a hosted model from JSON; returns the JSON patch (or `undefined` if id unknown).
91
+ * @param {bigint} id
92
+ * @param {string} value_json
93
+ * @returns {string | undefined}
94
+ */
95
+ mutate(id, value_json) {
96
+ const ptr0 = passStringToWasm0(value_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
97
+ const len0 = WASM_VECTOR_LEN;
98
+ const ret = wasm.store_mutate(this.__wbg_ptr, id, ptr0, len0);
99
+ if (ret[3]) {
100
+ throw takeFromExternrefTable0(ret[2]);
101
+ }
102
+ let v2;
103
+ if (ret[0] !== 0) {
104
+ v2 = getStringFromWasm0(ret[0], ret[1]).slice();
105
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
106
+ }
107
+ return v2;
108
+ }
109
+ constructor() {
110
+ const ret = wasm.store_new();
111
+ this.__wbg_ptr = ret;
112
+ StoreFinalization.register(this, this.__wbg_ptr, this);
113
+ return this;
114
+ }
115
+ /**
116
+ * `{"type_name":..,"rev":..,"value":..}` for a hosted model, or `undefined`.
117
+ * @param {bigint} id
118
+ * @returns {string | undefined}
119
+ */
120
+ snapshot(id) {
121
+ const ret = wasm.store_snapshot(this.__wbg_ptr, id);
122
+ let v1;
123
+ if (ret[0] !== 0) {
124
+ v1 = getStringFromWasm0(ret[0], ret[1]).slice();
125
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
126
+ }
127
+ return v1;
128
+ }
129
+ };
130
+ if (Symbol.dispose) Store.prototype[Symbol.dispose] = Store.prototype.free;
131
+ function cbor_to_json(data) {
132
+ let deferred3_0;
133
+ let deferred3_1;
134
+ try {
135
+ const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
136
+ const len0 = WASM_VECTOR_LEN;
137
+ const ret = wasm.cbor_to_json(ptr0, len0);
138
+ var ptr2 = ret[0];
139
+ var len2 = ret[1];
140
+ if (ret[3]) {
141
+ ptr2 = 0;
142
+ len2 = 0;
143
+ throw takeFromExternrefTable0(ret[2]);
144
+ }
145
+ deferred3_0 = ptr2;
146
+ deferred3_1 = len2;
147
+ return getStringFromWasm0(ptr2, len2);
148
+ } finally {
149
+ wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
150
+ }
151
+ }
152
+ function diff(old, _new) {
153
+ let deferred4_0;
154
+ let deferred4_1;
155
+ try {
156
+ const ptr0 = passStringToWasm0(old, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
157
+ const len0 = WASM_VECTOR_LEN;
158
+ const ptr1 = passStringToWasm0(_new, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
159
+ const len1 = WASM_VECTOR_LEN;
160
+ const ret = wasm.diff(ptr0, len0, ptr1, len1);
161
+ var ptr3 = ret[0];
162
+ var len3 = ret[1];
163
+ if (ret[3]) {
164
+ ptr3 = 0;
165
+ len3 = 0;
166
+ throw takeFromExternrefTable0(ret[2]);
167
+ }
168
+ deferred4_0 = ptr3;
169
+ deferred4_1 = len3;
170
+ return getStringFromWasm0(ptr3, len3);
171
+ } finally {
172
+ wasm.__wbindgen_free(deferred4_0, deferred4_1, 1);
173
+ }
174
+ }
175
+ function json_to_cbor(json) {
176
+ const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
177
+ const len0 = WASM_VECTOR_LEN;
178
+ const ret = wasm.json_to_cbor(ptr0, len0);
179
+ if (ret[3]) {
180
+ throw takeFromExternrefTable0(ret[2]);
181
+ }
182
+ var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
183
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
184
+ return v2;
185
+ }
186
+ function json_to_msgpack(json) {
187
+ const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
188
+ const len0 = WASM_VECTOR_LEN;
189
+ const ret = wasm.json_to_msgpack(ptr0, len0);
190
+ if (ret[3]) {
191
+ throw takeFromExternrefTable0(ret[2]);
192
+ }
193
+ var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
194
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
195
+ return v2;
196
+ }
197
+ function msgpack_to_json(data) {
198
+ let deferred3_0;
199
+ let deferred3_1;
200
+ try {
201
+ const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
202
+ const len0 = WASM_VECTOR_LEN;
203
+ const ret = wasm.msgpack_to_json(ptr0, len0);
204
+ var ptr2 = ret[0];
205
+ var len2 = ret[1];
206
+ if (ret[3]) {
207
+ ptr2 = 0;
208
+ len2 = 0;
209
+ throw takeFromExternrefTable0(ret[2]);
210
+ }
211
+ deferred3_0 = ptr2;
212
+ deferred3_1 = len2;
213
+ return getStringFromWasm0(ptr2, len2);
214
+ } finally {
215
+ wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
216
+ }
217
+ }
218
+ var StoreFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
219
+ }, unregister: () => {
220
+ } } : new FinalizationRegistry((ptr) => wasm.__wbg_store_free(ptr, 1));
221
+ function getArrayU8FromWasm0(ptr, len) {
222
+ ptr = ptr >>> 0;
223
+ return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
224
+ }
225
+ function getStringFromWasm0(ptr, len) {
226
+ return decodeText(ptr >>> 0, len);
227
+ }
228
+ var cachedUint8ArrayMemory0 = null;
229
+ function getUint8ArrayMemory0() {
230
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
231
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
232
+ }
233
+ return cachedUint8ArrayMemory0;
234
+ }
235
+ function passArray8ToWasm0(arg, malloc) {
236
+ const ptr = malloc(arg.length * 1, 1) >>> 0;
237
+ getUint8ArrayMemory0().set(arg, ptr / 1);
238
+ WASM_VECTOR_LEN = arg.length;
239
+ return ptr;
240
+ }
241
+ function passStringToWasm0(arg, malloc, realloc) {
242
+ if (realloc === void 0) {
243
+ const buf = cachedTextEncoder.encode(arg);
244
+ const ptr2 = malloc(buf.length, 1) >>> 0;
245
+ getUint8ArrayMemory0().subarray(ptr2, ptr2 + buf.length).set(buf);
246
+ WASM_VECTOR_LEN = buf.length;
247
+ return ptr2;
248
+ }
249
+ let len = arg.length;
250
+ let ptr = malloc(len, 1) >>> 0;
251
+ const mem = getUint8ArrayMemory0();
252
+ let offset = 0;
253
+ for (; offset < len; offset++) {
254
+ const code = arg.charCodeAt(offset);
255
+ if (code > 127) break;
256
+ mem[ptr + offset] = code;
257
+ }
258
+ if (offset !== len) {
259
+ if (offset !== 0) {
260
+ arg = arg.slice(offset);
261
+ }
262
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
263
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
264
+ const ret = cachedTextEncoder.encodeInto(arg, view);
265
+ offset += ret.written;
266
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
267
+ }
268
+ WASM_VECTOR_LEN = offset;
269
+ return ptr;
270
+ }
271
+ function takeFromExternrefTable0(idx) {
272
+ const value = wasm.__wbindgen_externrefs.get(idx);
273
+ wasm.__externref_table_dealloc(idx);
274
+ return value;
275
+ }
276
+ var cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
277
+ cachedTextDecoder.decode();
278
+ var MAX_SAFARI_DECODE_BYTES = 2146435072;
279
+ var numBytesDecoded = 0;
280
+ function decodeText(ptr, len) {
281
+ numBytesDecoded += len;
282
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
283
+ cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
284
+ cachedTextDecoder.decode();
285
+ numBytesDecoded = len;
286
+ }
287
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
288
+ }
289
+ var cachedTextEncoder = new TextEncoder();
290
+ if (!("encodeInto" in cachedTextEncoder)) {
291
+ cachedTextEncoder.encodeInto = function(arg, view) {
292
+ const buf = cachedTextEncoder.encode(arg);
293
+ view.set(buf);
294
+ return {
295
+ read: arg.length,
296
+ written: buf.length
297
+ };
298
+ };
299
+ }
300
+ var WASM_VECTOR_LEN = 0;
301
+ var wasm;
302
+
303
+ // src/ts/index.ts
304
+ var diff2 = (oldModel, newModel) => diff(oldModel, newModel);
305
+ var jsonToMsgpack = (json) => json_to_msgpack(json);
306
+ var msgpackToJson = (bytes) => msgpack_to_json(bytes);
307
+ var jsonToCbor = (json) => json_to_cbor(json);
308
+ var cborToJson = (bytes) => cbor_to_json(bytes);
309
+
310
+ // src/ts/client.ts
311
+ function mapValue(value) {
312
+ if (value && typeof value === "object" && "Map" in value && value.Map && typeof value.Map === "object" && !Array.isArray(value.Map))
313
+ return value.Map;
314
+ throw new Error("patch path expected a map");
315
+ }
316
+ function listValue(value) {
317
+ if (value && typeof value === "object" && "List" in value && Array.isArray(value.List))
318
+ return value.List;
319
+ throw new Error("patch path expected a list");
320
+ }
321
+ function updateAt(value, path, update) {
322
+ if (!path.length) return update(value);
323
+ const [segment, ...rest] = path;
324
+ if ("Key" in segment) {
325
+ const map = mapValue(value);
326
+ if (rest.length && !Object.prototype.hasOwnProperty.call(map, segment.Key))
327
+ throw new Error(
328
+ `patch path key ${JSON.stringify(segment.Key)} not found`
329
+ );
330
+ return {
331
+ Map: {
332
+ ...map,
333
+ [segment.Key]: updateAt(map[segment.Key], rest, update)
334
+ }
335
+ };
336
+ }
337
+ const list = listValue(value);
338
+ if (segment.Index < 0 || segment.Index >= list.length)
339
+ throw new Error(
340
+ `patch path index ${segment.Index} out of bounds (len ${list.length})`
341
+ );
342
+ const next = [...list];
343
+ next[segment.Index] = updateAt(next[segment.Index], rest, update);
344
+ return { List: next };
345
+ }
346
+ function applyOp(value, op) {
347
+ if ("Set" in op) return updateAt(value, op.Set.path, () => op.Set.value);
348
+ if ("Remove" in op) {
349
+ const { path } = op.Remove;
350
+ const segment = path[path.length - 1];
351
+ if (!segment || !("Key" in segment))
352
+ throw new Error("remove path must end in a map key");
353
+ return updateAt(value, path.slice(0, -1), (container) => {
354
+ const map = { ...mapValue(container) };
355
+ delete map[segment.Key];
356
+ return { Map: map };
357
+ });
358
+ }
359
+ if ("Insert" in op) {
360
+ const { path, index, value: inserted } = op.Insert;
361
+ return updateAt(value, path, (container) => {
362
+ const list = listValue(container);
363
+ if (index < 0 || index > list.length)
364
+ throw new Error(
365
+ `insert index ${index} out of bounds (len ${list.length})`
366
+ );
367
+ const next = [...list];
368
+ next.splice(index, 0, inserted);
369
+ return { List: next };
370
+ });
371
+ }
372
+ if ("RemoveAt" in op) {
373
+ const { path, index } = op.RemoveAt;
374
+ return updateAt(value, path, (container) => {
375
+ const list = listValue(container);
376
+ if (index < 0 || index >= list.length)
377
+ throw new Error(
378
+ `remove index ${index} out of bounds (len ${list.length})`
379
+ );
380
+ const next = [...list];
381
+ next.splice(index, 1);
382
+ return { List: next };
383
+ });
384
+ }
385
+ throw new Error("unknown patch op");
386
+ }
387
+ function applyPatch(value, patch) {
388
+ let next = value;
389
+ for (const op of patch.ops) next = applyOp(next, op);
390
+ return next;
391
+ }
392
+ var Client = class {
393
+ constructor(codec = "json") {
394
+ this.codec = codec;
395
+ }
396
+ codec;
397
+ values = /* @__PURE__ */ new Map();
398
+ revs = /* @__PURE__ */ new Map();
399
+ changeListeners = [];
400
+ rejectListeners = [];
401
+ /** Register a listener fired when the server refuses a proposed edit, with the decoded `reject`
402
+ * frame (model id, the server's current rev, and the validation error). The mirror itself reverts
403
+ * via the authoritative snapshot the server sends alongside. Returns an unsubscribe function.
404
+ */
405
+ onReject(listener) {
406
+ this.rejectListeners.push(listener);
407
+ return () => {
408
+ const i = this.rejectListeners.indexOf(listener);
409
+ if (i >= 0) this.rejectListeners.splice(i, 1);
410
+ };
411
+ }
412
+ /** Register a listener fired after each accepted snapshot or patch — the same `ReceiveChange`
413
+ * `recv` returns — so `connect`/`run`/`connectSSE` consumers get path-level changes without
414
+ * managing the socket themselves. Not fired for ignored frames (stale revision, unknown message
415
+ * type). Returns an unsubscribe function. A listener exception propagates to the `recv` caller;
416
+ * the mirror has already updated by then.
417
+ */
418
+ onChange(listener) {
419
+ this.changeListeners.push(listener);
420
+ return () => {
421
+ const i = this.changeListeners.indexOf(listener);
422
+ if (i >= 0) this.changeListeners.splice(i, 1);
423
+ };
424
+ }
425
+ accepted(change) {
426
+ for (const listener of [...this.changeListeners]) listener(change);
427
+ return change;
428
+ }
429
+ /** Apply an inbound snapshot or patch frame to the mirror.
430
+ *
431
+ * Decodes by the client's codec: a registered custom codec, else built-in JSON (text) / msgpack
432
+ * (binary). Returns the accepted change so reactive adapters can update only its paths; returns
433
+ * `undefined` for a patch whose revision was already applied, and for an unrecognized message
434
+ * type — ignored, not an error, so a newer server can add message types without breaking older
435
+ * clients. The returned change and values from `value()` share immutable branches with the
436
+ * mirror; consumers must not mutate them. Invalid frames throw without changing the mirror or its
437
+ * accepted revision.
438
+ */
439
+ recv(data) {
440
+ const custom = codecFor(this.codec);
441
+ let msg;
442
+ if (custom) {
443
+ msg = custom.decode(data);
444
+ } else if (typeof data === "string") {
445
+ msg = JSON.parse(data);
446
+ } else {
447
+ msg = JSON.parse(
448
+ this.codec === "cbor" ? cborToJson(data) : msgpackToJson(data)
449
+ );
450
+ }
451
+ if (msg.t === "snapshot") {
452
+ this.values.set(msg.id, msg.value);
453
+ this.revs.set(msg.id, msg.rev);
454
+ return this.accepted({ t: "snapshot", id: msg.id, rev: msg.rev });
455
+ } else if (msg.t === "patch") {
456
+ const seen = this.revs.get(msg.id);
457
+ if (seen !== void 0 && msg.patch.rev <= seen) return void 0;
458
+ const current = this.values.get(msg.id);
459
+ if (current === void 0)
460
+ throw new Error(`patch received before snapshot for model ${msg.id}`);
461
+ this.values.set(msg.id, applyPatch(current, msg.patch));
462
+ this.revs.set(msg.id, msg.patch.rev);
463
+ return this.accepted(msg);
464
+ } else if (msg.t === "reject") {
465
+ for (const listener of [...this.rejectListeners]) listener(msg);
466
+ return void 0;
467
+ }
468
+ return void 0;
469
+ }
470
+ /** The current mirrored core `Value` of a model. */
471
+ value(id) {
472
+ return this.values.get(id);
473
+ }
474
+ ids() {
475
+ return [...this.values.keys()];
476
+ }
477
+ /** Propose an edit to a mirrored model; returns the patch frame to send (encoded in this codec).
478
+ *
479
+ * Server-authoritative: the local mirror updates when the server echoes the authoritative patch
480
+ * back via `recv`, not optimistically.
481
+ */
482
+ edit(id, value) {
483
+ const patch = JSON.parse(
484
+ diff2(JSON.stringify(this.values.get(id)), JSON.stringify(value))
485
+ );
486
+ const msg = { t: "patch", id, patch };
487
+ const custom = codecFor(this.codec);
488
+ if (custom) return custom.encode(msg);
489
+ const s = JSON.stringify(msg);
490
+ if (this.codec === "msgpack") return jsonToMsgpack(s);
491
+ if (this.codec === "cbor") return jsonToCbor(s);
492
+ return s;
493
+ }
494
+ /** Connect to a transports server and mirror it. Returns the `WebSocket`.
495
+ *
496
+ * On a reconnect (this client already mirrors models) it appends `?since=` with its last-seen rev per
497
+ * model, so the server replays only the delta instead of re-sending each whole model.
498
+ */
499
+ connect(url) {
500
+ const sep = url.includes("?") ? "&" : "?";
501
+ let params = `codec=${this.codec}`;
502
+ if (this.revs.size) {
503
+ const since = encodeURIComponent(
504
+ JSON.stringify(Object.fromEntries(this.revs))
505
+ );
506
+ params += `&since=${since}`;
507
+ }
508
+ const ws = new WebSocket(`${url}${sep}${params}`);
509
+ ws.binaryType = "arraybuffer";
510
+ ws.addEventListener("message", (e) => {
511
+ const data = e.data;
512
+ this.recv(
513
+ typeof data === "string" ? data : new Uint8Array(data)
514
+ );
515
+ });
516
+ return ws;
517
+ }
518
+ /** Connect and mirror, **reconnecting** whenever the socket drops — so the client survives a server
519
+ * restart or a refresh. `authority` decides reconciliation on each (re)connect:
520
+ *
521
+ * - `"server"` (default): the server is canonical; the client adopts its state (resuming via `?since=`
522
+ * when it can, else a fresh snapshot) — the "refetch on refresh" behavior.
523
+ * - `"client"`: the client is canonical; after the server's snapshot it pushes its last-known state
524
+ * back as an edit, rectifying a server that came back stale/empty (merges under a CRDT, else
525
+ * overwrites).
526
+ *
527
+ * `onMessage` fires after each applied frame (e.g. to re-render). Returns `{ stop() }`.
528
+ */
529
+ run(url, opts = {}) {
530
+ const { authority = "server", retry = 1e3, onMessage } = opts;
531
+ let stopped = false;
532
+ const loop = () => {
533
+ if (stopped) return;
534
+ const pre = authority === "client" ? new Map(this.values) : null;
535
+ const pushed = /* @__PURE__ */ new Set();
536
+ const ws = this.connect(url);
537
+ ws.addEventListener("message", () => {
538
+ onMessage?.();
539
+ if (pre) {
540
+ for (const id of this.values.keys()) {
541
+ if (!pushed.has(id) && pre.has(id)) {
542
+ ws.send(
543
+ this.edit(id, pre.get(id))
544
+ );
545
+ pushed.add(id);
546
+ }
547
+ }
548
+ }
549
+ });
550
+ ws.addEventListener("close", () => {
551
+ if (!stopped) setTimeout(loop, retry);
552
+ });
553
+ ws.addEventListener("error", () => {
554
+ try {
555
+ ws.close();
556
+ } catch {
557
+ }
558
+ });
559
+ };
560
+ loop();
561
+ return {
562
+ stop() {
563
+ stopped = true;
564
+ }
565
+ };
566
+ }
567
+ /** Mirror a server over Server-Sent Events (receive-only, JSON). Returns the `EventSource`. */
568
+ connectSSE(url) {
569
+ const es = new EventSource(url);
570
+ es.addEventListener(
571
+ "message",
572
+ (e) => this.recv(e.data)
573
+ );
574
+ return es;
575
+ }
576
+ };
577
+
578
+ // src/ts/widget.ts
579
+ var clients = /* @__PURE__ */ new WeakMap();
580
+ function clientFor(model) {
581
+ let client = clients.get(model);
582
+ if (!client) {
583
+ const created = new Client();
584
+ clients.set(model, created);
585
+ model.on("msg:custom", (content) => {
586
+ const wire = content?.wire;
587
+ if (wire !== void 0) created.recv(wire);
588
+ });
589
+ model.send({ ready: true });
590
+ client = created;
591
+ }
592
+ return client;
593
+ }
594
+ function sendEdit(model, id, path, value) {
595
+ const segments = path.map(
596
+ (p) => typeof p === "number" ? { Index: p } : { Key: p }
597
+ );
598
+ const patch = {
599
+ rev: 0,
600
+ // a proposal's rev is ignored; the server owns rev
601
+ ops: [{ Set: { path: segments, value: toValue(value) } }]
602
+ };
603
+ model.send({ wire: JSON.stringify({ t: "patch", id, patch }) });
604
+ }
605
+ var widget_default = {
606
+ initialize({ model }) {
607
+ clientFor(model);
608
+ },
609
+ render({ model, el }) {
610
+ const client = clientFor(model);
611
+ const container = document.createElement("div");
612
+ const error = document.createElement("div");
613
+ error.setAttribute(
614
+ "style",
615
+ "color: #b91c1c; font-size: 0.85em; min-height: 1em;"
616
+ );
617
+ el.appendChild(container);
618
+ el.appendChild(error);
619
+ const views = /* @__PURE__ */ new Map();
620
+ const update = (id) => {
621
+ let pre = views.get(id);
622
+ if (!pre) {
623
+ pre = document.createElement("pre");
624
+ pre.setAttribute("style", "margin: 0.25em 0;");
625
+ views.set(id, pre);
626
+ container.appendChild(pre);
627
+ }
628
+ pre.textContent = JSON.stringify(
629
+ fromValue(client.value(id)),
630
+ null,
631
+ 2
632
+ );
633
+ };
634
+ for (const id of client.ids()) update(id);
635
+ const offChange = client.onChange((change) => {
636
+ error.textContent = "";
637
+ update(change.id);
638
+ el.dispatchEvent(
639
+ new CustomEvent("transports-change", { detail: change, bubbles: true })
640
+ );
641
+ });
642
+ const offReject = client.onReject((reject) => {
643
+ error.textContent = `rejected: ${reject.error}`;
644
+ el.dispatchEvent(
645
+ new CustomEvent("transports-reject", { detail: reject, bubbles: true })
646
+ );
647
+ });
648
+ el.transports = {
649
+ client,
650
+ edit: (id, path, value) => sendEdit(model, id, path, value)
651
+ };
652
+ return () => {
653
+ offChange();
654
+ offReject();
655
+ };
656
+ }
657
+ };
658
+ export {
659
+ widget_default as default
660
+ };
661
+ //# sourceMappingURL=widget.js.map