@noy-db/hub 0.6.0-pre.9 → 0.7.0-pre.0

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 (572) hide show
  1. package/CHANGELOG.md +7127 -0
  2. package/README.md +1 -1
  3. package/codemods/0.4.0-pre.json +24 -0
  4. package/codemods/0.6.0-pre.json +229 -0
  5. package/codemods/0.7.0-pre.json +258 -0
  6. package/dist/api-EQYRTZO2.js +20 -0
  7. package/dist/as/index.js +146 -0
  8. package/dist/as/index.js.map +1 -0
  9. package/dist/at/index.js +23 -0
  10. package/dist/attestation/index.js +19 -19
  11. package/dist/{backup-KULFZ2T4.js → backup-Z7ZBTAQ6.js} +36 -18
  12. package/dist/backup-Z7ZBTAQ6.js.map +1 -0
  13. package/dist/blobs/index.js +22 -20
  14. package/dist/blobs/index.js.map +1 -1
  15. package/dist/broker/index.js +12 -12
  16. package/dist/by/index.js +11 -0
  17. package/dist/cargo/index.js +40 -36
  18. package/dist/{chunk-YAWK6AWF.js → chunk-225O5CXQ.js} +2 -2
  19. package/dist/{chunk-MSWYQLMQ.js → chunk-2GXEQUEX.js} +2 -2
  20. package/dist/chunk-2GXEQUEX.js.map +1 -0
  21. package/dist/{chunk-3URQC7EH.js → chunk-2LPVI4PX.js} +355 -132
  22. package/dist/chunk-2LPVI4PX.js.map +1 -0
  23. package/dist/{chunk-JJNOLSG5.js → chunk-3L2MVE36.js} +15 -16
  24. package/dist/chunk-3L2MVE36.js.map +1 -0
  25. package/dist/{chunk-OF3L2SD6.js → chunk-3QARDAYW.js} +2 -2
  26. package/dist/{chunk-WLZ47GSL.js → chunk-467SKJ65.js} +12 -10
  27. package/dist/{chunk-WLZ47GSL.js.map → chunk-467SKJ65.js.map} +1 -1
  28. package/dist/{chunk-W3TVWF6N.js → chunk-4A4TYISP.js} +2 -2
  29. package/dist/{chunk-ZJADGNYF.js → chunk-4AOERLTV.js} +1 -1
  30. package/dist/chunk-4AOERLTV.js.map +1 -0
  31. package/dist/{chunk-CCZJJ4I2.js → chunk-4G25SDQL.js} +6 -6
  32. package/dist/{chunk-4I72F5DF.js → chunk-4LPF226H.js} +11 -14
  33. package/dist/chunk-4LPF226H.js.map +1 -0
  34. package/dist/{chunk-7F4DBNSP.js → chunk-4ZPE6SKS.js} +135 -18
  35. package/dist/chunk-4ZPE6SKS.js.map +1 -0
  36. package/dist/{chunk-7TSYBD3E.js → chunk-5263OEM3.js} +2 -2
  37. package/dist/{chunk-WFUIE565.js → chunk-57JTHWLQ.js} +17 -14
  38. package/dist/chunk-57JTHWLQ.js.map +1 -0
  39. package/dist/{chunk-FNSMZQS4.js → chunk-5ACAVJUI.js} +2 -2
  40. package/dist/{chunk-PDLLCOGD.js → chunk-5AFMP532.js} +20 -17
  41. package/dist/chunk-5AFMP532.js.map +1 -0
  42. package/dist/{chunk-JRKZTEZZ.js → chunk-5W7YXFV5.js} +444 -73
  43. package/dist/chunk-5W7YXFV5.js.map +1 -0
  44. package/dist/chunk-6EW2UCVF.js +190 -0
  45. package/dist/chunk-6EW2UCVF.js.map +1 -0
  46. package/dist/{chunk-4VUPLMZ6.js → chunk-6FOGTKBY.js} +68 -73
  47. package/dist/chunk-6FOGTKBY.js.map +1 -0
  48. package/dist/{chunk-VMCCGUQB.js → chunk-7LYUJNU3.js} +2 -2
  49. package/dist/{chunk-52JPHN5N.js → chunk-A2YW5EMU.js} +27 -149
  50. package/dist/chunk-A2YW5EMU.js.map +1 -0
  51. package/dist/{chunk-WLYIROCJ.js → chunk-AB5P32RE.js} +2 -2
  52. package/dist/{chunk-PL2GHSCM.js → chunk-ALB64CZM.js} +157 -90
  53. package/dist/chunk-ALB64CZM.js.map +1 -0
  54. package/dist/{chunk-SUFG5E73.js → chunk-ALUNQEBY.js} +2 -2
  55. package/dist/{chunk-CADUYBQD.js → chunk-ATL3ZVXT.js} +2 -2
  56. package/dist/{chunk-BWVKEOPE.js → chunk-ATV637J7.js} +7 -11
  57. package/dist/chunk-ATV637J7.js.map +1 -0
  58. package/dist/{chunk-DG27IUVI.js → chunk-CBRS2NEK.js} +2 -11
  59. package/dist/chunk-CBRS2NEK.js.map +1 -0
  60. package/dist/{chunk-7MNBICB5.js → chunk-CN6B5PEN.js} +16 -14
  61. package/dist/chunk-CN6B5PEN.js.map +1 -0
  62. package/dist/{chunk-6FJWSWFT.js → chunk-DBNYPLWY.js} +3 -3
  63. package/dist/{chunk-5JY5TSVY.js → chunk-DFAUMLD7.js} +25 -31
  64. package/dist/chunk-DFAUMLD7.js.map +1 -0
  65. package/dist/{chunk-FFDNKRCY.js → chunk-DKWPJOYH.js} +2 -2
  66. package/dist/chunk-DKWPJOYH.js.map +1 -0
  67. package/dist/{chunk-VJFMXYKP.js → chunk-E6YA6UAP.js} +2 -2
  68. package/dist/{chunk-WASHZV34.js → chunk-F23WQK3G.js} +65 -27
  69. package/dist/chunk-F23WQK3G.js.map +1 -0
  70. package/dist/{chunk-JIUVJ4M7.js → chunk-F7ZFRPGQ.js} +3 -3
  71. package/dist/{chunk-HXGUIPQB.js → chunk-FOG7YEJP.js} +3 -3
  72. package/dist/{chunk-QULVCV3M.js → chunk-GK4DRVUD.js} +6 -6
  73. package/dist/chunk-GK4DRVUD.js.map +1 -0
  74. package/dist/{chunk-BRVW2GS5.js → chunk-H36KSN6X.js} +87 -34
  75. package/dist/chunk-H36KSN6X.js.map +1 -0
  76. package/dist/{chunk-O2ERS4UJ.js → chunk-H4M7ADXY.js} +81 -52
  77. package/dist/chunk-H4M7ADXY.js.map +1 -0
  78. package/dist/{chunk-FZ6NYJ7L.js → chunk-H7HP56F6.js} +11 -8
  79. package/dist/chunk-H7HP56F6.js.map +1 -0
  80. package/dist/chunk-HK67PX4J.js +27 -0
  81. package/dist/chunk-HK67PX4J.js.map +1 -0
  82. package/dist/{chunk-X56RTUK3.js → chunk-HM4JSXX2.js} +3 -3
  83. package/dist/{chunk-AHLJSVRL.js → chunk-HTGRQZFB.js} +5 -7
  84. package/dist/chunk-HTGRQZFB.js.map +1 -0
  85. package/dist/{chunk-GQ3BX5EA.js → chunk-I3ISCYT7.js} +2 -2
  86. package/dist/{chunk-Q6TEJXBX.js → chunk-IESNYJXZ.js} +31 -49
  87. package/dist/chunk-IESNYJXZ.js.map +1 -0
  88. package/dist/{chunk-FUHKW252.js → chunk-J4MN6XIU.js} +2 -2
  89. package/dist/{chunk-ADW22QSB.js → chunk-J4UJ5FRV.js} +4 -4
  90. package/dist/{chunk-HNGSV2YC.js → chunk-JBIV4FLR.js} +67 -10
  91. package/dist/chunk-JBIV4FLR.js.map +1 -0
  92. package/dist/{chunk-HVQGCKY4.js → chunk-JVLSU7S2.js} +2 -2
  93. package/dist/{chunk-AR2JDFAE.js → chunk-KDJGJR7F.js} +2 -2
  94. package/dist/{chunk-NPP5R7FF.js → chunk-KN4W2OQ4.js} +22 -18
  95. package/dist/chunk-KN4W2OQ4.js.map +1 -0
  96. package/dist/{chunk-G6S5VVHP.js → chunk-L6GTLZRK.js} +10 -10
  97. package/dist/chunk-L6GTLZRK.js.map +1 -0
  98. package/dist/{chunk-2BMRJ6LQ.js → chunk-LF6DMX4C.js} +8 -11
  99. package/dist/{chunk-2BMRJ6LQ.js.map → chunk-LF6DMX4C.js.map} +1 -1
  100. package/dist/chunk-LFUID7OW.js +163 -0
  101. package/dist/chunk-LFUID7OW.js.map +1 -0
  102. package/dist/{chunk-747LRSOO.js → chunk-LKFKXS5K.js} +2 -2
  103. package/dist/{chunk-U5O6GIWZ.js → chunk-LR4Z47QD.js} +3 -3
  104. package/dist/{chunk-VZ3XFUQ7.js → chunk-MTBXJAS4.js} +16 -22
  105. package/dist/chunk-MTBXJAS4.js.map +1 -0
  106. package/dist/chunk-N4CNVSUF.js +66 -0
  107. package/dist/chunk-N4CNVSUF.js.map +1 -0
  108. package/dist/{chunk-RTAMLDWP.js → chunk-NLKLXXTO.js} +2 -2
  109. package/dist/{chunk-IGJCYUT5.js → chunk-NSITFOCJ.js} +1 -1
  110. package/dist/chunk-NSITFOCJ.js.map +1 -0
  111. package/dist/{chunk-FDX7OWWI.js → chunk-OPXR4PB2.js} +2 -2
  112. package/dist/{chunk-4GZ6XOVW.js → chunk-OWLVBOWO.js} +44 -42
  113. package/dist/chunk-OWLVBOWO.js.map +1 -0
  114. package/dist/{chunk-Z45YRGFO.js → chunk-P6ASQOZR.js} +2 -2
  115. package/dist/{chunk-5O5HRRTV.js → chunk-PCQDY6QN.js} +7 -7
  116. package/dist/{chunk-5O5HRRTV.js.map → chunk-PCQDY6QN.js.map} +1 -1
  117. package/dist/{chunk-BEFVYAR5.js → chunk-PGFKIOR3.js} +4 -4
  118. package/dist/chunk-PGFKIOR3.js.map +1 -0
  119. package/dist/{chunk-3FSX6LDG.js → chunk-POS53FG6.js} +18 -3
  120. package/dist/{chunk-3FSX6LDG.js.map → chunk-POS53FG6.js.map} +1 -1
  121. package/dist/{chunk-3IXIU6FP.js → chunk-PQ6Z2TAP.js} +7 -10
  122. package/dist/chunk-PQ6Z2TAP.js.map +1 -0
  123. package/dist/{chunk-CEJWMBXO.js → chunk-PUJTKLPL.js} +6 -2
  124. package/dist/chunk-PUJTKLPL.js.map +1 -0
  125. package/dist/{chunk-GAG7QOVO.js → chunk-QGJ4XIA7.js} +53 -18
  126. package/dist/chunk-QGJ4XIA7.js.map +1 -0
  127. package/dist/{chunk-2DHSSLOD.js → chunk-QHJKK77B.js} +13 -15
  128. package/dist/chunk-QHJKK77B.js.map +1 -0
  129. package/dist/{chunk-2Z3NCLNX.js → chunk-QI5NWLVW.js} +7 -7
  130. package/dist/{chunk-6SAFL5YE.js → chunk-RC4BROYR.js} +3 -3
  131. package/dist/{chunk-NJDQ4YSV.js → chunk-RDHUZ674.js} +4 -4
  132. package/dist/{chunk-YPYHVOXP.js → chunk-RK7N4OQ5.js} +2 -2
  133. package/dist/chunk-RK7N4OQ5.js.map +1 -0
  134. package/dist/{chunk-3737A6EA.js → chunk-S2VG3ABP.js} +127 -31
  135. package/dist/chunk-S2VG3ABP.js.map +1 -0
  136. package/dist/{chunk-3JVXVJ7L.js → chunk-S35S77YU.js} +10 -10
  137. package/dist/{chunk-KUDZVJKQ.js → chunk-SHILAQH5.js} +2 -2
  138. package/dist/{chunk-4UVDI4XE.js → chunk-T3PHCEN4.js} +4 -4
  139. package/dist/{chunk-55LKVALY.js → chunk-T7IR4N2S.js} +1 -3
  140. package/dist/chunk-T7IR4N2S.js.map +1 -0
  141. package/dist/{chunk-RXYYFSBB.js → chunk-TOV6VMHF.js} +6 -6
  142. package/dist/chunk-TOV6VMHF.js.map +1 -0
  143. package/dist/{chunk-W77KZHCW.js → chunk-TVIFAHZR.js} +16 -17
  144. package/dist/chunk-TVIFAHZR.js.map +1 -0
  145. package/dist/chunk-UBSFPGVJ.js +1 -0
  146. package/dist/{chunk-FAXZQ5UF.js → chunk-UCUALOSM.js} +2 -2
  147. package/dist/{chunk-4HDYQL3J.js → chunk-VAG47QHV.js} +2 -2
  148. package/dist/{chunk-35EBKWQU.js → chunk-VFIWDPXZ.js} +4 -4
  149. package/dist/{chunk-5ZKS6ZE2.js → chunk-VTG7327U.js} +4 -4
  150. package/dist/chunk-VTG7327U.js.map +1 -0
  151. package/dist/{chunk-VCETL77O.js → chunk-W5LHQXZU.js} +36 -7
  152. package/dist/chunk-W5LHQXZU.js.map +1 -0
  153. package/dist/{chunk-6NVPFKN3.js → chunk-WK5FSW7T.js} +92 -35
  154. package/dist/chunk-WK5FSW7T.js.map +1 -0
  155. package/dist/{chunk-HNHCQ556.js → chunk-WLLUM35R.js} +2 -2
  156. package/dist/{chunk-YJ6IONGA.js → chunk-X62MEF2O.js} +13 -5
  157. package/dist/chunk-X62MEF2O.js.map +1 -0
  158. package/dist/{chunk-7G6VDWXB.js → chunk-X67FCULK.js} +5 -5
  159. package/dist/chunk-X67FCULK.js.map +1 -0
  160. package/dist/{chunk-UHXCLPGC.js → chunk-XDVVBETV.js} +2 -2
  161. package/dist/chunk-XDVVBETV.js.map +1 -0
  162. package/dist/chunk-XJ3FEKEY.js +15 -0
  163. package/dist/chunk-XJ3FEKEY.js.map +1 -0
  164. package/dist/{chunk-E6427JU2.js → chunk-XSN63FUS.js} +19 -3
  165. package/dist/chunk-XSN63FUS.js.map +1 -0
  166. package/dist/{chunk-JRCYZEHU.js → chunk-XVU7J43V.js} +2 -2
  167. package/dist/{chunk-2GAJGUNM.js → chunk-Y3YLJORD.js} +408 -260
  168. package/dist/chunk-Y3YLJORD.js.map +1 -0
  169. package/dist/{chunk-6BU3L4UE.js → chunk-Y6GZ2P4M.js} +7 -10
  170. package/dist/chunk-Y6GZ2P4M.js.map +1 -0
  171. package/dist/{chunk-DMQCLZ4Z.js → chunk-YCSM3GZU.js} +2 -2
  172. package/dist/{chunk-RV3ARMPN.js → chunk-YKPGQJFU.js} +30 -180
  173. package/dist/chunk-YKPGQJFU.js.map +1 -0
  174. package/dist/{chunk-FMQJZH4R.js → chunk-YMLQBZFJ.js} +6 -6
  175. package/dist/{chunk-6HFM7EIT.js → chunk-YPSOHDNC.js} +2 -2
  176. package/dist/{chunk-CDB2HVQW.js → chunk-YXA2TCTZ.js} +14 -15
  177. package/dist/chunk-YXA2TCTZ.js.map +1 -0
  178. package/dist/{chunk-N35NC4JH.js → chunk-Z2PWOSCJ.js} +2 -2
  179. package/dist/{chunk-XWX7GL56.js → chunk-Z2WK53N6.js} +47 -23
  180. package/dist/chunk-Z2WK53N6.js.map +1 -0
  181. package/dist/{chunk-HPLWFNG4.js → chunk-Z7ZXZL6Y.js} +2 -2
  182. package/dist/{chunk-PNKHAKQ7.js → chunk-ZO252Q5S.js} +17 -10
  183. package/dist/chunk-ZO252Q5S.js.map +1 -0
  184. package/dist/classified/index.js +5 -5
  185. package/dist/{classified-marker-2KJAXRRO.js → classified-marker-BSQHU4JT.js} +3 -3
  186. package/dist/collection-facade-LG3NYZVB.js +45 -0
  187. package/dist/{computed-6G5M3UPH.js → computed-ASBNTLOK.js} +3 -3
  188. package/dist/consent/index.js +10 -10
  189. package/dist/cover/index.js +10 -3
  190. package/dist/custody/index.js +12 -11
  191. package/dist/{dead-filter-DCB62VWW.js → dead-filter-QKU56XTQ.js} +2 -2
  192. package/dist/debug/index.js +1 -1
  193. package/dist/{delegation-MO7YZYJS.js → delegation-XWRPYODW.js} +24 -23
  194. package/dist/delegation-XWRPYODW.js.map +1 -0
  195. package/dist/derivations/index.js +12 -12
  196. package/dist/derive-CXHCY46K.js +22 -0
  197. package/dist/directory/index.js +10 -10
  198. package/dist/{dispatch-MJ6SHB3Y.js → dispatch-4AP4PUZU.js} +18 -18
  199. package/dist/{dispatch-FZEAWKVM.js → dispatch-VR4LRXZ7.js} +9 -6
  200. package/dist/dispatch-VR4LRXZ7.js.map +1 -0
  201. package/dist/{enclave-JU4YIEPB.js → enclave-NYPT7WA7.js} +31 -9
  202. package/dist/executor-3KFRQETS.js +29 -0
  203. package/dist/executor-AFHQYRAU.js +9 -0
  204. package/dist/executor-YYDW6XQI.js +9 -0
  205. package/dist/export-accessible-BX2ILB4C.js +23 -0
  206. package/dist/extract-partition-UPOVITFI.js +38 -0
  207. package/dist/{fanout-sidecar-NNAJQXMX.js → fanout-sidecar-IWP3R4RC.js} +18 -27
  208. package/dist/fanout-sidecar-IWP3R4RC.js.map +1 -0
  209. package/dist/{fence-watcher-DHQ775JB.js → fence-watcher-ZVSMLKQD.js} +1 -1
  210. package/dist/fence-watcher-ZVSMLKQD.js.map +1 -0
  211. package/dist/find-SZBL2HPB.js +11 -0
  212. package/dist/forget/index.js +9 -9
  213. package/dist/guards/index.js +4 -4
  214. package/dist/history/index.js +23 -20
  215. package/dist/history/index.js.map +1 -1
  216. package/dist/i18n/index.js +14 -14
  217. package/dist/index.d.ts +35 -18
  218. package/dist/index.js +199 -204
  219. package/dist/index.js.map +1 -1
  220. package/dist/indexing/index.js +4 -4
  221. package/dist/introspection/index.js +12 -11
  222. package/dist/issue-G53NB6EW.js +19 -0
  223. package/dist/kernel/collection-config.d.ts +9 -9
  224. package/dist/kernel/collection.d.ts +9 -3
  225. package/dist/kernel/constants.d.ts +36 -0
  226. package/dist/kernel/enclave/crypto.d.ts +52 -4
  227. package/dist/kernel/enclave/index.d.ts +10 -3
  228. package/dist/kernel/enclave/record-aad.d.ts +131 -0
  229. package/dist/kernel/enclave/record-envelope.d.ts +76 -0
  230. package/dist/kernel/enclave/record-keys/envelope-body.d.ts +34 -2
  231. package/dist/kernel/enclave/record-keys/lifecycle.d.ts +22 -5
  232. package/dist/kernel/enclave/record-keys/record-codec.d.ts +47 -14
  233. package/dist/kernel/enclave/record-keys/rekey-blob.d.ts +88 -0
  234. package/dist/kernel/enclave/record-keys/rekey.d.ts +91 -0
  235. package/dist/kernel/enclave/record-keys/tombstone.d.ts +3 -2
  236. package/dist/kernel/errors.d.ts +134 -14
  237. package/dist/kernel/merge-authority.d.ts +25 -0
  238. package/dist/kernel/noydb.d.ts +33 -10
  239. package/dist/kernel/query/builder.d.ts +51 -4
  240. package/dist/kernel/query/join.d.ts +27 -0
  241. package/dist/kernel/query/live.d.ts +31 -9
  242. package/dist/kernel/query/predicate.d.ts +9 -0
  243. package/dist/kernel/refs.d.ts +3 -1
  244. package/dist/kernel/secret-mode.d.ts +1 -1
  245. package/dist/kernel/sync-policy.d.ts +0 -2
  246. package/dist/kernel/tier-visibility.d.ts +34 -0
  247. package/dist/kernel/types.d.ts +145 -28
  248. package/dist/kernel/vault.d.ts +16 -7
  249. package/dist/kernel/via/compose.d.ts +3 -3
  250. package/dist/kernel/via/index.d.ts +15 -6
  251. package/dist/kernel/via/pipeline.d.ts +6 -6
  252. package/dist/kernel/via/reconcile.d.ts +14 -2
  253. package/dist/kernel/via/taint-binding.d.ts +3 -3
  254. package/dist/{ledger-AETNF4OM.js → ledger-T5K4P2D7.js} +11 -11
  255. package/dist/liberate-VEOZRESE.js +25 -0
  256. package/dist/{link-set-E5HNY67I.js → link-set-76JZ6YB4.js} +11 -11
  257. package/dist/{managed-secret-CWQ6PND5.js → managed-secret-6YC32VXG.js} +13 -5
  258. package/dist/materialized-views/index.js +27 -27
  259. package/dist/migrate-cek-LBRKYUZZ.js +19 -0
  260. package/dist/migrate-cek-LBRKYUZZ.js.map +1 -0
  261. package/dist/money/index.js +5 -5
  262. package/dist/noydb-EDJA4JNJ.js +86 -0
  263. package/dist/on/index.js +1 -0
  264. package/dist/overlay-views/index.js +4 -4
  265. package/dist/periods/index.js +12 -12
  266. package/dist/pod/index.js +79 -88
  267. package/dist/pod-handle-P6DPBM5U.js +41 -0
  268. package/dist/pod-handle-P6DPBM5U.js.map +1 -0
  269. package/dist/policy/index.js +11 -4
  270. package/dist/port/as/active.d.ts +10 -0
  271. package/dist/port/as/index.d.ts +32 -0
  272. package/dist/port/as/types.d.ts +113 -0
  273. package/dist/port/at/index.d.ts +37 -0
  274. package/dist/port/by/default-provider.d.ts +3 -3
  275. package/dist/port/by/index.d.ts +32 -10
  276. package/dist/port/by/types.d.ts +29 -11
  277. package/dist/port/on/index.d.ts +50 -0
  278. package/dist/port/to/index.d.ts +4 -4
  279. package/dist/port/to/locator.d.ts +54 -8
  280. package/dist/port/with/computed-strategy.d.ts +1 -1
  281. package/dist/port/with/device-seal-strategy.d.ts +2 -2
  282. package/dist/port/with/formats-strategy.d.ts +76 -0
  283. package/dist/port/with/i18n-strategy.d.ts +4 -1
  284. package/dist/port/with/lookup-strategy.d.ts +4 -1
  285. package/dist/port/with/merge-authority.d.ts +52 -0
  286. package/dist/port/with/service-bus.d.ts +0 -4
  287. package/dist/port/with/strategies.d.ts +13 -5
  288. package/dist/port/with/team-strategy.d.ts +5 -1
  289. package/dist/portability/index.js +8 -8
  290. package/dist/{post-register-2XSSMGEQ.js → post-register-53O7AJRZ.js} +6 -6
  291. package/dist/query/index.js +6 -6
  292. package/dist/reduce/index.js +6 -6
  293. package/dist/register-6TCBR6XD.js +32 -0
  294. package/dist/registry-DH2L4O2V.js +18 -0
  295. package/dist/registry-IWFMXCHX.js +9 -0
  296. package/dist/registry-Q3FG3OAX.js +9 -0
  297. package/dist/registry-YC3IFG3A.js +19 -0
  298. package/dist/request-withdrawal-NM5VYR6F.js +31 -0
  299. package/dist/{reveal-BW36KCOQ.js → reveal-XBIMHAXR.js} +6 -6
  300. package/dist/revoke-MJNYWO72.js +24 -0
  301. package/dist/satellites/index.js +1 -1
  302. package/dist/schema-update/index.js +2 -2
  303. package/dist/sealed-record/index.js +20 -13
  304. package/dist/sealed-record/index.js.map +1 -1
  305. package/dist/search/index.js +4 -4
  306. package/dist/{seed-GDV5PT4R.js → seed-NSNIGYXE.js} +20 -22
  307. package/dist/seed-NSNIGYXE.js.map +1 -0
  308. package/dist/sequence/index.js +9 -9
  309. package/dist/session/index.js +10 -10
  310. package/dist/shadow/index.js +2 -2
  311. package/dist/share-link/index.js +1 -1
  312. package/dist/signer-6XVS2AU3.js +25 -0
  313. package/dist/snapshots/index.js +10 -10
  314. package/dist/snapshots/index.js.map +1 -1
  315. package/dist/{stale-ARHFVL5U.js → stale-MCS46TFO.js} +10 -10
  316. package/dist/storage-ZXUT476I.js +23 -0
  317. package/dist/storage-ZXUT476I.js.map +1 -0
  318. package/dist/{store-coordination-provider-GFCUOBR6.js → store-coordination-provider-6FM26VQM.js} +22 -15
  319. package/dist/store-coordination-provider-6FM26VQM.js.map +1 -0
  320. package/dist/sync/index.js +11 -11
  321. package/dist/team/index.js +17 -16
  322. package/dist/tiers/index.js +11 -10
  323. package/dist/to/index.js +17 -9
  324. package/dist/to/index.js.map +1 -1
  325. package/dist/transactions/index.js +4 -4
  326. package/dist/{ulid-PTAIMDG4.js → ulid-VQW6ERQN.js} +2 -2
  327. package/dist/ulid-VQW6ERQN.js.map +1 -0
  328. package/dist/util/index.js +1 -1
  329. package/dist/vault-diff-FE5J35NJ.js +9 -0
  330. package/dist/vault-diff-FE5J35NJ.js.map +1 -0
  331. package/dist/vault-head/index.js +115 -0
  332. package/dist/vault-head/index.js.map +1 -0
  333. package/dist/{verify-RO5RTZOJ.js → verify-WYOFLSNA.js} +5 -5
  334. package/dist/via/blob/binding.d.ts +6 -6
  335. package/dist/via/blob/index.d.ts +3 -0
  336. package/dist/via/classified/binding.d.ts +9 -9
  337. package/dist/via/computed/binding.d.ts +2 -2
  338. package/dist/via/i18n/binding.d.ts +4 -4
  339. package/dist/via/lookup/binding.d.ts +5 -5
  340. package/dist/via/lookup/handle.d.ts +4 -1
  341. package/dist/via/lookup/index.d.ts +1 -1
  342. package/dist/via/lookup/snapshot.d.ts +1 -1
  343. package/dist/via/money/binding.d.ts +3 -3
  344. package/dist/via/money/normalize.d.ts +1 -1
  345. package/dist/via/money/where.d.ts +3 -3
  346. package/dist/walk-JNEOYCAU.js +21 -0
  347. package/dist/walk-JNEOYCAU.js.map +1 -0
  348. package/dist/with-audit/periods/periods.d.ts +1 -1
  349. package/dist/with-audit/periods/strategy.d.ts +1 -1
  350. package/dist/with-audit/sealed-record/index.d.ts +13 -0
  351. package/dist/with-audit/tiers/index.d.ts +17 -2
  352. package/dist/with-cargo/adopt-partition.d.ts +7 -7
  353. package/dist/with-cargo/extract-partition.d.ts +1 -1
  354. package/dist/with-cargo/floor.d.ts +1 -1
  355. package/dist/with-cargo/index.d.ts +2 -2
  356. package/dist/with-commit/history/history.d.ts +26 -0
  357. package/dist/with-commit/history/index.d.ts +2 -1
  358. package/dist/with-commit/history/ledger/store.d.ts +7 -1
  359. package/dist/with-commit/history/strategy.d.ts +11 -1
  360. package/dist/with-commit/numbering/index.d.ts +0 -5
  361. package/dist/with-commit/vault-head/active.d.ts +2 -0
  362. package/dist/with-commit/vault-head/head.d.ts +28 -0
  363. package/dist/with-commit/vault-head/index.d.ts +10 -0
  364. package/dist/with-commit/vault-head/strategy.d.ts +127 -0
  365. package/dist/with-commit/vault-head/verify.d.ts +90 -0
  366. package/dist/with-formula/materialized-views/dependency-analyzer.d.ts +4 -0
  367. package/dist/with-formula/materialized-views/projection-legs.d.ts +59 -0
  368. package/dist/with-formula/materialized-views/registry.d.ts +50 -0
  369. package/dist/with-formula/materialized-views/types.d.ts +68 -10
  370. package/dist/with-party/directory/cover/storage.d.ts +0 -8
  371. package/dist/with-party/directory/storage.d.ts +0 -11
  372. package/dist/with-party/directory/visibility.d.ts +0 -21
  373. package/dist/with-party/policy/storage.d.ts +0 -10
  374. package/dist/with-party/team/deed.d.ts +4 -4
  375. package/dist/with-party/team/device-seal.d.ts +5 -5
  376. package/dist/with-party/team/echo-ceremony.d.ts +2 -2
  377. package/dist/with-party/team/echo-secret.d.ts +4 -4
  378. package/dist/with-party/team/index.d.ts +3 -3
  379. package/dist/with-party/team/keyring.d.ts +141 -4
  380. package/dist/with-party/team/managed-secret.d.ts +21 -11
  381. package/dist/with-party/team/noydb-facade.d.ts +7 -3
  382. package/dist/with-party/team/{shamir-recovery-provider.d.ts → noydb-shamir.d.ts} +1 -1
  383. package/dist/with-party/team/recovery.d.ts +3 -3
  384. package/dist/with-party/team/roster-tag.d.ts +101 -0
  385. package/dist/with-party/team/rotate-recover.d.ts +5 -5
  386. package/dist/with-party/team/tiers.d.ts +2 -1
  387. package/dist/with-pod/format.d.ts +11 -13
  388. package/dist/with-pod/index.d.ts +10 -10
  389. package/dist/with-pod/open.d.ts +2 -2
  390. package/dist/with-pod/pod-handle.d.ts +19 -0
  391. package/dist/with-pod/pod-store.d.ts +0 -8
  392. package/dist/with-pod/{bundle.d.ts → pod.d.ts} +17 -25
  393. package/dist/with-pod/ulid.d.ts +1 -1
  394. package/dist/with-shape/blobs/blob-compaction.d.ts +13 -0
  395. package/dist/with-shape/blobs/blob-set.d.ts +83 -11
  396. package/dist/with-shape/blobs/orphan-report.d.ts +62 -0
  397. package/dist/with-shape/introspection/describe.d.ts +2 -2
  398. package/dist/with-shape/schema-update/fence-controller.d.ts +4 -4
  399. package/dist/with-shape/schema-update/fence-watcher.d.ts +4 -4
  400. package/dist/with-shape/schema-update/store-coordination-provider.d.ts +7 -6
  401. package/dist/with-sync/engine.d.ts +54 -5
  402. package/dist/with-sync/strategy.d.ts +3 -0
  403. package/dist/withdraw-accessible-ILTSXTIE.js +28 -0
  404. package/dist/withdraw-accessible-ILTSXTIE.js.map +1 -0
  405. package/package.json +29 -5
  406. package/dist/api-RXUMEKT3.js +0 -20
  407. package/dist/backup-KULFZ2T4.js.map +0 -1
  408. package/dist/bundle-handle-GFNHT52M.js +0 -36
  409. package/dist/bundle-handle-GFNHT52M.js.map +0 -1
  410. package/dist/chunk-2DHSSLOD.js.map +0 -1
  411. package/dist/chunk-2GAJGUNM.js.map +0 -1
  412. package/dist/chunk-3737A6EA.js.map +0 -1
  413. package/dist/chunk-3IXIU6FP.js.map +0 -1
  414. package/dist/chunk-3URQC7EH.js.map +0 -1
  415. package/dist/chunk-4GZ6XOVW.js.map +0 -1
  416. package/dist/chunk-4I72F5DF.js.map +0 -1
  417. package/dist/chunk-4VUPLMZ6.js.map +0 -1
  418. package/dist/chunk-52JPHN5N.js.map +0 -1
  419. package/dist/chunk-55LKVALY.js.map +0 -1
  420. package/dist/chunk-5JY5TSVY.js.map +0 -1
  421. package/dist/chunk-5ZKS6ZE2.js.map +0 -1
  422. package/dist/chunk-6BU3L4UE.js.map +0 -1
  423. package/dist/chunk-6NVPFKN3.js.map +0 -1
  424. package/dist/chunk-7F4DBNSP.js.map +0 -1
  425. package/dist/chunk-7G6VDWXB.js.map +0 -1
  426. package/dist/chunk-7H73RIE3.js +0 -45
  427. package/dist/chunk-7H73RIE3.js.map +0 -1
  428. package/dist/chunk-7MNBICB5.js.map +0 -1
  429. package/dist/chunk-AFHQATY4.js +0 -47
  430. package/dist/chunk-AFHQATY4.js.map +0 -1
  431. package/dist/chunk-AHLJSVRL.js.map +0 -1
  432. package/dist/chunk-BEFVYAR5.js.map +0 -1
  433. package/dist/chunk-BRVW2GS5.js.map +0 -1
  434. package/dist/chunk-BWVKEOPE.js.map +0 -1
  435. package/dist/chunk-CDB2HVQW.js.map +0 -1
  436. package/dist/chunk-CEJWMBXO.js.map +0 -1
  437. package/dist/chunk-DG27IUVI.js.map +0 -1
  438. package/dist/chunk-E6427JU2.js.map +0 -1
  439. package/dist/chunk-FFDNKRCY.js.map +0 -1
  440. package/dist/chunk-FZ6NYJ7L.js.map +0 -1
  441. package/dist/chunk-G6S5VVHP.js.map +0 -1
  442. package/dist/chunk-GAG7QOVO.js.map +0 -1
  443. package/dist/chunk-HNGSV2YC.js.map +0 -1
  444. package/dist/chunk-IGJCYUT5.js.map +0 -1
  445. package/dist/chunk-JJNOLSG5.js.map +0 -1
  446. package/dist/chunk-JRKZTEZZ.js.map +0 -1
  447. package/dist/chunk-MSWYQLMQ.js.map +0 -1
  448. package/dist/chunk-NPP5R7FF.js.map +0 -1
  449. package/dist/chunk-O2ERS4UJ.js.map +0 -1
  450. package/dist/chunk-PDLLCOGD.js.map +0 -1
  451. package/dist/chunk-PL2GHSCM.js.map +0 -1
  452. package/dist/chunk-PNKHAKQ7.js.map +0 -1
  453. package/dist/chunk-Q6TEJXBX.js.map +0 -1
  454. package/dist/chunk-QULVCV3M.js.map +0 -1
  455. package/dist/chunk-RV3ARMPN.js.map +0 -1
  456. package/dist/chunk-RXYYFSBB.js.map +0 -1
  457. package/dist/chunk-UHXCLPGC.js.map +0 -1
  458. package/dist/chunk-VCETL77O.js.map +0 -1
  459. package/dist/chunk-VZ3XFUQ7.js.map +0 -1
  460. package/dist/chunk-W77KZHCW.js.map +0 -1
  461. package/dist/chunk-WASHZV34.js.map +0 -1
  462. package/dist/chunk-WFUIE565.js.map +0 -1
  463. package/dist/chunk-XWX7GL56.js.map +0 -1
  464. package/dist/chunk-YJ6IONGA.js.map +0 -1
  465. package/dist/chunk-YPYHVOXP.js.map +0 -1
  466. package/dist/chunk-ZJADGNYF.js.map +0 -1
  467. package/dist/collection-facade-QEJIM6BC.js +0 -45
  468. package/dist/delegation-MO7YZYJS.js.map +0 -1
  469. package/dist/derive-IUA6JFLB.js +0 -22
  470. package/dist/dispatch-FZEAWKVM.js.map +0 -1
  471. package/dist/executor-CYJQLKKI.js +0 -9
  472. package/dist/executor-S4QIKEHW.js +0 -9
  473. package/dist/executor-YIQB2S6N.js +0 -29
  474. package/dist/export-accessible-4S36PQNR.js +0 -23
  475. package/dist/extract-partition-IO7FDZ2P.js +0 -38
  476. package/dist/fanout-sidecar-NNAJQXMX.js.map +0 -1
  477. package/dist/fence-watcher-DHQ775JB.js.map +0 -1
  478. package/dist/find-RBBYKXI7.js +0 -11
  479. package/dist/issue-RIVHSY2S.js +0 -19
  480. package/dist/liberate-GFN4C7RR.js +0 -24
  481. package/dist/noydb-ASEXNJS6.js +0 -83
  482. package/dist/register-4EFJCVYD.js +0 -32
  483. package/dist/registry-4SDHHOJ7.js +0 -18
  484. package/dist/registry-CZVINVQH.js +0 -9
  485. package/dist/registry-IKUR2MXD.js +0 -9
  486. package/dist/registry-OYTFGWVK.js +0 -19
  487. package/dist/request-withdrawal-KGXGDPVQ.js +0 -31
  488. package/dist/revoke-JFN773KF.js +0 -24
  489. package/dist/seed-GDV5PT4R.js.map +0 -1
  490. package/dist/signer-TA55QB6R.js +0 -25
  491. package/dist/storage-V7MTFAQJ.js +0 -23
  492. package/dist/store-coordination-provider-GFCUOBR6.js.map +0 -1
  493. package/dist/walk-3ZECBFDA.js +0 -21
  494. package/dist/with-pod/bundle-handle.d.ts +0 -9
  495. package/dist/withdraw-accessible-7PG4DYQK.js +0 -28
  496. /package/dist/{api-RXUMEKT3.js.map → api-EQYRTZO2.js.map} +0 -0
  497. /package/dist/{collection-facade-QEJIM6BC.js.map → at/index.js.map} +0 -0
  498. /package/dist/{computed-6G5M3UPH.js.map → by/index.js.map} +0 -0
  499. /package/dist/{chunk-YAWK6AWF.js.map → chunk-225O5CXQ.js.map} +0 -0
  500. /package/dist/{chunk-OF3L2SD6.js.map → chunk-3QARDAYW.js.map} +0 -0
  501. /package/dist/{chunk-W3TVWF6N.js.map → chunk-4A4TYISP.js.map} +0 -0
  502. /package/dist/{chunk-CCZJJ4I2.js.map → chunk-4G25SDQL.js.map} +0 -0
  503. /package/dist/{chunk-7TSYBD3E.js.map → chunk-5263OEM3.js.map} +0 -0
  504. /package/dist/{chunk-FNSMZQS4.js.map → chunk-5ACAVJUI.js.map} +0 -0
  505. /package/dist/{chunk-VMCCGUQB.js.map → chunk-7LYUJNU3.js.map} +0 -0
  506. /package/dist/{chunk-WLYIROCJ.js.map → chunk-AB5P32RE.js.map} +0 -0
  507. /package/dist/{chunk-SUFG5E73.js.map → chunk-ALUNQEBY.js.map} +0 -0
  508. /package/dist/{chunk-CADUYBQD.js.map → chunk-ATL3ZVXT.js.map} +0 -0
  509. /package/dist/{chunk-6FJWSWFT.js.map → chunk-DBNYPLWY.js.map} +0 -0
  510. /package/dist/{chunk-VJFMXYKP.js.map → chunk-E6YA6UAP.js.map} +0 -0
  511. /package/dist/{chunk-JIUVJ4M7.js.map → chunk-F7ZFRPGQ.js.map} +0 -0
  512. /package/dist/{chunk-HXGUIPQB.js.map → chunk-FOG7YEJP.js.map} +0 -0
  513. /package/dist/{chunk-X56RTUK3.js.map → chunk-HM4JSXX2.js.map} +0 -0
  514. /package/dist/{chunk-GQ3BX5EA.js.map → chunk-I3ISCYT7.js.map} +0 -0
  515. /package/dist/{chunk-FUHKW252.js.map → chunk-J4MN6XIU.js.map} +0 -0
  516. /package/dist/{chunk-ADW22QSB.js.map → chunk-J4UJ5FRV.js.map} +0 -0
  517. /package/dist/{chunk-HVQGCKY4.js.map → chunk-JVLSU7S2.js.map} +0 -0
  518. /package/dist/{chunk-AR2JDFAE.js.map → chunk-KDJGJR7F.js.map} +0 -0
  519. /package/dist/{chunk-747LRSOO.js.map → chunk-LKFKXS5K.js.map} +0 -0
  520. /package/dist/{chunk-U5O6GIWZ.js.map → chunk-LR4Z47QD.js.map} +0 -0
  521. /package/dist/{chunk-RTAMLDWP.js.map → chunk-NLKLXXTO.js.map} +0 -0
  522. /package/dist/{chunk-FDX7OWWI.js.map → chunk-OPXR4PB2.js.map} +0 -0
  523. /package/dist/{chunk-Z45YRGFO.js.map → chunk-P6ASQOZR.js.map} +0 -0
  524. /package/dist/{chunk-2Z3NCLNX.js.map → chunk-QI5NWLVW.js.map} +0 -0
  525. /package/dist/{chunk-6SAFL5YE.js.map → chunk-RC4BROYR.js.map} +0 -0
  526. /package/dist/{chunk-NJDQ4YSV.js.map → chunk-RDHUZ674.js.map} +0 -0
  527. /package/dist/{chunk-3JVXVJ7L.js.map → chunk-S35S77YU.js.map} +0 -0
  528. /package/dist/{chunk-KUDZVJKQ.js.map → chunk-SHILAQH5.js.map} +0 -0
  529. /package/dist/{chunk-4UVDI4XE.js.map → chunk-T3PHCEN4.js.map} +0 -0
  530. /package/dist/{derive-IUA6JFLB.js.map → chunk-UBSFPGVJ.js.map} +0 -0
  531. /package/dist/{chunk-FAXZQ5UF.js.map → chunk-UCUALOSM.js.map} +0 -0
  532. /package/dist/{chunk-4HDYQL3J.js.map → chunk-VAG47QHV.js.map} +0 -0
  533. /package/dist/{chunk-35EBKWQU.js.map → chunk-VFIWDPXZ.js.map} +0 -0
  534. /package/dist/{chunk-HNHCQ556.js.map → chunk-WLLUM35R.js.map} +0 -0
  535. /package/dist/{chunk-JRCYZEHU.js.map → chunk-XVU7J43V.js.map} +0 -0
  536. /package/dist/{chunk-DMQCLZ4Z.js.map → chunk-YCSM3GZU.js.map} +0 -0
  537. /package/dist/{chunk-FMQJZH4R.js.map → chunk-YMLQBZFJ.js.map} +0 -0
  538. /package/dist/{chunk-6HFM7EIT.js.map → chunk-YPSOHDNC.js.map} +0 -0
  539. /package/dist/{chunk-N35NC4JH.js.map → chunk-Z2PWOSCJ.js.map} +0 -0
  540. /package/dist/{chunk-HPLWFNG4.js.map → chunk-Z7ZXZL6Y.js.map} +0 -0
  541. /package/dist/{classified-marker-2KJAXRRO.js.map → classified-marker-BSQHU4JT.js.map} +0 -0
  542. /package/dist/{enclave-JU4YIEPB.js.map → collection-facade-LG3NYZVB.js.map} +0 -0
  543. /package/dist/{executor-CYJQLKKI.js.map → computed-ASBNTLOK.js.map} +0 -0
  544. /package/dist/{dead-filter-DCB62VWW.js.map → dead-filter-QKU56XTQ.js.map} +0 -0
  545. /package/dist/{executor-S4QIKEHW.js.map → derive-CXHCY46K.js.map} +0 -0
  546. /package/dist/{dispatch-MJ6SHB3Y.js.map → dispatch-4AP4PUZU.js.map} +0 -0
  547. /package/dist/{executor-YIQB2S6N.js.map → enclave-NYPT7WA7.js.map} +0 -0
  548. /package/dist/{export-accessible-4S36PQNR.js.map → executor-3KFRQETS.js.map} +0 -0
  549. /package/dist/{extract-partition-IO7FDZ2P.js.map → executor-AFHQYRAU.js.map} +0 -0
  550. /package/dist/{find-RBBYKXI7.js.map → executor-YYDW6XQI.js.map} +0 -0
  551. /package/dist/{issue-RIVHSY2S.js.map → export-accessible-BX2ILB4C.js.map} +0 -0
  552. /package/dist/{ledger-AETNF4OM.js.map → extract-partition-UPOVITFI.js.map} +0 -0
  553. /package/dist/{liberate-GFN4C7RR.js.map → find-SZBL2HPB.js.map} +0 -0
  554. /package/dist/{link-set-E5HNY67I.js.map → issue-G53NB6EW.js.map} +0 -0
  555. /package/dist/{managed-secret-CWQ6PND5.js.map → ledger-T5K4P2D7.js.map} +0 -0
  556. /package/dist/{noydb-ASEXNJS6.js.map → liberate-VEOZRESE.js.map} +0 -0
  557. /package/dist/{register-4EFJCVYD.js.map → link-set-76JZ6YB4.js.map} +0 -0
  558. /package/dist/{registry-4SDHHOJ7.js.map → managed-secret-6YC32VXG.js.map} +0 -0
  559. /package/dist/{registry-CZVINVQH.js.map → noydb-EDJA4JNJ.js.map} +0 -0
  560. /package/dist/{registry-IKUR2MXD.js.map → on/index.js.map} +0 -0
  561. /package/dist/{post-register-2XSSMGEQ.js.map → post-register-53O7AJRZ.js.map} +0 -0
  562. /package/dist/{registry-OYTFGWVK.js.map → register-6TCBR6XD.js.map} +0 -0
  563. /package/dist/{request-withdrawal-KGXGDPVQ.js.map → registry-DH2L4O2V.js.map} +0 -0
  564. /package/dist/{revoke-JFN773KF.js.map → registry-IWFMXCHX.js.map} +0 -0
  565. /package/dist/{signer-TA55QB6R.js.map → registry-Q3FG3OAX.js.map} +0 -0
  566. /package/dist/{stale-ARHFVL5U.js.map → registry-YC3IFG3A.js.map} +0 -0
  567. /package/dist/{storage-V7MTFAQJ.js.map → request-withdrawal-NM5VYR6F.js.map} +0 -0
  568. /package/dist/{reveal-BW36KCOQ.js.map → reveal-XBIMHAXR.js.map} +0 -0
  569. /package/dist/{ulid-PTAIMDG4.js.map → revoke-MJNYWO72.js.map} +0 -0
  570. /package/dist/{walk-3ZECBFDA.js.map → signer-6XVS2AU3.js.map} +0 -0
  571. /package/dist/{withdraw-accessible-7PG4DYQK.js.map → stale-MCS46TFO.js.map} +0 -0
  572. /package/dist/{verify-RO5RTZOJ.js.map → verify-WYOFLSNA.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/with-audit/forget/strategy.ts","../src/with-audit/forget/subject-index.ts"],"sourcesContent":["/**\n * `withForget` — declaration surface for GDPR right-to-erasure via\n * per-record CEK crypto-shred.\n *\n * This file holds only the *declaration* shape and the disabled sentinel.\n * The actual erasure machinery lives in:\n * - `subject-index.ts` — the encrypted `_subject_index` reserved collection\n * - `vault.ts` `forget()` — the per-record tombstone + ledger flow\n * - `collection.ts` `_writeTombstone` — the envelope rewrite\n *\n * A `ForgetStrategy` declares which collections carry erasable subject data\n * and the (dotted-path) field on each record that names the data subject.\n * Declaring a collection here ALSO forces `perRecordKeys: true` for it (a\n * shred can only erase a record whose body is keyed off a per-record CEK),\n * so adopters opt into the CEK foundation transitively.\n *\n * @module\n */\nimport type { LedgerEntry } from '../../with-commit/history/ledger/entry.js'\n\n/**\n * User-supplied declaration passed to {@link withForget}. Maps a\n * collection name to the record field (dotted path supported, e.g.\n * `'billing.buyerId'`) that identifies the data subject for erasure.\n *\n * ```ts\n * withForget({ subjects: { invoices: 'buyerId', contacts: 'id' } })\n * ```\n */\nexport interface SubjectDeclaration {\n readonly subjects: Record<string, string>\n /**\n * #633 — opt-in: gate the vault-level `_sealed_cek` and blob purges on\n * per-collection via declarations instead of running them unconditionally\n * for every forgotten ref. Default `false`/absent = today's unconditional\n * behavior (byte-identical). See `purge-scope.ts` for the partition logic\n * and the `scopedPurgeResidue` skip-reporting this enables.\n *\n * **Footgun:** a bare `sensitive: [...]` collection — no `classifiedFields`\n * (no classified via binder compiled in) — counts as UNDECLARED for the\n * sealed-CEK arm. Under `scopedPurge: true`, its `_sealed_cek` host-delivery\n * envelopes are SKIPPED, not purged (reported via `scopedPurgeResidue`,\n * reason `'skipped-undeclared-sealed-cek'`) even if that collection called\n * `sealRecordToHost()` — the sealed CEK stays recoverable by that granted\n * host until purged. Add a `classifiedFields` binding to close the gap, or\n * leave `scopedPurge` off/false for the unconditional (always-purged) default.\n * The declaration signal is session-local: a declared collection never opened\n * (with its config) before `forget()` in this session counts as UNDECLARED —\n * open it first, or its entries are skipped-and-reported.\n */\n readonly scopedPurge?: boolean\n}\n\n/**\n * Resolved forget strategy threaded through Noydb → every Vault. Carries\n * the same `subjects` map the user declared. `NO_FORGET` (empty map) is the\n * off-by-default sentinel; `vault.forget()` throws\n * `ForgetStrategyNotConfiguredError` when the map is empty.\n */\nexport interface ForgetStrategy {\n /** Collection → subject-field (dotted path). Empty under `NO_FORGET`. */\n readonly subjects: Readonly<Record<string, string>>\n /** #633 — see {@link SubjectDeclaration.scopedPurge}. */\n readonly scopedPurge?: boolean\n}\n\n/**\n * Disabled sentinel — no collections declare a subject field. `vault.forget()`\n * refuses with `ForgetStrategyNotConfiguredError`; no write hooks register; no\n * collection is forced into `perRecordKeys`. Non-adopters pay nothing.\n */\nexport const NO_FORGET: ForgetStrategy = { subjects: {} }\n\n// The `withForget` factory lives in `active.ts` (canonical\n// strategy.ts/active.ts/index.ts split); this file holds only the\n// declaration shape + disabled sentinel.\n\n/**\n * The outcome of a `vault.forget(subjectId)` call.\n *\n * `unmigratedRecords` lists `collection:id` pairs that were tombstoned but\n * whose body had NOT been migrated to a per-record CEK at shred time (legacy\n * body still under the shared collection DEK). Those records are tombstoned\n * (live envelope + history stripped) but their pre-shred ciphertext, if it\n * leaked into a backup before migration, remains decryptable under the\n * collection DEK — so erasure-completeness is NOT guaranteed for them. Run\n * the per-record-CEK migration pass, then re-forget, to close the gap.\n *\n * Blob attachments: a shredded record's **erasable** blobs (on a\n * `perRecordKeys` collection) are crypto-shredded inline — `blobsShredded`\n * counts those taken to refCount 0 (BlobObject deleted → chunks permanently\n * undecryptable), `blobsRetainedShared` counts those still referenced by\n * another record (shared content legitimately persists for its other owner).\n * `blobResidueCollections` now lists only collections with blobs that could\n * NOT be crypto-shredded: **legacy** blobs (no per-blob `_cek`, chunks under\n * the shared `_blob` DEK — migrate them), or a session without the blob\n * service loaded. An all-erasable subject yields an empty residue list.\n */\nexport interface ForgetResult {\n /** The subject id passed to `forget()`. Echoed for caller convenience. */\n readonly subject: string\n /** Count of live records rewritten to a tombstone. */\n readonly recordsShredded: number\n /** Count of `_history` envelopes tombstoned across all shredded records. */\n readonly historyVersionsShredded: number\n /** Distinct collections that had at least one record shredded. */\n readonly collections: readonly string[]\n /** `collection:id` pairs shredded while still un-migrated (see type docs). */\n readonly unmigratedRecords: readonly string[]\n /** Count of erasable blobs crypto-shredded (refCount → 0, BlobObject deleted). */\n readonly blobsShredded: number\n /** Count of erasable blobs retained because still referenced elsewhere (shared). */\n readonly blobsRetainedShared: number\n /** Collections with blobs that could NOT be crypto-shredded — legacy (no `_cek`) or blobs disabled (see type docs). */\n readonly blobResidueCollections: readonly string[]\n /**\n * Count of persisted `_idx/<field>/<recordId>` index side-cars hard-deleted\n * across the shredded records. These live under the retained\n * collection DEK, so crypto-shred alone would leave the indexed field VALUES\n * readable — `forget()` must delete them.\n */\n readonly indexPostingsPurged: number\n /**\n * `collection:id:field` entries whose persisted `_idx` side-car could NOT be\n * deleted — index residue that still leaks the indexed value under the\n * retained collection DEK. Non-empty means erasure is INCOMPLETE: retry, or\n * purge the side-car out of band.\n */\n readonly indexResidue: readonly string[]\n /**\n * Count of `_sealed[field]` slots dropped from the live store across the\n * shredded records. For slots written under `sensitive` +\n * `perRecordKeys` (the current path), the key derives off the per-record CEK,\n * so tombstoning the record — which drops `_cek` and `_sealed` — also\n * crypto-shreds the value. A legacy slot (written before per-record CEKs) keys\n * off the collection DEK instead, so dropping it removes it from the live store but a\n * pre-forget backup remains recoverable by a DEK holder (same caveat `_data`\n * carries); migrate by re-`put`ting before forgetting for full crypto-shred.\n */\n readonly sealedFieldsShredded: number\n /** Count of `_sealed_cek` host-delivery envelopes deleted (#H-1). A record sealed to an\n * at-* host via sealRecordToHost persists its raw CEK there; forget() must destroy them. */\n readonly sealedCekEnvelopesPurged: number\n /** `collection:id` whose `_sealed_cek` purge failed (residue — the host-recoverable CEK may survive). */\n readonly sealedCekResidue: readonly string[]\n /** `collection:id:field` sealed slots that were DEK-derived (legacy, written before per-record CEKs) and thus NOT crypto-shredded\n * by dropping `_cek` — the collection DEK is retained, so synced/backup copies stay decryptable (#M-1). */\n readonly sealedResidue: readonly string[]\n /** Count of `_ledger_deltas` rows hard-deleted across the shredded records (#734) — the\n * erasure twin of #729's elevate-side purge. Entry metadata (that the record was mutated,\n * at which version/timestamp/actor) is retained; only the plaintext delta content is removed. */\n readonly ledgerDeltasPurged: number\n /** `collection:id` refs whose `_ledger_deltas` purge failed — plaintext delta residue still\n * readable under the retained ledger DEK. Non-empty means erasure is INCOMPLETE. */\n readonly ledgerDeltaResidue: readonly string[]\n /** The single `op:'forget'` ledger entry appended for this erasure. */\n readonly ledgerEntry: LedgerEntry\n /** #622 — record-grain derived artifacts (MV rows, per-record derived copies) erased\n * because their source subject was forgotten. Overlay outputs are intentionally out of\n * scope here — an overlay is always sourced from an MV, never directly from a subject\n * collection, so the personal-data-bearing MV rows it reads are already erased above. */\n readonly derivedRecordsErased: number\n /** #622 — aggregate-grain targets (rollups) recomputed without the forgotten contribution. */\n readonly derivedAggregatesRecomputed: number\n /** #622 — `collection:id` derived writes SKIPPED because the target period is frozen\n * (recompute deferred; the aggregate retains the forgotten contribution — audited). */\n readonly derivedResidueFrozen: readonly string[]\n /** #650 Task 5 (#648) — referencing records tombstoned via a `'ref'` edge's `cascade` policy. */\n readonly lookupReferencesCascaded: number\n /** #650 Task 5 (#648) — referencing fields cleared via a `'ref'` edge's `nullify` policy. */\n readonly lookupReferencesNullified: number\n /** #650 Task 5 review (Important fix) — `'ref'` edges whose compare-key could NOT be resolved,\n * even from the LIVE pre-shred backing row — cascade/nullify propagation was SKIPPED for these.\n * Always empty in the ordinary case; non-empty means the skip is reported, never silent. */\n readonly lookupReferencesResidue: readonly string[]\n /** #633 — scoped-purge skip notices (opt-in `scopedPurge`, see {@link SubjectDeclaration}).\n * Always empty under the unconditional default. Non-empty means a `_sealed_cek` entry or a\n * blob scan was skipped for an undeclared collection — reported, never a silent skip. */\n readonly scopedPurgeResidue: readonly ScopedPurgeResidueNotice[]\n /** #776/#782/#785 — `collection:id` MV-output rows that survived erasure invalidation (eager\n * tombstone leg AND lazy/manual `invalidateMVAtRest`) despite belonging to the forgotten\n * subject, because the `_materializedFrom` ownership stamp could NOT be decoded (undecodable\n * under the collection's default DEK — e.g. elevated above tier 0 on a tiered output\n * collection; ownership unconfirmed — could be a plain user record on a same-collection\n * partition MV). Never erased, but surfaced here rather than silently skipped (the #724\n * posture). Non-empty means the row may still hold the forgotten/pre-elevation contribution,\n * decryptable by tier-holders. */\n readonly derivedResidueUndecodable: readonly string[]\n /** #782/#785 — `collection:id` MV-output rows that DID decode and stamp-match via\n * `_materializedFrom`, but whose erasure was declined by the #718 tier-elevation gate\n * (`_internalDelete` returned false). Ownership CONFIRMED here — a real silent survival,\n * not a stamp-mismatch skip — surfaced rather than dropped. Non-empty means a live,\n * tier-holder-decryptable copy of the forgotten contribution was deliberately retained. */\n readonly derivedResidueDeclined: readonly string[]\n}\n\n/** #633 — the two `scopedPurgeResidue` skip reasons. Single source of truth: `purge-scope.ts`\n * (the port-internal partition helpers) imports this rather than redeclaring it. */\nexport type ScopedPurgeResidueReason = 'skipped-undeclared-sealed-cek' | 'skipped-undeclared-blob-scan'\n\n/** #633 — one `ForgetResult.scopedPurgeResidue` entry: an undeclared collection's sealed-CEK\n * entries left unpurged, or its blob scan skipped entirely, under `scopedPurge`. `count` is the\n * number of `_sealed_cek` entries left in place (sealed-cek reason) or the number of refs whose\n * blob scan was skipped (blob-scan reason) — aggregated per collection across the whole call. */\nexport interface ScopedPurgeResidueNotice {\n readonly reason: ScopedPurgeResidueReason\n readonly collection: string\n readonly count: number\n}\n","/**\n * The encrypted subject index.\n *\n * GDPR crypto-shred needs to answer \"which records belong to data subject\n * X?\" portably (the index must travel with the vault/bundle) WITHOUT leaking\n * subject-equivalence to the store. The rejected alternative — an unencrypted\n * subject tag in envelope metadata — would let anyone with store access see\n * which records share a subject. Instead we keep a reserved `_subject_index`\n * collection, encrypted under its OWN DEK (`getDEK('_subject_index')`):\n *\n * - record id = `HMAC-SHA256(indexDEK, subjectId)` (M-2). A bare\n * `sha256Hex(subjectId)` would be offline-computable: an attacker with\n * store access and a candidate list (emails / customer ids are low-entropy)\n * could dictionary the hash to confirm \"subject X is present here.\" Keying\n * the id with the vault-only index DEK removes that capability — without the\n * DEK the id cannot be derived. (Legacy entries written before M-2 used the\n * bare sha256 id; the read/remove paths dual-look-up both forms.)\n * - record body = AES-GCM(JSON `{ r: [{ collection, id }], p }`) under the\n * index DEK, where `p` pads the plaintext to a bucketed length so the\n * ciphertext `_data` length does not leak the approximate record count.\n * Legacy bodies were a bare `[{ collection, id }]` array; reads accept both.\n *\n * ## Concurrency (RISK #3 — known v1 limitation)\n *\n * `addSubjectRef` / `removeSubjectRef` are read-modify-write with no CAS. The\n * design assumes a SINGLE WRITER (the noy-db single-process write model). Two\n * concurrent writers racing on the SAME subject can lose an entry (last-write\n * wins on the ref list). This is documented, not fixed in v1:\n * `rebuildSubjectIndex` performs a full scan to recover a correct index from\n * the canonical records, so a lost ref is recoverable. A CAS-backed index is\n * deferred to a later slice.\n *\n * @module\n */\nimport { encrypt, openEnvelopeJson, hmacSha256Hex, sha256Hex, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport { NOYDB_FORMAT_VERSION } from '../../kernel/types.js'\n\n/** Reserved collection holding the encrypted subject → records index. */\nexport const SUBJECT_INDEX_COLLECTION = '_subject_index'\n\n/**\n * Bucket (bytes) the encrypted ref-list plaintext is padded up to, so the\n * ciphertext `_data` length leaks only `count` rounded up to a bucket — not the\n * exact record count. 256 keeps small subjects (the common case) indistinguishable.\n */\nconst REF_LIST_BUCKET = 256\n\n/** A single record reference held in a subject's index entry. */\nexport interface SubjectRef {\n readonly collection: string\n readonly id: string\n}\n\ntype GetDEK = (collectionName: string) => Promise<EnclaveKey>\n\n/** SHA-256 hex of a UTF-8 string. The LEGACY (pre-M-2) subject-index key. */\nasync function sha256HexString(input: string): Promise<string> {\n return sha256Hex(new TextEncoder().encode(input))\n}\n\n/**\n * The subject-index record id(s) to consult for a subject, most-current first.\n *\n * - Encrypted vault: the PRIMARY id is `HMAC-SHA256(indexDEK, subjectId)` (M-2)\n * — not offline-computable. The LEGACY `sha256Hex(subjectId)` id is also\n * returned so reads/removes still find entries written before M-2 (dual-lookup).\n * - Plaintext/debug vault: no DEK to key with, so the only id is the legacy\n * sha256 form (unchanged behaviour — plaintext mode is not zero-knowledge anyway).\n */\nasync function subjectKeys(getDEK: GetDEK, encrypted: boolean, subjectId: string): Promise<string[]> {\n const legacy = await sha256HexString(subjectId)\n if (!encrypted) return [legacy]\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const keyed = await hmacSha256Hex(dek, new TextEncoder().encode(subjectId))\n return keyed === legacy ? [keyed] : [keyed, legacy]\n}\n\n/** The id new writes land under (keyed when encrypted, else legacy sha256). */\nasync function primarySubjectKey(getDEK: GetDEK, encrypted: boolean, subjectId: string): Promise<string> {\n return (await subjectKeys(getDEK, encrypted, subjectId))[0]!\n}\n\n/** Parse a stored ref-list body: new padded `{ r, p }` wrapper OR legacy bare array. */\nfunction parseRefs(json: string): SubjectRef[] {\n const parsed = JSON.parse(json) as SubjectRef[] | { r: SubjectRef[] }\n return Array.isArray(parsed) ? parsed : parsed.r\n}\n\n/** Serialize + pad the ref list to a bucket boundary (encrypted vaults only). */\nfunction serializeRefs(refs: SubjectRef[]): string {\n const base = JSON.stringify({ r: refs, p: '' })\n const pad = Math.ceil(base.length / REF_LIST_BUCKET) * REF_LIST_BUCKET - base.length\n return JSON.stringify({ r: refs, p: ' '.repeat(pad) })\n}\n\n/** Read + decrypt the ref list at a SINGLE index key. Returns `[]` when absent. */\nasync function readRefs(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n key: string,\n): Promise<SubjectRef[]> {\n const env = await adapter.get(vault, SUBJECT_INDEX_COLLECTION, key)\n if (!env || !env._data) return []\n if (!encrypted) return parseRefs(env._data)\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const json = await openEnvelopeJson(env, dek)\n return parseRefs(json)\n}\n\n/** Encrypt + write a ref list for a subject under its derived key. */\nasync function writeRefs(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n key: string,\n refs: SubjectRef[],\n): Promise<void> {\n let env: EncryptedEnvelope\n if (!encrypted) {\n // Plaintext/debug vault: keep the legacy bare-array form (no padding needed).\n env = { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: new Date().toISOString(), _iv: '', _data: JSON.stringify(refs) }\n } else {\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const { iv, data } = await encrypt(serializeRefs(refs), dek)\n env = { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: new Date().toISOString(), _iv: iv, _data: data }\n }\n await adapter.put(vault, SUBJECT_INDEX_COLLECTION, key, env)\n}\n\n/**\n * Add a `{ collection, id }` ref to a subject's index entry (idempotent —\n * a duplicate ref is not appended). Read-modify-write; see the concurrency\n * note in the module docstring.\n */\nexport async function addSubjectRef(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n ref: SubjectRef,\n): Promise<void> {\n const key = await primarySubjectKey(getDEK, encrypted, subjectId)\n const refs = await readRefs(adapter, vault, getDEK, encrypted, key)\n if (refs.some((r) => r.collection === ref.collection && r.id === ref.id)) return\n refs.push(ref)\n await writeRefs(adapter, vault, getDEK, encrypted, key, refs)\n}\n\n/**\n * Remove a `{ collection, id }` ref from a subject's index entry. When the\n * last ref is removed the (now empty) entry is deleted so the store holds no\n * residual key for an erased subject.\n */\nexport async function removeSubjectRef(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n ref: SubjectRef,\n): Promise<void> {\n // Dual-lookup: drop the ref from BOTH the keyed (M-2) and the legacy sha256\n // entry, so a pre-M-2 subject is still fully erased.\n for (const key of await subjectKeys(getDEK, encrypted, subjectId)) {\n const refs = await readRefs(adapter, vault, getDEK, encrypted, key)\n const next = refs.filter((r) => !(r.collection === ref.collection && r.id === ref.id))\n if (next.length === refs.length) continue\n if (next.length === 0) {\n await adapter.delete(vault, SUBJECT_INDEX_COLLECTION, key)\n } else {\n await writeRefs(adapter, vault, getDEK, encrypted, key, next)\n }\n }\n}\n\n/**\n * Look up every record ref for a subject. Returns `[]` when none exist. Unions\n * the keyed (M-2) and legacy sha256 entries (dual-lookup), deduplicated, so a\n * subject indexed before M-2 is still fully found.\n */\nexport async function lookupSubject(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n): Promise<SubjectRef[]> {\n const keys = await subjectKeys(getDEK, encrypted, subjectId)\n const seen = new Set<string>()\n const out: SubjectRef[] = []\n for (const key of keys) {\n for (const ref of await readRefs(adapter, vault, getDEK, encrypted, key)) {\n const dedup = `${ref.collection}\\u0000${ref.id}`\n if (seen.has(dedup)) continue\n seen.add(dedup)\n out.push(ref)\n }\n }\n return out\n}\n\n/**\n * Rebuild the entire subject index from the canonical records (the recovery\n * path for the documented read-modify-write race). Scans each declared\n * collection, reads `record[subjectField]` (dotted path), and rewrites the\n * index from scratch. Tombstoned (already-shredded) records contribute no\n * ref — their body is gone, so they cannot be re-indexed.\n *\n * `decodeRecord` decrypts an envelope to a plain object (or returns null for\n * a tombstone / unreadable record); supplied by the caller so this module\n * stays free of Collection internals.\n */\nexport async function rebuildSubjectIndex(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjects: Readonly<Record<string, string>>,\n decodeRecord: (collection: string, id: string, env: EncryptedEnvelope) => Promise<Record<string, unknown> | null>,\n): Promise<number> {\n // Drop every existing index entry first so removed refs don't linger.\n const existing = await adapter.list(vault, SUBJECT_INDEX_COLLECTION)\n for (const k of existing) {\n await adapter.delete(vault, SUBJECT_INDEX_COLLECTION, k)\n }\n\n // subjectId → refs, accumulated across all declared collections.\n const bySubject = new Map<string, SubjectRef[]>()\n for (const [collection, field] of Object.entries(subjects)) {\n const ids = await adapter.list(vault, collection)\n for (const id of ids) {\n if (id.startsWith('_')) continue\n const env = await adapter.get(vault, collection, id)\n if (!env || !env._data) continue // missing or tombstone\n const record = await decodeRecord(collection, id, env)\n if (record === null) continue\n const subjectValue = readDottedPath(record, field)\n if (subjectValue === undefined || subjectValue === null) continue\n const subjectId = coerceSubjectId(subjectValue)\n const list = bySubject.get(subjectId) ?? []\n list.push({ collection, id })\n bySubject.set(subjectId, list)\n }\n }\n\n let entries = 0\n for (const [subjectId, refs] of bySubject) {\n const key = await primarySubjectKey(getDEK, encrypted, subjectId)\n await writeRefs(adapter, vault, getDEK, encrypted, key, refs)\n entries++\n }\n return entries\n}\n\n/**\n * Coerce a read subject-field value to a stable string id. Primitives use\n * their natural string form; objects/arrays are JSON-stringified so structural\n * subjects still get a deterministic key (avoids the `[object Object]` trap).\n */\nexport function coerceSubjectId(value: unknown): string {\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n return String(value)\n }\n return JSON.stringify(value)\n}\n\n/** Read a (possibly dotted) field path from a plain record. */\nexport function readDottedPath(record: Record<string, unknown>, field: string): unknown {\n if (!field.includes('.')) return record[field]\n let cursor: unknown = record\n for (const segment of field.split('.')) {\n if (cursor === null || cursor === undefined) return undefined\n cursor = (cursor as Record<string, unknown>)[segment]\n }\n return cursor\n}\n"],"mappings":";;;;;;;;;;;;;AAuEO,IAAM,YAA4B,EAAE,UAAU,CAAC,EAAE;;;AChCjD,IAAM,2BAA2B;AAOxC,IAAM,kBAAkB;AAWxB,eAAe,gBAAgB,OAAgC;AAC7D,SAAO,UAAU,IAAI,YAAY,EAAE,OAAO,KAAK,CAAC;AAClD;AAWA,eAAe,YAAY,QAAgB,WAAoB,WAAsC;AACnG,QAAM,SAAS,MAAM,gBAAgB,SAAS;AAC9C,MAAI,CAAC,UAAW,QAAO,CAAC,MAAM;AAC9B,QAAM,MAAM,MAAM,OAAO,wBAAwB;AACjD,QAAM,QAAQ,MAAM,cAAc,KAAK,IAAI,YAAY,EAAE,OAAO,SAAS,CAAC;AAC1E,SAAO,UAAU,SAAS,CAAC,KAAK,IAAI,CAAC,OAAO,MAAM;AACpD;AAGA,eAAe,kBAAkB,QAAgB,WAAoB,WAAoC;AACvG,UAAQ,MAAM,YAAY,QAAQ,WAAW,SAAS,GAAG,CAAC;AAC5D;AAGA,SAAS,UAAU,MAA4B;AAC7C,QAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,SAAO,MAAM,QAAQ,MAAM,IAAI,SAAS,OAAO;AACjD;AAGA,SAAS,cAAc,MAA4B;AACjD,QAAM,OAAO,KAAK,UAAU,EAAE,GAAG,MAAM,GAAG,GAAG,CAAC;AAC9C,QAAM,MAAM,KAAK,KAAK,KAAK,SAAS,eAAe,IAAI,kBAAkB,KAAK;AAC9E,SAAO,KAAK,UAAU,EAAE,GAAG,MAAM,GAAG,IAAI,OAAO,GAAG,EAAE,CAAC;AACvD;AAGA,eAAe,SACb,SACA,OACA,QACA,WACA,KACuB;AACvB,QAAM,MAAM,MAAM,QAAQ,IAA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C,IAAI,MAAO;AACxB,YAAM,SAAS,MAAM,aAAa,YAAY,IAAI,GAAG;AACrD,UAAI,WAAW,KAAM;AACrB,YAAM,eAAe,eAAe,QAAQ,KAAK;AACjD,UAAI,iBAAiB,UAAa,iBAAiB,KAAM;AACzD,YAAM,YAAY,gBAAgB,YAAY;AAC9C,YAAM,OAAO,UAAU,IAAI,SAAS,KAAK,CAAC;AAC1C,WAAK,KAAK,EAAE,YAAY,GAAG,CAAC;AAC5B,gBAAU,IAAI,WAAW,IAAI;AAAA,IAC/B;AAAA,EACF;AAEA,MAAI,UAAU;AACd,aAAW,CAAC,WAAW,IAAI,KAAK,WAAW;AACzC,UAAM,MAAM,MAAM,kBAAkB,QAAQ,WAAW,SAAS;AAChE,UAAM,UAAU,SAAS,OAAO,QAAQ,WAAW,KAAK,IAAI;AAC5D;AAAA,EACF;AACA,SAAO;AACT;AAOO,SAAS,gBAAgB,OAAwB;AACtD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,OAAO,UAAU,YAAY,OAAO,UAAU,aAAa,OAAO,UAAU,UAAU;AACxF,WAAO,OAAO,KAAK;AAAA,EACrB;AACA,SAAO,KAAK,UAAU,KAAK;AAC7B;AAGO,SAAS,eAAe,QAAiC,OAAwB;AACtF,MAAI,CAAC,MAAM,SAAS,GAAG,EAAG,QAAO,OAAO,KAAK;AAC7C,MAAI,SAAkB;AACtB,aAAW,WAAW,MAAM,MAAM,GAAG,GAAG;AACtC,QAAI,WAAW,QAAQ,WAAW,OAAW,QAAO;AACpD,aAAU,OAAmC,OAAO;AAAA,EACtD;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/with-audit/forget/strategy.ts","../src/with-audit/forget/subject-index.ts"],"sourcesContent":["/**\n * `withForget` — declaration surface for GDPR right-to-erasure via\n * per-record CEK crypto-shred.\n *\n * This file holds only the *declaration* shape and the disabled sentinel.\n * The actual erasure machinery lives in:\n * - `subject-index.ts` — the encrypted `_subject_index` reserved collection\n * - `vault.ts` `forget()` — the per-record tombstone + ledger flow\n * - `collection.ts` `_writeTombstone` — the envelope rewrite\n *\n * A `ForgetStrategy` declares which collections carry erasable subject data\n * and the (dotted-path) field on each record that names the data subject.\n * Declaring a collection here ALSO forces `perRecordKeys: true` for it (a\n * shred can only erase a record whose body is keyed off a per-record CEK),\n * so adopters opt into the CEK foundation transitively.\n *\n * @module\n */\nimport type { LedgerEntry } from '../../with-commit/history/ledger/entry.js'\n\n/**\n * User-supplied declaration passed to {@link withForget}. Maps a\n * collection name to the record field (dotted path supported, e.g.\n * `'billing.buyerId'`) that identifies the data subject for erasure.\n *\n * ```ts\n * withForget({ subjects: { invoices: 'buyerId', contacts: 'id' } })\n * ```\n */\nexport interface SubjectDeclaration {\n readonly subjects: Record<string, string>\n /**\n * #633 — opt-in: gate the vault-level `_sealed_cek` and blob purges on\n * per-collection via declarations instead of running them unconditionally\n * for every forgotten ref. Default `false`/absent = today's unconditional\n * behavior (byte-identical). See `purge-scope.ts` for the partition logic\n * and the `scopedPurgeResidue` skip-reporting this enables.\n *\n * **Footgun:** a bare `sensitive: [...]` collection — no `classifiedFields`\n * (no classified via binder compiled in) — counts as UNDECLARED for the\n * sealed-CEK arm. Under `scopedPurge: true`, its `_sealed_cek` host-delivery\n * envelopes are SKIPPED, not purged (reported via `scopedPurgeResidue`,\n * reason `'skipped-undeclared-sealed-cek'`) even if that collection called\n * `sealRecordToHost()` — the sealed CEK stays recoverable by that granted\n * host until purged. Add a `classifiedFields` binding to close the gap, or\n * leave `scopedPurge` off/false for the unconditional (always-purged) default.\n * The declaration signal is session-local: a declared collection never opened\n * (with its config) before `forget()` in this session counts as UNDECLARED —\n * open it first, or its entries are skipped-and-reported.\n */\n readonly scopedPurge?: boolean\n}\n\n/**\n * Resolved forget strategy threaded through Noydb → every Vault. Carries\n * the same `subjects` map the user declared. `NO_FORGET` (empty map) is the\n * off-by-default sentinel; `vault.forget()` throws\n * `ForgetStrategyNotConfiguredError` when the map is empty.\n */\nexport interface ForgetStrategy {\n /** Collection → subject-field (dotted path). Empty under `NO_FORGET`. */\n readonly subjects: Readonly<Record<string, string>>\n /** #633 — see {@link SubjectDeclaration.scopedPurge}. */\n readonly scopedPurge?: boolean\n}\n\n/**\n * Disabled sentinel — no collections declare a subject field. `vault.forget()`\n * refuses with `ForgetStrategyNotConfiguredError`; no write hooks register; no\n * collection is forced into `perRecordKeys`. Non-adopters pay nothing.\n */\nexport const NO_FORGET: ForgetStrategy = { subjects: {} }\n\n// The `withForget` factory lives in `active.ts` (canonical\n// strategy.ts/active.ts/index.ts split); this file holds only the\n// declaration shape + disabled sentinel.\n\n/**\n * The outcome of a `vault.forget(subjectId)` call.\n *\n * `unmigratedRecords` lists `collection:id` pairs that were tombstoned but\n * whose body had NOT been migrated to a per-record CEK at shred time (legacy\n * body still under the shared collection DEK). Those records are tombstoned\n * (live envelope + history stripped) but their pre-shred ciphertext, if it\n * leaked into a backup before migration, remains decryptable under the\n * collection DEK — so erasure-completeness is NOT guaranteed for them. Run\n * the per-record-CEK migration pass, then re-forget, to close the gap.\n *\n * Blob attachments: a shredded record's **erasable** blobs (on a\n * `perRecordKeys` collection) are crypto-shredded inline — `blobsShredded`\n * counts those taken to refCount 0 (BlobObject deleted → chunks permanently\n * undecryptable), `blobsRetainedShared` counts those still referenced by\n * another record (shared content legitimately persists for its other owner).\n * `blobResidueCollections` now lists only collections with blobs that could\n * NOT be crypto-shredded: **legacy** blobs (no per-blob `_cek`, chunks under\n * the shared `_blob` DEK — migrate them), or a session without the blob\n * service loaded. An all-erasable subject yields an empty residue list.\n */\nexport interface ForgetResult {\n /** The subject id passed to `forget()`. Echoed for caller convenience. */\n readonly subject: string\n /** Count of live records rewritten to a tombstone. */\n readonly recordsShredded: number\n /** Count of `_history` envelopes tombstoned across all shredded records. */\n readonly historyVersionsShredded: number\n /** Distinct collections that had at least one record shredded. */\n readonly collections: readonly string[]\n /** `collection:id` pairs shredded while still un-migrated (see type docs). */\n readonly unmigratedRecords: readonly string[]\n /** Count of erasable blobs crypto-shredded (refCount → 0, BlobObject deleted). */\n readonly blobsShredded: number\n /** Count of erasable blobs retained because still referenced elsewhere (shared). */\n readonly blobsRetainedShared: number\n /** Collections with blobs that could NOT be crypto-shredded — legacy (no `_cek`) or blobs disabled (see type docs). */\n readonly blobResidueCollections: readonly string[]\n /**\n * Count of persisted `_idx/<field>/<recordId>` index side-cars hard-deleted\n * across the shredded records. These live under the retained\n * collection DEK, so crypto-shred alone would leave the indexed field VALUES\n * readable — `forget()` must delete them.\n */\n readonly indexPostingsPurged: number\n /**\n * `collection:id:field` entries whose persisted `_idx` side-car could NOT be\n * deleted — index residue that still leaks the indexed value under the\n * retained collection DEK. Non-empty means erasure is INCOMPLETE: retry, or\n * purge the side-car out of band.\n */\n readonly indexResidue: readonly string[]\n /**\n * Count of `_sealed[field]` slots dropped from the live store across the\n * shredded records. For slots written under `sensitive` +\n * `perRecordKeys` (the current path), the key derives off the per-record CEK,\n * so tombstoning the record — which drops `_cek` and `_sealed` — also\n * crypto-shreds the value. A legacy slot (written before per-record CEKs) keys\n * off the collection DEK instead, so dropping it removes it from the live store but a\n * pre-forget backup remains recoverable by a DEK holder (same caveat `_data`\n * carries); migrate by re-`put`ting before forgetting for full crypto-shred.\n */\n readonly sealedFieldsShredded: number\n /** Count of `_sealed_cek` host-delivery envelopes deleted (#H-1). A record sealed to an\n * at-* host via sealRecordToHost persists its raw CEK there; forget() must destroy them. */\n readonly sealedCekEnvelopesPurged: number\n /** `collection:id` whose `_sealed_cek` purge failed (residue — the host-recoverable CEK may survive). */\n readonly sealedCekResidue: readonly string[]\n /** `collection:id:field` sealed slots that were DEK-derived (legacy, written before per-record CEKs) and thus NOT crypto-shredded\n * by dropping `_cek` — the collection DEK is retained, so synced/backup copies stay decryptable (#M-1). */\n readonly sealedResidue: readonly string[]\n /** Count of `_ledger_deltas` rows hard-deleted across the shredded records (#734) — the\n * erasure twin of #729's elevate-side purge. Entry metadata (that the record was mutated,\n * at which version/timestamp/actor) is retained; only the plaintext delta content is removed. */\n readonly ledgerDeltasPurged: number\n /** `collection:id` refs whose `_ledger_deltas` purge failed — plaintext delta residue still\n * readable under the retained ledger DEK. Non-empty means erasure is INCOMPLETE. */\n readonly ledgerDeltaResidue: readonly string[]\n /** The single `op:'forget'` ledger entry appended for this erasure. */\n readonly ledgerEntry: LedgerEntry\n /** #622 — record-grain derived artifacts (MV rows, per-record derived copies) erased\n * because their source subject was forgotten. Overlay outputs are intentionally out of\n * scope here — an overlay is always sourced from an MV, never directly from a subject\n * collection, so the personal-data-bearing MV rows it reads are already erased above. */\n readonly derivedRecordsErased: number\n /** #622 — aggregate-grain targets (rollups) recomputed without the forgotten contribution. */\n readonly derivedAggregatesRecomputed: number\n /** #622 — `collection:id` derived writes SKIPPED because the target period is frozen\n * (recompute deferred; the aggregate retains the forgotten contribution — audited). */\n readonly derivedResidueFrozen: readonly string[]\n /** #650 Task 5 (#648) — referencing records tombstoned via a `'ref'` edge's `cascade` policy. */\n readonly lookupReferencesCascaded: number\n /** #650 Task 5 (#648) — referencing fields cleared via a `'ref'` edge's `nullify` policy. */\n readonly lookupReferencesNullified: number\n /** #650 Task 5 review (Important fix) — `'ref'` edges whose compare-key could NOT be resolved,\n * even from the LIVE pre-shred backing row — cascade/nullify propagation was SKIPPED for these.\n * Always empty in the ordinary case; non-empty means the skip is reported, never silent. */\n readonly lookupReferencesResidue: readonly string[]\n /** #633 — scoped-purge skip notices (opt-in `scopedPurge`, see {@link SubjectDeclaration}).\n * Always empty under the unconditional default. Non-empty means a `_sealed_cek` entry or a\n * blob scan was skipped for an undeclared collection — reported, never a silent skip. */\n readonly scopedPurgeResidue: readonly ScopedPurgeResidueNotice[]\n /** #776/#782/#785 — `collection:id` MV-output rows that survived erasure invalidation (eager\n * tombstone leg AND lazy/manual `invalidateMVAtRest`) despite belonging to the forgotten\n * subject, because the `_materializedFrom` ownership stamp could NOT be decoded (undecodable\n * under the collection's default DEK — e.g. elevated above tier 0 on a tiered output\n * collection; ownership unconfirmed — could be a plain user record on a same-collection\n * partition MV). Never erased, but surfaced here rather than silently skipped (the #724\n * posture). Non-empty means the row may still hold the forgotten/pre-elevation contribution,\n * decryptable by tier-holders. */\n readonly derivedResidueUndecodable: readonly string[]\n /** #782/#785 — `collection:id` MV-output rows that DID decode and stamp-match via\n * `_materializedFrom`, but whose erasure was declined by the #718 tier-elevation gate\n * (`_internalDelete` returned false). Ownership CONFIRMED here — a real silent survival,\n * not a stamp-mismatch skip — surfaced rather than dropped. Non-empty means a live,\n * tier-holder-decryptable copy of the forgotten contribution was deliberately retained. */\n readonly derivedResidueDeclined: readonly string[]\n}\n\n/** #633 — the two `scopedPurgeResidue` skip reasons. Single source of truth: `purge-scope.ts`\n * (the port-internal partition helpers) imports this rather than redeclaring it. */\nexport type ScopedPurgeResidueReason = 'skipped-undeclared-sealed-cek' | 'skipped-undeclared-blob-scan'\n\n/** #633 — one `ForgetResult.scopedPurgeResidue` entry: an undeclared collection's sealed-CEK\n * entries left unpurged, or its blob scan skipped entirely, under `scopedPurge`. `count` is the\n * number of `_sealed_cek` entries left in place (sealed-cek reason) or the number of refs whose\n * blob scan was skipped (blob-scan reason) — aggregated per collection across the whole call. */\nexport interface ScopedPurgeResidueNotice {\n readonly reason: ScopedPurgeResidueReason\n readonly collection: string\n readonly count: number\n}\n","/**\n * The encrypted subject index.\n *\n * GDPR crypto-shred needs to answer \"which records belong to data subject\n * X?\" portably (the index must travel with the vault/bundle) WITHOUT leaking\n * subject-equivalence to the store. The rejected alternative — an unencrypted\n * subject tag in envelope metadata — would let anyone with store access see\n * which records share a subject. Instead we keep a reserved `_subject_index`\n * collection, encrypted under its OWN DEK (`getDEK('_subject_index')`):\n *\n * - record id = `HMAC-SHA256(indexDEK, subjectId)` (M-2). A bare\n * `sha256Hex(subjectId)` would be offline-computable: an attacker with\n * store access and a candidate list (emails / customer ids are low-entropy)\n * could dictionary the hash to confirm \"subject X is present here.\" Keying\n * the id with the vault-only index DEK removes that capability — without the\n * DEK the id cannot be derived. (Legacy entries written before M-2 used the\n * bare sha256 id; the read/remove paths dual-look-up both forms.)\n * - record body = AES-GCM(JSON `{ r: [{ collection, id }], p }`) under the\n * index DEK, where `p` pads the plaintext to a bucketed length so the\n * ciphertext `_data` length does not leak the approximate record count.\n * Legacy bodies were a bare `[{ collection, id }]` array; reads accept both.\n *\n * ## Concurrency (RISK #3 — known v1 limitation)\n *\n * `addSubjectRef` / `removeSubjectRef` are read-modify-write with no CAS. The\n * design assumes a SINGLE WRITER (the noy-db single-process write model). Two\n * concurrent writers racing on the SAME subject can lose an entry (last-write\n * wins on the ref list). This is documented, not fixed in v1:\n * `rebuildSubjectIndex` performs a full scan to recover a correct index from\n * the canonical records, so a lost ref is recoverable. A CAS-backed index is\n * deferred to a later slice.\n *\n * @module\n */\nimport { buildRecordAad, buildRecordEnvelope, encrypt, openEnvelopeJson, hmacSha256Hex, sha256Hex, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\n\n/** Reserved collection holding the encrypted subject → records index. */\nexport const SUBJECT_INDEX_COLLECTION = '_subject_index'\n\n/**\n * Bucket (bytes) the encrypted ref-list plaintext is padded up to, so the\n * ciphertext `_data` length leaks only `count` rounded up to a bucket — not the\n * exact record count. 256 keeps small subjects (the common case) indistinguishable.\n */\nconst REF_LIST_BUCKET = 256\n\n/** A single record reference held in a subject's index entry. */\nexport interface SubjectRef {\n readonly collection: string\n readonly id: string\n}\n\ntype GetDEK = (collectionName: string) => Promise<EnclaveKey>\n\n/** SHA-256 hex of a UTF-8 string. The LEGACY (pre-M-2) subject-index key. */\nasync function sha256HexString(input: string): Promise<string> {\n return sha256Hex(new TextEncoder().encode(input))\n}\n\n/**\n * The subject-index record id(s) to consult for a subject, most-current first.\n *\n * - Encrypted vault: the PRIMARY id is `HMAC-SHA256(indexDEK, subjectId)` (M-2)\n * — not offline-computable. The LEGACY `sha256Hex(subjectId)` id is also\n * returned so reads/removes still find entries written before M-2 (dual-lookup).\n * - Plaintext/debug vault: no DEK to key with, so the only id is the legacy\n * sha256 form (unchanged behaviour — plaintext mode is not zero-knowledge anyway).\n */\nasync function subjectKeys(getDEK: GetDEK, encrypted: boolean, subjectId: string): Promise<string[]> {\n const legacy = await sha256HexString(subjectId)\n if (!encrypted) return [legacy]\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const keyed = await hmacSha256Hex(dek, new TextEncoder().encode(subjectId))\n return keyed === legacy ? [keyed] : [keyed, legacy]\n}\n\n/** The id new writes land under (keyed when encrypted, else legacy sha256). */\nasync function primarySubjectKey(getDEK: GetDEK, encrypted: boolean, subjectId: string): Promise<string> {\n return (await subjectKeys(getDEK, encrypted, subjectId))[0]!\n}\n\n/** Parse a stored ref-list body: new padded `{ r, p }` wrapper OR legacy bare array. */\nfunction parseRefs(json: string): SubjectRef[] {\n const parsed = JSON.parse(json) as SubjectRef[] | { r: SubjectRef[] }\n return Array.isArray(parsed) ? parsed : parsed.r\n}\n\n/** Serialize + pad the ref list to a bucket boundary (encrypted vaults only). */\nfunction serializeRefs(refs: SubjectRef[]): string {\n const base = JSON.stringify({ r: refs, p: '' })\n const pad = Math.ceil(base.length / REF_LIST_BUCKET) * REF_LIST_BUCKET - base.length\n return JSON.stringify({ r: refs, p: ' '.repeat(pad) })\n}\n\n/** Read + decrypt the ref list at a SINGLE index key. Returns `[]` when absent. */\nasync function readRefs(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n key: string,\n): Promise<SubjectRef[]> {\n const env = await adapter.get(vault, SUBJECT_INDEX_COLLECTION, key)\n if (!env || !env._data) return []\n if (!encrypted) return parseRefs(env._data)\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const json = await openEnvelopeJson({ collection: SUBJECT_INDEX_COLLECTION, id: key }, env, dek)\n return parseRefs(json)\n}\n\n/** Encrypt + write a ref list for a subject under its derived key. */\nasync function writeRefs(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n key: string,\n refs: SubjectRef[],\n): Promise<void> {\n const identity = { collection: SUBJECT_INDEX_COLLECTION, id: key, version: 1 }\n let env: EncryptedEnvelope\n if (!encrypted) {\n // Plaintext/debug vault: keep the bare-array form (no padding needed).\n env = buildRecordEnvelope(identity, { iv: '', data: JSON.stringify(refs) })\n } else {\n const dek = await getDEK(SUBJECT_INDEX_COLLECTION)\n const { iv, data } = await encrypt(serializeRefs(refs), dek, buildRecordAad(identity))\n env = buildRecordEnvelope(identity, { iv, data })\n }\n await adapter.put(vault, SUBJECT_INDEX_COLLECTION, key, env)\n}\n\n/**\n * Add a `{ collection, id }` ref to a subject's index entry (idempotent —\n * a duplicate ref is not appended). Read-modify-write; see the concurrency\n * note in the module docstring.\n */\nexport async function addSubjectRef(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n ref: SubjectRef,\n): Promise<void> {\n const key = await primarySubjectKey(getDEK, encrypted, subjectId)\n const refs = await readRefs(adapter, vault, getDEK, encrypted, key)\n if (refs.some((r) => r.collection === ref.collection && r.id === ref.id)) return\n refs.push(ref)\n await writeRefs(adapter, vault, getDEK, encrypted, key, refs)\n}\n\n/**\n * Remove a `{ collection, id }` ref from a subject's index entry. When the\n * last ref is removed the (now empty) entry is deleted so the store holds no\n * residual key for an erased subject.\n */\nexport async function removeSubjectRef(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n ref: SubjectRef,\n): Promise<void> {\n // Dual-lookup: drop the ref from BOTH the keyed (M-2) and the legacy sha256\n // entry, so a pre-M-2 subject is still fully erased.\n for (const key of await subjectKeys(getDEK, encrypted, subjectId)) {\n const refs = await readRefs(adapter, vault, getDEK, encrypted, key)\n const next = refs.filter((r) => !(r.collection === ref.collection && r.id === ref.id))\n if (next.length === refs.length) continue\n if (next.length === 0) {\n await adapter.delete(vault, SUBJECT_INDEX_COLLECTION, key)\n } else {\n await writeRefs(adapter, vault, getDEK, encrypted, key, next)\n }\n }\n}\n\n/**\n * Look up every record ref for a subject. Returns `[]` when none exist. Unions\n * the keyed (M-2) and legacy sha256 entries (dual-lookup), deduplicated, so a\n * subject indexed before M-2 is still fully found.\n */\nexport async function lookupSubject(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjectId: string,\n): Promise<SubjectRef[]> {\n const keys = await subjectKeys(getDEK, encrypted, subjectId)\n const seen = new Set<string>()\n const out: SubjectRef[] = []\n for (const key of keys) {\n for (const ref of await readRefs(adapter, vault, getDEK, encrypted, key)) {\n const dedup = `${ref.collection}\\u0000${ref.id}`\n if (seen.has(dedup)) continue\n seen.add(dedup)\n out.push(ref)\n }\n }\n return out\n}\n\n/**\n * Rebuild the entire subject index from the canonical records (the recovery\n * path for the documented read-modify-write race). Scans each declared\n * collection, reads `record[subjectField]` (dotted path), and rewrites the\n * index from scratch. Tombstoned (already-shredded) records contribute no\n * ref — their body is gone, so they cannot be re-indexed.\n *\n * `decodeRecord` decrypts an envelope to a plain object (or returns null for\n * a tombstone / unreadable record); supplied by the caller so this module\n * stays free of Collection internals.\n */\nexport async function rebuildSubjectIndex(\n adapter: NoydbStore,\n vault: string,\n getDEK: GetDEK,\n encrypted: boolean,\n subjects: Readonly<Record<string, string>>,\n decodeRecord: (collection: string, id: string, env: EncryptedEnvelope) => Promise<Record<string, unknown> | null>,\n): Promise<number> {\n // Drop every existing index entry first so removed refs don't linger.\n const existing = await adapter.list(vault, SUBJECT_INDEX_COLLECTION)\n for (const k of existing) {\n await adapter.delete(vault, SUBJECT_INDEX_COLLECTION, k)\n }\n\n // subjectId → refs, accumulated across all declared collections.\n const bySubject = new Map<string, SubjectRef[]>()\n for (const [collection, field] of Object.entries(subjects)) {\n const ids = await adapter.list(vault, collection)\n for (const id of ids) {\n if (id.startsWith('_')) continue\n const env = await adapter.get(vault, collection, id)\n if (!env || !env._data) continue // missing or tombstone\n const record = await decodeRecord(collection, id, env)\n if (record === null) continue\n const subjectValue = readDottedPath(record, field)\n if (subjectValue === undefined || subjectValue === null) continue\n const subjectId = coerceSubjectId(subjectValue)\n const list = bySubject.get(subjectId) ?? []\n list.push({ collection, id })\n bySubject.set(subjectId, list)\n }\n }\n\n let entries = 0\n for (const [subjectId, refs] of bySubject) {\n const key = await primarySubjectKey(getDEK, encrypted, subjectId)\n await writeRefs(adapter, vault, getDEK, encrypted, key, refs)\n entries++\n }\n return entries\n}\n\n/**\n * Coerce a read subject-field value to a stable string id. Primitives use\n * their natural string form; objects/arrays are JSON-stringified so structural\n * subjects still get a deterministic key (avoids the `[object Object]` trap).\n */\nexport function coerceSubjectId(value: unknown): string {\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n return String(value)\n }\n return JSON.stringify(value)\n}\n\n/** Read a (possibly dotted) field path from a plain record. */\nexport function readDottedPath(record: Record<string, unknown>, field: string): unknown {\n if (!field.includes('.')) return record[field]\n let cursor: unknown = record\n for (const segment of field.split('.')) {\n if (cursor === null || cursor === undefined) return undefined\n cursor = (cursor as Record<string, unknown>)[segment]\n }\n return cursor\n}\n"],"mappings":";;;;;;;;;;;;;;AAuEO,IAAM,YAA4B,EAAE,UAAU,CAAC,EAAE;;;ACjCjD,IAAM,2BAA2B;AAOxC,IAAM,kBAAkB;AAWxB,eAAe,gBAAgB,OAAgC;AAC7D,SAAO,UAAU,IAAI,YAAY,EAAE,OAAO,KAAK,CAAC;AAClD;AAWA,eAAe,YAAY,QAAgB,WAAoB,WAAsC;AACnG,QAAM,SAAS,MAAM,gBAAgB,SAAS;AAC9C,MAAI,CAAC,UAAW,QAAO,CAAC,MAAM;AAC9B,QAAM,MAAM,MAAM,OAAO,wBAAwB;AACjD,QAAM,QAAQ,MAAM,cAAc,KAAK,IAAI,YAAY,EAAE,OAAO,SAAS,CAAC;AAC1E,SAAO,UAAU,SAAS,CAAC,KAAK,IAAI,CAAC,OAAO,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,aAAa,OAAO,UAAU,UAAU;AACxF,WAAO,OAAO,KAAK;AAAA,EACrB;AACA,SAAO,KAAK,UAAU,KAAK;AAC7B;AAGO,SAAS,eAAe,QAAiC,OAAwB;AACtF,MAAI,CAAC,MAAM,SAAS,GAAG,EAAG,QAAO,OAAO,KAAK;AAC7C,MAAI,SAAkB;AACtB,aAAW,WAAW,MAAM,MAAM,GAAG,GAAG;AACtC,QAAI,WAAW,QAAQ,WAAW,OAAW,QAAO;AACpD,aAAU,OAAmC,OAAO;AAAA,EACtD;AACA,SAAO;AACT;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  BrokerNotEnabledError
3
- } from "./chunk-HNGSV2YC.js";
3
+ } from "./chunk-JBIV4FLR.js";
4
4
 
