doxum 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +46 -5
  2. package/dist/{contract-BsY1XLiG.d.ts → contract-I99DUMbN.d.ts} +53 -40
  3. package/dist/{contract-D8kjdfqT.d.cts → contract-uYJTmT8o.d.cts} +53 -40
  4. package/dist/index.cjs +244 -630
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +3 -64
  7. package/dist/index.d.ts +3 -64
  8. package/dist/index.js +182 -569
  9. package/dist/index.js.map +1 -1
  10. package/dist/integration-Bs3pOk65.cjs +35 -0
  11. package/dist/integration-Bs3pOk65.cjs.map +1 -0
  12. package/dist/integration-xupBIKjU.js +30 -0
  13. package/dist/integration-xupBIKjU.js.map +1 -0
  14. package/dist/integration.cjs +4 -14
  15. package/dist/integration.d.cts +3 -2
  16. package/dist/integration.d.ts +3 -2
  17. package/dist/integration.js +3 -14
  18. package/dist/local-sync.cjs +1 -1
  19. package/dist/local-sync.d.cts +1 -1
  20. package/dist/local-sync.d.ts +1 -1
  21. package/dist/local-sync.js +1 -1
  22. package/dist/{ownership-CU-9DKJQ.cjs → ownership-CY0nPXGF.cjs} +4 -1
  23. package/dist/ownership-CY0nPXGF.cjs.map +1 -0
  24. package/dist/{ownership-B-VAPcce.js → ownership-CduRygE7.js} +4 -1
  25. package/dist/ownership-CduRygE7.js.map +1 -0
  26. package/dist/react.cjs +1 -1
  27. package/dist/react.js +1 -1
  28. package/dist/runtime-BJRXF0gq.js +1735 -0
  29. package/dist/runtime-BJRXF0gq.js.map +1 -0
  30. package/dist/runtime-CRijXjYp.cjs +1991 -0
  31. package/dist/runtime-CRijXjYp.cjs.map +1 -0
  32. package/dist/runtime-CUcvhFNP.d.ts +152 -0
  33. package/dist/runtime-C_vKHmhy.d.cts +152 -0
  34. package/package.json +1 -1
  35. package/skills/doxum-runtime/references/guide.en.md +35 -18
  36. package/skills/doxum-runtime/references/guide.zh-CN.md +26 -14
  37. package/skills/doxum-runtime/references/invariants.en.md +12 -9
  38. package/skills/doxum-runtime/references/invariants.zh-CN.md +2 -2
  39. package/skills/doxum-runtime/references/patterns.en.md +36 -56
  40. package/skills/doxum-runtime/references/patterns.zh-CN.md +27 -45
  41. package/dist/dependency-C5_R1tvQ.js +0 -496
  42. package/dist/dependency-C5_R1tvQ.js.map +0 -1
  43. package/dist/dependency-Dfzs3khk.cjs +0 -722
  44. package/dist/dependency-Dfzs3khk.cjs.map +0 -1
  45. package/dist/integration.cjs.map +0 -1
  46. package/dist/integration.js.map +0 -1
  47. package/dist/ownership-B-VAPcce.js.map +0 -1
  48. package/dist/ownership-CU-9DKJQ.cjs.map +0 -1
