@noy-db/hub 0.6.0-pre.22 → 0.6.0-pre.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (380) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/dist/api-56KUWV6E.js +20 -0
  3. package/dist/attestation/index.js +18 -18
  4. package/dist/{backup-4PZAH67W.js → backup-WLKPDY3V.js} +12 -12
  5. package/dist/blobs/index.js +22 -20
  6. package/dist/blobs/index.js.map +1 -1
  7. package/dist/broker/index.js +12 -12
  8. package/dist/cargo/index.js +29 -29
  9. package/dist/{chunk-PNXJV4OS.js → chunk-24ZDSTEQ.js} +41 -17
  10. package/dist/chunk-24ZDSTEQ.js.map +1 -0
  11. package/dist/{chunk-4RZTW5JH.js → chunk-25HI46CB.js} +2 -2
  12. package/dist/{chunk-PWK3SSNB.js → chunk-264AKW4K.js} +4 -4
  13. package/dist/{chunk-7LJA7T4W.js → chunk-2CURJCLC.js} +3 -3
  14. package/dist/{chunk-YF3CIA6E.js → chunk-2D5NXYWY.js} +2 -2
  15. package/dist/{chunk-REQJLII3.js → chunk-2MYYXXVM.js} +2 -2
  16. package/dist/{chunk-DIYI32MG.js → chunk-2S6HROLU.js} +5 -5
  17. package/dist/{chunk-23XKHFNT.js → chunk-2ZSBPXFW.js} +3 -3
  18. package/dist/{chunk-XZZIZ544.js → chunk-34MSA4AO.js} +51 -16
  19. package/dist/chunk-34MSA4AO.js.map +1 -0
  20. package/dist/{chunk-BXHG26KN.js → chunk-35K4VWMD.js} +2 -2
  21. package/dist/{chunk-DIVPOJPV.js → chunk-43FOH2OK.js} +20 -8
  22. package/dist/chunk-43FOH2OK.js.map +1 -0
  23. package/dist/{chunk-UQUWSM33.js → chunk-4P3OG2AO.js} +5 -5
  24. package/dist/{chunk-KYUKZIW5.js → chunk-4Y7VHLCT.js} +2 -2
  25. package/dist/{chunk-RJYPFCID.js → chunk-576CTQ77.js} +5 -5
  26. package/dist/{chunk-OCW3IM2F.js → chunk-57MEX4LL.js} +3 -3
  27. package/dist/{chunk-PKUJ3JLQ.js → chunk-5OFC3QYL.js} +19 -2
  28. package/dist/chunk-5OFC3QYL.js.map +1 -0
  29. package/dist/{chunk-4O52JH3C.js → chunk-65WBEFVT.js} +6 -6
  30. package/dist/{chunk-JSTQGUE5.js → chunk-6J7SSCJW.js} +15 -10
  31. package/dist/chunk-6J7SSCJW.js.map +1 -0
  32. package/dist/{chunk-7JOXCSDU.js → chunk-6PLCNLBC.js} +2 -2
  33. package/dist/{chunk-QK2QAMF7.js → chunk-ACIEKVFR.js} +10 -10
  34. package/dist/{chunk-JPVJTTHU.js → chunk-AKPIBKHK.js} +4 -4
  35. package/dist/{chunk-AELW6OJZ.js → chunk-AM6V36AG.js} +2 -2
  36. package/dist/{chunk-DUUARUZI.js → chunk-AU45F5FD.js} +2 -2
  37. package/dist/{chunk-4BYZIQ5T.js → chunk-BZKQRED6.js} +2 -2
  38. package/dist/{chunk-OZ5QBLEL.js → chunk-C3FCXXNI.js} +6 -6
  39. package/dist/{chunk-FKZI4NSG.js → chunk-C4DFJ76X.js} +6 -6
  40. package/dist/{chunk-PGHSH4TY.js → chunk-CDHX3SRW.js} +3 -3
  41. package/dist/{chunk-O5QXH7U7.js → chunk-D7STIWJO.js} +11 -2
  42. package/dist/chunk-D7STIWJO.js.map +1 -0
  43. package/dist/{chunk-VMYXYFPX.js → chunk-DBPQUICN.js} +2 -2
  44. package/dist/{chunk-3TWEXEKX.js → chunk-DL7NXFAY.js} +2 -2
  45. package/dist/{chunk-2VMCJUK6.js → chunk-DM2BZDNV.js} +5 -5
  46. package/dist/{chunk-FFSQFH6D.js → chunk-DNKVKO7K.js} +2 -2
  47. package/dist/{chunk-IPA6ODWG.js → chunk-E2LYQUB7.js} +4 -4
  48. package/dist/{chunk-ANYVM4SX.js → chunk-ENTVT7PF.js} +2 -2
  49. package/dist/{chunk-M3FKPVOU.js → chunk-ESP4K32V.js} +3 -3
  50. package/dist/{chunk-A66LJYFG.js → chunk-FEWCVAFV.js} +131 -17
  51. package/dist/chunk-FEWCVAFV.js.map +1 -0
  52. package/dist/{chunk-H27DIXOV.js → chunk-FJGNYSB3.js} +6 -6
  53. package/dist/{chunk-OBPL43F3.js → chunk-FKLKAO2C.js} +54 -7
  54. package/dist/chunk-FKLKAO2C.js.map +1 -0
  55. package/dist/{chunk-PENPHA45.js → chunk-FX3UIDCS.js} +2 -2
  56. package/dist/{chunk-H3SEW5HB.js → chunk-G3ZMEUWD.js} +7 -7
  57. package/dist/{chunk-ZAZW5LLF.js → chunk-GCTZNHDO.js} +2 -2
  58. package/dist/{chunk-D5EXZVQC.js → chunk-GDYDYUO7.js} +6 -6
  59. package/dist/{chunk-47F6AI2K.js → chunk-GU5XWSH4.js} +3 -3
  60. package/dist/{chunk-6ZGDIN2D.js → chunk-H6J6MZ4J.js} +3 -3
  61. package/dist/{chunk-ZUDIY7YP.js → chunk-HMS3OCMA.js} +7 -7
  62. package/dist/{chunk-H6K24KLL.js → chunk-HUAAYTVS.js} +4 -4
  63. package/dist/{chunk-2DFE4TUE.js → chunk-HUDP5NSI.js} +4 -4
  64. package/dist/{chunk-VKYEEJJ2.js → chunk-HWJZCZSI.js} +2 -2
  65. package/dist/{chunk-NB2CKJ27.js → chunk-ICGLT356.js} +2 -2
  66. package/dist/{chunk-CW3VJARJ.js → chunk-IYXP6OR5.js} +3 -3
  67. package/dist/{chunk-A5YEUQOY.js → chunk-JSJS7RHS.js} +2 -2
  68. package/dist/{chunk-NHXIFF4Y.js → chunk-K6J7JKZM.js} +7 -7
  69. package/dist/{chunk-LLLSK7UQ.js → chunk-K7HPGV5K.js} +2 -2
  70. package/dist/{chunk-F3BICEMK.js → chunk-KC3S3OH6.js} +2 -2
  71. package/dist/{chunk-HZIIDYJV.js → chunk-KEMD6B3W.js} +4 -4
  72. package/dist/{chunk-SRR22EW2.js → chunk-L34HKPIS.js} +8 -8
  73. package/dist/{chunk-AGETRKC5.js → chunk-LG2P6S32.js} +3 -3
  74. package/dist/{chunk-FUIG7QSS.js → chunk-LT26SRU5.js} +4 -4
  75. package/dist/{chunk-6QMOJTC6.js → chunk-LTC77D4V.js} +2 -2
  76. package/dist/{chunk-QTWWZ25B.js → chunk-LU2HAOVP.js} +18 -14
  77. package/dist/chunk-LU2HAOVP.js.map +1 -0
  78. package/dist/{chunk-QMJI5VHV.js → chunk-M3XEJJDE.js} +2 -2
  79. package/dist/{chunk-VWPJX5B3.js → chunk-MGIAYREB.js} +5 -5
  80. package/dist/{chunk-VYLC5KAT.js → chunk-MLTGIDNB.js} +2 -2
  81. package/dist/{chunk-L2YYIQYR.js → chunk-MXJMCTSI.js} +2 -2
  82. package/dist/{chunk-F5IFR56V.js → chunk-NFARMKWK.js} +34 -12
  83. package/dist/chunk-NFARMKWK.js.map +1 -0
  84. package/dist/{chunk-IUQPNAGR.js → chunk-NK7DO6A2.js} +3 -3
  85. package/dist/{chunk-TKLQWOTY.js → chunk-NKND2IMW.js} +2 -2
  86. package/dist/{chunk-WUNRUSBJ.js → chunk-NSZGZYZL.js} +13 -3
  87. package/dist/{chunk-WUNRUSBJ.js.map → chunk-NSZGZYZL.js.map} +1 -1
  88. package/dist/{chunk-XPTYXXMD.js → chunk-NUHIPODK.js} +2 -2
  89. package/dist/{chunk-REKDM67V.js → chunk-ODGV6Q6U.js} +2 -2
  90. package/dist/{chunk-WRGNEAUZ.js → chunk-OJYLLNQN.js} +2 -2
  91. package/dist/{chunk-NCAMIRFB.js → chunk-OQT3G55N.js} +2 -2
  92. package/dist/{chunk-BPLSGN4X.js → chunk-PORGC5MH.js} +2 -2
  93. package/dist/{chunk-BFNBYT62.js → chunk-PRBJ4BJD.js} +2 -2
  94. package/dist/{chunk-4IPP2P74.js → chunk-PU5PNTE2.js} +2 -2
  95. package/dist/{chunk-L3AM6EGU.js → chunk-PZEDIO72.js} +7 -7
  96. package/dist/{chunk-M7VSXBUL.js → chunk-RTBCWDJ3.js} +10 -10
  97. package/dist/{chunk-OTHHO3KI.js → chunk-S2I5MYSA.js} +2 -2
  98. package/dist/{chunk-FHEVZQQY.js → chunk-S447GUNV.js} +4 -4
  99. package/dist/{chunk-WKT7NNNR.js → chunk-SP3AFEB7.js} +4 -4
  100. package/dist/{chunk-KMGAFLCK.js → chunk-SQWXF2HP.js} +5 -5
  101. package/dist/{chunk-HRSEAGLI.js → chunk-TTGZ6KGY.js} +3 -3
  102. package/dist/{chunk-MQFKH3ZJ.js → chunk-UHFF4G53.js} +3 -3
  103. package/dist/{chunk-IGNJOJEP.js → chunk-UJ4Z67UQ.js} +2 -2
  104. package/dist/chunk-UJ4Z67UQ.js.map +1 -0
  105. package/dist/{chunk-FGZ7GJXO.js → chunk-VZEBHQRT.js} +3 -3
  106. package/dist/{chunk-HUEG3YP4.js → chunk-VZHEFFUO.js} +97 -82
  107. package/dist/chunk-VZHEFFUO.js.map +1 -0
  108. package/dist/{chunk-OIW75CLW.js → chunk-WN377AAV.js} +6 -6
  109. package/dist/{chunk-ESXVNASI.js → chunk-XCNYOVFV.js} +5 -5
  110. package/dist/{chunk-FFESJQ5A.js → chunk-YEEV4ZXL.js} +95 -32
  111. package/dist/chunk-YEEV4ZXL.js.map +1 -0
  112. package/dist/{chunk-YOMI3ZCA.js → chunk-YIC34H3M.js} +2 -2
  113. package/dist/{chunk-MBZFAJKM.js → chunk-YZWRJRMF.js} +6 -2
  114. package/dist/chunk-YZWRJRMF.js.map +1 -0
  115. package/dist/{chunk-GWJJ5CK3.js → chunk-Z45PK2H5.js} +5 -5
  116. package/dist/{chunk-RT7CWTUG.js → chunk-ZI43U6FN.js} +6 -6
  117. package/dist/{chunk-WFC2GHJG.js → chunk-ZJJ46LNY.js} +3 -3
  118. package/dist/{chunk-3ENNPCIW.js → chunk-ZY6P7M52.js} +2 -2
  119. package/dist/classified/index.js +5 -5
  120. package/dist/{classified-marker-EPL2NX3H.js → classified-marker-DLLGRRXG.js} +3 -3
  121. package/dist/collection-facade-OHBCHCJV.js +45 -0
  122. package/dist/{computed-UXN4AMI5.js → computed-X2RKYFGX.js} +3 -3
  123. package/dist/consent/index.js +9 -9
  124. package/dist/cover/index.js +9 -9
  125. package/dist/custody/index.js +12 -11
  126. package/dist/{dead-filter-56AYTNAO.js → dead-filter-CCLDPNTJ.js} +2 -2
  127. package/dist/debug/index.js +1 -1
  128. package/dist/{delegation-MCCWCFZA.js → delegation-OSXUSSUO.js} +11 -11
  129. package/dist/derivations/index.js +12 -12
  130. package/dist/derive-6K35IOIN.js +22 -0
  131. package/dist/directory/index.js +10 -10
  132. package/dist/{dispatch-JM7X5BLP.js → dispatch-HCCQPOC7.js} +9 -6
  133. package/dist/dispatch-HCCQPOC7.js.map +1 -0
  134. package/dist/{dispatch-UPZW4MAO.js → dispatch-TRXQIBLA.js} +18 -18
  135. package/dist/{enclave-CCXI3WEU.js → enclave-K33BCSHB.js} +13 -9
  136. package/dist/executor-44ONIZTV.js +9 -0
  137. package/dist/executor-H7KLBIJN.js +9 -0
  138. package/dist/executor-PDK7IAPQ.js +29 -0
  139. package/dist/export-accessible-2LJH6JTI.js +23 -0
  140. package/dist/extract-partition-QQFOPCJ6.js +38 -0
  141. package/dist/{fanout-sidecar-2EHAV6UP.js → fanout-sidecar-ORVUHI3J.js} +9 -9
  142. package/dist/find-H6GHRBNL.js +11 -0
  143. package/dist/forget/index.js +9 -9
  144. package/dist/guards/index.js +4 -4
  145. package/dist/history/index.js +13 -13
  146. package/dist/i18n/index.js +14 -14
  147. package/dist/index.d.ts +1 -1
  148. package/dist/index.js +93 -91
  149. package/dist/index.js.map +1 -1
  150. package/dist/indexing/index.js +2 -2
  151. package/dist/introspection/index.js +11 -11
  152. package/dist/issue-LV2IWCKY.js +19 -0
  153. package/dist/kernel/collection.d.ts +8 -2
  154. package/dist/kernel/constants.d.ts +18 -0
  155. package/dist/kernel/enclave/crypto.d.ts +28 -0
  156. package/dist/kernel/enclave/index.d.ts +2 -2
  157. package/dist/kernel/enclave/record-keys/rekey.d.ts +23 -0
  158. package/dist/kernel/errors.d.ts +41 -0
  159. package/dist/kernel/refs.d.ts +3 -1
  160. package/dist/kernel/tier-visibility.d.ts +19 -0
  161. package/dist/kernel/types.d.ts +1 -1
  162. package/dist/kernel/via/reconcile.d.ts +12 -0
  163. package/dist/{ledger-TZIDVW22.js → ledger-RM5672K4.js} +11 -11
  164. package/dist/liberate-PNPIQ45H.js +25 -0
  165. package/dist/{link-set-VOMRQB2H.js → link-set-AZ6VDH5X.js} +11 -11
  166. package/dist/{managed-secret-N6FWB5LX.js → managed-secret-QZKTYCLD.js} +10 -10
  167. package/dist/materialized-views/index.js +20 -20
  168. package/dist/{migrate-cek-UEO2EUWI.js → migrate-cek-BVAPYJ5T.js} +2 -2
  169. package/dist/money/index.js +4 -4
  170. package/dist/noydb-QZN7G26J.js +85 -0
  171. package/dist/overlay-views/index.js +4 -4
  172. package/dist/periods/index.js +12 -12
  173. package/dist/pod/index.js +56 -55
  174. package/dist/{pod-handle-D6ZRTO4N.js → pod-handle-LVSMK4XC.js} +9 -9
  175. package/dist/policy/index.js +10 -10
  176. package/dist/portability/index.js +8 -8
  177. package/dist/{post-register-XVGHYYSB.js → post-register-TZGQ34YR.js} +6 -6
  178. package/dist/query/index.js +3 -3
  179. package/dist/reduce/index.js +4 -4
  180. package/dist/register-IQJGJSQQ.js +32 -0
  181. package/dist/registry-3JY3YSMU.js +9 -0
  182. package/dist/registry-G365BQDC.js +19 -0
  183. package/dist/registry-HVS6PGHV.js +9 -0
  184. package/dist/registry-TQ5FRB4T.js +18 -0
  185. package/dist/request-withdrawal-XQCCKMB3.js +31 -0
  186. package/dist/{reveal-Z62PLVJT.js → reveal-5PXWDCLZ.js} +6 -6
  187. package/dist/revoke-6NSQWTED.js +24 -0
  188. package/dist/satellites/index.js +1 -1
  189. package/dist/schema-update/index.js +2 -2
  190. package/dist/sealed-record/index.js +12 -12
  191. package/dist/search/index.js +4 -4
  192. package/dist/{seed-R2JK2YQK.js → seed-ZLOK3Z4M.js} +12 -11
  193. package/dist/{seed-R2JK2YQK.js.map → seed-ZLOK3Z4M.js.map} +1 -1
  194. package/dist/sequence/index.js +9 -9
  195. package/dist/session/index.js +9 -9
  196. package/dist/shadow/index.js +2 -2
  197. package/dist/signer-AJ3MCSPI.js +25 -0
  198. package/dist/snapshots/index.js +10 -10
  199. package/dist/{stale-FVK3WRMM.js → stale-KQR5QAYJ.js} +10 -10
  200. package/dist/storage-GACYAH6W.js +23 -0
  201. package/dist/{store-coordination-provider-HIPOZMC2.js → store-coordination-provider-RII4H3PJ.js} +10 -10
  202. package/dist/sync/index.js +10 -10
  203. package/dist/team/index.js +15 -15
  204. package/dist/tiers/index.js +11 -11
  205. package/dist/to/index.js +1 -1
  206. package/dist/transactions/index.js +3 -3
  207. package/dist/util/index.js +1 -1
  208. package/dist/vault-head/index.js +8 -8
  209. package/dist/{verify-KYICK5IW.js → verify-OMPYUO7C.js} +5 -5
  210. package/dist/via/blob/index.d.ts +3 -0
  211. package/dist/walk-ZYC74R65.js +21 -0
  212. package/dist/with-formula/materialized-views/dependency-analyzer.d.ts +4 -0
  213. package/dist/with-formula/materialized-views/projection-legs.d.ts +59 -0
  214. package/dist/with-formula/materialized-views/registry.d.ts +50 -0
  215. package/dist/with-formula/materialized-views/types.d.ts +68 -10
  216. package/dist/with-party/team/roster-tag.d.ts +1 -1
  217. package/dist/with-shape/blobs/blob-compaction.d.ts +13 -0
  218. package/dist/with-shape/blobs/blob-set.d.ts +23 -3
  219. package/dist/with-shape/blobs/orphan-report.d.ts +62 -0
  220. package/dist/withdraw-accessible-MEFFAGRD.js +28 -0
  221. package/package.json +3 -3
  222. package/dist/api-D6DBNTOS.js +0 -20
  223. package/dist/chunk-A66LJYFG.js.map +0 -1
  224. package/dist/chunk-DIVPOJPV.js.map +0 -1
  225. package/dist/chunk-F5IFR56V.js.map +0 -1
  226. package/dist/chunk-FFESJQ5A.js.map +0 -1
  227. package/dist/chunk-HUEG3YP4.js.map +0 -1
  228. package/dist/chunk-IGNJOJEP.js.map +0 -1
  229. package/dist/chunk-JSTQGUE5.js.map +0 -1
  230. package/dist/chunk-MBZFAJKM.js.map +0 -1
  231. package/dist/chunk-O5QXH7U7.js.map +0 -1
  232. package/dist/chunk-OBPL43F3.js.map +0 -1
  233. package/dist/chunk-PKUJ3JLQ.js.map +0 -1
  234. package/dist/chunk-PNXJV4OS.js.map +0 -1
  235. package/dist/chunk-QTWWZ25B.js.map +0 -1
  236. package/dist/chunk-XZZIZ544.js.map +0 -1
  237. package/dist/collection-facade-3DN4ETEP.js +0 -45
  238. package/dist/derive-BSAF6N5X.js +0 -22
  239. package/dist/dispatch-JM7X5BLP.js.map +0 -1
  240. package/dist/executor-6YQYFGHK.js +0 -9
  241. package/dist/executor-GLKPMISJ.js +0 -9
  242. package/dist/executor-ZEIX7Y7I.js +0 -29
  243. package/dist/export-accessible-SDIQEFHQ.js +0 -23
  244. package/dist/extract-partition-K232SO2V.js +0 -38
  245. package/dist/find-GKFC5753.js +0 -11
  246. package/dist/issue-QTQYQJCB.js +0 -19
  247. package/dist/liberate-FOK7RFYQ.js +0 -24
  248. package/dist/noydb-3BBLBSHI.js +0 -84
  249. package/dist/register-FVUE46K4.js +0 -32
  250. package/dist/registry-7PBVHSD5.js +0 -19
  251. package/dist/registry-CCXD57GV.js +0 -18
  252. package/dist/registry-K75FRKSU.js +0 -9
  253. package/dist/registry-KZYPKIOF.js +0 -9
  254. package/dist/request-withdrawal-WS7PXD7B.js +0 -31
  255. package/dist/revoke-JH4VQTJ3.js +0 -24
  256. package/dist/signer-AFV6AXSN.js +0 -25
  257. package/dist/storage-EIM5HO2O.js +0 -23
  258. package/dist/walk-FV6JFWXV.js +0 -21
  259. package/dist/withdraw-accessible-JYX3SPVY.js +0 -28
  260. /package/dist/{api-D6DBNTOS.js.map → api-56KUWV6E.js.map} +0 -0
  261. /package/dist/{backup-4PZAH67W.js.map → backup-WLKPDY3V.js.map} +0 -0
  262. /package/dist/{chunk-4RZTW5JH.js.map → chunk-25HI46CB.js.map} +0 -0
  263. /package/dist/{chunk-PWK3SSNB.js.map → chunk-264AKW4K.js.map} +0 -0
  264. /package/dist/{chunk-7LJA7T4W.js.map → chunk-2CURJCLC.js.map} +0 -0
  265. /package/dist/{chunk-YF3CIA6E.js.map → chunk-2D5NXYWY.js.map} +0 -0
  266. /package/dist/{chunk-REQJLII3.js.map → chunk-2MYYXXVM.js.map} +0 -0
  267. /package/dist/{chunk-DIYI32MG.js.map → chunk-2S6HROLU.js.map} +0 -0
  268. /package/dist/{chunk-23XKHFNT.js.map → chunk-2ZSBPXFW.js.map} +0 -0
  269. /package/dist/{chunk-BXHG26KN.js.map → chunk-35K4VWMD.js.map} +0 -0
  270. /package/dist/{chunk-UQUWSM33.js.map → chunk-4P3OG2AO.js.map} +0 -0
  271. /package/dist/{chunk-KYUKZIW5.js.map → chunk-4Y7VHLCT.js.map} +0 -0
  272. /package/dist/{chunk-RJYPFCID.js.map → chunk-576CTQ77.js.map} +0 -0
  273. /package/dist/{chunk-OCW3IM2F.js.map → chunk-57MEX4LL.js.map} +0 -0
  274. /package/dist/{chunk-4O52JH3C.js.map → chunk-65WBEFVT.js.map} +0 -0
  275. /package/dist/{chunk-7JOXCSDU.js.map → chunk-6PLCNLBC.js.map} +0 -0
  276. /package/dist/{chunk-QK2QAMF7.js.map → chunk-ACIEKVFR.js.map} +0 -0
  277. /package/dist/{chunk-JPVJTTHU.js.map → chunk-AKPIBKHK.js.map} +0 -0
  278. /package/dist/{chunk-AELW6OJZ.js.map → chunk-AM6V36AG.js.map} +0 -0
  279. /package/dist/{chunk-DUUARUZI.js.map → chunk-AU45F5FD.js.map} +0 -0
  280. /package/dist/{chunk-4BYZIQ5T.js.map → chunk-BZKQRED6.js.map} +0 -0
  281. /package/dist/{chunk-OZ5QBLEL.js.map → chunk-C3FCXXNI.js.map} +0 -0
  282. /package/dist/{chunk-FKZI4NSG.js.map → chunk-C4DFJ76X.js.map} +0 -0
  283. /package/dist/{chunk-PGHSH4TY.js.map → chunk-CDHX3SRW.js.map} +0 -0
  284. /package/dist/{chunk-VMYXYFPX.js.map → chunk-DBPQUICN.js.map} +0 -0
  285. /package/dist/{chunk-3TWEXEKX.js.map → chunk-DL7NXFAY.js.map} +0 -0
  286. /package/dist/{chunk-2VMCJUK6.js.map → chunk-DM2BZDNV.js.map} +0 -0
  287. /package/dist/{chunk-FFSQFH6D.js.map → chunk-DNKVKO7K.js.map} +0 -0
  288. /package/dist/{chunk-IPA6ODWG.js.map → chunk-E2LYQUB7.js.map} +0 -0
  289. /package/dist/{chunk-ANYVM4SX.js.map → chunk-ENTVT7PF.js.map} +0 -0
  290. /package/dist/{chunk-M3FKPVOU.js.map → chunk-ESP4K32V.js.map} +0 -0
  291. /package/dist/{chunk-H27DIXOV.js.map → chunk-FJGNYSB3.js.map} +0 -0
  292. /package/dist/{chunk-PENPHA45.js.map → chunk-FX3UIDCS.js.map} +0 -0
  293. /package/dist/{chunk-H3SEW5HB.js.map → chunk-G3ZMEUWD.js.map} +0 -0
  294. /package/dist/{chunk-ZAZW5LLF.js.map → chunk-GCTZNHDO.js.map} +0 -0
  295. /package/dist/{chunk-D5EXZVQC.js.map → chunk-GDYDYUO7.js.map} +0 -0
  296. /package/dist/{chunk-47F6AI2K.js.map → chunk-GU5XWSH4.js.map} +0 -0
  297. /package/dist/{chunk-6ZGDIN2D.js.map → chunk-H6J6MZ4J.js.map} +0 -0
  298. /package/dist/{chunk-ZUDIY7YP.js.map → chunk-HMS3OCMA.js.map} +0 -0
  299. /package/dist/{chunk-H6K24KLL.js.map → chunk-HUAAYTVS.js.map} +0 -0
  300. /package/dist/{chunk-2DFE4TUE.js.map → chunk-HUDP5NSI.js.map} +0 -0
  301. /package/dist/{chunk-VKYEEJJ2.js.map → chunk-HWJZCZSI.js.map} +0 -0
  302. /package/dist/{chunk-NB2CKJ27.js.map → chunk-ICGLT356.js.map} +0 -0
  303. /package/dist/{chunk-CW3VJARJ.js.map → chunk-IYXP6OR5.js.map} +0 -0
  304. /package/dist/{chunk-A5YEUQOY.js.map → chunk-JSJS7RHS.js.map} +0 -0
  305. /package/dist/{chunk-NHXIFF4Y.js.map → chunk-K6J7JKZM.js.map} +0 -0
  306. /package/dist/{chunk-LLLSK7UQ.js.map → chunk-K7HPGV5K.js.map} +0 -0
  307. /package/dist/{chunk-F3BICEMK.js.map → chunk-KC3S3OH6.js.map} +0 -0
  308. /package/dist/{chunk-HZIIDYJV.js.map → chunk-KEMD6B3W.js.map} +0 -0
  309. /package/dist/{chunk-SRR22EW2.js.map → chunk-L34HKPIS.js.map} +0 -0
  310. /package/dist/{chunk-AGETRKC5.js.map → chunk-LG2P6S32.js.map} +0 -0
  311. /package/dist/{chunk-FUIG7QSS.js.map → chunk-LT26SRU5.js.map} +0 -0
  312. /package/dist/{chunk-6QMOJTC6.js.map → chunk-LTC77D4V.js.map} +0 -0
  313. /package/dist/{chunk-QMJI5VHV.js.map → chunk-M3XEJJDE.js.map} +0 -0
  314. /package/dist/{chunk-VWPJX5B3.js.map → chunk-MGIAYREB.js.map} +0 -0
  315. /package/dist/{chunk-VYLC5KAT.js.map → chunk-MLTGIDNB.js.map} +0 -0
  316. /package/dist/{chunk-L2YYIQYR.js.map → chunk-MXJMCTSI.js.map} +0 -0
  317. /package/dist/{chunk-IUQPNAGR.js.map → chunk-NK7DO6A2.js.map} +0 -0
  318. /package/dist/{chunk-TKLQWOTY.js.map → chunk-NKND2IMW.js.map} +0 -0
  319. /package/dist/{chunk-XPTYXXMD.js.map → chunk-NUHIPODK.js.map} +0 -0
  320. /package/dist/{chunk-REKDM67V.js.map → chunk-ODGV6Q6U.js.map} +0 -0
  321. /package/dist/{chunk-WRGNEAUZ.js.map → chunk-OJYLLNQN.js.map} +0 -0
  322. /package/dist/{chunk-NCAMIRFB.js.map → chunk-OQT3G55N.js.map} +0 -0
  323. /package/dist/{chunk-BPLSGN4X.js.map → chunk-PORGC5MH.js.map} +0 -0
  324. /package/dist/{chunk-BFNBYT62.js.map → chunk-PRBJ4BJD.js.map} +0 -0
  325. /package/dist/{chunk-4IPP2P74.js.map → chunk-PU5PNTE2.js.map} +0 -0
  326. /package/dist/{chunk-L3AM6EGU.js.map → chunk-PZEDIO72.js.map} +0 -0
  327. /package/dist/{chunk-M7VSXBUL.js.map → chunk-RTBCWDJ3.js.map} +0 -0
  328. /package/dist/{chunk-OTHHO3KI.js.map → chunk-S2I5MYSA.js.map} +0 -0
  329. /package/dist/{chunk-FHEVZQQY.js.map → chunk-S447GUNV.js.map} +0 -0
  330. /package/dist/{chunk-WKT7NNNR.js.map → chunk-SP3AFEB7.js.map} +0 -0
  331. /package/dist/{chunk-KMGAFLCK.js.map → chunk-SQWXF2HP.js.map} +0 -0
  332. /package/dist/{chunk-HRSEAGLI.js.map → chunk-TTGZ6KGY.js.map} +0 -0
  333. /package/dist/{chunk-MQFKH3ZJ.js.map → chunk-UHFF4G53.js.map} +0 -0
  334. /package/dist/{chunk-FGZ7GJXO.js.map → chunk-VZEBHQRT.js.map} +0 -0
  335. /package/dist/{chunk-OIW75CLW.js.map → chunk-WN377AAV.js.map} +0 -0
  336. /package/dist/{chunk-ESXVNASI.js.map → chunk-XCNYOVFV.js.map} +0 -0
  337. /package/dist/{chunk-YOMI3ZCA.js.map → chunk-YIC34H3M.js.map} +0 -0
  338. /package/dist/{chunk-GWJJ5CK3.js.map → chunk-Z45PK2H5.js.map} +0 -0
  339. /package/dist/{chunk-RT7CWTUG.js.map → chunk-ZI43U6FN.js.map} +0 -0
  340. /package/dist/{chunk-WFC2GHJG.js.map → chunk-ZJJ46LNY.js.map} +0 -0
  341. /package/dist/{chunk-3ENNPCIW.js.map → chunk-ZY6P7M52.js.map} +0 -0
  342. /package/dist/{classified-marker-EPL2NX3H.js.map → classified-marker-DLLGRRXG.js.map} +0 -0
  343. /package/dist/{collection-facade-3DN4ETEP.js.map → collection-facade-OHBCHCJV.js.map} +0 -0
  344. /package/dist/{computed-UXN4AMI5.js.map → computed-X2RKYFGX.js.map} +0 -0
  345. /package/dist/{dead-filter-56AYTNAO.js.map → dead-filter-CCLDPNTJ.js.map} +0 -0
  346. /package/dist/{delegation-MCCWCFZA.js.map → delegation-OSXUSSUO.js.map} +0 -0
  347. /package/dist/{derive-BSAF6N5X.js.map → derive-6K35IOIN.js.map} +0 -0
  348. /package/dist/{dispatch-UPZW4MAO.js.map → dispatch-TRXQIBLA.js.map} +0 -0
  349. /package/dist/{enclave-CCXI3WEU.js.map → enclave-K33BCSHB.js.map} +0 -0
  350. /package/dist/{executor-6YQYFGHK.js.map → executor-44ONIZTV.js.map} +0 -0
  351. /package/dist/{executor-GLKPMISJ.js.map → executor-H7KLBIJN.js.map} +0 -0
  352. /package/dist/{executor-ZEIX7Y7I.js.map → executor-PDK7IAPQ.js.map} +0 -0
  353. /package/dist/{export-accessible-SDIQEFHQ.js.map → export-accessible-2LJH6JTI.js.map} +0 -0
  354. /package/dist/{extract-partition-K232SO2V.js.map → extract-partition-QQFOPCJ6.js.map} +0 -0
  355. /package/dist/{fanout-sidecar-2EHAV6UP.js.map → fanout-sidecar-ORVUHI3J.js.map} +0 -0
  356. /package/dist/{find-GKFC5753.js.map → find-H6GHRBNL.js.map} +0 -0
  357. /package/dist/{issue-QTQYQJCB.js.map → issue-LV2IWCKY.js.map} +0 -0
  358. /package/dist/{ledger-TZIDVW22.js.map → ledger-RM5672K4.js.map} +0 -0
  359. /package/dist/{liberate-FOK7RFYQ.js.map → liberate-PNPIQ45H.js.map} +0 -0
  360. /package/dist/{link-set-VOMRQB2H.js.map → link-set-AZ6VDH5X.js.map} +0 -0
  361. /package/dist/{managed-secret-N6FWB5LX.js.map → managed-secret-QZKTYCLD.js.map} +0 -0
  362. /package/dist/{migrate-cek-UEO2EUWI.js.map → migrate-cek-BVAPYJ5T.js.map} +0 -0
  363. /package/dist/{noydb-3BBLBSHI.js.map → noydb-QZN7G26J.js.map} +0 -0
  364. /package/dist/{pod-handle-D6ZRTO4N.js.map → pod-handle-LVSMK4XC.js.map} +0 -0
  365. /package/dist/{post-register-XVGHYYSB.js.map → post-register-TZGQ34YR.js.map} +0 -0
  366. /package/dist/{register-FVUE46K4.js.map → register-IQJGJSQQ.js.map} +0 -0
  367. /package/dist/{registry-7PBVHSD5.js.map → registry-3JY3YSMU.js.map} +0 -0
  368. /package/dist/{registry-CCXD57GV.js.map → registry-G365BQDC.js.map} +0 -0
  369. /package/dist/{registry-K75FRKSU.js.map → registry-HVS6PGHV.js.map} +0 -0
  370. /package/dist/{registry-KZYPKIOF.js.map → registry-TQ5FRB4T.js.map} +0 -0
  371. /package/dist/{request-withdrawal-WS7PXD7B.js.map → request-withdrawal-XQCCKMB3.js.map} +0 -0
  372. /package/dist/{reveal-Z62PLVJT.js.map → reveal-5PXWDCLZ.js.map} +0 -0
  373. /package/dist/{revoke-JH4VQTJ3.js.map → revoke-6NSQWTED.js.map} +0 -0
  374. /package/dist/{signer-AFV6AXSN.js.map → signer-AJ3MCSPI.js.map} +0 -0
  375. /package/dist/{stale-FVK3WRMM.js.map → stale-KQR5QAYJ.js.map} +0 -0
  376. /package/dist/{storage-EIM5HO2O.js.map → storage-GACYAH6W.js.map} +0 -0
  377. /package/dist/{store-coordination-provider-HIPOZMC2.js.map → store-coordination-provider-RII4H3PJ.js.map} +0 -0
  378. /package/dist/{verify-KYICK5IW.js.map → verify-OMPYUO7C.js.map} +0 -0
  379. /package/dist/{walk-FV6JFWXV.js.map → walk-ZYC74R65.js.map} +0 -0
  380. /package/dist/{withdraw-accessible-JYX3SPVY.js.map → withdraw-accessible-MEFFAGRD.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/kernel/enclave/crypto.ts"],"sourcesContent":["/**\n * Cryptographic primitives — thin wrappers around the Web Crypto API.\n *\n * ## Design principle\n *\n * **Zero npm crypto dependencies.** Every operation uses `globalThis.crypto.subtle`,\n * which is available natively in Node.js ≥ 18, all modern browsers, and\n * Deno/Bun. This avoids supply-chain risk from third-party crypto packages and\n * ensures the library stays auditable.\n *\n * ## Algorithms\n *\n * | Use case | Algorithm | Parameters |\n * |----------|-----------|------------|\n * | Key derivation | PBKDF2-SHA256 | 600,000 iterations, 32-byte salt |\n * | Record encryption | AES-256-GCM | 12-byte random IV per operation |\n * | DEK wrapping | AES-KW (RFC 3394) | 256-bit KEK |\n * | Binary encrypt | AES-256-GCM | same as record encryption |\n * | Integrity | HMAC-SHA256 | for presence channels |\n * | Content hash | SHA-256 | for ledger and bundle integrity |\n *\n * ## Key lifecycle\n *\n * ```\n * secret + salt\n * └─► deriveKey() → KEK (CryptoKey, extractable: false)\n * └─► wrapKey() → wrapped DEK bytes [stored in keyring]\n * └─► unwrapKey() → DEK (CryptoKey) [memory only during session]\n * └─► encrypt() / decrypt() → ciphertext / plaintext\n * ```\n *\n * IVs are generated fresh by {@link generateIV} on every encrypt call.\n * Reusing an IV with the same key would break GCM's authentication guarantee —\n * this function should be the only place IVs are produced.\n *\n * @module\n */\n\nimport { DecryptionError, InvalidKeyError, TamperedError, ValidationError } from '../errors.js'\n\n/**\n * **EnclaveKey** — the opaque key type at the enclave seam.\n *\n * In noy-db's reference enclave this is `CryptoKey` (the Web Crypto API's\n * key handle). A fork's enclave redefines this alias to its own key\n * representation (e.g. `type EnclaveKey = null` for a keyless HSM-backed\n * fork) — outside `kernel/enclave/**`, every consumer must treat it as\n * opaque: never construct, inspect, or serialize it directly, only pass it\n * between barrel functions (`encrypt`/`decrypt`/`wrapKey`/`unwrapKey`/…).\n */\nexport type EnclaveKey = CryptoKey\n\nconst PBKDF2_ITERATIONS = 600_000\nconst SALT_BYTES = 32\nconst IV_BYTES = 12\nconst KEY_BITS = 256\n\nconst subtle = globalThis.crypto.subtle\n\n// ─── Key Derivation ────────────────────────────────────────────────────\n\n/** Derive a KEK from a secret and salt using PBKDF2-SHA256. */\nexport async function deriveKey(\n secret: string,\n salt: Uint8Array,\n): Promise<CryptoKey> {\n return deriveKekFromMaterial(new TextEncoder().encode(secret), salt)\n}\n\n/**\n * Shared PBKDF2 → AES-KW derivation core. `material` is the raw\n * pre-KDF input bytes (a UTF-8 phrase for standard mode, an\n * AG-1-encoded 3-part structure for echo mode).\n */\nasync function deriveKekFromMaterial(\n material: Uint8Array,\n salt: Uint8Array,\n): Promise<CryptoKey> {\n const keyMaterial = await subtle.importKey('raw', material as BufferSource, 'PBKDF2', false, ['deriveKey'])\n return subtle.deriveKey(\n { name: 'PBKDF2', salt: salt as BufferSource, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },\n keyMaterial,\n { name: 'AES-KW', length: KEY_BITS },\n false,\n ['wrapKey', 'unwrapKey'],\n )\n}\n\n/** One three-part echo secret: prompt (typed) → echo (revealed) → key (typed). */\nexport interface EchoSecretParts {\n readonly prompt: string\n readonly echo: string\n readonly key: string\n}\n\n/**\n * Domain context for the AG-1 encoding. The leading `0xFF` is the load-bearing\n * byte: it is not a legal UTF-8 lead byte, so `TextEncoder` can never emit it —\n * no string's UTF-8 encoding can equal an AG-1 encoding, whatever the string.\n */\nconst ECHO_KDF_CONTEXT = new Uint8Array([0xff, ...new TextEncoder().encode('noydb-echo-secret-v1')])\n\n/**\n * AG-1 encoding: domain context + 4-byte big-endian length prefix per\n * part. Two independent guarantees make a single typed string unable to\n * derive an echo vault's KEK (spec AG-1):\n *\n * 1. The `0xFF` context prefix — UTF-8 never produces that byte, so the\n * encoding is provably not the encoding of ANY string (not merely of\n * no separator-joined form).\n * 2. Structural length prefixes — part boundaries are key material, so\n * re-splitting the same characters changes the derived KEK.\n *\n * @throws ValidationError when any part is not a string — the single\n * chokepoint every echo KEK derivation and block mint passes through, so a\n * malformed parts object cannot be `TextEncoder`-coerced into key material.\n */\nexport function encodeEchoParts(parts: EchoSecretParts): Uint8Array {\n for (const name of ['prompt', 'echo', 'key'] as const) {\n if (typeof parts?.[name] !== 'string') {\n throw new ValidationError('echo secret parts must be three strings: prompt, echo, key')\n }\n }\n const enc = new TextEncoder()\n const segments = [parts.prompt, parts.echo, parts.key].map((p) => enc.encode(p))\n const total = ECHO_KDF_CONTEXT.length + segments.reduce((n, s) => n + 4 + s.length, 0)\n const out = new Uint8Array(total)\n out.set(ECHO_KDF_CONTEXT, 0)\n let offset = ECHO_KDF_CONTEXT.length\n for (const s of segments) {\n new DataView(out.buffer).setUint32(offset, s.length, false)\n out.set(s, offset + 4)\n offset += 4 + s.length\n }\n return out\n}\n\n/** Derive the tier-1 KEK from a 3-part echo secret (spec: KEK from ALL parts). */\nexport async function deriveEchoKey(\n parts: EchoSecretParts,\n salt: Uint8Array,\n): Promise<CryptoKey> {\n return deriveKekFromMaterial(encodeEchoParts(parts), salt)\n}\n\n/**\n * Which AES algorithm/usage a {@link deriveSecretKey} result is for:\n * `'aes-kw'` mints a key-wrapping key (`wrapKey`/`unwrapKey`, e.g. for\n * KEK derivation); `'aes-gcm'` mints a direct encrypt/decrypt key (e.g.\n * for the wrap-DEKs primitive in `with-party/team/wrapped-deks.ts`).\n */\nexport type SecretKeyUsage = 'aes-kw' | 'aes-gcm'\n\n/**\n * Derive a non-extractable AES key from a secret/credential and salt\n * via PBKDF2-SHA256, generalizing {@link deriveKey}'s AES-KW derivation to\n * also cover AES-GCM-usage keys. Callers pin their own `iterations` and\n * `keyUsage` so an existing call site's exact parameters (and thus its\n * derived-key bytes) are preserved verbatim when migrated onto this\n * shared primitive — this is call-site consolidation, not a KDF change.\n */\nexport async function deriveSecretKey(\n secret: string,\n salt: Uint8Array,\n params: { iterations: number; keyUsage: SecretKeyUsage },\n): Promise<CryptoKey> {\n const keyMaterial = await subtle.importKey(\n 'raw',\n new TextEncoder().encode(secret),\n 'PBKDF2',\n false,\n ['deriveKey'],\n )\n\n return params.keyUsage === 'aes-gcm'\n ? subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: salt as BufferSource,\n iterations: params.iterations,\n hash: 'SHA-256',\n },\n keyMaterial,\n { name: 'AES-GCM', length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n )\n : subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: salt as BufferSource,\n iterations: params.iterations,\n hash: 'SHA-256',\n },\n keyMaterial,\n { name: 'AES-KW', length: KEY_BITS },\n false,\n ['wrapKey', 'unwrapKey'],\n )\n}\n\n// ─── DEK Generation ────────────────────────────────────────────────────\n\n/** Generate a random AES-256-GCM data encryption key. */\nexport async function generateDEK(): Promise<CryptoKey> {\n return subtle.generateKey(\n { name: 'AES-GCM', length: KEY_BITS },\n true, // extractable — needed for AES-KW wrapping\n ['encrypt', 'decrypt'],\n )\n}\n\n// ─── Key Wrapping ──────────────────────────────────────────────────────\n\n/** Wrap (encrypt) a DEK with a KEK using AES-KW. Returns base64 string. */\nexport async function wrapKey(dek: CryptoKey, kek: CryptoKey): Promise<string> {\n const wrapped = await subtle.wrapKey('raw', dek, kek, 'AES-KW')\n return bufferToBase64(wrapped)\n}\n\n/** Unwrap (decrypt) a DEK from base64 string using a KEK. */\nexport async function unwrapKey(\n wrappedBase64: string,\n kek: CryptoKey,\n): Promise<CryptoKey> {\n try {\n return await subtle.unwrapKey(\n 'raw',\n base64ToBuffer(wrappedBase64) as BufferSource,\n kek,\n 'AES-KW',\n { name: 'AES-GCM', length: KEY_BITS },\n true,\n ['encrypt', 'decrypt'],\n )\n } catch {\n throw new InvalidKeyError()\n }\n}\n\n// ─── Per-record CEK wrapping ───────────────────────────────────────────\n\n/**\n * Derive a **dedicated** AES-KW wrapping key from a collection/tier DEK via\n * HKDF-SHA256, used to wrap/unwrap a per-record CEK.\n *\n * The collection/tier DEKs are AES-256-**GCM** keys (usages\n * `encrypt`/`decrypt`) and cannot themselves act as an AES-KW KEK. We do NOT\n * re-import the raw DEK bytes directly as an AES-KW key — that would reuse one\n * key across two primitives (AES-GCM for `_det`/presence, AES-KW for CEK\n * wrapping), violating key separation. Instead we HKDF-derive a domain-\n * separated KW key (salt `noydb-cek-wrap`), exactly as `derivePresenceKey`\n * derives a separate presence key. The derivation is deterministic, so\n * wrapping the same CEK under the same DEK always yields identical ciphertext\n * — which is what lets an update reuse a record's stable CEK and produce a\n * byte-identical `_cek`. The KW key is independent of the DEK's GCM key.\n *\n * The DEK must be extractable (it is — `generateDEK`/`unwrapKey` mint\n * extractable keys).\n */\nasync function asKwKey(dek: CryptoKey): Promise<CryptoKey> {\n const rawDek = await subtle.exportKey('raw', dek)\n const hkdfKey = await subtle.importKey('raw', rawDek, 'HKDF', false, ['deriveBits'])\n const salt = new TextEncoder().encode('noydb-cek-wrap')\n const info = new TextEncoder().encode('v1')\n const bits = await subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n hkdfKey,\n KEY_BITS,\n )\n return subtle.importKey('raw', bits, 'AES-KW', false, ['wrapKey', 'unwrapKey'])\n}\n\n/**\n * AES-KW-wrap a per-record CEK under a collection/tier DEK. Returns base64.\n * Deterministic over `(cek, dek)`.\n */\nexport async function wrapCek(cek: CryptoKey, dek: CryptoKey): Promise<string> {\n const kw = await asKwKey(dek)\n const wrapped = await subtle.wrapKey('raw', cek, kw, 'AES-KW')\n return bufferToBase64(wrapped)\n}\n\n/**\n * Unwrap a per-record CEK from base64 under a collection/tier DEK. Throws\n * `InvalidKeyError` if the wrapped bytes do not authenticate under the DEK.\n */\nexport async function unwrapCek(wrappedBase64: string, dek: CryptoKey): Promise<CryptoKey> {\n const kw = await asKwKey(dek)\n try {\n return await subtle.unwrapKey(\n 'raw',\n base64ToBuffer(wrappedBase64) as BufferSource,\n kw,\n 'AES-KW',\n { name: 'AES-GCM', length: KEY_BITS },\n true,\n ['encrypt', 'decrypt'],\n )\n } catch {\n throw new InvalidKeyError()\n }\n}\n\n/**\n * Import a raw 32-byte AES-256-GCM record CEK (e.g. from a sealed-CEK\n * delivery binding). Non-extractable, decrypt-only — the imported key is\n * used solely to open the record's `_iv`/`_data` body under `decrypt()`.\n */\nexport async function importCek(rawKey: Uint8Array): Promise<CryptoKey> {\n return subtle.importKey('raw', rawKey as BufferSource, { name: 'AES-GCM', length: KEY_BITS }, false, ['decrypt'])\n}\n\n// ─── Encrypt / Decrypt ─────────────────────────────────────────────────\n\nexport interface EncryptResult {\n iv: string // base64\n data: string // base64\n}\n\n/**\n * Encrypt plaintext JSON string with AES-256-GCM. Fresh IV per call.\n *\n * `aad` binds the record's identity into the auth tag (#1041) — see\n * `record-aad.ts` for what is bound and why `_v` is not. A body sealed with\n * AAD can only be opened by a reader supplying the identical bytes, which is\n * what stops an untrusted store from relocating or re-tiering an envelope.\n *\n * Optional **only while the call-site sweep is in progress**. It becomes\n * mandatory once every `encrypt`/`decrypt` pair supplies it, at which point\n * the format version bumps and the reader rejects anything unbound. Until\n * then an omitted `aad` reproduces the previous, unauthenticated behaviour.\n */\nexport async function encrypt(\n plaintext: string,\n dek: CryptoKey,\n aad?: Uint8Array,\n): Promise<EncryptResult> {\n const iv = generateIV()\n const encoded = new TextEncoder().encode(plaintext)\n\n const ciphertext = await subtle.encrypt(\n {\n name: 'AES-GCM',\n iv: iv as BufferSource,\n ...(aad !== undefined && { additionalData: aad as BufferSource }),\n },\n dek,\n encoded,\n )\n\n return {\n iv: bufferToBase64(iv),\n data: bufferToBase64(ciphertext),\n }\n}\n\n/**\n * Decrypt AES-256-GCM ciphertext. Throws on wrong key or tampered data.\n *\n * `aad` must be byte-identical to what {@link encrypt} was given, or the auth\n * tag fails and this throws `TamperedError` (#1041). Note the asymmetry that\n * makes this useful: a mismatched identity is indistinguishable from a\n * corrupted body, so relocation fails **closed** rather than returning a\n * plausible record in the wrong place.\n */\nexport async function decrypt(\n ivBase64: string,\n dataBase64: string,\n dek: CryptoKey,\n aad?: Uint8Array,\n): Promise<string> {\n const iv = base64ToBuffer(ivBase64)\n const ciphertext = base64ToBuffer(dataBase64)\n\n try {\n const plaintext = await subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: iv as BufferSource,\n ...(aad !== undefined && { additionalData: aad as BufferSource }),\n },\n dek,\n ciphertext as BufferSource,\n )\n return new TextDecoder().decode(plaintext)\n } catch (err) {\n if (err instanceof Error && err.name === 'OperationError') {\n throw new TamperedError(...(await classifyTagFailure(iv, ciphertext, dek, aad)))\n }\n throw new DecryptionError(\n err instanceof Error ? err.message : 'Decryption failed',\n )\n }\n}\n\n\n/**\n * Distinguish a FORMAT TRANSITION from an attack, when the enclave can (#1103).\n *\n * ## The problem\n *\n * Since #1041 switched identity AAD on, one `TamperedError` covers at least\n * four situations: legitimate pre-binding data, a store that reconstructs an\n * envelope and drops a bound field, a CEK/rotation mismatch, and actual\n * tampering. `SECURITY.md` and the subsystem docs teach the LAST reading — so a\n * user who upgrades, hits this on their own honest data, and consults the docs\n * is told their store has been compromised.\n *\n * That is a false positive on the product's central security claim, and the\n * cost is not merely a confusing message: **a tamper alarm that cries wolf is\n * one users learn to ignore.**\n *\n * ## Why the probe is sound, and why it is NOT a downgrade\n *\n * A body sealed before #1041 carries no AAD, so it opens under an empty one.\n * Retrying that way is **positive evidence** of the legacy format rather than a\n * guess: forging a body that decrypts under this DEK requires the DEK, and an\n * untrusted store does not hold one.\n *\n * ⚠️ **Classification ONLY — the plaintext is discarded and the caller still\n * throws.** That is the entire safety argument: the outcome is identical either\n * way, so this cannot become the lenient path #1041 exists to remove. A variant\n * that RETURNED the retry's plaintext would be exactly the accept-without-AAD\n * downgrade the binding was built to prevent. Do not \"optimise\" it into one.\n *\n * Note what the honest message concedes: pre-#1041 data had no authenticated\n * metadata, so a legacy record that was ALSO tampered with reads as legacy.\n * That is not a weakening — it is an accurate statement about data that\n * genuinely never carried a binding.\n */\nasync function classifyTagFailure(\n iv: Uint8Array,\n ciphertext: Uint8Array,\n dek: CryptoKey,\n aad: Uint8Array | undefined,\n): Promise<[] | [string, 'unbound-legacy-format']> {\n // Only meaningful when AAD was supplied: with none there is no second\n // interpretation to test, and the failure is a plain tag mismatch.\n if (aad === undefined) return []\n try {\n await subtle.decrypt({ name: 'AES-GCM', iv: iv as BufferSource }, dek, ciphertext as BufferSource)\n } catch {\n return [] // no benign explanation — the security alert stands\n }\n return [\n 'This record was sealed BEFORE record-identity binding (#1041) and cannot be read by this ' +\n 'version. Its body decrypts correctly under the record key, so this is a data-format ' +\n 'transition, not tampering — but it also means the record predates authenticated metadata. ' +\n 'There is no migration path; see noy-db #1100.',\n 'unbound-legacy-format',\n ]\n}\n\n// ─── Binary Encrypt / Decrypt ────────\n\n/**\n * Encrypt raw bytes with AES-256-GCM using a fresh random IV.\n * Used by the attachment store so binary blobs avoid double base64 encoding\n * (the existing `encrypt()` function calls `TextEncoder` on a string — here\n * we pass the `Uint8Array` directly to `subtle.encrypt`).\n */\nexport async function encryptBytes(\n data: Uint8Array,\n dek: CryptoKey,\n): Promise<EncryptResult> {\n const iv = generateIV()\n const ciphertext = await subtle.encrypt(\n { name: 'AES-GCM', iv: iv as BufferSource },\n dek,\n data as unknown as BufferSource,\n )\n return {\n iv: bufferToBase64(iv),\n data: bufferToBase64(ciphertext),\n }\n}\n\n/**\n * Decrypt AES-256-GCM ciphertext back to raw bytes.\n * Counterpart to `encryptBytes`. Throws `TamperedError` on auth-tag failure.\n */\nexport async function decryptBytes(\n ivBase64: string,\n dataBase64: string,\n dek: CryptoKey,\n): Promise<Uint8Array> {\n const iv = base64ToBuffer(ivBase64)\n const ciphertext = base64ToBuffer(dataBase64)\n try {\n const plaintext = await subtle.decrypt(\n { name: 'AES-GCM', iv: iv as BufferSource },\n dek,\n ciphertext as BufferSource,\n )\n return new Uint8Array(plaintext)\n } catch (err) {\n if (err instanceof Error && err.name === 'OperationError') {\n throw new TamperedError()\n }\n throw new DecryptionError(\n err instanceof Error ? err.message : 'Decryption failed',\n )\n }\n}\n\n/**\n * SHA-256 hex digest of raw bytes. Used to derive content-addressed\n * eTags for blob deduplication. Computed on plaintext bytes\n * before compression and encryption so the eTag identifies content, not\n * ciphertext, and survives re-encryption (key rotation, re-upload).\n */\nexport async function sha256Hex(data: Uint8Array): Promise<string> {\n const hash = await subtle.digest('SHA-256', data as unknown as BufferSource)\n return Array.from(new Uint8Array(hash))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n// ─── HMAC-SHA-256 ─────────────────────────────\n\n/**\n * Compute HMAC-SHA-256(key, data) and return hex string.\n *\n * Used to derive content-addressed eTags that are opaque to the store:\n * ```\n * eTag = hmacSha256Hex(blobDEK, plaintext)\n * ```\n *\n * Unlike a plain SHA-256, the HMAC is keyed by the vault-shared `_blob` DEK,\n * so an attacker with store access cannot pre-compute eTags for known files.\n * Deduplication still works within a vault (same key + same content = same eTag).\n */\n/**\n * Derive the blob CONTENT-ADDRESSING key for one tier (#1126).\n *\n * The blob eTag is an HMAC over the plaintext. It used to be keyed by the\n * `_blob` DEK — the very key `rotateKeys` replaces — so after any rotation\n * `HMAC(live DEK, plaintext) !== storedETag` for every blob written before it,\n * permanently. `decryptResponse()` checks that unconditionally, so the\n * presigned-URL read path raised `TamperedError` on legitimate data forever;\n * dedup also split, minting a second address for identical bytes.\n *\n * The fix is a `root` that rotation never touches (`_blob_addr`, refused by\n * `rotateKeys` exactly as `_roster` is). Rotation then re-keys chunk BODIES\n * while every address stays stable, which is what makes the AAD\n * `{eTag}:{i}:{count}` and every `_blob_index` / `_blob_slots_*` /\n * `_blob_versions_*` row survive it untouched.\n *\n * **Derived PER TIER, deliberately.** A single vault-wide address would make an\n * elevated blob and a tier-0 blob with identical content share an eTag,\n * leaking equality across a boundary the tier system exists to enforce — and\n * `rehomeForTier` re-addresses on a tier move precisely because the address is\n * tier-scoped today. Domain separation keeps that property while removing the\n * rotation coupling: the two are independent axes, and only one of them was\n * ever meant to change the address.\n *\n * Same HKDF idiom as `asKwKey`, with its own salt so the addressing key can\n * never coincide with a wrapping or encryption key.\n */\nexport async function deriveBlobAddressKey(root: CryptoKey, tier: number): Promise<CryptoKey> {\n const rawRoot = await subtle.exportKey('raw', root)\n const hkdfKey = await subtle.importKey('raw', rawRoot, 'HKDF', false, ['deriveBits'])\n const salt = new TextEncoder().encode('noydb-blob-address')\n const info = new TextEncoder().encode(`tier:${tier}`)\n const bits = await subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info }, hkdfKey, KEY_BITS)\n // Imported as AES-GCM only because `hmacSha256Hex` re-exports raw and\n // re-imports as HMAC; the algorithm tag here is a carrier, never used to\n // encrypt anything.\n return subtle.importKey('raw', bits, { name: 'AES-GCM' }, true, ['encrypt', 'decrypt'])\n}\n\nexport async function hmacSha256Hex(key: CryptoKey, data: Uint8Array): Promise<string> {\n // Export AES-GCM DEK raw bytes → import as HMAC key\n const rawKey = await subtle.exportKey('raw', key)\n const hmacKey = await subtle.importKey(\n 'raw',\n rawKey,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n )\n const sig = await subtle.sign('HMAC', hmacKey, data as unknown as BufferSource)\n return Array.from(new Uint8Array(sig))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n// ─── AAD-aware Binary Encrypt / Decrypt ──\n\n/**\n * Encrypt raw bytes with AES-256-GCM using Additional Authenticated Data.\n *\n * The AAD binds each chunk to its parent blob and position, preventing\n * chunk reorder, substitution, and truncation attacks:\n * ```\n * AAD = UTF-8(\"{eTag}:{chunkIndex}:{chunkCount}\")\n * ```\n *\n * The AAD is NOT stored — the reader reconstructs it from `BlobObject`\n * metadata and passes it to `decryptBytesWithAAD`.\n */\nexport async function encryptBytesWithAAD(\n data: Uint8Array,\n dek: CryptoKey,\n aad: Uint8Array,\n): Promise<EncryptResult> {\n const iv = generateIV()\n const ciphertext = await subtle.encrypt(\n {\n name: 'AES-GCM',\n iv: iv as BufferSource,\n additionalData: aad as BufferSource,\n },\n dek,\n data as unknown as BufferSource,\n )\n return {\n iv: bufferToBase64(iv),\n data: bufferToBase64(ciphertext),\n }\n}\n\n/**\n * Decrypt AES-256-GCM ciphertext with AAD verification.\n *\n * If the AAD does not match the one used at encryption time (e.g. because\n * a chunk was reordered or substituted from another blob), the GCM auth\n * tag fails and this throws `TamperedError`.\n */\nexport async function decryptBytesWithAAD(\n ivBase64: string,\n dataBase64: string,\n dek: CryptoKey,\n aad: Uint8Array,\n): Promise<Uint8Array> {\n const iv = base64ToBuffer(ivBase64)\n const ciphertext = base64ToBuffer(dataBase64)\n try {\n const plaintext = await subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: iv as BufferSource,\n additionalData: aad as BufferSource,\n },\n dek,\n ciphertext as BufferSource,\n )\n return new Uint8Array(plaintext)\n } catch (err) {\n if (err instanceof Error && err.name === 'OperationError') {\n throw new TamperedError()\n }\n throw new DecryptionError(\n err instanceof Error ? err.message : 'Decryption failed',\n )\n }\n}\n\n// ─── Presence Key Derivation ──────────────────────────────\n\n/**\n * Derive an AES-256-GCM presence key from a collection DEK using HKDF-SHA256.\n *\n * The presence key is domain-separated from the data DEK by the fixed salt\n * `'noydb-presence'` and the `info` = collection name. This means:\n * - The adapter never sees the presence key.\n * - Presence payloads rotate automatically when the collection DEK is rotated.\n * - Revoked users cannot derive the new presence key after a DEK rotation.\n *\n * @param dek The collection's AES-256-GCM DEK (extractable).\n * @param collectionName Used as the HKDF `info` parameter for domain separation.\n * @returns A non-extractable AES-256-GCM key suitable for presence payload encryption.\n */\nexport async function derivePresenceKey(dek: CryptoKey, collectionName: string): Promise<CryptoKey> {\n // Step 1: export DEK raw bytes\n const rawDek = await subtle.exportKey('raw', dek)\n\n // Step 2: import as HKDF key material\n const hkdfKey = await subtle.importKey(\n 'raw',\n rawDek,\n 'HKDF',\n false,\n ['deriveBits'],\n )\n\n // Step 3: derive 256 bits with salt='noydb-presence' and info=collectionName\n const salt = new TextEncoder().encode('noydb-presence')\n const info = new TextEncoder().encode(collectionName)\n const bits = await subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n hkdfKey,\n KEY_BITS,\n )\n\n // Step 4: import derived bits as AES-GCM key\n return subtle.importKey(\n 'raw',\n bits,\n { name: 'AES-GCM', length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n )\n}\n\n// ─── Sealed Field Key Derivation ──────────────────────────\n\n/**\n * Derive a **per-field** AES-256-GCM key from a collection DEK using\n * HKDF-SHA256, used to encrypt a single sensitive field into its own\n * `_sealed[field]` envelope slot (structural group-encryption).\n *\n * Domain-separated from the data DEK (and from the presence/deterministic\n * channels) by the fixed salt `'noydb-sealed'` and an `info` of\n * `JSON.stringify(['noydb-sealed', collectionName, field])`. The JSON-array\n * encoding is injective — each element is separately quoted/escaped — so\n * collection `a/sealed/b` + field `c` cannot collide with collection `a` +\n * field `b/sealed/c`. Each sensitive field gets a **distinct** key, so a\n * `_sealed[a]` ciphertext does not authenticate under field `b`'s key —\n * sealed fields are cryptographically isolated from one another. The\n * collection name keeps the same field name in two collections from sharing a\n * key, mirroring how `derivePresenceKey` / `encryptDeterministic` domain-separate.\n *\n * @param dek The collection's AES-256-GCM DEK (extractable).\n * @param collectionName Part of the HKDF `info` for domain separation.\n * @param field Sensitive field name — the rest of the `info`.\n * @returns A non-extractable AES-256-GCM key for that field's sealed slot.\n */\nexport async function deriveSealedFieldKey(\n dek: CryptoKey,\n collectionName: string,\n field: string,\n): Promise<CryptoKey> {\n const rawDek = await subtle.exportKey('raw', dek)\n const hkdfKey = await subtle.importKey('raw', rawDek, 'HKDF', false, ['deriveBits'])\n const salt = new TextEncoder().encode('noydb-sealed')\n // JSON-array encoding is injective: each element is separately quoted/\n // escaped, so collection `a/sealed/b` + field `c` cannot collide with\n // collection `a` + field `b/sealed/c`.\n const info = new TextEncoder().encode(JSON.stringify(['noydb-sealed', collectionName, field]))\n const bits = await subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n hkdfKey,\n KEY_BITS,\n )\n return subtle.importKey(\n 'raw',\n bits,\n { name: 'AES-GCM', length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n )\n}\n\n/**\n * Derive a per-record sealed-field key from the record's **per-record CEK**\n * rather than the collection DEK. Same HKDF construction as\n * {@link deriveSealedFieldKey} but with salt `'noydb-sealed-cek'` (distinct\n * from `'noydb-sealed'`), so a CEK-derived key can never collide with a\n * DEK-derived one for the same `{collection, field}`.\n *\n * The point: the sealed ciphertext's only key now flows from the record's CEK.\n * Dropping the record's wrapped `_cek` (crypto-shred / `forget`) makes the key\n * — and thus `_sealed[field]` — unrecoverable, giving sealed fields the same\n * erasure guarantee `_data` already has. The CEK must be extractable (it is —\n * `unwrapCek`/`generateDEK` mint extractable keys).\n *\n * @param cek The record's AES-256-GCM CEK (extractable).\n * @param collectionName Part of the HKDF `info` for domain separation.\n * @param field Sensitive field name — the rest of the `info`.\n * @returns A non-extractable AES-256-GCM key for that field's sealed slot.\n */\nexport async function deriveSealedFieldKeyFromCek(\n cek: CryptoKey,\n collectionName: string,\n field: string,\n): Promise<CryptoKey> {\n const rawCek = await subtle.exportKey('raw', cek)\n const hkdfKey = await subtle.importKey('raw', rawCek, 'HKDF', false, ['deriveBits'])\n const salt = new TextEncoder().encode('noydb-sealed-cek')\n const info = new TextEncoder().encode(JSON.stringify(['noydb-sealed-cek', collectionName, field]))\n const bits = await subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n hkdfKey,\n KEY_BITS,\n )\n return subtle.importKey(\n 'raw',\n bits,\n { name: 'AES-GCM', length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n )\n}\n\n// ─── Deterministic Encryption ────────────────────────────\n\n/**\n * Derive the collection's **dedicated deterministic-index key** from its DEK\n * via HKDF-SHA256 (L-1, #554).\n *\n * `_det` slots previously encrypted under the raw collection DEK — the same\n * key `_data` uses with a *randomized*-IV regime while `_det` uses a\n * *deterministic*-IV regime. Two IV regimes on one key is avoidable hygiene\n * debt (~2^-96 theoretical collision), so the deterministic index now gets its\n * own HKDF-separated key: salt `'noydb-det'`, info\n * `JSON.stringify(['noydb-det'])` (the injective JSON-array domain tag, same\n * convention as {@link deriveSealedFieldKey}). Per-field separation still\n * comes from the `'<collection>/<field>'` context inside\n * {@link encryptDeterministic}, exactly as before.\n *\n * The derived key stays **DEK-derived (collection-level)** on purpose: `_det`\n * is carried verbatim through per-record CEK rotation (see\n * `record-keys/sealing.ts`), so its key must not depend on the CEK. It rotates\n * with the collection DEK, like the presence key.\n *\n * The key is minted **extractable** — {@link encryptDeterministic} derives its\n * per-value IV via HKDF over the raw key bytes (an `exportKey` under the\n * hood), which a non-extractable key would forbid. Same in-memory posture as\n * the DEK itself (`generateDEK` mints extractable keys).\n *\n * @param dek The collection's AES-256-GCM DEK (extractable).\n * @returns A dedicated AES-256-GCM key for the `_det` deterministic index.\n */\nexport async function deriveDeterministicKey(dek: CryptoKey): Promise<CryptoKey> {\n const rawDek = await subtle.exportKey('raw', dek)\n const hkdfKey = await subtle.importKey('raw', rawDek, 'HKDF', false, ['deriveBits'])\n const salt = new TextEncoder().encode('noydb-det')\n const info = new TextEncoder().encode(JSON.stringify(['noydb-det']))\n const bits = await subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n hkdfKey,\n KEY_BITS,\n )\n return subtle.importKey(\n 'raw',\n bits,\n { name: 'AES-GCM', length: KEY_BITS },\n true,\n ['encrypt', 'decrypt'],\n )\n}\n\n/**\n * Derive a deterministic 12-byte IV from `{ DEK, context, plaintext }`\n * via HKDF-SHA256. Given the same three inputs, the IV is identical, so\n * `encryptDeterministic` produces the same ciphertext on every call —\n * which is precisely what enables blind equality search on encrypted\n * fields.\n *\n * **The side channel this opens.** Two records whose field value is the\n * same produce the same ciphertext. An observer with store access can\n * therefore tell which records share a value — not *what* the value is,\n * but the equivalence class. This is the well-known trade-off of\n * deterministic encryption and is why the feature is strictly opt-in\n * per field, guarded by `acknowledgeDeterministicRisk: true` at\n * collection creation.\n *\n * The context string MUST include the collection name and field name,\n * so:\n * - The same plaintext in two different fields encrypts differently\n * (no cross-field equality leak).\n * - The same plaintext in two different collections (different DEKs)\n * encrypts differently by virtue of the key, even before HKDF\n * domain separation kicks in.\n */\nasync function deriveDeterministicIV(\n dek: CryptoKey,\n context: string,\n plaintext: string,\n): Promise<Uint8Array> {\n const rawDek = await subtle.exportKey('raw', dek)\n const hkdfKey = await subtle.importKey('raw', rawDek, 'HKDF', false, ['deriveBits'])\n const salt = new TextEncoder().encode('noydb-deterministic-v1')\n const info = new TextEncoder().encode(`${context}\\x00${plaintext}`)\n const bits = await subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n hkdfKey,\n IV_BYTES * 8,\n )\n return new Uint8Array(bits)\n}\n\n/**\n * Encrypt a plaintext string with AES-256-GCM and a deterministic,\n * HKDF-derived IV.\n *\n * The same `{ dek, context, plaintext }` triple always produces the\n * same `{ iv, data }` — call this twice and you can string-compare the\n * ciphertexts to check equality of the inputs without decrypting them.\n *\n * @param context Domain-separation string — by convention\n * `'<collection>/<field>'`. Different contexts encrypt\n * the same plaintext to different ciphertexts, so\n * `email` in collection `users` does not collide with\n * `email` in collection `customers`.\n */\nexport async function encryptDeterministic(\n plaintext: string,\n dek: CryptoKey,\n context: string,\n): Promise<EncryptResult> {\n const iv = await deriveDeterministicIV(dek, context, plaintext)\n const encoded = new TextEncoder().encode(plaintext)\n const ciphertext = await subtle.encrypt(\n { name: 'AES-GCM', iv: iv as BufferSource },\n dek,\n encoded,\n )\n return {\n iv: bufferToBase64(iv),\n data: bufferToBase64(ciphertext),\n }\n}\n\n/**\n * Counterpart to {@link encryptDeterministic}. The IV is stored\n * alongside the ciphertext (exactly like the randomized path), so\n * decrypt uses the stored IV and verifies the GCM auth tag — a tampered\n * ciphertext throws `TamperedError` just like randomized AES-GCM.\n */\nexport async function decryptDeterministic(\n ivBase64: string,\n dataBase64: string,\n dek: CryptoKey,\n): Promise<string> {\n return decrypt(ivBase64, dataBase64, dek)\n}\n\n// ─── Random Generation ─────────────────────────────────────────────────\n\n/** Generate a random 12-byte IV for AES-GCM. */\nexport function generateIV(): Uint8Array {\n return globalThis.crypto.getRandomValues(new Uint8Array(IV_BYTES))\n}\n\n/** Generate a random 32-byte salt for PBKDF2. */\nexport function generateSalt(): Uint8Array {\n return globalThis.crypto.getRandomValues(new Uint8Array(SALT_BYTES))\n}\n\n// ─── Base64 Helpers ────────────────────────────────────────────────────\n\nexport function bufferToBase64(buffer: ArrayBuffer | Uint8Array): string {\n const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer)\n let binary = ''\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]!)\n }\n return btoa(binary)\n}\n\nexport function base64ToBuffer(base64: string): Uint8Array<ArrayBuffer> {\n const binary = atob(base64)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i)\n }\n return bytes\n}\n"],"mappings":";;;;;;;;AAoDA,IAAM,oBAAoB;AAC1B,IAAM,aAAa;AACnB,IAAM,WAAW;AACjB,IAAM,WAAW;AAEjB,IAAM,SAAS,WAAW,OAAO;AAKjC,eAAsB,UACpB,QACA,MACoB;AACpB,SAAO,sBAAsB,IAAI,YAAY,EAAE,OAAO,MAAM,GAAG,IAAI;AACrE;AAOA,eAAe,sBACb,UACA,MACoB;AACpB,QAAM,cAAc,MAAM,OAAO,UAAU,OAAO,UAA0B,UAAU,OAAO,CAAC,WAAW,CAAC;AAC1G,SAAO,OAAO;AAAA,IACZ,EAAE,MAAM,UAAU,MAA4B,YAAY,mBAAmB,MAAM,UAAU;AAAA,IAC7F;AAAA,IACA,EAAE,MAAM,UAAU,QAAQ,SAAS;AAAA,IACnC;AAAA,IACA,CAAC,WAAW,WAAW;AAAA,EACzB;AACF;AAcA,IAAM,mBAAmB,IAAI,WAAW,CAAC,KAAM,GAAG,IAAI,YAAY,EAAE,OAAO,sBAAsB,CAAC,CAAC;AAiB5F,SAAS,gBAAgB,OAAoC;AAClE,aAAW,QAAQ,CAAC,UAAU,QAAQ,KAAK,GAAY;AACrD,QAAI,OAAO,QAAQ,IAAI,MAAM,UAAU;AACrC,YAAM,IAAI,gBAAgB,4DAA4D;AAAA,IACxF;AAAA,EACF;AACA,QAAM,MAAM,IAAI,YAAY;AAC5B,QAAM,WAAW,CAAC,MAAM,QAAQ,MAAM,MAAM,MAAM,GAAG,EAAE,IAAI,CAAC,MAAM,IAAI,OAAO,CA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AQ,KAAK;AACrC,cAAU,OAAO,aAAa,MAAM,CAAC,CAAE;AAAA,EACzC;AACA,SAAO,KAAK,MAAM;AACpB;AAEO,SAAS,eAAe,QAAyC;AACtE,QAAM,SAAS,KAAK,MAAM;AAC1B,QAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;AAC1C,WAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;AACtC,UAAM,CAAC,IAAI,OAAO,WAAW,CAAC;AAAA,EAChC;AACA,SAAO;AACT;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  LookupHandle
3
- } from "./chunk-2DFE4TUE.js";
3
+ } from "./chunk-HUDP5NSI.js";
4
4
 
