@1kbgz/transports 0.8.0 → 0.8.4

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/dist/cdn/index.js CHANGED
@@ -1,889 +1,2 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // dist/pkg/transports.js
8
- var transports_exports = {};
9
- __export(transports_exports, {
10
- Store: () => Store,
11
- apply: () => apply,
12
- cbor_to_json: () => cbor_to_json,
13
- decode: () => decode,
14
- decode_as: () => decode_as,
15
- default: () => __wbg_init,
16
- diff: () => diff,
17
- encode: () => encode,
18
- encode_as: () => encode_as,
19
- initSync: () => initSync,
20
- json_to_cbor: () => json_to_cbor,
21
- json_to_msgpack: () => json_to_msgpack,
22
- msgpack_to_json: () => msgpack_to_json
23
- });
24
- var Store = class {
25
- __destroy_into_raw() {
26
- const ptr = this.__wbg_ptr;
27
- this.__wbg_ptr = 0;
28
- StoreFinalization.unregister(this);
29
- return ptr;
30
- }
31
- free() {
32
- const ptr = this.__destroy_into_raw();
33
- wasm.__wbg_store_free(ptr, 0);
34
- }
35
- /**
36
- * Apply a JSON patch to a mirrored model; returns whether the id was known.
37
- * @param {bigint} id
38
- * @param {string} patch_json
39
- * @returns {boolean}
40
- */
41
- apply(id, patch_json) {
42
- const ptr0 = passStringToWasm0(patch_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
43
- const len0 = WASM_VECTOR_LEN;
44
- const ret = wasm.store_apply(this.__wbg_ptr, id, ptr0, len0);
45
- if (ret[2]) {
46
- throw takeFromExternrefTable0(ret[1]);
47
- }
48
- return ret[0] !== 0;
49
- }
50
- /**
51
- * Host a model from its JSON; returns the assigned id.
52
- * @param {string} type_name
53
- * @param {string} value_json
54
- * @returns {bigint}
55
- */
56
- host(type_name, value_json) {
57
- const ptr0 = passStringToWasm0(type_name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
58
- const len0 = WASM_VECTOR_LEN;
59
- const ptr1 = passStringToWasm0(value_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
60
- const len1 = WASM_VECTOR_LEN;
61
- const ret = wasm.store_host(this.__wbg_ptr, ptr0, len0, ptr1, len1);
62
- if (ret[2]) {
63
- throw takeFromExternrefTable0(ret[1]);
64
- }
65
- return BigInt.asUintN(64, ret[0]);
66
- }
67
- /**
68
- * Replace a hosted model from JSON; returns the JSON patch (or `undefined` if id unknown).
69
- * @param {bigint} id
70
- * @param {string} value_json
71
- * @returns {string | undefined}
72
- */
73
- mutate(id, value_json) {
74
- const ptr0 = passStringToWasm0(value_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
75
- const len0 = WASM_VECTOR_LEN;
76
- const ret = wasm.store_mutate(this.__wbg_ptr, id, ptr0, len0);
77
- if (ret[3]) {
78
- throw takeFromExternrefTable0(ret[2]);
79
- }
80
- let v2;
81
- if (ret[0] !== 0) {
82
- v2 = getStringFromWasm0(ret[0], ret[1]).slice();
83
- wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
84
- }
85
- return v2;
86
- }
87
- constructor() {
88
- const ret = wasm.store_new();
89
- this.__wbg_ptr = ret;
90
- StoreFinalization.register(this, this.__wbg_ptr, this);
91
- return this;
92
- }
93
- /**
94
- * `{"type_name":..,"rev":..,"value":..}` for a hosted model, or `undefined`.
95
- * @param {bigint} id
96
- * @returns {string | undefined}
97
- */
98
- snapshot(id) {
99
- const ret = wasm.store_snapshot(this.__wbg_ptr, id);
100
- let v1;
101
- if (ret[0] !== 0) {
102
- v1 = getStringFromWasm0(ret[0], ret[1]).slice();
103
- wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
104
- }
105
- return v1;
106
- }
107
- };
108
- if (Symbol.dispose) Store.prototype[Symbol.dispose] = Store.prototype.free;
109
- function apply(value, patch) {
110
- let deferred4_0;
111
- let deferred4_1;
112
- try {
113
- const ptr0 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
114
- const len0 = WASM_VECTOR_LEN;
115
- const ptr1 = passStringToWasm0(patch, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
116
- const len1 = WASM_VECTOR_LEN;
117
- const ret = wasm.apply(ptr0, len0, ptr1, len1);
118
- var ptr3 = ret[0];
119
- var len3 = ret[1];
120
- if (ret[3]) {
121
- ptr3 = 0;
122
- len3 = 0;
123
- throw takeFromExternrefTable0(ret[2]);
124
- }
125
- deferred4_0 = ptr3;
126
- deferred4_1 = len3;
127
- return getStringFromWasm0(ptr3, len3);
128
- } finally {
129
- wasm.__wbindgen_free(deferred4_0, deferred4_1, 1);
130
- }
131
- }
132
- function cbor_to_json(data) {
133
- let deferred3_0;
134
- let deferred3_1;
135
- try {
136
- const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
137
- const len0 = WASM_VECTOR_LEN;
138
- const ret = wasm.cbor_to_json(ptr0, len0);
139
- var ptr2 = ret[0];
140
- var len2 = ret[1];
141
- if (ret[3]) {
142
- ptr2 = 0;
143
- len2 = 0;
144
- throw takeFromExternrefTable0(ret[2]);
145
- }
146
- deferred3_0 = ptr2;
147
- deferred3_1 = len2;
148
- return getStringFromWasm0(ptr2, len2);
149
- } finally {
150
- wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
151
- }
152
- }
153
- function decode(data) {
154
- let deferred3_0;
155
- let deferred3_1;
156
- try {
157
- const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
158
- const len0 = WASM_VECTOR_LEN;
159
- const ret = wasm.decode(ptr0, len0);
160
- var ptr2 = ret[0];
161
- var len2 = ret[1];
162
- if (ret[3]) {
163
- ptr2 = 0;
164
- len2 = 0;
165
- throw takeFromExternrefTable0(ret[2]);
166
- }
167
- deferred3_0 = ptr2;
168
- deferred3_1 = len2;
169
- return getStringFromWasm0(ptr2, len2);
170
- } finally {
171
- wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
172
- }
173
- }
174
- function decode_as(data, codec) {
175
- let deferred4_0;
176
- let deferred4_1;
177
- try {
178
- const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
179
- const len0 = WASM_VECTOR_LEN;
180
- const ptr1 = passStringToWasm0(codec, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
181
- const len1 = WASM_VECTOR_LEN;
182
- const ret = wasm.decode_as(ptr0, len0, ptr1, len1);
183
- var ptr3 = ret[0];
184
- var len3 = ret[1];
185
- if (ret[3]) {
186
- ptr3 = 0;
187
- len3 = 0;
188
- throw takeFromExternrefTable0(ret[2]);
189
- }
190
- deferred4_0 = ptr3;
191
- deferred4_1 = len3;
192
- return getStringFromWasm0(ptr3, len3);
193
- } finally {
194
- wasm.__wbindgen_free(deferred4_0, deferred4_1, 1);
195
- }
196
- }
197
- function diff(old, _new) {
198
- let deferred4_0;
199
- let deferred4_1;
200
- try {
201
- const ptr0 = passStringToWasm0(old, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
202
- const len0 = WASM_VECTOR_LEN;
203
- const ptr1 = passStringToWasm0(_new, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
204
- const len1 = WASM_VECTOR_LEN;
205
- const ret = wasm.diff(ptr0, len0, ptr1, len1);
206
- var ptr3 = ret[0];
207
- var len3 = ret[1];
208
- if (ret[3]) {
209
- ptr3 = 0;
210
- len3 = 0;
211
- throw takeFromExternrefTable0(ret[2]);
212
- }
213
- deferred4_0 = ptr3;
214
- deferred4_1 = len3;
215
- return getStringFromWasm0(ptr3, len3);
216
- } finally {
217
- wasm.__wbindgen_free(deferred4_0, deferred4_1, 1);
218
- }
219
- }
220
- function encode(value) {
221
- const ptr0 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
222
- const len0 = WASM_VECTOR_LEN;
223
- const ret = wasm.encode(ptr0, len0);
224
- if (ret[3]) {
225
- throw takeFromExternrefTable0(ret[2]);
226
- }
227
- var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
228
- wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
229
- return v2;
230
- }
231
- function encode_as(value, codec) {
232
- const ptr0 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
233
- const len0 = WASM_VECTOR_LEN;
234
- const ptr1 = passStringToWasm0(codec, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
235
- const len1 = WASM_VECTOR_LEN;
236
- const ret = wasm.encode_as(ptr0, len0, ptr1, len1);
237
- if (ret[3]) {
238
- throw takeFromExternrefTable0(ret[2]);
239
- }
240
- var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
241
- wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
242
- return v3;
243
- }
244
- function json_to_cbor(json) {
245
- const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
246
- const len0 = WASM_VECTOR_LEN;
247
- const ret = wasm.json_to_cbor(ptr0, len0);
248
- if (ret[3]) {
249
- throw takeFromExternrefTable0(ret[2]);
250
- }
251
- var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
252
- wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
253
- return v2;
254
- }
255
- function json_to_msgpack(json) {
256
- const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
257
- const len0 = WASM_VECTOR_LEN;
258
- const ret = wasm.json_to_msgpack(ptr0, len0);
259
- if (ret[3]) {
260
- throw takeFromExternrefTable0(ret[2]);
261
- }
262
- var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
263
- wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
264
- return v2;
265
- }
266
- function msgpack_to_json(data) {
267
- let deferred3_0;
268
- let deferred3_1;
269
- try {
270
- const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
271
- const len0 = WASM_VECTOR_LEN;
272
- const ret = wasm.msgpack_to_json(ptr0, len0);
273
- var ptr2 = ret[0];
274
- var len2 = ret[1];
275
- if (ret[3]) {
276
- ptr2 = 0;
277
- len2 = 0;
278
- throw takeFromExternrefTable0(ret[2]);
279
- }
280
- deferred3_0 = ptr2;
281
- deferred3_1 = len2;
282
- return getStringFromWasm0(ptr2, len2);
283
- } finally {
284
- wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
285
- }
286
- }
287
- function __wbg_get_imports() {
288
- const import0 = {
289
- __proto__: null,
290
- __wbg_Error_92b29b0548f8b746: function(arg0, arg1) {
291
- const ret = Error(getStringFromWasm0(arg0, arg1));
292
- return ret;
293
- },
294
- __wbg___wbindgen_throw_344f42d3211c4765: function(arg0, arg1) {
295
- throw new Error(getStringFromWasm0(arg0, arg1));
296
- },
297
- __wbindgen_init_externref_table: function() {
298
- const table = wasm.__wbindgen_externrefs;
299
- const offset = table.grow(4);
300
- table.set(0, void 0);
301
- table.set(offset + 0, void 0);
302
- table.set(offset + 1, null);
303
- table.set(offset + 2, true);
304
- table.set(offset + 3, false);
305
- }
306
- };
307
- return {
308
- __proto__: null,
309
- "./transports_bg.js": import0
310
- };
311
- }
312
- var StoreFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
313
- }, unregister: () => {
314
- } } : new FinalizationRegistry((ptr) => wasm.__wbg_store_free(ptr, 1));
315
- function getArrayU8FromWasm0(ptr, len) {
316
- ptr = ptr >>> 0;
317
- return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
318
- }
319
- function getStringFromWasm0(ptr, len) {
320
- return decodeText(ptr >>> 0, len);
321
- }
322
- var cachedUint8ArrayMemory0 = null;
323
- function getUint8ArrayMemory0() {
324
- if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
325
- cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
326
- }
327
- return cachedUint8ArrayMemory0;
328
- }
329
- function passArray8ToWasm0(arg, malloc) {
330
- const ptr = malloc(arg.length * 1, 1) >>> 0;
331
- getUint8ArrayMemory0().set(arg, ptr / 1);
332
- WASM_VECTOR_LEN = arg.length;
333
- return ptr;
334
- }
335
- function passStringToWasm0(arg, malloc, realloc) {
336
- if (realloc === void 0) {
337
- const buf = cachedTextEncoder.encode(arg);
338
- const ptr2 = malloc(buf.length, 1) >>> 0;
339
- getUint8ArrayMemory0().subarray(ptr2, ptr2 + buf.length).set(buf);
340
- WASM_VECTOR_LEN = buf.length;
341
- return ptr2;
342
- }
343
- let len = arg.length;
344
- let ptr = malloc(len, 1) >>> 0;
345
- const mem = getUint8ArrayMemory0();
346
- let offset = 0;
347
- for (; offset < len; offset++) {
348
- const code = arg.charCodeAt(offset);
349
- if (code > 127) break;
350
- mem[ptr + offset] = code;
351
- }
352
- if (offset !== len) {
353
- if (offset !== 0) {
354
- arg = arg.slice(offset);
355
- }
356
- ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
357
- const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
358
- const ret = cachedTextEncoder.encodeInto(arg, view);
359
- offset += ret.written;
360
- ptr = realloc(ptr, len, offset, 1) >>> 0;
361
- }
362
- WASM_VECTOR_LEN = offset;
363
- return ptr;
364
- }
365
- function takeFromExternrefTable0(idx) {
366
- const value = wasm.__wbindgen_externrefs.get(idx);
367
- wasm.__externref_table_dealloc(idx);
368
- return value;
369
- }
370
- var cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
371
- cachedTextDecoder.decode();
372
- var MAX_SAFARI_DECODE_BYTES = 2146435072;
373
- var numBytesDecoded = 0;
374
- function decodeText(ptr, len) {
375
- numBytesDecoded += len;
376
- if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
377
- cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
378
- cachedTextDecoder.decode();
379
- numBytesDecoded = len;
380
- }
381
- return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
382
- }
383
- var cachedTextEncoder = new TextEncoder();
384
- if (!("encodeInto" in cachedTextEncoder)) {
385
- cachedTextEncoder.encodeInto = function(arg, view) {
386
- const buf = cachedTextEncoder.encode(arg);
387
- view.set(buf);
388
- return {
389
- read: arg.length,
390
- written: buf.length
391
- };
392
- };
393
- }
394
- var WASM_VECTOR_LEN = 0;
395
- var wasmModule;
396
- var wasmInstance;
397
- var wasm;
398
- function __wbg_finalize_init(instance, module) {
399
- wasmInstance = instance;
400
- wasm = instance.exports;
401
- wasmModule = module;
402
- cachedUint8ArrayMemory0 = null;
403
- wasm.__wbindgen_start();
404
- return wasm;
405
- }
406
- async function __wbg_load(module, imports) {
407
- if (typeof Response === "function" && module instanceof Response) {
408
- if (typeof WebAssembly.instantiateStreaming === "function") {
409
- try {
410
- return await WebAssembly.instantiateStreaming(module, imports);
411
- } catch (e) {
412
- const validResponse = module.ok && expectedResponseType(module.type);
413
- if (validResponse && module.headers.get("Content-Type") !== "application/wasm") {
414
- console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
415
- } else {
416
- throw e;
417
- }
418
- }
419
- }
420
- const bytes = await module.arrayBuffer();
421
- return await WebAssembly.instantiate(bytes, imports);
422
- } else {
423
- const instance = await WebAssembly.instantiate(module, imports);
424
- if (instance instanceof WebAssembly.Instance) {
425
- return { instance, module };
426
- } else {
427
- return instance;
428
- }
429
- }
430
- function expectedResponseType(type) {
431
- switch (type) {
432
- case "basic":
433
- case "cors":
434
- case "default":
435
- return true;
436
- }
437
- return false;
438
- }
439
- }
440
- function initSync(module) {
441
- if (wasm !== void 0) return wasm;
442
- if (module !== void 0) {
443
- if (Object.getPrototypeOf(module) === Object.prototype) {
444
- ({ module } = module);
445
- } else {
446
- console.warn("using deprecated parameters for `initSync()`; pass a single object instead");
447
- }
448
- }
449
- const imports = __wbg_get_imports();
450
- if (!(module instanceof WebAssembly.Module)) {
451
- module = new WebAssembly.Module(module);
452
- }
453
- const instance = new WebAssembly.Instance(module, imports);
454
- return __wbg_finalize_init(instance, module);
455
- }
456
- async function __wbg_init(module_or_path) {
457
- if (wasm !== void 0) return wasm;
458
- if (module_or_path !== void 0) {
459
- if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
460
- ({ module_or_path } = module_or_path);
461
- } else {
462
- console.warn("using deprecated parameters for the initialization function; pass a single object instead");
463
- }
464
- }
465
- if (module_or_path === void 0) {
466
- module_or_path = new URL("transports_bg.wasm", import.meta.url);
467
- }
468
- const imports = __wbg_get_imports();
469
- if (typeof module_or_path === "string" || typeof Request === "function" && module_or_path instanceof Request || typeof URL === "function" && module_or_path instanceof URL) {
470
- module_or_path = fetch(module_or_path);
471
- }
472
- const { instance, module } = await __wbg_load(await module_or_path, imports);
473
- return __wbg_finalize_init(instance, module);
474
- }
475
-
476
- // src/ts/bridge.ts
477
- function toValue(v) {
478
- if (v === null || v === void 0) return "Null";
479
- if (typeof v === "boolean") return { Bool: v };
480
- if (typeof v === "number")
481
- return Number.isInteger(v) ? { Int: v } : { Float: v };
482
- if (typeof v === "string") return { Str: v };
483
- if (Array.isArray(v)) return { List: v.map(toValue) };
484
- if (typeof v === "object") {
485
- const m = {};
486
- for (const [k, x] of Object.entries(v)) m[k] = toValue(x);
487
- return { Map: m };
488
- }
489
- throw new TypeError(`unsupported value for transports: ${typeof v}`);
490
- }
491
- function fromValue(value) {
492
- if (value === "Null") return null;
493
- const [tag, inner] = Object.entries(value)[0];
494
- switch (tag) {
495
- case "Bool":
496
- case "Int":
497
- case "Float":
498
- case "Str":
499
- case "Submodel":
500
- return inner;
501
- case "List":
502
- return inner.map(fromValue);
503
- case "Map": {
504
- const o = {};
505
- for (const [k, x] of Object.entries(inner))
506
- o[k] = fromValue(x);
507
- return o;
508
- }
509
- default:
510
- throw new Error(`unrecognized tagged value: ${JSON.stringify(value)}`);
511
- }
512
- }
513
-
514
- // src/ts/codecs.ts
515
- var BUILTIN = /* @__PURE__ */ new Set([
516
- "",
517
- "json",
518
- "application/json",
519
- "msgpack",
520
- "application/msgpack",
521
- "x-msgpack",
522
- "application/x-msgpack",
523
- "cbor",
524
- "application/cbor"
525
- ]);
526
- var registry = /* @__PURE__ */ new Map();
527
- function registerCodec(contentType, encode3, decode3) {
528
- if (BUILTIN.has(contentType)) {
529
- throw new Error(`cannot override built-in codec: ${contentType}`);
530
- }
531
- registry.set(contentType, { encode: encode3, decode: decode3 });
532
- }
533
- function unregisterCodec(contentType) {
534
- registry.delete(contentType);
535
- }
536
- function codecFor(contentType) {
537
- return registry.get(contentType);
538
- }
539
-
540
- // src/ts/client.ts
541
- function mapValue(value) {
542
- if (value && typeof value === "object" && "Map" in value && value.Map && typeof value.Map === "object" && !Array.isArray(value.Map))
543
- return value.Map;
544
- throw new Error("patch path expected a map");
545
- }
546
- function listValue(value) {
547
- if (value && typeof value === "object" && "List" in value && Array.isArray(value.List))
548
- return value.List;
549
- throw new Error("patch path expected a list");
550
- }
551
- function validIndex(index) {
552
- return Number.isSafeInteger(index) && index >= 0;
553
- }
554
- function updateAt(value, path, update) {
555
- if (!path.length) return update(value);
556
- const [segment, ...rest] = path;
557
- if ("Key" in segment) {
558
- const map = mapValue(value);
559
- if (rest.length && !Object.prototype.hasOwnProperty.call(map, segment.Key))
560
- throw new Error(
561
- `patch path key ${JSON.stringify(segment.Key)} not found`
562
- );
563
- return {
564
- Map: {
565
- ...map,
566
- [segment.Key]: updateAt(map[segment.Key], rest, update)
567
- }
568
- };
569
- }
570
- const list = listValue(value);
571
- if (!validIndex(segment.Index) || segment.Index >= list.length)
572
- throw new Error(
573
- `patch path index ${segment.Index} out of bounds (len ${list.length})`
574
- );
575
- const next = [...list];
576
- next[segment.Index] = updateAt(next[segment.Index], rest, update);
577
- return { List: next };
578
- }
579
- function applyOp(value, op) {
580
- if ("Set" in op) return updateAt(value, op.Set.path, () => op.Set.value);
581
- if ("Remove" in op) {
582
- const { path } = op.Remove;
583
- const segment = path[path.length - 1];
584
- if (!segment || !("Key" in segment))
585
- throw new Error("remove path must end in a map key");
586
- return updateAt(value, path.slice(0, -1), (container) => {
587
- const map = { ...mapValue(container) };
588
- delete map[segment.Key];
589
- return { Map: map };
590
- });
591
- }
592
- if ("Insert" in op) {
593
- const { path, index, value: inserted } = op.Insert;
594
- return updateAt(value, path, (container) => {
595
- const list = listValue(container);
596
- if (!validIndex(index) || index > list.length)
597
- throw new Error(
598
- `insert index ${index} out of bounds (len ${list.length})`
599
- );
600
- const next = [...list];
601
- next.splice(index, 0, inserted);
602
- return { List: next };
603
- });
604
- }
605
- if ("RemoveAt" in op) {
606
- const { path, index } = op.RemoveAt;
607
- return updateAt(value, path, (container) => {
608
- const list = listValue(container);
609
- if (!validIndex(index) || index >= list.length)
610
- throw new Error(
611
- `remove index ${index} out of bounds (len ${list.length})`
612
- );
613
- const next = [...list];
614
- next.splice(index, 1);
615
- return { List: next };
616
- });
617
- }
618
- if ("Move" in op) {
619
- const { path, from, to } = op.Move;
620
- return updateAt(value, path, (container) => {
621
- const list = listValue(container);
622
- if (!validIndex(from) || from >= list.length)
623
- throw new Error(
624
- `move source index ${from} out of bounds (len ${list.length})`
625
- );
626
- if (!validIndex(to) || to >= list.length)
627
- throw new Error(
628
- `move destination index ${to} out of bounds (len ${list.length})`
629
- );
630
- if (from === to) return container;
631
- const next = [...list];
632
- const [moved] = next.splice(from, 1);
633
- next.splice(to, 0, moved);
634
- return { List: next };
635
- });
636
- }
637
- if ("Reorder" in op) {
638
- const { path, order } = op.Reorder;
639
- return updateAt(value, path, (container) => {
640
- const list = listValue(container);
641
- if (!Array.isArray(order))
642
- throw new Error("reorder order must be an array");
643
- if (order.length !== list.length)
644
- throw new Error(
645
- `reorder length ${order.length} does not match list length ${list.length}`
646
- );
647
- const seen = /* @__PURE__ */ new Set();
648
- for (const index of order) {
649
- if (!validIndex(index) || index >= list.length)
650
- throw new Error(
651
- `reorder index ${index} out of bounds (len ${list.length})`
652
- );
653
- if (seen.has(index))
654
- throw new Error(`reorder index ${index} is duplicated`);
655
- seen.add(index);
656
- }
657
- if (order.every((old, current) => old === current))
658
- return container;
659
- return { List: order.map((index) => list[index]) };
660
- });
661
- }
662
- throw new Error("unknown patch op");
663
- }
664
- function applyPatch(value, patch) {
665
- let next = value;
666
- for (const op of patch.ops) next = applyOp(next, op);
667
- return next;
668
- }
669
- var Client = class {
670
- constructor(codec = "json") {
671
- this.codec = codec;
672
- }
673
- codec;
674
- values = /* @__PURE__ */ new Map();
675
- revs = /* @__PURE__ */ new Map();
676
- changeListeners = [];
677
- rejectListeners = [];
678
- /** Register a listener fired when the server refuses a proposed edit, with the decoded `reject`
679
- * frame (model id, the server's current rev, and the validation error). The mirror itself reverts
680
- * via the authoritative snapshot the server sends alongside. Returns an unsubscribe function.
681
- */
682
- onReject(listener) {
683
- this.rejectListeners.push(listener);
684
- return () => {
685
- const i = this.rejectListeners.indexOf(listener);
686
- if (i >= 0) this.rejectListeners.splice(i, 1);
687
- };
688
- }
689
- /** Register a listener fired after each accepted snapshot or patch — the same `ReceiveChange`
690
- * `recv` returns — so `connect`/`run`/`connectSSE` consumers get path-level changes without
691
- * managing the socket themselves. Not fired for ignored frames (stale revision, unknown message
692
- * type). Returns an unsubscribe function. A listener exception propagates to the `recv` caller;
693
- * the mirror has already updated by then.
694
- */
695
- onChange(listener) {
696
- this.changeListeners.push(listener);
697
- return () => {
698
- const i = this.changeListeners.indexOf(listener);
699
- if (i >= 0) this.changeListeners.splice(i, 1);
700
- };
701
- }
702
- accepted(change) {
703
- for (const listener of [...this.changeListeners]) listener(change);
704
- return change;
705
- }
706
- /** Apply an inbound snapshot or patch frame to the mirror.
707
- *
708
- * Decodes by the client's codec: a registered custom codec, else built-in JSON (text) / msgpack
709
- * (binary). Returns the accepted change so reactive adapters can update only its paths; returns
710
- * `undefined` for a patch whose revision was already applied, and for an unrecognized message
711
- * type — ignored, not an error, so a newer server can add message types without breaking older
712
- * clients. The returned change and values from `value()` share immutable branches with the
713
- * mirror; consumers must not mutate them. Invalid frames throw without changing the mirror or its
714
- * accepted revision.
715
- */
716
- recv(data) {
717
- const custom = codecFor(this.codec);
718
- let msg;
719
- if (custom) {
720
- msg = custom.decode(data);
721
- } else if (typeof data === "string") {
722
- msg = JSON.parse(data);
723
- } else {
724
- msg = JSON.parse(
725
- this.codec === "cbor" ? cborToJson(data) : msgpackToJson(data)
726
- );
727
- }
728
- if (msg.t === "snapshot") {
729
- this.values.set(msg.id, msg.value);
730
- this.revs.set(msg.id, msg.rev);
731
- return this.accepted({ t: "snapshot", id: msg.id, rev: msg.rev });
732
- } else if (msg.t === "patch") {
733
- const seen = this.revs.get(msg.id);
734
- if (seen !== void 0 && msg.patch.rev <= seen) return void 0;
735
- const current = this.values.get(msg.id);
736
- if (current === void 0)
737
- throw new Error(`patch received before snapshot for model ${msg.id}`);
738
- this.values.set(msg.id, applyPatch(current, msg.patch));
739
- this.revs.set(msg.id, msg.patch.rev);
740
- return this.accepted(msg);
741
- } else if (msg.t === "reject") {
742
- for (const listener of [...this.rejectListeners]) listener(msg);
743
- return void 0;
744
- }
745
- return void 0;
746
- }
747
- /** The current mirrored core `Value` of a model. */
748
- value(id) {
749
- return this.values.get(id);
750
- }
751
- ids() {
752
- return [...this.values.keys()];
753
- }
754
- /** Propose an edit to a mirrored model; returns the patch frame to send (encoded in this codec).
755
- *
756
- * Server-authoritative: the local mirror updates when the server echoes the authoritative patch
757
- * back via `recv`, not optimistically.
758
- */
759
- edit(id, value) {
760
- const patch = JSON.parse(
761
- diff2(JSON.stringify(this.values.get(id)), JSON.stringify(value))
762
- );
763
- const msg = { t: "patch", id, patch };
764
- const custom = codecFor(this.codec);
765
- if (custom) return custom.encode(msg);
766
- const s = JSON.stringify(msg);
767
- if (this.codec === "msgpack") return jsonToMsgpack(s);
768
- if (this.codec === "cbor") return jsonToCbor(s);
769
- return s;
770
- }
771
- /** Connect to a transports server and mirror it. Returns the `WebSocket`.
772
- *
773
- * On a reconnect (this client already mirrors models) it appends `?since=` with its last-seen rev per
774
- * model, so the server replays only the delta instead of re-sending each whole model.
775
- */
776
- connect(url) {
777
- const sep = url.includes("?") ? "&" : "?";
778
- let params = `codec=${this.codec}`;
779
- if (this.revs.size) {
780
- const since = encodeURIComponent(
781
- JSON.stringify(Object.fromEntries(this.revs))
782
- );
783
- params += `&since=${since}`;
784
- }
785
- const ws = new WebSocket(`${url}${sep}${params}`);
786
- ws.binaryType = "arraybuffer";
787
- ws.addEventListener("message", (e) => {
788
- const data = e.data;
789
- this.recv(
790
- typeof data === "string" ? data : new Uint8Array(data)
791
- );
792
- });
793
- return ws;
794
- }
795
- /** Connect and mirror, **reconnecting** whenever the socket drops — so the client survives a server
796
- * restart or a refresh. `authority` decides reconciliation on each (re)connect:
797
- *
798
- * - `"server"` (default): the server is canonical; the client adopts its state (resuming via `?since=`
799
- * when it can, else a fresh snapshot) — the "refetch on refresh" behavior.
800
- * - `"client"`: the client is canonical; after the server's snapshot it pushes its last-known state
801
- * back as an edit, rectifying a server that came back stale/empty (merges under a CRDT, else
802
- * overwrites).
803
- *
804
- * `onMessage` fires after each applied frame (e.g. to re-render). Returns `{ stop() }`.
805
- */
806
- run(url, opts = {}) {
807
- const { authority = "server", retry = 1e3, onMessage } = opts;
808
- let stopped = false;
809
- const loop = () => {
810
- if (stopped) return;
811
- const pre = authority === "client" ? new Map(this.values) : null;
812
- const pushed = /* @__PURE__ */ new Set();
813
- const ws = this.connect(url);
814
- ws.addEventListener("message", () => {
815
- onMessage?.();
816
- if (pre) {
817
- for (const id of this.values.keys()) {
818
- if (!pushed.has(id) && pre.has(id)) {
819
- ws.send(
820
- this.edit(id, pre.get(id))
821
- );
822
- pushed.add(id);
823
- }
824
- }
825
- }
826
- });
827
- ws.addEventListener("close", () => {
828
- if (!stopped) setTimeout(loop, retry);
829
- });
830
- ws.addEventListener("error", () => {
831
- try {
832
- ws.close();
833
- } catch {
834
- }
835
- });
836
- };
837
- loop();
838
- return {
839
- stop() {
840
- stopped = true;
841
- }
842
- };
843
- }
844
- /** Mirror a server over Server-Sent Events (receive-only, JSON). Returns the `EventSource`. */
845
- connectSSE(url) {
846
- const es = new EventSource(url);
847
- es.addEventListener(
848
- "message",
849
- (e) => this.recv(e.data)
850
- );
851
- return es;
852
- }
853
- };
854
-
855
- // src/ts/index.ts
856
- var placeholder = "";
857
- var diff2 = (oldModel, newModel) => diff(oldModel, newModel);
858
- var apply2 = (model, patch) => apply(model, patch);
859
- var encode2 = (model) => encode(model);
860
- var decode2 = (bytes) => decode(bytes);
861
- var encodeAs = (model, codec) => encode_as(model, codec);
862
- var decodeAs = (bytes, codec) => decode_as(bytes, codec);
863
- var jsonToMsgpack = (json) => json_to_msgpack(json);
864
- var msgpackToJson = (bytes) => msgpack_to_json(bytes);
865
- var jsonToCbor = (json) => json_to_cbor(json);
866
- var cborToJson = (bytes) => cbor_to_json(bytes);
867
- var Store2 = Store;
868
- export {
869
- Client,
870
- Store2 as Store,
871
- apply2 as apply,
872
- cborToJson,
873
- codecFor,
874
- decode2 as decode,
875
- decodeAs,
876
- diff2 as diff,
877
- encode2 as encode,
878
- encodeAs,
879
- fromValue,
880
- jsonToCbor,
881
- jsonToMsgpack,
882
- msgpackToJson,
883
- placeholder,
884
- registerCodec,
885
- toValue,
886
- unregisterCodec,
887
- transports_exports as wasm
888
- };
1
+ var oe=Object.defineProperty;var ie=(n,e)=>{for(var r in e)oe(n,r,{get:e[r],enumerable:!0})};var z={};ie(z,{ClientState:()=>w,Store:()=>m,apply:()=>R,cbor_to_json:()=>C,decode:()=>P,decode_as:()=>V,decode_message:()=>U,default:()=>ge,diff:()=>I,encode:()=>$,encode_as:()=>N,encode_message:()=>T,initSync:()=>pe,json_to_cbor:()=>W,json_to_msgpack:()=>J,msgpack_to_json:()=>F,normalize_message:()=>B});var w=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,H.unregister(this),e}free(){let e=this.__destroy_into_raw();o.__wbg_clientstate_free(e,0)}abandon(e){let r=_(e,o.__wbindgen_malloc,o.__wbindgen_realloc),t=l;return o.clientstate_abandon(this.__wbg_ptr,r,t)!==0}commit(e){let r=_(e,o.__wbindgen_malloc,o.__wbindgen_realloc),t=l,s=o.clientstate_commit(this.__wbg_ptr,r,t);if(s[1])throw p(s[0])}disconnect(){let e,r;try{let i=o.clientstate_disconnect(this.__wbg_ptr);var t=i[0],s=i[1];if(i[3])throw t=0,s=0,p(i[2]);return e=t,r=s,g(t,s)}finally{o.__wbindgen_free(e,r,1)}}constructor(){let e=o.clientstate_new();return this.__wbg_ptr=e,H.register(this,this.__wbg_ptr,this),this}pending(){let e,r;try{let i=o.clientstate_pending(this.__wbg_ptr);var t=i[0],s=i[1];if(i[3])throw t=0,s=0,p(i[2]);return e=t,r=s,g(t,s)}finally{o.__wbindgen_free(e,r,1)}}prepare(e){let r,t;try{let c=_(e,o.__wbindgen_malloc,o.__wbindgen_realloc),a=l,d=o.clientstate_prepare(this.__wbg_ptr,c,a);var s=d[0],i=d[1];if(d[3])throw s=0,i=0,p(d[2]);return r=s,t=i,g(s,i)}finally{o.__wbindgen_free(r,t,1)}}proposal(e,r,t){let s,i;try{let f=_(r,o.__wbindgen_malloc,o.__wbindgen_realloc),b=l;var c=ce(t)?0:_(t,o.__wbindgen_malloc,o.__wbindgen_realloc),a=l;let E=o.clientstate_proposal(this.__wbg_ptr,e,f,b,c,a);var d=E[0],u=E[1];if(E[3])throw d=0,u=0,p(E[2]);return s=d,i=u,g(d,u)}finally{o.__wbindgen_free(s,i,1)}}revisions(){let e,r;try{let i=o.clientstate_revisions(this.__wbg_ptr);var t=i[0],s=i[1];if(i[3])throw t=0,s=0,p(i[2]);return e=t,r=s,g(t,s)}finally{o.__wbindgen_free(e,r,1)}}};Symbol.dispose&&(w.prototype[Symbol.dispose]=w.prototype.free);var m=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,Q.unregister(this),e}free(){let e=this.__destroy_into_raw();o.__wbg_store_free(e,0)}apply(e,r){let t=_(r,o.__wbindgen_malloc,o.__wbindgen_realloc),s=l,i=o.store_apply(this.__wbg_ptr,e,t,s);if(i[2])throw p(i[1]);return i[0]!==0}host(e,r){let t=_(e,o.__wbindgen_malloc,o.__wbindgen_realloc),s=l,i=_(r,o.__wbindgen_malloc,o.__wbindgen_realloc),c=l,a=o.store_host(this.__wbg_ptr,t,s,i,c);if(a[2])throw p(a[1]);return BigInt.asUintN(64,a[0])}mutate(e,r){let t=_(r,o.__wbindgen_malloc,o.__wbindgen_realloc),s=l,i=o.store_mutate(this.__wbg_ptr,e,t,s);if(i[3])throw p(i[2]);let c;return i[0]!==0&&(c=g(i[0],i[1]),o.__wbindgen_free(i[0],i[1]*1,1)),c}constructor(){let e=o.store_new();return this.__wbg_ptr=e,Q.register(this,this.__wbg_ptr,this),this}snapshot(e){let r=o.store_snapshot(this.__wbg_ptr,e),t;return r[0]!==0&&(t=g(r[0],r[1]),o.__wbindgen_free(r[0],r[1]*1,1)),t}};Symbol.dispose&&(m.prototype[Symbol.dispose]=m.prototype.free);function R(n,e){let r,t;try{let c=_(n,o.__wbindgen_malloc,o.__wbindgen_realloc),a=l,d=_(e,o.__wbindgen_malloc,o.__wbindgen_realloc),u=l,f=o.apply(c,a,d,u);var s=f[0],i=f[1];if(f[3])throw s=0,i=0,p(f[2]);return r=s,t=i,g(s,i)}finally{o.__wbindgen_free(r,t,1)}}function C(n){let e,r;try{let i=S(n,o.__wbindgen_malloc),c=l,a=o.cbor_to_json(i,c);var t=a[0],s=a[1];if(a[3])throw t=0,s=0,p(a[2]);return e=t,r=s,g(t,s)}finally{o.__wbindgen_free(e,r,1)}}function P(n){let e,r;try{let i=S(n,o.__wbindgen_malloc),c=l,a=o.decode(i,c);var t=a[0],s=a[1];if(a[3])throw t=0,s=0,p(a[2]);return e=t,r=s,g(t,s)}finally{o.__wbindgen_free(e,r,1)}}function V(n,e){let r,t;try{let c=S(n,o.__wbindgen_malloc),a=l,d=_(e,o.__wbindgen_malloc,o.__wbindgen_realloc),u=l,f=o.decode_as(c,a,d,u);var s=f[0],i=f[1];if(f[3])throw s=0,i=0,p(f[2]);return r=s,t=i,g(s,i)}finally{o.__wbindgen_free(r,t,1)}}function U(n,e){let r,t;try{let c=S(n,o.__wbindgen_malloc),a=l,d=_(e,o.__wbindgen_malloc,o.__wbindgen_realloc),u=l,f=o.decode_message(c,a,d,u);var s=f[0],i=f[1];if(f[3])throw s=0,i=0,p(f[2]);return r=s,t=i,g(s,i)}finally{o.__wbindgen_free(r,t,1)}}function I(n,e){let r,t;try{let c=_(n,o.__wbindgen_malloc,o.__wbindgen_realloc),a=l,d=_(e,o.__wbindgen_malloc,o.__wbindgen_realloc),u=l,f=o.diff(c,a,d,u);var s=f[0],i=f[1];if(f[3])throw s=0,i=0,p(f[2]);return r=s,t=i,g(s,i)}finally{o.__wbindgen_free(r,t,1)}}function $(n){let e=_(n,o.__wbindgen_malloc,o.__wbindgen_realloc),r=l,t=o.encode(e,r);if(t[3])throw p(t[2]);var s=A(t[0],t[1]).slice();return o.__wbindgen_free(t[0],t[1]*1,1),s}function N(n,e){let r=_(n,o.__wbindgen_malloc,o.__wbindgen_realloc),t=l,s=_(e,o.__wbindgen_malloc,o.__wbindgen_realloc),i=l,c=o.encode_as(r,t,s,i);if(c[3])throw p(c[2]);var a=A(c[0],c[1]).slice();return o.__wbindgen_free(c[0],c[1]*1,1),a}function T(n,e){let r=_(n,o.__wbindgen_malloc,o.__wbindgen_realloc),t=l,s=_(e,o.__wbindgen_malloc,o.__wbindgen_realloc),i=l,c=o.encode_message(r,t,s,i);if(c[3])throw p(c[2]);var a=A(c[0],c[1]).slice();return o.__wbindgen_free(c[0],c[1]*1,1),a}function W(n){let e=_(n,o.__wbindgen_malloc,o.__wbindgen_realloc),r=l,t=o.json_to_cbor(e,r);if(t[3])throw p(t[2]);var s=A(t[0],t[1]).slice();return o.__wbindgen_free(t[0],t[1]*1,1),s}function J(n){let e=_(n,o.__wbindgen_malloc,o.__wbindgen_realloc),r=l,t=o.json_to_msgpack(e,r);if(t[3])throw p(t[2]);var s=A(t[0],t[1]).slice();return o.__wbindgen_free(t[0],t[1]*1,1),s}function F(n){let e,r;try{let i=S(n,o.__wbindgen_malloc),c=l,a=o.msgpack_to_json(i,c);var t=a[0],s=a[1];if(a[3])throw t=0,s=0,p(a[2]);return e=t,r=s,g(t,s)}finally{o.__wbindgen_free(e,r,1)}}function B(n){let e,r;try{let i=_(n,o.__wbindgen_malloc,o.__wbindgen_realloc),c=l,a=o.normalize_message(i,c);var t=a[0],s=a[1];if(a[3])throw t=0,s=0,p(a[2]);return e=t,r=s,g(t,s)}finally{o.__wbindgen_free(e,r,1)}}function Z(){return{__proto__:null,"./transports_bg.js":{__proto__:null,__wbg_Error_408e67f47ca7b58b:function(e,r){return Error(g(e,r))},__wbg___wbindgen_throw_bb96b2010945f0bc:function(e,r){throw new Error(g(e,r))},__wbindgen_init_externref_table:function(){let e=o.__wbindgen_externrefs,r=e.grow(4);e.set(0,void 0),e.set(r+0,void 0),e.set(r+1,null),e.set(r+2,!0),e.set(r+3,!1)}}}}var H=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>o.__wbg_clientstate_free(n,1)),Q=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>o.__wbg_store_free(n,1));function A(n,e){return n=n>>>0,y().subarray(n/1,n/1+e)}function g(n,e){return de(n>>>0,e)}var x=null;function y(){return(x===null||x.byteLength===0)&&(x=new Uint8Array(o.memory.buffer)),x}function ce(n){return n==null}function S(n,e){let r=e(n.length*1,1)>>>0;return y().set(n,r/1),l=n.length,r}function _(n,e,r){if(r===void 0){let a=M.encode(n),d=e(a.length,1)>>>0;return y().subarray(d,d+a.length).set(a),l=a.length,d}let t=n.length,s=e(t,1)>>>0,i=y(),c=0;for(;c<t;c++){let a=n.charCodeAt(c);if(a>127)break;i[s+c]=a}if(c!==t){c!==0&&(n=n.slice(c)),s=r(s,t,t=c+n.length*3,1)>>>0;let a=y().subarray(s+c,s+t),d=M.encodeInto(n,a);c+=d.written,s=r(s,t,c,1)>>>0}return l=c,s}function p(n){let e=o.__wbindgen_externrefs.get(n);return o.__externref_table_dealloc(n),e}var O=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});O.decode();var ae=2146435072,L=0;function de(n,e){return L+=e,L>=ae&&(O=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),O.decode(),L=e),O.decode(y().subarray(n,n+e))}var M=new TextEncoder;"encodeInto"in M||(M.encodeInto=function(n,e){let r=M.encode(n);return e.set(r),{read:n.length,written:r.length}});var l=0,le,fe,o;function ee(n,e){return fe=n,o=n.exports,le=e,x=null,o.__wbindgen_start(),o}async function _e(n,e){if(typeof Response=="function"&&n instanceof Response){if(!n.ok)throw new Error(`failed to fetch Wasm: ${n.status} ${n.statusText} fetching '${n.url}'`);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(n,e)}catch(s){if(r(n.type)&&n.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",s);else throw s}let t=await n.arrayBuffer();return await WebAssembly.instantiate(t,e)}else{let t=await WebAssembly.instantiate(n,e);return t instanceof WebAssembly.Instance?{instance:t,module:n}:t}function r(t){switch(t){case"basic":case"cors":case"default":return!0}return!1}}function pe(n){if(o!==void 0)return o;n!==void 0&&(Object.getPrototypeOf(n)===Object.prototype?{module:n}=n:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let e=Z();n instanceof WebAssembly.Module||(n=new WebAssembly.Module(n));let r=new WebAssembly.Instance(n,e);return ee(r,n)}async function ge(n){if(o!==void 0)return o;n!==void 0&&(Object.getPrototypeOf(n)===Object.prototype?{module_or_path:n}=n:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),n===void 0&&(n=new URL("transports_bg.wasm",import.meta.url));let e=Z();(typeof n=="string"||typeof Request=="function"&&n instanceof Request||typeof URL=="function"&&n instanceof URL)&&(n=fetch(n));let{instance:r,module:t}=await _e(await n,e);return ee(r,t)}function D(n){if(n==null)return"Null";if(typeof n=="boolean")return{Bool:n};if(typeof n=="number")return Number.isInteger(n)?{Int:n}:{Float:n};if(typeof n=="string")return{Str:n};if(Array.isArray(n))return{List:n.map(D)};if(typeof n=="object"){let e={};for(let[r,t]of Object.entries(n))e[r]=D(t);return{Map:e}}throw new TypeError(`unsupported value for transports: ${typeof n}`)}function K(n){if(n==="Null")return null;let[e,r]=Object.entries(n)[0];switch(e){case"Bool":case"Int":case"Float":case"Str":case"Submodel":return r;case"List":return r.map(K);case"Map":{let t={};for(let[s,i]of Object.entries(r))t[s]=K(i);return t}default:throw new Error(`unrecognized tagged value: ${JSON.stringify(n)}`)}}var ue=new Set(["","json","application/json","msgpack","application/msgpack","x-msgpack","application/x-msgpack","cbor","application/cbor"]),q=new Map;function he(n,e,r){if(ue.has(n))throw new Error(`cannot override built-in codec: ${n}`);q.set(n,{encode:e,decode:r})}function be(n){q.delete(n)}function k(n){return q.get(n)}var X=class{inner=new se;prepare(e){return JSON.parse(this.inner.prepare(JSON.stringify(e)))}commit(e){this.inner.commit(JSON.stringify(e))}proposal(e,r,t){return this.inner.proposal(BigInt(e),JSON.stringify(r),t)}disconnect(){return JSON.parse(this.inner.disconnect())}revisions(){return JSON.parse(this.inner.revisions())}pending(){return JSON.parse(this.inner.pending())}abandon(e){return this.inner.abandon(e)}};function te(n){if(n&&typeof n=="object"&&"Map"in n&&n.Map&&typeof n.Map=="object"&&!Array.isArray(n.Map))return n.Map;throw new Error("patch path expected a map")}function j(n){if(n&&typeof n=="object"&&"List"in n&&Array.isArray(n.List))return n.List;throw new Error("patch path expected a list")}function v(n){return Number.isSafeInteger(n)&&n>=0}function h(n,e,r){if(!e.length)return r(n);let[t,...s]=e;if("Key"in t){let a=te(n);if(s.length&&!Object.prototype.hasOwnProperty.call(a,t.Key))throw new Error(`patch path key ${JSON.stringify(t.Key)} not found`);return{Map:{...a,[t.Key]:h(a[t.Key],s,r)}}}let i=j(n);if(!v(t.Index)||t.Index>=i.length)throw new Error(`patch path index ${t.Index} out of bounds (len ${i.length})`);let c=[...i];return c[t.Index]=h(c[t.Index],s,r),{List:c}}function we(n,e){if("Set"in e)return h(n,e.Set.path,()=>e.Set.value);if("Remove"in e){let{path:r}=e.Remove,t=r[r.length-1];if(!t||!("Key"in t))throw new Error("remove path must end in a map key");return h(n,r.slice(0,-1),s=>{let i={...te(s)};return delete i[t.Key],{Map:i}})}if("Insert"in e){let{path:r,index:t,value:s}=e.Insert;return h(n,r,i=>{let c=j(i);if(!v(t)||t>c.length)throw new Error(`insert index ${t} out of bounds (len ${c.length})`);let a=[...c];return a.splice(t,0,s),{List:a}})}if("RemoveAt"in e){let{path:r,index:t}=e.RemoveAt;return h(n,r,s=>{let i=j(s);if(!v(t)||t>=i.length)throw new Error(`remove index ${t} out of bounds (len ${i.length})`);let c=[...i];return c.splice(t,1),{List:c}})}if("Move"in e){let{path:r,from:t,to:s}=e.Move;return h(n,r,i=>{let c=j(i);if(!v(t)||t>=c.length)throw new Error(`move source index ${t} out of bounds (len ${c.length})`);if(!v(s)||s>=c.length)throw new Error(`move destination index ${s} out of bounds (len ${c.length})`);if(t===s)return i;let a=[...c],[d]=a.splice(t,1);return a.splice(s,0,d),{List:a}})}if("Reorder"in e){let{path:r,order:t}=e.Reorder;return h(n,r,s=>{let i=j(s);if(!Array.isArray(t))throw new Error("reorder order must be an array");if(t.length!==i.length)throw new Error(`reorder length ${t.length} does not match list length ${i.length}`);let c=new Set;for(let a of t){if(!v(a)||a>=i.length)throw new Error(`reorder index ${a} out of bounds (len ${i.length})`);if(c.has(a))throw new Error(`reorder index ${a} is duplicated`);c.add(a)}return t.every((a,d)=>a===d)?s:{List:t.map(a=>i[a])}})}throw new Error("unknown patch op")}function me(n,e){let r=n;for(let t of e.ops)r=we(r,t);return r}var Y=class{constructor(e="json"){this.codec=e;this.state=new X}codec;values=new Map;changeListeners=[];ackListeners=[];rejectListeners=[];abandonListeners=[];disconnectListeners=[];state;sender=null;get connected(){return this.sender!==null}send(e){return this.sender?(this.sender(e),!0):!1}propose(e,r,t){return this.sendProposal(this.edit(e,r,t))}proposeOps(e,r,t){return this.sendProposal(this.editOps(e,r,t))}sendProposal(e){let r=k(this.codec),t=r?r.decode(e):JSON.parse(typeof e=="string"?e:G(e,this.codec));try{let s=this.send(e);return!s&&t.proposal!==void 0&&this.state.abandon(t.proposal),s}catch(s){throw t.proposal!==void 0&&this.state.abandon(t.proposal),s}}onReject(e){return this.rejectListeners.push(e),()=>{let r=this.rejectListeners.indexOf(e);r>=0&&this.rejectListeners.splice(r,1)}}onAck(e){return this.ackListeners.push(e),()=>{let r=this.ackListeners.indexOf(e);r>=0&&this.ackListeners.splice(r,1)}}onDisconnect(e){return this.disconnectListeners.push(e),()=>{let r=this.disconnectListeners.indexOf(e);r>=0&&this.disconnectListeners.splice(r,1)}}onAbandon(e){return this.abandonListeners.push(e),()=>{let r=this.abandonListeners.indexOf(e);r>=0&&this.abandonListeners.splice(r,1)}}disconnected(){let{proposals:e}=this.state.disconnect();if(e.length)for(let r of[...this.abandonListeners])r(e);for(let r of[...this.disconnectListeners])r()}onChange(e){return this.changeListeners.push(e),()=>{let r=this.changeListeners.indexOf(e);r>=0&&this.changeListeners.splice(r,1)}}accepted(e){for(let r of[...this.changeListeners])r(e);return e}acknowledge(e){if(e.proposal!==void 0)for(let r of[...this.ackListeners])r(e)}recv(e){let r=k(this.codec),t;if(r?t=r.decode(e):typeof e=="string"?t=JSON.parse(e):t=JSON.parse(G(e,this.codec)),t.t==="batch"){let s=t.msgs.map(i=>this.apply(i)).filter(i=>i!==void 0);return s.length?s:void 0}return this.apply(t)}apply(e){let r=this.state.prepare(e);if(r.effect==="snapshot"){let t=e;return this.values.set(t.id,t.value),this.state.commit(r),this.accepted({t:"snapshot",id:t.id,rev:t.rev})}else if(r.effect==="patch"){let t=e,s=this.values.get(t.id);if(s===void 0)throw new Error(`patch received before snapshot for model ${t.id}`);let i=me(s,t.patch);this.state.commit(r),this.values.set(t.id,i);let c=this.accepted(t);return this.acknowledge(t),c}else if(r.effect==="stale_patch"){this.state.commit(r),this.acknowledge(e);return}else if(r.effect==="acknowledgement"){this.state.commit(r),this.acknowledge(e);return}else if(r.effect==="rejection"){this.state.commit(r);let t=e;for(let s of[...this.rejectListeners])s(t);return}}value(e){return this.values.get(e)}ids(){return[...this.values.keys()]}pendingProposals(){return this.state.pending()}edit(e,r,t){let s=JSON.parse(ne(JSON.stringify(this.values.get(e)),JSON.stringify(r)));return this.editOps(e,s.ops,t)}editOps(e,r,t){let s=this.state.proposal(e,r,t),i=JSON.parse(s);try{let c=k(this.codec);return c?c.encode(i):this.codec!=="json"?re(s,this.codec):s}catch(c){throw i.proposal!==void 0&&this.state.abandon(i.proposal),c}}connect(e){let r=e.includes("?")?"&":"?",t=`codec=${this.codec}`,s=this.state.revisions();if(Object.keys(s).length){let a=encodeURIComponent(JSON.stringify(s));t+=`&since=${a}`}let i=new WebSocket(`${e}${r}${t}`);i.binaryType="arraybuffer",i.addEventListener("message",a=>{let d=a.data;this.recv(typeof d=="string"?d:new Uint8Array(d))});let c=a=>i.send(a);return i.addEventListener("open",()=>{this.sender=c}),i.addEventListener("close",()=>{this.sender===c&&(this.sender=null,this.disconnected())}),i}run(e,r={}){let{authority:t="server",retry:s=1e3,onMessage:i}=r,c=!1,a=()=>{if(c)return;let d=t==="client"?new Map(this.values):null,u=new Set,f=this.connect(e);f.addEventListener("message",()=>{if(i?.(),d)for(let b of this.values.keys())!u.has(b)&&d.has(b)&&(f.send(this.edit(b,d.get(b))),u.add(b))}),f.addEventListener("close",()=>{c||setTimeout(a,s)}),f.addEventListener("error",()=>{try{f.close()}catch{}})};return a(),{stop(){c=!0}}}connectSSE(e){let r=new EventSource(e);return r.addEventListener("message",t=>this.recv(t.data)),r}};var ke="",ne=(n,e)=>I(n,e),je=(n,e)=>R(n,e),Ee=n=>$(n),Oe=n=>P(n),Le=(n,e)=>N(n,e),Re=(n,e)=>V(n,e),Ce=n=>J(n),Pe=n=>F(n),Ve=n=>W(n),Ue=n=>C(n),Ie=n=>B(n),re=(n,e)=>T(n,e),G=(n,e)=>U(n,e),$e=m,se=w;export{Y as Client,se as ClientState,$e as Store,je as apply,Ue as cborToJson,k as codecFor,Oe as decode,Re as decodeAs,G as decodeMessage,ne as diff,Ee as encode,Le as encodeAs,re as encodeMessage,K as fromValue,Ve as jsonToCbor,Ce as jsonToMsgpack,Pe as msgpackToJson,Ie as normalizeMessage,ke as placeholder,he as registerCodec,D as toValue,be as unregisterCodec,z as wasm};
889
2
  //# sourceMappingURL=index.js.map