5
5
  // src/port/with/broker-strategy.ts
6
6
  var NO_BROKER = {
@@ -27,4 +27,4 @@ export {
27
27
  NO_BROKER,
28
28
  buildCredentialBrokerHandle
29
29
  };
30
- //# sourceMappingURL=chunk-W3TVWF6N.js.map
30
+ //# sourceMappingURL=chunk-4A4TYISP.js.map
@@ -29,4 +29,4 @@ export {
29
29
  generateULID,
30
30
  isULID
31
31
  };
32
- //# sourceMappingURL=chunk-ZJADGNYF.js.map
32
+ //# sourceMappingURL=chunk-4AOERLTV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-pod/ulid.ts"],"sourcesContent":["/**\n * Minimal ULID generator — zero dependencies, Web Crypto API only.\n *\n *. Used by the bundle writer to generate stable opaque\n * handles for `.noydb` containers.\n *\n * **What's a ULID?** A 128-bit identifier encoded as 26 Crockford\n * base32 characters. Layout:\n *\n * ```\n * 01HYABCDEFGHJKMNPQRSTVWXYZ\n * |--------||---------------|\n * 48-bit 80-bit\n * timestamp randomness\n * ```\n *\n * The first 10 chars encode a millisecond Unix timestamp (so ULIDs\n * sort lexicographically by creation time), and the remaining 16\n * chars are random. Crockford base32 omits I/L/O/U to avoid\n * ambiguity in handwriting and URLs.\n *\n * **Why hand-roll instead of pulling in `ulid`?** The package adds\n * a dep, the implementation is ~30 lines, and the bundle module\n * is the only consumer. Adding `ulid` would also drag in its own\n * crypto polyfill that we don't need on Node 18+ or modern\n * browsers.\n *\n * **Privacy consideration:** the timestamp prefix is observable in\n * the bundle header. This is a deliberate trade-off:\n * - Pro: lexicographic sortability lets bundle adapters list\n * newest-first without an extra index.\n * - Con: a casual observer can read the bundle's creation time\n * from the handle. They cannot read it from any OTHER field\n * (the header explicitly forbids `_exported_at`), and a\n * creation timestamp is the same kind of metadata that\n * filesystem mtime would already expose for a downloaded\n * bundle. The leak is therefore equivalent to what's already\n * visible from the file's mtime — not a new exposure.\n *\n * If a future use case needs timestamp-free handles, a v2 of the\n * format could specify \"use the random portion only\" without a\n * format break — `validatePodHeaderFields` only checks the regex\n * shape, not the encoded timestamp.\n */\n\n/**\n * Crockford base32 alphabet — omits I, L, O, U to avoid handwriting\n * and URL-encoding ambiguity. 32 characters covering 5 bits each.\n */\nconst CROCKFORD_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\n/**\n * Encode a non-negative integer as a fixed-width Crockford base32\n * string. The width is fixed (not the natural log32 length) so\n * leading zeros are preserved — that's required for the timestamp\n * prefix to remain lexicographically sortable.\n *\n * Used twice: once for the 48-bit timestamp portion (10 chars) and\n * once for each 40-bit half of the randomness (8 chars × 2).\n */\nfunction encodeBase32(value: number, length: number): string {\n let out = ''\n let v = value\n for (let i = 0; i < length; i++) {\n out = CROCKFORD_ALPHABET[v % 32]! + out\n v = Math.floor(v / 32)\n }\n return out\n}\n\n/**\n * Generate a fresh ULID. Uses `crypto.getRandomValues` for the\n * randomness portion — same Web Crypto API the rest of the\n * codebase uses for IVs and salt.\n *\n * Returns a 26-character string. Calling twice in the same\n * millisecond produces two distinct ULIDs (the random portion\n * differs); ULIDs from the same millisecond are NOT guaranteed\n * to be monotonically ordered relative to each other, only\n * relative to ULIDs from a different millisecond. The bundle\n * format never relies on intra-millisecond ordering.\n */\nexport function generateULID(): string {\n const now = Date.now()\n\n // 48-bit timestamp → 10 Crockford base32 characters.\n // JavaScript's max safe integer is 2^53 - 1; Date.now() is well\n // within that range until the year ~285,000 AD. Splitting into\n // high and low 24-bit halves keeps every intermediate value\n // inside the safe-integer range and avoids any ambiguity in the\n // base32 encoder above.\n const timestampHigh = Math.floor(now / 0x1000000) // top 24 bits\n const timestampLow = now & 0xffffff // bottom 24 bits\n const tsPart =\n encodeBase32(timestampHigh, 5) + encodeBase32(timestampLow, 5)\n\n // 80-bit randomness → 16 Crockford base32 characters. Split into\n // two 40-bit halves so each fits in JavaScript's safe-integer\n // range (53 bits) and the base32 encoder doesn't have to deal\n // with bigints.\n const randBytes = new Uint8Array(10)\n crypto.getRandomValues(randBytes)\n\n // First 5 bytes (40 bits) → 8 Crockford base32 characters.\n // Reconstruct the 40-bit integer from bytes in big-endian order.\n // Multiplication by 2^32 (instead of bit-shift) avoids JavaScript's\n // 32-bit integer cast on the high byte.\n const rand1 =\n randBytes[0]! * 2 ** 32 +\n (randBytes[1]! << 24 >>> 0) +\n (randBytes[2]! << 16) +\n (randBytes[3]! << 8) +\n randBytes[4]!\n // Same for the second 5 bytes.\n const rand2 =\n randBytes[5]! * 2 ** 32 +\n (randBytes[6]! << 24 >>> 0) +\n (randBytes[7]! << 16) +\n (randBytes[8]! << 8) +\n randBytes[9]!\n const randPart = encodeBase32(rand1, 8) + encodeBase32(rand2, 8)\n\n return tsPart + randPart\n}\n\n/**\n * Validate that a string is a syntactically well-formed ULID. Used\n * by the bundle header validator. Does NOT verify that the\n * timestamp portion decodes to a sensible date — the format only\n * cares about the encoding shape.\n */\nexport function isULID(value: string): boolean {\n return /^[0-9A-HJKMNP-TV-Z]{26}$/.test(value)\n}\n"],"mappings":";AAiDA,IAAM,qBAAqB;AAW3B,SAAS,aAAa,OAAe,QAAwB;AAC3D,MAAI,MAAM;AACV,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,QAAQ,KAAK;AAC/B,UAAM,mBAAmB,IAAI,EAAE,IAAK;AACpC,QAAI,KAAK,MAAM,IAAI,EAAE;AAAA,EACvB;AACA,SAAO;AACT;AAcO,SAAS,eAAuB;AACrC,QAAM,MAAM,KAAK,IAAI;AAQrB,QAAM,gBAAgB,KAAK,MAAM,MAAM,QAAS;AAChD,QAAM,eAAe,MAAM;AAC3B,QAAM,SACJ,aAAa,eAAe,CAAC,IAAI,aAAa,cAAc,CAAC;AAM/D,QAAM,YAAY,IAAI,WAAW,EAAE;AACnC,SAAO,gBAAgB,SAAS;AAMhC,QAAM,QACJ,UAAU,CAAC,IAAK,KAAK,MACpB,UAAU,CAAC,KAAM,OAAO,MACxB,UAAU,CAAC,KAAM,OACjB,UAAU,CAAC,KAAM,KAClB,UAAU,CAAC;AAEb,QAAM,QACJ,UAAU,CAAC,IAAK,KAAK,MACpB,UAAU,CAAC,KAAM,OAAO,MACxB,UAAU,CAAC,KAAM,OACjB,UAAU,CAAC,KAAM,KAClB,UAAU,CAAC;AACb,QAAM,WAAW,aAAa,OAAO,CAAC,IAAI,aAAa,OAAO,CAAC;AAE/D,SAAO,SAAS;AAClB;AAQO,SAAS,OAAO,OAAwB;AAC7C,SAAO,2BAA2B,KAAK,KAAK;AAC9C;","names":[]}
@@ -3,19 +3,19 @@ import {
3
3
  } from "./chunk-XZHEOSQ2.js";
4
4
  import {
5
5
  reducerBuilder
6
- } from "./chunk-CADUYBQD.js";
6
+ } from "./chunk-ATL3ZVXT.js";
7
7
  import {
8
8
  readPath
9
- } from "./chunk-IGJCYUT5.js";
9
+ } from "./chunk-NSITFOCJ.js";
10
10
  import {
11
11
  applyI18nLocale
12
- } from "./chunk-7G6VDWXB.js";
12
+ } from "./chunk-X67FCULK.js";
13
13
  import {
14
14
  viaBinder
15
- } from "./chunk-UHXCLPGC.js";
15
+ } from "./chunk-XDVVBETV.js";
16
16
  import {
17
17
  GroupCardinalityError
18
- } from "./chunk-HNGSV2YC.js";
18
+ } from "./chunk-JBIV4FLR.js";
19
19
 