5
5
  // src/via/lookup/active.ts
6
6
  function withLookup() {
@@ -33,4 +33,4 @@ function withLookup() {
33
33
  export {
34
34
  withLookup
35
35
  };
36
- //# sourceMappingURL=chunk-VMYXYFPX.js.map
36
+ //# sourceMappingURL=chunk-DBPQUICN.js.map
@@ -5,7 +5,7 @@ import {
5
5
  import {
6
6
  FieldNotQueryableError,
7
7
  IndexRequiredError
8
- } from "./chunk-PKUJ3JLQ.js";
8
+ } from "./chunk-5OFC3QYL.js";
9
9
 
10
10
  // src/with-lookup/indexing/strategy.ts
11
11
  var NO_INDEXING = {
@@ -534,4 +534,4 @@ export {
534
534
  PersistedCollectionIndex,
535
535
  LazyQuery
536
536
  };
537
- //# sourceMappingURL=chunk-3TWEXEKX.js.map
537
+ //# sourceMappingURL=chunk-DL7NXFAY.js.map
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  pickLocale
3
- } from "./chunk-HRSEAGLI.js";
3
+ } from "./chunk-TTGZ6KGY.js";
4
4
  import {
5
5
  sha256Hex
6
- } from "./chunk-O5QXH7U7.js";
6
+ } from "./chunk-D7STIWJO.js";
7
7
  import {
8
8
  PodIntegrityError,
9
9
  PodSealMismatchError,
10
10
  ValidationError
11
- } from "./chunk-PKUJ3JLQ.js";
11
+ } from "./chunk-5OFC3QYL.js";
12
12
 
