@noy-db/hub 0.6.0-pre.21 → 0.6.0-pre.23

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 (360) hide show
  1. package/CHANGELOG.md +238 -0
  2. package/dist/api-ETB5Y4DY.js +20 -0
  3. package/dist/attestation/index.js +16 -16
  4. package/dist/{backup-FSC36VWC.js → backup-UOLAXOJ4.js} +10 -10
  5. package/dist/blobs/index.js +20 -18
  6. package/dist/blobs/index.js.map +1 -1
  7. package/dist/broker/index.js +10 -10
  8. package/dist/cargo/index.js +28 -28
  9. package/dist/{chunk-3B6S6RSI.js → chunk-22VRCUV2.js} +2 -2
  10. package/dist/{chunk-ESKIAXO2.js → chunk-23ODLABM.js} +4 -4
  11. package/dist/{chunk-IJ46VCWD.js → chunk-2DHEBIJA.js} +2 -2
  12. package/dist/{chunk-TMBSPLUG.js → chunk-2LHPMFSR.js} +2 -2
  13. package/dist/{chunk-ONVD6GBY.js → chunk-2QN6NPV6.js} +2 -2
  14. package/dist/{chunk-NW4TY6VC.js → chunk-3UIS6O6N.js} +3 -3
  15. package/dist/{chunk-LXECF2ZR.js → chunk-3ZOER5GD.js} +6 -2
  16. package/dist/chunk-3ZOER5GD.js.map +1 -0
  17. package/dist/{chunk-EKEIEJL6.js → chunk-4UZDDS4S.js} +3 -3
  18. package/dist/{chunk-S56VYR4Q.js → chunk-5FRZ7YYU.js} +2 -2
  19. package/dist/{chunk-H3G4I3PN.js → chunk-5MU7PUNA.js} +2 -2
  20. package/dist/{chunk-NCCEDL2K.js → chunk-66X4XWTM.js} +6 -6
  21. package/dist/{chunk-TQPASLY4.js → chunk-6G4NORTR.js} +2 -2
  22. package/dist/{chunk-RKCRPPNB.js → chunk-6W3BZCW6.js} +3 -3
  23. package/dist/{chunk-DVRZYAGT.js → chunk-6ZN6X2LW.js} +4 -4
  24. package/dist/{chunk-PPCOKVFA.js → chunk-6ZTPSVY7.js} +2 -2
  25. package/dist/{chunk-MZTUTEHP.js → chunk-7DRKK5FQ.js} +3 -3
  26. package/dist/{chunk-GBBDFE6C.js → chunk-7LWBD3NO.js} +2 -2
  27. package/dist/{chunk-KX57HODD.js → chunk-7W765AVV.js} +6 -6
  28. package/dist/{chunk-LN7P6MZB.js → chunk-7ZPAL3F7.js} +2 -2
  29. package/dist/{chunk-CAGI4LLJ.js → chunk-AK6EWGDO.js} +5 -5
  30. package/dist/chunk-AK6EWGDO.js.map +1 -0
  31. package/dist/{chunk-CADUYBQD.js → chunk-ATL3ZVXT.js} +2 -2
  32. package/dist/{chunk-RSXQNFGO.js → chunk-ATSIGJRX.js} +2 -2
  33. package/dist/{chunk-MSLPDFK2.js → chunk-AZPPARMG.js} +6 -6
  34. package/dist/{chunk-NR2SUJ3H.js → chunk-B3X6S37C.js} +2 -2
  35. package/dist/{chunk-GWO2IDAB.js → chunk-BNGGSNO7.js} +2 -2
  36. package/dist/{chunk-JLYQQNY4.js → chunk-BYX3AUXH.js} +80 -22
  37. package/dist/chunk-BYX3AUXH.js.map +1 -0
  38. package/dist/{chunk-INMHEMXX.js → chunk-C7B3XUI4.js} +2 -2
  39. package/dist/{chunk-D3R7Q4QK.js → chunk-CJU3KXHJ.js} +2 -2
  40. package/dist/{chunk-RFO4UXKQ.js → chunk-CWYTN4IK.js} +5 -5
  41. package/dist/{chunk-HR5R5JOM.js → chunk-D5DZ4R7X.js} +2 -2
  42. package/dist/{chunk-6YD5SYQS.js → chunk-DEKA2MV3.js} +2 -2
  43. package/dist/{chunk-SYS46BL7.js → chunk-DG4KFJNA.js} +2 -2
  44. package/dist/{chunk-P2MR5UNE.js → chunk-DRVF2YS5.js} +55 -16
  45. package/dist/chunk-DRVF2YS5.js.map +1 -0
  46. package/dist/{chunk-B6IYATME.js → chunk-DXJXVWWE.js} +6 -6
  47. package/dist/{chunk-O742QBZZ.js → chunk-DZBZCFS7.js} +5 -5
  48. package/dist/{chunk-FW7NGYLT.js → chunk-FNCX4N7X.js} +4 -4
  49. package/dist/{chunk-OHOKBMTM.js → chunk-FUE2KPKM.js} +6 -6
  50. package/dist/{chunk-YALD3SST.js → chunk-G4577GK7.js} +4 -4
  51. package/dist/{chunk-DIZ6HM7Q.js → chunk-G6DAESDS.js} +5 -5
  52. package/dist/{chunk-HYYVT2KZ.js → chunk-GAZTPQ3D.js} +2 -2
  53. package/dist/{chunk-LX46B56Q.js → chunk-GJ5TMHKC.js} +4 -4
  54. package/dist/{chunk-KRVS7YWY.js → chunk-GNSLP7KA.js} +2 -2
  55. package/dist/{chunk-CWM4GQD2.js → chunk-HKANJAOP.js} +28 -5
  56. package/dist/chunk-HKANJAOP.js.map +1 -0
  57. package/dist/{chunk-5Q7AJ7DN.js → chunk-I3D67XD7.js} +4 -4
  58. package/dist/{chunk-GQ3BX5EA.js → chunk-I3ISCYT7.js} +2 -2
  59. package/dist/{chunk-HQSPF5IY.js → chunk-ISRAQIYY.js} +5 -5
  60. package/dist/{chunk-JWMBG5S3.js → chunk-J2KGT2A5.js} +6 -6
  61. package/dist/{chunk-BEZDLIDG.js → chunk-JMN3I4OC.js} +4 -4
  62. package/dist/{chunk-7PJ3BKHS.js → chunk-JO4MRPEY.js} +5 -5
  63. package/dist/{chunk-4N5Q23KV.js → chunk-JXFQEOAQ.js} +5 -5
  64. package/dist/{chunk-ICDHUUMQ.js → chunk-KF34JCIJ.js} +4 -4
  65. package/dist/{chunk-6KTVJ5ZZ.js → chunk-KKVVBFKW.js} +3 -3
  66. package/dist/{chunk-DXKLLKME.js → chunk-L374ZR75.js} +3 -3
  67. package/dist/{chunk-EES37S2V.js → chunk-L5PTLL7A.js} +3 -3
  68. package/dist/{chunk-2LFOMUEA.js → chunk-LBDG6FHB.js} +3 -3
  69. package/dist/{chunk-T7JGWTES.js → chunk-LIWA5ROZ.js} +51 -16
  70. package/dist/chunk-LIWA5ROZ.js.map +1 -0
  71. package/dist/{chunk-3O72ZD2E.js → chunk-LPVZDTQF.js} +135 -18
  72. package/dist/chunk-LPVZDTQF.js.map +1 -0
  73. package/dist/{chunk-OIBEJN5H.js → chunk-LYQUFIHL.js} +2 -2
  74. package/dist/{chunk-JNMTN5D5.js → chunk-LZHIYH32.js} +2 -2
  75. package/dist/{chunk-7KAE7CQ2.js → chunk-M2KVSM43.js} +2 -2
  76. package/dist/{chunk-IGJCYUT5.js → chunk-NSITFOCJ.js} +1 -1
  77. package/dist/chunk-NSITFOCJ.js.map +1 -0
  78. package/dist/{chunk-32B7VCKU.js → chunk-O2A5YCFF.js} +2 -2
  79. package/dist/{chunk-4A34KWOU.js → chunk-OGB2UTBC.js} +5 -5
  80. package/dist/{chunk-GQXFOAYZ.js → chunk-OMXUQAZJ.js} +3 -3
  81. package/dist/{chunk-45YHJ3GV.js → chunk-PFHF3A72.js} +3 -3
  82. package/dist/{chunk-KV6JM2IA.js → chunk-PUGHLCBW.js} +2 -2
  83. package/dist/{chunk-ZZXLB6AS.js → chunk-R6BGN6IY.js} +2 -2
  84. package/dist/{chunk-CLAHBPOI.js → chunk-RBBTJ2HY.js} +3 -3
  85. package/dist/{chunk-YKXZHUOW.js → chunk-RGUAY5IX.js} +4 -4
  86. package/dist/{chunk-AU3AUJIZ.js → chunk-RQQIB7CD.js} +2 -2
  87. package/dist/{chunk-TX5MKAHA.js → chunk-RTKREHPV.js} +2 -2
  88. package/dist/{chunk-BAHOV5I5.js → chunk-SIACMXFK.js} +8 -8
  89. package/dist/{chunk-6WO62AJW.js → chunk-SZFNO7L4.js} +3 -3
  90. package/dist/{chunk-4OQZNXQG.js → chunk-TA67ZQUH.js} +53 -6
  91. package/dist/chunk-TA67ZQUH.js.map +1 -0
  92. package/dist/{chunk-U27Y4DJZ.js → chunk-TWELPVXG.js} +3 -3
  93. package/dist/{chunk-WVE6YKMX.js → chunk-U5ZDYJLQ.js} +3 -3
  94. package/dist/{chunk-4YL2LMXK.js → chunk-UW5YKCE4.js} +6 -6
  95. package/dist/{chunk-E5SC6ENM.js → chunk-UWRVDBDC.js} +10 -10
  96. package/dist/{chunk-GTHVPVAR.js → chunk-VNPSPQNN.js} +10 -10
  97. package/dist/{chunk-A4TOGAUW.js → chunk-VXH5Z22C.js} +2 -2
  98. package/dist/{chunk-FS7NTGCJ.js → chunk-WBFJZCDJ.js} +2 -2
  99. package/dist/{chunk-4RAS6HN6.js → chunk-WBRLSPA7.js} +2 -2
  100. package/dist/{chunk-AUPSEJ7O.js → chunk-WG66ZPEV.js} +4 -4
  101. package/dist/{chunk-QSIEL6TL.js → chunk-XXONVJWA.js} +5 -5
  102. package/dist/{chunk-ZLHHE5XZ.js → chunk-YLIGPHN4.js} +3 -3
  103. package/dist/{chunk-VVSOPRUE.js → chunk-YNWBBHQK.js} +3 -3
  104. package/dist/{chunk-I6QKB7MT.js → chunk-Z6UMKUAI.js} +2 -2
  105. package/dist/{chunk-7LNE2N2V.js → chunk-Z7AHYSZF.js} +5 -5
  106. package/dist/{chunk-3PMFMUFX.js → chunk-ZA3RBGT3.js} +2 -2
  107. package/dist/{chunk-LGFTOU27.js → chunk-ZILONQGE.js} +95 -80
  108. package/dist/chunk-ZILONQGE.js.map +1 -0
  109. package/dist/{chunk-TDSN2O2V.js → chunk-ZKZXS352.js} +5 -5
  110. package/dist/{chunk-OMYCSTXL.js → chunk-ZLU3IWHK.js} +3 -3
  111. package/dist/{chunk-6JPGVL7X.js → chunk-ZYG4UWHF.js} +2 -2
  112. package/dist/classified/index.js +4 -4
  113. package/dist/{classified-marker-NA6HUV33.js → classified-marker-RYWYYZDB.js} +3 -3
  114. package/dist/{collection-facade-VBM35WAH.js → collection-facade-XV3IMJBO.js} +15 -15
  115. package/dist/{computed-GSTLWSY5.js → computed-M4QZVSPX.js} +3 -3
  116. package/dist/consent/index.js +7 -7
  117. package/dist/cover/index.js +7 -7
  118. package/dist/custody/index.js +9 -9
  119. package/dist/{dead-filter-UALP5DJX.js → dead-filter-DRKJDNSF.js} +2 -2
  120. package/dist/debug/index.js +1 -1
  121. package/dist/{delegation-JLNXM7KH.js → delegation-UEJN2LDC.js} +9 -9
  122. package/dist/derivations/index.js +10 -10
  123. package/dist/{derive-YUO3TQYN.js → derive-WIWSPZ5M.js} +8 -8
  124. package/dist/directory/index.js +8 -8
  125. package/dist/{dispatch-77CB75KB.js → dispatch-2ZE7Z5V2.js} +16 -16
  126. package/dist/{dispatch-4ZHLSFZQ.js → dispatch-KNWYDUYM.js} +9 -6
  127. package/dist/dispatch-KNWYDUYM.js.map +1 -0
  128. package/dist/{enclave-O4NOROCJ.js → enclave-VNHDWCB6.js} +7 -7
  129. package/dist/executor-4SMYWPSU.js +29 -0
  130. package/dist/executor-BJ7PCXCV.js +9 -0
  131. package/dist/executor-O4UP4M3C.js +9 -0
  132. package/dist/export-accessible-A3N2V4IX.js +23 -0
  133. package/dist/extract-partition-3EUJXWYG.js +38 -0
  134. package/dist/{fanout-sidecar-NLQ7QAYW.js → fanout-sidecar-PBEVZ5IQ.js} +7 -7
  135. package/dist/find-W2DL2BEE.js +11 -0
  136. package/dist/forget/index.js +7 -7
  137. package/dist/guards/index.js +4 -4
  138. package/dist/history/index.js +11 -11
  139. package/dist/i18n/index.js +12 -12
  140. package/dist/index.d.ts +1 -1
  141. package/dist/index.js +91 -89
  142. package/dist/index.js.map +1 -1
  143. package/dist/indexing/index.js +4 -4
  144. package/dist/introspection/index.js +9 -9
  145. package/dist/issue-NLJ3FCKL.js +19 -0
  146. package/dist/kernel/collection.d.ts +8 -2
  147. package/dist/kernel/errors.d.ts +26 -0
  148. package/dist/kernel/query/builder.d.ts +36 -2
  149. package/dist/kernel/query/live.d.ts +31 -9
  150. package/dist/kernel/query/predicate.d.ts +9 -0
  151. package/dist/kernel/refs.d.ts +3 -1
  152. package/dist/kernel/via/reconcile.d.ts +12 -0
  153. package/dist/{ledger-MVPNG5OS.js → ledger-DDIDLWA3.js} +9 -9
  154. package/dist/liberate-EPTCY3DF.js +24 -0
  155. package/dist/{link-set-3POMQR3I.js → link-set-2AYA6BEI.js} +9 -9
  156. package/dist/{managed-secret-IARIJJ7Q.js → managed-secret-6QTGWZTW.js} +7 -7
  157. package/dist/materialized-views/index.js +20 -20
  158. package/dist/{migrate-cek-XM2ETTZW.js → migrate-cek-YBNJDJ2Q.js} +2 -2
  159. package/dist/money/index.js +5 -5
  160. package/dist/noydb-RFBNRUHH.js +85 -0
  161. package/dist/overlay-views/index.js +4 -4
  162. package/dist/periods/index.js +10 -10
  163. package/dist/pod/index.js +54 -53
  164. package/dist/{pod-handle-MELERCKU.js → pod-handle-77YAUM4J.js} +7 -7
  165. package/dist/policy/index.js +7 -7
  166. package/dist/portability/index.js +8 -8
  167. package/dist/{post-register-Z5T7FY45.js → post-register-WBDTOLWD.js} +6 -6
  168. package/dist/query/index.js +6 -6
  169. package/dist/reduce/index.js +6 -6
  170. package/dist/{register-UZ37QPDB.js → register-VSPL7VRW.js} +13 -13
  171. package/dist/registry-A7JADQXC.js +9 -0
  172. package/dist/registry-AOPJN2V4.js +18 -0
  173. package/dist/registry-I4I3QIQ6.js +9 -0
  174. package/dist/registry-QSMKWF4O.js +19 -0
  175. package/dist/{request-withdrawal-PVFEYX57.js → request-withdrawal-VL5N623Q.js} +12 -12
  176. package/dist/{reveal-DQ2E3QAZ.js → reveal-Z2X4JW6E.js} +4 -4
  177. package/dist/{revoke-YXY6SHUH.js → revoke-XQ5STGT4.js} +9 -9
  178. package/dist/satellites/index.js +1 -1
  179. package/dist/schema-update/index.js +2 -2
  180. package/dist/sealed-record/index.js +10 -10
  181. package/dist/search/index.js +4 -4
  182. package/dist/{seed-DZ4ORU5N.js → seed-WJWCFPZL.js} +9 -9
  183. package/dist/sequence/index.js +7 -7
  184. package/dist/session/index.js +7 -7
  185. package/dist/shadow/index.js +2 -2
  186. package/dist/{signer-Q7XQBMPA.js → signer-N5TGVOTN.js} +8 -8
  187. package/dist/snapshots/index.js +8 -8
  188. package/dist/{stale-NI7SAXAZ.js → stale-MIO5KGEP.js} +8 -8
  189. package/dist/{storage-3VNGSHXS.js → storage-NLYOMCDM.js} +8 -8
  190. package/dist/{store-coordination-provider-TYKNR3OU.js → store-coordination-provider-XCX77ZBE.js} +7 -7
  191. package/dist/sync/index.js +8 -8
  192. package/dist/team/index.js +12 -12
  193. package/dist/tiers/index.js +9 -9
  194. package/dist/to/index.js +1 -1
  195. package/dist/transactions/index.js +3 -3
  196. package/dist/util/index.js +1 -1
  197. package/dist/vault-head/index.js +6 -6
  198. package/dist/{verify-6J2YLKSO.js → verify-5QI3DGO2.js} +5 -5
  199. package/dist/via/blob/index.d.ts +3 -0
  200. package/dist/walk-G5OAA3RE.js +21 -0
  201. package/dist/with-formula/materialized-views/dependency-analyzer.d.ts +4 -0
  202. package/dist/with-formula/materialized-views/projection-legs.d.ts +59 -0
  203. package/dist/with-formula/materialized-views/registry.d.ts +50 -0
  204. package/dist/with-formula/materialized-views/types.d.ts +68 -10
  205. package/dist/with-shape/blobs/blob-compaction.d.ts +13 -0
  206. package/dist/with-shape/blobs/blob-set.d.ts +61 -7
  207. package/dist/with-shape/blobs/orphan-report.d.ts +62 -0
  208. package/dist/{withdraw-accessible-4JTDFRFZ.js → withdraw-accessible-H7G2AMSP.js} +11 -11
  209. package/package.json +3 -3
  210. package/dist/api-EYNT6KGS.js +0 -20
  211. package/dist/chunk-3O72ZD2E.js.map +0 -1
  212. package/dist/chunk-4OQZNXQG.js.map +0 -1
  213. package/dist/chunk-CAGI4LLJ.js.map +0 -1
  214. package/dist/chunk-CWM4GQD2.js.map +0 -1
  215. package/dist/chunk-IGJCYUT5.js.map +0 -1
  216. package/dist/chunk-JLYQQNY4.js.map +0 -1
  217. package/dist/chunk-LGFTOU27.js.map +0 -1
  218. package/dist/chunk-LXECF2ZR.js.map +0 -1
  219. package/dist/chunk-P2MR5UNE.js.map +0 -1
  220. package/dist/chunk-T7JGWTES.js.map +0 -1
  221. package/dist/dispatch-4ZHLSFZQ.js.map +0 -1
  222. package/dist/executor-CZDXBXKE.js +0 -29
  223. package/dist/executor-DVJAWN3B.js +0 -9
  224. package/dist/executor-VRLG4TQJ.js +0 -9
  225. package/dist/export-accessible-UXSMG7AB.js +0 -23
  226. package/dist/extract-partition-TVY7AMKH.js +0 -38
  227. package/dist/find-WSARMJBW.js +0 -11
  228. package/dist/issue-3JNJNPT3.js +0 -19
  229. package/dist/liberate-4LOJOLDT.js +0 -24
  230. package/dist/noydb-IRILUDED.js +0 -84
  231. package/dist/registry-ETJNA7PO.js +0 -9
  232. package/dist/registry-F7U6KSLX.js +0 -9
  233. package/dist/registry-L4ELKX6C.js +0 -18
  234. package/dist/registry-SDT5LIGO.js +0 -19
  235. package/dist/walk-WRA7RAPY.js +0 -21
  236. /package/dist/{api-EYNT6KGS.js.map → api-ETB5Y4DY.js.map} +0 -0
  237. /package/dist/{backup-FSC36VWC.js.map → backup-UOLAXOJ4.js.map} +0 -0
  238. /package/dist/{chunk-3B6S6RSI.js.map → chunk-22VRCUV2.js.map} +0 -0
  239. /package/dist/{chunk-ESKIAXO2.js.map → chunk-23ODLABM.js.map} +0 -0
  240. /package/dist/{chunk-IJ46VCWD.js.map → chunk-2DHEBIJA.js.map} +0 -0
  241. /package/dist/{chunk-TMBSPLUG.js.map → chunk-2LHPMFSR.js.map} +0 -0
  242. /package/dist/{chunk-ONVD6GBY.js.map → chunk-2QN6NPV6.js.map} +0 -0
  243. /package/dist/{chunk-NW4TY6VC.js.map → chunk-3UIS6O6N.js.map} +0 -0
  244. /package/dist/{chunk-EKEIEJL6.js.map → chunk-4UZDDS4S.js.map} +0 -0
  245. /package/dist/{chunk-S56VYR4Q.js.map → chunk-5FRZ7YYU.js.map} +0 -0
  246. /package/dist/{chunk-H3G4I3PN.js.map → chunk-5MU7PUNA.js.map} +0 -0
  247. /package/dist/{chunk-NCCEDL2K.js.map → chunk-66X4XWTM.js.map} +0 -0
  248. /package/dist/{chunk-TQPASLY4.js.map → chunk-6G4NORTR.js.map} +0 -0
  249. /package/dist/{chunk-RKCRPPNB.js.map → chunk-6W3BZCW6.js.map} +0 -0
  250. /package/dist/{chunk-DVRZYAGT.js.map → chunk-6ZN6X2LW.js.map} +0 -0
  251. /package/dist/{chunk-PPCOKVFA.js.map → chunk-6ZTPSVY7.js.map} +0 -0
  252. /package/dist/{chunk-MZTUTEHP.js.map → chunk-7DRKK5FQ.js.map} +0 -0
  253. /package/dist/{chunk-GBBDFE6C.js.map → chunk-7LWBD3NO.js.map} +0 -0
  254. /package/dist/{chunk-KX57HODD.js.map → chunk-7W765AVV.js.map} +0 -0
  255. /package/dist/{chunk-LN7P6MZB.js.map → chunk-7ZPAL3F7.js.map} +0 -0
  256. /package/dist/{chunk-CADUYBQD.js.map → chunk-ATL3ZVXT.js.map} +0 -0
  257. /package/dist/{chunk-RSXQNFGO.js.map → chunk-ATSIGJRX.js.map} +0 -0
  258. /package/dist/{chunk-MSLPDFK2.js.map → chunk-AZPPARMG.js.map} +0 -0
  259. /package/dist/{chunk-NR2SUJ3H.js.map → chunk-B3X6S37C.js.map} +0 -0
  260. /package/dist/{chunk-GWO2IDAB.js.map → chunk-BNGGSNO7.js.map} +0 -0
  261. /package/dist/{chunk-INMHEMXX.js.map → chunk-C7B3XUI4.js.map} +0 -0
  262. /package/dist/{chunk-D3R7Q4QK.js.map → chunk-CJU3KXHJ.js.map} +0 -0
  263. /package/dist/{chunk-RFO4UXKQ.js.map → chunk-CWYTN4IK.js.map} +0 -0
  264. /package/dist/{chunk-HR5R5JOM.js.map → chunk-D5DZ4R7X.js.map} +0 -0
  265. /package/dist/{chunk-6YD5SYQS.js.map → chunk-DEKA2MV3.js.map} +0 -0
  266. /package/dist/{chunk-SYS46BL7.js.map → chunk-DG4KFJNA.js.map} +0 -0
  267. /package/dist/{chunk-B6IYATME.js.map → chunk-DXJXVWWE.js.map} +0 -0
  268. /package/dist/{chunk-O742QBZZ.js.map → chunk-DZBZCFS7.js.map} +0 -0
  269. /package/dist/{chunk-FW7NGYLT.js.map → chunk-FNCX4N7X.js.map} +0 -0
  270. /package/dist/{chunk-OHOKBMTM.js.map → chunk-FUE2KPKM.js.map} +0 -0
  271. /package/dist/{chunk-YALD3SST.js.map → chunk-G4577GK7.js.map} +0 -0
  272. /package/dist/{chunk-DIZ6HM7Q.js.map → chunk-G6DAESDS.js.map} +0 -0
  273. /package/dist/{chunk-HYYVT2KZ.js.map → chunk-GAZTPQ3D.js.map} +0 -0
  274. /package/dist/{chunk-LX46B56Q.js.map → chunk-GJ5TMHKC.js.map} +0 -0
  275. /package/dist/{chunk-KRVS7YWY.js.map → chunk-GNSLP7KA.js.map} +0 -0
  276. /package/dist/{chunk-5Q7AJ7DN.js.map → chunk-I3D67XD7.js.map} +0 -0
  277. /package/dist/{chunk-GQ3BX5EA.js.map → chunk-I3ISCYT7.js.map} +0 -0
  278. /package/dist/{chunk-HQSPF5IY.js.map → chunk-ISRAQIYY.js.map} +0 -0
  279. /package/dist/{chunk-JWMBG5S3.js.map → chunk-J2KGT2A5.js.map} +0 -0
  280. /package/dist/{chunk-BEZDLIDG.js.map → chunk-JMN3I4OC.js.map} +0 -0
  281. /package/dist/{chunk-7PJ3BKHS.js.map → chunk-JO4MRPEY.js.map} +0 -0
  282. /package/dist/{chunk-4N5Q23KV.js.map → chunk-JXFQEOAQ.js.map} +0 -0
  283. /package/dist/{chunk-ICDHUUMQ.js.map → chunk-KF34JCIJ.js.map} +0 -0
  284. /package/dist/{chunk-6KTVJ5ZZ.js.map → chunk-KKVVBFKW.js.map} +0 -0
  285. /package/dist/{chunk-DXKLLKME.js.map → chunk-L374ZR75.js.map} +0 -0
  286. /package/dist/{chunk-EES37S2V.js.map → chunk-L5PTLL7A.js.map} +0 -0
  287. /package/dist/{chunk-2LFOMUEA.js.map → chunk-LBDG6FHB.js.map} +0 -0
  288. /package/dist/{chunk-OIBEJN5H.js.map → chunk-LYQUFIHL.js.map} +0 -0
  289. /package/dist/{chunk-JNMTN5D5.js.map → chunk-LZHIYH32.js.map} +0 -0
  290. /package/dist/{chunk-7KAE7CQ2.js.map → chunk-M2KVSM43.js.map} +0 -0
  291. /package/dist/{chunk-32B7VCKU.js.map → chunk-O2A5YCFF.js.map} +0 -0
  292. /package/dist/{chunk-4A34KWOU.js.map → chunk-OGB2UTBC.js.map} +0 -0
  293. /package/dist/{chunk-GQXFOAYZ.js.map → chunk-OMXUQAZJ.js.map} +0 -0
  294. /package/dist/{chunk-45YHJ3GV.js.map → chunk-PFHF3A72.js.map} +0 -0
  295. /package/dist/{chunk-KV6JM2IA.js.map → chunk-PUGHLCBW.js.map} +0 -0
  296. /package/dist/{chunk-ZZXLB6AS.js.map → chunk-R6BGN6IY.js.map} +0 -0
  297. /package/dist/{chunk-CLAHBPOI.js.map → chunk-RBBTJ2HY.js.map} +0 -0
  298. /package/dist/{chunk-YKXZHUOW.js.map → chunk-RGUAY5IX.js.map} +0 -0
  299. /package/dist/{chunk-AU3AUJIZ.js.map → chunk-RQQIB7CD.js.map} +0 -0
  300. /package/dist/{chunk-TX5MKAHA.js.map → chunk-RTKREHPV.js.map} +0 -0
  301. /package/dist/{chunk-BAHOV5I5.js.map → chunk-SIACMXFK.js.map} +0 -0
  302. /package/dist/{chunk-6WO62AJW.js.map → chunk-SZFNO7L4.js.map} +0 -0
  303. /package/dist/{chunk-U27Y4DJZ.js.map → chunk-TWELPVXG.js.map} +0 -0
  304. /package/dist/{chunk-WVE6YKMX.js.map → chunk-U5ZDYJLQ.js.map} +0 -0
  305. /package/dist/{chunk-4YL2LMXK.js.map → chunk-UW5YKCE4.js.map} +0 -0
  306. /package/dist/{chunk-E5SC6ENM.js.map → chunk-UWRVDBDC.js.map} +0 -0
  307. /package/dist/{chunk-GTHVPVAR.js.map → chunk-VNPSPQNN.js.map} +0 -0
  308. /package/dist/{chunk-A4TOGAUW.js.map → chunk-VXH5Z22C.js.map} +0 -0
  309. /package/dist/{chunk-FS7NTGCJ.js.map → chunk-WBFJZCDJ.js.map} +0 -0
  310. /package/dist/{chunk-4RAS6HN6.js.map → chunk-WBRLSPA7.js.map} +0 -0
  311. /package/dist/{chunk-AUPSEJ7O.js.map → chunk-WG66ZPEV.js.map} +0 -0
  312. /package/dist/{chunk-QSIEL6TL.js.map → chunk-XXONVJWA.js.map} +0 -0
  313. /package/dist/{chunk-ZLHHE5XZ.js.map → chunk-YLIGPHN4.js.map} +0 -0
  314. /package/dist/{chunk-VVSOPRUE.js.map → chunk-YNWBBHQK.js.map} +0 -0
  315. /package/dist/{chunk-I6QKB7MT.js.map → chunk-Z6UMKUAI.js.map} +0 -0
  316. /package/dist/{chunk-7LNE2N2V.js.map → chunk-Z7AHYSZF.js.map} +0 -0
  317. /package/dist/{chunk-3PMFMUFX.js.map → chunk-ZA3RBGT3.js.map} +0 -0
  318. /package/dist/{chunk-TDSN2O2V.js.map → chunk-ZKZXS352.js.map} +0 -0
  319. /package/dist/{chunk-OMYCSTXL.js.map → chunk-ZLU3IWHK.js.map} +0 -0
  320. /package/dist/{chunk-6JPGVL7X.js.map → chunk-ZYG4UWHF.js.map} +0 -0
  321. /package/dist/{classified-marker-NA6HUV33.js.map → classified-marker-RYWYYZDB.js.map} +0 -0
  322. /package/dist/{collection-facade-VBM35WAH.js.map → collection-facade-XV3IMJBO.js.map} +0 -0
  323. /package/dist/{computed-GSTLWSY5.js.map → computed-M4QZVSPX.js.map} +0 -0
  324. /package/dist/{dead-filter-UALP5DJX.js.map → dead-filter-DRKJDNSF.js.map} +0 -0
  325. /package/dist/{delegation-JLNXM7KH.js.map → delegation-UEJN2LDC.js.map} +0 -0
  326. /package/dist/{derive-YUO3TQYN.js.map → derive-WIWSPZ5M.js.map} +0 -0
  327. /package/dist/{dispatch-77CB75KB.js.map → dispatch-2ZE7Z5V2.js.map} +0 -0
  328. /package/dist/{enclave-O4NOROCJ.js.map → enclave-VNHDWCB6.js.map} +0 -0
  329. /package/dist/{executor-CZDXBXKE.js.map → executor-4SMYWPSU.js.map} +0 -0
  330. /package/dist/{executor-DVJAWN3B.js.map → executor-BJ7PCXCV.js.map} +0 -0
  331. /package/dist/{executor-VRLG4TQJ.js.map → executor-O4UP4M3C.js.map} +0 -0
  332. /package/dist/{export-accessible-UXSMG7AB.js.map → export-accessible-A3N2V4IX.js.map} +0 -0
  333. /package/dist/{extract-partition-TVY7AMKH.js.map → extract-partition-3EUJXWYG.js.map} +0 -0
  334. /package/dist/{fanout-sidecar-NLQ7QAYW.js.map → fanout-sidecar-PBEVZ5IQ.js.map} +0 -0
  335. /package/dist/{find-WSARMJBW.js.map → find-W2DL2BEE.js.map} +0 -0
  336. /package/dist/{issue-3JNJNPT3.js.map → issue-NLJ3FCKL.js.map} +0 -0
  337. /package/dist/{ledger-MVPNG5OS.js.map → ledger-DDIDLWA3.js.map} +0 -0
  338. /package/dist/{liberate-4LOJOLDT.js.map → liberate-EPTCY3DF.js.map} +0 -0
  339. /package/dist/{link-set-3POMQR3I.js.map → link-set-2AYA6BEI.js.map} +0 -0
  340. /package/dist/{managed-secret-IARIJJ7Q.js.map → managed-secret-6QTGWZTW.js.map} +0 -0
  341. /package/dist/{migrate-cek-XM2ETTZW.js.map → migrate-cek-YBNJDJ2Q.js.map} +0 -0
  342. /package/dist/{noydb-IRILUDED.js.map → noydb-RFBNRUHH.js.map} +0 -0
  343. /package/dist/{pod-handle-MELERCKU.js.map → pod-handle-77YAUM4J.js.map} +0 -0
  344. /package/dist/{post-register-Z5T7FY45.js.map → post-register-WBDTOLWD.js.map} +0 -0
  345. /package/dist/{register-UZ37QPDB.js.map → register-VSPL7VRW.js.map} +0 -0
  346. /package/dist/{registry-ETJNA7PO.js.map → registry-A7JADQXC.js.map} +0 -0
  347. /package/dist/{registry-F7U6KSLX.js.map → registry-AOPJN2V4.js.map} +0 -0
  348. /package/dist/{registry-L4ELKX6C.js.map → registry-I4I3QIQ6.js.map} +0 -0
  349. /package/dist/{registry-SDT5LIGO.js.map → registry-QSMKWF4O.js.map} +0 -0
  350. /package/dist/{request-withdrawal-PVFEYX57.js.map → request-withdrawal-VL5N623Q.js.map} +0 -0
  351. /package/dist/{reveal-DQ2E3QAZ.js.map → reveal-Z2X4JW6E.js.map} +0 -0
  352. /package/dist/{revoke-YXY6SHUH.js.map → revoke-XQ5STGT4.js.map} +0 -0
  353. /package/dist/{seed-DZ4ORU5N.js.map → seed-WJWCFPZL.js.map} +0 -0
  354. /package/dist/{signer-Q7XQBMPA.js.map → signer-N5TGVOTN.js.map} +0 -0
  355. /package/dist/{stale-NI7SAXAZ.js.map → stale-MIO5KGEP.js.map} +0 -0
  356. /package/dist/{storage-3VNGSHXS.js.map → storage-NLYOMCDM.js.map} +0 -0
  357. /package/dist/{store-coordination-provider-TYKNR3OU.js.map → store-coordination-provider-XCX77ZBE.js.map} +0 -0
  358. /package/dist/{verify-6J2YLKSO.js.map → verify-5QI3DGO2.js.map} +0 -0
  359. /package/dist/{walk-WRA7RAPY.js.map → walk-G5OAA3RE.js.map} +0 -0
  360. /package/dist/{withdraw-accessible-4JTDFRFZ.js.map → withdraw-accessible-H7G2AMSP.js.map} +0 -0