20
20
  // src/with-lookup/reduce/reduction.ts
21
21
  function reduceRecords(records, spec) {
@@ -361,4 +361,4 @@ export {
361
361
  groupAndReduce,
362
362
  GroupedReduction
363
363
  };
364
- //# sourceMappingURL=chunk-CCZJJ4I2.js.map
364
+ //# sourceMappingURL=chunk-4G25SDQL.js.map
@@ -1,17 +1,17 @@
1
1
  import {
2
2
  freezeAndDeleteClosure,
3
3
  randomId
4
- } from "./chunk-FZ6NYJ7L.js";
4
+ } from "./chunk-H7HP56F6.js";
5
5
  import {
6
6
  buildAccessibleBundle,
7
7
  resolveAccessibleCollections
8
- } from "./chunk-FFDNKRCY.js";
8
+ } from "./chunk-DKWPJOYH.js";
9
9
  import {
10
- NOYDB_FORMAT_VERSION
11
- } from "./chunk-YPYHVOXP.js";
10
+ buildRecordEnvelope
11
+ } from "./chunk-N4CNVSUF.js";
12
12
  import {
13
13
  NoydbError
14
- } from "./chunk-HNGSV2YC.js";
14
+ } from "./chunk-JBIV4FLR.js";
15
15
 
