doxum 0.1.1 → 0.1.2

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.
Files changed (44) hide show
  1. package/README.md +45 -2
  2. package/dist/{dependency-BdEMyquf.js → access-5D4KKFm7.js} +4 -21
  3. package/dist/access-5D4KKFm7.js.map +1 -0
  4. package/dist/{dependency-DLcCvNKq.cjs → access-z56fVqZ2.cjs} +21 -32
  5. package/dist/access-z56fVqZ2.cjs.map +1 -0
  6. package/dist/{contract-Otb5W6cQ.d.cts → contract-DGkZcTiP.d.cts} +63 -5
  7. package/dist/{contract-DwNiKioc.d.ts → contract-Dh3az8aN.d.ts} +63 -5
  8. package/dist/dependency-BRn1TRDi.js +20 -0
  9. package/dist/dependency-BRn1TRDi.js.map +1 -0
  10. package/dist/dependency-DmQXyj7q.cjs +25 -0
  11. package/dist/dependency-DmQXyj7q.cjs.map +1 -0
  12. package/dist/index.cjs +46 -2341
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +8 -5
  15. package/dist/index.d.ts +8 -5
  16. package/dist/index.js +5 -2304
  17. package/dist/index.js.map +1 -1
  18. package/dist/integration.cjs +3 -2
  19. package/dist/integration.cjs.map +1 -1
  20. package/dist/integration.d.cts +2 -2
  21. package/dist/integration.d.ts +2 -2
  22. package/dist/integration.js +2 -1
  23. package/dist/integration.js.map +1 -1
  24. package/dist/local-sync.cjs +660 -0
  25. package/dist/local-sync.cjs.map +1 -0
  26. package/dist/local-sync.d.cts +79 -0
  27. package/dist/local-sync.d.ts +79 -0
  28. package/dist/local-sync.js +653 -0
  29. package/dist/local-sync.js.map +1 -0
  30. package/dist/react.cjs.map +1 -1
  31. package/dist/react.d.cts +2 -2
  32. package/dist/react.d.ts +2 -2
  33. package/dist/react.js.map +1 -1
  34. package/dist/readable-B8E3FMq6.cjs +2614 -0
  35. package/dist/readable-B8E3FMq6.cjs.map +1 -0
  36. package/dist/readable-CIj02gIj.js +2579 -0
  37. package/dist/readable-CIj02gIj.js.map +1 -0
  38. package/package.json +14 -8
  39. package/skills/doxum-runtime/references/guide.en.md +9 -5
  40. package/skills/doxum-runtime/references/guide.zh-CN.md +3 -2
  41. package/skills/doxum-runtime/references/invariants.en.md +13 -8
  42. package/skills/doxum-runtime/references/invariants.zh-CN.md +2 -2
  43. package/dist/dependency-BdEMyquf.js.map +0 -1
  44. package/dist/dependency-DLcCvNKq.cjs.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,2328 +1,29 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_dependency = require("./dependency-DLcCvNKq.cjs");
