@noy-db/hub 0.7.0-pre.11 → 0.7.0-pre.13

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 (98) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/dist/as/index.js +3 -2
  3. package/dist/as/index.js.map +1 -1
  4. package/dist/{backup-VASRVLDZ.js → backup-R6A4VZRX.js} +4 -4
  5. package/dist/cargo/index.js +2 -2
  6. package/dist/chunk-66TQOPFM.js +37 -0
  7. package/dist/chunk-66TQOPFM.js.map +1 -0
  8. package/dist/{chunk-OEA5NVSU.js → chunk-AJQY44CE.js} +86 -6
  9. package/dist/chunk-AJQY44CE.js.map +1 -0
  10. package/dist/{chunk-S5AMPTNE.js → chunk-BMELYFHU.js} +2 -2
  11. package/dist/{chunk-T6PSWLAR.js → chunk-BUE2D7PX.js} +25 -2
  12. package/dist/chunk-BUE2D7PX.js.map +1 -0
  13. package/dist/chunk-BWXGSSFX.js +1589 -0
  14. package/dist/chunk-BWXGSSFX.js.map +1 -0
  15. package/dist/{chunk-HN4FNA4X.js → chunk-COTPDJR5.js} +8 -8
  16. package/dist/{chunk-E3EBMC4G.js → chunk-E2MYJGSG.js} +2 -2
  17. package/dist/{chunk-JJR2JIN4.js → chunk-FFBYRWDJ.js} +2 -2
  18. package/dist/{chunk-WQF3QABE.js → chunk-IHFXR2VQ.js} +9 -79
  19. package/dist/chunk-IHFXR2VQ.js.map +1 -0
  20. package/dist/chunk-MGOXJIBV.js +176 -0
  21. package/dist/chunk-MGOXJIBV.js.map +1 -0
  22. package/dist/chunk-PDD75NUZ.js +87 -0
  23. package/dist/chunk-PDD75NUZ.js.map +1 -0
  24. package/dist/chunk-RTBJ5IOO.js +87 -0
  25. package/dist/chunk-RTBJ5IOO.js.map +1 -0
  26. package/dist/chunk-RXLYKVTF.js +17 -0
  27. package/dist/chunk-RXLYKVTF.js.map +1 -0
  28. package/dist/{chunk-ESVREVWN.js → chunk-SXCYYMVS.js} +2 -2
  29. package/dist/chunk-TFMM5DBB.js +20 -0
  30. package/dist/chunk-TFMM5DBB.js.map +1 -0
  31. package/dist/chunk-TPHAGLUH.js +30 -0
  32. package/dist/chunk-TPHAGLUH.js.map +1 -0
  33. package/dist/{chunk-THNJ3IKU.js → chunk-ULUMAZ5S.js} +2 -2
  34. package/dist/{chunk-NO272T7Q.js → chunk-V4PXLYWM.js} +2 -31
  35. package/dist/chunk-V4PXLYWM.js.map +1 -0
  36. package/dist/{chunk-A5WZEPXJ.js → chunk-VGICZPVE.js} +5 -3
  37. package/dist/{chunk-A5WZEPXJ.js.map → chunk-VGICZPVE.js.map} +1 -1
  38. package/dist/{chunk-KHKKD62N.js → chunk-VYYM3MEN.js} +2 -16
  39. package/dist/chunk-VYYM3MEN.js.map +1 -0
  40. package/dist/{chunk-SWVNZQVR.js → chunk-YPXNAP72.js} +2 -169
  41. package/dist/chunk-YPXNAP72.js.map +1 -0
  42. package/dist/{chunk-I6DGKPTY.js → chunk-ZVCC36XQ.js} +101 -1273
  43. package/dist/chunk-ZVCC36XQ.js.map +1 -0
  44. package/dist/{collection-facade-MGGHQ3HU.js → collection-facade-4ACKIDDY.js} +4 -3
  45. package/dist/derivations/index.js +21 -6
  46. package/dist/dispatch-MSTR5VBI.js +255 -0
  47. package/dist/dispatch-MSTR5VBI.js.map +1 -0
  48. package/dist/{dispatch-44J4TL72.js → dispatch-PDP5TA73.js} +5 -5
  49. package/dist/{executor-KSPGNVDO.js → executor-YDDC5XGY.js} +4 -3
  50. package/dist/index.d.ts +2 -2
  51. package/dist/index.js +39 -35
  52. package/dist/index.js.map +1 -1
  53. package/dist/introspection/index.js +3 -2
  54. package/dist/kernel/collection.d.ts +11 -6
  55. package/dist/kernel/match-pairs.d.ts +30 -0
  56. package/dist/lazy/index.js +3 -2
  57. package/dist/materialized-views/index.js +4 -3
  58. package/dist/{noydb-QJFZAH34.js → noydb-2C6QQJ5S.js} +17 -12
  59. package/dist/pod/index.js +17 -12
  60. package/dist/registry-D2YXKRYC.js +33 -0
  61. package/dist/search/index.js +1 -1
  62. package/dist/{stale-KSPG6LFX.js → stale-2CHKZTMK.js} +2 -2
  63. package/dist/{walk-G3CZIL4L.js → walk-P3E6QSNC.js} +4 -3
  64. package/dist/with-formula/derivations/dispatch.d.ts +16 -1
  65. package/dist/with-formula/derivations/registry.d.ts +20 -6
  66. package/dist/with-formula/derivations/trigger-match.d.ts +52 -0
  67. package/dist/with-formula/derivations/types.d.ts +23 -0
  68. package/dist/with-shape/introspection/behaviors.d.ts +7 -0
  69. package/dist/with-shape/introspection/describe.d.ts +30 -0
  70. package/package.json +3 -3
  71. package/dist/chunk-I6DGKPTY.js.map +0 -1
  72. package/dist/chunk-KHKKD62N.js.map +0 -1
  73. package/dist/chunk-NO272T7Q.js.map +0 -1
  74. package/dist/chunk-OEA5NVSU.js.map +0 -1
  75. package/dist/chunk-SWVNZQVR.js.map +0 -1
  76. package/dist/chunk-T6PSWLAR.js.map +0 -1
  77. package/dist/chunk-UB5CRTFF.js +0 -344
  78. package/dist/chunk-UB5CRTFF.js.map +0 -1
  79. package/dist/chunk-WQF3QABE.js.map +0 -1
  80. package/dist/chunk-YPMW26SL.js +0 -81
  81. package/dist/chunk-YPMW26SL.js.map +0 -1
  82. package/dist/dispatch-IM52HDXT.js +0 -194
  83. package/dist/dispatch-IM52HDXT.js.map +0 -1
  84. package/dist/registry-FZXPQRAB.js +0 -18
  85. /package/dist/{backup-VASRVLDZ.js.map → backup-R6A4VZRX.js.map} +0 -0
  86. /package/dist/{chunk-S5AMPTNE.js.map → chunk-BMELYFHU.js.map} +0 -0
  87. /package/dist/{chunk-HN4FNA4X.js.map → chunk-COTPDJR5.js.map} +0 -0
  88. /package/dist/{chunk-E3EBMC4G.js.map → chunk-E2MYJGSG.js.map} +0 -0
  89. /package/dist/{chunk-JJR2JIN4.js.map → chunk-FFBYRWDJ.js.map} +0 -0
  90. /package/dist/{chunk-ESVREVWN.js.map → chunk-SXCYYMVS.js.map} +0 -0
  91. /package/dist/{chunk-THNJ3IKU.js.map → chunk-ULUMAZ5S.js.map} +0 -0
  92. /package/dist/{collection-facade-MGGHQ3HU.js.map → collection-facade-4ACKIDDY.js.map} +0 -0
  93. /package/dist/{dispatch-44J4TL72.js.map → dispatch-PDP5TA73.js.map} +0 -0
  94. /package/dist/{executor-KSPGNVDO.js.map → executor-YDDC5XGY.js.map} +0 -0
  95. /package/dist/{noydb-QJFZAH34.js.map → noydb-2C6QQJ5S.js.map} +0 -0
  96. /package/dist/{registry-FZXPQRAB.js.map → registry-D2YXKRYC.js.map} +0 -0
  97. /package/dist/{stale-KSPG6LFX.js.map → stale-2CHKZTMK.js.map} +0 -0
  98. /package/dist/{walk-G3CZIL4L.js.map → walk-P3E6QSNC.js.map} +0 -0