16
16
  // src/with-audit/portability/request-withdrawal.ts
17
17
  var WITHDRAWAL_REQUESTS_COLLECTION = "_user_withdrawal_requests";
@@ -24,14 +24,11 @@ var WithdrawalRequestError = class extends NoydbError {
24
24
  function writeRequest(vault, req, expectedVersion) {
25
25
  const { name: vaultName, adapter } = vault._introspectState();
26
26
  const body = JSON.stringify(req);
27
- const env = {
28
- _noydb: NOYDB_FORMAT_VERSION,
29
- _v: expectedVersion + 1,
30
- _ts: req.decidedAt ?? req.requestedAt,
31
- _iv: "",
32
- _data: body,
33
- _by: req.decidedBy ?? req.requester
34
- };
27
+ const actor = req.decidedBy ?? req.requester;
28
+ const env = buildRecordEnvelope(
29
+ { collection: WITHDRAWAL_REQUESTS_COLLECTION, id: req.requestId, by: actor, version: expectedVersion + 1 },
30
+ { ts: req.decidedAt ?? req.requestedAt, iv: "", data: body }
31
+ );
35
32
  return adapter.put(vaultName, WITHDRAWAL_REQUESTS_COLLECTION, req.requestId, env, expectedVersion);
36
33
  }
37
34
  async function readRequest(vault, requestId) {
@@ -161,4 +158,4 @@ export {
161
158
  approveWithdrawal,
162
159
  rejectWithdrawal
163
160
  };
164
- //# sourceMappingURL=chunk-4I72F5DF.js.map
161
+ //# sourceMappingURL=chunk-4LPF226H.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-audit/portability/request-withdrawal.ts"],"sourcesContent":["/**\n * Two-party withdrawal ceremony.\n *\n * The conservative counterpart to `unilateralWithdrawal`: a non-owner —\n * including a read-only `client`/`viewer` who cannot self-serve a deletion —\n * files a durable REQUEST; an owner/admin reviews it and either APPROVES\n * (extract-and-dispose under firm authority) or REJECTS it. Every step is\n * audited in the tamper-evident ledger.\n *\n * requester: vault.user.requestWithdrawal({ scope, disposition?, legalBasis? })\n * owner: vault.user.listWithdrawalRequests()\n * vault.user.approveWithdrawal(requestId, { reKey }) → { bundle, snapshot? }\n * vault.user.rejectWithdrawal(requestId, { reason })\n *\n * Requests live in the reserved `_user_withdrawal_requests` namespace. The\n * record body is plaintext metadata (collection names + disposition + legal\n * basis — none secret in this trust model; the owner sees the data anyway) and\n * carries NO secret: the re-key secret is supplied by the approver at\n * approval time and conveyed to the requester out-of-band, so no secret is\n * stored at rest.\n */\nimport type { Vault } from '../../kernel/vault.js'\nimport { buildRecordEnvelope } from '../../kernel/enclave/index.js'\nimport { NoydbError } from '../../kernel/errors.js'\nimport { resolveAccessibleCollections, buildAccessibleBundle } from './export-accessible.js'\nimport { freezeAndDeleteClosure, randomId, type FrozenSnapshotRef, type WithdrawResult } from './withdraw-accessible.js'\n\nexport const WITHDRAWAL_REQUESTS_COLLECTION = '_user_withdrawal_requests'\n\n/** Raised when a request is missing, already decided, or expired. */\nexport class WithdrawalRequestError extends NoydbError {\n constructor(message: string) {\n super('WITHDRAWAL_REQUEST', message)\n this.name = 'WithdrawalRequestError'\n }\n}\n\nexport type WithdrawalRequestStatus = 'pending' | 'approved' | 'rejected'\n\nexport interface WithdrawalRequest {\n readonly requestId: string\n readonly requester: string\n readonly collections: readonly string[]\n readonly disposition: 'delete' | 'freeze'\n readonly legalBasis?: string\n readonly status: WithdrawalRequestStatus\n readonly requestedAt: string\n readonly expiresAt?: string\n readonly decidedAt?: string\n readonly decidedBy?: string\n readonly rejectReason?: string\n readonly snapshotSha256?: string\n}\n\nexport interface RequestWithdrawalOptions {\n readonly scope?: { readonly collections?: readonly string[] }\n readonly disposition?: 'delete' | 'freeze'\n readonly legalBasis?: string\n /** Time-to-live in ms; after this the request can no longer be approved. */\n readonly expiresInMs?: number\n}\n\nexport interface RequestWithdrawalResult {\n readonly requestId: string\n readonly status: WithdrawalRequestStatus\n readonly expiresAt?: string\n}\n\nfunction writeRequest(vault: Vault, req: WithdrawalRequest, expectedVersion: number): Promise<void> {\n const { name: vaultName, adapter } = vault._introspectState()\n const body = JSON.stringify(req)\n const actor = req.decidedBy ?? req.requester\n const env = buildRecordEnvelope(\n { collection: WITHDRAWAL_REQUESTS_COLLECTION, id: req.requestId, by: actor, version: expectedVersion + 1 },\n { ts: req.decidedAt ?? req.requestedAt, iv: '', data: body},\n )\n return adapter.put(vaultName, WITHDRAWAL_REQUESTS_COLLECTION, req.requestId, env, expectedVersion)\n}\n\nasync function readRequest(vault: Vault, requestId: string): Promise<{ req: WithdrawalRequest; version: number }> {\n const { name: vaultName, adapter } = vault._introspectState()\n const env = await adapter.get(vaultName, WITHDRAWAL_REQUESTS_COLLECTION, requestId)\n if (!env) throw new WithdrawalRequestError(`withdrawal request \"${requestId}\" not found`)\n return { req: JSON.parse(env._data) as WithdrawalRequest, version: env._v }\n}\n\n/**\n * Requester side. Files a durable request for the caller's accessible scope.\n * Gated by `user-request-withdrawal` (checked in the UserApi wrapper).\n */\nexport async function requestWithdrawal(\n vault: Vault,\n opts: RequestWithdrawalOptions = {},\n): Promise<RequestWithdrawalResult> {\n const { keyring } = vault._introspectState()\n // Resolve the requester's accessible collections (read access defines \"theirs\";\n // the owner — who can delete anything — executes the disposition on approval).\n const collections = resolveAccessibleCollections(keyring, opts.scope, false)\n if (!collections || collections.length === 0) {\n throw new WithdrawalRequestError(\n 'requestWithdrawal needs a concrete scope.collections (the caller has all-collection access — name the collections to withdraw)',\n )\n }\n const requestId = `wr-${randomId()}`\n const requestedAt = new Date().toISOString()\n const req: WithdrawalRequest = {\n requestId, requester: keyring.userId, collections, disposition: opts.disposition ?? 'delete',\n status: 'pending', requestedAt,\n ...(opts.legalBasis ? { legalBasis: opts.legalBasis } : {}),\n ...(opts.expiresInMs ? { expiresAt: new Date(Date.parse(requestedAt) + opts.expiresInMs).toISOString() } : {}),\n }\n await writeRequest(vault, req, 0) // create-only\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle', collection: '', id: '', version: 0, actor: keyring.userId, payloadHash: '',\n reason: `user-withdrawal-request:${requestId}:${keyring.userId}`,\n })\n return { requestId, status: 'pending', ...(req.expiresAt ? { expiresAt: req.expiresAt } : {}) }\n}\n\n/** Owner side. List filed requests (optionally by status). */\nexport async function listWithdrawalRequests(\n vault: Vault,\n opts: { status?: WithdrawalRequestStatus } = {},\n): Promise<WithdrawalRequest[]> {\n const { name: vaultName, adapter } = vault._introspectState()\n const ids = await adapter.list(vaultName, WITHDRAWAL_REQUESTS_COLLECTION)\n const out: WithdrawalRequest[] = []\n for (const id of ids) {\n const env = await adapter.get(vaultName, WITHDRAWAL_REQUESTS_COLLECTION, id)\n if (!env) continue\n const req = JSON.parse(env._data) as WithdrawalRequest\n if (!opts.status || req.status === opts.status) out.push(req)\n }\n return out\n}\n\nfunction assertApprover(vault: Vault): string {\n const { keyring } = vault._introspectState()\n // FR-6: custodian is INTENTIONALLY excluded (SAFER default — review flag).\n // Approving a two-party withdrawal is a destructive extract-and-dispose\n // exercised under FIRM authority — a governance act adjacent to grant/revoke,\n // which a non-owning custodian cannot do. It stays owner/admin-only.\n if (keyring.role !== 'owner' && keyring.role !== 'admin') {\n throw new WithdrawalRequestError('approveWithdrawal / rejectWithdrawal require an owner or admin')\n }\n return keyring.userId\n}\n\nfunction assertPending(req: WithdrawalRequest): void {\n if (req.status !== 'pending') {\n throw new WithdrawalRequestError(`withdrawal request \"${req.requestId}\" is already ${req.status}`)\n }\n if (req.expiresAt && Date.now() > Date.parse(req.expiresAt)) {\n throw new WithdrawalRequestError(`withdrawal request \"${req.requestId}\" expired at ${req.expiresAt}`)\n }\n}\n\nexport interface ApproveWithdrawalOptions {\n /** Re-key the handed-back bundle to a secret the requester will use. */\n readonly reKey?: { readonly secret: string }\n}\n\n/**\n * Owner side. Extract the requester's recorded scope under firm authority,\n * dispose of the source per the request's disposition, mark the request\n * approved, and return the re-keyed bundle to hand back. Gated by\n * `approve-user-withdrawal` (checked in the UserApi wrapper) + owner/admin role.\n */\nexport async function approveWithdrawal(\n vault: Vault,\n requestId: string,\n opts: ApproveWithdrawalOptions = {},\n): Promise<WithdrawResult> {\n const approver = assertApprover(vault)\n const { req, version } = await readRequest(vault, requestId)\n assertPending(req)\n\n // 1. Produce the requester's re-keyed portable copy FIRST (owner authority\n // holds every DEK, so the recorded collections are all readable).\n const bundle = await buildAccessibleBundle(vault, [...req.collections], opts.reKey)\n\n // 2. + 3. dispose of the source (freeze snapshot, optional → delete-closure).\n const snapshot: FrozenSnapshotRef | undefined = await freezeAndDeleteClosure(vault, req.collections, {\n disposition: req.disposition, actorUserId: approver, withdrawalId: `wd-${requestId}`,\n })\n\n // 4. mark approved + audit (OCC against the version we read).\n const decidedAt = new Date().toISOString()\n await writeRequest(vault, {\n ...req, status: 'approved', decidedAt, decidedBy: approver,\n ...(snapshot ? { snapshotSha256: snapshot.sha256 } : {}),\n }, version)\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle', collection: '', id: '', version: 0, actor: approver, payloadHash: '',\n reason: `user-withdrawal-approved:${requestId}:${req.requester}:${req.disposition}`,\n })\n\n return snapshot ? { bundle, snapshot } : { bundle }\n}\n\nexport interface RejectWithdrawalOptions {\n readonly reason?: string\n}\n\n/** Owner side. Decline a pending request (no data is touched). */\nexport async function rejectWithdrawal(\n vault: Vault,\n requestId: string,\n opts: RejectWithdrawalOptions = {},\n): Promise<WithdrawalRequest> {\n const approver = assertApprover(vault)\n const { req, version } = await readRequest(vault, requestId)\n assertPending(req)\n const decidedAt = new Date().toISOString()\n const updated: WithdrawalRequest = {\n ...req, status: 'rejected', decidedAt, decidedBy: approver,\n ...(opts.reason ? { rejectReason: opts.reason } : {}),\n }\n await writeRequest(vault, updated, version)\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle', collection: '', id: '', version: 0, actor: approver, payloadHash: '',\n reason: `user-withdrawal-rejected:${requestId}:${req.requester}`,\n })\n return updated\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2BO,IAAM,iCAAiC;AAGvC,IAAM,yBAAN,cAAqC,WAAW;AAAA,EACrD,YAAY,SAAiB;AAC3B,UAAM,sBAAsB,OAAO;AACnC,SAAK,OAAO;AAAA,EACd;AACF;AAiCA,SAAS,aAAa,OAAc,KAAwB,iBAAwC;AAClG,QAAM,EAAE,MAAM,WAAW,QAAQ,IAAI,MAAM,iBAAiB;AAC5D,QAAM,OAAO,KAAK,UAAU,GAAG;AAC/B,QAAM,QAAQ,IAAI,aAAa,IAAI;AACnC,QAAM,MAAM;AAAA,IACV,EAAE,YAAY,gCAAgC,IAAI,IAAI,WAAW,IAAI,OAAO,SAAS,kBAAkB,EAAE;AAAA,IACzG,EAAE,IAAI,IAAI,aAAa,IAAI,aAAa,IAAI,IAAI,MAAM,KAAI;AAAA,EAC5D;AACA,SAAO,QAAQ,IAAI,WAAW,gCAAgC,IAAI,WAAW,KAAK,eAAe;AACnG;AAEA,eAAe,YAAY,OAAc,WAAyE;AAChH,QAAM,EAAE,MAAM,WAAW,QAAQ,IAAI,MAAM,iBAAiB;AAC5D,QAAM,MAAM,MAAM,QAAQ,IAAI,WAAW,gCAAgC,SAAS;AAClF,MAAI,CAAC,IAAK,OAAM,IAAI,uBAAuB,uBAAuB,SAAS,aAAa;AACxF,SAAO,EAAE,KAAK,KAAK,MAAM,I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terializedViewConfigError,
6
+ MaterializedViewSourceUnknownError,
7
+ RefNotDeclaredError
8
+ } from "./chunk-JBIV4FLR.js";
7
9
 
8
10
  // src/with-formula/materialized-views/dependency-analyzer.ts
9
11
  function analyzeDependencies(query) {
@@ -44,7 +46,10 @@ function summarizeQueryPlan(query) {
44
46
  as: c.as,
45
47
  // Inline on: callback: use sentinel — drift detection disabled for this MV
46
48
  onPredicateName: c.onPredicateName ?? (c.on ? "[inline]" : null),
47
- maxRows: c.maxRows ?? null
49
+ maxRows: c.maxRows ?? null,
50
+ // `outer` changes the row set, so it is part of the plan's identity
51
+ // for drift detection, not decoration (#1130).
52
+ outer: c.outer ?? false
48
53
  };
49
54
  }
50
55
  return c;
@@ -60,9 +65,10 @@ function summarizeUnionPlan(spec) {
60
65
  }
61
66
  function summarizeProjectionPlan(spec) {
62
67
  const projection = spec.projection;
63
- const legs = projection.joins.map(
64
- (leg) => "collect" in leg ? `collect:${leg.collect}.${leg.on}\u2192${leg.as}` : `field:${leg.field}\u2192${leg.as}`
65
- ).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();
66
72
  const body = JSON.stringify({ source: projection.source, legs });
67
73
  return `projection(${body})${summarizeGroupingTail(spec)}`;
68
74
  }
@@ -102,6 +108,44 @@ function canonicalizeQueryPlan(plan) {
102
108
  });