@@ -7,10 +7,10 @@ import {
7
7
  PERIOD_FREEZES_COLLECTION,
8
8
  PERIOD_TARGET_PURGES_COLLECTION,
9
9
  periodExclusiveUpperBound
10
- } from "./chunk-A4TOGAUW.js";
10
+ } from "./chunk-VXH5Z22C.js";
11
11
  import {
12
12
  envelopeBodySize
13
- } from "./chunk-OHOKBMTM.js";
13
+ } from "./chunk-FUE2KPKM.js";
14
14
  import {
15
15
  buildRecordEnvelope,
16
16
  isDeleteMarker,
@@ -20,14 +20,14 @@ import {
20
20
  decrypt,
21
21
  derivePresenceKey,
22
22
  encrypt
23
- } from "./chunk-AU3AUJIZ.js";
23
+ } from "./chunk-RQQIB7CD.js";
24
24
  import {
25
25
  NOYDB_SYNC_VERSION
26
26
  } from "./chunk-IGNJOJEP.js";
27
27
  import {
28
28
  ValidationError,
29
29
  isConflictError
30
- } from "./chunk-CWM4GQD2.js";
30
+ } from "./chunk-HKANJAOP.js";
31
31
 
32
32
  // src/with-sync/presence.ts
33
33
  var subtle = globalThis.crypto.subtle;