@@ -10,8 +10,9 @@ import {
10
10
  similarTo,
11
11
  syncTierSearch,
12
12
  warmIndex
13
- } from "./chunk-WQF3QABE.js";
14
- import "./chunk-HN4FNA4X.js";
13
+ } from "./chunk-IHFXR2VQ.js";
14
+ import "./chunk-RTBJ5IOO.js";
15
+ import "./chunk-COTPDJR5.js";
15
16
  import "./chunk-AURFOK3D.js";
16
17
  import "./chunk-MVMXZYXT.js";
17
18
  import "./chunk-RDZZHYMV.js";
@@ -42,4 +43,4 @@ export {
42
43
  syncTierSearch,
43
44
  warmIndex
44
45
  };
45
- //# sourceMappingURL=collection-facade-MGGHQ3HU.js.map
46
+ //# sourceMappingURL=collection-facade-4ACKIDDY.js.map
@@ -1,14 +1,29 @@
1
- import {
2
- withDerivation,
3
- withRollup
4
- } from "../chunk-T6PSWLAR.js";
5
1
  import {
6
2
  DerivationRegistry
7
- } from "../chunk-OEA5NVSU.js";
3
+ } from "../chunk-AJQY44CE.js";
4
+ import "../chunk-TPHAGLUH.js";
8
5
  import {
9
6
  DerivationExecutor
10
7
  } from "../chunk-TFR7DSOV.js";
11
- import "../chunk-UB5CRTFF.js";
8
+ import {
9
+ withDerivation,
10
+ withRollup
11
+ } from "../chunk-BUE2D7PX.js";
12
+ import "../chunk-BWXGSSFX.js";
13
+ import "../chunk-TFMM5DBB.js";
14
+ import "../chunk-RTBJ5IOO.js";
15
+ import "../chunk-KCUIMITG.js";
16
+ import "../chunk-VYYM3MEN.js";
17
+ import "../chunk-URHRIAV6.js";
18
+ import "../chunk-Y2NBBT6K.js";
19
+ import "../chunk-WWNYSV7S.js";
20
+ import "../chunk-YPXNAP72.js";
21
+ import "../chunk-V4PXLYWM.js";
22
+ import "../chunk-MVMXZYXT.js";
23
+ import "../chunk-RDZZHYMV.js";
24
+ import "../chunk-TRGTKX5E.js";
25
+ import "../chunk-UXVWEX5L.js";
26
+ import "../chunk-IPFE6MVM.js";
12
27
  import "../chunk-CIGAQBJR.js";
13
28
  import "../chunk-4RUFYGWG.js";
14
29
  import "../chunk-BOWNCWZT.js";