103
109
  }
104
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
+
105
149
  // src/with-formula/materialized-views/registry.ts
106
150
  var WHOLE_RECORD = "*";
107
151
  var MaterializedViewRegistry = class {
@@ -123,6 +167,33 @@ var MaterializedViewRegistry = class {
123
167
  * target has resolved (see `_resolvePendingForwardDeps`).
124
168
  */
125
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 = [];
126
197
  /**
127
198
  * Register an MV. Invokes `spec.query()` once at registration time to
128
199
  * read the plan + join context; the resulting `Query<T>` is discarded
@@ -149,13 +220,20 @@ var MaterializedViewRegistry = class {
149
220
  const projection = spec.projection;
150
221
  dependencies = /* @__PURE__ */ new Set([projection.source]);
151
222
  for (const leg of projection.joins) {
152
- if ("collect" in leg) dependencies.add(leg.collect);
153
- else pendingForwardFields.push(leg.field);
223
+ if (isCollectLeg(leg)) dependencies.add(leg.collect);
224
+ else pendingForwardFields.push(leg.as);
154
225
  }
155
226
  if (spec.sources) for (const s of spec.sources) dependencies.add(s);
156
227
  queryPlanSummary = summarizeProjectionPlan(spec);
157
228
  } else {
158
- 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
+ }
159
237
  qAny = q;
160
238
  isQuery = typeof qAny._plan === "function";
161
239
  if (isQuery) {
@@ -203,15 +281,51 @@ var MaterializedViewRegistry = class {
203
281
  }
204
282
  if (pendingForwardFields.length > 0) {
205
283
  const refRegistry = db.refRegistry;
206
- const source = spec.projection.source;
284
+ const projectionSpec = spec.projection;
285
+ const resolveRef = (c, f) => refRegistry?.getOutbound(c)[f] ?? null;
207
286
  this._pendingForwardDeps.push({
208
287
  reg,
209
- fields: new Set(pendingForwardFields),
210
- 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
+ }
211
294
  });
212
295
  this._resolvePendingForwardDeps();
213
296
  }
214
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
+ }
215
329
  /** All MVs that depend on `source`, in registration order. */