@@ -1213,4 +1213,4 @@ export {
1213
1213
  SyncEngine,
1214
1214
  SyncTransaction
1215
1215
  };
1216
- //# sourceMappingURL=chunk-4N5Q23KV.js.map
1216
+ //# sourceMappingURL=chunk-JXFQEOAQ.js.map
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  readPath
3
- } from "./chunk-IGJCYUT5.js";
3
+ } from "./chunk-NSITFOCJ.js";
4
4
  import {
5
5
  installViaBinder
6
- } from "./chunk-JNMTN5D5.js";
6
+ } from "./chunk-LZHIYH32.js";
7
7
  import {
8
8
  NoydbError,
9
9
  ValidationError
10
- } from "./chunk-CWM4GQD2.js";
10
+ } from "./chunk-HKANJAOP.js";
11
11
 
12
12
  // src/via/money/iso4217.ts
13
13
  var MINOR_UNITS = {
@@ -1044,4 +1044,4 @@ export {
1044
1044
  decodeMoneyFields,
1045
1045
  exactMath
1046
1046
  };
1047
- //# sourceMappingURL=chunk-ICDHUUMQ.js.map
1047
+ //# sourceMappingURL=chunk-KF34JCIJ.js.map
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  envelopePayloadHash
3
- } from "./chunk-ZLHHE5XZ.js";
3
+ } from "./chunk-YLIGPHN4.js";
4
4
  import {
5
5
  NOYDB_FORMAT_VERSION
6
6
  } from "./chunk-IGNJOJEP.js";
