@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
@@ -0,0 +1,1589 @@
1
+ import {
2
+ VectorSet
3
+ } from "./chunk-RTBJ5IOO.js";
4
+ import {
5
+ guardClassifiedCompat,
6
+ resolveClassifiedFields
7
+ } from "./chunk-KCUIMITG.js";
8
+ import {
9
+ jsonSchemaToFields
10
+ } from "./chunk-VYYM3MEN.js";
11
+ import {
12
+ derivePersistedSchema,
13
+ isZod4Schema
14
+ } from "./chunk-URHRIAV6.js";
15
+ import {
16
+ loadPersistedSchema
17
+ } from "./chunk-WWNYSV7S.js";
18
+ import {
19
+ buildPresentForJoin,
20
+ isLookupDescriptor
21
+ } from "./chunk-YPXNAP72.js";
22
+ import {
23
+ Lru
24
+ } from "./chunk-V4PXLYWM.js";
25
+ import {
26
+ isDictKeyDescriptor,
27
+ isI18nTextDescriptor,
28
+ isStaticDictDescriptor
29
+ } from "./chunk-TRGTKX5E.js";
30
+ import {
31
+ viaBinder
32
+ } from "./chunk-UXVWEX5L.js";
33
+ import {
34
+ ClassifiedConfigError,
35
+ DerivationCycleError,
36
+ FieldNotQueryableError,
37
+ MaterializedViewCycleError,
38
+ UnsupportedTierCompositionError,
39
+ ValidationError
40
+ } from "./chunk-7O3Y4PPD.js";
41
+
42
+ // src/with-shape/introspection/field-meta.ts
43
+ var FieldMetaUnknownFieldError = class extends Error {
44
+ constructor(collection, key) {
45
+ super(`fieldMeta for collection "${collection}" references unknown field "${key}". Declare it in the schema/config or remove the fieldMeta entry.`);
46
+ this.collection = collection;
47
+ this.key = key;
48
+ this.name = "FieldMetaUnknownFieldError";
49
+ }
50
+ collection;
51
+ key;
52
+ };
53
+ function validateFieldMetaKeys(collection, fieldMeta, knownFields) {
54
+ for (const key of Object.keys(fieldMeta)) {
55
+ if (!knownFields.has(key)) throw new FieldMetaUnknownFieldError(collection, key);
56
+ }
57
+ }
58
+ function humanizeFieldKey(key) {
59
+ return key.replace(/[_-]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").trim().split(/\s+/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
60
+ }
61
+ function resolveFieldMeta(key, inputs) {
62
+ const { channel, zodMeta, inferred } = inputs;
63
+ const pick = (k) => channel?.[k] ?? zodMeta?.[k] ?? inferred?.[k];
64
+ const description = pick("description");
65
+ const semanticType = pick("semanticType");
66
+ const unit = pick("unit");
67
+ const sensitivity = pick("sensitivity");
68
+ const aggregate = pick("aggregate");
69
+ const aliases = pick("aliases");
70
+ const displayFor = pick("displayFor");
71
+ const widget = pick("widget");
72
+ const group = pick("group");
73
+ const order = pick("order");
74
+ return {
75
+ label: pick("label") ?? humanizeFieldKey(key),
76
+ ...description !== void 0 ? { description } : {},
77
+ ...semanticType !== void 0 ? { semanticType } : {},
78
+ ...unit !== void 0 ? { unit } : {},
79
+ ...sensitivity !== void 0 ? { sensitivity } : {},
80
+ ...aggregate !== void 0 ? { aggregate } : {},
81
+ ...aliases !== void 0 ? { aliases } : {},
82
+ ...displayFor !== void 0 ? { displayFor } : {},
83
+ ...widget !== void 0 ? { widget } : {},
84
+ ...group !== void 0 ? { group } : {},
85
+ ...order !== void 0 ? { order } : {}
86
+ };
87
+ }
88
+
89
+ // src/with-shape/introspection/describe.ts
90
+ var ZOD_META_KEYS = /* @__PURE__ */ new Set([
91
+ "label",
92
+ "description",
93
+ "unit",
94
+ "semanticType",
95
+ "sensitivity",
96
+ "aggregate",
97
+ "aliases",
98
+ "displayFor",
99
+ "group",
100
+ "order"
101
+ ]);
102
+ function schemaFieldKeys(schema) {
103
+ let s = schema;
104
+ for (let depth = 0; depth < 10; depth++) {
105
+ if (s === null || typeof s !== "object") return void 0;
106
+ const shape = s.shape;
107
+ if (shape !== null && typeof shape === "object") {
108
+ const keys = Object.keys(shape);
109
+ return keys.length > 0 ? keys : void 0;
110
+ }
111
+ const def = s._def;
112
+ const effect = def?.effect?.type;
113
+ if (def?.schema !== void 0 && (effect === "refinement" || effect === "preprocess")) {
114
+ s = def.schema;
115
+ continue;
116
+ }
117
+ if (def?.out !== void 0) {
118
+ s = def.out;
119
+ continue;
120
+ }
121
+ return void 0;
122
+ }
123
+ return void 0;
124
+ }
125
+ async function deriveZodFields(schema) {
126
+ const envelope = await derivePersistedSchema(schema);
127
+ if (!envelope.jsonSchema) return {};
128
+ const isZod4 = isZod4Schema(schema);
129
+ const jsonSchema = envelope.jsonSchema;
130
+ const fieldDescriptors = jsonSchemaToFields(jsonSchema, "live-validator");
131
+ const propertiesRaw = jsonSchema["properties"];
132
+ const result = {};
133
+ for (const [key, descriptor] of Object.entries(fieldDescriptors)) {
134
+ let meta;
135
+ if (isZod4 && propertiesRaw) {
136
+ const prop = propertiesRaw[key];
137
+ if (prop) {
138
+ const extracted = {};
139
+ let hasAny = false;
140
+ for (const mk of ZOD_META_KEYS) {
141
+ if (mk in prop) {
142
+ extracted[mk] = prop[mk];
143
+ hasAny = true;
144
+ }
145
+ }
146
+ if (hasAny) meta = extracted;
147
+ }
148
+ }
149
+ result[key] = {
150
+ type: descriptor.type,
151
+ optional: descriptor.optional === true,
152
+ ...descriptor.constraints !== void 0 ? { constraints: descriptor.constraints } : {},
153
+ ...meta !== void 0 ? { meta } : {}
154
+ };
155
+ }
156
+ return result;
157
+ }
158
+ async function resolveDescribeFieldIds(store, vaultName, collectionName, getDEK) {
159
+ let dek;
160
+ try {
161
+ dek = await getDEK(collectionName);
162
+ } catch {
163
+ return {};
164
+ }
165
+ const persisted = await loadPersistedSchema(store, vaultName, collectionName, dek);
166
+ return persisted?.fieldIds !== void 0 ? { fieldIds: persisted.fieldIds } : {};
167
+ }
168
+ function deriveWidget(opts) {
169
+ if (opts.resolvedWidget !== void 0) return opts.resolvedWidget;
170
+ switch (opts.semanticType) {
171
+ case "date":
172
+ case "datetime":
173
+ return "date";
174
+ case "currency":
175
+ return "money";
176
+ case "entity":
177
+ return "ref-select";
178
+ case "url":
179
+ return "url";
180
+ case "email":
181
+ return "email";
182
+ case "percent":
183
+ return "number";
184
+ }
185
+ if (opts.dict !== void 0 || opts.lookup !== void 0) return "select";
186
+ if (opts.blob !== void 0) return "file";
187
+ if (opts.type === "boolean") return "checkbox";
188
+ if (opts.type === "number") return "number";
189
+ return "text";
190
+ }
191
+ function buildDescription(input) {
192
+ const { collection, fieldMeta, moneyFields, dictKeyFields, lookupFields, computed, refs, zodFields, schema, dictLabels, meta, i18nFields, classified, taint, fieldIds } = input;
193
+ const lookupFragments = input.viaFragments?.["lookup"]?.lookupFields;
194
+ const blobFragments = input.viaFragments?.["blob"]?.blobFields;
195
+ const validatorKeys = zodFields !== void 0 && Object.keys(zodFields).length > 0 ? Object.keys(zodFields) : schemaFieldKeys(schema);
196
+ const canEnumerateFields = validatorKeys !== void 0;
197
+ if (canEnumerateFields && fieldMeta !== void 0) {
198
+ const knownFields = /* @__PURE__ */ new Set([
199
+ ...Object.keys(moneyFields ?? {}),
200
+ ...Object.keys(dictKeyFields ?? {}),
201
+ ...Object.keys(refs),
202
+ ...Object.keys(computed ?? {}),
203
+ ...validatorKeys ?? [],
204
+ ...Object.keys(i18nFields ?? {}),
205
+ ...Object.keys(lookupFields ?? {}),
206
+ ...Object.keys(blobFragments ?? {}),
207
+ ...Object.keys(classified ?? {})
208
+ ]);
209
+ validateFieldMetaKeys(collection, fieldMeta, knownFields);
210
+ }
211
+ const allKeys = /* @__PURE__ */ new Set([
212
+ ...Object.keys(moneyFields ?? {}),
213
+ ...Object.keys(dictKeyFields ?? {}),
214
+ ...Object.keys(lookupFields ?? {}),
215
+ ...Object.keys(refs),
216
+ ...Object.keys(computed ?? {}),
217
+ ...Object.keys(fieldMeta ?? {}),
218
+ ...Object.keys(zodFields ?? {}),
219
+ ...Object.keys(i18nFields ?? {}),
220
+ ...Object.keys(classified ?? {}),
221
+ ...Object.keys(blobFragments ?? {})
222
+ ]);
223
+ const fields = [];
224
+ for (const key of [...allKeys].sort()) {
225
+ const zod = zodFields?.[key];
226
+ const money = moneyFields?.[key];
227
+ const dict = dictKeyFields?.[key];
228
+ const lookupDesc = lookupFields?.[key];
229
+ const refDesc = refs[key];
230
+ const isComputed = computed !== void 0 && key in computed;
231
+ const i18nDesc = i18nFields?.[key];
232
+ const cls = classified?.[key];
233
+ const blobFragmentEntry = blobFragments?.[key];
234
+ const taintPosture = taint?.postures.get(key);
235
+ let type = zod?.type ?? "unknown";
236
+ const inferred = {};
237
+ let moneyBlock;
238
+ let dictBlock;
239
+ let refBlock;
240
+ let lookupBlock;
241
+ let blobBlock;
242
+ if (money) {
243
+ type = "number";
244
+ inferred.semanticType = "currency";
245
+ inferred.aggregate = "sum";
246
+ const currency = money.soleCurrency();
247
+ const scale = currency !== void 0 ? money.scaleFor(currency) : void 0;
248
+ moneyBlock = {
249
+ mode: money.mode,
250
+ ...currency !== void 0 ? { currency } : {},
251
+ ...scale !== void 0 ? { scale } : {},
252
+ ...money.rounding !== void 0 ? { rounding: money.rounding } : {}
253
+ };
254
+ } else if (refDesc) {
255
+ type = refDesc.isArray ? "array" : "string";
256
+ inferred.semanticType = "entity";
257
+ refBlock = {
258
+ target: refDesc.target,
259
+ mode: refDesc.mode,
260
+ ...refDesc.isArray ? { isArray: true } : {}
261
+ };
262
+ } else if (dict) {
263
+ type = "enum";
264
+ if (isStaticDictDescriptor(dict)) {
265
+ const displayLocale = dict.displayLocale;
266
+ const values = dict.keys.map((k) => {
267
+ const localeMap = dict.table[k];
268
+ const label = displayLocale !== void 0 ? localeMap?.[displayLocale] ?? void 0 : void 0;
269
+ return label !== void 0 ? { value: k, label } : { value: k };
270
+ });
271
+ dictBlock = { name: dict.name, static: true, values };
272
+ } else {
273
+ const labelMap = dictLabels?.[dict.name];
274
+ const labelMapHasEntries = labelMap !== void 0 && Object.keys(labelMap).length > 0;
275
+ if (labelMapHasEntries) {
276
+ const values = Object.entries(labelMap).map(([value, label]) => ({ value, label }));
277
+ dictBlock = { name: dict.name, static: false, values };
278
+ } else if (dict.keys !== void 0) {
279
+ const values = dict.keys.map((k) => {
280
+ const label = dict.labels?.[k];
281
+ return label !== void 0 ? { value: k, label } : { value: k };
282
+ });
283
+ dictBlock = { name: dict.name, static: false, values };
284
+ } else {
285
+ dictBlock = { name: dict.name, static: false };
286
+ }
287
+ }
288
+ } else if (lookupDesc) {
289
+ type = "enum";
290
+ const lookupLabelMap = dictLabels?.[lookupDesc.dimension];
291
+ const lookupLabelMapHasEntries = lookupLabelMap !== void 0 && Object.keys(lookupLabelMap).length > 0;
292
+ if (lookupDesc.table !== void 0) {
293
+ const displayLocale = lookupDesc.displayLocale;
294
+ const table = lookupDesc.table;
295
+ const values = (lookupDesc.keys ?? Object.keys(table)).map((k) => {
296
+ const localeMap = table[k];
297
+ const label = displayLocale !== void 0 ? localeMap?.[displayLocale] ?? void 0 : void 0;
298
+ return label !== void 0 ? { value: k, label } : { value: k };
299
+ });
300
+ dictBlock = { name: lookupDesc.dimension, static: true, values };
301
+ } else if (lookupLabelMapHasEntries) {
302
+ const values = Object.entries(lookupLabelMap).map(([value, label]) => ({ value, label }));
303
+ dictBlock = { name: lookupDesc.dimension, static: false, values };
304
+ } else if (lookupDesc.keys !== void 0) {
305
+ const values = lookupDesc.keys.map((k) => {
306
+ const label = lookupDesc.labels?.[k];
307
+ return label !== void 0 ? { value: k, label } : { value: k };
308
+ });
309
+ dictBlock = { name: lookupDesc.dimension, static: false, values };
310
+ } else {
311
+ dictBlock = { name: lookupDesc.dimension, static: false };
312
+ }
313
+ } else if (i18nDesc) {
314
+ type = "string";
315
+ } else if (isComputed) {
316
+ } else if (blobFragmentEntry !== void 0) {
317
+ type = "blob";
318
+ blobBlock = { ...blobFragmentEntry, queryable: "none" };
319
+ }
320
+ const lookupFragmentEntry = lookupFragments?.[key];
321
+ if (lookupFragmentEntry !== void 0) {
322
+ lookupBlock = {
323
+ ...lookupFragmentEntry.dimension !== void 0 ? { dimension: lookupFragmentEntry.dimension } : {},
324
+ backing: lookupFragmentEntry.backing,
325
+ vocabulary: lookupFragmentEntry.vocabulary,
326
+ key: lookupFragmentEntry.key,
327
+ onDelete: lookupFragmentEntry.onDelete,
328
+ ...lookupFragmentEntry.altKeys !== void 0 ? { altKeys: lookupFragmentEntry.altKeys } : {},
329
+ ...lookupFragmentEntry.present !== void 0 ? { present: lookupFragmentEntry.present } : {},
330
+ ...lookupFragmentEntry.sortBy !== void 0 ? { sortBy: lookupFragmentEntry.sortBy } : {},
331
+ ...lookupFragmentEntry.keys !== void 0 ? { keys: lookupFragmentEntry.keys } : {}
332
+ };
333
+ }
334
+ if (cls !== void 0) inferred.sensitivity = cls.sensitivity;
335
+ const channelEntry = fieldMeta?.[key];
336
+ const zodMeta = zod?.meta;
337
+ const resolved = resolveFieldMeta(key, {
338
+ ...channelEntry !== void 0 ? { channel: channelEntry } : {},
339
+ ...zodMeta !== void 0 ? { zodMeta } : {},
340
+ inferred
341
+ });
342
+ let i18nBlock;
343
+ if (i18nDesc !== void 0) {
344
+ const locales = i18nDesc.options.languages;
345
+ const densify = i18nDesc.options.densifyOnWrite;
346
+ i18nBlock = {
347
+ ...locales !== void 0 ? { locales } : {},
348
+ ...densify !== void 0 ? { densify } : {}
349
+ };
350
+ }
351
+ const widget = deriveWidget({
352
+ type,
353
+ ...resolved.semanticType !== void 0 ? { semanticType: resolved.semanticType } : {},
354
+ ...dictBlock !== void 0 ? { dict: dictBlock } : {},
355
+ ...lookupBlock !== void 0 ? { lookup: lookupBlock } : {},
356
+ ...blobBlock !== void 0 ? { blob: blobBlock } : {},
357
+ ...resolved.widget !== void 0 ? { resolvedWidget: resolved.widget } : {}
358
+ });
359
+ const editable = !isComputed && key !== "id" && blobBlock === void 0;
360
+ const field = {
361
+ key,
362
+ ...fieldIds?.[key] !== void 0 ? { id: fieldIds[key] } : {},
363
+ type,
364
+ optional: zod?.optional ?? false,
365
+ ...zod?.constraints !== void 0 ? { constraints: zod.constraints } : {},
366
+ label: resolved.label,
367
+ ...resolved.description !== void 0 ? { description: resolved.description } : {},
368
+ ...resolved.group !== void 0 ? { group: resolved.group } : {},
369
+ ...resolved.order !== void 0 ? { order: resolved.order } : {},
370
+ ...resolved.semanticType !== void 0 ? { semanticType: resolved.semanticType } : {},
371
+ ...resolved.unit !== void 0 ? { unit: resolved.unit } : {},
372
+ ...resolved.sensitivity !== void 0 ? { sensitivity: resolved.sensitivity } : {},
373
+ ...resolved.aggregate !== void 0 ? { aggregate: resolved.aggregate } : {},
374
+ ...resolved.aliases !== void 0 ? { aliases: resolved.aliases } : {},
375
+ ...resolved.displayFor !== void 0 ? { displayFor: resolved.displayFor } : {},
376
+ ...refBlock !== void 0 ? { ref: refBlock } : {},
377
+ ...moneyBlock !== void 0 ? { money: moneyBlock } : {},
378
+ ...dictBlock !== void 0 ? { dict: dictBlock } : {},
379
+ ...lookupBlock !== void 0 ? { lookup: lookupBlock } : {},
380
+ ...blobBlock !== void 0 ? { blob: blobBlock } : {},
381
+ ...isComputed ? { computed: true } : {},
382
+ ...i18nBlock !== void 0 ? { i18n: i18nBlock } : {},
383
+ widget,
384
+ editable,
385
+ ...cls !== void 0 ? {
386
+ classified: {
387
+ preset: cls.preset,
388
+ storage: cls.storage,
389
+ list: cls.list.kind === "omit" ? "omit" : cls.list.kind === "mask" ? { mask: cls.list.pattern } : { rider: cls.list.rider },
390
+ ...cls.equatable === true ? { equatable: true } : {}
391
+ }
392
+ } : {},
393
+ ...taintPosture !== void 0 ? { taint: { posture: taintPosture, forcedBy: taint?.provenance?.get(key) ?? [] } } : {}
394
+ };
395
+ fields.push(field);
396
+ }
397
+ const collectionMeta = {
398
+ ...meta,
399
+ label: meta?.label ?? humanizeFieldKey(collection)
400
+ };
401
+ return {
402
+ collection,
403
+ fields,
404
+ meta: collectionMeta
405
+ };
406
+ }
407
+
408
+ // src/kernel/via/compose.ts
409
+ function via(...descriptors) {
410
+ if (descriptors.length === 0) {
411
+ throw new ValidationError("via(): at least one descriptor is required, e.g. via(money({ currency: 'EUR' }))");
412
+ }
413
+ return { _noydbVia: true, descriptors };
414
+ }
415
+ function isViaFieldSpec(x) {
416
+ return typeof x === "object" && x !== null && x._noydbVia === true;
417
+ }
418
+ function mergeViaFields(sources) {
419
+ for (const field of Object.keys(sources.dictKeyFields ?? {})) {
420
+ if (sources.lookupFields && field in sources.lookupFields) {
421
+ throw new ValidationError(
422
+ `mergeViaFields(): field "${field}" is declared in both \`dictKeyFields\` and \`lookupFields\` \u2014 declare it in one place only.`
423
+ );
424
+ }
425
+ }
426
+ if (!sources.viaFields || Object.keys(sources.viaFields).length === 0) {
427
+ return {
428
+ moneyFields: sources.moneyFields,
429
+ i18nFields: sources.i18nFields,
430
+ dictKeyFields: sources.dictKeyFields,
431
+ computedFields: void 0,
432
+ lookupFields: sources.lookupFields
433
+ };
434
+ }
435
+ const sugarFieldNames = /* @__PURE__ */ new Set([
436
+ ...Object.keys(sources.moneyFields ?? {}),
437
+ ...Object.keys(sources.i18nFields ?? {}),
438
+ ...Object.keys(sources.dictKeyFields ?? {}),
439
+ ...Object.keys(sources.lookupFields ?? {})
440
+ ]);
441
+ const viaMoney = {};
442
+ const viaI18nText = {};
443
+ const viaDictKey = {};
444
+ const viaComputed = {};
445
+ const viaLookup = {};
446
+ for (const [field, spec] of Object.entries(sources.viaFields)) {
447
+ if (sugarFieldNames.has(field)) {
448
+ throw new ValidationError(
449
+ `via(): field "${field}" is declared via both a sugar key and \`viaFields\` \u2014 declare it in one place only.`
450
+ );
451
+ }
452
+ for (const descriptor of spec.descriptors) {
453
+ if (descriptor._viaBrand === "money") {
454
+ viaMoney[field] = descriptor;
455
+ } else if (descriptor._viaBrand === "i18n") {
456
+ if (isI18nTextDescriptor(descriptor)) viaI18nText[field] = descriptor;
457
+ else if (isDictKeyDescriptor(descriptor) || isStaticDictDescriptor(descriptor)) viaDictKey[field] = descriptor;
458
+ } else if (descriptor._viaBrand === "computed") {
459
+ viaComputed[field] = descriptor;
460
+ } else if (descriptor._viaBrand === "lookup" && isLookupDescriptor(descriptor)) {
461
+ viaLookup[field] = descriptor;
462
+ } else {
463
+ throw new ValidationError(`via(): field "${field}" has a descriptor with unrecognized _viaBrand "${descriptor._viaBrand}" \u2014 via() only supports money/i18n/computed/lookup descriptors today.`);
464
+ }
465
+ }
466
+ }
467
+ return {
468
+ moneyFields: Object.keys(viaMoney).length > 0 ? { ...sources.moneyFields ?? {}, ...viaMoney } : sources.moneyFields,
469
+ i18nFields: Object.keys(viaI18nText).length > 0 ? { ...sources.i18nFields ?? {}, ...viaI18nText } : sources.i18nFields,
470
+ dictKeyFields: Object.keys(viaDictKey).length > 0 ? { ...sources.dictKeyFields ?? {}, ...viaDictKey } : sources.dictKeyFields,
471
+ computedFields: Object.keys(viaComputed).length > 0 ? viaComputed : void 0,
472
+ lookupFields: Object.keys(viaLookup).length > 0 ? { ...sources.lookupFields ?? {}, ...viaLookup } : sources.lookupFields
473
+ };
474
+ }
475
+ var VIA_FIELD_MAP_FAMILY = {
476
+ moneyFields: "money",
477
+ i18nFields: "i18n",
478
+ dictKeyFields: "i18n",
479
+ lookupFields: "lookup",
480
+ classifiedFields: "classified",
481
+ blobFields: "blob",
482
+ computed: "computed"
483
+ };
484
+ function guardCrossBindingFieldCollisions(fieldMaps, callerPrefix = "compileVias()") {
485
+ const claimantsByField = /* @__PURE__ */ new Map();
486
+ for (const [sourceKey, map] of Object.entries(fieldMaps)) {
487
+ for (const field of Object.keys(map ?? {})) {
488
+ const claimants = claimantsByField.get(field) ?? /* @__PURE__ */ new Set();
489
+ claimants.add(sourceKey);
490
+ claimantsByField.set(field, claimants);
491
+ }
492
+ }
493
+ for (const [field, sourceKeys] of claimantsByField) {
494
+ const families = new Set([...sourceKeys].map((key) => VIA_FIELD_MAP_FAMILY[key]));
495
+ if (families.size < 2) continue;
496
+ if (sourceKeys.size === 2 && families.has("computed")) {
497
+ const other = [...families].find((f) => f !== "computed");
498
+ if (other === "money" || other === "i18n" || other === "lookup") continue;
499
+ }
500
+ const keys = [...sourceKeys].sort().map((k) => `\`${k}\``);
501
+ const joined = keys.length === 2 ? keys.join(" and ") : `${keys.slice(0, -1).join(", ")}, and ${keys[keys.length - 1]}`;
502
+ throw new ValidationError(
503
+ `${callerPrefix}: field "${field}" is declared in both ${joined} \u2014 a field cannot be claimed by two different via-binding families. Declare it in one place only.`
504
+ );
505
+ }
506
+ }
507
+ function guardReconcileCollisions(existingVia, incomingFieldMaps) {
508
+ guardCrossBindingFieldCollisions(incomingFieldMaps, "guardReconcileCollisions()");
509
+ if (!existingVia) return;
510
+ const existingBindings = existingVia.bindings.filter((b) => b.brand !== "taint");
511
+ for (const [sourceKey, map] of Object.entries(incomingFieldMaps)) {
512
+ const incomingFamily = VIA_FIELD_MAP_FAMILY[sourceKey];
513
+ if (incomingFamily === void 0) continue;
514
+ for (const field of Object.keys(map ?? {})) {
515
+ const existingFamilies = new Set(
516
+ existingBindings.filter((b) => b.covers?.(field)).map((b) => b.brand)
517
+ );
518
+ for (const existingFamily of existingFamilies) {
519
+ if (existingFamily === incomingFamily) continue;
520
+ const isExempt = existingFamily === "computed" && (incomingFamily === "money" || incomingFamily === "i18n" || incomingFamily === "lookup") || incomingFamily === "computed" && (existingFamily === "money" || existingFamily === "i18n" || existingFamily === "lookup");
521
+ if (isExempt) continue;
522
+ throw new ValidationError(
523
+ `vault.collection(): field "${field}" is already bound by the "${existingFamily}" via family on this collection \u2014 an incoming \`${sourceKey}\` declaration cannot claim it for a different family ("${incomingFamily}"). Declare it in one place only.`
524
+ );
525
+ }
526
+ }
527
+ }
528
+ }
529
+
530
+ // src/kernel/via/pipeline.ts
531
+ var ViaPipeline = class _ViaPipeline {
532
+ constructor(bindings, taint) {
533
+ this.bindings = bindings;
534
+ this.taint = taint;
535
+ const moneyVias = bindings.filter((b) => b.brand === "money");
536
+ const computedVias = bindings.filter((b) => b.brand === "computed");
537
+ const restBindings = bindings.filter((b) => b.brand !== "money" && b.brand !== "computed");
538
+ this._presentOrder = [...moneyVias, ...computedVias, ...restBindings];
539
+ this._presentLateBoundary = moneyVias.length + computedVias.length;
540
+ }
541
+ bindings;
542
+ taint;
543
+ /**
544
+ * Present-phase-ONLY order (#665, corrected under #665 review) — a stable
545
+ * THREE-WAY partition of `bindings` computed once here at construction:
546
+ * every `'money'`-brand binding first (existing relative order), then
547
+ * every `'computed'`-brand binding (existing relative order), then
548
+ * everything else (existing relative order). `present()` folds over this
549
+ * instead of `bindings` so a `mode: 'virtual'` computed field's value
550
+ * exists before i18n/lookup's dressing `present()` hooks run on it
551
+ * (today's `compileVias` order is money→i18n→lookup→classified→
552
+ * blob→computed, `collection-config.ts:554`, so dressing unconditionally
553
+ * ran BEFORE the value it dresses existed). This reorder is binding-level,
554
+ * not conditioned on any particular field composition — it applies to
555
+ * EVERY collection that compiles a `'computed'` binding at all, not only
556
+ * ones stacking a dresser on the SAME field as a computed one. EVERY other
557
+ * phase (`ingest`/`encodeWrite`/`encodeAtRest`/`enforceWrite`/etc.) keeps
558
+ * folding over `bindings` unchanged — those write/query phases need
559
+ * money-first (`_applyMoneyFields` PREPENDS money, `_applyClassifiedFields`
560
+ * APPENDS classified to preserve it, `kernel/collection.ts:1275-1284,1364-
561
+ * 1368`).
562
+ *
563
+ * Money is deliberately carved OUT of the generic "everything else" slice
564
+ * and kept FIRST — the original two-way `[computed..., rest...]` partition
565
+ * regressed money's composed-field behavior from a benign missing-dressing
566
+ * gap into VALUE CORRUPTION: money's `present()` DECODES its input as a
567
+ * STORED SCALED-INT (and derives `<field>Formatted` from it) — it is not a
568
+ * pure dressing CONSUMER like i18n/lookup, which only ADD a `<field>Label`
569
+ * key and never rewrite the field's own value. Running money AFTER
570
+ * computed on a field composing `computed(virtual)` + `money(...)` on
571
+ * ITSELF means money's decode sees the virtual field's raw MAJOR-unit
572
+ * output (e.g. `21`) and misreads it as a scaled-int, producing a
573
+ * corrupted value (`'0.21'`) instead of the pre-#665 result (the raw `21`
574
+ * surviving untouched, with no `Formatted` key added — a benign
575
+ * missing-dressing gap, not a wrong value). Money-first restores money's
576
+ * exact pre-#665 present position — byte-identical money behavior; the
577
+ * materialized composition pins from the #631 work and the money suites
578
+ * all ran under money-first. i18n/lookup are genuine dressing consumers
579
+ * (they only ADD, never rewrite), so they stay after computed, which is
580
+ * the fix #665 intended. A `'taint'` binding (appended LAST by
581
+ * `via/graph-wiring.ts#applyTaintOverlay`) stays last here too (it's
582
+ * neither money nor computed, so it lands at the tail of the "everything
583
+ * else" slice), preserving its "runs after computed, redacts tainted
584
+ * virtual output" contract (`via/taint-binding.ts`'s `taintBinding` doc
585
+ * comment).
586
+ *
587
+ * Money-dressing a virtual computed field's OWN output (the composed
588
+ * `computed(virtual) + money` case) is NOT resolved by this partition
589
+ * alone — #669 resolves it with a separate mid-fold hook instead:
590
+ * `NoydbVia.presentLate` runs after every binding's `present()` in this
591
+ * money+computed segment, before the "everything else" segment below, so
592
+ * money can quantize/reinterpret a virtual field's fresh MAJOR-UNITS
593
+ * output as if it were a stored value, without perturbing this ordering
594
+ * or the #665 invariant above it (`_presentLateBoundary` below marks
595
+ * exactly where that mid-fold point sits within `_presentOrder`).
596
+ */
597
+ _presentOrder;
598
+ /** #669 — index into `_presentOrder` where the money+computed segment ends and the
599
+ * "everything else" segment begins (`moneyVias.length + computedVias.length`);
600
+ * `present()` runs every binding's `presentLate` at exactly this boundary. */
601
+ _presentLateBoundary;
602
+ /** undefined when there is nothing to enforce — the zero-via fast path is
603
+ * `this.via === undefined` (#553: keeps an all-plain collection sync). A
604
+ * `'*'`-defaulted output collection (#642) counts as "something to enforce"
605
+ * even with zero field-specific postures and zero bindings. */
606
+ static build(bindings, taint) {
607
+ if (bindings.length === 0 && (!taint || taint.postures.size === 0 && taint.defaultPosture === void 0)) return void 0;
608
+ return new _ViaPipeline(bindings, taint);
609
+ }
610
+ /** Refuse a write before crypto runs: awaits each binding's `enforceWrite` in order — first throw wins. */
611
+ async enforceWrite(record, ctx) {
612
+ for (const b of this.bindings) if (b.enforceWrite) await b.enforceWrite(record, ctx);
613
+ }
614
+ ingest(record) {
615
+ let r = record;
616
+ for (const b of this.bindings) if (b.ingest) r = b.ingest(r);
617
+ return r;
618
+ }
619
+ canonicalizeStored(record) {
620
+ let r = record;
621
+ for (const b of this.bindings) if (b.canonicalizeStored) r = b.canonicalizeStored(r);
622
+ return r;
623
+ }
624
+ async encodeWrite(record, ctx) {
625
+ let r = record;
626
+ for (const b of this.bindings) if (b.encodeWrite) r = await b.encodeWrite(r, ctx);
627
+ return r;
628
+ }
629
+ /**
630
+ * Final write-pipeline stage: folds each binding's `encodeAtRest` in
631
+ * order, threading the record and accumulating the sealed-slot map. A
632
+ * field belongs to exactly one via feature — two bindings sealing the
633
+ * same field is a brand-keyed collision and throws.
634
+ */
635
+ async encodeAtRest(record, crypto) {
636
+ let r = record;
637
+ let sealed;
638
+ const sealedBy = /* @__PURE__ */ new Map();
639
+ for (const b of this.bindings) {
640
+ if (!b.encodeAtRest) continue;
641
+ const result = await b.encodeAtRest(r, crypto);
642
+ r = result.record;
643
+ if (!result.sealed) continue;
644
+ for (const [field, ref] of Object.entries(result.sealed)) {
645
+ const priorBrand = sealedBy.get(field);
646
+ if (priorBrand !== void 0) {
647
+ throw new ValidationError(
648
+ `via encodeAtRest: field "${field}" sealed by binding "${priorBrand}" is also sealed by binding "${b.brand}"`
649
+ );
650
+ }
651
+ sealedBy.set(field, b.brand);
652
+ sealed ??= {};
653
+ sealed[field] = ref;
654
+ }
655
+ }
656
+ return sealed ? { record: r, sealed } : { record: r };
657
+ }
658
+ /** First read-pipeline stage: folds each binding's `decodeAtRest` in order. */
659
+ async decodeAtRest(record, sealed, crypto, opts) {
660
+ let r = record;
661
+ for (const b of this.bindings) if (b.decodeAtRest) r = await b.decodeAtRest(r, sealed, crypto, opts);
662
+ return r;
663
+ }
664
+ async present(record, ctx) {
665
+ let r = record;
666
+ for (let i = 0; i < this._presentLateBoundary; i++) {
667
+ const b = this._presentOrder[i];
668
+ if (b.present) r = await b.present(r, ctx);
669
+ }
670
+ for (const b of this.bindings) if (b.presentLate) r = await b.presentLate(r, ctx);
671
+ for (let i = this._presentLateBoundary; i < this._presentOrder.length; i++) {
672
+ const b = this._presentOrder[i];
673
+ if (b.present) r = await b.present(r, ctx);
674
+ }
675
+ return r;
676
+ }
677
+ buildClause(field, op, value) {
678
+ for (const b of this.bindings) {
679
+ const payload = b.buildClause?.(field, op, value);
680
+ if (payload !== void 0) return { brand: b.brand, payload };
681
+ }
682
+ return void 0;
683
+ }
684
+ evaluateClause(clause, actual, op) {
685
+ const b = this.bindings.find((x) => x.brand === clause.brand);
686
+ return b?.evaluateClause ? b.evaluateClause(actual, op, clause.payload) : false;
687
+ }
688
+ /**
689
+ * Resolve a `buildClause` payload to an index-probe operand (#625) —
690
+ * mirrors `evaluateClause`'s brand dispatch. `undefined` (a binding
691
+ * with no `indexProbe`, or one that declines to probe this op/payload)
692
+ * means the caller (`candidateRecords()`) must fall back to a scan.
693
+ */
694
+ // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
695
+ indexProbe(clause, op) {
696
+ const b = this.bindings.find((x) => x.brand === clause.brand);
697
+ return b?.indexProbe ? b.indexProbe(op, clause.payload) : void 0;
698
+ }
699
+ /**
700
+ * Resolve a raw STORED field value to its canonical eager-index bucket
701
+ * key (#672) — folds every binding's `canonicalizeIndexKey`, first
702
+ * non-undefined wins (same fold discipline as `buildClause`). `undefined`
703
+ * means no binding claims `field` (or the value can't be canonicalized)
704
+ * — the caller buckets the raw stringified value, unchanged from before
705
+ * this hook existed.
706
+ */
707
+ canonicalizeIndexKey(field, rawValue) {
708
+ for (const b of this.bindings) {
709
+ const key = b.canonicalizeIndexKey?.(field, rawValue);
710
+ if (key !== void 0) return key;
711
+ }
712
+ return void 0;
713
+ }
714
+ decodeResults(record) {
715
+ let r = record;
716
+ for (const b of this.bindings) if (b.decodeResults) r = b.decodeResults(r);
717
+ return r;
718
+ }
719
+ /** undefined = no binding covers the field → caller falls back to generic compare. */
720
+ compareForOrder(field, a, b) {
721
+ for (const bind of this.bindings) {
722
+ const c = bind.compareForOrder?.(field, a, b);
723
+ if (c !== void 0) return c;
724
+ }
725
+ return void 0;
726
+ }
727
+ /** undefined = no binding resolves an order-sort label for `key` at `field`/`locale` (#650 Task 7 —
728
+ * the `orderBy(..., {by:'label'})` per-call-locale channel `compareForOrder` above can't serve). */
729
+ resolveOrderLabel(field, key, locale) {
730
+ for (const bind of this.bindings) {
731
+ const label = bind.resolveOrderLabel?.(field, key, locale);
732
+ if (label !== void 0) return label;
733
+ }
734
+ return void 0;
735
+ }
736
+ /**
737
+ * Which posture governs `field`, if any binding covers it — `undefined`
738
+ * means no binding declares `field` (the generic, non-via query path
739
+ * applies). #629 Task 8's posture consumer: `.where()`/`.orderBy()`
740
+ * consult this before building/evaluating a clause, refusing fields whose
741
+ * posture is `queryable: 'none'` (e.g. blob); every other posture
742
+ * ('det-exact'/'ordered'/'full') is left to the existing per-binding
743
+ * buildClause/evaluateClause/compareForOrder machinery, unchanged.
744
+ *
745
+ * #638 Task 3: the graph-computed taint overlay is consulted FIRST — a
746
+ * derived field's assigned (most-restrictive-of-sources) posture wins over
747
+ * whatever a binding would otherwise report for that field name (no
748
+ * binding covers a computed/derived field today, so this never actually
749
+ * shadows one — see `via/taint-binding.ts`'s `taintBinding.covers`, which
750
+ * only claims the sealed subset for `encodeAtRest`/`decodeAtRest`, not for
751
+ * this lookup).
752
+ */
753
+ postureFor(field) {
754
+ const t = this.taint?.postures.get(field);
755
+ if (t) return t;
756
+ for (const b of this.bindings) {
757
+ if (b.covers?.(field)) return b.posture;
758
+ }
759
+ return this.taint?.defaultPosture;
760
+ }
761
+ /**
762
+ * Refuse any field-based reducer over a `queryable: 'none'` field (blob) —
763
+ * metadata-only: walks each reducer's `.field` and checks posture, no
764
+ * rewriting. Reducers with no `.field` (e.g. `count()`) are skipped.
765
+ *
766
+ * Shared by `wrapReducers` below (which ALSO applies each binding's
767
+ * rewrite, e.g. money's exact-BigInt reducer swap) and by
768
+ * `ScanBuilder.aggregate()` (#629 Task 8 review fix wave 1), which must
769
+ * call THIS, not `wrapReducers` — wiring full `wrapReducers` into
770
+ * `ScanBuilder.aggregate()` would newly activate money/i18n reducer
771
+ * wrapping on a path that has never run it, a parity-breaking behavior
772
+ * change for existing brands.
773
+ */
774
+ refuseUnqueryableReducers(spec) {
775
+ for (const reducer of Object.values(spec)) {
776
+ const field = reducer?.field;
777
+ if (field !== void 0 && this.postureFor(field)?.queryable === "none") {
778
+ throw new FieldNotQueryableError(field);
779
+ }
780
+ }
781
+ }
782
+ /**
783
+ * Rewrite an aggregate spec (money exact reducers), then refuse any
784
+ * field-based reducer over a `queryable: 'none'` field (blob) — the same
785
+ * posture gate `.where()`/`.orderBy()` apply, extended to `.aggregate()`
786
+ * (both the bare-spec and builder forms funnel through here).
787
+ */
788
+ wrapReducers(spec) {
789
+ this.refuseUnqueryableReducers(spec);
790
+ let s = spec;
791
+ for (const b of this.bindings) if (b.wrapReducers) s = b.wrapReducers(s);
792
+ return s;
793
+ }
794
+ /**
795
+ * Deliberate export-layer redaction (#629 Task 9's posture consumer):
796
+ * for every OWN field the decoded record carries, if the covering
797
+ * binding's posture declares `exportable: false` (classified today;
798
+ * money/i18n/blob are all `true`), replace the value with
799
+ * {@link EXPORT_REDACTION_MARKER} — the same `'[sealed]'` string
800
+ * `SealedHandle.toJSON()` (`kernel/types.ts`) already emits, so this is
801
+ * byte-parity with today's accidental redaction, now independent of the
802
+ * field's runtime shape. `SealedHandle.toJSON()` stays untouched as
803
+ * defense-in-depth: a record read via `collection.get()` and
804
+ * JSON.stringify'd outside `exportStream()` still gets the accident's
805
+ * redaction on its own. Never mutates the input; returns a new object
806
+ * only when a field was actually redacted.
807
+ */
808
+ redactForExport(record) {
809
+ let out;
810
+ for (const field of Object.keys(record)) {
811
+ if (this.postureFor(field)?.exportable === false) {
812
+ out ??= { ...record };
813
+ out[field] = EXPORT_REDACTION_MARKER;
814
+ }
815
+ }
816
+ return out ?? record;
817
+ }
818
+ /**
819
+ * Shared fold over a subset of `this.bindings`: runs each binding's
820
+ * `erase`, concatenating shredded/retainedShared counts and residue.
821
+ * Consults `posture.forgettable` (#629 Task 10) — a binding declaring
822
+ * `forgettable: false` is skipped even if it defines `erase` (none does
823
+ * today; a future non-forgettable binding is supported without a brand check).
824
+ */
825
+ async foldErase(ctx, bindings) {
826
+ let shredded = 0;
827
+ let retainedShared = 0;
828
+ const residue = [];
829
+ for (const b of bindings) {
830
+ if (!b.erase || b.posture.forgettable === false) continue;
831
+ const report = await b.erase(ctx);
832
+ shredded += report.shredded;
833
+ retainedShared += report.retainedShared ?? 0;
834
+ residue.push(...report.residue);
835
+ }
836
+ return retainedShared > 0 ? { shredded, residue, retainedShared } : { shredded, residue };
837
+ }
838
+ /** `forget()`'s per-ref erasure door: folds every binding's `erase`. */
839
+ async erase(ctx) {
840
+ return this.foldErase(ctx, this.bindings);
841
+ }
842
+ /**
843
+ * `forget()`'s SEALED-posture-only erase fold (#629 Task 10, `Collection._onViaErase`'s
844
+ * one caller) — classified today; metadata-filtered on
845
+ * `posture.encryptedAtRest`, not brand-checked. `undefined` when no
846
+ * sealed-posture binding is compiled in — `vault.ts` then falls back to
847
+ * its own bare-`sensitive` classification, which no via binding covers.
848
+ */
849
+ async eraseSealed(ctx) {
850
+ const sealed = this.bindings.filter((b) => b.posture.encryptedAtRest === "sealed");
851
+ return sealed.length === 0 ? void 0 : this.foldErase(ctx, sealed);
852
+ }
853
+ /** True iff any binding implements decodeResults (query fast-path gating). */
854
+ get hasResultDecode() {
855
+ return this.bindings.some((b) => b.decodeResults !== void 0);
856
+ }
857
+ /**
858
+ * True iff any binding declares an at-rest hook (`encodeAtRest`/
859
+ * `decodeAtRest`) — the codec boundary's async-stack gate (#629 Task 3
860
+ * consults this to choose between the hook path and today's inline
861
+ * sealed-slot path; a stack with only sync hooks, e.g. money-only, stays
862
+ * `false`).
863
+ */
864
+ get hasAtRestHooks() {
865
+ return this.bindings.some((b) => b.encodeAtRest !== void 0 || b.decodeAtRest !== void 0);
866
+ }
867
+ /**
868
+ * Fold every binding's `describeFragment()` into one `brand -> fragment`
869
+ * map (#650 Task 7 — the first-ever consumer; `describeFragment` was
870
+ * declared at `via/index.ts:136` since #623 with zero callers until this task).
871
+ * `undefined` when no compiled binding implements it. Consumed by
872
+ * `Collection.describe()`/`describeAsync()`, threaded to `buildDescription`
873
+ * as `BuildDescriptionInput.viaFragments`.
874
+ */
875
+ describeFragments() {
876
+ let out;
877
+ for (const b of this.bindings) {
878
+ const f = b.describeFragment?.();
879
+ if (f !== void 0) {
880
+ out ??= {};
881
+ out[b.brand] = f;
882
+ }
883
+ }
884
+ return out;
885
+ }
886
+ };
887
+ var EXPORT_REDACTION_MARKER = "[sealed]";
888
+ function exportRedact(coll, record) {
889
+ if (record === null || typeof record !== "object") return record;
890
+ const via2 = coll._via;
891
+ return via2 ? via2.redactForExport(record) : record;
892
+ }
893
+
894
+ // src/kernel/collection-config.ts
895
+ function computedEntryParts(entry) {
896
+ if (typeof entry === "function") return { fn: entry, mode: "materialized" };
897
+ return { fn: entry.fn, ...entry.deps !== void 0 ? { deps: entry.deps } : {}, mode: entry.mode ?? "materialized" };
898
+ }
899
+ function unifyComputedFields(opts, viaComputedFields) {
900
+ return { ...opts.computed ?? {}, ...viaComputedFields ?? {} };
901
+ }
902
+ function compileVias(opts, classifiedGuardCtx, eraseCfgOut) {
903
+ const { moneyFields, i18nFields, dictKeyFields, computedFields, lookupFields } = mergeViaFields(opts);
904
+ const allComputedFields = unifyComputedFields(opts, computedFields);
905
+ guardCrossBindingFieldCollisions({
906
+ moneyFields,
907
+ i18nFields,
908
+ dictKeyFields,
909
+ lookupFields,
910
+ classifiedFields: opts.classifiedFields !== void 0 ? resolveClassifiedFields(opts.name, opts.classifiedFields).byField : void 0,
911
+ blobFields: opts.blobFields,
912
+ computed: allComputedFields
913
+ });
914
+ const bindings = [];
915
+ const virtualFields = /* @__PURE__ */ new Map();
916
+ for (const [field, entry] of Object.entries(allComputedFields)) {
917
+ const parts = computedEntryParts(entry);
918
+ if (parts.mode === "virtual") {
919
+ virtualFields.set(field, { _viaBrand: "computed", fn: parts.fn, mode: "virtual", ...parts.deps !== void 0 ? { deps: parts.deps } : {} });
920
+ }
921
+ }
922
+ if (moneyFields) {
923
+ const virtualMoney = resolveVirtualMoneyFields(Object.keys(moneyFields), (f) => virtualFields.has(f));
924
+ bindings.push(viaBinder("money")({ moneyFields, ...virtualMoney.size > 0 ? { virtualMoneyFields: virtualMoney } : {} }));
925
+ }
926
+ if (i18nFields || dictKeyFields) {
927
+ const densify = i18nFields ? Object.fromEntries(
928
+ Object.entries(i18nFields).filter(([, d]) => d.options.densifyOnWrite === true)
929
+ ) : {};
930
+ const i18nDensifyFields = Object.keys(densify).length > 0 ? densify : void 0;
931
+ bindings.push(viaBinder("i18n")({
932
+ ...i18nFields !== void 0 ? { i18nFields } : {},
933
+ ...dictKeyFields !== void 0 ? { dictKeyFields } : {},
934
+ ...i18nDensifyFields !== void 0 ? { i18nDensifyFields } : {},
935
+ strategy: opts.strategies.i18n,
936
+ ...opts.defaultLocale !== void 0 ? { defaultLocale: opts.defaultLocale } : {},
937
+ ...opts.autoTranslateHook !== void 0 ? { autoTranslateHook: opts.autoTranslateHook } : {},
938
+ ...opts.dictLabelResolver !== void 0 ? { dictLabelResolver: opts.dictLabelResolver } : {},
939
+ ...opts.i18nPutValidator !== void 0 ? { i18nPutValidator: opts.i18nPutValidator } : {},
940
+ collectionName: opts.name
941
+ }));
942
+ }
943
+ if (lookupFields !== void 0) {
944
+ bindings.push(viaBinder("lookup")({
945
+ lookupFields,
946
+ ...opts.lookupLabelResolver !== void 0 ? { lookupLabelResolver: opts.lookupLabelResolver } : {},
947
+ ...opts.getLookupBacking !== void 0 ? { getLookupBacking: opts.getLookupBacking } : {},
948
+ ...opts.membership !== void 0 ? { membership: opts.membership } : {},
949
+ ...opts.getAltIndex !== void 0 ? { getAltIndex: opts.getAltIndex } : {},
950
+ ...opts.snapshotFor !== void 0 ? { snapshotFor: opts.snapshotFor } : {},
951
+ collectionName: opts.name
952
+ }));
953
+ }
954
+ if (opts.classifiedFields !== void 0) {
955
+ const classifiedCfg = {
956
+ entries: opts.classifiedFields,
957
+ collectionName: opts.name,
958
+ guardCtx: classifiedGuardCtx
959
+ };
960
+ if (eraseCfgOut) eraseCfgOut.classified = classifiedCfg;
961
+ bindings.push(viaBinder("classified")(classifiedCfg));
962
+ }
963
+ if (opts.blobFields !== void 0) {
964
+ bindings.push(viaBinder("blob")({
965
+ fields: opts.blobFields,
966
+ collectionName: opts.name
967
+ }));
968
+ }
969
+ if (virtualFields.size > 0) {
970
+ bindings.push(viaBinder("computed")({ virtualFields }));
971
+ }
972
+ return bindings;
973
+ }
974
+ function resolveVirtualMoneyFields(moneyFieldNames, isVirtual) {
975
+ const out = /* @__PURE__ */ new Set();
976
+ for (const field of moneyFieldNames) if (isVirtual(field)) out.add(field);
977
+ return out;
978
+ }
979
+ function collectKnownFieldNames(parts) {
980
+ return /* @__PURE__ */ new Set([
981
+ ...Object.keys(parts.moneyFields ?? {}),
982
+ ...Object.keys(parts.i18nFields ?? {}),
983
+ ...Object.keys(parts.dictKeyFields ?? {}),
984
+ ...Object.keys(parts.classifiedFields ?? {}),
985
+ ...Object.keys(parts.computed ?? {}),
986
+ ...Object.keys(parts.lookupFields ?? {})
987
+ ]);
988
+ }
989
+ var EMPTY_KNOWN_FIELDS = /* @__PURE__ */ new Set();
990
+ function resolveComputedEdges(collectionName, computed, hasClassifiedFields, knownFields = EMPTY_KNOWN_FIELDS) {
991
+ if (!computed) return [];
992
+ const edges = [];
993
+ for (const [field, entry] of Object.entries(computed)) {
994
+ const parts = computedEntryParts(entry);
995
+ const deps = parts.deps;
996
+ if (deps === void 0) {
997
+ if (hasClassifiedFields) {
998
+ throw new ValidationError(
999
+ `Collection "${collectionName}": computed field "${field}" has no declared \`deps\` and the collection declares classified fields \u2014 an opaque computed function could silently copy a classified field's plaintext into an ordinary, unredacted field. Declare \`deps\` naming the source fields it reads, e.g. computed: { ${field}: { fn, deps: [...] } } or via(computed(fn, { deps: [...] })).`
1000
+ );
1001
+ }
1002
+ continue;
1003
+ }
1004
+ if (deps.length === 0) {
1005
+ throw new ValidationError(`Collection "${collectionName}": computed field "${field}"'s \`deps\` must be non-empty.`);
1006
+ }
1007
+ for (const dep of deps) {
1008
+ if (typeof dep !== "string" || dep.length === 0) {
1009
+ throw new ValidationError(`Collection "${collectionName}": computed field "${field}"'s \`deps\` entries must be non-empty strings.`);
1010
+ }
1011
+ if (hasClassifiedFields && !knownFields.has(dep)) {
1012
+ throw new ValidationError(
1013
+ `Collection "${collectionName}": computed field "${field}"'s \`deps\` entry "${dep}" does not name a declared field, and the collection declares classified fields \u2014 an opaque computed function could silently copy a classified field's plaintext into an ordinary, unredacted field via a mistyped/unknown dep name. Declare \`deps\` naming only known fields (money/i18n/dictKey/classified/computed) \u2014 check "${dep}" for a typo.`
1014
+ );
1015
+ }
1016
+ }
1017
+ edges.push({
1018
+ target: { collection: collectionName, field },
1019
+ sources: deps.map((d) => ({ collection: collectionName, field: d })),
1020
+ grain: parts.mode === "virtual" ? "virtual" : "record"
1021
+ });
1022
+ }
1023
+ return edges;
1024
+ }
1025
+ function resolveViaDepsEdges(collectionName, bindings, knownFields) {
1026
+ const edges = [];
1027
+ for (const binding of bindings) {
1028
+ if (!binding.deps || binding.deps.length === 0) continue;
1029
+ for (const dep of binding.deps) {
1030
+ if (!knownFields.has(dep)) {
1031
+ throw new ValidationError(
1032
+ `Collection "${collectionName}": via binding "${binding.brand}" deps references undeclared field "${dep}".`
1033
+ );
1034
+ }
1035
+ }
1036
+ const sources = binding.deps.map((d) => ({ collection: collectionName, field: d }));
1037
+ for (const field of knownFields) {
1038
+ if (binding.covers?.(field)) edges.push({ target: { collection: collectionName, field }, sources });
1039
+ }
1040
+ }
1041
+ return edges;
1042
+ }
1043
+ function resolveCollectionConfig(opts) {
1044
+ if (opts.embeddings && opts.crdt) {
1045
+ throw new Error(
1046
+ `Collection "${opts.name}": embeddings are not supported on CRDT collections (L2). Use a non-CRDT collection for semantic search.`
1047
+ );
1048
+ }
1049
+ if (opts.sensitive && opts.sensitive.length > 0 && opts.crdt) {
1050
+ throw new Error(
1051
+ `Collection "${opts.name}": sensitive (structural group-encryption) is not supported on CRDT collections \u2014 the CRDT write path bypasses per-field sealing, so the fields would be stored in the ordinary encrypted body with no \`_sealed\` slot and no per-field key. Use a non-CRDT collection for sealed fields.`
1052
+ );
1053
+ }
1054
+ if (opts.tiers && opts.tiers.length > 0 && opts.blobFields !== void 0 && Object.keys(opts.blobFields).length > 0 && opts.perRecordKeys !== true) {
1055
+ throw new UnsupportedTierCompositionError(
1056
+ "blobs",
1057
+ `Collection "${opts.name}": tiered collections that declare blobFields require \`perRecordKeys: true\` \u2014 legacy (non-perRecordKeys) blobs have no per-blob content CEK and cannot be tier-isolated on elevate/demote.`
1058
+ );
1059
+ }
1060
+ if (opts.tiers && opts.tiers.length > 0 && opts.blobFields !== void 0) {
1061
+ for (const [field, policy] of Object.entries(opts.blobFields)) {
1062
+ if (policy?.external && policy.public === true) {
1063
+ throw new UnsupportedTierCompositionError(
1064
+ "blobs",
1065
+ `Collection "${opts.name}": blob field "${field}" cannot be both \`external: true, public: true\` and declared on a tiered collection \u2014 the object key is deterministic and its bytes are world-readable by design, so tier-invisibility can never be enforced for it once elevated. Use a private/presigned external field (\`public\` omitted or \`false\`) or move this field to a non-tiered collection.`
1066
+ );
1067
+ }
1068
+ }
1069
+ }
1070
+ if (opts.tiers && opts.tiers.length > 0 && opts.encrypted === false) {
1071
+ throw new UnsupportedTierCompositionError(
1072
+ "plaintext",
1073
+ `Collection "${opts.name}": tiers are per-tier ENCRYPTION keys \u2014 a plaintext collection (\`encrypted: false\`) has nothing to re-key, so \`putAtTier\`/\`elevate\` would encrypt/decrypt incoherently. Use an encrypted collection.`
1074
+ );
1075
+ }
1076
+ if (opts.tiers && opts.tiers.length > 0 && opts.crdt !== void 0 && ((opts.derivationSource?.registry().strategiesForSource(opts.name).length ?? 0) > 0 || (opts.materializedViewSource?.registry().mvsForSource(opts.name).length ?? 0) > 0)) {
1077
+ throw new UnsupportedTierCompositionError(
1078
+ "crdt-derivation",
1079
+ `Collection "${opts.name}": tiers + crdt cannot be combined with this collection acting as a derivation/rollup source (#739) \u2014 the tier-aware pre-move decode \`syncDerived\` uses on elevate()/demote() does not resolve CRDT state, so a registered derivation/rollup reads raw CrdtState instead of the record and silently no-ops. Use a non-CRDT collection for a tiered derivation/rollup source, or move the derivation off this collection.`
1080
+ );
1081
+ }
1082
+ const effectiveViaFields = mergeViaFields(opts);
1083
+ const resolvedClassified = opts.classifiedFields !== void 0 ? resolveClassifiedFields(opts.name, opts.classifiedFields) : void 0;
1084
+ const allComputed = unifyComputedFields(opts, effectiveViaFields.computedFields);
1085
+ const materializedComputed = {};
1086
+ for (const [field, entry] of Object.entries(allComputed)) {
1087
+ if (computedEntryParts(entry).mode !== "virtual") materializedComputed[field] = entry;
1088
+ }
1089
+ let mergedComputed = Object.keys(materializedComputed).length > 0 ? materializedComputed : void 0;
1090
+ if (resolvedClassified !== void 0) {
1091
+ for (const key of Object.keys(allComputed)) {
1092
+ if (resolvedClassified.riderComputed[key] !== void 0) {
1093
+ throw new ClassifiedConfigError(opts.name, `computed field "${key}" collides with a rider companion`);
1094
+ }
1095
+ }
1096
+ mergedComputed = { ...resolvedClassified.riderComputed, ...materializedComputed };
1097
+ }
1098
+ let deterministicFields;
1099
+ if (opts.deterministicFields && opts.deterministicFields.length > 0) {
1100
+ if (opts.acknowledgeDeterministicRisk !== true) {
1101
+ throw new Error(
1102
+ `Collection "${opts.name}": deterministicFields requires \`acknowledgeDeterministicRisk: true\`. Deterministic encryption leaks equality between records \u2014 two records with the same field value produce identical ciphertexts visible to anyone with store access. If that trade-off is acceptable for your threat model, set \`acknowledgeDeterministicRisk: true\` to enable.`
1103
+ );
1104
+ }
1105
+ deterministicFields = Object.freeze(new Set(opts.deterministicFields));
1106
+ } else {
1107
+ deterministicFields = null;
1108
+ }
1109
+ const guardIndexedFields = /* @__PURE__ */ new Set();
1110
+ for (const ix of opts.indexes ?? []) {
1111
+ if (typeof ix === "string") guardIndexedFields.add(ix);
1112
+ else if (Array.isArray(ix)) for (const f of ix) guardIndexedFields.add(f);
1113
+ else for (const f of ix.fields) guardIndexedFields.add(f);
1114
+ }
1115
+ const embeddingSources = opts.embeddings === void 0 ? [] : typeof opts.embeddings.source === "string" ? [opts.embeddings.source] : [...opts.embeddings.source];
1116
+ const classifiedGuardCtx = {
1117
+ perRecordKeys: opts.perRecordKeys === true,
1118
+ crdt: opts.crdt !== void 0,
1119
+ hasConflictPolicy: opts.conflictPolicy !== void 0,
1120
+ storeCiphertext: opts.encrypted,
1121
+ deterministicFields,
1122
+ indexedFields: guardIndexedFields,
1123
+ textIndexFields: new Set(opts.textIndexes ?? []),
1124
+ vectorSourceFields: new Set(embeddingSources),
1125
+ subjectKeyField: opts.subjectKeyField,
1126
+ bareSensitiveFields: new Set(opts.sensitive ?? []),
1127
+ acknowledgeEquatableRisk: opts.acknowledgeEquatableRisk === true
1128
+ };
1129
+ if (resolvedClassified !== void 0) {
1130
+ guardClassifiedCompat(opts.name, resolvedClassified.byField, classifiedGuardCtx);
1131
+ }
1132
+ const classifiedSensitive = resolvedClassified === void 0 ? [] : Object.entries(resolvedClassified.byField).filter(([, s]) => s.storage === "recoverable").map(([f]) => f);
1133
+ const sensitiveList = [...opts.sensitive ?? [], ...classifiedSensitive];
1134
+ const sensitiveFields = sensitiveList.length > 0 ? Object.freeze(new Set(sensitiveList)) : Object.freeze(/* @__PURE__ */ new Set());
1135
+ const vdigEntries = resolvedClassified === void 0 ? [] : Object.entries(resolvedClassified.byField).filter(([, s]) => s.storage === "digest-only").map(([f, s]) => [f, {
1136
+ normalize: s.verifyNormalize ?? "password",
1137
+ notLastN: s.notLastN ?? 0,
1138
+ equatable: s.equatable === true,
1139
+ ...s.rotateDays !== void 0 ? { rotateDays: s.rotateDays } : {}
1140
+ }]);
1141
+ const vdigFields = vdigEntries.length > 0 ? new Map(vdigEntries) : null;
1142
+ const perRecordCek = opts.perRecordKeys === true;
1143
+ const cekCache = perRecordCek ? new Lru({ maxRecords: 4096 }) : null;
1144
+ const viaEraseCfgOut = {};
1145
+ const via2 = ViaPipeline.build(compileVias(opts, classifiedGuardCtx, viaEraseCfgOut));
1146
+ const knownFields = collectKnownFieldNames({
1147
+ moneyFields: effectiveViaFields.moneyFields,
1148
+ i18nFields: effectiveViaFields.i18nFields,
1149
+ dictKeyFields: effectiveViaFields.dictKeyFields,
1150
+ classifiedFields: resolvedClassified?.byField,
1151
+ computed: allComputed,
1152
+ lookupFields: effectiveViaFields.lookupFields
1153
+ });
1154
+ const computedEdges = resolveComputedEdges(opts.name, allComputed, resolvedClassified !== void 0, knownFields);
1155
+ const viaDepsEdges = resolveViaDepsEdges(opts.name, via2?.bindings ?? [], knownFields);
1156
+ return {
1157
+ adapter: opts.adapter,
1158
+ vault: opts.vault,
1159
+ name: opts.name,
1160
+ keyring: opts.keyring,
1161
+ storeCiphertext: opts.encrypted,
1162
+ ramCiphertext: opts.ramCiphertext ?? false,
1163
+ emitter: opts.emitter,
1164
+ writeQueue: opts.writeQueue,
1165
+ schemaUpdateGate: opts.schemaUpdateGate,
1166
+ schemaFence: opts.schemaFence,
1167
+ writeHooks: opts.writeHooks,
1168
+ subsystemBus: opts.subsystemBus,
1169
+ activeTxId: opts.activeTxId,
1170
+ strategies: opts.strategies,
1171
+ objectStore: opts.objectStore,
1172
+ blobFields: opts.blobFields,
1173
+ reconcileOnOpen: opts.reconcileOnOpen ?? "off",
1174
+ getDEK: opts.getDEK,
1175
+ onDirty: opts.onDirty,
1176
+ tabCoordinated: opts.tabCoordinated,
1177
+ historyConfig: opts.historyConfig ?? { enabled: true },
1178
+ historyConfigExplicit: opts.historyConfigExplicit ?? false,
1179
+ schema: opts.schema,
1180
+ ledger: opts.ledger,
1181
+ refEnforcer: opts.refEnforcer,
1182
+ joinResolver: opts.joinResolver,
1183
+ i18nFields: effectiveViaFields.i18nFields,
1184
+ textIndexes: opts.textIndexes,
1185
+ embeddings: opts.embeddings,
1186
+ vectorSet: opts.embeddings ? new VectorSet() : void 0,
1187
+ dictKeyFields: effectiveViaFields.dictKeyFields,
1188
+ lookupFields: effectiveViaFields.lookupFields,
1189
+ // #650 Task 6 — the sync join-dressing hook (#626 retirement, spec §5);
1190
+ // `undefined` when this collection declares neither i18nText nor lookup
1191
+ // fields, matching today's `i18nFields`-absent JoinableSource shape.
1192
+ presentForJoin: buildPresentForJoin(effectiveViaFields.i18nFields, effectiveViaFields.lookupFields, opts.snapshotFor),
1193
+ fieldMeta: opts.fieldMeta,
1194
+ meta: opts.meta,
1195
+ _refs: opts.declaredRefs ?? {},
1196
+ via: via2,
1197
+ classifiedEraseCfg: viaEraseCfgOut.classified,
1198
+ moneyFields: effectiveViaFields.moneyFields,
1199
+ classified: resolvedClassified,
1200
+ classifiedGuardCtx,
1201
+ computed: mergedComputed,
1202
+ computedEdges,
1203
+ viaDepsEdges,
1204
+ // #638 Task 7 — every declared computed field name (both modes, both surfaces); the
1205
+ // reconcile path's cross-call depsless-computed leak-guard memory
1206
+ // (`via/graph-wiring.ts#registerCollectionGraphSources`) reads this instead of
1207
+ // `Object.keys(opts.computed ?? {})` alone, so a via(computed(...))-declared field
1208
+ // participates in that guard identically to a sugar-declared one.
1209
+ computedFieldNames: Object.keys(allComputed),
1210
+ dictLabelResolver: opts.dictLabelResolver,
1211
+ getDictionary: opts.getDictionary,
1212
+ i18nPutValidator: opts.i18nPutValidator,
1213
+ autoTranslateHook: opts.autoTranslateHook,
1214
+ defaultLocale: opts.defaultLocale,
1215
+ crdtMode: opts.crdt,
1216
+ syncAdapter: opts.syncAdapter,
1217
+ onAccess: opts.onAccess,
1218
+ derivationSource: opts.derivationSource,
1219
+ materializedViewSource: opts.materializedViewSource,
1220
+ graphDispatch: opts.graphDispatch,
1221
+ tiers: opts.tiers && opts.tiers.length > 0 ? new Set(opts.tiers) : null,
1222
+ tierMode: opts.tierMode ?? "invisibility",
1223
+ blobTierPolicy: opts.blobTierPolicy ?? "isolate",
1224
+ onCrossTierAccess: opts.onCrossTierAccess,
1225
+ addSubjectRef: opts.addSubjectRef,
1226
+ deterministicFields,
1227
+ sensitiveFields,
1228
+ vdigFields,
1229
+ perRecordCek,
1230
+ cekCache,
1231
+ provenance: opts.provenance === true
1232
+ };
1233
+ }
1234
+
1235
+ // src/kernel/via/graph.ts
1236
+ var DEFAULT_POSTURE = { encryptedAtRest: "envelope", queryable: "full", exportable: true, forgettable: false };
1237
+ var QUERYABLE_RANK = {
1238
+ none: 0,
1239
+ "det-exact": 1,
1240
+ ordered: 2,
1241
+ full: 3
1242
+ };
1243
+ function foldPosture(a, b) {
1244
+ return {
1245
+ encryptedAtRest: a.encryptedAtRest === "sealed" || b.encryptedAtRest === "sealed" ? "sealed" : "envelope",
1246
+ queryable: QUERYABLE_RANK[a.queryable] <= QUERYABLE_RANK[b.queryable] ? a.queryable : b.queryable,
1247
+ exportable: a.exportable && b.exportable,
1248
+ forgettable: a.forgettable || b.forgettable
1249
+ };
1250
+ }
1251
+ function foldWildcardSecurity(base, contributor) {
1252
+ return {
1253
+ encryptedAtRest: base.encryptedAtRest === "sealed" || contributor.encryptedAtRest === "sealed" ? "sealed" : "envelope",
1254
+ queryable: base.queryable,
1255
+ exportable: base.exportable && contributor.exportable,
1256
+ forgettable: base.forgettable || contributor.forgettable
1257
+ };
1258
+ }
1259
+ var FOLDED_KINDS = /* @__PURE__ */ new Set(["derivation", "rollup", "mv", "overlay"]);
1260
+ function isDefaultPosture(p) {
1261
+ return p.encryptedAtRest === DEFAULT_POSTURE.encryptedAtRest && p.queryable === DEFAULT_POSTURE.queryable && p.exportable === DEFAULT_POSTURE.exportable && p.forgettable === DEFAULT_POSTURE.forgettable;
1262
+ }
1263
+ var SEP = "\0";
1264
+ var EMPTY_SET = /* @__PURE__ */ new Set();
1265
+ function nodeId(ref) {
1266
+ return `${ref.collection}${SEP}${ref.field}`;
1267
+ }
1268
+ function displayNodeId(id) {
1269
+ const sep = id.indexOf(SEP);
1270
+ return `${id.slice(0, sep)}.${id.slice(sep + 1)}`;
1271
+ }
1272
+ var ViaGraph = class {
1273
+ /** Declared source-field postures (registerField), keyed by node id. */
1274
+ _posture = /* @__PURE__ */ new Map();
1275
+ /** Every derived target's registration, keyed by the target's node id. */
1276
+ _in = /* @__PURE__ */ new Map();
1277
+ /** source node id -> derived edges that depend on it (dispatch/erasure), each carrying
1278
+ * its own registration's `kind` (#678 — see {@link OutEdge}). */
1279
+ _out = /* @__PURE__ */ new Map();
1280
+ /** Memoized effective posture per derived target node id. */
1281
+ _effectiveCache = /* @__PURE__ */ new Map();
1282
+ /** Memoized whole-collection security-axes fold for `'*'` wildcard LEAF nodes (#642),
1283
+ * keyed by collection name — see {@link _wildcardContribution}. Cleared alongside
1284
+ * `_effectiveCache` on every `registerField`/`registerDerived` (a later-registered
1285
+ * field must re-fold on the next read — registration ordering is free). */
1286
+ _wildcardCache = /* @__PURE__ */ new Map();
1287
+ /** Collections with at least one classified field (#638 Task 2 fix wave 2,
1288
+ * Finding I1 — the reconcile path's combined-state leak guard memory). */
1289
+ _classifiedCollections = /* @__PURE__ */ new Set();
1290
+ /** Computed field names declared with no `deps` entry, per collection
1291
+ * (Finding I1 — such a field registers no edge when no classified field is
1292
+ * present yet, so a LATER, separate reconcile call attaching classifiedFields
1293
+ * still needs to see it regardless of declaration order). */
1294
+ _depslessComputed = /* @__PURE__ */ new Map();
1295
+ /** Declare a source field's posture (money/i18n/classified/plain). Plain fields
1296
+ * default to `DEFAULT_POSTURE`; a later declaration for the same node wins-first (idempotent). */
1297
+ registerField(collection, field, posture) {
1298
+ const id = nodeId({ collection, field });
1299
+ if (this._posture.has(id)) return;
1300
+ this._posture.set(id, posture);
1301
+ this._effectiveCache.clear();
1302
+ this._wildcardCache.clear();
1303
+ }
1304
+ /** A derived target depends on `sources` (may be cross-collection). `kind`/`grain`
1305
+ * drive dispatch + erasure semantics; sources drive taint. Re-registering the same
1306
+ * target replaces `_in` but does not prune stale `_out` edges — callers must
1307
+ * register each target at most once per graph lifetime. `onDelete`/`keyField` (#650 Task 5)
1308
+ * are meaningful only for `kind === 'ref'` edges — {@link referencingEdgesOf} reads them back. */
1309
+ registerDerived(target, sources, kind, grain, onDelete, keyField) {
1310
+ const id = nodeId(target);
1311
+ this._in.set(id, {
1312
+ target,
1313
+ sources,
1314
+ kind,
1315
+ grain,
1316
+ ...onDelete !== void 0 ? { onDelete } : {},
1317
+ ...keyField !== void 0 ? { keyField } : {}
1318
+ });
1319
+ for (const source of sources) {
1320
+ const sourceId = nodeId(source);
1321
+ const outEdge = { target, kind };
1322
+ const dependents = this._out.get(sourceId);
1323
+ if (dependents) dependents.push(outEdge);
1324
+ else this._out.set(sourceId, [outEdge]);
1325
+ }
1326
+ this._effectiveCache.clear();
1327
+ this._wildcardCache.clear();
1328
+ }
1329
+ /** Whether `target` already has a registered in-edge — lets a caller skip
1330
+ * re-registering the same target (#638 Task 2 fix wave 2, Finding I2i:
1331
+ * `registerDerived`'s at-most-once contract must hold across repeated
1332
+ * identical `vault.collection()` calls, not just within a single one). */
1333
+ hasDerived(target) {
1334
+ return this._in.has(nodeId(target));
1335
+ }
1336
+ /** Mark/query a collection as having declared at least one classified field. */
1337
+ markClassified(collection) {
1338
+ this._classifiedCollections.add(collection);
1339
+ }
1340
+ isClassified(collection) {
1341
+ return this._classifiedCollections.has(collection);
1342
+ }
1343
+ /** Mark/query a collection's depsless (no declared `deps`) computed
1344
+ * field names — see `_depslessComputed`'s doc comment above. */
1345
+ markDepslessComputed(collection, field) {
1346
+ let set = this._depslessComputed.get(collection);
1347
+ if (!set) {
1348
+ set = /* @__PURE__ */ new Set();
1349
+ this._depslessComputed.set(collection, set);
1350
+ }
1351
+ set.add(field);
1352
+ }
1353
+ depslessComputedFields(collection) {
1354
+ return this._depslessComputed.get(collection) ?? EMPTY_SET;
1355
+ }
1356
+ /** Every field name the graph already has memory of for `collection` — from an
1357
+ * EARLIER, separate `vault.collection()` call (registered postures, derived
1358
+ * targets, depsless-computed names) — regardless of which via feature declared
1359
+ * it. #645 — `via/graph-wiring.ts`'s reconcile-path `knownFields` universe
1360
+ * (`collectKnownFieldNames`) is scoped to THIS call's own options only, so a
1361
+ * computed field attached in a LATER call whose `deps` correctly names a field
1362
+ * declared in an EARLIER call was spuriously refused as "unknown"; this method
1363
+ * lets that call site union in the graph's cross-call memory. Excludes the `'*'`
1364
+ * wildcard target (an overlay/derivation whole-record fold node, never a real
1365
+ * record field — see {@link registerDerived}'s doc comment). */
1366
+ knownFieldNames(collection) {
1367
+ const out = /* @__PURE__ */ new Set();
1368
+ const prefix = `${collection}${SEP}`;
1369
+ for (const id of this._posture.keys()) {
1370
+ if (id.startsWith(prefix)) out.add(id.slice(prefix.length));
1371
+ }
1372
+ for (const edge of this._in.values()) {
1373
+ if (edge.target.collection === collection && edge.target.field !== "*") out.add(edge.target.field);
1374
+ }
1375
+ const depsless = this._depslessComputed.get(collection);
1376
+ if (depsless) for (const field of depsless) out.add(field);
1377
+ return out;
1378
+ }
1379
+ /** Reject cycles at declare time (vault open). Throws `DerivationCycleError` for a
1380
+ * derivation/rollup/computed cycle, `MaterializedViewCycleError` for an MV cycle —
1381
+ * same classes + message shape the registries throw today (behavior lock). */
1382
+ assertAcyclic() {
1383
+ const visited = /* @__PURE__ */ new Set();
1384
+ const stack = [];
1385
+ const notRefEdge = (entry) => entry.kind !== "ref";
1386
+ const neighboursOf = (id) => {
1387
+ const own = (this._out.get(id) ?? []).filter(notRefEdge).map((entry) => entry.target);
1388
+ const sep = id.indexOf(SEP);
1389
+ if (id.slice(sep + 1) === "*") return own;
1390
+ const wildcard = (this._out.get(`${id.slice(0, sep)}${SEP}*`) ?? []).filter(notRefEdge).map((entry) => entry.target);
1391
+ if (wildcard.length === 0) return own;
1392
+ return [...own, ...wildcard];
1393
+ };
1394
+ const visit = (id) => {
1395
+ const idx = stack.indexOf(id);
1396
+ if (idx !== -1) {
1397
+ const cycle = stack.slice(idx).concat(id);
1398
+ const isMv = cycle.some((cycleId) => this._in.get(cycleId)?.kind === "mv");
1399
+ const path = cycle.map(displayNodeId);
1400
+ if (isMv) throw new MaterializedViewCycleError(path);
1401
+ throw new DerivationCycleError(path);
1402
+ }
1403
+ if (visited.has(id)) return;
1404
+ stack.push(id);
1405
+ for (const dependent of neighboursOf(id)) visit(nodeId(dependent));
1406
+ stack.pop();
1407
+ visited.add(id);
1408
+ };
1409
+ for (const id of this._out.keys()) visit(id);
1410
+ }
1411
+ /** A leaf (non-derived) node's own posture contribution: its declared posture,
1412
+ * or `DEFAULT_POSTURE` if never declared via `registerField`. */
1413
+ _declaredPosture(id) {
1414
+ return this._posture.get(id) ?? DEFAULT_POSTURE;
1415
+ }
1416
+ /** A node's posture contribution when folded into a dependent: recurse if it is itself
1417
+ * derived; else its declared/default posture — UNLESS it is a `'*'` LEAF node consumed
1418
+ * by a folded formula kind (#642, `derivation|rollup|mv|overlay`), in which case it
1419
+ * contributes its collection's whole-record security fold ({@link _wildcardContribution}).
1420
+ * `kind` is the CONSUMING edge's kind, threaded from {@link _computeEffective}. `'ref'`
1421
+ * edges (and the provenance-only untyped call, `kind` left `undefined`) keep `'*'` =
1422
+ * identity — the phase-D lookup reliance (`via/lookup/registry.ts:392-397`) that a
1423
+ * referencing field must not seal just because its dimension collection has a classified
1424
+ * column. */
1425
+ _contribution(id, kind) {
1426
+ const edge = this._in.get(id);
1427
+ if (edge) return this._computeEffective(id, edge);
1428
+ if (kind !== void 0 && FOLDED_KINDS.has(kind) && id.endsWith(`${SEP}*`)) {
1429
+ return this._wildcardContribution(id.slice(0, -2));
1430
+ }
1431
+ return this._declaredPosture(id);
1432
+ }
1433
+ /** Lazy fold (#642) of a collection's REGISTERED field postures on the security axes only
1434
+ * ({@link foldWildcardSecurity} — sealed-wins encryptedAtRest, AND exportable, OR
1435
+ * forgettable; queryable stays at DEFAULT_POSTURE's 'full', never folded), seeded at
1436
+ * DEFAULT_POSTURE. This is the collection-level posture a `'*'` LEAF node contributes to a
1437
+ * folded-kind formula edge (derivation/rollup/mv/overlay) — see {@link _contribution}. A
1438
+ * plain (unregistered) field contributes nothing (the identity), so the fold is strictly
1439
+ * more conservative than deps-based taint and never hits the KNOWN-LIMIT wall (it names no
1440
+ * fields — seam map §1d). Memoized per collection in `_wildcardCache`. */
1441
+ _wildcardContribution(collection) {
1442
+ const cached = this._wildcardCache.get(collection);
1443
+ if (cached) return cached;
1444
+ let result = DEFAULT_POSTURE;
1445
+ const prefix = `${collection}${SEP}`;
1446
+ for (const [id, posture] of this._posture) {
1447
+ if (!id.startsWith(prefix) || id === `${prefix}*`) continue;
1448
+ result = foldWildcardSecurity(result, posture);
1449
+ }
1450
+ this._wildcardCache.set(collection, result);
1451
+ return result;
1452
+ }
1453
+ _computeEffective(id, edge) {
1454
+ const cached = this._effectiveCache.get(id);
1455
+ if (cached) return cached;
1456
+ let result = DEFAULT_POSTURE;
1457
+ for (const source of edge.sources) {
1458
+ result = foldPosture(result, this._contribution(nodeId(source), edge.kind));
1459
+ }
1460
+ if (edge.grain === "virtual" && result.queryable !== "none") {
1461
+ result = { ...result, queryable: "none" };
1462
+ }
1463
+ this._effectiveCache.set(id, result);
1464
+ return result;
1465
+ }
1466
+ /** Strictest source posture on every axis, per §2. `undefined` when `target` has no
1467
+ * in-edges (not a derived field). Transitive: folds through chained derivations. */
1468
+ effectivePosture(target) {
1469
+ const id = nodeId(target);
1470
+ const edge = this._in.get(id);
1471
+ if (!edge) return void 0;
1472
+ return this._computeEffective(id, edge);
1473
+ }
1474
+ /** Per-collection { field → effectivePosture } overlay the pipeline consumes (Task 3). */
1475
+ taintedPostures(collection) {
1476
+ const out = /* @__PURE__ */ new Map();
1477
+ for (const edge of this._in.values()) {
1478
+ if (edge.target.collection !== collection) continue;
1479
+ out.set(edge.target.field, this._computeEffective(nodeId(edge.target), edge));
1480
+ }
1481
+ return out;
1482
+ }
1483
+ /** Materialized (`grain !== 'virtual'`) derived fields on `collection` whose effective
1484
+ * encryptedAtRest resolves to 'sealed' — the taint-seal set (Task 3). #638 Task 7
1485
+ * makes the `grain !== 'virtual'` filter meaningful: a `computed(fn, { mode: 'virtual' })`
1486
+ * field is never stored (rides the `present` phase, seam map Part 4's money-Formatted/
1487
+ * i18n-Label precedent), so it is EXCLUDED here even when its effective `encryptedAtRest`
1488
+ * folds to `'sealed'` — there is no envelope slot to seal. It still surfaces in
1489
+ * {@link taintedPostures} (query refusal via `postureFor`'s `queryable` clamp above, and
1490
+ * export refusal via `exportable`) — only the AT-REST SEALING ACTION is skipped. */
1491
+ taintSealedFields(collection) {
1492
+ const out = /* @__PURE__ */ new Set();
1493
+ for (const edge of this._in.values()) {
1494
+ if (edge.target.collection !== collection || edge.grain === "virtual") continue;
1495
+ const posture = this._computeEffective(nodeId(edge.target), edge);
1496
+ if (posture.encryptedAtRest === "sealed") out.add(edge.target.field);
1497
+ }
1498
+ return out;
1499
+ }
1500
+ /** Fields on `collection` whose registered edge is `grain === 'virtual'` (#638 Task 7) —
1501
+ * `via/graph-wiring.ts#applyTaintOverlay` intersects this with `exportable === false`
1502
+ * postures to know which virtual fields need PRESENT-TIME (not just export-time)
1503
+ * redaction, since a virtual field's value is only ever materialized inside `present()`. */
1504
+ virtualFields(collection) {
1505
+ const out = /* @__PURE__ */ new Set();
1506
+ for (const edge of this._in.values()) {
1507
+ if (edge.target.collection === collection && edge.grain === "virtual") out.add(edge.target.field);
1508
+ }
1509
+ return out;
1510
+ }
1511
+ /** Per-collection { field → immediate source field names that forced its
1512
+ * effective posture away from `DEFAULT_POSTURE` } — `describe()`'s
1513
+ * provenance (Task 3). Only the DIRECT declared sources are named (not the
1514
+ * ultimate origin several hops up a transitive chain); a source absent
1515
+ * from the result contributed nothing restrictive. */
1516
+ taintProvenance(collection) {
1517
+ const out = /* @__PURE__ */ new Map();
1518
+ for (const edge of this._in.values()) {
1519
+ if (edge.target.collection !== collection) continue;
1520
+ const forcedBy = edge.sources.filter((source) => !isDefaultPosture(this._contribution(nodeId(source)))).map((source) => source.field);
1521
+ if (forcedBy.length > 0) out.set(edge.target.field, forcedBy);
1522
+ }
1523
+ return out;
1524
+ }
1525
+ _targetsDependingOn(collection) {
1526
+ const out = [];
1527
+ for (const edge of this._in.values()) {
1528
+ if (edge.sources.some((source) => source.collection === collection)) {
1529
+ out.push({ target: edge.target, kind: edge.kind, grain: edge.grain });
1530
+ }
1531
+ }
1532
+ return out;
1533
+ }
1534
+ /** Dispatch (Task 4): every derived target triggered by a write to `collection`. Excludes
1535
+ * `'ref'` edges (#650 Task 5 review, folded Minor) — a `'ref'` edge is consulted only by the
1536
+ * delete/forget-time restrict/cascade/nullify path ({@link referencingEdgesOf}), never by the
1537
+ * sync/cutover/restore dispatch wave (`runGraphDispatchWave`); counting it here defeated that
1538
+ * wave's zero-cost early-continue, costing every write to a referenced backing collection an
1539
+ * unconditional decrypt + two no-op dispatch passes. {@link derivedArtifactsOf} (erasure
1540
+ * fanout) still includes `'ref'` edges — the forget path genuinely needs them. */
1541
+ dependentsOf(collection) {
1542
+ return this._targetsDependingOn(collection).filter((edge) => edge.kind !== "ref");
1543
+ }
1544
+ /** Erasure (Task 6): derived artifacts of a forgotten record whose source is `collection`. */
1545
+ derivedArtifactsOf(collection) {
1546
+ return this._targetsDependingOn(collection);
1547
+ }
1548
+ /** Referencing edges pointing AT a backing dimension (delete/forget-time restrict/cascade/
1549
+ * nullify, #650 Task 5) — an O(1) reverse lookup via the existing `_out` map (keyed at the
1550
+ * dimension's wildcard `field:'*'` node, the same convention every whole-collection source
1551
+ * already uses), NEVER a scan across collections or records. `backing` is the collection name
1552
+ * a lookup field's edge was registered against (a reserved dimension's `_dict_<name>`/
1553
+ * `_lookup_<name>` collection name, or a matrix dimension's own collection name). */
1554
+ referencingEdgesOf(backing) {
1555
+ const targets = this._out.get(nodeId({ collection: backing, field: "*" }));
1556
+ if (!targets) return [];
1557
+ const out = [];
1558
+ for (const entry of targets) {
1559
+ if (entry.kind !== "ref") continue;
1560
+ const edge = this._in.get(nodeId(entry.target));
1561
+ if (edge?.onDelete !== void 0) {
1562
+ out.push({ referencing: entry.target, onDelete: edge.onDelete, keyField: edge.keyField ?? "id" });
1563
+ }
1564
+ }
1565
+ return out;
1566
+ }
1567
+ };
1568
+
1569
+ export {
1570
+ ViaPipeline,
1571
+ EXPORT_REDACTION_MARKER,
1572
+ exportRedact,
1573
+ schemaFieldKeys,
1574
+ deriveZodFields,
1575
+ resolveDescribeFieldIds,
1576
+ buildDescription,
1577
+ via,
1578
+ isViaFieldSpec,
1579
+ mergeViaFields,
1580
+ guardReconcileCollisions,
1581
+ computedEntryParts,
1582
+ resolveVirtualMoneyFields,
1583
+ collectKnownFieldNames,
1584
+ resolveComputedEdges,
1585
+ resolveCollectionConfig,
1586
+ DEFAULT_POSTURE,
1587
+ ViaGraph
1588
+ };
1589
+ //# sourceMappingURL=chunk-BWXGSSFX.js.map