3
- //#region core/src/impact.ts
4
- const emptyCollectionImpact = Object.freeze({
5
- kind: "incremental",
6
- added: /* @__PURE__ */ new Set(),
7
- removed: /* @__PURE__ */ new Set(),
8
- updated: /* @__PURE__ */ new Set(),
9
- orderChanged: false
10
- });
11
- const resetCollectionImpact = Object.freeze({ kind: "reset" });
12
- const createImpact = (input) => {
13
- const kind = input.reset ? "reset" : "incremental";
14
- const paths = input.paths ?? input.operations.map((operation) => operation.at);
15
- let pathBuckets;
16
- const somePath = (address, test) => {
17
- if (address.length === 0 || paths.length <= 8) return paths.some(test);
18
- if (!pathBuckets) {
19
- pathBuckets = /* @__PURE__ */ new Map();
20
- for (const changed of paths) {
21
- const first = changed[0];
22
- const bucket = pathBuckets.get(first) ?? [];
23
- bucket.push(changed);
24
- pathBuckets.set(first, bucket);
25
- }
26
- }
27
- if (pathBuckets.get(void 0)?.some(test)) return true;
28
- return pathBuckets.get(address[0])?.some(test) ?? false;
29
- };
30
- const pathsAffect = (address) => address.length === 0 ? paths.length > 0 : somePath(address, (changed) => require_dependency.overlaps(changed, address));
31
- let collectionCache;
32
- const findCollection = (address) => input.collections?.find((entry) => entry.address.length === address.length && entry.address.every((segment, index) => segment === address[index]));
33
- return {
34
- kind,
35
- operations: input.operations,
36
- affects: (value) => {
37
- require_dependency.profile.impact.affects();
38
- if (kind === "reset") return true;
39
- if (!require_dependency.belongs(value, input.schema)) return false;
40
- if (pathsAffect(require_dependency.address(value))) return true;
41
- if (value.kind === "collection") {
42
- const collection = findCollection(require_dependency.address(value));
43
- if (!collection) return false;
44
- const id$1 = require_dependency.id(value);
45
- if (id$1 !== void 0) return collection.added.has(id$1) || collection.removed.has(id$1) || collection.updated.has(id$1);
46
- return collection.added.size > 0 || collection.removed.size > 0 || collection.updated.size > 0 || collection.orderChanged;
47
- }
48
- return false;
49
- },
50
- collection: (selector) => {
51
- if (selector.schema !== input.schema) throw new Error("Collection selector belongs to another schema.");
52
- if (kind === "reset") return resetCollectionImpact;
53
- const cached = collectionCache?.find((entry) => entry.address.length === selector.address.length && entry.address.every((segment, index) => segment === selector.address[index]))?.value;
54
- if (cached) return cached;
55
- const exact = findCollection(selector.address);
56
- if (somePath(selector.address, (changed) => require_dependency.contains(changed, selector.address) && changed.length < selector.address.length)) {
57
- const reset = { kind: "reset" };
58
- (collectionCache ??= []).push({
59
- address: selector.address,
60
- value: reset
61
- });
62
- return reset;
63
- }
64
- if (!exact) {
65
- const empty = emptyCollectionImpact;
66
- (collectionCache ??= []).push({
67
- address: selector.address,
68
- value: empty
69
- });
70
- return empty;
71
- }
72
- const incremental = {
73
- kind: "incremental",
74
- added: exact.added,
75
- removed: exact.removed,
76
- updated: exact.updated,
77
- orderChanged: exact.orderChanged
78
- };
79
- (collectionCache ??= []).push({
80
- address: selector.address,
81
- value: incremental
82
- });
83
- return incremental;
84
- }
85
- };
86
- };
87
- //#endregion
88
- //#region core/src/history.ts
89
- const createHistory = (input) => {
90
- const undos = [];
91
- const redos = [];
92
- const listeners = /* @__PURE__ */ new Set();
93
- let state = Object.freeze({
94
- undoDepth: 0,
95
- redoDepth: 0
96
- });
97
- const current = () => {
98
- if (state.undoDepth !== undos.length || state.redoDepth !== redos.length) state = Object.freeze({
99
- undoDepth: undos.length,
100
- redoDepth: redos.length
101
- });
102
- return state;
103
- };
104
- const emit = () => {
105
- if (listeners.size === 0) return;
106
- current();
107
- Array.from(listeners).forEach((listener) => listener());
108
- };
109
- const clear = () => {
110
- if (undos.length || redos.length) {
111
- undos.length = 0;
112
- redos.length = 0;
113
- emit();
114
- }
115
- };
116
- return {
117
- api: {
118
- current,
119
- subscribe: (listener) => {
120
- listeners.add(listener);
121
- return () => listeners.delete(listener);
122
- },
123
- undo: () => {
124
- const entry = undos.pop();
125
- if (!entry) return {
126
- status: "unchanged",
127
- revision: input.revision()
128
- };
129
- const result = input.apply(entry.inverse);
130
- if (result.status === "committed") {
131
- redos.push(entry);
132
- emit();
133
- } else undos.push(entry);
134
- return result;
135
- },
136
- redo: () => {
137
- const entry = redos.pop();
138
- if (!entry) return {
139
- status: "unchanged",
140
- revision: input.revision()
141
- };
142
- const result = input.apply(entry.operations);
143
- if (result.status === "committed") {
144
- undos.push(entry);
145
- emit();
146
- } else redos.push(entry);
147
- return result;
148
- },
149
- clear
150
- },
151
- record: (operations, inverse) => {
152
- if (input.capacity <= 0) return;
153
- undos.push({
154
- operations,
155
- inverse
156
- });
157
- if (undos.length > input.capacity) undos.shift();
158
- redos.length = 0;
159
- emit();
160
- },
161
- invalidate: clear
162
- };
163
- };
164
- //#endregion
165
- //#region core/src/access/writer.ts
166
- const schemaRoot = (schema) => require_dependency.object(schema.shape);
167
- const emit = (sink, operation) => sink(operation);
168
- const writerFor = (node, inputAddress, sink) => {
169
- const address = Object.freeze(inputAddress);
170
- if (node.kind === "field") return {
171
- set: (value) => emit(sink, {
172
- type: "field.set",
173
- at: address,
174
- value
175
- }),
176
- clear: node.optional ? () => emit(sink, {
177
- type: "field.clear",
178
- at: address
179
- }) : void 0
180
- };
181
- if (node.kind === "dict" || node.kind === "record") return {
182
- set: (key, value) => emit(sink, {
183
- type: "dict.set",
184
- at: address,
185
- key,
186
- value
187
- }),
188
- delete: (key) => emit(sink, {
189
- type: "dict.delete",
190
- at: address,
191
- key
192
- }),
193
- replace: (value) => emit(sink, {
194
- type: "dict.replace",
195
- at: address,
196
- value
197
- })
198
- };
199
- if (node.kind === "list") return {
200
- insert: (value, anchor) => emit(sink, {
201
- type: "list.insert",
202
- at: address,
203
- key: node.keyOf(value),
204
- value,
205
- anchor
206
- }),
207
- move: (key, anchor) => emit(sink, {
208
- type: "list.move",
209
- at: address,
210
- key,
211
- anchor
212
- }),
213
- remove: (key) => emit(sink, {
214
- type: "list.remove",
215
- at: address,
216
- key
217
- }),
218
- replace: (value) => emit(sink, {
219
- type: "list.replace",
220
- at: address,
221
- value,
222
- keys: value.map(node.keyOf)
223
- })
224
- };
225
- if (node.kind === "tree") return {
226
- insert: (treeNodeId, value, parentId, index) => emit(sink, {
227
- type: "tree.insert",
228
- at: address,
229
- treeNodeId,
230
- value,
231
- parentId,
232
- index
233
- }),
234
- move: (treeNodeId, parentId, index) => emit(sink, {
235
- type: "tree.move",
236
- at: address,
237
- treeNodeId,
238
- parentId,
239
- index
240
- }),
241
- remove: (treeNodeId) => emit(sink, {
242
- type: "tree.remove",
243
- at: address,
244
- treeNodeId
245
- }),
246
- set: (treeNodeId, value) => emit(sink, {
247
- type: "tree.set",
248
- at: address,
249
- treeNodeId,
250
- value
251
- }),
252
- replace: (value) => emit(sink, {
253
- type: "tree.replace",
254
- at: address,
255
- value
256
- })
257
- };
258
- if (node.kind === "table") {
259
- let items;
260
- return {
261
- create: (input, anchor) => {
262
- emit(sink, {
263
- type: "entity.create",
264
- at: address,
265
- entries: (Array.isArray(input) ? input : [input]).map(({ id, value }) => ({
266
- id,
267
- value
268
- })),
269
- anchor
270
- });
271
- },
272
- item: (id) => {
273
- const cached = items?.get(id);
274
- if (cached) return cached;
275
- const writer = writerFor(node.value, [...address, id], sink);
276
- (items ??= /* @__PURE__ */ new Map()).set(id, writer);
277
- return writer;
278
- },
279
- remove: (input) => emit(sink, {
280
- type: "entity.remove",
281
- at: address,
282
- ids: Array.isArray(input) ? [...input] : [input]
283
- }),
284
- move: (id, anchor) => emit(sink, {
285
- type: "entity.move",
286
- at: address,
287
- id,
288
- anchor
289
- })
290
- };
291
- }
292
- if (node.kind === "map") {
293
- let items;
294
- return {
295
- create: (input) => {
296
- emit(sink, {
297
- type: "entity.create",
298
- at: address,
299
- entries: (Array.isArray(input) ? input : [input]).map(({ id, value }) => ({
300
- id,
301
- value
302
- }))
303
- });
304
- },
305
- item: (id) => {
306
- const cached = items?.get(id);
307
- if (cached) return cached;
308
- const writer = writerFor(node.value, [...address, id], sink);
309
- (items ??= /* @__PURE__ */ new Map()).set(id, writer);
310
- return writer;
311
- },
312
- remove: (input) => emit(sink, {
313
- type: "entity.remove",
314
- at: address,
315
- ids: Array.isArray(input) ? [...input] : [input]
316
- })
317
- };
318
- }
319
- if (node.kind === "single") return writerFor(node.value, address, sink);
320
- if (node.kind === "variant") return { replace: (value) => emit(sink, {
321
- type: "variant.replace",
322
- at: address,
323
- value
324
- }) };
325
- let children;
326
- return new Proxy({}, { get: (_target, property) => {
327
- if (typeof property !== "string" || !node.shape[property]) return void 0;
328
- const cached = children?.get(property);
329
- if (cached) return cached;
330
- const writer = writerFor(node.shape[property], [...address, property], sink);
331
- (children ??= /* @__PURE__ */ new Map()).set(property, writer);
332
- return writer;
333
- } });
334
- };
335
- const documentWriter = (schema, sink) => writerFor(schemaRoot(schema), [], sink);
336
- //#endregion
337
- //#region core/src/mutation/issue.ts
338
- const ownAddress$1 = (address) => Object.freeze(address.slice());
339
- const at$1 = (address, code, message, operation) => Object.freeze({
340
- source: "mutation",
341
- code,
342
- address: ownAddress$1(address),
343
- message,
344
- ...operation === void 0 ? {} : { operation }
345
- });
346
- const from = (operation, code, message) => at$1(operation.at, code, message, operation.type);
347
- const input = (code, message) => at$1([], code, message);
348
- //#endregion
349
- //#region core/src/mutation/anchor.ts
350
- const length = (keys) => keys.length;
351
- const keyAt = (keys, index) => Array.isArray(keys) ? keys[index] : keys.at(index);
352
- const keyIndex = (keys, key) => Array.isArray(keys) ? keys.indexOf(key) : keys.index(key);
353
- const keys = (values, keyOf) => ({
354
- length: values.length,
355
- at: (index) => index >= 0 && index < values.length ? keyOf(values[index]) : void 0,
356
- index: (key) => {
357
- for (let index = 0; index < values.length; index += 1) if (keyOf(values[index]) === key) return index;
358
- return -1;
359
- }
360
- });
361
- const index = (keys, anchor) => {
362
- if (!anchor) return length(keys);
363
- if ("at" in anchor) return anchor.at === "start" ? 0 : length(keys);
364
- if ("before" in anchor) return keyIndex(keys, anchor.before);
365
- return keyIndex(keys, anchor.after) + 1;
366
- };
367
- const at = (keys, position) => position <= 0 ? { at: "start" } : { after: keyAt(keys, position - 1) };
368
- const valid = (keys, anchor) => {
369
- if (!anchor) return true;
370
- if (typeof anchor !== "object" || anchor === null) return false;
371
- if (Number("at" in anchor) + Number("before" in anchor) + Number("after" in anchor) !== 1) return false;
372
- if ("at" in anchor) return anchor.at === "start" || anchor.at === "end";
373
- return keyIndex(keys, "before" in anchor ? anchor.before : anchor.after) >= 0;
374
- };
375
- const afterRemove = (keys, removedIndex, anchor) => {
376
- const position = index(keys, anchor);
377
- return position > removedIndex ? position - 1 : position;
378
- };
379
- const validPositions = (length, positions) => {
380
- let previous = -1;
381
- for (let index = 0; index < positions.length; index += 1) {
382
- const position = positions[index];
383
- if (!Number.isInteger(position) || position < 0 || position <= previous || position > length + index) return false;
384
- previous = position;
385
- }
386
- return true;
387
- };
388
- const restore = (keys, inserted, positions) => {
389
- const currentLength = keys.length;
390
- if (inserted.length !== positions.length || !validPositions(currentLength, positions)) throw new Error("Ordered restore positions are invalid.");
391
- let readIndex = currentLength - 1;
392
- let insertedIndex = inserted.length - 1;
393
- keys.length = currentLength + inserted.length;
394
- for (let writeIndex = keys.length - 1; writeIndex >= 0; writeIndex -= 1) if (insertedIndex >= 0 && positions[insertedIndex] === writeIndex) {
395
- keys[writeIndex] = inserted[insertedIndex];
396
- insertedIndex -= 1;
397
- } else {
398
- keys[writeIndex] = keys[readIndex];
399
- readIndex -= 1;
400
- }
401
- };
402
- //#endregion
403
- //#region core/src/mutation/execute-entity.ts
404
- const resolveEntityCollection = (node, value) => {
405
- if (node.kind === "table") {
406
- if (!require_dependency.isRecord(value) || !Array.isArray(value.ids) || !require_dependency.isRecord(value.byId)) return { status: "invalid" };
407
- return {
408
- status: "resolved",
409
- collection: {
410
- kind: "table",
411
- ids: value.ids,
412
- byId: value.byId
413
- }
414
- };
415
- }
416
- return require_dependency.isRecord(value) ? {
417
- status: "resolved",
418
- collection: {
419
- kind: "map",
420
- byId: value
421
- }
422
- } : { status: "invalid" };
423
- };
424
- const rejected$4 = (operation, code, message) => ({
425
- status: "rejected",
426
- issue: from(operation, code, message)
427
- });
428
- const executeEntity = (target, operation, copyPayload) => {
429
- if (target.node.kind !== "table" && target.node.kind !== "map") return rejected$4(operation, "invalid-address", "Collection target is invalid.");
430
- const resolution = resolveEntityCollection(target.node, target.value);
431
- if (resolution.status === "invalid") return rejected$4(operation, "invalid-address", "Collection target is invalid.");
432
- const collection = resolution.collection;
433
- const ids = collection.kind === "table" ? collection.ids : void 0;
434
- if (operation.type === "entity.move" && collection.kind === "map") return rejected$4(operation, "invalid-operation", "Map entries are unordered.");
435
- const byId = collection.byId;
436
- if (operation.type === "entity.create") {
437
- if (operation.entries.length === 0) return { status: "unchanged" };
438
- const seen = /* @__PURE__ */ new Set();
439
- for (const entry of operation.entries) {
440
- if (seen.has(entry.id)) return rejected$4(operation, "duplicate-entity", "Entity ids must be unique within a batch.");
441
- seen.add(entry.id);
442
- if (Object.prototype.hasOwnProperty.call(byId, entry.id)) return rejected$4(operation, "duplicate-entity", `Entity '${entry.id}' already exists.`);
443
- }
444
- if (collection.kind === "map" && (operation.anchor || operation.positions)) return rejected$4(operation, "invalid-anchor", "Map entries do not support ordering metadata.");
445
- if (ids && operation.positions) {
446
- if (operation.positions.length !== operation.entries.length || !validPositions(ids.length, operation.positions)) return rejected$4(operation, "invalid-operation", "Entity restore positions are invalid.");
447
- } else if (ids && !valid(ids, operation.anchor)) return rejected$4(operation, "invalid-anchor", "Collection anchor is invalid.");
448
- for (const entry of operation.entries) byId[entry.id] = copyPayload ? require_dependency.cloneValue(entry.value, "canonical") : require_dependency.transferPayload(entry.value);
449
- if (ids) if (operation.positions) restore(ids, operation.entries.map((entry) => entry.id), operation.positions);
450
- else if (!operation.anchor || "at" in operation.anchor && operation.anchor.at === "end") for (const entry of operation.entries) ids.push(entry.id);
451
- else {
452
- const insertion = index(ids, operation.anchor);
453
- const currentLength = ids.length;
454
- ids.length = currentLength + operation.entries.length;
455
- for (let index = currentLength - 1; index >= insertion; index -= 1) ids[index + operation.entries.length] = ids[index];
456
- for (let index = 0; index < operation.entries.length; index += 1) ids[insertion + index] = operation.entries[index].id;
457
- }
458
- return {
459
- status: "changed",
460
- inverse: [{
461
- type: "entity.remove",
462
- at: operation.at,
463
- ids: operation.entries.map((entry) => entry.id)
464
- }]
465
- };
466
- }
467
- if (operation.type === "entity.remove") {
468
- if (operation.ids.length === 0) return { status: "unchanged" };
469
- const seen = /* @__PURE__ */ new Set();
470
- for (const id of operation.ids) {
471
- if (seen.has(id)) return rejected$4(operation, "duplicate-entity", "Entity ids must be unique within a batch.");
472
- seen.add(id);
473
- if (!Object.prototype.hasOwnProperty.call(byId, id)) return rejected$4(operation, "missing-entity", `Entity '${id}' does not exist.`);
474
- }
475
- const entries = [];
476
- const positions = [];
477
- if (ids) {
478
- const positionsById = /* @__PURE__ */ new Map();
479
- for (let index = 0; index < ids.length; index += 1) {
480
- const id = ids[index];
481
- if (seen.has(id)) positionsById.set(id, index);
482
- }
483
- for (const id of operation.ids) if (!positionsById.has(id)) return rejected$4(operation, "invalid-collection", `Collection index is missing '${id}'.`);
484
- let writeIndex = 0;
485
- for (let index = 0; index < ids.length; index += 1) {
486
- const id = ids[index];
487
- if (seen.has(id)) {
488
- entries.push({
489
- id,
490
- value: require_dependency.cloneValue(byId[id], "inverse")
491
- });
492
- positions.push(index);
493
- delete byId[id];
494
- } else ids[writeIndex++] = id;
495
- }
496
- ids.length = writeIndex;
497
- } else for (const id of operation.ids) {
498
- entries.push({
499
- id,
500
- value: require_dependency.cloneValue(byId[id], "inverse")
501
- });
502
- delete byId[id];
503
- }
504
- return {
505
- status: "changed",
506
- inverse: [{
507
- type: "entity.create",
508
- at: operation.at,
509
- entries,
510
- ...ids ? { positions } : {}
511
- }]
512
- };
513
- }
514
- const exists = Object.prototype.hasOwnProperty.call(byId, operation.id);
515
- const position = ids?.indexOf(operation.id) ?? -1;
516
- if (!exists) return rejected$4(operation, "missing-entity", `Entity '${operation.id}' does not exist.`);
517
- if (!ids || position < 0) return rejected$4(operation, "invalid-collection", `Collection index is missing '${operation.id}'.`);
518
- if (!valid(ids, operation.anchor)) return rejected$4(operation, "invalid-anchor", "Collection anchor is invalid.");
519
- if (operation.anchor && ("before" in operation.anchor && operation.anchor.before === operation.id || "after" in operation.anchor && operation.anchor.after === operation.id)) return rejected$4(operation, "invalid-anchor", "An entity cannot be moved relative to itself.");
520
- const nextIndex = afterRemove(ids, position, operation.anchor);
521
- if (nextIndex === position) return { status: "unchanged" };
522
- const inverse = {
523
- type: "entity.move",
524
- at: operation.at,
525
- id: operation.id,
526
- anchor: at(ids, position)
527
- };
528
- ids.splice(position, 1);
529
- ids.splice(nextIndex, 0, operation.id);
530
- return {
531
- status: "changed",
532
- inverse: [inverse]
533
- };
534
- };
535
- //#endregion
536
- //#region core/src/mutation/execute-list.ts
537
- const rejected$3 = (operation, code, message) => ({
538
- status: "rejected",
539
- issue: from(operation, code, message)
540
- });
541
- const executeList = (target, operation, copyPayload) => {
542
- if (!Array.isArray(target.value) || target.node.kind !== "list") return rejected$3(operation, "invalid-address", "List target is invalid.");
543
- const list = target.value;
544
- const orderedKeys = keys(list, target.node.keyOf);
545
- const own = (value) => copyPayload ? require_dependency.ownPayload(value) : value;
546
- if (operation.type === "list.replace") {
547
- if (operation.keys.length !== operation.value.length) return rejected$3(operation, "invalid-list-keys", "List replacement keys are invalid.");
548
- const seen = /* @__PURE__ */ new Set();
549
- for (let index = 0; index < operation.value.length; index += 1) {
550
- const key = operation.keys[index];
551
- if (seen.has(key) || target.node.keyOf(operation.value[index]) !== key) return rejected$3(operation, "invalid-list-keys", "List replacement keys are invalid.");
552
- seen.add(key);
553
- }
554
- if (require_dependency.sameStructuralValue(list, operation.value)) return { status: "unchanged" };
555
- const keys = new Array(list.length);
556
- for (let index = 0; index < list.length; index += 1) keys[index] = target.node.keyOf(list[index]);
557
- const inverse = {
558
- type: "list.replace",
559
- at: operation.at,
560
- value: require_dependency.cloneValue(list, "inverse"),
561
- keys
562
- };
563
- const owned = own(operation.value);
564
- list.length = owned.length;
565
- for (let index = 0; index < owned.length; index += 1) list[index] = owned[index];
566
- return {
567
- status: "changed",
568
- inverse: [inverse]
569
- };
570
- }
571
- if (operation.type === "list.insert") {
572
- if (target.node.keyOf(operation.value) !== operation.key) return rejected$3(operation, "invalid-list-key", "List item key does not match schema.");
573
- if (orderedKeys.index(operation.key) >= 0) return rejected$3(operation, "duplicate-list-item", `List item '${operation.key}' already exists.`);
574
- if (!valid(orderedKeys, operation.anchor)) return rejected$3(operation, "invalid-anchor", "List anchor is invalid.");
575
- list.splice(index(orderedKeys, operation.anchor), 0, own(operation.value));
576
- return {
577
- status: "changed",
578
- inverse: [{
579
- type: "list.remove",
580
- at: operation.at,
581
- key: operation.key
582
- }]
583
- };
584
- }
585
- const position = orderedKeys.index(operation.key);
586
- if (position < 0) return rejected$3(operation, "missing-list-item", `List item '${operation.key}' does not exist.`);
587
- if (operation.type === "list.remove") {
588
- const inverse = {
589
- type: "list.insert",
590
- at: operation.at,
591
- key: operation.key,
592
- value: require_dependency.cloneValue(list[position], "inverse"),
593
- anchor: at(orderedKeys, position)
594
- };
595
- list.splice(position, 1);
596
- return {
597
- status: "changed",
598
- inverse: [inverse]
599
- };
600
- }
601
- if (!valid(orderedKeys, operation.anchor)) return rejected$3(operation, "invalid-anchor", "List anchor is invalid.");
602
- if (operation.anchor && ("before" in operation.anchor && operation.anchor.before === operation.key || "after" in operation.anchor && operation.anchor.after === operation.key)) return rejected$3(operation, "invalid-anchor", "A list item cannot be moved relative to itself.");
603
- const nextIndex = afterRemove(orderedKeys, position, operation.anchor);
604
- if (nextIndex === position) return { status: "unchanged" };
605
- const inverse = {
606
- type: "list.move",
607
- at: operation.at,
608
- key: operation.key,
609
- anchor: at(orderedKeys, position)
610
- };
611
- const [entry] = list.splice(position, 1);
612
- list.splice(nextIndex, 0, entry);
613
- return {
614
- status: "changed",
615
- inverse: [inverse]
616
- };
617
- };
618
- //#endregion
619
- //#region core/src/mutation/tree.ts
620
- const has$1 = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
621
- const validIndex = (index) => index === void 0 || Number.isInteger(index) && index >= 0;
622
- const rejected$2 = (code, message) => ({
623
- status: "rejected",
624
- code,
625
- message
626
- });
627
- const node = (tree, id) => tree.nodes[id];
628
- const childIndex = (parent, id) => parent.children.indexOf(id);
629
- const sameOrder$1 = (left, right) => {
630
- if (left.length !== right.length) return false;
631
- for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return false;
632
- return true;
633
- };
634
- const rootPresence = (id) => id === void 0 ? { status: "absent" } : {
635
- status: "present",
636
- id
637
- };
638
- const capture = (change, id, presence) => {
639
- if (!change.nodes.has(id)) change.nodes.set(id, presence);
640
- };
641
- const without = (values, id) => {
642
- const result = [];
643
- for (const value of values) if (value !== id) result.push(value);
644
- return result;
645
- };
646
- const inserted = (values, id, index) => {
647
- const result = [...values];
648
- result.splice(Math.min(index, result.length), 0, id);
649
- return result;
650
- };
651
- const moved = (values, id, index) => {
652
- const result = without(values, id);
653
- result.splice(Math.min(index, result.length), 0, id);
654
- return result;
655
- };
656
- const parentPresence = (tree, id, children) => {
657
- const entry = node(tree, id);
658
- return entry ? {
659
- status: "present",
660
- ...entry.parentId === void 0 ? {} : { parentId: entry.parentId },
661
- children,
662
- value: entry.value
663
- } : { status: "absent" };
664
- };
665
- const restoreIncremental = (value, change) => {
666
- if (!is(value)) return value;
667
- if (change.root.status === "absent") delete value.rootId;
668
- else value.rootId = change.root.id;
669
- for (const [id, before] of change.nodes) {
670
- if (before.status === "absent") {
671
- delete value.nodes[id];
672
- continue;
673
- }
674
- value.nodes[id] = {
675
- ...before.parentId === void 0 ? {} : { parentId: before.parentId },
676
- children: [...before.children],
677
- value: before.value
678
- };
679
- }
680
- return value;
681
- };
682
- const restoreChange = (value, change) => change.mode === "whole" ? require_dependency.ownPayload(change.value, "journal") : restoreIncremental(value, change);
683
- const wholeChange = (inverse, previous) => {
684
- if (!previous) return {
685
- mode: "whole",
686
- value: inverse.value
687
- };
688
- if (previous.mode === "whole") return previous;
689
- return {
690
- mode: "whole",
691
- value: restoreIncremental(require_dependency.ownPayload(inverse.value, "journal"), previous)
692
- };
693
- };
694
- const removedNodePresences = (inverses) => {
695
- const children = /* @__PURE__ */ new Map();
696
- for (const inverse of inverses) {
697
- if (inverse.parentId === void 0) continue;
698
- const entries = children.get(inverse.parentId);
699
- const child = {
700
- id: inverse.treeNodeId,
701
- index: inverse.index ?? Number.MAX_SAFE_INTEGER
702
- };
703
- if (entries) entries.push(child);
704
- else children.set(inverse.parentId, [child]);
705
- }
706
- const result = /* @__PURE__ */ new Map();
707
- for (const inverse of inverses) {
708
- const ordered = children.get(inverse.treeNodeId) ?? [];
709
- ordered.sort((left, right) => left.index - right.index);
710
- result.set(inverse.treeNodeId, {
711
- status: "present",
712
- ...inverse.parentId === void 0 ? {} : { parentId: inverse.parentId },
713
- children: ordered.map((entry) => entry.id),
714
- value: inverse.value
715
- });
716
- }
717
- return result;
718
- };
719
- const recordChange = (previous, current, forward, inverses) => {
720
- const replacement = inverses[0];
721
- if (replacement?.type === "tree.replace") return wholeChange(replacement, previous);
722
- if (previous?.mode === "whole") return previous;
723
- const change = previous ?? {
724
- mode: "incremental",
725
- root: forward.type === "tree.insert" && forward.parentId === void 0 ? { status: "absent" } : forward.type === "tree.remove" && inverses[0]?.type === "tree.insert" ? rootPresence(inverses[0].parentId === void 0 ? inverses[0].treeNodeId : current.rootId) : rootPresence(current.rootId),
726
- nodes: /* @__PURE__ */ new Map()
727
- };
728
- if (forward.type === "tree.insert") {
729
- capture(change, forward.treeNodeId, { status: "absent" });
730
- if (forward.parentId !== void 0) {
731
- const parentNode = node(current, forward.parentId);
732
- if (parentNode) capture(change, forward.parentId, parentPresence(current, forward.parentId, without(parentNode.children, forward.treeNodeId)));
733
- }
734
- return change;
735
- }
736
- if (forward.type === "tree.remove") {
737
- const inserts = inverses.filter((inverse) => inverse.type === "tree.insert");
738
- const removed = removedNodePresences(inserts);
739
- for (const [id, presence] of removed) capture(change, id, presence);
740
- const first = inserts[0];
741
- if (first?.parentId !== void 0) {
742
- const parentNode = node(current, first.parentId);
743
- if (parentNode) capture(change, first.parentId, parentPresence(current, first.parentId, inserted(parentNode.children, first.treeNodeId, first.index ?? parentNode.children.length)));
744
- }
745
- return change;
746
- }
747
- if (forward.type === "tree.set") {
748
- const inverse = inverses[0];
749
- const entry = node(current, forward.treeNodeId);
750
- if (entry && inverse?.type === "tree.set") capture(change, forward.treeNodeId, {
751
- status: "present",
752
- ...entry.parentId === void 0 ? {} : { parentId: entry.parentId },
753
- children: [...entry.children],
754
- value: inverse.value
755
- });
756
- return change;
757
- }
758
- if (forward.type === "tree.move") {
759
- const inverse = inverses[0];
760
- const entry = node(current, forward.treeNodeId);
761
- if (!entry || inverse?.type !== "tree.move" || inverse.parentId === void 0) return change;
762
- capture(change, forward.treeNodeId, {
763
- status: "present",
764
- parentId: inverse.parentId,
765
- children: [...entry.children],
766
- value: entry.value
767
- });
768
- const oldParent = node(current, inverse.parentId);
769
- if (oldParent) {
770
- const children = inverse.parentId === forward.parentId ? moved(oldParent.children, forward.treeNodeId, inverse.index ?? oldParent.children.length) : inserted(oldParent.children, forward.treeNodeId, inverse.index ?? oldParent.children.length);
771
- capture(change, inverse.parentId, parentPresence(current, inverse.parentId, children));
772
- }
773
- if (forward.parentId !== void 0 && forward.parentId !== inverse.parentId) {
774
- const nextParent = node(current, forward.parentId);
775
- if (nextParent) capture(change, forward.parentId, parentPresence(current, forward.parentId, without(nextParent.children, forward.treeNodeId)));
776
- }
777
- }
778
- return change;
779
- };
780
- const sameNodePresence = (before, value) => {
781
- if (before.status === "absent") return value === void 0;
782
- return value !== void 0 && before.parentId === value.parentId && sameOrder$1(before.children, value.children) && require_dependency.sameStructuralValue(before.value, value.value);
783
- };
784
- const changeChanged = (change, value) => {
785
- if (change.mode === "whole") return !require_dependency.sameStructuralValue(change.value, value);
786
- if (!is(value)) return true;
787
- if ((change.root.status === "present" ? change.root.id : void 0) !== value.rootId) return true;
788
- for (const [id, before] of change.nodes) if (!sameNodePresence(before, node(value, id))) return true;
789
- return false;
790
- };
791
- const is = (value) => require_dependency.isRecord(value) && require_dependency.isRecord(value.nodes);
792
- const contains$1 = (tree, id) => has$1(tree.nodes, id);
793
- const validate = (value) => {
794
- if (!is(value)) return false;
795
- const ids = Object.keys(value.nodes);
796
- if (ids.length === 0) return value.rootId === void 0;
797
- if (typeof value.rootId !== "string" || !has$1(value.nodes, value.rootId)) return false;
798
- for (const id of ids) {
799
- const entry = value.nodes[id];
800
- if (!require_dependency.isRecord(entry) || !Array.isArray(entry.children)) return false;
801
- if (entry.children.some((child) => typeof child !== "string") || new Set(entry.children).size !== entry.children.length) return false;
802
- if (entry.parentId !== void 0 && typeof entry.parentId !== "string") return false;
803
- if (id === value.rootId) {
804
- if (entry.parentId !== void 0) return false;
805
- } else if (entry.parentId === void 0 || !has$1(value.nodes, entry.parentId)) return false;
806
- for (const child of entry.children) {
807
- const childNode = value.nodes[child];
808
- if (!childNode || childNode.parentId !== id) return false;
809
- }
810
- }
811
- const seen = /* @__PURE__ */ new Set();
812
- const stack = [value.rootId];
813
- while (stack.length) {
814
- const id = stack.pop();
815
- if (seen.has(id)) return false;
816
- seen.add(id);
817
- const entry = value.nodes[id];
818
- if (!entry) return false;
819
- for (const child of entry.children) stack.push(child);
820
- }
821
- return seen.size === ids.length;
822
- };
823
- const documentTreeError = (node, value, address) => {
824
- if ("optional" in node && node.optional && value === void 0) return void 0;
825
- if (node.kind === "tree") return validate(value) ? void 0 : address;
826
- if (node.kind === "object") {
827
- if (!require_dependency.isRecord(value)) return void 0;
828
- for (const [key, child] of Object.entries(node.shape)) {
829
- const error = documentTreeError(child, value[key], [...address, key]);
830
- if (error) return error;
831
- }
832
- return;
833
- }
834
- if (node.kind === "single") return documentTreeError(node.value, value, address);
835
- if (node.kind === "variant") {
836
- if (!require_dependency.isRecord(value) || typeof value[node.tag] !== "string") return void 0;
837
- const variant = node.variants[value[node.tag]];
838
- return variant ? documentTreeError(variant, value, address) : void 0;
839
- }
840
- if (node.kind === "table") {
841
- if (!require_dependency.isRecord(value) || !require_dependency.isRecord(value.byId)) return void 0;
842
- for (const [id, entry] of Object.entries(value.byId)) {
843
- const error = documentTreeError(node.value, entry, [...address, id]);
844
- if (error) return error;
845
- }
846
- return;
847
- }
848
- if (node.kind === "map") {
849
- if (!require_dependency.isRecord(value)) return void 0;
850
- for (const [id, entry] of Object.entries(value)) {
851
- const error = documentTreeError(node.value, entry, [...address, id]);
852
- if (error) return error;
853
- }
854
- }
855
- };
856
- const invalidDocument = (schema, value) => documentTreeError({
857
- kind: "object",
858
- shape: schema.shape
859
- }, value, []);
860
- const replace = (current, operation) => {
861
- if (!validate(operation.value)) return rejected$2("invalid-tree", "Tree replacement is malformed.");
862
- if (require_dependency.sameStructuralValue(current, operation.value)) return { status: "unchanged" };
863
- return {
864
- status: "changed",
865
- inverse: [{
866
- type: "tree.replace",
867
- at: operation.at,
868
- value: require_dependency.cloneValue(current, "inverse")
869
- }]
870
- };
871
- };
872
- const insert = (tree, operation, value) => {
873
- if (contains$1(tree, operation.treeNodeId)) return rejected$2("duplicate-tree-node", `Tree node '${operation.treeNodeId}' already exists.`);
874
- if (!validIndex(operation.index)) return rejected$2("invalid-tree-index", "Tree index is invalid.");
875
- if (tree.rootId === void 0) {
876
- if (operation.parentId !== void 0) return rejected$2("missing-tree-parent", `Tree parent '${operation.parentId}' does not exist.`);
877
- tree.nodes[operation.treeNodeId] = {
878
- children: [],
879
- value
880
- };
881
- tree.rootId = operation.treeNodeId;
882
- } else {
883
- if (operation.parentId === void 0) return rejected$2("invalid-tree", "A non-empty tree has exactly one root.");
884
- const parentNode = node(tree, operation.parentId);
885
- if (!parentNode) return rejected$2("missing-tree-parent", `Tree parent '${operation.parentId}' does not exist.`);
886
- tree.nodes[operation.treeNodeId] = {
887
- parentId: operation.parentId,
888
- children: [],
889
- value
890
- };
891
- parentNode.children.splice(Math.min(operation.index ?? parentNode.children.length, parentNode.children.length), 0, operation.treeNodeId);
892
- }
893
- return {
894
- status: "changed",
895
- inverse: [{
896
- type: "tree.remove",
897
- at: operation.at,
898
- treeNodeId: operation.treeNodeId
899
- }]
900
- };
901
- };
902
- const set = (tree, operation, value) => {
903
- const entry = node(tree, operation.treeNodeId);
904
- if (!entry) return rejected$2("missing-tree-node", `Tree node '${operation.treeNodeId}' does not exist.`);
905
- if (Object.is(entry.value, value)) return { status: "unchanged" };
906
- const inverse = {
907
- type: "tree.set",
908
- at: operation.at,
909
- treeNodeId: operation.treeNodeId,
910
- value: require_dependency.cloneValue(entry.value, "inverse")
911
- };
912
- entry.value = value;
913
- return {
914
- status: "changed",
915
- inverse: [inverse]
916
- };
917
- };
918
- const remove = (tree, operation) => {
919
- const first = node(tree, operation.treeNodeId);
920
- if (!first) return rejected$2("missing-tree-node", `Tree node '${operation.treeNodeId}' does not exist.`);
921
- const parentId = first.parentId;
922
- const parentNode = parentId === void 0 ? void 0 : node(tree, parentId);
923
- const originalIndex = parentNode ? childIndex(parentNode, operation.treeNodeId) : 0;
924
- if (parentId !== void 0 && (!parentNode || originalIndex < 0) || parentId === void 0 && tree.rootId !== operation.treeNodeId) return rejected$2("invalid-tree", "Tree parent links are inconsistent.");
925
- const entries = [];
926
- const seen = /* @__PURE__ */ new Set();
927
- const stack = [{
928
- id: operation.treeNodeId,
929
- parentId,
930
- index: originalIndex
931
- }];
932
- while (stack.length) {
933
- const frame = stack.pop();
934
- const entry = node(tree, frame.id);
935
- if (!entry || seen.has(frame.id) || entry.parentId !== frame.parentId) return rejected$2("invalid-tree", "Tree contains an invalid descendant.");
936
- seen.add(frame.id);
937
- entries.push({
938
- id: frame.id,
939
- parentId: frame.parentId,
940
- index: frame.index,
941
- value: require_dependency.cloneValue(entry.value, "inverse")
942
- });
943
- for (let index = entry.children.length - 1; index >= 0; index -= 1) {
944
- const childId = entry.children[index];
945
- const child = node(tree, childId);
946
- if (!child || child.parentId !== frame.id) return rejected$2("invalid-tree", "Tree child links are inconsistent.");
947
- stack.push({
948
- id: childId,
949
- parentId: frame.id,
950
- index
951
- });
952
- }
953
- }
954
- if (parentNode) parentNode.children.splice(originalIndex, 1);
955
- for (let index = entries.length - 1; index >= 0; index -= 1) delete tree.nodes[entries[index].id];
956
- if (tree.rootId === operation.treeNodeId) delete tree.rootId;
957
- return {
958
- status: "changed",
959
- inverse: entries.map((entry) => ({
960
- type: "tree.insert",
961
- at: operation.at,
962
- treeNodeId: entry.id,
963
- ...entry.parentId === void 0 ? {} : { parentId: entry.parentId },
964
- index: entry.index,
965
- value: entry.value
966
- }))
967
- };
968
- };
969
- const move = (tree, operation) => {
970
- const entry = node(tree, operation.treeNodeId);
971
- if (!entry) return rejected$2("missing-tree-node", `Tree node '${operation.treeNodeId}' does not exist.`);
972
- if (!validIndex(operation.index)) return rejected$2("invalid-tree-index", "Tree index is invalid.");
973
- if (tree.rootId === operation.treeNodeId) return rejected$2("invalid-tree", "The root cannot be moved.");
974
- if (operation.parentId === void 0) return rejected$2("invalid-tree", "Only the root can have no parent.");
975
- const nextParent = node(tree, operation.parentId);
976
- if (!nextParent) return rejected$2("missing-tree-parent", `Tree parent '${operation.parentId}' does not exist.`);
977
- if (operation.parentId === operation.treeNodeId) return rejected$2("tree-cycle", "A tree node cannot parent itself.");
978
- const descendants = [operation.treeNodeId];
979
- const seen = /* @__PURE__ */ new Set();
980
- while (descendants.length) {
981
- const id = descendants.pop();
982
- if (seen.has(id)) return rejected$2("invalid-tree", "Tree contains a cycle.");
983
- seen.add(id);
984
- const current = node(tree, id);
985
- if (!current) return rejected$2("invalid-tree", "Tree contains a missing node.");
986
- for (const childId of current.children) {
987
- const child = node(tree, childId);
988
- if (!child || child.parentId !== id) return rejected$2("invalid-tree", "Tree child links are inconsistent.");
989
- if (childId === operation.parentId) return rejected$2("tree-cycle", "Tree move would create a cycle.");
990
- descendants.push(childId);
991
- }
992
- }
993
- const parentId = entry.parentId;
994
- const currentParent = parentId === void 0 ? void 0 : node(tree, parentId);
995
- if (!currentParent || parentId === void 0) return rejected$2("invalid-tree", "Tree parent links are inconsistent.");
996
- const originalIndex = childIndex(currentParent, operation.treeNodeId);
997
- if (originalIndex < 0) return rejected$2("invalid-tree", "Tree parent links are inconsistent.");
998
- let nextIndex = Math.min(operation.index ?? nextParent.children.length, nextParent.children.length);
999
- currentParent.children.splice(originalIndex, 1);
1000
- if (parentId === operation.parentId && nextIndex > originalIndex) nextIndex -= 1;
1001
- if (parentId === operation.parentId && nextIndex === originalIndex) {
1002
- currentParent.children.splice(originalIndex, 0, operation.treeNodeId);
1003
- return { status: "unchanged" };
1004
- }
1005
- nextParent.children.splice(nextIndex, 0, operation.treeNodeId);
1006
- entry.parentId = operation.parentId;
1007
- return {
1008
- status: "changed",
1009
- inverse: [{
1010
- type: "tree.move",
1011
- at: operation.at,
1012
- treeNodeId: operation.treeNodeId,
1013
- parentId,
1014
- index: originalIndex
1015
- }]
1016
- };
1017
- };
1018
- //#endregion
1019
- //#region core/src/mutation/execute-tree.ts
1020
- const outcome = (operation, value) => value.status === "rejected" ? {
1021
- status: "rejected",
1022
- issue: from(operation, value.code, value.message)
1023
- } : value;
1024
- const executeTree = (root, target, operation, copyPayload) => {
1025
- if (!is(target.value)) return {
1026
- status: "rejected",
1027
- issue: from(operation, "invalid-address", "Tree target is invalid.")
1028
- };
1029
- const own = (value) => copyPayload ? require_dependency.ownPayload(value) : value;
1030
- if (operation.type === "tree.replace") {
1031
- const result = replace(target.value, operation);
1032
- if (result.status === "changed") require_dependency.set(root, operation.at, require_dependency.ownPayload(operation.value));
1033
- return outcome(operation, result);
1034
- }
1035
- if (operation.type === "tree.insert") return outcome(operation, insert(target.value, operation, own(operation.value)));
1036
- if (operation.type === "tree.set") return outcome(operation, set(target.value, operation, own(operation.value)));
1037
- if (operation.type === "tree.remove") return outcome(operation, remove(target.value, operation));
1038
- return outcome(operation, move(target.value, operation));
1039
- };
1040
- //#endregion
1041
- //#region core/src/mutation/execute-value.ts
1042
- const rejected$1 = (operation, code, message) => ({
1043
- status: "rejected",
1044
- issue: from(operation, code, message)
1045
- });
1046
- const executeValue = (target, operation, copyPayload) => {
1047
- const own = (value) => copyPayload ? require_dependency.ownPayload(value) : value;
1048
- if (operation.type === "field.set" || operation.type === "field.clear") {
1049
- const existed = Object.prototype.hasOwnProperty.call(target.parent, target.key);
1050
- if (operation.type === "field.clear") {
1051
- if (target.node.kind !== "field" || !target.node.optional) return rejected$1(operation, "required-field", "Only optional fields can be cleared.");
1052
- if (!existed) return { status: "unchanged" };
1053
- const inverse = {
1054
- type: "field.set",
1055
- at: operation.at,
1056
- value: target.value
1057
- };
1058
- delete target.parent[target.key];
1059
- return {
1060
- status: "changed",
1061
- inverse: [inverse]
1062
- };
1063
- }
1064
- if (existed && Object.is(target.value, operation.value)) return { status: "unchanged" };
1065
- const inverse = existed ? {
1066
- type: "field.set",
1067
- at: operation.at,
1068
- value: target.value
1069
- } : {
1070
- type: "field.clear",
1071
- at: operation.at
1072
- };
1073
- target.parent[target.key] = operation.value;
1074
- return {
1075
- status: "changed",
1076
- inverse: [inverse]
1077
- };
1078
- }
1079
- if (operation.type === "variant.replace") {
1080
- if (require_dependency.sameStructuralValue(target.value, operation.value)) return { status: "unchanged" };
1081
- const inverse = {
1082
- type: "variant.replace",
1083
- at: operation.at,
1084
- value: require_dependency.ownPayload(target.value, "inverse")
1085
- };
1086
- target.parent[target.key] = own(operation.value);
1087
- return {
1088
- status: "changed",
1089
- inverse: [inverse]
1090
- };
1091
- }
1092
- if (!require_dependency.isRecord(target.value)) return rejected$1(operation, "invalid-address", "Dictionary target is invalid.");
1093
- if (operation.type === "dict.replace") {
1094
- if (require_dependency.sameStructuralValue(target.value, operation.value)) return { status: "unchanged" };
1095
- const inverse = {
1096
- type: "dict.replace",
1097
- at: operation.at,
1098
- value: require_dependency.cloneValue(target.value, "inverse")
1099
- };
1100
- target.parent[target.key] = own(operation.value);
1101
- return {
1102
- status: "changed",
1103
- inverse: [inverse]
1104
- };
1105
- }
1106
- const existed = Object.prototype.hasOwnProperty.call(target.value, operation.key);
1107
- if (operation.type === "dict.delete") {
1108
- if (!existed) return { status: "unchanged" };
1109
- const inverse = {
1110
- type: "dict.set",
1111
- at: operation.at,
1112
- key: operation.key,
1113
- value: target.value[operation.key]
1114
- };
1115
- delete target.value[operation.key];
1116
- return {
1117
- status: "changed",
1118
- inverse: [inverse]
1119
- };
1120
- }
1121
- if (existed && Object.is(target.value[operation.key], operation.value)) return { status: "unchanged" };
1122
- const inverse = existed ? {
1123
- type: "dict.set",
1124
- at: operation.at,
1125
- key: operation.key,
1126
- value: target.value[operation.key]
1127
- } : {
1128
- type: "dict.delete",
1129
- at: operation.at,
1130
- key: operation.key
1131
- };
1132
- target.value[operation.key] = operation.value;
1133
- return {
1134
- status: "changed",
1135
- inverse: [inverse]
1136
- };
1137
- };
1138
- //#endregion
1139
- //#region core/src/mutation/execute.ts
1140
- const invalidTarget = (operation) => ({
1141
- status: "rejected",
1142
- issue: from(operation, "invalid-address", `Operation '${operation.type}' does not match the schema address.`)
1143
- });
1144
- const execute = (root, operation, target, copyPayload) => {
1145
- if (operation.type === "field.set" || operation.type === "field.clear") return !target || target.node.kind !== "field" ? invalidTarget(operation) : executeValue(target, operation, copyPayload);
1146
- if (operation.type === "variant.replace") return !target || target.node.kind !== "variant" ? invalidTarget(operation) : executeValue(target, operation, copyPayload);
1147
- if (operation.type === "dict.set" || operation.type === "dict.delete" || operation.type === "dict.replace") return !target || target.node.kind !== "dict" && target.node.kind !== "record" ? invalidTarget(operation) : executeValue(target, operation, copyPayload);
1148
- if (operation.type === "entity.create" || operation.type === "entity.remove" || operation.type === "entity.move") return !target || target.node.kind !== "table" && target.node.kind !== "map" ? invalidTarget(operation) : executeEntity(target, operation, copyPayload);
1149
- if (operation.type === "list.insert" || operation.type === "list.move" || operation.type === "list.remove" || operation.type === "list.replace") return !target || target.node.kind !== "list" ? invalidTarget(operation) : executeList(target, operation, copyPayload);
1150
- if (operation.type === "tree.insert" || operation.type === "tree.move" || operation.type === "tree.remove" || operation.type === "tree.set" || operation.type === "tree.replace") return !target || target.node.kind !== "tree" ? invalidTarget(operation) : executeTree(root, target, operation, copyPayload);
1151
- return {
1152
- status: "rejected",
1153
- issue: from(operation, "unknown-operation", "Unknown document operation.")
1154
- };
1155
- };
1156
- //#endregion
1157
- //#region core/src/mutation/journal.ts
1158
- const indexNode = () => ({ children: /* @__PURE__ */ new Map() });
1159
- const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
1160
- const sameAddress = (left, right) => {
1161
- if (left.length !== right.length) return false;
1162
- for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return false;
1163
- return true;
1164
- };
1165
- const sameOrder = (left, right) => {
1166
- if (left.length !== right.length) return false;
1167
- for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return false;
1168
- return true;
1169
- };
1170
- const replaceArray = (target, value) => {
1171
- target.length = value.length;
1172
- for (let index = 0; index < value.length; index += 1) target[index] = value[index];
1173
- };
1174
- const present = (value) => ({
1175
- status: "present",
1176
- value
1177
- });
1178
- const absent = Object.freeze({ status: "absent" });
1179
- const inverseMismatch = (operation) => {
1180
- throw new Error(`Mutation inverse does not match '${operation.type}'.`);
1181
- };
1182
- const ownsDescendant = (subject, address) => {
1183
- if (subject.address.length >= address.length) return false;
1184
- if (subject.kind === "variant") return true;
1185
- if (subject.kind !== "entity") return false;
1186
- return subject.entries.has(address[subject.address.length]);
1187
- };
1188
- const nodeAt = (root, address) => {
1189
- let node = root;
1190
- for (const segment of address) {
1191
- node = node.children.get(segment);
1192
- if (!node) return void 0;
1193
- }
1194
- return node;
1195
- };
1196
- const indexedSubjects = (root, address) => {
1197
- const start = nodeAt(root, address);
1198
- if (!start) return [];
1199
- const subjects = [];
1200
- const stack = [start];
1201
- while (stack.length) {
1202
- const node = stack.pop();
1203
- if (!node) break;
1204
- if (node.subject) subjects.push(node.subject);
1205
- for (const child of node.children.values()) stack.push(child);
1206
- }
1207
- return subjects;
1208
- };
1209
- const writePresence = (root, address, before) => {
1210
- const target = require_dependency.locate(root, address);
1211
- if (!target) return;
1212
- if (before.status === "present") target.parent[target.key] = before.value;
1213
- else if (Array.isArray(target.parent)) target.parent.splice(Number(target.key), 1);
1214
- else delete target.parent[String(target.key)];
1215
- };
1216
- const writeContainer = (root, address, value) => {
1217
- const target = require_dependency.locate(root, address);
1218
- if (!target) return;
1219
- target.parent[target.key] = value;
1220
- };
1221
- const restoreDict = (value, state) => {
1222
- if (state.mode === "whole") {
1223
- for (const key of Object.keys(value)) delete value[key];
1224
- for (const [key, entry] of Object.entries(state.value)) value[key] = entry;
1225
- return;
1226
- }
1227
- for (const [key, before] of state.entries) if (before.status === "present") value[key] = before.value;
1228
- else delete value[key];
1229
- };
1230
- const restoreList = (value, subject) => {
1231
- if (subject.state.mode === "whole") {
1232
- replaceArray(value, subject.state.value);
1233
- return;
1234
- }
1235
- const entries = /* @__PURE__ */ new Map();
1236
- for (const entry of value) entries.set(subject.node.keyOf(entry), entry);
1237
- for (const [key, before] of subject.state.items) if (before.status === "present") entries.set(key, before.value);
1238
- else entries.delete(key);
1239
- const restored = new Array(subject.state.order.length);
1240
- for (let index = 0; index < subject.state.order.length; index += 1) restored[index] = entries.get(subject.state.order[index]);
1241
- replaceArray(value, restored);
1242
- };
1243
- const entityCollection = (subject, value) => resolveEntityCollection(subject.node, value);
1244
- const restoreEntity = (value, subject) => {
1245
- const resolution = entityCollection(subject, value);
1246
- if (resolution.status === "invalid") return;
1247
- const collection = resolution.collection;
1248
- for (const [id, before] of subject.entries) if (before.status === "present") collection.byId[id] = before.value;
1249
- else delete collection.byId[id];
1250
- if (collection.kind !== "table") return;
1251
- if (subject.order.kind === "tracked") {
1252
- replaceArray(collection.ids, subject.order.before);
1253
- return;
1254
- }
1255
- if (subject.order.kind === "stable") restoreEntityOrder(collection.ids, subject.order.inverses);
1256
- };
1257
- const restoreRootSubject = (value, subject) => {
1258
- if (subject.kind === "value") return subject.before.status === "present" ? subject.before.value : void 0;
1259
- if (subject.kind === "variant") return subject.before;
1260
- if (subject.kind === "dict") {
1261
- if (require_dependency.isRecord(value)) restoreDict(value, subject.state);
1262
- return value;
1263
- }
1264
- if (subject.kind === "entity") {
1265
- restoreEntity(value, subject);
1266
- return value;
1267
- }
1268
- if (subject.kind === "list") {
1269
- if (Array.isArray(value)) restoreList(value, subject);
1270
- return value;
1271
- }
1272
- return restoreChange(value, subject.state);
1273
- };
1274
- const restoreSubject = (value, prefix, subject) => {
1275
- if (sameAddress(prefix, subject.address)) return restoreRootSubject(value, subject);
1276
- const address = subject.address.slice(prefix.length);
1277
- if (subject.kind === "value") {
1278
- writePresence(value, address, subject.before);
1279
- return value;
1280
- }
1281
- if (subject.kind === "variant") {
1282
- writeContainer(value, address, subject.before);
1283
- return value;
1284
- }
1285
- const current = require_dependency.read(value, address);
1286
- if (subject.kind === "dict") {
1287
- if (require_dependency.isRecord(current)) restoreDict(current, subject.state);
1288
- return value;
1289
- }
1290
- if (subject.kind === "entity") {
1291
- restoreEntity(current, subject);
1292
- return value;
1293
- }
1294
- if (subject.kind === "list") {
1295
- if (Array.isArray(current)) restoreList(current, subject);
1296
- return value;
1297
- }
1298
- const restored = restoreChange(current, subject.state);
1299
- if (restored !== current) writeContainer(value, address, restored);
1300
- return value;
1301
- };
1302
- const valueChanged = (root, subject) => {
1303
- const target = require_dependency.locate(root, subject.address);
1304
- const exists = !!target && hasOwn(target.parent, target.key);
1305
- if (subject.before.status === "absent") return exists;
1306
- return !exists || !Object.is(subject.before.value, target?.value);
1307
- };
1308
- const dictChanged = (root, subject) => {
1309
- const value = require_dependency.read(root, subject.address);
1310
- if (!require_dependency.isRecord(value)) return true;
1311
- if (subject.state.mode === "whole") return !require_dependency.sameStructuralValue(subject.state.value, value);
1312
- for (const [key, before] of subject.state.entries) {
1313
- const exists = hasOwn(value, key);
1314
- if (before.status === "absent" ? exists : !exists || !Object.is(before.value, value[key])) return true;
1315
- }
1316
- return false;
1317
- };
1318
- const listChanged = (root, subject) => {
1319
- const value = require_dependency.read(root, subject.address);
1320
- if (!Array.isArray(value)) return true;
1321
- if (subject.state.mode === "whole") return !require_dependency.sameStructuralValue(subject.state.value, value);
1322
- const positions = /* @__PURE__ */ new Map();
1323
- const order = new Array(value.length);
1324
- for (let index = 0; index < value.length; index += 1) {
1325
- const key = subject.node.keyOf(value[index]);
1326
- order[index] = key;
1327
- positions.set(key, index);
1328
- }
1329
- if (!sameOrder(subject.state.order, order)) return true;
1330
- for (const [key, before] of subject.state.items) {
1331
- const position = positions.get(key);
1332
- if (before.status === "absent") {
1333
- if (position !== void 0) return true;
1334
- } else if (position === void 0 || !require_dependency.sameStructuralValue(before.value, value[position])) return true;
1335
- }
1336
- return false;
1337
- };
1338
- const commonOrderChanged = (before, after) => {
1339
- const finalPositions = /* @__PURE__ */ new Map();
1340
- for (let index = 0; index < after.length; index += 1) finalPositions.set(after[index], index);
1341
- let previous = -1;
1342
- for (const id of before) {
1343
- const position = finalPositions.get(id);
1344
- if (position === void 0) continue;
1345
- if (position < previous) return true;
1346
- previous = position;
1347
- }
1348
- return false;
1349
- };
1350
- const analyzeEntity = (root, subject) => {
1351
- const resolution = entityCollection(subject, require_dependency.read(root, subject.address));
1352
- const added = /* @__PURE__ */ new Set();
1353
- const removed = /* @__PURE__ */ new Set();
1354
- const updated = /* @__PURE__ */ new Set();
1355
- if (resolution.status === "invalid") return {
1356
- changed: true,
1357
- added,
1358
- removed,
1359
- updated,
1360
- orderChanged: false
1361
- };
1362
- const collection = resolution.collection;
1363
- for (const [id, before] of subject.entries) {
1364
- const exists = hasOwn(collection.byId, id);
1365
- if (before.status === "absent") {
1366
- if (exists) added.add(id);
1367
- } else if (!exists) removed.add(id);
1368
- else if (!require_dependency.sameStructuralValue(before.value, collection.byId[id])) updated.add(id);
1369
- }
1370
- const beforeOrder = subject.order.kind === "tracked" ? subject.order.before : void 0;
1371
- const finalOrder = collection.kind === "table" ? collection.ids : [];
1372
- const netOrderChanged = beforeOrder !== void 0 && !sameOrder(beforeOrder, finalOrder);
1373
- return {
1374
- changed: added.size > 0 || removed.size > 0 || updated.size > 0 || netOrderChanged,
1375
- added,
1376
- removed,
1377
- updated,
1378
- orderChanged: beforeOrder !== void 0 && commonOrderChanged(beforeOrder, finalOrder)
1379
- };
1380
- };
1381
- const subjectChanged = (root, subject) => {
1382
- if (subject.kind === "value") return valueChanged(root, subject);
1383
- if (subject.kind === "variant") return !require_dependency.sameStructuralValue(subject.before, require_dependency.read(root, subject.address));
1384
- if (subject.kind === "dict") return dictChanged(root, subject);
1385
- if (subject.kind === "list") return listChanged(root, subject);
1386
- return changeChanged(subject.state, require_dependency.read(root, subject.address));
1387
- };
1388
- const listOrderBefore = (value, node, inverse) => {
1389
- const order = value.map(node.keyOf);
1390
- if (inverse.type === "list.remove") return order.filter((key) => key !== inverse.key);
1391
- if (inverse.type === "list.insert") {
1392
- order.splice(index(order, inverse.anchor), 0, inverse.key);
1393
- return order;
1394
- }
1395
- if (inverse.type === "list.move") {
1396
- const position = order.indexOf(inverse.key);
1397
- if (position >= 0) order.splice(position, 1);
1398
- order.splice(index(order, inverse.anchor), 0, inverse.key);
1399
- }
1400
- return order;
1401
- };
1402
- const recordListPresence = (state, inverse) => {
1403
- if (inverse.type === "list.remove" && !state.items.has(inverse.key)) state.items.set(inverse.key, absent);
1404
- else if (inverse.type === "list.insert" && !state.items.has(inverse.key)) state.items.set(inverse.key, present(inverse.value));
1405
- };
1406
- const entityOrderInverse = (operation, inverse) => {
1407
- if (inverse.type === "entity.remove") return {
1408
- kind: "remove",
1409
- ids: inverse.ids
1410
- };
1411
- if (inverse.type === "entity.create") {
1412
- if (!inverse.positions || inverse.positions.length !== inverse.entries.length) return inverseMismatch(operation);
1413
- return {
1414
- kind: "restore",
1415
- ids: inverse.entries.map((entry) => entry.id),
1416
- positions: inverse.positions
1417
- };
1418
- }
1419
- if (inverse.type === "entity.move") return {
1420
- kind: "move",
1421
- id: inverse.id,
1422
- ...inverse.anchor ? { anchor: inverse.anchor } : {}
1423
- };
1424
- return inverseMismatch(operation);
1425
- };
1426
- const removeEntityIds = (order, ids) => {
1427
- const removed = new Set(ids);
1428
- let writeIndex = 0;
1429
- for (const id of order) if (!removed.has(id)) order[writeIndex++] = id;
1430
- order.length = writeIndex;
1431
- };
1432
- const restoreEntityOrder = (order, inverses) => {
1433
- for (let index = inverses.length - 1; index >= 0; index -= 1) {
1434
- const inverse = inverses[index];
1435
- if (inverse.kind === "remove") {
1436
- removeEntityIds(order, inverse.ids);
1437
- continue;
1438
- }
1439
- if (inverse.kind === "restore") {
1440
- restore(order, inverse.ids, inverse.positions);
1441
- continue;
1442
- }
1443
- const position = order.indexOf(inverse.id);
1444
- if (position < 0 || !valid(order, inverse.anchor)) throw new Error(`Entity order inverse cannot restore '${inverse.id}'.`);
1445
- const nextIndex = afterRemove(order, position, inverse.anchor);
1446
- order.splice(position, 1);
1447
- order.splice(nextIndex, 0, inverse.id);
1448
- }
1449
- };
1450
- const treeOperation = (operation) => operation.type.startsWith("tree.");
1451
- const createChangeJournal = (root) => {
1452
- const active = /* @__PURE__ */ new Set();
1453
- const index = indexNode();
1454
- const buckets = /* @__PURE__ */ new Map();
1455
- const add = (subject) => {
1456
- active.add(subject);
1457
- const candidates = buckets.get(subject.addressHash);
1458
- if (candidates) candidates.push(subject);
1459
- else buckets.set(subject.addressHash, [subject]);
1460
- let node = index;
1461
- for (const segment of subject.address) {
1462
- const existing = node.children.get(segment);
1463
- if (existing) node = existing;
1464
- else {
1465
- const created = indexNode();
1466
- node.children.set(segment, created);
1467
- node = created;
1468
- }
1469
- }
1470
- if (node.subject) throw new Error(`Change journal already owns '${subject.address.join(".")}'.`);
1471
- node.subject = subject;
1472
- require_dependency.profile.journal.subject();
1473
- return subject;
1474
- };
1475
- const remove = (subject) => {
1476
- if (!active.delete(subject)) return;
1477
- const candidates = buckets.get(subject.addressHash);
1478
- if (candidates) {
1479
- const position = candidates.indexOf(subject);
1480
- if (position >= 0) candidates.splice(position, 1);
1481
- if (candidates.length === 0) buckets.delete(subject.addressHash);
1482
- }
1483
- const nodes = [index];
1484
- let node = index;
1485
- for (const segment of subject.address) {
1486
- const child = node.children.get(segment);
1487
- if (!child) return;
1488
- nodes.push(child);
1489
- node = child;
1490
- }
1491
- if (node.subject === subject) delete node.subject;
1492
- for (let position = subject.address.length - 1; position >= 0; position -= 1) {
1493
- const child = nodes[position + 1];
1494
- if (child.subject || child.children.size > 0) break;
1495
- nodes[position].children.delete(subject.address[position]);
1496
- }
1497
- };
1498
- function find(kind, address, addressHash) {
1499
- const candidates = buckets.get(addressHash) ?? [];
1500
- for (const subject of candidates) {
1501
- require_dependency.profile.journal.comparison();
1502
- if (subject.kind === kind && sameAddress(subject.address, address)) return subject;
1503
- }
1504
- }
1505
- const ownerOf = (address) => {
1506
- let node = index;
1507
- for (let position = 0; position < address.length; position += 1) {
1508
- if (node.subject && ownsDescendant(node.subject, address)) return node.subject;
1509
- const child = node.children.get(address[position]);
1510
- if (!child) return void 0;
1511
- node = child;
1512
- }
1513
- };
1514
- const absorb = (value, address) => {
1515
- const subjects = indexedSubjects(index, address);
1516
- if (subjects.length === 0) return value;
1517
- subjects.sort((left, right) => left.address.length - right.address.length);
1518
- let before = require_dependency.ownPayload(value, "journal");
1519
- for (const subject of subjects) before = restoreSubject(before, address, subject);
1520
- for (const subject of subjects) {
1521
- remove(subject);
1522
- require_dependency.profile.journal.absorbed();
1523
- }
1524
- return before;
1525
- };
1526
- const base = (resolved, operation) => ({
1527
- address: operation.at,
1528
- addressHash: resolved.addressHash,
1529
- ...resolved.collection ? { collection: resolved.collection } : {}
1530
- });
1531
- const recordValue = (resolved, operation, inverse) => {
1532
- if (find("value", operation.at, resolved.addressHash)) return;
1533
- const first = inverse[0];
1534
- if (first?.type !== "field.set" && first?.type !== "field.clear") return inverseMismatch(operation);
1535
- add({
1536
- ...base(resolved, operation),
1537
- kind: "value",
1538
- before: first.type === "field.set" ? present(first.value) : absent
1539
- });
1540
- };
1541
- const recordVariant = (resolved, operation, inverse) => {
1542
- if (find("variant", operation.at, resolved.addressHash)) return;
1543
- const first = inverse[0];
1544
- if (first?.type !== "variant.replace") return inverseMismatch(operation);
1545
- add({
1546
- ...base(resolved, operation),
1547
- kind: "variant",
1548
- before: absorb(first.value, operation.at)
1549
- });
1550
- };
1551
- const recordDict = (resolved, operation, inverse) => {
1552
- const first = inverse[0];
1553
- if (!first) return inverseMismatch(operation);
1554
- const subject = find("dict", operation.at, resolved.addressHash) ?? add({
1555
- ...base(resolved, operation),
1556
- kind: "dict",
1557
- state: {
1558
- mode: "incremental",
1559
- entries: /* @__PURE__ */ new Map()
1560
- }
1561
- });
1562
- if (subject.state.mode === "whole") return;
1563
- if (first.type === "dict.replace") {
1564
- const value = require_dependency.ownPayload(first.value, "journal");
1565
- restoreDict(value, subject.state);
1566
- subject.state = {
1567
- mode: "whole",
1568
- value
1569
- };
1570
- return;
1571
- }
1572
- if (first.type !== "dict.set" && first.type !== "dict.delete") return inverseMismatch(operation);
1573
- if (!subject.state.entries.has(first.key)) subject.state.entries.set(first.key, first.type === "dict.set" ? present(first.value) : absent);
1574
- };
1575
- const recordList = (resolved, operation, inverse) => {
1576
- if (resolved.node.kind !== "list") return inverseMismatch(operation);
1577
- const first = inverse[0];
1578
- if (!first) return inverseMismatch(operation);
1579
- let subject = find("list", operation.at, resolved.addressHash);
1580
- if (!subject) {
1581
- if (first.type === "list.replace") {
1582
- add({
1583
- ...base(resolved, operation),
1584
- kind: "list",
1585
- node: resolved.node,
1586
- state: {
1587
- mode: "whole",
1588
- value: first.value
1589
- }
1590
- });
1591
- return;
1592
- }
1593
- const value = require_dependency.read(root, operation.at);
1594
- if (!Array.isArray(value)) return inverseMismatch(operation);
1595
- subject = add({
1596
- ...base(resolved, operation),
1597
- kind: "list",
1598
- node: resolved.node,
1599
- state: {
1600
- mode: "incremental",
1601
- items: /* @__PURE__ */ new Map(),
1602
- order: listOrderBefore(value, resolved.node, first)
1603
- }
1604
- });
1605
- }
1606
- if (subject.state.mode === "whole") return;
1607
- if (first.type === "list.replace") {
1608
- const value = Array.from(require_dependency.ownPayload(first.value, "journal"));
1609
- restoreList(value, subject);
1610
- subject.state = {
1611
- mode: "whole",
1612
- value
1613
- };
1614
- return;
1615
- }
1616
- if (first.type !== "list.insert" && first.type !== "list.move" && first.type !== "list.remove") return inverseMismatch(operation);
1617
- recordListPresence(subject.state, first);
1618
- };
1619
- const trackEntityOrder = (subject, collection) => {
1620
- if (subject.order.kind !== "stable") return;
1621
- require_dependency.profile.journal.orderSnapshot(collection.ids.length);
1622
- const before = [...collection.ids];
1623
- restoreEntityOrder(before, subject.order.inverses);
1624
- subject.order = {
1625
- kind: "tracked",
1626
- before
1627
- };
1628
- };
1629
- const recordEntity = (resolved, operation, inverse) => {
1630
- if (resolved.node.kind !== "table" && resolved.node.kind !== "map") return inverseMismatch(operation);
1631
- const resolution = resolveEntityCollection(resolved.node, require_dependency.read(root, operation.at));
1632
- if (resolution.status === "invalid") return inverseMismatch(operation);
1633
- const collection = resolution.collection;
1634
- const subject = find("entity", operation.at, resolved.addressHash) ?? add({
1635
- ...base(resolved, operation),
1636
- kind: "entity",
1637
- node: resolved.node,
1638
- entries: /* @__PURE__ */ new Map(),
1639
- order: collection.kind === "table" ? {
1640
- kind: "stable",
1641
- inverses: []
1642
- } : { kind: "unordered" }
1643
- });
1644
- const first = inverse[0];
1645
- if (!first) return inverseMismatch(operation);
1646
- if (collection.kind === "table" && subject.order.kind === "stable") subject.order.inverses.push(entityOrderInverse(operation, first));
1647
- if (first.type === "entity.remove") {
1648
- for (const id of first.ids) if (!subject.entries.has(id)) subject.entries.set(id, absent);
1649
- if (collection.kind === "table" && first.ids.some((id) => subject.entries.get(id)?.status === "present")) trackEntityOrder(subject, collection);
1650
- return;
1651
- }
1652
- if (first.type === "entity.create") {
1653
- for (const entry of first.entries) {
1654
- if (subject.entries.has(entry.id)) continue;
1655
- const address = [...operation.at, entry.id];
1656
- subject.entries.set(entry.id, present(absorb(entry.value, address)));
1657
- }
1658
- return;
1659
- }
1660
- if (first.type === "entity.move") {
1661
- if (collection.kind === "table" && subject.entries.get(first.id)?.status !== "absent") trackEntityOrder(subject, collection);
1662
- return;
1663
- }
1664
- return inverseMismatch(operation);
1665
- };
1666
- const recordTree = (resolved, operation, inverse) => {
1667
- const current = require_dependency.read(root, operation.at);
1668
- if (!is(current)) return inverseMismatch(operation);
1669
- const inverses = inverse.filter(treeOperation);
1670
- if (inverses.length === 0 || inverses.length !== inverse.length) return inverseMismatch(operation);
1671
- const subject = find("tree", operation.at, resolved.addressHash);
1672
- const state = recordChange(subject?.state, current, operation, inverses);
1673
- if (subject) subject.state = state;
1674
- else add({
1675
- ...base(resolved, operation),
1676
- kind: "tree",
1677
- state
1678
- });
1679
- };
1680
- return {
1681
- record: (resolved, operation, inverse) => {
1682
- require_dependency.profile.batch.journalRecord();
1683
- if (ownerOf(operation.at)) return;
1684
- if (operation.type === "field.set" || operation.type === "field.clear") {
1685
- recordValue(resolved, operation, inverse);
1686
- return;
1687
- }
1688
- if (operation.type === "variant.replace") {
1689
- recordVariant(resolved, operation, inverse);
1690
- return;
1691
- }
1692
- if (operation.type === "dict.set" || operation.type === "dict.delete" || operation.type === "dict.replace") {
1693
- recordDict(resolved, operation, inverse);
1694
- return;
1695
- }
1696
- if (operation.type === "entity.create" || operation.type === "entity.remove" || operation.type === "entity.move") {
1697
- recordEntity(resolved, operation, inverse);
1698
- return;
1699
- }
1700
- if (operation.type === "list.insert" || operation.type === "list.move" || operation.type === "list.remove" || operation.type === "list.replace") {
1701
- recordList(resolved, operation, inverse);
1702
- return;
1703
- }
1704
- recordTree(resolved, operation, inverse);
1705
- },
1706
- finish: () => {
1707
- const changed = [];
1708
- const entityChanges = /* @__PURE__ */ new Map();
1709
- for (const subject of active) {
1710
- require_dependency.profile.journal.comparison();
1711
- if (subject.kind === "entity") {
1712
- const analysis = analyzeEntity(root, subject);
1713
- if (!analysis.changed) continue;
1714
- entityChanges.set(subject, analysis);
1715
- changed.push(subject);
1716
- } else if (subjectChanged(root, subject)) changed.push(subject);
1717
- }
1718
- if (changed.length === 0) return { status: "unchanged" };
1719
- const collections = [];
1720
- const collectionBuckets = /* @__PURE__ */ new Map();
1721
- const changeAt = (address, addressHash) => {
1722
- const candidates = collectionBuckets.get(addressHash) ?? [];
1723
- collectionBuckets.set(addressHash, candidates);
1724
- let change = candidates.find((entry) => sameAddress(entry.address, address));
1725
- if (!change) {
1726
- change = {
1727
- address,
1728
- added: /* @__PURE__ */ new Set(),
1729
- removed: /* @__PURE__ */ new Set(),
1730
- updated: /* @__PURE__ */ new Set(),
1731
- orderChanged: false
1732
- };
1733
- candidates.push(change);
1734
- collections.push(change);
1735
- }
1736
- return change;
1737
- };
1738
- for (const subject of changed) {
1739
- if (subject.kind === "entity") {
1740
- const analysis = entityChanges.get(subject);
1741
- if (analysis) {
1742
- const change = changeAt(subject.address, subject.addressHash);
1743
- analysis.added.forEach((id) => change.added.add(id));
1744
- analysis.removed.forEach((id) => change.removed.add(id));
1745
- analysis.updated.forEach((id) => change.updated.add(id));
1746
- if (analysis.orderChanged) change.orderChanged = true;
1747
- }
1748
- }
1749
- for (let collection = subject.collection; collection; collection = collection.parent) changeAt(collection.address, collection.addressHash).updated.add(collection.id);
1750
- }
1751
- for (const change of collections) {
1752
- change.added.forEach((id) => change.updated.delete(id));
1753
- change.removed.forEach((id) => change.updated.delete(id));
1754
- }
1755
- return {
1756
- status: "changed",
1757
- paths: Object.freeze(changed.map((subject) => subject.address)),
1758
- collections
1759
- };
1760
- }
1761
- };
1762
- };
1763
- //#endregion
1764
- //#region core/src/mutation/operation.ts
1765
- const has = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
1766
- const stringArray = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
1767
- const positions = (value) => Array.isArray(value) && value.every((entry) => Number.isInteger(entry) && entry >= 0);
1768
- const address = (value) => stringArray(value);
1769
- const anchor = (value) => {
1770
- if (!require_dependency.isRecord(value)) return false;
1771
- if (Number(has(value, "at")) + Number(has(value, "before")) + Number(has(value, "after")) !== 1) return false;
1772
- if (has(value, "at")) return value.at === "start" || value.at === "end";
1773
- return typeof (has(value, "before") ? value.before : value.after) === "string";
1774
- };
1775
- const optionalAnchor = (value) => !has(value, "anchor") || value.anchor === void 0 || anchor(value.anchor);
1776
- const optionalParent = (value) => !has(value, "parentId") || value.parentId === void 0 || typeof value.parentId === "string";
1777
- const optionalIndex = (value) => !has(value, "index") || value.index === void 0 || Number.isInteger(value.index) && value.index >= 0;
1778
- const entries = (value) => Array.isArray(value) && value.every((entry) => require_dependency.isRecord(entry) && typeof entry.id === "string" && has(entry, "value"));
1779
- const decoded = (operation) => ({
1780
- status: "decoded",
1781
- operation
1782
- });
1783
- const rejected = (code, message) => ({
1784
- status: "rejected",
1785
- issue: input(code, message)
1786
- });
1787
- const decode = (input) => {
1788
- if (!require_dependency.isRecord(input)) return rejected("invalid-operation", "Operation must be an object.");
1789
- if (!address(input.at)) return rejected("invalid-address", "Operation address is malformed.");
1790
- if (typeof input.type !== "string") return rejected("invalid-operation", "Operation type must be a string.");
1791
- switch (input.type) {
1792
- case "field.set":
1793
- case "variant.replace": return has(input, "value") ? decoded(input) : rejected("invalid-operation", "Operation value is required.");
1794
- case "field.clear": return decoded(input);
1795
- case "dict.set": return typeof input.key === "string" && has(input, "value") ? decoded(input) : rejected("invalid-operation", "Dictionary set requires a string key and value.");
1796
- case "dict.delete": return typeof input.key === "string" ? decoded(input) : rejected("invalid-operation", "Dictionary delete requires a string key.");
1797
- case "dict.replace": return require_dependency.isRecord(input.value) ? decoded(input) : rejected("invalid-operation", "Dictionary replacement must be an object.");
1798
- case "entity.create": return entries(input.entries) && optionalAnchor(input) && (!has(input, "positions") || input.positions === void 0 || positions(input.positions)) ? decoded(input) : rejected("invalid-operation", "Entity create payload is malformed.");
1799
- case "entity.remove": return stringArray(input.ids) ? decoded(input) : rejected("invalid-operation", "Entity remove requires string ids.");
1800
- case "entity.move": return typeof input.id === "string" && optionalAnchor(input) ? decoded(input) : rejected("invalid-operation", "Entity move payload is malformed.");
1801
- case "list.insert": return typeof input.key === "string" && has(input, "value") && optionalAnchor(input) ? decoded(input) : rejected("invalid-operation", "List insert payload is malformed.");
1802
- case "list.move": return typeof input.key === "string" && optionalAnchor(input) ? decoded(input) : rejected("invalid-operation", "List move payload is malformed.");
1803
- case "list.remove": return typeof input.key === "string" ? decoded(input) : rejected("invalid-operation", "List remove requires a string key.");
1804
- case "list.replace": return Array.isArray(input.value) && stringArray(input.keys) ? decoded(input) : rejected("invalid-operation", "List replacement payload is malformed.");
1805
- case "tree.insert": return typeof input.treeNodeId === "string" && optionalParent(input) && optionalIndex(input) ? decoded(input) : rejected("invalid-operation", "Tree insert payload is malformed.");
1806
- case "tree.move": return typeof input.treeNodeId === "string" && optionalParent(input) && optionalIndex(input) ? decoded(input) : rejected("invalid-operation", "Tree move payload is malformed.");
1807
- case "tree.remove": return typeof input.treeNodeId === "string" ? decoded(input) : rejected("invalid-operation", "Tree remove requires a node id.");
1808
- case "tree.set": return typeof input.treeNodeId === "string" && has(input, "value") ? decoded(input) : rejected("invalid-operation", "Tree set payload is malformed.");
1809
- case "tree.replace": return has(input, "value") ? decoded(input) : rejected("invalid-operation", "Tree replacement value is required.");
1810
- default: return rejected("unknown-operation", "Unknown document operation.");
1811
- }
1812
- };
1813
- const decodeBatch = (input$1) => Array.isArray(input$1) ? {
1814
- status: "decoded",
1815
- operations: input$1
1816
- } : {
1817
- status: "rejected",
1818
- issue: input("invalid-operation", "Operation batch must be an array.")
1819
- };
1820
- const ownAddress = (value) => {
1821
- if (Object.isFrozen(value)) return value;
1822
- require_dependency.profile.address.arrayCopied();
1823
- return Object.freeze(value.slice());
1824
- };
1825
- const normalize = (operation) => {
1826
- require_dependency.profile.mutation.normalized();
1827
- const copy = {
1828
- ...operation,
1829
- at: ownAddress(operation.at)
1830
- };
1831
- if (copy.anchor) copy.anchor = Object.freeze({ ...copy.anchor });
1832
- if (copy.keys) copy.keys = Object.freeze([...copy.keys]);
1833
- if (copy.entries) copy.entries = Object.freeze(copy.entries.map((entry) => Object.freeze({ ...entry })));
1834
- if (copy.ids) copy.ids = Object.freeze([...copy.ids]);
1835
- if (copy.positions) copy.positions = Object.freeze([...copy.positions]);
1836
- return Object.freeze(copy);
1837
- };
1838
- const publish = (operation) => {
1839
- if (!require_dependency.operationOwnsStructuralPayload(operation)) return operation;
1840
- if (operation.type === "entity.create" && operation.entries.every((entry) => require_dependency.isStablePayload(entry.value))) return operation;
1841
- const copy = { ...operation };
1842
- if (copy.entries) copy.entries = Object.freeze(copy.entries.map((entry) => Object.freeze({
1843
- id: entry.id,
1844
- value: require_dependency.isStablePayload(entry.value) ? entry.value : require_dependency.snapshotPayload(entry.value, "commit")
1845
- })));
1846
- else if ("value" in copy) copy.value = require_dependency.isStablePayload(copy.value) ? copy.value : require_dependency.snapshotPayload(copy.value, "commit");
1847
- return Object.freeze(copy);
1848
- };
1849
- const inverse = (operation) => {
1850
- const copy = { ...operation };
1851
- if (copy.anchor) copy.anchor = Object.freeze({ ...copy.anchor });
1852
- if (copy.keys) copy.keys = Object.freeze([...copy.keys]);
1853
- if (copy.entries) copy.entries = Object.freeze(copy.entries.map((entry) => Object.freeze({ ...entry })));
1854
- if (copy.ids) copy.ids = Object.freeze([...copy.ids]);
1855
- if (copy.positions) copy.positions = Object.freeze([...copy.positions]);
1856
- return Object.freeze(copy);
1857
- };
1858
- //#endregion
1859
- //#region core/src/mutation/session.ts
1860
- const createMutationSession = (root, schema, options = {}) => {
1861
- const steps = [];
1862
- const journal = createChangeJournal(root);
1863
- let closed = false;
1864
- const rollback = () => {
1865
- if (closed) return;
1866
- for (let stepIndex = steps.length - 1; stepIndex >= 0; stepIndex -= 1) for (const inverse of steps[stepIndex].inverse) {
1867
- const result = execute(root, inverse, require_dependency.resolveLocated(schema, root, inverse.at), true);
1868
- if (result.status === "rejected") throw new Error(`Document rollback failed: ${result.issue.message}`);
1869
- }
1870
- closed = true;
1871
- };
1872
- return {
1873
- apply: (input) => {
1874
- if (closed) throw new Error("Mutation session is closed.");
1875
- require_dependency.profile.batch.operation();
1876
- const decoded = decode(input);
1877
- if (decoded.status === "rejected") {
1878
- require_dependency.profile.batch.rejected();
1879
- return decoded.issue;
1880
- }
1881
- const normalized = normalize(decoded.operation);
1882
- require_dependency.profile.batch.entry(normalized.type === "entity.create" ? normalized.entries.length : normalized.type === "entity.remove" ? normalized.ids.length : 1);
1883
- const resolved = require_dependency.resolveLocated(schema, root, normalized.at);
1884
- if (resolved?.collection) require_dependency.profile.batch.collectionResolved();
1885
- require_dependency.profile.mutation.executed();
1886
- const result = execute(root, normalized, resolved, options.copyPayload === true);
1887
- if (result.status === "rejected") {
1888
- require_dependency.profile.batch.rejected();
1889
- return result.issue;
1890
- }
1891
- if (result.status === "unchanged") return void 0;
1892
- const published = publish(normalized);
1893
- const group = [];
1894
- for (const rawInverse of result.inverse) {
1895
- const inverse$1 = inverse(rawInverse);
1896
- group.push(inverse$1);
1897
- require_dependency.profile.mutation.inverse();
1898
- require_dependency.profile.batch.inverse();
1899
- }
1900
- steps.push({
1901
- forward: published,
1902
- inverse: Object.freeze(group)
1903
- });
1904
- try {
1905
- if (!resolved) throw new Error(`Changed operation '${normalized.type}' was not resolved.`);
1906
- journal.record(resolved, normalized, result.inverse);
1907
- } catch (error) {
1908
- rollback();
1909
- throw error;
1910
- }
1911
- },
1912
- finish: () => {
1913
- if (closed) throw new Error("Mutation session is closed.");
1914
- closed = true;
1915
- const changes = journal.finish();
1916
- if (changes.status === "unchanged") return { status: "unchanged" };
1917
- let inverseCount = 0;
1918
- for (const step of steps) inverseCount += step.inverse.length;
1919
- const inverse = new Array(inverseCount);
1920
- let writeIndex = 0;
1921
- for (let stepIndex = steps.length - 1; stepIndex >= 0; stepIndex -= 1) for (const entry of steps[stepIndex].inverse) inverse[writeIndex++] = entry;
1922
- return {
1923
- status: "changed",
1924
- operations: Object.freeze(steps.map((step) => step.forward)),
1925
- inverse: Object.freeze(inverse),
1926
- paths: changes.paths,
1927
- collections: changes.collections
1928
- };
1929
- },
1930
- rollback
1931
- };
1932
- };
1933
- const mutateOperations = (root, schema, operations, options = {}) => {
1934
- const decodedBatch = decodeBatch(operations);
1935
- if (decodedBatch.status === "rejected") return {
1936
- status: "rejected",
1937
- issues: Object.freeze([decodedBatch.issue])
1938
- };
1939
- const session = createMutationSession(root, schema, options);
1940
- for (const input of decodedBatch.operations) {
1941
- const issue = session.apply(input);
1942
- if (!issue) continue;
1943
- session.rollback();
1944
- return {
1945
- status: "rejected",
1946
- issues: Object.freeze([issue])
1947
- };
1948
- }
1949
- return session.finish();
1950
- };
1951
- //#endregion
1952
- //#region core/src/runtime/notification.ts
1953
- const ROOT_BUCKET = Symbol("document-root");
1954
- const notifications = /* @__PURE__ */ new WeakMap();
1955
- const key = (value) => require_dependency.bucket(value) ?? ROOT_BUCKET;
1956
- const createNotification = (runtime) => {
1957
- const notification = {
1958
- root: /* @__PURE__ */ new Set(),
1959
- filtered: /* @__PURE__ */ new Set(),
1960
- buckets: /* @__PURE__ */ new Map(),
1961
- processors: [],
1962
- candidates: /* @__PURE__ */ new Set(),
1963
- rootSnapshot: [],
1964
- notifying: false
1965
- };
1966
- notifications.set(runtime, notification);
1967
- return notification;
1968
- };
1969
- const notificationOf = (runtime) => {
1970
- const value = notifications.get(runtime);
1971
- if (!value) throw new Error("Unknown Doxum runtime.");
1972
- return value;
1973
- };
1974
- const registerProcessor = (runtime, processor) => {
1975
- const notification = notificationOf(runtime);
1976
- const entry = {
1977
- processor,
1978
- active: true
1979
- };
1980
- notification.processors.push(entry);
1981
- return () => {
1982
- if (!entry.active) return;
1983
- entry.active = false;
1984
- if (!notification.notifying) {
1985
- const index = notification.processors.indexOf(entry);
1986
- if (index >= 0) notification.processors.splice(index, 1);
1987
- }
1988
- };
1989
- };
1990
- const subscribeRoot = (notification, listener) => {
1991
- const entry = {
1992
- listener,
1993
- active: true
1994
- };
1995
- notification.root.add(entry);
1996
- return () => {
1997
- entry.active = false;
1998
- if (!notification.notifying) notification.root.delete(entry);
1999
- };
2000
- };
2001
- const subscribeTargets = (notification, targets, listener) => {
2002
- const entry = {
2003
- targets: Object.freeze(targets.slice()),
2004
- listener,
2005
- active: true
2006
- };
2007
- notification.filtered.add(entry);
2008
- const keys = new Set(targets.map(key));
2009
- keys.forEach((key) => {
2010
- const bucket = notification.buckets.get(key) ?? /* @__PURE__ */ new Set();
2011
- bucket.add(entry);
2012
- notification.buckets.set(key, bucket);
2013
- });
2014
- return () => {
2015
- if (!entry.active) return;
2016
- entry.active = false;
2017
- if (notification.notifying) return;
2018
- notification.filtered.delete(entry);
2019
- keys.forEach((key) => {
2020
- const bucket = notification.buckets.get(key);
2021
- bucket?.delete(entry);
2022
- if (bucket?.size === 0) notification.buckets.delete(key);
2023
- });
2024
- };
2025
- };
2026
- const notify = (notification, commit) => {
2027
- notification.notifying = true;
2028
- const errors = [];
2029
- const call = (listener) => {
2030
- try {
2031
- listener(commit);
2032
- } catch (error) {
2033
- errors.push(Object.freeze({
2034
- phase: "listener",
2035
- error
2036
- }));
2037
- }
2038
- };
2039
- try {
2040
- const processorCount = notification.processors.length;
2041
- for (let index = 0; index < processorCount; index += 1) {
2042
- const entry = notification.processors[index];
2043
- if (!entry?.active) continue;
2044
- try {
2045
- entry.processor.process(commit);
2046
- } catch (error) {
2047
- errors.push(Object.freeze({
2048
- phase: "processor",
2049
- error
2050
- }));
2051
- }
2052
- }
2053
- for (let index = 0; index < processorCount; index += 1) {
2054
- const entry = notification.processors[index];
2055
- if (!entry?.active) continue;
2056
- try {
2057
- entry.processor.flush();
2058
- } catch (error) {
2059
- errors.push(Object.freeze({
2060
- phase: "flush",
2061
- error
2062
- }));
2063
- }
2064
- }
2065
- const candidates = notification.candidates;
2066
- candidates.clear();
2067
- if (commit.impact.kind === "reset") notification.filtered.forEach((entry) => candidates.add(entry));
2068
- else for (const operation of commit.operations) {
2069
- const key = operation.at[0] ?? ROOT_BUCKET;
2070
- notification.buckets.get(key)?.forEach((entry) => candidates.add(entry));
2071
- notification.buckets.get(ROOT_BUCKET)?.forEach((entry) => candidates.add(entry));
2072
- }
2073
- candidates.forEach((entry) => {
2074
- if (entry.active && entry.targets.some(commit.impact.affects)) call(entry.listener);
2075
- });
2076
- const rootSnapshot = notification.rootSnapshot;
2077
- rootSnapshot.length = 0;
2078
- notification.root.forEach((entry) => rootSnapshot.push(entry));
2079
- for (const entry of rootSnapshot) if (entry.active) call(entry.listener);
2080
- } finally {
2081
- notification.notifying = false;
2082
- let writeIndex = 0;
2083
- for (const entry of notification.processors) if (entry.active) notification.processors[writeIndex++] = entry;
2084
- notification.processors.length = writeIndex;
2085
- notification.root.forEach((entry) => {
2086
- if (!entry.active) notification.root.delete(entry);
2087
- });
2088
- notification.filtered.forEach((entry) => {
2089
- if (!entry.active) notification.filtered.delete(entry);
2090
- });
2091
- notification.buckets.forEach((bucket, key) => {
2092
- bucket.forEach((entry) => {
2093
- if (!entry.active) bucket.delete(entry);
2094
- });
2095
- if (bucket.size === 0) notification.buckets.delete(key);
2096
- });
2097
- }
2098
- return Object.freeze(errors);
2099
- };
2100
- const disposeNotification = (notification) => {
2101
- notification.root.clear();
2102
- notification.filtered.clear();
2103
- notification.buckets.clear();
2104
- notification.processors.length = 0;
2105
- notification.candidates.clear();
2106
- notification.rootSnapshot.length = 0;
2107
- };
2108
- //#endregion
2109
- //#region core/src/runtime.ts
2110
- var RejectedUpdate = class extends Error {
2111
- issues;
2112
- constructor(issues) {
2113
- super("Document update rejected.");
2114
- this.issues = Object.freeze(issues.slice());
2115
- }
2116
- };
2117
- const EMPTY = Object.freeze([]);
2118
- const publishDiagnostic = (value) => Object.freeze({
2119
- ...value,
2120
- ...value.address === void 0 ? {} : { address: Object.freeze(value.address.slice()) }
2121
- });
2122
- const createDocument = (input) => {
2123
- const initialTreeError = invalidDocument(input.schema, input.initial);
2124
- if (initialTreeError) throw new TypeError(`Initial document contains an invalid tree at '${initialTreeError.join(".")}'.`);
2125
- require_dependency.profile.clone.initialDocument();
2126
- const state = {
2127
- schema: input.schema,
2128
- document: require_dependency.cloneValue(input.initial, "initial"),
2129
- disposed: false
2130
- };
2131
- let revision = 0;
2132
- let busy = false;
2133
- let runtime;
2134
- let notification;
2135
- const assertWritable = () => {
2136
- if (state.disposed) throw new require_dependency.DocumentDisposedError();
2137
- if (busy) throw new require_dependency.DocumentReentrancyError();
2138
- };
2139
- const history = createHistory({
2140
- capacity: input.history === false ? 0 : Math.max(0, input.history?.capacity ?? 100),
2141
- revision: () => revision,
2142
- apply: (operations) => applyBatch(operations, "history", false)
2143
- });
2144
- const publish = (batch, source, kind, recordHistory) => {
2145
- revision += 1;
2146
- const commit = Object.freeze({
2147
- revision,
2148
- kind,
2149
- source,
2150
- operations: batch.operations,
2151
- inverse: batch.inverse,
2152
- impact: createImpact({
2153
- schema: input.schema,
2154
- operations: batch.operations,
2155
- paths: batch.paths,
2156
- collections: batch.collections,
2157
- reset: kind === "replace"
2158
- })
2159
- });
2160
- if (kind === "replace" || source === "remote") history.invalidate();
2161
- else if (recordHistory && (source === "local" || source === "system")) history.record(batch.operations, batch.inverse);
2162
- busy = true;
2163
- let observerErrors;
2164
- try {
2165
- observerErrors = notify(notification, commit);
2166
- } finally {
2167
- busy = false;
2168
- }
2169
- return {
2170
- status: "committed",
2171
- commit,
2172
- observerErrors
2173
- };
2174
- };
2175
- function applyBatch(operations, source, recordHistory) {
2176
- assertWritable();
2177
- const batch = mutateOperations(state.document, input.schema, operations, { copyPayload: source === "history" });
2178
- if (batch.status === "rejected") return {
2179
- status: "rejected",
2180
- issues: batch.issues,
2181
- revision
2182
- };
2183
- if (batch.status === "unchanged") return {
2184
- status: "unchanged",
2185
- revision
2186
- };
2187
- return publish(batch, source, "operations", recordHistory);
2188
- }
2189
- runtime = {
2190
- address: {
2191
- resolve: (address) => require_dependency.resolveAddress(input.schema, address, state.document),
2192
- read: (address) => require_dependency.read(state.document, address),
2193
- contains: require_dependency.contains,
2194
- overlaps: require_dependency.overlaps,
2195
- debugKey: require_dependency.debugKey
2196
- },
2197
- revision: () => revision,
2198
- update: (run, options) => {
2199
- assertWritable();
2200
- busy = true;
2201
- const session = createMutationSession(state.document, input.schema);
2202
- let reports;
2203
- let active = true;
2204
- const transaction = {
2205
- read: require_dependency.documentReader(input.schema, () => state.document, () => active),
2206
- write: documentWriter(input.schema, (operation) => {
2207
- if (!active) throw new Error("Document writer is no longer active.");
2208
- const rejected = session.apply(operation);
2209
- if (rejected) throw new RejectedUpdate([rejected]);
2210
- }),
2211
- reject: (diagnostic) => {
2212
- throw new RejectedUpdate((Array.isArray(diagnostic) ? diagnostic : [diagnostic]).map((entry) => publishDiagnostic(entry)));
2213
- },
2214
- report: (diagnostic) => {
2215
- if (!active) throw new Error("Document transaction is no longer active.");
2216
- (reports ??= []).push(publishDiagnostic(diagnostic));
2217
- }
2218
- };
2219
- try {
2220
- const value = run(transaction);
2221
- if (value !== null && typeof value === "object" && typeof value.then === "function") throw new TypeError("Document update callback must be synchronous.");
2222
- active = false;
2223
- busy = false;
2224
- const batch = session.finish();
2225
- if (batch.status === "unchanged") return {
2226
- status: "unchanged",
2227
- value,
2228
- revision,
2229
- reports: Object.freeze(reports ?? EMPTY)
2230
- };
2231
- if (batch.status === "rejected") return {
2232
- status: "rejected",
2233
- issues: batch.issues,
2234
- revision
2235
- };
2236
- const result = publish(batch, options?.source ?? "local", "operations", options?.history ?? true);
2237
- return {
2238
- status: "committed",
2239
- value,
2240
- commit: result.commit,
2241
- reports: Object.freeze(reports ?? EMPTY),
2242
- observerErrors: result.observerErrors
2243
- };
2244
- } catch (error) {
2245
- active = false;
2246
- try {
2247
- session.rollback();
2248
- } finally {
2249
- busy = false;
2250
- }
2251
- if (error instanceof RejectedUpdate) return {
2252
- status: "rejected",
2253
- issues: error.issues,
2254
- revision
2255
- };
2256
- throw error;
2257
- } finally {
2258
- active = false;
2259
- busy = false;
2260
- }
2261
- },
2262
- apply: (operations, options) => applyBatch(operations, options?.source ?? "local", options?.history ?? true),
2263
- replace: (document, options) => {
2264
- assertWritable();
2265
- const invalidTree = invalidDocument(input.schema, document);
2266
- if (invalidTree) return {
2267
- status: "rejected",
2268
- issues: [at$1(invalidTree, "invalid-tree", "Document replacement contains an invalid tree.")],
2269
- revision
2270
- };
2271
- if (require_dependency.deepEqual(state.document, document)) return {
2272
- status: "unchanged",
2273
- revision
2274
- };
2275
- state.document = require_dependency.cloneValue(document, "replace");
2276
- return publish({
2277
- status: "changed",
2278
- operations: EMPTY,
2279
- inverse: EMPTY,
2280
- paths: EMPTY,
2281
- collections: EMPTY
2282
- }, options?.source ?? "system", "replace", false);
2283
- },
2284
- subscribe: ((targetOrListener, listener) => {
2285
- if (state.disposed) throw new require_dependency.DocumentDisposedError();
2286
- if (typeof targetOrListener === "function") return subscribeRoot(notification, targetOrListener);
2287
- const targets = Array.isArray(targetOrListener) ? targetOrListener : [targetOrListener];
2288
- if (targets.length === 0 || !listener) throw new TypeError("Filtered subscribe requires at least one target and a listener.");
2289
- return subscribeTargets(notification, targets, listener);
2290
- }),
2291
- history: history.api,
2292
- dispose: () => {
2293
- if (state.disposed) return;
2294
- state.disposed = true;
2295
- disposeNotification(notification);
2296
- history.api.clear();
2297
- }
2298
- };
2299
- require_dependency.bindRuntimeAccess(runtime, state);
2300
- notification = createNotification(runtime);
2301
- return runtime;
2302
- };
2303
- //#endregion
2
+ const require_access = require("./access-z56fVqZ2.cjs");
3
+ const require_readable = require("./readable-B8E3FMq6.cjs");
4
+ const require_dependency = require("./dependency-DmQXyj7q.cjs");
2304
5
  //#region core/src/projection/select.ts
