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