@noy-db/hub 0.3.0-pre.1 → 0.3.0-pre.3

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 (332) hide show
  1. package/dist/adapter/index.d.ts +2 -2
  2. package/dist/adapter/index.js +1 -1
  3. package/dist/aggregate/index.d.ts +3 -3
  4. package/dist/aggregate/index.js +4 -4
  5. package/dist/api-LORZ2EZU.js +17 -0
  6. package/dist/as/index.d.ts +4 -4
  7. package/dist/as/index.js +9 -6
  8. package/dist/at/index.d.ts +2 -2
  9. package/dist/attestation/index.d.ts +3 -3
  10. package/dist/attestation/index.js +18 -15
  11. package/dist/attestation/index.js.map +1 -1
  12. package/dist/{backup-XV3IOEGB.js → backup-NGRJ46SH.js} +11 -6
  13. package/dist/backup-NGRJ46SH.js.map +1 -0
  14. package/dist/blobs/index.d.ts +4 -4
  15. package/dist/blobs/index.js +8 -5
  16. package/dist/blobs/index.js.map +1 -1
  17. package/dist/bundle/index.d.ts +5 -5
  18. package/dist/bundle/index.js +18 -15
  19. package/dist/bundle/index.js.map +1 -1
  20. package/dist/{bundle-CH-H06dp.d.ts → bundle-B-P3_Jvb.d.ts} +1 -1
  21. package/dist/by/index.js +2 -2
  22. package/dist/cargo/index.d.ts +4 -4
  23. package/dist/cargo/index.js +20 -17
  24. package/dist/{chunk-Y22T3KQE.js → chunk-2KSPDSWI.js} +3 -3
  25. package/dist/{chunk-ITNUCOXM.js → chunk-2N4MUSF3.js} +7 -5
  26. package/dist/{chunk-ITNUCOXM.js.map → chunk-2N4MUSF3.js.map} +1 -1
  27. package/dist/{chunk-5N6CZTCY.js → chunk-2ZORB5RW.js} +3 -3
  28. package/dist/{chunk-FISN7WE4.js → chunk-3UDPDRUC.js} +4 -4
  29. package/dist/{chunk-TA66UMI4.js → chunk-46YGCU6Z.js} +2 -2
  30. package/dist/{chunk-IPB7FTQX.js → chunk-4DZGZ7II.js} +8 -6
  31. package/dist/{chunk-IPB7FTQX.js.map → chunk-4DZGZ7II.js.map} +1 -1
  32. package/dist/{chunk-SKF73JOP.js → chunk-4NMFWOS2.js} +3 -3
  33. package/dist/{chunk-IAGBDSCS.js → chunk-4NZCZUGL.js} +2 -2
  34. package/dist/{chunk-DFEMTNPJ.js → chunk-55HDKLI3.js} +8 -6
  35. package/dist/{chunk-DFEMTNPJ.js.map → chunk-55HDKLI3.js.map} +1 -1
  36. package/dist/{chunk-WWGT2MDV.js → chunk-5A6TC3RQ.js} +5 -5
  37. package/dist/{chunk-5O3AOPDT.js → chunk-5EZAJEES.js} +151 -432
  38. package/dist/chunk-5EZAJEES.js.map +1 -0
  39. package/dist/{chunk-62QYRORB.js → chunk-5Z3RNFJC.js} +3 -3
  40. package/dist/{chunk-M6OST55S.js → chunk-5ZPWVNL3.js} +2 -2
  41. package/dist/{chunk-PSMV73A5.js → chunk-6CNLU4TO.js} +5 -5
  42. package/dist/{chunk-2P2HZEXU.js → chunk-6DP5HBQD.js} +11 -9
  43. package/dist/{chunk-2P2HZEXU.js.map → chunk-6DP5HBQD.js.map} +1 -1
  44. package/dist/{chunk-AIWULCUO.js → chunk-6EVZXETK.js} +5 -3
  45. package/dist/{chunk-AIWULCUO.js.map → chunk-6EVZXETK.js.map} +1 -1
  46. package/dist/{chunk-GYGWYIOZ.js → chunk-6I2YPLAG.js} +7 -5
  47. package/dist/{chunk-GYGWYIOZ.js.map → chunk-6I2YPLAG.js.map} +1 -1
  48. package/dist/{chunk-SRB2XEWB.js → chunk-6OQ7NKMZ.js} +6 -4
  49. package/dist/{chunk-SRB2XEWB.js.map → chunk-6OQ7NKMZ.js.map} +1 -1
  50. package/dist/chunk-6RASM2J4.js +25 -0
  51. package/dist/chunk-6RASM2J4.js.map +1 -0
  52. package/dist/{chunk-5LUY7UTV.js → chunk-7IP75FP2.js} +2 -2
  53. package/dist/{chunk-HCIPRAGS.js → chunk-7MHVHGQZ.js} +2 -2
  54. package/dist/{chunk-5R5JW2JT.js → chunk-ADBMJDBW.js} +380 -85
  55. package/dist/chunk-ADBMJDBW.js.map +1 -0
  56. package/dist/{chunk-ZCGAHGUS.js → chunk-AY4P6PHN.js} +2 -2
  57. package/dist/{chunk-ZYUC53LT.js → chunk-BLZRNHMG.js} +51 -2
  58. package/dist/{chunk-ZYUC53LT.js.map → chunk-BLZRNHMG.js.map} +1 -1
  59. package/dist/{chunk-KXGNJJXB.js → chunk-BV7KNFJY.js} +7 -7
  60. package/dist/{chunk-BG3SPSR4.js → chunk-BYW7EU5L.js} +2 -2
  61. package/dist/{chunk-NF5JWERG.js → chunk-BZIWKN74.js} +2 -2
  62. package/dist/chunk-CPAROOKP.js +124 -0
  63. package/dist/chunk-CPAROOKP.js.map +1 -0
  64. package/dist/{chunk-AQTBSL7R.js → chunk-CVXLJIAV.js} +5 -5
  65. package/dist/{chunk-CWPPNPOH.js → chunk-DA34OEZU.js} +2 -2
  66. package/dist/{chunk-RUEKROOS.js → chunk-DGUR3CC4.js} +2 -2
  67. package/dist/{chunk-LXQT4WMP.js → chunk-DHIN36UC.js} +8 -6
  68. package/dist/{chunk-LXQT4WMP.js.map → chunk-DHIN36UC.js.map} +1 -1
  69. package/dist/{chunk-JNUWZ6D3.js → chunk-E4YJUNPU.js} +7 -5
  70. package/dist/{chunk-JNUWZ6D3.js.map → chunk-E4YJUNPU.js.map} +1 -1
  71. package/dist/{chunk-UV5MFVO3.js → chunk-FELHYKIO.js} +2 -2
  72. package/dist/{chunk-KVOXU4T5.js → chunk-HGQG3VIP.js} +2 -2
  73. package/dist/{chunk-XXYIOFUB.js → chunk-IIK7W3AN.js} +5 -5
  74. package/dist/{chunk-IGUYVGGI.js → chunk-IJW6K6UX.js} +3 -3
  75. package/dist/{chunk-76722EBH.js → chunk-IWVWB7BZ.js} +11 -9
  76. package/dist/{chunk-76722EBH.js.map → chunk-IWVWB7BZ.js.map} +1 -1
  77. package/dist/{chunk-QHJW5EXU.js → chunk-JFYIHLU3.js} +2 -2
  78. package/dist/chunk-L4IRFTIF.js +424 -0
  79. package/dist/chunk-L4IRFTIF.js.map +1 -0
  80. package/dist/{chunk-SM3AVUHC.js → chunk-LES2Z7B4.js} +2 -2
  81. package/dist/{chunk-IUEN57TV.js → chunk-LHYQE3BP.js} +4 -4
  82. package/dist/{chunk-V7RWQRG7.js → chunk-LKBLAUOB.js} +3 -3
  83. package/dist/{chunk-UDRIWL7A.js → chunk-MCJAUQGE.js} +3 -3
  84. package/dist/chunk-MIOLJG2R.js +105 -0
  85. package/dist/chunk-MIOLJG2R.js.map +1 -0
  86. package/dist/{chunk-UIU2THRG.js → chunk-N2FP26NH.js} +5 -5
  87. package/dist/{chunk-DGDI2D4M.js → chunk-NIA5VQ7G.js} +8 -6
  88. package/dist/{chunk-DGDI2D4M.js.map → chunk-NIA5VQ7G.js.map} +1 -1
  89. package/dist/{chunk-CMGR4ZEW.js → chunk-NMRKAGHE.js} +2 -2
  90. package/dist/{chunk-LV7M27WM.js → chunk-NPVICKZE.js} +4 -4
  91. package/dist/chunk-NTHKOFVL.js +195 -0
  92. package/dist/chunk-NTHKOFVL.js.map +1 -0
  93. package/dist/{chunk-IO6GRPT6.js → chunk-O5DNEXQC.js} +2 -2
  94. package/dist/{chunk-5TDJ56JE.js → chunk-OCDUQUAP.js} +1 -1
  95. package/dist/chunk-OCDUQUAP.js.map +1 -0
  96. package/dist/{chunk-UPJNJGGA.js → chunk-OVIVYAQL.js} +10 -8
  97. package/dist/{chunk-UPJNJGGA.js.map → chunk-OVIVYAQL.js.map} +1 -1
  98. package/dist/{chunk-I2NOIW44.js → chunk-P6DN5QU7.js} +8 -6
  99. package/dist/{chunk-I2NOIW44.js.map → chunk-P6DN5QU7.js.map} +1 -1
  100. package/dist/{chunk-Q7SS3IME.js → chunk-P6UXDALK.js} +3 -3
  101. package/dist/{chunk-UAG5KWVA.js → chunk-PJDK2PPQ.js} +3 -3
  102. package/dist/{chunk-AXRXJTE2.js → chunk-PUNJAEY6.js} +5 -5
  103. package/dist/{chunk-LFLXAY2W.js → chunk-PYWW4KLO.js} +9 -7
  104. package/dist/{chunk-LFLXAY2W.js.map → chunk-PYWW4KLO.js.map} +1 -1
  105. package/dist/{chunk-M2YKN37S.js → chunk-QLQS5A7X.js} +2 -2
  106. package/dist/{chunk-I3TIKTJO.js → chunk-TICO2I2O.js} +2 -2
  107. package/dist/{chunk-3YFXJ3ZP.js → chunk-U5DWHU3S.js} +2 -2
  108. package/dist/{chunk-26LGBE4T.js → chunk-U6OM4E67.js} +6 -4
  109. package/dist/{chunk-26LGBE4T.js.map → chunk-U6OM4E67.js.map} +1 -1
  110. package/dist/{chunk-TEILUWOI.js → chunk-UP6EMMDI.js} +10 -10
  111. package/dist/{chunk-SMXWYP24.js → chunk-VBYVKOMJ.js} +3 -3
  112. package/dist/{chunk-AZAOEIKW.js → chunk-VHEEU4ZO.js} +2 -2
  113. package/dist/{chunk-MD3Y6J3L.js → chunk-WVIIJPTJ.js} +7 -5
  114. package/dist/{chunk-MD3Y6J3L.js.map → chunk-WVIIJPTJ.js.map} +1 -1
  115. package/dist/{chunk-EIZUR2XW.js → chunk-XRE4JOEO.js} +2 -2
  116. package/dist/{chunk-VFQGRQIH.js → chunk-YDP2SA5K.js} +7 -5
  117. package/dist/{chunk-VFQGRQIH.js.map → chunk-YDP2SA5K.js.map} +1 -1
  118. package/dist/{chunk-5R3ERCDH.js → chunk-YN66UOXT.js} +3 -3
  119. package/dist/{chunk-IELYAOGG.js → chunk-YTIAXSUE.js} +4 -4
  120. package/dist/{chunk-TJYQIGAP.js → chunk-Z44OY24N.js} +3 -3
  121. package/dist/{chunk-VCTFO5CO.js → chunk-ZAWD6O46.js} +2 -2
  122. package/dist/{chunk-PKHL44ER.js → chunk-ZD4D7UM6.js} +2 -2
  123. package/dist/{chunk-MTMJVJ5W.js → chunk-ZFME46HJ.js} +5 -3
  124. package/dist/chunk-ZFME46HJ.js.map +1 -0
  125. package/dist/{chunk-LMTH2RM6.js → chunk-ZNI3RTFV.js} +2 -2
  126. package/dist/{chunk-WYSO2NIH.js → chunk-ZRDYQZYH.js} +2 -2
  127. package/dist/classified/index.d.ts +17 -0
  128. package/dist/classified/index.js +38 -0
  129. package/dist/collection-facade-XPVRHBGU.js +36 -0
  130. package/dist/consent/index.d.ts +3 -3
  131. package/dist/consent/index.js +7 -4
  132. package/dist/consent/index.js.map +1 -1
  133. package/dist/crdt/index.d.ts +3 -3
  134. package/dist/delegation-4HUHUE6T.js +22 -0
  135. package/dist/derivations/index.d.ts +4 -4
  136. package/dist/derivations/index.js +9 -6
  137. package/dist/describe/index.d.ts +1 -1
  138. package/dist/{describe-aBkJR2sd.d.ts → describe-0tiXAjoO.d.ts} +22 -0
  139. package/dist/{dev-unlock-C9Ro3v_O.d.ts → dev-unlock-B_s9DUWa.d.ts} +1 -1
  140. package/dist/{enclave-UL5LW66V.js → enclave-IS7HZSQ7.js} +34 -18
  141. package/dist/executor-ANFBCOYA.js +9 -0
  142. package/dist/executor-IKT47SH2.js +9 -0
  143. package/dist/executor-OIECZXTV.js +18 -0
  144. package/dist/export-accessible-NZWCFZHL.js +20 -0
  145. package/dist/extract-partition-52LX6RQH.js +33 -0
  146. package/dist/{fanout-sidecar-GF3DJ6KR.js → fanout-sidecar-DDKRG2MX.js} +14 -14
  147. package/dist/fanout-sidecar-DDKRG2MX.js.map +1 -0
  148. package/dist/forget/index.js +7 -4
  149. package/dist/forget/index.js.map +1 -1
  150. package/dist/guards/index.d.ts +4 -4
  151. package/dist/guards/index.js +3 -3
  152. package/dist/{hash-Cp5uwiox.d.ts → hash-CWxn7sf6.d.ts} +7 -2
  153. package/dist/history/index.d.ts +4 -4
  154. package/dist/history/index.js +9 -6
  155. package/dist/history/index.js.map +1 -1
  156. package/dist/i18n/index.d.ts +3 -3
  157. package/dist/i18n/index.js +11 -8
  158. package/dist/i18n/index.js.map +1 -1
  159. package/dist/in/index.d.ts +2 -2
  160. package/dist/{index-BzUo1B6n.d.ts → index-D05bV0_g.d.ts} +245 -5
  161. package/dist/{index-BF9_96A5.d.ts → index-DTMUUwwW.d.ts} +3 -3
  162. package/dist/index.d.ts +30 -14
  163. package/dist/index.js +136 -75
  164. package/dist/index.js.map +1 -1
  165. package/dist/indexing/index.d.ts +3 -3
  166. package/dist/indexing/index.js +4 -4
  167. package/dist/issue-F4SYPJGJ.js +16 -0
  168. package/dist/kernel/index.d.ts +3 -3
  169. package/dist/kernel/index.js +10 -7
  170. package/dist/{ledger-RYI35CDS.js → ledger-YUAJUNFP.js} +9 -6
  171. package/dist/liberate-6LDETRIW.js +21 -0
  172. package/dist/materialized-views/index.d.ts +4 -4
  173. package/dist/materialized-views/index.js +13 -10
  174. package/dist/{mime-magic-CGhw37_E.d.ts → mime-magic-Qr_4HjP6.d.ts} +1 -1
  175. package/dist/noydb-WQNBVJIG.js +54 -0
  176. package/dist/on/index.d.ts +2 -2
  177. package/dist/on/index.js +7 -4
  178. package/dist/overlay-views/index.d.ts +4 -4
  179. package/dist/overlay-views/index.js +4 -4
  180. package/dist/periods/index.d.ts +3 -3
  181. package/dist/periods/index.js +10 -7
  182. package/dist/pod/index.d.ts +3 -3
  183. package/dist/pod/index.js +9 -6
  184. package/dist/{policy-IXK4FVXP.js → policy-LRE6HTO5.js} +5 -5
  185. package/dist/portability/index.d.ts +3 -3
  186. package/dist/portability/index.js +8 -8
  187. package/dist/{public-envelope-JHDQCPSX.js → public-envelope-WVRRUVAJ.js} +4 -4
  188. package/dist/query/index.d.ts +2 -2
  189. package/dist/query/index.js +6 -6
  190. package/dist/registry-6HZ2JSQ7.js +14 -0
  191. package/dist/registry-GPXZQ7DT.js +9 -0
  192. package/dist/registry-USYD2ECC.js +16 -0
  193. package/dist/request-withdrawal-54V4L6CR.js +28 -0
  194. package/dist/reveal-WSUHXCSS.js +37 -0
  195. package/dist/reveal-WSUHXCSS.js.map +1 -0
  196. package/dist/revoke-JV26NTQD.js +21 -0
  197. package/dist/sealed-record/index.d.ts +3 -3
  198. package/dist/sealed-record/index.js +10 -7
  199. package/dist/sealed-record/index.js.map +1 -1
  200. package/dist/session/index.d.ts +4 -4
  201. package/dist/session/index.js +7 -4
  202. package/dist/session/index.js.map +1 -1
  203. package/dist/shadow/index.d.ts +3 -3
  204. package/dist/shadow/index.js +2 -2
  205. package/dist/{signer-PNKTBVF7.js → signer-AE56T5HE.js} +8 -5
  206. package/dist/snapshots/index.d.ts +3 -3
  207. package/dist/snapshots/index.js +8 -5
  208. package/dist/snapshots/index.js.map +1 -1
  209. package/dist/{stale-3JWHNDIY.js → stale-LX4BR43V.js} +2 -2
  210. package/dist/{store-coordination-provider-3I7XWZZK.js → store-coordination-provider-KTRIC6PR.js} +3 -3
  211. package/dist/sync/index.d.ts +2 -2
  212. package/dist/sync/index.js +7 -4
  213. package/dist/sync/index.js.map +1 -1
  214. package/dist/team/index.d.ts +3 -3
  215. package/dist/team/index.js +13 -10
  216. package/dist/tiers/index.d.ts +2 -2
  217. package/dist/tiers/index.js +8 -5
  218. package/dist/to/index.d.ts +2 -2
  219. package/dist/to/index.js +1 -1
  220. package/dist/{transition-guard-C7ol6oPw.d.ts → transition-guard-C1Pyz8nH.d.ts} +1 -1
  221. package/dist/tx/index.d.ts +3 -3
  222. package/dist/tx/index.js +3 -3
  223. package/dist/ui/index.d.ts +1 -1
  224. package/dist/util/index.js +1 -1
  225. package/dist/validators-Dzn7T-3x.d.ts +62 -0
  226. package/dist/{vault-diff-B5fYNBL7.d.ts → vault-diff-Fn0WeY2w.d.ts} +1 -1
  227. package/dist/verify-SW6J63Q2.js +135 -0
  228. package/dist/verify-SW6J63Q2.js.map +1 -0
  229. package/dist/with/index.d.ts +3 -3
  230. package/dist/with/index.js +9 -6
  231. package/dist/{with-materialized-view-6p0Fk8bL.d.ts → with-materialized-view-NKxs6iK5.d.ts} +1 -1
  232. package/dist/{with-overlayed-view-BJ6mXGMd.d.ts → with-overlayed-view-B4fPYHwV.d.ts} +1 -1
  233. package/dist/{with-rollup-BvQo3ROo.d.ts → with-rollup-Bl0sRFEt.d.ts} +1 -1
  234. package/dist/withdraw-accessible-DGA4V2TP.js +25 -0
  235. package/dist/withdraw-accessible-DGA4V2TP.js.map +1 -0
  236. package/package.json +7 -3
  237. package/dist/api-RW3KP7WU.js +0 -14
  238. package/dist/backup-XV3IOEGB.js.map +0 -1
  239. package/dist/chunk-5O3AOPDT.js.map +0 -1
  240. package/dist/chunk-5R5JW2JT.js.map +0 -1
  241. package/dist/chunk-5TDJ56JE.js.map +0 -1
  242. package/dist/chunk-MTMJVJ5W.js.map +0 -1
  243. package/dist/collection-facade-GQAOGJP2.js +0 -33
  244. package/dist/delegation-UL5HKLER.js +0 -19
  245. package/dist/executor-2FWQRLMG.js +0 -15
  246. package/dist/executor-QZ7BXICW.js +0 -9
  247. package/dist/executor-Z5ZLJVTV.js +0 -9
  248. package/dist/export-accessible-KRV5W4GH.js +0 -17
  249. package/dist/extract-partition-GLKBOXFQ.js +0 -30
  250. package/dist/fanout-sidecar-GF3DJ6KR.js.map +0 -1
  251. package/dist/issue-Y6UVIR43.js +0 -13
  252. package/dist/liberate-CRPZEV7O.js +0 -18
  253. package/dist/noydb-367AM4HT.js +0 -50
  254. package/dist/registry-45RJNWGU.js +0 -9
  255. package/dist/registry-5GRV5VXI.js +0 -13
  256. package/dist/registry-WEUCHBO4.js +0 -11
  257. package/dist/request-withdrawal-GBPH2FDY.js +0 -25
  258. package/dist/revoke-TUFRGI6S.js +0 -18
  259. package/dist/withdraw-accessible-FFS46EOD.js +0 -22
  260. /package/dist/{api-RW3KP7WU.js.map → api-LORZ2EZU.js.map} +0 -0
  261. /package/dist/{chunk-Y22T3KQE.js.map → chunk-2KSPDSWI.js.map} +0 -0
  262. /package/dist/{chunk-5N6CZTCY.js.map → chunk-2ZORB5RW.js.map} +0 -0
  263. /package/dist/{chunk-FISN7WE4.js.map → chunk-3UDPDRUC.js.map} +0 -0
  264. /package/dist/{chunk-TA66UMI4.js.map → chunk-46YGCU6Z.js.map} +0 -0
  265. /package/dist/{chunk-SKF73JOP.js.map → chunk-4NMFWOS2.js.map} +0 -0
  266. /package/dist/{chunk-IAGBDSCS.js.map → chunk-4NZCZUGL.js.map} +0 -0
  267. /package/dist/{chunk-WWGT2MDV.js.map → chunk-5A6TC3RQ.js.map} +0 -0
  268. /package/dist/{chunk-62QYRORB.js.map → chunk-5Z3RNFJC.js.map} +0 -0
  269. /package/dist/{chunk-M6OST55S.js.map → chunk-5ZPWVNL3.js.map} +0 -0
  270. /package/dist/{chunk-PSMV73A5.js.map → chunk-6CNLU4TO.js.map} +0 -0
  271. /package/dist/{chunk-5LUY7UTV.js.map → chunk-7IP75FP2.js.map} +0 -0
  272. /package/dist/{chunk-HCIPRAGS.js.map → chunk-7MHVHGQZ.js.map} +0 -0
  273. /package/dist/{chunk-ZCGAHGUS.js.map → chunk-AY4P6PHN.js.map} +0 -0
  274. /package/dist/{chunk-KXGNJJXB.js.map → chunk-BV7KNFJY.js.map} +0 -0
  275. /package/dist/{chunk-BG3SPSR4.js.map → chunk-BYW7EU5L.js.map} +0 -0
  276. /package/dist/{chunk-NF5JWERG.js.map → chunk-BZIWKN74.js.map} +0 -0
  277. /package/dist/{chunk-AQTBSL7R.js.map → chunk-CVXLJIAV.js.map} +0 -0
  278. /package/dist/{chunk-CWPPNPOH.js.map → chunk-DA34OEZU.js.map} +0 -0
  279. /package/dist/{chunk-RUEKROOS.js.map → chunk-DGUR3CC4.js.map} +0 -0
  280. /package/dist/{chunk-UV5MFVO3.js.map → chunk-FELHYKIO.js.map} +0 -0
  281. /package/dist/{chunk-KVOXU4T5.js.map → chunk-HGQG3VIP.js.map} +0 -0
  282. /package/dist/{chunk-XXYIOFUB.js.map → chunk-IIK7W3AN.js.map} +0 -0
  283. /package/dist/{chunk-IGUYVGGI.js.map → chunk-IJW6K6UX.js.map} +0 -0
  284. /package/dist/{chunk-QHJW5EXU.js.map → chunk-JFYIHLU3.js.map} +0 -0
  285. /package/dist/{chunk-SM3AVUHC.js.map → chunk-LES2Z7B4.js.map} +0 -0
  286. /package/dist/{chunk-IUEN57TV.js.map → chunk-LHYQE3BP.js.map} +0 -0
  287. /package/dist/{chunk-V7RWQRG7.js.map → chunk-LKBLAUOB.js.map} +0 -0
  288. /package/dist/{chunk-UDRIWL7A.js.map → chunk-MCJAUQGE.js.map} +0 -0
  289. /package/dist/{chunk-UIU2THRG.js.map → chunk-N2FP26NH.js.map} +0 -0
  290. /package/dist/{chunk-CMGR4ZEW.js.map → chunk-NMRKAGHE.js.map} +0 -0
  291. /package/dist/{chunk-LV7M27WM.js.map → chunk-NPVICKZE.js.map} +0 -0
  292. /package/dist/{chunk-IO6GRPT6.js.map → chunk-O5DNEXQC.js.map} +0 -0
  293. /package/dist/{chunk-Q7SS3IME.js.map → chunk-P6UXDALK.js.map} +0 -0
  294. /package/dist/{chunk-UAG5KWVA.js.map → chunk-PJDK2PPQ.js.map} +0 -0
  295. /package/dist/{chunk-AXRXJTE2.js.map → chunk-PUNJAEY6.js.map} +0 -0
  296. /package/dist/{chunk-M2YKN37S.js.map → chunk-QLQS5A7X.js.map} +0 -0
  297. /package/dist/{chunk-I3TIKTJO.js.map → chunk-TICO2I2O.js.map} +0 -0
  298. /package/dist/{chunk-3YFXJ3ZP.js.map → chunk-U5DWHU3S.js.map} +0 -0
  299. /package/dist/{chunk-TEILUWOI.js.map → chunk-UP6EMMDI.js.map} +0 -0
  300. /package/dist/{chunk-SMXWYP24.js.map → chunk-VBYVKOMJ.js.map} +0 -0
  301. /package/dist/{chunk-AZAOEIKW.js.map → chunk-VHEEU4ZO.js.map} +0 -0
  302. /package/dist/{chunk-EIZUR2XW.js.map → chunk-XRE4JOEO.js.map} +0 -0
  303. /package/dist/{chunk-5R3ERCDH.js.map → chunk-YN66UOXT.js.map} +0 -0
  304. /package/dist/{chunk-IELYAOGG.js.map → chunk-YTIAXSUE.js.map} +0 -0
  305. /package/dist/{chunk-TJYQIGAP.js.map → chunk-Z44OY24N.js.map} +0 -0
  306. /package/dist/{chunk-VCTFO5CO.js.map → chunk-ZAWD6O46.js.map} +0 -0
  307. /package/dist/{chunk-PKHL44ER.js.map → chunk-ZD4D7UM6.js.map} +0 -0
  308. /package/dist/{chunk-LMTH2RM6.js.map → chunk-ZNI3RTFV.js.map} +0 -0
  309. /package/dist/{chunk-WYSO2NIH.js.map → chunk-ZRDYQZYH.js.map} +0 -0
  310. /package/dist/{collection-facade-GQAOGJP2.js.map → classified/index.js.map} +0 -0
  311. /package/dist/{delegation-UL5HKLER.js.map → collection-facade-XPVRHBGU.js.map} +0 -0
  312. /package/dist/{enclave-UL5LW66V.js.map → delegation-4HUHUE6T.js.map} +0 -0
  313. /package/dist/{executor-2FWQRLMG.js.map → enclave-IS7HZSQ7.js.map} +0 -0
  314. /package/dist/{executor-QZ7BXICW.js.map → executor-ANFBCOYA.js.map} +0 -0
  315. /package/dist/{executor-Z5ZLJVTV.js.map → executor-IKT47SH2.js.map} +0 -0
  316. /package/dist/{export-accessible-KRV5W4GH.js.map → executor-OIECZXTV.js.map} +0 -0
  317. /package/dist/{extract-partition-GLKBOXFQ.js.map → export-accessible-NZWCFZHL.js.map} +0 -0
  318. /package/dist/{issue-Y6UVIR43.js.map → extract-partition-52LX6RQH.js.map} +0 -0
  319. /package/dist/{ledger-RYI35CDS.js.map → issue-F4SYPJGJ.js.map} +0 -0
  320. /package/dist/{liberate-CRPZEV7O.js.map → ledger-YUAJUNFP.js.map} +0 -0
  321. /package/dist/{noydb-367AM4HT.js.map → liberate-6LDETRIW.js.map} +0 -0
  322. /package/dist/{policy-IXK4FVXP.js.map → noydb-WQNBVJIG.js.map} +0 -0
  323. /package/dist/{public-envelope-JHDQCPSX.js.map → policy-LRE6HTO5.js.map} +0 -0
  324. /package/dist/{registry-45RJNWGU.js.map → public-envelope-WVRRUVAJ.js.map} +0 -0
  325. /package/dist/{registry-5GRV5VXI.js.map → registry-6HZ2JSQ7.js.map} +0 -0
  326. /package/dist/{registry-WEUCHBO4.js.map → registry-GPXZQ7DT.js.map} +0 -0
  327. /package/dist/{request-withdrawal-GBPH2FDY.js.map → registry-USYD2ECC.js.map} +0 -0
  328. /package/dist/{revoke-TUFRGI6S.js.map → request-withdrawal-54V4L6CR.js.map} +0 -0
  329. /package/dist/{signer-PNKTBVF7.js.map → revoke-JV26NTQD.js.map} +0 -0
  330. /package/dist/{stale-3JWHNDIY.js.map → signer-AE56T5HE.js.map} +0 -0
  331. /package/dist/{withdraw-accessible-FFS46EOD.js.map → stale-LX4BR43V.js.map} +0 -0
  332. /package/dist/{store-coordination-provider-3I7XWZZK.js.map → store-coordination-provider-KTRIC6PR.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/with-commit/sequence/strategy.ts","../src/with-commit/sequence/index.ts","../src/with-commit/sequence/active.ts"],"sourcesContent":["/**\n * Sequence capability strategy — the single on-demand factory the vault routes\n * `vault.sequence()` through to build its atomic-CAS {@link SequenceStore}. The\n * active engine ({@link withSequence}) constructs the real store (kept out of\n * the floor bundle — the store class is reached only via the opt-in\n * `active.ts` chunk); {@link NO_SEQUENCE} throws. The vault always assembles the\n * per-call {@link SequenceStoreOptions} and delegates here, so an un-opted-in\n * caller hits `NO_SEQUENCE`'s throw at `vault.sequence()`.\n *\n * Note: `vault.sequence()` is synchronous, so the factory is a plain (sync)\n * constructor — the engine is tree-shaken by reachability (only `withSequence()`\n * pulls `active.ts`, which statically imports the store), not by a dynamic\n * import. Deferred-numbering series (`withDeferredNumbering`) are a distinct\n * capability and are NOT routed through this strategy.\n * @internal\n */\nimport type { SequenceStore, SequenceStoreOptions } from './index.js'\nimport { SequenceNotEnabledError } from '../../kernel/errors.js'\n\nexport interface SequenceStrategy {\n createStore(opts: SequenceStoreOptions): SequenceStore\n}\n\n/**\n * No-op stub — the floor default. The capability factory throws\n * {@link SequenceNotEnabledError}; opt in with `sequenceStrategy: withSequence()`\n * in createNoydb. @internal\n */\nexport const NO_SEQUENCE: SequenceStrategy = {\n createStore(): SequenceStore {\n throw new SequenceNotEnabledError()\n },\n}\n","/**\n * Atomic sequence primitive — online-coordinated gap-free numbering.\n *\n * `vault.sequence('invoice-2026').next()` returns 1, 2, 3, … with no\n * gaps and no duplicates, even under concurrent callers. Each named\n * sequence is an independent counter record at `_sequences/<name>`,\n * incremented with an optimistic compare-and-swap retry loop — the same\n * proven pattern as the ledger head (`history/ledger/store.ts`).\n *\n * **Explicitly online-only.** Gap-free numbering requires single-authority\n * serialization, which an offline / non-CAS store cannot provide. `next()`\n * throws {@link SequenceOfflineError} unless the backing store advertises\n * `capabilities.casAtomic`. This is a deliberate, honest wall — an offline\n * writer cannot safely allocate a global sequence number.\n *\n * Note on \"gap-free\": the *sequence* is gap-free (each `next()` yields a\n * unique, +1 value). If a caller discards a value without using it, that\n * is a gap in *usage*, not in the sequence — assign each `next()` result\n * to its record in the same operation.\n */\n\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport { NOYDB_FORMAT_VERSION } from '../../kernel/types.js'\nimport { encrypt, openEnvelopeJson, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport { ConflictError, SequenceContentionError, SequenceOfflineError, ValidationError } from '../../kernel/errors.js'\n\n// Capability opt-in seam (S4): `vault.sequence()` builds its CAS store through\n// the sequenceStrategy, so it throws SequenceNotEnabledError unless opted in.\nexport { withSequence } from './active.js'\nexport { NO_SEQUENCE, type SequenceStrategy } from './strategy.js'\nexport { SequenceNotEnabledError } from '../../kernel/errors.js'\n\nexport const SEQUENCE_COLLECTION = '_sequences'\n// A sequence is a single hot CAS row — higher contention than a ledger\n// append. A larger budget + jittered backoff absorbs moderate concurrency;\n// a genuine burst beyond this surfaces SequenceContentionError so the\n// caller can retry / queue (the honest online-only contract).\nconst MAX_NEXT_ATTEMPTS = 16\n\ninterface SequenceState {\n value: number\n}\n\n/** Options for `SequenceHandle.next`. Deferred-numbering series use `for`; the CAS counter ignores all of these. */\nexport interface NextOptions {\n /** Deferred mode: the record id to number. Ignored by the CAS counter. */\n readonly for?: string\n /** Deferred mode: reject after this many ms if still unsealed (reserved; not yet enforced in this slice). */\n readonly timeoutMs?: number\n}\n\n/**\n * Partitioning for a CAS sequence. A partitioned sequence is an\n * independent counter scoped to one tuple of values — e.g.\n * `sequence('invoice', { partition: [2026, 'EU'] })` numbers EU-2026 invoices\n * separately from `[2026, 'US']` and from the bare `invoice` series.\n *\n * Partition components are URI-encoded (so `/`, null bytes and other\n * separators in a value can never collide with the structural separators) and\n * `'/'`-joined, then appended to the series with a null-byte (`\\x00`)\n * separator. The null byte is illegal in a plain series name, which guarantees\n * a partitioned key is always disjoint from any unpartitioned series.\n */\nexport interface SequenceOptions {\n /** Partition tuple. Each component is URI-encoded and `'/'`-joined. */\n readonly partition?: readonly (string | number)[]\n /**\n * Render template for the serial string. When set, `vault.sequence`\n * returns a {@link FormattedSequenceHandle} whose `next()` resolves to\n * `{ serial, formatted }`. Tokens:\n * - `{seq}` — the allocated integer\n * - `{seq:0N}` — zero-padded to width N (e.g. `{seq:04}` → `0001`)\n * - `{partition.i}` — the i-th `partition` component (original value)\n *\n * Any other token, or a `{partition.i}` index beyond the supplied\n * `partition`, throws `ValidationError` at `vault.sequence()` construction.\n * Per-partition reset is inherent: a new partition tuple starts at 1.\n */\n readonly format?: string\n}\n\n/**\n * A formatted sequence handle. Identical to {@link SequenceHandle}\n * except `next()` also returns the rendered `formatted` string. `peek()` /\n * `seedTo()` operate on the underlying integer counter, unchanged.\n */\nexport interface FormattedSequenceHandle {\n /** Allocate the next value and return it with its rendered serial string. */\n next(opts?: NextOptions): Promise<{ serial: number; formatted: string }>\n /** Read the current integer value without allocating. Returns 0 if never used. */\n peek(): Promise<number>\n /** Set-if-greater on the underlying integer counter. See {@link SequenceHandle.seedTo}. */\n seedTo(n: number): Promise<void>\n}\n\n// Matches a single `{...}` token with no nested braces.\nconst SEQ_FORMAT_TOKEN = /\\{([^{}]*)\\}/g\nconst SEQ_PAD_TOKEN = /^seq:0(\\d+)$/\nconst SEQ_PARTITION_TOKEN = /^partition\\.(\\d+)$/\n\n/**\n * Validate a sequence `format` against the supplied partition and return a\n * pure `(serial) => string` renderer. Eager validation: every token is\n * checked now, so a bad pattern throws `ValidationError` at construction —\n * never at `next()` time.\n */\nexport function compileSequenceFormat(\n format: string,\n series: string,\n partition: readonly (string | number)[] | undefined,\n): (serial: number) => string {\n const parts = partition ?? []\n for (const m of format.matchAll(SEQ_FORMAT_TOKEN)) {\n const token = m[1] ?? ''\n if (token === 'seq') continue\n if (SEQ_PAD_TOKEN.test(token)) continue\n const partMatch = SEQ_PARTITION_TOKEN.exec(token)\n if (partMatch) {\n const idx = Number(partMatch[1])\n if (idx >= parts.length) {\n throw new ValidationError(\n `sequence(\"${series}\"): format token \"{${token}}\" references partition index ${idx}, ` +\n `but only ${parts.length} partition component(s) were supplied.`,\n )\n }\n continue\n }\n throw new ValidationError(\n `sequence(\"${series}\"): format contains unknown token \"{${token}}\". ` +\n `Accepted tokens: {seq}, {seq:0N}, {partition.i}.`,\n )\n }\n return (serial: number): string =>\n format.replace(SEQ_FORMAT_TOKEN, (full, token: string) => {\n if (token === 'seq') return String(serial)\n const padMatch = SEQ_PAD_TOKEN.exec(token)\n if (padMatch) return String(serial).padStart(Number(padMatch[1]), '0')\n const partMatch = SEQ_PARTITION_TOKEN.exec(token)\n if (partMatch) return String(parts[Number(partMatch[1])])\n return full // unreachable — validated above\n })\n}\n\n/**\n * Resolve the CAS storage key for a (series, partition) pair.\n *\n * With no partition the key is `series` verbatim. With a partition the key is\n * `${series}\\x00${parts}` where `parts` is each component passed through\n * `encodeURIComponent(String(part))` and `'/'`-joined. The null-byte separator\n * is illegal in a plain series name, so partitioned keys never collide with\n * unpartitioned ones; URI-encoding keeps any component containing `/` distinct\n * from a multi-component partition.\n *\n * @throws {ValidationError} if any partition component is empty after `String()`\n * or is a non-finite number (`NaN`, `±Infinity`).\n */\nexport function resolveSequenceKey(series: string, opts?: SequenceOptions): string {\n const partition = opts?.partition\n if (!partition || partition.length === 0) return series\n const parts = partition.map((p) => {\n if (typeof p === 'number' && !Number.isFinite(p)) {\n throw new ValidationError(`sequence partition component must be a finite number, got ${p}`)\n }\n const s = String(p)\n if (s === '') {\n throw new ValidationError('sequence partition component must not be empty')\n }\n return encodeURIComponent(s)\n })\n return `${series}\\x00${parts.join('/')}`\n}\n\nexport interface SequenceHandle {\n /** Atomically allocate and return the next value (1, 2, 3, …). Deferred series resolve at the next pass. */\n next(opts?: NextOptions): Promise<number>\n /** Read the current value without allocating. Returns 0 if never used. */\n peek(): Promise<number>\n /**\n * Set-if-greater: advance the counter to at least `n`. A no-op if the\n * current value is already `>= n` (so it never rewinds), and `seedTo(0)` is\n * a no-op. Idempotent and CAS-safe under concurrent `next()` / `seedTo()`.\n *\n * Use after a bundle / CSV import to fast-forward the counter past the\n * highest imported serial, so subsequent `next()` calls cannot re-use a\n * number that is already on a record.\n *\n * Online-only: throws {@link SequenceOfflineError} on a non-CAS store.\n */\n seedTo(n: number): Promise<void>\n}\n\nasync function sleepBackoff(attempt: number): Promise<void> {\n // Exponential backoff with full jitter to break the thundering herd\n // when many writers contend on the same counter row.\n const ceil = Math.min(2 ** attempt, 32)\n const ms = Math.floor(Math.random() * ceil)\n await new Promise((r) => setTimeout(r, ms))\n}\n\n/** Per-call context the vault assembles to build a {@link SequenceStore}. */\nexport interface SequenceStoreOptions {\n adapter: NoydbStore\n vault: string\n encrypted: boolean\n getDEK: (collectionName: string) => Promise<EnclaveKey>\n actor: string\n}\n\nexport class SequenceStore {\n private readonly adapter: NoydbStore\n private readonly vault: string\n private readonly encrypted: boolean\n private readonly getDEK: (collectionName: string) => Promise<EnclaveKey>\n private readonly actor: string\n /**\n * Memoized DEK promise. The `_sequences` collection DEK is created on\n * first access; without sharing one promise, a burst of concurrent\n * `next()` calls would each trigger DEK creation and diverge (one\n * writer's ciphertext unreadable by another). One shared promise → one\n * DEK.\n */\n private dekPromise: Promise<EnclaveKey> | null = null\n\n constructor(opts: SequenceStoreOptions) {\n this.adapter = opts.adapter\n this.vault = opts.vault\n this.encrypted = opts.encrypted\n this.getDEK = opts.getDEK\n this.actor = opts.actor\n }\n\n /** A handle bound to one sequence name. */\n handle(name: string): SequenceHandle {\n return {\n next: () => this.next(name),\n peek: () => this.peek(name),\n seedTo: (n) => this.seedTo(name, n),\n }\n }\n\n private assertOnline(): void {\n if (this.adapter.capabilities?.casAtomic !== true) {\n throw new SequenceOfflineError()\n }\n }\n\n private dek(): Promise<EnclaveKey> {\n if (!this.dekPromise) this.dekPromise = this.getDEK(SEQUENCE_COLLECTION)\n return this.dekPromise\n }\n\n private async read(name: string): Promise<{ env: EncryptedEnvelope | null; value: number }> {\n const env = await this.adapter.get(this.vault, SEQUENCE_COLLECTION, name)\n if (!env) return { env: null, value: 0 }\n const json = this.encrypted ? await openEnvelopeJson(env, await this.dek()) : env._data\n const state = JSON.parse(json) as SequenceState\n return { env, value: state.value }\n }\n\n private async encryptState(state: SequenceState, version: number): Promise<EncryptedEnvelope> {\n const json = JSON.stringify(state)\n if (!this.encrypted) {\n return { _noydb: NOYDB_FORMAT_VERSION, _v: version, _ts: new Date().toISOString(), _iv: '', _data: json, _by: this.actor }\n }\n const { iv, data } = await encrypt(json, await this.dek())\n return { _noydb: NOYDB_FORMAT_VERSION, _v: version, _ts: new Date().toISOString(), _iv: iv, _data: data, _by: this.actor }\n }\n\n async peek(name: string): Promise<number> {\n return (await this.read(name)).value\n }\n\n async next(name: string): Promise<number> {\n this.assertOnline()\n let lastConflict: ConflictError | undefined\n for (let attempt = 0; attempt < MAX_NEXT_ATTEMPTS; attempt++) {\n const { env, value } = await this.read(name)\n const nextValue = value + 1\n const expectedVersion = env?._v ?? 0 // 0 ≡ \"must not yet exist\" (create)\n const envelope = await this.encryptState({ value: nextValue }, expectedVersion + 1)\n try {\n await this.adapter.put(this.vault, SEQUENCE_COLLECTION, name, envelope, expectedVersion)\n return nextValue\n } catch (err) {\n if (err instanceof ConflictError) {\n lastConflict = err\n if (attempt < MAX_NEXT_ATTEMPTS - 1) await sleepBackoff(attempt)\n continue\n }\n throw err\n }\n }\n void lastConflict\n throw new SequenceContentionError(name, MAX_NEXT_ATTEMPTS)\n }\n\n async seedTo(name: string, n: number): Promise<void> {\n this.assertOnline()\n if (n <= 0) return // set-if-greater: 0 (and any non-positive seed) is a no-op\n let lastConflict: ConflictError | undefined\n for (let attempt = 0; attempt < MAX_NEXT_ATTEMPTS; attempt++) {\n const { env, value } = await this.read(name)\n if (value >= n) return // already at or past the floor — no write, idempotent\n const expectedVersion = env?._v ?? 0 // 0 ≡ \"must not yet exist\" (create)\n const envelope = await this.encryptState({ value: n }, expectedVersion + 1)\n try {\n await this.adapter.put(this.vault, SEQUENCE_COLLECTION, name, envelope, expectedVersion)\n return\n } catch (err) {\n if (err instanceof ConflictError) {\n lastConflict = err\n if (attempt < MAX_NEXT_ATTEMPTS - 1) await sleepBackoff(attempt)\n continue\n }\n throw err\n }\n }\n void lastConflict\n throw new SequenceContentionError(name, MAX_NEXT_ATTEMPTS)\n }\n}\n","/**\n * Enable the atomic-sequence capability.\n * Pass to `createNoydb({ sequenceStrategy: withSequence() })` to make\n * `vault.sequence('name').next()` / `.peek()` / `.seedTo()` live. The\n * {@link SequenceStore} CAS engine is statically imported here, so it is pulled\n * into the bundle only when `withSequence()` is referenced (the floor never\n * imports it).\n */\nimport type { SequenceStrategy } from './strategy.js'\nimport { SequenceStore } from './index.js'\n\nexport function withSequence(): SequenceStrategy {\n return {\n createStore(opts) {\n return new SequenceStore(opts)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4BO,IAAM,cAAgC;AAAA,EAC3C,cAA6B;AAC3B,UAAM,IAAI,wBAAwB;AAAA,EACpC;AACF;;;ACAO,IAAM,sBAAsB;AAKnC,IAAM,oBAAoB;AA2D1B,IAAM,mBAAmB;AACzB,IAAM,gBAAgB;AACtB,IAAM,sBAAsB;AAQrB,SAAS,sBACd,QACA,QACA,WAC4B;AAC5B,QAAM,QAAQ,aAAa,CAAC;AAC5B,aAAW,KAAK,OAAO,SAAS,gBAAgB,GAAG;AACjD,UAAM,QAAQ,EAAE,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;AAAA,EAEA,MAAM,OAAO,MAAc,GAA0B;AACnD,SAAK,aAAa;AAClB,QAAI,KAAK,EAAG;AACZ,QAAI;AACJ,aAAS,UAAU,GAAG,UAAU,mBAAmB,WAAW;AAC5D,YAAM,EAAE,KAAK,MAAM,IAAI,MAAM,KAAK,KAAK,IAAI;AAC3C,UAAI,SAAS,EAAG;AAChB,YAAM,kBAAkB,KAAK,MAAM;AACnC,YAAM,WAAW,MAAM,KAAK,aAAa,EAAE,OAAO,EAAE,GAAG,kBAAkB,CAAC;AAC1E,UAAI;AACF,cAAM,KAAK,QAAQ,IAAI,KAAK,OAAO,qBAAqB,MAAM,UAAU,eAAe;AACvF;AAAA,MACF,SAAS,KAAK;AACZ,YAAI,eAAe,eAAe;AAChC,yBAAe;AACf,cAAI,UAAU,oBAAoB,EAAG,OAAM,aAAa,OAAO;AAC/D;AAAA,QACF;AACA,cAAM;AAAA,MACR;AAAA,IACF;AACA,SAAK;AACL,UAAM,IAAI,wBAAwB,MAAM,iBAAiB;AAAA,EAC3D;AACF;;;ACrTO,SAAS,eAAiC;AAC/C,SAAO;AAAA,IACL,YAAY,MAAM;AAChB,aAAO,IAAI,cAAc,IAAI;AAAA,IAC/B;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/with-commit/sequence/strategy.ts","../src/with-commit/sequence/index.ts","../src/with-commit/sequence/active.ts"],"sourcesContent":["/**\n * Sequence capability strategy — the single on-demand factory the vault routes\n * `vault.sequence()` through to build its atomic-CAS {@link SequenceStore}. The\n * active engine ({@link withSequence}) constructs the real store (kept out of\n * the floor bundle — the store class is reached only via the opt-in\n * `active.ts` chunk); {@link NO_SEQUENCE} throws. The vault always assembles the\n * per-call {@link SequenceStoreOptions} and delegates here, so an un-opted-in\n * caller hits `NO_SEQUENCE`'s throw at `vault.sequence()`.\n *\n * Note: `vault.sequence()` is synchronous, so the factory is a plain (sync)\n * constructor — the engine is tree-shaken by reachability (only `withSequence()`\n * pulls `active.ts`, which statically imports the store), not by a dynamic\n * import. Deferred-numbering series (`withDeferredNumbering`) are a distinct\n * capability and are NOT routed through this strategy.\n * @internal\n */\nimport type { SequenceStore, SequenceStoreOptions } from './index.js'\nimport { SequenceNotEnabledError } from '../../kernel/errors.js'\n\nexport interface SequenceStrategy {\n createStore(opts: SequenceStoreOptions): SequenceStore\n}\n\n/**\n * No-op stub — the floor default. The capability factory throws\n * {@link SequenceNotEnabledError}; opt in with `sequenceStrategy: withSequence()`\n * in createNoydb. @internal\n */\nexport const NO_SEQUENCE: SequenceStrategy = {\n createStore(): SequenceStore {\n throw new SequenceNotEnabledError()\n },\n}\n","/**\n * Atomic sequence primitive — online-coordinated gap-free numbering.\n *\n * `vault.sequence('invoice-2026').next()` returns 1, 2, 3, … with no\n * gaps and no duplicates, even under concurrent callers. Each named\n * sequence is an independent counter record at `_sequences/<name>`,\n * incremented with an optimistic compare-and-swap retry loop — the same\n * proven pattern as the ledger head (`history/ledger/store.ts`).\n *\n * **Explicitly online-only.** Gap-free numbering requires single-authority\n * serialization, which an offline / non-CAS store cannot provide. `next()`\n * throws {@link SequenceOfflineError} unless the backing store advertises\n * `capabilities.casAtomic`. This is a deliberate, honest wall — an offline\n * writer cannot safely allocate a global sequence number.\n *\n * Note on \"gap-free\": the *sequence* is gap-free (each `next()` yields a\n * unique, +1 value). If a caller discards a value without using it, that\n * is a gap in *usage*, not in the sequence — assign each `next()` result\n * to its record in the same operation.\n */\n\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport { NOYDB_FORMAT_VERSION } from '../../kernel/types.js'\nimport { encrypt, openEnvelopeJson, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport { ConflictError, SequenceContentionError, SequenceOfflineError, ValidationError } from '../../kernel/errors.js'\n\n// Capability opt-in seam (S4): `vault.sequence()` builds its CAS store through\n// the sequenceStrategy, so it throws SequenceNotEnabledError unless opted in.\nexport { withSequence } from './active.js'\nexport { NO_SEQUENCE, type SequenceStrategy } from './strategy.js'\nexport { SequenceNotEnabledError } from '../../kernel/errors.js'\n\nexport const SEQUENCE_COLLECTION = '_sequences'\n// A sequence is a single hot CAS row — higher contention than a ledger\n// append. A larger budget + jittered backoff absorbs moderate concurrency;\n// a genuine burst beyond this surfaces SequenceContentionError so the\n// caller can retry / queue (the honest online-only contract).\nconst MAX_NEXT_ATTEMPTS = 16\n\ninterface SequenceState {\n value: number\n}\n\n/** Options for `SequenceHandle.next`. Deferred-numbering series use `for`; the CAS counter ignores all of these. */\nexport interface NextOptions {\n /** Deferred mode: the record id to number. Ignored by the CAS counter. */\n readonly for?: string\n /** Deferred mode: reject after this many ms if still unsealed (reserved; not yet enforced in this slice). */\n readonly timeoutMs?: number\n}\n\n/**\n * Partitioning for a CAS sequence. A partitioned sequence is an\n * independent counter scoped to one tuple of values — e.g.\n * `sequence('invoice', { partition: [2026, 'EU'] })` numbers EU-2026 invoices\n * separately from `[2026, 'US']` and from the bare `invoice` series.\n *\n * Partition components are URI-encoded (so `/`, null bytes and other\n * separators in a value can never collide with the structural separators) and\n * `'/'`-joined, then appended to the series with a null-byte (`\\x00`)\n * separator. The null byte is illegal in a plain series name, which guarantees\n * a partitioned key is always disjoint from any unpartitioned series.\n */\nexport interface SequenceOptions {\n /** Partition tuple. Each component is URI-encoded and `'/'`-joined. */\n readonly partition?: readonly (string | number)[]\n /**\n * Render template for the serial string. When set, `vault.sequence`\n * returns a {@link FormattedSequenceHandle} whose `next()` resolves to\n * `{ serial, formatted }`. Tokens:\n * - `{seq}` — the allocated integer\n * - `{seq:0N}` — zero-padded to width N (e.g. `{seq:04}` → `0001`)\n * - `{partition.i}` — the i-th `partition` component (original value)\n *\n * Any other token, or a `{partition.i}` index beyond the supplied\n * `partition`, throws `ValidationError` at `vault.sequence()` construction.\n * Per-partition reset is inherent: a new partition tuple starts at 1.\n */\n readonly format?: string\n}\n\n/**\n * A formatted sequence handle. Identical to {@link SequenceHandle}\n * except `next()` also returns the rendered `formatted` string. `peek()` /\n * `seedTo()` operate on the underlying integer counter, unchanged.\n */\nexport interface FormattedSequenceHandle {\n /** Allocate the next value and return it with its rendered serial string. */\n next(opts?: NextOptions): Promise<{ serial: number; formatted: string }>\n /** Read the current integer value without allocating. Returns 0 if never used. */\n peek(): Promise<number>\n /** Set-if-greater on the underlying integer counter. See {@link SequenceHandle.seedTo}. */\n seedTo(n: number): Promise<void>\n}\n\n// Matches a single `{...}` token with no nested braces.\nconst SEQ_FORMAT_TOKEN = /\\{([^{}]*)\\}/g\nconst SEQ_PAD_TOKEN = /^seq:0(\\d+)$/\nconst SEQ_PARTITION_TOKEN = /^partition\\.(\\d+)$/\n\n/**\n * Validate a sequence `format` against the supplied partition and return a\n * pure `(serial) => string` renderer. Eager validation: every token is\n * checked now, so a bad pattern throws `ValidationError` at construction —\n * never at `next()` time.\n */\nexport function compileSequenceFormat(\n format: string,\n series: string,\n partition: readonly (string | number)[] | undefined,\n): (serial: number) => string {\n const parts = partition ?? []\n for (const m of format.matchAll(SEQ_FORMAT_TOKEN)) {\n const token = m[1] ?? ''\n if (token === 'seq') continue\n if (SEQ_PAD_TOKEN.test(token)) continue\n const partMatch = SEQ_PARTITION_TOKEN.exec(token)\n if (partMatch) {\n const idx = Number(partMatch[1])\n if (idx >= parts.length) {\n throw new ValidationError(\n `sequence(\"${series}\"): format token \"{${token}}\" references partition index ${idx}, ` +\n `but only ${parts.length} partition component(s) were supplied.`,\n )\n }\n continue\n }\n throw new ValidationError(\n `sequence(\"${series}\"): format contains unknown token \"{${token}}\". ` +\n `Accepted tokens: {seq}, {seq:0N}, {partition.i}.`,\n )\n }\n return (serial: number): string =>\n format.replace(SEQ_FORMAT_TOKEN, (full, token: string) => {\n if (token === 'seq') return String(serial)\n const padMatch = SEQ_PAD_TOKEN.exec(token)\n if (padMatch) return String(serial).padStart(Number(padMatch[1]), '0')\n const partMatch = SEQ_PARTITION_TOKEN.exec(token)\n if (partMatch) return String(parts[Number(partMatch[1])])\n return full // unreachable — validated above\n })\n}\n\n/**\n * Resolve the CAS storage key for a (series, partition) pair.\n *\n * With no partition the key is `series` verbatim. With a partition the key is\n * `${series}\\x00${parts}` where `parts` is each component passed through\n * `encodeURIComponent(String(part))` and `'/'`-joined. The null-byte separator\n * is illegal in a plain series name, so partitioned keys never collide with\n * unpartitioned ones; URI-encoding keeps any component containing `/` distinct\n * from a multi-component partition.\n *\n * @throws {ValidationError} if any partition component is empty after `String()`\n * or is a non-finite number (`NaN`, `±Infinity`).\n */\nexport function resolveSequenceKey(series: string, opts?: SequenceOptions): string {\n const partition = opts?.partition\n if (!partition || partition.length === 0) return series\n const parts = partition.map((p) => {\n if (typeof p === 'number' && !Number.isFinite(p)) {\n throw new ValidationError(`sequence partition component must be a finite number, got ${p}`)\n }\n const s = String(p)\n if (s === '') {\n throw new ValidationError('sequence partition component must not be empty')\n }\n return encodeURIComponent(s)\n })\n return `${series}\\x00${parts.join('/')}`\n}\n\nexport interface SequenceHandle {\n /** Atomically allocate and return the next value (1, 2, 3, …). Deferred series resolve at the next pass. */\n next(opts?: NextOptions): Promise<number>\n /** Read the current value without allocating. Returns 0 if never used. */\n peek(): Promise<number>\n /**\n * Set-if-greater: advance the counter to at least `n`. A no-op if the\n * current value is already `>= n` (so it never rewinds), and `seedTo(0)` is\n * a no-op. Idempotent and CAS-safe under concurrent `next()` / `seedTo()`.\n *\n * Use after a bundle / CSV import to fast-forward the counter past the\n * highest imported serial, so subsequent `next()` calls cannot re-use a\n * number that is already on a record.\n *\n * Online-only: throws {@link SequenceOfflineError} on a non-CAS store.\n */\n seedTo(n: number): Promise<void>\n}\n\nasync function sleepBackoff(attempt: number): Promise<void> {\n // Exponential backoff with full jitter to break the thundering herd\n // when many writers contend on the same counter row.\n const ceil = Math.min(2 ** attempt, 32)\n const ms = Math.floor(Math.random() * ceil)\n await new Promise((r) => setTimeout(r, ms))\n}\n\n/** Per-call context the vault assembles to build a {@link SequenceStore}. */\nexport interface SequenceStoreOptions {\n adapter: NoydbStore\n vault: string\n encrypted: boolean\n getDEK: (collectionName: string) => Promise<EnclaveKey>\n actor: string\n}\n\nexport class SequenceStore {\n private readonly adapter: NoydbStore\n private readonly vault: string\n private readonly encrypted: boolean\n private readonly getDEK: (collectionName: string) => Promise<EnclaveKey>\n private readonly actor: string\n /**\n * Memoized DEK promise. The `_sequences` collection DEK is created on\n * first access; without sharing one promise, a burst of concurrent\n * `next()` calls would each trigger DEK creation and diverge (one\n * writer's ciphertext unreadable by another). One shared promise → one\n * DEK.\n */\n private dekPromise: Promise<EnclaveKey> | null = null\n\n constructor(opts: SequenceStoreOptions) {\n this.adapter = opts.adapter\n this.vault = opts.vault\n this.encrypted = opts.encrypted\n this.getDEK = opts.getDEK\n this.actor = opts.actor\n }\n\n /** A handle bound to one sequence name. */\n handle(name: string): SequenceHandle {\n return {\n next: () => this.next(name),\n peek: () => this.peek(name),\n seedTo: (n) => this.seedTo(name, n),\n }\n }\n\n private assertOnline(): void {\n if (this.adapter.capabilities?.casAtomic !== true) {\n throw new SequenceOfflineError()\n }\n }\n\n private dek(): Promise<EnclaveKey> {\n if (!this.dekPromise) this.dekPromise = this.getDEK(SEQUENCE_COLLECTION)\n return this.dekPromise\n }\n\n private async read(name: string): Promise<{ env: EncryptedEnvelope | null; value: number }> {\n const env = await this.adapter.get(this.vault, SEQUENCE_COLLECTION, name)\n if (!env) return { env: null, value: 0 }\n const json = this.encrypted ? await openEnvelopeJson(env, await this.dek()) : env._data\n const state = JSON.parse(json) as SequenceState\n return { env, value: state.value }\n }\n\n private async encryptState(state: SequenceState, version: number): Promise<EncryptedEnvelope> {\n const json = JSON.stringify(state)\n if (!this.encrypted) {\n return { _noydb: NOYDB_FORMAT_VERSION, _v: version, _ts: new Date().toISOString(), _iv: '', _data: json, _by: this.actor }\n }\n const { iv, data } = await encrypt(json, await this.dek())\n return { _noydb: NOYDB_FORMAT_VERSION, _v: version, _ts: new Date().toISOString(), _iv: iv, _data: data, _by: this.actor }\n }\n\n async peek(name: string): Promise<number> {\n return (await this.read(name)).value\n }\n\n async next(name: string): Promise<number> {\n this.assertOnline()\n let lastConflict: ConflictError | undefined\n for (let attempt = 0; attempt < MAX_NEXT_ATTEMPTS; attempt++) {\n const { env, value } = await this.read(name)\n const nextValue = value + 1\n const expectedVersion = env?._v ?? 0 // 0 ≡ \"must not yet exist\" (create)\n const envelope = await this.encryptState({ value: nextValue }, expectedVersion + 1)\n try {\n await this.adapter.put(this.vault, SEQUENCE_COLLECTION, name, envelope, expectedVersion)\n return nextValue\n } catch (err) {\n if (err instanceof ConflictError) {\n lastConflict = err\n if (attempt < MAX_NEXT_ATTEMPTS - 1) await sleepBackoff(attempt)\n continue\n }\n throw err\n }\n }\n void lastConflict\n throw new SequenceContentionError(name, MAX_NEXT_ATTEMPTS)\n }\n\n async seedTo(name: string, n: number): Promise<void> {\n this.assertOnline()\n if (n <= 0) return // set-if-greater: 0 (and any non-positive seed) is a no-op\n let lastConflict: ConflictError | undefined\n for (let attempt = 0; attempt < MAX_NEXT_ATTEMPTS; attempt++) {\n const { env, value } = await this.read(name)\n if (value >= n) return // already at or past the floor — no write, idempotent\n const expectedVersion = env?._v ?? 0 // 0 ≡ \"must not yet exist\" (create)\n const envelope = await this.encryptState({ value: n }, expectedVersion + 1)\n try {\n await this.adapter.put(this.vault, SEQUENCE_COLLECTION, name, envelope, expectedVersion)\n return\n } catch (err) {\n if (err instanceof ConflictError) {\n lastConflict = err\n if (attempt < MAX_NEXT_ATTEMPTS - 1) await sleepBackoff(attempt)\n continue\n }\n throw err\n }\n }\n void lastConflict\n throw new SequenceContentionError(name, MAX_NEXT_ATTEMPTS)\n }\n}\n","/**\n * Enable the atomic-sequence capability.\n * Pass to `createNoydb({ sequenceStrategy: withSequence() })` to make\n * `vault.sequence('name').next()` / `.peek()` / `.seedTo()` live. The\n * {@link SequenceStore} CAS engine is statically imported here, so it is pulled\n * into the bundle only when `withSequence()` is referenced (the floor never\n * imports it).\n */\nimport type { SequenceStrategy } from './strategy.js'\nimport { SequenceStore } from './index.js'\n\nexport function with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 openEnvelopeJson
3
+ } from "./chunk-5EZAJEES.js";
1
4
  import {
2
5
  encrypt,
3
6
  hmacSha256Hex,
4
- openEnvelopeJson,
5
7
  sha256Hex
6
- } from "./chunk-5O3AOPDT.js";
8
+ } from "./chunk-L4IRFTIF.js";
7
9
  import {
8
10
  NOYDB_FORMAT_VERSION
9
- } from "./chunk-5TDJ56JE.js";
11
+ } from "./chunk-OCDUQUAP.js";
10
12
 