13
13
  // src/with-pod/format.ts
14
14
  var NOYDB_POD_MAGIC = new Uint8Array([78, 68, 66, 49]);
@@ -812,7 +812,7 @@ async function applySatelliteLivenessFilter(vault, dumpJson) {
812
812
  if (!backup.collections || typeof backup.collections !== "object") return dumpJson;
813
813
  if (typeof vault._introspectState !== "function") return dumpJson;
814
814
  const { adapter, name, getDEK } = vault._introspectState();
815
- const { liveBaseIdSetsForBundle } = await import("./dead-filter-56AYTNAO.js");
815
+ const { liveBaseIdSetsForBundle } = await import("./dead-filter-CCLDPNTJ.js");
816
816
  const satLive = await liveBaseIdSetsForBundle(adapter, name, Object.keys(backup.collections), getDEK);
817
817
  if (satLive.size === 0) return dumpJson;
818
818
  const next = {};
@@ -1059,4 +1059,4 @@ export {
1059
1059
  readPodRedirect,
1060
1060
  readPod
1061
1061
  };
1062
- //# sourceMappingURL=chunk-2VMCJUK6.js.map
1062
+ //# sourceMappingURL=chunk-DM2BZDNV.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  buildRecordEnvelope
3
- } from "./chunk-PENPHA45.js";
3
+ } from "./chunk-FX3UIDCS.js";
4
4
 