@@ -0,0 +1,1735 @@
1
+ import { t as __exportAll } from "./chunk-pbuEa-1d.js";
2
+ import { i as isRecord$1, t as cloneValue, u as profile } from "./ownership-CduRygE7.js";
3
+ //#region core/src/schema.ts
4
+ const node = (value) => Object.freeze(value);
5
+ const field = () => node({ kind: "field" });
6
+ const optional = (value) => node({
7
+ ...value,
8
+ optional: true
9
+ });
10
+ const object = (shape) => node({
11
+ kind: "object",
12
+ shape
13
+ });
14
+ const variant = (tag, variants) => node({
15
+ kind: "variant",
16
+ tag,
17
+ variants
18
+ });
19
+ const single = (value) => node({
20
+ kind: "single",
21
+ value
22
+ });
23
+ const table = (value) => node({
24
+ kind: "table",
25
+ value
26
+ });
27
+ const map = (value) => node({
28
+ kind: "map",
29
+ value
30
+ });
31
+ const record = () => node({ kind: "record" });
32
+ const dict = () => node({ kind: "dict" });
33
+ const list = (config) => ({
34
+ kind: "list",
35
+ keyOf: config.keyOf
36
+ });
37
+ const tree = () => node({ kind: "tree" });
38
+ const pathProxy = (address) => new Proxy({ address }, { get: (_target, property) => {
39
+ if (property === "address") return address;
40
+ if (property === "item") return (id) => pathProxy([...address, id]);
41
+ if (typeof property === "symbol") return void 0;
42
+ return pathProxy([...address, property]);
43
+ } });
44
+ const select = (owner, kind, pick) => {
45
+ const selected = pick(pathProxy([]));
46
+ return Object.freeze({
47
+ kind,
48
+ schema: owner,
49
+ address: Object.freeze([...selected.address ?? []])
50
+ });
51
+ };
52
+ const schema = (shape) => {
53
+ const result = {
54
+ kind: "schema",
55
+ shape,
56
+ collection: (pick) => select(result, "collection", pick),
57
+ value: (pick) => select(result, "value", pick)
58
+ };
59
+ return Object.freeze(result);
60
+ };
61
+ //#endregion
62
+ //#region core/src/address.ts
63
+ const registries = /* @__PURE__ */ new WeakMap();
64
+ const registryNode = () => ({ static: /* @__PURE__ */ new Map() });
65
+ const registryFor = (schema) => {
66
+ const cached = registries.get(schema);
67
+ if (cached) return cached;
68
+ const registry = {
69
+ root: registryNode(),
70
+ nextPath: 0
71
+ };
72
+ registries.set(schema, registry);
73
+ return registry;
74
+ };
75
+ const hashText = (value, seed) => {
76
+ let hash = seed;
77
+ for (let index = 0; index < value.length; index += 1) hash = Math.imul(hash ^ value.charCodeAt(index), 16777619);
78
+ return hash >>> 0;
79
+ };
80
+ const appendAddressHash = (hash, segment) => hashText(segment, hashText("/", hash));
81
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
82
+ const unwrap = (node) => {
83
+ let current = node;
84
+ while (current?.kind === "single") current = current.value;
85
+ return current;
86
+ };
87
+ const variantNode = (node, value) => {
88
+ const tag = isRecord(value) && typeof value[node.tag] === "string" ? value[node.tag] : void 0;
89
+ return node.variants[String(tag ?? Object.keys(node.variants)[0] ?? "")];
90
+ };
91
+ const schemaRoot$1 = (schema) => ({
92
+ kind: "object",
93
+ shape: schema.shape
94
+ });
95
+ const step = (nodeInput, value, segment) => {
96
+ let node = unwrap(nodeInput);
97
+ if (!node) return {
98
+ node: void 0,
99
+ dynamic: false
100
+ };
101
+ if (node.kind === "variant") node = unwrap(variantNode(node, value));
102
+ if (!node) return {
103
+ node: void 0,
104
+ dynamic: false
105
+ };
106
+ if (node.kind === "object") return {
107
+ node: node.shape[segment],
108
+ dynamic: false
109
+ };
110
+ if (node.kind === "table" || node.kind === "map") return {
111
+ node: node.value,
112
+ dynamic: true
113
+ };
114
+ if (node.kind === "record" || node.kind === "dict" || node.kind === "list" || node.kind === "tree") return {
115
+ node,
116
+ dynamic: true
117
+ };
118
+ return {
119
+ node: void 0,
120
+ dynamic: false
121
+ };
122
+ };
123
+ const pathFor = (schema, address, document) => {
124
+ const registry = registryFor(schema);
125
+ let trie = registry.root;
126
+ let node = schemaRoot$1(schema);
127
+ let value = document;
128
+ for (const segment of address) {
129
+ profile.address.schemaStep();
130
+ profile.address.documentStep();
131
+ const resolved = step(node, value, segment);
132
+ if (!resolved.node) return void 0;
133
+ trie = resolved.dynamic ? trie.dynamic ??= registryNode() : (() => {
134
+ const existing = trie.static.get(segment);
135
+ if (existing) return existing;
136
+ const created = registryNode();
137
+ trie.static.set(segment, created);
138
+ return created;
139
+ })();
140
+ node = resolved.node;
141
+ value = readSegment(value, segment);
142
+ }
143
+ if (trie.path === void 0) trie.path = registry.nextPath++;
144
+ return trie.path;
145
+ };
146
+ const resolveAddress = (schema, address, document) => {
147
+ if (!Array.isArray(address)) return void 0;
148
+ for (const segment of address) if (typeof segment !== "string") return void 0;
149
+ profile.address.arrayCopied();
150
+ const owned = Object.freeze(address.slice());
151
+ const path = pathFor(schema, owned, document);
152
+ return path === void 0 ? void 0 : {
153
+ path,
154
+ address: owned
155
+ };
156
+ };
157
+ const nodeAt = (schema, address, document) => {
158
+ let node = schemaRoot$1(schema);
159
+ let value = document;
160
+ for (const segment of address) {
161
+ node = step(node, value, segment).node;
162
+ value = readSegment(value, segment);
163
+ if (!node) return void 0;
164
+ }
165
+ return unwrap(node);
166
+ };
167
+ const readSegment = (value, segment) => {
168
+ if (!isRecord(value) && !Array.isArray(value)) return void 0;
169
+ if (isRecord(value) && "byId" in value && isRecord(value.byId)) {
170
+ const entity = value.byId[segment];
171
+ if (entity !== void 0 || Object.prototype.hasOwnProperty.call(value.byId, segment)) return entity;
172
+ }
173
+ return value[segment];
174
+ };
175
+ const read = (root, address) => {
176
+ let value = root;
177
+ for (const segment of address) {
178
+ value = readSegment(value, segment);
179
+ if (value === void 0) return void 0;
180
+ }
181
+ return value;
182
+ };
183
+ /** Resolves schema and document location in one address traversal. */
184
+ const resolveLocated = (schema, root, address) => {
185
+ if (address.length === 0) return void 0;
186
+ let node = schemaRoot$1(schema);
187
+ let current = root;
188
+ let collection;
189
+ let addressHash = 2166136261;
190
+ for (let index = 0; index < address.length - 1; index += 1) {
191
+ profile.address.schemaStep();
192
+ profile.address.documentStep();
193
+ const resolved = step(node, current, address[index]);
194
+ if (!resolved.node) return void 0;
195
+ if (node?.kind === "table" || node?.kind === "map") collection = {
196
+ address: address.slice(0, index),
197
+ addressHash,
198
+ id: address[index],
199
+ ...collection ? { parent: collection } : {}
200
+ };
201
+ addressHash = appendAddressHash(addressHash, address[index]);
202
+ node = resolved.node;
203
+ current = readSegment(current, address[index]);
204
+ if (!node) return void 0;
205
+ }
206
+ profile.address.schemaStep();
207
+ profile.address.documentStep();
208
+ const last = address[address.length - 1];
209
+ const resolved = step(node, current, last);
210
+ if (!resolved.node || !isRecord(current) && !Array.isArray(current)) return void 0;
211
+ if (node?.kind === "table" || node?.kind === "map") collection = {
212
+ address: address.slice(0, -1),
213
+ addressHash,
214
+ id: last,
215
+ ...collection ? { parent: collection } : {}
216
+ };
217
+ addressHash = appendAddressHash(addressHash, last);
218
+ if (isRecord(current) && "byId" in current && isRecord(current.byId) && last in current.byId) return {
219
+ addressHash,
220
+ node: resolved.node,
221
+ parent: current.byId,
222
+ key: last,
223
+ value: current.byId[last],
224
+ ...collection ? { collection } : {}
225
+ };
226
+ return {
227
+ addressHash,
228
+ node: resolved.node,
229
+ parent: current,
230
+ key: Array.isArray(current) && /^\d+$/.test(last) ? Number(last) : last,
231
+ value: readSegment(current, last),
232
+ ...collection ? { collection } : {}
233
+ };
234
+ };
235
+ const locate = (root, address) => {
236
+ if (address.length === 0) return void 0;
237
+ let current = root;
238
+ for (let index = 0; index < address.length - 1; index += 1) current = readSegment(current, address[index]);
239
+ if (!isRecord(current) && !Array.isArray(current)) return void 0;
240
+ const last = address[address.length - 1];
241
+ if (isRecord(current) && "byId" in current && isRecord(current.byId) && last in current.byId) return {
242
+ parent: current.byId,
243
+ key: last,
244
+ value: current.byId[last]
245
+ };
246
+ return {
247
+ parent: current,
248
+ key: Array.isArray(current) && /^\d+$/.test(last) ? Number(last) : last,
249
+ value: readSegment(current, last)
250
+ };
251
+ };
252
+ const set = (root, address, value) => {
253
+ const target = locate(root, address);
254
+ if (!target) return false;
255
+ target.parent[target.key] = value;
256
+ return true;
257
+ };
258
+ const contains = (parent, child) => {
259
+ profile.address.prefixComparison();
260
+ if (parent.length > child.length) return false;
261
+ for (let index = 0; index < parent.length; index += 1) {
262
+ profile.address.segmentCompared();
263
+ if (parent[index] !== child[index]) return false;
264
+ }
265
+ return true;
266
+ };
267
+ const overlaps = (a, b) => contains(a, b) || contains(b, a);
268
+ const debugKey = (address) => {
269
+ let result = "";
270
+ for (let index = 0; index < address.length; index += 1) {
271
+ if (index > 0) result += "/";
272
+ result += address[index].replaceAll("~", "~~").replaceAll("/", "~/");
273
+ }
274
+ return result;
275
+ };
276
+ //#endregion
277
+ //#region core/src/impact-target.ts
278
+ var impact_target_exports = /* @__PURE__ */ __exportAll({
279
+ address: () => address,
280
+ belongs: () => belongs,
281
+ bucket: () => bucket,
282
+ id: () => id,
283
+ same: () => same
284
+ });
285
+ const address = (target) => "at" in target ? target.at : target.address;
286
+ const id = (target) => target.kind === "collection" && "id" in target ? target.id : void 0;
287
+ const belongs = (target, schema) => !("schema" in target) || target.schema === schema;
288
+ const same = (left, right) => {
289
+ if (left.kind !== right.kind) return false;
290
+ if ("schema" in left && "schema" in right && left.schema !== right.schema) return false;
291
+ const leftAddress = address(left);
292
+ const rightAddress = address(right);
293
+ if (leftAddress.length !== rightAddress.length) return false;
294
+ for (let index = 0; index < leftAddress.length; index += 1) if (leftAddress[index] !== rightAddress[index]) return false;
295
+ return left.kind !== "collection" || id(left) === id(right);
296
+ };
297
+ const bucket = (target) => address(target)[0];
298
+ //#endregion
299
+ //#region core/src/access/reader.ts
300
+ const schemaRoot = (schema) => object(schema.shape);
301
+ const assertActive = (context) => {
302
+ if (!context.active()) throw new Error("Document reader is no longer active.");
303
+ };
304
+ const readAt = (context, address) => {
305
+ assertActive(context);
306
+ profile.reader.lookup();
307
+ return read(context.root(), address);
308
+ };
309
+ const collectValue = (context, address) => {
310
+ context.dependencies?.record({
311
+ kind: "value",
312
+ at: address
313
+ });
314
+ };
315
+ const collectCollection = (context, address, id) => {
316
+ const target = {
317
+ kind: "collection",
318
+ at: address,
319
+ ...id === void 0 ? {} : { id }
320
+ };
321
+ context.dependencies?.record(target);
322
+ };
323
+ const readerFor = (node, context, address = []) => {
324
+ if (node.kind === "field") return { get: () => {
325
+ collectValue(context, address);
326
+ return readAt(context, address);
327
+ } };
328
+ if (node.kind === "dict" || node.kind === "record") return { get: () => {
329
+ collectValue(context, address);
330
+ profile.reader.structuralSnapshot();
331
+ return cloneValue(readAt(context, address), "reader");
332
+ } };
333
+ if (node.kind === "list") return {
334
+ values: () => {
335
+ collectValue(context, address);
336
+ const value = readAt(context, address);
337
+ profile.reader.structuralSnapshot();
338
+ return cloneValue(Array.isArray(value) ? value : [], "reader");
339
+ },
340
+ length: () => {
341
+ collectValue(context, address);
342
+ const value = readAt(context, address);
343
+ return Array.isArray(value) ? value.length : 0;
344
+ },
345
+ at: (index) => {
346
+ collectValue(context, address);
347
+ const value = readAt(context, address);
348
+ profile.reader.structuralSnapshot();
349
+ return cloneValue(Array.isArray(value) ? value[index] : void 0, "reader");
350
+ }
351
+ };
352
+ if (node.kind === "tree") return {
353
+ rootId: () => {
354
+ collectValue(context, address);
355
+ const value = readAt(context, address);
356
+ return isRecord$1(value) && typeof value.rootId === "string" ? value.rootId : void 0;
357
+ },
358
+ has: (id) => {
359
+ collectValue(context, address);
360
+ const value = readAt(context, address);
361
+ return isRecord$1(value) && isRecord$1(value.nodes) && Object.prototype.hasOwnProperty.call(value.nodes, id);
362
+ },
363
+ value: (id) => {
364
+ collectValue(context, address);
365
+ const value = readAt(context, address);
366
+ profile.reader.structuralSnapshot();
367
+ return cloneValue(isRecord$1(value) && isRecord$1(value.nodes) && isRecord$1(value.nodes[id]) ? value.nodes[id].value : void 0, "reader");
368
+ },
369
+ parent: (id) => {
370
+ collectValue(context, address);
371
+ const value = readAt(context, address);
372
+ const entry = isRecord$1(value) && isRecord$1(value.nodes) ? value.nodes[id] : void 0;
373
+ return isRecord$1(entry) && typeof entry.parentId === "string" ? entry.parentId : void 0;
374
+ },
375
+ children: (id) => {
376
+ collectValue(context, address);
377
+ const value = readAt(context, address);
378
+ const entry = isRecord$1(value) && isRecord$1(value.nodes) ? value.nodes[id] : void 0;
379
+ return isRecord$1(entry) && Array.isArray(entry.children) ? [...entry.children] : [];
380
+ }
381
+ };
382
+ if (node.kind === "table" || node.kind === "map") {
383
+ let items;
384
+ return {
385
+ ids: () => {
386
+ collectCollection(context, address);
387
+ const value = readAt(context, address);
388
+ const ids = node.kind === "table" && isRecord$1(value) && Array.isArray(value.ids) ? [...value.ids] : isRecord$1(value) ? Object.keys(value) : [];
389
+ profile.reader.collectionIds(ids.length);
390
+ return ids;
391
+ },
392
+ has: (id) => {
393
+ collectCollection(context, address, id);
394
+ const value = readAt(context, address);
395
+ const byId = node.kind === "table" && isRecord$1(value) && isRecord$1(value.byId) ? value.byId : value;
396
+ return isRecord$1(byId) && Object.prototype.hasOwnProperty.call(byId, id);
397
+ },
398
+ get: (id) => {
399
+ collectCollection(context, address, id);
400
+ const value = readAt(context, address);
401
+ const byId = node.kind === "table" && isRecord$1(value) && isRecord$1(value.byId) ? value.byId : value;
402
+ if (!isRecord$1(byId) || !Object.prototype.hasOwnProperty.call(byId, id)) return void 0;
403
+ const cached = items?.get(id);
404
+ if (cached) return cached;
405
+ const reader = readerFor(node.value, context, [...address, id]);
406
+ (items ??= /* @__PURE__ */ new Map()).set(id, reader);
407
+ return reader;
408
+ }
409
+ };
410
+ }
411
+ if (node.kind === "single") return readerFor(node.value, context, address);
412
+ if (node.kind === "variant") return new Proxy({}, { get: (_target, property) => {
413
+ if (typeof property === "symbol") return void 0;
414
+ const value = readAt(context, address);
415
+ const tag = isRecord$1(value) && typeof value[node.tag] === "string" ? String(value[node.tag]) : void 0;
416
+ const child = (tag ? node.variants[tag] : void 0)?.shape[property];
417
+ return child ? readerFor(child, context, [...address, property]) : void 0;
418
+ } });
419
+ let children;
420
+ return new Proxy({}, { get: (_target, property) => {
421
+ if (typeof property === "symbol") return void 0;
422
+ const child = node.shape[property];
423
+ if (!child) return void 0;
424
+ const cached = children?.get(property);
425
+ if (cached) return cached;
426
+ const reader = readerFor(child, context, [...address, property]);
427
+ (children ??= /* @__PURE__ */ new Map()).set(property, reader);
428
+ return reader;
429
+ } });
430
+ };
431
+ const documentReader = (schema, root, active, dependencies) => {
432
+ profile.reader.session();
433
+ return readerFor(schemaRoot(schema), {
434
+ root,
435
+ active,
436
+ dependencies
437
+ });
438
+ };
439
+ //#endregion
440
+ //#region core/src/runtime/contract.ts
441
+ var DocumentReentrancyError = class extends Error {
442
+ constructor() {
443
+ super("Document writes cannot be re-entered during an update or notification.");
444
+ this.name = "DocumentReentrancyError";
445
+ }
446
+ };
447
+ var DocumentDisposedError = class extends Error {
448
+ constructor() {
449
+ super("Doxum runtime has been disposed.");
450
+ this.name = "DocumentDisposedError";
451
+ }
452
+ };
453
+ //#endregion
454
+ //#region core/src/runtime/access.ts
455
+ const states = /* @__PURE__ */ new WeakMap();
456
+ const bindRuntimeAccess = (runtime, state) => {
457
+ states.set(runtime, state);
458
+ };
459
+ const accessOf = (runtime) => {
460
+ const state = states.get(runtime);
461
+ if (!state) throw new Error("Unknown Doxum runtime.");
462
+ return state;
463
+ };
464
+ const readWith = (runtime, run, dependencies) => {
465
+ const state = accessOf(runtime);
466
+ if (state.disposed) throw new DocumentDisposedError();
467
+ let active = true;
468
+ const reader = documentReader(state.schema, () => state.document, () => active, dependencies);
469
+ try {
470
+ return run(reader);
471
+ } finally {
472
+ active = false;
473
+ }
474
+ };
475
+ //#endregion
476
+ //#region core/src/runtime/notification.ts
477
+ const ROOT_BUCKET = Symbol("document-root");
478
+ const notifications = /* @__PURE__ */ new WeakMap();
479
+ const key = (value) => bucket(value) ?? ROOT_BUCKET;
480
+ const createNotification = (runtime) => {
481
+ const notification = {
482
+ root: /* @__PURE__ */ new Set(),
483
+ filtered: /* @__PURE__ */ new Set(),
484
+ buckets: /* @__PURE__ */ new Map(),
485
+ processors: [],
486
+ candidates: /* @__PURE__ */ new Set(),
487
+ rootSnapshot: [],
488
+ notifying: false
489
+ };
490
+ notifications.set(runtime, notification);
491
+ return notification;
492
+ };
493
+ const notificationOf = (runtime) => {
494
+ const value = notifications.get(runtime);
495
+ if (!value) throw new Error("Unknown Doxum runtime.");
496
+ return value;
497
+ };
498
+ const shareNotification = (source, target) => {
499
+ notifications.set(target, notificationOf(source));
500
+ };
501
+ const attachProjection = (runtime, processor) => {
502
+ const notification = notificationOf(runtime);
503
+ const entry = {
504
+ processor,
505
+ active: true
506
+ };
507
+ notification.processors.push(entry);
508
+ return () => {
509
+ if (!entry.active) return;
510
+ entry.active = false;
511
+ if (!notification.notifying) {
512
+ const index = notification.processors.indexOf(entry);
513
+ if (index >= 0) notification.processors.splice(index, 1);
514
+ }
515
+ };
516
+ };
517
+ const subscribeRoot = (notification, listener) => {
518
+ const entry = {
519
+ listener,
520
+ active: true
521
+ };
522
+ notification.root.add(entry);
523
+ return () => {
524
+ entry.active = false;
525
+ if (!notification.notifying) notification.root.delete(entry);
526
+ };
527
+ };
528
+ const subscribeTargets = (notification, targets, listener) => {
529
+ const entry = {
530
+ targets: Object.freeze(targets.slice()),
531
+ listener,
532
+ active: true
533
+ };
534
+ notification.filtered.add(entry);
535
+ const keys = new Set(targets.map(key));
536
+ keys.forEach((key) => {
537
+ const bucket = notification.buckets.get(key) ?? /* @__PURE__ */ new Set();
538
+ bucket.add(entry);
539
+ notification.buckets.set(key, bucket);
540
+ });
541
+ return () => {
542
+ if (!entry.active) return;
543
+ entry.active = false;
544
+ if (notification.notifying) return;
545
+ notification.filtered.delete(entry);
546
+ keys.forEach((key) => {
547
+ const bucket = notification.buckets.get(key);
548
+ bucket?.delete(entry);
549
+ if (bucket?.size === 0) notification.buckets.delete(key);
550
+ });
551
+ };
552
+ };
553
+ const notify = (notification, commit) => {
554
+ notification.notifying = true;
555
+ const errors = [];
556
+ const call = (listener) => {
557
+ try {
558
+ listener(commit);
559
+ } catch (error) {
560
+ errors.push(Object.freeze({
561
+ phase: "listener",
562
+ error
563
+ }));
564
+ }
565
+ };
566
+ try {
567
+ const processorCount = notification.processors.length;
568
+ for (let index = 0; index < processorCount; index += 1) {
569
+ const entry = notification.processors[index];
570
+ if (!entry?.active) continue;
571
+ try {
572
+ entry.processor.capture(commit);
573
+ } catch (error) {
574
+ errors.push(Object.freeze({
575
+ phase: "processor",
576
+ error
577
+ }));
578
+ }
579
+ }
580
+ for (let index = 0; index < processorCount; index += 1) {
581
+ const entry = notification.processors[index];
582
+ if (!entry?.active) continue;
583
+ try {
584
+ entry.processor.settle();
585
+ } catch (error) {
586
+ errors.push(Object.freeze({
587
+ phase: "processor",
588
+ error
589
+ }));
590
+ }
591
+ }
592
+ for (let index = 0; index < processorCount; index += 1) {
593
+ const entry = notification.processors[index];
594
+ if (!entry?.active) continue;
595
+ try {
596
+ errors.push(...entry.processor.flush());
597
+ } catch (error) {
598
+ errors.push(Object.freeze({
599
+ phase: "flush",
600
+ error
601
+ }));
602
+ }
603
+ }
604
+ const candidates = notification.candidates;
605
+ candidates.clear();
606
+ if (commit.impact.kind === "reset") notification.filtered.forEach((entry) => candidates.add(entry));
607
+ else for (const operation of commit.operations) {
608
+ const key = operation.at[0] ?? ROOT_BUCKET;
609
+ notification.buckets.get(key)?.forEach((entry) => candidates.add(entry));
610
+ notification.buckets.get(ROOT_BUCKET)?.forEach((entry) => candidates.add(entry));
611
+ }
612
+ candidates.forEach((entry) => {
613
+ if (entry.active && entry.targets.some(commit.impact.affects)) call(entry.listener);
614
+ });
615
+ const rootSnapshot = notification.rootSnapshot;
616
+ rootSnapshot.length = 0;
617
+ notification.root.forEach((entry) => rootSnapshot.push(entry));
618
+ for (const entry of rootSnapshot) if (entry.active) call(entry.listener);
619
+ } finally {
620
+ notification.notifying = false;
621
+ let writeIndex = 0;
622
+ for (const entry of notification.processors) if (entry.active) notification.processors[writeIndex++] = entry;
623
+ notification.processors.length = writeIndex;
624
+ notification.root.forEach((entry) => {
625
+ if (!entry.active) notification.root.delete(entry);
626
+ });
627
+ notification.filtered.forEach((entry) => {
628
+ if (!entry.active) notification.filtered.delete(entry);
629
+ });
630
+ notification.buckets.forEach((bucket, key) => {
631
+ bucket.forEach((entry) => {
632
+ if (!entry.active) bucket.delete(entry);
633
+ });
634
+ if (bucket.size === 0) notification.buckets.delete(key);
635
+ });
636
+ }
637
+ return Object.freeze(errors);
638
+ };
639
+ const disposeNotification = (notification) => {
640
+ const attachments = notification.processors.slice();
641
+ notification.root.clear();
642
+ notification.filtered.clear();
643
+ notification.buckets.clear();
644
+ notification.processors.length = 0;
645
+ notification.candidates.clear();
646
+ notification.rootSnapshot.length = 0;
647
+ const errors = [];
648
+ attachments.forEach((entry) => {
649
+ if (!entry.active) return;
650
+ try {
651
+ entry.processor.dispose();
652
+ } catch (error) {
653
+ errors.push(error);
654
+ }
655
+ });
656
+ if (errors.length) throw new AggregateError(errors, "Projection disposal notification failed.");
657
+ };
658
+ //#endregion
659
+ //#region core/src/projection/contract.ts
660
+ var ProjectionError = class extends Error {
661
+ constructor(phase, identity, revisions, cause) {
662
+ super(`Projection ${phase} failed: ${identity}`, { cause });
663
+ this.phase = phase;
664
+ this.identity = identity;
665
+ this.revisions = revisions;
666
+ this.name = "ProjectionError";
667
+ }
668
+ };
669
+ var ProjectionDisposedError = class extends Error {
670
+ constructor() {
671
+ super("Projection has been disposed.");
672
+ this.name = "ProjectionDisposedError";
673
+ }
674
+ };
675
+ //#endregion
676
+ //#region core/src/projection/scheduler.ts
677
+ const projectionHandles = /* @__PURE__ */ new WeakSet();
678
+ const createScheduler = (onError) => {
679
+ let disposed = false;
680
+ let depth = 0;
681
+ let phase = "idle";
682
+ let sequence = 0;
683
+ const records = /* @__PURE__ */ new Map();
684
+ const nodes = /* @__PURE__ */ new Set();
685
+ const pending = /* @__PURE__ */ new Set();
686
+ const heap = [];
687
+ const queued = /* @__PURE__ */ new Set();
688
+ const completed = [];
689
+ const emissions = /* @__PURE__ */ new Set();
690
+ const errors = [];
691
+ let reportingFailures = [];
692
+ const guards = /* @__PURE__ */ new Set();
693
+ const cleanups = /* @__PURE__ */ new Set();
694
+ const assertActive = () => {
695
+ if (disposed) throw new ProjectionDisposedError();
696
+ };
697
+ const assertIdle = () => {
698
+ assertActive();
699
+ if (phase !== "idle") throw new Error("Projection cannot be re-entered during processing or notification.");
700
+ };
701
+ const lock = (value) => guards.forEach((guard) => guard(value));
702
+ const enqueue = (node) => {
703
+ if (node.disposed || queued.has(node)) return;
704
+ queued.add(node);
705
+ profile.projection("scheduledNodes");
706
+ let i = heap.length;
707
+ heap.push(node);
708
+ while (i > 0) {
709
+ const p = i - 1 >> 1;
710
+ if (heap[p].order < node.order) break;
711
+ heap[i] = heap[p];
712
+ i = p;
713
+ }
714
+ heap[i] = node;
715
+ };
716
+ const pop = () => {
717
+ const first = heap[0];
718
+ const last = heap.pop();
719
+ if (heap.length) {
720
+ let i = 0;
721
+ while (i * 2 + 1 < heap.length) {
722
+ let c = i * 2 + 1;
723
+ if (c + 1 < heap.length && heap[c + 1].order < heap[c].order) c++;
724
+ if (last.order < heap[c].order) break;
725
+ heap[i] = heap[c];
726
+ i = c;
727
+ }
728
+ heap[i] = last;
729
+ }
730
+ return first;
731
+ };
732
+ const errorFor = (node, cause, kind = "processor") => new ProjectionError(kind, node.name, node.sources.map((source) => source.revision()), cause);
733
+ const capture = (source) => {
734
+ if (disposed) return;
735
+ if (phase !== "idle") {
736
+ source.fault = new ProjectionError("source", "reentrant source", [source.revision()], /* @__PURE__ */ new Error("Source changed while projection was running."));
737
+ errors.push(source.fault);
738
+ throw source.fault;
739
+ }
740
+ pending.add(source);
741
+ profile.projection("sourceEvents");
742
+ if (source.fault) errors.push(source.fault);
743
+ };
744
+ const settle = () => {
745
+ if (disposed || depth || phase !== "idle") return;
746
+ phase = "compute";
747
+ lock(true);
748
+ try {
749
+ pending.forEach((source) => source.consumers.forEach(enqueue));
750
+ while (heap.length) {
751
+ const node = pop();
752
+ if (node.disposed) continue;
753
+ const wasFaulted = node.fault !== void 0;
754
+ profile.projection("processedNodes");
755
+ let changed = false;
756
+ const blocked = node.sources.find((source) => source.fault || source.disposed);
757
+ if (blocked) node.fault = errorFor(node, blocked.fault ?? new ProjectionDisposedError(), "blocked");
758
+ else {
759
+ const build = node.forced || wasFaulted || node.sources.some((source) => source.reset());
760
+ try {
761
+ changed = node.evaluate(build);
762
+ const failure = node.sources.find((source) => source.fault)?.fault;
763
+ if (failure) throw failure;
764
+ node.fault = void 0;
765
+ } catch (cause) {
766
+ const error = errorFor(node, cause);
767
+ errors.push(error);
768
+ node.fault = error;
769
+ if (!build) try {
770
+ changed = node.evaluate(true);
771
+ const failure = node.sources.find((source) => source.fault)?.fault;
772
+ if (failure) throw failure;
773
+ node.fault = void 0;
774
+ } catch (cause) {
775
+ node.fault = errorFor(node, cause);
776
+ errors.push(node.fault);
777
+ }
778
+ }
779
+ }
780
+ node.forced = false;
781
+ node.statusChanged = wasFaulted !== (node.fault !== void 0);
782
+ completed.push(node);
783
+ if (changed || wasFaulted || node.fault) {
784
+ profile.projection("publishedNodes");
785
+ emissions.add(node);
786
+ node.consumers.forEach(enqueue);
787
+ }
788
+ }
789
+ completed.forEach((node) => node.publish());
790
+ } finally {
791
+ lock(false);
792
+ phase = "idle";
793
+ }
794
+ };
795
+ const flush = () => {
796
+ if (disposed || depth) return [];
797
+ if (pending.size || completed.length) profile.projection("flushes");
798
+ phase = "notify";
799
+ lock(true);
800
+ const reportFailures = [];
801
+ try {
802
+ emissions.forEach((node) => node.emit((listener) => {
803
+ try {
804
+ listener();
805
+ } catch (cause) {
806
+ errors.push(errorFor(node, cause, "listener"));
807
+ }
808
+ }));
809
+ for (const error of errors.slice()) try {
810
+ onError(error);
811
+ } catch (cause) {
812
+ reportFailures.push(cause);
813
+ }
814
+ return Object.freeze([...errors.map((error) => Object.freeze({
815
+ phase: error.phase === "listener" ? "listener" : "processor",
816
+ error
817
+ })), ...reportFailures.map((error) => Object.freeze({
818
+ phase: "listener",
819
+ error
820
+ }))]);
821
+ } finally {
822
+ pending.forEach((source) => source.clear());
823
+ completed.forEach((node) => node.clear());
824
+ pending.clear();
825
+ queued.clear();
826
+ completed.length = 0;
827
+ emissions.clear();
828
+ errors.length = 0;
829
+ reportingFailures = reportFailures;
830
+ lock(false);
831
+ phase = "idle";
832
+ }
833
+ };
834
+ const run = () => {
835
+ settle();
836
+ const result = flush();
837
+ const failures = reportingFailures;
838
+ reportingFailures = [];
839
+ if (failures.length) throw new AggregateError(failures, "Projection error reporter failed.");
840
+ return result;
841
+ };
842
+ return {
843
+ assertActive,
844
+ assertIdle,
845
+ capture,
846
+ settle,
847
+ flush,
848
+ run,
849
+ records,
850
+ guards,
851
+ cleanups,
852
+ get active() {
853
+ return !disposed;
854
+ },
855
+ register(handle, record) {
856
+ assertIdle();
857
+ records.set(handle, record);
858
+ projectionHandles.add(handle);
859
+ },
860
+ unregisterSource(handle) {
861
+ const record = records.get(handle);
862
+ if (record) {
863
+ record.disposed = true;
864
+ pending.delete(record);
865
+ record.clear();
866
+ records.delete(handle);
867
+ }
868
+ },
869
+ source(handle) {
870
+ assertActive();
871
+ const source = records.get(handle);
872
+ if (!source || source.disposed) throw new Error("Unknown, disposed, or foreign projection source.");
873
+ return source;
874
+ },
875
+ addNode(node) {
876
+ nodes.add(node);
877
+ node.sources.forEach((source) => source.consumers.add(node));
878
+ },
879
+ order: () => sequence++,
880
+ initialize(run) {
881
+ assertIdle();
882
+ phase = "compute";
883
+ lock(true);
884
+ try {
885
+ return run();
886
+ } finally {
887
+ lock(false);
888
+ phase = "idle";
889
+ }
890
+ },
891
+ rebuild(node) {
892
+ assertIdle();
893
+ if (node.disposed) throw new ProjectionDisposedError();
894
+ node.forced = true;
895
+ enqueue(node);
896
+ run();
897
+ },
898
+ disposeNode(node) {
899
+ if (node.disposed) return;
900
+ assertIdle();
901
+ if (node.consumers.size) throw new Error("Cannot dispose a projection node with downstream consumers.");
902
+ node.disposed = true;
903
+ node.sources.forEach((source) => source.consumers.delete(node));
904
+ nodes.delete(node);
905
+ node.release();
906
+ for (const [handle, record] of records) if (record === node) records.delete(handle);
907
+ },
908
+ batch(callback) {
909
+ assertIdle();
910
+ depth++;
911
+ let failed = false;
912
+ try {
913
+ const value = callback();
914
+ assertSynchronous(value);
915
+ return value;
916
+ } catch (error) {
917
+ failed = true;
918
+ throw error;
919
+ } finally {
920
+ depth--;
921
+ if (!depth) if (failed) try {
922
+ run();
923
+ } catch {}
924
+ else run();
925
+ }
926
+ },
927
+ dispose() {
928
+ if (disposed) return;
929
+ assertIdle();
930
+ disposed = true;
931
+ const failures = [];
932
+ cleanups.forEach((cleanup) => {
933
+ try {
934
+ cleanup();
935
+ } catch (error) {
936
+ failures.push(error);
937
+ }
938
+ });
939
+ cleanups.clear();
940
+ nodes.forEach((node) => {
941
+ node.disposed = true;
942
+ node.release();
943
+ node.consumers.clear();
944
+ });
945
+ records.forEach((source) => {
946
+ source.disposed = true;
947
+ source.consumers.clear();
948
+ source.clear();
949
+ });
950
+ nodes.clear();
951
+ records.clear();
952
+ pending.clear();
953
+ heap.length = 0;
954
+ completed.length = 0;
955
+ queued.clear();
956
+ emissions.clear();
957
+ guards.clear();
958
+ errors.length = 0;
959
+ reportingFailures = [];
960
+ if (failures.length) throw new AggregateError(failures, "Projection cleanup failed.");
961
+ },
962
+ debug: () => ({
963
+ nodes: nodes.size,
964
+ sources: records.size - nodes.size,
965
+ subscriptions: cleanups.size,
966
+ pending: pending.size + heap.length
967
+ })
968
+ };
969
+ };
970
+ const assertSynchronous = (value) => {
971
+ if (value != null && (typeof value === "object" || typeof value === "function") && "then" in value && typeof value.then === "function") throw new TypeError("Projection callbacks must be synchronous.");
972
+ };
973
+ const assertScope = (active) => {
974
+ if (!active()) throw new Error("Projection reader or writer is no longer active.");
975
+ };
976
+ //#endregion
977
+ //#region core/src/projection/source.ts
978
+ const createSources = (scheduler) => {
979
+ const documents = /* @__PURE__ */ new Map();
980
+ const readables = /* @__PURE__ */ new Map();
981
+ const collections = /* @__PURE__ */ new WeakMap();
982
+ const document = (runtime) => {
983
+ scheduler.assertIdle();
984
+ const state = accessOf(runtime);
985
+ if (state.disposed) throw new Error("Document has been disposed.");
986
+ const existing = documents.get(state);
987
+ if (existing) return existing;
988
+ const bindings = [];
989
+ const make = (targets, collection) => {
990
+ if (state.disposed) throw new Error("Document has been disposed.");
991
+ targets.forEach((value) => {
992
+ if (!belongs(value, state.schema)) throw new Error("Projection target belongs to another schema.");
993
+ });
994
+ const old = bindings.find((entry) => Boolean(collection) === collections.has(entry.handle) && entry.targets.length === targets.length && entry.targets.every((value, i) => same(value, targets[i])));
995
+ if (old) return old.handle;
996
+ let commits = [];
997
+ const record = {
998
+ consumers: /* @__PURE__ */ new Set(),
999
+ disposed: false,
1000
+ fault: void 0,
1001
+ revision: runtime.revision,
1002
+ reset: () => commits.some((commit) => commit.kind === "replace"),
1003
+ clear: () => {
1004
+ commits = [];
1005
+ },
1006
+ context: (active) => {
1007
+ assertScope(active);
1008
+ if (state.disposed) throw new Error("Document has been disposed.");
1009
+ const read = collection ? readerFor(nodeAt(state.schema, collection.address), {
1010
+ root: () => state.document,
1011
+ active
1012
+ }, collection.address) : documentReader(state.schema, () => state.document, active);
1013
+ return Object.freeze({
1014
+ read,
1015
+ target: collection,
1016
+ revision: runtime.revision(),
1017
+ commits: Object.freeze(commits.slice()),
1018
+ reset: record.reset()
1019
+ });
1020
+ }
1021
+ };
1022
+ const handle = collection ? {} : {
1023
+ collection: (pick) => {
1024
+ scheduler.assertIdle();
1025
+ const selector = state.schema.collection(pick);
1026
+ const node = nodeAt(state.schema, selector.address);
1027
+ if (node?.kind !== "table" && node?.kind !== "map") throw new TypeError("Expected a table or map collection path.");
1028
+ return make([selector], selector);
1029
+ },
1030
+ targets: (...selected) => {
1031
+ scheduler.assertIdle();
1032
+ if (!selected.length) throw new TypeError("Expected at least one target.");
1033
+ return make(selected);
1034
+ }
1035
+ };
1036
+ Object.freeze(handle);
1037
+ bindings.push({
1038
+ handle,
1039
+ targets,
1040
+ record
1041
+ });
1042
+ if (collection) collections.set(handle, {
1043
+ source: handle,
1044
+ target: collection
1045
+ });
1046
+ scheduler.register(handle, record);
1047
+ receivers.set(record, (commit) => {
1048
+ commits.push(commit);
1049
+ });
1050
+ return handle;
1051
+ };
1052
+ const receivers = /* @__PURE__ */ new Map();
1053
+ const handle = make([]);
1054
+ const guard = (locked) => {
1055
+ state.projectionLocks = (state.projectionLocks ?? 0) + (locked ? 1 : -1);
1056
+ };
1057
+ scheduler.guards.add(guard);
1058
+ const unsubscribe = attachProjection(runtime, {
1059
+ capture: (commit) => {
1060
+ for (const binding of bindings) if (!binding.targets.length || binding.targets.some(commit.impact.affects)) {
1061
+ receivers.get(binding.record)(commit);
1062
+ scheduler.capture(binding.record);
1063
+ }
1064
+ },
1065
+ settle: scheduler.settle,
1066
+ flush: scheduler.flush,
1067
+ dispose: () => {
1068
+ bindings.forEach(({ record }) => {
1069
+ record.fault = new ProjectionError("source", "document disposed", [runtime.revision()], /* @__PURE__ */ new Error("Document has been disposed."));
1070
+ scheduler.capture(record);
1071
+ });
1072
+ scheduler.run();
1073
+ }
1074
+ });
1075
+ scheduler.cleanups.add(() => {
1076
+ unsubscribe();
1077
+ scheduler.guards.delete(guard);
1078
+ });
1079
+ documents.set(state, handle);
1080
+ return handle;
1081
+ };
1082
+ const valueSource = (initial, equal) => {
1083
+ let value = initial;
1084
+ let previous = initial;
1085
+ let revision = 0;
1086
+ const handle = Object.freeze({});
1087
+ const record = {
1088
+ consumers: /* @__PURE__ */ new Set(),
1089
+ disposed: false,
1090
+ fault: void 0,
1091
+ revision: () => revision,
1092
+ reset: () => false,
1093
+ clear: () => {
1094
+ previous = value;
1095
+ },
1096
+ context: (active) => {
1097
+ assertScope(active);
1098
+ return Object.freeze({
1099
+ value,
1100
+ previous,
1101
+ revision,
1102
+ changed: !equal(previous, value),
1103
+ reset: false
1104
+ });
1105
+ }
1106
+ };
1107
+ scheduler.register(handle, record);
1108
+ const accept = (next) => {
1109
+ scheduler.assertIdle();
1110
+ const recovering = record.fault !== void 0;
1111
+ if (equal(value, next) && !recovering) return;
1112
+ record.fault = void 0;
1113
+ value = next;
1114
+ revision++;
1115
+ scheduler.capture(record);
1116
+ };
1117
+ return {
1118
+ source: handle,
1119
+ accept,
1120
+ set(next) {
1121
+ accept(next);
1122
+ scheduler.run();
1123
+ }
1124
+ };
1125
+ };
1126
+ return {
1127
+ dispose: () => {
1128
+ documents.clear();
1129
+ readables.clear();
1130
+ },
1131
+ document,
1132
+ input: (initial, options) => {
1133
+ const { source, set } = valueSource(initial, options?.isEqual ?? Object.is);
1134
+ return Object.freeze({
1135
+ source,
1136
+ set
1137
+ });
1138
+ },
1139
+ fromReadable: (readable, options) => {
1140
+ scheduler.assertIdle();
1141
+ if (projectionHandles.has(readable)) throw new Error("Projection nodes must be declared directly as sources.");
1142
+ const old = readables.get(readable);
1143
+ if (old) return old;
1144
+ const input = valueSource(readable.current(), options?.isEqual ?? Object.is);
1145
+ const receive = () => {
1146
+ if (!scheduler.active) return;
1147
+ try {
1148
+ input.accept(readable.current());
1149
+ } catch (cause) {
1150
+ const record = scheduler.source(input.source);
1151
+ record.fault = new ProjectionError("source", "external readable", [readable.revision()], cause);
1152
+ scheduler.capture(record);
1153
+ }
1154
+ scheduler.run();
1155
+ };
1156
+ let unsubscribe;
1157
+ try {
1158
+ unsubscribe = readable.subscribe(receive);
1159
+ input.accept(readable.current());
1160
+ } catch (error) {
1161
+ try {
1162
+ unsubscribe?.();
1163
+ } finally {
1164
+ scheduler.unregisterSource(input.source);
1165
+ }
1166
+ throw error;
1167
+ }
1168
+ scheduler.cleanups.add(unsubscribe);
1169
+ readables.set(readable, input.source);
1170
+ scheduler.run();
1171
+ return input.source;
1172
+ },
1173
+ collectionTarget: (handle) => {
1174
+ scheduler.source(handle);
1175
+ const value = collections.get(handle);
1176
+ if (!value) throw new Error("map requires a document collection source.");
1177
+ return value.target;
1178
+ }
1179
+ };
1180
+ };
1181
+ //#endregion
1182
+ //#region core/src/projection/node.ts
1183
+ const createNode = (scheduler, spec, behavior) => {
1184
+ scheduler.assertIdle();
1185
+ const entries = Object.entries(spec.sources).map(([key, handle]) => [key, scheduler.source(handle)]);
1186
+ const order = scheduler.order();
1187
+ const node = {
1188
+ ...behavior,
1189
+ publish: () => {
1190
+ if (node.fault) behavior.clear();
1191
+ else behavior.publish();
1192
+ },
1193
+ order,
1194
+ name: spec.name ? `${spec.name} (${order})` : `projection-${order}`,
1195
+ sources: entries.map(([, source]) => source),
1196
+ consumers: /* @__PURE__ */ new Set(),
1197
+ disposed: false,
1198
+ fault: void 0,
1199
+ forced: false,
1200
+ statusChanged: false,
1201
+ evaluate: (build) => {
1202
+ let active = true;
1203
+ try {
1204
+ const inputs = Object.fromEntries(entries.map(([key, source]) => [key, source.context(() => active)]));
1205
+ return behavior.evaluate(inputs, build, () => active);
1206
+ } finally {
1207
+ active = false;
1208
+ }
1209
+ }
1210
+ };
1211
+ scheduler.initialize(() => {
1212
+ const invalid = node.sources.find((source) => source.fault || source.disposed);
1213
+ if (invalid) throw invalid.fault ?? new ProjectionDisposedError();
1214
+ node.evaluate(true);
1215
+ node.publish();
1216
+ node.clear();
1217
+ });
1218
+ const check = () => {
1219
+ if (node.disposed || !scheduler.active) throw new ProjectionDisposedError();
1220
+ if (node.fault) throw node.fault;
1221
+ };
1222
+ return {
1223
+ node,
1224
+ check,
1225
+ install(handle) {
1226
+ scheduler.register(handle, node);
1227
+ scheduler.addNode(node);
1228
+ },
1229
+ rebuild: () => scheduler.rebuild(node),
1230
+ dispose: () => scheduler.disposeNode(node)
1231
+ };
1232
+ };
1233
+ //#endregion
1234
+ //#region core/src/projection/value.ts
1235
+ const createValue = (scheduler, spec) => {
1236
+ let instance;
1237
+ let value;
1238
+ let next;
1239
+ let previous;
1240
+ let initialized = false;
1241
+ let revision = 0;
1242
+ let changed = false;
1243
+ let reset = false;
1244
+ const listeners = /* @__PURE__ */ new Set();
1245
+ const owner = createNode(scheduler, spec, {
1246
+ evaluate: (sources, build) => {
1247
+ let candidate;
1248
+ if (build || !instance) {
1249
+ profile.materialized.rebuilt();
1250
+ instance = void 0;
1251
+ const built = spec.build(sources);
1252
+ assertSynchronous(built);
1253
+ instance = built;
1254
+ candidate = built.value;
1255
+ } else {
1256
+ profile.materialized.updated();
1257
+ const result = instance.update(sources);
1258
+ assertSynchronous(result);
1259
+ if (result.kind === "rebuild") {
1260
+ instance = void 0;
1261
+ const built = spec.build(sources);
1262
+ assertSynchronous(built);
1263
+ instance = built;
1264
+ candidate = built.value;
1265
+ build = true;
1266
+ } else candidate = result.kind === "changed" ? result.value : value;
1267
+ }
1268
+ previous = value;
1269
+ changed = !initialized || !(spec.isEqual ?? Object.is)(value, candidate);
1270
+ next = changed ? candidate : value;
1271
+ reset = build;
1272
+ return changed;
1273
+ },
1274
+ context: (active) => {
1275
+ assertScope(active);
1276
+ return Object.freeze({
1277
+ value: next,
1278
+ previous,
1279
+ changed,
1280
+ revision: revision + (changed ? 1 : 0),
1281
+ reset
1282
+ });
1283
+ },
1284
+ revision: () => revision,
1285
+ reset: () => reset,
1286
+ publish: () => {
1287
+ if (changed && initialized) revision++;
1288
+ value = next;
1289
+ initialized = true;
1290
+ },
1291
+ emit: (call) => {
1292
+ profile.materialized.notification();
1293
+ Array.from(listeners).forEach((listener) => call(listener));
1294
+ },
1295
+ clear: () => {
1296
+ next = value;
1297
+ previous = value;
1298
+ changed = false;
1299
+ reset = false;
1300
+ },
1301
+ release: () => {
1302
+ listeners.clear();
1303
+ instance = void 0;
1304
+ value = next = previous = void 0;
1305
+ }
1306
+ });
1307
+ const handle = Object.freeze({
1308
+ current: () => {
1309
+ owner.check();
1310
+ return value;
1311
+ },
1312
+ revision: () => {
1313
+ owner.check();
1314
+ return revision;
1315
+ },
1316
+ subscribe: (listener) => {
1317
+ owner.check();
1318
+ listeners.add(listener);
1319
+ return () => {
1320
+ listeners.delete(listener);
1321
+ };
1322
+ },
1323
+ rebuild: owner.rebuild,
1324
+ dispose: owner.dispose
1325
+ });
1326
+ owner.install(handle);
1327
+ return handle;
1328
+ };
1329
+ //#endregion
1330
+ //#region core/src/projection/collection.ts
1331
+ const readonlySet = (values) => {
1332
+ const set = new Set(values);
1333
+ const view = Object.freeze({
1334
+ get size() {
1335
+ return set.size;
1336
+ },
1337
+ has: (value) => set.has(value),
1338
+ entries: () => set.entries(),
1339
+ keys: () => set.keys(),
1340
+ values: () => set.values(),
1341
+ [Symbol.iterator]: () => set.values(),
1342
+ forEach: (callback, thisArg) => set.forEach((value) => callback.call(thisArg, value, value, view))
1343
+ });
1344
+ return view;
1345
+ };
1346
+ const createCollection = (scheduler, spec) => {
1347
+ const values = /* @__PURE__ */ new Map();
1348
+ let ids = Object.freeze([]);
1349
+ let staged = /* @__PURE__ */ new Map();
1350
+ let nextIds = ids;
1351
+ let change;
1352
+ let instance;
1353
+ let initialized = false;
1354
+ let reset = false;
1355
+ let revision = 0;
1356
+ let idsRevision = 0;
1357
+ let all;
1358
+ const itemVersions = /* @__PURE__ */ new Map();
1359
+ const items = /* @__PURE__ */ new Map();
1360
+ const itemListeners = /* @__PURE__ */ new Map();
1361
+ const idsListeners = /* @__PURE__ */ new Set();
1362
+ const allListeners = /* @__PURE__ */ new Set();
1363
+ const listeners = /* @__PURE__ */ new Set();
1364
+ const changedKeys = /* @__PURE__ */ new Set();
1365
+ let orderChanged = false;
1366
+ const hasNext = (key) => staged.has(key) ? staged.get(key).present : values.has(key);
1367
+ const getNext = (key) => {
1368
+ const entry = staged.get(key);
1369
+ return entry ? entry.present ? entry.value : void 0 : values.get(key);
1370
+ };
1371
+ const owner = createNode(scheduler, spec, {
1372
+ evaluate: (sources, build, active) => {
1373
+ staged = /* @__PURE__ */ new Map();
1374
+ nextIds = ids;
1375
+ change = void 0;
1376
+ changedKeys.clear();
1377
+ let explicitOrder;
1378
+ let cleared = false;
1379
+ const nextHas = (key) => staged.has(key) ? staged.get(key).present : !cleared && values.has(key);
1380
+ const nextGet = (key) => {
1381
+ const entry = staged.get(key);
1382
+ return entry ? entry.present ? entry.value : void 0 : cleared ? void 0 : values.get(key);
1383
+ };
1384
+ const deriveIds = () => {
1385
+ const result = cleared ? [] : ids.filter(nextHas);
1386
+ for (const [key, entry] of staged) if (entry.present && (cleared || !values.has(key))) result.push(key);
1387
+ return result;
1388
+ };
1389
+ const read = (next) => ({
1390
+ get: (key) => {
1391
+ assertScope(active);
1392
+ return next ? nextGet(key) : values.get(key);
1393
+ },
1394
+ has: (key) => {
1395
+ assertScope(active);
1396
+ return next ? nextHas(key) : values.has(key);
1397
+ },
1398
+ ids: () => {
1399
+ assertScope(active);
1400
+ return next ? Object.freeze(explicitOrder ? explicitOrder.slice() : deriveIds()) : ids;
1401
+ }
1402
+ });
1403
+ const writer = {
1404
+ set: (key, value) => {
1405
+ assertScope(active);
1406
+ if (typeof key !== "string") throw new TypeError("Projection keys must be strings.");
1407
+ staged.set(key, {
1408
+ present: true,
1409
+ value
1410
+ });
1411
+ },
1412
+ remove: (key) => {
1413
+ assertScope(active);
1414
+ staged.set(key, { present: false });
1415
+ },
1416
+ order: (order) => {
1417
+ assertScope(active);
1418
+ explicitOrder = order.slice();
1419
+ },
1420
+ replace: (entries) => {
1421
+ assertScope(active);
1422
+ staged.clear();
1423
+ cleared = true;
1424
+ const order = [];
1425
+ for (const [key, value] of entries) {
1426
+ if (staged.has(key)) throw new TypeError("Duplicate projection key.");
1427
+ writer.set(key, value);
1428
+ order.push(key);
1429
+ }
1430
+ explicitOrder = order;
1431
+ }
1432
+ };
1433
+ const input = {
1434
+ sources,
1435
+ previous: read(false),
1436
+ next: read(true),
1437
+ writer
1438
+ };
1439
+ if (build || !instance) {
1440
+ profile.materialized.rebuilt();
1441
+ instance = void 0;
1442
+ cleared = true;
1443
+ const built = spec.build(input);
1444
+ assertSynchronous(built);
1445
+ instance = built;
1446
+ } else {
1447
+ profile.materialized.updated();
1448
+ const result = instance.update(input);
1449
+ assertSynchronous(result);
1450
+ if (result?.kind === "rebuild") {
1451
+ staged.clear();
1452
+ cleared = true;
1453
+ explicitOrder = void 0;
1454
+ instance = void 0;
1455
+ const built = spec.build(input);
1456
+ assertSynchronous(built);
1457
+ instance = built;
1458
+ build = true;
1459
+ }
1460
+ }
1461
+ if (cleared) {
1462
+ for (const key of values.keys()) if (!staged.has(key)) staged.set(key, { present: false });
1463
+ }
1464
+ const added = /* @__PURE__ */ new Set();
1465
+ const removed = /* @__PURE__ */ new Set();
1466
+ const updated = /* @__PURE__ */ new Set();
1467
+ profile.projection("touchedKeys", staged.size);
1468
+ for (const [key, entry] of staged) {
1469
+ const existed = values.has(key);
1470
+ if (entry.present) if (!existed) added.add(key);
1471
+ else if (!(spec.isEqual ?? Object.is)(values.get(key), entry.value)) updated.add(key);
1472
+ else staged.delete(key);
1473
+ else if (existed) removed.add(key);
1474
+ else staged.delete(key);
1475
+ }
1476
+ if (explicitOrder || added.size || removed.size) {
1477
+ const order = explicitOrder ?? [...ids.filter((key) => !removed.has(key)), ...added];
1478
+ if (new Set(order).size !== order.length || order.length !== values.size + added.size - removed.size || order.some((key) => !hasNext(key))) throw new TypeError("Projection order must contain every key exactly once.");
1479
+ nextIds = ids.length === order.length && ids.every((key, i) => key === order[i]) ? ids : Object.freeze(order.slice());
1480
+ }
1481
+ orderChanged = nextIds !== ids;
1482
+ if (added.size || removed.size || updated.size || orderChanged) {
1483
+ let commonOrderChanged = false;
1484
+ if (orderChanged) {
1485
+ const before = ids.filter((key) => !removed.has(key));
1486
+ const after = nextIds.filter((key) => !added.has(key));
1487
+ commonOrderChanged = before.some((key, i) => after[i] !== key);
1488
+ }
1489
+ change = Object.freeze({
1490
+ kind: "incremental",
1491
+ added: readonlySet(added),
1492
+ removed: readonlySet(removed),
1493
+ updated: readonlySet(updated),
1494
+ orderChanged: commonOrderChanged
1495
+ });
1496
+ [
1497
+ ...added,
1498
+ ...removed,
1499
+ ...updated
1500
+ ].forEach((key) => changedKeys.add(key));
1501
+ profile.projection("changedKeys", changedKeys.size);
1502
+ }
1503
+ reset = build;
1504
+ return change !== void 0;
1505
+ },
1506
+ context: (active) => {
1507
+ const input = {
1508
+ get: (key) => {
1509
+ assertScope(active);
1510
+ return getNext(key);
1511
+ },
1512
+ has: (key) => {
1513
+ assertScope(active);
1514
+ return hasNext(key);
1515
+ },
1516
+ ids: () => {
1517
+ assertScope(active);
1518
+ return nextIds;
1519
+ },
1520
+ change,
1521
+ revision: revision + (change ? 1 : 0),
1522
+ reset
1523
+ };
1524
+ return Object.freeze(input);
1525
+ },
1526
+ revision: () => revision,
1527
+ reset: () => reset,
1528
+ publish: () => {
1529
+ for (const [key, entry] of staged) if (entry.present) values.set(key, entry.value);
1530
+ else values.delete(key);
1531
+ if (change) {
1532
+ if (initialized) revision++;
1533
+ if (orderChanged && initialized) idsRevision++;
1534
+ all = void 0;
1535
+ changedKeys.forEach((key) => {
1536
+ if (items.has(key)) itemVersions.set(key, (itemVersions.get(key) ?? 0) + (initialized ? 1 : 0));
1537
+ });
1538
+ }
1539
+ ids = nextIds;
1540
+ initialized = true;
1541
+ },
1542
+ emit: (call) => {
1543
+ profile.materialized.notification();
1544
+ const fault = owner.node.fault !== void 0;
1545
+ const resetEvent = Object.freeze({ kind: "reset" });
1546
+ Array.from(listeners).forEach((listener) => call(() => listener(change ?? resetEvent)));
1547
+ if (orderChanged || !change || fault || owner.node.statusChanged) Array.from(idsListeners).forEach((listener) => call(listener));
1548
+ Array.from(allListeners).forEach((listener) => call(listener));
1549
+ const keys = !change || fault || owner.node.statusChanged ? itemListeners.keys() : changedKeys;
1550
+ for (const key of keys) Array.from(itemListeners.get(key) ?? []).forEach((listener) => call(listener));
1551
+ },
1552
+ clear: () => {
1553
+ staged.clear();
1554
+ nextIds = ids;
1555
+ change = void 0;
1556
+ reset = false;
1557
+ changedKeys.clear();
1558
+ orderChanged = false;
1559
+ },
1560
+ release: () => {
1561
+ values.clear();
1562
+ staged.clear();
1563
+ items.clear();
1564
+ itemVersions.clear();
1565
+ itemListeners.clear();
1566
+ idsListeners.clear();
1567
+ allListeners.clear();
1568
+ listeners.clear();
1569
+ ids = nextIds = Object.freeze([]);
1570
+ all = void 0;
1571
+ instance = void 0;
1572
+ }
1573
+ });
1574
+ const handle = {
1575
+ ids: {
1576
+ current: () => {
1577
+ owner.check();
1578
+ return ids;
1579
+ },
1580
+ revision: () => {
1581
+ owner.check();
1582
+ return idsRevision;
1583
+ },
1584
+ subscribe: (listener) => {
1585
+ owner.check();
1586
+ idsListeners.add(listener);
1587
+ return () => {
1588
+ idsListeners.delete(listener);
1589
+ };
1590
+ }
1591
+ },
1592
+ all: {
1593
+ current: () => {
1594
+ owner.check();
1595
+ if (!all) {
1596
+ profile.collectionView.arrayCopied();
1597
+ all = Object.freeze(ids.map((key) => values.get(key)));
1598
+ }
1599
+ return all;
1600
+ },
1601
+ revision: () => {
1602
+ owner.check();
1603
+ return revision;
1604
+ },
1605
+ subscribe: (listener) => {
1606
+ owner.check();
1607
+ allListeners.add(listener);
1608
+ return () => {
1609
+ allListeners.delete(listener);
1610
+ };
1611
+ }
1612
+ },
1613
+ item: (key) => {
1614
+ owner.check();
1615
+ const old = items.get(key);
1616
+ if (old) return old;
1617
+ itemVersions.set(key, 0);
1618
+ const readable = Object.freeze({
1619
+ current: () => {
1620
+ owner.check();
1621
+ return values.get(key);
1622
+ },
1623
+ revision: () => {
1624
+ owner.check();
1625
+ return itemVersions.get(key) ?? 0;
1626
+ },
1627
+ subscribe: (listener) => {
1628
+ owner.check();
1629
+ const set = itemListeners.get(key) ?? /* @__PURE__ */ new Set();
1630
+ set.add(listener);
1631
+ itemListeners.set(key, set);
1632
+ return () => {
1633
+ set.delete(listener);
1634
+ if (!set.size) itemListeners.delete(key);
1635
+ };
1636
+ }
1637
+ });
1638
+ projectionHandles.add(readable);
1639
+ items.set(key, readable);
1640
+ return readable;
1641
+ },
1642
+ revision: () => {
1643
+ owner.check();
1644
+ return revision;
1645
+ },
1646
+ subscribe: (listener) => {
1647
+ owner.check();
1648
+ listeners.add(listener);
1649
+ return () => {
1650
+ listeners.delete(listener);
1651
+ };
1652
+ },
1653
+ rebuild: owner.rebuild,
1654
+ dispose: owner.dispose
1655
+ };
1656
+ projectionHandles.add(handle.ids);
1657
+ projectionHandles.add(handle.all);
1658
+ owner.install(handle);
1659
+ return Object.freeze(handle);
1660
+ };
1661
+ //#endregion
1662
+ //#region core/src/projection/runtime.ts
1663
+ const debug = /* @__PURE__ */ new WeakMap();
1664
+ const projectionDebug = (runtime) => {
1665
+ const read = debug.get(runtime);
1666
+ if (!read) throw new Error("Unknown projection runtime.");
1667
+ return Object.freeze(read());
1668
+ };
1669
+ const createProjectionRuntime = (options) => {
1670
+ const scheduler = createScheduler(options.onError);
1671
+ const sources = createSources(scheduler);
1672
+ const runtime = {
1673
+ document: sources.document,
1674
+ input: sources.input,
1675
+ fromReadable: sources.fromReadable,
1676
+ value: (spec) => createValue(scheduler, spec),
1677
+ collection: (spec) => createCollection(scheduler, spec),
1678
+ map: (source, mapper, options) => {
1679
+ sources.collectionTarget(source);
1680
+ return createCollection(scheduler, {
1681
+ sources: { source },
1682
+ isEqual: options?.isEqual,
1683
+ build: ({ sources, writer }) => {
1684
+ const ids = sources.source.read.ids();
1685
+ profile.collectionView.idsScanned(ids.length);
1686
+ for (const id of ids) {
1687
+ profile.collectionView.mapped();
1688
+ writer.set(id, mapper(id, sources.source.read.get(id)));
1689
+ }
1690
+ writer.order(ids);
1691
+ return { update: ({ sources, writer }) => {
1692
+ const input = sources.source;
1693
+ const keys = /* @__PURE__ */ new Set();
1694
+ let structural = false;
1695
+ for (const commit of input.commits) {
1696
+ const impact = commit.impact.collection(input.target);
1697
+ if (impact.kind === "reset") return { kind: "rebuild" };
1698
+ impact.added.forEach((key) => keys.add(key));
1699
+ impact.removed.forEach((key) => keys.add(key));
1700
+ impact.updated.forEach((key) => keys.add(key));
1701
+ structural ||= Boolean(impact.added.size || impact.removed.size || impact.orderChanged);
1702
+ }
1703
+ for (const key of keys) {
1704
+ const entry = input.read.get(key);
1705
+ if (!entry) writer.remove(key);
1706
+ else {
1707
+ profile.collectionView.mapped();
1708
+ writer.set(key, mapper(key, entry));
1709
+ }
1710
+ }
1711
+ if (structural) {
1712
+ const ids = input.read.ids();
1713
+ profile.collectionView.idsScanned(ids.length);
1714
+ writer.order(ids);
1715
+ }
1716
+ } };
1717
+ }
1718
+ });
1719
+ },
1720
+ batch: scheduler.batch,
1721
+ dispose: () => {
1722
+ try {
1723
+ scheduler.dispose();
1724
+ } finally {
1725
+ if (!scheduler.active) sources.dispose();
1726
+ }
1727
+ }
1728
+ };
1729
+ debug.set(runtime, scheduler.debug);
1730
+ return Object.freeze(runtime);
1731
+ };
1732
+ //#endregion
1733
+ export { dict as A, tree as B, debugKey as C, resolveAddress as D, read as E, optional as F, record as I, schema as L, list as M, map as N, resolveLocated as O, object as P, single as R, contains as S, overlaps as T, variant as V, address as _, createNotification as a, impact_target_exports as b, shareNotification as c, accessOf as d, bindRuntimeAccess as f, documentReader as g, DocumentReentrancyError as h, ProjectionError as i, field as j, set as k, subscribeRoot as l, DocumentDisposedError as m, projectionDebug as n, disposeNotification as o, readWith as p, ProjectionDisposedError as r, notify as s, createProjectionRuntime as t, subscribeTargets as u, belongs as v, locate as w, same as x, id as y, table as z };
1734
+
1735
+ //# sourceMappingURL=runtime-BJRXF0gq.js.map