216
330
  mvsForSource(source) {
217
331
  if (this._pendingForwardDeps.length > 0) this._resolvePendingForwardDeps();
@@ -234,17 +348,17 @@ var MaterializedViewRegistry = class {
234
348
  _resolvePendingForwardDeps() {
235
349
  for (let i = this._pendingForwardDeps.length - 1; i >= 0; i--) {
236
350
  const entry = this._pendingForwardDeps[i];
237
- for (const field of [...entry.fields]) {
238
- const target = entry.resolveTarget(field);
351
+ for (const alias of [...entry.aliases]) {
352
+ const target = entry.resolveTarget(alias);
239
353
  if (target === null) continue;
240
- entry.fields.delete(field);
354
+ entry.aliases.delete(alias);
241
355
  if (entry.reg.dependencies.has(target)) continue;
242
356
  entry.reg.dependencies.add(target);
243
357
  const arr = this._bySource.get(target);
244
358
  if (arr) arr.push(entry.reg);
245
359
  else this._bySource.set(target, [entry.reg]);
246
360
  }
247
- if (entry.fields.size === 0) this._pendingForwardDeps.splice(i, 1);
361
+ if (entry.aliases.size === 0) this._pendingForwardDeps.splice(i, 1);
248
362
  }
249
363
  }
250
364
  /** Single MV by name, or `undefined`. */
@@ -363,7 +477,10 @@ export {
363
477
  summarizeQueryPlan,
364
478
  computeQueryHash,
365
479
  canonicalizeQueryPlan,
480
+ isCollectLeg,
481
+ validateProjectionLegs,
482
+ resolveLegOwner,
366
483
  MaterializedViewRegistry,
367
484
  wrapDbWithPredicates
368
485
  };
369
- //# sourceMappingURL=chunk-7F4DBNSP.js.map
486
+ //# sourceMappingURL=chunk-4ZPE6SKS.js.map