11
13
  // src/with-audit/forget/strategy.ts
12
14
  var NO_FORGET = { subjects: {} };
@@ -145,4 +147,4 @@ export {
145
147
  coerceSubjectId,
146
148
  readDottedPath
147
149
  };
148
- //# sourceMappingURL=chunk-SRB2XEWB.js.map
150
+ //# sourceMappingURL=chunk-6OQ7NKMZ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/with-audit/forget/strategy.ts","../src/with-audit/forget/subject-index.ts"],"sourcesContent":["/**\n * `withForgetCascade` — 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 withForgetCascade}. 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 * withForgetCascade({ subjects: { invoices: 'buyerId', contacts: 'id' } })\n * ```\n */\nexport interface SubjectDeclaration {\n readonly subjects: Record<string, string>\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}\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 `withForgetCascade` 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 /** The single `op:'forget'` ledger entry appended for this erasure. */\n readonly ledgerEntry: LedgerEntry\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":";;;;;;;;;;;AAiDO,IAAM,YAA4B,EAA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AI,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 * `withForgetCascade` — 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 withForgetCascade}. 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 * withForgetCascade({ subjects: { invoices: 'buyerId', contacts: 'id' } })\n * ```\n */\nexport interface SubjectDeclaration {\n readonly subjects: Record<string, string>\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}\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 `withForgetCascade` 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 /** The single `op:'forget'` ledger entry appended for this erasure. */\n readonly ledgerEntry: LedgerEntry\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":";;;;;;;;;;;;;AAiDO,IAAM,YAA4B,EAAE,UAAU,CAAC,EAAE;;;ACVjD,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;AACv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{
7
+ if (!encrypted) return false;
8
+ return !envelope._data && envelope._cek === void 0;
9
+ }
10
+ function buildTombstone(version, actor) {
11
+ return {
12
+ _noydb: NOYDB_FORMAT_VERSION,
13
+ _v: version,
14
+ _ts: (/* @__PURE__ */ new Date()).toISOString(),
15
+ _iv: "",
16
+ _data: "",
17
+ ...actor ? { _by: actor } : {}
18
+ };
19
+ }
20
+
21
+ export {
22
+ isTombstone,
23
+ buildTombstone
24
+ };
25
+ //# sourceMappingURL=chunk-6RASM2J4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/kernel/enclave/record-keys/tombstone.ts"],"sourcesContent":["/**\n * Tombstone shape + predicate for the per-record-key (CEK) layer.\n *\n * A *tombstone* is the residue a GDPR crypto-shred (`vault.forget()`)\n * leaves on disk: the live envelope rewritten to `{ _noydb, _v, _ts, _by,\n * _iv:'', _data:'' }`, dropping `_iv`/`_data`/`_cek`/`_det`. With the wrapped\n * per-record CEK gone, the body — and every history version under the same\n * CEK — is permanently undecryptable, while the record KEY survives so the\n * version counter and \"record existed and was erased\" persist for the audit\n * ledger.\n *\n * These two helpers are the pure, collection-independent core of that\n * contract: {@link buildTombstone} mints the shape, {@link isTombstone}\n * recognises it on the read path. The orchestration that *writes* a tombstone\n * (`_writeTombstone`) and drives `vault.forget()` lives with the collection /\n * vault; it calls into these.\n */\nimport { NOYDB_FORMAT_VERSION, type EncryptedEnvelope } from '../../types.js'\n\n/**\n * Is this envelope a crypto-shred tombstone?\n *\n * A tombstone carries no body (`_data` empty) and no wrapped CEK (`_cek`\n * absent) — decrypting it would call `decrypt('', '', dek)` → an AES-GCM\n * throw, so every read choke point must short-circuit to `null` instead.\n *\n * `encrypted` is the collection's encryption flag: on an unencrypted\n * collection there are no envelopes to shred, so nothing is ever a tombstone.\n * (Legacy migration envelopes carry non-empty `_iv`/`_data`, so they are not\n * tombstones and stay readable.)\n */\nexport function isTombstone(envelope: EncryptedEnvelope, encrypted: boolean): boolean {\n if (!encrypted) return false\n return !envelope._data && envelope._cek === undefined\n}\n\n/**\n * Mint a tombstone envelope from a record's live version + actor.\n *\n * Keeps `_v` (the displaced version) so the counter is monotonic across the\n * shred, stamps a fresh `_ts`, and records `_by` when an actor is supplied.\n * Deliberately omits `_iv`/`_data`/`_cek`/`_det` — that omission *is* the\n * erasure.\n */\nexport function buildTombstone(version: number, actor: string): EncryptedEnvelope {\n return {\n _noydb: NOYDB_FORMAT_VERSION,\n _v: version,\n _ts: new Date().toISOString(),\n _iv: '',\n _data: '',\n ...(actor ? { _by: actor } : {}),\n }\n}\n"],"mappings":";;;;;AA+BO,SAAS,YAAY,UAA6B,WAA6B;AACpF,MAAI,CAAC,UAAW,QAAO;AACvB,SAAO,CAAC,SAAS,SAAS,SAAS,SAAS;AAC9C;AAUO,SAAS,eAAe,SAAiB,OAAkC;AAChF,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,IAAI;AAAA,IACJ,MAAK,oBAAI,KAAK,GAAE,YAAY;AAAA,IAC5B,KAAK;AAAA,IACL,OAAO;AAAA,IACP,GAAI,QAAQ,EAAE,KAAK,MAAM,IAAI,CAAC;AAAA,EAChC;AACF;","names":[]}
@@ -2,7 +2,7 @@ import {
2
2
  LocaleNotSpecifiedError,
3
3
  MissingTranslationError,
4
4
  ScriptViolationError
5
- } from "./chunk-ZYUC53LT.js";
5
+ } from "./chunk-BLZRNHMG.js";
6
6
 
7
7
  // src/with-shape/i18n/policy.ts
8
8
  function resolvePolicy(onMissing, layer) {
@@ -377,4 +377,4 @@ export {
377
377
  applyI18nLocale,
378
378
  stripI18nFilled
379
379
  };
380
- //# sourceMappingURL=chunk-5LUY7UTV.js.map
380
+ //# sourceMappingURL=chunk-7IP75FP2.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  writePod
3
- } from "./chunk-FISN7WE4.js";
3
+ } from "./chunk-3UDPDRUC.js";
4
4
 
5
5
  // src/with-audit/portability/export-accessible.ts
6
6
  function resolveAccessibleCollections(keyring, scope, writableOnly = false) {
@@ -42,4 +42,4 @@ export {
42
42
  buildAccessibleBundle,
43
43
  exportAccessibleData
44
44
  };
45
- //# sourceMappingURL=chunk-HCIPRAGS.js.map
45
+ //# sourceMappingURL=chunk-7MHVHGQZ.js.map