@noy-db/hub 0.6.0-pre.2 → 0.6.0-pre.21
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/CHANGELOG.md +5234 -0
- package/codemods/0.4.0-pre.json +699 -0
- package/codemods/0.6.0-pre.json +211 -0
- package/dist/api-EYNT6KGS.js +20 -0
- package/dist/attestation/index.js +19 -19
- package/dist/{backup-YYBE5RPC.js → backup-FSC36VWC.js} +36 -18
- package/dist/backup-FSC36VWC.js.map +1 -0
- package/dist/blobs/index.js +13 -13
- package/dist/broker/index.js +12 -12
- package/dist/cargo/index.js +33 -33
- package/dist/{chunk-35EBKWQU.js → chunk-2LFOMUEA.js} +4 -4
- package/dist/{chunk-OF3L2SD6.js → chunk-32B7VCKU.js} +2 -2
- package/dist/{chunk-MSWYQLMQ.js → chunk-3B6S6RSI.js} +2 -2
- package/dist/{chunk-PJNTR2NV.js → chunk-3ENNPCIW.js} +7 -10
- package/dist/chunk-3ENNPCIW.js.map +1 -0
- package/dist/{chunk-7F4DBNSP.js → chunk-3O72ZD2E.js} +3 -3
- package/dist/{chunk-FNSMZQS4.js → chunk-3PMFMUFX.js} +2 -2
- package/dist/{chunk-WQDTCJ6W.js → chunk-45YHJ3GV.js} +11 -3
- package/dist/{chunk-WQDTCJ6W.js.map → chunk-45YHJ3GV.js.map} +1 -1
- package/dist/{chunk-NIVEDYJZ.js → chunk-4A34KWOU.js} +31 -49
- package/dist/chunk-4A34KWOU.js.map +1 -0
- package/dist/{chunk-ZJADGNYF.js → chunk-4AOERLTV.js} +1 -1
- package/dist/chunk-4AOERLTV.js.map +1 -0
- package/dist/{chunk-EDXAQ6JI.js → chunk-4N5Q23KV.js} +87 -34
- package/dist/chunk-4N5Q23KV.js.map +1 -0
- package/dist/{chunk-VV4NSB7P.js → chunk-4OQZNXQG.js} +15 -24
- package/dist/chunk-4OQZNXQG.js.map +1 -0
- package/dist/{chunk-FAXZQ5UF.js → chunk-4RAS6HN6.js} +2 -2
- package/dist/{chunk-C2OOEM57.js → chunk-4YL2LMXK.js} +92 -35
- package/dist/chunk-4YL2LMXK.js.map +1 -0
- package/dist/{chunk-EP7VPR7Y.js → chunk-5Q7AJ7DN.js} +11 -8
- package/dist/chunk-5Q7AJ7DN.js.map +1 -0
- package/dist/{chunk-VMCCGUQB.js → chunk-6JPGVL7X.js} +2 -2
- package/dist/{chunk-PRDRGL73.js → chunk-6KTVJ5ZZ.js} +17 -14
- package/dist/chunk-6KTVJ5ZZ.js.map +1 -0
- package/dist/{chunk-4MC5JRRX.js → chunk-6WO62AJW.js} +14 -15
- package/dist/chunk-6WO62AJW.js.map +1 -0
- package/dist/{chunk-WLYIROCJ.js → chunk-6YD5SYQS.js} +2 -2
- package/dist/{chunk-YAWK6AWF.js → chunk-7KAE7CQ2.js} +2 -2
- package/dist/{chunk-MWKDOHEF.js → chunk-7LNE2N2V.js} +17 -10
- package/dist/chunk-7LNE2N2V.js.map +1 -0
- package/dist/{chunk-5PR33AC4.js → chunk-7PJ3BKHS.js} +20 -17
- package/dist/chunk-7PJ3BKHS.js.map +1 -0
- package/dist/{chunk-JXIDGFKS.js → chunk-A4TOGAUW.js} +4 -2
- package/dist/chunk-A4TOGAUW.js.map +1 -0
- package/dist/{chunk-VCETL77O.js → chunk-AU3AUJIZ.js} +27 -7
- package/dist/chunk-AU3AUJIZ.js.map +1 -0
- package/dist/{chunk-NKH7GSIH.js → chunk-AUPSEJ7O.js} +4 -4
- package/dist/{chunk-CCZJJ4I2.js → chunk-B6IYATME.js} +4 -4
- package/dist/{chunk-WYZ5MYUA.js → chunk-BAHOV5I5.js} +44 -42
- package/dist/chunk-BAHOV5I5.js.map +1 -0
- package/dist/{chunk-G5APARUV.js → chunk-BEZDLIDG.js} +13 -15
- package/dist/chunk-BEZDLIDG.js.map +1 -0
- package/dist/{chunk-ERB6NDDW.js → chunk-CAGI4LLJ.js} +427 -72
- package/dist/chunk-CAGI4LLJ.js.map +1 -0
- package/dist/{chunk-4UVDI4XE.js → chunk-CLAHBPOI.js} +4 -4
- package/dist/{chunk-HNGSV2YC.js → chunk-CWM4GQD2.js} +39 -10
- package/dist/chunk-CWM4GQD2.js.map +1 -0
- package/dist/{chunk-HVQGCKY4.js → chunk-D3R7Q4QK.js} +2 -2
- package/dist/{chunk-I4F6PKUK.js → chunk-DIZ6HM7Q.js} +16 -17
- package/dist/chunk-DIZ6HM7Q.js.map +1 -0
- package/dist/{chunk-ZNACADFG.js → chunk-DVRZYAGT.js} +4 -4
- package/dist/chunk-DVRZYAGT.js.map +1 -0
- package/dist/{chunk-P7OG2ETF.js → chunk-DXKLLKME.js} +3 -3
- package/dist/{chunk-TDJPS3T2.js → chunk-E5SC6ENM.js} +24 -19
- package/dist/chunk-E5SC6ENM.js.map +1 -0
- package/dist/{chunk-26JMGSSC.js → chunk-EES37S2V.js} +4 -4
- package/dist/chunk-EES37S2V.js.map +1 -0
- package/dist/{chunk-JIUVJ4M7.js → chunk-EKEIEJL6.js} +2 -2
- package/dist/{chunk-GASWQ3XG.js → chunk-ESKIAXO2.js} +15 -16
- package/dist/chunk-ESKIAXO2.js.map +1 -0
- package/dist/{chunk-TOAIYQJR.js → chunk-FFSQFH6D.js} +7 -10
- package/dist/chunk-FFSQFH6D.js.map +1 -0
- package/dist/{chunk-DG27IUVI.js → chunk-FS7NTGCJ.js} +2 -2
- package/dist/{chunk-V5KYPBUR.js → chunk-FW7NGYLT.js} +11 -14
- package/dist/chunk-FW7NGYLT.js.map +1 -0
- package/dist/{chunk-52QYGZHH.js → chunk-GBBDFE6C.js} +2 -2
- package/dist/chunk-GBBDFE6C.js.map +1 -0
- package/dist/{chunk-HXGUIPQB.js → chunk-GQXFOAYZ.js} +3 -3
- package/dist/{chunk-BTVYJWSN.js → chunk-GTHVPVAR.js} +10 -10
- package/dist/{chunk-DMQCLZ4Z.js → chunk-GWO2IDAB.js} +2 -2
- package/dist/{chunk-6HFM7EIT.js → chunk-H3G4I3PN.js} +2 -2
- package/dist/chunk-HK67PX4J.js +27 -0
- package/dist/chunk-HK67PX4J.js.map +1 -0
- package/dist/{chunk-E7OBCBXS.js → chunk-HQSPF5IY.js} +22 -18
- package/dist/chunk-HQSPF5IY.js.map +1 -0
- package/dist/{chunk-VJFMXYKP.js → chunk-HR5R5JOM.js} +2 -2
- package/dist/{chunk-FDX7OWWI.js → chunk-HYYVT2KZ.js} +2 -2
- package/dist/{chunk-JRCYZEHU.js → chunk-I6QKB7MT.js} +2 -2
- package/dist/{chunk-MZ5ZFO2D.js → chunk-ICDHUUMQ.js} +84 -112
- package/dist/chunk-ICDHUUMQ.js.map +1 -0
- package/dist/{chunk-W5W6KHN2.js → chunk-IGNJOJEP.js} +1 -1
- package/dist/chunk-IGNJOJEP.js.map +1 -0
- package/dist/{chunk-KUDZVJKQ.js → chunk-IJ46VCWD.js} +2 -2
- package/dist/{chunk-4HDYQL3J.js → chunk-INMHEMXX.js} +2 -2
- package/dist/{chunk-66W5OOCX.js → chunk-JLYQQNY4.js} +52 -65
- package/dist/chunk-JLYQQNY4.js.map +1 -0
- package/dist/{chunk-UHXCLPGC.js → chunk-JNMTN5D5.js} +2 -2
- package/dist/chunk-JNMTN5D5.js.map +1 -0
- package/dist/{chunk-I4ZAO7F7.js → chunk-JWMBG5S3.js} +7 -11
- package/dist/chunk-JWMBG5S3.js.map +1 -0
- package/dist/chunk-KRVS7YWY.js +123 -0
- package/dist/chunk-KRVS7YWY.js.map +1 -0
- package/dist/{chunk-AR2JDFAE.js → chunk-KV6JM2IA.js} +2 -2
- package/dist/{chunk-PVU7LW5L.js → chunk-KX57HODD.js} +6 -6
- package/dist/{chunk-PY7CI6L5.js → chunk-LGFTOU27.js} +553 -275
- package/dist/chunk-LGFTOU27.js.map +1 -0
- package/dist/chunk-LN7P6MZB.js +190 -0
- package/dist/chunk-LN7P6MZB.js.map +1 -0
- package/dist/{chunk-UIBGXRDD.js → chunk-LX46B56Q.js} +25 -31
- package/dist/chunk-LX46B56Q.js.map +1 -0
- package/dist/{chunk-CEJWMBXO.js → chunk-LXECF2ZR.js} +2 -2
- package/dist/{chunk-7VHY5E3X.js → chunk-MSLPDFK2.js} +7 -7
- package/dist/{chunk-I6SDX7WX.js → chunk-MZTUTEHP.js} +16 -22
- package/dist/chunk-MZTUTEHP.js.map +1 -0
- package/dist/{chunk-VRA4Q7DA.js → chunk-NCCEDL2K.js} +55 -48
- package/dist/chunk-NCCEDL2K.js.map +1 -0
- package/dist/{chunk-HNHCQ556.js → chunk-NR2SUJ3H.js} +2 -2
- package/dist/{chunk-AHLJSVRL.js → chunk-NW4TY6VC.js} +5 -7
- package/dist/chunk-NW4TY6VC.js.map +1 -0
- package/dist/{chunk-RKKORO4M.js → chunk-O742QBZZ.js} +10 -10
- package/dist/chunk-O742QBZZ.js.map +1 -0
- package/dist/{chunk-VN45YLWM.js → chunk-OHOKBMTM.js} +343 -132
- package/dist/chunk-OHOKBMTM.js.map +1 -0
- package/dist/{chunk-W3TVWF6N.js → chunk-OIBEJN5H.js} +2 -2
- package/dist/{chunk-QD724WDJ.js → chunk-OMYCSTXL.js} +4 -4
- package/dist/{chunk-Z45YRGFO.js → chunk-ONVD6GBY.js} +2 -2
- package/dist/{chunk-TAGFGKHP.js → chunk-OTHHO3KI.js} +7 -10
- package/dist/chunk-OTHHO3KI.js.map +1 -0
- package/dist/{chunk-3737A6EA.js → chunk-P2MR5UNE.js} +75 -18
- package/dist/chunk-P2MR5UNE.js.map +1 -0
- package/dist/chunk-PENPHA45.js +66 -0
- package/dist/chunk-PENPHA45.js.map +1 -0
- package/dist/{chunk-3FSX6LDG.js → chunk-PPCOKVFA.js} +8 -3
- package/dist/{chunk-3FSX6LDG.js.map → chunk-PPCOKVFA.js.map} +1 -1
- package/dist/{chunk-VOQW5LAM.js → chunk-QSIEL6TL.js} +102 -71
- package/dist/chunk-QSIEL6TL.js.map +1 -0
- package/dist/chunk-RFO4UXKQ.js +201 -0
- package/dist/chunk-RFO4UXKQ.js.map +1 -0
- package/dist/{chunk-KCQX65FU.js → chunk-RKCRPPNB.js} +3 -3
- package/dist/{chunk-7TSYBD3E.js → chunk-RSXQNFGO.js} +2 -2
- package/dist/{chunk-SZ2K3MHL.js → chunk-S56VYR4Q.js} +8 -11
- package/dist/{chunk-SZ2K3MHL.js.map → chunk-S56VYR4Q.js.map} +1 -1
- package/dist/{chunk-7NXHMW6Y.js → chunk-SYS46BL7.js} +2 -2
- package/dist/{chunk-55LKVALY.js → chunk-T7IR4N2S.js} +1 -3
- package/dist/chunk-T7IR4N2S.js.map +1 -0
- package/dist/{chunk-A67356IR.js → chunk-T7JGWTES.js} +33 -8
- package/dist/chunk-T7JGWTES.js.map +1 -0
- package/dist/{chunk-WHJKIZS7.js → chunk-TDSN2O2V.js} +27 -149
- package/dist/chunk-TDSN2O2V.js.map +1 -0
- package/dist/{chunk-747LRSOO.js → chunk-TMBSPLUG.js} +2 -2
- package/dist/{chunk-LWSJG3LI.js → chunk-TQPASLY4.js} +7 -3
- package/dist/chunk-TQPASLY4.js.map +1 -0
- package/dist/{chunk-WKPJXWKR.js → chunk-TX5MKAHA.js} +3 -3
- package/dist/{chunk-HFQ6LGIO.js → chunk-U27Y4DJZ.js} +12 -10
- package/dist/{chunk-HFQ6LGIO.js.map → chunk-U27Y4DJZ.js.map} +1 -1
- package/dist/{chunk-E6427JU2.js → chunk-VVSOPRUE.js} +18 -2
- package/dist/chunk-VVSOPRUE.js.map +1 -0
- package/dist/{chunk-7G6VDWXB.js → chunk-WVE6YKMX.js} +3 -3
- package/dist/chunk-WVE6YKMX.js.map +1 -0
- package/dist/{chunk-GLKDWWNO.js → chunk-YALD3SST.js} +16 -14
- package/dist/chunk-YALD3SST.js.map +1 -0
- package/dist/{chunk-NJDQ4YSV.js → chunk-YKXZHUOW.js} +4 -4
- package/dist/{chunk-VW6ZZGCG.js → chunk-ZLHHE5XZ.js} +3 -3
- package/dist/{chunk-FUHKW252.js → chunk-ZZXLB6AS.js} +2 -2
- package/dist/classified/index.js +5 -5
- package/dist/{classified-marker-FTOX7Q5L.js → classified-marker-NA6HUV33.js} +3 -3
- package/dist/collection-facade-VBM35WAH.js +45 -0
- package/dist/{computed-6G5M3UPH.js → computed-GSTLWSY5.js} +3 -3
- package/dist/consent/index.js +10 -10
- package/dist/cover/index.js +10 -3
- package/dist/custody/index.js +11 -11
- package/dist/{dead-filter-ENRIOQIE.js → dead-filter-UALP5DJX.js} +2 -2
- package/dist/debug/index.js +1 -1
- package/dist/{delegation-SSEPLXXO.js → delegation-JLNXM7KH.js} +24 -23
- package/dist/delegation-JLNXM7KH.js.map +1 -0
- package/dist/derivations/index.js +12 -12
- package/dist/derive-YUO3TQYN.js +22 -0
- package/dist/directory/index.js +10 -10
- package/dist/{dispatch-RE74SH6L.js → dispatch-4ZHLSFZQ.js} +5 -5
- package/dist/{dispatch-BDVGYC6X.js → dispatch-77CB75KB.js} +18 -18
- package/dist/{enclave-52VUXNRL.js → enclave-O4NOROCJ.js} +27 -9
- package/dist/executor-CZDXBXKE.js +29 -0
- package/dist/executor-DVJAWN3B.js +9 -0
- package/dist/executor-VRLG4TQJ.js +9 -0
- package/dist/export-accessible-UXSMG7AB.js +23 -0
- package/dist/extract-partition-TVY7AMKH.js +38 -0
- package/dist/{fanout-sidecar-DTBIDOWF.js → fanout-sidecar-NLQ7QAYW.js} +18 -27
- package/dist/fanout-sidecar-NLQ7QAYW.js.map +1 -0
- package/dist/find-WSARMJBW.js +11 -0
- package/dist/forget/index.js +9 -9
- package/dist/guards/index.js +7 -7
- package/dist/history/index.js +23 -20
- package/dist/history/index.js.map +1 -1
- package/dist/i18n/index.js +14 -14
- package/dist/index.d.ts +33 -15
- package/dist/index.js +187 -191
- package/dist/index.js.map +1 -1
- package/dist/indexing/index.js +2 -2
- package/dist/introspection/index.js +11 -11
- package/dist/issue-3JNJNPT3.js +19 -0
- package/dist/kernel/constants.d.ts +18 -0
- package/dist/kernel/enclave/crypto.d.ts +24 -4
- package/dist/kernel/enclave/index.d.ts +9 -2
- package/dist/kernel/enclave/record-aad.d.ts +131 -0
- package/dist/kernel/enclave/record-envelope.d.ts +76 -0
- package/dist/kernel/enclave/record-keys/envelope-body.d.ts +34 -2
- package/dist/kernel/enclave/record-keys/lifecycle.d.ts +22 -5
- package/dist/kernel/enclave/record-keys/record-codec.d.ts +47 -14
- package/dist/kernel/enclave/record-keys/rekey-blob.d.ts +88 -0
- package/dist/kernel/enclave/record-keys/rekey.d.ts +68 -0
- package/dist/kernel/enclave/record-keys/tombstone.d.ts +3 -2
- package/dist/kernel/errors.d.ts +71 -12
- package/dist/kernel/merge-authority.d.ts +25 -0
- package/dist/kernel/noydb.d.ts +27 -4
- package/dist/kernel/query/builder.d.ts +15 -2
- package/dist/kernel/query/join.d.ts +27 -0
- package/dist/kernel/sync-policy.d.ts +0 -2
- package/dist/kernel/tier-visibility.d.ts +15 -0
- package/dist/kernel/types.d.ts +145 -12
- package/dist/kernel/vault.d.ts +22 -18
- package/dist/kernel/via/index.d.ts +11 -2
- package/dist/{ledger-4WJL66BW.js → ledger-MVPNG5OS.js} +11 -11
- package/dist/liberate-4LOJOLDT.js +24 -0
- package/dist/{link-set-N4ZPV6E6.js → link-set-3POMQR3I.js} +11 -11
- package/dist/{managed-secret-OTHS64IF.js → managed-secret-IARIJJ7Q.js} +11 -3
- package/dist/materialized-views/index.js +22 -21
- package/dist/migrate-cek-XM2ETTZW.js +19 -0
- package/dist/migrate-cek-XM2ETTZW.js.map +1 -0
- package/dist/money/index.js +12 -8
- package/dist/noydb-IRILUDED.js +84 -0
- package/dist/overlay-views/index.js +4 -4
- package/dist/periods/index.js +22 -12
- package/dist/pod/index.js +75 -86
- package/dist/pod-handle-MELERCKU.js +41 -0
- package/dist/pod-handle-MELERCKU.js.map +1 -0
- package/dist/policy/index.js +11 -4
- package/dist/port/to/index.d.ts +4 -4
- package/dist/port/to/locator.d.ts +54 -8
- package/dist/port/with/i18n-strategy.d.ts +4 -1
- package/dist/port/with/lookup-strategy.d.ts +4 -1
- package/dist/port/with/merge-authority.d.ts +52 -0
- package/dist/port/with/service-bus.d.ts +0 -4
- package/dist/port/with/strategies.d.ts +2 -0
- package/dist/port/with/team-strategy.d.ts +5 -1
- package/dist/portability/index.js +8 -8
- package/dist/{post-register-ZAG2CAIY.js → post-register-Z5T7FY45.js} +6 -6
- package/dist/query/index.js +3 -3
- package/dist/reduce/index.js +4 -4
- package/dist/register-UZ37QPDB.js +32 -0
- package/dist/registry-ETJNA7PO.js +9 -0
- package/dist/registry-F7U6KSLX.js +9 -0
- package/dist/registry-L4ELKX6C.js +18 -0
- package/dist/registry-SDT5LIGO.js +19 -0
- package/dist/request-withdrawal-PVFEYX57.js +31 -0
- package/dist/{reveal-CMOJY4VO.js → reveal-DQ2E3QAZ.js} +6 -6
- package/dist/revoke-YXY6SHUH.js +24 -0
- package/dist/satellites/index.js +1 -1
- package/dist/schema-update/index.js +2 -2
- package/dist/sealed-record/index.js +20 -13
- package/dist/sealed-record/index.js.map +1 -1
- package/dist/search/index.js +4 -4
- package/dist/{seed-UK4QRIUN.js → seed-DZ4ORU5N.js} +19 -22
- package/dist/seed-DZ4ORU5N.js.map +1 -0
- package/dist/sequence/index.js +9 -9
- package/dist/session/index.js +10 -10
- package/dist/shadow/index.js +2 -2
- package/dist/share-link/index.js +1 -1
- package/dist/signer-Q7XQBMPA.js +25 -0
- package/dist/snapshots/index.js +10 -10
- package/dist/snapshots/index.js.map +1 -1
- package/dist/{stale-ZWXSOWJI.js → stale-NI7SAXAZ.js} +10 -10
- package/dist/storage-3VNGSHXS.js +23 -0
- package/dist/{store-coordination-provider-PB6QZ57W.js → store-coordination-provider-TYKNR3OU.js} +18 -12
- package/dist/store-coordination-provider-TYKNR3OU.js.map +1 -0
- package/dist/sync/index.js +11 -11
- package/dist/team/index.js +15 -14
- package/dist/tiers/index.js +11 -10
- package/dist/to/index.js +17 -9
- package/dist/to/index.js.map +1 -1
- package/dist/transactions/index.js +4 -4
- package/dist/{ulid-PTAIMDG4.js → ulid-VQW6ERQN.js} +2 -2
- package/dist/util/index.js +1 -1
- package/dist/vault-head/index.js +115 -0
- package/dist/vault-head/index.js.map +1 -0
- package/dist/{verify-RO5RTZOJ.js → verify-6J2YLKSO.js} +5 -5
- package/dist/via/lookup/handle.d.ts +4 -1
- package/dist/via/money/exact.d.ts +44 -0
- package/dist/via/money/index.d.ts +2 -0
- package/dist/via/money/normalize.d.ts +20 -0
- package/dist/walk-WRA7RAPY.js +21 -0
- package/dist/with-audit/guards/immutable-guard.d.ts +14 -0
- package/dist/with-audit/periods/active.d.ts +28 -1
- package/dist/with-audit/periods/index.d.ts +4 -2
- package/dist/with-audit/periods/periods.d.ts +161 -6
- package/dist/with-audit/periods/strategy.d.ts +14 -5
- package/dist/with-audit/periods/vault-facade.d.ts +89 -10
- package/dist/with-audit/periods/window.d.ts +10 -0
- package/dist/with-audit/sealed-record/index.d.ts +13 -0
- package/dist/with-audit/tiers/index.d.ts +17 -2
- package/dist/with-cargo/adopt-partition.d.ts +1 -1
- package/dist/with-cargo/extract-partition.d.ts +1 -1
- package/dist/with-cargo/index.d.ts +2 -2
- package/dist/with-commit/history/history.d.ts +26 -0
- package/dist/with-commit/history/index.d.ts +2 -1
- package/dist/with-commit/history/ledger/store.d.ts +7 -1
- package/dist/with-commit/history/strategy.d.ts +11 -1
- package/dist/with-commit/numbering/index.d.ts +0 -5
- package/dist/with-commit/vault-head/active.d.ts +2 -0
- package/dist/with-commit/vault-head/head.d.ts +28 -0
- package/dist/with-commit/vault-head/index.d.ts +10 -0
- package/dist/with-commit/vault-head/strategy.d.ts +127 -0
- package/dist/with-commit/vault-head/verify.d.ts +90 -0
- package/dist/with-formula/materialized-views/types.d.ts +52 -0
- package/dist/with-party/directory/cover/storage.d.ts +0 -8
- package/dist/with-party/directory/storage.d.ts +0 -11
- package/dist/with-party/directory/visibility.d.ts +0 -21
- package/dist/with-party/policy/storage.d.ts +0 -10
- package/dist/with-party/team/index.d.ts +1 -1
- package/dist/with-party/team/keyring.d.ts +149 -3
- package/dist/with-party/team/noydb-facade.d.ts +5 -1
- package/dist/with-party/team/roster-tag.d.ts +101 -0
- package/dist/with-party/team/tiers.d.ts +2 -1
- package/dist/with-pod/format.d.ts +10 -12
- package/dist/with-pod/index.d.ts +10 -10
- package/dist/with-pod/open.d.ts +2 -2
- package/dist/with-pod/pod-handle.d.ts +19 -0
- package/dist/with-pod/pod-store.d.ts +0 -8
- package/dist/with-pod/{bundle.d.ts → pod.d.ts} +26 -19
- package/dist/with-pod/ulid.d.ts +1 -1
- package/dist/with-shape/blobs/blob-set.d.ts +2 -2
- package/dist/with-shape/introspection/index.d.ts +1 -0
- package/dist/with-sync/engine.d.ts +54 -5
- package/dist/with-sync/strategy.d.ts +3 -0
- package/dist/withdraw-accessible-4JTDFRFZ.js +28 -0
- package/package.json +13 -5
- package/dist/api-WVY3H3YH.js +0 -20
- package/dist/backup-YYBE5RPC.js.map +0 -1
- package/dist/bundle-handle-JEUWU2SJ.js +0 -36
- package/dist/bundle-handle-JEUWU2SJ.js.map +0 -1
- package/dist/chunk-26JMGSSC.js.map +0 -1
- package/dist/chunk-3737A6EA.js.map +0 -1
- package/dist/chunk-4MC5JRRX.js.map +0 -1
- package/dist/chunk-52QYGZHH.js.map +0 -1
- package/dist/chunk-55LKVALY.js.map +0 -1
- package/dist/chunk-5PR33AC4.js.map +0 -1
- package/dist/chunk-66W5OOCX.js.map +0 -1
- package/dist/chunk-7G6VDWXB.js.map +0 -1
- package/dist/chunk-A67356IR.js.map +0 -1
- package/dist/chunk-AFHQATY4.js +0 -47
- package/dist/chunk-AFHQATY4.js.map +0 -1
- package/dist/chunk-AHLJSVRL.js.map +0 -1
- package/dist/chunk-C2OOEM57.js.map +0 -1
- package/dist/chunk-DIMKRG2E.js +0 -131
- package/dist/chunk-DIMKRG2E.js.map +0 -1
- package/dist/chunk-E6427JU2.js.map +0 -1
- package/dist/chunk-E7OBCBXS.js.map +0 -1
- package/dist/chunk-EDXAQ6JI.js.map +0 -1
- package/dist/chunk-EP7VPR7Y.js.map +0 -1
- package/dist/chunk-ERB6NDDW.js.map +0 -1
- package/dist/chunk-G5APARUV.js.map +0 -1
- package/dist/chunk-GASWQ3XG.js.map +0 -1
- package/dist/chunk-GLKDWWNO.js.map +0 -1
- package/dist/chunk-HNGSV2YC.js.map +0 -1
- package/dist/chunk-I4F6PKUK.js.map +0 -1
- package/dist/chunk-I4ZAO7F7.js.map +0 -1
- package/dist/chunk-I6SDX7WX.js.map +0 -1
- package/dist/chunk-JXIDGFKS.js.map +0 -1
- package/dist/chunk-LWSJG3LI.js.map +0 -1
- package/dist/chunk-MWKDOHEF.js.map +0 -1
- package/dist/chunk-MZ5ZFO2D.js.map +0 -1
- package/dist/chunk-NIVEDYJZ.js.map +0 -1
- package/dist/chunk-NWCGDAV6.js +0 -45
- package/dist/chunk-NWCGDAV6.js.map +0 -1
- package/dist/chunk-PJNTR2NV.js.map +0 -1
- package/dist/chunk-PRDRGL73.js.map +0 -1
- package/dist/chunk-PY7CI6L5.js.map +0 -1
- package/dist/chunk-RKKORO4M.js.map +0 -1
- package/dist/chunk-TAGFGKHP.js.map +0 -1
- package/dist/chunk-TDJPS3T2.js.map +0 -1
- package/dist/chunk-TOAIYQJR.js.map +0 -1
- package/dist/chunk-UHXCLPGC.js.map +0 -1
- package/dist/chunk-UIBGXRDD.js.map +0 -1
- package/dist/chunk-V5KYPBUR.js.map +0 -1
- package/dist/chunk-VCETL77O.js.map +0 -1
- package/dist/chunk-VN45YLWM.js.map +0 -1
- package/dist/chunk-VOQW5LAM.js.map +0 -1
- package/dist/chunk-VRA4Q7DA.js.map +0 -1
- package/dist/chunk-VV4NSB7P.js.map +0 -1
- package/dist/chunk-W5W6KHN2.js.map +0 -1
- package/dist/chunk-WHJKIZS7.js.map +0 -1
- package/dist/chunk-WYZ5MYUA.js.map +0 -1
- package/dist/chunk-ZJADGNYF.js.map +0 -1
- package/dist/chunk-ZNACADFG.js.map +0 -1
- package/dist/collection-facade-QN5ULWYC.js +0 -45
- package/dist/delegation-SSEPLXXO.js.map +0 -1
- package/dist/derive-6V3PIZF7.js +0 -22
- package/dist/executor-CYJQLKKI.js +0 -9
- package/dist/executor-FHHLXO4Y.js +0 -28
- package/dist/executor-S4QIKEHW.js +0 -9
- package/dist/export-accessible-PE5AYKZR.js +0 -23
- package/dist/extract-partition-X2L26O6A.js +0 -38
- package/dist/fanout-sidecar-DTBIDOWF.js.map +0 -1
- package/dist/find-RBBYKXI7.js +0 -11
- package/dist/issue-RNU55YOF.js +0 -19
- package/dist/liberate-PX4CAT5V.js +0 -24
- package/dist/noydb-YPSEGK32.js +0 -83
- package/dist/register-TMD6YRCX.js +0 -32
- package/dist/registry-CZVINVQH.js +0 -9
- package/dist/registry-FVLDWQKT.js +0 -18
- package/dist/registry-IKUR2MXD.js +0 -9
- package/dist/registry-JET4HBLY.js +0 -19
- package/dist/request-withdrawal-RH55LNZL.js +0 -31
- package/dist/revoke-R5TBYVA6.js +0 -24
- package/dist/seed-UK4QRIUN.js.map +0 -1
- package/dist/signer-AGALOXOO.js +0 -25
- package/dist/storage-N7LB275C.js +0 -23
- package/dist/store-coordination-provider-PB6QZ57W.js.map +0 -1
- package/dist/walk-OCUHCYJ6.js +0 -21
- package/dist/with-pod/bundle-handle.d.ts +0 -9
- package/dist/withdraw-accessible-QQNWM5BO.js +0 -28
- /package/dist/{api-WVY3H3YH.js.map → api-EYNT6KGS.js.map} +0 -0
- /package/dist/{chunk-35EBKWQU.js.map → chunk-2LFOMUEA.js.map} +0 -0
- /package/dist/{chunk-OF3L2SD6.js.map → chunk-32B7VCKU.js.map} +0 -0
- /package/dist/{chunk-MSWYQLMQ.js.map → chunk-3B6S6RSI.js.map} +0 -0
- /package/dist/{chunk-7F4DBNSP.js.map → chunk-3O72ZD2E.js.map} +0 -0
- /package/dist/{chunk-FNSMZQS4.js.map → chunk-3PMFMUFX.js.map} +0 -0
- /package/dist/{chunk-FAXZQ5UF.js.map → chunk-4RAS6HN6.js.map} +0 -0
- /package/dist/{chunk-VMCCGUQB.js.map → chunk-6JPGVL7X.js.map} +0 -0
- /package/dist/{chunk-WLYIROCJ.js.map → chunk-6YD5SYQS.js.map} +0 -0
- /package/dist/{chunk-YAWK6AWF.js.map → chunk-7KAE7CQ2.js.map} +0 -0
- /package/dist/{chunk-NKH7GSIH.js.map → chunk-AUPSEJ7O.js.map} +0 -0
- /package/dist/{chunk-CCZJJ4I2.js.map → chunk-B6IYATME.js.map} +0 -0
- /package/dist/{chunk-4UVDI4XE.js.map → chunk-CLAHBPOI.js.map} +0 -0
- /package/dist/{chunk-HVQGCKY4.js.map → chunk-D3R7Q4QK.js.map} +0 -0
- /package/dist/{chunk-P7OG2ETF.js.map → chunk-DXKLLKME.js.map} +0 -0
- /package/dist/{chunk-JIUVJ4M7.js.map → chunk-EKEIEJL6.js.map} +0 -0
- /package/dist/{chunk-DG27IUVI.js.map → chunk-FS7NTGCJ.js.map} +0 -0
- /package/dist/{chunk-HXGUIPQB.js.map → chunk-GQXFOAYZ.js.map} +0 -0
- /package/dist/{chunk-BTVYJWSN.js.map → chunk-GTHVPVAR.js.map} +0 -0
- /package/dist/{chunk-DMQCLZ4Z.js.map → chunk-GWO2IDAB.js.map} +0 -0
- /package/dist/{chunk-6HFM7EIT.js.map → chunk-H3G4I3PN.js.map} +0 -0
- /package/dist/{chunk-VJFMXYKP.js.map → chunk-HR5R5JOM.js.map} +0 -0
- /package/dist/{chunk-FDX7OWWI.js.map → chunk-HYYVT2KZ.js.map} +0 -0
- /package/dist/{chunk-JRCYZEHU.js.map → chunk-I6QKB7MT.js.map} +0 -0
- /package/dist/{chunk-KUDZVJKQ.js.map → chunk-IJ46VCWD.js.map} +0 -0
- /package/dist/{chunk-4HDYQL3J.js.map → chunk-INMHEMXX.js.map} +0 -0
- /package/dist/{chunk-AR2JDFAE.js.map → chunk-KV6JM2IA.js.map} +0 -0
- /package/dist/{chunk-PVU7LW5L.js.map → chunk-KX57HODD.js.map} +0 -0
- /package/dist/{chunk-CEJWMBXO.js.map → chunk-LXECF2ZR.js.map} +0 -0
- /package/dist/{chunk-7VHY5E3X.js.map → chunk-MSLPDFK2.js.map} +0 -0
- /package/dist/{chunk-HNHCQ556.js.map → chunk-NR2SUJ3H.js.map} +0 -0
- /package/dist/{chunk-W3TVWF6N.js.map → chunk-OIBEJN5H.js.map} +0 -0
- /package/dist/{chunk-QD724WDJ.js.map → chunk-OMYCSTXL.js.map} +0 -0
- /package/dist/{chunk-Z45YRGFO.js.map → chunk-ONVD6GBY.js.map} +0 -0
- /package/dist/{chunk-KCQX65FU.js.map → chunk-RKCRPPNB.js.map} +0 -0
- /package/dist/{chunk-7TSYBD3E.js.map → chunk-RSXQNFGO.js.map} +0 -0
- /package/dist/{chunk-7NXHMW6Y.js.map → chunk-SYS46BL7.js.map} +0 -0
- /package/dist/{chunk-747LRSOO.js.map → chunk-TMBSPLUG.js.map} +0 -0
- /package/dist/{chunk-WKPJXWKR.js.map → chunk-TX5MKAHA.js.map} +0 -0
- /package/dist/{chunk-NJDQ4YSV.js.map → chunk-YKXZHUOW.js.map} +0 -0
- /package/dist/{chunk-VW6ZZGCG.js.map → chunk-ZLHHE5XZ.js.map} +0 -0
- /package/dist/{chunk-FUHKW252.js.map → chunk-ZZXLB6AS.js.map} +0 -0
- /package/dist/{classified-marker-FTOX7Q5L.js.map → classified-marker-NA6HUV33.js.map} +0 -0
- /package/dist/{collection-facade-QN5ULWYC.js.map → collection-facade-VBM35WAH.js.map} +0 -0
- /package/dist/{computed-6G5M3UPH.js.map → computed-GSTLWSY5.js.map} +0 -0
- /package/dist/{dead-filter-ENRIOQIE.js.map → dead-filter-UALP5DJX.js.map} +0 -0
- /package/dist/{derive-6V3PIZF7.js.map → derive-YUO3TQYN.js.map} +0 -0
- /package/dist/{dispatch-RE74SH6L.js.map → dispatch-4ZHLSFZQ.js.map} +0 -0
- /package/dist/{dispatch-BDVGYC6X.js.map → dispatch-77CB75KB.js.map} +0 -0
- /package/dist/{enclave-52VUXNRL.js.map → enclave-O4NOROCJ.js.map} +0 -0
- /package/dist/{executor-CYJQLKKI.js.map → executor-CZDXBXKE.js.map} +0 -0
- /package/dist/{executor-FHHLXO4Y.js.map → executor-DVJAWN3B.js.map} +0 -0
- /package/dist/{executor-S4QIKEHW.js.map → executor-VRLG4TQJ.js.map} +0 -0
- /package/dist/{export-accessible-PE5AYKZR.js.map → export-accessible-UXSMG7AB.js.map} +0 -0
- /package/dist/{extract-partition-X2L26O6A.js.map → extract-partition-TVY7AMKH.js.map} +0 -0
- /package/dist/{find-RBBYKXI7.js.map → find-WSARMJBW.js.map} +0 -0
- /package/dist/{issue-RNU55YOF.js.map → issue-3JNJNPT3.js.map} +0 -0
- /package/dist/{ledger-4WJL66BW.js.map → ledger-MVPNG5OS.js.map} +0 -0
- /package/dist/{liberate-PX4CAT5V.js.map → liberate-4LOJOLDT.js.map} +0 -0
- /package/dist/{link-set-N4ZPV6E6.js.map → link-set-3POMQR3I.js.map} +0 -0
- /package/dist/{managed-secret-OTHS64IF.js.map → managed-secret-IARIJJ7Q.js.map} +0 -0
- /package/dist/{noydb-YPSEGK32.js.map → noydb-IRILUDED.js.map} +0 -0
- /package/dist/{post-register-ZAG2CAIY.js.map → post-register-Z5T7FY45.js.map} +0 -0
- /package/dist/{register-TMD6YRCX.js.map → register-UZ37QPDB.js.map} +0 -0
- /package/dist/{registry-CZVINVQH.js.map → registry-ETJNA7PO.js.map} +0 -0
- /package/dist/{registry-FVLDWQKT.js.map → registry-F7U6KSLX.js.map} +0 -0
- /package/dist/{registry-IKUR2MXD.js.map → registry-L4ELKX6C.js.map} +0 -0
- /package/dist/{registry-JET4HBLY.js.map → registry-SDT5LIGO.js.map} +0 -0
- /package/dist/{request-withdrawal-RH55LNZL.js.map → request-withdrawal-PVFEYX57.js.map} +0 -0
- /package/dist/{reveal-CMOJY4VO.js.map → reveal-DQ2E3QAZ.js.map} +0 -0
- /package/dist/{revoke-R5TBYVA6.js.map → revoke-YXY6SHUH.js.map} +0 -0
- /package/dist/{signer-AGALOXOO.js.map → signer-Q7XQBMPA.js.map} +0 -0
- /package/dist/{stale-ZWXSOWJI.js.map → stale-NI7SAXAZ.js.map} +0 -0
- /package/dist/{storage-N7LB275C.js.map → storage-3VNGSHXS.js.map} +0 -0
- /package/dist/{ulid-PTAIMDG4.js.map → ulid-VQW6ERQN.js.map} +0 -0
- /package/dist/{verify-RO5RTZOJ.js.map → verify-6J2YLKSO.js.map} +0 -0
- /package/dist/{walk-OCUHCYJ6.js.map → walk-WRA7RAPY.js.map} +0 -0
- /package/dist/{withdraw-accessible-QQNWM5BO.js.map → withdraw-accessible-4JTDFRFZ.js.map} +0 -0
|
@@ -1,136 +1,16 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
isRewrappedUnder,
|
|
6
|
-
openEnvelopeJson,
|
|
7
|
-
rewrapEnvelope
|
|
8
|
-
} from "./chunk-VN45YLWM.js";
|
|
2
|
+
getHistory,
|
|
3
|
+
historyIdentity
|
|
4
|
+
} from "./chunk-LN7P6MZB.js";
|
|
9
5
|
import {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
} from "./chunk-NWCGDAV6.js";
|
|
6
|
+
liveRecordIsElevated
|
|
7
|
+
} from "./chunk-PPCOKVFA.js";
|
|
13
8
|
import {
|
|
14
|
-
|
|
15
|
-
} from "./chunk-
|
|
9
|
+
openEnvelopeJson
|
|
10
|
+
} from "./chunk-OHOKBMTM.js";
|
|
16
11
|
import {
|
|
17
12
|
ReadOnlyAtInstantError
|
|
18
|
-
} from "./chunk-
|
|
19
|
-
|
|
20
|
-
// src/with-commit/history/history.ts
|
|
21
|
-
var HISTORY_COLLECTION = "_history";
|
|
22
|
-
var VERSION_PAD = 10;
|
|
23
|
-
function historyId(collection, recordId, version) {
|
|
24
|
-
return `${collection}:${recordId}:${String(version).padStart(VERSION_PAD, "0")}`;
|
|
25
|
-
}
|
|
26
|
-
function matchesPrefix(id, collection, recordId) {
|
|
27
|
-
if (recordId) {
|
|
28
|
-
return id.startsWith(`${collection}:${recordId}:`);
|
|
29
|
-
}
|
|
30
|
-
return id.startsWith(`${collection}:`);
|
|
31
|
-
}
|
|
32
|
-
async function saveHistory(adapter, vault, collection, recordId, envelope) {
|
|
33
|
-
const id = historyId(collection, recordId, envelope._v);
|
|
34
|
-
await adapter.put(vault, HISTORY_COLLECTION, id, envelope);
|
|
35
|
-
}
|
|
36
|
-
async function getHistory(adapter, vault, collection, recordId, options) {
|
|
37
|
-
const allIds = await adapter.list(vault, HISTORY_COLLECTION);
|
|
38
|
-
const matchingIds = allIds.filter((id) => matchesPrefix(id, collection, recordId)).sort().reverse();
|
|
39
|
-
const entries = [];
|
|
40
|
-
for (const id of matchingIds) {
|
|
41
|
-
const envelope = await adapter.get(vault, HISTORY_COLLECTION, id);
|
|
42
|
-
if (!envelope) continue;
|
|
43
|
-
if (options?.from && envelope._ts < options.from) continue;
|
|
44
|
-
if (options?.to && envelope._ts > options.to) continue;
|
|
45
|
-
entries.push(envelope);
|
|
46
|
-
if (options?.limit && entries.length >= options.limit) break;
|
|
47
|
-
}
|
|
48
|
-
return entries;
|
|
49
|
-
}
|
|
50
|
-
async function getVersionEnvelope(adapter, vault, collection, recordId, version) {
|
|
51
|
-
const id = historyId(collection, recordId, version);
|
|
52
|
-
return adapter.get(vault, HISTORY_COLLECTION, id);
|
|
53
|
-
}
|
|
54
|
-
async function pruneHistory(adapter, vault, collection, recordId, options) {
|
|
55
|
-
const allIds = await adapter.list(vault, HISTORY_COLLECTION);
|
|
56
|
-
const matchingIds = allIds.filter((id) => recordId ? matchesPrefix(id, collection, recordId) : matchesPrefix(id, collection)).sort();
|
|
57
|
-
let toDelete = [];
|
|
58
|
-
if (options.keepVersions !== void 0) {
|
|
59
|
-
const keep = options.keepVersions;
|
|
60
|
-
if (matchingIds.length > keep) {
|
|
61
|
-
toDelete = matchingIds.slice(0, matchingIds.length - keep);
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
if (options.beforeDate) {
|
|
65
|
-
for (const id of matchingIds) {
|
|
66
|
-
if (toDelete.includes(id)) continue;
|
|
67
|
-
const envelope = await adapter.get(vault, HISTORY_COLLECTION, id);
|
|
68
|
-
if (envelope && envelope._ts < options.beforeDate) {
|
|
69
|
-
toDelete.push(id);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
const uniqueDeletes = [...new Set(toDelete)];
|
|
74
|
-
for (const id of uniqueDeletes) {
|
|
75
|
-
await adapter.delete(vault, HISTORY_COLLECTION, id);
|
|
76
|
-
}
|
|
77
|
-
return uniqueDeletes.length;
|
|
78
|
-
}
|
|
79
|
-
async function clearHistory(adapter, vault, collection, recordId) {
|
|
80
|
-
const allIds = await adapter.list(vault, HISTORY_COLLECTION);
|
|
81
|
-
let toDelete;
|
|
82
|
-
if (collection && recordId) {
|
|
83
|
-
toDelete = allIds.filter((id) => matchesPrefix(id, collection, recordId));
|
|
84
|
-
} else if (collection) {
|
|
85
|
-
toDelete = allIds.filter((id) => matchesPrefix(id, collection));
|
|
86
|
-
} else {
|
|
87
|
-
toDelete = allIds;
|
|
88
|
-
}
|
|
89
|
-
for (const id of toDelete) {
|
|
90
|
-
await adapter.delete(vault, HISTORY_COLLECTION, id);
|
|
91
|
-
}
|
|
92
|
-
return toDelete.length;
|
|
93
|
-
}
|
|
94
|
-
async function tombstoneHistory(adapter, vault, collection, recordId, actor, encrypted) {
|
|
95
|
-
const allIds = await adapter.list(vault, HISTORY_COLLECTION);
|
|
96
|
-
const matchingIds = allIds.filter((id) => matchesPrefix(id, collection, recordId));
|
|
97
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
98
|
-
let count = 0;
|
|
99
|
-
for (const id of matchingIds) {
|
|
100
|
-
const env = await adapter.get(vault, HISTORY_COLLECTION, id);
|
|
101
|
-
if (!env) continue;
|
|
102
|
-
if (isTombstone(env, encrypted)) continue;
|
|
103
|
-
const tombstone = {
|
|
104
|
-
_noydb: NOYDB_FORMAT_VERSION,
|
|
105
|
-
_v: env._v,
|
|
106
|
-
_ts: now,
|
|
107
|
-
_iv: "",
|
|
108
|
-
_data: "",
|
|
109
|
-
...actor ? { _by: actor } : {}
|
|
110
|
-
};
|
|
111
|
-
await adapter.put(vault, HISTORY_COLLECTION, id, tombstone);
|
|
112
|
-
count++;
|
|
113
|
-
}
|
|
114
|
-
return count;
|
|
115
|
-
}
|
|
116
|
-
async function rewrapHistory(adapter, vault, collection, recordId, fromDek, toDek, tier0Dek) {
|
|
117
|
-
const allIds = await adapter.list(vault, HISTORY_COLLECTION);
|
|
118
|
-
const matchingIds = allIds.filter((id) => matchesPrefix(id, collection, recordId));
|
|
119
|
-
for (const id of matchingIds) {
|
|
120
|
-
const env = await adapter.get(vault, HISTORY_COLLECTION, id);
|
|
121
|
-
if (!env) continue;
|
|
122
|
-
if (isTombstoneShape(env)) continue;
|
|
123
|
-
if (await isRewrappedUnder(env, toDek)) continue;
|
|
124
|
-
let next;
|
|
125
|
-
try {
|
|
126
|
-
next = await rewrapEnvelope(env, fromDek, toDek);
|
|
127
|
-
} catch (err) {
|
|
128
|
-
if (!tier0Dek) throw err;
|
|
129
|
-
next = await rewrapEnvelope(env, tier0Dek, toDek);
|
|
130
|
-
}
|
|
131
|
-
await adapter.put(vault, HISTORY_COLLECTION, id, next);
|
|
132
|
-
}
|
|
133
|
-
}
|
|
13
|
+
} from "./chunk-CWM4GQD2.js";
|
|
134
14
|
|
|
135
15
|
// src/with-commit/history/time-machine.ts
|
|
136
16
|
var VaultInstant = class {
|
|
@@ -170,9 +50,9 @@ var CollectionInstant = class {
|
|
|
170
50
|
* DEK directly.
|
|
171
51
|
*/
|
|
172
52
|
async get(id) {
|
|
173
|
-
const
|
|
174
|
-
if (!
|
|
175
|
-
const plaintext = this.engine.encrypted ? await openEnvelopeJson(envelope, await this.engine.getDEK(this.name)) : envelope._data;
|
|
53
|
+
const found = await this.resolveVisibleEnvelope(id);
|
|
54
|
+
if (!found) return null;
|
|
55
|
+
const plaintext = this.engine.encrypted ? await openEnvelopeJson(found.ref, found.envelope, await this.engine.getDEK(this.name)) : found.envelope._data;
|
|
176
56
|
return JSON.parse(plaintext);
|
|
177
57
|
}
|
|
178
58
|
/**
|
|
@@ -219,10 +99,10 @@ var CollectionInstant = class {
|
|
|
219
99
|
* just a decrypt failure.
|
|
220
100
|
*/
|
|
221
101
|
async resolveVisibleEnvelope(id) {
|
|
222
|
-
const
|
|
223
|
-
if (!
|
|
102
|
+
const found = await this.resolveEnvelope(id);
|
|
103
|
+
if (!found || (found.envelope._tier ?? 0) > 0) return null;
|
|
224
104
|
if (await liveRecordIsElevated(this.engine.adapter, this.engine.name, this.name, id)) return null;
|
|
225
|
-
return
|
|
105
|
+
return found;
|
|
226
106
|
}
|
|
227
107
|
/**
|
|
228
108
|
* Return the envelope that represents the record's state at
|
|
@@ -283,12 +163,14 @@ var CollectionInstant = class {
|
|
|
283
163
|
);
|
|
284
164
|
const live = await this.engine.adapter.get(this.engine.name, this.name, id);
|
|
285
165
|
const byVersion = /* @__PURE__ */ new Map();
|
|
286
|
-
for (const e of history)
|
|
287
|
-
|
|
166
|
+
for (const e of history) {
|
|
167
|
+
byVersion.set(e._v, { envelope: e, ref: historyIdentity(this.name, id, e._v) });
|
|
168
|
+
}
|
|
169
|
+
if (live) byVersion.set(live._v, { envelope: live, ref: { collection: this.name, id } });
|
|
288
170
|
const sorted = [...byVersion.values()].sort(
|
|
289
|
-
(a, b) => a._ts < b._ts ? 1 : a._ts > b._ts ? -1 : 0
|
|
171
|
+
(a, b) => a.envelope._ts < b.envelope._ts ? 1 : a.envelope._ts > b.envelope._ts ? -1 : 0
|
|
290
172
|
);
|
|
291
|
-
return sorted.find((e) => e._ts <= this.targetTs) ?? null;
|
|
173
|
+
return sorted.find((e) => e.envelope._ts <= this.targetTs) ?? null;
|
|
292
174
|
}
|
|
293
175
|
/**
|
|
294
176
|
* Fetch the envelope for a specific version. The live record (most
|
|
@@ -300,9 +182,12 @@ var CollectionInstant = class {
|
|
|
300
182
|
*/
|
|
301
183
|
async loadVersion(id, version) {
|
|
302
184
|
const live = await this.engine.adapter.get(this.engine.name, this.name, id);
|
|
303
|
-
if (live && live._v === version)
|
|
304
|
-
|
|
305
|
-
|
|
185
|
+
if (live && live._v === version) {
|
|
186
|
+
return { envelope: live, ref: { collection: this.name, id } };
|
|
187
|
+
}
|
|
188
|
+
const ref = historyIdentity(this.name, id, version);
|
|
189
|
+
const envelope = await this.engine.adapter.get(this.engine.name, ref.collection, ref.id);
|
|
190
|
+
return envelope ? { envelope, ref } : null;
|
|
306
191
|
}
|
|
307
192
|
};
|
|
308
193
|
async function collectHistoryIds(adapter, vault, collection) {
|
|
@@ -320,14 +205,7 @@ async function collectHistoryIds(adapter, vault, collection) {
|
|
|
320
205
|
}
|
|
321
206
|
|
|
322
207
|
export {
|
|
323
|
-
saveHistory,
|
|
324
|
-
getHistory,
|
|
325
|
-
getVersionEnvelope,
|
|
326
|
-
pruneHistory,
|
|
327
|
-
clearHistory,
|
|
328
|
-
tombstoneHistory,
|
|
329
|
-
rewrapHistory,
|
|
330
208
|
VaultInstant,
|
|
331
209
|
CollectionInstant
|
|
332
210
|
};
|
|
333
|
-
//# sourceMappingURL=chunk-
|
|
211
|
+
//# sourceMappingURL=chunk-TDSN2O2V.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-commit/history/time-machine.ts"],"sourcesContent":["/**\n * Time-machine queries — point-in-time reads reconstructed from the\n * existing history + ledger infrastructure.\n *\n * ## Usage\n *\n * ```ts\n * const vault = await db.openVault('acme', { secret })\n * const q1End = vault.at('2026-03-31T23:59:59Z')\n * const invoice = await q1End.collection<Invoice>('invoices').get('inv-001')\n * // → the record as it stood at the close of Q1 2026\n * ```\n *\n * ## How it works\n *\n * Every write path already fans out into two persistence lanes:\n *\n * 1. `saveHistory(...)` persists a **full encrypted envelope snapshot**\n * per version under the `_history` collection (one envelope per\n * version, keyed by `{collection}:{id}:{paddedVersion}`). Each\n * envelope carries its own `_ts` (the write timestamp).\n * 2. `ledger.append(...)` appends a hash-chained audit entry that\n * records the `op` (put / delete), `version`, and `ts`.\n *\n * Reconstruction at a target timestamp T is therefore:\n *\n * - Find the newest history envelope for `(collection, id)` whose\n * `_ts ≤ T` — that's the state the record was in at T.\n * - Check the ledger for any `op: 'delete'` entry for the same\n * `(collection, id)` with `entry.ts` in `(latestEnvelope._ts, T]` —\n * if present, the record was deleted before T, so return `null`.\n * - Decrypt the surviving envelope with the current collection DEK\n * (DEKs are per-collection but stable across versions — the same\n * key encrypts v1 and v15 of a record).\n *\n * No delta replay. The existing `history.ts` module already stores\n * complete snapshots; we just pick the right one.\n *\n * ## Read-only contract\n *\n * Every write method on `CollectionInstant` throws\n * {@link ReadOnlyAtInstantError}. A historical view is a *read*\n * surface — mutating the past would require either a branch/shadow\n * mechanism (tracked under shadow vaults) or a rewrite of\n * history, which breaks the ledger's tamper-evidence guarantee.\n *\n * @module\n */\nimport type { EncryptedEnvelope, NoydbStore } from '../../kernel/types.js'\nimport type { LedgerStore } from './ledger/store.js'\nimport { getHistory, historyIdentity } from './history.js'\n\n/**\n * An envelope together with **the address it was fetched from**.\n *\n * The time machine resolves a record's state at an instant from two different\n * places — the live collection, or a `_history` snapshot — and those are sealed\n * against different identities (#1041). Returning the envelope alone discards\n * the one fact the reader needs to open it, which is precisely the read-side\n * data-flow gap that binding identity exposes.\n */\ninterface ResolvedEnvelope {\n readonly envelope: EncryptedEnvelope\n readonly ref: { readonly collection: string; readonly id: string }\n}\nimport { openEnvelopeJson, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport { ReadOnlyAtInstantError } from '../../kernel/errors.js'\nimport { liveRecordIsElevated } from '../../kernel/tier-visibility.js'\n\n/**\n * Narrow view of a {@link Vault}'s internals that\n * {@link VaultInstant} needs. Passed in by `Vault.at()` rather than\n * constructed here so all crypto + adapter access stays inside the\n * Vault class.\n *\n * Not exported from the public barrel — consumers should get a\n * `VaultInstant` via `vault.at(ts)`, never by constructing one\n * directly.\n */\nexport interface VaultEngine {\n readonly adapter: NoydbStore\n /** Vault name (the compartment). */\n readonly name: string\n /**\n * `true` when the vault was opened with a secret (the normal\n * case). `false` in plaintext-mode vaults (`encrypt: false`) — in\n * that case `envelope._data` is raw JSON and we skip the DEK lookup.\n */\n readonly encrypted: boolean\n /**\n * Resolves the DEK used to decrypt a given collection's envelopes.\n * Not called when `encrypted` is false.\n */\n getDEK(collection: string): Promise<EnclaveKey>\n /**\n * Lazily-initialised ledger. We consult it to detect deletes that\n * happened between the latest history snapshot and the target\n * timestamp. `null` when history is disabled for this vault — in\n * that case time-machine reads fall back to history-only\n * reconstruction (which may miss deletes).\n */\n getLedger(): LedgerStore | null\n}\n\n/**\n * A vault at a fixed instant. Produced by `vault.at(timestamp)`.\n * Carries no session state of its own — every read is a fresh\n * lookup through the vault's adapter.\n *\n * Cheap to construct; safe to throw away. Create one per query.\n */\nexport class VaultInstant {\n constructor(\n private readonly engine: VaultEngine,\n /** Fully-resolved target timestamp (ISO-8601 UTC). */\n public readonly timestamp: string,\n ) {}\n\n /** Get a point-in-time view of a collection. */\n collection<T = unknown>(name: string): CollectionInstant<T> {\n return new CollectionInstant<T>(this.engine, this.timestamp, name)\n }\n}\n\n/**\n * A read-only collection view anchored to a past instant.\n *\n * Every write method throws {@link ReadOnlyAtInstantError} — see the\n * module docstring for why. The read surface is intentionally smaller\n * than the live {@link Collection}: `get` and `list` cover the\n * \"what did the books look like on date X\" use case without pulling\n * in the full query DSL / joins / aggregates at this stage. Follow-up\n * work tracked under.\n */\nexport class CollectionInstant<T = unknown> {\n constructor(\n private readonly engine: VaultEngine,\n private readonly targetTs: string,\n public readonly name: string,\n ) {}\n\n /**\n * Return the record as it existed at the target timestamp, or\n * `null` if the record had not been created yet or had already been\n * deleted by then.\n *\n * Gated on the LIVE record's current tier — #730, mirroring the #712\n * read-gate `history()`/`getVersion()` already apply: an elevated record\n * is invisible through the whole time-machine surface, not just a\n * decrypt failure. See {@link resolveVisibleEnvelope}.\n *\n * Decrypts through {@link openEnvelopeJson}, the `_cek`-aware envelope\n * body opener — a snapshot from a `perRecordKeys` collection is encrypted\n * under its own per-record CEK (wrapped in `_cek`), not the collection\n * DEK directly.\n */\n async get(id: string): Promise<T | null> {\n const found = await this.resolveVisibleEnvelope(id)\n if (!found) return null\n // The envelope may be the LIVE record or a `_history` snapshot, and the two\n // are sealed against different identities (#1041). `resolveEnvelope` carries\n // the address down with the bytes precisely so this read can name it.\n const plaintext = this.engine.encrypted\n ? await openEnvelopeJson(found.ref, found.envelope, await this.engine.getDEK(this.name))\n : found.envelope._data\n return JSON.parse(plaintext) as T\n }\n\n /**\n * IDs of records that existed (had at least one `put` and were not\n * subsequently deleted) at the target timestamp.\n *\n * Implemented as a linear scan over history + ledger. Performance\n * is bounded by total history size (not live-vault size), so the\n * memory-first vault-scale cap (1K–50K records × average history\n * depth) still applies.\n */\n async list(): Promise<string[]> {\n const historyIds = await collectHistoryIds(this.engine.adapter, this.engine.name, this.name)\n const liveIds = await this.engine.adapter.list(this.engine.name, this.name)\n const candidateIds = new Set<string>([...historyIds, ...liveIds])\n const alive: string[] = []\n for (const id of candidateIds) {\n const env = await this.resolveVisibleEnvelope(id)\n if (env) alive.push(id)\n }\n return alive.sort()\n }\n\n // ── write guards ───────────────────────────────────────────────────\n\n async put(_id: string, _record: T): Promise<never> {\n throw new ReadOnlyAtInstantError('put', this.targetTs)\n }\n async delete(_id: string): Promise<never> {\n throw new ReadOnlyAtInstantError('delete', this.targetTs)\n }\n async update(_id: string, _patch: Partial<T>): Promise<never> {\n throw new ReadOnlyAtInstantError('update', this.targetTs)\n }\n\n // ── internals ─────────────────────────────────────────────────────\n\n /**\n * {@link resolveEnvelope}, additionally gated on the record's LIVE\n * (current, not historical) tier — #730. Mirrors the #712 read-gate\n * `history()`/`getVersion()` apply: history snapshots keep their\n * tier-0-wrapped CEKs and carry no `_tier` of their own, so an elevated\n * record's prior versions would otherwise stay tier-0-decryptable here.\n * `null` for a resolved envelope carrying its own `_tier > 0` (a\n * tier-aware snapshot reached some other way) or whose LIVE record is\n * currently elevated — both `get()` and `list()` route through this so\n * the invisibility law holds on the whole time-machine read surface, not\n * just a decrypt failure.\n */\n private async resolveVisibleEnvelope(id: string): Promise<ResolvedEnvelope | null> {\n const found = await this.resolveEnvelope(id)\n if (!found || (found.envelope._tier ?? 0) > 0) return null\n if (await liveRecordIsElevated(this.engine.adapter, this.engine.name, this.name, id)) return null\n return found\n }\n\n /**\n * Return the envelope that represents the record's state at\n * `targetTs`, accounting for deletes. `null` if the record didn't\n * exist at that instant.\n *\n * ## Why we use the ledger as the authoritative timeline\n *\n * The per-version history snapshots saved by `saveHistory()` do\n * carry a `_ts` field, but that timestamp is the moment the\n * snapshot was *captured* (i.e. the instant right before the\n * subsequent overwrite), not the original write time. The ledger,\n * by contrast, records `ts` at the moment of each `put` / `delete`\n * — it's the only source that tracks the real timeline. So:\n *\n * 1. Walk the ledger; find the latest entry for `(collection, id)`\n * with `ts ≤ targetTs`.\n * 2. If that entry is a `delete`, the record was gone at the\n * target instant — return null.\n * 3. Otherwise it's a `put` with a specific `version`. Load the\n * envelope for that version from history, falling back to the\n * live collection for the most recent version.\n *\n * ## Fallback when the ledger is disabled\n *\n * If the vault has history disabled, `getLedger()` returns null and\n * we fall back to comparing envelope `_ts` fields. This is\n * approximate and gets the *last write* right but may confuse the\n * intermediate versions; adopters needing accurate time-machine\n * reads should leave history enabled.\n */\n private async resolveEnvelope(id: string): Promise<ResolvedEnvelope | null> {\n const ledger = this.engine.getLedger()\n if (ledger) {\n return this.resolveViaLedger(id, ledger)\n }\n return this.resolveViaEnvelopeTs(id)\n }\n\n private async resolveViaLedger(id: string, ledger: LedgerStore): Promise<ResolvedEnvelope | null> {\n const entries = await ledger.entries()\n // Entries are already ordered by index which is the mutation order.\n let latest: { op: 'put' | 'delete'; version: number } | null = null\n for (const e of entries) {\n if (e.collection !== this.name || e.id !== id) continue\n if (e.ts > this.targetTs) break // entries are time-ordered by index\n // `amendment` + `lifecycle` entries are audit-only summaries — they\n // carry no (collection, id) tuple of their own and would never match\n // the filter above. The narrow here is a type guard, not a runtime\n // skip.\n // `forget` is a subject-erasure summary with empty (collection, id) —\n // never matches the filter above; the narrow is a type guard.\n if (e.op === 'amendment' || e.op === 'lifecycle' || e.op === 'forget') continue\n // `migration` is a record rewrite (cutover) — resolve it like a put.\n latest = { op: e.op === 'migration' ? 'put' : e.op, version: e.version }\n }\n if (!latest) return null\n if (latest.op === 'delete') return null\n return this.loadVersion(id, latest.version)\n }\n\n private async resolveViaEnvelopeTs(id: string): Promise<ResolvedEnvelope | null> {\n const history = await getHistory(\n this.engine.adapter, this.engine.name, this.name, id,\n )\n const live = await this.engine.adapter.get(this.engine.name, this.name, id)\n // Each candidate keeps the address it came from — a snapshot and the live\n // record are sealed against different identities, and this map is exactly\n // where that provenance used to be discarded (#1041).\n const byVersion = new Map<number, ResolvedEnvelope>()\n for (const e of history) {\n byVersion.set(e._v, { envelope: e, ref: historyIdentity(this.name, id, e._v) })\n }\n if (live) byVersion.set(live._v, { envelope: live, ref: { collection: this.name, id } })\n const sorted = [...byVersion.values()].sort((a, b) =>\n a.envelope._ts < b.envelope._ts ? 1 : a.envelope._ts > b.envelope._ts ? -1 : 0,\n )\n return sorted.find((e) => e.envelope._ts <= this.targetTs) ?? null\n }\n\n /**\n * Fetch the envelope for a specific version. The live record (most\n * recent put) lives in the main collection; prior versions live in\n * `_history`. We check live first because the common case after a\n * delete is that we're trying to load the last-live version from\n * history, and skipping live for the current-version case avoids a\n * redundant lookup.\n */\n private async loadVersion(id: string, version: number): Promise<ResolvedEnvelope | null> {\n const live = await this.engine.adapter.get(this.engine.name, this.name, id)\n if (live && live._v === version) {\n return { envelope: live, ref: { collection: this.name, id } }\n }\n\n // Direct lookup by (collection, id, version) — avoids scanning all history.\n //\n // This used to rebuild the key inline as\n // `${name}:${id}:${padStart(10,'0')}` — a SECOND definition of the history\n // layout, free to drift from `historyId`'s. It now goes through\n // `historyIdentity`, the same function `saveHistory` writes with, so the\n // read address and the write address cannot disagree (#1041).\n const ref = historyIdentity(this.name, id, version)\n const envelope = await this.engine.adapter.get(this.engine.name, ref.collection, ref.id)\n return envelope ? { envelope, ref } : null\n }\n}\n\n/**\n * Scan the `_history` collection once and collect every distinct\n * `recordId` for the given collection. History keys follow the\n * shape `<collection>:<recordId>:<paddedVersion>`; we split on the\n * last two colons (delimiter-safe because `paddedVersion` is\n * exactly 10 digits).\n */\nasync function collectHistoryIds(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n): Promise<string[]> {\n const all = await adapter.list(vault, '_history')\n const prefix = `${collection}:`\n const seen = new Set<string>()\n for (const key of all) {\n if (!key.startsWith(prefix)) continue\n const lastColon = key.lastIndexOf(':')\n if (lastColon <= prefix.length) continue\n const middle = key.slice(prefix.length, lastColon)\n seen.add(middle)\n }\n return [...seen]\n}\n"],"mappings":";;;;;;;;;;;;;;;AA+GO,IAAM,eAAN,MAAmB;AAAA,EACxB,YACmB,QAED,WAChB;AAHiB;AAED;AAAA,EACf;AAAA,EAHgB;AAAA,EAED;AAAA;AAAA,EAIlB,WAAwB,MAAoC;AAC1D,WAAO,IAAI,kBAAqB,KAAK,QAAQ,KAAK,WAAW,IAAI;AAAA,EACnE;AACF;AAYO,IAAM,oBAAN,MAAqC;AAAA,EAC1C,YACmB,QACA,UACD,MAChB;AAHiB;AACA;AACD;AAAA,EACf;AAAA,EAHgB;AAAA,EACA;AAAA,EACD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBlB,MAAM,IAAI,IAA+B;AACvC,UAAM,QAAQ,MAAM,KAAK,uBAAuB,EAAE;AAClD,QAAI,CAAC,MAAO,QAAO;AAInB,UAAM,YAAY,KAAK,OAAO,YAC1B,MAAM,iBAAiB,MAAM,KAAK,MAAM,UAAU,MAAM,KAAK,OAAO,OAAO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B;AACA,SAAO,CAAC,GAAG,IAAI;AACjB;","names":[]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
} from "./chunk-LP7BEXCT.js";
|
|
6
6
|
import {
|
|
7
7
|
bufferToBase64
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-AU3AUJIZ.js";
|
|
9
9
|
|
|
10
10
|
// src/kernel/enclave/classify/bidx.ts
|
|
11
11
|
var subtle = globalThis.crypto.subtle;
|
|
@@ -66,4 +66,4 @@ export {
|
|
|
66
66
|
mintBidxTag,
|
|
67
67
|
computeBidxTarget
|
|
68
68
|
};
|
|
69
|
-
//# sourceMappingURL=chunk-
|
|
69
|
+
//# sourceMappingURL=chunk-TMBSPLUG.js.map
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
IllegalTransitionError,
|
|
3
3
|
RecordLockedError,
|
|
4
4
|
ValidationError
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-CWM4GQD2.js";
|
|
6
6
|
|
|
7
7
|
// src/with-audit/guards/with-guard.ts
|
|
8
8
|
function withGuard(strategy) {
|
|
@@ -21,7 +21,7 @@ function recordId(record) {
|
|
|
21
21
|
return typeof id === "string" ? id : "";
|
|
22
22
|
}
|
|
23
23
|
function immutableGuard(config) {
|
|
24
|
-
const { collection, after, appendOnly, amendmentRoles, amendmentInvariant } = config;
|
|
24
|
+
const { collection, name, after, appendOnly, amendmentRoles, amendmentInvariant } = config;
|
|
25
25
|
if (appendOnly && after !== void 0) {
|
|
26
26
|
throw new ValidationError("immutableGuard: `after` and `appendOnly` are mutually exclusive");
|
|
27
27
|
}
|
|
@@ -32,6 +32,10 @@ function immutableGuard(config) {
|
|
|
32
32
|
const reason = appendOnly ? "append-only collection" : "record is immutable after issue";
|
|
33
33
|
const spec = {
|
|
34
34
|
collection,
|
|
35
|
+
// Pass-through only — omitting the key entirely (rather than setting
|
|
36
|
+
// it to `undefined`) keeps the positional-fallback path in
|
|
37
|
+
// `buildGuardEntries` reachable for callers who don't name a guard.
|
|
38
|
+
...name !== void 0 ? { name } : {},
|
|
35
39
|
// Block updates to an already-immutable record. Inserts (existing
|
|
36
40
|
// null) and the transition write that first makes the record
|
|
37
41
|
// immutable are allowed — `after` reads the prior state.
|
|
@@ -120,4 +124,4 @@ export {
|
|
|
120
124
|
immutableGuard,
|
|
121
125
|
transitionGuard
|
|
122
126
|
};
|
|
123
|
-
//# sourceMappingURL=chunk-
|
|
127
|
+
//# sourceMappingURL=chunk-TQPASLY4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-audit/guards/with-guard.ts","../src/with-audit/guards/immutable-guard.ts","../src/with-audit/guards/transition-guard.ts"],"sourcesContent":["import { ValidationError } from '../../kernel/errors.js'\nimport type { GuardSpec, GuardStrategy } from './types.js'\n\n/**\n * Register a guard for a collection. Guards run on every `put()` /\n * `delete()` for the named collection (after permissions, before\n * encryption) and may:\n *\n * - `check` — block writes by throwing (typically `RecordLockedError`)\n * - `frozenFields` — freeze specific fields once a condition is true\n * - `amendment` — declare an authorized-override path with invariant\n *\n * Pass the returned handle to `createNoydb({ strategies: [...] })`.\n *\n * @see design-history/2026-05-18-guards-design.md\n */\nexport function withGuard<T extends Record<string, unknown>>(\n strategy: GuardSpec<T>,\n): GuardStrategy<T> {\n if (!strategy.collection || strategy.collection.length === 0) {\n throw new ValidationError('withGuard: collection name is required')\n }\n return {\n __noydb_strategy: 'guard',\n spec: strategy,\n }\n}\n","/**\n * `immutableGuard` — declarative WORM / append-only sugar over the guard\n * service.\n *\n * Issued fiscal documents (invoices, DDTs) must be immutable after issue.\n * That is expressible today with a hand-rolled `withGuard` (block on\n * `check`/`onDelete`, allow an admin `amendment`), but the boilerplate is\n * repetitive and easy to get subtly wrong. `immutableGuard` generates\n * exactly that guard from a declarative config, reusing the guard\n * machinery wholesale — `check`/`onDelete` rejection, the ledgered\n * `amendment` override, and composition with `periods`/`history`.\n *\n * ```ts\n * createNoydb({ guardStrategies: [\n * immutableGuard({\n * collection: 'invoices',\n * after: (r) => r.status === 'issued', // immutable once issued\n * }),\n * ] })\n * ```\n *\n * A record is mutable until `after(record)` holds; from then on, updates\n * and deletes throw `RecordLockedError` unless performed inside an\n * `amendment` transaction by an authorized role (the override is\n * ledgered by the guard amendment mechanism). `appendOnly: true` is\n * shorthand for `after: () => true` — immutable from creation.\n */\n\nimport { withGuard } from './with-guard.js'\nimport type { GuardSpec, GuardStrategy, GuardContext, GuardChange } from './types.js'\nimport { RecordLockedError, ValidationError } from '../../kernel/errors.js'\n\nexport interface ImmutableGuardConfig<T extends Record<string, unknown>> {\n /** The collection to make WORM. */\n collection: string\n /**\n * Optional stable per-vault identifier, forwarded verbatim to the\n * underlying {@link GuardSpec.name} — `immutableGuard` is a wrapper\n * around `withGuard` and grants the same identity affordance (#1006).\n *\n * Omit and `vault.listBehaviors()` falls back to a POSITIONAL\n * `${collection}#${occurrence}` key, which renumbers when another\n * guard on the same collection is registered ahead of this one. Pass\n * a name whenever something joins to the behavior manifest by key —\n * a generated rulebook, a diff between two vault versions, an audit\n * report — so the identifier tracks the rule rather than its\n * registration order.\n */\n readonly name?: string\n /**\n * A record becomes immutable once this predicate holds. Evaluated on\n * the *existing* (already-persisted) record, so the write that first\n * makes it true is still allowed; subsequent writes are blocked.\n * Mutually exclusive with `appendOnly`.\n */\n after?: (record: T) => boolean\n /** Shorthand for `after: () => true` — immutable from creation. */\n appendOnly?: boolean\n /** Roles permitted to override via an amendment transaction. Default `['admin', 'owner']`. */\n amendmentRoles?: ReadonlyArray<'admin' | 'owner'>\n /**\n * Optional set-level invariant run over the amendment change-set after\n * the writes execute. Signature matches `GuardSpec.amendment.invariant`\n * exactly: it receives every {before, after} pair touching this\n * collection in the amendment plus the guard context; throwing reverts\n * the whole amendment and surfaces as `InvariantError`.\n *\n * Use this to keep a constraint inviolable EVEN under amendment — e.g.\n * forbid deleting an issued document by re-throwing on any\n * `before !== null && after === null` change, or assert a cross-record\n * sum is preserved. When omitted the amendment is unconditionally\n * allowed (the amendment itself is the sanctioned, ledgered override) —\n * this is the backward-compatible default.\n */\n amendmentInvariant?: (\n changes: ReadonlyArray<GuardChange<T>>,\n ctx: GuardContext<T>,\n ) => Promise<void> | void\n}\n\nfunction recordId(record: Record<string, unknown> | null): string {\n const id = record?.id\n return typeof id === 'string' ? id : ''\n}\n\n/**\n * Build an immutability guard. Pass the returned handle to\n * `createNoydb({ guardStrategies: [...] })`.\n */\nexport function immutableGuard<T extends Record<string, unknown>>(\n config: ImmutableGuardConfig<T>,\n): GuardStrategy<T> {\n const { collection, name, after, appendOnly, amendmentRoles, amendmentInvariant } = config\n if (appendOnly && after !== undefined) {\n throw new ValidationError('immutableGuard: `after` and `appendOnly` are mutually exclusive')\n }\n if (!appendOnly && after === undefined) {\n throw new ValidationError('immutableGuard: provide `after` or `appendOnly: true`')\n }\n\n const isImmutable: (record: T) => boolean = appendOnly ? () => true : after!\n const reason = appendOnly ? 'append-only collection' : 'record is immutable after issue'\n\n const spec: GuardSpec<T> = {\n collection,\n // Pass-through only — omitting the key entirely (rather than setting\n // it to `undefined`) keeps the positional-fallback path in\n // `buildGuardEntries` reachable for callers who don't name a guard.\n ...(name !== undefined ? { name } : {}),\n // Block updates to an already-immutable record. Inserts (existing\n // null) and the transition write that first makes the record\n // immutable are allowed — `after` reads the prior state.\n check: (incoming: T, ctx: GuardContext<T>) => {\n if (ctx.existing !== null && isImmutable(ctx.existing)) {\n throw new RecordLockedError(collection, recordId(incoming as Record<string, unknown>), reason)\n }\n },\n // Block deletes of an immutable record.\n onDelete: (existing: T) => {\n if (isImmutable(existing)) {\n throw new RecordLockedError(collection, recordId(existing as Record<string, unknown>), reason)\n }\n },\n // The authorized override: inside an amendment transaction the\n // check/onDelete are skipped and the change is ledgered. By default\n // there is no extra invariant — the amendment itself is the\n // sanctioned exception. Callers may supply `amendmentInvariant` to\n // keep a constraint inviolable even under amendment (e.g. forbid\n // deletes, or preserve a cross-record sum); a throw reverts the\n // amendment and surfaces as `InvariantError`.\n amendment: {\n roles: amendmentRoles ?? ['admin', 'owner'],\n invariant: amendmentInvariant ?? (() => {\n /* allow — the amendment is the override, and is ledgered */\n }),\n },\n }\n\n return withGuard<T>(spec)\n}\n","/**\n * `transitionGuard` — declarative state-machine sugar over the guard\n * service.\n *\n * Any record with a lifecycle field (invoice `status`, order state,\n * ticket workflow, subscription phase) needs transition validation: a\n * write may only move the field along a declared arc. That is expressible\n * with a hand-rolled `withGuard({ check })`, but every consumer\n * re-implements the same graph lookup + error. `transitionGuard`\n * generates exactly that guard from a state graph, reusing the guard\n * machinery wholesale — `check` rejection, the ledgered `amendment`\n * override, and composition with `periods`/`history`.\n *\n * It generalizes {@link immutableGuard}: WORM is the special case \"every\n * state has no outgoing arcs\", i.e. `transitions` mapping each state to `[]`.\n *\n * ```ts\n * createNoydb({ guardStrategies: [\n * transitionGuard<Sale>({\n * collection: 'sales', field: 'status',\n * transitions: { // absence of an arc = forbidden\n * draft: ['to_verify', 'cancelled'],\n * to_verify: ['proforma', 'draft', 'cancelled'],\n * proforma: ['invoiced', 'cancelled'],\n * invoiced: ['paid'], paid: [], cancelled: [],\n * },\n * initial: ['draft', 'to_verify'], // allowed status on insert\n * }),\n * ] })\n * ```\n *\n * Semantics:\n * - **Insert** (`ctx.existing === null`): `incoming[field]` must be in\n * `initial`. When `initial` is omitted, any value is allowed on insert.\n * - **Update**: the arc `(existing[field] → incoming[field])` must be\n * listed in `transitions[from]`, else `IllegalTransitionError`. A\n * same-value write (`from === to`) is allowed when `allowIdempotent`\n * (default `true`) — so writes that touch other fields without moving\n * state pass.\n * - **Override**: inside an `amendment` transaction by an authorized role\n * the check is skipped and the change is ledgered (mirrors every guard).\n *\n * The status graph is caller-supplied data — no UI, no domain logic.\n */\n\nimport { withGuard } from './with-guard.js'\nimport type { GuardSpec, GuardStrategy, GuardContext, GuardChange } from './types.js'\nimport { IllegalTransitionError, ValidationError } from '../../kernel/errors.js'\n\nexport interface TransitionGuardConfig<T extends Record<string, unknown>> {\n /** The collection whose state field is governed. */\n collection: string\n /** The state field on the record (e.g. `'status'`). */\n field: keyof T & string\n /**\n * The transition graph: each state maps to the states it may move to.\n * A state absent from the map (or mapped to `[]`) is terminal — no\n * outgoing arc, so any non-idempotent write from it is rejected.\n */\n transitions: Readonly<Record<string, readonly string[]>>\n /**\n * States allowed as the initial value on insert (`existing === null`).\n * Omit to allow any value on insert.\n */\n initial?: readonly string[]\n /**\n * Allow a same-value write (`from === to`) on update. Default `true` —\n * lets a put that changes other fields, but not the state, through.\n */\n allowIdempotent?: boolean\n /** Roles permitted to override via an amendment transaction. Default `['admin', 'owner']`. */\n amendmentRoles?: ReadonlyArray<'admin' | 'owner'>\n /**\n * Optional set-level invariant run over the amendment change-set after\n * the writes execute. Signature matches `GuardSpec.amendment.invariant`\n * exactly. When omitted the amendment is unconditionally allowed (the\n * amendment itself is the sanctioned, ledgered override) — the\n * backward-compatible default. Mirrors {@link immutableGuard}.\n */\n amendmentInvariant?: (\n changes: ReadonlyArray<GuardChange<T>>,\n ctx: GuardContext<T>,\n ) => Promise<void> | void\n}\n\nfunction recordId(record: Record<string, unknown> | null): string {\n const id = record?.id\n return typeof id === 'string' ? id : ''\n}\n\nfunction stateOf(record: Record<string, unknown>, field: string): string {\n const v = record[field]\n return typeof v === 'string' ? v : String(v)\n}\n\n/**\n * Build a state-machine transition guard. Pass the returned handle to\n * `createNoydb({ guardStrategies: [...] })`.\n */\nexport function transitionGuard<T extends Record<string, unknown>>(\n config: TransitionGuardConfig<T>,\n): GuardStrategy<T> {\n const { collection, field, transitions, initial, amendmentRoles, amendmentInvariant } = config\n const allowIdempotent = config.allowIdempotent ?? true\n\n if (!field) {\n throw new ValidationError('transitionGuard: `field` is required')\n }\n if (transitions === undefined || typeof transitions !== 'object') {\n throw new ValidationError('transitionGuard: `transitions` must be a state→states map')\n }\n\n const spec: GuardSpec<T> = {\n collection,\n check: (incoming: T, ctx: GuardContext<T>) => {\n const rec = incoming as Record<string, unknown>\n const to = stateOf(rec, field)\n\n // Insert — gate on the allowed initial set (any value if unset).\n if (ctx.existing === null) {\n if (initial !== undefined && !initial.includes(to)) {\n throw new IllegalTransitionError(collection, recordId(rec), '(none)', to)\n }\n return\n }\n\n // Update — the arc (from → to) must be a declared edge.\n const from = stateOf(ctx.existing as Record<string, unknown>, field)\n if (from === to) {\n if (allowIdempotent) return\n throw new IllegalTransitionError(collection, recordId(rec), from, to)\n }\n const allowed = transitions[from] ?? []\n if (!allowed.includes(to)) {\n throw new IllegalTransitionError(collection, recordId(rec), from, to)\n }\n },\n // The authorized override: inside an amendment transaction the check\n // is skipped and the change is ledgered. By default no extra invariant\n // — the amendment itself is the sanctioned exception. Callers may\n // supply `amendmentInvariant` to keep a constraint inviolable even\n // under amendment; a throw reverts the amendment as `InvariantError`.\n amendment: {\n roles: amendmentRoles ?? ['admin', 'owner'],\n invariant: amendmentInvariant ?? (() => {\n /* allow — the amendment is the override, and is ledgered */\n }),\n },\n }\n\n return withGuard<T>(spec)\n}\n"],"mappings":";;;;;;;AAgBO,SAAS,UACd,UACkB;AAClB,MAAI,CAAC,SAAS,cAAc,SAAS,WAAW,WAAW,GAAG;AAC5D,UAAM,IAAI,gBAAgB,wCAAwC;AAAA,EACpE;AACA,SAAO;AAAA,IACL,kBAAkB;AAAA,IAClB,MAAM;AAAA,EACR;AACF;;;ACsDA,SAAS,SAAS,QAAgD;AAChE,QAAM,KAAK,QAAQ;AACnB,SAAO,OAAO,OAAO,WAAW,KAAK;AACvC;AAMO,SAAS,eACd,QACkB;AAClB,QAAM,EAAE,YAAY,MAAM,OAAO,YAAY,gBAAgB,mBAAmB,IAAI;AACpF,MAAI,cAAc,UAAU,QAAW;AACrC,UAAM,IAAI,gBAAgB,iEAAiE;AAAA,EAC7F;AACA,MAAI,CAAC,cAAc,UAAU,QAAW;AACtC,UAAM,IAAI,gBAAgB,uDAAuD;AAAA,EACnF;AAEA,QAAM,cAAsC,aAAa,MAAM,OAAO;AACt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CAAC,UAAa,QAAyB;AAC5C,YAAM,MAAM;AACZ,YAAM,KAAK,QAAQ,KAAK,KAAK;AAG7B,UAAI,IAAI,aAAa,MAAM;AACzB,YAAI,YAAY,UAAa,CAAC,QAAQ,SAAS,EAAE,GAAG;AAClD,gBAAM,IAAI,uBAAuB,YAAYA,UAAS,GAAG,GAAG,UAAU,EAAE;AAAA,QAC1E;AACA;AAAA,MACF;AAGA,YAAM,OAAO,QAAQ,IAAI,UAAqC,KAAK;AACnE,UAAI,SAAS,IAAI;AACf,YAAI,gBAAiB;AACrB,cAAM,IAAI,uBAAuB,YAAYA,UAAS,GAAG,GAAG,MAAM,EAAE;AAAA,MACtE;AACA,YAAM,UAAU,YAAY,IAAI,KAAK,CAAC;AACtC,UAAI,CAAC,QAAQ,SAAS,EAAE,GAAG;AACzB,cAAM,IAAI,uBAAuB,YAAYA,UAAS,GAAG,GAAG,MAAM,EAAE;AAAA,MACtE;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMA,WAAW;AAAA,MACT,OAAO,kBAAkB,CAAC,SAAS,OAAO;AAAA,MAC1C,WAAW,uBAAuB,MAAM;AAAA,MAExC;AAAA,IACF;AAAA,EACF;AAEA,SAAO,UAAa,IAAI;AAC1B;","names":["recordId"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
loadVaultPolicy,
|
|
3
3
|
saveVaultPolicy
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-3ENNPCIW.js";
|
|
5
5
|
import {
|
|
6
6
|
PolicyDeniedError,
|
|
7
7
|
ValidationError
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-CWM4GQD2.js";
|
|
9
9
|
|
|
10
10
|
// src/with-party/policy/presets.ts
|
|
11
11
|
var PERSONAL_POLICY = Object.freeze({
|
|
@@ -364,4 +364,4 @@ export {
|
|
|
364
364
|
describeGate,
|
|
365
365
|
createNoydbPolicy
|
|
366
366
|
};
|
|
367
|
-
//# sourceMappingURL=chunk-
|
|
367
|
+
//# sourceMappingURL=chunk-TX5MKAHA.js.map
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import {
|
|
2
|
+
buildRecordAad,
|
|
2
3
|
openEnvelopeJson
|
|
3
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-OHOKBMTM.js";
|
|
5
|
+
import {
|
|
6
|
+
buildRecordEnvelope
|
|
7
|
+
} from "./chunk-PENPHA45.js";
|
|
4
8
|
import {
|
|
5
9
|
encrypt,
|
|
6
10
|
hmacSha256Hex,
|
|
7
11
|
sha256Hex
|
|
8
|
-
} from "./chunk-
|
|
9
|
-
import {
|
|
10
|
-
NOYDB_FORMAT_VERSION
|
|
11
|
-
} from "./chunk-W5W6KHN2.js";
|
|
12
|
+
} from "./chunk-AU3AUJIZ.js";
|
|
12
13
|
|
|
13
14
|
// src/with-audit/forget/strategy.ts
|
|
14
15
|
var NO_FORGET = { subjects: {} };
|
|
@@ -43,17 +44,18 @@ async function readRefs(adapter, vault, getDEK, encrypted, key) {
|
|
|
43
44
|
if (!env || !env._data) return [];
|
|
44
45
|
if (!encrypted) return parseRefs(env._data);
|
|
45
46
|
const dek = await getDEK(SUBJECT_INDEX_COLLECTION);
|
|
46
|
-
const json = await openEnvelopeJson(env, dek);
|
|
47
|
+
const json = await openEnvelopeJson({ collection: SUBJECT_INDEX_COLLECTION, id: key }, env, dek);
|
|
47
48
|
return parseRefs(json);
|
|
48
49
|
}
|
|
49
50
|
async function writeRefs(adapter, vault, getDEK, encrypted, key, refs) {
|
|
51
|
+
const identity = { collection: SUBJECT_INDEX_COLLECTION, id: key, version: 1 };
|
|
50
52
|
let env;
|
|
51
53
|
if (!encrypted) {
|
|
52
|
-
env =
|
|
54
|
+
env = buildRecordEnvelope(identity, { iv: "", data: JSON.stringify(refs) });
|
|
53
55
|
} else {
|
|
54
56
|
const dek = await getDEK(SUBJECT_INDEX_COLLECTION);
|
|
55
|
-
const { iv, data } = await encrypt(serializeRefs(refs), dek);
|
|
56
|
-
env =
|
|
57
|
+
const { iv, data } = await encrypt(serializeRefs(refs), dek, buildRecordAad(identity));
|
|
58
|
+
env = buildRecordEnvelope(identity, { iv, data });
|
|
57
59
|
}
|
|
58
60
|
await adapter.put(vault, SUBJECT_INDEX_COLLECTION, key, env);
|
|
59
61
|
}
|
|
@@ -147,4 +149,4 @@ export {
|
|
|
147
149
|
coerceSubjectId,
|
|
148
150
|
readDottedPath
|
|
149
151
|
};
|
|
150
|
-
//# sourceMappingURL=chunk-
|
|
152
|
+
//# sourceMappingURL=chunk-U27Y4DJZ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/with-audit/forget/strategy.ts","../src/with-audit/forget/subject-index.ts"],"sourcesContent":["/**\n * `withForget` — declaration surface for GDPR right-to-erasure via\n * per-record CEK crypto-shred.\n *\n * This file holds only the *declaration* shape and the disabled sentinel.\n * The actual erasure machinery lives in:\n * - `subject-index.ts` — the encrypted `_subject_index` reserved collection\n * - `vault.ts` `forget()` — the per-record tombstone + ledger flow\n * - `collection.ts` `_writeTombstone` — the envelope rewrite\n *\n * A `ForgetStrategy` declares which collections carry erasable subject data\n * and the (dotted-path) field on each record that names the data subject.\n * Declaring a collection here ALSO forces `perRecordKeys: true` for it (a\n * shred can only erase a record whose body is keyed off a per-record CEK),\n * so adopters opt into the CEK foundation transitively.\n *\n * @module\n */\nimport type { LedgerEntry } from '../../with-commit/history/ledger/entry.js'\n\n/**\n * User-supplied declaration passed to {@link withForget}. Maps a\n * collection name to the record field (dotted path supported, e.g.\n * `'billing.buyerId'`) that identifies the data subject for erasure.\n *\n * ```ts\n * withForget({ subjects: { invoices: 'buyerId', contacts: 'id' } })\n * ```\n */\nexport interface SubjectDeclaration {\n readonly subjects: Record<string, string>\n /**\n * #633 — opt-in: gate the vault-level `_sealed_cek` and blob purges on\n * per-collection via declarations instead of running them unconditionally\n * for every forgotten ref. Default `false`/absent = today's unconditional\n * behavior (byte-identical). See `purge-scope.ts` for the partition logic\n * and the `scopedPurgeResidue` skip-reporting this enables.\n *\n * **Footgun:** a bare `sensitive: [...]` collection — no `classifiedFields`\n * (no classified via binder compiled in) — counts as UNDECLARED for the\n * sealed-CEK arm. Under `scopedPurge: true`, its `_sealed_cek` host-delivery\n * envelopes are SKIPPED, not purged (reported via `scopedPurgeResidue`,\n * reason `'skipped-undeclared-sealed-cek'`) even if that collection called\n * `sealRecordToHost()` — the sealed CEK stays recoverable by that granted\n * host until purged. Add a `classifiedFields` binding to close the gap, or\n * leave `scopedPurge` off/false for the unconditional (always-purged) default.\n * The declaration signal is session-local: a declared collection never opened\n * (with its config) before `forget()` in this session counts as UNDECLARED —\n * open it first, or its entries are skipped-and-reported.\n */\n readonly scopedPurge?: boolean\n}\n\n/**\n * Resolved forget strategy threaded through Noydb → every Vault. Carries\n * the same `subjects` map the user declared. `NO_FORGET` (empty map) is the\n * off-by-default sentinel; `vault.forget()` throws\n * `ForgetStrategyNotConfiguredError` when the map is empty.\n */\nexport interface ForgetStrategy {\n /** Collection → subject-field (dotted path). Empty under `NO_FORGET`. */\n readonly subjects: Readonly<Record<string, string>>\n /** #633 — see {@link SubjectDeclaration.scopedPurge}. */\n readonly scopedPurge?: boolean\n}\n\n/**\n * Disabled sentinel — no collections declare a subject field. `vault.forget()`\n * refuses with `ForgetStrategyNotConfiguredError`; no write hooks register; no\n * collection is forced into `perRecordKeys`. Non-adopters pay nothing.\n */\nexport const NO_FORGET: ForgetStrategy = { subjects: {} }\n\n// The `withForget` factory lives in `active.ts` (canonical\n// strategy.ts/active.ts/index.ts split); this file holds only the\n// declaration shape + disabled sentinel.\n\n/**\n * The outcome of a `vault.forget(subjectId)` call.\n *\n * `unmigratedRecords` lists `collection:id` pairs that were tombstoned but\n * whose body had NOT been migrated to a per-record CEK at shred time (legacy\n * body still under the shared collection DEK). Those records are tombstoned\n * (live envelope + history stripped) but their pre-shred ciphertext, if it\n * leaked into a backup before migration, remains decryptable under the\n * collection DEK — so erasure-completeness is NOT guaranteed for them. Run\n * the per-record-CEK migration pass, then re-forget, to close the gap.\n *\n * Blob attachments: a shredded record's **erasable** blobs (on a\n * `perRecordKeys` collection) are crypto-shredded inline — `blobsShredded`\n * counts those taken to refCount 0 (BlobObject deleted → chunks permanently\n * undecryptable), `blobsRetainedShared` counts those still referenced by\n * another record (shared content legitimately persists for its other owner).\n * `blobResidueCollections` now lists only collections with blobs that could\n * NOT be crypto-shredded: **legacy** blobs (no per-blob `_cek`, chunks under\n * the shared `_blob` DEK — migrate them), or a session without the blob\n * service loaded. An all-erasable subject yields an empty residue list.\n */\nexport interface ForgetResult {\n /** The subject id passed to `forget()`. Echoed for caller convenience. */\n readonly subject: string\n /** Count of live records rewritten to a tombstone. */\n readonly recordsShredded: number\n /** Count of `_history` envelopes tombstoned across all shredded records. */\n readonly historyVersionsShredded: number\n /** Distinct collections that had at least one record shredded. */\n readonly collections: readonly string[]\n /** `collection:id` pairs shredded while still un-migrated (see type docs). */\n readonly unmigratedRecords: readonly string[]\n /** Count of erasable blobs crypto-shredded (refCount → 0, BlobObject deleted). */\n readonly blobsShredded: number\n /** Count of erasable blobs retained because still referenced elsewhere (shared). */\n readonly blobsRetainedShared: number\n /** Collections with blobs that could NOT be crypto-shredded — legacy (no `_cek`) or blobs disabled (see type docs). */\n readonly blobResidueCollections: readonly string[]\n /**\n * Count of persisted `_idx/<field>/<recordId>` index side-cars hard-deleted\n * across the shredded records. These live under the retained\n * collection DEK, so crypto-shred alone would leave the indexed field VALUES\n * readable — `forget()` must delete them.\n */\n readonly indexPostingsPurged: number\n /**\n * `collection:id:field` entries whose persisted `_idx` side-car could NOT be\n * deleted — index residue that still leaks the indexed value under the\n * retained collection DEK. Non-empty means erasure is INCOMPLETE: retry, or\n * purge the side-car out of band.\n */\n readonly indexResidue: readonly string[]\n /**\n * Count of `_sealed[field]` slots dropped from the live store across the\n * shredded records. For slots written under `sensitive` +\n * `perRecordKeys` (the current path), the key derives off the per-record CEK,\n * so tombstoning the record — which drops `_cek` and `_sealed` — also\n * crypto-shreds the value. A legacy slot (written before per-record CEKs) keys\n * off the collection DEK instead, so dropping it removes it from the live store but a\n * pre-forget backup remains recoverable by a DEK holder (same caveat `_data`\n * carries); migrate by re-`put`ting before forgetting for full crypto-shred.\n */\n readonly sealedFieldsShredded: number\n /** Count of `_sealed_cek` host-delivery envelopes deleted (#H-1). A record sealed to an\n * at-* host via sealRecordToHost persists its raw CEK there; forget() must destroy them. */\n readonly sealedCekEnvelopesPurged: number\n /** `collection:id` whose `_sealed_cek` purge failed (residue — the host-recoverable CEK may survive). */\n readonly sealedCekResidue: readonly string[]\n /** `collection:id:field` sealed slots that were DEK-derived (legacy, written before per-record CEKs) and thus NOT crypto-shredded\n * by dropping `_cek` — the collection DEK is retained, so synced/backup copies stay decryptable (#M-1). */\n readonly sealedResidue: readonly string[]\n /** Count of `_ledger_deltas` rows hard-deleted across the shredded records (#734) — the\n * erasure twin of #729's elevate-side purge. Entry metadata (that the record was mutated,\n * at which version/timestamp/actor) is retained; only the plaintext delta content is removed. */\n readonly ledgerDeltasPurged: number\n /** `collection:id` refs whose `_ledger_deltas` purge failed — plaintext delta residue still\n * readable under the retained ledger DEK. Non-empty means erasure is INCOMPLETE. */\n readonly ledgerDeltaResidue: readonly string[]\n /** The single `op:'forget'` ledger entry appended for this erasure. */\n readonly ledgerEntry: LedgerEntry\n /** #622 — record-grain derived artifacts (MV rows, per-record derived copies) erased\n * because their source subject was forgotten. Overlay outputs are intentionally out of\n * scope here — an overlay is always sourced from an MV, never directly from a subject\n * collection, so the personal-data-bearing MV rows it reads are already erased above. */\n readonly derivedRecordsErased: number\n /** #622 — aggregate-grain targets (rollups) recomputed without the forgotten contribution. */\n readonly derivedAggregatesRecomputed: number\n /** #622 — `collection:id` derived writes SKIPPED because the target period is frozen\n * (recompute deferred; the aggregate retains the forgotten contribution — audited). */\n readonly derivedResidueFrozen: readonly string[]\n /** #650 Task 5 (#648) — referencing records tombstoned via a `'ref'` edge's `cascade` policy. */\n readonly lookupReferencesCascaded: number\n /** #650 Task 5 (#648) — referencing fields cleared via a `'ref'` edge's `nullify` policy. */\n readonly lookupReferencesNullified: number\n /** #650 Task 5 review (Important fix) — `'ref'` edges whose compare-key could NOT be resolved,\n * even from the LIVE pre-shred backing row — cascade/nullify propagation was SKIPPED for these.\n * Always empty in the ordinary case; non-empty means the skip is reported, never silent. */\n readonly lookupReferencesResidue: readonly string[]\n /** #633 — scoped-purge skip notices (opt-in `scopedPurge`, see {@link SubjectDeclaration}).\n * Always empty under the unconditional default. Non-empty means a `_sealed_cek` entry or a\n * blob scan was skipped for an undeclared collection — reported, never a silent skip. */\n readonly scopedPurgeResidue: readonly ScopedPurgeResidueNotice[]\n /** #776/#782/#785 — `collection:id` MV-output rows that survived erasure invalidation (eager\n * tombstone leg AND lazy/manual `invalidateMVAtRest`) despite belonging to the forgotten\n * subject, because the `_materializedFrom` ownership stamp could NOT be decoded (undecodable\n * under the collection's default DEK — e.g. elevated above tier 0 on a tiered output\n * collection; ownership unconfirmed — could be a plain user record on a same-collection\n * partition MV). Never erased, but surfaced here rather than silently skipped (the #724\n * posture). Non-empty means the row may still hold the forgotten/pre-elevation contribution,\n * decryptable by tier-holders. */\n readonly derivedResidueUndecodable: readonly string[]\n /** #782/#785 — `collection:id` MV-output rows that DID decode and stamp-match via\n * `_materializedFrom`, but whose erasure was declined by the #718 tier-elevation gate\n * (`_internalDelete` returned false). Ownership CONFIRMED here — a real silent survival,\n * not a stamp-mismatch skip — surfaced rather than dropped. Non-empty means a live,\n * tier-holder-decryptable copy of the forgotten contribution was deliberately retained. */\n readonly derivedResidueDeclined: readonly string[]\n}\n\n/** #633 — the two `scopedPurgeResidue` skip reasons. Single source of truth: `purge-scope.ts`\n * (the port-internal partition helpers) imports this rather than redeclaring it. */\nexport type ScopedPurgeResidueReason = 'skipped-undeclared-sealed-cek' | 'skipped-undeclared-blob-scan'\n\n/** #633 — one `ForgetResult.scopedPurgeResidue` entry: an undeclared collection's sealed-CEK\n * entries left unpurged, or its blob scan skipped entirely, under `scopedPurge`. `count` is the\n * number of `_sealed_cek` entries left in place (sealed-cek reason) or the number of refs whose\n * blob scan was skipped (blob-scan reason) — aggregated per collection across the whole call. */\nexport interface ScopedPurgeResidueNotice {\n readonly reason: ScopedPurgeResidueReason\n readonly collection: string\n readonly count: number\n}\n","/**\n * The encrypted subject index.\n *\n * GDPR crypto-shred needs to answer \"which records belong to data subject\n * X?\" portably (the index must travel with the vault/bundle) WITHOUT leaking\n * subject-equivalence to the store. The rejected alternative — an unencrypted\n * subject tag in envelope metadata — would let anyone with store access see\n * which records share a subject. Instead we keep a reserved `_subject_index`\n * collection, encrypted under its OWN DEK (`getDEK('_subject_index')`):\n *\n * - record id = `HMAC-SHA256(indexDEK, subjectId)` (M-2). A bare\n * `sha256Hex(subjectId)` would be offline-computable: an attacker with\n * store access and a candidate list (emails / customer ids are low-entropy)\n * could dictionary the hash to confirm \"subject X is present here.\" Keying\n * the id with the vault-only index DEK removes that capability — without the\n * DEK the id cannot be derived. (Legacy entries written before M-2 used the\n * bare sha256 id; the read/remove paths dual-look-up both forms.)\n * - record body = AES-GCM(JSON `{ r: [{ collection, id }], p }`) under the\n * index DEK, where `p` pads the plaintext to a bucketed length so the\n * ciphertext `_data` length does not leak the approximate record count.\n * Legacy bodies were a bare `[{ collection, id }]` array; reads accept both.\n *\n * ## Concurrency (RISK #3 — known v1 limitation)\n *\n * `addSubjectRef` / `removeSubjectRef` are read-modify-write with no CAS. The\n * design assumes a SINGLE WRITER (the noy-db single-process write model). Two\n * concurrent writers racing on the SAME subject can lose an entry (last-write\n * wins on the ref list). This is documented, not fixed in v1:\n * `rebuildSubjectIndex` performs a full scan to recover a correct index from\n * the canonical records, so a lost ref is recoverable. A CAS-backed index is\n * deferred to a later slice.\n *\n * @module\n */\nimport { encrypt, openEnvelopeJson, hmacSha256Hex, sha256Hex, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport { NOYDB_FORMAT_VERSION } from '../../kernel/types.js'\n\n/** Reserved collection holding the encrypted subject → records index. */\nexport const SUBJECT_INDEX_COLLECTION = '_subject_index'\n\n/**\n * Bucket (bytes) the encrypted ref-list plaintext is padded up to, so the\n * ciphertext `_data` length leaks only `count` rounded up to a bucket — not the\n * exact record count. 256 keeps small subjects (the common case) indistinguishable.\n */\nconst REF_LIST_BUCKET = 256\n\n/** A single record reference held in a subject's index entry. */\nexport interface SubjectRef {\n readonly collection: string\n readonly id: string\n}\n\ntype GetDEK = (collectionName: string) => Promise<EnclaveKey>\n\n/** SHA-256 hex of a UTF-8 string. The LEGACY (pre-M-2) subject-index key. */\nasync function sha256HexString(input: string): Promise<string> {\n return sha256Hex(new TextEncoder().encode(input))\n}\n\n/**\n * The subject-index record id(s) to consult for a subject, most-current first.\n *\n * - Encrypted vault: the PRIMARY id is `HMAC-SHA256(indexDEK, subjectId)` (M-2)\n * — not offline-computable. The LEGACY `sha256Hex(subjectId)` id is also\n * returned so reads/removes still find entries written before M-2 (dual-lookup).\n * - Plaintext/debug vault: no DEK to key with, so the only id is the legacy\n * sha256 form (unchanged behaviour — plaintext mode is not zero-knowledge anyway).\n */\nasync function subjectKeys(getDEK: GetDEK, encrypted: boolean, subjectId: string): Promise<string[]> {\n const legacy = await sha256HexString(subjectId)\n if (!encrypted) return [legacy]\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const keyed = await hmacSha256Hex(dek, new TextEncoder().encode(subjectId))\n return keyed === legacy ? [keyed] : [keyed, legacy]\n}\n\n/** The id new writes land under (keyed when encrypted, else legacy sha256). */\nasync function primarySubjectKey(getDEK: GetDEK, encrypted: boolean, subjectId: string): Promise<string> {\n return (await subjectKeys(getDEK, encrypted, subjectId))[0]!\n}\n\n/** Parse a stored ref-list body: new padded `{ r, p }` wrapper OR legacy bare array. */\nfunction parseRefs(json: string): SubjectRef[] {\n const parsed = JSON.parse(json) as SubjectRef[] | { r: SubjectRef[] }\n return Array.isArray(parsed) ? parsed : parsed.r\n}\n\n/** Serialize + pad the ref list to a bucket boundary (encrypted vaults only). */\nfunction serializeRefs(refs: SubjectRef[]): string {\n const base = JSON.stringify({ r: refs, p: '' })\n const pad = Math.ceil(base.length / REF_LIST_BUCKET) * REF_LIST_BUCKET - base.length\n return JSON.stringify({ r: refs, p: ' '.repeat(pad) })\n}\n\n/** Read + decrypt the ref list at a SINGLE index key. Returns `[]` when absent. */\nasync function readRefs(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n key: string,\n): Promise<SubjectRef[]> {\n const env = await adapter.get(vault, SUBJECT_INDEX_COLLECTION, key)\n if (!env || !env._data) return []\n if (!encrypted) return parseRefs(env._data)\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const json = await openEnvelopeJson(env, dek)\n return parseRefs(json)\n}\n\n/** Encrypt + write a ref list for a subject under its derived key. */\nasync function writeRefs(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n key: string,\n refs: SubjectRef[],\n): Promise<void> {\n let env: EncryptedEnvelope\n if (!encrypted) {\n // Plaintext/debug vault: keep the legacy bare-array form (no padding needed).\n env = { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: new Date().toISOString(), _iv: '', _data: JSON.stringify(refs) }\n } else {\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const { iv, data } = await encrypt(serializeRefs(refs), dek)\n env = { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: new Date().toISOString(), _iv: iv, _data: data }\n }\n await adapter.put(vault, SUBJECT_INDEX_COLLECTION, key, env)\n}\n\n/**\n * Add a `{ collection, id }` ref to a subject's index entry (idempotent —\n * a duplicate ref is not appended). Read-modify-write; see the concurrency\n * note in the module docstring.\n */\nexport async function addSubjectRef(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n ref: SubjectRef,\n): Promise<void> {\n const key = await primarySubjectKey(getDEK, encrypted, subjectId)\n const refs = await readRefs(adapter, vault, getDEK, encrypted, key)\n if (refs.some((r) => r.collection === ref.collection && r.id === ref.id)) return\n refs.push(ref)\n await writeRefs(adapter, vault, getDEK, encrypted, key, refs)\n}\n\n/**\n * Remove a `{ collection, id }` ref from a subject's index entry. When the\n * last ref is removed the (now empty) entry is deleted so the store holds no\n * residual key for an erased subject.\n */\nexport async function removeSubjectRef(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n ref: SubjectRef,\n): Promise<void> {\n // Dual-lookup: drop the ref from BOTH the keyed (M-2) and the legacy sha256\n // entry, so a pre-M-2 subject is still fully erased.\n for (const key of await subjectKeys(getDEK, encrypted, subjectId)) {\n const refs = await readRefs(adapter, vault, getDEK, encrypted, key)\n const next = refs.filter((r) => !(r.collection === ref.collection && r.id === ref.id))\n if (next.length === refs.length) continue\n if (next.length === 0) {\n await adapter.delete(vault, SUBJECT_INDEX_COLLECTION, key)\n } else {\n await writeRefs(adapter, vault, getDEK, encrypted, key, next)\n }\n }\n}\n\n/**\n * Look up every record ref for a subject. Returns `[]` when none exist. Unions\n * the keyed (M-2) and legacy sha256 entries (dual-lookup), deduplicated, so a\n * subject indexed before M-2 is still fully found.\n */\nexport async function lookupSubject(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n): Promise<SubjectRef[]> {\n const keys = await subjectKeys(getDEK, encrypted, subjectId)\n const seen = new Set<string>()\n const out: SubjectRef[] = []\n for (const key of keys) {\n for (const ref of await readRefs(adapter, vault, getDEK, encrypted, key)) {\n const dedup = `${ref.collection}\\u0000${ref.id}`\n if (seen.has(dedup)) continue\n seen.add(dedup)\n out.push(ref)\n }\n }\n return out\n}\n\n/**\n * Rebuild the entire subject index from the canonical records (the recovery\n * path for the documented read-modify-write race). Scans each declared\n * collection, reads `record[subjectField]` (dotted path), and rewrites the\n * index from scratch. Tombstoned (already-shredded) records contribute no\n * ref — their body is gone, so they cannot be re-indexed.\n *\n * `decodeRecord` decrypts an envelope to a plain object (or returns null for\n * a tombstone / unreadable record); supplied by the caller so this module\n * stays free of Collection internals.\n */\nexport async function rebuildSubjectIndex(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjects: Readonly<Record<string, string>>,\n decodeRecord: (collection: string, id: string, env: EncryptedEnvelope) => Promise<Record<string, unknown> | null>,\n): Promise<number> {\n // Drop every existing index entry first so removed refs don't linger.\n const existing = await adapter.list(vault, SUBJECT_INDEX_COLLECTION)\n for (const k of existing) {\n await adapter.delete(vault, SUBJECT_INDEX_COLLECTION, k)\n }\n\n // subjectId → refs, accumulated across all declared collections.\n const bySubject = new Map<string, SubjectRef[]>()\n for (const [collection, field] of Object.entries(subjects)) {\n const ids = await adapter.list(vault, collection)\n for (const id of ids) {\n if (id.startsWith('_')) continue\n const env = await adapter.get(vault, collection, id)\n if (!env || !env._data) continue // missing or tombstone\n const record = await decodeRecord(collection, id, env)\n if (record === null) continue\n const subjectValue = readDottedPath(record, field)\n if (subjectValue === undefined || subjectValue === null) continue\n const subjectId = coerceSubjectId(subjectValue)\n const list = bySubject.get(subjectId) ?? []\n list.push({ collection, id })\n bySubject.set(subjectId, list)\n }\n }\n\n let entries = 0\n for (const [subjectId, refs] of bySubject) {\n const key = await primarySubjectKey(getDEK, encrypted, subjectId)\n await writeRefs(adapter, vault, getDEK, encrypted, key, refs)\n entries++\n }\n return entries\n}\n\n/**\n * Coerce a read subject-field value to a stable string id. Primitives use\n * their natural string form; objects/arrays are JSON-stringified so structural\n * subjects still get a deterministic key (avoids the `[object Object]` trap).\n */\nexport function coerceSubjectId(value: unknown): string {\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n return String(value)\n }\n return JSON.stringify(value)\n}\n\n/** Read a (possibly dotted) field path from a plain record. */\nexport function readDottedPath(record: Record<string, unknown>, field: string): unknown {\n if (!field.includes('.')) return record[field]\n let cursor: unknown = record\n for (const segment of field.split('.')) {\n if (cursor === null || cursor === undefined) return undefined\n cursor = (cursor as Record<string, unknown>)[segment]\n }\n return cursor\n}\n"],"mappings":";;;;;;;;;;;;;AAuEO,IAAM,YAA4B,EAAE,UAAU,CAAC,EAAE;;;AChCjD,IAAM,2BAA2B;AAOxC,IAAM,kBAAkB;AAWxB,eAAe,gBAAgB,OAAgC;AAC7D,SAAO,UAAU,IAAI,YAAY,EAAE,OAAO,KAAK,CAAC;AAClD;AAWA,eAAe,YAAY,QAAgB,WAAoB,WAAsC;AACnG,QAAM,SAAS,MAAM,gBAAgB,SAAS;AAC9C,MAAI,CAAC,UAAW,QAAO,CAAC,MAAM;AAC9B,QAAM,MAAM,MAAM,OAAO,wBAAwB;AACjD,QAAM,QAAQ,MAAM,cAAc,KAAK,IAAI,YAAY,EAAE,OAAO,SAAS,CAAC;AAC1E,SAAO,UAAU,SAAS,CAAC,KAAK,IAAI,CAAC,OAAO,MAAM;AACpD;AAGA,eAAe,kBAAkB,QAAgB,WAAoB,WAAoC;AACvG,UAAQ,MAAM,YAAY,QAAQ,WAAW,SAAS,GAAG,CAAC;AAC5D;AAGA,SAAS,UAAU,MAA4B;AAC7C,QAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,SAAO,MAAM,QAAQ,MAAM,IAAI,SAAS,OAAO;AACjD;AAGA,SAAS,cAAc,MAA4B;AACjD,QAAM,OAAO,KAAK,UAAU,EAAE,GAAG,MAAM,GAAG,GAAG,CAAC;AAC9C,QAAM,MAAM,KAAK,KAAK,KAAK,SAAS,eAAe,IAAI,kBAAkB,KAAK;AAC9E,SAAO,KAAK,UAAU,EAAE,GAAG,MAAM,GAAG,IAAI,OAAO,GAAG,EAAE,CAAC;AACvD;AAGA,eAAe,SACb,SACA,OACA,QACA,WACA,KACuB;AACvB,QAAM,MAAM,MAAM,QAAQ,IAAI,OAAO,0BAA0B,GAAG;AAClE,M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S,MAAM,aAAa,YAAY,IAAI,GAAG;AACrD,UAAI,WAAW,KAAM;AACrB,YAAM,eAAe,eAAe,QAAQ,KAAK;AACjD,UAAI,iBAAiB,UAAa,iBAAiB,KAAM;AACzD,YAAM,YAAY,gBAAgB,YAAY;AAC9C,YAAM,OAAO,UAAU,IAAI,SAAS,KAAK,CAAC;AAC1C,WAAK,KAAK,EAAE,YAAY,GAAG,CAAC;AAC5B,gBAAU,IAAI,WAAW,IAAI;AAAA,IAC/B;AAAA,EACF;AAEA,MAAI,UAAU;AACd,aAAW,CAAC,WAAW,IAAI,KAAK,WAAW;AACzC,UAAM,MAAM,MAAM,kBAAkB,QAAQ,WAAW,SAAS;AAChE,UAAM,UAAU,SAAS,OAAO,QAAQ,WAAW,KAAK,IAAI;AAC5D;AAAA,EACF;AACA,SAAO;AACT;AAOO,SAAS,gBAAgB,OAAwB;AACtD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,OAAO,UAAU,YAAY,OAAO,UAAU,aAAa,OAAO,UAAU,UAAU;AACxF,WAAO,OAAO,KAAK;AAAA,EACrB;AACA,SAAO,KAAK,UAAU,KAAK;AAC7B;AAGO,SAAS,eAAe,QAAiC,OAAwB;AACtF,MAAI,CAAC,MAAM,SAAS,GAAG,EAAG,QAAO,OAAO,KAAK;AAC7C,MAAI,SAAkB;AACtB,aAAW,WAAW,MAAM,MAAM,GAAG,GAAG;AACtC,QAAI,WAAW,QAAQ,WAAW,OAAW,QAAO;AACpD,aAAU,OAAmC,OAAO;AAAA,EACtD;AACA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/with-audit/forget/strategy.ts","../src/with-audit/forget/subject-index.ts"],"sourcesContent":["/**\n * `withForget` — declaration surface for GDPR right-to-erasure via\n * per-record CEK crypto-shred.\n *\n * This file holds only the *declaration* shape and the disabled sentinel.\n * The actual erasure machinery lives in:\n * - `subject-index.ts` — the encrypted `_subject_index` reserved collection\n * - `vault.ts` `forget()` — the per-record tombstone + ledger flow\n * - `collection.ts` `_writeTombstone` — the envelope rewrite\n *\n * A `ForgetStrategy` declares which collections carry erasable subject data\n * and the (dotted-path) field on each record that names the data subject.\n * Declaring a collection here ALSO forces `perRecordKeys: true` for it (a\n * shred can only erase a record whose body is keyed off a per-record CEK),\n * so adopters opt into the CEK foundation transitively.\n *\n * @module\n */\nimport type { LedgerEntry } from '../../with-commit/history/ledger/entry.js'\n\n/**\n * User-supplied declaration passed to {@link withForget}. Maps a\n * collection name to the record field (dotted path supported, e.g.\n * `'billing.buyerId'`) that identifies the data subject for erasure.\n *\n * ```ts\n * withForget({ subjects: { invoices: 'buyerId', contacts: 'id' } })\n * ```\n */\nexport interface SubjectDeclaration {\n readonly subjects: Record<string, string>\n /**\n * #633 — opt-in: gate the vault-level `_sealed_cek` and blob purges on\n * per-collection via declarations instead of running them unconditionally\n * for every forgotten ref. Default `false`/absent = today's unconditional\n * behavior (byte-identical). See `purge-scope.ts` for the partition logic\n * and the `scopedPurgeResidue` skip-reporting this enables.\n *\n * **Footgun:** a bare `sensitive: [...]` collection — no `classifiedFields`\n * (no classified via binder compiled in) — counts as UNDECLARED for the\n * sealed-CEK arm. Under `scopedPurge: true`, its `_sealed_cek` host-delivery\n * envelopes are SKIPPED, not purged (reported via `scopedPurgeResidue`,\n * reason `'skipped-undeclared-sealed-cek'`) even if that collection called\n * `sealRecordToHost()` — the sealed CEK stays recoverable by that granted\n * host until purged. Add a `classifiedFields` binding to close the gap, or\n * leave `scopedPurge` off/false for the unconditional (always-purged) default.\n * The declaration signal is session-local: a declared collection never opened\n * (with its config) before `forget()` in this session counts as UNDECLARED —\n * open it first, or its entries are skipped-and-reported.\n */\n readonly scopedPurge?: boolean\n}\n\n/**\n * Resolved forget strategy threaded through Noydb → every Vault. Carries\n * the same `subjects` map the user declared. `NO_FORGET` (empty map) is the\n * off-by-default sentinel; `vault.forget()` throws\n * `ForgetStrategyNotConfiguredError` when the map is empty.\n */\nexport interface ForgetStrategy {\n /** Collection → subject-field (dotted path). Empty under `NO_FORGET`. */\n readonly subjects: Readonly<Record<string, string>>\n /** #633 — see {@link SubjectDeclaration.scopedPurge}. */\n readonly scopedPurge?: boolean\n}\n\n/**\n * Disabled sentinel — no collections declare a subject field. `vault.forget()`\n * refuses with `ForgetStrategyNotConfiguredError`; no write hooks register; no\n * collection is forced into `perRecordKeys`. Non-adopters pay nothing.\n */\nexport const NO_FORGET: ForgetStrategy = { subjects: {} }\n\n// The `withForget` factory lives in `active.ts` (canonical\n// strategy.ts/active.ts/index.ts split); this file holds only the\n// declaration shape + disabled sentinel.\n\n/**\n * The outcome of a `vault.forget(subjectId)` call.\n *\n * `unmigratedRecords` lists `collection:id` pairs that were tombstoned but\n * whose body had NOT been migrated to a per-record CEK at shred time (legacy\n * body still under the shared collection DEK). Those records are tombstoned\n * (live envelope + history stripped) but their pre-shred ciphertext, if it\n * leaked into a backup before migration, remains decryptable under the\n * collection DEK — so erasure-completeness is NOT guaranteed for them. Run\n * the per-record-CEK migration pass, then re-forget, to close the gap.\n *\n * Blob attachments: a shredded record's **erasable** blobs (on a\n * `perRecordKeys` collection) are crypto-shredded inline — `blobsShredded`\n * counts those taken to refCount 0 (BlobObject deleted → chunks permanently\n * undecryptable), `blobsRetainedShared` counts those still referenced by\n * another record (shared content legitimately persists for its other owner).\n * `blobResidueCollections` now lists only collections with blobs that could\n * NOT be crypto-shredded: **legacy** blobs (no per-blob `_cek`, chunks under\n * the shared `_blob` DEK — migrate them), or a session without the blob\n * service loaded. An all-erasable subject yields an empty residue list.\n */\nexport interface ForgetResult {\n /** The subject id passed to `forget()`. Echoed for caller convenience. */\n readonly subject: string\n /** Count of live records rewritten to a tombstone. */\n readonly recordsShredded: number\n /** Count of `_history` envelopes tombstoned across all shredded records. */\n readonly historyVersionsShredded: number\n /** Distinct collections that had at least one record shredded. */\n readonly collections: readonly string[]\n /** `collection:id` pairs shredded while still un-migrated (see type docs). */\n readonly unmigratedRecords: readonly string[]\n /** Count of erasable blobs crypto-shredded (refCount → 0, BlobObject deleted). */\n readonly blobsShredded: number\n /** Count of erasable blobs retained because still referenced elsewhere (shared). */\n readonly blobsRetainedShared: number\n /** Collections with blobs that could NOT be crypto-shredded — legacy (no `_cek`) or blobs disabled (see type docs). */\n readonly blobResidueCollections: readonly string[]\n /**\n * Count of persisted `_idx/<field>/<recordId>` index side-cars hard-deleted\n * across the shredded records. These live under the retained\n * collection DEK, so crypto-shred alone would leave the indexed field VALUES\n * readable — `forget()` must delete them.\n */\n readonly indexPostingsPurged: number\n /**\n * `collection:id:field` entries whose persisted `_idx` side-car could NOT be\n * deleted — index residue that still leaks the indexed value under the\n * retained collection DEK. Non-empty means erasure is INCOMPLETE: retry, or\n * purge the side-car out of band.\n */\n readonly indexResidue: readonly string[]\n /**\n * Count of `_sealed[field]` slots dropped from the live store across the\n * shredded records. For slots written under `sensitive` +\n * `perRecordKeys` (the current path), the key derives off the per-record CEK,\n * so tombstoning the record — which drops `_cek` and `_sealed` — also\n * crypto-shreds the value. A legacy slot (written before per-record CEKs) keys\n * off the collection DEK instead, so dropping it removes it from the live store but a\n * pre-forget backup remains recoverable by a DEK holder (same caveat `_data`\n * carries); migrate by re-`put`ting before forgetting for full crypto-shred.\n */\n readonly sealedFieldsShredded: number\n /** Count of `_sealed_cek` host-delivery envelopes deleted (#H-1). A record sealed to an\n * at-* host via sealRecordToHost persists its raw CEK there; forget() must destroy them. */\n readonly sealedCekEnvelopesPurged: number\n /** `collection:id` whose `_sealed_cek` purge failed (residue — the host-recoverable CEK may survive). */\n readonly sealedCekResidue: readonly string[]\n /** `collection:id:field` sealed slots that were DEK-derived (legacy, written before per-record CEKs) and thus NOT crypto-shredded\n * by dropping `_cek` — the collection DEK is retained, so synced/backup copies stay decryptable (#M-1). */\n readonly sealedResidue: readonly string[]\n /** Count of `_ledger_deltas` rows hard-deleted across the shredded records (#734) — the\n * erasure twin of #729's elevate-side purge. Entry metadata (that the record was mutated,\n * at which version/timestamp/actor) is retained; only the plaintext delta content is removed. */\n readonly ledgerDeltasPurged: number\n /** `collection:id` refs whose `_ledger_deltas` purge failed — plaintext delta residue still\n * readable under the retained ledger DEK. Non-empty means erasure is INCOMPLETE. */\n readonly ledgerDeltaResidue: readonly string[]\n /** The single `op:'forget'` ledger entry appended for this erasure. */\n readonly ledgerEntry: LedgerEntry\n /** #622 — record-grain derived artifacts (MV rows, per-record derived copies) erased\n * because their source subject was forgotten. Overlay outputs are intentionally out of\n * scope here — an overlay is always sourced from an MV, never directly from a subject\n * collection, so the personal-data-bearing MV rows it reads are already erased above. */\n readonly derivedRecordsErased: number\n /** #622 — aggregate-grain targets (rollups) recomputed without the forgotten contribution. */\n readonly derivedAggregatesRecomputed: number\n /** #622 — `collection:id` derived writes SKIPPED because the target period is frozen\n * (recompute deferred; the aggregate retains the forgotten contribution — audited). */\n readonly derivedResidueFrozen: readonly string[]\n /** #650 Task 5 (#648) — referencing records tombstoned via a `'ref'` edge's `cascade` policy. */\n readonly lookupReferencesCascaded: number\n /** #650 Task 5 (#648) — referencing fields cleared via a `'ref'` edge's `nullify` policy. */\n readonly lookupReferencesNullified: number\n /** #650 Task 5 review (Important fix) — `'ref'` edges whose compare-key could NOT be resolved,\n * even from the LIVE pre-shred backing row — cascade/nullify propagation was SKIPPED for these.\n * Always empty in the ordinary case; non-empty means the skip is reported, never silent. */\n readonly lookupReferencesResidue: readonly string[]\n /** #633 — scoped-purge skip notices (opt-in `scopedPurge`, see {@link SubjectDeclaration}).\n * Always empty under the unconditional default. Non-empty means a `_sealed_cek` entry or a\n * blob scan was skipped for an undeclared collection — reported, never a silent skip. */\n readonly scopedPurgeResidue: readonly ScopedPurgeResidueNotice[]\n /** #776/#782/#785 — `collection:id` MV-output rows that survived erasure invalidation (eager\n * tombstone leg AND lazy/manual `invalidateMVAtRest`) despite belonging to the forgotten\n * subject, because the `_materializedFrom` ownership stamp could NOT be decoded (undecodable\n * under the collection's default DEK — e.g. elevated above tier 0 on a tiered output\n * collection; ownership unconfirmed — could be a plain user record on a same-collection\n * partition MV). Never erased, but surfaced here rather than silently skipped (the #724\n * posture). Non-empty means the row may still hold the forgotten/pre-elevation contribution,\n * decryptable by tier-holders. */\n readonly derivedResidueUndecodable: readonly string[]\n /** #782/#785 — `collection:id` MV-output rows that DID decode and stamp-match via\n * `_materializedFrom`, but whose erasure was declined by the #718 tier-elevation gate\n * (`_internalDelete` returned false). Ownership CONFIRMED here — a real silent survival,\n * not a stamp-mismatch skip — surfaced rather than dropped. Non-empty means a live,\n * tier-holder-decryptable copy of the forgotten contribution was deliberately retained. */\n readonly derivedResidueDeclined: readonly string[]\n}\n\n/** #633 — the two `scopedPurgeResidue` skip reasons. Single source of truth: `purge-scope.ts`\n * (the port-internal partition helpers) imports this rather than redeclaring it. */\nexport type ScopedPurgeResidueReason = 'skipped-undeclared-sealed-cek' | 'skipped-undeclared-blob-scan'\n\n/** #633 — one `ForgetResult.scopedPurgeResidue` entry: an undeclared collection's sealed-CEK\n * entries left unpurged, or its blob scan skipped entirely, under `scopedPurge`. `count` is the\n * number of `_sealed_cek` entries left in place (sealed-cek reason) or the number of refs whose\n * blob scan was skipped (blob-scan reason) — aggregated per collection across the whole call. */\nexport interface ScopedPurgeResidueNotice {\n readonly reason: ScopedPurgeResidueReason\n readonly collection: string\n readonly count: number\n}\n","/**\n * The encrypted subject index.\n *\n * GDPR crypto-shred needs to answer \"which records belong to data subject\n * X?\" portably (the index must travel with the vault/bundle) WITHOUT leaking\n * subject-equivalence to the store. The rejected alternative — an unencrypted\n * subject tag in envelope metadata — would let anyone with store access see\n * which records share a subject. Instead we keep a reserved `_subject_index`\n * collection, encrypted under its OWN DEK (`getDEK('_subject_index')`):\n *\n * - record id = `HMAC-SHA256(indexDEK, subjectId)` (M-2). A bare\n * `sha256Hex(subjectId)` would be offline-computable: an attacker with\n * store access and a candidate list (emails / customer ids are low-entropy)\n * could dictionary the hash to confirm \"subject X is present here.\" Keying\n * the id with the vault-only index DEK removes that capability — without the\n * DEK the id cannot be derived. (Legacy entries written before M-2 used the\n * bare sha256 id; the read/remove paths dual-look-up both forms.)\n * - record body = AES-GCM(JSON `{ r: [{ collection, id }], p }`) under the\n * index DEK, where `p` pads the plaintext to a bucketed length so the\n * ciphertext `_data` length does not leak the approximate record count.\n * Legacy bodies were a bare `[{ collection, id }]` array; reads accept both.\n *\n * ## Concurrency (RISK #3 — known v1 limitation)\n *\n * `addSubjectRef` / `removeSubjectRef` are read-modify-write with no CAS. The\n * design assumes a SINGLE WRITER (the noy-db single-process write model). Two\n * concurrent writers racing on the SAME subject can lose an entry (last-write\n * wins on the ref list). This is documented, not fixed in v1:\n * `rebuildSubjectIndex` performs a full scan to recover a correct index from\n * the canonical records, so a lost ref is recoverable. A CAS-backed index is\n * deferred to a later slice.\n *\n * @module\n */\nimport { buildRecordAad, buildRecordEnvelope, encrypt, openEnvelopeJson, hmacSha256Hex, sha256Hex, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\n\n/** Reserved collection holding the encrypted subject → records index. */\nexport const SUBJECT_INDEX_COLLECTION = '_subject_index'\n\n/**\n * Bucket (bytes) the encrypted ref-list plaintext is padded up to, so the\n * ciphertext `_data` length leaks only `count` rounded up to a bucket — not the\n * exact record count. 256 keeps small subjects (the common case) indistinguishable.\n */\nconst REF_LIST_BUCKET = 256\n\n/** A single record reference held in a subject's index entry. */\nexport interface SubjectRef {\n readonly collection: string\n readonly id: string\n}\n\ntype GetDEK = (collectionName: string) => Promise<EnclaveKey>\n\n/** SHA-256 hex of a UTF-8 string. The LEGACY (pre-M-2) subject-index key. */\nasync function sha256HexString(input: string): Promise<string> {\n return sha256Hex(new TextEncoder().encode(input))\n}\n\n/**\n * The subject-index record id(s) to consult for a subject, most-current first.\n *\n * - Encrypted vault: the PRIMARY id is `HMAC-SHA256(indexDEK, subjectId)` (M-2)\n * — not offline-computable. The LEGACY `sha256Hex(subjectId)` id is also\n * returned so reads/removes still find entries written before M-2 (dual-lookup).\n * - Plaintext/debug vault: no DEK to key with, so the only id is the legacy\n * sha256 form (unchanged behaviour — plaintext mode is not zero-knowledge anyway).\n */\nasync function subjectKeys(getDEK: GetDEK, encrypted: boolean, subjectId: string): Promise<string[]> {\n const legacy = await sha256HexString(subjectId)\n if (!encrypted) return [legacy]\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const keyed = await hmacSha256Hex(dek, new TextEncoder().encode(subjectId))\n return keyed === legacy ? [keyed] : [keyed, legacy]\n}\n\n/** The id new writes land under (keyed when encrypted, else legacy sha256). */\nasync function primarySubjectKey(getDEK: GetDEK, encrypted: boolean, subjectId: string): Promise<string> {\n return (await subjectKeys(getDEK, encrypted, subjectId))[0]!\n}\n\n/** Parse a stored ref-list body: new padded `{ r, p }` wrapper OR legacy bare array. */\nfunction parseRefs(json: string): SubjectRef[] {\n const parsed = JSON.parse(json) as SubjectRef[] | { r: SubjectRef[] }\n return Array.isArray(parsed) ? parsed : parsed.r\n}\n\n/** Serialize + pad the ref list to a bucket boundary (encrypted vaults only). */\nfunction serializeRefs(refs: SubjectRef[]): string {\n const base = JSON.stringify({ r: refs, p: '' })\n const pad = Math.ceil(base.length / REF_LIST_BUCKET) * REF_LIST_BUCKET - base.length\n return JSON.stringify({ r: refs, p: ' '.repeat(pad) })\n}\n\n/** Read + decrypt the ref list at a SINGLE index key. Returns `[]` when absent. */\nasync function readRefs(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n key: string,\n): Promise<SubjectRef[]> {\n const env = await adapter.get(vault, SUBJECT_INDEX_COLLECTION, key)\n if (!env || !env._data) return []\n if (!encrypted) return parseRefs(env._data)\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const json = await openEnvelopeJson({ collection: SUBJECT_INDEX_COLLECTION, id: key }, env, dek)\n return parseRefs(json)\n}\n\n/** Encrypt + write a ref list for a subject under its derived key. */\nasync function writeRefs(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n key: string,\n refs: SubjectRef[],\n): Promise<void> {\n const identity = { collection: SUBJECT_INDEX_COLLECTION, id: key, version: 1 }\n let env: EncryptedEnvelope\n if (!encrypted) {\n // Plaintext/debug vault: keep the bare-array form (no padding needed).\n env = buildRecordEnvelope(identity, { iv: '', data: JSON.stringify(refs) })\n } else {\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const { iv, data } = await encrypt(serializeRefs(refs), dek, buildRecordAad(identity))\n env = buildRecordEnvelope(identity, { iv, data })\n }\n await adapter.put(vault, SUBJECT_INDEX_COLLECTION, key, env)\n}\n\n/**\n * Add a `{ collection, id }` ref to a subject's index entry (idempotent —\n * a duplicate ref is not appended). Read-modify-write; see the concurrency\n * note in the module docstring.\n */\nexport async function addSubjectRef(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n ref: SubjectRef,\n): Promise<void> {\n const key = await primarySubjectKey(getDEK, encrypted, subjectId)\n const refs = await readRefs(adapter, vault, getDEK, encrypted, key)\n if (refs.some((r) => r.collection === ref.collection && r.id === ref.id)) return\n refs.push(ref)\n await writeRefs(adapter, vault, getDEK, encrypted, key, refs)\n}\n\n/**\n * Remove a `{ collection, id }` ref from a subject's index entry. When the\n * last ref is removed the (now empty) entry is deleted so the store holds no\n * residual key for an erased subject.\n */\nexport async function removeSubjectRef(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n ref: SubjectRef,\n): Promise<void> {\n // Dual-lookup: drop the ref from BOTH the keyed (M-2) and the legacy sha256\n // entry, so a pre-M-2 subject is still fully erased.\n for (const key of await subjectKeys(getDEK, encrypted, subjectId)) {\n const refs = await readRefs(adapter, vault, getDEK, encrypted, key)\n const next = refs.filter((r) => !(r.collection === ref.collection && r.id === ref.id))\n if (next.length === refs.length) continue\n if (next.length === 0) {\n await adapter.delete(vault, SUBJECT_INDEX_COLLECTION, key)\n } else {\n await writeRefs(adapter, vault, getDEK, encrypted, key, next)\n }\n }\n}\n\n/**\n * Look up every record ref for a subject. Returns `[]` when none exist. Unions\n * the keyed (M-2) and legacy sha256 entries (dual-lookup), deduplicated, so a\n * subject indexed before M-2 is still fully found.\n */\nexport async function lookupSubject(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n): Promise<SubjectRef[]> {\n const keys = await subjectKeys(getDEK, encrypted, subjectId)\n const seen = new Set<string>()\n const out: SubjectRef[] = []\n for (const key of keys) {\n for (const ref of await readRefs(adapter, vault, getDEK, encrypted, key)) {\n const dedup = `${ref.collection}\\u0000${ref.id}`\n if (seen.has(dedup)) continue\n seen.add(dedup)\n out.push(ref)\n }\n }\n return out\n}\n\n/**\n * Rebuild the entire subject index from the canonical records (the recovery\n * path for the documented read-modify-write race). Scans each declared\n * collection, reads `record[subjectField]` (dotted path), and rewrites the\n * index from scratch. Tombstoned (already-shredded) records contribute no\n * ref — their body is gone, so they cannot be re-indexed.\n *\n * `decodeRecord` decrypts an envelope to a plain object (or returns null for\n * a tombstone / unreadable record); supplied by the caller so this module\n * stays free of Collection internals.\n */\nexport async function rebuildSubjectIndex(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjects: Readonly<Record<string, string>>,\n decodeRecord: (collection: string, id: string, env: EncryptedEnvelope) => Promise<Record<string, unknown> | null>,\n): Promise<number> {\n // Drop every existing index entry first so removed refs don't linger.\n const existing = await adapter.list(vault, SUBJECT_INDEX_COLLECTION)\n for (const k of existing) {\n await adapter.delete(vault, SUBJECT_INDEX_COLLECTION, k)\n }\n\n // subjectId → refs, accumulated across all declared collections.\n const bySubject = new Map<string, SubjectRef[]>()\n for (const [collection, field] of Object.entries(subjects)) {\n const ids = await adapter.list(vault, collection)\n for (const id of ids) {\n if (id.startsWith('_')) continue\n const env = await adapter.get(vault, collection, id)\n if (!env || !env._data) continue // missing or tombstone\n const record = await decodeRecord(collection, id, env)\n if (record === null) continue\n const subjectValue = readDottedPath(record, field)\n if (subjectValue === undefined || subjectValue === null) continue\n const subjectId = coerceSubjectId(subjectValue)\n const list = bySubject.get(subjectId) ?? []\n list.push({ collection, id })\n bySubject.set(subjectId, list)\n }\n }\n\n let entries = 0\n for (const [subjectId, refs] of bySubject) {\n const key = await primarySubjectKey(getDEK, encrypted, subjectId)\n await writeRefs(adapter, vault, getDEK, encrypted, key, refs)\n entries++\n }\n return entries\n}\n\n/**\n * Coerce a read subject-field value to a stable string id. Primitives use\n * their natural string form; objects/arrays are JSON-stringified so structural\n * subjects still get a deterministic key (avoids the `[object Object]` trap).\n */\nexport function coerceSubjectId(value: unknown): string {\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n return String(value)\n }\n return JSON.stringify(value)\n}\n\n/** Read a (possibly dotted) field path from a plain record. */\nexport function readDottedPath(record: Record<string, unknown>, field: string): unknown {\n if (!field.includes('.')) return record[field]\n let cursor: unknown = record\n for (const segment of field.split('.')) {\n if (cursor === null || cursor === undefined) return undefined\n cursor = (cursor as Record<string, unknown>)[segment]\n }\n return cursor\n}\n"],"mappings":";;;;;;;;;;;;;;AAuEO,IAAM,YAA4B,EAAE,UAAU,CAAC,EAAE;;;ACjCjD,IAAM,2BAA2B;AAOxC,IAAM,kBAAkB;AAWxB,eAAe,gBAAgB,OAAgC;AAC7D,SAAO,UAAU,IAAI,YAAY,EAAE,OAAO,KAAK,CAAC;AAClD;AAWA,eAAe,YAAY,QAAgB,WAAoB,WAAsC;AACnG,QAAM,SAAS,MAAM,gBAAgB,SAAS;AAC9C,MAAI,CAAC,UAAW,QAAO,CAAC,MAAM;AAC9B,QAAM,MAAM,MAAM,OAAO,wBAAwB;AACjD,QAAM,QAAQ,MAAM,cAAc,KAAK,IAAI,YAAY,EAAE,OAAO,SAAS,CAAC;AAC1E,SAAO,UAAU,SAAS,CAAC,KAAK,IAAI,CAAC,OAAO,MAAM;AACpD;AAGA,eAAe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U;AACxF,WAAO,OAAO,KAAK;AAAA,EACrB;AACA,SAAO,KAAK,UAAU,KAAK;AAC7B;AAGO,SAAS,eAAe,QAAiC,OAAwB;AACtF,MAAI,CAAC,MAAM,SAAS,GAAG,EAAG,QAAO,OAAO,KAAK;AAC7C,MAAI,SAAkB;AACtB,aAAW,WAAW,MAAM,MAAM,GAAG,GAAG;AACtC,QAAI,WAAW,QAAQ,WAAW,OAAW,QAAO;AACpD,aAAU,OAAmC,OAAO;AAAA,EACtD;AACA,SAAO;AACT;","names":[]}
|
|
@@ -4,11 +4,26 @@ import {
|
|
|
4
4
|
import {
|
|
5
5
|
DanglingReferenceError,
|
|
6
6
|
JoinTooLargeError
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-CWM4GQD2.js";
|
|
8
8
|
|
|
9
9
|
// src/kernel/query/join.ts
|
|
10
10
|
var DEFAULT_JOIN_MAX_ROWS = 5e4;
|
|
11
11
|
var JOIN_WARN_FRACTION = 0.8;
|
|
12
|
+
function referencesJoinAlias(clause, aliases) {
|
|
13
|
+
if (clause.type !== "field") return false;
|
|
14
|
+
return aliases.has(clause.field.split(".")[0]);
|
|
15
|
+
}
|
|
16
|
+
function splitAroundJoins(clauses, joins) {
|
|
17
|
+
if (joins.length === 0 || clauses.length === 0) return { preJoin: clauses, postJoin: [] };
|
|
18
|
+
const aliases = new Set(joins.map((leg) => leg.as));
|
|
19
|
+
const preJoin = [];
|
|
20
|
+
const postJoin = [];
|
|
21
|
+
for (const clause of clauses) {
|
|
22
|
+
;
|
|
23
|
+
(referencesJoinAlias(clause, aliases) ? postJoin : preJoin).push(clause);
|
|
24
|
+
}
|
|
25
|
+
return { preJoin, postJoin };
|
|
26
|
+
}
|
|
12
27
|
function coerceRefKey(value) {
|
|
13
28
|
if (value === null || value === void 0) return null;
|
|
14
29
|
if (typeof value === "string") return value;
|
|
@@ -167,7 +182,8 @@ function resetJoinWarnings() {
|
|
|
167
182
|
|
|
168
183
|
export {
|
|
169
184
|
DEFAULT_JOIN_MAX_ROWS,
|
|
185
|
+
splitAroundJoins,
|
|
170
186
|
applyJoins,
|
|
171
187
|
resetJoinWarnings
|
|
172
188
|
};
|
|
173
|
-
//# sourceMappingURL=chunk-
|
|
189
|
+
//# sourceMappingURL=chunk-VVSOPRUE.js.map
|