@@ -0,0 +1,255 @@
1
+ import {
2
+ sameTuple,
3
+ tupleFromWritten
4
+ } from "./chunk-TPHAGLUH.js";
5
+ import {
6
+ markStale
7
+ } from "./chunk-PDD75NUZ.js";
8
+ import "./chunk-TFMM5DBB.js";
9
+ import {
10
+ putDerivedOutput,
11
+ selfWriteFieldEqual
12
+ } from "./chunk-MGOXJIBV.js";
13
+ import "./chunk-YPXNAP72.js";
14
+ import "./chunk-5D2ALSM5.js";
15
+ import "./chunk-RDZZHYMV.js";
16
+ import "./chunk-TRGTKX5E.js";
17
+ import "./chunk-UXVWEX5L.js";
18
+ import "./chunk-IPFE6MVM.js";
19
+ import "./chunk-CIGAQBJR.js";
20
+ import "./chunk-4RUFYGWG.js";
21
+ import "./chunk-BOWNCWZT.js";
22
+ import "./chunk-YSRUYAVU.js";
23
+ import "./chunk-RMF67KCG.js";
24
+ import "./chunk-LP7BEXCT.js";
25
+ import "./chunk-SL3JAAKN.js";
26
+ import "./chunk-N4CHCXDL.js";
27
+ import {
28
+ DerivationCapExceededError
29
+ } from "./chunk-7O3Y4PPD.js";
30
+ import "./chunk-PZ5AY32C.js";
31
+
32
+ // src/with-formula/derivations/dispatch.ts
33
+ async function dispatchArrayDerivationsOnDelete(ctx, id, eraseRecordShapeToo = false) {
34
+ const { derivationSource, collectionName, adapter, vault, getDEK, storeCiphertext } = ctx;
35
+ const strategies = derivationSource.registry().strategiesForSource(collectionName);
36
+ if (strategies.length === 0) return 0;
37
+ const { loadFanoutSidecar, deleteFanoutSidecar } = await import("./fanout-sidecar-TSFPXY5C.js");
38
+ const txCtx = derivationSource.getActiveTxContext();
39
+ let erased = 0;
40
+ for (const { spec } of strategies) {
41
+ for (const [outputKey, outSpec] of Object.entries(spec.outputs)) {
42
+ if (outSpec.shape === "record") {
43
+ if (eraseRecordShapeToo && spec.source === collectionName && outSpec.collection !== collectionName) {
44
+ if (await derivationSource.getCollection(outSpec.collection)._internalDelete(id, txCtx)) erased += 1;
45
+ }
46
+ continue;
47
+ }
48
+ const sidecar = await loadFanoutSidecar(adapter, vault, spec.source, id, outputKey, getDEK, storeCiphertext);
49
+ if (!sidecar) continue;
50
+ const outputCollection = derivationSource.getCollection(outSpec.collection);
51
+ for (const derivedId of sidecar.keys) {
52
+ if (await outputCollection._internalDelete(derivedId, txCtx)) erased += 1;
53
+ }
54
+ await deleteFanoutSidecar(adapter, vault, spec.source, id, outputKey);
55
+ }
56
+ }
57
+ return erased;
58
+ }
59
+ async function dispatchDerivations(ctx, id, record, version, wave, prior) {
60
+ const { derivationSource, collectionName, via, recomputeRollup } = ctx;
61
+ const incoming = via ? via.canonicalizeStored(record) : record;
62
+ if (incoming && typeof incoming === "object" && "_derivedFrom" in incoming) return;
63
+ const canonicalPrior = prior != null ? via ? via.canonicalizeStored(prior) : prior : prior;
64
+ const registry = derivationSource.registry();
65
+ const strategies = registry.strategiesForSource(collectionName);
66
+ if (strategies.length === 0) return;
67
+ let executorClass = null;
68
+ for (const { spec, strategyHash, triggers } of strategies) {
69
+ const mode = typeof spec.lifecycle === "string" ? spec.lifecycle : spec.lifecycle.mode;
70
+ if (spec.rollup) {
71
+ if (mode !== "eager") continue;
72
+ const asParentId = (v) => typeof v === "string" || typeof v === "number" ? String(v) : null;
73
+ let parentId;
74
+ let oldParentId = null;
75
+ if (collectionName === spec.rollup.from) {
76
+ parentId = asParentId(incoming[spec.rollup.key]);
77
+ const priorKey = canonicalPrior != null ? asParentId(canonicalPrior[spec.rollup.key]) : null;
78
+ if (priorKey !== null && priorKey !== parentId) oldParentId = priorKey;
79
+ } else {
80
+ parentId = id;
81
+ }
82
+ if (parentId !== null) await recomputeRollup(spec, parentId, { collection: collectionName, id }, wave);
83
+ if (oldParentId !== null) await recomputeRollup(spec, oldParentId, { collection: collectionName, id }, wave);
84
+ continue;
85
+ }
86
+ const isSource = spec.source === collectionName;
87
+ const isSibling = !isSource && (spec.sources?.includes(collectionName) ?? false);
88
+ const triggerEntries = !isSource && !isSibling ? triggers.filter((t) => t.collection === collectionName) : [];
89
+ const runs = [];
90
+ if (isSource) {
91
+ runs.push({ input: { ...incoming, id }, base: incoming, runId: id, version });
92
+ } else if (isSibling) {
93
+ const p = await derivationSource.getCollection(spec.source).get(id);
94
+ if (p !== null && p !== void 0) {
95
+ const raw = await derivationSource.getCollection(spec.source)._getStoredRecord(id);
96
+ runs.push({ input: { ...p, id }, base: raw ?? p, runId: id, version: 0 });
97
+ }
98
+ } else if (triggerEntries.length > 0) {
99
+ const srcColl = derivationSource.getCollection(spec.source);
100
+ const matched = /* @__PURE__ */ new Set();
101
+ for (const trigger of triggerEntries) {
102
+ const tuples = [tupleFromWritten(trigger.match, id, incoming)];
103
+ if (canonicalPrior != null && trigger.match.some((p) => p.from !== "id")) {
104
+ const old = tupleFromWritten(trigger.match, id, canonicalPrior);
105
+ if (!sameTuple(old, tuples[0])) tuples.push(old);
106
+ }
107
+ const ids = /* @__PURE__ */ new Set();
108
+ for (const tuple of tuples) {
109
+ if (tuple === null) continue;
110
+ for (const sid of await srcColl._findMatchingCompositeIds(tuple)) ids.add(sid);
111
+ }
112
+ if (trigger.maxFanout !== void 0 && ids.size > trigger.maxFanout) {
113
+ throw new DerivationCapExceededError(
114
+ `triggerBy ${collectionName}\u2192${spec.source} [${trigger.match.map((p) => p.to).join(",")}]`,
115
+ ids.size,
116
+ trigger.maxFanout
117
+ );
118
+ }
119
+ for (const sid of ids) matched.add(sid);
120
+ }
121
+ for (const sid of matched) {
122
+ const raw = await srcColl._getStoredRecord(sid);
123
+ if (raw === null) continue;
124
+ runs.push({ input: { ...raw, id: sid }, base: raw, runId: sid, version: 0 });
125
+ }
126
+ }
127
+ if (runs.length === 0) continue;
128
+ if (mode !== "eager") {
129
+ for (const run of runs) await markStale(registry, spec, run.runId);
130
+ continue;
131
+ }
132
+ if (executorClass === null) {
133
+ ;
134
+ ({ DerivationExecutor: executorClass } = await import("./executor-TOLPBHOC.js"));
135
+ }
136
+ for (const run of runs) await runOne(ctx, spec, strategyHash, executorClass, run);
137
+ }
138
+ }
139
+ async function runOne(ctx, spec, strategyHash, executorClass, run) {
140
+ const { derivationSource, adapter, vault, getDEK, storeCiphertext, dispatchCtx, trackPut } = ctx;
141
+ const execCtx = { vault: derivationSource.getReadOnlyFacade() };
142
+ const outCtx = dispatchCtx({ collection: spec.source, id: run.runId });
143
+ const result = await executorClass.run(spec, run.input, run.version, strategyHash, execCtx);
144
+ for (const key of Object.keys(spec.outputs)) {
145
+ const out = result.outputs[key];
146
+ if (!out) continue;
147
+ if (out.kind === "failed") {
148
+ const err = out.error;
149
+ if (spec.strict) throw err;
150
+ console.warn(`[derivation] output "${key}" for source "${spec.source}" id="${run.runId}" failed:`, err);
151
+ continue;
152
+ }
153
+ const outSpec = spec.outputs[key];
154
+ if (!outSpec) continue;
155
+ const outputCollection = derivationSource.getCollection(outSpec.collection);
156
+ const txCtx = derivationSource.getActiveTxContext();
157
+ if (out.kind === "array") {
158
+ const { loadFanoutSidecar, saveFanoutSidecar } = await import("./fanout-sidecar-TSFPXY5C.js");
159
+ const prior = await loadFanoutSidecar(adapter, vault, spec.source, run.runId, key, getDEK, storeCiphertext);
160
+ const prevKeys = new Set(prior?.keys ?? []);
161
+ const newKeysList = out.entries.map((e) => e.key);
162
+ const newKeysSet = new Set(newKeysList);
163
+ for (const k of prevKeys) {
164
+ if (newKeysSet.has(k)) continue;
165
+ await outputCollection._internalDelete(k, txCtx);
166
+ }
167
+ for (const entry of out.entries) {
168
+ if (txCtx !== null) {
169
+ trackPut(txCtx, outSpec.collection, entry.key, await adapter.get(vault, outSpec.collection, entry.key));
170
+ }
171
+ await putDerivedOutput(outputCollection, entry.key, entry.value, outCtx, { source: "derived" });
172
+ }
173
+ await saveFanoutSidecar(adapter, vault, {
174
+ source: spec.source,
175
+ sourceId: run.runId,
176
+ outputKey: key,
177
+ outputCollection: outSpec.collection,
178
+ keys: newKeysList
179
+ }, getDEK, storeCiphertext);
180
+ continue;
181
+ }
182
+ if (out.skipped === true) {
183
+ await outputCollection._internalDelete(run.runId, txCtx);
184
+ continue;
185
+ }
186
+ if (outSpec.shape === "record" && outSpec.denorm !== void 0 && outSpec.collection === spec.source) {
187
+ const value = out.value;
188
+ const patched = { ...run.base };
189
+ let changed = false;
190
+ for (const f of outSpec.denorm) {
191
+ if (!selfWriteFieldEqual(run.base[f], value[f])) {
192
+ patched[f] = value[f];
193
+ changed = true;
194
+ }
195
+ }
196
+ if (!changed) continue;
197
+ if (txCtx !== null) {
198
+ trackPut(txCtx, outSpec.collection, run.runId, await adapter.get(vault, outSpec.collection, run.runId));
199
+ }
200
+ await putDerivedOutput(outputCollection, run.runId, patched, outCtx, { source: "derived" });
201
+ continue;
202
+ }
203
+ if (txCtx !== null) {
204
+ trackPut(txCtx, outSpec.collection, run.runId, await adapter.get(vault, outSpec.collection, run.runId));
205
+ }
206
+ await putDerivedOutput(outputCollection, run.runId, out.value, outCtx, { source: "derived" });
207
+ }
208
+ }
209
+ async function dispatchTriggerDerivationsOnDelete(ctx, id, deleted) {
210
+ const { derivationSource, collectionName } = ctx;
211
+ const registry = derivationSource.registry();
212
+ const strategies = registry.strategiesForSource(collectionName);
213
+ if (strategies.length === 0) return;
214
+ let executorClass = null;
215
+ for (const { spec, strategyHash, triggers } of strategies) {
216
+ if (spec.rollup) continue;
217
+ if (spec.source === collectionName) continue;
218
+ if (spec.sources?.includes(collectionName)) continue;
219
+ const entries = triggers.filter((t) => t.collection === collectionName);
220
+ if (entries.length === 0) continue;
221
+ const mode = typeof spec.lifecycle === "string" ? spec.lifecycle : spec.lifecycle.mode;
222
+ const srcColl = derivationSource.getCollection(spec.source);
223
+ const matched = /* @__PURE__ */ new Set();
224
+ for (const trigger of entries) {
225
+ const tuple = tupleFromWritten(trigger.match, id, deleted);
226
+ if (tuple === null) continue;
227
+ const ids = await srcColl._findMatchingCompositeIds(tuple);
228
+ if (trigger.maxFanout !== void 0 && ids.length > trigger.maxFanout) {
229
+ throw new DerivationCapExceededError(
230
+ `triggerBy ${collectionName}\u2192${spec.source} [${trigger.match.map((p) => p.to).join(",")}] (delete)`,
231
+ ids.length,
232
+ trigger.maxFanout
233
+ );
234
+ }
235
+ for (const sid of ids) matched.add(sid);
236
+ }
237
+ if (matched.size === 0) continue;
238
+ if (mode !== "eager") {
239
+ for (const sid of matched) await markStale(registry, spec, sid);
240
+ continue;
241
+ }
242
+ if (executorClass === null) ({ DerivationExecutor: executorClass } = await import("./executor-TOLPBHOC.js"));
243
+ for (const sid of matched) {
244
+ const raw = await srcColl._getStoredRecord(sid);
245
+ if (raw === null) continue;
246
+ await runOne(ctx, spec, strategyHash, executorClass, { input: { ...raw, id: sid }, base: raw, runId: sid, version: 0 });
247
+ }
248
+ }
249
+ }
250
+ export {
251
+ dispatchArrayDerivationsOnDelete,
252
+ dispatchDerivations,
253
+ dispatchTriggerDerivationsOnDelete
254
+ };
255
+ //# sourceMappingURL=dispatch-MSTR5VBI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-formula/derivations/dispatch.ts"],"sourcesContent":["/**\n * Derivation dispatch, lifted out of the kernel spine (#842 part b).\n *\n * `Collection` carried ~380 lines of dispatch logic that belongs to the\n * derivation service, not to the always-on kernel. These are free functions\n * taking an explicit context so the spine keeps only a thin delegator.\n *\n * ## How the spine reaches this module\n *\n * By dynamic `import()`, never a static one. `check-architecture.mjs`'s\n * `port-layering` check forbids the spine from statically importing a\n * `with-*` service; `collection.ts` is grandfathered for ten\n * `with-formula/*` specifiers, but that list is frozen per file and a new\n * one is a violation. A dynamic import is the sanctioned S4 gate recipe, and\n * it keeps this chunk out of the floor bundle for consumers who never fire a\n * derivation.\n *\n * The `Collection` type reference below points back at the spine. That is\n * inward (service → kernel) and so allowed, and it is TYPE-ONLY — erased at\n * build, so no runtime cycle exists.\n *\n * @internal\n */\n\nimport type { NoydbStore } from '../../kernel/types.js'\nimport type { TxContext } from '../../with-commit/tx/transaction.js'\nimport type { DerivationRegistry } from './registry.js'\nimport type { ReadOnlyVaultFacade } from '../../with-audit/guards/types.js'\nimport type { Collection } from '../../kernel/collection.js'\nimport type { EnclaveKey } from '../../kernel/enclave/index.js'\nimport type { EncryptedEnvelope } from '../../kernel/types.js'\nimport type { ledgerAuditHook, WaveContext } from '../../kernel/via/dispatch.js'\nimport { putDerivedOutput, selfWriteFieldEqual } from '../../kernel/via/dispatch.js'\nimport { DerivationCapExceededError } from '../../kernel/errors.js'\nimport { tupleFromWritten, sameTuple } from './trigger-match.js'\nimport { markStale } from './stale.js'\nimport type { DerivationExecutor } from './executor.js'\n\n/** The per-write dispatch context threaded into `putDerivedOutput`. */\ninterface DispatchCtx {\n emit: (e: string, p: unknown) => void\n source: { readonly collection: string; readonly id: string }\n audit: ReturnType<typeof ledgerAuditHook>\n}\n\n/**\n * What the dispatchers need from the collection that owns them. Passing this\n * explicitly is what lets the logic live outside the class.\n */\nexport interface DerivationDeleteCtx {\n readonly derivationSource: {\n registry(): DerivationRegistry\n getCollection(name: string): Collection<Record<string, unknown>>\n getActiveTxContext(): TxContext | null\n getReadOnlyFacade(): ReadOnlyVaultFacade\n }\n /** The collection the delete happened in. */\n readonly collectionName: string\n readonly adapter: NoydbStore\n readonly vault: string\n readonly getDEK: (collectionName: string) => Promise<EnclaveKey>\n readonly storeCiphertext: boolean\n}\n\n/**\n * Erase the derived rows a deleted source record fanned out to, and drop the\n * fan-out sidecars that recorded them.\n *\n * @param eraseRecordShapeToo also erase same-id `shape: 'record'` outputs.\n * Restricted to a source-triggered strategy writing into a DIFFERENT\n * collection — the self-denorm case would re-delete the record just\n * tombstoned, and triggerBy/sibling strategies derive under a different id.\n * @returns rows ACTUALLY deleted, not edges visited (#622).\n */\nexport async function dispatchArrayDerivationsOnDelete(\n ctx: DerivationDeleteCtx,\n id: string,\n eraseRecordShapeToo = false,\n): Promise<number> {\n const { derivationSource, collectionName, adapter, vault, getDEK, storeCiphertext } = ctx\n\n const strategies = derivationSource.registry().strategiesForSource(collectionName)\n if (strategies.length === 0) return 0\n\n const { loadFanoutSidecar, deleteFanoutSidecar } = await import('./fanout-sidecar.js')\n const txCtx = derivationSource.getActiveTxContext()\n let erased = 0\n\n for (const { spec } of strategies) {\n for (const [outputKey, outSpec] of Object.entries(spec.outputs)) {\n if (outSpec.shape === 'record') {\n if (eraseRecordShapeToo && spec.source === collectionName && outSpec.collection !== collectionName) {\n if (await derivationSource.getCollection(outSpec.collection)._internalDelete(id, txCtx)) erased += 1\n }\n continue\n }\n\n const sidecar = await loadFanoutSidecar(adapter, vault, spec.source, id, outputKey, getDEK, storeCiphertext)\n if (!sidecar) continue\n\n const outputCollection = derivationSource.getCollection(outSpec.collection)\n for (const derivedId of sidecar.keys) {\n if (await outputCollection._internalDelete(derivedId, txCtx)) erased += 1\n }\n await deleteFanoutSidecar(adapter, vault, spec.source, id, outputKey)\n }\n }\n\n return erased\n}\n\n/** Adds what the on-write derivation dispatch needs beyond the delete path. */\nexport interface DerivationDispatchCtx extends DerivationDeleteCtx {\n /** Via pipeline, for decoding the stored form back to canonical money shape. */\n readonly via: { canonicalizeStored(r: Record<string, unknown>): Record<string, unknown> } | undefined\n /** Recompute a rollup aggregate onto a parent. Stays on the spine — it walks collections. */\n readonly recomputeRollup: (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n spec: any,\n parentId: string,\n source: { readonly collection: string; readonly id: string },\n wave?: WaveContext,\n ) => Promise<unknown>\n /** Builds the per-write dispatch context threaded into `putDerivedOutput`. */\n readonly dispatchCtx: (source: { readonly collection: string; readonly id: string }) => DispatchCtx\n /** Registers a write on the active transaction for rollback. */\n readonly trackPut: (txCtx: TxContext, collectionName: string, id: string, priorEnvelope: EncryptedEnvelope | null) => void\n}\n\n/**\n * Fire registered derivation strategies for this source collection.\n *\n * Eager mode runs `derive` inline and writes each output; lazy mode records a\n * stale mark for cold-session recompute. Rollups are handled here rather than\n * by the executor — a write to the child recomputes the parent aggregate, and\n * a write to the parent recomputes its own.\n */\nexport async function dispatchDerivations(\n ctx: DerivationDispatchCtx,\n id: string,\n record: Record<string, unknown>,\n version: number,\n wave?: WaveContext,\n /** The pre-write record at `id` in THIS collection (undefined = not\n * captured — no field-match trigger, or a sync-applied wave; null =\n * captured and absent, i.e. a create). Only a `Record` re-fires the OLD\n * matched set alongside the new one (spec §7). */\n prior?: Record<string, unknown> | null,\n): Promise<void> {\n const { derivationSource, collectionName, via, recomputeRollup } = ctx\n\n // `record` is the stored form here (post-quantize) — decode so\n // derive(source, ctx) sees the canonical money shape.\n const incoming = (via ? via.canonicalizeStored(record) : record)\n if (incoming && typeof incoming === 'object' && '_derivedFrom' in incoming) return\n // `prior` is the raw stored pre-write record — canonicalize it the same\n // way as `incoming` before it feeds `tupleFromWritten` below, or a\n // via-shaped match field (e.g. a money field) compares canonical against\n // raw and never matches the old tuple (Min 5).\n const canonicalPrior = prior != null ? (via ? via.canonicalizeStored(prior) : prior) : prior\n const registry = derivationSource.registry()\n const strategies = registry.strategiesForSource(collectionName)\n if (strategies.length === 0) return\n // Dynamic-import the executor only on the first eager-mode\n // dispatch. Lazy-mode dispatches use `markStale` (a pure helper)\n // which doesn't reach into the executor at all. Keeps the\n // derivation executor chunk out of the floor bundle for any\n // consumer that doesn't fire an eager derivation.\n let executorClass: typeof DerivationExecutor | null = null\n for (const { spec, strategyHash, triggers } of strategies) {\n const mode = typeof spec.lifecycle === 'string' ? spec.lifecycle : spec.lifecycle.mode\n\n // Rollup: a write to the child `from` recomputes the\n // parent at id child[key]; a write to the parent (source = into)\n // recomputes its own aggregate. Handled here (the executor is not run).\n if (spec.rollup) {\n if (mode !== 'eager') continue\n const asParentId = (v: unknown): string | null =>\n (typeof v === 'string' || typeof v === 'number') ? String(v) : null\n let parentId: string | null\n // #1257 — a child that RE-PARENTS strands the old parent's aggregate\n // unless the old key is recomputed too. Reads the prior stored record\n // (canonicalized alongside `incoming`, so a via-shaped key compares like\n // for like). `undefined` prior — a sync-applied wave write or a tiers\n // restore, which do not thread it — degrades to new-parent-only, the\n // pre-#1257 behaviour, rather than guessing.\n let oldParentId: string | null = null\n if (collectionName === spec.rollup.from) {\n parentId = asParentId(incoming[spec.rollup.key])\n const priorKey = canonicalPrior != null ? asParentId(canonicalPrior[spec.rollup.key]) : null\n if (priorKey !== null && priorKey !== parentId) oldParentId = priorKey\n } else {\n parentId = id // a write to the parent recomputes its own aggregate\n }\n if (parentId !== null) await recomputeRollup(spec, parentId, { collection: collectionName, id }, wave)\n // The old parent is recomputed AFTER the new one so a `maxFanout`-style\n // failure on the new parent surfaces before extra work is spent.\n if (oldParentId !== null) await recomputeRollup(spec, oldParentId, { collection: collectionName, id }, wave)\n continue\n }\n\n // Determine how `collectionName` triggers this strategy, and build the list\n // of source records to (re-)derive:\n // • source — re-derive the written record itself (same-id).\n // • sources[] — re-derive the PRIMARY source at the same id.\n // • triggerBy — FK fan-out: re-derive every source record\n // whose `on` field equals the written parent's id.\n // `input` is passed to derive(); `base` is the raw stored source record\n // used as the patch base for a self-write reverse-denorm output.\n const isSource = spec.source === collectionName\n const isSibling = !isSource && (spec.sources?.includes(collectionName) ?? false)\n const triggerEntries = !isSource && !isSibling\n ? triggers.filter((t) => t.collection === collectionName)\n : []\n\n const runs: Array<{\n input: Record<string, unknown> & { id: string }\n base: Record<string, unknown>\n runId: string\n version: number\n }> = []\n\n if (isSource) {\n runs.push({ input: { ...incoming, id }, base: incoming, runId: id, version })\n } else if (isSibling) {\n const p = await derivationSource.getCollection(spec.source).get(id)\n if (p !== null && p !== undefined) {\n // Raw base for a (rare) sibling self-write; falls back to the\n // resolved primary if the raw read misses.\n const raw = await derivationSource.getCollection(spec.source)._getStoredRecord(id)\n runs.push({ input: { ...p, id }, base: raw ?? p, runId: id, version: 0 })\n }\n } else if (triggerEntries.length > 0) {\n const srcColl = derivationSource.getCollection(spec.source)\n const matched = new Set<string>()\n for (const trigger of triggerEntries) {\n // Union fan-out (spec §7): an update changing any matched component\n // must re-fire BOTH the old and the new matched set, or the old\n // set's derived output goes stale (never re-derived once it no\n // longer matches). `prior` is only ever a `Record` here — a wave\n // dispatch and a create both skip the old tuple outright.\n const tuples = [tupleFromWritten(trigger.match, id, incoming)]\n if (canonicalPrior != null && trigger.match.some((p) => p.from !== 'id')) {\n const old = tupleFromWritten(trigger.match, id, canonicalPrior)\n if (!sameTuple(old, tuples[0]!)) tuples.push(old)\n }\n const ids = new Set<string>()\n for (const tuple of tuples) {\n if (tuple === null) continue // a from-value is absent/non-scalar: matches nothing\n for (const sid of await srcColl._findMatchingCompositeIds(tuple)) ids.add(sid)\n }\n if (trigger.maxFanout !== undefined && ids.size > trigger.maxFanout) {\n throw new DerivationCapExceededError(\n `triggerBy ${collectionName}→${spec.source} [${trigger.match.map(p => p.to).join(',')}]`,\n ids.size, trigger.maxFanout)\n }\n for (const sid of ids) matched.add(sid)\n }\n for (const sid of matched) {\n const raw = await srcColl._getStoredRecord(sid)\n if (raw === null) continue\n runs.push({ input: { ...raw, id: sid }, base: raw, runId: sid, version: 0 })\n }\n }\n\n if (runs.length === 0) continue\n\n if (mode !== 'eager') {\n for (const run of runs) await markStale(registry, spec, run.runId)\n continue\n }\n\n if (executorClass === null) {\n ;({ DerivationExecutor: executorClass } = await import('./executor.js'))\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n for (const run of runs) await runOne(ctx, spec as any, strategyHash, executorClass, run)\n }\n}\n\n/**\n * Run the executor for one (spec, run) pair and write its outputs. Shared by\n * `dispatchDerivations`' eager loop and `dispatchTriggerDerivationsOnDelete`\n * (#1249) — the write-out logic (array diff, record self-write reverse-denorm,\n * normal record output) is identical for a live write and a delete-triggered\n * re-derive; only how `runs` gets built differs.\n */\nasync function runOne(\n ctx: DerivationDispatchCtx,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n spec: any,\n strategyHash: string,\n executorClass: typeof DerivationExecutor,\n run: { input: Record<string, unknown> & { id: string }; base: Record<string, unknown>; runId: string; version: number },\n): Promise<void> {\n const { derivationSource, adapter, vault, getDEK, storeCiphertext, dispatchCtx, trackPut } = ctx\n const execCtx = { vault: derivationSource.getReadOnlyFacade() }\n const outCtx = dispatchCtx({ collection: spec.source, id: run.runId })\n const result = await executorClass.run(spec, run.input, run.version, strategyHash, execCtx)\n for (const key of Object.keys(spec.outputs)) {\n const out = result.outputs[key]\n if (!out) continue\n if (out.kind === 'failed') {\n const err = out.error\n if (spec.strict) throw err\n console.warn(`[derivation] output \"${key}\" for source \"${spec.source}\" id=\"${run.runId}\" failed:`, err)\n continue\n }\n const outSpec = spec.outputs[key]\n if (!outSpec) continue\n const outputCollection = derivationSource.getCollection(outSpec.collection)\n // If we're inside a multi-record transaction, register\n // derived writes as side-effect ops on the active ctx\n // BEFORE they fire. `revertExecuted` walks `_executed` in\n // reverse on rollback, so capturing the pre-write envelope\n // here lets a later mid-batch failure restore this output's\n // prior state alongside the source op. Outside a transaction\n // the context is null and tracking is skipped.\n const txCtx = derivationSource.getActiveTxContext()\n\n // ── Array-shape branch ─────────────────────────────────\n if (out.kind === 'array') {\n // Load the prior key set from the fanout sidecar.\n const { loadFanoutSidecar, saveFanoutSidecar } = await import('./fanout-sidecar.js')\n const prior = await loadFanoutSidecar(adapter, vault, spec.source, run.runId, key, getDEK, storeCiphertext)\n const prevKeys = new Set<string>(prior?.keys ?? [])\n const newKeysList = out.entries.map((e: { key: string }) => e.key)\n const newKeysSet = new Set<string>(newKeysList)\n\n // Diff — delete keys that were in prev but not in new.\n for (const k of prevKeys) {\n if (newKeysSet.has(k)) continue\n await outputCollection._internalDelete(k, txCtx)\n }\n\n // Upsert every entry in the new set. (Slice 1: no\n // identity-skip optimisation; write every row, idempotent\n // at the (collection, id) level.)\n for (const entry of out.entries) {\n if (txCtx !== null) {\n trackPut(txCtx, outSpec.collection, entry.key, await adapter.get(vault, outSpec.collection, entry.key))\n }\n await putDerivedOutput(outputCollection, entry.key, entry.value, outCtx, { source: 'derived' })\n }\n\n // Persist the new key set last, for failure-mode symmetry.\n await saveFanoutSidecar(adapter, vault, {\n source: spec.source,\n sourceId: run.runId,\n outputKey: key,\n outputCollection: outSpec.collection,\n keys: newKeysList,\n }, getDEK, storeCiphertext)\n continue\n }\n\n // ── Record-shape branch ────────────────────────────────\n if (out.skipped === true) {\n // Optional output returned null. Delete the\n // previously-emitted output at this id, if any. Routed\n // through `_internalDelete` so a user-registered\n // `onDelete` on the output collection does NOT\n // fire — this is a system-internal tombstone, not a\n // user-initiated delete. The txCtx hookup captures the\n // prior envelope inside `_internalDelete` for rollback\n // symmetry; delete-of-absent is a silent no-op.\n await outputCollection._internalDelete(run.runId, txCtx)\n continue\n }\n\n // ── Self-write reverse-denorm ───────────────────────────\n // An output back to its own source: patch ONLY the declared\n // `denorm` fields onto the raw stored record, never the whole\n // value (which would clobber user fields / i18n maps and carries\n // the executor's `_derivedFrom` tag). If the patch changes\n // nothing, skip the write — that value-equality is the cycle\n // guard: the self-write re-fires the source-path derivation,\n // which recomputes identical fields and terminates here.\n if (outSpec.shape === 'record' && outSpec.denorm !== undefined && outSpec.collection === spec.source) {\n const value = out.value\n const patched: Record<string, unknown> = { ...run.base }\n let changed = false\n for (const f of outSpec.denorm) {\n if (!selfWriteFieldEqual(run.base[f], value[f])) {\n patched[f] = value[f]\n changed = true\n }\n }\n if (!changed) continue // cycle guard — nothing to write\n if (txCtx !== null) {\n trackPut(txCtx, outSpec.collection, run.runId, await adapter.get(vault, outSpec.collection, run.runId))\n }\n await putDerivedOutput(outputCollection, run.runId, patched, outCtx, { source: 'derived' })\n continue\n }\n\n // ── Normal record output (separate output collection) ──\n if (txCtx !== null) {\n trackPut(txCtx, outSpec.collection, run.runId, await adapter.get(vault, outSpec.collection, run.runId))\n }\n await putDerivedOutput(outputCollection, run.runId, out.value, outCtx, { source: 'derived' })\n }\n}\n\n/**\n * Trigger fan-out for a DELETED parent record (#1249, spec §8). Distinct from\n * the \"record-shape derivations not dispatched on delete\" rule — that is\n * about deleting a SOURCE record; this fires when a TRIGGER collection's\n * record is deleted, re-deriving source records that still exist. Pairs\n * evaluate against the tombstoned record's values; matched sources re-derive\n * through the normal executor (their derive() reads the now-absent parent\n * and decides what that means — the engine never cascades deletes).\n */\nexport async function dispatchTriggerDerivationsOnDelete(\n ctx: DerivationDispatchCtx, id: string, deleted: Record<string, unknown>,\n): Promise<void> {\n const { derivationSource, collectionName } = ctx\n const registry = derivationSource.registry()\n const strategies = registry.strategiesForSource(collectionName)\n if (strategies.length === 0) return\n let executorClass: typeof DerivationExecutor | null = null\n for (const { spec, strategyHash, triggers } of strategies) {\n if (spec.rollup) continue // rollup-on-delete already exists\n if (spec.source === collectionName) continue // source delete: existing rule, untouched\n if (spec.sources?.includes(collectionName)) continue // declared sibling source: same exclusion as the write path's isSibling check\n const entries = triggers.filter((t) => t.collection === collectionName)\n if (entries.length === 0) continue\n const mode = typeof spec.lifecycle === 'string' ? spec.lifecycle : spec.lifecycle.mode\n const srcColl = derivationSource.getCollection(spec.source)\n const matched = new Set<string>()\n for (const trigger of entries) {\n const tuple = tupleFromWritten(trigger.match, id, deleted)\n if (tuple === null) continue\n const ids = await srcColl._findMatchingCompositeIds(tuple)\n if (trigger.maxFanout !== undefined && ids.length > trigger.maxFanout) {\n throw new DerivationCapExceededError(\n `triggerBy ${collectionName}→${spec.source} [${trigger.match.map(p => p.to).join(',')}] (delete)`,\n ids.length, trigger.maxFanout)\n }\n for (const sid of ids) matched.add(sid)\n }\n if (matched.size === 0) continue\n if (mode !== 'eager') { for (const sid of matched) await markStale(registry, spec, sid); continue }\n if (executorClass === null) ({ DerivationExecutor: executorClass } = await import('./executor.js'))\n for (const sid of matched) {\n const raw = await srcColl._getStoredRecord(sid)\n if (raw === null) continue\n await runOne(ctx, spec, strategyHash, executorClass, { input: { ...raw, id: sid }, base: raw, runId: sid, version: 0 })\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,eAAsB,iCACpB,KACA,IACA,sBAAsB,OACL;AACjB,QAAM,EAAE,kBAAkB,gBAAgB,SAAS,OAAO,QAAQ,gBAAgB,IAAI;AAEtF,QAAM,aAAa,iBAAiB,SAAS,EAAE,oBAAoB,cAAc;AACjF,MAAI,WAAW,WAAW,EAAG,QAAO;AAEpC,QAAM,EAAE,mBAAmB,oBAAoB,IAAI,MAAM,OAAO,8BAAqB;AACrF,QAAM,QAAQ,iBAAiB,mBAAmB;AAClD,MAAI,SAAS;AAEb,aAAW,EAAE,KAAK,KAAK,YAAY;AACjC,eAAW,CAAC,WAAW,OAAO,KAAK,OAAO,QAAQ,KAAK,OAAO,GAAG;AAC/D,UAAI,QAAQ,UAAU,UAAU;AAC9B,YAAI,uBAAuB,KAAK,WAAW,kBAAkB,QAAQ,eAAe,gBAAgB;AAClG,cAAI,MAAM,iBAAiB,cAAc,QAAQ,UAAU,EAAE,gBAAgB,IAAI,KAAK,EAAG,WAAU;AAAA,QACrG;AACA;AAAA,MACF;AAEA,YAAM,UAAU,MAAM,kBAAkB,SAAS,OAAO,KAAK,QAAQ,IAAI,WAAW,QAAQ,eAAe;AAC3G,UAAI,CAAC,QAAS;AAEd,YAAM,mBAAmB,iBAAiB,cAAc,QAAQ,UAAU;AAC1E,iBAAW,aAAa,QAAQ,MAAM;AACpC,YAAI,MAAM,iBAAiB,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IAAI,IAAI,GAAG,MAAM,KAAK,OAAO,KAAK,SAAS,EAAE,CAAC;AAAA,IACxH;AAAA,EACF;AACF;","names":[]}
@@ -16,7 +16,7 @@ async function dispatchMaterializedViews(ctx, id, record, wave) {
16
16
  if (wave?.seen(`mv\0${reg.spec.name}`)) continue;
17
17
  if (executor === null) {
18
18
  ;
19
- ({ MaterializedViewExecutor: executor } = await import("./executor-KSPGNVDO.js"));
19
+ ({ MaterializedViewExecutor: executor } = await import("./executor-YDDC5XGY.js"));
20
20
  }
21
21
  await executor.refresh(reg, {
22
22
  getCollection: (name) => source.getCollection(name),
@@ -25,7 +25,7 @@ async function dispatchMaterializedViews(ctx, id, record, wave) {
25
25
  dispatchCtx: dispatchCtx({ collection: collectionName, id })
26
26
  });
27
27
  } else if (mode === "lazy") {
28
- if (staleHelpers === null) staleHelpers = await import("./stale-KSPG6LFX.js");
28
+ if (staleHelpers === null) staleHelpers = await import("./stale-2CHKZTMK.js");
29
29
  staleHelpers.markMVStale(registry, reg.spec.name);
30
30
  }
31
31
  }
