@noy-db/hub 0.2.0-pre.3 → 0.2.0-pre.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (384) hide show
  1. package/README.md +126 -0
  2. package/dist/adapter/index.d.ts +9 -0
  3. package/dist/adapter/index.js +14 -0
  4. package/dist/aggregate/index.d.ts +3 -2
  5. package/dist/aggregate/index.js +10 -8
  6. package/dist/aggregate/index.js.map +1 -1
  7. package/dist/attestation/index.d.ts +7 -5
  8. package/dist/attestation/index.js +7 -6
  9. package/dist/attestation/index.js.map +1 -1
  10. package/dist/blobs/index.d.ts +9 -7
  11. package/dist/blobs/index.js +12 -6
  12. package/dist/blobs/index.js.map +1 -1
  13. package/dist/bundle/index.d.ts +29 -18
  14. package/dist/bundle/index.js +53 -192
  15. package/dist/bundle/index.js.map +1 -1
  16. package/dist/{chunk-75QDHSE4.js → chunk-2QDWRK3B.js} +5 -5
  17. package/dist/{chunk-74JEQFMT.js → chunk-2UT7HJJR.js} +5 -5
  18. package/dist/chunk-2UT7HJJR.js.map +1 -0
  19. package/dist/{chunk-FCDO7UAO.js → chunk-2ZYIN3BL.js} +2 -2
  20. package/dist/{chunk-BFI3RS42.js → chunk-33EQCZXE.js} +2 -2
  21. package/dist/chunk-33EQCZXE.js.map +1 -0
  22. package/dist/{chunk-WRLHNG6H.js → chunk-4K4QKYK4.js} +4 -4
  23. package/dist/chunk-4K4QKYK4.js.map +1 -0
  24. package/dist/{chunk-HGZ7DC5H.js → chunk-4L6N56B4.js} +2 -2
  25. package/dist/chunk-4L6N56B4.js.map +1 -0
  26. package/dist/{chunk-YMYK7US4.js → chunk-4YD7VZH4.js} +2 -2
  27. package/dist/chunk-4YD7VZH4.js.map +1 -0
  28. package/dist/{chunk-ZUMGGHRB.js → chunk-5PTX7PKD.js} +4 -4
  29. package/dist/{chunk-QAU5HM6Q.js → chunk-6EKRQ7QF.js} +3 -3
  30. package/dist/{chunk-ZC2AAE6J.js → chunk-7GPQPLGO.js} +19 -4
  31. package/dist/chunk-7GPQPLGO.js.map +1 -0
  32. package/dist/{chunk-EPK6A3WJ.js → chunk-A3JMGXPG.js} +2 -2
  33. package/dist/chunk-A3JMGXPG.js.map +1 -0
  34. package/dist/{chunk-FXQYZNOW.js → chunk-A7DNZVAV.js} +1 -1
  35. package/dist/chunk-A7DNZVAV.js.map +1 -0
  36. package/dist/{chunk-UMLVJTYV.js → chunk-ADB7GPM3.js} +7 -4
  37. package/dist/chunk-ADB7GPM3.js.map +1 -0
  38. package/dist/{chunk-YL2DR3HY.js → chunk-ASIGWYRA.js} +2 -2
  39. package/dist/chunk-ASIGWYRA.js.map +1 -0
  40. package/dist/{chunk-2EYC3WDT.js → chunk-AWU4JF7C.js} +93 -93
  41. package/dist/chunk-AWU4JF7C.js.map +1 -0
  42. package/dist/chunk-BEZ2EV43.js +129 -0
  43. package/dist/chunk-BEZ2EV43.js.map +1 -0
  44. package/dist/{chunk-IS5HWQO7.js → chunk-CIZDUAHI.js} +30 -4
  45. package/dist/chunk-CIZDUAHI.js.map +1 -0
  46. package/dist/{chunk-4OQWR46B.js → chunk-CUPTCF4R.js} +5 -5
  47. package/dist/chunk-CUPTCF4R.js.map +1 -0
  48. package/dist/{chunk-5ZGZ6HIZ.js → chunk-DEE4CRYN.js} +30 -7
  49. package/dist/chunk-DEE4CRYN.js.map +1 -0
  50. package/dist/{chunk-UOF74WQY.js → chunk-E2MDPPOC.js} +37 -2
  51. package/dist/chunk-E2MDPPOC.js.map +1 -0
  52. package/dist/{chunk-SAVQ6E2O.js → chunk-FFKQ65YX.js} +10 -3
  53. package/dist/chunk-FFKQ65YX.js.map +1 -0
  54. package/dist/{chunk-2XLVPKXG.js → chunk-G7ALNCQH.js} +10 -2
  55. package/dist/chunk-G7ALNCQH.js.map +1 -0
  56. package/dist/chunk-GGXN73NM.js +252 -0
  57. package/dist/chunk-GGXN73NM.js.map +1 -0
  58. package/dist/{chunk-UVPGJXVO.js → chunk-JOJPBZSZ.js} +5 -5
  59. package/dist/{chunk-YDLAFP36.js → chunk-JZ5DS4DP.js} +346 -3
  60. package/dist/chunk-JZ5DS4DP.js.map +1 -0
  61. package/dist/{chunk-KMI2NBBF.js → chunk-K4JID2ZE.js} +44 -8
  62. package/dist/chunk-K4JID2ZE.js.map +1 -0
  63. package/dist/{aggregate/index.cjs → chunk-K6NVSHAH.js} +241 -210
  64. package/dist/chunk-K6NVSHAH.js.map +1 -0
  65. package/dist/chunk-KJ3K5VZM.js +524 -0
  66. package/dist/chunk-KJ3K5VZM.js.map +1 -0
  67. package/dist/chunk-L5HHBOMS.js +232 -0
  68. package/dist/chunk-L5HHBOMS.js.map +1 -0
  69. package/dist/{chunk-YK72A4IT.js → chunk-LBILABKZ.js} +4 -4
  70. package/dist/chunk-LXKBG52H.js +151 -0
  71. package/dist/chunk-LXKBG52H.js.map +1 -0
  72. package/dist/{chunk-NGSPBLLE.js → chunk-MPIZQGFA.js} +50 -20
  73. package/dist/chunk-MPIZQGFA.js.map +1 -0
  74. package/dist/{chunk-4X2S7PBF.js → chunk-MRJPSXPE.js} +84 -70
  75. package/dist/chunk-MRJPSXPE.js.map +1 -0
  76. package/dist/{chunk-6S3LLAQ5.js → chunk-MSMDDDDJ.js} +3 -3
  77. package/dist/{chunk-6S3LLAQ5.js.map → chunk-MSMDDDDJ.js.map} +1 -1
  78. package/dist/{chunk-GAUBWHAF.js → chunk-OCYFFBZS.js} +4 -4
  79. package/dist/{chunk-NCO2JGKK.js → chunk-PDVP3C2I.js} +1 -1
  80. package/dist/chunk-PDVP3C2I.js.map +1 -0
  81. package/dist/chunk-PZ5AY32C.js +10 -0
  82. package/dist/{chunk-P6256WTJ.js → chunk-QBLPY44S.js} +3 -3
  83. package/dist/chunk-QBLPY44S.js.map +1 -0
  84. package/dist/{query/index.cjs → chunk-QGBBQKDS.js} +706 -831
  85. package/dist/chunk-QGBBQKDS.js.map +1 -0
  86. package/dist/{chunk-FS7A4XNF.js → chunk-QWJCNXH2.js} +3 -3
  87. package/dist/chunk-QXWJQ7UU.js +380 -0
  88. package/dist/chunk-QXWJQ7UU.js.map +1 -0
  89. package/dist/{chunk-GDTCGIPX.js → chunk-RCB6GWTC.js} +27 -5
  90. package/dist/chunk-RCB6GWTC.js.map +1 -0
  91. package/dist/{chunk-K5PVGKE4.js → chunk-SAAJYSVV.js} +2 -2
  92. package/dist/{chunk-G7PAZ3TD.js → chunk-SHJ3BRTZ.js} +46 -10
  93. package/dist/chunk-SHJ3BRTZ.js.map +1 -0
  94. package/dist/chunk-SQXTKZL7.js +125 -0
  95. package/dist/chunk-SQXTKZL7.js.map +1 -0
  96. package/dist/chunk-STNPB3UM.js +9 -0
  97. package/dist/chunk-STNPB3UM.js.map +1 -0
  98. package/dist/{chunk-NSLTPGEN.js → chunk-TMUMMAWV.js} +12 -2
  99. package/dist/{chunk-NSLTPGEN.js.map → chunk-TMUMMAWV.js.map} +1 -1
  100. package/dist/{chunk-LS3JLEIB.js → chunk-TZGWI5AX.js} +4 -4
  101. package/dist/{chunk-GD3BGKAR.js → chunk-UBF5JEOJ.js} +44 -5
  102. package/dist/chunk-UBF5JEOJ.js.map +1 -0
  103. package/dist/{chunk-T6HQMVML.js → chunk-W5NVNJDX.js} +5250 -801
  104. package/dist/chunk-W5NVNJDX.js.map +1 -0
  105. package/dist/chunk-XAYDHD2O.js +123 -0
  106. package/dist/chunk-XAYDHD2O.js.map +1 -0
  107. package/dist/{chunk-LOL725S4.js → chunk-XYW2CSCI.js} +31 -3
  108. package/dist/chunk-XYW2CSCI.js.map +1 -0
  109. package/dist/{chunk-TLFUDXVV.js → chunk-ZCMOS4H2.js} +31 -10
  110. package/dist/chunk-ZCMOS4H2.js.map +1 -0
  111. package/dist/{chunk-FBMXWVGP.js → chunk-ZK66B5EY.js} +450 -30
  112. package/dist/chunk-ZK66B5EY.js.map +1 -0
  113. package/dist/{chunk-GVXBHCZ2.js → chunk-ZPJSQPQH.js} +66 -7
  114. package/dist/chunk-ZPJSQPQH.js.map +1 -0
  115. package/dist/consent/index.d.ts +8 -6
  116. package/dist/consent/index.js +4 -3
  117. package/dist/consent/index.js.map +1 -1
  118. package/dist/crdt/index.js +1 -0
  119. package/dist/crdt/index.js.map +1 -1
  120. package/dist/{crypto-H2Y3DDFW.js → crypto-OSIV2IIW.js} +8 -3
  121. package/dist/{ulid-CiM2OAeM.d.ts → decrypt-partition-CXS5KopB.d.ts} +37 -82
  122. package/dist/{delegation-QSC7G5QC.js → delegation-BQTRJATI.js} +6 -5
  123. package/dist/derivations/index.d.ts +11 -9
  124. package/dist/derivations/index.js +9 -6
  125. package/dist/{dev-unlock-Cf2B7Kih.d.ts → dev-unlock-CnHTTVea.d.ts} +1 -1
  126. package/dist/discriminant-BN9REW3o.d.ts +60 -0
  127. package/dist/errors-BAWO5Z5a.d.ts +1500 -0
  128. package/dist/executor-KYSKFJ2R.js +9 -0
  129. package/dist/executor-M7W3NEKR.js +9 -0
  130. package/dist/executor-VDTDGWO6.js +13 -0
  131. package/dist/{fanout-sidecar-NRBWSLRK.js → fanout-sidecar-AZALISHB.js} +3 -2
  132. package/dist/fanout-sidecar-AZALISHB.js.map +1 -0
  133. package/dist/forget/index.d.ts +1 -0
  134. package/dist/forget/index.js +15 -0
  135. package/dist/guards/index.d.ts +16 -8
  136. package/dist/guards/index.js +12 -5
  137. package/dist/{hash-gVn_uKhp.d.ts → hash-oc5paYl0.d.ts} +1 -1
  138. package/dist/history/index.d.ts +9 -7
  139. package/dist/history/index.js +10 -7
  140. package/dist/history/index.js.map +1 -1
  141. package/dist/i18n/index.d.ts +8 -6
  142. package/dist/i18n/index.js +116 -15
  143. package/dist/i18n/index.js.map +1 -1
  144. package/dist/index-BMmajblo.d.ts +362 -0
  145. package/dist/index-BmhGztUi.d.ts +93 -0
  146. package/dist/{types-D9eB0Rvh.d.ts → index-DHn9lEP0.d.ts} +4305 -1523
  147. package/dist/{index-BF1B2HB9.d.ts → index-Ddm8D3Oo.d.ts} +186 -1151
  148. package/dist/index.d.ts +342 -70
  149. package/dist/index.js +420 -112
  150. package/dist/index.js.map +1 -1
  151. package/dist/indexing/index.d.ts +3 -3
  152. package/dist/indexing/index.js +5 -4
  153. package/dist/indexing/index.js.map +1 -1
  154. package/dist/issue-DPHRF2TI.js +13 -0
  155. package/dist/kernel/index.d.ts +11 -0
  156. package/dist/kernel/index.js +50 -0
  157. package/dist/{lazy-builder-Rpd-V3jP.d.ts → lazy-builder-ChSqcF5t.d.ts} +2 -2
  158. package/dist/{ledger-WOEJUYTP.js → ledger-CI7GSMLB.js} +7 -6
  159. package/dist/materialized-views/index.d.ts +23 -20
  160. package/dist/materialized-views/index.js +9 -7
  161. package/dist/mime-magic-JeLKHRng.d.ts +103 -0
  162. package/dist/noydb-NAU2DTFP.js +40 -0
  163. package/dist/overlay-views/index.d.ts +32 -12
  164. package/dist/overlay-views/index.js +7 -6
  165. package/dist/periods/index.d.ts +8 -6
  166. package/dist/periods/index.js +7 -6
  167. package/dist/{predicate-Dnu81tsS.d.cts → predicate-BmhBSPCH.d.ts} +87 -5
  168. package/dist/{public-envelope-OHQ5UZFM.js → public-envelope-MFMBFJLZ.js} +5 -4
  169. package/dist/query/index.d.ts +4 -3
  170. package/dist/query/index.js +14 -6
  171. package/dist/read-only-facade-3OQRZ3VS.js +8 -0
  172. package/dist/registry-IX5WKK4F.js +8 -0
  173. package/dist/registry-LMHO5265.js +11 -0
  174. package/dist/registry-TXCKWH26.js +9 -0
  175. package/dist/registry-VFEDQSYV.js +9 -0
  176. package/dist/revoke-5PUOZPJJ.js +18 -0
  177. package/dist/revoke-5PUOZPJJ.js.map +1 -0
  178. package/dist/sealed-record/index.d.ts +123 -0
  179. package/dist/sealed-record/index.js +43 -0
  180. package/dist/sealed-record/index.js.map +1 -0
  181. package/dist/session/index.d.ts +9 -7
  182. package/dist/session/index.js +4 -3
  183. package/dist/session/index.js.map +1 -1
  184. package/dist/shadow/index.d.ts +8 -6
  185. package/dist/shadow/index.js +3 -2
  186. package/dist/shadow/index.js.map +1 -1
  187. package/dist/{signer-M4K5HBLD.js → signer-UB5TQOZ6.js} +6 -5
  188. package/dist/signer-UB5TQOZ6.js.map +1 -0
  189. package/dist/snapshots/index.d.ts +30 -0
  190. package/dist/snapshots/index.js +153 -0
  191. package/dist/snapshots/index.js.map +1 -0
  192. package/dist/{stale-PAGCS4K5.js → stale-J3TUF5C5.js} +3 -2
  193. package/dist/stale-J3TUF5C5.js.map +1 -0
  194. package/dist/store/index.d.ts +15 -6
  195. package/dist/store/index.js +3 -2
  196. package/dist/{strategy-DSTrsZ8t.d.ts → strategy-8QGs5KQE.d.ts} +475 -7
  197. package/dist/sync/index.d.ts +7 -5
  198. package/dist/sync/index.js +5 -4
  199. package/dist/sync/index.js.map +1 -1
  200. package/dist/team/index.d.ts +8 -6
  201. package/dist/team/index.js +9 -8
  202. package/dist/transition-guard-Dy3NioQr.d.ts +165 -0
  203. package/dist/tx/index.d.ts +26 -8
  204. package/dist/tx/index.js +10 -5
  205. package/dist/tx/index.js.map +1 -1
  206. package/dist/ulid-DRH25k3y.d.ts +66 -0
  207. package/dist/{ulid-COREQ2RQ.js → ulid-KEPZMD2N.js} +2 -1
  208. package/dist/ulid-KEPZMD2N.js.map +1 -0
  209. package/dist/util/index.d.ts +2 -0
  210. package/dist/util/index.js +6 -1
  211. package/dist/util/index.js.map +1 -1
  212. package/dist/{with-materialized-view-qtoJ3xKJ.d.ts → with-materialized-view-DIVeez0W.d.ts} +2 -2
  213. package/dist/{with-overlayed-view-DFaRfgMr.d.ts → with-overlayed-view-DVZrc5Hb.d.ts} +2 -2
  214. package/dist/with-rollup-CbU-O4wP.d.ts +47 -0
  215. package/dist/zod-HAJM7LMS.js +14763 -0
  216. package/dist/zod-HAJM7LMS.js.map +1 -0
  217. package/package.json +73 -191
  218. package/dist/aggregate/index.cjs.map +0 -1
  219. package/dist/aggregate/index.d.cts +0 -38
  220. package/dist/attestation/index.cjs +0 -305
  221. package/dist/attestation/index.cjs.map +0 -1
  222. package/dist/attestation/index.d.cts +0 -52
  223. package/dist/blobs/index.cjs +0 -1480
  224. package/dist/blobs/index.cjs.map +0 -1
  225. package/dist/blobs/index.d.cts +0 -46
  226. package/dist/bundle/index.cjs +0 -18561
  227. package/dist/bundle/index.cjs.map +0 -1
  228. package/dist/bundle/index.d.cts +0 -176
  229. package/dist/chunk-2EYC3WDT.js.map +0 -1
  230. package/dist/chunk-2XLVPKXG.js.map +0 -1
  231. package/dist/chunk-4OQWR46B.js.map +0 -1
  232. package/dist/chunk-4UBOTYP5.js +0 -1367
  233. package/dist/chunk-4UBOTYP5.js.map +0 -1
  234. package/dist/chunk-4X2S7PBF.js.map +0 -1
  235. package/dist/chunk-5YHWBPOT.js +0 -19
  236. package/dist/chunk-5YHWBPOT.js.map +0 -1
  237. package/dist/chunk-5ZGZ6HIZ.js.map +0 -1
  238. package/dist/chunk-74JEQFMT.js.map +0 -1
  239. package/dist/chunk-A6SWRXUQ.js +0 -118
  240. package/dist/chunk-A6SWRXUQ.js.map +0 -1
  241. package/dist/chunk-BFI3RS42.js.map +0 -1
  242. package/dist/chunk-EMEX37ZN.js +0 -51
  243. package/dist/chunk-EMEX37ZN.js.map +0 -1
  244. package/dist/chunk-EPK6A3WJ.js.map +0 -1
  245. package/dist/chunk-FBMXWVGP.js.map +0 -1
  246. package/dist/chunk-FXQYZNOW.js.map +0 -1
  247. package/dist/chunk-G7PAZ3TD.js.map +0 -1
  248. package/dist/chunk-GD3BGKAR.js.map +0 -1
  249. package/dist/chunk-GDTCGIPX.js.map +0 -1
  250. package/dist/chunk-GVXBHCZ2.js.map +0 -1
  251. package/dist/chunk-HGZ7DC5H.js.map +0 -1
  252. package/dist/chunk-IS5HWQO7.js.map +0 -1
  253. package/dist/chunk-KMI2NBBF.js.map +0 -1
  254. package/dist/chunk-KYKMKLJ6.js +0 -340
  255. package/dist/chunk-KYKMKLJ6.js.map +0 -1
  256. package/dist/chunk-LOL725S4.js.map +0 -1
  257. package/dist/chunk-MRIBLZL3.js +0 -86
  258. package/dist/chunk-MRIBLZL3.js.map +0 -1
  259. package/dist/chunk-NCO2JGKK.js.map +0 -1
  260. package/dist/chunk-NGSPBLLE.js.map +0 -1
  261. package/dist/chunk-P6256WTJ.js.map +0 -1
  262. package/dist/chunk-SAVQ6E2O.js.map +0 -1
  263. package/dist/chunk-T6HQMVML.js.map +0 -1
  264. package/dist/chunk-TLFUDXVV.js.map +0 -1
  265. package/dist/chunk-UMLVJTYV.js.map +0 -1
  266. package/dist/chunk-UOF74WQY.js.map +0 -1
  267. package/dist/chunk-WRLHNG6H.js.map +0 -1
  268. package/dist/chunk-YDLAFP36.js.map +0 -1
  269. package/dist/chunk-YL2DR3HY.js.map +0 -1
  270. package/dist/chunk-YMYK7US4.js.map +0 -1
  271. package/dist/chunk-ZC2AAE6J.js.map +0 -1
  272. package/dist/consent/index.cjs +0 -204
  273. package/dist/consent/index.cjs.map +0 -1
  274. package/dist/consent/index.d.cts +0 -25
  275. package/dist/crdt/index.cjs +0 -152
  276. package/dist/crdt/index.cjs.map +0 -1
  277. package/dist/crdt/index.d.cts +0 -30
  278. package/dist/derivations/index.cjs +0 -351
  279. package/dist/derivations/index.cjs.map +0 -1
  280. package/dist/derivations/index.d.cts +0 -72
  281. package/dist/dev-unlock-De3mjQWv.d.cts +0 -263
  282. package/dist/executor-BZKFZVRC.js +0 -8
  283. package/dist/executor-GFZFDQXV.js +0 -8
  284. package/dist/executor-KT2IOZVP.js +0 -11
  285. package/dist/fanout-sidecar-NRBWSLRK.js.map +0 -1
  286. package/dist/guards/index.cjs +0 -322
  287. package/dist/guards/index.cjs.map +0 -1
  288. package/dist/guards/index.d.cts +0 -31
  289. package/dist/hash-vBCB0-Ps.d.cts +0 -63
  290. package/dist/history/index.cjs +0 -1222
  291. package/dist/history/index.cjs.map +0 -1
  292. package/dist/history/index.d.cts +0 -63
  293. package/dist/i18n/index.cjs +0 -840
  294. package/dist/i18n/index.cjs.map +0 -1
  295. package/dist/i18n/index.d.cts +0 -39
  296. package/dist/index-DVkvrgpm.d.cts +0 -2290
  297. package/dist/index.cjs +0 -23590
  298. package/dist/index.cjs.map +0 -1
  299. package/dist/index.d.cts +0 -778
  300. package/dist/indexing/index.cjs +0 -738
  301. package/dist/indexing/index.cjs.map +0 -1
  302. package/dist/indexing/index.d.cts +0 -36
  303. package/dist/issue-BAJ7ZB4S.js +0 -12
  304. package/dist/lazy-builder-C-rPfWG0.d.cts +0 -304
  305. package/dist/materialized-views/index.cjs +0 -837
  306. package/dist/materialized-views/index.cjs.map +0 -1
  307. package/dist/materialized-views/index.d.cts +0 -184
  308. package/dist/mime-magic-CBBSOkjm.d.cts +0 -50
  309. package/dist/mime-magic-CBBSOkjm.d.ts +0 -50
  310. package/dist/noydb-XNQSKXGO.js +0 -34
  311. package/dist/overlay-views/index.cjs +0 -359
  312. package/dist/overlay-views/index.cjs.map +0 -1
  313. package/dist/overlay-views/index.d.cts +0 -82
  314. package/dist/periods/index.cjs +0 -1041
  315. package/dist/periods/index.cjs.map +0 -1
  316. package/dist/periods/index.d.cts +0 -22
  317. package/dist/predicate-Dnu81tsS.d.ts +0 -185
  318. package/dist/query/index.cjs.map +0 -1
  319. package/dist/query/index.d.cts +0 -3
  320. package/dist/read-only-facade-ITU6L7BL.js +0 -7
  321. package/dist/registry-2IEARCGT.js +0 -7
  322. package/dist/registry-CDHASH73.js +0 -10
  323. package/dist/registry-EMGLZGR6.js +0 -8
  324. package/dist/registry-NQALYR77.js +0 -8
  325. package/dist/revoke-7JOVLZFD.js +0 -17
  326. package/dist/session/index.cjs +0 -495
  327. package/dist/session/index.cjs.map +0 -1
  328. package/dist/session/index.d.cts +0 -46
  329. package/dist/shadow/index.cjs +0 -133
  330. package/dist/shadow/index.cjs.map +0 -1
  331. package/dist/shadow/index.d.cts +0 -17
  332. package/dist/store/index.cjs +0 -1083
  333. package/dist/store/index.cjs.map +0 -1
  334. package/dist/store/index.d.cts +0 -492
  335. package/dist/strategy-BSxFXGzb.d.cts +0 -110
  336. package/dist/strategy-DSTrsZ8t.d.cts +0 -601
  337. package/dist/sync/index.cjs +0 -1062
  338. package/dist/sync/index.cjs.map +0 -1
  339. package/dist/sync/index.d.cts +0 -43
  340. package/dist/team/index.cjs +0 -2798
  341. package/dist/team/index.cjs.map +0 -1
  342. package/dist/team/index.d.cts +0 -118
  343. package/dist/tx/index.cjs +0 -544
  344. package/dist/tx/index.cjs.map +0 -1
  345. package/dist/tx/index.d.cts +0 -21
  346. package/dist/types-CSLcfytP.d.cts +0 -12493
  347. package/dist/ulid-CG2YvAbg.d.cts +0 -603
  348. package/dist/util/index.cjs +0 -230
  349. package/dist/util/index.cjs.map +0 -1
  350. package/dist/util/index.d.cts +0 -77
  351. package/dist/with-derivation-Bzpj6UTv.d.ts +0 -13
  352. package/dist/with-derivation-DWajFh4K.d.cts +0 -13
  353. package/dist/with-guard-DF_Ul3DT.d.cts +0 -18
  354. package/dist/with-guard-DR7U-l4v.d.ts +0 -18
  355. package/dist/with-materialized-view-_piodoIz.d.cts +0 -27
  356. package/dist/with-overlayed-view-DwzCKxn2.d.cts +0 -13
  357. /package/dist/{crypto-H2Y3DDFW.js.map → adapter/index.js.map} +0 -0
  358. /package/dist/{chunk-75QDHSE4.js.map → chunk-2QDWRK3B.js.map} +0 -0
  359. /package/dist/{chunk-FCDO7UAO.js.map → chunk-2ZYIN3BL.js.map} +0 -0
  360. /package/dist/{chunk-ZUMGGHRB.js.map → chunk-5PTX7PKD.js.map} +0 -0
  361. /package/dist/{chunk-QAU5HM6Q.js.map → chunk-6EKRQ7QF.js.map} +0 -0
  362. /package/dist/{chunk-UVPGJXVO.js.map → chunk-JOJPBZSZ.js.map} +0 -0
  363. /package/dist/{chunk-YK72A4IT.js.map → chunk-LBILABKZ.js.map} +0 -0
  364. /package/dist/{chunk-GAUBWHAF.js.map → chunk-OCYFFBZS.js.map} +0 -0
  365. /package/dist/{delegation-QSC7G5QC.js.map → chunk-PZ5AY32C.js.map} +0 -0
  366. /package/dist/{chunk-FS7A4XNF.js.map → chunk-QWJCNXH2.js.map} +0 -0
  367. /package/dist/{chunk-K5PVGKE4.js.map → chunk-SAAJYSVV.js.map} +0 -0
  368. /package/dist/{chunk-LS3JLEIB.js.map → chunk-TZGWI5AX.js.map} +0 -0
  369. /package/dist/{executor-BZKFZVRC.js.map → crypto-OSIV2IIW.js.map} +0 -0
  370. /package/dist/{executor-GFZFDQXV.js.map → delegation-BQTRJATI.js.map} +0 -0
  371. /package/dist/{executor-KT2IOZVP.js.map → executor-KYSKFJ2R.js.map} +0 -0
  372. /package/dist/{issue-BAJ7ZB4S.js.map → executor-M7W3NEKR.js.map} +0 -0
  373. /package/dist/{ledger-WOEJUYTP.js.map → executor-VDTDGWO6.js.map} +0 -0
  374. /package/dist/{noydb-XNQSKXGO.js.map → forget/index.js.map} +0 -0
  375. /package/dist/{public-envelope-OHQ5UZFM.js.map → issue-DPHRF2TI.js.map} +0 -0
  376. /package/dist/{read-only-facade-ITU6L7BL.js.map → kernel/index.js.map} +0 -0
  377. /package/dist/{registry-2IEARCGT.js.map → ledger-CI7GSMLB.js.map} +0 -0
  378. /package/dist/{registry-CDHASH73.js.map → noydb-NAU2DTFP.js.map} +0 -0
  379. /package/dist/{registry-EMGLZGR6.js.map → public-envelope-MFMBFJLZ.js.map} +0 -0
  380. /package/dist/{registry-NQALYR77.js.map → read-only-facade-3OQRZ3VS.js.map} +0 -0
  381. /package/dist/{revoke-7JOVLZFD.js.map → registry-IX5WKK4F.js.map} +0 -0
  382. /package/dist/{signer-M4K5HBLD.js.map → registry-LMHO5265.js.map} +0 -0
  383. /package/dist/{stale-PAGCS4K5.js.map → registry-TXCKWH26.js.map} +0 -0
  384. /package/dist/{ulid-COREQ2RQ.js.map → registry-VFEDQSYV.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/blobs/mime-magic.ts","../src/blobs/blob-set.ts","../src/blobs/object-projection.ts","../src/blobs/import-external.ts"],"sourcesContent":["/**\n * Lightweight MIME type detection from magic bytes (file signatures).\n *\n * Designed for the blob store's auto-detection feature. Operates on the first 16 bytes of\n * plaintext — no filesystem access, no filename guessing.\n *\n * ## Detection strategies\n *\n * 1. **Prefix match** — magic bytes at offset 0 (most formats).\n * 2. **Offset match** — magic bytes at a fixed offset > 0 (ISOBMFF: offset 4).\n * 3. **Compound match** — two separate byte sequences at different offsets\n * (RIFF-based: bytes 0-3 + bytes 8-11).\n *\n * ## Formats excluded (require offset > 16 bytes)\n *\n * - TAR (`ustar` at offset 257)\n * - ISO 9660 (`CD001` at offset 32769)\n *\n * @module\n */\n\n// ─── Types ───────────────────────────────────────────────────────────────\n\ninterface MagicRule {\n /** IANA MIME type (or widely-used x- type). */\n readonly mime: string\n /** Human-readable format name for diagnostics. */\n readonly format: string\n /** Magic bytes to match, as a Uint8Array. */\n readonly bytes: Uint8Array\n /** Byte offset where the magic starts. Default 0. */\n readonly offset?: number\n /**\n * For compound checks (RIFF, FORM): a second byte sequence that must\n * also match at `secondaryOffset`.\n */\n readonly secondaryBytes?: Uint8Array\n /** Offset of the secondary match. */\n readonly secondaryOffset?: number\n /** If true, the format is already compressed — skip gzip in blob.put(). */\n readonly preCompressed?: true\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────\n\n/** Convert a hex string like `'FF D8 FF'` to Uint8Array. */\nfunction hex(s: string): Uint8Array {\n return new Uint8Array(s.split(' ').map((b) => parseInt(b, 16)))\n}\n\n// ─── Magic rules ─────────────────────────────────────────────────────────\n//\n// Ordered by detection priority: more specific (longer) signatures first\n// within the same offset group, so that e.g. RAR v5 (8 bytes) is tested\n// before RAR v4 (7 bytes).\n//\n// Sources verified against:\n// - Gary Kessler's File Signatures Table\n// - Wikipedia \"List of file signatures\"\n// - IANA MIME type registry\n// - Individual format specifications (PNG RFC 2083, PDF ISO 32000, etc.)\n//\n// Each entry includes the original CSV row number for traceability.\n\nconst MAGIC_RULES: readonly MagicRule[] = [\n // ── Images ───────────────────────────────────────────────────────────\n\n // #2 PNG — full 8-byte signature (RFC 2083)\n { mime: 'image/png', format: 'PNG', bytes: hex('89 50 4E 47 0D 0A 1A 0A'), preCompressed: true },\n\n // #1 JPEG — FF D8 FF (third byte is start of APP marker, always FF)\n { mime: 'image/jpeg', format: 'JPEG', bytes: hex('FF D8 FF'), preCompressed: true },\n\n // #7 WebP — RIFF compound: bytes 0-3 = RIFF, bytes 8-11 = WEBP\n {\n mime: 'image/webp',\n format: 'WebP',\n bytes: hex('52 49 46 46'),\n secondaryBytes: hex('57 45 42 50'),\n secondaryOffset: 8,\n preCompressed: true,\n },\n\n // #5 TIFF (little-endian) — II + version 42\n { mime: 'image/tiff', format: 'TIFF', bytes: hex('49 49 2A 00') },\n\n // #6 TIFF (big-endian) — MM + version 42\n { mime: 'image/tiff', format: 'TIFF', bytes: hex('4D 4D 00 2A') },\n\n // #3 GIF — GIF8 (covers GIF87a and GIF89a)\n { mime: 'image/gif', format: 'GIF', bytes: hex('47 49 46 38'), preCompressed: true },\n\n // #4 BMP — BM\n { mime: 'image/bmp', format: 'BMP', bytes: hex('42 4D') },\n\n // PSD — 8BPS\n { mime: 'image/vnd.adobe.photoshop', format: 'PSD', bytes: hex('38 42 50 53') },\n\n // #8 ICO — 00 00 01 00 (note: 00 00 02 00 is CUR cursor format)\n { mime: 'image/x-icon', format: 'ICO', bytes: hex('00 00 01 00') },\n\n // #9 HEIC — ISOBMFF: ftyp at offset 4, brand \"heic\" at offset 8\n {\n mime: 'image/heic',\n format: 'HEIC',\n bytes: hex('66 74 79 70'),\n offset: 4,\n secondaryBytes: hex('68 65 69 63'),\n secondaryOffset: 8,\n preCompressed: true,\n },\n\n // ── Documents ────────────────────────────────────────────────────────\n\n // PDF — %PDF\n { mime: 'application/pdf', format: 'PDF', bytes: hex('25 50 44 46') },\n\n // RTF — {\\rtf\n { mime: 'application/rtf', format: 'RTF', bytes: hex('7B 5C 72 74 66') },\n\n // ── Archives & compression ───────────────────────────────────────────\n\n // RAR v5 — 8-byte signature (test before RAR v4)\n { mime: 'application/vnd.rar', format: 'RAR v5', bytes: hex('52 61 72 21 1A 07 01 00'), preCompressed: true },\n\n // RAR v4 — 7-byte signature\n { mime: 'application/vnd.rar', format: 'RAR v4', bytes: hex('52 61 72 21 1A 07 00'), preCompressed: true },\n\n // 7-Zip — 6-byte signature\n { mime: 'application/x-7z-compressed', format: '7Z', bytes: hex('37 7A BC AF 27 1C'), preCompressed: true },\n\n // XZ — 6-byte stream header\n { mime: 'application/x-xz', format: 'XZ', bytes: hex('FD 37 7A 58 5A 00'), preCompressed: true },\n\n // ZIP — PK\\x03\\x04 (local file header)\n { mime: 'application/zip', format: 'ZIP', bytes: hex('50 4B 03 04'), preCompressed: true },\n\n // GZIP — 1F 8B\n { mime: 'application/gzip', format: 'GZIP', bytes: hex('1F 8B'), preCompressed: true },\n\n // BZIP2 — BZh\n { mime: 'application/x-bzip2', format: 'BZIP2', bytes: hex('42 5A 68'), preCompressed: true },\n\n // LZIP — LZIP\n { mime: 'application/x-lzip', format: 'LZIP', bytes: hex('4C 5A 49 50'), preCompressed: true },\n\n // ── Audio ────────────────────────────────────────────────────────────\n\n // WAV — RIFF compound: bytes 0-3 = RIFF, bytes 8-11 = WAVE\n {\n mime: 'audio/wav',\n format: 'WAV',\n bytes: hex('52 49 46 46'),\n secondaryBytes: hex('57 41 56 45'),\n secondaryOffset: 8,\n },\n\n // AIFF — FORM compound: bytes 0-3 = FORM, bytes 8-11 = AIFF\n {\n mime: 'audio/aiff',\n format: 'AIFF',\n bytes: hex('46 4F 52 4D'),\n secondaryBytes: hex('41 49 46 46'),\n secondaryOffset: 8,\n },\n\n // FLAC — fLaC\n { mime: 'audio/flac', format: 'FLAC', bytes: hex('66 4C 61 43') },\n\n // OGG — OggS (container — may hold Vorbis, Opus, Theora, etc.)\n { mime: 'application/ogg', format: 'OGG', bytes: hex('4F 67 67 53') },\n\n // MIDI — MThd\n { mime: 'audio/midi', format: 'MIDI', bytes: hex('4D 54 68 64') },\n\n // MP3 (ID3-tagged) — ID3\n { mime: 'audio/mpeg', format: 'MP3', bytes: hex('49 44 33'), preCompressed: true },\n\n // ── Video ────────────────────────────────────────────────────────────\n\n // AVI — RIFF compound: bytes 0-3 = RIFF, bytes 8-11 = AVI\\x20\n {\n mime: 'video/x-msvideo',\n format: 'AVI',\n bytes: hex('52 49 46 46'),\n secondaryBytes: hex('41 56 49 20'),\n secondaryOffset: 8,\n preCompressed: true,\n },\n\n // WMV/ASF — 8-byte ASF header GUID prefix\n { mime: 'video/x-ms-wmv', format: 'WMV', bytes: hex('30 26 B2 75 8E 66 CF 11'), preCompressed: true },\n\n // MKV/WebM — EBML header (Matroska container)\n { mime: 'video/x-matroska', format: 'MKV', bytes: hex('1A 45 DF A3'), preCompressed: true },\n\n // FLV — FLV\n { mime: 'video/x-flv', format: 'FLV', bytes: hex('46 4C 56'), preCompressed: true },\n\n // MOV — ISOBMFF: ftyp at offset 4, brand \"qt \" at offset 8\n {\n mime: 'video/quicktime',\n format: 'MOV',\n bytes: hex('66 74 79 70'),\n offset: 4,\n secondaryBytes: hex('71 74 20 20'),\n secondaryOffset: 8,\n preCompressed: true,\n },\n\n // MP4 — ISOBMFF: ftyp at offset 4 (brands vary: isom, mp41, mp42, etc.)\n // Tested AFTER MOV and HEIC so their specific brands match first.\n { mime: 'video/mp4', format: 'MP4', bytes: hex('66 74 79 70'), offset: 4, preCompressed: true },\n\n // ── Executables & binaries ───────────────────────────────────────────\n\n // SQLite — \"SQLite 3\" (first 8 bytes of the 16-byte header)\n { mime: 'application/vnd.sqlite3', format: 'SQLite', bytes: hex('53 51 4C 69 74 65 20 33') },\n\n // WASM — \\0asm\n { mime: 'application/wasm', format: 'WASM', bytes: hex('00 61 73 6D') },\n\n // ELF — \\x7FELF\n { mime: 'application/x-elf', format: 'ELF', bytes: hex('7F 45 4C 46') },\n\n // PE (EXE/DLL) — MZ\n { mime: 'application/vnd.microsoft.portable-executable', format: 'PE', bytes: hex('4D 5A') },\n\n // Mach-O — all four single-arch variants\n { mime: 'application/x-mach-binary', format: 'Mach-O 64 LE', bytes: hex('CF FA ED FE') },\n { mime: 'application/x-mach-binary', format: 'Mach-O 64 BE', bytes: hex('FE ED FA CF') },\n { mime: 'application/x-mach-binary', format: 'Mach-O 32 LE', bytes: hex('CE FA ED FE') },\n { mime: 'application/x-mach-binary', format: 'Mach-O 32 BE', bytes: hex('FE ED FA CE') },\n\n // Java Class — CA FE BA BE\n // Note: collides with Mach-O Universal Binary. Disambiguated by checking\n // bytes 4-7: Java class version is >= 0x002D (45), while fat binary\n // arch count is a small number (typically 0x00000002).\n // We place Java after Mach-O single-arch entries so the more common\n // Mach-O variants match first. The CA FE BA BE collision between Java\n // and Mach-O fat binary is resolved by the caller if needed.\n { mime: 'application/java-vm', format: 'Java Class', bytes: hex('CA FE BA BE') },\n\n // DEX — dex\\n (Android Dalvik Executable)\n { mime: 'application/vnd.android.dex', format: 'DEX', bytes: hex('64 65 78 0A') },\n\n // ── Package formats ──────────────────────────────────────────────────\n\n // DEB — !<arch> (ar archive; DEB-specific member follows)\n { mime: 'application/vnd.debian.binary-package', format: 'DEB', bytes: hex('21 3C 61 72 63 68 3E') },\n\n // RPM — ED AB EE DB\n { mime: 'application/x-rpm', format: 'RPM', bytes: hex('ED AB EE DB') },\n\n // CAB — MSCF\n { mime: 'application/vnd.ms-cab-compressed', format: 'CAB', bytes: hex('4D 53 43 46'), preCompressed: true },\n\n // ── Capture & Flash ──────────────────────────────────────────────────\n\n // PCAP (little-endian) — D4 C3 B2 A1\n { mime: 'application/vnd.tcpdump.pcap', format: 'PCAP', bytes: hex('D4 C3 B2 A1') },\n\n // PCAP (big-endian) — A1 B2 C3 D4\n { mime: 'application/vnd.tcpdump.pcap', format: 'PCAP BE', bytes: hex('A1 B2 C3 D4') },\n\n // PCAPNG — Section Header Block\n { mime: 'application/x-pcapng', format: 'PCAPNG', bytes: hex('0A 0D 0D 0A') },\n\n // SWF — all three variants (uncompressed, zlib, LZMA)\n { mime: 'application/x-shockwave-flash', format: 'SWF', bytes: hex('46 57 53') },\n { mime: 'application/x-shockwave-flash', format: 'SWF zlib', bytes: hex('43 57 53'), preCompressed: true },\n { mime: 'application/x-shockwave-flash', format: 'SWF LZMA', bytes: hex('5A 57 53'), preCompressed: true },\n\n // ── Data formats ─────────────────────────────────────────────────────\n\n // Parquet — PAR1 (no registered IANA MIME; using Apache's informal type)\n { mime: 'application/vnd.apache.parquet', format: 'Parquet', bytes: hex('50 41 52 31') },\n\n // Avro Object Container — Obj\\x01\n { mime: 'application/avro', format: 'Avro', bytes: hex('4F 62 6A 01') },\n\n // NES ROM — NES\\x1A (iNES header)\n { mime: 'application/x-nintendo-nes-rom', format: 'NES ROM', bytes: hex('4E 45 53 1A') },\n] as const\n\n// ─── MP3 sync word ───────────────────────────────────────────────────────\n//\n// MP3 files without an ID3 tag start with a frame sync word where the top\n// 11 bits are set: 0xFFE0 mask. The ID3 signature (49 44 33) is handled\n// as a normal rule above. The sync-word check is a fallback tested in\n// `detectMimeType` after all rules.\n\nfunction isMp3SyncWord(byte0: number, byte1: number): boolean {\n return byte0 === 0xff && (byte1 & 0xe0) === 0xe0\n}\n\n// ─── Detection ───────────────────────────────────────────────────────────\n\n/**\n * Detect MIME type from the first bytes of a file.\n *\n * @param header - The first 16 bytes (or more) of the plaintext. Passing\n * fewer than 16 bytes may miss compound and offset-based matches.\n * @returns Detected MIME type, or `'application/octet-stream'` if unknown.\n */\nexport function detectMimeType(header: Uint8Array): string {\n const result = detectMagic(header)\n return result?.mime ?? 'application/octet-stream'\n}\n\n/**\n * Detect MIME type and whether the format is already compressed.\n *\n * Used by `BlobSet.put()` to decide whether to skip gzip compression.\n *\n * @param header - The first 16 bytes (or more) of the plaintext.\n * @returns `{ mime, preCompressed }` or `null` if no match.\n */\nexport function detectMagic(\n header: Uint8Array,\n): { mime: string; format: string; preCompressed: boolean } | null {\n for (const rule of MAGIC_RULES) {\n if (matchRule(header, rule)) {\n return {\n mime: rule.mime,\n format: rule.format,\n preCompressed: rule.preCompressed ?? false,\n }\n }\n }\n\n // Fallback: MP3 sync word (no ID3 tag)\n if (header.length >= 2 && isMp3SyncWord(header[0]!, header[1]!)) {\n return { mime: 'audio/mpeg', format: 'MP3', preCompressed: true }\n }\n\n return null\n}\n\n/**\n * Check whether a format is already compressed (should skip gzip).\n *\n * @param mimeType - A MIME type string.\n * @returns `true` if the format is known to be pre-compressed.\n */\nexport function isPreCompressed(mimeType: string): boolean {\n return PRE_COMPRESSED_MIMES.has(mimeType)\n}\n\n// ─── Internal matching ───────────────────────────────────────────────────\n\nfunction matchRule(header: Uint8Array, rule: MagicRule): boolean {\n const offset = rule.offset ?? 0\n const end = offset + rule.bytes.length\n\n // Not enough data for the primary match\n if (header.length < end) return false\n\n // Primary byte sequence\n for (let i = 0; i < rule.bytes.length; i++) {\n if (header[offset + i] !== rule.bytes[i]) return false\n }\n\n // Secondary byte sequence (compound check)\n if (rule.secondaryBytes && rule.secondaryOffset !== undefined) {\n const sEnd = rule.secondaryOffset + rule.secondaryBytes.length\n if (header.length < sEnd) return false\n for (let i = 0; i < rule.secondaryBytes.length; i++) {\n if (header[rule.secondaryOffset + i] !== rule.secondaryBytes[i]) return false\n }\n }\n\n return true\n}\n\n// ─── Pre-compressed MIME set ─────────────────────────────────────────────\n//\n// Built from the rules above. Used by `isPreCompressed()` for callers who\n// already know the MIME type (e.g. from a Content-Type header) and want to\n// skip the magic-byte detection step.\n\nconst PRE_COMPRESSED_MIMES = new Set<string>(\n MAGIC_RULES.filter((r) => r.preCompressed).map((r) => r.mime),\n)\n","import type {\n NoydbStore,\n EncryptedEnvelope,\n BlobObject,\n SlotRecord,\n SlotInfo,\n VersionRecord,\n BlobPutOptions,\n BlobResponseOptions,\n} from '../types.js'\nimport { NOYDB_FORMAT_VERSION } from '../types.js'\nimport type { ObjectProjection } from './object-projection.js'\nimport type { BlobFieldsConfig } from './blob-compaction.js'\nimport {\n encrypt,\n decrypt,\n hmacSha256Hex,\n encryptBytesWithAAD,\n decryptBytesWithAAD,\n bufferToBase64,\n base64ToBuffer,\n generateDEK,\n} from '../crypto.js'\nimport { wrapCek, unwrapCek } from '../record-keys/index.js'\nimport { ConflictError, NotFoundError } from '../errors.js'\nimport { detectMagic, isPreCompressed } from './mime-magic.js'\n\n// ─── Internal collection names ─────────────────────────────────────────\n\n/**\n * DEK slot name for vault-shared blob data. Calling `getDEK('_blob')`\n * auto-creates a blob DEK the first time — same lazy-creation mechanism\n * used for any user-defined collection.\n */\nexport const BLOB_COLLECTION = '_blob'\n\n/** Stores `BlobObject` metadata envelopes, keyed by eTag. */\nexport const BLOB_INDEX_COLLECTION = '_blob_index'\n\n/**\n * Stores encrypted chunk envelopes, keyed by `{eTag}/{chunkIndex}`.\n * NOT loaded into the in-memory query layer. Fetched on demand by\n * `BlobSet.get()` / `BlobSet.response()`.\n */\nexport const BLOB_CHUNKS_COLLECTION = '_blob_chunks'\n\n/** Prefix for per-collection slot metadata collections. */\nexport const BLOB_SLOTS_PREFIX = '_blob_slots_'\n\n/** Prefix for per-collection version records. */\nexport const BLOB_VERSIONS_PREFIX = '_blob_versions_'\n\n/**\n * Default chunk size: 256 KB raw bytes.\n * After AES-GCM (same size) + base64 (~33% inflation) → ~342 KB per\n * envelope, safely within DynamoDB's 400 KB item limit.\n */\nexport const DEFAULT_CHUNK_SIZE = 256 * 1024\n\n/** Maximum CAS retry attempts for refCount and slot metadata updates. */\nconst MAX_CAS_RETRIES = 5\n\n// ─── Compression helpers ───────────────────────────────────────────────\n\nasync function compressBytes(\n data: Uint8Array,\n): Promise<{ bytes: Uint8Array; algorithm: 'gzip' | 'none' }> {\n if (typeof CompressionStream === 'undefined') {\n return { bytes: data, algorithm: 'none' }\n }\n // Pipe through the stream so `readable` is drained CONCURRENTLY with the\n // write. The await-write-then-read form deadlocks once the output exceeds the\n // stream's internal buffer (the writer backpressures waiting for a reader that\n // hasn't started yet) — see #409.\n const piped = new Response(data as Uint8Array<ArrayBuffer>).body!.pipeThrough(new CompressionStream('gzip'))\n const buf = await new Response(piped).arrayBuffer()\n return { bytes: new Uint8Array(buf), algorithm: 'gzip' }\n}\n\nasync function decompressBytes(data: Uint8Array): Promise<Uint8Array> {\n if (typeof DecompressionStream === 'undefined') {\n throw new Error(\n '[noy-db] DecompressionStream not available — cannot decompress blob chunk',\n )\n }\n // Concurrent read via pipeThrough — the await-write-then-read form deadlocks\n // when the DECOMPRESSED output exceeds the stream buffer (~16 KB), which is\n // exactly the #409 hang (small compressed input → large output → backpressure).\n const piped = new Response(data as Uint8Array<ArrayBuffer>).body!.pipeThrough(new DecompressionStream('gzip'))\n const buf = await new Response(piped).arrayBuffer()\n return new Uint8Array(buf)\n}\n\nfunction concatChunks(chunks: Uint8Array[]): Uint8Array {\n const total = chunks.reduce((s, c) => s + c.byteLength, 0)\n const out = new Uint8Array(total)\n let offset = 0\n for (const c of chunks) {\n out.set(c, offset)\n offset += c.byteLength\n }\n return out\n}\n\n/** Build the AAD binding for chunk integrity: \"{eTag}:{chunkIndex}:{chunkCount}\" */\nfunction chunkAAD(eTag: string, chunkIndex: number, chunkCount: number): Uint8Array {\n return new TextEncoder().encode(`${eTag}:${chunkIndex}:${chunkCount}`)\n}\n\n// ─── BlobSet ──────────────────────────────────────────────────────────\n\n/**\n * Handle for reading, writing, versioning, and deleting binary blobs\n * on a specific record.\n *\n * Obtained via `collection.blob(id)`. No I/O is performed until you\n * call a method.\n *\n * ## Storage layout\n *\n * ```\n * _blob_index/{eTag} BlobObject metadata (vault-shared DEK)\n * _blob_chunks/{eTag}/{chunkIndex} Encrypted chunk data (vault-shared DEK + AAD)\n * _blob_slots_{collection}/{recordId} Slot map (parent collection DEK)\n * _blob_versions_{collection}/{recordId}/{slot}/{label} Published versions (parent collection DEK)\n * ```\n *\n * ## Deduplication\n *\n * `put()` computes `eTag = HMAC-SHA-256(blobDEK, plaintext)` — keyed so the\n * store cannot predict eTags for known content. If another record already\n * uploaded the same bytes, the chunks are reused and `refCount` is incremented.\n *\n * ## Chunk integrity\n *\n * Each chunk is encrypted with AES-256-GCM using AAD = `{eTag}:{index}:{count}`,\n * preventing chunk reorder, substitution, and truncation attacks.\n */\nexport class BlobSet {\n private readonly store: NoydbStore\n private readonly vault: string\n private readonly collection: string\n private readonly recordId: string\n private readonly getDEK: (name: string) => Promise<CryptoKey>\n private readonly encrypted: boolean\n private readonly userId: string | undefined\n private readonly maxBlobBytes: number | undefined\n private readonly erasableBlobs: boolean\n private readonly debugPlaintext: boolean\n private readonly objectStore: ObjectProjection | undefined\n private readonly blobFields: BlobFieldsConfig | undefined\n\n constructor(opts: {\n store: NoydbStore\n vault: string\n collection: string\n recordId: string\n getDEK: (name: string) => Promise<CryptoKey>\n encrypted: boolean\n userId?: string\n maxBlobBytes?: number\n erasableBlobs?: boolean\n debugPlaintext?: boolean\n objectStore?: ObjectProjection\n blobFields?: BlobFieldsConfig\n }) {\n this.store = opts.store\n this.vault = opts.vault\n this.collection = opts.collection\n this.recordId = opts.recordId\n this.getDEK = opts.getDEK\n this.encrypted = opts.encrypted\n this.userId = opts.userId\n this.maxBlobBytes = opts.maxBlobBytes\n this.erasableBlobs = opts.erasableBlobs === true\n this.debugPlaintext = opts.debugPlaintext === true\n this.objectStore = opts.objectStore\n this.blobFields = opts.blobFields\n }\n\n /**\n * Resolve the key the blob's CHUNKS are encrypted under.\n *\n * - `_cek` present (erasable blob) → unwrap the per-blob content CEK under\n * the `_blob` DEK. Deleting the BlobObject (at `refCount → 0`) makes this\n * key unrecoverable → the chunks are crypto-shredded.\n * - `_cek` absent (legacy) → the `_blob` DEK encrypts chunks directly.\n * - unencrypted vault → `null` (chunks stored as plaintext base64).\n */\n private async resolveChunkKey(blob: Pick<BlobObject, '_cek'>): Promise<CryptoKey | null> {\n if (!this.encrypted) return null\n const blobDEK = await this.getDEK(BLOB_COLLECTION)\n return blob._cek !== undefined ? await unwrapCek(blob._cek, blobDEK) : blobDEK\n }\n\n /** The internal collection that holds slot metadata for this collection's blobs. */\n private get slotsCollection(): string {\n return `${BLOB_SLOTS_PREFIX}${this.collection}`\n }\n\n /** The internal collection that holds published versions for this collection's blobs. */\n private get versionsCollection(): string {\n return `${BLOB_VERSIONS_PREFIX}${this.collection}`\n }\n\n // ─── Slot Metadata I/O (CAS-protected) ─────────────────────────────\n\n private async loadSlots(): Promise<{\n slots: Record<string, SlotRecord>\n version: number\n }> {\n const envelope = await this.store.get(this.vault, this.slotsCollection, this.recordId)\n if (!envelope) return { slots: {}, version: 0 }\n\n if (!this.encrypted) {\n return {\n slots: JSON.parse(envelope._data) as Record<string, SlotRecord>,\n version: envelope._v,\n }\n }\n\n const dek = await this.getDEK(this.collection)\n const json = await decrypt(envelope._iv, envelope._data, dek)\n return {\n slots: JSON.parse(json) as Record<string, SlotRecord>,\n version: envelope._v,\n }\n }\n\n private async saveSlots(\n slots: Record<string, SlotRecord>,\n currentVersion: number,\n ): Promise<void> {\n const json = JSON.stringify(slots)\n const now = new Date().toISOString()\n let envelope: EncryptedEnvelope\n\n if (this.encrypted) {\n const dek = await this.getDEK(this.collection)\n const { iv, data } = await encrypt(json, dek)\n envelope = {\n _noydb: NOYDB_FORMAT_VERSION,\n _v: currentVersion + 1,\n _ts: now,\n _iv: iv,\n _data: data,\n }\n } else {\n envelope = {\n _noydb: NOYDB_FORMAT_VERSION,\n _v: currentVersion + 1,\n _ts: now,\n _iv: '',\n _data: json,\n }\n }\n\n await this.store.put(\n this.vault,\n this.slotsCollection,\n this.recordId,\n envelope,\n currentVersion > 0 ? currentVersion : undefined,\n )\n }\n\n /**\n * CAS retry loop for slot metadata updates. Re-reads slots on conflict\n * and re-applies the mutation function.\n */\n private async casUpdateSlots(\n mutate: (slots: Record<string, SlotRecord>) => Record<string, SlotRecord> | null,\n ): Promise<void> {\n for (let attempt = 0; attempt < MAX_CAS_RETRIES; attempt++) {\n const { slots, version } = await this.loadSlots()\n const updated = mutate(slots)\n if (updated === null) return // no-op\n try {\n await this.saveSlots(updated, version)\n return\n } catch (err) {\n if (err instanceof ConflictError && attempt < MAX_CAS_RETRIES - 1) continue\n throw err\n }\n }\n }\n\n // ─── Blob Index I/O (versioned for CAS refCount) ──────────────────\n\n private async loadBlobObject(eTag: string): Promise<{ blob: BlobObject; version: number } | null> {\n const envelope = await this.store.get(this.vault, BLOB_INDEX_COLLECTION, eTag)\n if (!envelope) return null\n\n if (!this.encrypted) {\n return { blob: JSON.parse(envelope._data) as BlobObject, version: envelope._v }\n }\n\n const dek = await this.getDEK(BLOB_COLLECTION)\n const json = await decrypt(envelope._iv, envelope._data, dek)\n return { blob: JSON.parse(json) as BlobObject, version: envelope._v }\n }\n\n private async writeBlobObject(blob: BlobObject, expectedVersion?: number): Promise<void> {\n const json = JSON.stringify(blob)\n const now = new Date().toISOString()\n const newVersion = (expectedVersion ?? 0) + 1\n let envelope: EncryptedEnvelope\n\n if (this.encrypted) {\n const dek = await this.getDEK(BLOB_COLLECTION)\n const { iv, data } = await encrypt(json, dek)\n envelope = { _noydb: NOYDB_FORMAT_VERSION, _v: newVersion, _ts: now, _iv: iv, _data: data }\n } else {\n envelope = { _noydb: NOYDB_FORMAT_VERSION, _v: newVersion, _ts: now, _iv: '', _data: json }\n }\n\n await this.store.put(\n this.vault,\n BLOB_INDEX_COLLECTION,\n blob.eTag,\n envelope,\n expectedVersion,\n )\n }\n\n /**\n * CAS retry loop for refCount changes on a BlobObject.\n */\n private async casUpdateRefCount(eTag: string, delta: number): Promise<number> {\n for (let attempt = 0; attempt < MAX_CAS_RETRIES; attempt++) {\n const result = await this.loadBlobObject(eTag)\n if (!result) throw new NotFoundError(`BlobObject ${eTag} not found`)\n const { blob, version } = result\n const updated: BlobObject = { ...blob, refCount: blob.refCount + delta }\n try {\n await this.writeBlobObject(updated, version)\n return updated.refCount\n } catch (err) {\n if (err instanceof ConflictError && attempt < MAX_CAS_RETRIES - 1) continue\n throw err\n }\n }\n throw new ConflictError(-1) // exhausted retries\n }\n\n /**\n * Release `n` references to a blob and reclaim it at refCount 0 (#365 slice 4).\n *\n * The single reclaim choke point for every reference-drop path — slot\n * delete/overwrite, published-version delete, and `forget()` shred — so the\n * refCount-0 policy is uniform:\n * - **erasable blob** (`_cek` present) → delete the `BlobObject` (the SOLE\n * copy of the wrapped content CEK → chunks permanently undecryptable) and\n * reclaim the chunks. The crypto-shred is EAGER on every path: GDPR erasure\n * must not wait on orphan retention.\n * - **legacy blob** (no `_cek`) → reclaimed only when `reclaimLegacy` (the\n * `forget()` erasure path); otherwise left for deferred GC so the existing\n * `BlobLifecyclePolicy.orphanRetentionDays` semantics are preserved.\n *\n * @returns `'shredded'` (erasable, refCount 0, chunks dead) · `'retainedShared'`\n * (erasable, still referenced) · `'residue'` (legacy — not a crypto-shred).\n */\n private async releaseRef(\n eTag: string,\n n: number,\n reclaimLegacy: boolean,\n ): Promise<'shredded' | 'retainedShared' | 'residue'> {\n const loaded = await this.loadBlobObject(eTag)\n if (!loaded) return 'shredded' // already gone\n const erasable = loaded.blob._cek !== undefined\n const remaining = await this.casUpdateRefCount(eTag, -n)\n if (remaining > 0) return erasable ? 'retainedShared' : 'residue'\n\n if (erasable || reclaimLegacy) {\n await this.store.delete(this.vault, BLOB_INDEX_COLLECTION, eTag)\n for (let i = 0; i < loaded.blob.chunkCount; i++) {\n await this.store.delete(this.vault, BLOB_CHUNKS_COLLECTION, `${eTag}_${i}`)\n }\n }\n return erasable ? 'shredded' : 'residue'\n }\n\n /**\n * Crypto-shred this record's blob attachments (#365 slice 2) — called by\n * `vault.forget()`.\n *\n * For each distinct eTag the record references (a record may attach the same\n * content under several slot names → several refCount holds): decrement the\n * blob's refCount by that many. When it reaches 0:\n * - **erasable blob** (`_cek` present) → delete the `BlobObject` (the SOLE\n * recoverable copy of the wrapped content CEK → chunks permanently\n * undecryptable) and reclaim the chunk bytes. This is the crypto-shred.\n * - **legacy blob** (no `_cek`) → chunks are under the shared `_blob` DEK and\n * stay decryptable until byte-deleted; we delete the orphaned chunks +\n * index but report it as residue, not a cryptographic erasure.\n * When refCount stays > 0 the content legitimately persists for its other\n * owner — reported as `retainedShared` (or `residue` if legacy).\n *\n * Finally drops the record's slot map, severing the subject's link.\n */\n async shredAllForRecord(): Promise<{\n shredded: string[]\n retainedShared: string[]\n residue: string[]\n }> {\n const { slots } = await this.loadSlots()\n const slotNames = Object.keys(slots)\n const shredded: string[] = []\n const retainedShared: string[] = []\n const residue: string[] = []\n if (slotNames.length === 0) return { shredded, retainedShared, residue }\n\n // Reference count from THIS record per eTag.\n const holds = new Map<string, number>()\n for (const name of slotNames) {\n const eTag = slots[name]!.eTag\n holds.set(eTag, (holds.get(eTag) ?? 0) + 1)\n }\n\n for (const [eTag, n] of holds) {\n // Forget erasure reclaims legacy orphans too (the record is being erased),\n // so reclaimLegacy = true — but only erasable blobs count as a crypto-shred.\n const outcome = await this.releaseRef(eTag, n, true)\n if (outcome === 'shredded') shredded.push(eTag)\n else if (outcome === 'retainedShared') retainedShared.push(eTag)\n else residue.push(eTag)\n }\n\n // Sever the subject's link: drop the record's slot map.\n await this.store.delete(this.vault, this.slotsCollection, this.recordId)\n return { shredded, retainedShared, residue }\n }\n\n /** CAS retry loop for an arbitrary BlobObject mutation. */\n private async casUpdateBlobObject(\n eTag: string,\n mutate: (blob: BlobObject) => BlobObject,\n ): Promise<void> {\n for (let attempt = 0; attempt < MAX_CAS_RETRIES; attempt++) {\n const result = await this.loadBlobObject(eTag)\n if (!result) throw new NotFoundError(`BlobObject ${eTag} not found`)\n try {\n await this.writeBlobObject(mutate(result.blob), result.version)\n return\n } catch (err) {\n if (err instanceof ConflictError && attempt < MAX_CAS_RETRIES - 1) continue\n throw err\n }\n }\n throw new ConflictError(-1) // exhausted retries\n }\n\n /**\n * Migrate this record's LEGACY blobs (no `_cek`, chunks under the shared\n * `_blob` DEK) to per-blob content CEKs so they become crypto-shreddable\n * (#365 slice 3). Returns the eTags migrated vs. already-erasable.\n *\n * **Explicit maintenance pass** (mirrors the record-CEK migration posture):\n * re-encrypts the existing compressed chunks IN PLACE under a fresh content\n * CEK — preserving the eTag, chunkCount, chunkSize, and compression — then\n * flips the `_cek` discriminant. Crash-safe + idempotent via `_cekPending`:\n * 1. persist the wrapped content CEK in `_cekPending` (readers ignore it →\n * the blob stays readable under the `_blob` DEK; the key survives a crash);\n * 2. re-encrypt each chunk under the content CEK (a resume reads an\n * already-migrated chunk under the content CEK, else under the `_blob` DEK);\n * 3. promote `_cekPending` → `_cek` (atomic flip). Reads now use the CEK.\n * A re-run after a crash resumes from whichever phase was reached.\n *\n * Dedup-safe: migrating a shared blob (refCount > 1) re-keys it for every\n * referencer at once; a non-erasable collection still reads it (it unwraps\n * `_cek` under the `_blob` DEK it holds).\n */\n async migrate(): Promise<{ migrated: string[]; alreadyErasable: string[] }> {\n const migrated: string[] = []\n const alreadyErasable: string[] = []\n if (!this.encrypted) return { migrated, alreadyErasable }\n\n const blobDEK = await this.getDEK(BLOB_COLLECTION)\n const { slots } = await this.loadSlots()\n const eTags = new Set(Object.values(slots).map((s) => s.eTag))\n\n for (const eTag of eTags) {\n const loaded = await this.loadBlobObject(eTag)\n if (!loaded) continue\n const blob = loaded.blob\n if (blob._cek !== undefined) { alreadyErasable.push(eTag); continue }\n\n // Phase 1 — persist the content CEK (resume reuses an existing pending one).\n let contentCek: CryptoKey\n if (blob._cekPending !== undefined) {\n contentCek = await unwrapCek(blob._cekPending, blobDEK)\n } else {\n contentCek = await generateDEK()\n const wrapped = await wrapCek(contentCek, blobDEK)\n await this.casUpdateBlobObject(eTag, (b) => ({ ...b, _cekPending: wrapped }))\n }\n\n // Phase 2 — re-encrypt each chunk under the content CEK, in place.\n for (let i = 0; i < blob.chunkCount; i++) {\n let raw: Uint8Array | null\n try {\n raw = await this.readChunk(eTag, i, blob.chunkCount, blobDEK)\n } catch {\n // Already re-encrypted under the content CEK (crash resume).\n raw = await this.readChunk(eTag, i, blob.chunkCount, contentCek)\n }\n if (!raw) {\n throw new NotFoundError(\n `Blob chunk ${i}/${blob.chunkCount} missing for eTag \"${eTag}\" during migration`,\n )\n }\n await this.writeChunk(eTag, i, blob.chunkCount, raw, contentCek)\n }\n\n // Phase 3 — promote _cekPending → _cek (atomic flip).\n await this.casUpdateBlobObject(eTag, (b) => {\n const { _cekPending, ...rest } = b\n return _cekPending === undefined ? b : { ...rest, _cek: _cekPending }\n })\n migrated.push(eTag)\n }\n return { migrated, alreadyErasable }\n }\n\n // ─── Chunk I/O (with AAD binding) ─────────────────────────────────\n\n private async writeChunk(\n eTag: string,\n index: number,\n chunkCount: number,\n chunk: Uint8Array,\n dek: CryptoKey | null,\n ): Promise<void> {\n const id = `${eTag}_${index}`\n const now = new Date().toISOString()\n let envelope: EncryptedEnvelope\n\n if (dek) {\n const aad = chunkAAD(eTag, index, chunkCount)\n const { iv, data } = await encryptBytesWithAAD(chunk, dek, aad)\n envelope = { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: now, _iv: iv, _data: data }\n } else {\n envelope = {\n _noydb: NOYDB_FORMAT_VERSION,\n _v: 1,\n _ts: now,\n _iv: '',\n _data: bufferToBase64(chunk),\n }\n }\n\n await this.store.put(this.vault, BLOB_CHUNKS_COLLECTION, id, envelope)\n }\n\n private async readChunk(\n eTag: string,\n index: number,\n chunkCount: number,\n dek: CryptoKey | null,\n ): Promise<Uint8Array | null> {\n const envelope = await this.store.get(this.vault, BLOB_CHUNKS_COLLECTION, `${eTag}_${index}`)\n if (!envelope) return null\n\n if (dek) {\n const aad = chunkAAD(eTag, index, chunkCount)\n return await decryptBytesWithAAD(envelope._iv, envelope._data, dek, aad)\n }\n\n return base64ToBuffer(envelope._data)\n }\n\n // ─── Version record I/O ───────────────────────────────────────────\n\n private versionKey(slotName: string, label: string): string {\n return `${this.recordId}::${slotName}::${label}`\n }\n\n private async loadVersionRecord(slotName: string, label: string): Promise<VersionRecord | null> {\n const key = this.versionKey(slotName, label)\n const envelope = await this.store.get(this.vault, this.versionsCollection, key)\n if (!envelope) return null\n\n if (!this.encrypted) {\n return JSON.parse(envelope._data) as VersionRecord\n }\n\n const dek = await this.getDEK(this.collection)\n const json = await decrypt(envelope._iv, envelope._data, dek)\n return JSON.parse(json) as VersionRecord\n }\n\n private async writeVersionRecord(slotName: string, record: VersionRecord): Promise<void> {\n const key = this.versionKey(slotName, record.label)\n const json = JSON.stringify(record)\n const now = new Date().toISOString()\n let envelope: EncryptedEnvelope\n\n if (this.encrypted) {\n const dek = await this.getDEK(this.collection)\n const { iv, data } = await encrypt(json, dek)\n envelope = { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: now, _iv: iv, _data: data }\n } else {\n envelope = { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: now, _iv: '', _data: json }\n }\n\n await this.store.put(this.vault, this.versionsCollection, key, envelope)\n }\n\n private async deleteVersionRecord(slotName: string, label: string): Promise<void> {\n const key = this.versionKey(slotName, label)\n await this.store.delete(this.vault, this.versionsCollection, key)\n }\n\n // ─── Effective chunk size ─────────────────────────────────────────\n\n private effectiveChunkSize(opts?: BlobPutOptions): number {\n if (opts?.chunkSize) return opts.chunkSize\n if (this.maxBlobBytes) return this.maxBlobBytes\n return DEFAULT_CHUNK_SIZE\n }\n\n // ─── Fetch all chunks for a blob ──────────────────────────────────\n\n private async fetchAllChunks(blob: BlobObject): Promise<Uint8Array> {\n // Chunks are keyed under the per-blob content CEK (erasable) or directly\n // under the `_blob` DEK (legacy) — resolveChunkKey discriminates on `_cek`.\n const chunkKey = await this.resolveChunkKey(blob)\n const chunks: Uint8Array[] = []\n\n for (let i = 0; i < blob.chunkCount; i++) {\n const chunk = await this.readChunk(blob.eTag, i, blob.chunkCount, chunkKey)\n if (!chunk) {\n throw new NotFoundError(\n `Blob chunk ${i}/${blob.chunkCount} missing for eTag \"${blob.eTag}\" on record \"${this.recordId}\"`,\n )\n }\n chunks.push(chunk)\n }\n\n const assembled = concatChunks(chunks)\n return blob.compression === 'gzip' ? await decompressBytes(assembled) : assembled\n }\n\n // ─── Public API: Slot management ──────────────────────────────────\n\n /**\n * Upload bytes and attach them to this record under `slotName`.\n *\n * 1. Computes `eTag = HMAC-SHA-256(blobDEK, plaintext)` for keyed content-addressing.\n * 2. Auto-detects MIME type from magic bytes if not provided.\n * 3. If a blob with this eTag already exists, skips chunk upload (deduplication)\n * and CAS-increments refCount.\n * 4. Otherwise: compresses → splits into chunks → encrypts each chunk with\n * AAD binding → writes `_blob_chunks` → writes `BlobObject` to `_blob_index`.\n * 5. CAS-updates the slot metadata in `_blob_slots_{collection}`.\n * If overwriting an existing slot, decrements the old eTag's refCount.\n */\n async put(slotName: string, data: Uint8Array, opts?: BlobPutOptions): Promise<void> {\n // External-projection path: the field is declared `external` and an\n // ObjectProjection is configured → write the raw bytes as ONE native object\n // (unencrypted, servable) and record an `external` slot (the catalog entry).\n // Bypasses eTag/chunk/CEK/dedup entirely.\n if (this.objectStore && this.blobFields?.[slotName]?.external) {\n const policy = this.blobFields[slotName]\n let contentType = opts?.mimeType\n if (!contentType) {\n const detected = detectMagic(data.subarray(0, 16))\n contentType = detected?.mime ?? 'application/octet-stream'\n }\n const key = `${this.collection}/${this.recordId}/${slotName}`\n const isPublic = policy.public === true\n // Stamp a self-describing backlink onto the object's metadata (the\n // \"secondary store\"): default opaque-token (no name leak).\n const backlink = await this.buildBacklink(slotName, policy.backlink ?? 'opaque-token')\n await this.objectStore.putObject(key, data, {\n contentType,\n public: isPublic,\n ...(backlink.userMeta ? { userMeta: backlink.userMeta } : {}),\n })\n\n const uploaderUserId = opts?.uploadedBy ?? this.userId\n let oldETag: string | undefined\n await this.casUpdateSlots((slots) => {\n oldETag = slots[slotName]?.eTag || undefined\n // Preserve any previously-synced derived metadata across re-upload.\n const prevMeta = slots[slotName]?.external?.meta\n slots[slotName] = {\n eTag: '',\n external: {\n key,\n contentType,\n ...(isPublic ? { public: true } : {}),\n ...(backlink.token ? { backlink: backlink.token } : {}),\n ...(prevMeta ? { meta: prevMeta } : {}),\n },\n filename: opts?.filename ?? slotName,\n size: data.byteLength,\n mimeType: contentType,\n uploadedAt: new Date().toISOString(),\n ...(uploaderUserId !== undefined ? { uploadedBy: uploaderUserId } : {}),\n }\n return slots\n })\n // If this slot previously held a chunk-based blob, release that eTag.\n if (oldETag) {\n await this.releaseRef(oldETag, 1, false).catch(() => {})\n }\n return\n }\n\n // Step 1 — keyed content-hash (plaintext, before compression)\n const blobDEK = this.encrypted ? await this.getDEK(BLOB_COLLECTION) : null\n const eTag = blobDEK\n ? await hmacSha256Hex(blobDEK, data)\n : await plainSha256Hex(data)\n\n // Step 2 — MIME detection\n let mimeType = opts?.mimeType\n if (!mimeType) {\n const detected = detectMagic(data.subarray(0, 16))\n if (detected) mimeType = detected.mime\n }\n\n // Determine compression: explicit opt > auto-detect > default true\n let shouldCompress: boolean\n if (opts?.compress !== undefined) {\n shouldCompress = opts.compress\n } else if (mimeType && isPreCompressed(mimeType)) {\n shouldCompress = false\n } else {\n shouldCompress = true\n }\n // Debug-plaintext: write the blob as a single un-gzipped object so the\n // stored chunk's base64 `_data` decodes directly to the original bytes\n // (`base64 -d`) — no gzip layer, no multi-chunk reassembly. (encrypt:false\n // already stores chunks unencrypted; this drops the remaining indirection.)\n if (this.debugPlaintext) shouldCompress = false\n\n // Step 3 — deduplication check\n const existingBlob = await this.loadBlobObject(eTag)\n\n if (existingBlob) {\n // eTag already exists — just increment refCount (CAS retry). Dedup is\n // preserved across the content-CEK split: the chunks (and the BlobObject's\n // `_cek`, if any) are reused as-is; a new referencer never re-encrypts.\n await this.casUpdateRefCount(eTag, +1)\n } else {\n // Step 4 — compress\n const { bytes: compressed, algorithm } = shouldCompress\n ? await compressBytes(data)\n : { bytes: data, algorithm: 'none' as const }\n\n // Debug-plaintext stores the whole blob as one object (single chunk) so\n // it is one directly-openable file in the store rather than N shards.\n const chunkSize = this.debugPlaintext\n ? Math.max(compressed.byteLength, 1)\n : this.effectiveChunkSize(opts)\n const chunkCount = Math.max(1, Math.ceil(compressed.byteLength / chunkSize))\n\n // Erasable collection (`perRecordKeys`): mint a fresh per-blob content\n // CEK and encrypt the chunks under it instead of the shared `_blob` DEK,\n // so the BlobObject's wrapped `_cek` is the sole recoverable copy → a\n // refCount-0 delete crypto-shreds the chunks. `eTag` (the dedup address)\n // is still keyed off the `_blob` DEK, unchanged.\n let chunkKey = blobDEK\n let wrappedCek: string | undefined\n if (blobDEK && this.erasableBlobs) {\n const contentCek = await generateDEK()\n wrappedCek = await wrapCek(contentCek, blobDEK)\n chunkKey = contentCek\n }\n\n // Step 5 — write chunks FIRST with AAD binding (safe failure order)\n for (let i = 0; i < chunkCount; i++) {\n const start = i * chunkSize\n await this.writeChunk(\n eTag, i, chunkCount,\n compressed.subarray(start, start + chunkSize),\n chunkKey,\n )\n }\n\n // Step 6 — write blob index entry after all chunks succeed\n await this.writeBlobObject({\n eTag,\n size: data.byteLength,\n compressedSize: compressed.byteLength,\n compression: algorithm,\n chunkSize,\n chunkCount,\n ...(mimeType !== undefined ? { mimeType } : {}),\n createdAt: new Date().toISOString(),\n refCount: 1,\n ...(wrappedCek !== undefined ? { _cek: wrappedCek } : {}),\n })\n }\n\n // Step 7 — CAS-update slot metadata\n const uploaderUserId = opts?.uploadedBy ?? this.userId\n await this.casUpdateSlots((slots) => {\n const oldETag = slots[slotName]?.eTag\n slots[slotName] = {\n eTag,\n filename: opts?.filename ?? slotName,\n size: data.byteLength,\n ...(mimeType !== undefined ? { mimeType } : {}),\n uploadedAt: new Date().toISOString(),\n ...(uploaderUserId !== undefined ? { uploadedBy: uploaderUserId } : {}),\n }\n // Schedule old eTag refCount decrement (non-blocking best-effort)\n if (oldETag && oldETag !== eTag) {\n this._deferredRefDecrement = oldETag\n }\n return slots\n })\n\n // Release the old eTag outside the CAS loop. An erasable blob dropping to\n // refCount 0 here is crypto-shredded eagerly; a legacy one defers to GC.\n if (this._deferredRefDecrement) {\n const oldETag = this._deferredRefDecrement\n this._deferredRefDecrement = undefined\n await this.releaseRef(oldETag, 1, false).catch(() => {\n // Best-effort — a missed decrement is reconciled by a later pass.\n })\n }\n }\n\n private _deferredRefDecrement: string | undefined\n\n /**\n * Fetch all bytes for the named slot.\n * Returns `null` if the slot does not exist.\n * Throws `NotFoundError` if the index entry exists but a chunk is missing.\n */\n async get(slotName: string): Promise<Uint8Array | null> {\n const { slots } = await this.loadSlots()\n const slot = slots[slotName]\n if (!slot) return null\n\n if (slot.external) {\n if (!this.objectStore) {\n throw new NotFoundError(`Blob slot \"${slotName}\" is external but no objectStore is configured`)\n }\n return this.objectStore.getObject(slot.external.key)\n }\n\n const result = await this.loadBlobObject(slot.eTag)\n if (!result) return null\n\n return this.fetchAllChunks(result.blob)\n }\n\n /**\n * A URL to fetch an `external` slot's object directly — presigned\n * (time-limited) or public, per the projection. Returns `null` if the slot\n * does not exist. Throws for a non-external slot (use `get()`/`response()`).\n */\n async url(slotName: string, opts?: { expiresInSeconds?: number }): Promise<string | null> {\n const { slots } = await this.loadSlots()\n const slot = slots[slotName]\n if (!slot) return null\n if (!slot.external) {\n throw new NotFoundError(`Blob slot \"${slotName}\" is not external — url() is only for external fields`)\n }\n if (!this.objectStore) {\n throw new NotFoundError(`Blob slot \"${slotName}\" is external but no objectStore is configured`)\n }\n return this.objectStore.objectUrl(slot.external.key, opts)\n }\n\n /**\n * Build the backlink stamped onto an external object's metadata — the\n * self-describing \"secondary store\" reference back to this record. See\n * {@link BlobFieldPolicy.backlink}. Returns the `userMeta` to attach and, for\n * `opaque-token`, the `token` to record on the slot.\n */\n private async buildBacklink(\n slotName: string,\n mode: 'opaque-token' | 'encrypted' | 'plain' | 'none',\n ): Promise<{ userMeta?: Record<string, string>; token?: string }> {\n if (mode === 'none') return {}\n const ref = { vault: this.vault, collection: this.collection, record: this.recordId, field: slotName }\n if (mode === 'plain') {\n return {\n userMeta: {\n 'noydb-vault': ref.vault,\n 'noydb-collection': ref.collection,\n 'noydb-record': ref.record,\n 'noydb-field': ref.field,\n },\n }\n }\n if (mode === 'encrypted' && this.encrypted) {\n const dek = await this.getDEK(BLOB_COLLECTION)\n const { iv, data } = await encrypt(JSON.stringify(ref), dek)\n return { userMeta: { 'noydb-backlink-enc': `${iv}.${data}` } }\n }\n // opaque-token — also the fallback when `encrypted` is requested on a\n // plaintext vault (no DEK to encrypt under).\n const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16))\n const token = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n return { userMeta: { 'noydb-backlink': token }, token }\n }\n\n /**\n * Adopt an EXISTING object in the projection into this slot **without\n * re-uploading** — used by import/bootstrap to anchor objects already in the\n * bucket. Writes the external slot record (the catalog entry).\n */\n async adoptExternal(\n slotName: string,\n ref: {\n key: string\n size?: number\n contentType?: string\n public?: boolean\n backlink?: string\n meta?: Record<string, unknown>\n },\n ): Promise<void> {\n const uploaderUserId = this.userId\n await this.casUpdateSlots((slots) => {\n slots[slotName] = {\n eTag: '',\n external: {\n key: ref.key,\n ...(ref.contentType ? { contentType: ref.contentType } : {}),\n ...(ref.public ? { public: true } : {}),\n ...(ref.backlink ? { backlink: ref.backlink } : {}),\n ...(ref.meta ? { meta: ref.meta } : {}),\n },\n filename: slotName,\n size: ref.size ?? 0,\n ...(ref.contentType ? { mimeType: ref.contentType } : {}),\n uploadedAt: new Date().toISOString(),\n ...(uploaderUserId !== undefined ? { uploadedBy: uploaderUserId } : {}),\n }\n return slots\n })\n }\n\n /**\n * Merge derived metadata (video `duration`, image `width`/`height`, arbitrary\n * metatags) into an external slot's secondary metadata store. Typically called\n * from an AWS-side processing callback (MediaConvert / ffprobe / Rekognition)\n * once it has probed the object. No-op for a missing or non-external slot.\n */\n async setExternalMeta(slotName: string, meta: Record<string, unknown>): Promise<void> {\n await this.casUpdateSlots((slots) => {\n const slot = slots[slotName]\n if (!slot?.external) return null\n slots[slotName] = {\n ...slot,\n external: { ...slot.external, meta: { ...slot.external.meta, ...meta } },\n }\n return slots\n })\n }\n\n /**\n * Read an external slot's synced derived metadata (the secondary store).\n * Returns `null` for a missing or non-external slot, `{}` if none synced yet.\n */\n async externalMeta(slotName: string): Promise<Record<string, unknown> | null> {\n const { slots } = await this.loadSlots()\n const slot = slots[slotName]\n if (!slot?.external) return null\n return slot.external.meta ?? {}\n }\n\n /**\n * List all slot entries for this record.\n * Returns metadata only — no chunk data is loaded.\n */\n async list(): Promise<SlotInfo[]> {\n const { slots } = await this.loadSlots()\n return Object.entries(slots).map(([name, slot]) => ({ name, ...slot }))\n }\n\n /**\n * Delete the named slot from this record.\n * Decrements refCount on the blob. Chunks are GC'd by `vault.blobGC()`.\n */\n async delete(slotName: string): Promise<void> {\n let eTagToRelease: string | undefined\n let externalKeyToDelete: string | undefined\n\n await this.casUpdateSlots((slots) => {\n if (!(slotName in slots)) return null\n const slot = slots[slotName]!\n if (slot.external) externalKeyToDelete = slot.external.key\n else eTagToRelease = slot.eTag\n delete slots[slotName]\n return slots\n })\n\n if (externalKeyToDelete && this.objectStore) {\n // External objects are hard-deleted (no crypto-shred — they were never\n // encrypted). CDN/replica cache TTLs may retain a copy; see the design.\n await this.objectStore.deleteObject(externalKeyToDelete).catch(() => {})\n }\n\n if (eTagToRelease) {\n // Erasable blobs are crypto-shredded at refCount 0 (this also covers\n // compaction eviction, which routes through delete()); legacy blobs keep\n // deferred-GC / orphan-retention semantics.\n await this.releaseRef(eTagToRelease, 1, false).catch(() => {\n // Best-effort — a missed decrement is reconciled by a later pass.\n })\n }\n }\n\n /**\n * Return a native `Response` whose body streams the decrypted,\n * decompressed blob bytes with full HTTP metadata headers.\n *\n * Note: implementation is buffered — all chunks are loaded into\n * memory before being enqueued. True streaming deferred to.\n *\n * Returns `null` if the slot does not exist.\n */\n async response(slotName: string, opts?: BlobResponseOptions): Promise<Response | null> {\n const { slots } = await this.loadSlots()\n const slot = slots[slotName]\n if (!slot) return null\n\n const result = await this.loadBlobObject(slot.eTag)\n if (!result) return null\n\n return this.buildResponse(slot, result.blob, opts)\n }\n\n /**\n * Decrypt the slot and wrap the bytes in a browser ObjectURL ready\n * to feed into `<img src>`, `<a href>`, etc. The caller MUST call\n * `revoke()` when the URL is no longer needed — otherwise the URL\n * (and the underlying decrypted Blob) are pinned for the lifetime\n * of the document, which leaks memory in long-lived pages.\n *\n * Returns `null` when the slot does not exist.\n *\n * Throws when `URL.createObjectURL` is unavailable in the host\n * environment (Node without DOM, restricted workers). Framework\n * adapters — `useBlobURL` in `@noy-db/in-vue`, etc. — guard against\n * this for SSR contexts and stay at `null` instead of propagating.\n */\n async objectURL(\n slotName: string,\n opts?: { mimeType?: string },\n ): Promise<{ url: string; revoke: () => void } | null> {\n if (typeof URL === 'undefined' || typeof URL.createObjectURL !== 'function') {\n throw new Error(\n 'BlobSet.objectURL: URL.createObjectURL is unavailable in this environment. ' +\n 'Call this from the browser, or use BlobSet.get() and create the URL yourself.',\n )\n }\n const bytes = await this.get(slotName)\n if (!bytes) return null\n\n const { slots } = await this.loadSlots()\n const slot = slots[slotName]\n const type = opts?.mimeType ?? slot?.mimeType ?? 'application/octet-stream'\n\n // Pinning the underlying ArrayBuffer in a Blob is what backs the\n // ObjectURL — once we createObjectURL the URL holds a strong ref\n // to the Blob, so the local `blob` variable can fall out of scope.\n // Copy through a fresh ArrayBuffer so TS narrows away the\n // SharedArrayBuffer branch of `ArrayBufferLike` (Uint8Array is\n // generic over the backing buffer type since TS 5.7).\n const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer\n const blob = new Blob([buffer], { type })\n const url = URL.createObjectURL(blob)\n let revoked = false\n const revoke = (): void => {\n if (revoked) return\n revoked = true\n URL.revokeObjectURL(url)\n }\n return { url, revoke }\n }\n\n // ─── Public API: Published versions (UC-3 amendment versioning) ───\n\n /**\n * Publish the current slot content as a named version snapshot.\n *\n * The published version holds an independent refCount reference to\n * the blob. Even if the slot is later overwritten or deleted, the\n * published version keeps the blob data alive.\n *\n * Publishing with an existing label overwrites it — if the eTags differ,\n * refCounts are adjusted accordingly.\n */\n async publish(slotName: string, label: string): Promise<void> {\n const { slots } = await this.loadSlots()\n const slot = slots[slotName]\n if (!slot) throw new NotFoundError(`Slot \"${slotName}\" not found on record \"${this.recordId}\"`)\n\n // Check for existing version with this label\n const existing = await this.loadVersionRecord(slotName, label)\n if (existing && existing.eTag === slot.eTag) return // no-op: same blob\n\n // Write the version record\n const record: VersionRecord = {\n label,\n eTag: slot.eTag,\n publishedAt: new Date().toISOString(),\n ...(this.userId !== undefined ? { publishedBy: this.userId } : {}),\n }\n await this.writeVersionRecord(slotName, record)\n\n // Increment refCount for the new version's eTag\n await this.casUpdateRefCount(slot.eTag, +1)\n\n // If overwriting an existing version with a different eTag, release the old\n // one (crypto-shred at refCount 0 when erasable).\n if (existing && existing.eTag !== slot.eTag) {\n await this.releaseRef(existing.eTag, 1, false).catch(() => {})\n }\n }\n\n /**\n * Fetch bytes for a published version.\n * Returns `null` if the version does not exist.\n */\n async getVersion(slotName: string, label: string): Promise<Uint8Array | null> {\n const record = await this.loadVersionRecord(slotName, label)\n if (!record) return null\n\n const result = await this.loadBlobObject(record.eTag)\n if (!result) return null\n\n return this.fetchAllChunks(result.blob)\n }\n\n /**\n * List all published versions for a slot.\n */\n async listVersions(slotName: string): Promise<VersionRecord[]> {\n const prefix = `${this.recordId}::${slotName}::`\n const allKeys = await this.store.list(this.vault, this.versionsCollection)\n const matchingKeys = allKeys.filter((k) => k.startsWith(prefix))\n\n const versions: VersionRecord[] = []\n for (const key of matchingKeys) {\n const envelope = await this.store.get(this.vault, this.versionsCollection, key)\n if (!envelope) continue\n\n if (!this.encrypted) {\n versions.push(JSON.parse(envelope._data) as VersionRecord)\n } else {\n const dek = await this.getDEK(this.collection)\n const json = await decrypt(envelope._iv, envelope._data, dek)\n versions.push(JSON.parse(json) as VersionRecord)\n }\n }\n\n return versions\n }\n\n /**\n * Delete a published version. Decrements refCount on its blob.\n */\n async deleteVersion(slotName: string, label: string): Promise<void> {\n const record = await this.loadVersionRecord(slotName, label)\n if (!record) return\n\n await this.deleteVersionRecord(slotName, label)\n await this.releaseRef(record.eTag, 1, false).catch(() => {})\n }\n\n /**\n * Return a `Response` for a published version — same as `response()`\n * but reads from the version record's eTag instead of the current slot.\n */\n async responseVersion(\n slotName: string,\n label: string,\n opts?: BlobResponseOptions,\n ): Promise<Response | null> {\n const record = await this.loadVersionRecord(slotName, label)\n if (!record) return null\n\n const result = await this.loadBlobObject(record.eTag)\n if (!result) return null\n\n // Build a synthetic SlotRecord from the version + blob data\n const slotLike: SlotRecord = {\n eTag: record.eTag,\n filename: opts?.filename ?? `${slotName}-${label}`,\n size: result.blob.size,\n ...(result.blob.mimeType !== undefined ? { mimeType: result.blob.mimeType } : {}),\n uploadedAt: record.publishedAt,\n ...(record.publishedBy !== undefined ? { uploadedBy: record.publishedBy } : {}),\n }\n\n return this.buildResponse(slotLike, result.blob, opts)\n }\n\n // ─── Diagnostics ──────────────────────────────────────────────────\n\n /**\n * Return the `BlobObject` metadata for the named slot.\n * Returns `null` if the slot or blob does not exist.\n */\n async blobInfo(slotName: string): Promise<BlobObject | null> {\n const { slots } = await this.loadSlots()\n const slot = slots[slotName]\n if (!slot) return null\n const result = await this.loadBlobObject(slot.eTag)\n return result?.blob ?? null\n }\n\n // ─── Presigned URL (E5) ────────────────────────────────────────────\n\n /**\n * Generate a presigned URL for direct client download of the blob's\n * ciphertext. Only works when the blob store supports `presignUrl`.\n *\n * **Important:** The URL returns encrypted data. The caller must\n * decrypt client-side using `decryptResponse()` or a service worker.\n *\n * Returns `null` if the slot doesn't exist or the store doesn't support presigning.\n */\n async presignedUrl(slotName: string, expiresInSeconds = 3600): Promise<string | null> {\n const { slots } = await this.loadSlots()\n const slot = slots[slotName]\n if (!slot) return null\n\n const result = await this.loadBlobObject(slot.eTag)\n if (!result) return null\n\n // Only works for single-chunk blobs where the store supports presigning\n if (result.blob.chunkCount !== 1) return null\n if (!this.store.presignUrl) return null\n\n const chunkId = `${slot.eTag}_0`\n return this.store.presignUrl(this.vault, '_blob_chunks', chunkId, expiresInSeconds)\n }\n\n /**\n * Decrypt a ciphertext Response (e.g. from a presigned URL fetch)\n * back into a plaintext Response with correct headers.\n *\n * Usage with service worker or client-side fetch:\n * ```ts\n * const url = await blobs.presignedUrl('invoice.pdf')\n * const cipherResponse = await fetch(url)\n * const plainResponse = await blobs.decryptResponse('invoice.pdf', cipherResponse)\n * ```\n */\n async decryptResponse(slotName: string, cipherResponse: Response): Promise<Response | null> {\n const { slots } = await this.loadSlots()\n const slot = slots[slotName]\n if (!slot) return null\n\n const result = await this.loadBlobObject(slot.eTag)\n if (!result) return null\n\n // Parse the envelope from the ciphertext response\n const text = await cipherResponse.text()\n const envelope = JSON.parse(text) as { _iv: string; _data: string }\n\n const blobDEK = this.encrypted ? await this.getDEK('_blob') : null\n if (!blobDEK) {\n return this.buildResponse(slot, result.blob, { inline: true })\n }\n\n // Decrypt the single chunk\n const aad = chunkAAD(slot.eTag, 0, result.blob.chunkCount)\n const { decryptBytesWithAAD: decryptAAD } = await import('../crypto.js')\n const decrypted = await decryptAAD(envelope._iv, envelope._data, blobDEK, aad)\n const plaintext = result.blob.compression === 'gzip'\n ? await decompressBytes(decrypted)\n : decrypted\n\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(plaintext)\n controller.close()\n },\n })\n\n const filename = slot.filename\n return new Response(body, {\n headers: {\n 'Content-Type': slot.mimeType ?? 'application/octet-stream',\n 'Content-Length': String(slot.size),\n 'ETag': `\"${slot.eTag}\"`,\n 'Content-Disposition': `inline; filename=\"${filename}\"`,\n 'Last-Modified': new Date(slot.uploadedAt).toUTCString(),\n },\n })\n }\n\n // ─── Internal: build Response from slot + blob ────────────────────\n\n private async buildResponse(\n slot: SlotRecord,\n blob: BlobObject,\n opts?: BlobResponseOptions,\n ): Promise<Response> {\n const fetchAllChunks = this.fetchAllChunks.bind(this)\n\n // buffered — all chunks loaded into memory then enqueued.\n const body = new ReadableStream<Uint8Array>({\n async start(controller) {\n try {\n const output = await fetchAllChunks(blob)\n controller.enqueue(output)\n controller.close()\n } catch (err) {\n controller.error(err)\n }\n },\n })\n\n const filename = opts?.filename ?? slot.filename\n const disposition = opts?.inline\n ? `inline; filename=\"${filename}\"`\n : `attachment; filename=\"${filename}\"`\n\n return new Response(body, {\n headers: {\n 'Content-Type': slot.mimeType ?? 'application/octet-stream',\n 'Content-Length': String(slot.size),\n 'ETag': `\"${slot.eTag}\"`,\n 'Content-Disposition': disposition,\n 'Last-Modified': new Date(slot.uploadedAt).toUTCString(),\n },\n })\n }\n}\n\n// ─── Fallback for unencrypted mode ──────────────────────────────────────\n\nimport { sha256Hex } from '../crypto.js'\n\nasync function plainSha256Hex(data: Uint8Array): Promise<string> {\n return sha256Hex(data)\n}\n","/**\n * `ObjectProjection` — the capability an `as-*` projection store implements to\n * hold blob bytes as native, directly-consumable objects (e.g. servable S3\n * objects) rather than the encrypted-envelope chunks a `NoydbStore` holds.\n *\n * This is the shared seam behind **direct-serve blobs** (#412) and the\n * **debug raw-object path** (#413): \"write these bytes as one real object and\n * give me a URL to it.\" See the as-aws-s3 design spec.\n *\n * Unlike `NoydbStore` (ciphertext in / ciphertext out), an `ObjectProjection`\n * sees **raw bytes** — it is `as-*`, not `to-*`, and lives **outside** the\n * zero-knowledge guarantee. Wiring it up is a deliberate, per-field opt-in.\n */\n\n/** Metadata about a stored object, without its body. */\nexport interface ObjectMeta {\n readonly size: number\n readonly contentType?: string\n readonly etag?: string\n readonly lastModified?: string\n /** S3-style user metadata (`x-amz-meta-*`). Small; see the design's\n * plain / encrypted / opaque-token modes. */\n readonly userMeta?: Record<string, string>\n}\n\nexport interface PutObjectOptions {\n readonly contentType: string\n /** World-readable object (CDN origin) vs private (presigned-only). Default false. */\n readonly public?: boolean\n /** User metadata mirrored onto the object (the \"secondary store\"). */\n readonly userMeta?: Record<string, string>\n}\n\nexport interface ObjectUrlOptions {\n /** TTL for a presigned URL (ignored for a public object). */\n readonly expiresInSeconds?: number\n}\n\nexport interface PutUrlOptions {\n readonly contentType: string\n readonly expiresInSeconds?: number\n}\n\n/** One entry returned by {@link ObjectProjection.listPrefix}. */\nexport interface ObjectListEntry {\n readonly key: string\n readonly meta: ObjectMeta\n}\n\nexport interface ObjectProjection {\n /** Diagnostic name (e.g. `'aws-s3'`, `'memory'`). */\n readonly name?: string\n /** Write raw bytes as a single native object with a real content type. */\n putObject(key: string, bytes: Uint8Array, opts: PutObjectOptions): Promise<void>\n /** Read the raw bytes back; `null` if absent. */\n getObject(key: string): Promise<Uint8Array | null>\n /** Delete the object. Idempotent — absent is not an error. */\n deleteObject(key: string): Promise<void>\n /** Object metadata without the body; `null` if absent. */\n headObject(key: string): Promise<ObjectMeta | null>\n /** A URL to GET the object — presigned (time-limited) or stable public. */\n objectUrl(key: string, opts?: ObjectUrlOptions): Promise<string>\n /** A presigned URL the client PUTs bytes to directly (large-file upload,\n * bytes bypass the hub). */\n putUrl(key: string, opts: PutUrlOptions): Promise<string>\n /** List objects under a key prefix — for import / reconcile. */\n listPrefix(prefix: string): Promise<ObjectListEntry[]>\n}\n\n/**\n * In-memory {@link ObjectProjection} — a reference implementation for tests,\n * local development, and the hub's blob-wiring conformance. Holds bytes in a\n * `Map`; URLs are synthetic (`memory://…`). Not for production.\n */\nexport function memoryObjectProjection(opts: { baseUrl?: string } = {}): ObjectProjection {\n const base = opts.baseUrl ?? 'memory://objects'\n const store = new Map<\n string,\n { bytes: Uint8Array; contentType: string; userMeta?: Record<string, string>; public: boolean }\n >()\n return {\n name: 'memory',\n async putObject(key, bytes, o) {\n store.set(key, {\n bytes,\n contentType: o.contentType,\n public: o.public === true,\n ...(o.userMeta ? { userMeta: o.userMeta } : {}),\n })\n },\n async getObject(key) {\n return store.get(key)?.bytes ?? null\n },\n async deleteObject(key) {\n store.delete(key)\n },\n async headObject(key) {\n const e = store.get(key)\n if (!e) return null\n return {\n size: e.bytes.byteLength,\n contentType: e.contentType,\n ...(e.userMeta ? { userMeta: e.userMeta } : {}),\n }\n },\n async objectUrl(key, o) {\n const e = store.get(key)\n if (e?.public) return `${base}/${key}`\n return `${base}/${key}?sig=memory&expires=${o?.expiresInSeconds ?? 900}`\n },\n async putUrl(key, o) {\n return `${base}/${key}?upload=memory&ct=${encodeURIComponent(o.contentType)}`\n },\n async listPrefix(prefix) {\n const out: ObjectListEntry[] = []\n for (const [key, e] of store) {\n if (!key.startsWith(prefix)) continue\n out.push({\n key,\n meta: { size: e.bytes.byteLength, contentType: e.contentType, ...(e.userMeta ? { userMeta: e.userMeta } : {}) },\n })\n }\n return out\n },\n }\n}\n","/**\n * Import / bootstrap (reverse projection) — walk an existing bucket/prefix in an\n * {@link ObjectProjection} and build a master collection where each record\n * anchors one object, restoring the record-anchoring invariant for objects that\n * pre-date noy-db (or were written by another system). See as-aws-s3 §3.8.\n *\n * Idempotent: re-running re-adopts the same objects under the same record ids.\n */\nimport type { ObjectProjection } from './object-projection.js'\n\n/** Minimal collection surface this utility needs (avoids importing the kernel). */\nexport interface ImportableCollection {\n get(id: string): Promise<unknown>\n put(id: string, record: unknown): Promise<unknown>\n blob(id: string): {\n adoptExternal(\n slot: string,\n ref: { key: string; size?: number; contentType?: string; public?: boolean; backlink?: string },\n ): Promise<void>\n }\n}\n\nexport interface ImportExternalOptions {\n /** Only consider objects under this key prefix. Default `''` (all). */\n prefix?: string\n /**\n * Derive the record id for an object key. Default: the path segment before\n * the last — i.e. `{collection}/{recordId}/{field}` → `recordId`. Return\n * `null` to skip the object.\n */\n deriveRecordId?: (key: string) => string | null\n /** Build the anchor record for a new id. Default `{ id }`. */\n makeRecord?: (id: string) => unknown\n}\n\nexport interface ImportExternalResult {\n imported: number\n skipped: number\n recordIds: string[]\n}\n\nfunction defaultDeriveRecordId(key: string): string | null {\n const parts = key.split('/')\n return parts.length >= 2 ? (parts[parts.length - 2] ?? null) : null\n}\n\n/**\n * Build/extend `collection` from the objects under `prefix` in `objectStore`,\n * adopting each as the `field` blob on its derived record.\n */\nexport async function importExternalObjects(args: {\n collection: ImportableCollection\n objectStore: ObjectProjection\n field: string\n options?: ImportExternalOptions\n}): Promise<ImportExternalResult> {\n const { collection, objectStore, field } = args\n const opts = args.options ?? {}\n const derive = opts.deriveRecordId ?? defaultDeriveRecordId\n const makeRecord = opts.makeRecord ?? ((id: string) => ({ id }))\n\n const objects = await objectStore.listPrefix(opts.prefix ?? '')\n const recordIds: string[] = []\n let imported = 0\n let skipped = 0\n\n for (const { key, meta } of objects) {\n const recordId = derive(key)\n if (!recordId) {\n skipped++\n continue\n }\n if ((await collection.get(recordId)) == null) {\n await collection.put(recordId, makeRecord(recordId))\n }\n await collection.blob(recordId).adoptExternal(field, {\n key,\n ...(meta.size !== undefined ? { size: meta.size } : {}),\n ...(meta.contentType ? { contentType: meta.contentType } : {}),\n })\n recordIds.push(recordId)\n imported++\n }\n\n return { imported, skipped, recordIds }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAS,IAAI,GAAuB;AAClC,SAAO,IAAI,WAAW,EAAE,MAAM,GAAG,EAAE,IAAI,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC,CAAC;AAChE;AAgBA,IAAM,cAAoC;AAAA;AAAA;AAAA,EAIxC,EAAE,MAAM,aAAa,QAAQ,OAAO,OAAO,IAAI,yBAAyB,GAAG,eAAe,KAAK;AAAA;AAAA,EAG/F,EAAE,MAAM,cAAc,QAAQ,QAAQ,OAAO,IAAI,UAAU,GAAG,eAAe,KAAK;AAAA;AAAA,EAGlF;AAAA,IACE,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,OAAO,IAAI,aAAa;AAAA,IACxB,gBAAgB,IAAI,aAAa;AAAA,IACjC,iBAAiB;AAAA,IACjB,eAAe;AAAA,EACjB;AAAA;AAAA,EAGA,EAAE,MAAM,cAAc,QAAQ,QAAQ,OAAO,IAAI,aAAa,EAAE;AAAA;AAAA,EAGhE,EAAE,MAAM,cAAc,QAAQ,QAAQ,OAAO,IAAI,aAAa,EAAE;AAAA;AAAA,EAGhE,EAAE,MAAM,aAAa,QAAQ,OAAO,OAAO,IAAI,aAAa,GAAG,eAAe,KAAK;AAAA;AAAA,EAGnF,EAAE,MAAM,aAAa,QAAQ,OAAO,OAAO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AAM,WAAW,OAAO,GAAG;AAC3B,QAAI,CAAC,UAAU;AACb;AACA;AAAA,IACF;AACA,QAAK,MAAM,WAAW,IAAI,QAAQ,KAAM,MAAM;AAC5C,YAAM,WAAW,IAAI,UAAU,WAAW,QAAQ,CAAC;AAAA,IACrD;AACA,UAAM,WAAW,KAAK,QAAQ,EAAE,cAAc,OAAO;AAAA,MACnD;AAAA,MACA,GAAI,KAAK,SAAS,SAAY,EAAE,MAAM,KAAK,KAAK,IAAI,CAAC;AAAA,MACrD,GAAI,KAAK,cAAc,EAAE,aAAa,KAAK,YAAY,IAAI,CAAC;AAAA,IAC9D,CAAC;AACD,cAAU,KAAK,QAAQ;AACvB;AAAA,EACF;AAEA,SAAO,EAAE,UAAU,SAAS,UAAU;AACxC;","names":["uploaderUserId"]}
@@ -6,11 +6,11 @@ import {
6
6
  ConflictError,
7
7
  InvariantError,
8
8
  ValidationError
9
- } from "./chunk-YDLAFP36.js";
9
+ } from "./chunk-JZ5DS4DP.js";
10
10
 