7
7
  import {
8
8
  DictKeyMissingError,
9
9
  PermissionDeniedError
10
- } from "./chunk-CWM4GQD2.js";
10
+ } from "./chunk-HKANJAOP.js";
11
11
 
12
12
  // src/via/lookup/handle.ts
13
13
  function isDeleteMarker(envelope) {
@@ -392,4 +392,4 @@ export {
392
392
  dictCollectionName,
393
393
  LookupHandle
394
394
  };
395
- //# sourceMappingURL=chunk-6KTVJ5ZZ.js.map
395
+ //# sourceMappingURL=chunk-KKVVBFKW.js.map
@@ -4,10 +4,10 @@ import {
4
4
  } from "./chunk-KHKKD62N.js";
5
5
  import {
6
6
  derivePersistedSchema
7
- } from "./chunk-ONVD6GBY.js";
7
+ } from "./chunk-2QN6NPV6.js";
8
8
  import {
9
9
  loadPersistedSchema
10
- } from "./chunk-6WO62AJW.js";
10
+ } from "./chunk-SZFNO7L4.js";
11
11
 
12
12
  // src/with-shape/introspection/walk.ts
13
13
  var INTERNAL_PREFIX = "_";
@@ -238,4 +238,4 @@ function summariseAggregateOp(value) {
238
238
  export {
239
239
  dumpVaultSchema
240
240
  };
241
- //# sourceMappingURL=chunk-DXKLLKME.js.map
241
+ //# sourceMappingURL=chunk-L374ZR75.js.map
@@ -3,10 +3,10 @@ import {
3
3
  } from "./chunk-5D2ALSM5.js";
4
4
  import {
5
5
  RecordCodec
6
- } from "./chunk-OHOKBMTM.js";
6
+ } from "./chunk-FUE2KPKM.js";
7
7
 