5
5
  // src/with-shape/schema-update/fence.ts
6
6
  var FENCE_RECORD_ID = "schema-fence";
@@ -36,4 +36,4 @@ export {
36
36
  loadFence,
37
37
  saveFence
38
38
  };
39
- //# sourceMappingURL=chunk-FFSQFH6D.js.map
39
+ //# sourceMappingURL=chunk-DNKVKO7K.js.map
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  installViaBinder
3
- } from "./chunk-7JOXCSDU.js";
3
+ } from "./chunk-6PLCNLBC.js";
4
4
  import {
5
5
  SealedHandle
6
- } from "./chunk-IGNJOJEP.js";
6
+ } from "./chunk-UJ4Z67UQ.js";
7
7
  import {
8
8
  ClassifiedConfigError,
9
9
  ClassifiedNotEnabledError
10
- } from "./chunk-PKUJ3JLQ.js";
10
+ } from "./chunk-5OFC3QYL.js";
11
11
 
12
12
  // src/via/classified/descriptor.ts
13
13
  function isClassifiedFieldSpec(x) {
@@ -262,4 +262,4 @@ export {
262
262
  enforceClassifiedWrite,
263
263
  NO_CLASSIFIED
264
264
  };
265
- //# sourceMappingURL=chunk-IPA6ODWG.js.map
265
+ //# sourceMappingURL=chunk-E2LYQUB7.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  OverlayIdMismatchError
3
- } from "./chunk-PKUJ3JLQ.js";
3
+ } from "./chunk-5OFC3QYL.js";
4
4
 
