@noy-db/hub 0.2.0-pre.3 → 0.2.0-pre.31
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/README.md +126 -0
- package/dist/adapter/index.d.ts +9 -0
- package/dist/adapter/index.js +14 -0
- package/dist/aggregate/index.d.ts +3 -2
- package/dist/aggregate/index.js +10 -8
- package/dist/aggregate/index.js.map +1 -1
- package/dist/attestation/index.d.ts +7 -5
- package/dist/attestation/index.js +7 -6
- package/dist/attestation/index.js.map +1 -1
- package/dist/blobs/index.d.ts +9 -7
- package/dist/blobs/index.js +12 -6
- package/dist/blobs/index.js.map +1 -1
- package/dist/bundle/index.d.ts +29 -18
- package/dist/bundle/index.js +53 -192
- package/dist/bundle/index.js.map +1 -1
- package/dist/{chunk-75QDHSE4.js → chunk-2QDWRK3B.js} +5 -5
- package/dist/{chunk-74JEQFMT.js → chunk-2UT7HJJR.js} +5 -5
- package/dist/chunk-2UT7HJJR.js.map +1 -0
- package/dist/{chunk-FCDO7UAO.js → chunk-2ZYIN3BL.js} +2 -2
- package/dist/{chunk-BFI3RS42.js → chunk-33EQCZXE.js} +2 -2
- package/dist/chunk-33EQCZXE.js.map +1 -0
- package/dist/{chunk-WRLHNG6H.js → chunk-4K4QKYK4.js} +4 -4
- package/dist/chunk-4K4QKYK4.js.map +1 -0
- package/dist/{chunk-HGZ7DC5H.js → chunk-4L6N56B4.js} +2 -2
- package/dist/chunk-4L6N56B4.js.map +1 -0
- package/dist/{chunk-YMYK7US4.js → chunk-4YD7VZH4.js} +2 -2
- package/dist/chunk-4YD7VZH4.js.map +1 -0
- package/dist/{chunk-ZUMGGHRB.js → chunk-5PTX7PKD.js} +4 -4
- package/dist/{chunk-QAU5HM6Q.js → chunk-6EKRQ7QF.js} +3 -3
- package/dist/{chunk-ZC2AAE6J.js → chunk-7GPQPLGO.js} +19 -4
- package/dist/chunk-7GPQPLGO.js.map +1 -0
- package/dist/{chunk-EPK6A3WJ.js → chunk-A3JMGXPG.js} +2 -2
- package/dist/chunk-A3JMGXPG.js.map +1 -0
- package/dist/{chunk-FXQYZNOW.js → chunk-A7DNZVAV.js} +1 -1
- package/dist/chunk-A7DNZVAV.js.map +1 -0
- package/dist/{chunk-UMLVJTYV.js → chunk-ADB7GPM3.js} +7 -4
- package/dist/chunk-ADB7GPM3.js.map +1 -0
- package/dist/{chunk-YL2DR3HY.js → chunk-ASIGWYRA.js} +2 -2
- package/dist/chunk-ASIGWYRA.js.map +1 -0
- package/dist/{chunk-2EYC3WDT.js → chunk-AWU4JF7C.js} +93 -93
- package/dist/chunk-AWU4JF7C.js.map +1 -0
- package/dist/chunk-BEZ2EV43.js +129 -0
- package/dist/chunk-BEZ2EV43.js.map +1 -0
- package/dist/{chunk-IS5HWQO7.js → chunk-CIZDUAHI.js} +30 -4
- package/dist/chunk-CIZDUAHI.js.map +1 -0
- package/dist/{chunk-4OQWR46B.js → chunk-CUPTCF4R.js} +5 -5
- package/dist/chunk-CUPTCF4R.js.map +1 -0
- package/dist/{chunk-5ZGZ6HIZ.js → chunk-DEE4CRYN.js} +30 -7
- package/dist/chunk-DEE4CRYN.js.map +1 -0
- package/dist/{chunk-UOF74WQY.js → chunk-E2MDPPOC.js} +37 -2
- package/dist/chunk-E2MDPPOC.js.map +1 -0
- package/dist/{chunk-SAVQ6E2O.js → chunk-FFKQ65YX.js} +10 -3
- package/dist/chunk-FFKQ65YX.js.map +1 -0
- package/dist/{chunk-2XLVPKXG.js → chunk-G7ALNCQH.js} +10 -2
- package/dist/chunk-G7ALNCQH.js.map +1 -0
- package/dist/chunk-GGXN73NM.js +252 -0
- package/dist/chunk-GGXN73NM.js.map +1 -0
- package/dist/{chunk-UVPGJXVO.js → chunk-JOJPBZSZ.js} +5 -5
- package/dist/{chunk-YDLAFP36.js → chunk-JZ5DS4DP.js} +346 -3
- package/dist/chunk-JZ5DS4DP.js.map +1 -0
- package/dist/{chunk-KMI2NBBF.js → chunk-K4JID2ZE.js} +44 -8
- package/dist/chunk-K4JID2ZE.js.map +1 -0
- package/dist/{aggregate/index.cjs → chunk-K6NVSHAH.js} +241 -210
- package/dist/chunk-K6NVSHAH.js.map +1 -0
- package/dist/chunk-KJ3K5VZM.js +524 -0
- package/dist/chunk-KJ3K5VZM.js.map +1 -0
- package/dist/chunk-L5HHBOMS.js +232 -0
- package/dist/chunk-L5HHBOMS.js.map +1 -0
- package/dist/{chunk-YK72A4IT.js → chunk-LBILABKZ.js} +4 -4
- package/dist/chunk-LXKBG52H.js +151 -0
- package/dist/chunk-LXKBG52H.js.map +1 -0
- package/dist/{chunk-NGSPBLLE.js → chunk-MPIZQGFA.js} +50 -20
- package/dist/chunk-MPIZQGFA.js.map +1 -0
- package/dist/{chunk-4X2S7PBF.js → chunk-MRJPSXPE.js} +84 -70
- package/dist/chunk-MRJPSXPE.js.map +1 -0
- package/dist/{chunk-6S3LLAQ5.js → chunk-MSMDDDDJ.js} +3 -3
- package/dist/{chunk-6S3LLAQ5.js.map → chunk-MSMDDDDJ.js.map} +1 -1
- package/dist/{chunk-GAUBWHAF.js → chunk-OCYFFBZS.js} +4 -4
- package/dist/{chunk-NCO2JGKK.js → chunk-PDVP3C2I.js} +1 -1
- package/dist/chunk-PDVP3C2I.js.map +1 -0
- package/dist/chunk-PZ5AY32C.js +10 -0
- package/dist/{chunk-P6256WTJ.js → chunk-QBLPY44S.js} +3 -3
- package/dist/chunk-QBLPY44S.js.map +1 -0
- package/dist/{query/index.cjs → chunk-QGBBQKDS.js} +706 -831
- package/dist/chunk-QGBBQKDS.js.map +1 -0
- package/dist/{chunk-FS7A4XNF.js → chunk-QWJCNXH2.js} +3 -3
- package/dist/chunk-QXWJQ7UU.js +380 -0
- package/dist/chunk-QXWJQ7UU.js.map +1 -0
- package/dist/{chunk-GDTCGIPX.js → chunk-RCB6GWTC.js} +27 -5
- package/dist/chunk-RCB6GWTC.js.map +1 -0
- package/dist/{chunk-K5PVGKE4.js → chunk-SAAJYSVV.js} +2 -2
- package/dist/{chunk-G7PAZ3TD.js → chunk-SHJ3BRTZ.js} +46 -10
- package/dist/chunk-SHJ3BRTZ.js.map +1 -0
- package/dist/chunk-SQXTKZL7.js +125 -0
- package/dist/chunk-SQXTKZL7.js.map +1 -0
- package/dist/chunk-STNPB3UM.js +9 -0
- package/dist/chunk-STNPB3UM.js.map +1 -0
- package/dist/{chunk-NSLTPGEN.js → chunk-TMUMMAWV.js} +12 -2
- package/dist/{chunk-NSLTPGEN.js.map → chunk-TMUMMAWV.js.map} +1 -1
- package/dist/{chunk-LS3JLEIB.js → chunk-TZGWI5AX.js} +4 -4
- package/dist/{chunk-GD3BGKAR.js → chunk-UBF5JEOJ.js} +44 -5
- package/dist/chunk-UBF5JEOJ.js.map +1 -0
- package/dist/{chunk-T6HQMVML.js → chunk-W5NVNJDX.js} +5250 -801
- package/dist/chunk-W5NVNJDX.js.map +1 -0
- package/dist/chunk-XAYDHD2O.js +123 -0
- package/dist/chunk-XAYDHD2O.js.map +1 -0
- package/dist/{chunk-LOL725S4.js → chunk-XYW2CSCI.js} +31 -3
- package/dist/chunk-XYW2CSCI.js.map +1 -0
- package/dist/{chunk-TLFUDXVV.js → chunk-ZCMOS4H2.js} +31 -10
- package/dist/chunk-ZCMOS4H2.js.map +1 -0
- package/dist/{chunk-FBMXWVGP.js → chunk-ZK66B5EY.js} +450 -30
- package/dist/chunk-ZK66B5EY.js.map +1 -0
- package/dist/{chunk-GVXBHCZ2.js → chunk-ZPJSQPQH.js} +66 -7
- package/dist/chunk-ZPJSQPQH.js.map +1 -0
- package/dist/consent/index.d.ts +8 -6
- package/dist/consent/index.js +4 -3
- package/dist/consent/index.js.map +1 -1
- package/dist/crdt/index.js +1 -0
- package/dist/crdt/index.js.map +1 -1
- package/dist/{crypto-H2Y3DDFW.js → crypto-OSIV2IIW.js} +8 -3
- package/dist/{ulid-CiM2OAeM.d.ts → decrypt-partition-CXS5KopB.d.ts} +37 -82
- package/dist/{delegation-QSC7G5QC.js → delegation-BQTRJATI.js} +6 -5
- package/dist/derivations/index.d.ts +11 -9
- package/dist/derivations/index.js +9 -6
- package/dist/{dev-unlock-Cf2B7Kih.d.ts → dev-unlock-CnHTTVea.d.ts} +1 -1
- package/dist/discriminant-BN9REW3o.d.ts +60 -0
- package/dist/errors-BAWO5Z5a.d.ts +1500 -0
- package/dist/executor-KYSKFJ2R.js +9 -0
- package/dist/executor-M7W3NEKR.js +9 -0
- package/dist/executor-VDTDGWO6.js +13 -0
- package/dist/{fanout-sidecar-NRBWSLRK.js → fanout-sidecar-AZALISHB.js} +3 -2
- package/dist/fanout-sidecar-AZALISHB.js.map +1 -0
- package/dist/forget/index.d.ts +1 -0
- package/dist/forget/index.js +15 -0
- package/dist/guards/index.d.ts +16 -8
- package/dist/guards/index.js +12 -5
- package/dist/{hash-gVn_uKhp.d.ts → hash-oc5paYl0.d.ts} +1 -1
- package/dist/history/index.d.ts +9 -7
- package/dist/history/index.js +10 -7
- package/dist/history/index.js.map +1 -1
- package/dist/i18n/index.d.ts +8 -6
- package/dist/i18n/index.js +116 -15
- package/dist/i18n/index.js.map +1 -1
- package/dist/index-BMmajblo.d.ts +362 -0
- package/dist/index-BmhGztUi.d.ts +93 -0
- package/dist/{types-D9eB0Rvh.d.ts → index-DHn9lEP0.d.ts} +4305 -1523
- package/dist/{index-BF1B2HB9.d.ts → index-Ddm8D3Oo.d.ts} +186 -1151
- package/dist/index.d.ts +342 -70
- package/dist/index.js +420 -112
- package/dist/index.js.map +1 -1
- package/dist/indexing/index.d.ts +3 -3
- package/dist/indexing/index.js +5 -4
- package/dist/indexing/index.js.map +1 -1
- package/dist/issue-DPHRF2TI.js +13 -0
- package/dist/kernel/index.d.ts +11 -0
- package/dist/kernel/index.js +50 -0
- package/dist/{lazy-builder-Rpd-V3jP.d.ts → lazy-builder-ChSqcF5t.d.ts} +2 -2
- package/dist/{ledger-WOEJUYTP.js → ledger-CI7GSMLB.js} +7 -6
- package/dist/materialized-views/index.d.ts +23 -20
- package/dist/materialized-views/index.js +9 -7
- package/dist/mime-magic-JeLKHRng.d.ts +103 -0
- package/dist/noydb-NAU2DTFP.js +40 -0
- package/dist/overlay-views/index.d.ts +32 -12
- package/dist/overlay-views/index.js +7 -6
- package/dist/periods/index.d.ts +8 -6
- package/dist/periods/index.js +7 -6
- package/dist/{predicate-Dnu81tsS.d.cts → predicate-BmhBSPCH.d.ts} +87 -5
- package/dist/{public-envelope-OHQ5UZFM.js → public-envelope-MFMBFJLZ.js} +5 -4
- package/dist/query/index.d.ts +4 -3
- package/dist/query/index.js +14 -6
- package/dist/read-only-facade-3OQRZ3VS.js +8 -0
- package/dist/registry-IX5WKK4F.js +8 -0
- package/dist/registry-LMHO5265.js +11 -0
- package/dist/registry-TXCKWH26.js +9 -0
- package/dist/registry-VFEDQSYV.js +9 -0
- package/dist/revoke-5PUOZPJJ.js +18 -0
- package/dist/revoke-5PUOZPJJ.js.map +1 -0
- package/dist/sealed-record/index.d.ts +123 -0
- package/dist/sealed-record/index.js +43 -0
- package/dist/sealed-record/index.js.map +1 -0
- package/dist/session/index.d.ts +9 -7
- package/dist/session/index.js +4 -3
- package/dist/session/index.js.map +1 -1
- package/dist/shadow/index.d.ts +8 -6
- package/dist/shadow/index.js +3 -2
- package/dist/shadow/index.js.map +1 -1
- package/dist/{signer-M4K5HBLD.js → signer-UB5TQOZ6.js} +6 -5
- package/dist/signer-UB5TQOZ6.js.map +1 -0
- package/dist/snapshots/index.d.ts +30 -0
- package/dist/snapshots/index.js +153 -0
- package/dist/snapshots/index.js.map +1 -0
- package/dist/{stale-PAGCS4K5.js → stale-J3TUF5C5.js} +3 -2
- package/dist/stale-J3TUF5C5.js.map +1 -0
- package/dist/store/index.d.ts +15 -6
- package/dist/store/index.js +3 -2
- package/dist/{strategy-DSTrsZ8t.d.ts → strategy-8QGs5KQE.d.ts} +475 -7
- package/dist/sync/index.d.ts +7 -5
- package/dist/sync/index.js +5 -4
- package/dist/sync/index.js.map +1 -1
- package/dist/team/index.d.ts +8 -6
- package/dist/team/index.js +9 -8
- package/dist/transition-guard-Dy3NioQr.d.ts +165 -0
- package/dist/tx/index.d.ts +26 -8
- package/dist/tx/index.js +10 -5
- package/dist/tx/index.js.map +1 -1
- package/dist/ulid-DRH25k3y.d.ts +66 -0
- package/dist/{ulid-COREQ2RQ.js → ulid-KEPZMD2N.js} +2 -1
- package/dist/ulid-KEPZMD2N.js.map +1 -0
- package/dist/util/index.d.ts +2 -0
- package/dist/util/index.js +6 -1
- package/dist/util/index.js.map +1 -1
- package/dist/{with-materialized-view-qtoJ3xKJ.d.ts → with-materialized-view-DIVeez0W.d.ts} +2 -2
- package/dist/{with-overlayed-view-DFaRfgMr.d.ts → with-overlayed-view-DVZrc5Hb.d.ts} +2 -2
- package/dist/with-rollup-CbU-O4wP.d.ts +47 -0
- package/dist/zod-HAJM7LMS.js +14763 -0
- package/dist/zod-HAJM7LMS.js.map +1 -0
- package/package.json +73 -191
- package/dist/aggregate/index.cjs.map +0 -1
- package/dist/aggregate/index.d.cts +0 -38
- package/dist/attestation/index.cjs +0 -305
- package/dist/attestation/index.cjs.map +0 -1
- package/dist/attestation/index.d.cts +0 -52
- package/dist/blobs/index.cjs +0 -1480
- package/dist/blobs/index.cjs.map +0 -1
- package/dist/blobs/index.d.cts +0 -46
- package/dist/bundle/index.cjs +0 -18561
- package/dist/bundle/index.cjs.map +0 -1
- package/dist/bundle/index.d.cts +0 -176
- package/dist/chunk-2EYC3WDT.js.map +0 -1
- package/dist/chunk-2XLVPKXG.js.map +0 -1
- package/dist/chunk-4OQWR46B.js.map +0 -1
- package/dist/chunk-4UBOTYP5.js +0 -1367
- package/dist/chunk-4UBOTYP5.js.map +0 -1
- package/dist/chunk-4X2S7PBF.js.map +0 -1
- package/dist/chunk-5YHWBPOT.js +0 -19
- package/dist/chunk-5YHWBPOT.js.map +0 -1
- package/dist/chunk-5ZGZ6HIZ.js.map +0 -1
- package/dist/chunk-74JEQFMT.js.map +0 -1
- package/dist/chunk-A6SWRXUQ.js +0 -118
- package/dist/chunk-A6SWRXUQ.js.map +0 -1
- package/dist/chunk-BFI3RS42.js.map +0 -1
- package/dist/chunk-EMEX37ZN.js +0 -51
- package/dist/chunk-EMEX37ZN.js.map +0 -1
- package/dist/chunk-EPK6A3WJ.js.map +0 -1
- package/dist/chunk-FBMXWVGP.js.map +0 -1
- package/dist/chunk-FXQYZNOW.js.map +0 -1
- package/dist/chunk-G7PAZ3TD.js.map +0 -1
- package/dist/chunk-GD3BGKAR.js.map +0 -1
- package/dist/chunk-GDTCGIPX.js.map +0 -1
- package/dist/chunk-GVXBHCZ2.js.map +0 -1
- package/dist/chunk-HGZ7DC5H.js.map +0 -1
- package/dist/chunk-IS5HWQO7.js.map +0 -1
- package/dist/chunk-KMI2NBBF.js.map +0 -1
- package/dist/chunk-KYKMKLJ6.js +0 -340
- package/dist/chunk-KYKMKLJ6.js.map +0 -1
- package/dist/chunk-LOL725S4.js.map +0 -1
- package/dist/chunk-MRIBLZL3.js +0 -86
- package/dist/chunk-MRIBLZL3.js.map +0 -1
- package/dist/chunk-NCO2JGKK.js.map +0 -1
- package/dist/chunk-NGSPBLLE.js.map +0 -1
- package/dist/chunk-P6256WTJ.js.map +0 -1
- package/dist/chunk-SAVQ6E2O.js.map +0 -1
- package/dist/chunk-T6HQMVML.js.map +0 -1
- package/dist/chunk-TLFUDXVV.js.map +0 -1
- package/dist/chunk-UMLVJTYV.js.map +0 -1
- package/dist/chunk-UOF74WQY.js.map +0 -1
- package/dist/chunk-WRLHNG6H.js.map +0 -1
- package/dist/chunk-YDLAFP36.js.map +0 -1
- package/dist/chunk-YL2DR3HY.js.map +0 -1
- package/dist/chunk-YMYK7US4.js.map +0 -1
- package/dist/chunk-ZC2AAE6J.js.map +0 -1
- package/dist/consent/index.cjs +0 -204
- package/dist/consent/index.cjs.map +0 -1
- package/dist/consent/index.d.cts +0 -25
- package/dist/crdt/index.cjs +0 -152
- package/dist/crdt/index.cjs.map +0 -1
- package/dist/crdt/index.d.cts +0 -30
- package/dist/derivations/index.cjs +0 -351
- package/dist/derivations/index.cjs.map +0 -1
- package/dist/derivations/index.d.cts +0 -72
- package/dist/dev-unlock-De3mjQWv.d.cts +0 -263
- package/dist/executor-BZKFZVRC.js +0 -8
- package/dist/executor-GFZFDQXV.js +0 -8
- package/dist/executor-KT2IOZVP.js +0 -11
- package/dist/fanout-sidecar-NRBWSLRK.js.map +0 -1
- package/dist/guards/index.cjs +0 -322
- package/dist/guards/index.cjs.map +0 -1
- package/dist/guards/index.d.cts +0 -31
- package/dist/hash-vBCB0-Ps.d.cts +0 -63
- package/dist/history/index.cjs +0 -1222
- package/dist/history/index.cjs.map +0 -1
- package/dist/history/index.d.cts +0 -63
- package/dist/i18n/index.cjs +0 -840
- package/dist/i18n/index.cjs.map +0 -1
- package/dist/i18n/index.d.cts +0 -39
- package/dist/index-DVkvrgpm.d.cts +0 -2290
- package/dist/index.cjs +0 -23590
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -778
- package/dist/indexing/index.cjs +0 -738
- package/dist/indexing/index.cjs.map +0 -1
- package/dist/indexing/index.d.cts +0 -36
- package/dist/issue-BAJ7ZB4S.js +0 -12
- package/dist/lazy-builder-C-rPfWG0.d.cts +0 -304
- package/dist/materialized-views/index.cjs +0 -837
- package/dist/materialized-views/index.cjs.map +0 -1
- package/dist/materialized-views/index.d.cts +0 -184
- package/dist/mime-magic-CBBSOkjm.d.cts +0 -50
- package/dist/mime-magic-CBBSOkjm.d.ts +0 -50
- package/dist/noydb-XNQSKXGO.js +0 -34
- package/dist/overlay-views/index.cjs +0 -359
- package/dist/overlay-views/index.cjs.map +0 -1
- package/dist/overlay-views/index.d.cts +0 -82
- package/dist/periods/index.cjs +0 -1041
- package/dist/periods/index.cjs.map +0 -1
- package/dist/periods/index.d.cts +0 -22
- package/dist/predicate-Dnu81tsS.d.ts +0 -185
- package/dist/query/index.cjs.map +0 -1
- package/dist/query/index.d.cts +0 -3
- package/dist/read-only-facade-ITU6L7BL.js +0 -7
- package/dist/registry-2IEARCGT.js +0 -7
- package/dist/registry-CDHASH73.js +0 -10
- package/dist/registry-EMGLZGR6.js +0 -8
- package/dist/registry-NQALYR77.js +0 -8
- package/dist/revoke-7JOVLZFD.js +0 -17
- package/dist/session/index.cjs +0 -495
- package/dist/session/index.cjs.map +0 -1
- package/dist/session/index.d.cts +0 -46
- package/dist/shadow/index.cjs +0 -133
- package/dist/shadow/index.cjs.map +0 -1
- package/dist/shadow/index.d.cts +0 -17
- package/dist/store/index.cjs +0 -1083
- package/dist/store/index.cjs.map +0 -1
- package/dist/store/index.d.cts +0 -492
- package/dist/strategy-BSxFXGzb.d.cts +0 -110
- package/dist/strategy-DSTrsZ8t.d.cts +0 -601
- package/dist/sync/index.cjs +0 -1062
- package/dist/sync/index.cjs.map +0 -1
- package/dist/sync/index.d.cts +0 -43
- package/dist/team/index.cjs +0 -2798
- package/dist/team/index.cjs.map +0 -1
- package/dist/team/index.d.cts +0 -118
- package/dist/tx/index.cjs +0 -544
- package/dist/tx/index.cjs.map +0 -1
- package/dist/tx/index.d.cts +0 -21
- package/dist/types-CSLcfytP.d.cts +0 -12493
- package/dist/ulid-CG2YvAbg.d.cts +0 -603
- package/dist/util/index.cjs +0 -230
- package/dist/util/index.cjs.map +0 -1
- package/dist/util/index.d.cts +0 -77
- package/dist/with-derivation-Bzpj6UTv.d.ts +0 -13
- package/dist/with-derivation-DWajFh4K.d.cts +0 -13
- package/dist/with-guard-DF_Ul3DT.d.cts +0 -18
- package/dist/with-guard-DR7U-l4v.d.ts +0 -18
- package/dist/with-materialized-view-_piodoIz.d.cts +0 -27
- package/dist/with-overlayed-view-DwzCKxn2.d.cts +0 -13
- /package/dist/{crypto-H2Y3DDFW.js.map → adapter/index.js.map} +0 -0
- /package/dist/{chunk-75QDHSE4.js.map → chunk-2QDWRK3B.js.map} +0 -0
- /package/dist/{chunk-FCDO7UAO.js.map → chunk-2ZYIN3BL.js.map} +0 -0
- /package/dist/{chunk-ZUMGGHRB.js.map → chunk-5PTX7PKD.js.map} +0 -0
- /package/dist/{chunk-QAU5HM6Q.js.map → chunk-6EKRQ7QF.js.map} +0 -0
- /package/dist/{chunk-UVPGJXVO.js.map → chunk-JOJPBZSZ.js.map} +0 -0
- /package/dist/{chunk-YK72A4IT.js.map → chunk-LBILABKZ.js.map} +0 -0
- /package/dist/{chunk-GAUBWHAF.js.map → chunk-OCYFFBZS.js.map} +0 -0
- /package/dist/{delegation-QSC7G5QC.js.map → chunk-PZ5AY32C.js.map} +0 -0
- /package/dist/{chunk-FS7A4XNF.js.map → chunk-QWJCNXH2.js.map} +0 -0
- /package/dist/{chunk-K5PVGKE4.js.map → chunk-SAAJYSVV.js.map} +0 -0
- /package/dist/{chunk-LS3JLEIB.js.map → chunk-TZGWI5AX.js.map} +0 -0
- /package/dist/{executor-BZKFZVRC.js.map → crypto-OSIV2IIW.js.map} +0 -0
- /package/dist/{executor-GFZFDQXV.js.map → delegation-BQTRJATI.js.map} +0 -0
- /package/dist/{executor-KT2IOZVP.js.map → executor-KYSKFJ2R.js.map} +0 -0
- /package/dist/{issue-BAJ7ZB4S.js.map → executor-M7W3NEKR.js.map} +0 -0
- /package/dist/{ledger-WOEJUYTP.js.map → executor-VDTDGWO6.js.map} +0 -0
- /package/dist/{noydb-XNQSKXGO.js.map → forget/index.js.map} +0 -0
- /package/dist/{public-envelope-OHQ5UZFM.js.map → issue-DPHRF2TI.js.map} +0 -0
- /package/dist/{read-only-facade-ITU6L7BL.js.map → kernel/index.js.map} +0 -0
- /package/dist/{registry-2IEARCGT.js.map → ledger-CI7GSMLB.js.map} +0 -0
- /package/dist/{registry-CDHASH73.js.map → noydb-NAU2DTFP.js.map} +0 -0
- /package/dist/{registry-EMGLZGR6.js.map → public-envelope-MFMBFJLZ.js.map} +0 -0
- /package/dist/{registry-NQALYR77.js.map → read-only-facade-3OQRZ3VS.js.map} +0 -0
- /package/dist/{revoke-7JOVLZFD.js.map → registry-IX5WKK4F.js.map} +0 -0
- /package/dist/{signer-M4K5HBLD.js.map → registry-LMHO5265.js.map} +0 -0
- /package/dist/{stale-PAGCS4K5.js.map → registry-TXCKWH26.js.map} +0 -0
- /package/dist/{ulid-COREQ2RQ.js.map → registry-VFEDQSYV.js.map} +0 -0
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import {
|
|
2
|
+
LocaleNotSpecifiedError,
|
|
3
|
+
MissingTranslationError,
|
|
4
|
+
ScriptViolationError
|
|
5
|
+
} from "./chunk-JZ5DS4DP.js";
|
|
6
|
+
|
|
7
|
+
// src/i18n/policy.ts
|
|
8
|
+
function resolvePolicy(onMissing, layer) {
|
|
9
|
+
const explicit = onMissing && typeof onMissing === "object" ? onMissing[layer] : void 0;
|
|
10
|
+
const scalar = typeof onMissing === "string" ? onMissing : void 0;
|
|
11
|
+
const layerDefault = layer === "guard" ? "substitute" : void 0;
|
|
12
|
+
return explicit ?? layerDefault ?? scalar ?? "throw";
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// src/i18n/script.ts
|
|
16
|
+
var LATIN_BASE = /* @__PURE__ */ new Set([
|
|
17
|
+
"en",
|
|
18
|
+
"fr",
|
|
19
|
+
"de",
|
|
20
|
+
"es",
|
|
21
|
+
"it",
|
|
22
|
+
"pt",
|
|
23
|
+
"nl",
|
|
24
|
+
"sv",
|
|
25
|
+
"no",
|
|
26
|
+
"da",
|
|
27
|
+
"fi",
|
|
28
|
+
"is",
|
|
29
|
+
"pl",
|
|
30
|
+
"cs",
|
|
31
|
+
"sk",
|
|
32
|
+
"hu",
|
|
33
|
+
"ro",
|
|
34
|
+
"hr",
|
|
35
|
+
"sl",
|
|
36
|
+
"et",
|
|
37
|
+
"lv",
|
|
38
|
+
"lt",
|
|
39
|
+
"tr",
|
|
40
|
+
"vi",
|
|
41
|
+
"id",
|
|
42
|
+
"ms",
|
|
43
|
+
"tl",
|
|
44
|
+
"sw",
|
|
45
|
+
"af",
|
|
46
|
+
"ca",
|
|
47
|
+
"gl",
|
|
48
|
+
"eu",
|
|
49
|
+
"cy",
|
|
50
|
+
"ga"
|
|
51
|
+
]);
|
|
52
|
+
var SCRIPT_TABLE = {
|
|
53
|
+
th: ["Thai"],
|
|
54
|
+
ko: ["Hangul", "Han"],
|
|
55
|
+
ja: ["Han", "Hiragana", "Katakana"],
|
|
56
|
+
zh: ["Han"],
|
|
57
|
+
ar: ["Arabic"],
|
|
58
|
+
fa: ["Arabic"],
|
|
59
|
+
ur: ["Arabic"],
|
|
60
|
+
ru: ["Cyrillic"],
|
|
61
|
+
uk: ["Cyrillic"],
|
|
62
|
+
bg: ["Cyrillic"],
|
|
63
|
+
sr: ["Cyrillic"],
|
|
64
|
+
he: ["Hebrew"],
|
|
65
|
+
el: ["Greek"],
|
|
66
|
+
hi: ["Devanagari"],
|
|
67
|
+
ta: ["Tamil"],
|
|
68
|
+
km: ["Khmer"],
|
|
69
|
+
lo: ["Lao"],
|
|
70
|
+
my: ["Myanmar"]
|
|
71
|
+
};
|
|
72
|
+
var SUBTAG_SCRIPTS = {
|
|
73
|
+
Latn: ["Latin"],
|
|
74
|
+
Cyrl: ["Cyrillic", "Latin"],
|
|
75
|
+
Hans: ["Han", "Latin"],
|
|
76
|
+
Hant: ["Han", "Latin"],
|
|
77
|
+
Thai: ["Thai", "Latin"],
|
|
78
|
+
Arab: ["Arabic", "Latin"]
|
|
79
|
+
};
|
|
80
|
+
function inferScripts(locale) {
|
|
81
|
+
const parts = locale.split("-");
|
|
82
|
+
const subtag = parts.find((t) => /^[A-Z][a-z]{3}$/.test(t));
|
|
83
|
+
if (subtag && SUBTAG_SCRIPTS[subtag]) return SUBTAG_SCRIPTS[subtag];
|
|
84
|
+
const base = (parts[0] ?? "").toLowerCase();
|
|
85
|
+
if (LATIN_BASE.has(base)) return ["Latin"];
|
|
86
|
+
const primary = SCRIPT_TABLE[base];
|
|
87
|
+
if (primary) return [...primary, "Latin"];
|
|
88
|
+
return ["Latin"];
|
|
89
|
+
}
|
|
90
|
+
function allowedFor(descriptor, locale) {
|
|
91
|
+
const script = descriptor.options.script;
|
|
92
|
+
if (script && script !== "auto") {
|
|
93
|
+
const explicit = script[locale];
|
|
94
|
+
if (explicit) return explicit;
|
|
95
|
+
}
|
|
96
|
+
return inferScripts(locale);
|
|
97
|
+
}
|
|
98
|
+
var BASELINE = String.raw`\p{White_Space}\p{Script=Common}\p{Script=Inherited}\p{Mark}`;
|
|
99
|
+
function fullMatcher(scripts) {
|
|
100
|
+
const cls = scripts.map((s) => `\\p{Script=${s}}`).join("");
|
|
101
|
+
return new RegExp(`^[${BASELINE}${cls}]*$`, "u");
|
|
102
|
+
}
|
|
103
|
+
function charMatcher(scripts) {
|
|
104
|
+
const cls = scripts.map((s) => `\\p{Script=${s}}`).join("");
|
|
105
|
+
return new RegExp(`[${BASELINE}${cls}]`, "u");
|
|
106
|
+
}
|
|
107
|
+
function offendingSample(str, scripts) {
|
|
108
|
+
const ok = charMatcher(scripts);
|
|
109
|
+
const bad = [];
|
|
110
|
+
for (const ch of str) {
|
|
111
|
+
if (!ok.test(ch)) bad.push(ch);
|
|
112
|
+
if (bad.length >= 8) break;
|
|
113
|
+
}
|
|
114
|
+
return bad.join("");
|
|
115
|
+
}
|
|
116
|
+
function stripDisallowed(str, scripts) {
|
|
117
|
+
const ok = charMatcher(scripts);
|
|
118
|
+
let out = "";
|
|
119
|
+
for (const ch of str) if (ok.test(ch)) out += ch;
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
function enforceScript(value, field, descriptor, exempt) {
|
|
123
|
+
const opt = descriptor.options;
|
|
124
|
+
if (!opt.script) return { value, warnings: [] };
|
|
125
|
+
const mode = opt.onScriptViolation ?? "reject";
|
|
126
|
+
const warnings = [];
|
|
127
|
+
let out = value;
|
|
128
|
+
for (const [locale, raw] of Object.entries(value)) {
|
|
129
|
+
if (exempt?.has(locale)) continue;
|
|
130
|
+
if (typeof raw !== "string") continue;
|
|
131
|
+
const allowed = allowedFor(descriptor, locale);
|
|
132
|
+
if (fullMatcher(allowed).test(raw)) continue;
|
|
133
|
+
const sample = offendingSample(raw, allowed);
|
|
134
|
+
if (mode === "reject") {
|
|
135
|
+
throw new ScriptViolationError(field, locale, allowed, sample);
|
|
136
|
+
}
|
|
137
|
+
warnings.push({ field, locale, expected: allowed, sample });
|
|
138
|
+
if (mode === "filter") {
|
|
139
|
+
if (out === value) out = { ...value };
|
|
140
|
+
out[locale] = stripDisallowed(raw, allowed);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return { value: out, warnings };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// src/i18n/core.ts
|
|
147
|
+
function i18nText(options) {
|
|
148
|
+
if (options.densifyOnWrite === true && hasThrowPolicy(options.onMissing)) {
|
|
149
|
+
throw new Error(
|
|
150
|
+
`i18nText: densifyOnWrite cannot be combined with an explicit onMissing 'throw' policy \u2014 densify fills every empty slot, so a 'throw' would be unreachable. Remove the 'throw' policy or disable densifyOnWrite.`
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
return { _noydbI18nText: true, options };
|
|
154
|
+
}
|
|
155
|
+
function hasThrowPolicy(onMissing) {
|
|
156
|
+
if (onMissing === void 0) return false;
|
|
157
|
+
if (typeof onMissing === "string") return onMissing === "throw";
|
|
158
|
+
return Object.values(onMissing).includes("throw");
|
|
159
|
+
}
|
|
160
|
+
function isI18nTextDescriptor(x) {
|
|
161
|
+
return typeof x === "object" && x !== null && x._noydbI18nText === true;
|
|
162
|
+
}
|
|
163
|
+
function validateI18nTextValue(value, field, descriptor) {
|
|
164
|
+
const { options } = descriptor;
|
|
165
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
166
|
+
throw new MissingTranslationError(
|
|
167
|
+
field,
|
|
168
|
+
options.languages,
|
|
169
|
+
`Field "${field}" must be a { [locale]: string } map, got ${typeof value}.`
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
const map = value;
|
|
173
|
+
for (const [locale, v] of Object.entries(map)) {
|
|
174
|
+
if (typeof v !== "string") {
|
|
175
|
+
throw new MissingTranslationError(
|
|
176
|
+
field,
|
|
177
|
+
[locale],
|
|
178
|
+
`Field "${field}": locale "${locale}" must be a string, got ${typeof v}.`
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
const { required } = options;
|
|
183
|
+
if (required === "all") {
|
|
184
|
+
const missing = options.languages.filter(
|
|
185
|
+
(lang) => !(lang in map) || map[lang] === ""
|
|
186
|
+
);
|
|
187
|
+
if (missing.length > 0) {
|
|
188
|
+
throw new MissingTranslationError(
|
|
189
|
+
field,
|
|
190
|
+
missing,
|
|
191
|
+
`Field "${field}" requires all declared languages. Missing: ${missing.join(", ")}.`
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
} else if (required === "any") {
|
|
195
|
+
const present = options.languages.some(
|
|
196
|
+
(lang) => lang in map && map[lang] !== ""
|
|
197
|
+
);
|
|
198
|
+
if (!present) {
|
|
199
|
+
throw new MissingTranslationError(
|
|
200
|
+
field,
|
|
201
|
+
options.languages,
|
|
202
|
+
`Field "${field}" requires at least one declared language. None present.`
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
} else {
|
|
206
|
+
const requiredList = required;
|
|
207
|
+
const missing = requiredList.filter(
|
|
208
|
+
(lang) => !(lang in map) || map[lang] === ""
|
|
209
|
+
);
|
|
210
|
+
if (missing.length > 0) {
|
|
211
|
+
throw new MissingTranslationError(
|
|
212
|
+
field,
|
|
213
|
+
missing,
|
|
214
|
+
`Field "${field}" requires: ${requiredList.join(", ")}. Missing: ${missing.join(", ")}.`
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
function toChain(fallback) {
|
|
220
|
+
return Array.isArray(fallback) ? fallback : fallback ? [fallback] : [];
|
|
221
|
+
}
|
|
222
|
+
function pickFromChain(value, chain) {
|
|
223
|
+
for (const fb of chain) {
|
|
224
|
+
if (fb === "any") {
|
|
225
|
+
const any = Object.values(value).find((v) => v !== "");
|
|
226
|
+
if (any !== void 0) return any;
|
|
227
|
+
} else if (value[fb] !== void 0 && value[fb] !== "") {
|
|
228
|
+
return value[fb];
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return void 0;
|
|
232
|
+
}
|
|
233
|
+
function resolveI18nText(value, locale, fallback, field, opts) {
|
|
234
|
+
if (locale === "raw") {
|
|
235
|
+
return value;
|
|
236
|
+
}
|
|
237
|
+
if (!locale) {
|
|
238
|
+
throw new LocaleNotSpecifiedError(field ?? "<unknown>");
|
|
239
|
+
}
|
|
240
|
+
if (value[locale] !== void 0 && value[locale] !== "") {
|
|
241
|
+
return value[locale];
|
|
242
|
+
}
|
|
243
|
+
const policy = opts?.policy ?? "throw";
|
|
244
|
+
const callerChain = toChain(fallback);
|
|
245
|
+
const callerHit = pickFromChain(value, callerChain);
|
|
246
|
+
if (callerHit !== void 0) return callerHit;
|
|
247
|
+
if (policy === "substitute") {
|
|
248
|
+
const subHit = pickFromChain(value, toChain(opts?.substitute));
|
|
249
|
+
if (subHit !== void 0) return subHit;
|
|
250
|
+
if (opts?.smartSubstitute) {
|
|
251
|
+
const smartHit = pickNearestScript(value, locale);
|
|
252
|
+
if (smartHit !== void 0) return smartHit;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (policy === "throw") {
|
|
256
|
+
throw new LocaleNotSpecifiedError(
|
|
257
|
+
field ?? "<unknown>",
|
|
258
|
+
`No translation available for locale "${locale}"` + (callerChain.length > 0 ? ` or fallback chain [${callerChain.join(", ")}]` : "") + "."
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
return null;
|
|
262
|
+
}
|
|
263
|
+
function pickNearestScript(value, target) {
|
|
264
|
+
const targetScript = inferScripts(target)[0] ?? "Latin";
|
|
265
|
+
let best;
|
|
266
|
+
for (const [loc, v] of Object.entries(value)) {
|
|
267
|
+
if (typeof v !== "string" || v === "") continue;
|
|
268
|
+
const s = inferScripts(loc)[0] ?? "Latin";
|
|
269
|
+
const score = s === targetScript ? 0 : s === "Latin" ? 1 : 2;
|
|
270
|
+
if (best === void 0 || score < best.score) best = { score, v };
|
|
271
|
+
if (score === 0) break;
|
|
272
|
+
}
|
|
273
|
+
return best?.v;
|
|
274
|
+
}
|
|
275
|
+
function getAtPath(obj, path) {
|
|
276
|
+
const arrayIdx = path.indexOf("[].");
|
|
277
|
+
if (arrayIdx !== -1) {
|
|
278
|
+
const arrayKey = path.slice(0, arrayIdx);
|
|
279
|
+
const restPath = path.slice(arrayIdx + 3);
|
|
280
|
+
const arr = obj[arrayKey];
|
|
281
|
+
if (!Array.isArray(arr)) return [];
|
|
282
|
+
return arr.flatMap((item) => {
|
|
283
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) return [];
|
|
284
|
+
return getAtPath(item, restPath);
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
const dotIdx = path.indexOf(".");
|
|
288
|
+
if (dotIdx !== -1) {
|
|
289
|
+
const head = path.slice(0, dotIdx);
|
|
290
|
+
const rest = path.slice(dotIdx + 1);
|
|
291
|
+
const nested = obj[head];
|
|
292
|
+
if (!nested || typeof nested !== "object" || Array.isArray(nested)) return [];
|
|
293
|
+
return getAtPath(nested, rest);
|
|
294
|
+
}
|
|
295
|
+
const val = obj[path];
|
|
296
|
+
return val !== void 0 ? [val] : [];
|
|
297
|
+
}
|
|
298
|
+
function setAtPathInPlace(obj, path, value) {
|
|
299
|
+
const dotIdx = path.indexOf(".");
|
|
300
|
+
if (dotIdx !== -1) {
|
|
301
|
+
const head = path.slice(0, dotIdx);
|
|
302
|
+
const rest = path.slice(dotIdx + 1);
|
|
303
|
+
const nested = obj[head];
|
|
304
|
+
if (!nested || typeof nested !== "object" || Array.isArray(nested)) return;
|
|
305
|
+
setAtPathInPlace(nested, rest, value);
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
obj[path] = value;
|
|
309
|
+
}
|
|
310
|
+
function applyAtPath(obj, path, locale, fallback, opts) {
|
|
311
|
+
const arrayIdx = path.indexOf("[].");
|
|
312
|
+
if (arrayIdx !== -1) {
|
|
313
|
+
const arrayKey = path.slice(0, arrayIdx);
|
|
314
|
+
const restPath = path.slice(arrayIdx + 3);
|
|
315
|
+
const arr = obj[arrayKey];
|
|
316
|
+
if (!Array.isArray(arr)) return obj;
|
|
317
|
+
return {
|
|
318
|
+
...obj,
|
|
319
|
+
[arrayKey]: arr.map((item) => {
|
|
320
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) return item;
|
|
321
|
+
return applyAtPath(item, restPath, locale, fallback, opts);
|
|
322
|
+
})
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
const dotIdx = path.indexOf(".");
|
|
326
|
+
if (dotIdx !== -1) {
|
|
327
|
+
const head = path.slice(0, dotIdx);
|
|
328
|
+
const rest = path.slice(dotIdx + 1);
|
|
329
|
+
const nested = obj[head];
|
|
330
|
+
if (!nested || typeof nested !== "object" || Array.isArray(nested)) return obj;
|
|
331
|
+
return {
|
|
332
|
+
...obj,
|
|
333
|
+
[head]: applyAtPath(nested, rest, locale, fallback, opts)
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
const raw = obj[path];
|
|
337
|
+
if (raw === void 0 || raw === null) return obj;
|
|
338
|
+
if (typeof raw !== "object" || Array.isArray(raw)) return obj;
|
|
339
|
+
return {
|
|
340
|
+
...obj,
|
|
341
|
+
[path]: resolveI18nText(raw, locale, fallback, path, opts)
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
function applyI18nLocale(record, i18nFields, locale, fallback, layer = "read") {
|
|
345
|
+
const fieldNames = Object.keys(i18nFields);
|
|
346
|
+
if (fieldNames.length === 0) return record;
|
|
347
|
+
let result = record;
|
|
348
|
+
for (const [field, descriptor] of Object.entries(i18nFields)) {
|
|
349
|
+
const { onMissing, substitute, smartSubstitute } = descriptor.options;
|
|
350
|
+
const opts = {
|
|
351
|
+
policy: resolvePolicy(onMissing, layer),
|
|
352
|
+
...substitute !== void 0 ? { substitute } : {},
|
|
353
|
+
...smartSubstitute ? { smartSubstitute } : {}
|
|
354
|
+
};
|
|
355
|
+
result = applyAtPath(result, field, locale, fallback, opts);
|
|
356
|
+
}
|
|
357
|
+
result = stripI18nFilled(result);
|
|
358
|
+
return result;
|
|
359
|
+
}
|
|
360
|
+
function stripI18nFilled(record) {
|
|
361
|
+
if (!Object.prototype.hasOwnProperty.call(record, "_i18nFilled")) return record;
|
|
362
|
+
const rest = { ...record };
|
|
363
|
+
delete rest._i18nFilled;
|
|
364
|
+
return rest;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
export {
|
|
368
|
+
resolvePolicy,
|
|
369
|
+
inferScripts,
|
|
370
|
+
enforceScript,
|
|
371
|
+
i18nText,
|
|
372
|
+
isI18nTextDescriptor,
|
|
373
|
+
validateI18nTextValue,
|
|
374
|
+
resolveI18nText,
|
|
375
|
+
getAtPath,
|
|
376
|
+
setAtPathInPlace,
|
|
377
|
+
applyI18nLocale,
|
|
378
|
+
stripI18nFilled
|
|
379
|
+
};
|
|
380
|
+
//# sourceMappingURL=chunk-QXWJQ7UU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/i18n/policy.ts","../src/i18n/script.ts","../src/i18n/core.ts"],"sourcesContent":["/**\n * Per-layer i18n resolution policy.\n *\n * `onMissing` governs what happens when a multilingual field is resolved\n * to a target locale that is absent. It may be a single scalar policy or\n * a per-layer map, so a field can be lenient at the app read boundary but\n * strict inside a materialized view.\n *\n * Effective policy for layer `λ`:\n *\n * ```\n * explicit(λ) = typeof onMissing === 'object' ? onMissing[λ] : undefined\n * scalar = typeof onMissing === 'string' ? onMissing : undefined\n * policy(λ) = explicit(λ) ?? layerDefault(λ) ?? scalar ?? 'throw'\n * ```\n *\n * - `layerDefault('guard') = 'substitute'` — guards are lenient unless\n * EXPLICITLY overridden; they never inherit a scalar policy (a guard\n * reading a display value must not hard-fail on a missing locale).\n * - every other layer has no default, so it inherits the scalar, else\n * falls back to `'throw'` (today's behavior — zero breaking change).\n *\n * @public\n */\nexport type OnMissing = 'substitute' | 'null' | 'throw'\n\n/**\n * The contexts in which a multilingual field is resolved. Each can carry\n * its own `onMissing` policy.\n *\n * - `read` — ordinary app reads (`get`/`list`/query projection).\n * - `guard` — a guard callback reading a value.\n * - `join` — a joined record expanded onto a row.\n * - `mv` — materialized-view input.\n * - `derivation` — derivation input.\n * - `export` — bundle/public-envelope export.\n */\nexport type Layer = 'read' | 'guard' | 'join' | 'mv' | 'derivation' | 'export'\n\n/** Field-level policy: a single scalar, or a per-layer map. */\nexport type OnMissingPolicy = OnMissing | Partial<Record<Layer, OnMissing>>\n\n/**\n * Resolve the effective `OnMissing` for a layer from a field's declared\n * policy. See module docs for the resolution rule.\n */\nexport function resolvePolicy(\n onMissing: OnMissingPolicy | undefined,\n layer: Layer,\n): OnMissing {\n const explicit =\n onMissing && typeof onMissing === 'object' ? onMissing[layer] : undefined\n const scalar = typeof onMissing === 'string' ? onMissing : undefined\n const layerDefault: OnMissing | undefined =\n layer === 'guard' ? 'substitute' : undefined\n return explicit ?? layerDefault ?? scalar ?? 'throw'\n}\n","/**\n * Per-locale script enforcement for `i18nText` fields (write-time).\n *\n * Each locale slot's string is validated against an allowed set of\n * Unicode scripts. `'auto'` infers the set from the locale code with\n * **asymmetric Latin tolerance** (#283): every non-Latin-script locale\n * also allows `Latin`, because proper names and addresses in those\n * locales routinely embed Latin brand/building/technical names — while\n * Latin-script locales do NOT allow other scripts, so the common error\n * (e.g. Thai text dumped into an `en` slot) is still caught.\n *\n * The always-on baseline is `Common` (digits, punctuation), `Inherited`\n * and `Mark` (combining diacritics, joiners, harakat, tone marks), and\n * whitespace — so Latin digits and in-script combining marks never\n * false-reject.\n *\n * @public\n */\nimport { ScriptViolationError } from '../errors.js'\nimport type { I18nTextDescriptor } from './core.js'\n\n/** Locales whose base language is written in the Latin script. */\nconst LATIN_BASE = new Set([\n 'en', 'fr', 'de', 'es', 'it', 'pt', 'nl', 'sv', 'no', 'da', 'fi', 'is',\n 'pl', 'cs', 'sk', 'hu', 'ro', 'hr', 'sl', 'et', 'lv', 'lt', 'tr', 'vi',\n 'id', 'ms', 'tl', 'sw', 'af', 'ca', 'gl', 'eu', 'cy', 'ga',\n])\n\n/** Base-language → primary (non-Latin) scripts. Latin is appended by inferScripts. */\nconst SCRIPT_TABLE: Record<string, readonly string[]> = {\n th: ['Thai'],\n ko: ['Hangul', 'Han'],\n ja: ['Han', 'Hiragana', 'Katakana'],\n zh: ['Han'],\n ar: ['Arabic'],\n fa: ['Arabic'],\n ur: ['Arabic'],\n ru: ['Cyrillic'],\n uk: ['Cyrillic'],\n bg: ['Cyrillic'],\n sr: ['Cyrillic'],\n he: ['Hebrew'],\n el: ['Greek'],\n hi: ['Devanagari'],\n ta: ['Tamil'],\n km: ['Khmer'],\n lo: ['Lao'],\n my: ['Myanmar'],\n}\n\n/** Map a BCP-47 script subtag (e.g. `Latn`, `Cyrl`) to allowed scripts. */\nconst SUBTAG_SCRIPTS: Record<string, readonly string[]> = {\n Latn: ['Latin'],\n Cyrl: ['Cyrillic', 'Latin'],\n Hans: ['Han', 'Latin'],\n Hant: ['Han', 'Latin'],\n Thai: ['Thai', 'Latin'],\n Arab: ['Arabic', 'Latin'],\n}\n\n/**\n * Infer the allowed Unicode scripts for a BCP-47 locale, with asymmetric\n * Latin tolerance. A script subtag (`th-Latn`) wins over the base\n * language. Unknown locales default to `['Latin']`.\n */\nexport function inferScripts(locale: string): readonly string[] {\n const parts = locale.split('-')\n const subtag = parts.find((t) => /^[A-Z][a-z]{3}$/.test(t))\n if (subtag && SUBTAG_SCRIPTS[subtag]) return SUBTAG_SCRIPTS[subtag]\n\n const base = (parts[0] ?? '').toLowerCase()\n if (LATIN_BASE.has(base)) return ['Latin']\n const primary = SCRIPT_TABLE[base]\n if (primary) return [...primary, 'Latin'] // asymmetric Latin tolerance (#283)\n return ['Latin']\n}\n\n/** Resolve the allowed scripts for a field's locale slot. */\nfunction allowedFor(descriptor: I18nTextDescriptor, locale: string): readonly string[] {\n const script = descriptor.options.script\n if (script && script !== 'auto') {\n const explicit = script[locale]\n if (explicit) return explicit\n }\n return inferScripts(locale)\n}\n\n/** Always-allowed baseline character classes (besides the named scripts). */\nconst BASELINE = String.raw`\\p{White_Space}\\p{Script=Common}\\p{Script=Inherited}\\p{Mark}`\n\n/** Build a whole-string matcher for the allowed scripts. */\nfunction fullMatcher(scripts: readonly string[]): RegExp {\n const cls = scripts.map((s) => `\\\\p{Script=${s}}`).join('')\n return new RegExp(`^[${BASELINE}${cls}]*$`, 'u')\n}\n\n/** Build a single-character matcher (for sampling / stripping). */\nfunction charMatcher(scripts: readonly string[]): RegExp {\n const cls = scripts.map((s) => `\\\\p{Script=${s}}`).join('')\n return new RegExp(`[${BASELINE}${cls}]`, 'u')\n}\n\n/** Collect a short sample of characters that violate the allowed scripts. */\nfunction offendingSample(str: string, scripts: readonly string[]): string {\n const ok = charMatcher(scripts)\n const bad: string[] = []\n for (const ch of str) {\n if (!ok.test(ch)) bad.push(ch)\n if (bad.length >= 8) break\n }\n return bad.join('')\n}\n\n/** Remove characters that violate the allowed scripts. */\nfunction stripDisallowed(str: string, scripts: readonly string[]): string {\n const ok = charMatcher(scripts)\n let out = ''\n for (const ch of str) if (ok.test(ch)) out += ch\n return out\n}\n\n/** A non-fatal script violation recorded under `'filter'`/`'warn'` modes. */\nexport interface ScriptWarning {\n readonly field: string\n readonly locale: string\n readonly expected: readonly string[]\n readonly sample: string\n}\n\n/**\n * Enforce a field's script constraint over an i18nText value map.\n *\n * - No `script` option ⇒ returns the value unchanged.\n * - `onScriptViolation: 'reject'` (default) ⇒ throws {@link ScriptViolationError}.\n * - `'filter'` ⇒ returns a copy with disallowed characters stripped + warnings.\n * - `'warn'` ⇒ returns the value unchanged + warnings.\n */\nexport function enforceScript(\n value: Record<string, unknown>,\n field: string,\n descriptor: I18nTextDescriptor,\n exempt?: ReadonlySet<string>,\n): { value: Record<string, unknown>; warnings: ScriptWarning[] } {\n const opt = descriptor.options\n if (!opt.script) return { value, warnings: [] }\n\n const mode = opt.onScriptViolation ?? 'reject'\n const warnings: ScriptWarning[] = []\n let out = value\n\n for (const [locale, raw] of Object.entries(value)) {\n if (exempt?.has(locale)) continue\n if (typeof raw !== 'string') continue\n const allowed = allowedFor(descriptor, locale)\n if (fullMatcher(allowed).test(raw)) continue\n\n const sample = offendingSample(raw, allowed)\n if (mode === 'reject') {\n throw new ScriptViolationError(field, locale, allowed, sample)\n }\n warnings.push({ field, locale, expected: allowed, sample })\n if (mode === 'filter') {\n if (out === value) out = { ...value }\n out[locale] = stripDisallowed(raw, allowed)\n }\n }\n\n return { value: out, warnings }\n}\n","/**\n * i18nText schema type —\n *\n * `i18nText({ languages, required })` creates a descriptor for a\n * multi-language content field whose value is stored as a\n * `{ [locale]: string }` map (e.g. `{ en: 'Consulting', th: 'ที่ปรึกษา' }`).\n *\n * On put, the descriptor validates that required languages are present.\n * On read (when a `locale` option is passed), the map is collapsed to the\n * caller's locale string via the fallback chain.\n *\n * Design decisions\n * ────────────────\n *\n * **Descriptor pattern (not a Zod type).**\n * `i18nText()` returns a plain descriptor object used in the collection's\n * `i18nFields` option — same pattern as `ref()` / `dictKey()`. This keeps\n * `@noy-db/core` at zero runtime dependencies and avoids Zod v3 field-type\n * constraints. TypeScript inference is handled via the descriptor's type.\n *\n * **Enforcement at the collection boundary.**\n * The `required` option is checked by `Collection.put()` via the compartment's\n * registered `i18nFields`. Failed validation throws `MissingTranslationError`\n * — a distinct class from `SchemaValidationError` so callers can tell\n * \"wrong shape\" from \"missing translations\".\n *\n * **Resolution is post-decryption.**\n * Locale resolution happens AFTER `decryptRecord()`, as a pure in-memory\n * transform. No additional crypto work is needed. The resolved record is\n * returned in place of the stored one, with i18nText fields replaced by\n * their locale-resolved strings.\n *\n * **`locale: 'raw'`.**\n * Passing `{ locale: 'raw' }` skips resolution and returns the full\n * `{ [locale]: string }` map — useful for bilingual exports, admin UIs,\n * and any context where all translations must be visible at once.\n *\n * **Out of scope.**\n * Pluralization, RTL rendering, date/number formatting, per-locale CRDT\n * merging.\n */\n\nimport { MissingTranslationError, LocaleNotSpecifiedError } from '../errors.js'\nimport type { OnMissing, OnMissingPolicy, Layer } from './policy.js'\nimport { resolvePolicy } from './policy.js'\nimport { inferScripts } from './script.js'\n\n// ─── I18nMap type helper ───────────────────────────────────────────────\n\n/** Flatten an intersection into a single object literal for nicer hovers. */\ntype Prettify<T> = { [K in keyof T]: T[K] } & {}\n\n/**\n * The stored shape of a multilingual field, inferred from its `required`\n * mode — so the compiler forces you to handle an absent optional locale\n * (`string | undefined`) instead of silently yielding `undefined`.\n *\n * Mirrors `i18nText({ languages, required })`:\n * - `'all'` (default) — every locale required: `{ th: string; en: string }`\n * - `'any'` — every locale optional: `{ th?: string; en?: string }`\n * (the \"at least one present\" guarantee is runtime-only — not expressible\n * in TypeScript — so each key is optional)\n * - `readonly L[]` — listed locales required, the rest optional:\n * `I18nMap<'th'|'en', ['th']>` → `{ th: string; en?: string }`\n *\n * @example\n * ```ts\n * type Lang = 'th' | 'en'\n * interface Contact {\n * name: I18nMap<Lang, 'any'> // { th?: string; en?: string }\n * legalName: I18nMap<Lang, ['th']> // { th: string; en?: string }\n * slug: I18nMap<Lang> // { th: string; en: string }\n * }\n * ```\n *\n * @public\n */\nexport type I18nMap<\n Langs extends string,\n Required extends 'all' | 'any' | readonly Langs[] = 'all',\n> = Required extends 'all'\n ? Record<Langs, string>\n : Required extends 'any'\n ? Partial<Record<Langs, string>>\n : Required extends readonly (infer R extends Langs)[]\n ? Prettify<Record<R, string> & Partial<Record<Exclude<Langs, R>, string>>>\n : never\n\n// ─── i18nText descriptor ───────────────────────────────────────────────\n\n/**\n * Options for `i18nText()`.\n *\n * `languages` declares the full set of supported locales. `required`\n * controls which must be present on every `put()`.\n *\n * `autoTranslate` is the per-field opt-in for the `plaintextTranslator`\n * hook. When `true` and a `plaintextTranslator` is configured\n * on `createNoydb()`, missing translations are generated before `put()`.\n * Default: `false`.\n */\nexport interface I18nTextOptions {\n /** All supported locale codes (BCP 47). */\n readonly languages: readonly string[]\n /**\n * Which locales must be present on every `put()`.\n *\n * - `'all'` — every declared language must be present.\n * - `'any'` — at least one declared language must be present.\n * - `string[]` — listed locales are required; others are optional.\n */\n readonly required: 'all' | 'any' | readonly string[]\n /**\n * Per-field opt-in for the `plaintextTranslator` hook.\n * When `true`, missing required translations are auto-generated\n * before `put()` if a translator is configured. Default: `false`.\n */\n readonly autoTranslate?: boolean\n /**\n * What to do when this field is resolved to a locale that is absent.\n * A single policy, or a per-layer map (read/guard/join/mv/derivation/\n * export). Default `'throw'` — today's behavior, zero breaking change.\n * See {@link OnMissingPolicy}.\n *\n * NOTE (current wiring): ALL layers are enforced — `read` (`get`/`list`),\n * `guard`, `derivation`, `mv`, `join`, `export`. Guard / derivation\n * `ctx.vault` reads resolve under their own layer policy (`guard` defaults to\n * the lenient `'substitute'`). The `mv` layer fires for materialized views\n * that declare `{ i18nLocale, i18nFields }` — UNION (group-key i18n fields\n * resolve before the unified-row bucketing) and query-form (resolved in\n * `GroupedAggregation.run` before `groupAndReduce`); grouping a raw i18n field\n * without a locale throws. The `join` layer resolves a joined right-side i18n\n * field to the query locale (`toArray({ locale })` or the vault default; raw\n * when locale-less). The `export` layer fires for\n * `exportStream`/`exportJSON({ resolveLabels })` — records collapse to the\n * export locale.\n */\n readonly onMissing?: OnMissingPolicy\n /**\n * Ordered preferred-substitute locales used when `onMissing` resolves\n * to `'substitute'` and the target locale is absent. `'any'` as an\n * element means \"first non-empty value\". A caller-supplied `fallback`\n * at read time takes precedence over this declared list.\n */\n readonly substitute?: readonly string[]\n /**\n * #285 smart-substitute. When `true`, a missing-locale `substitute` walk that\n * misses the explicit chain prefers the available locale whose script is\n * nearest the target (same script, then Latin) rather than an arbitrary value\n * — e.g. a missing Thai label prefers another Thai (or Latin) translation over\n * an unreadable script. Default `false` (legacy first-non-empty behavior).\n */\n readonly smartSubstitute?: boolean\n /**\n * Per-locale script enforcement (write-time). `'auto'` infers the\n * allowed Unicode scripts per locale (asymmetric Latin tolerance); an\n * object overrides per slot. Absent ⇒ no check. See `./script.ts`.\n */\n readonly script?: 'auto' | Partial<Record<string, readonly string[]>>\n /**\n * What to do when a slot's value contains characters outside its\n * allowed script set. Default `'reject'`.\n */\n readonly onScriptViolation?: 'reject' | 'filter' | 'warn'\n /**\n * #435 v1.x — eager-fill empty locale slots from the substitute chain at\n * write time, recording provenance in the internal `_i18nFilled` marker.\n * Mutually exclusive with an EXPLICIT `'throw'` onMissing policy (densify\n * fills every hole, so a throw would be unreachable). Without an explicit\n * `substitute`, fills from `'any'` (first non-empty). Default absent.\n */\n readonly densifyOnWrite?: boolean\n}\n\n/**\n * Descriptor returned by `i18nText()`. Attach to the collection's\n * `i18nFields` option:\n *\n * ```ts\n * const lineItems = company.collection<LineItem>('line-items', {\n * i18nFields: {\n * description: i18nText({ languages: ['en', 'th'], required: 'all' }),\n * },\n * })\n * ```\n */\nexport interface I18nTextDescriptor {\n readonly _noydbI18nText: true\n readonly options: I18nTextOptions\n}\n\n/**\n * Create an `I18nTextDescriptor` for a multi-language content field.\n *\n * @param options Language list + enforcement mode.\n *\n * @example\n * ```ts\n * i18nText({ languages: ['en', 'th'], required: 'all' })\n * i18nText({ languages: ['en', 'th'], required: ['th'], autoTranslate: true })\n * ```\n */\nexport function i18nText(options: I18nTextOptions): I18nTextDescriptor {\n if (options.densifyOnWrite === true && hasThrowPolicy(options.onMissing)) {\n throw new Error(\n `i18nText: densifyOnWrite cannot be combined with an explicit onMissing 'throw' ` +\n `policy — densify fills every empty slot, so a 'throw' would be unreachable. ` +\n `Remove the 'throw' policy or disable densifyOnWrite.`,\n )\n }\n return { _noydbI18nText: true, options }\n}\n\n/** True when `onMissing` declares `'throw'` for any layer (scalar or per-layer). */\nfunction hasThrowPolicy(onMissing: OnMissingPolicy | undefined): boolean {\n if (onMissing === undefined) return false\n if (typeof onMissing === 'string') return onMissing === 'throw'\n return Object.values(onMissing).includes('throw')\n}\n\n/** Runtime predicate for detecting an `I18nTextDescriptor`. */\nexport function isI18nTextDescriptor(x: unknown): x is I18nTextDescriptor {\n return (\n typeof x === 'object' &&\n x !== null &&\n (x as { _noydbI18nText?: unknown })._noydbI18nText === true\n )\n}\n\n// ─── Validation helpers ────────────────────────────────────────────────\n\n/**\n * Validate that a value is a valid `{ [locale]: string }` map and that\n * all required locales are present. Throws `MissingTranslationError`\n * when the required constraint is violated.\n *\n * Called by `Collection.put()` for each registered `i18nField`.\n *\n * @param value The raw field value from the record being put.\n * @param field The field name (used in the thrown error message).\n * @param descriptor The `i18nText()` descriptor for this field.\n */\nexport function validateI18nTextValue(\n value: unknown,\n field: string,\n descriptor: I18nTextDescriptor,\n): void {\n const { options } = descriptor\n\n // Must be a non-null object\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new MissingTranslationError(\n field,\n options.languages,\n `Field \"${field}\" must be a { [locale]: string } map, got ${typeof value}.`,\n )\n }\n\n const map = value as Record<string, unknown>\n\n // All values must be strings\n for (const [locale, v] of Object.entries(map)) {\n if (typeof v !== 'string') {\n throw new MissingTranslationError(\n field,\n [locale],\n `Field \"${field}\": locale \"${locale}\" must be a string, got ${typeof v}.`,\n )\n }\n }\n\n // Check required constraint\n const { required } = options\n if (required === 'all') {\n const missing = options.languages.filter(\n (lang) => !(lang in map) || map[lang] === '',\n )\n if (missing.length > 0) {\n throw new MissingTranslationError(\n field,\n missing,\n `Field \"${field}\" requires all declared languages. Missing: ${missing.join(', ')}.`,\n )\n }\n } else if (required === 'any') {\n const present = options.languages.some(\n (lang) => lang in map && map[lang] !== '',\n )\n if (!present) {\n throw new MissingTranslationError(\n field,\n options.languages,\n `Field \"${field}\" requires at least one declared language. None present.`,\n )\n }\n } else {\n // string[] — named required locales; TypeScript narrows required to readonly string[]\n const requiredList = required\n const missing = requiredList.filter(\n (lang) => !(lang in map) || map[lang] === '',\n )\n if (missing.length > 0) {\n throw new MissingTranslationError(\n field,\n missing,\n `Field \"${field}\" requires: ${requiredList.join(', ')}. Missing: ${missing.join(', ')}.`,\n )\n }\n }\n}\n\n// ─── Locale resolution ─────────────────────────────────────────────────\n\n/**\n * Resolve an i18nText value (`{ [locale]: string }` map) to a string\n * for the given locale.\n *\n * @param value The stored locale map.\n * @param locale The requested locale code, or `'raw'` to return the map.\n * @param fallback Single locale or ordered list; use `'any'` as the last\n * element to fall back to any available translation.\n * @param field Field name used in `LocaleNotSpecifiedError` messages.\n * @returns The resolved string, OR the original map when `locale === 'raw'`.\n */\n/** Options for the policy-aware form of {@link resolveI18nText}. */\nexport interface ResolveI18nOptions {\n /** Effective policy for the resolution layer. Default `'throw'`. */\n readonly policy?: OnMissing\n /** Declared substitute chain; applied only under policy `'substitute'`. */\n readonly substitute?: readonly string[]\n /**\n * #285 smart-substitute. When `true` and policy is `'substitute'`, after the\n * explicit chain misses, pick the available locale whose script is nearest the\n * target (same script first, then Latin's broad readability) instead of an\n * arbitrary value. Default `false`.\n */\n readonly smartSubstitute?: boolean\n}\n\n/** Normalize a single-or-list fallback into an array. */\nfunction toChain(fallback: string | readonly string[] | undefined): readonly string[] {\n return Array.isArray(fallback) ? fallback : fallback ? [fallback as string] : []\n}\n\n/** Walk a chain, returning the first non-empty value (or `'any'` match). */\nfunction pickFromChain(\n value: Record<string, string>,\n chain: readonly string[],\n): string | undefined {\n for (const fb of chain) {\n if (fb === 'any') {\n const any = Object.values(value).find((v) => v !== '')\n if (any !== undefined) return any\n } else if (value[fb] !== undefined && value[fb] !== '') {\n return value[fb]\n }\n }\n return undefined\n}\n\n// Legacy 4-arg form: can only throw or return — never null. Keeps every\n// existing call site's type unchanged (default policy is 'throw').\nexport function resolveI18nText(\n value: Record<string, string>,\n locale: string,\n fallback?: string | readonly string[],\n field?: string,\n): string | Record<string, string>\n// Policy-aware form: may return null under 'null'/'substitute' policies.\nexport function resolveI18nText(\n value: Record<string, string>,\n locale: string,\n fallback: string | readonly string[] | undefined,\n field: string | undefined,\n opts: ResolveI18nOptions,\n): string | Record<string, string> | null\nexport function resolveI18nText(\n value: Record<string, string>,\n locale: string,\n fallback?: string | readonly string[],\n field?: string,\n opts?: ResolveI18nOptions,\n): string | Record<string, string> | null {\n if (locale === 'raw') {\n return value\n }\n\n if (!locale) {\n throw new LocaleNotSpecifiedError(field ?? '<unknown>')\n }\n\n // Primary locale\n if (value[locale] !== undefined && value[locale] !== '') {\n return value[locale]\n }\n\n const policy: OnMissing = opts?.policy ?? 'throw'\n\n // Caller-supplied fallback ALWAYS applies first (backward compat +\n // explicit read-time override), regardless of policy.\n const callerChain = toChain(fallback)\n const callerHit = pickFromChain(value, callerChain)\n if (callerHit !== undefined) return callerHit\n\n // Declared substitute applies ONLY under policy 'substitute'.\n if (policy === 'substitute') {\n const subHit = pickFromChain(value, toChain(opts?.substitute))\n if (subHit !== undefined) return subHit\n // #285 smart-substitute: after the explicit chain, prefer the script-nearest\n // available locale over an arbitrary first-non-empty value.\n if (opts?.smartSubstitute) {\n const smartHit = pickNearestScript(value, locale)\n if (smartHit !== undefined) return smartHit\n }\n }\n\n // Exhausted.\n if (policy === 'throw') {\n throw new LocaleNotSpecifiedError(\n field ?? '<unknown>',\n `No translation available for locale \"${locale}\"` +\n (callerChain.length > 0 ? ` or fallback chain [${callerChain.join(', ')}]` : '') +\n '.',\n )\n }\n return null\n}\n\n/**\n * #285 smart-substitute: among the non-empty locales in `value`, pick the one\n * whose primary script is nearest the target `locale` — same script first, then\n * Latin (broadly readable), then any other — so a missing Thai label falls back\n * to another Thai (or Latin) value rather than, say, an Arabic one. First-seen\n * wins on ties. Returns the value string, or `undefined` when `value` has no\n * non-empty entry.\n */\nfunction pickNearestScript(value: Record<string, string>, target: string): string | undefined {\n const targetScript = inferScripts(target)[0] ?? 'Latin'\n let best: { score: number; v: string } | undefined\n for (const [loc, v] of Object.entries(value)) {\n if (typeof v !== 'string' || v === '') continue\n const s = inferScripts(loc)[0] ?? 'Latin'\n const score = s === targetScript ? 0 : s === 'Latin' ? 1 : 2\n if (best === undefined || score < best.score) best = { score, v }\n if (score === 0) break // nothing beats a same-script match\n }\n return best?.v\n}\n\n// ─── Path helpers (nested i18nFields like 'address.lineOne') ──────────\n\n/**\n * Return all leaf values at `path`, expanding `[].` array wildcards.\n *\n * - `'name'` → `[obj.name]`\n * - `'address.lineOne'` → `[obj.address.lineOne]`\n * - `'contacts[].title'` → `[obj.contacts[0].title, obj.contacts[1].title, …]`\n *\n * Returns an empty array when the path does not resolve (missing key,\n * wrong type, etc.). Used by `enforceI18nOnPut` to validate nested fields.\n */\nexport function getAtPath(obj: Record<string, unknown>, path: string): unknown[] {\n const arrayIdx = path.indexOf('[].')\n if (arrayIdx !== -1) {\n const arrayKey = path.slice(0, arrayIdx)\n const restPath = path.slice(arrayIdx + 3)\n const arr = obj[arrayKey]\n if (!Array.isArray(arr)) return []\n return arr.flatMap(item => {\n if (!item || typeof item !== 'object' || Array.isArray(item)) return []\n return getAtPath(item as Record<string, unknown>, restPath)\n })\n }\n const dotIdx = path.indexOf('.')\n if (dotIdx !== -1) {\n const head = path.slice(0, dotIdx)\n const rest = path.slice(dotIdx + 1)\n const nested = obj[head]\n if (!nested || typeof nested !== 'object' || Array.isArray(nested)) return []\n return getAtPath(nested as Record<string, unknown>, rest)\n }\n const val = obj[path]\n return val !== undefined ? [val] : []\n}\n\n/**\n * Mutate `obj` in-place, setting `value` at the nested `path`.\n * Supports dot notation (`'address.lineOne'`) but not array wildcards —\n * auto-translate on `contacts[].title` style paths is not supported.\n */\nexport function setAtPathInPlace(\n obj: Record<string, unknown>,\n path: string,\n value: unknown,\n): void {\n const dotIdx = path.indexOf('.')\n if (dotIdx !== -1) {\n const head = path.slice(0, dotIdx)\n const rest = path.slice(dotIdx + 1)\n const nested = obj[head]\n if (!nested || typeof nested !== 'object' || Array.isArray(nested)) return\n setAtPathInPlace(nested as Record<string, unknown>, rest, value)\n return\n }\n obj[path] = value\n}\n\n/** Recursively resolve i18nText at a single path within a record copy. */\nfunction applyAtPath(\n obj: Record<string, unknown>,\n path: string,\n locale: string,\n fallback: string | readonly string[] | undefined,\n opts: ResolveI18nOptions,\n): Record<string, unknown> {\n const arrayIdx = path.indexOf('[].')\n if (arrayIdx !== -1) {\n const arrayKey = path.slice(0, arrayIdx)\n const restPath = path.slice(arrayIdx + 3)\n const arr = obj[arrayKey]\n if (!Array.isArray(arr)) return obj\n return {\n ...obj,\n [arrayKey]: arr.map(item => {\n if (!item || typeof item !== 'object' || Array.isArray(item)) return item\n return applyAtPath(item as Record<string, unknown>, restPath, locale, fallback, opts)\n }),\n }\n }\n const dotIdx = path.indexOf('.')\n if (dotIdx !== -1) {\n const head = path.slice(0, dotIdx)\n const rest = path.slice(dotIdx + 1)\n const nested = obj[head]\n if (!nested || typeof nested !== 'object' || Array.isArray(nested)) return obj\n return {\n ...obj,\n [head]: applyAtPath(nested as Record<string, unknown>, rest, locale, fallback, opts),\n }\n }\n const raw = obj[path]\n if (raw === undefined || raw === null) return obj\n if (typeof raw !== 'object' || Array.isArray(raw)) return obj\n return {\n ...obj,\n [path]: resolveI18nText(raw as Record<string, string>, locale, fallback, path, opts),\n }\n}\n\n/**\n * Apply locale resolution to a single record, returning a new copy.\n *\n * For each field registered as an `i18nText` descriptor:\n * - If `locale === 'raw'`, the field value is left as the stored map.\n * - Otherwise, the field value is replaced with the resolved string.\n *\n * Field paths support dot notation (`'address.lineOne'`) and array\n * wildcards (`'contacts[].title'`). Top-level fields work as before.\n *\n * @param record The decrypted record.\n * @param i18nFields Map of field path → `I18nTextDescriptor`.\n * @param locale The requested locale (or `'raw'`).\n * @param fallback Fallback chain (optional).\n * @param layer Resolution layer (default `'read'`). Each field's\n * `onMissing` policy is resolved for this layer, so the\n * same record resolves leniently on a get but strictly\n * inside an mv/derivation.\n */\nexport function applyI18nLocale(\n record: Record<string, unknown>,\n i18nFields: Record<string, I18nTextDescriptor>,\n locale: string,\n fallback?: string | readonly string[],\n layer: Layer = 'read',\n): Record<string, unknown> {\n const fieldNames = Object.keys(i18nFields)\n if (fieldNames.length === 0) return record\n\n let result = record\n\n for (const [field, descriptor] of Object.entries(i18nFields)) {\n const { onMissing, substitute, smartSubstitute } = descriptor.options\n const opts: ResolveI18nOptions = {\n policy: resolvePolicy(onMissing, layer),\n ...(substitute !== undefined ? { substitute } : {}),\n ...(smartSubstitute ? { smartSubstitute } : {}),\n }\n result = applyAtPath(result, field, locale, fallback, opts)\n }\n\n // #435 — the internal densify provenance marker never leaves the store.\n result = stripI18nFilled(result)\n\n return result\n}\n\n/**\n * Remove the internal densify provenance marker (`_i18nFilled`) from a\n * read-facing record (#435). NON-mutating: returns the same object when the\n * marker is absent, otherwise a shallow copy without the marker.\n *\n * MUST be applied on every user-facing read return — even locale-less ones,\n * which bypass {@link applyI18nLocale}. MUST NOT be applied on the internal\n * prior-read path (decryptRecord / resolveDensifyPrior), where densify needs\n * the marker.\n */\nexport function stripI18nFilled<T extends Record<string, unknown>>(record: T): T {\n if (!Object.prototype.hasOwnProperty.call(record, '_i18nFilled')) return record\n const rest: T = { ...record }\n delete (rest as Record<string, unknown>)._i18nFilled\n return rest\n}\n"],"mappings":";;;;;;;AA8CO,SAAS,cACd,WACA,OACW;AACX,QAAM,WACJ,aAAa,OAAO,cAAc,WAAW,UAAU,KAAK,IAAI;AAClE,QAAM,SAAS,OAAO,cAAc,WAAW,YAAY;AAC3D,QAAM,eACJ,UAAU,UAAU,eAAe;AACrC,SAAO,YAAY,gBAAgB,UAAU;AAC/C;;;AClCA,IAAM,aAAa,oBAAI,IAAI;AAAA,EACzB;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAClE;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;A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ency-analyzer.ts
|
|
7
7
|
function analyzeDependencies(query) {
|
|
@@ -14,6 +14,11 @@ function analyzeDependencies(query) {
|
|
|
14
14
|
for (const leg of plan.joins) {
|
|
15
15
|
deps.add(leg.target);
|
|
16
16
|
}
|
|
17
|
+
for (const clause of plan.clauses) {
|
|
18
|
+
if (clause.type === "crossJoin") {
|
|
19
|
+
deps.add(clause.target);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
17
22
|
walkClausesForJoins(plan, deps, ctx);
|
|
18
23
|
return deps;
|
|
19
24
|
}
|
|
@@ -29,7 +34,19 @@ function summarizeQueryPlan(query) {
|
|
|
29
34
|
const ctx = query._joinContext();
|
|
30
35
|
return JSON.stringify({
|
|
31
36
|
root: ctx?.leftCollection ?? null,
|
|
32
|
-
clauses: plan.clauses
|
|
37
|
+
clauses: plan.clauses.map((c) => {
|
|
38
|
+
if (c.type === "crossJoin") {
|
|
39
|
+
return {
|
|
40
|
+
type: "crossJoin",
|
|
41
|
+
target: c.target,
|
|
42
|
+
as: c.as,
|
|
43
|
+
// Inline on: callback: use sentinel — drift detection disabled for this MV
|
|
44
|
+
onPredicateName: c.onPredicateName ?? (c.on ? "[inline]" : null),
|
|
45
|
+
maxRows: c.maxRows ?? null
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
return c;
|
|
49
|
+
}),
|
|
33
50
|
orderBy: plan.orderBy,
|
|
34
51
|
limit: plan.limit ?? null,
|
|
35
52
|
offset: plan.offset,
|
|
@@ -37,10 +54,14 @@ function summarizeQueryPlan(query) {
|
|
|
37
54
|
});
|
|
38
55
|
}
|
|
39
56
|
function summarizeUnionPlan(spec) {
|
|
40
|
-
const arms = (spec.unionSources ?? []).map((s) =>
|
|
57
|
+
const arms = (spec.unionSources ?? []).map((s) => {
|
|
58
|
+
const joins = s.join?.length ? `[${s.join.map((j) => `${j.field}\u2192${j.as}`).join(";")}]` : "";
|
|
59
|
+
return `${s.collection}${joins}`;
|
|
60
|
+
}).join(",");
|
|
41
61
|
const groupBy = Array.isArray(spec.groupBy) ? [...spec.groupBy].sort().join(",") : typeof spec.groupBy === "string" ? spec.groupBy : "";
|
|
42
62
|
const aggKeys = spec.aggregate ? Object.keys(spec.aggregate).sort().join(",") : "";
|
|
43
|
-
|
|
63
|
+
const moneyKeys = spec.moneyFields ? Object.keys(spec.moneyFields).sort().join(",") : "";
|
|
64
|
+
return `union(${arms})|groupBy(${groupBy})|aggregate(${aggKeys})|money(${moneyKeys})`;
|
|
44
65
|
}
|
|
45
66
|
|
|
46
67
|
// src/materialized-views/query-hash.ts
|
|
@@ -92,6 +113,7 @@ var MaterializedViewRegistry = class {
|
|
|
92
113
|
let isQuery = false;
|
|
93
114
|
if (spec.unionSources) {
|
|
94
115
|
dependencies = new Set(spec.unionSources.map((s) => s.collection));
|
|
116
|
+
if (spec.sources) for (const s of spec.sources) dependencies.add(s);
|
|
95
117
|
queryPlanSummary = summarizeUnionPlan(spec);
|
|
96
118
|
} else {
|
|
97
119
|
const q = spec.query(dbForQuery);
|
|
@@ -293,4 +315,4 @@ export {
|
|
|
293
315
|
MaterializedViewRegistry,
|
|
294
316
|
wrapDbWithPredicates
|
|
295
317
|
};
|
|
296
|
-
//# sourceMappingURL=chunk-
|
|
318
|
+
//# sourceMappingURL=chunk-RCB6GWTC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/materialized-views/dependency-analyzer.ts","../src/materialized-views/query-hash.ts","../src/materialized-views/registry.ts"],"sourcesContent":["import type { Query, QueryPlan } from '../query/builder.js'\nimport type { JoinContext } from '../query/join.js'\nimport type { MaterializedViewStrategy } from './types.js'\n\n/**\n * Walks a `Query<T>` plan and returns the set of source collection\n * names that any source-write should trigger a refresh on.\n *\n * Handles:\n * - root collection (the one the query was built from)\n * - FK join targets (`.join(field, { as })`)\n *\n * Also handles:\n * - cross-join targets (`.crossJoin(target, { as })`) — v3\n *\n * Deferred:\n * - `.wherePredicate(name)` — v2 predicate primitive\n * - Overlay-name expansion to {base, overlay}\n *\n * The set is materialized at MV registration time. The MV registry\n * uses it to (a) dispatch `onSourceWrite` only to MVs that actually\n * care, and (b) contribute edges to the shared cycle-detection graph.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function analyzeDependencies(query: Query<any>): Set<string> {\n const deps = new Set<string>()\n const plan = query._plan()\n const ctx = query._joinContext()\n\n // The root collection is always a dependency.\n if (ctx?.leftCollection) {\n deps.add(ctx.leftCollection)\n }\n\n // FK join targets contribute additional sources.\n for (const leg of plan.joins) {\n deps.add(leg.target)\n }\n\n // Cross-join targets are also dependency sources — writes to either side\n // must trigger MV refresh. Symmetric with FK-join target handling above.\n for (const clause of plan.clauses) {\n if (clause.type === 'crossJoin') {\n deps.add(clause.target)\n }\n }\n\n // Sub-plans inside OR clauses can carry nested joins. Walk them.\n // (Today only top-level `.join()` populates `plan.joins`, but the\n // OR-group machinery permits sub-plans, so we recurse defensively.)\n walkClausesForJoins(plan, deps, ctx)\n\n return deps\n}\n\nfunction walkClausesForJoins(\n plan: QueryPlan,\n deps: Set<string>,\n ctx: JoinContext | undefined,\n): void {\n void ctx\n // Today `plan.joins` carries all join legs at top level. Sub-plans\n // inside OR groups don't currently support nested joins, so the loop\n // below is a no-op safety net for future builder extensions.\n for (const clause of plan.clauses) {\n if (clause.type === 'group') {\n // Group clauses don't (yet) carry their own joins; this is a\n // forward-compat anchor for when OR-groups support nested\n // sources.\n }\n }\n}\n\n/**\n * Convenience: produce a stable string summary of the query plan\n * suitable for `queryHash` derivation. Captures everything the\n * dependency analyzer reads + the where/orderBy/limit/offset\n * structure that affects materialized rows.\n *\n * `joinContext` is intentionally NOT included — the join-resolution\n * function references would defeat hash determinism. The set of join\n * TARGETS (collection names) IS included via the plan.joins legs.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function summarizeQueryPlan(query: Query<any>): string {\n const plan = query._plan()\n const ctx = query._joinContext()\n return JSON.stringify({\n root: ctx?.leftCollection ?? null,\n clauses: plan.clauses.map(c => {\n if (c.type === 'crossJoin') {\n return {\n type: 'crossJoin',\n target: c.target,\n as: c.as,\n // Inline on: callback: use sentinel — drift detection disabled for this MV\n onPredicateName: c.onPredicateName ?? (c.on ? '[inline]' : null),\n maxRows: c.maxRows ?? null,\n }\n }\n return c\n }),\n orderBy: plan.orderBy,\n limit: plan.limit ?? null,\n offset: plan.offset,\n joins: plan.joins.map(j => ({ field: j.field, as: j.as, target: j.target, mode: j.mode })),\n })\n}\n\n/**\n * Canonical string description of a UNION MV's plan, used as input to\n * `computeQueryHash`.\n *\n * Asymmetry note:\n * - Arm collection names are NOT sorted. Declaration order is\n * semantically meaningful for the dedup-only UNION path —\n * `materializeUnionResult` iterates `spec.unionSources` in\n * declaration order and keeps the first-seen row per composite key\n * (tie-break precedence). If we sorted arms here, a consumer who\n * reordered `unionSources` to change precedence would compute the\n * same `queryHash`, refresh would be a no-op, and stale MV rows\n * would persist. Hashing in declaration order makes any reorder\n * trigger a refresh.\n * - `groupBy` fields ARE sorted. Multi-key groupBy buckets are\n * commutative (`canonicalGroupKey` produces the same composite key\n * regardless of field order in the input spec).\n * - `aggregate` keys ARE sorted. Reducer-spec keys are independent\n * of each other — order of declaration doesn't change output.\n *\n * Per-arm `map` functions are NOT fingerprinted; consumers must bump\n * the MV's `name` (or rely on application-level cache busting) when\n * `map` semantics change non-equivalently.\n */\nexport function summarizeUnionPlan<T extends Record<string, unknown>>(\n spec: MaterializedViewStrategy<T>,\n): string {\n const arms = (spec.unionSources ?? [])\n .map(s => {\n // Fold each arm's join legs into the summary so adding or\n // reordering joins (which changes the materialized rows) bumps\n // queryHash. Leg order is declaration-significant (legs chain), so\n // it is NOT sorted — same rationale as arm declaration order.\n const joins = s.join?.length\n ? `[${s.join.map(j => `${j.field}→${j.as}`).join(';')}]`\n : ''\n return `${s.collection}${joins}`\n })\n .join(',')\n const groupBy: string = Array.isArray(spec.groupBy)\n ? [...spec.groupBy].sort().join(',')\n : typeof spec.groupBy === 'string'\n ? spec.groupBy\n : ''\n const aggKeys = spec.aggregate ? Object.keys(spec.aggregate).sort().join(',') : ''\n // `moneyFields` changes reducer semantics (float → exact BigInt), so\n // declaring / removing / re-keying it must bump queryHash. Keys are\n // sorted — they're independent of each other (one descriptor per\n // output field), same rationale as aggregate keys.\n const moneyKeys = spec.moneyFields ? Object.keys(spec.moneyFields).sort().join(',') : ''\n return `union(${arms})|groupBy(${groupBy})|aggregate(${aggKeys})|money(${moneyKeys})`\n}\n","/**\n * Deterministic hash of a materialized view strategy's \"shape\": MV\n * name + canonical query-plan summary + sorted dependency-set.\n *\n * Used to detect strategy drift: a row whose `_materializedFrom.queryHash`\n * doesn't match the current strategy is considered stale.\n *\n * Web Crypto SHA-256 — no extra deps. Mirrors the v1\n * `computeStrategyHash` pattern.\n */\nexport async function computeQueryHash(\n mvName: string,\n /**\n * Source-collection set the query depends on. Sorted before\n * canonicalization so set iteration order doesn't affect the hash.\n */\n dependencies: ReadonlySet<string>,\n /**\n * Stringified query-plan summary. The caller produces this from the\n * `Query<T>` builder — concretely: a JSON serialization of clauses +\n * orderBy + limit + offset + joins. Function bodies inside\n * `wherePredicate` are NOT included here (those carry their own\n * `predicateHash` to be folded in by a later sub-issue).\n */\n queryPlanSummary: string,\n): Promise<string> {\n const canonical = JSON.stringify({\n mvName,\n dependencies: [...dependencies].sort(),\n queryPlanSummary,\n })\n const bytes = new TextEncoder().encode(canonical)\n const digest = await crypto.subtle.digest('SHA-256', bytes)\n return Array.from(new Uint8Array(digest))\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Canonicalize a query plan for hashing. Walks the plan structure\n * with sorted keys so insertion order doesn't perturb the result.\n * Lives here rather than in `query/builder.ts` to keep that module\n * stable across MV-specific evolutions.\n *\n * @internal exported for testing\n */\nexport function canonicalizeQueryPlan(plan: unknown): string {\n return JSON.stringify(plan, (_key, value) => {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n const sorted: Record<string, unknown> = {}\n for (const k of Object.keys(value as Record<string, unknown>).sort()) {\n sorted[k] = (value as Record<string, unknown>)[k]\n }\n return sorted\n }\n return value\n })\n}\n","import { MaterializedViewCycleError, MaterializedViewSourceUnknownError } from '../errors.js'\nimport type { DerivationRegistry } from '../derivations/registry.js'\nimport type { Clause, FieldClause } from '../query/predicate.js'\nimport type { DeclaredPredicate } from '../query/builder.js'\nimport { analyzeDependencies, summarizeQueryPlan, summarizeUnionPlan } from './dependency-analyzer.js'\nimport { computeQueryHash } from './query-hash.js'\nimport type { MaterializedViewStrategy, MVQueryContext } from './types.js'\n\n/**\n * One registered MV strategy alongside its derived metadata. Stored\n * type-erased on `TRow` so the registry can hold heterogeneous MVs.\n */\nexport interface RegisteredMV {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly spec: MaterializedViewStrategy<any>\n /** Output collection name (`spec.output?.collection ?? spec.name`). */\n readonly outputCollection: string\n /** Set of source collections; populated at registration via the analyzer. */\n readonly dependencies: ReadonlySet<string>\n /** Canonical `queryHash` — `_materializedFrom.queryHash` for every emitted row. */\n readonly queryHash: string\n /**\n * Top-level FieldClauses on the partition field, captured at\n * registration time. Used by the cycle detector to resolve\n * same-collection-as-source edges via the partition-discriminator\n * check. Empty when `spec.output?.partition` is undefined.\n */\n readonly partitionClauses: readonly FieldClause[]\n}\n\n/**\n * Vault-internal registry of MV strategies. Owned by `Vault`; not\n * exported. Parallel to v1's `DerivationRegistry`; the two graphs share\n * a single cycle-detection pass at vault open (see `validate`).\n *\n * @internal\n */\nexport class MaterializedViewRegistry {\n /** Keyed by `spec.name`. */\n private readonly _byName = new Map<string, RegisteredMV>()\n /** Keyed by dependency source-collection → MVs that depend on it. */\n private readonly _bySource = new Map<string, RegisteredMV[]>()\n\n /**\n * Register an MV. Invokes `spec.query()` once at registration time to\n * read the plan + join context; the resulting `Query<T>` is discarded\n * after dependency extraction. `vault.collection(...)` must therefore\n * be functional by the time this runs — typically wired from\n * `Vault._initMaterializedViews` after collection bootstrap.\n *\n * Throws `MaterializedViewSourceUnknownError` if the analyzer\n * surfaces a dependency the vault doesn't know about (when a\n * `knownCollections` checker is supplied).\n */\n async register(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n spec: MaterializedViewStrategy<any>,\n db: MVQueryContext,\n options?: { knownCollections?: (name: string) => boolean },\n ): Promise<void> {\n // Build a predicate-aware db wrapper. If `spec.predicates` is\n // declared, the wrapper intercepts `.collection().query()` and\n // attaches the predicates map to the resulting Query<T>. With no\n // predicates declared, the wrapper is the original db unchanged.\n const dbForQuery = spec.predicates ? wrapDbWithPredicates(db, spec.predicates) : db\n\n // Invoke the query callback once to inspect its plan / dependencies.\n // For Query<T> shapes the analyzer extracts deps + plan summary\n // automatically. Aggregation / GroupedAggregation shapes don't\n // expose the underlying Query, so the spec must declare `sources`\n // explicitly. `partitionClauses` are only populated for Query<T>\n // since same-collection-partition is a non-aggregate concern.\n // UNION-form strategies: dependencies and plan summary come\n // straight off the strategy — no `query` callback to introspect.\n // The dependency-analyzer + summarizer are bypassed entirely; the\n // executor handles materialization via `materializeUnionResult`.\n let dependencies: Set<string>\n let queryPlanSummary: string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let qAny: any = null\n let isQuery = false\n if (spec.unionSources) {\n dependencies = new Set(spec.unionSources.map(s => s.collection))\n // Per-arm joins resolve right-side collections that aren't among\n // the arm `collection`s. The consumer lists those in `sources`;\n // fold them into the dependency set so a write to a join-target\n // collection triggers MV refresh (and contributes a cycle edge).\n if (spec.sources) for (const s of spec.sources) dependencies.add(s)\n queryPlanSummary = summarizeUnionPlan(spec)\n } else {\n const q = spec.query!(dbForQuery)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n qAny = q as any\n isQuery = typeof qAny._plan === 'function'\n if (isQuery) {\n dependencies = analyzeDependencies(q)\n queryPlanSummary = summarizeQueryPlan(q)\n // Fold `.wherePredicate(name, ctx)` references into the plan\n // summary so predicate function or ctx changes (signalled by\n // bumping `hash` or supplying a different ctx) propagate into\n // `queryHash` and force refresh on next visit.\n const predicateRefs = extractPredicateRefs(qAny._plan())\n if (predicateRefs.length > 0) {\n queryPlanSummary = JSON.stringify({ plan: queryPlanSummary, predicates: predicateRefs })\n }\n // If `sources` is ALSO declared, take the union (consumer's\n // explicit list extends the auto-analyzed set).\n if (spec.sources) for (const s of spec.sources) dependencies.add(s)\n } else {\n // Aggregate shape: require explicit `sources`.\n if (!spec.sources || spec.sources.length === 0) {\n throw new Error(\n `withMaterializedView \"${spec.name}\": query() returned an aggregate ` +\n `(Aggregation or GroupedAggregation) but no \\`sources\\` field is declared. ` +\n `The dependency analyzer cannot walk through groupBy().aggregate() ` +\n `back to the source — declare sources: [...] explicitly.`,\n )\n }\n dependencies = new Set(spec.sources)\n // Aggregate plans don't carry a chainable query plan for summary\n // purposes; the dep-set + spec.name serve as the queryHash inputs.\n queryPlanSummary = JSON.stringify({ aggregate: true, sources: [...spec.sources].sort() })\n }\n }\n\n // Sanity-check declared dependencies against the vault's known\n // collections. Optional — when the checker isn't supplied (test\n // wiring, in-process composition) the registration succeeds and\n // any typo surfaces at first onSourceWrite as a no-op.\n if (options?.knownCollections) {\n for (const dep of dependencies) {\n if (!options.knownCollections(dep)) {\n throw new MaterializedViewSourceUnknownError(spec.name, dep)\n }\n }\n }\n\n const outputCollection = spec.output?.collection ?? spec.name\n const queryHash = await computeQueryHash(spec.name, dependencies, queryPlanSummary)\n // For same-collection-as-source MVs, capture the where-clauses on\n // the partition field so cycle detection can prove disjointness.\n // Only applicable to Query<T> shapes — aggregate MVs don't carry\n // a chainable plan to inspect (and same-collection aggregation\n // doesn't make sense for same-collection aggregation).\n const partitionClauses: FieldClause[] = []\n const partitionField = spec.output?.partition?.field\n if (partitionField !== undefined && isQuery) {\n const plan = qAny._plan()\n for (const clause of plan.clauses) {\n if (isFieldClauseOnField(clause, partitionField)) partitionClauses.push(clause)\n }\n }\n const reg: RegisteredMV = { spec, outputCollection, dependencies, queryHash, partitionClauses }\n\n this._byName.set(spec.name, reg)\n for (const dep of dependencies) {\n const arr = this._bySource.get(dep)\n if (arr) arr.push(reg)\n else this._bySource.set(dep, [reg])\n }\n }\n\n /** All MVs that depend on `source`, in registration order. */\n mvsForSource(source: string): ReadonlyArray<RegisteredMV> {\n return this._bySource.get(source) ?? []\n }\n\n /** Single MV by name, or `undefined`. */\n byName(name: string): RegisteredMV | undefined {\n return this._byName.get(name)\n }\n\n /** Iterate over every registered MV. */\n all(): ReadonlyArray<RegisteredMV> {\n return [...this._byName.values()]\n }\n\n /**\n * Cycle detection over the combined derivation + MV graph. Edges:\n * - Derivation: derivation.source → output.collection (each output)\n * - MV: every dep in MV.dependencies → MV.outputCollection\n *\n * Throws `MaterializedViewCycleError` if the cycle's terminal node\n * is an MV output collection; otherwise (a pure-derivation cycle)\n * the caller's `DerivationRegistry.validate()` will surface\n * `DerivationCycleError` separately at vault open.\n *\n * Call AFTER all `register()` calls complete.\n */\n validate(derivationRegistry?: DerivationRegistry | null): void {\n const visited = new Set<string>()\n const stack: string[] = []\n const mvOutputs = new Set<string>()\n for (const reg of this._byName.values()) mvOutputs.add(reg.outputCollection)\n\n const edges = new Map<string, string[]>()\n\n // MV edges: every dep → output. Same-collection edges (dep ===\n // outputCollection) are skipped IFF the MV declares an\n // `output.partition` discriminator AND the query has a where-clause\n // that provably excludes the partition value. Otherwise the cycle\n // detector treats the edge as real — naïve same-collection MVs\n // surface as `MaterializedViewCycleError`.\n for (const reg of this._byName.values()) {\n for (const dep of reg.dependencies) {\n if (dep === reg.outputCollection && partitionDisjoint(reg)) continue\n const arr = edges.get(dep)\n if (arr) arr.push(reg.outputCollection)\n else edges.set(dep, [reg.outputCollection])\n }\n }\n\n // Derivation edges: source → output collections\n if (derivationRegistry) {\n // The shared DerivationRegistry exposes its edges via the same\n // `strategiesForSource` API its own `validate()` uses. We don't\n // duplicate cycle detection — we add MV nodes to the graph and\n // run the unified DFS, attributing cycles that touch an MV\n // output to `MaterializedViewCycleError`.\n for (const reg of this._byName.values()) {\n // Walk every dependency through derivation edges too: a\n // derivation whose output we depend on is itself a source.\n void reg\n }\n // Pull derivation edges by scanning every MV dep + every MV\n // output as potential derivation sources.\n const sourcesToScan = new Set<string>()\n for (const reg of this._byName.values()) {\n for (const dep of reg.dependencies) sourcesToScan.add(dep)\n sourcesToScan.add(reg.outputCollection)\n }\n for (const src of sourcesToScan) {\n const strategies = derivationRegistry.strategiesForSource(src)\n if (strategies.length === 0) continue\n for (const s of strategies) {\n for (const key of Object.keys(s.spec.outputs)) {\n const o = s.spec.outputs[key]\n if (!o) continue\n const arr = edges.get(src)\n if (arr) arr.push(o.collection)\n else edges.set(src, [o.collection])\n }\n }\n }\n }\n\n const visit = (node: string): void => {\n if (stack.includes(node)) {\n const cycle = stack.slice(stack.indexOf(node)).concat(node)\n // If any node on the cycle is an MV output, attribute as MV\n // cycle. Otherwise let DerivationRegistry.validate() surface it.\n if (cycle.some(n => mvOutputs.has(n))) {\n throw new MaterializedViewCycleError(cycle)\n }\n // Pure-derivation cycle — caller's DerivationRegistry.validate()\n // will catch it separately. Don't double-report.\n return\n }\n if (visited.has(node)) return\n stack.push(node)\n const outs = edges.get(node)\n if (outs) for (const o of outs) visit(o)\n stack.pop()\n visited.add(node)\n }\n\n for (const node of edges.keys()) visit(node)\n }\n}\n\n/**\n * Type guard: is the clause a top-level `FieldClause` on the given\n * field? Used by the partition-disjoint check.\n *\n * @internal\n */\nfunction isFieldClauseOnField(clause: Clause, field: string): clause is FieldClause {\n return clause.type === 'field' && clause.field === field\n}\n\n/**\n * Wrap an `MVQueryContext` so its `.collection().query()` returns a\n * Query<T> with the MV's declared predicates attached. Bare Queries\n * (outside of any MV) don't gain `.wherePredicate()` — only Queries\n * obtained through this wrapped db do.\n *\n * @internal\n */\nexport function wrapDbWithPredicates(\n db: MVQueryContext,\n predicates: NonNullable<MaterializedViewStrategy<Record<string, unknown>>['predicates']>,\n): MVQueryContext {\n // Build the predicate map once — the fn signature in the MV spec\n // is row-typed but the QueryBuilder casts to unknown, so we widen\n // here for the Map.\n const map = new Map<string, DeclaredPredicate>()\n for (const [name, decl] of Object.entries(predicates)) {\n map.set(name, {\n hash: decl.hash,\n fn: decl.fn as (record: unknown, ctx?: unknown) => boolean,\n })\n }\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n collection<T extends Record<string, unknown>>(name: string): any {\n const c = db.collection<T>(name)\n // Return an object that delegates everything to `c` but\n // overrides `.query()` to attach predicates via the new\n // `Query._withPredicates()` accessor.\n return new Proxy(c, {\n get(target, prop, receiver) {\n if (prop === 'query') {\n return (...args: unknown[]) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const q = (target.query as any)(...args)\n // For non-aggregate Query<T>, attach predicates. For\n // legacy predicate-arg overload that returns T[] (sync\n // filter), pass through unchanged.\n \n if (q && typeof q._withPredicates === 'function') {\n return q._withPredicates(map)\n }\n return q\n }\n }\n return Reflect.get(target, prop, receiver)\n },\n })\n },\n }\n}\n\n/**\n * Walk a QueryPlan's clauses and collect predicate-reference markers\n * for `queryHash` derivation. Returns a sorted array (deterministic\n * order) of `{ name, predicateHash, ctxHash }` tuples — these are the\n * hashable identity of each `.wherePredicate()` call site.\n *\n * @internal\n */\nfunction extractPredicateRefs(\n plan: { clauses: readonly Clause[] },\n): Array<{ name: string; predicateHash: string; ctxHash: string }> {\n const refs: Array<{ name: string; predicateHash: string; ctxHash: string }> = []\n const walk = (clauses: readonly Clause[]): void => {\n for (const c of clauses) {\n if (c.type === 'wherePredicate') {\n refs.push({ name: c.name, predicateHash: c.predicateHash, ctxHash: c.ctxHash })\n } else if (c.type === 'group') {\n walk(c.clauses)\n }\n }\n }\n walk(plan.clauses)\n // Stable-sort by (name, predicateHash, ctxHash) — same predicate\n // appearing twice with different ctx hashes both flow through.\n refs.sort((a, b) => {\n if (a.name !== b.name) return a.name < b.name ? -1 : 1\n if (a.predicateHash !== b.predicateHash) return a.predicateHash < b.predicateHash ? -1 : 1\n return a.ctxHash < b.ctxHash ? -1 : a.ctxHash > b.ctxHash ? 1 : 0\n })\n return refs\n}\n\n/**\n * Provability check for the same-collection partition-discriminator\n * (spec § Same-collection-as-source MV). Returns `true` when\n * the captured partition clauses on the MV's query provably exclude\n * the partition's value — meaning the input filter and the output\n * partition are disjoint and the same-collection edge isn't really a\n * cycle.\n *\n * Supported provability shapes (narrow on purpose — DERIV-PP30-001\n * is the load-bearing case):\n *\n * - `.where(field, '==', X)` where X !== partition.value → disjoint\n * - `.where(field, '!=', partition.value)` → disjoint\n * - `.where(field, 'in', [...])` where partition.value NOT in list → disjoint\n *\n * Anything else (no clause on the partition field, an 'in' list that\n * contains partition.value, unsupported operators) → not disjoint,\n * the cycle detector surfaces `MaterializedViewCycleError`.\n *\n * @internal\n */\nfunction partitionDisjoint(reg: RegisteredMV): boolean {\n const partition = reg.spec.output?.partition\n if (partition === undefined) return false\n const value = partition.value\n // The OR-semantics of multiple where-clauses on the same field\n // would muddy this check. v2 only treats AND-chained clauses;\n // any clause that proves disjoint is sufficient.\n for (const c of reg.partitionClauses) {\n if (c.op === '==' && c.value !== value) return true\n if (c.op === '!=' && c.value === value) return true\n if (c.op === 'in' && Array.isArray(c.value)) {\n const list = c.value as readonly unknown[]\n if (!list.includes(value)) return true\n }\n }\n return false\n}\n"],"mappings":";;;;;;AAwBO,SAAS,oBAAoB,OAAgC;AAClE,QAAM,OAAO,oBAAI,IAAY;AAC7B,QAAM,OAAO,MAAM,MAAM;AACzB,QAAM,MAAM,MAAM,aAAa;AAG/B,MAAI,KAAK,gBAAgB;AACvB,SAAK,IAAI,IAAI,cAAc;AAAA,EAC7B;AAGA,aAAW,OAAO,KAAK,OAAO;AAC5B,SAAK,IAAI,IAAI,MAAM;AAAA,EACrB;AAIA,aAAW,UAAU,KAAK,SAAS;AACjC,QAAI,OAAO,SAAS,aAAa;AAC/B,WAAK,IAAI,OAAO,MAAM;AAAA,IACxB;AAAA,EACF;AAKA,sBAAoB,MAAM,MAAM,GAAG;AAEnC,SAAO;AACT;AAEA,S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,aAAK,EAAE,OAAO;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACA,OAAK,KAAK,OAAO;AAGjB,OAAK,KAAK,CAAC,GAAG,MAAM;AAClB,QAAI,EAAE,SAAS,EAAE,KAAM,QAAO,EAAE,OAAO,EAAE,OAAO,KAAK;AACrD,QAAI,EAAE,kBAAkB,EAAE,cAAe,QAAO,EAAE,gBAAgB,EAAE,gBAAgB,KAAK;AACzF,WAAO,EAAE,UAAU,EAAE,UAAU,KAAK,EAAE,UAAU,EAAE,UAAU,IAAI;AAAA,EAClE,CAAC;AACD,SAAO;AACT;AAuBA,SAAS,kBAAkB,KAA4B;AACrD,QAAM,YAAY,IAAI,KAAK,QAAQ;AACnC,MAAI,cAAc,OAAW,QAAO;AACpC,QAAM,QAAQ,UAAU;AAIxB,aAAW,KAAK,IAAI,kBAAkB;AACpC,QAAI,EAAE,OAAO,QAAQ,EAAE,UAAU,MAAO,QAAO;AAC/C,QAAI,EAAE,OAAO,QAAQ,EAAE,UAAU,MAAO,QAAO;AAC/C,QAAI,EAAE,OAAO,QAAQ,MAAM,QAAQ,EAAE,KAAK,GAAG;AAC3C,YAAM,OAAO,EAAE;AACf,UAAI,CAAC,KAAK,SAAS,KAAK,EAAG,QAAO;AAAA,IACpC;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
import {
|
|
5
5
|
decrypt,
|
|
6
6
|
encrypt
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-E2MDPPOC.js";
|
|
8
8
|
|
|
9
9
|
// src/consent/consent.ts
|
|
10
10
|
var CONSENT_AUDIT_COLLECTION = "_consent_audit";
|
|
@@ -69,4 +69,4 @@ export {
|
|
|
69
69
|
writeConsentEntry,
|
|
70
70
|
loadConsentEntries
|
|
71
71
|
};
|
|
72
|
-
//# sourceMappingURL=chunk-
|
|
72
|
+
//# sourceMappingURL=chunk-SAAJYSVV.js.map
|