8
8
  // src/with-formula/materialized-views/stale.ts
9
- var loadMVExecutor = lazy(() => import("./executor-CZDXBXKE.js"));
9
+ var loadMVExecutor = lazy(() => import("./executor-4SMYWPSU.js"));
10
10
  var _staleByRegistry = /* @__PURE__ */ new WeakMap();
11
11
  function markMVStale(registry, mvName) {
12
12
  let set = _staleByRegistry.get(registry);
@@ -134,4 +134,4 @@ export {
134
134
  clearMVStale,
135
135
  clearMVStaleFully
136
136
  };
137
- //# sourceMappingURL=chunk-EES37S2V.js.map
137
+ //# sourceMappingURL=chunk-L5PTLL7A.js.map
@@ -6,7 +6,7 @@ import {
6
6
  ConflictError,
7
7
  InvariantError,
8
8
  ValidationError
9
- } from "./chunk-CWM4GQD2.js";
9
+ } from "./chunk-HKANJAOP.js";
10
10
 
11
11
  // src/with-commit/tx/atomic-eligibility.ts
12
12
  function canCommitAtomically(db, ctx) {
@@ -270,7 +270,7 @@ async function runTransaction(db, fn, options, txInvariants) {
270
270
  db._clearActiveTxContext(ctx);
271
271
  }
272
272
  if (ctx._amendment) {
273
- const { GuardExecutor } = await import("./executor-DVJAWN3B.js");
273
+ const { GuardExecutor } = await import("./executor-O4UP4M3C.js");
274
274
  try {
275
275
  for (const [vaultName, v] of ctx._amendmentVaults) {
276
276
  const registry = v._getGuardRegistry();
@@ -447,4 +447,4 @@ export {
447
447
  TxCollection,
448
448
  runTransaction
449
449
  };
450
- //# sourceMappingURL=chunk-2LFOMUEA.js.map
450
+ //# sourceMappingURL=chunk-LBDG6FHB.js.map
@@ -1,32 +1,34 @@
1
1
  import {
2
+ isCollectLeg,
3
+ resolveLegOwner,
2
4
  wrapDbWithPredicates
3
- } from "./chunk-3O72ZD2E.js";
5
+ } from "./chunk-LPVZDTQF.js";
4
6
  import {
5
7
  canonicalizeMoneyFieldsAsDecimal,
6
8
  decodeMoneyFields,
7
9
  exactMath
8
- } from "./chunk-ICDHUUMQ.js";
10
+ } from "./chunk-KF34JCIJ.js";
9
11
  import {
10
12
  putDerivedOutput
11
- } from "./chunk-DVRZYAGT.js";
13
+ } from "./chunk-6ZN6X2LW.js";
12
14
  import {
13
15
  DEFAULT_JOIN_MAX_ROWS
14
- } from "./chunk-VVSOPRUE.js";
16
+ } from "./chunk-YNWBBHQK.js";
15
17
  import {
16
18
  groupAndReduce
17
- } from "./chunk-B6IYATME.js";
19
+ } from "./chunk-DXJXVWWE.js";
18
20
  import {
19
21
  canonicalGroupKey
20
22
  } from "./chunk-XZHEOSQ2.js";