5
5
  // src/with-formula/overlay-views/virtual-collection.ts
6
6
  var OverlayedCollection = class {
@@ -206,4 +206,4 @@ var OverlayedCollection = class {
206
206
  export {
207
207
  OverlayedCollection
208
208
  };
209
- //# sourceMappingURL=chunk-ANYVM4SX.js.map
209
+ //# sourceMappingURL=chunk-ENTVT7PF.js.map
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  loadVaultPolicy,
3
3
  saveVaultPolicy
4
- } from "./chunk-3ENNPCIW.js";
4
+ } from "./chunk-ZY6P7M52.js";
5
5
  import {
6
6
  PolicyDeniedError,
7
7
  ValidationError
8
- } from "./chunk-PKUJ3JLQ.js";
8
+ } from "./chunk-5OFC3QYL.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-M3FKPVOU.js.map
367
+ //# sourceMappingURL=chunk-ESP4K32V.js.map
@@ -1,9 +1,11 @@
1
1
  import {
2
2
  sha256Hex
3
- } from "./chunk-O5QXH7U7.js";
3
+ } from "./chunk-D7STIWJO.js";
4
4
  import {
5
- MaterializedViewSourceUnknownError
6
- } from "./chunk-PKUJ3JLQ.js";
5
+ MaterializedViewConfigError,
6
+ MaterializedViewSourceUnknownError,
7
+ RefNotDeclaredError
8
+ } from "./chunk-5OFC3QYL.js";
7
9
 
8
10
  // src/with-formula/materialized-views/dependency-analyzer.ts
9
11
  function analyzeDependencies(query) {
@@ -63,9 +65,10 @@ function summarizeUnionPlan(spec) {
63
65
  }
64
66
  function summarizeProjectionPlan(spec) {
65
67
  const projection = spec.projection;
66
- const legs = projection.joins.map(
67
- (leg) => "collect" in leg ? `collect:${leg.collect}.${leg.on}\u2192${leg.as}` : `field:${leg.field}\u2192${leg.as}`
68
- ).sort();
68
+ const legs = projection.joins.map((leg) => {
69
+ const at = leg.from !== void 0 ? `@${leg.from}` : "";
70
+ return "collect" in leg ? `collect${at}:${leg.collect}.${leg.on}\u2192${leg.as}` : `field${at}:${leg.field}\u2192${leg.as}`;
71
+ }).sort();
69
72
  const body = JSON.stringify({ source: projection.source, legs });
70
73
  return `projection(${body})${summarizeGroupingTail(spec)}`;
71
74
  }
@@ -105,6 +108,44 @@ function canonicalizeQueryPlan(plan) {
105
108
  });
106
109
  }
107
110
 
111
+ // src/with-formula/materialized-views/projection-legs.ts
112
+ function isCollectLeg(leg) {
113
+ return "collect" in leg;
114
+ }
115
+ function validateProjectionLegs(mvName, projection) {
116
+ const seen = /* @__PURE__ */ new Map();
117
+ for (const leg of projection.joins) {
118
+ if (leg.from !== void 0) {
119
+ const parent = seen.get(leg.from);
120
+ if (!parent) {
121
+ throw new MaterializedViewConfigError(
122
+ `"${mvName}": projection leg "${leg.as}" declares from: "${leg.from}", which is not an alias declared EARLIER in \`joins\`. A leg may only attach to the primary row or to a preceding leg \u2014 that ordering rule is what makes a cycle impossible. Known so far: ${[...seen.keys()].map((a) => `"${a}"`).join(", ") || "(none)"}`
123
+ );
124
+ }
125
+ if (isCollectLeg(parent)) {
126
+ throw new MaterializedViewConfigError(
127
+ `"${mvName}": projection leg "${leg.as}" declares from: "${leg.from}", but "${leg.from}" is a collect leg and holds an ARRAY of rows, not one record. A leg can only hang off a forward leg (record | null). Attach it to the primary row instead, or collect the far side directly if its ref() reaches "${projection.source}".`
128
+ );
129
+ }
130
+ }
131
+ seen.set(leg.as, leg);
132
+ }
133
+ }
134
+ function resolveLegOwner(leg, joins, source, resolveRef) {
135
+ if (leg.from === void 0) return source;
136
+ const parent = joins.find((l) => l.as === leg.from);
137
+ if (!parent) return null;
138
+ if (isCollectLeg(parent)) return parent.collect;
139
+ const parentOwner = resolveLegOwner(parent, joins, source, resolveRef);
140
+ if (parentOwner === null) return null;
141
+ return resolveRef(parentOwner, parent.field)?.target ?? null;
142
+ }
143
+ function resolveForwardLegTarget(leg, joins, source, resolveRef) {
144
+ const owner = resolveLegOwner(leg, joins, source, resolveRef);
145
+ if (owner === null) return null;
146
+ return resolveRef(owner, leg.field)?.target ?? null;
147
+ }
148
+
108
149
  // src/with-formula/materialized-views/registry.ts
