@rotorsoft/act-sse 1.0.1 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -23,668 +23,62 @@ __export(index_exports, {
23
23
  BroadcastChannel: () => BroadcastChannel,
24
24
  PresenceTracker: () => PresenceTracker,
25
25
  StateCache: () => StateCache,
26
- applyBroadcastMessage: () => applyBroadcastMessage
26
+ applyPatchMessage: () => applyPatchMessage,
27
+ patch: () => patch
27
28
  });
28
29
  module.exports = __toCommonJS(index_exports);
29
30
 
30
- // ../../node_modules/.pnpm/fast-json-patch@3.1.1/node_modules/fast-json-patch/module/core.mjs
31
- var core_exports = {};
32
- __export(core_exports, {
33
- JsonPatchError: () => JsonPatchError,
34
- _areEquals: () => _areEquals,
35
- applyOperation: () => applyOperation,
36
- applyPatch: () => applyPatch,
37
- applyReducer: () => applyReducer,
38
- deepClone: () => deepClone,
39
- getValueByPointer: () => getValueByPointer,
40
- validate: () => validate,
41
- validator: () => validator
42
- });
43
-
44
- // ../../node_modules/.pnpm/fast-json-patch@3.1.1/node_modules/fast-json-patch/module/helpers.mjs
45
- var __extends = /* @__PURE__ */ (function() {
46
- var extendStatics = function(d, b) {
47
- extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
48
- d2.__proto__ = b2;
49
- } || function(d2, b2) {
50
- for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
51
- };
52
- return extendStatics(d, b);
53
- };
54
- return function(d, b) {
55
- extendStatics(d, b);
56
- function __() {
57
- this.constructor = d;
58
- }
59
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
60
- };
61
- })();
62
- var _hasOwnProperty = Object.prototype.hasOwnProperty;
63
- function hasOwnProperty(obj, key) {
64
- return _hasOwnProperty.call(obj, key);
65
- }
66
- function _objectKeys(obj) {
67
- if (Array.isArray(obj)) {
68
- var keys_1 = new Array(obj.length);
69
- for (var k = 0; k < keys_1.length; k++) {
70
- keys_1[k] = "" + k;
71
- }
72
- return keys_1;
73
- }
74
- if (Object.keys) {
75
- return Object.keys(obj);
76
- }
77
- var keys = [];
78
- for (var i in obj) {
79
- if (hasOwnProperty(obj, i)) {
80
- keys.push(i);
81
- }
82
- }
83
- return keys;
84
- }
85
- function _deepClone(obj) {
86
- switch (typeof obj) {
87
- case "object":
88
- return JSON.parse(JSON.stringify(obj));
89
- //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5
90
- case "undefined":
91
- return null;
92
- //this is how JSON.stringify behaves for array items
93
- default:
94
- return obj;
95
- }
96
- }
97
- function isInteger(str) {
98
- var i = 0;
99
- var len = str.length;
100
- var charCode;
101
- while (i < len) {
102
- charCode = str.charCodeAt(i);
103
- if (charCode >= 48 && charCode <= 57) {
104
- i++;
105
- continue;
106
- }
107
- return false;
108
- }
109
- return true;
110
- }
111
- function escapePathComponent(path) {
112
- if (path.indexOf("/") === -1 && path.indexOf("~") === -1)
113
- return path;
114
- return path.replace(/~/g, "~0").replace(/\//g, "~1");
115
- }
116
- function unescapePathComponent(path) {
117
- return path.replace(/~1/g, "/").replace(/~0/g, "~");
118
- }
119
- function hasUndefined(obj) {
120
- if (obj === void 0) {
121
- return true;
122
- }
123
- if (obj) {
124
- if (Array.isArray(obj)) {
125
- for (var i_1 = 0, len = obj.length; i_1 < len; i_1++) {
126
- if (hasUndefined(obj[i_1])) {
127
- return true;
128
- }
129
- }
130
- } else if (typeof obj === "object") {
131
- var objKeys = _objectKeys(obj);
132
- var objKeysLength = objKeys.length;
133
- for (var i = 0; i < objKeysLength; i++) {
134
- if (hasUndefined(obj[objKeys[i]])) {
135
- return true;
136
- }
137
- }
138
- }
139
- }
140
- return false;
141
- }
142
- function patchErrorMessageFormatter(message, args) {
143
- var messageParts = [message];
144
- for (var key in args) {
145
- var value = typeof args[key] === "object" ? JSON.stringify(args[key], null, 2) : args[key];
146
- if (typeof value !== "undefined") {
147
- messageParts.push(key + ": " + value);
148
- }
149
- }
150
- return messageParts.join("\n");
151
- }
152
- var PatchError = (
153
- /** @class */
154
- (function(_super) {
155
- __extends(PatchError2, _super);
156
- function PatchError2(message, name, index, operation, tree) {
157
- var _newTarget = this.constructor;
158
- var _this = _super.call(this, patchErrorMessageFormatter(message, { name, index, operation, tree })) || this;
159
- _this.name = name;
160
- _this.index = index;
161
- _this.operation = operation;
162
- _this.tree = tree;
163
- Object.setPrototypeOf(_this, _newTarget.prototype);
164
- _this.message = patchErrorMessageFormatter(message, { name, index, operation, tree });
165
- return _this;
166
- }
167
- return PatchError2;
168
- })(Error)
169
- );
170
-
171
- // ../../node_modules/.pnpm/fast-json-patch@3.1.1/node_modules/fast-json-patch/module/core.mjs
172
- var JsonPatchError = PatchError;
173
- var deepClone = _deepClone;
174
- var objOps = {
175
- add: function(obj, key, document) {
176
- obj[key] = this.value;
177
- return { newDocument: document };
178
- },
179
- remove: function(obj, key, document) {
180
- var removed = obj[key];
181
- delete obj[key];
182
- return { newDocument: document, removed };
183
- },
184
- replace: function(obj, key, document) {
185
- var removed = obj[key];
186
- obj[key] = this.value;
187
- return { newDocument: document, removed };
188
- },
189
- move: function(obj, key, document) {
190
- var removed = getValueByPointer(document, this.path);
191
- if (removed) {
192
- removed = _deepClone(removed);
193
- }
194
- var originalValue = applyOperation(document, { op: "remove", path: this.from }).removed;
195
- applyOperation(document, { op: "add", path: this.path, value: originalValue });
196
- return { newDocument: document, removed };
197
- },
198
- copy: function(obj, key, document) {
199
- var valueToCopy = getValueByPointer(document, this.from);
200
- applyOperation(document, { op: "add", path: this.path, value: _deepClone(valueToCopy) });
201
- return { newDocument: document };
202
- },
203
- test: function(obj, key, document) {
204
- return { newDocument: document, test: _areEquals(obj[key], this.value) };
205
- },
206
- _get: function(obj, key, document) {
207
- this.value = obj[key];
208
- return { newDocument: document };
209
- }
31
+ // src/patch.ts
32
+ var UNMERGEABLES = [
33
+ RegExp,
34
+ Date,
35
+ Array,
36
+ Map,
37
+ Set,
38
+ WeakMap,
39
+ WeakSet,
40
+ ArrayBuffer,
41
+ ...typeof SharedArrayBuffer !== "undefined" ? [SharedArrayBuffer] : [],
42
+ DataView,
43
+ Int8Array,
44
+ Uint8Array,
45
+ Uint8ClampedArray,
46
+ Int16Array,
47
+ Uint16Array,
48
+ Int32Array,
49
+ Uint32Array,
50
+ Float32Array,
51
+ Float64Array
52
+ ];
53
+ var is_mergeable = (value) => !!value && typeof value === "object" && !UNMERGEABLES.some((t) => value instanceof t);
54
+ var patch = (original, patches) => {
55
+ const copy = {};
56
+ Object.keys({ ...original, ...patches }).forEach((key) => {
57
+ const patched_value = patches[key];
58
+ const original_value = original[key];
59
+ const patched = patches && key in patches;
60
+ const deleted = patched && (typeof patched_value === "undefined" || patched_value === null);
61
+ const value = patched && !deleted ? patched_value : original_value;
62
+ !deleted && (copy[key] = is_mergeable(value) ? patch(original_value || {}, patched_value || {}) : value);
63
+ });
64
+ return copy;
210
65
  };
211
- var arrOps = {
212
- add: function(arr, i, document) {
213
- if (isInteger(i)) {
214
- arr.splice(i, 0, this.value);
215
- } else {
216
- arr[i] = this.value;
217
- }
218
- return { newDocument: document, index: i };
219
- },
220
- remove: function(arr, i, document) {
221
- var removedList = arr.splice(i, 1);
222
- return { newDocument: document, removed: removedList[0] };
223
- },
224
- replace: function(arr, i, document) {
225
- var removed = arr[i];
226
- arr[i] = this.value;
227
- return { newDocument: document, removed };
228
- },
229
- move: objOps.move,
230
- copy: objOps.copy,
231
- test: objOps.test,
232
- _get: objOps._get
233
- };
234
- function getValueByPointer(document, pointer) {
235
- if (pointer == "") {
236
- return document;
237
- }
238
- var getOriginalDestination = { op: "_get", path: pointer };
239
- applyOperation(document, getOriginalDestination);
240
- return getOriginalDestination.value;
241
- }
242
- function applyOperation(document, operation, validateOperation, mutateDocument, banPrototypeModifications, index) {
243
- if (validateOperation === void 0) {
244
- validateOperation = false;
245
- }
246
- if (mutateDocument === void 0) {
247
- mutateDocument = true;
248
- }
249
- if (banPrototypeModifications === void 0) {
250
- banPrototypeModifications = true;
251
- }
252
- if (index === void 0) {
253
- index = 0;
254
- }
255
- if (validateOperation) {
256
- if (typeof validateOperation == "function") {
257
- validateOperation(operation, 0, document, operation.path);
258
- } else {
259
- validator(operation, 0);
260
- }
261
- }
262
- if (operation.path === "") {
263
- var returnValue = { newDocument: document };
264
- if (operation.op === "add") {
265
- returnValue.newDocument = operation.value;
266
- return returnValue;
267
- } else if (operation.op === "replace") {
268
- returnValue.newDocument = operation.value;
269
- returnValue.removed = document;
270
- return returnValue;
271
- } else if (operation.op === "move" || operation.op === "copy") {
272
- returnValue.newDocument = getValueByPointer(document, operation.from);
273
- if (operation.op === "move") {
274
- returnValue.removed = document;
275
- }
276
- return returnValue;
277
- } else if (operation.op === "test") {
278
- returnValue.test = _areEquals(document, operation.value);
279
- if (returnValue.test === false) {
280
- throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document);
281
- }
282
- returnValue.newDocument = document;
283
- return returnValue;
284
- } else if (operation.op === "remove") {
285
- returnValue.removed = document;
286
- returnValue.newDocument = null;
287
- return returnValue;
288
- } else if (operation.op === "_get") {
289
- operation.value = document;
290
- return returnValue;
291
- } else {
292
- if (validateOperation) {
293
- throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document);
294
- } else {
295
- return returnValue;
296
- }
297
- }
298
- } else {
299
- if (!mutateDocument) {
300
- document = _deepClone(document);
301
- }
302
- var path = operation.path || "";
303
- var keys = path.split("/");
304
- var obj = document;
305
- var t = 1;
306
- var len = keys.length;
307
- var existingPathFragment = void 0;
308
- var key = void 0;
309
- var validateFunction = void 0;
310
- if (typeof validateOperation == "function") {
311
- validateFunction = validateOperation;
312
- } else {
313
- validateFunction = validator;
314
- }
315
- while (true) {
316
- key = keys[t];
317
- if (key && key.indexOf("~") != -1) {
318
- key = unescapePathComponent(key);
319
- }
320
- if (banPrototypeModifications && (key == "__proto__" || key == "prototype" && t > 0 && keys[t - 1] == "constructor")) {
321
- throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");
322
- }
323
- if (validateOperation) {
324
- if (existingPathFragment === void 0) {
325
- if (obj[key] === void 0) {
326
- existingPathFragment = keys.slice(0, t).join("/");
327
- } else if (t == len - 1) {
328
- existingPathFragment = operation.path;
329
- }
330
- if (existingPathFragment !== void 0) {
331
- validateFunction(operation, 0, document, existingPathFragment);
332
- }
333
- }
334
- }
335
- t++;
336
- if (Array.isArray(obj)) {
337
- if (key === "-") {
338
- key = obj.length;
339
- } else {
340
- if (validateOperation && !isInteger(key)) {
341
- throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document);
342
- } else if (isInteger(key)) {
343
- key = ~~key;
344
- }
345
- }
346
- if (t >= len) {
347
- if (validateOperation && operation.op === "add" && key > obj.length) {
348
- throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document);
349
- }
350
- var returnValue = arrOps[operation.op].call(operation, obj, key, document);
351
- if (returnValue.test === false) {
352
- throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document);
353
- }
354
- return returnValue;
355
- }
356
- } else {
357
- if (t >= len) {
358
- var returnValue = objOps[operation.op].call(operation, obj, key, document);
359
- if (returnValue.test === false) {
360
- throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document);
361
- }
362
- return returnValue;
363
- }
364
- }
365
- obj = obj[key];
366
- if (validateOperation && t < len && (!obj || typeof obj !== "object")) {
367
- throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document);
368
- }
369
- }
370
- }
371
- }
372
- function applyPatch(document, patch, validateOperation, mutateDocument, banPrototypeModifications) {
373
- if (mutateDocument === void 0) {
374
- mutateDocument = true;
375
- }
376
- if (banPrototypeModifications === void 0) {
377
- banPrototypeModifications = true;
378
- }
379
- if (validateOperation) {
380
- if (!Array.isArray(patch)) {
381
- throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY");
382
- }
383
- }
384
- if (!mutateDocument) {
385
- document = _deepClone(document);
386
- }
387
- var results = new Array(patch.length);
388
- for (var i = 0, length_1 = patch.length; i < length_1; i++) {
389
- results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i);
390
- document = results[i].newDocument;
391
- }
392
- results.newDocument = document;
393
- return results;
394
- }
395
- function applyReducer(document, operation, index) {
396
- var operationResult = applyOperation(document, operation);
397
- if (operationResult.test === false) {
398
- throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document);
399
- }
400
- return operationResult.newDocument;
401
- }
402
- function validator(operation, index, document, existingPathFragment) {
403
- if (typeof operation !== "object" || operation === null || Array.isArray(operation)) {
404
- throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document);
405
- } else if (!objOps[operation.op]) {
406
- throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document);
407
- } else if (typeof operation.path !== "string") {
408
- throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document);
409
- } else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) {
410
- throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index, operation, document);
411
- } else if ((operation.op === "move" || operation.op === "copy") && typeof operation.from !== "string") {
412
- throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document);
413
- } else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && operation.value === void 0) {
414
- throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document);
415
- } else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && hasUndefined(operation.value)) {
416
- throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document);
417
- } else if (document) {
418
- if (operation.op == "add") {
419
- var pathLen = operation.path.split("/").length;
420
- var existingPathLen = existingPathFragment.split("/").length;
421
- if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {
422
- throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document);
423
- }
424
- } else if (operation.op === "replace" || operation.op === "remove" || operation.op === "_get") {
425
- if (operation.path !== existingPathFragment) {
426
- throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document);
427
- }
428
- } else if (operation.op === "move" || operation.op === "copy") {
429
- var existingValue = { op: "_get", path: operation.from, value: void 0 };
430
- var error = validate([existingValue], document);
431
- if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") {
432
- throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document);
433
- }
434
- }
435
- }
436
- }
437
- function validate(sequence, document, externalValidator) {
438
- try {
439
- if (!Array.isArray(sequence)) {
440
- throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY");
441
- }
442
- if (document) {
443
- applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true);
444
- } else {
445
- externalValidator = externalValidator || validator;
446
- for (var i = 0; i < sequence.length; i++) {
447
- externalValidator(sequence[i], i, document, void 0);
448
- }
449
- }
450
- } catch (e) {
451
- if (e instanceof JsonPatchError) {
452
- return e;
453
- } else {
454
- throw e;
455
- }
456
- }
457
- }
458
- function _areEquals(a, b) {
459
- if (a === b)
460
- return true;
461
- if (a && b && typeof a == "object" && typeof b == "object") {
462
- var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key;
463
- if (arrA && arrB) {
464
- length = a.length;
465
- if (length != b.length)
466
- return false;
467
- for (i = length; i-- !== 0; )
468
- if (!_areEquals(a[i], b[i]))
469
- return false;
470
- return true;
471
- }
472
- if (arrA != arrB)
473
- return false;
474
- var keys = Object.keys(a);
475
- length = keys.length;
476
- if (length !== Object.keys(b).length)
477
- return false;
478
- for (i = length; i-- !== 0; )
479
- if (!b.hasOwnProperty(keys[i]))
480
- return false;
481
- for (i = length; i-- !== 0; ) {
482
- key = keys[i];
483
- if (!_areEquals(a[key], b[key]))
484
- return false;
485
- }
486
- return true;
487
- }
488
- return a !== a && b !== b;
489
- }
490
-
491
- // ../../node_modules/.pnpm/fast-json-patch@3.1.1/node_modules/fast-json-patch/module/duplex.mjs
492
- var duplex_exports = {};
493
- __export(duplex_exports, {
494
- compare: () => compare,
495
- generate: () => generate,
496
- observe: () => observe,
497
- unobserve: () => unobserve
498
- });
499
- var beforeDict = /* @__PURE__ */ new WeakMap();
500
- var Mirror = (
501
- /** @class */
502
- /* @__PURE__ */ (function() {
503
- function Mirror2(obj) {
504
- this.observers = /* @__PURE__ */ new Map();
505
- this.obj = obj;
506
- }
507
- return Mirror2;
508
- })()
509
- );
510
- var ObserverInfo = (
511
- /** @class */
512
- /* @__PURE__ */ (function() {
513
- function ObserverInfo2(callback, observer) {
514
- this.callback = callback;
515
- this.observer = observer;
516
- }
517
- return ObserverInfo2;
518
- })()
519
- );
520
- function getMirror(obj) {
521
- return beforeDict.get(obj);
522
- }
523
- function getObserverFromMirror(mirror, callback) {
524
- return mirror.observers.get(callback);
525
- }
526
- function removeObserverFromMirror(mirror, observer) {
527
- mirror.observers.delete(observer.callback);
528
- }
529
- function unobserve(root, observer) {
530
- observer.unobserve();
531
- }
532
- function observe(obj, callback) {
533
- var patches = [];
534
- var observer;
535
- var mirror = getMirror(obj);
536
- if (!mirror) {
537
- mirror = new Mirror(obj);
538
- beforeDict.set(obj, mirror);
539
- } else {
540
- var observerInfo = getObserverFromMirror(mirror, callback);
541
- observer = observerInfo && observerInfo.observer;
542
- }
543
- if (observer) {
544
- return observer;
545
- }
546
- observer = {};
547
- mirror.value = _deepClone(obj);
548
- if (callback) {
549
- observer.callback = callback;
550
- observer.next = null;
551
- var dirtyCheck = function() {
552
- generate(observer);
553
- };
554
- var fastCheck = function() {
555
- clearTimeout(observer.next);
556
- observer.next = setTimeout(dirtyCheck);
557
- };
558
- if (typeof window !== "undefined") {
559
- window.addEventListener("mouseup", fastCheck);
560
- window.addEventListener("keyup", fastCheck);
561
- window.addEventListener("mousedown", fastCheck);
562
- window.addEventListener("keydown", fastCheck);
563
- window.addEventListener("change", fastCheck);
564
- }
565
- }
566
- observer.patches = patches;
567
- observer.object = obj;
568
- observer.unobserve = function() {
569
- generate(observer);
570
- clearTimeout(observer.next);
571
- removeObserverFromMirror(mirror, observer);
572
- if (typeof window !== "undefined") {
573
- window.removeEventListener("mouseup", fastCheck);
574
- window.removeEventListener("keyup", fastCheck);
575
- window.removeEventListener("mousedown", fastCheck);
576
- window.removeEventListener("keydown", fastCheck);
577
- window.removeEventListener("change", fastCheck);
578
- }
579
- };
580
- mirror.observers.set(callback, new ObserverInfo(callback, observer));
581
- return observer;
582
- }
583
- function generate(observer, invertible) {
584
- if (invertible === void 0) {
585
- invertible = false;
586
- }
587
- var mirror = beforeDict.get(observer.object);
588
- _generate(mirror.value, observer.object, observer.patches, "", invertible);
589
- if (observer.patches.length) {
590
- applyPatch(mirror.value, observer.patches);
591
- }
592
- var temp = observer.patches;
593
- if (temp.length > 0) {
594
- observer.patches = [];
595
- if (observer.callback) {
596
- observer.callback(temp);
597
- }
598
- }
599
- return temp;
600
- }
601
- function _generate(mirror, obj, patches, path, invertible) {
602
- if (obj === mirror) {
603
- return;
604
- }
605
- if (typeof obj.toJSON === "function") {
606
- obj = obj.toJSON();
607
- }
608
- var newKeys = _objectKeys(obj);
609
- var oldKeys = _objectKeys(mirror);
610
- var changed = false;
611
- var deleted = false;
612
- for (var t = oldKeys.length - 1; t >= 0; t--) {
613
- var key = oldKeys[t];
614
- var oldVal = mirror[key];
615
- if (hasOwnProperty(obj, key) && !(obj[key] === void 0 && oldVal !== void 0 && Array.isArray(obj) === false)) {
616
- var newVal = obj[key];
617
- if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) {
618
- _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible);
619
- } else {
620
- if (oldVal !== newVal) {
621
- changed = true;
622
- if (invertible) {
623
- patches.push({ op: "test", path: path + "/" + escapePathComponent(key), value: _deepClone(oldVal) });
624
- }
625
- patches.push({ op: "replace", path: path + "/" + escapePathComponent(key), value: _deepClone(newVal) });
626
- }
627
- }
628
- } else if (Array.isArray(mirror) === Array.isArray(obj)) {
629
- if (invertible) {
630
- patches.push({ op: "test", path: path + "/" + escapePathComponent(key), value: _deepClone(oldVal) });
631
- }
632
- patches.push({ op: "remove", path: path + "/" + escapePathComponent(key) });
633
- deleted = true;
634
- } else {
635
- if (invertible) {
636
- patches.push({ op: "test", path, value: mirror });
637
- }
638
- patches.push({ op: "replace", path, value: obj });
639
- changed = true;
640
- }
641
- }
642
- if (!deleted && newKeys.length == oldKeys.length) {
643
- return;
644
- }
645
- for (var t = 0; t < newKeys.length; t++) {
646
- var key = newKeys[t];
647
- if (!hasOwnProperty(mirror, key) && obj[key] !== void 0) {
648
- patches.push({ op: "add", path: path + "/" + escapePathComponent(key), value: _deepClone(obj[key]) });
649
- }
650
- }
651
- }
652
- function compare(tree1, tree2, invertible) {
653
- if (invertible === void 0) {
654
- invertible = false;
655
- }
656
- var patches = [];
657
- _generate(tree1, tree2, patches, "", invertible);
658
- return patches;
659
- }
660
-
661
- // ../../node_modules/.pnpm/fast-json-patch@3.1.1/node_modules/fast-json-patch/index.mjs
662
- var fast_json_patch_default = Object.assign({}, core_exports, duplex_exports, {
663
- JsonPatchError: PatchError,
664
- deepClone: _deepClone,
665
- escapePathComponent,
666
- unescapePathComponent
667
- });
668
66
 