11
11
  // src/tx/transaction.ts
12
12
  var TxContext = class {
13
- /** Stable id for this transaction; shared by all writes it performs (#230). */
13
+ /** Stable id for this transaction; shared by all writes it performs. */
14
14
  txId = generateULID();
15
15
  /** @internal */
16
16
  _ops = [];
@@ -20,7 +20,7 @@ var TxContext = class {
20
20
  * restore prior state via `revertExecuted`. Side-effect writes (e.g.
21
21
  * recursive derivation outputs fired inside `Collection.put`) are
22
22
  * appended here in execution order so they roll back alongside the
23
- * main staged ops (#133).
23
+ * main staged ops.
24
24
  */
25
25
  _executed = [];
26
26
  /** @internal */
@@ -43,7 +43,7 @@ var TxContext = class {
43
43
  const v = this._db.vault(name);
44
44
  if (this._amendment && !this._amendmentVaults.has(name)) {
45
45
  const role = v.role;
46
- if (role !== "admin" && role !== "owner") {
46
+ if (role !== "admin" && role !== "owner" && role !== "custodian") {
47
47
  throw new AmendmentForbiddenError(v.userId, role);
48
48
  }
49
49
  const reg = v._getGuardRegistry();
@@ -137,7 +137,7 @@ var TxCollection = class {
137
137
  this._ctx._ops.push(op);
138
138
  }
139
139
  };
140
- async function runTransaction(db, fn, options) {
140
+ async function runTransaction(db, fn, options, txInvariants) {
141
141
  if (options?.amendment) {
142
142
  if (typeof options.reason !== "string" || options.reason.trim().length === 0) {
143
143
  throw new ValidationError(
@@ -161,12 +161,19 @@ async function runTransaction(db, fn, options) {
161
161
  }
162
162
  const priorEnvelopes = /* @__PURE__ */ new Map();
163
163
  const store = db._store;
164
+ const invariants = txInvariants ?? [];
165
+ const watchedScopes = new Set(invariants.map((i) => i.scope));
166
+ const plainBefore = /* @__PURE__ */ new Map();
164
167
  for (const op of ctx._ops) {
165
168
  const key = keyOf(op);
166
169
  if (!priorEnvelopes.has(key)) {
167
170
  const env = await store.get(op.vaultName, op.collectionName, op.id);
168
171
  priorEnvelopes.set(key, env);
169
172
  }
173
+ if (watchedScopes.has(op.collectionName) && !plainBefore.has(key)) {
174
+ const prior = await db.vault(op.vaultName).collection(op.collectionName).get(op.id);
175
+ plainBefore.set(key, prior ?? null);
176
+ }
170
177
  if (op.expectedVersion !== void 0) {
171
178
  const env = priorEnvelopes.get(key) ?? null;
172
179
  const actual = env?._v ?? 0;
@@ -209,7 +216,7 @@ async function runTransaction(db, fn, options) {
209
216
  db._clearActiveTxContext(ctx);
210
217
  }
211
218
  if (ctx._amendment) {
212
- const { GuardExecutor } = await import("./executor-BZKFZVRC.js");
219
+ const { GuardExecutor } = await import("./executor-M7W3NEKR.js");
213
220
  try {
214
221
  for (const [vaultName, v] of ctx._amendmentVaults) {
215
222
  const registry = v._getGuardRegistry();
@@ -264,6 +271,58 @@ async function runTransaction(db, fn, options) {
264
271
  );
265
272
  }
266
273
  }
274
+ if (invariants.length > 0) {
275
+ const lastOp = /* @__PURE__ */ new Map();
276
+ const order = [];
277
+ for (const op of ctx._ops) {
278
+ const key = keyOf(op);
279
+ if (!lastOp.has(key)) order.push(key);
280
+ lastOp.set(key, op);
281
+ }
282
+ const changesByScope = /* @__PURE__ */ new Map();
283
+ const scopeVault = /* @__PURE__ */ new Map();
284
+ for (const key of order) {
285
+ const op = lastOp.get(key);
286
+ if (!watchedScopes.has(op.collectionName)) continue;
287
+ const before = plainBefore.get(key) ?? null;
288
+ const after = op.type === "delete" ? null : op.record ?? null;
289
+ const change = { before, after };
290
+ const arr = changesByScope.get(op.collectionName);
291
+ if (arr) arr.push(change);
292
+ else changesByScope.set(op.collectionName, [change]);
293
+ scopeVault.set(op.collectionName, op.vaultName);
294
+ }
295
+ try {
296
+ for (const inv of invariants) {
297
+ const changes = changesByScope.get(inv.scope);
298
+ if (changes === void 0 || changes.length === 0) continue;
299
+ const vaultName = scopeVault.get(inv.scope);
300
+ const v = db.vault(vaultName);
301
+ const facade = v._getReadOnlyFacade() ?? {
302
+ collection(name) {
303
+ const c = v.collection(name);
304
+ return {
305
+ get: (id) => c.get(id),
306
+ list: () => c.list(),
307
+ query: () => c.query()
308
+ };
309
+ }
310
+ };
311
+ const ctxForInv = {
312
+ existing: null,
313
+ vault: facade,
314
+ userId: v.userId,
315
+ role: v.role
316
+ };
317
+ await inv.check(changes, ctxForInv);
318
+ }
319
+ } catch (err) {
320
+ await revertExecuted(ctx._executed, store, db);
321
+ throw err instanceof InvariantError ? err : new InvariantError(
322
+ err instanceof Error ? err.message : `invariant violated: ${String(err)}`
323
+ );
324
+ }
325
+ }
267
326
  return bodyResult;
268
327
  }
269
328
  async function revertExecuted(executed, store, db) {
@@ -293,4 +352,4 @@ export {
293
352
  runTransaction,
294
353
  revertExecuted
295
354
  };
296
- //# sourceMappingURL=chunk-GVXBHCZ2.js.map
355
+ //# sourceMappingURL=chunk-ZPJSQPQH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tx/transaction.ts"],"sourcesContent":["/**\n * Multi-record atomic transactions.\n *\n * Lets an application stage writes across two or more collections (or\n * vaults) and commit them all-or-nothing.\n *\n * ```ts\n * await db.transaction(async (tx) => {\n * const inv = tx.vault('acme').collection<Invoice>('invoices')\n * const pay = tx.vault('acme').collection<Payment>('payments')\n * await inv.put(invoiceId, { ...invoice, status: 'paid' })\n * await pay.put(paymentId, { invoiceId, amount, paidAt })\n * })\n * // If the body throws before returning: nothing persisted.\n * // If the body returns: all puts committed; any CAS mismatch rolls\n * // the batch back and surfaces as ConflictError.\n * ```\n *\n * ## Atomicity semantics\n *\n * Ops are buffered during the body. On body-return the hub:\n *\n * 1. **Pre-flight** — re-reads every touched envelope and enforces\n * any caller-supplied `expectedVersion`. A mismatch throws\n * `ConflictError` with *no* writes performed.\n * 2. **Execute** — calls `Collection.put()` / `.delete()` for each\n * staged op in declaration order. History snapshots, ledger\n * appends, and change events fire as normal per op.\n * 3. **Unwind on failure** — if step 2 throws mid-batch, each\n * already-committed op is reverted via the raw store (restoring\n * the captured prior envelope, or deleting if none existed). The\n * ledger is NOT rewritten — audit history preserves the partial\n * commit and the revert.\n *\n * **Crash window.** Steps 2–3 are not a storage-layer transaction —\n * if the process dies between two executed ops, the on-disk state is\n * partial. True all-or-nothing atomicity requires a store that\n * implements `NoydbStore.tx()` (DynamoDB `TransactWriteItems`,\n * IndexedDB `readwrite` transaction, …). This executor declares\n * that future integration point via the `tx?()` method + the\n * `StoreCapabilities.txAtomic` bit, but does not yet delegate\n * to it — the cascade into `Fork · Stores` tracks the per-adapter\n * wire-up.\n *\n * ## Not covered\n *\n * - Cross-sync-peer atomicity. Transactions commit against the\n * primary store only; the sync engine pushes on its normal\n * schedule. For cross-peer two-phase commit use `SyncTransaction`\n * via `db.transaction(vaultName)`.\n * - Read-your-writes within the body. `tx.collection().get(id)`\n * returns the most-recently-staged value for that id when one\n * exists; if no staged op has touched the id, it reads the current\n * committed state. Version numbers returned by `get` reflect the\n * pre-transaction state (staged puts have no version yet).\n *\n * @module\n */\n\nimport type { Noydb } from '../noydb.js'\nimport type { Vault } from '../vault.js'\nimport type { Collection } from '../collection.js'\nimport type { EncryptedEnvelope } from '../types.js'\nimport {\n AmendmentForbiddenError,\n ConflictError,\n InvariantError,\n ValidationError,\n} from '../errors.js'\nimport { generateULID } from '../bundle/ulid.js'\nimport type { GuardExecutor as GuardExecutorModule } from '../guards/executor.js'\nimport type { LedgerEntry } from '../history/ledger/entry.js'\nimport type { TransactionInvariant } from './invariants.js'\nimport type { GuardChange, GuardContext, ReadOnlyVaultFacade } from '../guards/types.js'\n\n/** One op buffered inside a running `TxContext`. @internal */\nexport interface StagedOp {\n type: 'put' | 'delete'\n vaultName: string\n collectionName: string\n id: string\n record?: unknown\n expectedVersion?: number\n /**\n * Optional human-readable tag forwarded to the resulting ledger\n * entry's `reason` field. Set by callers via\n * `tx.vault(v).collection(c).put(id, record, { reason })`.\n */\n reason?: string\n}\n\n/**\n * One executed op (main staged op or recursive side-effect like a\n * derivation output) paired with the envelope captured before the write.\n * `revertExecuted` walks this array in reverse on rollback.\n * @internal\n */\nexport interface ExecutedOp {\n op: StagedOp\n priorEnvelope: EncryptedEnvelope | null\n}\n\n/**\n * Options accepted by `db.transaction({ amendment, reason }, fn)`.\n * Only the amendment variant uses these — a plain `db.transaction(fn)`\n * never sees this shape.\n */\nexport interface AmendmentTxOptions {\n /** Opt into amendment mode. Required to be `true`. */\n readonly amendment: true\n /** Human-readable rationale recorded in the ledger entry. Required. */\n readonly reason: string\n}\n\n/**\n * Transaction handle passed to the user's body. Use\n * `tx.vault(name).collection<T>(name)` to get a per-collection\n * facade; its `put`/`delete`/`get` calls stage ops against the tx.\n */\nexport class TxContext {\n /** Stable id for this transaction; shared by all writes it performs. */\n readonly txId: string = generateULID()\n /** @internal */\n readonly _ops: StagedOp[] = []\n /**\n * @internal — write log built up in Phase 2. Each entry records the\n * envelope captured BEFORE the write so a mid-batch failure can\n * restore prior state via `revertExecuted`. Side-effect writes (e.g.\n * recursive derivation outputs fired inside `Collection.put`) are\n * appended here in execution order so they roll back alongside the\n * main staged ops.\n */\n readonly _executed: ExecutedOp[] = []\n /** @internal */\n readonly _db: Noydb\n /**\n * @internal — true when this TxContext was opened in amendment\n * mode. Toggles the lazy-`beginAmendment` + role-check path on first\n * `tx.vault(name)` and unlocks the post-Phase-2 invariant + audit run.\n */\n readonly _amendment: boolean\n /** @internal — vaults that have already had `beginAmendment` called. */\n readonly _amendmentVaults = new Map<string, Vault>()\n\n /** @internal */\n constructor(db: Noydb, amendment = false) {\n this._db = db\n this._amendment = amendment\n }\n\n /** Scope subsequent `collection()` calls to the named vault. */\n vault(name: string): TxVault {\n const v = this._db.vault(name)\n if (this._amendment && !this._amendmentVaults.has(name)) {\n // Role check is per-vault. The task spec (\"only admin or owner\n // can open an amendment\") is implemented lazy-on-first-touch\n // because the role lives on the vault's keyring, and `tx.vault()`\n // is the first place we know which vault we're addressing. The\n // observable effect is identical to an eager check in the single-\n // vault case the tests exercise; multi-vault amendments check\n // each touched vault as they first appear.\n const role = v.role\n // FR-6: custodian is admin-rank for operational mutations, and an\n // amendment is an operational (data-correcting) act — not an ownership\n // meta-capability — so custodian is allowed alongside owner/admin.\n if (role !== 'admin' && role !== 'owner' && role !== 'custodian') {\n throw new AmendmentForbiddenError(v.userId, role)\n }\n // Amendments require an initialised guard registry — they\n // produce a structured invariant + change-set audit. A vault\n // opened without `guardStrategies` (or via the sync fallback\n // path) has a null registry and cannot run an amendment.\n const reg = v._getGuardRegistry()\n if (reg === null) {\n throw new ValidationError(\n `Vault \"${name}\": amendment mode requires at least one ` +\n `guardStrategy registered via createNoydb({ guardStrategies }). ` +\n `Open the vault with guardStrategies before calling ` +\n `db.transaction({ amendment: true }).`,\n )\n }\n reg.beginAmendment()\n this._amendmentVaults.set(name, v)\n }\n return new TxVault(this, v)\n }\n}\n\n/** Per-vault facade inside a running transaction. */\nexport class TxVault {\n /** @internal */\n readonly _ctx: TxContext\n /** @internal */\n readonly _vault: Vault\n\n /** @internal */\n constructor(ctx: TxContext, vault: Vault) {\n this._ctx = ctx\n this._vault = vault\n }\n\n /** Scope subsequent op calls to the named collection. */\n collection<T>(name: string): TxCollection<T> {\n const c = this._vault.collection<T>(name)\n return new TxCollection<T>(this._ctx, this._vault, c, name)\n }\n}\n\n/** Per-collection facade inside a running transaction. */\nexport class TxCollection<T> {\n /** @internal */\n readonly _ctx: TxContext\n /** @internal */\n readonly _vault: Vault\n /** @internal */\n readonly _coll: Collection<T>\n /** @internal */\n readonly _name: string\n\n /** @internal */\n constructor(ctx: TxContext, vault: Vault, coll: Collection<T>, name: string) {\n this._ctx = ctx\n this._vault = vault\n this._coll = coll\n this._name = name\n }\n\n /**\n * Read the current committed value, or the most-recently-staged\n * value from the same transaction if one exists.\n */\n async get(id: string): Promise<T | null> {\n for (let i = this._ctx._ops.length - 1; i >= 0; i--) {\n const op = this._ctx._ops[i]!\n if (\n op.vaultName === this._vault.name &&\n op.collectionName === this._name &&\n op.id === id\n ) {\n if (op.type === 'delete') return null\n return op.record as T\n }\n }\n return this._coll.get(id)\n }\n\n /**\n * Stage a put. Does not write until the transaction body returns.\n * Supply `{ expectedVersion }` to enforce optimistic concurrency\n * during the commit pre-flight.\n */\n put(id: string, record: T, options?: { expectedVersion?: number; reason?: string }): void {\n const op: StagedOp = {\n type: 'put',\n vaultName: this._vault.name,\n collectionName: this._name,\n id,\n record,\n }\n if (options?.expectedVersion !== undefined) op.expectedVersion = options.expectedVersion\n if (options?.reason !== undefined) op.reason = options.reason\n this._ctx._ops.push(op)\n }\n\n /**\n * Stage a delete. Does not write until the transaction body returns.\n * Supply `{ expectedVersion }` to enforce optimistic concurrency\n * during the commit pre-flight.\n */\n delete(id: string, options?: { expectedVersion?: number }): void {\n const op: StagedOp = {\n type: 'delete',\n vaultName: this._vault.name,\n collectionName: this._name,\n id,\n }\n if (options?.expectedVersion !== undefined) op.expectedVersion = options.expectedVersion\n this._ctx._ops.push(op)\n }\n}\n\n/**\n * Commit plan: pre-flight check + execution + revert plan.\n *\n * @internal — driven by `withTransactions()` (via `tx/active.ts`) for\n * user-facing `db.transaction(...)` calls and by the `amendment` path\n * in `noydb.ts`. `Collection.putManyAtomic` runs its own Phase 2 loop\n * but shares the `_activeTxContext` mechanism (and the `revertExecuted`\n * helper) so nested side-effect derivation writes get registered for\n * revert alongside the bulk-put source ops.\n */\nexport async function runTransaction<T>(\n db: Noydb,\n fn: (tx: TxContext) => Promise<T> | T,\n options?: AmendmentTxOptions,\n txInvariants?: ReadonlyArray<TransactionInvariant>,\n): Promise<T> {\n // ─── Amendment-mode pre-flight ───────────────────────────────\n // `reason` is the only thing we can validate before the body runs;\n // the per-vault role check happens lazily on first `tx.vault(name)`\n // because we don't know which vaults the body will touch ahead of\n // time. Throwing here keeps the failure mode close to the call site\n // so the developer doesn't have to walk an async stack to find the\n // missing-reason mistake.\n if (options?.amendment) {\n if (typeof options.reason !== 'string' || options.reason.trim().length === 0) {\n throw new ValidationError(\n 'db.transaction({ amendment: true }) requires a non-empty `reason` string.',\n )\n }\n }\n\n const ctx = new TxContext(db, options?.amendment === true)\n const bodyResult = await fn(ctx)\n\n if (ctx._ops.length === 0) {\n // Body produced no ops. If amendment mode was active we still\n // need to close any opened windows so a subsequent (unrelated)\n // write doesn't surprise-collect into a stale change-set. Each\n // `beginAmendment` is matched by exactly one `consumeChanges`.\n if (ctx._amendment) {\n for (const v of ctx._amendmentVaults.values()) {\n // Registry is guaranteed non-null here — `tx.vault(name)`\n // threw above if it was null before adding to\n // `_amendmentVaults`.\n const reg = v._getGuardRegistry()\n if (reg !== null) {\n reg.consumeChanges()\n reg.consumeMeta()\n }\n }\n }\n return bodyResult\n }\n\n // Phase 1 — pre-flight: snapshot every touched envelope and enforce\n // any caller-supplied expectedVersion. Same (vault, coll, id) touched\n // more than once in one tx snapshots only the *initial* committed\n // state; the in-order replay in Phase 2 takes care of successor ops.\n const priorEnvelopes = new Map<string, EncryptedEnvelope | null>()\n const store = db._store\n\n // Commit-time changeset invariants (#342) need PLAINTEXT prior records\n // for `before`, but `priorEnvelopes` holds ENCRYPTED envelopes. So for\n // ops in a watched scope we additionally decrypt the prior record here,\n // in Phase 1, BEFORE Phase 2 overwrites it. Snapshots only the initial\n // committed state per (vault, coll, id), matching the envelope snapshot.\n const invariants = txInvariants ?? []\n const watchedScopes = new Set(invariants.map(i => i.scope))\n const plainBefore = new Map<string, unknown>()\n\n for (const op of ctx._ops) {\n const key = keyOf(op)\n if (!priorEnvelopes.has(key)) {\n const env = await store.get(op.vaultName, op.collectionName, op.id)\n priorEnvelopes.set(key, env)\n }\n if (watchedScopes.has(op.collectionName) && !plainBefore.has(key)) {\n const prior = await db\n .vault(op.vaultName)\n .collection(op.collectionName)\n .get(op.id)\n plainBefore.set(key, prior ?? null)\n }\n if (op.expectedVersion !== undefined) {\n const env = priorEnvelopes.get(key) ?? null\n const actual = env?._v ?? 0\n if (actual !== op.expectedVersion) {\n throw new ConflictError(\n actual,\n `Transaction pre-flight: ${op.vaultName}/${op.collectionName}/${op.id} ` +\n `expected v${op.expectedVersion}, found v${actual}`,\n )\n }\n }\n }\n\n // Phase 2 — execute via the Collection layer so history snapshots,\n // ledger entries, and change events fire normally. We capture each\n // successful op so a mid-batch throw can revert in Phase 3.\n //\n // `_activeTxContext` is published on the Noydb instance for the\n // duration of Phase 2 so recursive writes triggered inside\n // `Collection.put` (today: eager derivation outputs) can register\n // their own envelopes onto `ctx._executed` and roll back alongside\n // the main staged ops. The `finally` clears it before the\n // amendment commit phase runs.\n db._setActiveTxContext(ctx)\n try {\n try {\n for (const op of ctx._ops) {\n const coll = db.vault(op.vaultName).collection(op.collectionName)\n const key = keyOf(op)\n const prior = priorEnvelopes.get(key) ?? null\n // Record the revert plan BEFORE the call so a mid-`coll.put` throw\n // (e.g. strict-mode derivation failure firing after `store.put`\n // has already committed the envelope) still has its source write\n // reverted. `revertExecuted` is best-effort: putting prior back is\n // idempotent when the failing op never actually wrote, and\n // `_invalidateCacheEntry` is a no-op when the collection isn't\n // hydrated.\n ctx._executed.push({ op, priorEnvelope: prior })\n if (op.type === 'put') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await coll.put(op.id, op.record as any, op.reason !== undefined ? { reason: op.reason } : undefined)\n } else {\n await coll.delete(op.id)\n }\n }\n } catch (err) {\n // Phase 3 — best-effort revert. See helper docstring.\n await revertExecuted(ctx._executed, store, db)\n // Drain amendment windows so the next transaction starts clean.\n if (ctx._amendment) {\n for (const v of ctx._amendmentVaults.values()) {\n const reg = v._getGuardRegistry()\n if (reg !== null) {\n reg.consumeChanges()\n reg.consumeMeta()\n }\n }\n }\n throw err\n }\n } finally {\n db._clearActiveTxContext(ctx)\n }\n\n // ─── Amendment commit phase (only if amendment === true) ────\n // Body succeeded — now run each touched vault's invariants over the\n // collected change-set, then append a structured ledger entry. If\n // any invariant throws, treat it exactly like a mid-Phase-2 failure:\n // revert every executed op and re-throw the InvariantError.\n if (ctx._amendment) {\n // Lazy-load GuardExecutor at the dispatch site — keeps the floor\n // bundle free of the guards subsystem when amendments aren't used.\n // Mirrors the deferred-load pattern from elsewhere in this module.\n const { GuardExecutor } = (await import('../guards/executor.js')) as {\n GuardExecutor: typeof GuardExecutorModule\n }\n try {\n for (const [vaultName, v] of ctx._amendmentVaults) {\n const registry = v._getGuardRegistry()\n // Registry is guaranteed non-null at this point — the\n // `tx.vault(name)` path that populates `_amendmentVaults`\n // throws if the registry is null. The defensive check here\n // is for TypeScript's narrowing.\n if (registry === null) continue\n const changesByCollection = registry.consumeChanges()\n const meta = registry.consumeMeta()\n if (changesByCollection.size === 0) continue\n\n const readOnlyVault = v._getReadOnlyFacade()\n if (readOnlyVault === null) continue\n\n // Build the invariant ctx once per vault — it's the same shape\n // every guard sees on the normal `check` path, just with a\n // synthetic `existing: null` (invariants get the full change\n // set in their first parameter; `existing` is a per-record\n // concept that doesn't apply here).\n const invariantsPassed: string[] = []\n for (const [collection, changes] of changesByCollection) {\n const guards = registry.guardsFor(collection).filter(g => g.amendment !== undefined)\n for (const guard of guards) {\n await GuardExecutor.runInvariant(guard, changes, {\n existing: null,\n vault: readOnlyVault,\n userId: v.userId,\n role: v.role,\n })\n }\n if (guards.length > 0) invariantsPassed.push(collection)\n }\n\n // Append the audit ledger entry. Silent no-op when the\n // history strategy isn't configured — the records still\n // committed, only the multi-record summary is unavailable.\n const ledger = v._getLedgerOrNull()\n if (ledger) {\n const role = v.role as 'admin' | 'owner'\n const amendment: NonNullable<LedgerEntry['amendment']> = {\n reason: options!.reason,\n role,\n changes: meta,\n invariantsPassed,\n }\n await ledger.append({\n op: 'amendment',\n collection: '',\n id: '',\n version: 0,\n actor: v.userId,\n // No payload to hash — the per-record entries already\n // captured `payloadHash` at their own append time. We use\n // a sha256 of the canonical reason string so the field is\n // populated with something deterministic and non-empty.\n payloadHash: '',\n amendment,\n })\n }\n void vaultName\n }\n } catch (err) {\n await revertExecuted(ctx._executed, store, db)\n throw err instanceof InvariantError ? err : new InvariantError(\n err instanceof Error ? err.message : `invariant violated: ${String(err)}`,\n )\n }\n }\n\n // ─── Commit-time changeset invariant phase (#342) ───────────\n // Runs for BOTH ordinary and amendment transactions (placed after the\n // amendment phase so an amendment commit is still subject to these\n // set-level constraints). Assemble the changeset from the executed\n // staged ops, deduped to the LAST write per (vault, coll, id) while\n // preserving write order, then group `GuardChange` by collection\n // (scope) and run each matching invariant. A throw mirrors the\n // amendment-phase failure mode exactly: revert every executed op and\n // re-throw as `InvariantError`.\n if (invariants.length > 0) {\n // Dedup ctx._ops to the last write per key, preserving first-seen\n // (write) order so the changeset is stable and order-meaningful.\n const lastOp = new Map<string, StagedOp>()\n const order: string[] = []\n for (const op of ctx._ops) {\n const key = keyOf(op)\n if (!lastOp.has(key)) order.push(key)\n lastOp.set(key, op)\n }\n\n // Group {before, after} pairs by collection name (the invariant\n // scope). `before` is the plaintext prior captured in Phase 1 (null\n // for inserts / unwatched — only watched scopes were captured, and\n // every grouped key belongs to a watched scope). `after` is the\n // written record, null for a delete.\n const changesByScope = new Map<string, GuardChange<unknown>[]>()\n // Parallel map: scope → the vault name of its (last-seen) op, used to\n // build the per-invariant read-only ctx (facade + userId + role).\n const scopeVault = new Map<string, string>()\n for (const key of order) {\n const op = lastOp.get(key)!\n if (!watchedScopes.has(op.collectionName)) continue\n const before = plainBefore.get(key) ?? null\n const after = op.type === 'delete' ? null : (op.record ?? null)\n const change = { before, after } as GuardChange<unknown>\n const arr = changesByScope.get(op.collectionName)\n if (arr) arr.push(change)\n else changesByScope.set(op.collectionName, [change])\n\n // Stash the vault name alongside so we can build a per-vault ctx.\n // (All ops in a scope group could span vaults; we resolve the\n // vault per change below via a parallel map keyed the same way.)\n scopeVault.set(op.collectionName, op.vaultName)\n }\n\n try {\n for (const inv of invariants) {\n const changes = changesByScope.get(inv.scope)\n if (changes === undefined || changes.length === 0) continue\n const vaultName = scopeVault.get(inv.scope)!\n const v = db.vault(vaultName)\n // Prefer the real read-only facade so the invariant can read\n // sibling collections; fall back to a minimal read-only stub.\n const facade: ReadOnlyVaultFacade =\n v._getReadOnlyFacade() ?? {\n collection<R = unknown>(name: string) {\n const c = v.collection<R>(name)\n return {\n get: (id: string) => c.get(id),\n list: () => c.list(),\n query: () => c.query(),\n }\n },\n }\n const ctxForInv: GuardContext<unknown> = {\n existing: null,\n vault: facade,\n userId: v.userId,\n role: v.role,\n }\n await inv.check(changes, ctxForInv)\n }\n } catch (err) {\n await revertExecuted(ctx._executed, store, db)\n throw err instanceof InvariantError ? err : new InvariantError(\n err instanceof Error ? err.message : `invariant violated: ${String(err)}`,\n )\n }\n }\n\n return bodyResult\n}\n\n/**\n * Phase 3 helper — restore captured prior envelopes via the raw store\n * to avoid re-firing Collection-level side effects (we don't want a\n * cascade of change events undoing themselves). The ledger is left\n * as-is: each committed op appended an entry; the revert is\n * deliberately NOT recorded as a compensating entry because the\n * caller-facing contract is \"atomic or not at all,\" not \"every write\n * visible in the audit trail.\" Auditors who need the intermediate\n * state can still reconstruct it by walking the ledger through the\n * failed-tx timestamp.\n *\n * @internal — shared between `runTransaction` and\n * `Collection.putManyAtomic`. Both register source ops + nested\n * derivation side-effect ops onto `_executed`; this helper unwinds the\n * combined list in reverse on rollback.\n */\nexport async function revertExecuted(\n executed: ReadonlyArray<ExecutedOp>,\n store: Noydb['_store'],\n db?: Noydb,\n): Promise<void> {\n for (const { op, priorEnvelope } of executed.slice().reverse()) {\n try {\n if (priorEnvelope) {\n await store.put(op.vaultName, op.collectionName, op.id, priorEnvelope)\n } else {\n await store.delete(op.vaultName, op.collectionName, op.id)\n }\n // Sync the Collection-layer cache with what we just wrote at\n // the raw store. Without this, eager-mode `get` would still\n // return the rolled-back record from its in-memory map. The\n // Collection's `_invalidateCacheEntry` is a no-op when the\n // collection hasn't yet been hydrated.\n if (db) {\n const coll = db.vault(op.vaultName).collection(op.collectionName)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await (coll as any)._invalidateCacheEntry(op.id)\n }\n } catch {\n // swallow — best-effort. Surfacing the revert error would mask\n // the original one that triggered the rollback.\n }\n }\n}\n\nfunction keyOf(op: StagedOp): string {\n return `${op.vaultName}\\x00${op.collectionName}\\x00${op.id}`\n}\n"],"mappings":";;;;;;;;;;;AAuHO,IAAM,YAAN,MAAgB;AAAA;AAAA,EAEZ,OAAe,aAAa;AAAA;AAAA,EAE5B,OAAmB,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASpB,YAA0B,CAAC;AAAA;AAAA,EAE3B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA;AAAA,EAEA,mBAAmB,oBAAI,IAAmB;AAAA;AAAA,EAGnD,YAAY,IAAW,YAAY,OAAO;AACxC,SAAK,MAAM;AACX,SAAK,aAAa;AAAA,EACpB;AAAA;AAAA,EAGA,MAAM,MAAuB;AAC3B,UAAM,IAAI,KAAK,IAAI,MAAM,IAAI;AAC7B,QAAI,KAAK,cAAc,CAAC,KAAK,iBAAiB,IAAI,IAAI,GAAG;AAQvD,YAAM,OAAO,EAAE;AAIf,UAAI,SAAS,WAAW,SAAS,WAAW,SAAS,aAAa;AAChE,cAAM,IAAI,wBAAwB,EAAE,QAAQ,IAAI;AAAA,MAClD;AAKA,YAAM,MAAM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AS,EAAE,WAAW,GAAG,cAAc;AAEhE,cAAO,KAAa,sBAAsB,GAAG,EAAE;AAAA,MACjD;AAAA,IACF,QAAQ;AAAA,IAGR;AAAA,EACF;AACF;AAEA,SAAS,MAAM,IAAsB;AACnC,SAAO,GAAG,GAAG,SAAS,KAAO,GAAG,cAAc,KAAO,GAAG,EAAE;AAC5D;","names":[]}
@@ -1,10 +1,12 @@
1
- import { Z as ConsentStrategy } from '../types-D9eB0Rvh.js';
2
- export { _ as CONSENT_AUDIT_COLLECTION, $ as ConsentAuditEntry, a0 as ConsentAuditFilter, a1 as ConsentContext, a2 as ConsentOp, a3 as loadConsentEntries, a4 as writeConsentEntry } from '../types-D9eB0Rvh.js';
3
- import '../lazy-builder-Rpd-V3jP.js';
4
- import '../predicate-Dnu81tsS.js';
5
- import '../strategy-DSTrsZ8t.js';
1
+ import { a3 as ConsentStrategy } from '../index-DHn9lEP0.js';
2
+ export { a4 as CONSENT_AUDIT_COLLECTION, a5 as ConsentAuditEntry, a6 as ConsentAuditFilter, a7 as ConsentContext, a8 as ConsentOp, a9 as loadConsentEntries, aa as writeConsentEntry } from '../index-DHn9lEP0.js';
3
+ import '../lazy-builder-ChSqcF5t.js';
4
+ import '../predicate-BmhBSPCH.js';
5
+ import '../strategy-8QGs5KQE.js';
6
+ import '../errors-BAWO5Z5a.js';
6
7
  import '../strategy-BSxFXGzb.js';
7
- import '../index-BF1B2HB9.js';
8
+ import '../index-BMmajblo.js';
9
+ import '../index-Ddm8D3Oo.js';
8
10
  import '@noy-db/attestation';
9
11
 
10
12
  /**
@@ -2,10 +2,11 @@ import {
2
2
  CONSENT_AUDIT_COLLECTION,
3
3
  loadConsentEntries,
4
4
  writeConsentEntry
5
- } from "../chunk-K5PVGKE4.js";
5
+ } from "../chunk-SAAJYSVV.js";
6
6
  import "../chunk-FZU343FL.js";
7
- import "../chunk-UOF74WQY.js";
8
- import "../chunk-YDLAFP36.js";
7
+ import "../chunk-E2MDPPOC.js";
8
+ import "../chunk-JZ5DS4DP.js";
9
+ import "../chunk-PZ5AY32C.js";
9
10
 
10
11
  // src/consent/active.ts
11
12
  function withConsent() {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/consent/active.ts"],"sourcesContent":["/**\n * Active consent strategy. Calling `withConsent()` returns a\n * `ConsentStrategy` that delegates to the real\n * `writeConsentEntry` / `loadConsentEntries` functions. Only\n * reachable through the `@noy-db/hub/consent` subpath.\n */\n\nimport { writeConsentEntry, loadConsentEntries } from './consent.js'\nimport type { ConsentStrategy } from './strategy.js'\n\n/**\n * Build the default consent strategy. Pass into\n * `createNoydb({ consentStrategy: withConsent() })` to enable\n * per-operation audit writes into the reserved `_consent_audit`\n * collection.\n */\nexport function withConsent(): ConsentStrategy {\n return {\n write: writeConsentEntry,\n read: loadConsentEntries,\n }\n}\n"],"mappings":";;;;;;;;;;AAgBO,SAAS,cAA+B;AAC7C,SAAO;AAAA,IACL,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/consent/active.ts"],"sourcesContent":["/**\n * Active consent strategy. Calling `withConsent()` returns a\n * `ConsentStrategy` that delegates to the real\n * `writeConsentEntry` / `loadConsentEntries` functions. Only\n * reachable through the `@noy-db/hub/consent` subpath.\n */\n\nimport { writeConsentEntry, loadConsentEntries } from './consent.js'\nimport type { ConsentStrategy } from './strategy.js'\n\n/**\n * Build the default consent strategy. Pass into\n * `createNoydb({ consentStrategy: withConsent() })` to enable\n * per-operation audit writes into the reserved `_consent_audit`\n * collection.\n */\nexport function withConsent(): ConsentStrategy {\n return {\n write: writeConsentEntry,\n read: loadConsentEntries,\n }\n}\n"],"mappings":";;;;;;;;;;;AAgBO,SAAS,cAA+B;AAC7C,SAAO;AAAA,IACL,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AACF;","names":[]}
@@ -4,6 +4,7 @@ import {
4
4
  mergeCrdtStates,
5
5
  resolveCrdtSnapshot
6
6
  } from "../chunk-J66GRPNH.js";
7
+ import "../chunk-PZ5AY32C.js";
7
8
 
8
9
  // src/crdt/active.ts
9
10
  function withCrdt() {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/crdt/active.ts"],"sourcesContent":["/**\n * Active CRDT strategy factory. Calling `withCrdt()` returns a\n * `CrdtStrategy` whose methods delegate to the real LWW-Map / RGA /\n * merge / snapshot helpers in `./crdt.ts`. Only reachable through\n * the `@noy-db/hub/crdt` subpath.\n */\n\nimport {\n buildLwwMapState,\n buildRgaState,\n mergeCrdtStates,\n resolveCrdtSnapshot,\n} from './crdt.js'\nimport type { CrdtStrategy } from './strategy.js'\n\n/**\n * Build the default CRDT strategy. Pass into\n * `createNoydb({ crdtStrategy: withCrdt() })` to enable collections\n * declared with `crdt: 'lww-map' | 'rga' | 'yjs'`.\n *\n * @example\n * ```ts\n * import { createNoydb } from '@noy-db/hub'\n * import { withCrdt } from '@noy-db/hub/crdt'\n *\n * const db = await createNoydb({\n * store, user, secret,\n * crdtStrategy: withCrdt(),\n * })\n * const notes = vault.collection('notes', { crdt: 'lww-map' })\n * ```\n */\nexport function withCrdt(): CrdtStrategy {\n return {\n buildLwwMapState,\n buildRgaState,\n mergeCrdtStates,\n resolveCrdtSnapshot,\n }\n}\n"],"mappings":";;;;;;;;AAgCO,SAAS,WAAyB;AACvC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/crdt/active.ts"],"sourcesContent":["/**\n * Active CRDT strategy factory. Calling `withCrdt()` returns a\n * `CrdtStrategy` whose methods delegate to the real LWW-Map / RGA /\n * merge / snapshot helpers in `./crdt.ts`. Only reachable through\n * the `@noy-db/hub/crdt` subpath.\n */\n\nimport {\n buildLwwMapState,\n buildRgaState,\n mergeCrdtStates,\n resolveCrdtSnapshot,\n} from './crdt.js'\nimport type { CrdtStrategy } from './strategy.js'\n\n/**\n * Build the default CRDT strategy. Pass into\n * `createNoydb({ crdtStrategy: withCrdt() })` to enable collections\n * declared with `crdt: 'lww-map' | 'rga' | 'yjs'`.\n *\n * @example\n * ```ts\n * import { createNoydb } from '@noy-db/hub'\n * import { withCrdt } from '@noy-db/hub/crdt'\n *\n * const db = await createNoydb({\n * store, user, secret,\n * crdtStrategy: withCrdt(),\n * })\n * const notes = vault.collection('notes', { crdt: 'lww-map' })\n * ```\n */\nexport function withCrdt(): CrdtStrategy {\n return {\n buildLwwMapState,\n buildRgaState,\n mergeCrdtStates,\n resolveCrdtSnapshot,\n }\n}\n"],"mappings":";;;;;;;;;AAgCO,SAAS,WAAyB;AACvC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -16,10 +16,13 @@ import {
16
16
  generateSalt,
17
17
  hmacSha256Hex,
18
18
  sha256Hex,
19
+ unwrapCek,
19
20
  unwrapKey,
21
+ wrapCek,
20
22
  wrapKey
21
- } from "./chunk-UOF74WQY.js";
22
- import "./chunk-YDLAFP36.js";
23
+ } from "./chunk-E2MDPPOC.js";
24
+ import "./chunk-JZ5DS4DP.js";
25
+ import "./chunk-PZ5AY32C.js";
23
26
  export {
24
27
  base64ToBuffer,
25
28
  bufferToBase64,
@@ -38,7 +41,9 @@ export {
38
41
  generateSalt,
39
42
  hmacSha256Hex,
40
43
  sha256Hex,
44
+ unwrapCek,
41
45
  unwrapKey,
46
+ wrapCek,
42
47
  wrapKey
43
48
  };
44
- //# sourceMappingURL=crypto-H2Y3DDFW.js.map
49
+ //# sourceMappingURL=crypto-OSIV2IIW.js.map