@@ -47,7 +47,7 @@ async function dispatchMaterializedViewsOnDelete(ctx, id) {
47
47
  if (mode === "eager") {
48
48
  if (executor === null) {
49
49
  ;
50
- ({ MaterializedViewExecutor: executor } = await import("./executor-KSPGNVDO.js"));
50
+ ({ MaterializedViewExecutor: executor } = await import("./executor-YDDC5XGY.js"));
51
51
  }
52
52
  const rr = await executor.refresh(reg, {
53
53
  getCollection: (name) => source.getCollection(name),
@@ -60,7 +60,7 @@ async function dispatchMaterializedViewsOnDelete(ctx, id) {
60
60
  residueDeclined.push(...rr.residueDeclined);
61
61
  continue;
62
62
  }
63
- if (staleHelpers === null) staleHelpers = await import("./stale-KSPG6LFX.js");
63
+ if (staleHelpers === null) staleHelpers = await import("./stale-2CHKZTMK.js");
64
64
  const inv = await staleHelpers.invalidateMVAtRest(source, reg, mode);
65
65
  deleted += inv.deleted;
66
66
  residueUndecodable.push(...inv.residueUndecodable.map((rid) => `${reg.outputCollection}:${rid}`));
@@ -72,4 +72,4 @@ export {
72
72
  dispatchMaterializedViews,
73
73
  dispatchMaterializedViewsOnDelete
74
74
  };
75
- //# sourceMappingURL=dispatch-44J4TL72.js.map
75
+ //# sourceMappingURL=dispatch-PDP5TA73.js.map
@@ -1,9 +1,10 @@
1
1
  import {
2
2
  MaterializedViewExecutor
3
- } from "./chunk-JJR2JIN4.js";
3
+ } from "./chunk-FFBYRWDJ.js";
4
4
  import "./chunk-QIBVIOXO.js";
5
5
  import "./chunk-VXANTWBJ.js";
6
- import "./chunk-SWVNZQVR.js";
6
+ import "./chunk-MGOXJIBV.js";
7
+ import "./chunk-YPXNAP72.js";
7
8
  import "./chunk-ZORTV6NH.js";
8
9
  import "./chunk-ZN4FD4PE.js";
9
10
  import "./chunk-XZHEOSQ2.js";
@@ -26,4 +27,4 @@ import "./chunk-PZ5AY32C.js";
26
27
  export {
27
28
  MaterializedViewExecutor
28
29
  };
29
- //# sourceMappingURL=executor-KSPGNVDO.js.map
30
+ //# sourceMappingURL=executor-YDDC5XGY.js.map
package/dist/index.d.ts CHANGED
@@ -274,8 +274,8 @@ export type { ImmutableGuardConfig } from './with-audit/guards/index.js';
274
274
  export { transitionGuard } from './with-audit/guards/index.js';
275
275
  export type { TransitionGuardConfig } from './with-audit/guards/index.js';
276
276
  export type { GuardSpec, GuardStrategy, GuardContext, GuardChange, } from './with-audit/guards/index.js';
277
- export { withDerivation } from './with-formula/derivations/index.js';
278
- export { withRollup } from './with-formula/derivations/index.js';
277
+ export { withDerivation } from './with-formula/derivations/with-derivation.js';
278
+ export { withRollup } from './with-formula/derivations/with-rollup.js';
279
279
  export type { WithRollupOptions } from './with-formula/derivations/index.js';
280
280
  export type { DerivationSpec, DerivationStrategy, DerivedFromMeta, OutputSpec, RecordOutputSpec, ArrayOutputSpec, } from './with-formula/derivations/index.js';
281
281
  export { DerivationCycleError, DerivationDepthError, DerivationOutputUnknownError, DerivationOutputShapeError, DerivationCapExceededError, DuplicateBehaviorNameError, } from './kernel/errors.js';
package/dist/index.js CHANGED
@@ -63,7 +63,7 @@ import {
63
63
  import {
64
64
  decryptExtractedPartition,
65
65
  withCargo
66
- } from "./chunk-ESVREVWN.js";
66
+ } from "./chunk-SXCYYMVS.js";
67
67
  import "./chunk-DJ3LNNZQ.js";
68
68
  import {
69
69
  diffVault
@@ -86,15 +86,13 @@ import {
86
86
  import {
87
87
  withDerivation,
88
88
  withRollup
89
- } from "./chunk-T6PSWLAR.js";
90
- import "./chunk-OEA5NVSU.js";
91
- import "./chunk-TFR7DSOV.js";
89
+ } from "./chunk-BUE2D7PX.js";
92
90
  import {
93
91
  withMaterializedView
94
92
  } from "./chunk-PQKG5AHH.js";
95
- import "./chunk-JJR2JIN4.js";
93
+ import "./chunk-FFBYRWDJ.js";
96
94
  import "./chunk-QIBVIOXO.js";
97
- import "./chunk-E3EBMC4G.js";
95
+ import "./chunk-E2MYJGSG.js";
98
96
  import {
99
97
  MoneyCurrencyError,
100
98
  MoneyPrecisionError,
@@ -123,7 +121,7 @@ import {
123
121
  signRedirect,
124
122
  verifyRedirect,
125
123
  wrapPodStore
126
- } from "./chunk-S5AMPTNE.js";
124
+ } from "./chunk-BMELYFHU.js";
127
125
  import {
128
126
  Collection,
129
127
  ELEVATION_AUDIT_COLLECTION,
@@ -136,14 +134,12 @@ import {
136
134
  Vault,
137
135
  createNoydb,
138
136
  isRefArray,
139
- isViaFieldSpec,
140
137
  memoryStore,
141
138
  ref,
142
139
  refArray,
143
- via,
144
140
  withArchive
145
- } from "./chunk-I6DGKPTY.js";
146
- import "./chunk-YPMW26SL.js";
141
+ } from "./chunk-ZVCC36XQ.js";
142
+ import "./chunk-PDD75NUZ.js";
147
143
  import {
148
144
  deriveSchemaManifest,
149
145
  loadSchemaManifestEntry
@@ -158,17 +154,10 @@ import {
158
154
  } from "./chunk-QIZPZMUI.js";
159
155
  import "./chunk-TUFM4UZP.js";
160
156
  import "./chunk-GM4IM7TC.js";
161
- import "./chunk-WQF3QABE.js";
157
+ import "./chunk-IHFXR2VQ.js";
162
158
  import "./chunk-GYGLAVCX.js";
163
159
  import "./chunk-6LJY7X5A.js";
164
160
  import "./chunk-Q7HZX3IF.js";
165
- import {
166
- ClassifiedNeverStoredError,
167
- ClassifiedValidationError,
168
- isClassifiedFieldSpec,
169
- isClassifiedGroup,
170
- resolveClassifiedFields
171
- } from "./chunk-KCUIMITG.js";
172
161
  import "./chunk-RTYJRFQO.js";
173
162
  import "./chunk-BZ3534YM.js";
174
163
  import {
@@ -182,17 +171,7 @@ import {
182
171
  sealRsaOaepTlv
183
172
  } from "./chunk-JUBWUJY5.js";
184
173
  import "./chunk-VTFVLCUH.js";
185
- import "./chunk-KHKKD62N.js";
186
- import {
187
- derivePersistedSchema,
188
- isZodSchema
189
- } from "./chunk-URHRIAV6.js";
190
- import "./chunk-Y2NBBT6K.js";
191
- import {
192
- SCHEMAS_COLLECTION,
193
- loadPersistedSchema,
194
- savePersistedSchema
195
- } from "./chunk-WWNYSV7S.js";
174
+ import "./chunk-RXLYKVTF.js";
196
175
  import {
197
176
  NO_SEQUENCE,
198
177
  SequenceStore,
@@ -205,10 +184,34 @@ import {
205
184
  NO_CUSTODY,
206
185
  withCustody
207
186
  } from "./chunk-Y4MJQ2UG.js";
208
- import "./chunk-UB5CRTFF.js";
187
+ import {
188
+ isViaFieldSpec,
189
+ via
190
+ } from "./chunk-BWXGSSFX.js";
191
+ import "./chunk-TFMM5DBB.js";
192
+ import "./chunk-RTBJ5IOO.js";
193
+ import {
194
+ ClassifiedNeverStoredError,
195
+ ClassifiedValidationError,
196
+ isClassifiedFieldSpec,
197
+ isClassifiedGroup,
198
+ resolveClassifiedFields
199
+ } from "./chunk-KCUIMITG.js";
200
+ import "./chunk-VYYM3MEN.js";
201
+ import {
202
+ derivePersistedSchema,
203
+ isZodSchema
204
+ } from "./chunk-URHRIAV6.js";
205
+ import "./chunk-Y2NBBT6K.js";
206
+ import {
207
+ SCHEMAS_COLLECTION,
208
+ loadPersistedSchema,
209
+ savePersistedSchema
210
+ } from "./chunk-WWNYSV7S.js";
211
+ import "./chunk-MGOXJIBV.js";
209
212
  import {
210
213
  buildLookupSnapshot
211
- } from "./chunk-SWVNZQVR.js";
214
+ } from "./chunk-YPXNAP72.js";
212
215
  import "./chunk-SKGMN35F.js";
213
216
  import {
214
217
  INDEXED_STORE_POLICY,
@@ -273,7 +276,7 @@ import {
273
276
  NO_SEARCH,
274
277
  tokenize,
275
278
  withSearch
276
- } from "./chunk-HN4FNA4X.js";
279
+ } from "./chunk-COTPDJR5.js";
277
280
  import {
278
281
  fuseRetrieval
279
282
  } from "./chunk-AURFOK3D.js";
@@ -317,12 +320,13 @@ import {
317
320
  } from "./chunk-I3ISCYT7.js";
318
321
  import {
319
322
  withLazy
320
- } from "./chunk-THNJ3IKU.js";
323
+ } from "./chunk-ULUMAZ5S.js";
324
+ import "./chunk-66TQOPFM.js";
321
325
  import {
322
326
  Lru,
323
327
  estimateRecordBytes,
324
328
  parseBytes
325
- } from "./chunk-NO272T7Q.js";
329
+ } from "./chunk-V4PXLYWM.js";
326
330
  import "./chunk-ZN4FD4PE.js";
327
331
  import "./chunk-XZHEOSQ2.js";
328
332
  import "./chunk-YMUFFJCO.js";