669
67
  // src/apply-patch.ts
670
- function applyBroadcastMessage(msg, cached) {
68
+ function applyPatchMessage(msg, cached) {
671
69
  const cachedV = cached?._v ?? 0;
672
- if (msg._type === "full") {
673
- if (msg._v < cachedV) return { ok: false, reason: "stale" };
674
- const { _type, ...state } = msg;
675
- return { ok: true, state };
676
- }
677
- if (msg._baseV < cachedV) return { ok: false, reason: "stale" };
678
- if (msg._baseV > cachedV) return { ok: false, reason: "behind" };
679
- if (!cached) return { ok: false, reason: "behind" };
680
- try {
681
- const clone = structuredClone(cached);
682
- applyPatch(clone, msg._patch, true);
683
- clone._v = msg._v;
684
- return { ok: true, state: clone };
685
- } catch {
686
- return { ok: false, reason: "patch-failed" };
687
- }
70
+ const versions = Object.keys(msg).map(Number).sort((a, b) => a - b);
71
+ if (!versions.length) return { ok: false, reason: "stale" };
72
+ const minV = versions[0];
73
+ const maxV = versions[versions.length - 1];
74
+ if (maxV <= cachedV) return { ok: false, reason: "stale" };
75
+ if (!cached || minV > cachedV + 1) return { ok: false, reason: "behind" };
76
+ let state = cached;
77
+ for (const v of versions) {
78
+ if (v <= cachedV) continue;
79
+ state = { ...patch(state, msg[v]), _v: v };
80
+ }
81
+ return { ok: true, state };
688
82
  }
689
83
 
690
84
  // src/state-cache.ts
@@ -730,27 +124,27 @@ var StateCache = class {
730
124
  };
731
125
 
732
126
  // src/broadcast.ts
733
- var DEFAULT_MAX_PATCH_OPS = 50;
734
127
  var BroadcastChannel = class {
735
128
  channels = /* @__PURE__ */ new Map();
736
129
  stateCache;
737
- maxPatchOps;
738
130
  constructor(options) {
739
131
  this.stateCache = new StateCache(options?.cacheSize ?? 50);
740
- this.maxPatchOps = options?.maxPatchOps ?? DEFAULT_MAX_PATCH_OPS;
741
132
  }
742
133
  /**
743
- * Publish new state for a stream. Computes a patch against the previously
744
- * cached state and pushes to all subscribers.
134
+ * Publish domain patches from a commit.
135
+ * patches[i] corresponds to version baseV + i + 1.
745
136
  *
746
137
  * @param streamId - The event store stream ID
747
138
  * @param state - Full state with `_v` set from `snap.event.version`
748
- * @returns The broadcast message that was sent (or undefined if no subscribers and no cache change)
139
+ * @param patches - Array of domain patches, one per emitted event
749
140
  */
750
- publish(streamId, state) {
751
- const prev = this.stateCache.get(streamId);
141
+ publish(streamId, state, patches = []) {
752
142
  this.stateCache.set(streamId, state);
753
- const msg = this.computeMessage(prev, state);
143
+ const baseV = state._v - patches.length;
144
+ const msg = {};
145
+ patches.forEach((p, i) => {
146
+ msg[baseV + i + 1] = p;
147
+ });
754
148
  const subs = this.channels.get(streamId);
755
149
  if (subs?.size) {
756
150
  for (const cb of subs) cb(msg);
@@ -760,13 +154,14 @@ var BroadcastChannel = class {
760
154
  /**
761
155
  * Publish a state update that doesn't change the event version
762
156
  * (e.g. presence overlay, computed field refresh).
763
- * Uses the same version as the cached state for _baseV and _v.
157
+ * Uses the same version as the cached state, single entry.
764
158
  */
765
- publishOverlay(streamId, state) {
159
+ publishOverlay(streamId, overlayPatch) {
766
160
  const prev = this.stateCache.get(streamId);
767
161
  if (!prev) return void 0;
162
+ const state = patch(prev, overlayPatch);
768
163
  this.stateCache.set(streamId, state);
769
- const msg = this.computeMessage(prev, state);
164
+ const msg = { [state._v]: overlayPatch };
770
165
  const subs = this.channels.get(streamId);
771
166
  if (subs?.size) {
772
167
  for (const cb of subs) cb(msg);
@@ -799,27 +194,6 @@ var BroadcastChannel = class {
799
194
  get cache() {
800
195
  return this.stateCache;
801
196
  }
802
- // --- internals ---
803
- computeMessage(prev, next) {
804
- const serverTime = (/* @__PURE__ */ new Date()).toISOString();
805
- if (!prev) {
806
- return { _type: "full", ...next, serverTime };
807
- }
808
- const ops = compare(prev, next);
809
- if (ops.length === 0) {
810
- return { _type: "full", ...next, serverTime };
811
- }
812
- if (ops.length > this.maxPatchOps) {
813
- return { _type: "full", ...next, serverTime };
814
- }
815
- return {
816
- _type: "patch",
817
- _v: next._v,
818
- _baseV: prev._v,
819
- _patch: ops,
820
- serverTime
821
- };
822
- }
823
197
  };
824
198
 
825
199
  // src/presence.ts
@@ -855,22 +229,7 @@ var PresenceTracker = class {
855
229
  BroadcastChannel,
856
230
  PresenceTracker,
857
231
  StateCache,
858
- applyBroadcastMessage
232
+ applyPatchMessage,
233
+ patch
859
234
  });
860
- /*! Bundled license information:
861
-
862
- fast-json-patch/module/helpers.mjs:
863
- (*!
864
- * https://github.com/Starcounter-Jack/JSON-Patch
865
- * (c) 2017-2022 Joachim Wester
866
- * MIT licensed
867
- *)
868
-
869
- fast-json-patch/module/duplex.mjs:
870
- (*!
871
- * https://github.com/Starcounter-Jack/JSON-Patch
872
- * (c) 2017-2021 Joachim Wester
873
- * MIT license
874
- *)
875
- */
876
235
  //# sourceMappingURL=index.cjs.map