2305
- const select = (runtime, selector) => require_dependency.readWith(runtime, selector);
6
+ const select = (runtime, selector) => require_access.readWith(runtime, selector);
2306
7
  //#endregion
2307
8
  //#region core/src/projection/collection-view.ts
2308
9
  const createCollectionView = (input) => {
2309
- if (require_dependency.schemaOf(input.runtime) !== input.source.schema) throw new Error("Collection selector belongs to another schema.");
10
+ if (require_access.schemaOf(input.runtime) !== input.source.schema) throw new Error("Collection selector belongs to another schema.");
2310
11
  const idsListeners = /* @__PURE__ */ new Set();
2311
12
  const allListeners = /* @__PURE__ */ new Set();
2312
13
  const itemListeners = /* @__PURE__ */ new Map();
2313
14
  const itemReadables = /* @__PURE__ */ new Map();
2314
15
  let disposed = false;
2315
- const sourceNode = require_dependency.nodeAt(input.source.schema, input.source.address);
16
+ const sourceNode = require_access.nodeAt(input.source.schema, input.source.address);
2316
17
  const entryNode = sourceNode?.kind === "table" || sourceNode?.kind === "map" ? sourceNode.value : {
2317
18
  kind: "object",
2318
19
  shape: {}
2319
20
  };
2320
21
  const mapEntry = (document, id) => {
2321
- require_dependency.profile.collectionView.mapped();
22
+ require_access.profile.collectionView.mapped();
2322
23
  const address = [...input.source.address, String(id)];
2323
24
  let active = true;
2324
25
  try {
2325
- return input.map(id, require_dependency.readerFor(entryNode, {
26
+ return input.map(id, require_access.readerFor(entryNode, {
2326
27
  root: () => document,
2327
28
  active: () => active
2328
29
  }, address));
@@ -2331,10 +32,10 @@ const createCollectionView = (input) => {
2331
32
  }
2332
33
  };
2333
34
  const build = (previous, changed) => {
2334
- const document = require_dependency.documentOf(input.runtime);
2335
- const collection = require_dependency.read(document, input.source.address);
35
+ const document = require_access.documentOf(input.runtime);
36
+ const collection = require_access.read(document, input.source.address);
2336
37
  const ids = collection && typeof collection === "object" && "ids" in collection && Array.isArray(collection.ids) ? [...collection.ids] : Object.keys(collection ?? {});
2337
- require_dependency.profile.collectionView.idsScanned(ids.length);
38
+ require_access.profile.collectionView.idsScanned(ids.length);
2338
39
  const values = previous && changed ? previous.values : /* @__PURE__ */ new Map();
2339
40
  if (previous && changed) {
2340
41
  const nextIds = new Set(ids);
@@ -2362,7 +63,7 @@ const createCollectionView = (input) => {
2362
63
  let state = build();
2363
64
  const ensureAll = () => {
2364
65
  if (!state.allDirty && state.all) return state.all;
2365
- require_dependency.profile.collectionView.arrayCopied();
66
+ require_access.profile.collectionView.arrayCopied();
2366
67
  const all = new Array(state.ids.length);
2367
68
  for (let index = 0; index < state.ids.length; index += 1) all[index] = state.values.get(state.ids[index]);
2368
69
  const stable = Object.freeze(all);
@@ -2379,7 +80,7 @@ const createCollectionView = (input) => {
2379
80
  if (impact.kind === "incremental" && impact.added.size === 0 && impact.removed.size === 0 && !impact.orderChanged) {
2380
81
  const previous = state;
2381
82
  const changes = [];
2382
- const document = require_dependency.documentOf(input.runtime);
83
+ const document = require_access.documentOf(input.runtime);
2383
84
  impact.updated.forEach((id) => {
2384
85
  if (!previous.values.has(id)) return;
2385
86
  const before = previous.values.get(id);
@@ -2519,7 +220,7 @@ const createMaterializedView = (runtime, spec) => {
2519
220
  entry.change = meta?.change;
2520
221
  if (commitRevision !== void 0 && meta?.changedRevision === commitRevision) {
2521
222
  sourceChanged = true;
2522
- require_dependency.profile.materialized.sourceChanged();
223
+ require_access.profile.materialized.sourceChanged();
2523
224
  }
2524
225
  }
2525
226
  return sourceValuesRecord;
@@ -2566,12 +267,12 @@ const createMaterializedView = (runtime, spec) => {
2566
267
  });
2567
268
  };
2568
269
  const build = () => {
2569
- require_dependency.profile.materialized.rebuilt();
270
+ require_access.profile.materialized.rebuilt();
2570
271
  dependencies.clear();
2571
272
  let active = true;
2572
273
  try {
2573
274
  instance = spec.build({
2574
- read: require_dependency.documentReader(require_dependency.schemaOf(runtime), () => require_dependency.documentOf(runtime), () => active),
275
+ read: require_access.documentReader(require_access.schemaOf(runtime), () => require_access.documentOf(runtime), () => active),
2575
276
  sources: sourceValues()
2576
277
  });
2577
278
  currentValue = instance.value;
@@ -2583,7 +284,7 @@ const createMaterializedView = (runtime, spec) => {
2583
284
  };
2584
285
  build();
2585
286
  const emit = () => {
2586
- require_dependency.profile.materialized.notification();
287
+ require_access.profile.materialized.notification();
2587
288
  Array.from(listeners).forEach((listener) => listener());
2588
289
  };
2589
290
  const process = (commit) => {
@@ -2597,19 +298,19 @@ const createMaterializedView = (runtime, spec) => {
2597
298
  }
2598
299
  const sourceSnapshot = sourceValues(commit.revision);
2599
300
  if (!sourceChanged && dependencies.size() > 0 && !dependencies.some(commit.impact.affects)) {
2600
- require_dependency.profile.materialized.skipped();
301
+ require_access.profile.materialized.skipped();
2601
302
  revision = commit.revision;
2602
303
  writeMeta(void 0, currentValue, commit.revision, false);
2603
304
  return;
2604
305
  }
2605
306
  dependencies.clear();
2606
- require_dependency.profile.materialized.updated();
307
+ require_access.profile.materialized.updated();
2607
308
  let active = true;
2608
309
  let result;
2609
310
  try {
2610
311
  activeImpact = commit.impact;
2611
312
  result = instance.update({
2612
- read: require_dependency.documentReader(require_dependency.schemaOf(runtime), () => require_dependency.documentOf(runtime), () => active),
313
+ read: require_access.documentReader(require_access.schemaOf(runtime), () => require_access.documentOf(runtime), () => active),
2613
314
  revision: commit.revision,
2614
315
  source: commit.source,
2615
316
  impact: trackedImpact,
@@ -2674,7 +375,7 @@ const createMaterializedView = (runtime, spec) => {
2674
375
  revision,
2675
376
  changedRevision: -1
2676
377
  });
2677
- const unregister = registerProcessor(runtime, {
378
+ const unregister = require_readable.registerProcessor(runtime, {
2678
379
  process,
2679
380
  flush: () => {
2680
381
  if (!pendingEmit) return;
@@ -2685,34 +386,38 @@ const createMaterializedView = (runtime, spec) => {
2685
386
  return view;
2686
387
  };
2687
388
  //#endregion
2688
- exports.DocumentDisposedError = require_dependency.DocumentDisposedError;
2689
- exports.DocumentReentrancyError = require_dependency.DocumentReentrancyError;
2690
- exports.contains = require_dependency.contains;
389
+ exports.DocumentDisposedError = require_access.DocumentDisposedError;
390
+ exports.DocumentReentrancyError = require_access.DocumentReentrancyError;
391
+ exports.asReadable = require_readable.asReadable;
392
+ exports.commandFootprint = require_readable.commandFootprint;
393
+ exports.contains = require_access.contains;
2691
394
  exports.createCollectionView = createCollectionView;
2692
- exports.createDocument = createDocument;
395
+ exports.createDocument = require_readable.createDocument;
2693
396
  exports.createMaterializedView = createMaterializedView;
2694
- exports.debugKey = require_dependency.debugKey;
2695
- exports.dict = require_dependency.dict;
2696
- exports.field = require_dependency.field;
2697
- exports.list = require_dependency.list;
2698
- exports.map = require_dependency.map;
2699
- exports.object = require_dependency.object;
2700
- exports.optional = require_dependency.optional;
2701
- exports.overlaps = require_dependency.overlaps;
2702
- exports.readAddress = require_dependency.read;
2703
- exports.record = require_dependency.record;
2704
- exports.resolveAddress = require_dependency.resolveAddress;
2705
- exports.schema = require_dependency.schema;
397
+ exports.debugKey = require_access.debugKey;
398
+ exports.decodeCommandFootprint = require_readable.decodeCommandFootprint;
399
+ exports.dict = require_access.dict;
400
+ exports.field = require_access.field;
401
+ exports.footprintsOverlap = require_readable.footprintsOverlap;
402
+ exports.list = require_access.list;
403
+ exports.map = require_access.map;
404
+ exports.object = require_access.object;
405
+ exports.optional = require_access.optional;
406
+ exports.overlaps = require_access.overlaps;
407
+ exports.readAddress = require_access.read;
408
+ exports.record = require_access.record;
409
+ exports.resolveAddress = require_access.resolveAddress;
410
+ exports.schema = require_access.schema;
2706
411
  exports.select = select;
2707
- exports.single = require_dependency.single;
2708
- exports.table = require_dependency.table;
412
+ exports.single = require_access.single;
413
+ exports.table = require_access.table;
2709
414
  Object.defineProperty(exports, "target", {
2710
415
  enumerable: true,
2711
416
  get: function() {
2712
- return require_dependency.impact_target_exports;
417
+ return require_access.impact_target_exports;
2713
418
  }
2714
419
  });
2715
- exports.tree = require_dependency.tree;
2716
- exports.variant = require_dependency.variant;
420
+ exports.tree = require_access.tree;
421
+ exports.variant = require_access.variant;
2717
422
 
2718
423
  //# sourceMappingURL=index.cjs.map