109
150
  var WHOLE_RECORD = "*";
110
151
  var MaterializedViewRegistry = class {
@@ -126,6 +167,33 @@ var MaterializedViewRegistry = class {
126
167
  * target has resolved (see `_resolvePendingForwardDeps`).
127
168
  */
128
169
  _pendingForwardDeps = [];
170
+ /**
171
+ * Query-form strategies whose `query()` callback could not be planned at
172
+ * registration time because a `.join()` names a field whose `ref()` is not
173
+ * declared YET (#1139).
174
+ *
175
+ * Registration runs inside `openVault()`; a collection's refs can only be
176
+ * declared afterwards, so for a query-form MV that joins a declared FK there
177
+ * is NO call ordering the consumer can choose — the plan is simply built too
178
+ * early. Rather than failing the vault open, the strategy is parked here and
179
+ * replanned from {@link resolvePendingPlans}, which every write dispatch and
180
+ * `vault.refreshView()` call runs first. This is the query-form counterpart
181
+ * of `_pendingForwardDeps`, one level up: that defers a leg's TARGET, this
182
+ * defers the whole plan.
183
+ *
184
+ * Only `RefNotDeclaredError` parks a strategy. Every other planning failure
185
+ * still throws out of `openVault()` exactly as before, so a typo'd source or
186
+ * a malformed spec keeps its loud, early error.
187
+ *
188
+ * A parked strategy is invisible until it resolves: it contributes no
189
+ * `_bySource` entries and no cycle-detection edges (same caveat as a
190
+ * late-resolved forward target — `edges()` runs once at vault open). It also
191
+ * cannot be dispatched, which is why {@link hasPendingPlans} forces the
192
+ * conservative branch in `Collection._txAtomicSafe`: the atomic write path
193
+ * skips MV dispatch, and skipping it here would mean the write that was
194
+ * supposed to trigger the first replan is the one that gets missed.
195
+ */
196
+ _pendingPlans = [];
129
197
  /**
130
198
  * Register an MV. Invokes `spec.query()` once at registration time to
131
199
  * read the plan + join context; the resulting `Query<T>` is discarded
@@ -152,13 +220,20 @@ var MaterializedViewRegistry = class {
152
220
  const projection = spec.projection;
153
221
  dependencies = /* @__PURE__ */ new Set([projection.source]);
154
222
  for (const leg of projection.joins) {
155
- if ("collect" in leg) dependencies.add(leg.collect);
156
- else pendingForwardFields.push(leg.field);
223
+ if (isCollectLeg(leg)) dependencies.add(leg.collect);
224
+ else pendingForwardFields.push(leg.as);
157
225
  }
158
226
  if (spec.sources) for (const s of spec.sources) dependencies.add(s);
159
227
  queryPlanSummary = summarizeProjectionPlan(spec);
160
228
  } else {
161
- const q = spec.query(dbForQuery);
229
+ let q;
230
+ try {
231
+ q = spec.query(dbForQuery);
232
+ } catch (e) {
233
+ if (!(e instanceof RefNotDeclaredError)) throw e;
234
+ this._pendingPlans.push({ spec, db, ...options !== void 0 ? { options } : {} });
235
+ return;
236
+ }
162
237
  qAny = q;
163
238
  isQuery = typeof qAny._plan === "function";
164
239
  if (isQuery) {
@@ -206,15 +281,51 @@ var MaterializedViewRegistry = class {
206
281
  }
207
282
  if (pendingForwardFields.length > 0) {
208
283
  const refRegistry = db.refRegistry;
209
- const source = spec.projection.source;
284
+ const projectionSpec = spec.projection;
285
+ const resolveRef = (c, f) => refRegistry?.getOutbound(c)[f] ?? null;
210
286
  this._pendingForwardDeps.push({
211
287
  reg,
212
- fields: new Set(pendingForwardFields),
213
- resolveTarget: (field) => refRegistry?.getOutbound(source)[field]?.target ?? null
288
+ aliases: new Set(pendingForwardFields),
289
+ resolveTarget: (alias) => {
290
+ const leg = projectionSpec.joins.find((l) => l.as === alias);
291
+ if (!leg || isCollectLeg(leg)) return null;
292
+ return resolveForwardLegTarget(leg, projectionSpec.joins, projectionSpec.source, resolveRef);
293
+ }
214
294
  });
215
295
  this._resolvePendingForwardDeps();
216
296
  }
217
297
  }
298
+ /**
299
+ * `true` while any query-form strategy is still unplanned (#1139). Read by
300
+ * `Collection._txAtomicSafe`, which must refuse the atomic write path while
301
+ * this holds — see the `_pendingPlans` doc comment for why.
302
+ */
303
+ hasPendingPlans() {
304
+ return this._pendingPlans.length > 0;
305
+ }
306
+ /**
307
+ * Replan every parked query-form strategy (#1139). Called at the head of both
308
+ * write dispatchers and of `vault.refreshView()`, so a strategy resolves on the
309
+ * first write or refresh after its source collection's refs are declared —
310
+ * which is the earliest moment it could produce a correct plan, and strictly
311
+ * before the first moment it could have any output to produce.
312
+ *
313
+ * Each entry is handed straight back to {@link register}, so a strategy that
314
+ * is STILL unplannable simply re-parks itself and the next dispatch tries
315
+ * again. Idempotent and cheap: the array empties as strategies resolve, and
316
+ * both callers skip the await entirely once it is empty.
317
+ *
318
+ * A late-resolved strategy does NOT retro-feed `edges()` — the unified cycle
319
+ * pass runs once at vault open, before refs exist. Same caveat, and the same
320
+ * reason, as a late-resolved forward-leg target.
321
+ */
322
+ async resolvePendingPlans() {
323
+ if (this._pendingPlans.length === 0) return;
324
+ const parked = this._pendingPlans.splice(0);
325
+ for (const entry of parked) {
326
+ await this.register(entry.spec, entry.db, entry.options);
327
+ }
328
+ }
218
329
  /** All MVs that depend on `source`, in registration order. */
219
330
  mvsForSource(source) {
220
331
  if (this._pendingForwardDeps.length > 0) this._resolvePendingForwardDeps();
@@ -237,17 +348,17 @@ var MaterializedViewRegistry = class {
237
348
  _resolvePendingForwardDeps() {
238
349
  for (let i = this._pendingForwardDeps.length - 1; i >= 0; i--) {
239
350
  const entry = this._pendingForwardDeps[i];
240
- for (const field of [...entry.fields]) {
241
- const target = entry.resolveTarget(field);
351
+ for (const alias of [...entry.aliases]) {
352
+ const target = entry.resolveTarget(alias);
242
353
  if (target === null) continue;
243
- entry.fields.delete(field);
354
+ entry.aliases.delete(alias);
244
355
  if (entry.reg.dependencies.has(target)) continue;
245
356
  entry.reg.dependencies.add(target);
246
357
  const arr = this._bySource.get(target);
247
358
  if (arr) arr.push(entry.reg);
248
359
  else this._bySource.set(target, [entry.reg]);
249
360
  }
250
- if (entry.fields.size === 0) this._pendingForwardDeps.splice(i, 1);
361
+ if (entry.aliases.size === 0) this._pendingForwardDeps.splice(i, 1);
251
362
  }
252
363
  }
253
364
  /** Single MV by name, or `undefined`. */
@@ -366,7 +477,10 @@ export {
366
477
  summarizeQueryPlan,
367
478
  computeQueryHash,
368
479
  canonicalizeQueryPlan,
480
+ isCollectLeg,
481
+ validateProjectionLegs,
482
+ resolveLegOwner,
369
483
  MaterializedViewRegistry,
370
484
  wrapDbWithPredicates
371
485
  };
372
- //# sourceMappingURL=chunk-A66LJYFG.js.map
486
+ //# sourceMappingURL=chunk-FEWCVAFV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-formula/materialized-views/dependency-analyzer.ts","../src/with-formula/materialized-views/query-hash.ts","../src/with-formula/materialized-views/projection-legs.ts","../src/with-formula/materialized-views/registry.ts"],"sourcesContent":["import type { Query, QueryPlan } from '../../kernel/query/builder.js'\nimport type { JoinContext } from '../../kernel/query/join.js'\nimport type { MaterializedViewSpec } from './types.js'\n\n/**\n * Walks a `Query<T>` plan and returns the set of source collection\n * names that any source-write should trigger a refresh on.\n *\n * Handles:\n * - root collection (the one the query was built from)\n * - FK join targets (`.join(field, { as })`)\n *\n * Also handles:\n * - cross-join targets (`.crossJoin(target, { as })`) — v3\n *\n * Deferred:\n * - `.wherePredicate(name)` — v2 predicate primitive\n * - Overlay-name expansion to {base, overlay}\n *\n * The set is materialized at MV registration time. The MV registry\n * uses it to (a) dispatch `onSourceWrite` only to MVs that actually\n * care, and (b) contribute edges to the shared cycle-detection graph.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function analyzeDependencies(query: Query<any>): Set<string> {\n const deps = new Set<string>()\n const plan = query._plan()\n const ctx = query._joinContext()\n\n // The root collection is always a dependency.\n if (ctx?.leftCollection) {\n deps.add(ctx.leftCollection)\n }\n\n // FK join targets contribute additional sources.\n for (const leg of plan.joins) {\n deps.add(leg.target)\n }\n\n // Cross-join targets are also dependency sources — writes to either side\n // must trigger MV refresh. Symmetric with FK-join target handling above.\n for (const clause of plan.clauses) {\n if (clause.type === 'crossJoin') {\n deps.add(clause.target)\n }\n }\n\n // Sub-plans inside OR clauses can carry nested joins. Walk them.\n // (Today only top-level `.join()` populates `plan.joins`, but the\n // OR-group machinery permits sub-plans, so we recurse defensively.)\n walkClausesForJoins(plan, deps, ctx)\n\n return deps\n}\n\nfunction walkClausesForJoins(\n plan: QueryPlan,\n deps: Set<string>,\n ctx: JoinContext | undefined,\n): void {\n void ctx\n // Today `plan.joins` carries all join legs at top level. Sub-plans\n // inside OR groups don't currently support nested joins, so the loop\n // below is a no-op safety net for future builder extensions.\n for (const clause of plan.clauses) {\n if (clause.type === 'group') {\n // Group clauses don't (yet) carry their own joins; this is a\n // forward-compat anchor for when OR-groups support nested\n // sources.\n }\n }\n}\n\n/**\n * Convenience: produce a stable string summary of the query plan\n * suitable for `queryHash` derivation. Captures everything the\n * dependency analyzer reads + the where/orderBy/limit/offset\n * structure that affects materialized rows.\n *\n * `joinContext` is intentionally NOT included — the join-resolution\n * function references would defeat hash determinism. The set of join\n * TARGETS (collection names) IS included via the plan.joins legs.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function summarizeQueryPlan(query: Query<any>): string {\n const plan = query._plan()\n const ctx = query._joinContext()\n return JSON.stringify({\n root: ctx?.leftCollection ?? null,\n clauses: plan.clauses.map(c => {\n if (c.type === 'crossJoin') {\n return {\n type: 'crossJoin',\n target: c.target,\n as: c.as,\n // Inline on: callback: use sentinel — drift detection disabled for this MV\n onPredicateName: c.onPredicateName ?? (c.on ? '[inline]' : null),\n maxRows: c.maxRows ?? null,\n // `outer` changes the row set, so it is part of the plan's identity\n // for drift detection, not decoration (#1130).\n outer: c.outer ?? false,\n }\n }\n return c\n }),\n orderBy: plan.orderBy,\n limit: plan.limit ?? null,\n offset: plan.offset,\n joins: plan.joins.map(j => ({ field: j.field, as: j.as, target: j.target, mode: j.mode })),\n })\n}\n\n/**\n * Canonical string description of a UNION MV's plan, used as input to\n * `computeQueryHash`.\n *\n * Asymmetry note:\n * - Arm collection names are NOT sorted. Declaration order is\n * semantically meaningful for the dedup-only UNION path —\n * `materializeUnionResult` iterates `spec.unionSources` in\n * declaration order and keeps the first-seen row per composite key\n * (tie-break precedence). If we sorted arms here, a consumer who\n * reordered `unionSources` to change precedence would compute the\n * same `queryHash`, refresh would be a no-op, and stale MV rows\n * would persist. Hashing in declaration order makes any reorder\n * trigger a refresh.\n * - `groupBy` fields ARE sorted. Multi-key groupBy buckets are\n * commutative (`canonicalGroupKey` produces the same composite key\n * regardless of field order in the input spec).\n * - `aggregate` keys ARE sorted. Reducer-spec keys are independent\n * of each other — order of declaration doesn't change output.\n *\n * Per-arm `map` functions are NOT fingerprinted; consumers must bump\n * the MV's `name` (or rely on application-level cache busting) when\n * `map` semantics change non-equivalently.\n */\nexport function summarizeUnionPlan<T extends Record<string, unknown>>(\n spec: MaterializedViewSpec<T>,\n): string {\n return `union(${summarizeUnionArms(spec)})${summarizeGroupingTail(spec)}`\n}\n\n/**\n * Canonical string description of a projection MV's plan (#810), used\n * as input to `computeQueryHash`.\n *\n * Leg descriptors ARE sorted (contrast with UNION arm order): every\n * leg attaches under a distinct `as` alias, forward legs are\n * one-to-one attachments and collect legs are independent\n * hash-grouped passes, so declaration order never changes the\n * materialized rows — a pure reorder must NOT force a refresh.\n * `from` (#1140) constrains the legal orderings (a leg must follow the\n * alias it attaches to) without making order meaningful: each descriptor\n * carries its own `@alias`, and aliases are unique, so the sorted set\n * still determines the leg graph exactly.\n *\n * The projection `map` is NOT fingerprinted (identical limitation as\n * the UNION arm `map`); consumers must bump the MV's `name` when\n * `map` semantics change non-equivalently.\n */\nexport function summarizeProjectionPlan<T extends Record<string, unknown>>(\n spec: MaterializedViewSpec<T>,\n): string {\n const projection = spec.projection!\n const legs = projection.joins\n .map(leg => {\n // #1140 — `from` changes which rows a leg attaches to, so it is part of\n // the plan's identity. Omitting it would let two structurally different\n // projections share a queryHash and silently skip a refresh.\n const at = leg.from !== undefined ? `@${leg.from}` : ''\n return 'collect' in leg\n ? `collect${at}:${leg.collect}.${leg.on}→${leg.as}`\n : `field${at}:${leg.field}→${leg.as}`\n })\n .sort()\n const body = JSON.stringify({ source: projection.source, legs })\n return `projection(${body})${summarizeGroupingTail(spec)}`\n}\n\n/** Arm descriptors for `summarizeUnionPlan` — declaration order preserved (see its doc). */\nfunction summarizeUnionArms<T extends Record<string, unknown>>(\n spec: MaterializedViewSpec<T>,\n): string {\n return (spec.unionSources ?? [])\n .map(s => {\n // Fold each arm's join legs into the summary so adding or\n // reordering joins (which changes the materialized rows) bumps\n // queryHash. Leg order is declaration-significant (legs chain), so\n // it is NOT sorted — same rationale as arm declaration order.\n const joins = s.join?.length\n ? `[${s.join.map(j => `${j.field}→${j.as}`).join(';')}]`\n : ''\n return `${s.collection}${joins}`\n })\n .join(',')\n}\n\n/**\n * Shared `|groupBy(…)|aggregate(…)|money(…)` tail for the UNION and\n * projection summaries — both feed the same post-map grouping pipeline,\n * so the same spec fields fold into both hashes with the same rules.\n */\nfunction summarizeGroupingTail<T extends Record<string, unknown>>(\n spec: MaterializedViewSpec<T>,\n): string {\n const groupBy: string = Array.isArray(spec.groupBy)\n ? [...spec.groupBy].sort().join(',')\n : typeof spec.groupBy === 'string'\n ? spec.groupBy\n : ''\n const aggKeys = spec.aggregate ? Object.keys(spec.aggregate).sort().join(',') : ''\n // `moneyFields` changes reducer semantics (float → exact BigInt), so\n // declaring / removing / re-keying it must bump queryHash. Keys are\n // sorted — they're independent of each other (one descriptor per\n // output field), same rationale as aggregate keys.\n const moneyKeys = spec.moneyFields ? Object.keys(spec.moneyFields).sort().join(',') : ''\n return `|groupBy(${groupBy})|aggregate(${aggKeys})|money(${moneyKeys})`\n}\n","/**\n * Deterministic hash of a materialized view strategy's \"shape\": MV\n * name + canonical query-plan summary + sorted dependency-set.\n *\n * Used to detect strategy drift: a row whose `_materializedFrom.queryHash`\n * doesn't match the current strategy is considered stale.\n *\n * Web Crypto SHA-256 — no extra deps. Mirrors the v1\n * `computeStrategyHash` pattern.\n */\nimport { sha256Hex } from '../../kernel/enclave/index.js'\n\nexport async function computeQueryHash(\n mvName: string,\n /**\n * Source-collection set the query depends on. Sorted before\n * canonicalization so set iteration order doesn't affect the hash.\n */\n dependencies: ReadonlySet<string>,\n /**\n * Stringified query-plan summary. The caller produces this from the\n * `Query<T>` builder — concretely: a JSON serialization of clauses +\n * orderBy + limit + offset + joins. Function bodies inside\n * `wherePredicate` are NOT included here (those carry their own\n * `predicateHash` to be folded in by a later sub-issue).\n */\n queryPlanSummary: string,\n): Promise<string> {\n const canonical = JSON.stringify({\n mvName,\n dependencies: [...dependencies].sort(),\n queryPlanSummary,\n })\n const bytes = new TextEncoder().encode(canonical)\n return sha256Hex(bytes)\n}\n\n/**\n * Canonicalize a query plan for hashing. Walks the plan structure\n * with sorted keys so insertion order doesn't perturb the result.\n * Lives here rather than in `query/builder.ts` to keep that module\n * stable across MV-specific evolutions.\n *\n * @internal exported for testing\n */\nexport function canonicalizeQueryPlan(plan: unknown): string {\n return JSON.stringify(plan, (_key, value) => {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n const sorted: Record<string, unknown> = {}\n for (const k of Object.keys(value as Record<string, unknown>).sort()) {\n sorted[k] = (value as Record<string, unknown>)[k]\n }\n return sorted\n }\n return value\n })\n}\n","/**\n * Projection-leg topology (#810, extended by #1140).\n *\n * A projection MV's legs originally all attached to the PRIMARY row: a forward\n * leg named an FK field on `projection.source`, and a reverse `collect` leg's\n * `on` field had to `ref()` the source itself. Anything two FKs away was\n * therefore inexpressible — `bill → entity → client` has no leg shape, because\n * the bill has no `clientId` and `clients.entityId` refs `entities`, not\n * `bills`.\n *\n * `from` closes that: a leg may attach to a previously-declared ALIAS instead of\n * to the primary row. This module owns the two questions that follow from it —\n * *is this leg graph well-formed?* and *which collection does a leg's rows come\n * from?* — so neither the registry nor the executor has to re-derive them.\n *\n * **Why cycles are impossible by construction, and there is no depth cap.**\n * `from` may only name an alias declared EARLIER in `joins`. A leg can therefore\n * never reach forward, the graph is a forest rooted at the primary row, and its\n * depth is bounded by the number of legs. Validation refuses an unknown or\n * not-yet-declared alias, which is the same check.\n */\n\nimport { MaterializedViewConfigError } from '../../kernel/errors.js'\nimport type { ProjectionJoinLeg, ProjectionSpec } from './types.js'\n\n/** Reverse (one-to-many) leg — discriminated on `collect`, as the type is. */\nexport function isCollectLeg(\n leg: ProjectionJoinLeg,\n): leg is Extract<ProjectionJoinLeg, { collect: string }> {\n return 'collect' in leg\n}\n\n/**\n * Refuse a malformed leg graph where `withMaterializedView()` checks the rest of\n * the leg shape — at spec CONSTRUCTION, not at vault open and not at first\n * materialization. Alias wiring is pure configuration: it needs no refs, no\n * records and no store, so the earliest failure is the best one.\n * (Ref EXISTENCE still resolves at first materialization, unchanged — refs\n * cannot exist until after `openVault()` returns.)\n */\nexport function validateProjectionLegs<T extends Record<string, unknown>>(\n mvName: string,\n projection: ProjectionSpec<T>,\n): void {\n // Non-empty and unique `as` are already refused by `withMaterializedView()`\n // itself, earlier and with its own message — not re-checked here. This\n // function owns the `from` wiring and nothing else.\n const seen = new Map<string, ProjectionJoinLeg>()\n for (const leg of projection.joins) {\n if (leg.from !== undefined) {\n const parent = seen.get(leg.from)\n if (!parent) {\n throw new MaterializedViewConfigError(\n `\"${mvName}\": projection leg \"${leg.as}\" declares from: \"${leg.from}\", which is not an ` +\n `alias declared EARLIER in \\`joins\\`. A leg may only attach to the primary row or to a ` +\n `preceding leg — that ordering rule is what makes a cycle impossible. Known so far: ` +\n `${[...seen.keys()].map(a => `\"${a}\"`).join(', ') || '(none)'}`,\n )\n }\n if (isCollectLeg(parent)) {\n throw new MaterializedViewConfigError(\n `\"${mvName}\": projection leg \"${leg.as}\" declares from: \"${leg.from}\", but \"${leg.from}\" ` +\n `is a collect leg and holds an ARRAY of rows, not one record. A leg can only hang off a ` +\n `forward leg (record | null). Attach it to the primary row instead, or collect the ` +\n `far side directly if its ref() reaches \"${projection.source}\".`,\n )\n }\n }\n seen.set(leg.as, leg)\n }\n}\n\n/**\n * The collection a leg's rows come from — the primary source for a root leg, the\n * `from` leg's own target otherwise.\n *\n * Returns `null` when a forward `ref()` somewhere along the chain is not\n * declared yet, which at registration time is the normal case rather than an\n * error: refs are declared after `openVault()` returns, so the registry retries\n * this on every dispatch until it resolves (`_pendingForwardDeps`).\n *\n * `resolveRef` is passed in rather than imported so this module stays free of\n * vault wiring — the registry hands it the ref registry's `getOutbound`, the\n * executor hands it a join context lookup. Both answer the same question.\n */\nexport type RefLookup = (collection: string, field: string) => { target: string } | null\n\nexport function resolveLegOwner(\n leg: ProjectionJoinLeg,\n joins: ReadonlyArray<ProjectionJoinLeg>,\n source: string,\n resolveRef: RefLookup,\n): string | null {\n if (leg.from === undefined) return source\n const parent = joins.find(l => l.as === leg.from)\n if (!parent) return null // refused by validateProjectionLegs; defensive here\n if (isCollectLeg(parent)) return parent.collect // refused too, same reason\n const parentOwner = resolveLegOwner(parent, joins, source, resolveRef)\n if (parentOwner === null) return null\n return resolveRef(parentOwner, parent.field)?.target ?? null\n}\n\n/**\n * The collection a FORWARD leg resolves INTO — i.e. its dependency. `null` while\n * any ref in the chain (including this leg's own) is still undeclared.\n */\nexport function resolveForwardLegTarget(\n leg: Extract<ProjectionJoinLeg, { field: string }>,\n joins: ReadonlyArray<ProjectionJoinLeg>,\n source: string,\n resolveRef: RefLookup,\n): string | null {\n const owner = resolveLegOwner(leg, joins, source, resolveRef)\n if (owner === null) return null\n return resolveRef(owner, leg.field)?.target ?? null\n}\n","import { MaterializedViewSourceUnknownError, RefNotDeclaredError } from '../../kernel/errors.js'\nimport type { ViaGraph, FieldRef, EdgeKind, Grain } from '../../kernel/via/graph.js'\nimport type { Clause, FieldClause } from '../../kernel/query/predicate.js'\nimport type { DeclaredPredicate } from '../../kernel/query/builder.js'\nimport { analyzeDependencies, summarizeQueryPlan, summarizeUnionPlan, summarizeProjectionPlan } from './dependency-analyzer.js'\nimport { computeQueryHash } from './query-hash.js'\nimport { isCollectLeg, resolveForwardLegTarget } from './projection-legs.js'\nimport type { MaterializedViewSpec, MVQueryContext } from './types.js'\n\n/**\n * Whole-record artifact-grain field marker (#638 Task 2) — MUST match\n * `derivations/registry.ts`'s and `vault.ts`'s overlay-edge marker so\n * cross-registry edges (a derivation feeding an MV, or vice versa) resolve\n * to the SAME graph node. See that file's `WHOLE_RECORD` doc comment.\n */\nconst WHOLE_RECORD = '*'\n\n/**\n * One registered MV strategy alongside its derived metadata. Stored\n * type-erased on `TRow` so the registry can hold heterogeneous MVs.\n */\nexport interface RegisteredMV {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly spec: MaterializedViewSpec<any>\n /** Output collection name (`spec.output?.collection ?? spec.name`). */\n readonly outputCollection: string\n /** Set of source collections; populated at registration via the analyzer. */\n readonly dependencies: ReadonlySet<string>\n /** Canonical `queryHash` — `_materializedFrom.queryHash` for every emitted row. */\n readonly queryHash: string\n /**\n * Top-level FieldClauses on the partition field, captured at\n * registration time. Used by the cycle detector to resolve\n * same-collection-as-source edges via the partition-discriminator\n * check. Empty when `spec.output?.partition` is undefined.\n */\n readonly partitionClauses: readonly FieldClause[]\n /**\n * #638 Task 2 — `'record'` for a row-per-source-row Query<T> or\n * `unionSources` MV, `'aggregate'` for a `.groupBy().aggregate()` MV\n * (the shape that requires explicit `sources`, since the dependency\n * analyzer can't walk an aggregate plan). Feeds `edges()`'s grain.\n */\n readonly grain: Grain\n}\n\n/**\n * Vault-internal registry of MV strategies. Owned by `Vault`; not\n * exported. Parallel to v1's `DerivationRegistry`; the two graphs share\n * a single cycle-detection pass at vault open (see `validate`).\n *\n * @internal\n */\nexport class MaterializedViewRegistry {\n /** Keyed by `spec.name`. */\n private readonly _byName = new Map<string, RegisteredMV>()\n /** Keyed by dependency source-collection → MVs that depend on it. */\n private readonly _bySource = new Map<string, RegisteredMV[]>()\n /**\n * Projection MVs (#810) whose forward-leg ref() targets could not be\n * resolved at registration time. A forward leg names only the FK\n * FIELD; its dependency is the field's ref() TARGET, declared on the\n * source collection — but registration runs at vault open, BEFORE\n * user code declares collections (and their refs). Constructing the\n * source collection here to look them up would be worse: a later\n * `vault.collection(source, { refs })` call only registers refs on a\n * cache miss, so an early construction would silently drop them.\n * Instead each entry carries a non-constructive ref-registry probe;\n * `mvsForSource` retries on every dispatch until every forward\n * target has resolved (see `_resolvePendingForwardDeps`).\n */\n private readonly _pendingForwardDeps: Array<{\n reg: RegisteredMV\n /** Forward-leg ALIASES still awaiting resolution (#1140 — a leg is identified\n * by its alias, not its field: with `from`, two legs may name the same FK\n * field on different collections). */\n aliases: Set<string>\n resolveTarget: (alias: string) => string | null\n }> = []\n\n /**\n * Query-form strategies whose `query()` callback could not be planned at\n * registration time because a `.join()` names a field whose `ref()` is not\n * declared YET (#1139).\n *\n * Registration runs inside `openVault()`; a collection's refs can only be\n * declared afterwards, so for a query-form MV that joins a declared FK there\n * is NO call ordering the consumer can choose — the plan is simply built too\n * early. Rather than failing the vault open, the strategy is parked here and\n * replanned from {@link resolvePendingPlans}, which every write dispatch and\n * `vault.refreshView()` call runs first. This is the query-form counterpart\n * of `_pendingForwardDeps`, one level up: that defers a leg's TARGET, this\n * defers the whole plan.\n *\n * Only `RefNotDeclaredError` parks a strategy. Every other planning failure\n * still throws out of `openVault()` exactly as before, so a typo'd source or\n * a malformed spec keeps its loud, early error.\n *\n * A parked strategy is invisible until it resolves: it contributes no\n * `_bySource` entries and no cycle-detection edges (same caveat as a\n * late-resolved forward target — `edges()` runs once at vault open). It also\n * cannot be dispatched, which is why {@link hasPendingPlans} forces the\n * conservative branch in `Collection._txAtomicSafe`: the atomic write path\n * skips MV dispatch, and skipping it here would mean the write that was\n * supposed to trigger the first replan is the one that gets missed.\n */\n private readonly _pendingPlans: Array<{\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n spec: MaterializedViewSpec<any>\n db: MVQueryContext\n options?: { knownCollections?: (name: string) => boolean }\n }> = []\n\n /**\n * Register an MV. Invokes `spec.query()` once at registration time to\n * read the plan + join context; the resulting `Query<T>` is discarded\n * after dependency extraction. `vault.collection(...)` must therefore\n * be functional by the time this runs — typically wired from\n * `Vault._initMaterializedViews` after collection bootstrap.\n *\n * Throws `MaterializedViewSourceUnknownError` if the analyzer\n * surfaces a dependency the vault doesn't know about (when a\n * `knownCollections` checker is supplied).\n */\n async register(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n spec: MaterializedViewSpec<any>,\n db: MVQueryContext,\n options?: { knownCollections?: (name: string) => boolean },\n ): Promise<void> {\n // Build a predicate-aware db wrapper. If `spec.predicates` is\n // declared, the wrapper intercepts `.collection().query()` and\n // attaches the predicates map to the resulting Query<T>. With no\n // predicates declared, the wrapper is the original db unchanged.\n const dbForQuery = spec.predicates ? wrapDbWithPredicates(db, spec.predicates) : db\n\n // Invoke the query callback once to inspect its plan / dependencies.\n // For Query<T> shapes the analyzer extracts deps + plan summary\n // automatically. Reduction / GroupedReduction shapes don't\n // expose the underlying Query, so the spec must declare `sources`\n // explicitly. `partitionClauses` are only populated for Query<T>\n // since same-collection-partition is a non-aggregate concern.\n // UNION-form strategies: dependencies and plan summary come\n // straight off the strategy — no `query` callback to introspect.\n // The dependency-analyzer + summarizer are bypassed entirely; the\n // executor handles materialization via `materializeUnionResult`.\n let dependencies: Set<string>\n let queryPlanSummary: string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let qAny: any = null\n let isQuery = false\n // Projection-form (#810): forward legs whose ref() target wasn't\n // resolvable at registration time — folded in lazily, see\n // `_pendingForwardDeps`.\n const pendingForwardFields: string[] = []\n if (spec.unionSources) {\n dependencies = new Set(spec.unionSources.map(s => s.collection))\n // Per-arm joins resolve right-side collections that aren't among\n // the arm `collection`s. The consumer lists those in `sources`;\n // fold them into the dependency set so a write to a join-target\n // collection triggers MV refresh (and contributes a cycle edge).\n if (spec.sources) for (const s of spec.sources) dependencies.add(s)\n queryPlanSummary = summarizeUnionPlan(spec)\n } else if (spec.projection) {\n // Projection-form (#810): dependencies are all AUTO — the primary\n // source, every collect leg's collection (both literal names), and\n // every forward leg's ref() target. Forward targets usually can't\n // resolve yet (refs are declared after vault open) — those go\n // through the pending-resolution path below. Explicit `sources`\n // remains additive, same as the other two forms.\n const projection = spec.projection\n dependencies = new Set([projection.source])\n for (const leg of projection.joins) {\n // A collect leg's dependency is its literal collection name, whatever it\n // attaches to — which is why `from` needs no new dependency machinery on\n // that side. A forward leg's dependency is a ref() target, still unknown.\n if (isCollectLeg(leg)) dependencies.add(leg.collect)\n else pendingForwardFields.push(leg.as)\n }\n if (spec.sources) for (const s of spec.sources) dependencies.add(s)\n queryPlanSummary = summarizeProjectionPlan(spec)\n } else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let q: any\n try {\n q = spec.query!(dbForQuery)\n } catch (e) {\n // #1139 — a join on a ref that is not declared YET. Park and replan;\n // see `_pendingPlans`. Anything else is a real registration failure.\n if (!(e instanceof RefNotDeclaredError)) throw e\n this._pendingPlans.push({ spec, db, ...(options !== undefined ? { options } : {}) })\n return\n }\n qAny = q // already `any` — see the declaration above\n isQuery = typeof qAny._plan === 'function'\n if (isQuery) {\n // `q` is the `Query` arm of the union here (runtime-confirmed via\n // `qAny._plan` above); reuse the already-`any` `qAny` the block uses\n // for `_plan()` rather than re-narrowing.\n dependencies = analyzeDependencies(qAny)\n queryPlanSummary = summarizeQueryPlan(qAny)\n // Fold `.wherePredicate(name, ctx)` references into the plan\n // summary so predicate function or ctx changes (signalled by\n // bumping `hash` or supplying a different ctx) propagate into\n // `queryHash` and force refresh on next visit.\n const predicateRefs = extractPredicateRefs(qAny._plan())\n if (predicateRefs.length > 0) {\n queryPlanSummary = JSON.stringify({ plan: queryPlanSummary, predicates: predicateRefs })\n }\n // If `sources` is ALSO declared, take the union (consumer's\n // explicit list extends the auto-analyzed set).\n if (spec.sources) for (const s of spec.sources) dependencies.add(s)\n } else {\n // Aggregate shape: require explicit `sources`.\n if (!spec.sources || spec.sources.length === 0) {\n throw new Error(\n `withMaterializedView \"${spec.name}\": query() returned an aggregate ` +\n `(Reduction or GroupedReduction) but no \\`sources\\` field is declared. ` +\n `The dependency analyzer cannot walk through groupBy().aggregate() ` +\n `back to the source — declare sources: [...] explicitly.`,\n )\n }\n dependencies = new Set(spec.sources)\n // Aggregate plans don't carry a chainable query plan for summary\n // purposes; the dep-set + spec.name serve as the queryHash inputs.\n queryPlanSummary = JSON.stringify({ aggregate: true, sources: [...spec.sources].sort() })\n }\n }\n\n // Sanity-check declared dependencies against the vault's known\n // collections. Optional — when the checker isn't supplied (test\n // wiring, in-process composition) the registration succeeds and\n // any typo surfaces at first onSourceWrite as a no-op.\n if (options?.knownCollections) {\n for (const dep of dependencies) {\n if (!options.knownCollections(dep)) {\n throw new MaterializedViewSourceUnknownError(spec.name, dep)\n }\n }\n }\n\n const outputCollection = spec.output?.collection ?? spec.name\n const queryHash = await computeQueryHash(spec.name, dependencies, queryPlanSummary)\n // For same-collection-as-source MVs, capture the where-clauses on\n // the partition field so cycle detection can prove disjointness.\n // Only applicable to Query<T> shapes — aggregate MVs don't carry\n // a chainable plan to inspect (and same-collection aggregation\n // doesn't make sense for same-collection aggregation).\n const partitionClauses: FieldClause[] = []\n const partitionField = spec.output?.partition?.field\n if (partitionField !== undefined && isQuery) {\n const plan = qAny._plan()\n for (const clause of plan.clauses) {\n if (isFieldClauseOnField(clause, partitionField)) partitionClauses.push(clause)\n }\n }\n // #638 Task 2 — 'aggregate' only for the explicit-sources aggregate shape\n // (groupBy().aggregate() with no chainable plan); a row-per-source-row\n // Query<T>, unionSources, or projection MV is 'record'.\n const grain: Grain = spec.unionSources || spec.projection || isQuery ? 'record' : 'aggregate'\n const reg: RegisteredMV = { spec, outputCollection, dependencies, queryHash, partitionClauses, grain }\n\n this._byName.set(spec.name, reg)\n for (const dep of dependencies) {\n const arr = this._bySource.get(dep)\n if (arr) arr.push(reg)\n else this._bySource.set(dep, [reg])\n }\n if (pendingForwardFields.length > 0) {\n // Non-constructive ref-registry probe: the Vault (the real\n // MVQueryContext) carries its RefRegistry as a private field,\n // reachable structurally at runtime. Test stubs without one simply\n // never resolve — forward deps then come only from explicit `sources`.\n const refRegistry = (db as unknown as {\n refRegistry?: { getOutbound(collection: string): Record<string, { target: string }> }\n }).refRegistry\n const projectionSpec = spec.projection!\n const resolveRef = (c: string, f: string): { target: string } | null =>\n refRegistry?.getOutbound(c)[f] ?? null\n this._pendingForwardDeps.push({\n reg,\n aliases: new Set(pendingForwardFields),\n resolveTarget: (alias) => {\n const leg = projectionSpec.joins.find(l => l.as === alias)\n if (!leg || isCollectLeg(leg)) return null\n // Walks the `from` chain — every hop needs its own ref declared, so a\n // two-hop leg simply resolves one dispatch later than a one-hop one.\n return resolveForwardLegTarget(leg, projectionSpec.joins, projectionSpec.source, resolveRef)\n },\n })\n // Immediate attempt — covers refs already declared by the time\n // this MV registers (re-registration flows, test wiring).\n this._resolvePendingForwardDeps()\n }\n }\n\n /**\n * `true` while any query-form strategy is still unplanned (#1139). Read by\n * `Collection._txAtomicSafe`, which must refuse the atomic write path while\n * this holds — see the `_pendingPlans` doc comment for why.\n */\n hasPendingPlans(): boolean {\n return this._pendingPlans.length > 0\n }\n\n /**\n * Replan every parked query-form strategy (#1139). Called at the head of both\n * write dispatchers and of `vault.refreshView()`, so a strategy resolves on the\n * first write or refresh after its source collection's refs are declared —\n * which is the earliest moment it could produce a correct plan, and strictly\n * before the first moment it could have any output to produce.\n *\n * Each entry is handed straight back to {@link register}, so a strategy that\n * is STILL unplannable simply re-parks itself and the next dispatch tries\n * again. Idempotent and cheap: the array empties as strategies resolve, and\n * both callers skip the await entirely once it is empty.\n *\n * A late-resolved strategy does NOT retro-feed `edges()` — the unified cycle\n * pass runs once at vault open, before refs exist. Same caveat, and the same\n * reason, as a late-resolved forward-leg target.\n */\n async resolvePendingPlans(): Promise<void> {\n if (this._pendingPlans.length === 0) return\n // Splice first: `register` re-parks anything still unplannable, and reading\n // a live array it is concurrently pushing to would loop.\n const parked = this._pendingPlans.splice(0)\n for (const entry of parked) {\n await this.register(entry.spec, entry.db, entry.options)\n }\n }\n\n /** All MVs that depend on `source`, in registration order. */\n mvsForSource(source: string): ReadonlyArray<RegisteredMV> {\n if (this._pendingForwardDeps.length > 0) this._resolvePendingForwardDeps()\n return this._bySource.get(source) ?? []\n }\n\n /**\n * Retry ref() resolution for every pending projection forward leg\n * (#810). A field resolves once its source collection's refs have\n * been declared; the target then folds into the owning MV's\n * dependency set and `_bySource`, so subsequent writes to it\n * dispatch a refresh. Idempotent and cheap — the pending list\n * empties as fields resolve, and `mvsForSource` skips the call\n * entirely once it's empty.\n *\n * Late-resolved targets do NOT retro-feed `edges()` — the cycle\n * pass runs once at vault open, before refs exist. A cycle routed\n * exclusively through a forward leg is therefore not detected at\n * open (collect + source edges, the literal names, are).\n */\n private _resolvePendingForwardDeps(): void {\n for (let i = this._pendingForwardDeps.length - 1; i >= 0; i--) {\n const entry = this._pendingForwardDeps[i]!\n for (const alias of [...entry.aliases]) {\n const target = entry.resolveTarget(alias)\n if (target === null) continue\n entry.aliases.delete(alias)\n if (entry.reg.dependencies.has(target)) continue\n // `dependencies` is declared ReadonlySet for consumers; the\n // registry owns the underlying Set and is the one writer.\n ;(entry.reg.dependencies as Set<string>).add(target)\n const arr = this._bySource.get(target)\n if (arr) arr.push(entry.reg)\n else this._bySource.set(target, [entry.reg])\n }\n if (entry.aliases.size === 0) this._pendingForwardDeps.splice(i, 1)\n }\n }\n\n /** Single MV by name, or `undefined`. */\n byName(name: string): RegisteredMV | undefined {\n return this._byName.get(name)\n }\n\n /** Iterate over every registered MV. */\n all(): ReadonlyArray<RegisteredMV> {\n return [...this._byName.values()]\n }\n\n /**\n * Graph edges for #638 Task 2: one `'mv'` edge per registered MV — target\n * = the output collection (a `WHOLE_RECORD` artifact node), sources =\n * every dependency (also `WHOLE_RECORD` nodes). Same-collection edges\n * (`dep === outputCollection`) are skipped IFF the MV declares an\n * `output.partition` discriminator AND the query has a where-clause that\n * provably excludes the partition value (`partitionDisjoint`) — the SAME\n * condition the old local DFS used. Grain comes from the registration-time\n * `RegisteredMV.grain`.\n */\n edges(): ReadonlyArray<{ readonly target: FieldRef; readonly sources: readonly FieldRef[]; readonly kind: EdgeKind; readonly grain: Grain }> {\n const out: Array<{ target: FieldRef; sources: FieldRef[]; kind: EdgeKind; grain: Grain }> = []\n for (const reg of this._byName.values()) {\n const sources: FieldRef[] = []\n for (const dep of reg.dependencies) {\n if (dep === reg.outputCollection && partitionDisjoint(reg)) continue\n sources.push({ collection: dep, field: WHOLE_RECORD })\n }\n if (sources.length === 0) continue\n out.push({ target: { collection: reg.outputCollection, field: WHOLE_RECORD }, sources, kind: 'mv', grain: reg.grain })\n }\n return out\n }\n\n /**\n * Cycle detection, delegated to `ViaGraph.assertAcyclic()` (#638 Task 2 —\n * retires the local DFS). `graph` is the caller's shared per-vault graph,\n * ALREADY carrying this registry's `edges()` AND `DerivationRegistry`'s\n * (registered by the caller — see `Vault._initMaterializedViews`, which\n * runs after `_initDerivations`, so a pure-derivation cycle already threw\n * `DerivationCycleError` there; any cycle surfacing here necessarily\n * touches an MV edge). Throws `MaterializedViewCycleError` — SAME class as\n * before.\n */\n validate(graph: ViaGraph): void {\n graph.assertAcyclic()\n }\n}\n\n/**\n * Type guard: is the clause a top-level `FieldClause` on the given\n * field? Used by the partition-disjoint check.\n *\n * @internal\n */\nfunction isFieldClauseOnField(clause: Clause, field: string): clause is FieldClause {\n return clause.type === 'field' && clause.field === field\n}\n\n/**\n * Wrap an `MVQueryContext` so its `.collection().query()` returns a\n * Query<T> with the MV's declared predicates attached. Bare Queries\n * (outside of any MV) don't gain `.wherePredicate()` — only Queries\n * obtained through this wrapped db do.\n *\n * @internal\n */\nexport function wrapDbWithPredicates(\n db: MVQueryContext,\n predicates: NonNullable<MaterializedViewSpec<Record<string, unknown>>['predicates']>,\n): MVQueryContext {\n // Build the predicate map once — the fn signature in the MV spec\n // is row-typed but the QueryBuilder casts to unknown, so we widen\n // here for the Map.\n const map = new Map<string, DeclaredPredicate>()\n for (const [name, decl] of Object.entries(predicates)) {\n map.set(name, {\n hash: decl.hash,\n fn: decl.fn as (record: unknown, ctx?: unknown) => boolean,\n })\n }\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n collection<T extends Record<string, unknown>>(name: string): any {\n const c = db.collection<T>(name)\n // Return an object that delegates everything to `c` but\n // overrides `.query()` to attach predicates via the new\n // `Query._withPredicates()` accessor.\n return new Proxy(c, {\n get(target, prop, receiver) {\n if (prop === 'query') {\n return (...args: unknown[]) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const q = (target.query as any)(...args)\n // For non-aggregate Query<T>, attach predicates. For\n // legacy predicate-arg overload that returns T[] (sync\n // filter), pass through unchanged.\n \n if (q && typeof q._withPredicates === 'function') {\n return q._withPredicates(map)\n }\n return q\n }\n }\n return Reflect.get(target, prop, receiver)\n },\n })\n },\n }\n}\n\n/**\n * Walk a QueryPlan's clauses and collect predicate-reference markers\n * for `queryHash` derivation. Returns a sorted array (deterministic\n * order) of `{ name, predicateHash, ctxHash }` tuples — these are the\n * hashable identity of each `.wherePredicate()` call site.\n *\n * @internal\n */\nfunction extractPredicateRefs(\n plan: { clauses: readonly Clause[] },\n): Array<{ name: string; predicateHash: string; ctxHash: string }> {\n const refs: Array<{ name: string; predicateHash: string; ctxHash: string }> = []\n const walk = (clauses: readonly Clause[]): void => {\n for (const c of clauses) {\n if (c.type === 'wherePredicate') {\n refs.push({ name: c.name, predicateHash: c.predicateHash, ctxHash: c.ctxHash })\n } else if (c.type === 'group') {\n walk(c.clauses)\n }\n }\n }\n walk(plan.clauses)\n // Stable-sort by (name, predicateHash, ctxHash) — same predicate\n // appearing twice with different ctx hashes both flow through.\n refs.sort((a, b) => {\n if (a.name !== b.name) return a.name < b.name ? -1 : 1\n if (a.predicateHash !== b.predicateHash) return a.predicateHash < b.predicateHash ? -1 : 1\n return a.ctxHash < b.ctxHash ? -1 : a.ctxHash > b.ctxHash ? 1 : 0\n })\n return refs\n}\n\n/**\n * Provability check for the same-collection partition-discriminator.\n * Returns `true` when\n * the captured partition clauses on the MV's query provably exclude\n * the partition's value — meaning the input filter and the output\n * partition are disjoint and the same-collection edge isn't really a\n * cycle.\n *\n * Supported provability shapes (narrow on purpose — DERIV-PP30-001\n * is the load-bearing case):\n *\n * - `.where(field, '==', X)` where X !== partition.value → disjoint\n * - `.where(field, '!=', partition.value)` → disjoint\n * - `.where(field, 'in', [...])` where partition.value NOT in list → disjoint\n *\n * Anything else (no clause on the partition field, an 'in' list that\n * contains partition.value, unsupported operators) → not disjoint,\n * the cycle detector surfaces `MaterializedViewCycleError`.\n *\n * @internal\n */\nfunction partitionDisjoint(reg: RegisteredMV): boolean {\n const partition = reg.spec.output?.partition\n if (partition === undefined) return false\n const value = partition.value\n // The OR-semantics of multiple where-clauses on the same field\n // would muddy this check. v2 only treats AND-chained clauses;\n // any clause that proves disjoint is sufficient.\n for (const c of reg.partitionClauses) {\n if (c.op === '==' && c.value !== value) return true\n if (c.op === '!=' && c.value === value) return true\n if (c.op === 'in' && Array.isArray(c.value)) {\n const list = c.value as readonly unknown[]\n if (!list.includes(value)) return true\n }\n }\n return false\n}\n"],"mappings":";;;;;;;;;;AAwBO,SAAS,oBAAoB,OAAgC;AAClE,QAAM,OAAO,oBAAI,IAAY;AAC7B,QAAM,OAAO,MAAM,MAAM;AACzB,QAAM,MAAM,MAAM,aAAa;AAG/B,MAAI,KAAK,gBAAgB;AACvB,SAAK,IAAI,IAAI,cAAc;AAAA,EAC7B;AAGA,aAAW,OAAO,KAAK,OAAO;AAC5B,SAAK,IAAI,IAAI,MAAM;AAAA,EACrB;AAIA,aAAW,UAAU,KAAK,SAAS;AACjC,QAAI,OAAO,SAAS,aAAa;AAC/B,WAAK,IAA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AAQ,EAAE,UAAU,MAAO,QAAO;AAC/C,QAAI,EAAE,OAAO,QAAQ,EAAE,UAAU,MAAO,QAAO;AAC/C,QAAI,EAAE,OAAO,QAAQ,MAAM,QAAQ,EAAE,KAAK,GAAG;AAC3C,YAAM,OAAO,EAAE;AACf,UAAI,CAAC,KAAK,SAAS,KAAK,EAAG,QAAO;AAAA,IACpC;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
@@ -7,21 +7,21 @@ import {
7
7
  hashEntry,
8
8
  paddedIndex,
9
9
  sha256Hex
10
- } from "./chunk-47F6AI2K.js";
10
+ } from "./chunk-GU5XWSH4.js";
11
11
  import {
12
12
  buildRecordAad,
13
13
  openEnvelopeJson
14
- } from "./chunk-DIVPOJPV.js";
14
+ } from "./chunk-43FOH2OK.js";
15
15
  import {
16
16
  buildRecordEnvelope
17
- } from "./chunk-PENPHA45.js";
17
+ } from "./chunk-FX3UIDCS.js";
18
18
  import {
19
19
  encrypt
20
- } from "./chunk-O5QXH7U7.js";
20
+ } from "./chunk-D7STIWJO.js";
21
21
  import {
22
22
  LedgerContentionError,
23
23
  isConflictError
24
- } from "./chunk-PKUJ3JLQ.js";
24
+ } from "./chunk-5OFC3QYL.js";
25
25
 
26
26
  // src/with-commit/history/ledger/patch.ts
27
27
  function computePatch(prev, next) {
@@ -699,4 +699,4 @@ export {
699
699
  applyPatch,
700
700
  LedgerStore
701
701
  };
702
- //# sourceMappingURL=chunk-H27DIXOV.js.map
702
+ //# sourceMappingURL=chunk-FJGNYSB3.js.map