@noy-db/hub 0.6.0-pre.5 → 0.6.0-pre.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/codemods/0.4.0-pre.json +40 -0
- package/dist/broker/index.js +3 -3
- package/dist/cargo/index.js +4 -4
- package/dist/{chunk-BA2L5K25.js → chunk-ADW22QSB.js} +3 -3
- package/dist/{chunk-VZUVORWV.js → chunk-BEFVYAR5.js} +2 -2
- package/dist/{chunk-Q2VEFHDQ.js → chunk-GAG7QOVO.js} +26 -1
- package/dist/chunk-GAG7QOVO.js.map +1 -0
- package/dist/{chunk-J5HZUP3M.js → chunk-H73G4XF4.js} +3 -3
- package/dist/{chunk-LJNGRBEG.js → chunk-IMZLOJTK.js} +3 -3
- package/dist/{chunk-WB24CH3C.js → chunk-JRKZTEZZ.js} +36 -6
- package/dist/chunk-JRKZTEZZ.js.map +1 -0
- package/dist/chunk-N35NC4JH.js +123 -0
- package/dist/chunk-N35NC4JH.js.map +1 -0
- package/dist/{chunk-W3AEW5CF.js → chunk-NPP5R7FF.js} +2 -2
- package/dist/{chunk-CXJTWRBD.js → chunk-O2ERS4UJ.js} +2 -2
- package/dist/{chunk-MZ5ZFO2D.js → chunk-RXYYFSBB.js} +82 -110
- package/dist/chunk-RXYYFSBB.js.map +1 -0
- package/dist/{chunk-7OWLS6MF.js → chunk-WK5XUYYF.js} +10 -10
- package/dist/{chunk-CTHXKNMO.js → chunk-YJ6IONGA.js} +2 -2
- package/dist/custody/index.js +2 -2
- package/dist/{dispatch-5DN7ZJGM.js → dispatch-FZEAWKVM.js} +5 -5
- package/dist/{executor-TZNM4GCW.js → executor-YIQB2S6N.js} +3 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +22 -18
- package/dist/index.js.map +1 -1
- package/dist/{liberate-AOU6GEDB.js → liberate-GFN4C7RR.js} +3 -3
- package/dist/materialized-views/index.js +3 -2
- package/dist/money/index.js +10 -6
- package/dist/{noydb-XE4VECNM.js → noydb-3MT74MZS.js} +5 -5
- package/dist/pod/index.js +5 -5
- package/dist/{seed-RZRHXL5E.js → seed-GDV5PT4R.js} +2 -2
- package/dist/{stale-4E3VZXGV.js → stale-ARHFVL5U.js} +2 -2
- package/dist/team/index.js +3 -3
- package/dist/via/money/exact.d.ts +44 -0
- package/dist/via/money/index.d.ts +2 -0
- package/dist/via/money/normalize.d.ts +20 -0
- package/dist/with-formula/materialized-views/types.d.ts +52 -0
- package/dist/with-party/team/keyring.d.ts +10 -0
- package/package.json +3 -3
- package/dist/chunk-MZ5ZFO2D.js.map +0 -1
- package/dist/chunk-Q2VEFHDQ.js.map +0 -1
- package/dist/chunk-WB24CH3C.js.map +0 -1
- /package/dist/{chunk-BA2L5K25.js.map → chunk-ADW22QSB.js.map} +0 -0
- /package/dist/{chunk-VZUVORWV.js.map → chunk-BEFVYAR5.js.map} +0 -0
- /package/dist/{chunk-J5HZUP3M.js.map → chunk-H73G4XF4.js.map} +0 -0
- /package/dist/{chunk-LJNGRBEG.js.map → chunk-IMZLOJTK.js.map} +0 -0
- /package/dist/{chunk-W3AEW5CF.js.map → chunk-NPP5R7FF.js.map} +0 -0
- /package/dist/{chunk-CXJTWRBD.js.map → chunk-O2ERS4UJ.js.map} +0 -0
- /package/dist/{chunk-7OWLS6MF.js.map → chunk-WK5XUYYF.js.map} +0 -0
- /package/dist/{chunk-CTHXKNMO.js.map → chunk-YJ6IONGA.js.map} +0 -0
- /package/dist/{dispatch-5DN7ZJGM.js.map → dispatch-FZEAWKVM.js.map} +0 -0
- /package/dist/{executor-TZNM4GCW.js.map → executor-YIQB2S6N.js.map} +0 -0
- /package/dist/{liberate-AOU6GEDB.js.map → liberate-GFN4C7RR.js.map} +0 -0
- /package/dist/{noydb-XE4VECNM.js.map → noydb-3MT74MZS.js.map} +0 -0
- /package/dist/{seed-RZRHXL5E.js.map → seed-GDV5PT4R.js.map} +0 -0
- /package/dist/{stale-4E3VZXGV.js.map → stale-ARHFVL5U.js.map} +0 -0
package/codemods/0.4.0-pre.json
CHANGED
|
@@ -654,6 +654,46 @@
|
|
|
654
654
|
"safeGlobalReplace": true,
|
|
655
655
|
"section": "§3",
|
|
656
656
|
"note": "Pod-write option; refused rather than ignored as of 0.6.0-pre.3 (#991)."
|
|
657
|
+
},
|
|
658
|
+
{
|
|
659
|
+
"from": "sum",
|
|
660
|
+
"to": "@noy-db/hub/reduce",
|
|
661
|
+
"kind": "import-move",
|
|
662
|
+
"safeGlobalReplace": false,
|
|
663
|
+
"section": "§5",
|
|
664
|
+
"note": "Same name, new home: the reducer factories were pruned off the root barrel and republished at `@noy-db/hub/reduce` in the 0.4.0-pre line (§5). Edit the import, not the identifier — and note these names are ordinary English, so this row is NOT safe to replace globally."
|
|
665
|
+
},
|
|
666
|
+
{
|
|
667
|
+
"from": "count",
|
|
668
|
+
"to": "@noy-db/hub/reduce",
|
|
669
|
+
"kind": "import-move",
|
|
670
|
+
"safeGlobalReplace": false,
|
|
671
|
+
"section": "§5",
|
|
672
|
+
"note": "Same name, new home: the reducer factories were pruned off the root barrel and republished at `@noy-db/hub/reduce` in the 0.4.0-pre line (§5). Edit the import, not the identifier — and note these names are ordinary English, so this row is NOT safe to replace globally."
|
|
673
|
+
},
|
|
674
|
+
{
|
|
675
|
+
"from": "avg",
|
|
676
|
+
"to": "@noy-db/hub/reduce",
|
|
677
|
+
"kind": "import-move",
|
|
678
|
+
"safeGlobalReplace": false,
|
|
679
|
+
"section": "§5",
|
|
680
|
+
"note": "Same name, new home: the reducer factories were pruned off the root barrel and republished at `@noy-db/hub/reduce` in the 0.4.0-pre line (§5). Edit the import, not the identifier — and note these names are ordinary English, so this row is NOT safe to replace globally."
|
|
681
|
+
},
|
|
682
|
+
{
|
|
683
|
+
"from": "min",
|
|
684
|
+
"to": "@noy-db/hub/reduce",
|
|
685
|
+
"kind": "import-move",
|
|
686
|
+
"safeGlobalReplace": false,
|
|
687
|
+
"section": "§5",
|
|
688
|
+
"note": "Same name, new home: the reducer factories were pruned off the root barrel and republished at `@noy-db/hub/reduce` in the 0.4.0-pre line (§5). Edit the import, not the identifier — and note these names are ordinary English, so this row is NOT safe to replace globally."
|
|
689
|
+
},
|
|
690
|
+
{
|
|
691
|
+
"from": "max",
|
|
692
|
+
"to": "@noy-db/hub/reduce",
|
|
693
|
+
"kind": "import-move",
|
|
694
|
+
"safeGlobalReplace": false,
|
|
695
|
+
"section": "§5",
|
|
696
|
+
"note": "Same name, new home: the reducer factories were pruned off the root barrel and republished at `@noy-db/hub/reduce` in the 0.4.0-pre line (§5). Edit the import, not the identifier — and note these names are ordinary English, so this row is NOT safe to replace globally."
|
|
657
697
|
}
|
|
658
698
|
]
|
|
659
699
|
}
|
package/dist/broker/index.js
CHANGED
|
@@ -30,7 +30,7 @@ function withBroker(config) {
|
|
|
30
30
|
const cache = /* @__PURE__ */ new Map();
|
|
31
31
|
return {
|
|
32
32
|
async enroll(ctx) {
|
|
33
|
-
const { enrollSeed } = await import("../seed-
|
|
33
|
+
const { enrollSeed } = await import("../seed-GDV5PT4R.js");
|
|
34
34
|
return enrollSeed({ ...ctx, config });
|
|
35
35
|
},
|
|
36
36
|
async rotate(ctx) {
|
|
@@ -39,7 +39,7 @@ function withBroker(config) {
|
|
|
39
39
|
const inFlight = scoped.map(([, e]) => e.inFlight).filter((p) => p !== void 0);
|
|
40
40
|
await Promise.allSettled(inFlight);
|
|
41
41
|
for (const [key] of scoped) cache.delete(key);
|
|
42
|
-
const { rotateSeed } = await import("../seed-
|
|
42
|
+
const { rotateSeed } = await import("../seed-GDV5PT4R.js");
|
|
43
43
|
return rotateSeed({ ...ctx, config });
|
|
44
44
|
},
|
|
45
45
|
credentialSource(ctx, profile) {
|
|
@@ -56,7 +56,7 @@ function withBroker(config) {
|
|
|
56
56
|
const skewMs = config.skewMs ?? DEFAULT_SKEW_MS;
|
|
57
57
|
const capturedEntry = entry;
|
|
58
58
|
const inFlight = (async () => {
|
|
59
|
-
const { mintStoreCredentials } = await import("../seed-
|
|
59
|
+
const { mintStoreCredentials } = await import("../seed-GDV5PT4R.js");
|
|
60
60
|
const creds = await mintStoreCredentials({ ...ctx, config }, profile);
|
|
61
61
|
capturedEntry.cached = { creds, validUntil: cacheFloor(creds, skewMs) };
|
|
62
62
|
return creds;
|
package/dist/cargo/index.js
CHANGED
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
diffVault,
|
|
7
7
|
unsealDeks,
|
|
8
8
|
withCargo
|
|
9
|
-
} from "../chunk-
|
|
9
|
+
} from "../chunk-IMZLOJTK.js";
|
|
10
10
|
import {
|
|
11
11
|
extractPartition,
|
|
12
12
|
walkClosure
|
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
isDeedVault,
|
|
17
17
|
liberateVault,
|
|
18
18
|
loadDeedMarker
|
|
19
|
-
} from "../chunk-
|
|
19
|
+
} from "../chunk-NPP5R7FF.js";
|
|
20
20
|
import "../chunk-FZ6NYJ7L.js";
|
|
21
21
|
import "../chunk-FFDNKRCY.js";
|
|
22
22
|
import "../chunk-PL2GHSCM.js";
|
|
@@ -33,7 +33,7 @@ import "../chunk-XWX7GL56.js";
|
|
|
33
33
|
import "../chunk-CDB2HVQW.js";
|
|
34
34
|
import {
|
|
35
35
|
CustodyApi
|
|
36
|
-
} from "../chunk-
|
|
36
|
+
} from "../chunk-ADW22QSB.js";
|
|
37
37
|
import "../chunk-4VUPLMZ6.js";
|
|
38
38
|
import "../chunk-2BMRJ6LQ.js";
|
|
39
39
|
import {
|
|
@@ -46,7 +46,7 @@ import {
|
|
|
46
46
|
} from "../chunk-IGJCYUT5.js";
|
|
47
47
|
import "../chunk-7G6VDWXB.js";
|
|
48
48
|
import "../chunk-UHXCLPGC.js";
|
|
49
|
-
import "../chunk-
|
|
49
|
+
import "../chunk-JRKZTEZZ.js";
|
|
50
50
|
import "../chunk-5JY5TSVY.js";
|
|
51
51
|
import "../chunk-AHLJSVRL.js";
|
|
52
52
|
import {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
grant,
|
|
3
3
|
revoke
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-JRKZTEZZ.js";
|
|
5
5
|
import {
|
|
6
6
|
CustodyNotEnabledError
|
|
7
7
|
} from "./chunk-HNGSV2YC.js";
|
|
@@ -16,7 +16,7 @@ function withCustody() {
|
|
|
16
16
|
return host._revokeCustodianImpl(revoke, vault, options, factors);
|
|
17
17
|
},
|
|
18
18
|
async liberate(vault, opts) {
|
|
19
|
-
const { liberateVault } = await import("./liberate-
|
|
19
|
+
const { liberateVault } = await import("./liberate-GFN4C7RR.js");
|
|
20
20
|
return liberateVault(vault, opts);
|
|
21
21
|
}
|
|
22
22
|
};
|
|
@@ -74,4 +74,4 @@ export {
|
|
|
74
74
|
withCustody,
|
|
75
75
|
CustodyApi
|
|
76
76
|
};
|
|
77
|
-
//# sourceMappingURL=chunk-
|
|
77
|
+
//# sourceMappingURL=chunk-ADW22QSB.js.map
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-3URQC7EH.js";
|
|
7
7
|
|
|
8
8
|
// src/with-formula/materialized-views/stale.ts
|
|
9
|
-
var loadMVExecutor = lazy(() => import("./executor-
|
|
9
|
+
var loadMVExecutor = lazy(() => import("./executor-YIQB2S6N.js"));
|
|
10
10
|
var _staleByRegistry = /* @__PURE__ */ new WeakMap();
|
|
11
11
|
function markMVStale(registry, mvName) {
|
|
12
12
|
let set = _staleByRegistry.get(registry);
|
|
@@ -134,4 +134,4 @@ export {
|
|
|
134
134
|
clearMVStale,
|
|
135
135
|
clearMVStaleFully
|
|
136
136
|
};
|
|
137
|
-
//# sourceMappingURL=chunk-
|
|
137
|
+
//# sourceMappingURL=chunk-BEFVYAR5.js.map
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
wrapDbWithPredicates
|
|
3
3
|
} from "./chunk-7F4DBNSP.js";
|
|
4
|
+
import {
|
|
5
|
+
canonicalizeMoneyFieldsAsDecimal,
|
|
6
|
+
decodeMoneyFields,
|
|
7
|
+
exactMath
|
|
8
|
+
} from "./chunk-RXYYFSBB.js";
|
|
4
9
|
import {
|
|
5
10
|
groupAndReduce
|
|
6
11
|
} from "./chunk-CCZJJ4I2.js";
|
|
@@ -96,6 +101,25 @@ function finalizeMappedRows(spec, unified) {
|
|
|
96
101
|
}
|
|
97
102
|
return groupAndReduce(unified, groupFields, spec.aggregate, spec.moneyFields);
|
|
98
103
|
}
|
|
104
|
+
function applyDerive(spec, rows) {
|
|
105
|
+
const groupFields = new Set(
|
|
106
|
+
spec.groupBy === void 0 ? [] : typeof spec.groupBy === "string" ? [spec.groupBy] : spec.groupBy
|
|
107
|
+
);
|
|
108
|
+
return rows.map((row) => {
|
|
109
|
+
const view = spec.moneyFields ? decodeMoneyFields(row, spec.moneyFields, "raw") : row;
|
|
110
|
+
const patch = spec.derive(view, exactMath);
|
|
111
|
+
if (patch === null || patch === void 0) return row;
|
|
112
|
+
for (const key of Object.keys(patch)) {
|
|
113
|
+
if (groupFields.has(key)) {
|
|
114
|
+
throw new MaterializedViewConfigError(
|
|
115
|
+
`Materialized view "${spec.name}": derive() returned the group key "${key}". A group key is the row's identity and feeds rowKey \u2014 rewriting it would re-home the row into a bucket it was not aggregated for. Emit a differently-named field instead.`
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const canonical = spec.moneyFields ? canonicalizeMoneyFieldsAsDecimal(patch, spec.moneyFields) : patch;
|
|
120
|
+
return { ...row, ...canonical };
|
|
121
|
+
});
|
|
122
|
+
}
|
|
99
123
|
async function materializeProjectionResult(spec, db) {
|
|
100
124
|
const projection = spec.projection;
|
|
101
125
|
const coll = db.collection(projection.source);
|
|
@@ -181,6 +205,7 @@ var MaterializedViewExecutor = {
|
|
|
181
205
|
const q = spec.query(ctxForQuery);
|
|
182
206
|
rows = await materializeQueryResult(q, spec.name, spec.i18nLocale, spec.i18nFields);
|
|
183
207
|
}
|
|
208
|
+
if (spec.derive) rows = applyDerive(spec, rows);
|
|
184
209
|
rows = rows.filter((row) => {
|
|
185
210
|
const stamp = row._materializedFrom;
|
|
186
211
|
return stamp?.mvName !== spec.name;
|
|
@@ -282,4 +307,4 @@ async function listOutputIds(outputColl) {
|
|
|
282
307
|
export {
|
|
283
308
|
MaterializedViewExecutor
|
|
284
309
|
};
|
|
285
|
-
//# sourceMappingURL=chunk-
|
|
310
|
+
//# sourceMappingURL=chunk-GAG7QOVO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-formula/materialized-views/executor.ts"],"sourcesContent":["import type { Collection } from '../../kernel/collection.js'\nimport type { TxContext } from '../../with-commit/tx/transaction.js'\nimport type { EncryptedEnvelope } from '../../kernel/types.js'\nimport { MaterializedViewTooLargeError, MaterializedViewConfigError, LocaleNotSpecifiedError, JoinTooLargeError } from '../../kernel/errors.js'\nimport { DEFAULT_JOIN_MAX_ROWS } from '../../kernel/query/join.js'\nimport type { MaterializedFromMeta, MVQueryContext, MaterializedViewSpec } from './types.js'\nimport type { RegisteredMV } from './registry.js'\nimport { wrapDbWithPredicates } from './registry.js'\nimport { groupAndReduce } from '../../with-lookup/reduce/groupby.js'\nimport { canonicalGroupKey } from '../../with-lookup/reduce/canonical-key.js'\nimport { applyI18nLocale, type I18nTextDescriptor } from '../../via/i18n/core.js'\nimport { canonicalizeMoneyFieldsAsDecimal, decodeMoneyFields } from '../../via/money/normalize.js'\nimport { exactMath } from '../../via/money/exact.js'\nimport { putDerivedOutput, type PutDerivedOutputCtx } from '../../kernel/via/dispatch.js'\n\n/**\n * Accessor shape passed in from the owning Vault. Mirrors v1's\n * `DerivationStaleAccessor` — provides the per-collection resolver\n * and the active TxContext so refresh writes/tombstones register on\n * `_executed` for rollback symmetry.\n */\nexport interface MVExecutorAccessor {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getCollection(name: string): Collection<any>\n getActiveTxContext(): TxContext | null\n /**\n * Vault-shaped accessor passed to the MV's `query()` callback at\n * each refresh. Same instance the registry used at registration\n * time; threading through the executor lets the refresh path\n * re-evaluate the closure against the live vault state.\n */\n getQueryContext(): MVQueryContext\n /**\n * #638 Task 5 — ctx for `putDerivedOutput`'s frozen-period skip+audit. #641: the lazy\n * resolve-on-read caller (`stale.ts#resolveStaleMVOnRead`) now supplies one too — built at\n * the `Collection.get()`/`list()` entry point with a `'resolve-on-read'` sentinel id (no\n * real \"reacting write\" for a read-triggered materialize, mirroring `refreshView()`'s\n * `'refreshView'` sentinel). Still declared optional here since `MVExecutorAccessor` is a\n * general shape and a future caller could reasonably omit it.\n */\n dispatchCtx?: PutDerivedOutputCtx\n}\n\nexport interface RefreshResult {\n /** Rows newly written / overwritten. */\n written: number\n /** Rows tombstoned via `_internalDelete` (only when `onEmpty: 'delete'`). */\n deleted: number\n /** Failed row writes (non-strict mode). */\n failed: number\n /** #782/#785 — `outputCollection:id` entries from the tombstone pass whose ownership stamp\n * couldn't be decoded under the collection's default DEK (undecodable, mirroring\n * `invalidateMVAtRest`'s #776 posture) — ownership UNCONFIRMED. Only populated when\n * `onEmpty: 'delete'`. */\n residueUndecodable: string[]\n /** #782/#785 — `outputCollection:id` entries that decoded, stamp-matched this MV, but\n * `_internalDelete` declined (the #718 tier-elevation gate) — ownership CONFIRMED, a real\n * silent survival, surfaced rather than dropped. Only populated when `onEmpty: 'delete'`. */\n residueDeclined: string[]\n}\n\n/** Default cost ceiling — overridable per-MV via `spec.maxRows`. */\nconst DEFAULT_MAX_ROWS = 100_000\n\n/**\n * Materialize a query terminal that may be a `Query<T>` (call\n * `.toArray()`), an `Reduction<R>` (call `.run()` returning a\n * single object — wrap as a one-row array), or a `GroupedReduction<R>`\n * (call `.run()` returning an array of grouped rows). Branches on\n * available terminal at runtime — no type-discrimination at registration.\n */\nasync function materializeQueryResult(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n q: any,\n mvName: string,\n i18nLocale?: string,\n i18nFields?: Record<string, I18nTextDescriptor>,\n): Promise<ReadonlyArray<Record<string, unknown>>> {\n if (typeof q?.toArray === 'function') {\n // Query<T> — non-aggregate path. `.toArray()` returns Promise<T[]>.\n return await q.toArray()\n }\n if (typeof q?.run === 'function') {\n // Reduction<R> or GroupedReduction<R>. `.run()` is synchronous\n // and returns either a single object (Reduction) or an array of\n // rows (GroupedReduction). Promise.resolve() normalizes both\n // sync and async (future) variants.\n // Query-form MV grouping: when the MV declares i18nLocale, pass it +\n // i18nFields so a GroupedReduction resolves i18n group keys before\n // bucketing (the Reduction path ignores the extra arg).\n const runOpts = i18nLocale !== undefined ? { locale: i18nLocale, i18nFields } : undefined\n const result: unknown = await Promise.resolve(q.run(runOpts))\n if (Array.isArray(result)) {\n return result as ReadonlyArray<Record<string, unknown>>\n }\n // Single-aggregate result — wrap as one-row array. The consumer's\n // `rowKey()` should return a stable identity (often a literal\n // constant like `'total'`) since there's only one row.\n return [result as Record<string, unknown>]\n }\n throw new Error(\n `MV \"${mvName}\": query() must return a Query<T>, Reduction, or GroupedReduction. ` +\n `Got something without a .toArray() or .run() terminal.`,\n )\n}\n\n/**\n * Materialize a UNION-form MV: read every arm's source\n * collection, apply each arm's `map` to project rows into the unified\n * MV row shape, concatenate the mapped streams, then optionally run\n * `groupBy` + `aggregate` over the result.\n *\n * Modes (driven by `spec.groupBy` / `spec.aggregate`):\n *\n * - No `groupBy` → return the concatenated mapped rows unchanged.\n * - `groupBy` without `aggregate` → dedupe by composite group key,\n * keep the first row seen per key (later arms don't overwrite\n * earlier arms — Map insertion order rules).\n * - `groupBy` + `aggregate` → delegate to the shared `groupAndReduce`\n * pipeline used by `Query.groupBy().aggregate()`.\n *\n * Per-arm `map` is the schema-unification boundary; the strategy's\n * `TRow` type parameter enforces that every arm projects into the\n * same shape at compile time.\n *\n * @internal\n */\nasync function materializeUnionResult<TRow extends Record<string, unknown>>(\n spec: MaterializedViewSpec<TRow>,\n db: MVQueryContext,\n): Promise<ReadonlyArray<Record<string, unknown>>> {\n const unified: TRow[] = []\n for (const arm of spec.unionSources!) {\n const coll = db.collection<Record<string, unknown>>(arm.collection)\n // Optional per-arm FK joins: chain `.join(field, { as, ... })` for\n // each declared leg before terminating. The aliased right-side\n // record lands at `sourceRow[leg.as]`, where the arm's `map` reads\n // it. Cast to `any` because the chained join widens the row type but\n // the executor treats every row as `Record<string, unknown>` — same\n // pattern the query-form join path uses.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let q: any = coll.query()\n if (arm.join?.length) {\n for (const leg of arm.join) {\n q = q.join(leg.field, { as: leg.as, maxRows: leg.maxRows, strategy: leg.strategy })\n }\n }\n const sourceRows = q.toArray() as ReadonlyArray<Record<string, unknown>>\n for (const r of sourceRows) {\n const mapped = arm.map(r)\n // null / undefined means \"omit this source row\" — skip without\n // pushing so groupBy/aggregate never see a null entry.\n if (mapped == null) continue\n unified.push(mapped)\n }\n }\n\n return finalizeMappedRows(spec, unified)\n}\n\n/**\n * Shared post-map tail for the UNION and projection (#810) forms:\n * optional `groupBy` (+ `aggregate`) over the mapped-row stream.\n * Extracted verbatim from `materializeUnionResult` so both forms feed\n * the identical grouping pipeline — i18n group-key resolution, the\n * object-group-key guard, dedup-without-aggregate, and the shared\n * `groupAndReduce` delegate.\n *\n * @internal\n */\nfunction finalizeMappedRows<TRow extends Record<string, unknown>>(\n spec: MaterializedViewSpec<TRow>,\n unified: TRow[],\n): ReadonlyArray<Record<string, unknown>> {\n if (!spec.groupBy) return unified\n\n const groupFields: readonly string[] =\n typeof spec.groupBy === 'string' ? [spec.groupBy] : spec.groupBy\n\n // i18n-aware group keys. An `i18nText` group field carries a raw\n // `{ locale: string }` map, an unstable object key. When `i18nLocale` is\n // declared (with `i18nFields` describing those fields), resolve the declared\n // group-key i18n fields to it at the `mv` layer FIRST — the same unified-rows\n // boundary where money is threaded — so buckets are stable strings and the\n // `mv`-layer `onMissing` policy fires here.\n if (spec.i18nLocale !== undefined && spec.i18nFields !== undefined) {\n const groupI18n: Record<string, I18nTextDescriptor> = {}\n for (const f of groupFields) {\n const d = spec.i18nFields[f]\n if (d !== undefined) groupI18n[f] = d\n }\n if (Object.keys(groupI18n).length > 0) {\n for (let i = 0; i < unified.length; i++) {\n unified[i] = applyI18nLocale(unified[i] as Record<string, unknown>, groupI18n, spec.i18nLocale, undefined, 'mv') as TRow\n }\n }\n }\n // Guard (always): a remaining object-valued group key — an undeclared i18n\n // field or a locale-less MV — would bucket on a map. Refuse, don't bucket wrong.\n for (const f of groupFields) {\n for (const row of unified) {\n const v = (row as Record<string, unknown>)[f]\n if (v !== null && typeof v === 'object') {\n throw new LocaleNotSpecifiedError(\n f,\n `Materialized view \"${spec.name}\" groups by \"${f}\", whose value is a raw i18n locale map — ` +\n `an unstable object group key. Declare { i18nLocale, i18nFields } on the MV to resolve it at ` +\n `the 'mv' layer, or group by a dictKey/staticDict code (the stable key) and resolve the label at read time.`,\n )\n }\n }\n }\n\n // groupBy without aggregate — dedupe by composite key, keep first\n // seen row per key. Useful for cross-arm uniqueness (e.g. unify two\n // sibling collections, keeping one row per natural key).\n if (!spec.aggregate) {\n const seen = new Map<string, TRow>()\n for (const row of unified) {\n const k = canonicalGroupKey(groupFields, row as Record<string, unknown>)\n if (!seen.has(k)) seen.set(k, row)\n }\n return [...seen.values()]\n }\n\n // groupBy + aggregate — delegate to the shared pipeline used by\n // `Query.groupBy().aggregate()`. Result rows carry each grouped\n // field in declaration order followed by the spec's reducer outputs.\n return groupAndReduce<Record<string, unknown>>(unified, groupFields, spec.aggregate, spec.moneyFields)\n}\n\n/**\n * Apply the spec's `derive` to each finished row (#1007).\n *\n * Three rules, all of them about keeping the hook narrow enough that the\n * engine never has to reason about the function:\n *\n * - a `null` / `undefined` return leaves the row untouched;\n * - a returned key that collides with a `groupBy` field is refused — group\n * keys are the row's identity and feed `rowKey`, so letting `derive`\n * rewrite one would silently re-home the row into a different bucket than\n * the one it was aggregated for;\n * - a derived field declared in `moneyFields` is quantised through its\n * descriptor, so the stored value is exact at the declared scale instead of\n * whatever the user's arithmetic produced.\n *\n * @internal\n */\nfunction applyDerive<TRow extends Record<string, unknown>>(\n spec: MaterializedViewSpec<TRow>,\n rows: ReadonlyArray<Record<string, unknown>>,\n): ReadonlyArray<Record<string, unknown>> {\n const groupFields = new Set<string>(\n spec.groupBy === undefined ? [] : typeof spec.groupBy === 'string' ? [spec.groupBy] : spec.groupBy,\n )\n return rows.map((row) => {\n // `derive` sees the row the way a READER would: money decoded to its\n // canonical decimal form, not the scaled integer the reducer left behind.\n // Handing over `1005` where the schema says `10.05` would make every\n // derived money expression quietly wrong by a factor of the scale.\n // `'raw'` keeps it at the exact decimal rather than a locale-formatted\n // string, which is what `exact.*` consumes.\n const view = spec.moneyFields ? decodeMoneyFields(row, spec.moneyFields, 'raw') : row\n const patch = spec.derive!(view as TRow, exactMath)\n if (patch === null || patch === undefined) return row\n for (const key of Object.keys(patch)) {\n if (groupFields.has(key)) {\n throw new MaterializedViewConfigError(\n `Materialized view \"${spec.name}\": derive() returned the group key \"${key}\". ` +\n 'A group key is the row\\'s identity and feeds rowKey — rewriting it would re-home the ' +\n 'row into a bucket it was not aggregated for. Emit a differently-named field instead.',\n )\n }\n }\n // Canonicalize the PATCH only, into the DECIMAL form the money-aware\n // reducers emit — not the scaled-integer storage form a collection uses.\n // An MV row's money fields are decimal strings, so a derived field\n // quantised into storage form reads back as the scaled integer beside\n // correctly-decoded siblings: `\"1000000\"` next to `\"10000.00\"` (#1018).\n // Precision is still enforced; only the output shape differs.\n const canonical = spec.moneyFields\n ? canonicalizeMoneyFieldsAsDecimal(patch, spec.moneyFields)\n : patch\n return { ...row, ...canonical }\n })\n}\n\n/**\n * Materialize a projection-form MV (#810): hydrate the primary source\n * rows, resolve forward FK legs through the same `.join()` machinery\n * the UNION arms use, attach reverse \"collect\" legs via one\n * hash-grouped snapshot pass per leg, then run the projection `map`\n * (null / undefined omits the primary row) and the shared post-map\n * grouping tail.\n *\n * @internal\n */\nasync function materializeProjectionResult<TRow extends Record<string, unknown>>(\n spec: MaterializedViewSpec<TRow>,\n db: MVQueryContext,\n): Promise<ReadonlyArray<Record<string, unknown>>> {\n const projection = spec.projection!\n const coll = db.collection<Record<string, unknown>>(projection.source)\n // Forward legs chain through the query builder exactly like UNION arm\n // joins — ref() resolution, dangling-mode semantics, presentation\n // dressing, and ceilings all ride the existing `.join()` path. Cast to\n // `any` for the same reason `materializeUnionResult` does.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let q: any = coll.query()\n for (const leg of projection.joins) {\n if ('collect' in leg) continue\n q = q.join(leg.field, { as: leg.as, maxRows: leg.maxRows, strategy: leg.strategy })\n }\n let rows = q.toArray() as Array<Record<string, unknown>>\n for (const leg of projection.joins) {\n if (!('collect' in leg)) continue\n rows = applyCollectLeg(rows, leg, spec.name, projection.source, db)\n }\n const mapped: TRow[] = []\n for (const r of rows) {\n const m = projection.map(r)\n // null / undefined means \"omit this primary row\" — same contract\n // as the UNION arm `map`.\n if (m == null) continue\n mapped.push(m)\n }\n return finalizeMappedRows(spec, mapped)\n}\n\n/**\n * Attach one reverse \"collect\" leg (#810): every row of `leg.collect`\n * whose `leg.on` field references a primary record's id lands in a\n * possibly-empty ARRAY under `leg.as` on that primary row. One\n * snapshot pass over the collect collection, hash-grouped by the `on`\n * FK — O(N+M), mirroring the forward hash-join fallback.\n *\n * Semantic check (first materialization, not factory time — parity\n * with join-time ref errors): `leg.on` must carry a `ref()` declared\n * on the collect collection targeting the projection `source`.\n *\n * @internal\n */\nfunction applyCollectLeg(\n primaryRows: ReadonlyArray<Record<string, unknown>>,\n leg: { readonly collect: string; readonly on: string; readonly as: string; readonly maxRows?: number },\n mvName: string,\n source: string,\n db: MVQueryContext,\n): Array<Record<string, unknown>> {\n const childColl = db.collection<Record<string, unknown>>(leg.collect)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const childQ = childColl.query() as any\n const refDesc = childQ._joinContext?.()?.resolveRef(leg.on) as { target: string } | null | undefined\n if (refDesc == null) {\n throw new MaterializedViewConfigError(\n `\"${mvName}\": projection collect leg \"${leg.as}\" requires a ref() on field \"${leg.on}\" of `\n + `collection \"${leg.collect}\" targeting \"${source}\" — declare `\n + `refs: { ${leg.on}: ref('${source}') } on collection \"${leg.collect}\", then retry`,\n )\n }\n if (refDesc.target !== source) {\n throw new MaterializedViewConfigError(\n `\"${mvName}\": projection collect leg \"${leg.as}\" expects field \"${leg.on}\" of collection `\n + `\"${leg.collect}\" to reference the projection source \"${source}\", but its ref() targets `\n + `\"${refDesc.target}\"`,\n )\n }\n const maxRows = leg.maxRows ?? DEFAULT_JOIN_MAX_ROWS\n const groups = new Map<string, Array<Record<string, unknown>>>()\n for (const child of childQ.toArray() as Array<Record<string, unknown>>) {\n const key = coerceCollectKey(child[leg.on])\n // Nullish / non-scalar FK values mean \"no reference\" — same\n // narrowing as the forward join path's key coercion.\n if (key === null) continue\n const bucket = groups.get(key)\n if (bucket) bucket.push(child)\n else groups.set(key, [child])\n }\n const out: Array<Record<string, unknown>> = []\n for (const row of primaryRows) {\n const key = coerceCollectKey(row.id)\n const children = key === null ? [] : groups.get(key) ?? []\n if (children.length > maxRows) {\n throw new JoinTooLargeError({\n leftRows: primaryRows.length,\n rightRows: children.length,\n maxRows,\n side: 'right',\n message:\n `projection MV \"${mvName}\": collect leg \"${leg.as}\" gathered ${children.length} ` +\n `\"${leg.collect}\" rows for one \"${source}\" record, exceeding the ${maxRows}-row ` +\n `per-primary-row ceiling. Raise the ceiling via { maxRows } on the leg if the ` +\n `fan-out genuinely fits in memory, or restructure the child collection.`,\n })\n }\n out.push({ ...row, [leg.as]: children })\n }\n return out\n}\n\n/**\n * Coerce an unknown FK value into a collect-grouping key. Same\n * narrowing as the join path's `coerceRefKey` (not exported from\n * there): strings and numbers are legitimate ref values; anything\n * else is \"no reference\" and returns `null`.\n *\n * @internal\n */\nfunction coerceCollectKey(value: unknown): string | null {\n if (value === null || value === undefined) return null\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'bigint') return String(value)\n return null\n}\n\n/**\n * Run an MV's `query()` and write the result rows to the output\n * collection. Same-DEK encryption: routes through the standard\n * `Collection.put` pipeline, so the output collection's DEK is what\n * gets used (matches the v2 spec's \"same DEK as the left-most source\"\n * invariant — `Collection.put` looks up the DEK by collection name,\n * and the output collection IS the MV's owned collection).\n *\n * Stamps `_materializedFrom` onto every emitted row.\n *\n * **Tombstoning:** when `spec.onEmpty: 'delete'` (default), rows\n * that existed in a prior refresh but no longer appear in the new\n * materialized result are deleted via `Collection._internalDelete` —\n * the housekeeping bypass primitive prevents user\n * `onDelete` guards on the output collection from firing on these\n * system-internal deletes. `onEmpty: 'keep'` opts out (rows from\n * prior refreshes linger even when the new result lacks them).\n *\n * **Cost ceiling:** if the materialized row count exceeds\n * `spec.maxRows` (default 100k), throws `MaterializedViewTooLargeError`\n * before any writes hit the store — so strict-mode rollback is\n * clean.\n *\n * **Strict mode:** `spec.strict === true` re-throws on any\n * row-write failure; the active TxContext registration means the\n * source-write rolls back atomically via `revertExecuted`.\n *\n * @internal\n */\nexport const MaterializedViewExecutor = {\n async refresh(\n reg: RegisteredMV,\n accessor: MVExecutorAccessor,\n ): Promise<RefreshResult> {\n const spec = reg.spec\n const outputColl = accessor.getCollection(reg.outputCollection)\n const maxRows = spec.maxRows ?? DEFAULT_MAX_ROWS\n const onEmpty = spec.onEmpty ?? 'delete'\n const strict = spec.strict ?? false\n\n // 1. Materialize the query (branches on terminal shape). If the\n // MV declared predicates, wrap the query context the same way\n // the registry did at registration time so `.wherePredicate()`\n // calls resolve to the registered functions.\n const baseCtx = accessor.getQueryContext()\n const ctxForQuery: MVQueryContext = spec.predicates\n ? wrapDbWithPredicates(baseCtx, spec.predicates)\n : baseCtx\n // UNION-form strategies: read every arm, map to the unified\n // row shape, concatenate, then optionally groupBy + aggregate.\n // Projection-form strategies (#810): hydrate the primary source,\n // attach forward + collect legs, map, then the same optional\n // grouping tail. The single-source `query()` path is untouched.\n let rows: ReadonlyArray<Record<string, unknown>>\n if (spec.unionSources) {\n rows = await materializeUnionResult(spec, ctxForQuery)\n } else if (spec.projection) {\n rows = await materializeProjectionResult(spec, ctxForQuery)\n } else {\n const q = spec.query!(ctxForQuery)\n rows = await materializeQueryResult(q, spec.name, spec.i18nLocale, spec.i18nFields)\n }\n\n // #1007 — the post-aggregate projection. Applied here, after every form has\n // produced its finished rows, so union / projection / query all get the\n // same single definition of \"last step before materialisation\".\n if (spec.derive) rows = applyDerive(spec, rows)\n\n // #777 — exclude this MV's OWN previously-stamped output rows from the\n // input scan. A same-collection Query-form MV copies the whole source row\n // verbatim into its output, so a stale output row can itself satisfy the\n // MV's own input filter (when the filter is on a field disjoint from the\n // partition field) and get re-selected as if it were live source — the\n // row self-perpetuates after its true source is gone. Prior output is\n // never this MV's own source.\n rows = rows.filter((row) => {\n const stamp = row._materializedFrom as { mvName?: string } | undefined\n return stamp?.mvName !== spec.name\n })\n\n // 2. Cost ceiling check BEFORE any writes — keeps the rollback\n // clean if the source-write is wrapped in a transaction.\n if (rows.length > maxRows) {\n throw new MaterializedViewTooLargeError(spec.name, rows.length, maxRows)\n }\n\n const txCtx = accessor.getActiveTxContext()\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const adapter = (outputColl as any).adapter as {\n get(v: string, c: string, i: string): Promise<EncryptedEnvelope | null>\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const vaultName = (outputColl as any).vault as string\n\n // 3. Compute the post-refresh id set so we can diff against the\n // prior-emitted id set for tombstoning (when onEmpty === 'delete').\n const newIds = new Set<string>()\n const enrichedRows: Array<{ id: string; record: Record<string, unknown> }> = []\n for (const row of rows) {\n const id = spec.rowKey(row)\n newIds.add(id)\n const meta: MaterializedFromMeta = {\n mvName: spec.name,\n queryHash: reg.queryHash,\n sourceVersions: {},\n materializedAt: new Date().toISOString(),\n }\n enrichedRows.push({ id, record: { ...row, _materializedFrom: meta } })\n }\n\n // 4. Write the new rows.\n let written = 0\n let failed = 0\n for (const { id, record } of enrichedRows) {\n try {\n if (txCtx !== null) {\n const prior = await adapter.get(vaultName, reg.outputCollection, id)\n txCtx._executed.push({\n op: { type: 'put', vaultName, collectionName: reg.outputCollection, id },\n priorEnvelope: prior,\n })\n }\n if (accessor.dispatchCtx) {\n if (await putDerivedOutput(outputColl, id, record, accessor.dispatchCtx) === 'written') written++\n } else {\n await outputColl.put(id, record)\n written++\n }\n } catch (err) {\n failed++\n if (strict) throw err\n \n console.warn(`[mv] \"${spec.name}\" row write failed:`, err)\n }\n }\n\n // 5. Tombstone rows that existed before but don't appear now.\n // `onEmpty: 'keep'` skips this pass entirely. Uses\n // `_internalDelete` so a user-registered `onDelete` on the\n // output collection does NOT fire on housekeeping (composition fix).\n let deleted = 0\n const residueUndecodable: string[] = []\n const residueDeclined: string[] = []\n if (onEmpty === 'delete') {\n const priorIds = await listOutputIds(outputColl)\n for (const priorId of priorIds) {\n if (newIds.has(priorId)) continue\n // #762 — a same-collection partition MV (`output: { collection: <source>, partition }`,\n // the DERIV-PP30-001 shape) writes INTO its own source collection, so `listOutputIds`\n // also returns untouched USER source rows here. Decode each candidate and only\n // tombstone rows THIS MV stamped via `_materializedFrom.mvName` — the exact discipline\n // `invalidateMVAtRest` uses (stale.ts:151-162). An unstamped row, or one stamped by a\n // different MV, is never this MV's to delete.\n const priorEnvelope = await adapter.get(vaultName, reg.outputCollection, priorId)\n if (priorEnvelope === null) continue\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const priorDecoded = await (outputColl as any)._decodeEnvelope(priorEnvelope, priorId)\n if (priorDecoded === null) {\n // #782 part a — ownership unknown (undecodable, e.g. elevated above tier 0 on a\n // tiered output collection): can't rule out this being THIS MV's own stamped row.\n // Surface it rather than silently skip (mirrors invalidateMVAtRest's #776 posture —\n // previously this leg had NO residue channel at all).\n residueUndecodable.push(`${reg.outputCollection}:${priorId}`)\n continue\n }\n const priorStampedBy =\n typeof priorDecoded === 'object'\n ? (priorDecoded as Record<string, unknown>)._materializedFrom as { mvName?: string } | undefined\n : undefined\n if (priorStampedBy?.mvName !== spec.name) continue\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const outAny = outputColl as any\n if (typeof outAny._internalDelete === 'function') {\n // #776 part b — gate on the boolean, matching invalidateMVAtRest's discipline\n // (stale.ts): `_internalDelete` returns `false` for a #718 elevated-skip (no\n // erasure happened), and that must not inflate the tombstone count.\n if (await outAny._internalDelete(priorId, txCtx)) {\n deleted++\n } else {\n // #782 part b — decoded AND stamp-owned, but erasure was declined (#718\n // tier-elevation gate). Ownership IS confirmed here — a real silent survival,\n // not a legit stamp-mismatch skip. Surface it too.\n residueDeclined.push(`${reg.outputCollection}:${priorId}`)\n }\n } else {\n // Defensive fallback — should never hit in real flow since\n // every Collection has `_internalDelete`.\n await outputColl.delete(priorId)\n deleted++\n }\n } catch (err) {\n failed++\n if (strict) throw err\n\n console.warn(`[mv] \"${spec.name}\" tombstone failed for id=\"${priorId}\":`, err)\n }\n }\n }\n\n return { written, deleted, failed, residueUndecodable, residueDeclined }\n },\n}\n\n/**\n * List ids currently present in the MV's output collection via the\n * adapter directly (avoids triggering the lazy resolve-on-read path\n * we're INSIDE). Returns an empty array if the collection doesn't\n * exist or the adapter doesn't surface a list method.\n *\n * @internal\n */\nasync function listOutputIds(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n outputColl: Collection<any>,\n): Promise<string[]> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const cAny = outputColl as any\n const adapter = cAny.adapter as { list?: (v: string, c: string) => Promise<readonly string[]> }\n const vault = cAny.vault as string\n const name = cAny.name as string\n if (typeof adapter?.list !== 'function') return []\n try {\n const ids = await adapter.list(vault, name)\n return [...ids]\n } catch {\n return []\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,IAAM,mBAAmB;AASzB,eAAe,uBAEb,GACA,QACA,YACA,YACiD;AACjD,MAAI,OAAO,GAAG,YAAY,YAAY;AAEpC,WAAO,MAAM,EAAE,QAAQ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BAAgB,WAAW,KAAK,KAAM;AAC1C,YAAI;AAEF,gBAAM,SAAS;AACf,cAAI,OAAO,OAAO,oBAAoB,YAAY;AAIhD,gBAAI,MAAM,OAAO,gBAAgB,SAAS,KAAK,GAAG;AAChD;AAAA,YACF,OAAO;AAIL,8BAAgB,KAAK,GAAG,IAAI,gBAAgB,IAAI,OAAO,EAAE;AAAA,YAC3D;AAAA,UACF,OAAO;AAGL,kBAAM,WAAW,OAAO,OAAO;AAC/B;AAAA,UACF;AAAA,QACF,SAAS,KAAK;AACZ;AACA,cAAI,OAAQ,OAAM;AAElB,kBAAQ,KAAK,SAAS,KAAK,IAAI,8BAA8B,OAAO,MAAM,GAAG;AAAA,QAC/E;AAAA,MACF;AAAA,IACF;AAEA,WAAO,EAAE,SAAS,SAAS,QAAQ,oBAAoB,gBAAgB;AAAA,EACzE;AACF;AAUA,eAAe,cAEb,YACmB;AAEnB,QAAM,OAAO;AACb,QAAM,UAAU,KAAK;AACrB,QAAM,QAAQ,KAAK;AACnB,QAAM,OAAO,KAAK;AAClB,MAAI,OAAO,SAAS,SAAS,WAAY,QAAO,CAAC;AACjD,MAAI;AACF,UAAM,MAAM,MAAM,QAAQ,KAAK,OAAO,IAAI;AAC1C,WAAO,CAAC,GAAG,GAAG;AAAA,EAChB,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createNoydb
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-WK5XUYYF.js";
|
|
4
4
|
import {
|
|
5
5
|
deriveSchemaManifest
|
|
6
6
|
} from "./chunk-2DHSSLOD.js";
|
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
} from "./chunk-4VUPLMZ6.js";
|
|
17
17
|
import {
|
|
18
18
|
loadKeyring
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-JRKZTEZZ.js";
|
|
20
20
|
import {
|
|
21
21
|
ConflictError,
|
|
22
22
|
MigrationRequiredError,
|
|
@@ -290,4 +290,4 @@ export {
|
|
|
290
290
|
followRedirects,
|
|
291
291
|
open
|
|
292
292
|
};
|
|
293
|
-
//# sourceMappingURL=chunk-
|
|
293
|
+
//# sourceMappingURL=chunk-H73G4XF4.js.map
|
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
} from "./chunk-4VUPLMZ6.js";
|
|
12
12
|
import {
|
|
13
13
|
createOwnerKeyring
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-JRKZTEZZ.js";
|
|
15
15
|
import {
|
|
16
16
|
diff
|
|
17
17
|
} from "./chunk-SVLR4POP.js";
|
|
@@ -399,7 +399,7 @@ async function createOwnerOnAdoptedPartition(store, vaultName, opts) {
|
|
|
399
399
|
}
|
|
400
400
|
}
|
|
401
401
|
if (isManaged(opts)) {
|
|
402
|
-
const { createNoydb } = await import("./noydb-
|
|
402
|
+
const { createNoydb } = await import("./noydb-3MT74MZS.js");
|
|
403
403
|
const db = await createNoydb({
|
|
404
404
|
store,
|
|
405
405
|
user: userId,
|
|
@@ -455,4 +455,4 @@ export {
|
|
|
455
455
|
withCargo,
|
|
456
456
|
describeExtraction
|
|
457
457
|
};
|
|
458
|
-
//# sourceMappingURL=chunk-
|
|
458
|
+
//# sourceMappingURL=chunk-IMZLOJTK.js.map
|
|
@@ -464,6 +464,7 @@ async function grant(store, vault, callerKeyring, options) {
|
|
|
464
464
|
const granteeMayHoldSecrets = options.role === "owner" || options.role === "admin";
|
|
465
465
|
let mintedForGrant = false;
|
|
466
466
|
for (const collName of Object.keys(permissions)) {
|
|
467
|
+
if (collName === PERMISSION_WILDCARD) continue;
|
|
467
468
|
if (isSecretBearingReservedCollection(collName) && !granteeMayHoldSecrets) continue;
|
|
468
469
|
if (callerKeyring.deks.has(collName)) continue;
|
|
469
470
|
if (await collectionHasRecords(store, vault, collName)) continue;
|
|
@@ -473,13 +474,14 @@ async function grant(store, vault, callerKeyring, options) {
|
|
|
473
474
|
if (mintedForGrant) await persistKeyring(store, vault, callerKeyring);
|
|
474
475
|
const wrappedDeks = {};
|
|
475
476
|
for (const collName of Object.keys(permissions)) {
|
|
477
|
+
if (collName === PERMISSION_WILDCARD) continue;
|
|
476
478
|
if (isSecretBearingReservedCollection(collName) && !granteeMayHoldSecrets) continue;
|
|
477
479
|
const dek = callerKeyring.deks.get(collName);
|
|
478
480
|
if (dek) {
|
|
479
481
|
wrappedDeks[collName] = await wrapKey(dek, newKek);
|
|
480
482
|
}
|
|
481
483
|
}
|
|
482
|
-
if (options.role === "owner" || options.role === "admin" || options.role === "custodian" || options.role === "viewer") {
|
|
484
|
+
if (options.role === "owner" || options.role === "admin" || options.role === "custodian" || options.role === "viewer" || permissionsAreWildcard(options.permissions)) {
|
|
483
485
|
for (const [collName, dek] of callerKeyring.deks) {
|
|
484
486
|
if (collName in wrappedDeks) continue;
|
|
485
487
|
if (isSecretBearingReservedCollection(collName) && !granteeMayHoldSecrets) continue;
|
|
@@ -836,6 +838,19 @@ async function collectionHasRecords(store, vault, collectionName) {
|
|
|
836
838
|
const ids = await store.list(vault, collectionName);
|
|
837
839
|
return ids.length > 0;
|
|
838
840
|
}
|
|
841
|
+
async function reloadPersistedDEK(store, vault, keyring, collectionName) {
|
|
842
|
+
if (!keyring.kek) return null;
|
|
843
|
+
const found = await readKeyringFile(store, vault, keyring.userId);
|
|
844
|
+
const wrapped = found?.file.deks[collectionName];
|
|
845
|
+
if (wrapped === void 0) return null;
|
|
846
|
+
try {
|
|
847
|
+
const dek = await unwrapKey(wrapped, keyring.kek);
|
|
848
|
+
keyring.deks.set(collectionName, dek);
|
|
849
|
+
return dek;
|
|
850
|
+
} catch {
|
|
851
|
+
return null;
|
|
852
|
+
}
|
|
853
|
+
}
|
|
839
854
|
async function ensureCollectionDEK(store, vault, keyring) {
|
|
840
855
|
const inFlight = /* @__PURE__ */ new Map();
|
|
841
856
|
return async (collectionName) => {
|
|
@@ -844,10 +859,19 @@ async function ensureCollectionDEK(store, vault, keyring) {
|
|
|
844
859
|
const pending = inFlight.get(collectionName);
|
|
845
860
|
if (pending) return pending;
|
|
846
861
|
const promise = (async () => {
|
|
847
|
-
if (!collectionName.startsWith("_")
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
862
|
+
if (!collectionName.startsWith("_")) {
|
|
863
|
+
if (!hasAccess(keyring, collectionName)) {
|
|
864
|
+
throw new NoAccessError(
|
|
865
|
+
`No access \u2014 user does not have a key for collection "${collectionName}". Grant them this collection in \`permissions\` to give them one.`
|
|
866
|
+
);
|
|
867
|
+
}
|
|
868
|
+
if (await collectionHasRecords(store, vault, collectionName)) {
|
|
869
|
+
const refreshed = await reloadPersistedDEK(store, vault, keyring, collectionName);
|
|
870
|
+
if (refreshed) return refreshed;
|
|
871
|
+
throw new NoAccessError(
|
|
872
|
+
`No access \u2014 user "${keyring.userId}" is entitled to collection "${collectionName}" but holds no key for it, because the collection was created AFTER their grant. A collection DEK can only be wrapped at grant time (wrapping needs the grantee's secret, which the vault never stores), so this cannot be back-filled \u2014 re-grant the user to give them the key.`
|
|
873
|
+
);
|
|
874
|
+
}
|
|
851
875
|
}
|
|
852
876
|
const dek = await generateDEK();
|
|
853
877
|
keyring.deks.set(collectionName, dek);
|
|
@@ -862,14 +886,20 @@ async function ensureCollectionDEK(store, vault, keyring) {
|
|
|
862
886
|
}
|
|
863
887
|
};
|
|
864
888
|
}
|
|
889
|
+
var PERMISSION_WILDCARD = "*";
|
|
890
|
+
function permissionsAreWildcard(permissions) {
|
|
891
|
+
return permissions !== void 0 && PERMISSION_WILDCARD in permissions;
|
|
892
|
+
}
|
|
865
893
|
function hasWritePermission(keyring, collectionName) {
|
|
866
894
|
if (keyring.role === "owner" || keyring.role === "admin" || keyring.role === "custodian") return true;
|
|
867
895
|
if (keyring.role === "viewer" || keyring.role === "client") return false;
|
|
896
|
+
if (keyring.permissions[PERMISSION_WILDCARD] === "rw") return true;
|
|
868
897
|
return keyring.permissions[collectionName] === "rw";
|
|
869
898
|
}
|
|
870
899
|
function hasAccess(keyring, collectionName) {
|
|
871
900
|
if (keyring.role === "owner" || keyring.role === "admin" || keyring.role === "custodian" || keyring.role === "viewer")
|
|
872
901
|
return true;
|
|
902
|
+
if (PERMISSION_WILDCARD in keyring.permissions) return true;
|
|
873
903
|
return collectionName in keyring.permissions;
|
|
874
904
|
}
|
|
875
905
|
async function persistKeyring(store, vault, keyring) {
|
|
@@ -994,4 +1024,4 @@ export {
|
|
|
994
1024
|
hasImportCapability,
|
|
995
1025
|
evaluateImportCapability
|
|
996
1026
|
};
|
|
997
|
-
//# sourceMappingURL=chunk-
|
|
1027
|
+
//# sourceMappingURL=chunk-JRKZTEZZ.js.map
|