21
23
  import {
22
24
  applyI18nLocale
23
- } from "./chunk-WVE6YKMX.js";
25
+ } from "./chunk-U5ZDYJLQ.js";
24
26
  import {
25
27
  JoinTooLargeError,
26
28
  LocaleNotSpecifiedError,
27
29
  MaterializedViewConfigError,
28
30
  MaterializedViewTooLargeError
29
- } from "./chunk-CWM4GQD2.js";
31
+ } from "./chunk-HKANJAOP.js";
30
32
 
31
33
  // src/with-formula/materialized-views/executor.ts
32
34
  var DEFAULT_MAX_ROWS = 1e5;
@@ -125,13 +127,16 @@ async function materializeProjectionResult(spec, db) {
125
127
  const coll = db.collection(projection.source);
126
128
  let q = coll.query();
127
129
  for (const leg of projection.joins) {
128
- if ("collect" in leg) continue;
130
+ if (isCollectLeg(leg) || leg.from !== void 0) continue;
129
131
  q = q.join(leg.field, { as: leg.as, maxRows: leg.maxRows, strategy: leg.strategy });
130
132
  }
131
133
  let rows = q.toArray();
132
134
  for (const leg of projection.joins) {
133
- if (!("collect" in leg)) continue;
134
- rows = applyCollectLeg(rows, leg, spec.name, projection.source, db);
135
+ if (isCollectLeg(leg)) {
136
+ rows = applyCollectLeg(rows, leg, spec.name, projection.source, projection.joins, db);
137
+ } else if (leg.from !== void 0) {
138
+ rows = applyLegRelativeForwardLeg(rows, leg, spec.name, projection.source, projection.joins, db);
139
+ }
135
140
  }
136
141
  const mapped = [];
137
142
  for (const r of rows) {
@@ -141,18 +146,47 @@ async function materializeProjectionResult(spec, db) {
141
146
  }
142
147
  return finalizeMappedRows(spec, mapped);
143
148
  }
144
- function applyCollectLeg(primaryRows, leg, mvName, source, db) {
149
+ function legOwnerLookup(db) {
150
+ return (collection, field) => {
151
+ const q = db.collection(collection).query();
152
+ return q._joinContext?.()?.resolveRef(field) ?? null;
153
+ };
154
+ }
155
+ function applyLegRelativeForwardLeg(primaryRows, leg, mvName, source, joins, db) {
156
+ const lookup = legOwnerLookup(db);
157
+ const owner = resolveLegOwner(leg, joins, source, lookup);
158
+ const refDesc = owner === null ? null : lookup(owner, leg.field);
159
+ if (owner === null || refDesc === null) {
160
+ throw new MaterializedViewConfigError(
161
+ `"${mvName}": projection leg "${leg.as}" requires a ref() on field "${leg.field}" of collection "${owner ?? `(behind from: "${leg.from}")`}" \u2014 declare it on that collection, then retry`
162
+ );
163
+ }
164
+ const targetQ = db.collection(refDesc.target).query();
165
+ const byId = /* @__PURE__ */ new Map();
166
+ for (const row of targetQ.toArray()) {
167
+ const id = coerceCollectKey(row.id);
168
+ if (id !== null) byId.set(id, row);
169
+ }
170
+ return primaryRows.map((row) => {
171
+ const anchor = leg.from === void 0 ? row : row[leg.from];
172
+ const key = anchor == null ? null : coerceCollectKey(anchor[leg.field]);
173
+ return { ...row, [leg.as]: key === null ? null : byId.get(key) ?? null };
174
+ });
175
+ }
176
+ function applyCollectLeg(primaryRows, leg, mvName, source, joins, db) {
145
177
  const childColl = db.collection(leg.collect);
146
178
  const childQ = childColl.query();
147
179
  const refDesc = childQ._joinContext?.()?.resolveRef(leg.on);
180
+ const expected = resolveLegOwner(leg, joins, source, legOwnerLookup(db));
181
+ const expectedName = expected ?? source;
148
182
  if (refDesc == null) {
149
183
  throw new MaterializedViewConfigError(
150
- `"${mvName}": projection collect leg "${leg.as}" requires a ref() on field "${leg.on}" of collection "${leg.collect}" targeting "${source}" \u2014 declare refs: { ${leg.on}: ref('${source}') } on collection "${leg.collect}", then retry`
184
+ `"${mvName}": projection collect leg "${leg.as}" requires a ref() on field "${leg.on}" of collection "${leg.collect}" targeting "${expectedName}" \u2014 declare refs: { ${leg.on}: ref('${expectedName}') } on collection "${leg.collect}", then retry`
151
185
  );
152
186
  }
153
- if (refDesc.target !== source) {
187
+ if (refDesc.target !== expectedName) {
154
188
  throw new MaterializedViewConfigError(
155
- `"${mvName}": projection collect leg "${leg.as}" expects field "${leg.on}" of collection "${leg.collect}" to reference the projection source "${source}", but its ref() targets "${refDesc.target}"`
189
+ `"${mvName}": projection collect leg "${leg.as}" expects field "${leg.on}" of collection "${leg.collect}" to reference ${leg.from === void 0 ? `the projection source "${expectedName}"` : `"${expectedName}" (the collection behind from: "${leg.from}")`}, but its ref() targets "${refDesc.target}"`
156
190
  );
157
191
  }
158
192
  const maxRows = leg.maxRows ?? DEFAULT_JOIN_MAX_ROWS;
@@ -166,7 +200,8 @@ function applyCollectLeg(primaryRows, leg, mvName, source, db) {
166
200
  }
167
201
  const out = [];
168
202
  for (const row of primaryRows) {
169
- const key = coerceCollectKey(row.id);
203
+ const anchor = leg.from === void 0 ? row : row[leg.from];
204
+ const key = anchor == null ? null : coerceCollectKey(anchor.id);
170
205
  const children = key === null ? [] : groups.get(key) ?? [];
171
206
  if (children.length > maxRows) {
172
207
  throw new JoinTooLargeError({
@@ -307,4 +342,4 @@ async function listOutputIds(outputColl) {
307
342
  export {
308
343
  MaterializedViewExecutor
309
344
  };
310
- //# sourceMappingURL=chunk-T7JGWTES.js.map
345
+ //# sourceMappingURL=chunk-LIWA5ROZ.js.map
@@ -0,0 +1 @@
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, ProjectionJoinLeg } 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'\nimport { isCollectLeg, resolveLegOwner, type RefLookup } from './projection-legs.js' // #1140\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 // ROOT forward legs chain through the query builder exactly like UNION arm\n // joins — ref() resolution, dangling-mode semantics, presentation dressing,\n // and ceilings all ride the existing `.join()` path. Cast to `any` for the\n // 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 (isCollectLeg(leg) || leg.from !== undefined) 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 // Remaining legs in DECLARATION order — which is what makes `from` work: a leg\n // may only name an alias declared earlier, so by the time it runs, the rows it\n // attaches to are already on the row. Root collect legs are in this loop too;\n // they were never part of the query chain.\n for (const leg of projection.joins) {\n if (isCollectLeg(leg)) {\n rows = applyCollectLeg(rows, leg, spec.name, projection.source, projection.joins, db)\n } else if (leg.from !== undefined) {\n rows = applyLegRelativeForwardLeg(rows, leg, spec.name, projection.source, projection.joins, db)\n }\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 * A `RefLookup` backed by the live join contexts — the executor's answer to the\n * same question the registry answers from the ref registry. Reads through, so a\n * ref declared after `openVault()` (the only place refs CAN be declared) is\n * visible here.\n *\n * @internal\n */\nfunction legOwnerLookup(db: MVQueryContext): RefLookup {\n return (collection, field) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const q = db.collection<Record<string, unknown>>(collection).query() as any\n return (q._joinContext?.()?.resolveRef(field) as { target: string } | null | undefined) ?? null\n }\n}\n\n/**\n * Attach one FORWARD leg that hangs off another leg's alias (#1140).\n *\n * Root forward legs ride `Query.join()` and are resolved before this runs; a\n * leg-relative one cannot, because the FK it follows lives on an already-attached\n * record rather than on a column of the primary query. It is therefore resolved\n * the same way a collect leg is — one snapshot of the target collection, indexed\n * by id — which keeps it O(N+M) rather than one `get()` per row.\n *\n * Attaches `null` when the `from` alias is null (a dangling ref upstream), when\n * the FK is nullish, or when the target row is missing. That is deliberately\n * outer-by-nature and matches the collect leg's empty array: a projection MV\n * must not drop a primary row because something two hops away is absent.\n *\n * @internal\n */\nfunction applyLegRelativeForwardLeg(\n primaryRows: ReadonlyArray<Record<string, unknown>>,\n leg: Extract<ProjectionJoinLeg, { field: string }>,\n mvName: string,\n source: string,\n joins: ReadonlyArray<ProjectionJoinLeg>,\n db: MVQueryContext,\n): Array<Record<string, unknown>> {\n const lookup = legOwnerLookup(db)\n const owner = resolveLegOwner(leg, joins, source, lookup)\n const refDesc = owner === null ? null : lookup(owner, leg.field)\n if (owner === null || refDesc === null) {\n throw new MaterializedViewConfigError(\n `\"${mvName}\": projection leg \"${leg.as}\" requires a ref() on field \"${leg.field}\" of `\n + `collection \"${owner ?? `(behind from: \"${leg.from}\")`}\" — declare it on that collection, `\n + `then retry`,\n )\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const targetQ = db.collection<Record<string, unknown>>(refDesc.target).query() as any\n const byId = new Map<string, Record<string, unknown>>()\n for (const row of targetQ.toArray() as Array<Record<string, unknown>>) {\n const id = coerceCollectKey(row.id)\n if (id !== null) byId.set(id, row)\n }\n return primaryRows.map((row) => {\n const anchor = leg.from === undefined\n ? row\n : (row[leg.from] as Record<string, unknown> | null | undefined)\n const key = anchor == null ? null : coerceCollectKey(anchor[leg.field])\n return { ...row, [leg.as]: key === null ? null : byId.get(key) ?? null }\n })\n}\n\n/**\n * Attach one reverse \"collect\" leg (#810): every row of `leg.collect`\n * whose `leg.on` field references the ATTACH POINT'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 * The attach point is the primary record, or — with `from` (#1140) — the record\n * already attached under that alias. Matching then keys off `row[from].id`\n * instead of `row.id`, and `leg.on` must ref THAT leg's collection. A row whose\n * `from` alias is null (a dangling forward ref) gets `[]`, which is the same\n * outer-by-nature semantics a root collect leg already has for a primary record\n * with no children.\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 attach point's collection.\n *\n * @internal\n */\nfunction applyCollectLeg(\n primaryRows: ReadonlyArray<Record<string, unknown>>,\n leg: { readonly collect: string; readonly on: string; readonly as: string; readonly from?: string; readonly maxRows?: number },\n mvName: string,\n source: string,\n joins: ReadonlyArray<ProjectionJoinLeg>,\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 // The collection this leg matches AGAINST: the projection source for a root\n // leg, the `from` leg's own target otherwise (#1140).\n const expected = resolveLegOwner(leg, joins, source, legOwnerLookup(db))\n const expectedName = expected ?? source\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 \"${expectedName}\" — declare `\n + `refs: { ${leg.on}: ref('${expectedName}') } on collection \"${leg.collect}\", then retry`,\n )\n }\n if (refDesc.target !== expectedName) {\n throw new MaterializedViewConfigError(\n `\"${mvName}\": projection collect leg \"${leg.as}\" expects field \"${leg.on}\" of collection `\n + `\"${leg.collect}\" to reference ${leg.from === undefined\n ? `the projection source \"${expectedName}\"`\n : `\"${expectedName}\" (the collection behind from: \"${leg.from}\")`}`\n + `, but its ref() targets \"${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 // `from` matches against the attached record's id, not the primary row's.\n const anchor = leg.from === undefined\n ? row\n : (row[leg.from] as Record<string, unknown> | null | undefined)\n const key = anchor == null ? null : coerceCollectKey(anchor.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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,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,MAAM;AACxB,QAAI,IAAI,M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AAM,WAAW,OAAO,OAAO;AAC/B;AAAA,UACF;AAAA,QACF,SAAS,KAAK;AACZ;AACA,cAAI,OAAQ,OAAM;AAElB,kBAAQ,KAAK,SAAS,KAAK,IAAI,8BAA8B,OAAO,MAAM,GAAG;AAAA,QAC/E;AAAA,MACF;AAAA,IACF;AAEA,WAAO,EAAE,SAAS,SAAS,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,9 +1,11 @@
1
1
  import {
2
2
  sha256Hex
3
- } from "./chunk-AU3AUJIZ.js";
3
+ } from "./chunk-RQQIB7CD.js";
4
4
  import {
5
- MaterializedViewSourceUnknownError
6
- } from "./chunk-CWM4GQD2.js";
5
+ MaterializedViewConfigError,
6
+ MaterializedViewSourceUnknownError,
7
+ RefNotDeclaredError
8
+ } from "./chunk-HKANJAOP.js";
7
9
 
8
10
  // src/with-formula/materialized-views/dependency-analyzer.ts
9
11
  function analyzeDependencies(query) {
@@ -44,7 +46,10 @@ function summarizeQueryPlan(query) {
44
46
  as: c.as,
45
47
  // Inline on: callback: use sentinel — drift detection disabled for this MV
46
48
  onPredicateName: c.onPredicateName ?? (c.on ? "[inline]" : null),
47
- maxRows: c.maxRows ?? null
49
+ maxRows: c.maxRows ?? null,
50
+ // `outer` changes the row set, so it is part of the plan's identity
51
+ // for drift detection, not decoration (#1130).
52
+ outer: c.outer ?? false
48
53
  };
49
54
  }
50
55
  return c;
@@ -60,9 +65,10 @@ function summarizeUnionPlan(spec) {
60
65
  }
61
66
  function summarizeProjectionPlan(spec) {
62
67
  const projection = spec.projection;
63
- const legs = projection.joins.map(
64
- (leg) => "collect" in leg ? `collect:${leg.collect}.${leg.on}\u2192${leg.as}` : `field:${leg.field}\u2192${leg.as}`
65
- ).sort();
68
+ const legs = projection.joins.map((leg) => {
69
+ const at = leg.from !== void 0 ? `@${leg.from}` : "";
70
+ return "collect" in leg ? `collect${at}:${leg.collect}.${leg.on}\u2192${leg.as}` : `field${at}:${leg.field}\u2192${leg.as}`;
71
+ }).sort();
66
72
  const body = JSON.stringify({ source: projection.source, legs });
67
73
  return `projection(${body})${summarizeGroupingTail(spec)}`;
68
74
  }
@@ -102,6 +108,44 @@ function canonicalizeQueryPlan(plan) {
102
108
  });
103
109
  }
104
110
 
111
+ // src/with-formula/materialized-views/projection-legs.ts
112
+ function isCollectLeg(leg) {
113
+ return "collect" in leg;
114
+ }
115
+ function validateProjectionLegs(mvName, projection) {
116
+ const seen = /* @__PURE__ */ new Map();
117
+ for (const leg of projection.joins) {
118
+ if (leg.from !== void 0) {
119
+ const parent = seen.get(leg.from);
120
+ if (!parent) {
121
+ throw new MaterializedViewConfigError(
122
+ `"${mvName}": projection leg "${leg.as}" declares from: "${leg.from}", which is not an alias declared EARLIER in \`joins\`. A leg may only attach to the primary row or to a preceding leg \u2014 that ordering rule is what makes a cycle impossible. Known so far: ${[...seen.keys()].map((a) => `"${a}"`).join(", ") || "(none)"}`
123
+ );
124
+ }
125
+ if (isCollectLeg(parent)) {
126
+ throw new MaterializedViewConfigError(
127
+ `"${mvName}": projection leg "${leg.as}" declares from: "${leg.from}", but "${leg.from}" is a collect leg and holds an ARRAY of rows, not one record. A leg can only hang off a forward leg (record | null). Attach it to the primary row instead, or collect the far side directly if its ref() reaches "${projection.source}".`
128
+ );
129
+ }
130
+ }
131
+ seen.set(leg.as, leg);
132
+ }
133
+ }
134
+ function resolveLegOwner(leg, joins, source, resolveRef) {
135
+ if (leg.from === void 0) return source;
136
+ const parent = joins.find((l) => l.as === leg.from);
137
+ if (!parent) return null;
138
+ if (isCollectLeg(parent)) return parent.collect;
139
+ const parentOwner = resolveLegOwner(parent, joins, source, resolveRef);
140
+ if (parentOwner === null) return null;
141
+ return resolveRef(parentOwner, parent.field)?.target ?? null;
142
+ }
143
+ function resolveForwardLegTarget(leg, joins, source, resolveRef) {
144
+ const owner = resolveLegOwner(leg, joins, source, resolveRef);
145
+ if (owner === null) return null;
146
+ return resolveRef(owner, leg.field)?.target ?? null;
147
+ }
148
+
105
149
  // src/with-formula/materialized-views/registry.ts
106
150
  var WHOLE_RECORD = "*";
107
151
  var MaterializedViewRegistry = class {
@@ -123,6 +167,33 @@ var MaterializedViewRegistry = class {
123
167
  * target has resolved (see `_resolvePendingForwardDeps`).
124
168
  */
125
169
  _pendingForwardDeps = [];
170
+ /**
171
+ * Query-form strategies whose `query()` callback could not be planned at
172
+ * registration time because a `.join()` names a field whose `ref()` is not
173
+ * declared YET (#1139).
174
+ *
175
+ * Registration runs inside `openVault()`; a collection's refs can only be
176
+ * declared afterwards, so for a query-form MV that joins a declared FK there
177
+ * is NO call ordering the consumer can choose — the plan is simply built too
178
+ * early. Rather than failing the vault open, the strategy is parked here and
179
+ * replanned from {@link resolvePendingPlans}, which every write dispatch and
180
+ * `vault.refreshView()` call runs first. This is the query-form counterpart
181
+ * of `_pendingForwardDeps`, one level up: that defers a leg's TARGET, this
182
+ * defers the whole plan.
183
+ *
184
+ * Only `RefNotDeclaredError` parks a strategy. Every other planning failure
185
+ * still throws out of `openVault()` exactly as before, so a typo'd source or
186
+ * a malformed spec keeps its loud, early error.
187
+ *
188
+ * A parked strategy is invisible until it resolves: it contributes no
189
+ * `_bySource` entries and no cycle-detection edges (same caveat as a
190
+ * late-resolved forward target — `edges()` runs once at vault open). It also
191
+ * cannot be dispatched, which is why {@link hasPendingPlans} forces the
192
+ * conservative branch in `Collection._txAtomicSafe`: the atomic write path
193
+ * skips MV dispatch, and skipping it here would mean the write that was
194
+ * supposed to trigger the first replan is the one that gets missed.
195
+ */
196
+ _pendingPlans = [];
126
197
  /**
127
198
  * Register an MV. Invokes `spec.query()` once at registration time to
128
199
  * read the plan + join context; the resulting `Query<T>` is discarded
@@ -149,13 +220,20 @@ var MaterializedViewRegistry = class {
149
220
  const projection = spec.projection;
150
221
  dependencies = /* @__PURE__ */ new Set([projection.source]);
151
222
  for (const leg of projection.joins) {
152
- if ("collect" in leg) dependencies.add(leg.collect);
153
- else pendingForwardFields.push(leg.field);
223
+ if (isCollectLeg(leg)) dependencies.add(leg.collect);
224
+ else pendingForwardFields.push(leg.as);
154
225
  }
155
226
  if (spec.sources) for (const s of spec.sources) dependencies.add(s);
156
227
  queryPlanSummary = summarizeProjectionPlan(spec);
157
228
  } else {
158
- const q = spec.query(dbForQuery);
229
+ let q;
230
+ try {
231
+ q = spec.query(dbForQuery);
232
+ } catch (e) {
233
+ if (!(e instanceof RefNotDeclaredError)) throw e;
234
+ this._pendingPlans.push({ spec, db, ...options !== void 0 ? { options } : {} });
235
+ return;
236
+ }
159
237
  qAny = q;
160
238
  isQuery = typeof qAny._plan === "function";
161
239
  if (isQuery) {
@@ -203,15 +281,51 @@ var MaterializedViewRegistry = class {
203
281
  }
204
282
  if (pendingForwardFields.length > 0) {
205
283
  const refRegistry = db.refRegistry;
206
- const source = spec.projection.source;
284
+ const projectionSpec = spec.projection;
285
+ const resolveRef = (c, f) => refRegistry?.getOutbound(c)[f] ?? null;
207
286
  this._pendingForwardDeps.push({
208
287
  reg,
209
- fields: new Set(pendingForwardFields),
210
- resolveTarget: (field) => refRegistry?.getOutbound(source)[field]?.target ?? null
288
+ aliases: new Set(pendingForwardFields),
289
+ resolveTarget: (alias) => {
290
+ const leg = projectionSpec.joins.find((l) => l.as === alias);
291
+ if (!leg || isCollectLeg(leg)) return null;
292
+ return resolveForwardLegTarget(leg, projectionSpec.joins, projectionSpec.source, resolveRef);
293
+ }
211
294
  });
212
295
  this._resolvePendingForwardDeps();
213
296
  }
214
297
  }
298
+ /**
299
+ * `true` while any query-form strategy is still unplanned (#1139). Read by
300
+ * `Collection._txAtomicSafe`, which must refuse the atomic write path while
301
+ * this holds — see the `_pendingPlans` doc comment for why.
302
+ */
303
+ hasPendingPlans() {
304
+ return this._pendingPlans.length > 0;
305
+ }
306
+ /**
307
+ * Replan every parked query-form strategy (#1139). Called at the head of both
308
+ * write dispatchers and of `vault.refreshView()`, so a strategy resolves on the
309
+ * first write or refresh after its source collection's refs are declared —
310
+ * which is the earliest moment it could produce a correct plan, and strictly
311
+ * before the first moment it could have any output to produce.
312
+ *
313
+ * Each entry is handed straight back to {@link register}, so a strategy that
314
+ * is STILL unplannable simply re-parks itself and the next dispatch tries
315
+ * again. Idempotent and cheap: the array empties as strategies resolve, and
316
+ * both callers skip the await entirely once it is empty.
317
+ *
318
+ * A late-resolved strategy does NOT retro-feed `edges()` — the unified cycle
319
+ * pass runs once at vault open, before refs exist. Same caveat, and the same
320
+ * reason, as a late-resolved forward-leg target.
321
+ */
322
+ async resolvePendingPlans() {
323
+ if (this._pendingPlans.length === 0) return;
324
+ const parked = this._pendingPlans.splice(0);
325
+ for (const entry of parked) {
326
+ await this.register(entry.spec, entry.db, entry.options);
327
+ }
328
+ }
215
329
  /** All MVs that depend on `source`, in registration order. */
216
330
  mvsForSource(source) {
217
331
  if (this._pendingForwardDeps.length > 0) this._resolvePendingForwardDeps();
@@ -234,17 +348,17 @@ var MaterializedViewRegistry = class {
234
348
  _resolvePendingForwardDeps() {
235
349
  for (let i = this._pendingForwardDeps.length - 1; i >= 0; i--) {
236
350
  const entry = this._pendingForwardDeps[i];
237
- for (const field of [...entry.fields]) {
238
- const target = entry.resolveTarget(field);
351
+ for (const alias of [...entry.aliases]) {
352
+ const target = entry.resolveTarget(alias);
239
353
  if (target === null) continue;
240
- entry.fields.delete(field);
354
+ entry.aliases.delete(alias);
241
355
  if (entry.reg.dependencies.has(target)) continue;
242
356
  entry.reg.dependencies.add(target);
243
357
  const arr = this._bySource.get(target);
244
358
  if (arr) arr.push(entry.reg);
245
359
  else this._bySource.set(target, [entry.reg]);
246
360
  }
247
- if (entry.fields.size === 0) this._pendingForwardDeps.splice(i, 1);
361
+ if (entry.aliases.size === 0) this._pendingForwardDeps.splice(i, 1);
248
362
  }
249
363
  }
250
364
  /** Single MV by name, or `undefined`. */
@@ -363,7 +477,10 @@ export {
363
477
  summarizeQueryPlan,
364
478
  computeQueryHash,
365
479
  canonicalizeQueryPlan,
480
+ isCollectLeg,
481
+ validateProjectionLegs,
482
+ resolveLegOwner,
366
483
  MaterializedViewRegistry,
367
484
  wrapDbWithPredicates
368
485
  };
369
- //# sourceMappingURL=chunk-3O72ZD2E.js.map
486
+ //# sourceMappingURL=chunk-LPVZDTQF.js.map