@noy-db/hub 0.6.0-pre.8 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (512) hide show
  1. package/CHANGELOG.md +7079 -0
  2. package/codemods/0.6.0-pre.json +211 -0
  3. package/dist/api-6X2VLZ7J.js +20 -0
  4. package/dist/attestation/index.js +19 -19
  5. package/dist/{backup-KULFZ2T4.js → backup-VL4GRIEW.js} +36 -18
  6. package/dist/backup-VL4GRIEW.js.map +1 -0
  7. package/dist/blobs/index.js +22 -20
  8. package/dist/blobs/index.js.map +1 -1
  9. package/dist/broker/index.js +12 -12
  10. package/dist/cargo/index.js +35 -35
  11. package/dist/{chunk-KUDZVJKQ.js → chunk-22GR3O4J.js} +2 -2
  12. package/dist/{chunk-CCZJJ4I2.js → chunk-2CBFYXJX.js} +6 -6
  13. package/dist/{chunk-JJNOLSG5.js → chunk-2J5IT37K.js} +15 -16
  14. package/dist/chunk-2J5IT37K.js.map +1 -0
  15. package/dist/{chunk-PNKHAKQ7.js → chunk-2ZCWHCLF.js} +17 -10
  16. package/dist/chunk-2ZCWHCLF.js.map +1 -0
  17. package/dist/{chunk-2BMRJ6LQ.js → chunk-2ZT4INZ4.js} +8 -11
  18. package/dist/{chunk-2BMRJ6LQ.js.map → chunk-2ZT4INZ4.js.map} +1 -1
  19. package/dist/{chunk-FAXZQ5UF.js → chunk-323MN67Z.js} +2 -2
  20. package/dist/{chunk-VMCCGUQB.js → chunk-36CEG6CM.js} +2 -2
  21. package/dist/{chunk-PDLLCOGD.js → chunk-3OE2QNSM.js} +20 -17
  22. package/dist/chunk-3OE2QNSM.js.map +1 -0
  23. package/dist/{chunk-AHLJSVRL.js → chunk-3YGUHUJA.js} +5 -7
  24. package/dist/chunk-3YGUHUJA.js.map +1 -0
  25. package/dist/{chunk-ZJADGNYF.js → chunk-4AOERLTV.js} +1 -1
  26. package/dist/chunk-4AOERLTV.js.map +1 -0
  27. package/dist/{chunk-J7FM3RAU.js → chunk-4ATF4BLF.js} +87 -34
  28. package/dist/chunk-4ATF4BLF.js.map +1 -0
  29. package/dist/{chunk-747LRSOO.js → chunk-4K6BIMLF.js} +2 -2
  30. package/dist/{chunk-PXCBVDFY.js → chunk-5ATC6UT4.js} +40 -7
  31. package/dist/chunk-5ATC6UT4.js.map +1 -0
  32. package/dist/{chunk-4GZ6XOVW.js → chunk-5F7BZAGV.js} +44 -42
  33. package/dist/chunk-5F7BZAGV.js.map +1 -0
  34. package/dist/{chunk-FNSMZQS4.js → chunk-5IHGJHWC.js} +2 -2
  35. package/dist/{chunk-4I72F5DF.js → chunk-5LZZQMIC.js} +11 -14
  36. package/dist/chunk-5LZZQMIC.js.map +1 -0
  37. package/dist/{chunk-JXIDGFKS.js → chunk-5O5ZSW7N.js} +4 -2
  38. package/dist/chunk-5O5ZSW7N.js.map +1 -0
  39. package/dist/{chunk-CEJWMBXO.js → chunk-5OT4G5N5.js} +6 -2
  40. package/dist/chunk-5OT4G5N5.js.map +1 -0
  41. package/dist/{chunk-GAG7QOVO.js → chunk-64WHKBMP.js} +53 -18
  42. package/dist/chunk-64WHKBMP.js.map +1 -0
  43. package/dist/{chunk-7TSYBD3E.js → chunk-65JXA63J.js} +2 -2
  44. package/dist/{chunk-Z45YRGFO.js → chunk-6NR36UNB.js} +2 -2
  45. package/dist/{chunk-W77KZHCW.js → chunk-6RH7PRTL.js} +16 -17
  46. package/dist/chunk-6RH7PRTL.js.map +1 -0
  47. package/dist/{chunk-3JVXVJ7L.js → chunk-7OBIBPCV.js} +10 -10
  48. package/dist/{chunk-AR2JDFAE.js → chunk-7Q3RHOA5.js} +2 -2
  49. package/dist/chunk-7ZGPQOFV.js +190 -0
  50. package/dist/chunk-7ZGPQOFV.js.map +1 -0
  51. package/dist/{chunk-QULVCV3M.js → chunk-AJGGBXWA.js} +4 -4
  52. package/dist/{chunk-CADUYBQD.js → chunk-ATL3ZVXT.js} +2 -2
  53. package/dist/{chunk-DMQCLZ4Z.js → chunk-ATY3ZASK.js} +2 -2
  54. package/dist/{chunk-4HDYQL3J.js → chunk-B4CRUZPR.js} +2 -2
  55. package/dist/{chunk-IMZLOJTK.js → chunk-BMU2DS3S.js} +30 -21
  56. package/dist/chunk-BMU2DS3S.js.map +1 -0
  57. package/dist/{chunk-6SAFL5YE.js → chunk-BZ3WMOYX.js} +3 -3
  58. package/dist/{chunk-UHXCLPGC.js → chunk-C3XWJCG7.js} +2 -2
  59. package/dist/chunk-C3XWJCG7.js.map +1 -0
  60. package/dist/{chunk-HXGUIPQB.js → chunk-CKKN25P2.js} +3 -3
  61. package/dist/{chunk-3URQC7EH.js → chunk-CXPOG3ZY.js} +355 -132
  62. package/dist/chunk-CXPOG3ZY.js.map +1 -0
  63. package/dist/{chunk-3FSX6LDG.js → chunk-D2YFQ7XG.js} +18 -3
  64. package/dist/{chunk-3FSX6LDG.js.map → chunk-D2YFQ7XG.js.map} +1 -1
  65. package/dist/{chunk-52JPHN5N.js → chunk-D6SXRMZZ.js} +27 -149
  66. package/dist/chunk-D6SXRMZZ.js.map +1 -0
  67. package/dist/{chunk-2DHSSLOD.js → chunk-DECNV4QK.js} +13 -15
  68. package/dist/chunk-DECNV4QK.js.map +1 -0
  69. package/dist/{chunk-6BU3L4UE.js → chunk-DNKVKO7K.js} +7 -10
  70. package/dist/chunk-DNKVKO7K.js.map +1 -0
  71. package/dist/{chunk-6HFM7EIT.js → chunk-EHRIDNZX.js} +2 -2
  72. package/dist/{chunk-3737A6EA.js → chunk-EHW7NLGD.js} +127 -31
  73. package/dist/chunk-EHW7NLGD.js.map +1 -0
  74. package/dist/{chunk-BEFVYAR5.js → chunk-EQOTJL76.js} +4 -4
  75. package/dist/chunk-EQOTJL76.js.map +1 -0
  76. package/dist/{chunk-E6427JU2.js → chunk-EV2TDHQZ.js} +19 -3
  77. package/dist/chunk-EV2TDHQZ.js.map +1 -0
  78. package/dist/{chunk-WFUIE565.js → chunk-FNYCT27B.js} +17 -14
  79. package/dist/chunk-FNYCT27B.js.map +1 -0
  80. package/dist/{chunk-RTAMLDWP.js → chunk-FU5VYEYK.js} +2 -2
  81. package/dist/chunk-FX3UIDCS.js +66 -0
  82. package/dist/chunk-FX3UIDCS.js.map +1 -0
  83. package/dist/{chunk-7F4DBNSP.js → chunk-GANFIM2M.js} +135 -18
  84. package/dist/chunk-GANFIM2M.js.map +1 -0
  85. package/dist/{chunk-4VUPLMZ6.js → chunk-GCU42IG7.js} +66 -71
  86. package/dist/chunk-GCU42IG7.js.map +1 -0
  87. package/dist/{chunk-RXYYFSBB.js → chunk-GKTW3KLV.js} +4 -4
  88. package/dist/chunk-HK67PX4J.js +27 -0
  89. package/dist/chunk-HK67PX4J.js.map +1 -0
  90. package/dist/{chunk-OF3L2SD6.js → chunk-HOPNIR5R.js} +2 -2
  91. package/dist/{chunk-WLZ47GSL.js → chunk-HSJBJIB2.js} +12 -10
  92. package/dist/{chunk-WLZ47GSL.js.map → chunk-HSJBJIB2.js.map} +1 -1
  93. package/dist/{chunk-ADW22QSB.js → chunk-HWI7GHJZ.js} +4 -4
  94. package/dist/{chunk-GQ3BX5EA.js → chunk-I3ISCYT7.js} +2 -2
  95. package/dist/{chunk-YJ6IONGA.js → chunk-IWKCJCLP.js} +11 -3
  96. package/dist/{chunk-YJ6IONGA.js.map → chunk-IWKCJCLP.js.map} +1 -1
  97. package/dist/{chunk-NJDQ4YSV.js → chunk-IWQPYT6S.js} +4 -4
  98. package/dist/{chunk-JRKZTEZZ.js → chunk-J6I5VR6P.js} +444 -73
  99. package/dist/chunk-J6I5VR6P.js.map +1 -0
  100. package/dist/{chunk-2Z3NCLNX.js → chunk-JHYKSMVX.js} +7 -7
  101. package/dist/{chunk-6FJWSWFT.js → chunk-JIHWBKMQ.js} +3 -3
  102. package/dist/{chunk-YAWK6AWF.js → chunk-JKATP6OE.js} +2 -2
  103. package/dist/{chunk-PL2GHSCM.js → chunk-JMJSCI7U.js} +157 -90
  104. package/dist/chunk-JMJSCI7U.js.map +1 -0
  105. package/dist/{chunk-Q6TEJXBX.js → chunk-JXHNUYQO.js} +31 -49
  106. package/dist/chunk-JXHNUYQO.js.map +1 -0
  107. package/dist/{chunk-WK5XUYYF.js → chunk-JYPRZWCZ.js} +473 -231
  108. package/dist/chunk-JYPRZWCZ.js.map +1 -0
  109. package/dist/{chunk-5ZKS6ZE2.js → chunk-K6CPIK3R.js} +4 -4
  110. package/dist/chunk-K6CPIK3R.js.map +1 -0
  111. package/dist/{chunk-CDB2HVQW.js → chunk-KM6ZXG7U.js} +14 -15
  112. package/dist/chunk-KM6ZXG7U.js.map +1 -0
  113. package/dist/{chunk-DG27IUVI.js → chunk-LC6NE4IQ.js} +2 -2
  114. package/dist/{chunk-WASHZV34.js → chunk-LIR2DJWP.js} +63 -25
  115. package/dist/chunk-LIR2DJWP.js.map +1 -0
  116. package/dist/{chunk-VZ3XFUQ7.js → chunk-LUYPYCHY.js} +16 -22
  117. package/dist/chunk-LUYPYCHY.js.map +1 -0
  118. package/dist/{chunk-G6S5VVHP.js → chunk-M7WBE3OR.js} +10 -10
  119. package/dist/chunk-M7WBE3OR.js.map +1 -0
  120. package/dist/{chunk-VJFMXYKP.js → chunk-MPKP6L5E.js} +2 -2
  121. package/dist/{chunk-IGJCYUT5.js → chunk-NSITFOCJ.js} +1 -1
  122. package/dist/chunk-NSITFOCJ.js.map +1 -0
  123. package/dist/{chunk-FUHKW252.js → chunk-OCJ3JA4O.js} +2 -2
  124. package/dist/{chunk-VCETL77O.js → chunk-ONPVHX2Y.js} +36 -7
  125. package/dist/chunk-ONPVHX2Y.js.map +1 -0
  126. package/dist/{chunk-WLYIROCJ.js → chunk-OQMCFHUX.js} +2 -2
  127. package/dist/{chunk-JRCYZEHU.js → chunk-OR2FYRYR.js} +2 -2
  128. package/dist/{chunk-HNHCQ556.js → chunk-PFWE7FJG.js} +2 -2
  129. package/dist/{chunk-NPP5R7FF.js → chunk-PJX72ICF.js} +22 -18
  130. package/dist/chunk-PJX72ICF.js.map +1 -0
  131. package/dist/{chunk-U5O6GIWZ.js → chunk-POFYIGQ2.js} +3 -3
  132. package/dist/{chunk-35EBKWQU.js → chunk-QH47SQLD.js} +4 -4
  133. package/dist/{chunk-FZ6NYJ7L.js → chunk-QQRRKO7W.js} +11 -8
  134. package/dist/chunk-QQRRKO7W.js.map +1 -0
  135. package/dist/{chunk-HVQGCKY4.js → chunk-QVXZFJBU.js} +2 -2
  136. package/dist/{chunk-FMQJZH4R.js → chunk-RDB66EKD.js} +6 -6
  137. package/dist/{chunk-X56RTUK3.js → chunk-RJZQ2PVD.js} +3 -3
  138. package/dist/{chunk-SUFG5E73.js → chunk-RPRASGEY.js} +2 -2
  139. package/dist/{chunk-XWX7GL56.js → chunk-S2I5MYSA.js} +7 -10
  140. package/dist/chunk-S2I5MYSA.js.map +1 -0
  141. package/dist/{chunk-FFDNKRCY.js → chunk-S6PJ6ZKE.js} +2 -2
  142. package/dist/chunk-S6PJ6ZKE.js.map +1 -0
  143. package/dist/{chunk-JIUVJ4M7.js → chunk-S7PM7Z4K.js} +3 -3
  144. package/dist/{chunk-55LKVALY.js → chunk-T7IR4N2S.js} +1 -3
  145. package/dist/chunk-T7IR4N2S.js.map +1 -0
  146. package/dist/{chunk-N35NC4JH.js → chunk-TKBB62DN.js} +2 -2
  147. package/dist/{chunk-YPYHVOXP.js → chunk-UJ4Z67UQ.js} +2 -2
  148. package/dist/chunk-UJ4Z67UQ.js.map +1 -0
  149. package/dist/{chunk-7MNBICB5.js → chunk-W3HAIN6U.js} +16 -14
  150. package/dist/chunk-W3HAIN6U.js.map +1 -0
  151. package/dist/{chunk-4UVDI4XE.js → chunk-WPZ5FVAS.js} +4 -4
  152. package/dist/{chunk-MSWYQLMQ.js → chunk-XINT4VJA.js} +2 -2
  153. package/dist/{chunk-7G6VDWXB.js → chunk-XPEPMK4Y.js} +3 -3
  154. package/dist/chunk-XPEPMK4Y.js.map +1 -0
  155. package/dist/{chunk-W3TVWF6N.js → chunk-YCGLAANM.js} +2 -2
  156. package/dist/{chunk-O2ERS4UJ.js → chunk-YTUFV7U7.js} +80 -51
  157. package/dist/chunk-YTUFV7U7.js.map +1 -0
  158. package/dist/{chunk-FDX7OWWI.js → chunk-YYV53EHO.js} +2 -2
  159. package/dist/{chunk-HNGSV2YC.js → chunk-Z3BZXPRO.js} +67 -10
  160. package/dist/chunk-Z3BZXPRO.js.map +1 -0
  161. package/dist/{chunk-6NVPFKN3.js → chunk-ZIMQDXTQ.js} +92 -35
  162. package/dist/chunk-ZIMQDXTQ.js.map +1 -0
  163. package/dist/{chunk-5JY5TSVY.js → chunk-ZJUZOJVW.js} +25 -31
  164. package/dist/chunk-ZJUZOJVW.js.map +1 -0
  165. package/dist/{chunk-3IXIU6FP.js → chunk-ZY6P7M52.js} +7 -10
  166. package/dist/chunk-ZY6P7M52.js.map +1 -0
  167. package/dist/{chunk-H73G4XF4.js → chunk-ZYZJLYNS.js} +7 -11
  168. package/dist/chunk-ZYZJLYNS.js.map +1 -0
  169. package/dist/classified/index.js +5 -5
  170. package/dist/{classified-marker-2KJAXRRO.js → classified-marker-AZDSDG6V.js} +3 -3
  171. package/dist/collection-facade-WSUAYFJ4.js +45 -0
  172. package/dist/{computed-6G5M3UPH.js → computed-VG2PCM4L.js} +3 -3
  173. package/dist/consent/index.js +10 -10
  174. package/dist/cover/index.js +10 -3
  175. package/dist/custody/index.js +12 -11
  176. package/dist/{dead-filter-DCB62VWW.js → dead-filter-JNQNB3TA.js} +2 -2
  177. package/dist/debug/index.js +1 -1
  178. package/dist/{delegation-MO7YZYJS.js → delegation-5F36DRDH.js} +24 -23
  179. package/dist/delegation-5F36DRDH.js.map +1 -0
  180. package/dist/derivations/index.js +12 -12
  181. package/dist/derive-MPOGZ4NR.js +22 -0
  182. package/dist/directory/index.js +10 -10
  183. package/dist/{dispatch-MJ6SHB3Y.js → dispatch-3ZA733EY.js} +18 -18
  184. package/dist/{dispatch-FZEAWKVM.js → dispatch-TNM5CRLZ.js} +9 -6
  185. package/dist/dispatch-TNM5CRLZ.js.map +1 -0
  186. package/dist/{enclave-JU4YIEPB.js → enclave-Y2ALNDRD.js} +31 -9
  187. package/dist/executor-BBEEUFO3.js +9 -0
  188. package/dist/executor-G6G3YEWR.js +9 -0
  189. package/dist/executor-ZUTUMTPA.js +29 -0
  190. package/dist/export-accessible-S3KEB763.js +23 -0
  191. package/dist/extract-partition-KVCTSUVE.js +38 -0
  192. package/dist/{fanout-sidecar-NNAJQXMX.js → fanout-sidecar-3QZU7ZZX.js} +18 -27
  193. package/dist/fanout-sidecar-3QZU7ZZX.js.map +1 -0
  194. package/dist/find-V4FN5ITT.js +11 -0
  195. package/dist/forget/index.js +9 -9
  196. package/dist/guards/index.js +7 -7
  197. package/dist/history/index.js +23 -20
  198. package/dist/history/index.js.map +1 -1
  199. package/dist/i18n/index.js +14 -14
  200. package/dist/index.d.ts +30 -13
  201. package/dist/index.js +180 -188
  202. package/dist/index.js.map +1 -1
  203. package/dist/indexing/index.js +4 -4
  204. package/dist/introspection/index.js +11 -11
  205. package/dist/issue-5CFBWBRX.js +19 -0
  206. package/dist/kernel/collection.d.ts +8 -2
  207. package/dist/kernel/constants.d.ts +36 -0
  208. package/dist/kernel/enclave/crypto.d.ts +52 -4
  209. package/dist/kernel/enclave/index.d.ts +10 -3
  210. package/dist/kernel/enclave/record-aad.d.ts +131 -0
  211. package/dist/kernel/enclave/record-envelope.d.ts +76 -0
  212. package/dist/kernel/enclave/record-keys/envelope-body.d.ts +34 -2
  213. package/dist/kernel/enclave/record-keys/lifecycle.d.ts +22 -5
  214. package/dist/kernel/enclave/record-keys/record-codec.d.ts +47 -14
  215. package/dist/kernel/enclave/record-keys/rekey-blob.d.ts +88 -0
  216. package/dist/kernel/enclave/record-keys/rekey.d.ts +91 -0
  217. package/dist/kernel/enclave/record-keys/tombstone.d.ts +3 -2
  218. package/dist/kernel/errors.d.ts +132 -12
  219. package/dist/kernel/merge-authority.d.ts +25 -0
  220. package/dist/kernel/noydb.d.ts +27 -4
  221. package/dist/kernel/query/builder.d.ts +51 -4
  222. package/dist/kernel/query/join.d.ts +27 -0
  223. package/dist/kernel/query/live.d.ts +31 -9
  224. package/dist/kernel/query/predicate.d.ts +9 -0
  225. package/dist/kernel/refs.d.ts +3 -1
  226. package/dist/kernel/sync-policy.d.ts +0 -2
  227. package/dist/kernel/tier-visibility.d.ts +34 -0
  228. package/dist/kernel/types.d.ts +111 -13
  229. package/dist/kernel/vault.d.ts +14 -8
  230. package/dist/kernel/via/index.d.ts +11 -2
  231. package/dist/kernel/via/reconcile.d.ts +12 -0
  232. package/dist/{ledger-AETNF4OM.js → ledger-MQIIOTZB.js} +11 -11
  233. package/dist/liberate-LW7OKVBH.js +25 -0
  234. package/dist/{link-set-E5HNY67I.js → link-set-5PJBBR63.js} +11 -11
  235. package/dist/{managed-secret-CWQ6PND5.js → managed-secret-ETDG6AAE.js} +11 -3
  236. package/dist/materialized-views/index.js +24 -24
  237. package/dist/migrate-cek-V3VDRV24.js +19 -0
  238. package/dist/migrate-cek-V3VDRV24.js.map +1 -0
  239. package/dist/money/index.js +5 -5
  240. package/dist/noydb-LFDRMYZ5.js +85 -0
  241. package/dist/overlay-views/index.js +4 -4
  242. package/dist/periods/index.js +18 -12
  243. package/dist/pod/index.js +79 -89
  244. package/dist/pod-handle-AZ3CXY5Y.js +41 -0
  245. package/dist/pod-handle-AZ3CXY5Y.js.map +1 -0
  246. package/dist/policy/index.js +11 -4
  247. package/dist/port/to/index.d.ts +4 -4
  248. package/dist/port/to/locator.d.ts +54 -8
  249. package/dist/port/with/i18n-strategy.d.ts +4 -1
  250. package/dist/port/with/lookup-strategy.d.ts +4 -1
  251. package/dist/port/with/merge-authority.d.ts +52 -0
  252. package/dist/port/with/service-bus.d.ts +0 -4
  253. package/dist/port/with/strategies.d.ts +2 -0
  254. package/dist/port/with/team-strategy.d.ts +5 -1
  255. package/dist/portability/index.js +8 -8
  256. package/dist/{post-register-2XSSMGEQ.js → post-register-QCJYRMIK.js} +6 -6
  257. package/dist/query/index.js +6 -6
  258. package/dist/reduce/index.js +6 -6
  259. package/dist/register-JBOEHTVX.js +32 -0
  260. package/dist/registry-5DYHQFJS.js +9 -0
  261. package/dist/registry-EANV44W2.js +9 -0
  262. package/dist/registry-J25H6VB4.js +19 -0
  263. package/dist/registry-R23SQUQH.js +18 -0
  264. package/dist/request-withdrawal-KQ4W4UT5.js +31 -0
  265. package/dist/{reveal-BW36KCOQ.js → reveal-W7BKZSUP.js} +6 -6
  266. package/dist/revoke-H3VSTAIE.js +24 -0
  267. package/dist/satellites/index.js +1 -1
  268. package/dist/schema-update/index.js +2 -2
  269. package/dist/sealed-record/index.js +20 -13
  270. package/dist/sealed-record/index.js.map +1 -1
  271. package/dist/search/index.js +4 -4
  272. package/dist/{seed-GDV5PT4R.js → seed-55FPOMYP.js} +20 -22
  273. package/dist/seed-55FPOMYP.js.map +1 -0
  274. package/dist/sequence/index.js +9 -9
  275. package/dist/session/index.js +10 -10
  276. package/dist/shadow/index.js +2 -2
  277. package/dist/share-link/index.js +1 -1
  278. package/dist/signer-53AQ3BU2.js +25 -0
  279. package/dist/snapshots/index.js +10 -10
  280. package/dist/snapshots/index.js.map +1 -1
  281. package/dist/{stale-ARHFVL5U.js → stale-TH7SSVRV.js} +10 -10
  282. package/dist/storage-WSF7ZKTL.js +23 -0
  283. package/dist/{store-coordination-provider-GFCUOBR6.js → store-coordination-provider-R27VRD6K.js} +18 -12
  284. package/dist/store-coordination-provider-R27VRD6K.js.map +1 -0
  285. package/dist/sync/index.js +11 -11
  286. package/dist/team/index.js +15 -14
  287. package/dist/tiers/index.js +11 -10
  288. package/dist/to/index.js +17 -9
  289. package/dist/to/index.js.map +1 -1
  290. package/dist/transactions/index.js +4 -4
  291. package/dist/{ulid-PTAIMDG4.js → ulid-VQW6ERQN.js} +2 -2
  292. package/dist/util/index.js +1 -1
  293. package/dist/vault-head/index.js +115 -0
  294. package/dist/vault-head/index.js.map +1 -0
  295. package/dist/{verify-RO5RTZOJ.js → verify-M5LQH43C.js} +5 -5
  296. package/dist/via/blob/index.d.ts +3 -0
  297. package/dist/via/lookup/handle.d.ts +4 -1
  298. package/dist/walk-NABCHDZN.js +21 -0
  299. package/dist/with-audit/periods/index.d.ts +3 -3
  300. package/dist/with-audit/periods/periods.d.ts +82 -2
  301. package/dist/with-audit/periods/strategy.d.ts +1 -1
  302. package/dist/with-audit/periods/vault-facade.d.ts +54 -1
  303. package/dist/with-audit/periods/window.d.ts +10 -0
  304. package/dist/with-audit/sealed-record/index.d.ts +13 -0
  305. package/dist/with-audit/tiers/index.d.ts +17 -2
  306. package/dist/with-cargo/adopt-partition.d.ts +1 -1
  307. package/dist/with-cargo/extract-partition.d.ts +1 -1
  308. package/dist/with-cargo/index.d.ts +1 -1
  309. package/dist/with-commit/history/history.d.ts +26 -0
  310. package/dist/with-commit/history/index.d.ts +2 -1
  311. package/dist/with-commit/history/ledger/store.d.ts +7 -1
  312. package/dist/with-commit/history/strategy.d.ts +11 -1
  313. package/dist/with-commit/numbering/index.d.ts +0 -5
  314. package/dist/with-commit/vault-head/active.d.ts +2 -0
  315. package/dist/with-commit/vault-head/head.d.ts +28 -0
  316. package/dist/with-commit/vault-head/index.d.ts +10 -0
  317. package/dist/with-commit/vault-head/strategy.d.ts +127 -0
  318. package/dist/with-commit/vault-head/verify.d.ts +90 -0
  319. package/dist/with-formula/materialized-views/dependency-analyzer.d.ts +4 -0
  320. package/dist/with-formula/materialized-views/projection-legs.d.ts +59 -0
  321. package/dist/with-formula/materialized-views/registry.d.ts +50 -0
  322. package/dist/with-formula/materialized-views/types.d.ts +68 -10
  323. package/dist/with-party/directory/cover/storage.d.ts +0 -8
  324. package/dist/with-party/directory/storage.d.ts +0 -11
  325. package/dist/with-party/directory/visibility.d.ts +0 -21
  326. package/dist/with-party/policy/storage.d.ts +0 -10
  327. package/dist/with-party/team/index.d.ts +1 -1
  328. package/dist/with-party/team/keyring.d.ts +139 -2
  329. package/dist/with-party/team/noydb-facade.d.ts +5 -1
  330. package/dist/with-party/team/roster-tag.d.ts +101 -0
  331. package/dist/with-party/team/tiers.d.ts +2 -1
  332. package/dist/with-pod/format.d.ts +10 -12
  333. package/dist/with-pod/index.d.ts +10 -10
  334. package/dist/with-pod/open.d.ts +2 -2
  335. package/dist/with-pod/pod-handle.d.ts +19 -0
  336. package/dist/with-pod/pod-store.d.ts +0 -8
  337. package/dist/with-pod/{bundle.d.ts → pod.d.ts} +11 -19
  338. package/dist/with-pod/ulid.d.ts +1 -1
  339. package/dist/with-shape/blobs/blob-compaction.d.ts +13 -0
  340. package/dist/with-shape/blobs/blob-set.d.ts +83 -11
  341. package/dist/with-shape/blobs/orphan-report.d.ts +62 -0
  342. package/dist/with-shape/introspection/index.d.ts +1 -0
  343. package/dist/with-sync/engine.d.ts +54 -5
  344. package/dist/with-sync/strategy.d.ts +3 -0
  345. package/dist/withdraw-accessible-VCINIG6V.js +28 -0
  346. package/package.json +10 -4
  347. package/dist/api-RXUMEKT3.js +0 -20
  348. package/dist/backup-KULFZ2T4.js.map +0 -1
  349. package/dist/bundle-handle-GFNHT52M.js +0 -36
  350. package/dist/bundle-handle-GFNHT52M.js.map +0 -1
  351. package/dist/chunk-2DHSSLOD.js.map +0 -1
  352. package/dist/chunk-3737A6EA.js.map +0 -1
  353. package/dist/chunk-3IXIU6FP.js.map +0 -1
  354. package/dist/chunk-3URQC7EH.js.map +0 -1
  355. package/dist/chunk-4GZ6XOVW.js.map +0 -1
  356. package/dist/chunk-4I72F5DF.js.map +0 -1
  357. package/dist/chunk-4VUPLMZ6.js.map +0 -1
  358. package/dist/chunk-52JPHN5N.js.map +0 -1
  359. package/dist/chunk-55LKVALY.js.map +0 -1
  360. package/dist/chunk-5JY5TSVY.js.map +0 -1
  361. package/dist/chunk-5ZKS6ZE2.js.map +0 -1
  362. package/dist/chunk-6BU3L4UE.js.map +0 -1
  363. package/dist/chunk-6NVPFKN3.js.map +0 -1
  364. package/dist/chunk-7F4DBNSP.js.map +0 -1
  365. package/dist/chunk-7G6VDWXB.js.map +0 -1
  366. package/dist/chunk-7H73RIE3.js +0 -45
  367. package/dist/chunk-7H73RIE3.js.map +0 -1
  368. package/dist/chunk-7MNBICB5.js.map +0 -1
  369. package/dist/chunk-AFHQATY4.js +0 -47
  370. package/dist/chunk-AFHQATY4.js.map +0 -1
  371. package/dist/chunk-AHLJSVRL.js.map +0 -1
  372. package/dist/chunk-BEFVYAR5.js.map +0 -1
  373. package/dist/chunk-CDB2HVQW.js.map +0 -1
  374. package/dist/chunk-CEJWMBXO.js.map +0 -1
  375. package/dist/chunk-E6427JU2.js.map +0 -1
  376. package/dist/chunk-FFDNKRCY.js.map +0 -1
  377. package/dist/chunk-FZ6NYJ7L.js.map +0 -1
  378. package/dist/chunk-G6S5VVHP.js.map +0 -1
  379. package/dist/chunk-GAG7QOVO.js.map +0 -1
  380. package/dist/chunk-H73G4XF4.js.map +0 -1
  381. package/dist/chunk-HNGSV2YC.js.map +0 -1
  382. package/dist/chunk-IGJCYUT5.js.map +0 -1
  383. package/dist/chunk-IMZLOJTK.js.map +0 -1
  384. package/dist/chunk-J7FM3RAU.js.map +0 -1
  385. package/dist/chunk-JJNOLSG5.js.map +0 -1
  386. package/dist/chunk-JRKZTEZZ.js.map +0 -1
  387. package/dist/chunk-JXIDGFKS.js.map +0 -1
  388. package/dist/chunk-NPP5R7FF.js.map +0 -1
  389. package/dist/chunk-O2ERS4UJ.js.map +0 -1
  390. package/dist/chunk-PDLLCOGD.js.map +0 -1
  391. package/dist/chunk-PL2GHSCM.js.map +0 -1
  392. package/dist/chunk-PNKHAKQ7.js.map +0 -1
  393. package/dist/chunk-PXCBVDFY.js.map +0 -1
  394. package/dist/chunk-Q6TEJXBX.js.map +0 -1
  395. package/dist/chunk-UHXCLPGC.js.map +0 -1
  396. package/dist/chunk-VCETL77O.js.map +0 -1
  397. package/dist/chunk-VZ3XFUQ7.js.map +0 -1
  398. package/dist/chunk-W77KZHCW.js.map +0 -1
  399. package/dist/chunk-WASHZV34.js.map +0 -1
  400. package/dist/chunk-WFUIE565.js.map +0 -1
  401. package/dist/chunk-WK5XUYYF.js.map +0 -1
  402. package/dist/chunk-XWX7GL56.js.map +0 -1
  403. package/dist/chunk-YPYHVOXP.js.map +0 -1
  404. package/dist/chunk-ZJADGNYF.js.map +0 -1
  405. package/dist/collection-facade-QEJIM6BC.js +0 -45
  406. package/dist/delegation-MO7YZYJS.js.map +0 -1
  407. package/dist/derive-IUA6JFLB.js +0 -22
  408. package/dist/dispatch-FZEAWKVM.js.map +0 -1
  409. package/dist/executor-CYJQLKKI.js +0 -9
  410. package/dist/executor-S4QIKEHW.js +0 -9
  411. package/dist/executor-YIQB2S6N.js +0 -29
  412. package/dist/export-accessible-4S36PQNR.js +0 -23
  413. package/dist/extract-partition-IO7FDZ2P.js +0 -38
  414. package/dist/fanout-sidecar-NNAJQXMX.js.map +0 -1
  415. package/dist/find-RBBYKXI7.js +0 -11
  416. package/dist/issue-RIVHSY2S.js +0 -19
  417. package/dist/liberate-GFN4C7RR.js +0 -24
  418. package/dist/noydb-3MT74MZS.js +0 -83
  419. package/dist/register-4EFJCVYD.js +0 -32
  420. package/dist/registry-4SDHHOJ7.js +0 -18
  421. package/dist/registry-CZVINVQH.js +0 -9
  422. package/dist/registry-IKUR2MXD.js +0 -9
  423. package/dist/registry-OYTFGWVK.js +0 -19
  424. package/dist/request-withdrawal-KGXGDPVQ.js +0 -31
  425. package/dist/revoke-JFN773KF.js +0 -24
  426. package/dist/seed-GDV5PT4R.js.map +0 -1
  427. package/dist/signer-TA55QB6R.js +0 -25
  428. package/dist/storage-V7MTFAQJ.js +0 -23
  429. package/dist/store-coordination-provider-GFCUOBR6.js.map +0 -1
  430. package/dist/walk-3ZECBFDA.js +0 -21
  431. package/dist/with-pod/bundle-handle.d.ts +0 -9
  432. package/dist/withdraw-accessible-7PG4DYQK.js +0 -28
  433. /package/dist/{api-RXUMEKT3.js.map → api-6X2VLZ7J.js.map} +0 -0
  434. /package/dist/{chunk-KUDZVJKQ.js.map → chunk-22GR3O4J.js.map} +0 -0
  435. /package/dist/{chunk-CCZJJ4I2.js.map → chunk-2CBFYXJX.js.map} +0 -0
  436. /package/dist/{chunk-FAXZQ5UF.js.map → chunk-323MN67Z.js.map} +0 -0
  437. /package/dist/{chunk-VMCCGUQB.js.map → chunk-36CEG6CM.js.map} +0 -0
  438. /package/dist/{chunk-747LRSOO.js.map → chunk-4K6BIMLF.js.map} +0 -0
  439. /package/dist/{chunk-FNSMZQS4.js.map → chunk-5IHGJHWC.js.map} +0 -0
  440. /package/dist/{chunk-7TSYBD3E.js.map → chunk-65JXA63J.js.map} +0 -0
  441. /package/dist/{chunk-Z45YRGFO.js.map → chunk-6NR36UNB.js.map} +0 -0
  442. /package/dist/{chunk-3JVXVJ7L.js.map → chunk-7OBIBPCV.js.map} +0 -0
  443. /package/dist/{chunk-AR2JDFAE.js.map → chunk-7Q3RHOA5.js.map} +0 -0
  444. /package/dist/{chunk-QULVCV3M.js.map → chunk-AJGGBXWA.js.map} +0 -0
  445. /package/dist/{chunk-CADUYBQD.js.map → chunk-ATL3ZVXT.js.map} +0 -0
  446. /package/dist/{chunk-DMQCLZ4Z.js.map → chunk-ATY3ZASK.js.map} +0 -0
  447. /package/dist/{chunk-4HDYQL3J.js.map → chunk-B4CRUZPR.js.map} +0 -0
  448. /package/dist/{chunk-6SAFL5YE.js.map → chunk-BZ3WMOYX.js.map} +0 -0
  449. /package/dist/{chunk-HXGUIPQB.js.map → chunk-CKKN25P2.js.map} +0 -0
  450. /package/dist/{chunk-6HFM7EIT.js.map → chunk-EHRIDNZX.js.map} +0 -0
  451. /package/dist/{chunk-RTAMLDWP.js.map → chunk-FU5VYEYK.js.map} +0 -0
  452. /package/dist/{chunk-RXYYFSBB.js.map → chunk-GKTW3KLV.js.map} +0 -0
  453. /package/dist/{chunk-OF3L2SD6.js.map → chunk-HOPNIR5R.js.map} +0 -0
  454. /package/dist/{chunk-ADW22QSB.js.map → chunk-HWI7GHJZ.js.map} +0 -0
  455. /package/dist/{chunk-GQ3BX5EA.js.map → chunk-I3ISCYT7.js.map} +0 -0
  456. /package/dist/{chunk-NJDQ4YSV.js.map → chunk-IWQPYT6S.js.map} +0 -0
  457. /package/dist/{chunk-2Z3NCLNX.js.map → chunk-JHYKSMVX.js.map} +0 -0
  458. /package/dist/{chunk-6FJWSWFT.js.map → chunk-JIHWBKMQ.js.map} +0 -0
  459. /package/dist/{chunk-YAWK6AWF.js.map → chunk-JKATP6OE.js.map} +0 -0
  460. /package/dist/{chunk-DG27IUVI.js.map → chunk-LC6NE4IQ.js.map} +0 -0
  461. /package/dist/{chunk-VJFMXYKP.js.map → chunk-MPKP6L5E.js.map} +0 -0
  462. /package/dist/{chunk-FUHKW252.js.map → chunk-OCJ3JA4O.js.map} +0 -0
  463. /package/dist/{chunk-WLYIROCJ.js.map → chunk-OQMCFHUX.js.map} +0 -0
  464. /package/dist/{chunk-JRCYZEHU.js.map → chunk-OR2FYRYR.js.map} +0 -0
  465. /package/dist/{chunk-HNHCQ556.js.map → chunk-PFWE7FJG.js.map} +0 -0
  466. /package/dist/{chunk-U5O6GIWZ.js.map → chunk-POFYIGQ2.js.map} +0 -0
  467. /package/dist/{chunk-35EBKWQU.js.map → chunk-QH47SQLD.js.map} +0 -0
  468. /package/dist/{chunk-HVQGCKY4.js.map → chunk-QVXZFJBU.js.map} +0 -0
  469. /package/dist/{chunk-FMQJZH4R.js.map → chunk-RDB66EKD.js.map} +0 -0
  470. /package/dist/{chunk-X56RTUK3.js.map → chunk-RJZQ2PVD.js.map} +0 -0
  471. /package/dist/{chunk-SUFG5E73.js.map → chunk-RPRASGEY.js.map} +0 -0
  472. /package/dist/{chunk-JIUVJ4M7.js.map → chunk-S7PM7Z4K.js.map} +0 -0
  473. /package/dist/{chunk-N35NC4JH.js.map → chunk-TKBB62DN.js.map} +0 -0
  474. /package/dist/{chunk-4UVDI4XE.js.map → chunk-WPZ5FVAS.js.map} +0 -0
  475. /package/dist/{chunk-MSWYQLMQ.js.map → chunk-XINT4VJA.js.map} +0 -0
  476. /package/dist/{chunk-W3TVWF6N.js.map → chunk-YCGLAANM.js.map} +0 -0
  477. /package/dist/{chunk-FDX7OWWI.js.map → chunk-YYV53EHO.js.map} +0 -0
  478. /package/dist/{classified-marker-2KJAXRRO.js.map → classified-marker-AZDSDG6V.js.map} +0 -0
  479. /package/dist/{collection-facade-QEJIM6BC.js.map → collection-facade-WSUAYFJ4.js.map} +0 -0
  480. /package/dist/{computed-6G5M3UPH.js.map → computed-VG2PCM4L.js.map} +0 -0
  481. /package/dist/{dead-filter-DCB62VWW.js.map → dead-filter-JNQNB3TA.js.map} +0 -0
  482. /package/dist/{derive-IUA6JFLB.js.map → derive-MPOGZ4NR.js.map} +0 -0
  483. /package/dist/{dispatch-MJ6SHB3Y.js.map → dispatch-3ZA733EY.js.map} +0 -0
  484. /package/dist/{enclave-JU4YIEPB.js.map → enclave-Y2ALNDRD.js.map} +0 -0
  485. /package/dist/{executor-CYJQLKKI.js.map → executor-BBEEUFO3.js.map} +0 -0
  486. /package/dist/{executor-S4QIKEHW.js.map → executor-G6G3YEWR.js.map} +0 -0
  487. /package/dist/{executor-YIQB2S6N.js.map → executor-ZUTUMTPA.js.map} +0 -0
  488. /package/dist/{export-accessible-4S36PQNR.js.map → export-accessible-S3KEB763.js.map} +0 -0
  489. /package/dist/{extract-partition-IO7FDZ2P.js.map → extract-partition-KVCTSUVE.js.map} +0 -0
  490. /package/dist/{find-RBBYKXI7.js.map → find-V4FN5ITT.js.map} +0 -0
  491. /package/dist/{issue-RIVHSY2S.js.map → issue-5CFBWBRX.js.map} +0 -0
  492. /package/dist/{ledger-AETNF4OM.js.map → ledger-MQIIOTZB.js.map} +0 -0
  493. /package/dist/{liberate-GFN4C7RR.js.map → liberate-LW7OKVBH.js.map} +0 -0
  494. /package/dist/{link-set-E5HNY67I.js.map → link-set-5PJBBR63.js.map} +0 -0
  495. /package/dist/{managed-secret-CWQ6PND5.js.map → managed-secret-ETDG6AAE.js.map} +0 -0
  496. /package/dist/{noydb-3MT74MZS.js.map → noydb-LFDRMYZ5.js.map} +0 -0
  497. /package/dist/{post-register-2XSSMGEQ.js.map → post-register-QCJYRMIK.js.map} +0 -0
  498. /package/dist/{register-4EFJCVYD.js.map → register-JBOEHTVX.js.map} +0 -0
  499. /package/dist/{registry-4SDHHOJ7.js.map → registry-5DYHQFJS.js.map} +0 -0
  500. /package/dist/{registry-CZVINVQH.js.map → registry-EANV44W2.js.map} +0 -0
  501. /package/dist/{registry-IKUR2MXD.js.map → registry-J25H6VB4.js.map} +0 -0
  502. /package/dist/{registry-OYTFGWVK.js.map → registry-R23SQUQH.js.map} +0 -0
  503. /package/dist/{request-withdrawal-KGXGDPVQ.js.map → request-withdrawal-KQ4W4UT5.js.map} +0 -0
  504. /package/dist/{reveal-BW36KCOQ.js.map → reveal-W7BKZSUP.js.map} +0 -0
  505. /package/dist/{revoke-JFN773KF.js.map → revoke-H3VSTAIE.js.map} +0 -0
  506. /package/dist/{signer-TA55QB6R.js.map → signer-53AQ3BU2.js.map} +0 -0
  507. /package/dist/{stale-ARHFVL5U.js.map → stale-TH7SSVRV.js.map} +0 -0
  508. /package/dist/{storage-V7MTFAQJ.js.map → storage-WSF7ZKTL.js.map} +0 -0
  509. /package/dist/{ulid-PTAIMDG4.js.map → ulid-VQW6ERQN.js.map} +0 -0
  510. /package/dist/{verify-RO5RTZOJ.js.map → verify-M5LQH43C.js.map} +0 -0
  511. /package/dist/{walk-3ZECBFDA.js.map → walk-NABCHDZN.js.map} +0 -0
  512. /package/dist/{withdraw-accessible-7PG4DYQK.js.map → withdraw-accessible-VCINIG6V.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-audit/portability/withdraw-accessible.ts"],"sourcesContent":["/**\n * `unilateralWithdrawal`: a non-owner extracts their accessible scope\n * AND disposes of the source copy. Destructive; gated by the default-off\n * fail-closed built-in `client-unilateral-withdraw` policy (checked in the\n * UserApi wrapper).\n *\n * Two source dispositions:\n * - 'delete' — delete-closure: the records leave the source vault entirely.\n * - 'freeze' — the firm retains a cryptographically-frozen, read-only, write-once\n * snapshot (hash-pinned in the tamper-evident ledger) while the live\n * records are removed.\n *\n * Ordering guarantees no data loss: the client's re-keyed export bundle (and the\n * freeze snapshot) are produced BEFORE anything is deleted.\n *\n * The `freezeAndDeleteClosure` core is shared with the two-party approval path\n * (`request-withdrawal.ts`).\n */\nimport type { Vault } from '../../kernel/vault.js'\nimport { sha256Hex } from '../../kernel/enclave/index.js'\nimport { ReadOnlyError } from '../../kernel/errors.js'\nimport { NOYDB_FORMAT_VERSION } from '../../kernel/types.js'\nimport { resolveAccessibleCollections, buildAccessibleBundle } from './export-accessible.js'\n\nexport const FROZEN_SNAPSHOTS_COLLECTION = '_frozen_snapshots'\nconst ENC = new TextEncoder()\n\n/** 24-hex-char random id (used for withdrawal ids + request ids). */\nexport function randomId(): string {\n const b = globalThis.crypto.getRandomValues(new Uint8Array(12))\n return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')\n}\n\nexport interface FrozenSnapshotRef {\n readonly withdrawalId: string\n readonly sha256: string\n readonly recordCount: number\n readonly frozenAt: string\n}\n\nexport interface WithdrawAccessibleOptions {\n /** Legal/contractual basis recorded in the audit (e.g. 'gdpr-art-17'). */\n readonly legalBasis: string\n /** Re-key the exported bundle to a new owner secret. */\n readonly reKey?: { readonly secret: string }\n /** Source disposition. Default 'delete'. */\n readonly disposition?: 'delete' | 'freeze'\n readonly scope?: { readonly collections?: readonly string[] }\n /** Stable id for idempotent resume (default random). */\n readonly withdrawalId?: string\n}\n\nexport interface WithdrawResult {\n readonly bundle: Uint8Array\n readonly snapshot?: FrozenSnapshotRef\n}\n\n/**\n * Freeze a write-once, hash-pinned snapshot of the current ciphertext for\n * `collections` WITHOUT touching the live records. Returns the snapshot ref.\n *\n * This is the non-destructive core shared by two callers:\n * - `freezeAndDeleteClosure` (withdrawal, disposition `'freeze'`) — which\n * pins the snapshot and THEN delete-closures the live records.\n * - FR-6 `liberateVault` (custody) — which pins a PRE-liberation evidence\n * snapshot but PRESERVES the live data for the new owner (operational\n * continuity; liberation transfers, it does not erase).\n *\n * The snapshot put is write-once (CAS expectedVersion 0) and the ledger pin is\n * appended on success, so a crashed run re-run with the same `withdrawalId` is\n * safe. The snapshot is taken under the vault's own firm-owned DEKs — no re-key.\n */\nexport async function freezeSnapshotOnly(\n vault: Vault,\n collections: readonly string[],\n opts: { actorUserId: string; withdrawalId?: string },\n): Promise<FrozenSnapshotRef> {\n const { name: vaultName, adapter } = vault._introspectState()\n\n // Enumerate the closure (record ids per collection).\n const closure: Array<{ collection: string; id: string }> = []\n for (const c of collections) {\n for (const id of await adapter.list(vaultName, c)) closure.push({ collection: c, id })\n }\n\n const withdrawalId = opts.withdrawalId ?? `wd-${randomId()}`\n const snap: Record<string, Record<string, unknown>> = {}\n for (const { collection, id } of closure) {\n const env = await adapter.get(vaultName, collection, id)\n if (env) (snap[collection] ??= {})[id] = env\n }\n const frozenAt = new Date().toISOString()\n const body = JSON.stringify({ withdrawalId, frozenAt, by: opts.actorUserId, collections: snap })\n const sha = await sha256Hex(ENC.encode(body))\n // Write-once: expectedVersion 0 rejects an overwrite (idempotent resume).\n await adapter.put(\n vaultName,\n FROZEN_SNAPSHOTS_COLLECTION,\n withdrawalId,\n { _noydb: NOYDB_FORMAT_VERSION, _v: 1, _ts: frozenAt, _iv: '', _data: body, _by: opts.actorUserId },\n 0,\n )\n // Hash-pin into the tamper-evident ledger — makes the snapshot provably unaltered.\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle', collection: '', id: '', version: 0, actor: opts.actorUserId, payloadHash: '',\n reason: `withdrawal-frozen-snapshot:${withdrawalId}:${sha}`,\n })\n return { withdrawalId, sha256: sha, recordCount: closure.length, frozenAt }\n}\n\n/**\n * Dispose of the source records for `collections`: optionally freeze a\n * write-once hash-pinned snapshot of the original ciphertext, then\n * delete-closure the live records. Returns the snapshot ref on freeze.\n *\n * Caller MUST have produced the portable bundle FIRST — this is destructive.\n * The delete is best-effort + idempotent (re-deleting an absent record is a\n * no-op) and the snapshot put is write-once (CAS expectedVersion 0), so a\n * crashed run re-run with the same `withdrawalId` is safe.\n */\nexport async function freezeAndDeleteClosure(\n vault: Vault,\n collections: readonly string[],\n opts: { disposition: 'delete' | 'freeze'; actorUserId: string; withdrawalId?: string },\n): Promise<FrozenSnapshotRef | undefined> {\n // freeze: pin a write-once, hash-pinned snapshot BEFORE any delete. The\n // snapshot-only core is shared with FR-6 liberation (which never deletes).\n const snapshot = opts.disposition === 'freeze'\n ? await freezeSnapshotOnly(vault, collections, {\n actorUserId: opts.actorUserId,\n ...(opts.withdrawalId ? { withdrawalId: opts.withdrawalId } : {}),\n })\n : undefined\n\n // delete-closure — only after the snapshot is durable.\n const { name: vaultName, adapter } = vault._introspectState()\n for (const c of collections) {\n for (const id of await adapter.list(vaultName, c)) {\n await vault.collection(c).delete(id)\n }\n }\n\n return snapshot\n}\n\nexport async function withdrawAccessibleData(\n vault: Vault,\n opts: WithdrawAccessibleOptions,\n): Promise<WithdrawResult> {\n const { keyring } = vault._introspectState()\n const disposition = opts.disposition ?? 'delete'\n\n // Owner-class roles hold blanket authority — they use extractPartition.\n if (keyring.role === 'owner' || keyring.role === 'admin') {\n throw new ReadOnlyError(\n 'unilateralWithdrawal is the scoped self-service path; an owner/admin should use extractPartition',\n )\n }\n // FR-6: a custodian must NOT destructively SEVER the vault. It holds the DEKs\n // and operates fully, but ownership is claimed only through the audited\n // Liberate ceremony — never by a one-sided delete/freeze withdrawal. Fires\n // BEFORE the operator rw-scope path below (where a custodian would otherwise\n // be rejected with the wrong \"requires rw access\" message).\n if (keyring.role === 'custodian') {\n throw new ReadOnlyError(\n 'a custodian cannot destructively withdraw/sever; use vault.custody.liberate for an audited ownership claim',\n )\n }\n // client/viewer are read-only by construction (see hasWritePermission): a\n // destructive withdrawal they cannot self-serve — they use the two-party\n // requestWithdrawal flow where firm authority executes the delete-closure.\n if (keyring.role === 'client' || keyring.role === 'viewer') {\n throw new ReadOnlyError(\n 'read-only role cannot self-serve a destructive withdrawal — use requestWithdrawal (two-party)',\n )\n }\n // Operator path: destructive ops need rw on the whole scope.\n const collections = resolveAccessibleCollections(keyring, opts.scope, true)\n if (!collections || collections.length === 0) {\n throw new ReadOnlyError(\n 'unilateralWithdrawal requires rw access on the withdrawn collections — use requestWithdrawal for read-only scope',\n )\n }\n\n // 1. Produce the client's re-keyed portable copy FIRST (nothing destroyed yet).\n const bundle = await buildAccessibleBundle(vault, collections, opts.reKey)\n\n // 2. + 3. freeze (optional) then delete-closure.\n const snapshot = await freezeAndDeleteClosure(vault, collections, {\n disposition, actorUserId: keyring.userId, ...(opts.withdrawalId ? { withdrawalId: opts.withdrawalId } : {}),\n })\n\n // 4. audit\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle', collection: '', id: '', version: 0, actor: keyring.userId, payloadHash: '',\n reason: `user-unilateral-withdrawal:${keyring.userId}:${disposition}:${opts.legalBasis}`,\n })\n\n return snapshot ? { bundle, snapshot } : { bundle }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwBO,IAAM,8BAA8B;AAC3C,IAAM,MAAM,IAAI,YAAY;AAGrB,SAAS,WAAmB;AACjC,QAAM,IAAI,WAAW,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC;AAC9D,SAAO,MAAM,KAAK,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AACtE;AAyCA,eAAsB,mBACpB,OACA,aACA,MAC4B;AAC5B,QAAM,EAAE,MAAM,WAAW,QAAQ,IAAI,MAAM,iBAAiB;AAG5D,QAAM,UAAqD,CAAC;AAC5D,aAAW,KAAK,aAAa;AAC3B,eAAW,MAAM,MAAM,QAAQ,KAAK,WAAW,CAAC,EAAG,SAAQ,KAAK,EAAE,YAAY,GAAG,GAAG,CAAC;AAAA,EACvF;AAEA,QAAM,eAAe,KAAK,gBAAgB,MA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/descriptor.ts","../src/with-lookup/embeddings/vector-set.ts","../src/with-lookup/embeddings/vec-id.ts","../src/with-lookup/search/collection-facade.ts"],"sourcesContent":["/** Cosine similarity in [-1,1]; 0 on zero-norm or length mismatch (no NaN). (L2) */\nexport function cosine(a: Float32Array | number[], b: Float32Array | number[]): number {\n if (a.length !== b.length) return 0\n let dot = 0, na = 0, nb = 0\n for (let i = 0; i < a.length; i++) {\n const x = a[i]!, y = b[i]!\n dot += x * y; na += x * x; nb += y * y\n }\n if (na === 0 || nb === 0) return 0\n return dot / (Math.sqrt(na) * Math.sqrt(nb))\n}\n","/** Per-collection embedding config (L2). The encode hook is host/remote — no bundled model. */\nimport { getAtPath } from '../../via/i18n/core.js'\n\nexport interface EmbeddingDescriptor {\n readonly source: string | readonly string[]\n readonly encode: (text: string) => Promise<Float32Array>\n readonly dim: number\n readonly model: string\n}\n\n/** Concatenate the record's source-field text (skips empties; supports nested/[]-wildcard paths). */\nexport function embeddingSourceText(record: Record<string, unknown>, source: string | readonly string[]): string {\n const fields = typeof source === 'string' ? [source] : source\n const parts: string[] = []\n for (const f of fields) {\n for (const leaf of getAtPath(record, f)) {\n if (typeof leaf === 'string' && leaf !== '') parts.push(leaf)\n }\n }\n return parts.join(' ')\n}\n","/** In-memory vector set for L2 semantic retrieval. Loaded once per session from\n * decrypted _vec sidecars (injected loader), brute-force cosine kNN, model-guarded. */\nimport { cosine } from './cosine.js'\nimport { EmbeddingModelMismatchError } from '../../kernel/errors.js'\n\nexport interface StoredVector { readonly id: string; readonly vec: Float32Array; readonly model: string }\nexport interface VectorHit { readonly id: string; readonly score: number }\n\nexport class VectorSet {\n private vectors: StoredVector[] | undefined\n get loaded(): boolean { return this.vectors !== undefined }\n\n async ensureLoaded(load: () => Promise<StoredVector[]>): Promise<void> {\n if (this.vectors === undefined) this.vectors = await load()\n }\n\n markDirty(): void { this.vectors = undefined }\n\n cosineTopK(query: Float32Array, k: number, opts: { minScore?: number; expectModel?: string } = {}): VectorHit[] {\n const all = this.vectors ?? []\n const minScore = opts.minScore ?? -Infinity\n const hits: VectorHit[] = []\n for (const v of all) {\n if (opts.expectModel !== undefined && v.model !== opts.expectModel) {\n throw new EmbeddingModelMismatchError(opts.expectModel, v.model)\n }\n const score = cosine(query, v.vec)\n if (score >= minScore) hits.push({ id: v.id, score })\n }\n hits.sort((a, b) => b.score - a.score)\n return hits.slice(0, k)\n }\n}\n","/**\n * Collection-namespaced `_vec` side-car ids (#726).\n *\n * `_vec` embedding side-cars used to be keyed by the bare record id,\n * vault-wide — two collections sharing a record id shared one `_vec` row.\n * This was verified to be a clobber/crash bug, NOT a confidentiality leak:\n * every collection has its own DEK, and AES-GCM auth-tag verification means\n * decrypting a foreign collection's `_vec` row under the wrong DEK throws\n * `TamperedError` rather than returning wrong plaintext — no disclosure\n * mechanism exists. The real bug was id collision: a same-id write/forget in\n * one collection could clobber or delete the other collection's row, and a\n * collection whose `similarTo()` / cold semantic `retrieve()` encountered a\n * foreign same-id row crashed with an uncaught `TamperedError` (a DoS). The\n * store-collection bucket stays the literal `'_vec'`; the id becomes\n * composite: `${collection}/${recordId}`. Mirrors `encodeIdxId`\n * (`../indexing/persisted-indexes.js`).\n *\n * Decode is deliberately NOT split-on-`/`: the collection is always known\n * at the decode site (`ctx.name`), so `decodeVecId` strips that known\n * prefix — correct even when `recordId` itself contains `/`.\n *\n * Precondition: `collection` itself must not contain `/` — otherwise\n * `${collection}/${recordId}` is ambiguous (e.g. collection `'a'` would\n * misattribute collection `'a/b'`'s rows via prefix match in `isVecIdFor`).\n * Collection names are NOT currently restricted to a `/`-free charset by\n * `vault.collection()`, so `encodeVecId` enforces the precondition itself,\n * failing loud at the write boundary rather than silently misencoding.\n */\n\n/**\n * Encode the `_vec` side-car id for a (collection, recordId) pair.\n * Format: `<collection>/<recordId>` — no escaping; `recordId` may contain `/`.\n *\n * Throws if `collection` contains `/`: that would make the composite id\n * ambiguous against `isVecIdFor`'s prefix match (collection `'a'` would\n * appear to own collection `'a/b'`'s rows), reintroducing the clobber/crash\n * risk the namespacing fix exists to close.\n */\nexport function encodeVecId(collection: string, recordId: string): string {\n if (collection.includes('/')) {\n throw new Error(\n `encodeVecId: collection name \"${collection}\" must not contain \"/\" — ` +\n `it would make the \"${collection}/${recordId}\" _vec id ambiguous against another collection's rows.`,\n )\n }\n return `${collection}/${recordId}`\n}\n\n/**\n * Decode a `_vec` id back to the bare record id, given the KNOWN owning\n * collection — strips the `<collection>/` prefix rather than splitting on\n * `/`, so a `recordId` containing `/` round-trips correctly. Returns `null`\n * if `vecId` does not belong to `collection`.\n */\nexport function decodeVecId(collection: string, vecId: string): string | null {\n const prefix = `${collection}/`\n if (!vecId.startsWith(prefix)) return null\n return vecId.slice(prefix.length)\n}\n\n/** Predicate form of {@link decodeVecId} — used to filter `list()` results. */\nexport function isVecIdFor(collection: string, vecId: string): boolean {\n return vecId.startsWith(`${collection}/`)\n}\n","/**\n * Collection-level search / retrieval (`search` / `retrieve` / `similarTo` +\n * the lexical-index build/flush/warm machinery).\n *\n * This is the retrieval surface: a pure client-side lexical scan\n * (`search`), the persisted-or-in-memory inverted-index lifecycle\n * (`flushIndex` / `warmIndex` / `buildRetrievalDocs` + the dict-label / blob-\n * filename resolvers that feed it), and the lexical / semantic / hybrid\n * `retrieve` fan-out plus raw-vector kNN (`similarTo`). None of it touches the\n * write path — it reads the live eager cache and the encrypted `_vec` / `_ftindex`\n * side-cars.\n *\n * Every function takes a small {@link SearchContext} instead of `this`,\n * mirroring the `record-keys/` siblings.\n *\n * The `cache` is the SAME `Map` reference `Collection` owns (passed by\n * reference, never copied) so the index always builds over the live working\n * set. {@link buildPersistedIndexCallbacks} is special: it is invoked from the\n * `Collection` constructor *before* `this.codec` exists, so it takes a context\n * THUNK and resolves the context lazily at each callback invocation.\n *\n * Internal service — not exported as a `@noy-db/hub/*` subpath.\n */\nimport type { NoydbStore } from '../../kernel/types.js'\nimport type { RecordCodec } from '../../kernel/enclave/index.js'\nimport { stripI18nFilled, type I18nTextDescriptor } from '../../via/i18n/core.js'\nimport { isStaticDictDescriptor, type DictKeyDescriptor, type StaticDictDescriptor, type DictionaryHandle } from '../../via/i18n/dictionary.js'\nimport type { BlobSet } from '../../with-shape/blobs/blob-set.js'\nimport type { BlobFieldsConfig } from '../../with-shape/blobs/blob-compaction.js'\nimport type { Query } from '../../kernel/query/index.js'\nimport { embeddingSourceText, type VectorSet, type EmbeddingDescriptor, type StoredVector } from '../embeddings/index.js'\nimport { encodeVecId, decodeVecId, isVecIdFor } from '../embeddings/vec-id.js'\nimport { EmbeddingDimMismatchError } from '../../kernel/errors.js'\nimport { liveRecordIsElevated } from '../../kernel/tier-visibility.js'\nimport { searchScan, fuseRetrieval, type SearchOptions, type SearchResult } from './index.js'\nimport type { IndexStore } from './index-store.js'\nimport type { PersistedIndexCallbacks } from './persisted-index-store.js'\nimport { extractSnippet } from './snippet.js'\nimport { buildStringFieldEntries, buildI18nFieldEntries, buildDictKeyFieldEntries, buildBlobFieldEntries } from './build-docs.js'\nimport type { IndexDoc, IndexHit } from './inverted-index.js'\nimport type { RetrieveOptions, RetrieveHit } from './retrieve-types.js'\n\n/** Everything the moving search/retrieval methods touched on `this.*`. */\nexport interface SearchContext<T> {\n /** Collection name — error context + `_ftindex` row key. */\n readonly name: string\n /** Vault namespace the side-cars (`_vec`, `_ftindex`) live under. */\n readonly vault: string\n /** The ciphertext store. */\n readonly adapter: NoydbStore\n /** The record codec — decrypts the `_vec` / `_ftindex` side-car bodies. */\n readonly codec: RecordCodec<T>\n /** The eager working-set cache (SHARED `Map` reference, never copied). */\n readonly cache: Map<string, { record: T; version: number }>\n /** True in lazy mode — search/retrieve/warm require eager mode. */\n readonly lazy: boolean\n /** Declared text-index fields, or undefined. */\n readonly textIndexes: readonly string[] | undefined\n /** Declared i18n fields, or undefined. */\n readonly i18nFields: Record<string, I18nTextDescriptor> | undefined\n /** Declared dictionary-key fields, or undefined. */\n readonly dictKeyFields: Record<string, DictKeyDescriptor | StaticDictDescriptor> | undefined\n /** Declared blob fields, or undefined. */\n readonly blobFields: BlobFieldsConfig | undefined\n /** Dictionary handle resolver (dynamic dict-key labels), or undefined. */\n readonly getDictionary: ((name: string) => Promise<DictionaryHandle>) | undefined\n /** The lexical inverted-index store (in-memory or persisted), or undefined. */\n readonly searchIndexStore: IndexStore | undefined\n /** The vector set for semantic retrieval, or undefined. */\n readonly vectorSet: VectorSet | undefined\n /** The embeddings descriptor, or undefined. */\n readonly embeddings: EmbeddingDescriptor | undefined\n /** Hydrate the eager cache before reading it. */\n ensureHydrated(): Promise<void>\n /** Open the blob facade for a record (used to list indexed blob filenames). */\n blob(id: string): BlobSet\n}\n\n/**\n * Client-side lexical scan over the live eager cache. Eager mode only;\n * nothing searchable is written to the store.\n */\nexport async function search<T>(ctx: SearchContext<T>, field: string, query: string, opts: SearchOptions = {}): Promise<SearchResult<T>[]> {\n if (ctx.lazy) {\n throw new Error(\n `Collection \"${ctx.name}\": search() (scan mode) requires eager mode (prefetch: true). ` +\n `A store-usable blind index for lazy / at-scale search is a separate gated opt-in (#308).`,\n )\n }\n await ctx.ensureHydrated()\n const entries: { id: string; record: T }[] = []\n // Strip the internal densify marker from the user-facing records.\n // Non-mutating: never touches the cached record object. The search index\n // is built over the same (marker-free) record, which is fine — the marker\n // is never a searchable field.\n for (const [id, e] of ctx.cache) entries.push({ id, record: stripI18nFilled(e.record as Record<string, unknown>) as T })\n return searchScan(entries, field, query, opts)\n}\n\n/** L1 — build IndexDoc[] for the configured text fields over the live cache. */\nexport function buildRetrievalDocs<T>(\n ctx: SearchContext<T>,\n labelMaps: Map<string, Map<string, Record<string, string>>>,\n blobFilenames: Map<string, Map<string, string[]>>,\n only?: readonly string[],\n): IndexDoc[] {\n const docs: IndexDoc[] = []\n for (const [id, e] of ctx.cache) {\n const rec = stripI18nFilled(e.record as Record<string, unknown>)\n const fields = buildStringFieldEntries(rec, ctx.textIndexes ?? [], only)\n if (ctx.i18nFields) fields.push(...buildI18nFieldEntries(rec, ctx.i18nFields, ctx.textIndexes ?? [], only))\n if (ctx.dictKeyFields) fields.push(...buildDictKeyFieldEntries(rec, ctx.dictKeyFields, labelMaps, ctx.textIndexes ?? [], only))\n const blobNames = blobFilenames.get(id)\n if (blobNames) fields.push(...buildBlobFieldEntries(blobNames))\n if (fields.length > 0) docs.push({ id, fields })\n }\n return docs\n}\n\n/** L1 — true iff any configured text index is also a blob field (gates ALL slot I/O). */\nexport function hasIndexedBlobFields<T>(ctx: SearchContext<T>, only?: readonly string[]): boolean {\n if (!ctx.blobFields || !ctx.textIndexes) return false\n const fields = only ? ctx.textIndexes.filter((f) => only.includes(f)) : ctx.textIndexes\n return fields.some((f) => f in ctx.blobFields!)\n}\n\n/**\n * L1 — resolve `recordId -> (blobField -> filenames[])` by listing slots\n * for the configured blob fields of each cached record. Blob slot metadata is\n * NOT inline on the record: it lives in a separate `_blob_slots_*` collection,\n * so this costs ONE `blob(id).list()` (a `listSlots`) per record at build time\n * — the heaviest indexing source. Fully gated by {@link hasIndexedBlobFields};\n * non-blob (and blob-but-not-indexed) collections do ZERO slot I/O.\n */\nasync function resolveBlobFilenames<T>(ctx: SearchContext<T>, only?: readonly string[]): Promise<Map<string, Map<string, string[]>>> {\n const out = new Map<string, Map<string, string[]>>()\n if (!hasIndexedBlobFields(ctx, only)) return out\n const indexed = (only ? ctx.textIndexes!.filter((f) => only.includes(f)) : ctx.textIndexes!)\n .filter((f) => f in ctx.blobFields!)\n const indexedSet = new Set(indexed)\n for (const id of ctx.cache.keys()) {\n let slots\n try {\n slots = await ctx.blob(id).list()\n } catch {\n continue\n }\n let byField: Map<string, string[]> | undefined\n for (const slot of slots) {\n if (!indexedSet.has(slot.name) || !slot.filename) continue\n if (!byField) { byField = new Map(); out.set(id, byField) }\n const names = byField.get(slot.name)\n if (names) names.push(slot.filename)\n else byField.set(slot.name, [slot.filename])\n }\n }\n return out\n}\n\n/** L1 — field -> (key -> {locale->label}) for dictKey fields; static from table, dynamic via getDictionary().list(). */\nasync function resolveDictLabelMaps<T>(ctx: SearchContext<T>): Promise<Map<string, Map<string, Record<string, string>>>> {\n const maps = new Map<string, Map<string, Record<string, string>>>()\n if (!ctx.dictKeyFields || !ctx.textIndexes) return maps\n for (const field of ctx.textIndexes) {\n const desc = ctx.dictKeyFields[field]\n if (!desc) continue\n const m = new Map<string, Record<string, string>>()\n if (isStaticDictDescriptor(desc)) {\n for (const [key, labels] of Object.entries(desc.table)) m.set(key, labels as Record<string, string>)\n } else {\n if (ctx.getDictionary) {\n const handle = await ctx.getDictionary(desc.name)\n for (const e of await handle.list()) m.set(e.key, e.labels)\n }\n }\n maps.set(field, m)\n }\n return maps\n}\n\n/** L1.5 — force-persist the lexical index now (e.g. on save/idle). Persists only when textIndexPersist is enabled; a no-op otherwise. */\nexport async function flushIndex<T>(ctx: SearchContext<T>): Promise<void> {\n if (!ctx.searchIndexStore) return\n await ctx.ensureHydrated()\n const labelMaps = await resolveDictLabelMaps(ctx)\n const blobFilenames = await resolveBlobFilenames(ctx)\n await ctx.searchIndexStore.ensureBuilt(() => buildRetrievalDocs(ctx, labelMaps, blobFilenames))\n await ctx.searchIndexStore.flush?.()\n}\n\n/** L2 — load + decrypt all _vec sidecars into StoredVector[] for the VectorSet. */\nfunction buildVectorLoad<T>(ctx: SearchContext<T>): () => Promise<StoredVector[]> {\n return async () => {\n const ids = await ctx.adapter.list(ctx.vault, '_vec')\n const out: StoredVector[] = []\n for (const vecId of ids) {\n // #726: _vec is a vault-wide bucket namespaced by collection prefix —\n // skip rows belonging to other collections before touching this one's.\n if (!isVecIdFor(ctx.name, vecId)) continue\n const id = decodeVecId(ctx.name, vecId)!\n // #721 defense-in-depth: a _vec row carries no _tier of its own; the purge\n // on elevate is best-effort and cannot reach a legacy sidecar, so gate on\n // the owning record's live tier. Envelope peek, no decryption.\n if (await liveRecordIsElevated(ctx.adapter, ctx.vault, ctx.name, id)) continue\n const env = await ctx.adapter.get(ctx.vault, '_vec', vecId)\n if (!env) continue\n // #726 fails-safe: a row can pass isVecIdFor's prefix filter yet still\n // be undecryptable under THIS collection's DEK — a surviving legacy\n // bare-id row whose record id happens to start with `<thisCollection>/`,\n // or plain corruption. _vec sidecars are derived, re-derivable\n // artifacts (embedOnWrite regenerates them on the record's next put()),\n // so best-effort skip is correct: never let one poison row crash\n // similarTo()/retrieve() for the whole collection.\n let body: string | null\n try {\n body = await ctx.codec.decryptJsonString(env)\n } catch {\n continue\n }\n if (body === null) continue\n const parsed = JSON.parse(body) as { vec: number[]; model: string }\n out.push({ id, vec: new Float32Array(parsed.vec), model: parsed.model })\n }\n return out\n }\n}\n\n/**\n * L1.5 — build the PersistedIndexCallbacks bridge: crypto lives here\n * (collection has getDEK / encryptJsonString / decryptJsonString / adapter),\n * the index store itself is crypto-free.\n *\n * Fingerprint encoding: body-wrap approach — save(json, fp) stores\n * JSON.stringify({ fp, idx: json }) as the encrypted body so the standard\n * EncryptedEnvelope shape is never extended. load() decrypts and JSON.parses\n * the wrapper back out.\n *\n * Cache shape: ctx.cache stores { record, version } — currentFingerprint()\n * iterates over e.version.\n *\n * NOTE: this factory is invoked from the `Collection` constructor *before*\n * `this.codec` is assigned, so it takes a context THUNK and resolves the\n * context lazily inside each callback — by the time a callback actually runs,\n * the codec and cache are fully wired.\n */\nexport function buildPersistedIndexCallbacks<T>(provideCtx: () => SearchContext<T>): PersistedIndexCallbacks {\n const FT = '_ftindex'\n return {\n load: async () => {\n const ctx = provideCtx()\n const env = await ctx.adapter.get(ctx.vault, FT, ctx.name)\n if (!env) return null\n const body = await ctx.codec.decryptJsonString(env)\n if (body === null) return null\n try {\n const wrapped = JSON.parse(body) as { fp: { count: number; maxVersion: number }; idx: string }\n return { json: wrapped.idx, fingerprint: wrapped.fp }\n } catch {\n return null\n }\n },\n save: async (json, fp, isStale) => {\n const ctx = provideCtx()\n const body = JSON.stringify({ fp, idx: json })\n const env = await ctx.codec.encryptJsonString(body, fp.count)\n // #725 review: a purge (removePersisted) can land while the encrypt above was\n // in flight — check right before the write and skip it rather than resurrect a\n // purged/forgotten record's blob. PersistedIndexStore's own post-save epoch\n // check is the backstop for every other ordering (incl. a purge landing during\n // this very put).\n if (isStale()) return\n await ctx.adapter.put(ctx.vault, FT, ctx.name, env)\n },\n remove: async () => { const ctx = provideCtx(); await ctx.adapter.delete(ctx.vault, FT, ctx.name) },\n currentFingerprint: () => {\n const ctx = provideCtx()\n let maxVersion = 0\n for (const e of ctx.cache.values()) if (e.version > maxVersion) maxVersion = e.version\n return { count: ctx.cache.size, maxVersion }\n },\n }\n}\n\n/** L1 — pre-build the lexical index (e.g. on open) so the first retrieve() pays no build scan. */\nexport async function warmIndex<T>(ctx: SearchContext<T>): Promise<void> {\n if (!ctx.searchIndexStore) return\n if (ctx.lazy) {\n throw new Error(\n `Collection \"${ctx.name}\": warmIndex() requires eager mode (prefetch: true).`,\n )\n }\n await ctx.ensureHydrated()\n const built = ctx.searchIndexStore.built\n const labelMaps = built ? new Map() : await resolveDictLabelMaps(ctx)\n const blobFilenames = built ? new Map() : await resolveBlobFilenames(ctx)\n await ctx.searchIndexStore.ensureBuilt(() => buildRetrievalDocs(ctx, labelMaps, blobFilenames))\n}\n\n/** Retrieval. mode: 'lexical' (default) | 'semantic' (L2) | 'hybrid' (L3). */\nexport async function retrieve<T>(ctx: SearchContext<T>, query: string, opts: RetrieveOptions<T> = {}): Promise<RetrieveHit<T>[]> {\n const hits =\n opts.mode === 'semantic' ? await retrieveSemantic(ctx, query, opts)\n : opts.mode === 'hybrid' ? await retrieveHybrid(ctx, query, opts)\n : await retrieveLexical(ctx, query, opts)\n return opts.within ? applyWithin(hits, opts.within) : hits\n}\n\n/** L3 — keep only hits whose id matches the structured query, re-rank 1-based. */\nfunction applyWithin<T>(hits: RetrieveHit<T>[], within: Query<T>): RetrieveHit<T>[] {\n const ids = new Set(within._idArray())\n return hits.filter(h => ids.has(h.id)).map((h, i) => ({ ...h, rank: i + 1 }))\n}\n\n/** L1 — client-side lexical retrieval; ranked { id, score, field, snippet, locale? }. */\nasync function retrieveLexical<T>(ctx: SearchContext<T>, query: string, opts: RetrieveOptions<T>): Promise<RetrieveHit<T>[]> {\n if (!ctx.searchIndexStore) {\n throw new Error(`Collection \"${ctx.name}\": retrieve() requires a textIndexes config.`)\n }\n if (ctx.lazy) {\n throw new Error(\n `Collection \"${ctx.name}\": retrieve() requires eager mode (prefetch: true).`,\n )\n }\n await ctx.ensureHydrated()\n const built = ctx.searchIndexStore.built\n const labelMaps = built ? new Map() : await resolveDictLabelMaps(ctx)\n const blobFilenames = built ? new Map() : await resolveBlobFilenames(ctx)\n const index = await ctx.searchIndexStore.ensureBuilt(() => buildRetrievalDocs(ctx, labelMaps, blobFilenames))\n const hits = index.query(query, {\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.match ? { match: opts.match } : {}),\n ...(opts.prefix ? { prefix: opts.prefix } : {}),\n ...(opts.fields ? { fields: opts.fields } : {}),\n })\n const window = opts.snippetWindow ?? 80\n return hits.map((h: IndexHit, i: number) => {\n const base: RetrieveHit<T> = {\n id: h.id,\n score: h.score,\n rank: i + 1,\n field: h.field,\n snippet: extractSnippet(h.text, h.offset, window),\n ...(h.locale !== undefined ? { locale: h.locale } : {}),\n ...(opts.includeRecord\n ? (() => {\n const e = ctx.cache.get(h.id)\n return e ? { record: stripI18nFilled(e.record as Record<string, unknown>) as T } : {}\n })()\n : {}),\n }\n return base\n })\n}\n\n/** L3 — hybrid: fuse lexical (L1) + semantic (L2) by RRF. Requires embeddings. */\nasync function retrieveHybrid<T>(ctx: SearchContext<T>, query: string, opts: RetrieveOptions<T>): Promise<RetrieveHit<T>[]> {\n if (!ctx.embeddings) {\n throw new Error(`Collection \"${ctx.name}\": retrieve({mode:'hybrid'}) requires an embeddings config.`)\n }\n const [lex, sem] = await Promise.all([\n retrieveLexical(ctx, query, opts),\n retrieveSemantic(ctx, query, opts),\n ])\n return fuseRetrieval([lex, sem], opts.limit !== undefined ? { limit: opts.limit } : {})\n}\n\n/** L2 — semantic branch of retrieve(): encode query → similarTo(). */\nasync function retrieveSemantic<T>(ctx: SearchContext<T>, query: string, opts: RetrieveOptions<T>): Promise<RetrieveHit<T>[]> {\n if (!ctx.embeddings) throw new Error(`Collection \"${ctx.name}\": retrieve({mode:'semantic'}) requires an embeddings config.`)\n if (ctx.lazy) throw new Error(`Collection \"${ctx.name}\": retrieve() requires eager mode (prefetch: true).`)\n const qVec = await ctx.embeddings.encode(query)\n return similarTo(ctx, qVec, {\n ...(opts.limit !== undefined ? { k: opts.limit } : {}),\n ...(opts.minScore !== undefined ? { minScore: opts.minScore } : {}),\n ...(opts.includeRecord ? { includeRecord: true } : {}),\n })\n}\n\n/** L2 — raw-vector kNN over the encrypted vector set (decrypted in the trusted tier).\n * Snippet is '' for vector hits in v1 (semantic match isn't span-located). */\nexport async function similarTo<T>(ctx: SearchContext<T>, vector: Float32Array, opts: { k?: number; minScore?: number; includeRecord?: boolean } = {}): Promise<RetrieveHit<T>[]> {\n if (!ctx.embeddings || !ctx.vectorSet) throw new Error(`Collection \"${ctx.name}\": similarTo() requires an embeddings config.`)\n if (ctx.lazy) throw new Error(`Collection \"${ctx.name}\": similarTo() requires eager mode (prefetch: true).`)\n await ctx.ensureHydrated()\n await ctx.vectorSet.ensureLoaded(buildVectorLoad(ctx))\n const hits = ctx.vectorSet.cosineTopK(vector, opts.k ?? 10, {\n ...(opts.minScore !== undefined ? { minScore: opts.minScore } : {}),\n expectModel: ctx.embeddings.model,\n })\n return hits.map((h, i) => {\n const base: RetrieveHit<T> = { id: h.id, score: h.score, rank: i + 1, field: '(vector)', snippet: '' }\n if (opts.includeRecord) { const e = ctx.cache.get(h.id); if (e) (base as { record?: T }).record = stripI18nFilled(e.record as Record<string, unknown>) as T }\n return base\n })\n}\n\n/**\n * L2 — the embedding write-hook: derive a record's embedding vector at\n * write and persist it as the encrypted `_vec` side-car. Routed through the\n * search strategy so it runs only when `withSearch()` is opted in — computing\n * vectors that no gated `similarTo` / semantic `retrieve` could query would be\n * dead weight, so the compute is paired with the search capability. The caller\n * (`Collection.put`) only invokes this when `embeddings` is declared.\n */\nexport async function embedOnWrite<T>(ctx: SearchContext<T>, id: string, record: T, version: number): Promise<void> {\n if (!ctx.embeddings) return\n const text = embeddingSourceText(record as Record<string, unknown>, ctx.embeddings.source)\n const vec = await ctx.embeddings.encode(text)\n if (vec.length !== ctx.embeddings.dim) throw new EmbeddingDimMismatchError('embeddings', ctx.embeddings.dim, vec.length)\n const body = JSON.stringify({ vec: Array.from(vec), model: ctx.embeddings.model, dim: ctx.embeddings.dim })\n const vecEnv = await ctx.codec.encryptJsonString(body, version)\n await ctx.adapter.put(ctx.vault, '_vec', encodeVecId(ctx.name, id), vecEnv)\n ctx.vectorSet?.markDirty()\n}\n\n/**\n * Force-re-derive every eligible tier-0 record's `_vec` sidecar once (#788).\n * Opt-in bulk repair for the #726 re-namespace: legacy bare-id rows are\n * unreachable to `buildVectorLoad` (it only recognises `<collection>/<id>`\n * keys) and otherwise self-heal only when a record is next `put()` — this\n * lets an adopter recover recall immediately instead of waiting on writes.\n *\n * **Skips elevated records** (`liveRecordIsElevated`) rather than refusing\n * the whole walk — the OPPOSITE of `_applyCutoverTransform`'s\n * `assertCutoverTierSafe` refuse-whole-batch precedent. An elevated record is\n * SUPPOSED to have no `_vec` (`syncTierSearch` purges it on elevate);\n * re-embedding one here would write searchable plaintext-derived data above\n * tier 0. Load-bearing: never write a `_vec` row for an elevated record.\n *\n * Tombstones, delete markers, and a raw `get` racing a delete between `list`\n * and `get` all decrypt to `null` (`decryptRecord` already folds\n * tombstone/delete-marker into that null) and are skipped the same way.\n * Unconditional re-derive, no already-migrated check — safe to re-run after\n * a partial failure (each id is independently idempotent).\n */\nexport async function rebuildEmbeddings<T>(ctx: SearchContext<T>): Promise<{ rebuilt: number; skipped: number }> {\n if (!ctx.embeddings) return { rebuilt: 0, skipped: 0 }\n const ids = await ctx.adapter.list(ctx.vault, ctx.name)\n let rebuilt = 0\n let skipped = 0\n for (const id of ids) {\n if (await liveRecordIsElevated(ctx.adapter, ctx.vault, ctx.name, id)) { skipped++; continue }\n const env = await ctx.adapter.get(ctx.vault, ctx.name, id)\n if (!env) { skipped++; continue }\n const decoded = await ctx.codec.decryptRecord(env, { id })\n if (decoded === null) { skipped++; continue }\n await embedOnWrite(ctx, id, decoded, env._v ?? 1)\n rebuilt++\n }\n return { rebuilt, skipped }\n}\n\n/**\n * Sync the collection's SEARCH artifacts after a tier move (#721). Both the\n * lexical `_ftindex` blob and the `_vec/<id>` embedding are encrypted under\n * the tier-0 DEK and hold the record's derived plaintext (full field text /\n * a text-invertible vector), so leaving them means elevation never hid what\n * the record was searchable by — the `forget()` precedent, unapplied to\n * elevate. `null` → the record left tier 0: purge its `_vec` sidecar (mirrors\n * `Collection._purgeVector`), and invalidate the `_ftindex` blob (mirrors\n * `Collection._purgeSearchIndex`: deletes the persisted blob when persisted,\n * else drops the in-memory index) so the next `retrieve()` rebuilds from the\n * elevated-free `ctx.cache`. A record → it is tier-0 again: re-embed it via\n * {@link embedOnWrite}, then invalidate `_ftindex` so the rebuild includes it\n * again. No-op fast when the collection has neither a lexical index nor a\n * vector set.\n */\nexport async function syncTierSearch<T>(\n ctx: SearchContext<T>,\n id: string,\n record: T | null,\n version?: number,\n): Promise<void> {\n if (!ctx.searchIndexStore && !ctx.vectorSet) return\n if (record === null) {\n await ctx.adapter.delete(ctx.vault, '_vec', encodeVecId(ctx.name, id))\n ctx.vectorSet?.markDirty()\n } else {\n await embedOnWrite(ctx, id, record, version ?? 1)\n }\n const store = ctx.searchIndexStore\n if (store && 'removePersisted' in store) await (store as { removePersisted(): Promise<void> }).removePersisted()\n else store?.markDirty()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AACO,SAAS,OAAO,GAA4B,GAAoC;AACrF,MAAI,EAAE,WAAW,EAAE,OAAQ,QAAO;AAClC,MAAI,MAAM,GAAG,KAAK,GAAG,KAAK;AAC1B,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK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KAAsE;AAC/G,MAAI,CAAC,IAAI,WAAY,QAAO,EAAE,SAAS,GAAG,SAAS,EAAE;AACrD,QAAM,MAAM,MAAM,IAAI,QAAQ,KAAK,IAAI,OAAO,IAAI,IAAI;AACtD,MAAI,UAAU;AACd,MAAI,UAAU;AACd,aAAW,MAAM,KAAK;AACpB,QAAI,MAAM,qBAAqB,IAAI,SAAS,IAAI,OAAO,IAAI,MAAM,EAAE,GAAG;AAAE;AAAW;AAAA,IAAS;AAC5F,UAAM,MAAM,MAAM,IAAI,QAAQ,IAAI,IAAI,OAAO,IAAI,MAAM,EAAE;AACzD,QAAI,CAAC,KAAK;AAAE;AAAW;AAAA,IAAS;AAChC,UAAM,UAAU,MAAM,IAAI,MAAM,cAAc,KAAK,EAAE,GAAG,CAAC;AACzD,QAAI,YAAY,MAAM;AAAE;AAAW;AAAA,IAAS;AAC5C,UAAM,aAAa,KAAK,IAAI,SAAS,IAAI,MAAM,CAAC;AAChD;AAAA,EACF;AACA,SAAO,EAAE,SAAS,QAAQ;AAC5B;AAiBA,eAAsB,eACpB,KACA,IACA,QACA,SACe;AACf,MAAI,CAAC,IAAI,oBAAoB,CAAC,IAAI,UAAW;AAC7C,MAAI,WAAW,MAAM;AACnB,UAAM,IAAI,QAAQ,OAAO,IAAI,OAAO,QAAQ,YAAY,IAAI,MAAM,EAAE,CAAC;AACrE,QAAI,WAAW,UAAU;AAAA,EAC3B,OAAO;AACL,UAAM,aAAa,KAAK,IAAI,QAAQ,WAAW,CAAC;AAAA,EAClD;AACA,QAAM,QAAQ,IAAI;AAClB,MAAI,SAAS,qBAAqB,MAAO,OAAO,MAA+C,gBAAgB;AAAA,MAC1G,QAAO,UAAU;AACxB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-formula/materialized-views/executor.ts"],"sourcesContent":["import type { Collection } from '../../kernel/collection.js'\nimport type { TxContext } from '../../with-commit/tx/transaction.js'\nimport type { EncryptedEnvelope } from '../../kernel/types.js'\nimport { MaterializedViewTooLargeError, MaterializedViewConfigError, LocaleNotSpecifiedError, JoinTooLargeError } from '../../kernel/errors.js'\nimport { DEFAULT_JOIN_MAX_ROWS } from '../../kernel/query/join.js'\nimport type { MaterializedFromMeta, MVQueryContext, MaterializedViewSpec } from './types.js'\nimport type { RegisteredMV } from './registry.js'\nimport { wrapDbWithPredicates } from './registry.js'\nimport { groupAndReduce } from '../../with-lookup/reduce/groupby.js'\nimport { canonicalGroupKey } from '../../with-lookup/reduce/canonical-key.js'\nimport { applyI18nLocale, type I18nTextDescriptor } from '../../via/i18n/core.js'\nimport { canonicalizeMoneyFieldsAsDecimal, decodeMoneyFields } from '../../via/money/normalize.js'\nimport { exactMath } from '../../via/money/exact.js'\nimport { putDerivedOutput, type PutDerivedOutputCtx } from '../../kernel/via/dispatch.js'\n\n/**\n * Accessor shape passed in from the owning Vault. Mirrors v1's\n * `DerivationStaleAccessor` — provides the per-collection resolver\n * and the active TxContext so refresh writes/tombstones register on\n * `_executed` for rollback symmetry.\n */\nexport interface MVExecutorAccessor {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getCollection(name: string): Collection<any>\n getActiveTxContext(): TxContext | null\n /**\n * Vault-shaped accessor passed to the MV's `query()` callback at\n * each refresh. Same instance the registry used at registration\n * time; threading through the executor lets the refresh path\n * re-evaluate the closure against the live vault state.\n */\n getQueryContext(): MVQueryContext\n /**\n * #638 Task 5 — ctx for `putDerivedOutput`'s frozen-period skip+audit. #641: the lazy\n * resolve-on-read caller (`stale.ts#resolveStaleMVOnRead`) now supplies one too — built at\n * the `Collection.get()`/`list()` entry point with a `'resolve-on-read'` sentinel id (no\n * real \"reacting write\" for a read-triggered materialize, mirroring `refreshView()`'s\n * `'refreshView'` sentinel). Still declared optional here since `MVExecutorAccessor` is a\n * general shape and a future caller could reasonably omit it.\n */\n dispatchCtx?: PutDerivedOutputCtx\n}\n\nexport interface RefreshResult {\n /** Rows newly written / overwritten. */\n written: number\n /** Rows tombstoned via `_internalDelete` (only when `onEmpty: 'delete'`). */\n deleted: number\n /** Failed row writes (non-strict mode). */\n failed: number\n /** #782/#785 — `outputCollection:id` entries from the tombstone pass whose ownership stamp\n * couldn't be decoded under the collection's default DEK (undecodable, mirroring\n * `invalidateMVAtRest`'s #776 posture) — ownership UNCONFIRMED. Only populated when\n * `onEmpty: 'delete'`. */\n residueUndecodable: string[]\n /** #782/#785 — `outputCollection:id` entries that decoded, stamp-matched this MV, but\n * `_internalDelete` declined (the #718 tier-elevation gate) — ownership CONFIRMED, a real\n * silent survival, surfaced rather than dropped. Only populated when `onEmpty: 'delete'`. */\n residueDeclined: string[]\n}\n\n/** Default cost ceiling — overridable per-MV via `spec.maxRows`. */\nconst DEFAULT_MAX_ROWS = 100_000\n\n/**\n * Materialize a query terminal that may be a `Query<T>` (call\n * `.toArray()`), an `Reduction<R>` (call `.run()` returning a\n * single object — wrap as a one-row array), or a `GroupedReduction<R>`\n * (call `.run()` returning an array of grouped rows). Branches on\n * available terminal at runtime — no type-discrimination at registration.\n */\nasync function materializeQueryResult(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n q: any,\n mvName: string,\n i18nLocale?: string,\n i18nFields?: Record<string, I18nTextDescriptor>,\n): Promise<ReadonlyArray<Record<string, unknown>>> {\n if (typeof q?.toArray === 'function') {\n // Query<T> — non-aggregate path. `.toArray()` returns Promise<T[]>.\n return await q.toArray()\n }\n if (typeof q?.run === 'function') {\n // Reduction<R> or GroupedReduction<R>. `.run()` is synchronous\n // and returns either a single object (Reduction) or an array of\n // rows (GroupedReduction). Promise.resolve() normalizes both\n // sync and async (future) variants.\n // Query-form MV grouping: when the MV declares i18nLocale, pass it +\n // i18nFields so a GroupedReduction resolves i18n group keys before\n // bucketing (the Reduction path ignores the extra arg).\n const runOpts = i18nLocale !== undefined ? { locale: i18nLocale, i18nFields } : undefined\n const result: unknown = await Promise.resolve(q.run(runOpts))\n if (Array.isArray(result)) {\n return result as ReadonlyArray<Record<string, unknown>>\n }\n // Single-aggregate result — wrap as one-row array. The consumer's\n // `rowKey()` should return a stable identity (often a literal\n // constant like `'total'`) since there's only one row.\n return [result as Record<string, unknown>]\n }\n throw new Error(\n `MV \"${mvName}\": query() must return a Query<T>, Reduction, or GroupedReduction. ` +\n `Got something without a .toArray() or .run() terminal.`,\n )\n}\n\n/**\n * Materialize a UNION-form MV: read every arm's source\n * collection, apply each arm's `map` to project rows into the unified\n * MV row shape, concatenate the mapped streams, then optionally run\n * `groupBy` + `aggregate` over the result.\n *\n * Modes (driven by `spec.groupBy` / `spec.aggregate`):\n *\n * - No `groupBy` → return the concatenated mapped rows unchanged.\n * - `groupBy` without `aggregate` → dedupe by composite group key,\n * keep the first row seen per key (later arms don't overwrite\n * earlier arms — Map insertion order rules).\n * - `groupBy` + `aggregate` → delegate to the shared `groupAndReduce`\n * pipeline used by `Query.groupBy().aggregate()`.\n *\n * Per-arm `map` is the schema-unification boundary; the strategy's\n * `TRow` type parameter enforces that every arm projects into the\n * same shape at compile time.\n *\n * @internal\n */\nasync function materializeUnionResult<TRow extends Record<string, unknown>>(\n spec: MaterializedViewSpec<TRow>,\n db: MVQueryContext,\n): Promise<ReadonlyArray<Record<string, unknown>>> {\n const unified: TRow[] = []\n for (const arm of spec.unionSources!) {\n const coll = db.collection<Record<string, unknown>>(arm.collection)\n // Optional per-arm FK joins: chain `.join(field, { as, ... })` for\n // each declared leg before terminating. The aliased right-side\n // record lands at `sourceRow[leg.as]`, where the arm's `map` reads\n // it. Cast to `any` because the chained join widens the row type but\n // the executor treats every row as `Record<string, unknown>` — same\n // pattern the query-form join path uses.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let q: any = coll.query()\n if (arm.join?.length) {\n for (const leg of arm.join) {\n q = q.join(leg.field, { as: leg.as, maxRows: leg.maxRows, strategy: leg.strategy })\n }\n }\n const sourceRows = q.toArray() as ReadonlyArray<Record<string, unknown>>\n for (const r of sourceRows) {\n const mapped = arm.map(r)\n // null / undefined means \"omit this source row\" — skip without\n // pushing so groupBy/aggregate never see a null entry.\n if (mapped == null) continue\n unified.push(mapped)\n }\n }\n\n return finalizeMappedRows(spec, unified)\n}\n\n/**\n * Shared post-map tail for the UNION and projection (#810) forms:\n * optional `groupBy` (+ `aggregate`) over the mapped-row stream.\n * Extracted verbatim from `materializeUnionResult` so both forms feed\n * the identical grouping pipeline — i18n group-key resolution, the\n * object-group-key guard, dedup-without-aggregate, and the shared\n * `groupAndReduce` delegate.\n *\n * @internal\n */\nfunction finalizeMappedRows<TRow extends Record<string, unknown>>(\n spec: MaterializedViewSpec<TRow>,\n unified: TRow[],\n): ReadonlyArray<Record<string, unknown>> {\n if (!spec.groupBy) return unified\n\n const groupFields: readonly string[] =\n typeof spec.groupBy === 'string' ? [spec.groupBy] : spec.groupBy\n\n // i18n-aware group keys. An `i18nText` group field carries a raw\n // `{ locale: string }` map, an unstable object key. When `i18nLocale` is\n // declared (with `i18nFields` describing those fields), resolve the declared\n // group-key i18n fields to it at the `mv` layer FIRST — the same unified-rows\n // boundary where money is threaded — so buckets are stable strings and the\n // `mv`-layer `onMissing` policy fires here.\n if (spec.i18nLocale !== undefined && spec.i18nFields !== undefined) {\n const groupI18n: Record<string, I18nTextDescriptor> = {}\n for (const f of groupFields) {\n const d = spec.i18nFields[f]\n if (d !== undefined) groupI18n[f] = d\n }\n if (Object.keys(groupI18n).length > 0) {\n for (let i = 0; i < unified.length; i++) {\n unified[i] = applyI18nLocale(unified[i] as Record<string, unknown>, groupI18n, spec.i18nLocale, undefined, 'mv') as TRow\n }\n }\n }\n // Guard (always): a remaining object-valued group key — an undeclared i18n\n // field or a locale-less MV — would bucket on a map. Refuse, don't bucket wrong.\n for (const f of groupFields) {\n for (const row of unified) {\n const v = (row as Record<string, unknown>)[f]\n if (v !== null && typeof v === 'object') {\n throw new LocaleNotSpecifiedError(\n f,\n `Materialized view \"${spec.name}\" groups by \"${f}\", whose value is a raw i18n locale map — ` +\n `an unstable object group key. Declare { i18nLocale, i18nFields } on the MV to resolve it at ` +\n `the 'mv' layer, or group by a dictKey/staticDict code (the stable key) and resolve the label at read time.`,\n )\n }\n }\n }\n\n // groupBy without aggregate — dedupe by composite key, keep first\n // seen row per key. Useful for cross-arm uniqueness (e.g. unify two\n // sibling collections, keeping one row per natural key).\n if (!spec.aggregate) {\n const seen = new Map<string, TRow>()\n for (const row of unified) {\n const k = canonicalGroupKey(groupFields, row as Record<string, unknown>)\n if (!seen.has(k)) seen.set(k, row)\n }\n return [...seen.values()]\n }\n\n // groupBy + aggregate — delegate to the shared pipeline used by\n // `Query.groupBy().aggregate()`. Result rows carry each grouped\n // field in declaration order followed by the spec's reducer outputs.\n return groupAndReduce<Record<string, unknown>>(unified, groupFields, spec.aggregate, spec.moneyFields)\n}\n\n/**\n * Apply the spec's `derive` to each finished row (#1007).\n *\n * Three rules, all of them about keeping the hook narrow enough that the\n * engine never has to reason about the function:\n *\n * - a `null` / `undefined` return leaves the row untouched;\n * - a returned key that collides with a `groupBy` field is refused — group\n * keys are the row's identity and feed `rowKey`, so letting `derive`\n * rewrite one would silently re-home the row into a different bucket than\n * the one it was aggregated for;\n * - a derived field declared in `moneyFields` is quantised through its\n * descriptor, so the stored value is exact at the declared scale instead of\n * whatever the user's arithmetic produced.\n *\n * @internal\n */\nfunction applyDerive<TRow extends Record<string, unknown>>(\n spec: MaterializedViewSpec<TRow>,\n rows: ReadonlyArray<Record<string, unknown>>,\n): ReadonlyArray<Record<string, unknown>> {\n const groupFields = new Set<string>(\n spec.groupBy === undefined ? [] : typeof spec.groupBy === 'string' ? [spec.groupBy] : spec.groupBy,\n )\n return rows.map((row) => {\n // `derive` sees the row the way a READER would: money decoded to its\n // canonical decimal form, not the scaled integer the reducer left behind.\n // Handing over `1005` where the schema says `10.05` would make every\n // derived money expression quietly wrong by a factor of the scale.\n // `'raw'` keeps it at the exact decimal rather than a locale-formatted\n // string, which is what `exact.*` consumes.\n const view = spec.moneyFields ? decodeMoneyFields(row, spec.moneyFields, 'raw') : row\n const patch = spec.derive!(view as TRow, exactMath)\n if (patch === null || patch === undefined) return row\n for (const key of Object.keys(patch)) {\n if (groupFields.has(key)) {\n throw new MaterializedViewConfigError(\n `Materialized view \"${spec.name}\": derive() returned the group key \"${key}\". ` +\n 'A group key is the row\\'s identity and feeds rowKey — rewriting it would re-home the ' +\n 'row into a bucket it was not aggregated for. Emit a differently-named field instead.',\n )\n }\n }\n // Canonicalize the PATCH only, into the DECIMAL form the money-aware\n // reducers emit — not the scaled-integer storage form a collection uses.\n // An MV row's money fields are decimal strings, so a derived field\n // quantised into storage form reads back as the scaled integer beside\n // correctly-decoded siblings: `\"1000000\"` next to `\"10000.00\"` (#1018).\n // Precision is still enforced; only the output shape differs.\n const canonical = spec.moneyFields\n ? canonicalizeMoneyFieldsAsDecimal(patch, spec.moneyFields)\n : patch\n return { ...row, ...canonical }\n })\n}\n\n/**\n * Materialize a projection-form MV (#810): hydrate the primary source\n * rows, resolve forward FK legs through the same `.join()` machinery\n * the UNION arms use, attach reverse \"collect\" legs via one\n * hash-grouped snapshot pass per leg, then run the projection `map`\n * (null / undefined omits the primary row) and the shared post-map\n * grouping tail.\n *\n * @internal\n */\nasync function materializeProjectionResult<TRow extends Record<string, unknown>>(\n spec: MaterializedViewSpec<TRow>,\n db: MVQueryContext,\n): Promise<ReadonlyArray<Record<string, unknown>>> {\n const projection = spec.projection!\n const coll = db.collection<Record<string, unknown>>(projection.source)\n // Forward legs chain through the query builder exactly like UNION arm\n // joins — ref() resolution, dangling-mode semantics, presentation\n // dressing, and ceilings all ride the existing `.join()` path. Cast to\n // `any` for the same reason `materializeUnionResult` does.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let q: any = coll.query()\n for (const leg of projection.joins) {\n if ('collect' in leg) continue\n q = q.join(leg.field, { as: leg.as, maxRows: leg.maxRows, strategy: leg.strategy })\n }\n let rows = q.toArray() as Array<Record<string, unknown>>\n for (const leg of projection.joins) {\n if (!('collect' in leg)) continue\n rows = applyCollectLeg(rows, leg, spec.name, projection.source, db)\n }\n const mapped: TRow[] = []\n for (const r of rows) {\n const m = projection.map(r)\n // null / undefined means \"omit this primary row\" — same contract\n // as the UNION arm `map`.\n if (m == null) continue\n mapped.push(m)\n }\n return finalizeMappedRows(spec, mapped)\n}\n\n/**\n * Attach one reverse \"collect\" leg (#810): every row of `leg.collect`\n * whose `leg.on` field references a primary record's id lands in a\n * possibly-empty ARRAY under `leg.as` on that primary row. One\n * snapshot pass over the collect collection, hash-grouped by the `on`\n * FK — O(N+M), mirroring the forward hash-join fallback.\n *\n * Semantic check (first materialization, not factory time — parity\n * with join-time ref errors): `leg.on` must carry a `ref()` declared\n * on the collect collection targeting the projection `source`.\n *\n * @internal\n */\nfunction applyCollectLeg(\n primaryRows: ReadonlyArray<Record<string, unknown>>,\n leg: { readonly collect: string; readonly on: string; readonly as: string; readonly maxRows?: number },\n mvName: string,\n source: string,\n db: MVQueryContext,\n): Array<Record<string, unknown>> {\n const childColl = db.collection<Record<string, unknown>>(leg.collect)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const childQ = childColl.query() as any\n const refDesc = childQ._joinContext?.()?.resolveRef(leg.on) as { target: string } | null | undefined\n if (refDesc == null) {\n throw new MaterializedViewConfigError(\n `\"${mvName}\": projection collect leg \"${leg.as}\" requires a ref() on field \"${leg.on}\" of `\n + `collection \"${leg.collect}\" targeting \"${source}\" — declare `\n + `refs: { ${leg.on}: ref('${source}') } on collection \"${leg.collect}\", then retry`,\n )\n }\n if (refDesc.target !== source) {\n throw new MaterializedViewConfigError(\n `\"${mvName}\": projection collect leg \"${leg.as}\" expects field \"${leg.on}\" of collection `\n + `\"${leg.collect}\" to reference the projection source \"${source}\", but its ref() targets `\n + `\"${refDesc.target}\"`,\n )\n }\n const maxRows = leg.maxRows ?? DEFAULT_JOIN_MAX_ROWS\n const groups = new Map<string, Array<Record<string, unknown>>>()\n for (const child of childQ.toArray() as Array<Record<string, unknown>>) {\n const key = coerceCollectKey(child[leg.on])\n // Nullish / non-scalar FK values mean \"no reference\" — same\n // narrowing as the forward join path's key coercion.\n if (key === null) continue\n const bucket = groups.get(key)\n if (bucket) bucket.push(child)\n else groups.set(key, [child])\n }\n const out: Array<Record<string, unknown>> = []\n for (const row of primaryRows) {\n const key = coerceCollectKey(row.id)\n const children = key === null ? [] : groups.get(key) ?? []\n if (children.length > maxRows) {\n throw new JoinTooLargeError({\n leftRows: primaryRows.length,\n rightRows: children.length,\n maxRows,\n side: 'right',\n message:\n `projection MV \"${mvName}\": collect leg \"${leg.as}\" gathered ${children.length} ` +\n `\"${leg.collect}\" rows for one \"${source}\" record, exceeding the ${maxRows}-row ` +\n `per-primary-row ceiling. Raise the ceiling via { maxRows } on the leg if the ` +\n `fan-out genuinely fits in memory, or restructure the child collection.`,\n })\n }\n out.push({ ...row, [leg.as]: children })\n }\n return out\n}\n\n/**\n * Coerce an unknown FK value into a collect-grouping key. Same\n * narrowing as the join path's `coerceRefKey` (not exported from\n * there): strings and numbers are legitimate ref values; anything\n * else is \"no reference\" and returns `null`.\n *\n * @internal\n */\nfunction coerceCollectKey(value: unknown): string | null {\n if (value === null || value === undefined) return null\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'bigint') return String(value)\n return null\n}\n\n/**\n * Run an MV's `query()` and write the result rows to the output\n * collection. Same-DEK encryption: routes through the standard\n * `Collection.put` pipeline, so the output collection's DEK is what\n * gets used (matches the v2 spec's \"same DEK as the left-most source\"\n * invariant — `Collection.put` looks up the DEK by collection name,\n * and the output collection IS the MV's owned collection).\n *\n * Stamps `_materializedFrom` onto every emitted row.\n *\n * **Tombstoning:** when `spec.onEmpty: 'delete'` (default), rows\n * that existed in a prior refresh but no longer appear in the new\n * materialized result are deleted via `Collection._internalDelete` —\n * the housekeeping bypass primitive prevents user\n * `onDelete` guards on the output collection from firing on these\n * system-internal deletes. `onEmpty: 'keep'` opts out (rows from\n * prior refreshes linger even when the new result lacks them).\n *\n * **Cost ceiling:** if the materialized row count exceeds\n * `spec.maxRows` (default 100k), throws `MaterializedViewTooLargeError`\n * before any writes hit the store — so strict-mode rollback is\n * clean.\n *\n * **Strict mode:** `spec.strict === true` re-throws on any\n * row-write failure; the active TxContext registration means the\n * source-write rolls back atomically via `revertExecuted`.\n *\n * @internal\n */\nexport const MaterializedViewExecutor = {\n async refresh(\n reg: RegisteredMV,\n accessor: MVExecutorAccessor,\n ): Promise<RefreshResult> {\n const spec = reg.spec\n const outputColl = accessor.getCollection(reg.outputCollection)\n const maxRows = spec.maxRows ?? DEFAULT_MAX_ROWS\n const onEmpty = spec.onEmpty ?? 'delete'\n const strict = spec.strict ?? false\n\n // 1. Materialize the query (branches on terminal shape). If the\n // MV declared predicates, wrap the query context the same way\n // the registry did at registration time so `.wherePredicate()`\n // calls resolve to the registered functions.\n const baseCtx = accessor.getQueryContext()\n const ctxForQuery: MVQueryContext = spec.predicates\n ? wrapDbWithPredicates(baseCtx, spec.predicates)\n : baseCtx\n // UNION-form strategies: read every arm, map to the unified\n // row shape, concatenate, then optionally groupBy + aggregate.\n // Projection-form strategies (#810): hydrate the primary source,\n // attach forward + collect legs, map, then the same optional\n // grouping tail. The single-source `query()` path is untouched.\n let rows: ReadonlyArray<Record<string, unknown>>\n if (spec.unionSources) {\n rows = await materializeUnionResult(spec, ctxForQuery)\n } else if (spec.projection) {\n rows = await materializeProjectionResult(spec, ctxForQuery)\n } else {\n const q = spec.query!(ctxForQuery)\n rows = await materializeQueryResult(q, spec.name, spec.i18nLocale, spec.i18nFields)\n }\n\n // #1007 — the post-aggregate projection. Applied here, after every form has\n // produced its finished rows, so union / projection / query all get the\n // same single definition of \"last step before materialisation\".\n if (spec.derive) rows = applyDerive(spec, rows)\n\n // #777 — exclude this MV's OWN previously-stamped output rows from the\n // input scan. A same-collection Query-form MV copies the whole source row\n // verbatim into its output, so a stale output row can itself satisfy the\n // MV's own input filter (when the filter is on a field disjoint from the\n // partition field) and get re-selected as if it were live source — the\n // row self-perpetuates after its true source is gone. Prior output is\n // never this MV's own source.\n rows = rows.filter((row) => {\n const stamp = row._materializedFrom as { mvName?: string } | undefined\n return stamp?.mvName !== spec.name\n })\n\n // 2. Cost ceiling check BEFORE any writes — keeps the rollback\n // clean if the source-write is wrapped in a transaction.\n if (rows.length > maxRows) {\n throw new MaterializedViewTooLargeError(spec.name, rows.length, maxRows)\n }\n\n const txCtx = accessor.getActiveTxContext()\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const adapter = (outputColl as any).adapter as {\n get(v: string, c: string, i: string): Promise<EncryptedEnvelope | null>\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const vaultName = (outputColl as any).vault as string\n\n // 3. Compute the post-refresh id set so we can diff against the\n // prior-emitted id set for tombstoning (when onEmpty === 'delete').\n const newIds = new Set<string>()\n const enrichedRows: Array<{ id: string; record: Record<string, unknown> }> = []\n for (const row of rows) {\n const id = spec.rowKey(row)\n newIds.add(id)\n const meta: MaterializedFromMeta = {\n mvName: spec.name,\n queryHash: reg.queryHash,\n sourceVersions: {},\n materializedAt: new Date().toISOString(),\n }\n enrichedRows.push({ id, record: { ...row, _materializedFrom: meta } })\n }\n\n // 4. Write the new rows.\n let written = 0\n let failed = 0\n for (const { id, record } of enrichedRows) {\n try {\n if (txCtx !== null) {\n const prior = await adapter.get(vaultName, reg.outputCollection, id)\n txCtx._executed.push({\n op: { type: 'put', vaultName, collectionName: reg.outputCollection, id },\n priorEnvelope: prior,\n })\n }\n if (accessor.dispatchCtx) {\n if (await putDerivedOutput(outputColl, id, record, accessor.dispatchCtx) === 'written') written++\n } else {\n await outputColl.put(id, record)\n written++\n }\n } catch (err) {\n failed++\n if (strict) throw err\n \n console.warn(`[mv] \"${spec.name}\" row write failed:`, err)\n }\n }\n\n // 5. Tombstone rows that existed before but don't appear now.\n // `onEmpty: 'keep'` skips this pass entirely. Uses\n // `_internalDelete` so a user-registered `onDelete` on the\n // output collection does NOT fire on housekeeping (composition fix).\n let deleted = 0\n const residueUndecodable: string[] = []\n const residueDeclined: string[] = []\n if (onEmpty === 'delete') {\n const priorIds = await listOutputIds(outputColl)\n for (const priorId of priorIds) {\n if (newIds.has(priorId)) continue\n // #762 — a same-collection partition MV (`output: { collection: <source>, partition }`,\n // the DERIV-PP30-001 shape) writes INTO its own source collection, so `listOutputIds`\n // also returns untouched USER source rows here. Decode each candidate and only\n // tombstone rows THIS MV stamped via `_materializedFrom.mvName` — the exact discipline\n // `invalidateMVAtRest` uses (stale.ts:151-162). An unstamped row, or one stamped by a\n // different MV, is never this MV's to delete.\n const priorEnvelope = await adapter.get(vaultName, reg.outputCollection, priorId)\n if (priorEnvelope === null) continue\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const priorDecoded = await (outputColl as any)._decodeEnvelope(priorEnvelope, priorId)\n if (priorDecoded === null) {\n // #782 part a — ownership unknown (undecodable, e.g. elevated above tier 0 on a\n // tiered output collection): can't rule out this being THIS MV's own stamped row.\n // Surface it rather than silently skip (mirrors invalidateMVAtRest's #776 posture —\n // previously this leg had NO residue channel at all).\n residueUndecodable.push(`${reg.outputCollection}:${priorId}`)\n continue\n }\n const priorStampedBy =\n typeof priorDecoded === 'object'\n ? (priorDecoded as Record<string, unknown>)._materializedFrom as { mvName?: string } | undefined\n : undefined\n if (priorStampedBy?.mvName !== spec.name) continue\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const outAny = outputColl as any\n if (typeof outAny._internalDelete === 'function') {\n // #776 part b — gate on the boolean, matching invalidateMVAtRest's discipline\n // (stale.ts): `_internalDelete` returns `false` for a #718 elevated-skip (no\n // erasure happened), and that must not inflate the tombstone count.\n if (await outAny._internalDelete(priorId, txCtx)) {\n deleted++\n } else {\n // #782 part b — decoded AND stamp-owned, but erasure was declined (#718\n // tier-elevation gate). Ownership IS confirmed here — a real silent survival,\n // not a legit stamp-mismatch skip. Surface it too.\n residueDeclined.push(`${reg.outputCollection}:${priorId}`)\n }\n } else {\n // Defensive fallback — should never hit in real flow since\n // every Collection has `_internalDelete`.\n await outputColl.delete(priorId)\n deleted++\n }\n } catch (err) {\n failed++\n if (strict) throw err\n\n console.warn(`[mv] \"${spec.name}\" tombstone failed for id=\"${priorId}\":`, err)\n }\n }\n }\n\n return { written, deleted, failed, residueUndecodable, residueDeclined }\n },\n}\n\n/**\n * List ids currently present in the MV's output collection via the\n * adapter directly (avoids triggering the lazy resolve-on-read path\n * we're INSIDE). Returns an empty array if the collection doesn't\n * exist or the adapter doesn't surface a list method.\n *\n * @internal\n */\nasync function listOutputIds(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n outputColl: Collection<any>,\n): Promise<string[]> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const cAny = outputColl as any\n const adapter = cAny.adapter as { list?: (v: string, c: string) => Promise<readonly string[]> }\n const vault = cAny.vault as string\n const name = cAny.name as string\n if (typeof adapter?.list !== 'function') return []\n try {\n const ids = await adapter.list(vault, name)\n return [...ids]\n } catch {\n return []\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,IAAM,mBAAmB;AASzB,eAAe,uBAEb,GACA,QACA,YACA,YACiD;AACjD,MAAI,OAAO,GAAG,YAAY,YAAY;AAEpC,WAAO,MAAM,EAAE,QAAQ;AAAA,EACzB;AACA,MAAI,OAAO,GAAG,QAAQ,YAAY;AAQhC,UAAM,UAAU,eAAe,SAAY,EAAE,QAAQ,YAAY,WAAW,IAAI;AAChF,UAAM,SAAkB,MAAM,QAAQ,QAAQ,EAAE,IAAI,OAAO,CAAC;AAC5D,QAAI,MAAM,QAAQ,MAAM,GAAG;AACzB,aAAO;AAAA,IACT;AAIA,WAAO,CAAC,MAAiC;AAAA,EAC3C;AACA,QAAM,IAAI;AAAA,IACR,OAAO,MAAM;AAAA,EAEf;AACF;AAuBA,eAAe,uBACb,MACA,IACiD;AACjD,QAAM,UAAkB,CAAC;AACzB,aAAW,OAAO,KAAK,cAAe;AACpC,UAAM,OAAO,GAAG,WAAoC,IAAI,UAAU;AAQlE,QAAI,IAAS,KAAK,MAA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,QAAQ,oBAAoB,gBAAgB;AAAA,EACzE;AACF;AAUA,eAAe,cAEb,YACmB;AAEnB,QAAM,OAAO;AACb,QAAM,UAAU,KAAK;AACrB,QAAM,QAAQ,KAAK;AACnB,QAAM,OAAO,KAAK;AAClB,MAAI,OAAO,SAAS,SAAS,WAAY,QAAO,CAAC;AACjD,MAAI;AACF,UAAM,MAAM,MAAM,QAAQ,KAAK,OAAO,IAAI;AAC1C,WAAO,CAAC,GAAG,GAAG;AAAA,EAChB,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-pod/pod-store.ts","../src/with-pod/redirect.ts","../src/with-pod/open.ts"],"sourcesContent":["import type { NoydbStore, NoydbPodStore, VaultSnapshot, EncryptedEnvelope } from '../kernel/types.js'\nimport { ConflictError, PodVersionConflictError } from '../kernel/errors.js'\n\n// ─── Bundle format ─────────────────────────────────────────────────────\n\nconst BUNDLE_STORE_VERSION = 1 as const\n\n/**\n * Wire format written by `wrapPodStore`. A JSON-serialised object that\n * contains the entire `VaultSnapshot` (all encrypted envelopes) plus a small\n * header for integrity checking. The envelopes inside are already AES-GCM\n * encrypted by core — the bundle bytes themselves are not additionally\n * encrypted, but they are safe to store on untrusted blob hosts because\n * every record inside is already ciphertext.\n *\n * @internal\n */\ninterface BundleStoreData {\n readonly _noydb_bundle_store: typeof BUNDLE_STORE_VERSION\n readonly vault: string\n readonly ts: string\n readonly data: VaultSnapshot\n}\n\n// ─── Options ───────────────────────────────────────────────────────────\n\nexport interface WrapPodStoreOptions {\n /**\n * When `true` (default), every `put()` and `delete()` flushes the full\n * vault snapshot to the bundle backend. Set to `false` for bulk operations\n * and call `store.flush(vaultId)` manually.\n */\n autoFlush?: boolean\n}\n\n// ─── Extended NoydbStore with flush/batch ───────────────────────────────\n\nexport interface WrappedPodNoydbStore extends NoydbStore {\n /** Manually flush the in-memory snapshot to the bundle backend. */\n flush(vaultId: string): Promise<void>\n /**\n * Run a batch of mutations without flushing until the callback completes.\n * A single flush is performed at the end.\n */\n batch(vaultId: string, fn: () => Promise<void>): Promise<void>\n}\n\n// ─── wrapPodStore ───────────────────────────────────────────────────\n\nconst MAX_CONFLICT_RETRIES = 3\n\n/**\n * Convert a `NoydbPodStore` (blob-oriented read/write with OCC) into the\n * standard six-method `NoydbStore` interface expected by `createNoydb({ store })`.\n *\n * Bundle stores operate on the entire vault as a single serialised unit —\n * ideal for backends like Google Drive, WebDAV, or iCloud Drive that work\n * best with whole-file I/O rather than per-record KV operations.\n *\n * ## Optimistic concurrency\n *\n * The wrapper tracks the `version` token from the last `readBundle` and\n * passes it as `expectedVersion` on every flush. On\n * `PodVersionConflictError`, it re-reads, merges the remote snapshot\n * (last-write-wins per record key), and retries (max 3 attempts).\n *\n * ## Flush modes\n *\n * By default, flushes on every mutation (O(vault size) per write). Options:\n * - `autoFlush: false` + explicit `store.flush(vaultId)` calls\n * - `store.batch(vaultId, async () => { ... })` — defers flush until end\n * - Pair with `syncPolicy: { push: { mode: 'debounce' } }` from \n */\nexport function wrapPodStore(\n bundle: NoydbPodStore,\n options?: WrapPodStoreOptions,\n): WrappedPodNoydbStore {\n const autoFlush = options?.autoFlush !== false\n\n // Per-vault state\n const snapshots = new Map<string, VaultSnapshot>()\n const versions = new Map<string, string | null>()\n const loaded = new Set<string>()\n\n // Batch mode: when > 0, suppress auto-flush\n let batchDepth = 0\n\n // #908 — in-flight loads, keyed by vault. Without this, every concurrent\n // caller issued its own `readBundle` and then REPLACED `snapshots` with a\n // freshly parsed object — orphaning the mutations earlier callers had\n // already made to the object they were handed. 100 racing puts kept 1.\n const loading = new Map<string, Promise<VaultSnapshot>>()\n\n async function load(vault: string): Promise<VaultSnapshot> {\n if (loaded.has(vault)) return snapshots.get(vault)!\n\n const inFlight = loading.get(vault)\n if (inFlight) return inFlight\n\n const pending = (async () => {\n const result = await bundle.readBundle(vault)\n if (result) {\n const text = new TextDecoder().decode(result.bytes)\n const format = JSON.parse(text) as BundleStoreData\n snapshots.set(vault, format.data)\n versions.set(vault, result.version)\n } else {\n snapshots.set(vault, {})\n versions.set(vault, null)\n }\n\n loaded.add(vault)\n return snapshots.get(vault)!\n })()\n\n loading.set(vault, pending)\n try {\n return await pending\n } finally {\n // Clear on failure too, so a transient read error does not poison\n // every later load of this vault with a rejected promise.\n loading.delete(vault)\n }\n }\n\n async function flush(vault: string): Promise<void> {\n const snapshot = snapshots.get(vault) ?? {}\n const format: BundleStoreData = {\n _noydb_bundle_store: BUNDLE_STORE_VERSION,\n vault,\n ts: new Date().toISOString(),\n data: snapshot,\n }\n const bytes = new TextEncoder().encode(JSON.stringify(format))\n const expectedVersion = versions.get(vault) ?? null\n\n for (let attempt = 0; attempt < MAX_CONFLICT_RETRIES; attempt++) {\n try {\n const { version: newVersion } = await bundle.writeBundle(vault, bytes, expectedVersion)\n versions.set(vault, newVersion)\n return\n } catch (err) {\n if (err instanceof PodVersionConflictError && attempt < MAX_CONFLICT_RETRIES - 1) {\n // Pull remote, merge (last-write-wins by record key), retry\n const remote = await bundle.readBundle(vault)\n if (remote) {\n const remoteText = new TextDecoder().decode(remote.bytes)\n const remoteFormat = JSON.parse(remoteText) as BundleStoreData\n const localSnap = snapshots.get(vault) ?? {}\n const mergedSnap = mergeSnapshots(remoteFormat.data, localSnap)\n snapshots.set(vault, mergedSnap)\n versions.set(vault, remote.version)\n }\n // Re-encode with merged data for the retry\n continue\n }\n throw err\n }\n }\n }\n\n // #908 — one flush at a time per vault. `flush` reads and writes the vault's\n // version token, so concurrent flushes race: each sends the same\n // `expectedVersion`, the losers take the conflict/merge path, and with enough\n // of them the retry budget is exhausted and the error surfaces to a caller\n // whose write was perfectly valid. Serialising makes every flush see the\n // token its predecessor produced.\n const flushChain = new Map<string, Promise<void>>()\n\n function serialFlush(vault: string): Promise<void> {\n const prev = flushChain.get(vault) ?? Promise.resolve()\n // Chain past a rejection as well — one failed flush must not wedge every\n // subsequent write to this vault.\n const next = prev.then(() => flush(vault), () => flush(vault))\n flushChain.set(vault, next)\n return next\n }\n\n async function maybeFlush(vault: string): Promise<void> {\n if (autoFlush && batchDepth === 0) {\n await serialFlush(vault)\n }\n }\n\n const store: WrappedPodNoydbStore = {\n name: bundle.name ?? 'bundle',\n\n async flush(vaultId: string): Promise<void> {\n await serialFlush(vaultId)\n },\n\n async batch(vaultId: string, fn: () => Promise<void>): Promise<void> {\n await load(vaultId) // ensure loaded before batch\n batchDepth++\n try {\n await fn()\n } finally {\n batchDepth--\n }\n await serialFlush(vaultId)\n },\n\n async get(vault: string, collection: string, id: string): Promise<EncryptedEnvelope | null> {\n const snap = await load(vault)\n return snap[collection]?.[id] ?? null\n },\n\n async put(\n vault: string,\n collection: string,\n id: string,\n envelope: EncryptedEnvelope,\n expectedVersion?: number,\n ): Promise<void> {\n const snap = await load(vault)\n\n if (expectedVersion !== undefined) {\n const current = snap[collection]?.[id]\n const currentVersion = current?._v ?? 0\n if (currentVersion !== expectedVersion) {\n throw new ConflictError(\n currentVersion,\n `Expected version ${expectedVersion} but found ${currentVersion} on ${collection}/${id}`,\n )\n }\n }\n\n snap[collection] ??= {}\n snap[collection][id] = envelope\n await maybeFlush(vault)\n },\n\n async delete(vault: string, collection: string, id: string): Promise<void> {\n const snap = await load(vault)\n if (snap[collection]) {\n delete snap[collection][id]\n await maybeFlush(vault)\n }\n },\n\n async list(vault: string, collection: string): Promise<string[]> {\n const snap = await load(vault)\n return Object.keys(snap[collection] ?? {})\n },\n\n async loadAll(vault: string): Promise<VaultSnapshot> {\n const snap = await load(vault)\n // #908 — two contract fixes in one place:\n // 1. internal collections (`_keyring`, `_sync`) are the vault's own\n // bookkeeping and must not appear in a snapshot — `@noy-db/to-file`\n // sets the reference behaviour with this same `_`-prefix rule;\n // 2. copy rather than hand out the live cache, which let a caller\n // mutating the result silently rewrite the wrapper's own state.\n // `get()`/`list()` still serve internal collections; this is about what\n // a *snapshot* claims, not about hiding data.\n const out: VaultSnapshot = {}\n for (const [collection, records] of Object.entries(snap)) {\n if (collection.startsWith('_')) continue\n out[collection] = { ...records }\n }\n return out\n },\n\n async saveAll(vault: string, data: VaultSnapshot): Promise<void> {\n snapshots.set(vault, data)\n loaded.add(vault)\n await serialFlush(vault)\n },\n }\n\n return store\n}\n\n// ─── Snapshot merge (last-write-wins per record) ────────────────────────\n\nfunction mergeSnapshots(remote: VaultSnapshot, local: VaultSnapshot): VaultSnapshot {\n const merged: VaultSnapshot = {}\n\n // Start with all remote collections\n for (const [coll, records] of Object.entries(remote)) {\n merged[coll] = { ...records }\n }\n\n // Overlay local collections — LWW by _ts per record\n for (const [coll, records] of Object.entries(local)) {\n if (!merged[coll]) {\n merged[coll] = { ...records }\n continue\n }\n for (const [id, envelope] of Object.entries(records)) {\n const existing = merged[coll][id]\n if (!existing || envelope._ts >= existing._ts) {\n merged[coll][id] = envelope\n }\n }\n }\n\n return merged\n}\n\n// ─── Factory helper ─────────────────────────────────────────────────────\n\n/**\n * Type-safe factory helper for `NoydbPodStore` implementations,\n * analogous to `createStore` for KV stores.\n */\nexport function createPodStore<TOptions>(\n factory: (options: TOptions) => NoydbPodStore,\n): (options: TOptions) => NoydbPodStore {\n return factory\n}\n\n// ─── Deprecated aliases (pre-rename compatibility) ──────────────────────\n\n/** @deprecated Use wrapPodStore. */\nexport const wrapBundleStore = wrapPodStore\n/** @deprecated Use createPodStore. */\nexport const createBundleStore = createPodStore\n/** @deprecated Use WrappedPodNoydbStore. */\nexport type WrappedBundleNoydbStore = WrappedPodNoydbStore\n/** @deprecated Use WrapPodStoreOptions. */\nexport type WrapBundleStoreOptions = WrapPodStoreOptions\n","/**\n * Redirect record (#944) — a signed \"this moved, go there\" pointer carried\n * in the pod's PLAINTEXT header (`NoydbPodHeader.redirect`, see\n * `format.ts`) so a dispatcher can follow it pre-auth: no secret, no\n * decompression.\n *\n * The record carries its OWN inner `sig` (via `signRecord`/`verifyRecord`\n * from `signature.ts`) — independent from, and in addition to, the #943\n * pod-header signature. A Redirect is REQUIRED to be signed: there is no\n * legacy unsigned install base for this new record type, so an absent or\n * invalid signature is invalid for following, not merely \"unverified\".\n *\n * Minimum-disclosure: the record is kept to exactly\n * `{ v, target, reason, issuedBy, sig }` — no timestamps, no identities\n * beyond the signer's `keyId` fingerprint.\n */\n\nimport type { DocSigner } from '../with-audit/attestation/signer.js'\nimport { signRecord, verifyRecord } from './signature.js'\nimport { readPodRedirect } from './bundle.js'\nimport {\n RedirectBadSignatureError,\n RedirectDepthExceededError,\n RedirectLoopError,\n RedirectUnreachableError,\n} from '../kernel/errors.js'\n\n/**\n * A signed pointer to another pod. `target` is a locator string or URL —\n * the forthcoming #945 `Locator` type isn't built yet, so `target` stays a\n * plain string for now (forward-seam noted, not blurred: a Redirect says\n * \"go elsewhere once\"; a Locator will say \"where cargo lives\").\n */\nexport interface Redirect {\n readonly v: 1\n readonly target: string\n readonly reason: 'moved' | 'release' | 'tombstone' | 'repoint'\n readonly issuedBy: string\n readonly sig: string\n}\n\n/**\n * Sign a new Redirect record with `signer`. Builds the record minus `sig`,\n * signs it via the #943 `signRecord` convention, and returns the complete\n * signed record.\n */\nexport async function signRedirect(\n signer: DocSigner,\n fields: { readonly target: string; readonly reason: Redirect['reason'] },\n): Promise<Redirect> {\n const record = {\n v: 1 as const,\n target: fields.target,\n reason: fields.reason,\n issuedBy: signer.keyId,\n }\n const sig = await signRecord(signer.privateKeyPkcs8B64, record)\n return { ...record, sig }\n}\n\n/**\n * Verify a Redirect record's signature against `trustedKeys`\n * (`keyId → publicKeyB64`). Fails closed: an `issuedBy` not present in\n * `trustedKeys` is untrusted/unverifiable and returns `false`, same as a\n * tampered or forged signature.\n */\nexport async function verifyRedirect(\n record: Redirect,\n trustedKeys: Readonly<Record<string, string>>,\n): Promise<boolean> {\n const publicKeyB64 = trustedKeys[record.issuedBy]\n if (publicKeyB64 === undefined) return false\n const payload = { v: record.v, target: record.target, reason: record.reason, issuedBy: record.issuedBy }\n return verifyRecord(publicKeyB64, record.sig, payload)\n}\n\n/** One followed hop's provenance — surfaced so a UI can show \"moved from X via Y\". */\nexport interface RedirectHop {\n readonly target: string\n readonly reason: Redirect['reason']\n readonly issuedBy: string\n}\n\n/** Result of {@link followRedirects}: the terminal (non-redirect) pod's bytes, plus the ordered hop list that led there. */\nexport interface FollowRedirectsResult {\n readonly terminal: Uint8Array\n readonly hops: readonly RedirectHop[]\n}\n\n/**\n * Follow a chain of Redirect records starting from `start`'s pod bytes,\n * fetching each hop's target via `fetcher`, until a pod with no `redirect`\n * header field (the terminal) is reached.\n *\n * HTTP-redirect discipline: each hop's Redirect is verified against\n * `opts.trustedKeys` BEFORE it is followed (fail closed — an untrusted or\n * forged hop never advances the walk), loops are detected on the target\n * about to be followed, and the hop count is capped at `opts.maxDepth`\n * (default 8). `fetcher` throwing or returning `null` for a target means\n * that hop is unreachable.\n *\n * @throws {RedirectBadSignatureError} a hop's Redirect fails verification.\n * @throws {RedirectLoopError} a hop's target was already followed in this chain.\n * @throws {RedirectDepthExceededError} more than `maxDepth` hops were followed.\n * @throws {RedirectUnreachableError} `fetcher` threw or returned `null` for a target.\n */\nexport async function followRedirects(\n start: Uint8Array,\n fetcher: (target: string) => Promise<Uint8Array | null>,\n opts: { readonly trustedKeys: Readonly<Record<string, string>>; readonly maxDepth?: number },\n): Promise<FollowRedirectsResult> {\n const maxDepth = opts.maxDepth ?? 8\n let current = start\n const hops: RedirectHop[] = []\n const visited = new Set<string>()\n\n for (;;) {\n const rec = readPodRedirect(current)\n if (rec === undefined) return { terminal: current, hops }\n\n if (!(await verifyRedirect(rec, opts.trustedKeys))) {\n throw new RedirectBadSignatureError(rec.target)\n }\n if (visited.has(rec.target)) {\n throw new RedirectLoopError(rec.target)\n }\n visited.add(rec.target)\n\n hops.push({ target: rec.target, reason: rec.reason, issuedBy: rec.issuedBy })\n if (hops.length > maxDepth) {\n throw new RedirectDepthExceededError(maxDepth)\n }\n\n let next: Uint8Array | null\n try {\n next = await fetcher(rec.target)\n } catch (cause) {\n throw new RedirectUnreachableError(rec.target, cause)\n }\n if (next === null) {\n throw new RedirectUnreachableError(rec.target)\n }\n current = next\n }\n}\n","/**\n * `open(podBytesOrFile)` — the pod READ-path orchestrator (#941 Task 4).\n *\n * A free function (never a `Vault` method — `kernel/vault.ts` is at its\n * line ceiling and open() needs no vault-internal state that isn't already\n * reachable through published seams). Composes, in order:\n *\n * 1. `readPod` — parse + integrity-check the container (throws\n * `BundleIntegrityError` on a corrupted/truncated pod).\n * 2. `verifyPodHeader` — only when `opts.trustedKeys` is supplied.\n * `'unsigned'` is benign (legacy pod, or `writePod({ sign: false })`)\n * and open() proceeds; `'untrusted'` / `'tampered'` are fail-closed —\n * `PodHeaderVerificationError` — mirroring `followRedirects`'s\n * `RedirectBadSignatureError` posture: once a caller opts into\n * verification, an unverifiable header is a hard stop.\n * 3. `createNoydb` + `openVault` + `vault.load(dumpJson)` — the exact\n * unlock+restore sequence `bundle-roundtrip.test.ts` drives by hand.\n * The pod header carries no vault name (minimum-disclosure —\n * `format.ts`'s forbidden-fields list), so the caller names the\n * target vault via `opts.vault`.\n * 4. Re-derive the `SchemaManifest` from the just-restored `_schemas/*`\n * (the source of truth — Task 3's `deriveSchemaManifest`), via a\n * NON-MINTING `LookupDEK` built from `loadKeyring`'s already-unwrapped\n * `UnlockedKeyring.deks` map directly (`with-party/team/keyring.js`).\n * **Not** `ensureCollectionDEK` (#941 review fix — Important 2): that\n * helper mints+persists a fresh DEK into `_keyring/<user>` for any\n * collection absent from the keyring, which is correct for a WRITE\n * path but wrong here — `deriveSchemaManifest` only ever reads\n * collections that already have a `_schemas` envelope, so an absent\n * DEK means \"this principal can't decrypt this sibling\" (e.g. a\n * collection-scoped grantee), never \"new collection.\" The old\n * minting call polluted a scoped principal's freshly-restored keyring\n * with garbage sibling DEKs on every `open()`. The returned\n * `manifest` is that principal's own visible slice — see\n * `derive.ts`'s `LookupDEK` doc and `sync.ts`'s module doc for the\n * full rationale (the same distinction governs why the sync path\n * must SKIP rather than write a partial manifest).\n * 5. Generation check (AC #4 coexistence): compare the HIGHEST\n * per-collection generation stamp carried by the restored manifest\n * against THIS store's schema-fence generation as it stood\n * immediately before the restore (0 for a brand-new vault; whatever a\n * coexisting local vault already had). If the pod is ahead and\n * `!opts.allowGenerationAhead`, throw `MigrationRequiredError` (the\n * same class `SchemaFenceController`'s write-path gate throws) — the\n * reader hasn't reconciled schema changes that happened elsewhere.\n * `allowGenerationAhead: true` is the documented dev override: open\n * proceeds, with a console warning. Divergence in the OTHER direction\n * (reader ahead of the pod) is non-fatal but also warned (#941\n * review, Important 3 — AC #4 coexistence divergence must be\n * observable in either direction, not just the bypass case).\n *\n * NOTE: this deliberately reads per-collection entries, not\n * `manifest.generation` itself. `_meta/schema-fence` is local\n * session-coordination state and does NOT travel in a pod dump\n * (`with-pod/backup.ts`'s reserved-collection list carries `_schemas`\n * and `_manifest` but not `_meta`) — a fresh re-derive's top-level\n * `generation` is always driven by the (untouched-by-restore) target\n * store's own fence, not the pod's. Each `_schemas/<collection>`\n * envelope's own `generation` field DOES travel (it's stamped at\n * declare-time from the writer's real fence), so per-collection\n * entries are the only signal that survives a restore intact.\n *\n * @module\n */\n\nimport { readPod, verifyPodHeader } from './bundle.js'\nimport type { NoydbPodHeader } from './format.js'\nimport type { PodVerifyResult } from './bundle.js'\nimport { createNoydb } from '../kernel/noydb.js'\nimport type { Noydb } from '../kernel/noydb.js'\nimport type { Vault } from '../kernel/vault.js'\nimport type { NoydbOptions, NoydbStore, EchoSecretParts } from '../kernel/types.js'\nimport { MigrationRequiredError, PodHeaderVerificationError } from '../kernel/errors.js'\nimport { loadKeyring } from '../with-party/team/keyring.js'\nimport { loadFence } from '../with-shape/schema-update/fence.js'\nimport { deriveSchemaManifest, type LookupDEK } from '../with-shape/manifest/derive.js'\nimport type { SchemaManifest } from '../with-shape/manifest/types.js'\n\nexport interface OpenPodOptions {\n /** The ciphertext store to restore into (and where the opened `Vault` lives). */\n readonly store: NoydbStore\n /**\n * The target vault name. The pod header deliberately carries no vault\n * name (minimum-disclosure — `NoydbPodHeader`'s forbidden-fields list),\n * so the caller names the vault to restore into/open.\n */\n readonly vault: string\n /** User identifier — passed through to `createNoydb`. */\n readonly user: string\n /** That user's secret — passed through to `createNoydb` / `loadKeyring`. */\n readonly secret: string | EchoSecretParts\n /**\n * Trusted signing keys (`keyId → publicKeyB64`). When supplied,\n * `verifyPodHeader` runs and its result is returned as `verification`.\n * Omitted → no verification attempted, `verification` is absent.\n */\n readonly trustedKeys?: Readonly<Record<string, string>>\n /**\n * Passthrough to `createNoydb` for every option beyond `store`/`user`/\n * `secret` (history/indexing/blobs/… strategies, `secretMode`, etc.).\n */\n readonly noydbOptions?: Omit<NoydbOptions, 'store' | 'user' | 'secret'>\n /**\n * Dev override for the generation-ahead fence (AC #4). Default `false`:\n * a pod whose schema manifest generation is ahead of this store's\n * pre-restore fence generation throws `MigrationRequiredError`. `true`\n * opens anyway, logging a console warning.\n */\n readonly allowGenerationAhead?: boolean\n}\n\nexport interface OpenPodResult {\n readonly db: Noydb\n readonly vault: Vault\n readonly header: NoydbPodHeader\n /** Present iff `opts.trustedKeys` was supplied. */\n readonly verification?: PodVerifyResult\n /** The pod's schema manifest, re-derived from the just-restored `_schemas/*`. */\n readonly manifest?: SchemaManifest\n}\n\n/**\n * Open a `.noydb` pod: verify its integrity (and, opt-in, its signature),\n * unlock + restore it into `opts.vault`, and re-derive its schema manifest.\n * See the module doc for the full flow and the errors each step can throw.\n */\nexport async function open(podFileOrBytes: Uint8Array, opts: OpenPodOptions): Promise<OpenPodResult> {\n const { header, dumpJson } = await readPod(podFileOrBytes)\n\n let verification: PodVerifyResult | undefined\n if (opts.trustedKeys !== undefined) {\n verification = await verifyPodHeader(podFileOrBytes, opts.trustedKeys)\n if (verification.status === 'untrusted' || verification.status === 'tampered') {\n throw new PodHeaderVerificationError(verification.status, verification.keyId)\n }\n }\n\n // Reader's pre-restore generation snapshot (see module doc, step 5) —\n // must be read from the raw store BEFORE vault.load() overwrites it.\n const readerGeneration = (await loadFence(opts.store, opts.vault)).currentSchemaVersion\n\n const db = await createNoydb({ ...opts.noydbOptions, store: opts.store, user: opts.user, secret: opts.secret })\n const vault = await db.openVault(opts.vault)\n await vault.load(dumpJson)\n\n // #941 review fix: a NON-MINTING lookup, not `ensureCollectionDEK` (which\n // mints+persists a fresh DEK for any collection absent from the keyring).\n // open() is a READ path — deriveSchemaManifest only ever iterates\n // collections that already have a `_schemas` envelope, so an absent DEK\n // here means \"this principal cannot decrypt this sibling,\" never \"new\n // collection.\" The old minting call polluted a scoped principal's just-\n // restored `_keyring/<user>` file with garbage sibling DEKs on every\n // open(). See `derive.ts`'s `LookupDEK` doc for the full rationale.\n const keyring = await loadKeyring(opts.store, opts.vault, { userId: opts.user, secret: opts.secret })\n const lookupDEK: LookupDEK = async (name) => keyring.deks.get(name)\n const { manifest, undecodableCollections } = await deriveSchemaManifest(opts.store, opts.vault, lookupDEK)\n\n // A scoped principal's `manifest` is legitimately their own visible\n // slice (see `sync.ts`'s module doc) — `open()` is a per-principal read,\n // not an assertion of pod-wide completeness. `undecodableCollections` is\n // intentionally not surfaced on `OpenPodResult` (out of this fix's\n // scope); callers that need it can call `deriveSchemaManifest` directly.\n void undecodableCollections\n\n // See module doc, step 5 — the pod's generation signal is the highest\n // per-collection stamp, not the (locally re-derived, fence-driven)\n // top-level `manifest.generation`.\n const podGeneration = Object.values(manifest.collections)\n .reduce((max, entry) => Math.max(max, entry.generation), 0)\n\n if (podGeneration > readerGeneration) {\n if (!opts.allowGenerationAhead) {\n throw new MigrationRequiredError(\n `open(): pod's schema generation (${podGeneration}) is ahead of vault ` +\n `\"${opts.vault}\"'s local generation (${readerGeneration}). Pass ` +\n `\\`allowGenerationAhead: true\\` to open anyway, or reconcile the schema first.`,\n )\n }\n console.warn(\n `[noy-db] open(): vault \"${opts.vault}\" opened with allowGenerationAhead — pod schema ` +\n `generation ${podGeneration} is ahead of the local generation ${readerGeneration}.`,\n )\n } else if (podGeneration < readerGeneration) {\n // #941 review (Important 3, AC #4): divergence in EITHER direction\n // should be observable, not just the ahead-bypass case above. The\n // reader being ahead of the pod is non-fatal (the pod is simply older\n // content) but silent coexistence divergence is exactly what AC #4\n // asks to surface — same `[noy-db]`-prefixed console.warn facility as\n // `sync.ts`'s cap-exhaustion warning.\n console.warn(\n `[noy-db] open(): vault \"${opts.vault}\"'s local schema generation (${readerGeneration}) is ` +\n `ahead of the pod's (${podGeneration}) — the pod reflects an earlier schema than this reader.`,\n )\n }\n\n return { db, vault, header, manifest, ...(verification !== undefined ? { verification } : {}) }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,IAAM,uBAAuB;AA4C7B,IAAM,uBAAuB;AAwBtB,SAAS,aACd,QACA,SACsB;AACtB,QAAM,YAAY,SAAS,cAAc;AAGzC,QAAM,YAAY,oBAAI,IAA2B;AACjD,QAAM,WAAW,oBAAI,IAA2B;AAChD,QAAM,SAAS,oBAAI,IAAY;AAG/B,MAAI,aAAa;AAMjB,QAAM,UAAU,oBAAI,IAAoC;AAExD,iBAAe,KAAK,OAAuC;AACzD,QAAI,OAAO,IAAI,KAAK,EAAG,QAAO,UAAU,IAAI,KAAK;AAEjD,UAAM,WAAW,QAAQ,IAAI,KAAK;AAClC,QAAI,SAAU,QAAO;AAErB,UAAM,WAAW,YAAY;AAC3B,YAAM,SAAS,MAAM,OAAO,WAAW,KAAK;AAC5C,UAAI,QAAQ;AACV,cAAM,OAAO,IAAI,YAAY,EAAE,OAAO,OAAO,KAAK;AAClD,cAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,kBAAU,IAAI,OAAO,OAAO,IAAI;AAChC,iBAAS,IAAI,OAAO,OAAO,OAAO;AAAA,MACpC,OAAO;AACL,kBAAU,IAAI,OAAO,CAAC,CAAC;AACvB,iBAAS,IAAI,OAAO,IAAI;AAAA,MAC1B;AAEA,aAAO,IAAI,KAAK;AAChB,aAAO,UAAU,IAAI,KAAK;AAAA,IAC5B,GAAG;AAEH,YAAQ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