@noy-db/hub 0.2.0-pre.9 → 0.3.0-pre.2

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 (541) hide show
  1. package/README.md +129 -3
  2. package/dist/adapter/index.d.ts +5 -0
  3. package/dist/adapter/index.js +15 -0
  4. package/dist/aggregate/index.d.ts +6 -2
  5. package/dist/aggregate/index.js +24 -16
  6. package/dist/aggregate/index.js.map +1 -1
  7. package/dist/api-RW3KP7WU.js +14 -0
  8. package/dist/as/index.d.ts +7 -0
  9. package/dist/as/index.js +24 -0
  10. package/dist/at/index.d.ts +5 -0
  11. package/dist/at/index.js +1 -0
  12. package/dist/attestation/index.d.ts +15 -47
  13. package/dist/attestation/index.js +54 -10
  14. package/dist/attestation/index.js.map +1 -1
  15. package/dist/backup-KMJQ66MF.js +219 -0
  16. package/dist/backup-KMJQ66MF.js.map +1 -0
  17. package/dist/blobs/index.d.ts +6 -8
  18. package/dist/blobs/index.js +19 -12
  19. package/dist/blobs/index.js.map +1 -1
  20. package/dist/bundle/index.d.ts +16 -70
  21. package/dist/bundle/index.js +39 -476
  22. package/dist/bundle/index.js.map +1 -1
  23. package/dist/{ulid-CJ8RzRrm.d.ts → bundle-PwBGkhpe.d.ts} +31 -86
  24. package/dist/by/index.d.ts +1 -0
  25. package/dist/by/index.js +11 -0
  26. package/dist/cargo/index.d.ts +9 -0
  27. package/dist/cargo/index.js +89 -0
  28. package/dist/chunk-26LGBE4T.js +42 -0
  29. package/dist/chunk-26LGBE4T.js.map +1 -0
  30. package/dist/{chunk-K3DK3NU5.js → chunk-3YFXJ3ZP.js} +20 -5
  31. package/dist/chunk-3YFXJ3ZP.js.map +1 -0
  32. package/dist/chunk-4Q6HSHHL.js +90 -0
  33. package/dist/chunk-4Q6HSHHL.js.map +1 -0
  34. package/dist/chunk-5LUY7UTV.js +380 -0
  35. package/dist/chunk-5LUY7UTV.js.map +1 -0
  36. package/dist/chunk-5N6CZTCY.js +367 -0
  37. package/dist/chunk-5N6CZTCY.js.map +1 -0
  38. package/dist/chunk-5O3AOPDT.js +992 -0
  39. package/dist/chunk-5O3AOPDT.js.map +1 -0
  40. package/dist/chunk-5R3ERCDH.js +239 -0
  41. package/dist/chunk-5R3ERCDH.js.map +1 -0
  42. package/dist/chunk-5TDJ56JE.js +32 -0
  43. package/dist/chunk-5TDJ56JE.js.map +1 -0
  44. package/dist/{chunk-T7JEBOGN.js → chunk-62QYRORB.js} +18 -11
  45. package/dist/chunk-62QYRORB.js.map +1 -0
  46. package/dist/{chunk-J66GRPNH.js → chunk-6S7T6WC4.js} +2 -2
  47. package/dist/chunk-6S7T6WC4.js.map +1 -0
  48. package/dist/chunk-76722EBH.js +451 -0
  49. package/dist/chunk-76722EBH.js.map +1 -0
  50. package/dist/{chunk-Z6FNBOTC.js → chunk-AIWULCUO.js} +13 -17
  51. package/dist/chunk-AIWULCUO.js.map +1 -0
  52. package/dist/{chunk-O3VZPBZG.js → chunk-AQTBSL7R.js} +47 -11
  53. package/dist/chunk-AQTBSL7R.js.map +1 -0
  54. package/dist/chunk-AURFOK3D.js +35 -0
  55. package/dist/chunk-AURFOK3D.js.map +1 -0
  56. package/dist/{chunk-53XBRIRT.js → chunk-AXRXJTE2.js} +9 -9
  57. package/dist/chunk-AXRXJTE2.js.map +1 -0
  58. package/dist/chunk-AZAOEIKW.js +155 -0
  59. package/dist/chunk-AZAOEIKW.js.map +1 -0
  60. package/dist/{chunk-HNRHLRDC.js → chunk-BG3SPSR4.js} +3 -3
  61. package/dist/chunk-BG3SPSR4.js.map +1 -0
  62. package/dist/chunk-BGIZAFY7.js +1 -0
  63. package/dist/chunk-CHFZDSE4.js +1 -0
  64. package/dist/{chunk-DJHHA6XH.js → chunk-CMGR4ZEW.js} +50 -20
  65. package/dist/chunk-CMGR4ZEW.js.map +1 -0
  66. package/dist/chunk-CWPPNPOH.js +23 -0
  67. package/dist/chunk-CWPPNPOH.js.map +1 -0
  68. package/dist/{chunk-QODLLGQ7.js → chunk-DFEMTNPJ.js} +371 -38
  69. package/dist/chunk-DFEMTNPJ.js.map +1 -0
  70. package/dist/{chunk-ZYWZWG6G.js → chunk-DGDI2D4M.js} +10 -10
  71. package/dist/chunk-DGDI2D4M.js.map +1 -0
  72. package/dist/{chunk-SYMWGEET.js → chunk-EIZUR2XW.js} +3 -3
  73. package/dist/chunk-EIZUR2XW.js.map +1 -0
  74. package/dist/{chunk-BVRYKATC.js → chunk-FISN7WE4.js} +36 -33
  75. package/dist/chunk-FISN7WE4.js.map +1 -0
  76. package/dist/chunk-GHVIKOHT.js +1 -0
  77. package/dist/chunk-GYGWYIOZ.js +200 -0
  78. package/dist/chunk-GYGWYIOZ.js.map +1 -0
  79. package/dist/chunk-HCIPRAGS.js +45 -0
  80. package/dist/chunk-HCIPRAGS.js.map +1 -0
  81. package/dist/{chunk-PX35GA7L.js → chunk-I2NOIW44.js} +10 -10
  82. package/dist/chunk-I2NOIW44.js.map +1 -0
  83. package/dist/{chunk-OIF6LZUR.js → chunk-I3TIKTJO.js} +3 -3
  84. package/dist/chunk-I3TIKTJO.js.map +1 -0
  85. package/dist/chunk-I7FD46FF.js +9 -0
  86. package/dist/chunk-I7FD46FF.js.map +1 -0
  87. package/dist/chunk-IAGBDSCS.js +40 -0
  88. package/dist/chunk-IAGBDSCS.js.map +1 -0
  89. package/dist/{chunk-JWRVQKRZ.js → chunk-IELYAOGG.js} +6 -18
  90. package/dist/chunk-IELYAOGG.js.map +1 -0
  91. package/dist/chunk-IGUYVGGI.js +205 -0
  92. package/dist/chunk-IGUYVGGI.js.map +1 -0
  93. package/dist/{chunk-U26HQ6KJ.js → chunk-IO6GRPT6.js} +4 -4
  94. package/dist/chunk-IO6GRPT6.js.map +1 -0
  95. package/dist/chunk-IPB7FTQX.js +273 -0
  96. package/dist/chunk-IPB7FTQX.js.map +1 -0
  97. package/dist/chunk-ITNUCOXM.js +148 -0
  98. package/dist/chunk-ITNUCOXM.js.map +1 -0
  99. package/dist/{chunk-WPLVTJ5D.js → chunk-IUEN57TV.js} +10 -10
  100. package/dist/chunk-IUEN57TV.js.map +1 -0
  101. package/dist/{chunk-DL3HWOQ5.js → chunk-JNUWZ6D3.js} +9 -9
  102. package/dist/chunk-JNUWZ6D3.js.map +1 -0
  103. package/dist/chunk-K2WCO3NX.js +1 -0
  104. package/dist/chunk-KVOXU4T5.js +30 -0
  105. package/dist/chunk-KVOXU4T5.js.map +1 -0
  106. package/dist/chunk-KXGNJJXB.js +135 -0
  107. package/dist/chunk-KXGNJJXB.js.map +1 -0
  108. package/dist/chunk-LB7FD65R.js +163 -0
  109. package/dist/chunk-LB7FD65R.js.map +1 -0
  110. package/dist/{chunk-22DWZL57.js → chunk-LFLXAY2W.js} +43 -218
  111. package/dist/chunk-LFLXAY2W.js.map +1 -0
  112. package/dist/chunk-LMTH2RM6.js +129 -0
  113. package/dist/chunk-LMTH2RM6.js.map +1 -0
  114. package/dist/{aggregate/index.cjs → chunk-LV7M27WM.js} +390 -219
  115. package/dist/chunk-LV7M27WM.js.map +1 -0
  116. package/dist/{chunk-PE2FR4J3.js → chunk-LXQT4WMP.js} +16 -18
  117. package/dist/chunk-LXQT4WMP.js.map +1 -0
  118. package/dist/chunk-M2YKN37S.js +524 -0
  119. package/dist/chunk-M2YKN37S.js.map +1 -0
  120. package/dist/chunk-M6OST55S.js +14 -0
  121. package/dist/chunk-M6OST55S.js.map +1 -0
  122. package/dist/{chunk-F3GDRNUT.js → chunk-MD3Y6J3L.js} +35 -69
  123. package/dist/chunk-MD3Y6J3L.js.map +1 -0
  124. package/dist/{chunk-XJFLDA7A.js → chunk-MTMJVJ5W.js} +8 -7
  125. package/dist/chunk-MTMJVJ5W.js.map +1 -0
  126. package/dist/{chunk-DFMLEQZB.js → chunk-NF5JWERG.js} +5 -10
  127. package/dist/chunk-NF5JWERG.js.map +1 -0
  128. package/dist/{chunk-DO7C2TOG.js → chunk-PKHL44ER.js} +3 -3
  129. package/dist/{chunk-DO7C2TOG.js.map → chunk-PKHL44ER.js.map} +1 -1
  130. package/dist/{chunk-6CME4UEK.js → chunk-PSHOXR6C.js} +7008 -4827
  131. package/dist/chunk-PSHOXR6C.js.map +1 -0
  132. package/dist/chunk-PSMV73A5.js +117 -0
  133. package/dist/chunk-PSMV73A5.js.map +1 -0
  134. package/dist/chunk-PY4KJPYU.js +9 -0
  135. package/dist/chunk-PY4KJPYU.js.map +1 -0
  136. package/dist/chunk-PZ5AY32C.js +10 -0
  137. package/dist/{chunk-DE6GKS6G.js → chunk-Q7SS3IME.js} +50 -9
  138. package/dist/chunk-Q7SS3IME.js.map +1 -0
  139. package/dist/chunk-QHJW5EXU.js +54 -0
  140. package/dist/chunk-QHJW5EXU.js.map +1 -0
  141. package/dist/chunk-QZISFCVG.js +233 -0
  142. package/dist/chunk-QZISFCVG.js.map +1 -0
  143. package/dist/{chunk-NONAAENK.js → chunk-RUEKROOS.js} +11 -4
  144. package/dist/chunk-RUEKROOS.js.map +1 -0
  145. package/dist/chunk-RUIMKQTA.js +23 -0
  146. package/dist/chunk-RUIMKQTA.js.map +1 -0
  147. package/dist/{chunk-TFBP23BX.js → chunk-SKF73JOP.js} +66 -7
  148. package/dist/chunk-SKF73JOP.js.map +1 -0
  149. package/dist/chunk-SM3AVUHC.js +42 -0
  150. package/dist/chunk-SM3AVUHC.js.map +1 -0
  151. package/dist/{chunk-ML236QKC.js → chunk-SMXWYP24.js} +5 -5
  152. package/dist/chunk-SMXWYP24.js.map +1 -0
  153. package/dist/chunk-SRB2XEWB.js +148 -0
  154. package/dist/chunk-SRB2XEWB.js.map +1 -0
  155. package/dist/chunk-SVLR4POP.js +64 -0
  156. package/dist/chunk-SVLR4POP.js.map +1 -0
  157. package/dist/chunk-TA66UMI4.js +123 -0
  158. package/dist/chunk-TA66UMI4.js.map +1 -0
  159. package/dist/chunk-TEILUWOI.js +664 -0
  160. package/dist/chunk-TEILUWOI.js.map +1 -0
  161. package/dist/chunk-TJYQIGAP.js +82 -0
  162. package/dist/chunk-TJYQIGAP.js.map +1 -0
  163. package/dist/{chunk-H2X3ISXG.js → chunk-UAG5KWVA.js} +7 -7
  164. package/dist/chunk-UAG5KWVA.js.map +1 -0
  165. package/dist/chunk-UDRIWL7A.js +382 -0
  166. package/dist/chunk-UDRIWL7A.js.map +1 -0
  167. package/dist/{chunk-2GLDA55J.js → chunk-UIU2THRG.js} +498 -133
  168. package/dist/chunk-UIU2THRG.js.map +1 -0
  169. package/dist/{chunk-3YPCK6JX.js → chunk-UPJNJGGA.js} +165 -423
  170. package/dist/chunk-UPJNJGGA.js.map +1 -0
  171. package/dist/chunk-UV5MFVO3.js +21 -0
  172. package/dist/chunk-UV5MFVO3.js.map +1 -0
  173. package/dist/{chunk-2WUSG3IT.js → chunk-V7RWQRG7.js} +5 -5
  174. package/dist/chunk-V7RWQRG7.js.map +1 -0
  175. package/dist/{chunk-VTKGMEPP.js → chunk-VCTFO5CO.js} +13 -3
  176. package/dist/chunk-VCTFO5CO.js.map +1 -0
  177. package/dist/{chunk-5T22KDPN.js → chunk-VFQGRQIH.js} +8 -8
  178. package/dist/chunk-VFQGRQIH.js.map +1 -0
  179. package/dist/{chunk-2QR2PQTT.js → chunk-VQNJ7UZL.js} +5 -3
  180. package/dist/chunk-VQNJ7UZL.js.map +1 -0
  181. package/dist/{chunk-DONMZAD2.js → chunk-WWGT2MDV.js} +43 -165
  182. package/dist/chunk-WWGT2MDV.js.map +1 -0
  183. package/dist/{chunk-EMIGCR7X.js → chunk-WXSYDNBT.js} +2 -2
  184. package/dist/chunk-WXSYDNBT.js.map +1 -0
  185. package/dist/chunk-WYSO2NIH.js +30 -0
  186. package/dist/chunk-WYSO2NIH.js.map +1 -0
  187. package/dist/chunk-XXYIOFUB.js +164 -0
  188. package/dist/chunk-XXYIOFUB.js.map +1 -0
  189. package/dist/{chunk-3BFJOWSU.js → chunk-Y22T3KQE.js} +35 -7
  190. package/dist/chunk-Y22T3KQE.js.map +1 -0
  191. package/dist/{chunk-A3JMGXPG.js → chunk-YMUGBZN2.js} +2 -2
  192. package/dist/chunk-YMUGBZN2.js.map +1 -0
  193. package/dist/{chunk-I5FOWO4J.js → chunk-ZCGAHGUS.js} +52 -73
  194. package/dist/chunk-ZCGAHGUS.js.map +1 -0
  195. package/dist/{chunk-FZU343FL.js → chunk-ZJADGNYF.js} +2 -2
  196. package/dist/chunk-ZJADGNYF.js.map +1 -0
  197. package/dist/{chunk-B6PB7JLN.js → chunk-ZYUC53LT.js} +427 -6
  198. package/dist/chunk-ZYUC53LT.js.map +1 -0
  199. package/dist/collection-facade-GQAOGJP2.js +33 -0
  200. package/dist/consent/index.d.ts +5 -7
  201. package/dist/consent/index.js +7 -5
  202. package/dist/consent/index.js.map +1 -1
  203. package/dist/crdt/index.d.ts +6 -2
  204. package/dist/crdt/index.js +3 -2
  205. package/dist/crdt/index.js.map +1 -1
  206. package/dist/decrypt-partition-IHtxEnTi.d.ts +21 -0
  207. package/dist/delegation-UL5HKLER.js +19 -0
  208. package/dist/derivations/index.d.ts +7 -9
  209. package/dist/derivations/index.js +11 -6
  210. package/dist/describe/index.d.ts +1 -0
  211. package/dist/describe/index.js +1 -0
  212. package/dist/describe-Ccd1hS7a.d.ts +143 -0
  213. package/dist/{dev-unlock-B4kDxep_.d.ts → dev-unlock-h0K-UZTk.d.ts} +1 -1
  214. package/dist/discriminant-BN9REW3o.d.ts +60 -0
  215. package/dist/enclave-UL5LW66V.js +88 -0
  216. package/dist/executor-2FWQRLMG.js +15 -0
  217. package/dist/executor-QZ7BXICW.js +9 -0
  218. package/dist/executor-Z5ZLJVTV.js +9 -0
  219. package/dist/export-accessible-KRV5W4GH.js +17 -0
  220. package/dist/extract-partition-GLKBOXFQ.js +30 -0
  221. package/dist/{fanout-sidecar-OKPMMPLG.js → fanout-sidecar-GF3DJ6KR.js} +34 -14
  222. package/dist/fanout-sidecar-GF3DJ6KR.js.map +1 -0
  223. package/dist/forget/index.d.ts +36 -0
  224. package/dist/forget/index.js +19 -0
  225. package/dist/forget/index.js.map +1 -0
  226. package/dist/guards/index.d.ts +13 -9
  227. package/dist/guards/index.js +12 -5
  228. package/dist/{hash-DdpVypUp.d.cts → hash-CdSr06sm.d.ts} +5 -1
  229. package/dist/history/index.d.ts +6 -8
  230. package/dist/history/index.js +19 -12
  231. package/dist/history/index.js.map +1 -1
  232. package/dist/i18n/index.d.ts +5 -7
  233. package/dist/i18n/index.js +104 -15
  234. package/dist/i18n/index.js.map +1 -1
  235. package/dist/in/index.d.ts +5 -0
  236. package/dist/in/index.js +1 -0
  237. package/dist/in/index.js.map +1 -0
  238. package/dist/index-B9QdHytu.d.ts +123 -0
  239. package/dist/index-CGLLRtFc.d.ts +123 -0
  240. package/dist/{types-Df28QFKb.d.ts → index-_6At2_9_.d.ts} +16270 -8358
  241. package/dist/index.d.ts +1088 -450
  242. package/dist/index.js +1165 -293
  243. package/dist/index.js.map +1 -1
  244. package/dist/indexing/index.d.ts +6 -3
  245. package/dist/indexing/index.js +6 -5
  246. package/dist/indexing/index.js.map +1 -1
  247. package/dist/issue-Y6UVIR43.js +13 -0
  248. package/dist/issue-Y6UVIR43.js.map +1 -0
  249. package/dist/kernel/index.d.ts +32 -0
  250. package/dist/kernel/index.js +53 -0
  251. package/dist/kernel/index.js.map +1 -0
  252. package/dist/{ledger-TMRZYNVJ.js → ledger-RYI35CDS.js} +12 -9
  253. package/dist/ledger-RYI35CDS.js.map +1 -0
  254. package/dist/liberate-CRPZEV7O.js +18 -0
  255. package/dist/liberate-CRPZEV7O.js.map +1 -0
  256. package/dist/materialized-views/index.d.ts +6 -19
  257. package/dist/materialized-views/index.js +16 -12
  258. package/dist/mime-magic-B4RoFj3B.d.ts +103 -0
  259. package/dist/noydb-LDEBLNHY.js +50 -0
  260. package/dist/noydb-LDEBLNHY.js.map +1 -0
  261. package/dist/on/index.d.ts +5 -0
  262. package/dist/on/index.js +11 -0
  263. package/dist/on/index.js.map +1 -0
  264. package/dist/overlay-views/index.d.ts +27 -11
  265. package/dist/overlay-views/index.js +7 -6
  266. package/dist/periods/index.d.ts +5 -7
  267. package/dist/periods/index.js +13 -9
  268. package/dist/pod/index.d.ts +63 -0
  269. package/dist/pod/index.js +61 -0
  270. package/dist/pod/index.js.map +1 -0
  271. package/dist/policy-IXK4FVXP.js +41 -0
  272. package/dist/policy-IXK4FVXP.js.map +1 -0
  273. package/dist/portability/index.d.ts +20 -0
  274. package/dist/portability/index.js +43 -0
  275. package/dist/portability/index.js.map +1 -0
  276. package/dist/{public-envelope-BW6OXORV.js → public-envelope-JHDQCPSX.js} +6 -5
  277. package/dist/public-envelope-JHDQCPSX.js.map +1 -0
  278. package/dist/query/index.d.ts +5 -3
  279. package/dist/query/index.js +21 -13
  280. package/dist/read-only-facade-5ADRJVTM.js +8 -0
  281. package/dist/read-only-facade-5ADRJVTM.js.map +1 -0
  282. package/dist/registry-45RJNWGU.js +9 -0
  283. package/dist/registry-45RJNWGU.js.map +1 -0
  284. package/dist/registry-5GRV5VXI.js +13 -0
  285. package/dist/registry-5GRV5VXI.js.map +1 -0
  286. package/dist/registry-VW6P6A3J.js +8 -0
  287. package/dist/registry-VW6P6A3J.js.map +1 -0
  288. package/dist/registry-WEUCHBO4.js +11 -0
  289. package/dist/registry-WEUCHBO4.js.map +1 -0
  290. package/dist/request-withdrawal-GBPH2FDY.js +25 -0
  291. package/dist/request-withdrawal-GBPH2FDY.js.map +1 -0
  292. package/dist/revoke-TUFRGI6S.js +18 -0
  293. package/dist/revoke-TUFRGI6S.js.map +1 -0
  294. package/dist/sealed-record/index.d.ts +69 -0
  295. package/dist/sealed-record/index.js +65 -0
  296. package/dist/sealed-record/index.js.map +1 -0
  297. package/dist/session/index.d.ts +6 -8
  298. package/dist/session/index.js +7 -5
  299. package/dist/session/index.js.map +1 -1
  300. package/dist/shadow/index.d.ts +5 -7
  301. package/dist/shadow/index.js +4 -3
  302. package/dist/shadow/index.js.map +1 -1
  303. package/dist/{signer-72QAUSVW.js → signer-PNKTBVF7.js} +6 -5
  304. package/dist/signer-PNKTBVF7.js.map +1 -0
  305. package/dist/snapshots/index.d.ts +6 -8
  306. package/dist/snapshots/index.js +13 -11
  307. package/dist/snapshots/index.js.map +1 -1
  308. package/dist/{stale-6ZDBTQT7.js → stale-3JWHNDIY.js} +3 -2
  309. package/dist/stale-3JWHNDIY.js.map +1 -0
  310. package/dist/store-coordination-provider-3I7XWZZK.js +142 -0
  311. package/dist/store-coordination-provider-3I7XWZZK.js.map +1 -0
  312. package/dist/subject-index-O75wKshW.d.ts +362 -0
  313. package/dist/sync/index.d.ts +4 -6
  314. package/dist/sync/index.js +7 -6
  315. package/dist/sync/index.js.map +1 -1
  316. package/dist/team/index.d.ts +5 -7
  317. package/dist/team/index.js +20 -16
  318. package/dist/tiers/index.d.ts +5 -0
  319. package/dist/tiers/index.js +33 -0
  320. package/dist/tiers/index.js.map +1 -0
  321. package/dist/to/index.d.ts +5 -0
  322. package/dist/to/index.js +17 -0
  323. package/dist/to/index.js.map +1 -0
  324. package/dist/transition-guard-DqodPNKw.d.ts +165 -0
  325. package/dist/tx/index.d.ts +23 -9
  326. package/dist/tx/index.js +13 -8
  327. package/dist/tx/index.js.map +1 -1
  328. package/dist/ui/index.d.ts +1 -0
  329. package/dist/ui/index.js +1 -0
  330. package/dist/ui/index.js.map +1 -0
  331. package/dist/ulid-DRH25k3y.d.ts +66 -0
  332. package/dist/ulid-PTAIMDG4.js +10 -0
  333. package/dist/ulid-PTAIMDG4.js.map +1 -0
  334. package/dist/util/index.d.ts +2 -0
  335. package/dist/util/index.js +7 -2
  336. package/dist/util/index.js.map +1 -1
  337. package/dist/vault-diff-BtpiBvic.d.ts +147 -0
  338. package/dist/with/index.d.ts +38 -0
  339. package/dist/with/index.js +25 -0
  340. package/dist/with/index.js.map +1 -0
  341. package/dist/{with-materialized-view-BLkQxoQN.d.ts → with-materialized-view-DMmWtYfJ.d.ts} +1 -1
  342. package/dist/{with-overlayed-view-CRsSEwHR.d.ts → with-overlayed-view-D_IB2nkM.d.ts} +2 -3
  343. package/dist/with-rollup-em2wxoHP.d.ts +47 -0
  344. package/dist/withdraw-accessible-FFS46EOD.js +22 -0
  345. package/dist/withdraw-accessible-FFS46EOD.js.map +1 -0
  346. package/dist/zod-HAJM7LMS.js +14763 -0
  347. package/dist/zod-HAJM7LMS.js.map +1 -0
  348. package/package.json +121 -201
  349. package/dist/aggregate/index.cjs.map +0 -1
  350. package/dist/aggregate/index.d.cts +0 -38
  351. package/dist/attestation/index.cjs +0 -305
  352. package/dist/attestation/index.cjs.map +0 -1
  353. package/dist/attestation/index.d.cts +0 -52
  354. package/dist/blobs/index.cjs +0 -1480
  355. package/dist/blobs/index.cjs.map +0 -1
  356. package/dist/blobs/index.d.cts +0 -46
  357. package/dist/bundle/index.cjs +0 -19264
  358. package/dist/bundle/index.cjs.map +0 -1
  359. package/dist/bundle/index.d.cts +0 -176
  360. package/dist/chunk-22DWZL57.js.map +0 -1
  361. package/dist/chunk-2GLDA55J.js.map +0 -1
  362. package/dist/chunk-2QR2PQTT.js.map +0 -1
  363. package/dist/chunk-2WUSG3IT.js.map +0 -1
  364. package/dist/chunk-3BFJOWSU.js.map +0 -1
  365. package/dist/chunk-3YPCK6JX.js.map +0 -1
  366. package/dist/chunk-53XBRIRT.js.map +0 -1
  367. package/dist/chunk-5T22KDPN.js.map +0 -1
  368. package/dist/chunk-5XHKQ56N.js +0 -340
  369. package/dist/chunk-5XHKQ56N.js.map +0 -1
  370. package/dist/chunk-6CME4UEK.js.map +0 -1
  371. package/dist/chunk-6STK5TQP.js +0 -139
  372. package/dist/chunk-6STK5TQP.js.map +0 -1
  373. package/dist/chunk-A3JMGXPG.js.map +0 -1
  374. package/dist/chunk-B6PB7JLN.js.map +0 -1
  375. package/dist/chunk-BVRYKATC.js.map +0 -1
  376. package/dist/chunk-DE6GKS6G.js.map +0 -1
  377. package/dist/chunk-DFMLEQZB.js.map +0 -1
  378. package/dist/chunk-DJHHA6XH.js.map +0 -1
  379. package/dist/chunk-DL3HWOQ5.js.map +0 -1
  380. package/dist/chunk-DONMZAD2.js.map +0 -1
  381. package/dist/chunk-EMIGCR7X.js.map +0 -1
  382. package/dist/chunk-F3GDRNUT.js.map +0 -1
  383. package/dist/chunk-FZU343FL.js.map +0 -1
  384. package/dist/chunk-H2X3ISXG.js.map +0 -1
  385. package/dist/chunk-HNRHLRDC.js.map +0 -1
  386. package/dist/chunk-I5FOWO4J.js.map +0 -1
  387. package/dist/chunk-J66GRPNH.js.map +0 -1
  388. package/dist/chunk-JWRVQKRZ.js.map +0 -1
  389. package/dist/chunk-K3DK3NU5.js.map +0 -1
  390. package/dist/chunk-ML236QKC.js.map +0 -1
  391. package/dist/chunk-NONAAENK.js.map +0 -1
  392. package/dist/chunk-O3VZPBZG.js.map +0 -1
  393. package/dist/chunk-OIF6LZUR.js.map +0 -1
  394. package/dist/chunk-OQ6PIGHA.js +0 -19
  395. package/dist/chunk-OQ6PIGHA.js.map +0 -1
  396. package/dist/chunk-PE2FR4J3.js.map +0 -1
  397. package/dist/chunk-PP6W64Y3.js +0 -275
  398. package/dist/chunk-PP6W64Y3.js.map +0 -1
  399. package/dist/chunk-PX35GA7L.js.map +0 -1
  400. package/dist/chunk-QEILDE6R.js +0 -793
  401. package/dist/chunk-QEILDE6R.js.map +0 -1
  402. package/dist/chunk-QODLLGQ7.js.map +0 -1
  403. package/dist/chunk-RAZ4OVLL.js +0 -51
  404. package/dist/chunk-RAZ4OVLL.js.map +0 -1
  405. package/dist/chunk-SYMWGEET.js.map +0 -1
  406. package/dist/chunk-T7JEBOGN.js.map +0 -1
  407. package/dist/chunk-TFBP23BX.js.map +0 -1
  408. package/dist/chunk-TV3YZ35S.js +0 -90
  409. package/dist/chunk-TV3YZ35S.js.map +0 -1
  410. package/dist/chunk-U26HQ6KJ.js.map +0 -1
  411. package/dist/chunk-UF3BUNQZ.js +0 -1
  412. package/dist/chunk-UMLVJTYV.js +0 -20
  413. package/dist/chunk-UMLVJTYV.js.map +0 -1
  414. package/dist/chunk-VTKGMEPP.js.map +0 -1
  415. package/dist/chunk-W6EQLGMB.js +0 -100
  416. package/dist/chunk-W6EQLGMB.js.map +0 -1
  417. package/dist/chunk-WIRRPTFH.js +0 -17
  418. package/dist/chunk-WIRRPTFH.js.map +0 -1
  419. package/dist/chunk-WPLVTJ5D.js.map +0 -1
  420. package/dist/chunk-XJFLDA7A.js.map +0 -1
  421. package/dist/chunk-Z6FNBOTC.js.map +0 -1
  422. package/dist/chunk-ZYWZWG6G.js.map +0 -1
  423. package/dist/consent/index.cjs +0 -204
  424. package/dist/consent/index.cjs.map +0 -1
  425. package/dist/consent/index.d.cts +0 -25
  426. package/dist/crdt/index.cjs +0 -152
  427. package/dist/crdt/index.cjs.map +0 -1
  428. package/dist/crdt/index.d.cts +0 -30
  429. package/dist/crypto-HTZ4FJOP.js +0 -44
  430. package/dist/delegation-RI54P6I5.js +0 -17
  431. package/dist/derivations/index.cjs +0 -351
  432. package/dist/derivations/index.cjs.map +0 -1
  433. package/dist/derivations/index.d.cts +0 -72
  434. package/dist/dev-unlock-BIoEFbwm.d.cts +0 -263
  435. package/dist/executor-5PNY7LGW.js +0 -8
  436. package/dist/executor-B4QIYGZX.js +0 -8
  437. package/dist/executor-BWXXDQ7K.js +0 -11
  438. package/dist/fanout-sidecar-OKPMMPLG.js.map +0 -1
  439. package/dist/guards/index.cjs +0 -322
  440. package/dist/guards/index.cjs.map +0 -1
  441. package/dist/guards/index.d.cts +0 -31
  442. package/dist/hash-HJqD14vS.d.ts +0 -63
  443. package/dist/history/index.cjs +0 -1222
  444. package/dist/history/index.cjs.map +0 -1
  445. package/dist/history/index.d.cts +0 -63
  446. package/dist/i18n/index.cjs +0 -1100
  447. package/dist/i18n/index.cjs.map +0 -1
  448. package/dist/i18n/index.d.cts +0 -39
  449. package/dist/index-4fBVt8j9.d.cts +0 -2387
  450. package/dist/index-D8I_pyJD.d.ts +0 -2387
  451. package/dist/index.cjs +0 -24487
  452. package/dist/index.cjs.map +0 -1
  453. package/dist/index.d.cts +0 -776
  454. package/dist/indexing/index.cjs +0 -742
  455. package/dist/indexing/index.cjs.map +0 -1
  456. package/dist/indexing/index.d.cts +0 -36
  457. package/dist/issue-VGDPP4B5.js +0 -12
  458. package/dist/lazy-builder-7tIpFyWN.d.ts +0 -304
  459. package/dist/lazy-builder-wY4pMCEe.d.cts +0 -304
  460. package/dist/materialized-views/index.cjs +0 -854
  461. package/dist/materialized-views/index.cjs.map +0 -1
  462. package/dist/materialized-views/index.d.cts +0 -186
  463. package/dist/mime-magic-CBBSOkjm.d.cts +0 -50
  464. package/dist/mime-magic-CBBSOkjm.d.ts +0 -50
  465. package/dist/noydb-G725ZSZG.js +0 -34
  466. package/dist/overlay-views/index.cjs +0 -359
  467. package/dist/overlay-views/index.cjs.map +0 -1
  468. package/dist/overlay-views/index.d.cts +0 -82
  469. package/dist/periods/index.cjs +0 -1041
  470. package/dist/periods/index.cjs.map +0 -1
  471. package/dist/periods/index.d.cts +0 -22
  472. package/dist/predicate-BSAGEyu5.d.cts +0 -209
  473. package/dist/predicate-BSAGEyu5.d.ts +0 -209
  474. package/dist/query/index.cjs +0 -2375
  475. package/dist/query/index.cjs.map +0 -1
  476. package/dist/query/index.d.cts +0 -3
  477. package/dist/read-only-facade-ITU6L7BL.js +0 -7
  478. package/dist/registry-3QP3YKQS.js +0 -8
  479. package/dist/registry-DKEXOJVO.js +0 -7
  480. package/dist/registry-OJIOSBV6.js +0 -10
  481. package/dist/registry-USRVT6YF.js +0 -8
  482. package/dist/revoke-JCC7N56X.js +0 -17
  483. package/dist/session/index.cjs +0 -495
  484. package/dist/session/index.cjs.map +0 -1
  485. package/dist/session/index.d.cts +0 -46
  486. package/dist/shadow/index.cjs +0 -133
  487. package/dist/shadow/index.cjs.map +0 -1
  488. package/dist/shadow/index.d.cts +0 -17
  489. package/dist/snapshots/index.cjs +0 -937
  490. package/dist/snapshots/index.cjs.map +0 -1
  491. package/dist/snapshots/index.d.cts +0 -28
  492. package/dist/store/index.cjs +0 -1083
  493. package/dist/store/index.cjs.map +0 -1
  494. package/dist/store/index.d.cts +0 -492
  495. package/dist/store/index.d.ts +0 -492
  496. package/dist/store/index.js +0 -37
  497. package/dist/strategy-BSxFXGzb.d.cts +0 -110
  498. package/dist/strategy-BSxFXGzb.d.ts +0 -110
  499. package/dist/strategy-DSTrsZ8t.d.cts +0 -601
  500. package/dist/strategy-DSTrsZ8t.d.ts +0 -601
  501. package/dist/sync/index.cjs +0 -1062
  502. package/dist/sync/index.cjs.map +0 -1
  503. package/dist/sync/index.d.cts +0 -43
  504. package/dist/team/index.cjs +0 -2798
  505. package/dist/team/index.cjs.map +0 -1
  506. package/dist/team/index.d.cts +0 -118
  507. package/dist/tx/index.cjs +0 -544
  508. package/dist/tx/index.cjs.map +0 -1
  509. package/dist/tx/index.d.cts +0 -21
  510. package/dist/types-DyXYr8rE.d.cts +0 -12818
  511. package/dist/ulid-COREQ2RQ.js +0 -9
  512. package/dist/ulid-Drr7ykr6.d.cts +0 -603
  513. package/dist/util/index.cjs +0 -230
  514. package/dist/util/index.cjs.map +0 -1
  515. package/dist/util/index.d.cts +0 -77
  516. package/dist/with-derivation-DFnFByiQ.d.ts +0 -13
  517. package/dist/with-derivation-DU3Sjazm.d.cts +0 -13
  518. package/dist/with-guard-ByyxmEe7.d.cts +0 -18
  519. package/dist/with-guard-qube6BMI.d.ts +0 -18
  520. package/dist/with-materialized-view-BmEToIR1.d.cts +0 -27
  521. package/dist/with-overlayed-view-BMsQQbWm.d.cts +0 -13
  522. /package/dist/{store → adapter}/index.js.map +0 -0
  523. /package/dist/{chunk-UF3BUNQZ.js.map → api-RW3KP7WU.js.map} +0 -0
  524. /package/dist/{crypto-HTZ4FJOP.js.map → as/index.js.map} +0 -0
  525. /package/dist/{delegation-RI54P6I5.js.map → at/index.js.map} +0 -0
  526. /package/dist/{executor-5PNY7LGW.js.map → by/index.js.map} +0 -0
  527. /package/dist/{executor-B4QIYGZX.js.map → cargo/index.js.map} +0 -0
  528. /package/dist/{executor-BWXXDQ7K.js.map → chunk-BGIZAFY7.js.map} +0 -0
  529. /package/dist/{issue-VGDPP4B5.js.map → chunk-CHFZDSE4.js.map} +0 -0
  530. /package/dist/{ledger-TMRZYNVJ.js.map → chunk-GHVIKOHT.js.map} +0 -0
  531. /package/dist/{noydb-G725ZSZG.js.map → chunk-K2WCO3NX.js.map} +0 -0
  532. /package/dist/{public-envelope-BW6OXORV.js.map → chunk-PZ5AY32C.js.map} +0 -0
  533. /package/dist/{read-only-facade-ITU6L7BL.js.map → collection-facade-GQAOGJP2.js.map} +0 -0
  534. /package/dist/{registry-3QP3YKQS.js.map → delegation-UL5HKLER.js.map} +0 -0
  535. /package/dist/{registry-DKEXOJVO.js.map → describe/index.js.map} +0 -0
  536. /package/dist/{registry-OJIOSBV6.js.map → enclave-UL5LW66V.js.map} +0 -0
  537. /package/dist/{registry-USRVT6YF.js.map → executor-2FWQRLMG.js.map} +0 -0
  538. /package/dist/{revoke-JCC7N56X.js.map → executor-QZ7BXICW.js.map} +0 -0
  539. /package/dist/{signer-72QAUSVW.js.map → executor-Z5ZLJVTV.js.map} +0 -0
  540. /package/dist/{stale-6ZDBTQT7.js.map → export-accessible-KRV5W4GH.js.map} +0 -0
  541. /package/dist/{ulid-COREQ2RQ.js.map → extract-partition-GLKBOXFQ.js.map} +0 -0
@@ -1,2375 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/query/index.ts
21
- var query_exports = {};
22
- __export(query_exports, {
23
- Aggregation: () => Aggregation,
24
- CollectionIndexes: () => CollectionIndexes,
25
- CrossJoinSourceUnknownError: () => CrossJoinSourceUnknownError,
26
- CrossJoinTooLargeError: () => CrossJoinTooLargeError,
27
- DEFAULT_CROSS_JOIN_MAX_ROWS: () => DEFAULT_CROSS_JOIN_MAX_ROWS,
28
- DEFAULT_JOIN_MAX_ROWS: () => DEFAULT_JOIN_MAX_ROWS,
29
- DanglingReferenceError: () => DanglingReferenceError,
30
- GROUPBY_MAX_CARDINALITY: () => GROUPBY_MAX_CARDINALITY,
31
- GROUPBY_WARN_CARDINALITY: () => GROUPBY_WARN_CARDINALITY,
32
- GroupCardinalityError: () => GroupCardinalityError,
33
- GroupedAggregation: () => GroupedAggregation,
34
- GroupedQuery: () => GroupedQuery,
35
- GroupedQueryN: () => GroupedQueryN,
36
- IndexRequiredError: () => IndexRequiredError,
37
- IndexWriteFailureError: () => IndexWriteFailureError,
38
- JoinTooLargeError: () => JoinTooLargeError,
39
- Query: () => Query,
40
- ScanBuilder: () => ScanBuilder,
41
- applyJoins: () => applyJoins,
42
- avg: () => avg,
43
- buildLiveAggregation: () => buildLiveAggregation,
44
- buildLiveQuery: () => buildLiveQuery,
45
- count: () => count,
46
- evaluateClause: () => evaluateClause,
47
- evaluateFieldClause: () => evaluateFieldClause,
48
- executePlan: () => executePlan,
49
- groupAndReduce: () => groupAndReduce,
50
- max: () => max,
51
- min: () => min,
52
- readPath: () => readPath,
53
- reduceRecords: () => reduceRecords,
54
- resetGroupByWarnings: () => resetGroupByWarnings,
55
- resetJoinWarnings: () => resetJoinWarnings,
56
- sum: () => sum
57
- });
58
- module.exports = __toCommonJS(query_exports);
59
-
60
- // src/query/predicate.ts
61
- function readPath(record, path) {
62
- if (record === null || record === void 0) return void 0;
63
- if (!path.includes(".")) {
64
- return record[path];
65
- }
66
- const segments = path.split(".");
67
- let cursor = record;
68
- for (const segment of segments) {
69
- if (cursor === null || cursor === void 0) return void 0;
70
- cursor = cursor[segment];
71
- }
72
- return cursor;
73
- }
74
- function evaluateFieldClause(record, clause) {
75
- const actual = readPath(record, clause.field);
76
- const { op, value } = clause;
77
- switch (op) {
78
- case "==":
79
- return actual === value;
80
- case "!=":
81
- return actual !== value;
82
- case "<":
83
- return isComparable(actual, value) && actual < value;
84
- case "<=":
85
- return isComparable(actual, value) && actual <= value;
86
- case ">":
87
- return isComparable(actual, value) && actual > value;
88
- case ">=":
89
- return isComparable(actual, value) && actual >= value;
90
- case "in":
91
- return Array.isArray(value) && value.includes(actual);
92
- case "contains":
93
- if (typeof actual === "string") return typeof value === "string" && actual.includes(value);
94
- if (Array.isArray(actual)) return actual.includes(value);
95
- return false;
96
- case "startsWith":
97
- return typeof actual === "string" && typeof value === "string" && actual.startsWith(value);
98
- case "between": {
99
- if (!Array.isArray(value) || value.length !== 2) return false;
100
- const [lo, hi] = value;
101
- if (!isComparable(actual, lo) || !isComparable(actual, hi)) return false;
102
- return actual >= lo && actual <= hi;
103
- }
104
- default: {
105
- const _exhaustive = op;
106
- void _exhaustive;
107
- return false;
108
- }
109
- }
110
- }
111
- function isComparable(a, b) {
112
- if (typeof a === "number" && typeof b === "number") return true;
113
- if (typeof a === "string" && typeof b === "string") return true;
114
- if (a instanceof Date && b instanceof Date) return true;
115
- return false;
116
- }
117
- function evaluateClause(record, clause) {
118
- switch (clause.type) {
119
- case "field":
120
- return evaluateFieldClause(record, clause);
121
- case "filter":
122
- return clause.fn(record);
123
- case "wherePredicate":
124
- return clause.fn(record, clause.ctx);
125
- case "crossJoin":
126
- throw new Error(
127
- `evaluateClause: 'crossJoin' clauses are expansion primitives and are not evaluated per-record. This is a query planner routing error \u2014 crossJoin clauses must be extracted from the clause list before calling evaluateClause or filterRecords.`
128
- );
129
- case "group":
130
- if (clause.op === "and") {
131
- for (const child of clause.clauses) {
132
- if (!evaluateClause(record, child)) return false;
133
- }
134
- return true;
135
- } else {
136
- for (const child of clause.clauses) {
137
- if (evaluateClause(record, child)) return true;
138
- }
139
- return false;
140
- }
141
- }
142
- }
143
-
144
- // src/errors.ts
145
- var NoydbError = class extends Error {
146
- /** Machine-readable error code. Stable across library versions. */
147
- code;
148
- constructor(code, message) {
149
- super(message);
150
- this.name = "NoydbError";
151
- this.code = code;
152
- }
153
- };
154
- var GroupCardinalityError = class extends NoydbError {
155
- /** The field being grouped on. */
156
- field;
157
- /** Observed number of distinct groups at the moment the cap tripped. */
158
- cardinality;
159
- /** The cap that was exceeded. */
160
- maxGroups;
161
- constructor(field, cardinality, maxGroups) {
162
- super(
163
- "GROUP_CARDINALITY",
164
- `.groupBy("${field}") produced ${cardinality} distinct groups, exceeding the ${maxGroups}-group ceiling. This is almost always a query mistake \u2014 grouping on a high-uniqueness field like "id" or "createdAt" produces one bucket per record. Narrow the query with .where() before grouping, or group on a lower-cardinality field (status, category, clientId). If you genuinely need high-cardinality grouping, file an issue with your use case.`
165
- );
166
- this.name = "GroupCardinalityError";
167
- this.field = field;
168
- this.cardinality = cardinality;
169
- this.maxGroups = maxGroups;
170
- }
171
- };
172
- var IndexRequiredError = class extends NoydbError {
173
- collection;
174
- touchedFields;
175
- missingFields;
176
- constructor(args) {
177
- super(
178
- "INDEX_REQUIRED",
179
- `Collection "${args.collection}": query references unindexed fields in lazy mode (missing: ${args.missingFields.join(", ")}). Declare an index on each field, or use collection.scan() for non-indexed iteration.`
180
- );
181
- this.name = "IndexRequiredError";
182
- this.collection = args.collection;
183
- this.touchedFields = [...args.touchedFields];
184
- this.missingFields = [...args.missingFields];
185
- }
186
- };
187
- var IndexWriteFailureError = class extends NoydbError {
188
- recordId;
189
- field;
190
- op;
191
- cause;
192
- constructor(args) {
193
- super(
194
- "INDEX_WRITE_FAILURE",
195
- `Index side-car ${args.op} failed for field "${args.field}" on record "${args.recordId}"`
196
- );
197
- this.name = "IndexWriteFailureError";
198
- this.recordId = args.recordId;
199
- this.field = args.field;
200
- this.op = args.op;
201
- this.cause = args.cause;
202
- }
203
- };
204
- var JoinTooLargeError = class extends NoydbError {
205
- leftRows;
206
- rightRows;
207
- maxRows;
208
- side;
209
- constructor(opts) {
210
- super("JOIN_TOO_LARGE", opts.message);
211
- this.name = "JoinTooLargeError";
212
- this.leftRows = opts.leftRows;
213
- this.rightRows = opts.rightRows;
214
- this.maxRows = opts.maxRows;
215
- this.side = opts.side;
216
- }
217
- };
218
- var CrossJoinTooLargeError = class extends NoydbError {
219
- target;
220
- expected;
221
- limit;
222
- constructor(opts) {
223
- super(
224
- "CROSS_JOIN_TOO_LARGE",
225
- `crossJoin("${opts.target}"): would produce ${opts.expected} rows, exceeding the limit of ${opts.limit}. Narrow the left side with .where() first, or raise the ceiling with crossJoin("${opts.target}", { ..., maxRows: ${opts.expected} }).`
226
- );
227
- this.name = "CrossJoinTooLargeError";
228
- this.target = opts.target;
229
- this.expected = opts.expected;
230
- this.limit = opts.limit;
231
- }
232
- };
233
- var CrossJoinSourceUnknownError = class extends NoydbError {
234
- target;
235
- leftCollection;
236
- constructor(target, leftCollection) {
237
- super(
238
- "CROSS_JOIN_SOURCE_UNKNOWN",
239
- `crossJoin("${target}"): collection "${target}" is not known in the vault (cross-joining from "${leftCollection}"). Make sure "${target}" is open in the same vault before executing this query.`
240
- );
241
- this.name = "CrossJoinSourceUnknownError";
242
- this.target = target;
243
- this.leftCollection = leftCollection;
244
- }
245
- };
246
- var DanglingReferenceError = class extends NoydbError {
247
- field;
248
- target;
249
- refId;
250
- constructor(opts) {
251
- super("DANGLING_REFERENCE", opts.message);
252
- this.name = "DanglingReferenceError";
253
- this.field = opts.field;
254
- this.target = opts.target;
255
- this.refId = opts.refId;
256
- }
257
- };
258
-
259
- // src/query/join.ts
260
- var DEFAULT_JOIN_MAX_ROWS = 5e4;
261
- var JOIN_WARN_FRACTION = 0.8;
262
- function coerceRefKey(value) {
263
- if (value === null || value === void 0) return null;
264
- if (typeof value === "string") return value;
265
- if (typeof value === "number" || typeof value === "bigint") return String(value);
266
- return null;
267
- }
268
- var warnedDanglingKeys = /* @__PURE__ */ new Set();
269
- function warnOnceDangling(field, target, refId) {
270
- const key = `${field}\u2192${target}:${refId}`;
271
- if (warnedDanglingKeys.has(key)) return;
272
- warnedDanglingKeys.add(key);
273
- console.warn(
274
- `[noy-db] .join() encountered dangling ref in 'warn' mode: field "${field}" \u2192 "${target}:${refId}" not found. Attaching null.`
275
- );
276
- }
277
- var warnedCeilingKeys = /* @__PURE__ */ new Set();
278
- function warnCeilingApproaching(target, side, rows, maxRows) {
279
- const key = `${target}:${side}`;
280
- if (warnedCeilingKeys.has(key)) return;
281
- warnedCeilingKeys.add(key);
282
- const pct = Math.round(rows / maxRows * 100);
283
- console.warn(
284
- `[noy-db] .join() ${side} side is at ${pct}% of the ${maxRows}-row ceiling for target "${target}" (${rows} rows). Streaming joins over scan() are not yet supported for collections that need to exceed this.`
285
- );
286
- }
287
- function applyJoins(rows, joins, context) {
288
- if (joins.length === 0) return [...rows];
289
- let result = [...rows];
290
- for (const leg of joins) {
291
- result = applyOneJoin(result, leg, context);
292
- }
293
- return result;
294
- }
295
- function applyOneJoin(leftRows, leg, context) {
296
- if (leg.isDictJoin) {
297
- const dictSource = context.resolveDictSource?.(leg.field);
298
- if (!dictSource) {
299
- throw new Error(
300
- `.join() field "${leg.field}" on "${context.leftCollection}" is declared as a dictKey join but the dict source could not be resolved. Ensure the dictionary has at least one entry.`
301
- );
302
- }
303
- const out = [];
304
- const snapshot = dictSource.snapshot();
305
- const dictMap = /* @__PURE__ */ new Map();
306
- for (const entry of snapshot) {
307
- const k = readPath(entry, "key");
308
- if (typeof k === "string") dictMap.set(k, entry);
309
- }
310
- for (const left of leftRows) {
311
- const rawId = readPath(left, leg.field);
312
- const key = coerceRefKey(rawId);
313
- const dictEntry = key === null ? void 0 : dictMap.get(key);
314
- out.push({ ...left, [leg.as]: dictEntry ?? null });
315
- }
316
- return out;
317
- }
318
- const source = context.resolveSource(leg.target);
319
- if (!source) {
320
- throw new Error(
321
- `.join() cannot resolve target collection "${leg.target}" (referenced from field "${leg.field}" on "${context.leftCollection}"). Make sure the target collection has been opened via vault.collection() at least once before running the query.`
322
- );
323
- }
324
- const maxRows = leg.maxRows ?? DEFAULT_JOIN_MAX_ROWS;
325
- if (leftRows.length > maxRows) {
326
- throw new JoinTooLargeError({
327
- leftRows: leftRows.length,
328
- rightRows: -1,
329
- maxRows,
330
- side: "left",
331
- message: `.join() left side has ${leftRows.length} rows, exceeding the ${maxRows}-row ceiling for target "${leg.target}". Filter the left side further with where()/limit() before joining, or raise the ceiling via { maxRows }. Streaming joins over scan() are not yet supported.`
332
- });
333
- }
334
- if (leftRows.length > maxRows * JOIN_WARN_FRACTION) {
335
- warnCeilingApproaching(leg.target, "left", leftRows.length, maxRows);
336
- }
337
- const rightSnapshot = source.snapshot();
338
- if (rightSnapshot.length > maxRows) {
339
- throw new JoinTooLargeError({
340
- leftRows: leftRows.length,
341
- rightRows: rightSnapshot.length,
342
- maxRows,
343
- side: "right",
344
- message: `.join() right side "${leg.target}" has ${rightSnapshot.length} rows, exceeding the ${maxRows}-row ceiling. Raise the ceiling via { maxRows } if the data genuinely fits in memory, or track for streaming joins.`
345
- });
346
- }
347
- if (rightSnapshot.length > maxRows * JOIN_WARN_FRACTION) {
348
- warnCeilingApproaching(leg.target, "right", rightSnapshot.length, maxRows);
349
- }
350
- const strategy = leg.strategy ?? (source.lookupById ? "nested" : "hash");
351
- if (strategy === "nested" && source.lookupById) {
352
- const lookup = (id) => source.lookupById?.(id);
353
- return nestedLoopJoin(leftRows, leg, lookup);
354
- }
355
- return hashJoin(leftRows, leg, rightSnapshot);
356
- }
357
- function nestedLoopJoin(leftRows, leg, lookupById) {
358
- const out = [];
359
- for (const left of leftRows) {
360
- const rawId = readPath(left, leg.field);
361
- const key = coerceRefKey(rawId);
362
- const right = key === null ? void 0 : lookupById(key);
363
- out.push(attachJoin(left, leg, right, rawId));
364
- }
365
- return out;
366
- }
367
- function hashJoin(leftRows, leg, rightSnapshot) {
368
- const rightMap = /* @__PURE__ */ new Map();
369
- for (const record of rightSnapshot) {
370
- const rawId = readPath(record, "id");
371
- const key = coerceRefKey(rawId);
372
- if (key !== null) {
373
- rightMap.set(key, record);
374
- }
375
- }
376
- const out = [];
377
- for (const left of leftRows) {
378
- const rawId = readPath(left, leg.field);
379
- const key = coerceRefKey(rawId);
380
- const right = key === null ? void 0 : rightMap.get(key);
381
- out.push(attachJoin(left, leg, right, rawId));
382
- }
383
- return out;
384
- }
385
- function attachJoin(left, leg, right, rawId) {
386
- if (left === null || typeof left !== "object") {
387
- return left;
388
- }
389
- const merged = { ...left };
390
- const refKey = coerceRefKey(rawId);
391
- if (right === void 0) {
392
- if (refKey !== null && leg.mode === "strict") {
393
- throw new DanglingReferenceError({
394
- field: leg.field,
395
- target: leg.target,
396
- refId: refKey,
397
- message: `.join() strict dangling: record references "${leg.target}:${refKey}" via field "${leg.field}", but no such record exists. Use ref() mode 'warn' or 'cascade' if dangling refs are acceptable, or run vault.checkIntegrity() to find and fix the orphans.`
398
- });
399
- }
400
- if (refKey !== null && leg.mode === "warn") {
401
- warnOnceDangling(leg.field, leg.target, refKey);
402
- }
403
- merged[leg.as] = null;
404
- } else {
405
- merged[leg.as] = right;
406
- }
407
- return merged;
408
- }
409
- function resetJoinWarnings() {
410
- warnedDanglingKeys.clear();
411
- warnedCeilingKeys.clear();
412
- }
413
-
414
- // src/query/live.ts
415
- function buildLiveQuery(recompute, upstreams) {
416
- return new LiveQueryImpl(recompute, upstreams);
417
- }
418
- var LiveQueryImpl = class {
419
- constructor(recompute, upstreams) {
420
- this.recompute = recompute;
421
- this.refresh();
422
- for (const upstream of upstreams) {
423
- try {
424
- this.unsubs.push(upstream.subscribe(this.onUpstreamChange));
425
- } catch (err) {
426
- this._error = err instanceof Error ? err : new Error(String(err));
427
- }
428
- }
429
- }
430
- recompute;
431
- _value = [];
432
- _error = null;
433
- listeners = /* @__PURE__ */ new Set();
434
- unsubs = [];
435
- stopped = false;
436
- get value() {
437
- return this._value;
438
- }
439
- get error() {
440
- return this._error;
441
- }
442
- /**
443
- * Bound change handler — used as the callback passed to every
444
- * upstream's subscribe. Bound via class field so the `this`
445
- * context survives the indirect call from arbitrary upstreams.
446
- */
447
- onUpstreamChange = () => {
448
- this.refresh();
449
- for (const cb of this.listeners) {
450
- try {
451
- cb();
452
- } catch {
453
- }
454
- }
455
- };
456
- refresh() {
457
- if (this.stopped) return;
458
- try {
459
- this._value = this.recompute();
460
- this._error = null;
461
- } catch (err) {
462
- this._error = err instanceof Error ? err : new Error(String(err));
463
- }
464
- }
465
- subscribe(cb) {
466
- if (this.stopped) return () => {
467
- };
468
- this.listeners.add(cb);
469
- return () => this.listeners.delete(cb);
470
- }
471
- stop() {
472
- if (this.stopped) return;
473
- this.stopped = true;
474
- for (const unsub of this.unsubs) {
475
- try {
476
- unsub();
477
- } catch {
478
- }
479
- }
480
- this.unsubs.length = 0;
481
- this.listeners.clear();
482
- }
483
- };
484
-
485
- // src/aggregate/strategy.ts
486
- var NOT_ENABLED = new Error(
487
- 'Aggregate / groupBy is not enabled on this Noydb instance. Import `{ withAggregate }` from "@noy-db/hub/aggregate" and pass it to `createNoydb({ aggregateStrategy: withAggregate() })`.'
488
- );
489
- var NO_AGGREGATE = {
490
- aggregate() {
491
- throw NOT_ENABLED;
492
- },
493
- groupBy() {
494
- throw NOT_ENABLED;
495
- },
496
- groupByN() {
497
- throw NOT_ENABLED;
498
- },
499
- scanAggregate() {
500
- throw NOT_ENABLED;
501
- }
502
- };
503
-
504
- // src/query/builder.ts
505
- var EMPTY_PLAN = {
506
- clauses: [],
507
- orderBy: [],
508
- limit: void 0,
509
- offset: 0,
510
- joins: []
511
- };
512
- var DEFAULT_CROSS_JOIN_MAX_ROWS = 5e4;
513
- var Query = class _Query {
514
- source;
515
- plan;
516
- joinContext;
517
- aggregateStrategy;
518
- predicates;
519
- constructor(source, plan = EMPTY_PLAN, joinContext, aggregateStrategy = NO_AGGREGATE, predicates) {
520
- this.source = source;
521
- this.plan = plan;
522
- this.joinContext = joinContext;
523
- this.aggregateStrategy = aggregateStrategy;
524
- this.predicates = predicates;
525
- }
526
- /**
527
- * @internal — accessor for the materialized-view dependency
528
- * analyzer. Not part of the public API; consumers should use the
529
- * builder methods, not inspect the plan directly.
530
- */
531
- _plan() {
532
- return this.plan;
533
- }
534
- /**
535
- * @internal — accessor for the materialized-view dependency
536
- * analyzer. Returns the join resolution context (or `undefined` for
537
- * queries constructed without a Collection backing).
538
- */
539
- _joinContext() {
540
- return this.joinContext;
541
- }
542
- /**
543
- * @internal — clone this Query with a declared-predicate map
544
- * attached. Used by the materialized-view registry to enable
545
- * `.wherePredicate(name, ctx?)` for the MV's query callback.
546
- * Consumers don't call this directly.
547
- */
548
- _withPredicates(predicates) {
549
- return new _Query(
550
- this.source,
551
- this.plan,
552
- this.joinContext,
553
- this.aggregateStrategy,
554
- predicates
555
- );
556
- }
557
- /**
558
- * Filter by a registered deterministic predicate. Requires
559
- * the Query to have been augmented with a predicates map (typically
560
- * via the materialized-view registry — bare Queries constructed
561
- * outside an MV throw on `.wherePredicate()`).
562
- *
563
- * `ctx` is an optional opaque value passed verbatim to the predicate
564
- * function. Both `predicateHash` (from the registration) and a
565
- * canonical-JSON hash of `ctx` fold into the MV's `queryHash`, so
566
- * either changing forces refresh on next visit.
567
- */
568
- wherePredicate(name, ctx) {
569
- if (!this.predicates) {
570
- throw new Error(
571
- `.wherePredicate("${name}"): no predicates registered on this Query. Function-based predicates require the Query to be obtained from inside a materialized-view query() callback whose strategy declares \`predicates: { ${name}: { hash, fn } }\`.`
572
- );
573
- }
574
- const decl = this.predicates.get(name);
575
- if (!decl) {
576
- throw new Error(
577
- `.wherePredicate("${name}"): predicate not registered. Available: ${[...this.predicates.keys()].join(", ") || "(none)"}.`
578
- );
579
- }
580
- const clause = {
581
- type: "wherePredicate",
582
- name,
583
- ctx,
584
- predicateHash: decl.hash,
585
- ctxHash: canonicalCtxHash(ctx),
586
- fn: decl.fn
587
- };
588
- return new _Query(
589
- this.source,
590
- { ...this.plan, clauses: [...this.plan.clauses, clause] },
591
- this.joinContext,
592
- this.aggregateStrategy,
593
- this.predicates
594
- );
595
- }
596
- /** Add a field comparison. Multiple where() calls are AND-combined. */
597
- where(field, op, value) {
598
- const clause = { type: "field", field, op, value };
599
- return new _Query(
600
- this.source,
601
- { ...this.plan, clauses: [...this.plan.clauses, clause] },
602
- this.joinContext,
603
- this.aggregateStrategy,
604
- this.predicates
605
- );
606
- }
607
- /**
608
- * Logical OR group. Pass a callback that builds a sub-query.
609
- * Each clause inside the callback is OR-combined; the group itself
610
- * joins the parent plan with AND.
611
- */
612
- or(builder) {
613
- const sub = builder(
614
- new _Query(this.source, EMPTY_PLAN, this.joinContext, this.aggregateStrategy, this.predicates)
615
- );
616
- const group = {
617
- type: "group",
618
- op: "or",
619
- clauses: sub.plan.clauses
620
- };
621
- return new _Query(
622
- this.source,
623
- { ...this.plan, clauses: [...this.plan.clauses, group] },
624
- this.joinContext,
625
- this.aggregateStrategy,
626
- this.predicates
627
- );
628
- }
629
- /**
630
- * Logical AND group. Same shape as `or()` but every clause inside the group
631
- * must match. Useful for explicit grouping inside a larger OR.
632
- */
633
- and(builder) {
634
- const sub = builder(
635
- new _Query(this.source, EMPTY_PLAN, this.joinContext, this.aggregateStrategy, this.predicates)
636
- );
637
- const group = {
638
- type: "group",
639
- op: "and",
640
- clauses: sub.plan.clauses
641
- };
642
- return new _Query(
643
- this.source,
644
- { ...this.plan, clauses: [...this.plan.clauses, group] },
645
- this.joinContext,
646
- this.aggregateStrategy,
647
- this.predicates
648
- );
649
- }
650
- /** Escape hatch: add an arbitrary predicate function. Not serializable. */
651
- filter(fn) {
652
- const clause = {
653
- type: "filter",
654
- fn
655
- };
656
- return new _Query(
657
- this.source,
658
- { ...this.plan, clauses: [...this.plan.clauses, clause] },
659
- this.joinContext,
660
- this.aggregateStrategy,
661
- this.predicates
662
- );
663
- }
664
- /** Sort by a field. Subsequent calls are tie-breakers. */
665
- orderBy(field, direction = "asc") {
666
- return new _Query(
667
- this.source,
668
- { ...this.plan, orderBy: [...this.plan.orderBy, { field, direction }] },
669
- this.joinContext,
670
- this.aggregateStrategy,
671
- this.predicates
672
- );
673
- }
674
- /** Cap the result size. */
675
- limit(n) {
676
- return new _Query(
677
- this.source,
678
- { ...this.plan, limit: n },
679
- this.joinContext,
680
- this.aggregateStrategy,
681
- this.predicates
682
- );
683
- }
684
- /** Skip the first N matching records (after ordering). */
685
- offset(n) {
686
- return new _Query(
687
- this.source,
688
- { ...this.plan, offset: n },
689
- this.joinContext,
690
- this.aggregateStrategy,
691
- this.predicates
692
- );
693
- }
694
- /**
695
- * Resolve a `ref()`-declared foreign key and attach the right-side
696
- * record under `opts.as`. — eager, single-FK, intra-
697
- * vault joins.
698
- *
699
- * ```ts
700
- * const rows = invoices.query()
701
- * .where('status', '==', 'open')
702
- * .join('clientId', { as: 'client' })
703
- * .toArray()
704
- * // → [{ id, amount, client: { id, name, ... } }, ...]
705
- * ```
706
- *
707
- * Preconditions:
708
- * - The Query must have a `joinContext` (constructed via
709
- * `Collection.query()`, not `new Query`).
710
- * - `field` must have a matching `refs: { [field]: ref('<target>') }`
711
- * declaration on the left collection.
712
- * - The target collection must be reachable via the vault
713
- * (either currently open or openable on demand).
714
- *
715
- * Strategy:
716
- * - Nested-loop against `lookupById` when the target source
717
- * provides it (the common path for Collection targets).
718
- * - Hash join otherwise, or when `{ strategy: 'hash' }` is
719
- * explicitly passed for test purposes.
720
- *
721
- * Ref-mode semantics on dangling refs (left record has a non-null
722
- * FK value pointing at a right-side id that doesn't exist):
723
- * - `strict` → throws `DanglingReferenceError` with the full
724
- * field / target / refId context.
725
- * - `warn` → attaches `null` and emits a one-shot warning per
726
- * unique dangling pair.
727
- * - `cascade` → attaches `null` silently. Cascade is a
728
- * delete-time mode; dangling refs visible at read time are
729
- * either mid-flight cascades or pre-existing orphans, not a
730
- * DSL-level error.
731
- *
732
- * A left-side record whose FK field is `null` / `undefined` is NOT
733
- * a dangling ref — it's "no reference at all", always allowed
734
- * regardless of mode.
735
- *
736
- * The return type widens `T` with `Record<As, R | null>`. The `R`
737
- * parameter is optional — supply it explicitly for type-checked
738
- * access to the joined fields:
739
- *
740
- * ```ts
741
- * invoices.query().join<'client', Client>('clientId', { as: 'client' })
742
- * // ^^^^^^^^^^^^^^^^^^^ alias literal + right-side type
743
- * ```
744
- *
745
- * Without the generic, the joined field is typed as `unknown`, which
746
- * still works but requires a cast to access its properties.
747
- *
748
- * Joins stay intra-vault by construction — cross-vault
749
- * correlation goes through `Noydb.queryAcross`, not
750
- * `.join()`.
751
- */
752
- join(field, opts) {
753
- if (!this.joinContext) {
754
- throw new Error(
755
- `Query.join() requires a join context. Use collection.query() to construct a join-capable Query instead of the Query constructor directly (the direct constructor is only used for tests with plain-object sources).`
756
- );
757
- }
758
- const descriptor = this.joinContext.resolveRef(field);
759
- const isDictJoinField = !descriptor && this.joinContext.resolveDictSource?.(field) != null;
760
- if (!descriptor && !isDictJoinField) {
761
- throw new Error(
762
- `Query.join(): no ref() declared for field "${field}" on collection "${this.joinContext.leftCollection}". Add refs: { ${field}: ref('<target-collection>') } to the collection options, then retry. See the ref() docs for the full list of modes.`
763
- );
764
- }
765
- const leg = descriptor ? {
766
- field,
767
- as: opts.as,
768
- target: descriptor.target,
769
- mode: descriptor.mode,
770
- strategy: opts.strategy,
771
- maxRows: opts.maxRows,
772
- // constraint #1 — always 'all' in. Do not remove.
773
- partitionScope: "all"
774
- } : {
775
- // Dict join leg
776
- field,
777
- as: opts.as,
778
- target: field,
779
- // dict name = field name for dictKey
780
- mode: "strict",
781
- strategy: opts.strategy,
782
- maxRows: opts.maxRows,
783
- partitionScope: "all",
784
- isDictJoin: true
785
- };
786
- return new _Query(
787
- this.source,
788
- { ...this.plan, joins: [...this.plan.joins, leg] },
789
- this.joinContext,
790
- this.aggregateStrategy,
791
- this.predicates
792
- );
793
- }
794
- /**
795
- * Cartesian-product cross-join against `target` collection. Each result row
796
- * carries the original `T` fields plus `result[as]` populated from every
797
- * right-side row (or the filtered subset when `on:` is supplied).
798
- *
799
- * **Order matters:** `.where().crossJoin()` filters BEFORE expanding (cheaper);
800
- * `.crossJoin().where('alias.field', ...)` filters AFTER (required when the
801
- * where clause references the aliased fields).
802
- *
803
- * **Cost ceiling:** `CrossJoinTooLargeError` fires before allocation when
804
- * `leftRows × rightRows` (or the cumulative lateral count) exceeds the limit.
805
- * Default: 50,000 rows. Override per-clause with `{ maxRows: N }`.
806
- *
807
- * **`on:` shapes:**
808
- * - `on: (left) => TTarget[]` — subset form (most efficient)
809
- * - `on: (left) => (right) => boolean` — predicate form
810
- * - `on: { predicate: 'name' }` — MV-safe, hash-tracked form
811
- * (requires the Query to have been augmented via `_withPredicates`)
812
- *
813
- * Requires a JoinContext (constructed via `collection.query()`).
814
- */
815
- crossJoin(target, opts) {
816
- if (!this.joinContext) {
817
- throw new Error(
818
- `Query.crossJoin("${target}"): requires a join context. Use collection.query() to construct a cross-join-capable Query instead of the Query constructor directly.`
819
- );
820
- }
821
- let onFn;
822
- let onPredicateName;
823
- if (opts.on !== void 0) {
824
- if (typeof opts.on === "function") {
825
- onFn = opts.on;
826
- if (this.predicates) {
827
- console.warn(
828
- `Query.crossJoin("${target}", { on: callback }): inline on: callback inside a withMaterializedView query() disables queryHash drift detection for this cross-join. Use on: { predicate: '<name>' } to enable it.`
829
- );
830
- }
831
- } else {
832
- const predName = opts.on.predicate;
833
- if (!this.predicates) {
834
- throw new Error(
835
- `Query.crossJoin("${target}", { on: { predicate: "${predName}" } }): the { predicate } form requires a predicates map. Use this form inside a withMaterializedView query() callback that declares predicates: { ${predName}: { hash, fn } }.`
836
- );
837
- }
838
- const decl = this.predicates.get(predName);
839
- if (!decl) {
840
- throw new Error(
841
- `Query.crossJoin("${target}"): predicate "${predName}" not registered. Available: ${[...this.predicates.keys()].join(", ") || "(none)"}.`
842
- );
843
- }
844
- const as = opts.as;
845
- const predicateFn = decl.fn;
846
- onFn = (_left) => (right) => predicateFn({ ..._left, [as]: right });
847
- onPredicateName = predName;
848
- }
849
- }
850
- const clause = {
851
- type: "crossJoin",
852
- target,
853
- as: opts.as,
854
- ...onFn !== void 0 && { on: onFn },
855
- ...onPredicateName !== void 0 && { onPredicateName },
856
- ...opts.maxRows !== void 0 && { maxRows: opts.maxRows }
857
- };
858
- return new _Query(
859
- this.source,
860
- { ...this.plan, clauses: [...this.plan.clauses, clause] },
861
- this.joinContext,
862
- this.aggregateStrategy,
863
- this.predicates
864
- );
865
- }
866
- /**
867
- * Execute the plan and return the matching records. When the plan
868
- * carries any join legs, they are applied after `where` / `orderBy`
869
- * / `limit` / `offset` narrow the left set. See the `.join()` doc
870
- * for the ordering rationale.
871
- */
872
- toArray() {
873
- const base = executePlanWithSource(this.source, this.plan, this.joinContext);
874
- if (this.plan.joins.length === 0) return base;
875
- if (!this.joinContext) {
876
- throw new Error(
877
- `Query.toArray(): plan carries ${this.plan.joins.length} join leg(s) but no JoinContext is attached. This usually means the Query was constructed via the raw Query constructor with a plan that had joins pre-populated. Use collection.query().join(...) instead.`
878
- );
879
- }
880
- return applyJoins(base, this.plan.joins, this.joinContext);
881
- }
882
- /** Return the first matching record, or null. Joins are applied. */
883
- first() {
884
- const arr = this.limit(1).toArray();
885
- return arr[0] ?? null;
886
- }
887
- /**
888
- * Return the number of matching records (after where/filter,
889
- * before limit). **Joins are NOT applied** — count() reports the
890
- * left-side cardinality, because joins in are projection-only
891
- * (they attach an aliased field; they never filter). Running joins
892
- * here just to discard the aliases would be wasteful, and in strict
893
- * mode it could throw `DanglingReferenceError` for a call whose
894
- * intent is purely to count.
895
- */
896
- count() {
897
- if (this.plan.clauses.some((c) => c.type === "crossJoin")) {
898
- if (!this.joinContext) {
899
- throw new Error(
900
- `Query.count(): plan contains crossJoin clauses but no JoinContext is attached.`
901
- );
902
- }
903
- return executeClausePipeline(this.source, this.plan.clauses, this.joinContext).length;
904
- }
905
- const { candidates, remainingClauses } = candidateRecords(this.source, this.plan.clauses);
906
- if (remainingClauses.length === 0) return candidates.length;
907
- return filterRecords(candidates, remainingClauses).length;
908
- }
909
- /**
910
- * Reduce the matching records through a named set of reducers.
911
- * the aggregation terminal.
912
- *
913
- * ```ts
914
- * const { total, n, avgAmount } = invoices.query()
915
- * .where('status', '==', 'open')
916
- * .aggregate({
917
- * total: sum('amount'),
918
- * n: count(),
919
- * avgAmount: avg('amount'),
920
- * })
921
- * .run()
922
- * ```
923
- *
924
- * Returns an `Aggregation<R>` wrapper with two terminals:
925
- * - `.run(): R` — synchronous one-shot reduction
926
- * - `.live(): LiveAggregation<R>` — reactive primitive that
927
- * re-runs the reduction whenever the source notifies of a
928
- * change. Always call `live.stop()` when finished.
929
- *
930
- * The reducer spec is bound here once and reused by both
931
- * terminals — this is why `.aggregate()` returns a wrapper instead
932
- * of being a direct terminal. Consumers who only need the static
933
- * value read `.run()`; consumers wiring a reactive UI read
934
- * `.live()`.
935
- *
936
- * Joins are intentionally NOT applied to aggregations in —
937
- * the same logic as `.count()`. Joins in are projection-only
938
- * (they attach an aliased field and never filter), so running
939
- * them just to throw the aliases away would be wasteful. If you
940
- * need a reducer that reads a joined field, open an issue —
941
- * aggregations-across-joins is explicitly out of scope for v1.
942
- *
943
- * Every reducer factory accepts an optional `{ seed }` parameter
944
- * that is plumbed through the protocol but unused by the
945
- * executor — that's constraint #2. When partition-aware
946
- * aggregation lands, the seed will carry running state across
947
- * partition boundaries without an API break.
948
- */
949
- aggregate(spec) {
950
- const source = this.source;
951
- const clauses = this.plan.clauses;
952
- const joinCtx = this.joinContext;
953
- const hasCrossJoins = clauses.some((c) => c.type === "crossJoin");
954
- const executeRecords = () => {
955
- if (hasCrossJoins) {
956
- if (!joinCtx) throw new Error("Query.aggregate(): crossJoin requires a join context");
957
- return executeClausePipeline(source, clauses, joinCtx);
958
- }
959
- const { candidates, remainingClauses } = candidateRecords(source, clauses);
960
- return remainingClauses.length === 0 ? candidates : filterRecords(candidates, remainingClauses);
961
- };
962
- const upstreams = [];
963
- if (source.subscribe) {
964
- const subscribe = source.subscribe.bind(source);
965
- upstreams.push({ subscribe: (cb) => subscribe(cb) });
966
- }
967
- return this.aggregateStrategy.aggregate(executeRecords, spec, upstreams);
968
- }
969
- groupBy(...fields) {
970
- if (fields.length === 0) {
971
- throw new Error(".groupBy() requires at least one field");
972
- }
973
- const source = this.source;
974
- const clauses = this.plan.clauses;
975
- const joinCtx = this.joinContext;
976
- const hasCrossJoins = clauses.some((c) => c.type === "crossJoin");
977
- const executeRecords = () => {
978
- if (hasCrossJoins) {
979
- if (!joinCtx) throw new Error("Query.groupBy(): crossJoin requires a join context");
980
- return executeClausePipeline(source, clauses, joinCtx);
981
- }
982
- const { candidates, remainingClauses } = candidateRecords(source, clauses);
983
- return remainingClauses.length === 0 ? candidates : filterRecords(candidates, remainingClauses);
984
- };
985
- const upstreams = [];
986
- if (source.subscribe) {
987
- const subscribe = source.subscribe.bind(source);
988
- upstreams.push({ subscribe: (cb) => subscribe(cb) });
989
- }
990
- if (fields.length === 1) {
991
- const field = fields[0];
992
- const dictLabelResolver = buildDictLabelResolver(this.joinContext, field);
993
- return this.aggregateStrategy.groupBy(
994
- executeRecords,
995
- field,
996
- upstreams,
997
- dictLabelResolver
998
- );
999
- }
1000
- return this.aggregateStrategy.groupByN(
1001
- executeRecords,
1002
- fields,
1003
- upstreams
1004
- );
1005
- }
1006
- /**
1007
- * Re-run the query whenever the source notifies of changes.
1008
- * Returns an unsubscribe function. The callback receives the latest result.
1009
- * Throws if the source does not support subscriptions.
1010
- *
1011
- * **For joined queries, prefer `.live()`** — `subscribe()`
1012
- * only re-fires on LEFT-side changes, so joined data can be
1013
- * stale if the right side mutates between emissions. `.live()`
1014
- * merges change streams from every join target.
1015
- */
1016
- subscribe(cb) {
1017
- if (!this.source.subscribe) {
1018
- throw new Error("Query source does not support subscriptions. Pass a source with a subscribe() method.");
1019
- }
1020
- cb(this.toArray());
1021
- return this.source.subscribe(() => cb(this.toArray()));
1022
- }
1023
- /**
1024
- * Reactive terminal — returns a `LiveQuery<T>` that re-runs the
1025
- * query and updates its `value` whenever any source feeding it
1026
- * mutates..
1027
- *
1028
- * For non-joined queries, `.live()` is a convenience over the
1029
- * existing `.subscribe()` callback shape: a hand-rolled reactive
1030
- * primitive with `value` / `error` fields and a `subscribe(cb)`
1031
- * notification channel. Frame-agnostic — Vue / React / Solid
1032
- * adapters wrap it in their own primitive.
1033
- *
1034
- * For joined queries, `.live()` additionally subscribes to every
1035
- * join target's change stream. Mutations on a right-side
1036
- * collection (insert / update / delete of a client referenced by
1037
- * an invoice) re-fire the live query and re-evaluate every
1038
- * dependent left row. Right-side targets are deduped by
1039
- * collection name, so a chain that joins the same target twice
1040
- * (e.g. billing client + shipping client → both 'clients') only
1041
- * subscribes once.
1042
- *
1043
- * **Ref-mode behavior on right-side disappearance** — matches the
1044
- * eager `.toArray()` contract from :
1045
- * - `strict` → re-run throws `DanglingReferenceError`. The
1046
- * LiveQuery catches the throw, stores it in `live.error`, and
1047
- * notifies listeners (the throw does NOT propagate out of
1048
- * the source's change handler — that would tear down the
1049
- * emitter). Consumers check `live.error` after each
1050
- * notification and render an error state in the UI.
1051
- * - `warn` → joined value flips to `null`; the existing
1052
- * warn-channel deduplication keeps repeated re-runs from
1053
- * spamming the console.
1054
- * - `cascade` → no special handling needed; the cascade-
1055
- * delete mechanism propagates the right-side delete into the
1056
- * left collection on the next tick, and the live query
1057
- * naturally re-fires with the orphaned left rows gone.
1058
- *
1059
- * Always call `live.stop()` when finished — it tears down every
1060
- * upstream subscription. The Vue layer's `onUnmounted` hook
1061
- * should call `stop()` automatically; raw consumers must do it
1062
- * themselves.
1063
- *
1064
- * **Limitations:**
1065
- * - No granular delta updates — the whole query re-runs on
1066
- * every change.
1067
- * - No microtask batching — bursty changes produce one re-run
1068
- * per change.
1069
- * - No re-planning under live mutations — the planner picks
1070
- * once at subscription time and reuses the same plan.
1071
- * - Streaming live joins are deferred.
1072
- */
1073
- live() {
1074
- const upstreams = [];
1075
- if (this.source.subscribe) {
1076
- const leftSubscribe = this.source.subscribe.bind(this.source);
1077
- upstreams.push({
1078
- subscribe: (cb) => leftSubscribe(cb)
1079
- });
1080
- }
1081
- if (this.plan.joins.length > 0 && this.joinContext) {
1082
- const subscribed = /* @__PURE__ */ new Set();
1083
- for (const leg of this.plan.joins) {
1084
- if (subscribed.has(leg.target)) continue;
1085
- subscribed.add(leg.target);
1086
- const rightSource = this.joinContext.resolveSource(leg.target);
1087
- if (rightSource?.subscribe) {
1088
- const rightSubscribe = rightSource.subscribe.bind(rightSource);
1089
- upstreams.push({
1090
- subscribe: (cb) => rightSubscribe(cb)
1091
- });
1092
- }
1093
- }
1094
- }
1095
- if (this.joinContext) {
1096
- const subscribedCross = /* @__PURE__ */ new Set();
1097
- for (const clause of this.plan.clauses) {
1098
- if (clause.type !== "crossJoin") continue;
1099
- if (subscribedCross.has(clause.target)) continue;
1100
- subscribedCross.add(clause.target);
1101
- const rightSource = this.joinContext.resolveSource(clause.target);
1102
- if (rightSource?.subscribe) {
1103
- const rightSubscribe = rightSource.subscribe.bind(rightSource);
1104
- upstreams.push({
1105
- subscribe: (cb) => rightSubscribe(cb)
1106
- });
1107
- }
1108
- }
1109
- }
1110
- return buildLiveQuery(() => this.toArray(), upstreams);
1111
- }
1112
- /**
1113
- * Return the plan as a JSON-friendly object. FilterClause entries are
1114
- * stripped (their `fn` cannot be serialized) and replaced with
1115
- * { type: 'filter', fn: '[function]' } so devtools can still see them.
1116
- */
1117
- toPlan() {
1118
- return serializePlan(this.plan);
1119
- }
1120
- };
1121
- function executePlanWithSource(source, plan, joinContext) {
1122
- const hasCrossJoins = plan.clauses.some((c) => c.type === "crossJoin");
1123
- let result;
1124
- if (hasCrossJoins) {
1125
- if (!joinContext) {
1126
- throw new Error(
1127
- `Query.toArray(): plan contains crossJoin clauses but no JoinContext is attached. Use collection.query() instead of new Query() for cross-join support.`
1128
- );
1129
- }
1130
- result = executeClausePipeline(source, plan.clauses, joinContext);
1131
- } else {
1132
- const { candidates, remainingClauses } = candidateRecords(source, plan.clauses);
1133
- result = remainingClauses.length === 0 ? [...candidates] : filterRecords(candidates, remainingClauses);
1134
- }
1135
- if (plan.orderBy.length > 0) {
1136
- result = sortRecords(result, plan.orderBy);
1137
- }
1138
- if (plan.offset > 0) {
1139
- result = result.slice(plan.offset);
1140
- }
1141
- if (plan.limit !== void 0) {
1142
- result = result.slice(0, plan.limit);
1143
- }
1144
- return result;
1145
- }
1146
- function candidateRecords(source, clauses) {
1147
- const indexes = source.getIndexes?.();
1148
- if (!indexes || !source.lookupById || clauses.length === 0) {
1149
- return { candidates: source.snapshot(), remainingClauses: clauses };
1150
- }
1151
- const lookupById = (id) => source.lookupById?.(id);
1152
- for (let i = 0; i < clauses.length; i++) {
1153
- const clause = clauses[i];
1154
- if (clause.type !== "field") continue;
1155
- if (!indexes.has(clause.field)) continue;
1156
- let ids = null;
1157
- if (clause.op === "==") {
1158
- ids = indexes.lookupEqual(clause.field, clause.value);
1159
- } else if (clause.op === "in" && Array.isArray(clause.value)) {
1160
- ids = indexes.lookupIn(clause.field, clause.value);
1161
- }
1162
- if (ids !== null) {
1163
- const remaining = [];
1164
- for (let j = 0; j < clauses.length; j++) {
1165
- if (j !== i) remaining.push(clauses[j]);
1166
- }
1167
- return {
1168
- candidates: materializeIds(ids, lookupById),
1169
- remainingClauses: remaining
1170
- };
1171
- }
1172
- }
1173
- return { candidates: source.snapshot(), remainingClauses: clauses };
1174
- }
1175
- function materializeIds(ids, lookupById) {
1176
- const out = [];
1177
- for (const id of ids) {
1178
- const record = lookupById(id);
1179
- if (record !== void 0) out.push(record);
1180
- }
1181
- return out;
1182
- }
1183
- function executePlan(records, plan) {
1184
- if (plan.clauses.some((c) => c.type === "crossJoin")) {
1185
- throw new Error(
1186
- `executePlan(): does not support crossJoin clauses. executePlan is a stateless pure function \u2014 it cannot resolve cross-join right-side collections. Use Query.toArray() (via collection.query()) instead.`
1187
- );
1188
- }
1189
- let result = filterRecords(records, plan.clauses);
1190
- if (plan.orderBy.length > 0) {
1191
- result = sortRecords(result, plan.orderBy);
1192
- }
1193
- if (plan.offset > 0) {
1194
- result = result.slice(plan.offset);
1195
- }
1196
- if (plan.limit !== void 0) {
1197
- result = result.slice(0, plan.limit);
1198
- }
1199
- return result;
1200
- }
1201
- function filterRecords(records, clauses) {
1202
- if (clauses.length === 0) return [...records];
1203
- const out = [];
1204
- for (const r of records) {
1205
- let matches = true;
1206
- for (const clause of clauses) {
1207
- if (!evaluateClause(r, clause)) {
1208
- matches = false;
1209
- break;
1210
- }
1211
- }
1212
- if (matches) out.push(r);
1213
- }
1214
- return out;
1215
- }
1216
- function executeClausePipeline(source, clauses, joinContext) {
1217
- let rel = [...source.snapshot()];
1218
- let filterBatch = [];
1219
- for (const clause of clauses) {
1220
- if (clause.type === "crossJoin") {
1221
- if (filterBatch.length > 0) {
1222
- rel = filterRecords(rel, filterBatch);
1223
- filterBatch = [];
1224
- }
1225
- const rightSource = joinContext.resolveSource(clause.target);
1226
- if (!rightSource) {
1227
- throw new CrossJoinSourceUnknownError(clause.target, joinContext.leftCollection);
1228
- }
1229
- rel = applyCrossJoin(rel, clause, rightSource);
1230
- } else {
1231
- filterBatch.push(clause);
1232
- }
1233
- }
1234
- if (filterBatch.length > 0) {
1235
- rel = filterRecords(rel, filterBatch);
1236
- }
1237
- return rel;
1238
- }
1239
- function applyCrossJoin(leftRel, clause, rightSource) {
1240
- const rightRows = rightSource.snapshot();
1241
- const maxRows = clause.maxRows ?? DEFAULT_CROSS_JOIN_MAX_ROWS;
1242
- const { as } = clause;
1243
- if (!clause.on) {
1244
- const product = leftRel.length * rightRows.length;
1245
- if (product > maxRows) {
1246
- throw new CrossJoinTooLargeError({ target: clause.target, expected: product, limit: maxRows });
1247
- }
1248
- const expanded2 = [];
1249
- for (const left of leftRel) {
1250
- const leftObj = left;
1251
- for (const right of rightRows) {
1252
- expanded2.push({ ...leftObj, [as]: right });
1253
- }
1254
- }
1255
- return expanded2;
1256
- }
1257
- const expanded = [];
1258
- let cumulative = 0;
1259
- for (const left of leftRel) {
1260
- const callbackResult = clause.on(left);
1261
- let filteredRight;
1262
- if (Array.isArray(callbackResult)) {
1263
- filteredRight = callbackResult;
1264
- } else {
1265
- filteredRight = rightRows.filter(
1266
- callbackResult
1267
- );
1268
- }
1269
- cumulative += filteredRight.length;
1270
- if (cumulative > maxRows) {
1271
- throw new CrossJoinTooLargeError({
1272
- target: clause.target,
1273
- expected: cumulative,
1274
- limit: maxRows
1275
- });
1276
- }
1277
- const leftObj = left;
1278
- for (const right of filteredRight) {
1279
- expanded.push({ ...leftObj, [as]: right });
1280
- }
1281
- }
1282
- return expanded;
1283
- }
1284
- function sortRecords(records, orderBy) {
1285
- return [...records].sort((a, b) => {
1286
- for (const { field, direction } of orderBy) {
1287
- const av = readField(a, field);
1288
- const bv = readField(b, field);
1289
- const cmp = compareValues(av, bv);
1290
- if (cmp !== 0) return direction === "asc" ? cmp : -cmp;
1291
- }
1292
- return 0;
1293
- });
1294
- }
1295
- function readField(record, field) {
1296
- if (record === null || record === void 0) return void 0;
1297
- if (!field.includes(".")) {
1298
- return record[field];
1299
- }
1300
- const segments = field.split(".");
1301
- let cursor = record;
1302
- for (const segment of segments) {
1303
- if (cursor === null || cursor === void 0) return void 0;
1304
- cursor = cursor[segment];
1305
- }
1306
- return cursor;
1307
- }
1308
- function compareValues(a, b) {
1309
- if (a === void 0 || a === null) return b === void 0 || b === null ? 0 : 1;
1310
- if (b === void 0 || b === null) return -1;
1311
- if (typeof a === "number" && typeof b === "number") return a - b;
1312
- if (typeof a === "string" && typeof b === "string") return a < b ? -1 : a > b ? 1 : 0;
1313
- if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();
1314
- return 0;
1315
- }
1316
- function serializePlan(plan) {
1317
- return {
1318
- clauses: plan.clauses.map(serializeClause),
1319
- orderBy: plan.orderBy,
1320
- limit: plan.limit,
1321
- offset: plan.offset,
1322
- joins: plan.joins
1323
- };
1324
- }
1325
- function serializeClause(clause) {
1326
- if (clause.type === "filter") {
1327
- return { type: "filter", fn: "[function]" };
1328
- }
1329
- if (clause.type === "wherePredicate") {
1330
- return {
1331
- type: "wherePredicate",
1332
- name: clause.name,
1333
- ctx: clause.ctx,
1334
- predicateHash: clause.predicateHash,
1335
- ctxHash: clause.ctxHash,
1336
- fn: "[function]"
1337
- };
1338
- }
1339
- if (clause.type === "group") {
1340
- return {
1341
- type: "group",
1342
- op: clause.op,
1343
- clauses: clause.clauses.map(serializeClause)
1344
- };
1345
- }
1346
- if (clause.type === "crossJoin") {
1347
- return {
1348
- type: "crossJoin",
1349
- target: clause.target,
1350
- as: clause.as,
1351
- on: clause.on ? "[function]" : void 0,
1352
- onPredicateName: clause.onPredicateName,
1353
- maxRows: clause.maxRows
1354
- };
1355
- }
1356
- return clause;
1357
- }
1358
- function canonicalCtxHash(ctx) {
1359
- if (ctx === void 0) return "";
1360
- const canonical = JSON.stringify(ctx, (_key, value) => {
1361
- if (value && typeof value === "object" && !Array.isArray(value)) {
1362
- const sorted = {};
1363
- for (const k of Object.keys(value).sort()) {
1364
- sorted[k] = value[k];
1365
- }
1366
- return sorted;
1367
- }
1368
- return value;
1369
- });
1370
- let h = 5381;
1371
- for (let i = 0; i < canonical.length; i++) {
1372
- h = (h << 5) + h ^ canonical.charCodeAt(i);
1373
- }
1374
- return (h >>> 0).toString(16).padStart(8, "0");
1375
- }
1376
- function buildDictLabelResolver(joinCtx, field) {
1377
- if (!joinCtx?.resolveDictSource) return void 0;
1378
- const dictSource = joinCtx.resolveDictSource(field);
1379
- if (!dictSource) return void 0;
1380
- const snapshot = dictSource.snapshot();
1381
- const dictMap = /* @__PURE__ */ new Map();
1382
- for (const entry of snapshot) {
1383
- const k = entry["key"];
1384
- const labels = entry["labels"];
1385
- if (typeof k === "string" && labels && typeof labels === "object") {
1386
- dictMap.set(k, labels);
1387
- }
1388
- }
1389
- return async (key, locale, fallback) => {
1390
- const labels = dictMap.get(key);
1391
- if (!labels) return void 0;
1392
- if (labels[locale] !== void 0) return labels[locale];
1393
- const chain = Array.isArray(fallback) ? fallback : fallback ? [fallback] : [];
1394
- for (const fb of chain) {
1395
- if (fb === "any") {
1396
- const any = Object.values(labels)[0];
1397
- if (any !== void 0) return any;
1398
- } else if (labels[fb] !== void 0) {
1399
- return labels[fb];
1400
- }
1401
- }
1402
- return void 0;
1403
- };
1404
- }
1405
-
1406
- // src/indexing/eager-indexes.ts
1407
- var CollectionIndexes = class {
1408
- indexes = /* @__PURE__ */ new Map();
1409
- /**
1410
- * Declare an index. Subsequent record additions are tracked under it.
1411
- * Calling this twice for the same field is a no-op (idempotent).
1412
- */
1413
- declare(field) {
1414
- if (this.indexes.has(field)) return;
1415
- this.indexes.set(field, { field, buckets: /* @__PURE__ */ new Map() });
1416
- }
1417
- /** True if the given field has a declared index. */
1418
- has(field) {
1419
- return this.indexes.has(field);
1420
- }
1421
- /** All declared field names, in declaration order. */
1422
- fields() {
1423
- return [...this.indexes.keys()];
1424
- }
1425
- /**
1426
- * Build all declared indexes from a snapshot of records.
1427
- * Called once per hydration. O(N × indexes.size).
1428
- */
1429
- build(records) {
1430
- for (const idx of this.indexes.values()) {
1431
- idx.buckets.clear();
1432
- for (const { id, record } of records) {
1433
- addToIndex(idx, id, record);
1434
- }
1435
- }
1436
- }
1437
- /**
1438
- * Insert or update a single record across all indexes.
1439
- * Called by `Collection.put()` after the encrypted write succeeds.
1440
- *
1441
- * If `previousRecord` is provided, the record is removed from any old
1442
- * buckets first — this is the update path. Pass `null` for fresh adds.
1443
- */
1444
- upsert(id, newRecord, previousRecord) {
1445
- if (this.indexes.size === 0) return;
1446
- if (previousRecord !== null) {
1447
- this.remove(id, previousRecord);
1448
- }
1449
- for (const idx of this.indexes.values()) {
1450
- addToIndex(idx, id, newRecord);
1451
- }
1452
- }
1453
- /**
1454
- * Remove a record from all indexes. Called by `Collection.delete()`
1455
- * (and as the first half of `upsert` for the update path).
1456
- */
1457
- remove(id, record) {
1458
- if (this.indexes.size === 0) return;
1459
- for (const idx of this.indexes.values()) {
1460
- removeFromIndex(idx, id, record);
1461
- }
1462
- }
1463
- /** Drop all index data. Called when the collection is invalidated. */
1464
- clear() {
1465
- for (const idx of this.indexes.values()) {
1466
- idx.buckets.clear();
1467
- }
1468
- }
1469
- /**
1470
- * Equality lookup: return the set of record ids whose `field` matches
1471
- * the given value. Returns `null` if no index covers the field — the
1472
- * caller should fall back to a linear scan.
1473
- *
1474
- * The returned Set is a reference to the index's internal storage —
1475
- * callers must NOT mutate it.
1476
- */
1477
- lookupEqual(field, value) {
1478
- const idx = this.indexes.get(field);
1479
- if (!idx) return null;
1480
- const key = stringifyKey(value);
1481
- return idx.buckets.get(key) ?? EMPTY_SET;
1482
- }
1483
- /**
1484
- * Set lookup: return the union of record ids whose `field` matches any
1485
- * of the given values. Returns `null` if no index covers the field.
1486
- */
1487
- lookupIn(field, values) {
1488
- const idx = this.indexes.get(field);
1489
- if (!idx) return null;
1490
- const out = /* @__PURE__ */ new Set();
1491
- for (const value of values) {
1492
- const key = stringifyKey(value);
1493
- const bucket = idx.buckets.get(key);
1494
- if (bucket) {
1495
- for (const id of bucket) out.add(id);
1496
- }
1497
- }
1498
- return out;
1499
- }
1500
- };
1501
- var EMPTY_SET = /* @__PURE__ */ new Set();
1502
- function stringifyKey(value) {
1503
- if (value === null || value === void 0) return "\0NULL\0";
1504
- if (typeof value === "string") return value;
1505
- if (typeof value === "number" || typeof value === "boolean") return String(value);
1506
- if (value instanceof Date) return value.toISOString();
1507
- return "\0OBJECT\0";
1508
- }
1509
- function addToIndex(idx, id, record) {
1510
- const value = readPath(record, idx.field);
1511
- if (value === null || value === void 0) return;
1512
- const key = stringifyKey(value);
1513
- let bucket = idx.buckets.get(key);
1514
- if (!bucket) {
1515
- bucket = /* @__PURE__ */ new Set();
1516
- idx.buckets.set(key, bucket);
1517
- }
1518
- bucket.add(id);
1519
- }
1520
- function removeFromIndex(idx, id, record) {
1521
- const value = readPath(record, idx.field);
1522
- if (value === null || value === void 0) return;
1523
- const key = stringifyKey(value);
1524
- const bucket = idx.buckets.get(key);
1525
- if (!bucket) return;
1526
- bucket.delete(id);
1527
- if (bucket.size === 0) idx.buckets.delete(key);
1528
- }
1529
-
1530
- // src/aggregate/reducers.ts
1531
- function count(opts) {
1532
- const _seed = opts?.seed;
1533
- void _seed;
1534
- return {
1535
- init: () => 0,
1536
- step: (state) => state + 1,
1537
- remove: (state) => state - 1,
1538
- finalize: (state) => state
1539
- };
1540
- }
1541
- function sum(field, opts) {
1542
- const _seed = opts?.seed;
1543
- void _seed;
1544
- return {
1545
- init: () => 0,
1546
- step: (state, record) => state + readNumber(record, field),
1547
- remove: (state, record) => state - readNumber(record, field),
1548
- finalize: (state) => state
1549
- };
1550
- }
1551
- function avg(field, opts) {
1552
- const _seed = opts?.seed;
1553
- void _seed;
1554
- return {
1555
- init: () => ({ sum: 0, count: 0 }),
1556
- step: (state, record) => ({
1557
- sum: state.sum + readNumber(record, field),
1558
- count: state.count + 1
1559
- }),
1560
- remove: (state, record) => ({
1561
- sum: state.sum - readNumber(record, field),
1562
- count: state.count - 1
1563
- }),
1564
- finalize: (state) => state.count === 0 ? null : state.sum / state.count
1565
- };
1566
- }
1567
- function pushValue(state, value) {
1568
- return { values: [...state.values, value] };
1569
- }
1570
- function removeValue(state, value) {
1571
- const idx = state.values.indexOf(value);
1572
- if (idx < 0) return state;
1573
- const next = state.values.slice();
1574
- next.splice(idx, 1);
1575
- return { values: next };
1576
- }
1577
- function min(field, opts) {
1578
- const _seed = opts?.seed;
1579
- void _seed;
1580
- return {
1581
- init: () => ({ values: [] }),
1582
- step: (state, record) => pushValue(state, readNumber(record, field)),
1583
- remove: (state, record) => removeValue(state, readNumber(record, field)),
1584
- finalize: (state) => {
1585
- if (state.values.length === 0) return null;
1586
- let out = state.values[0];
1587
- for (let i = 1; i < state.values.length; i++) {
1588
- const v = state.values[i];
1589
- if (v < out) out = v;
1590
- }
1591
- return out;
1592
- }
1593
- };
1594
- }
1595
- function max(field, opts) {
1596
- const _seed = opts?.seed;
1597
- void _seed;
1598
- return {
1599
- init: () => ({ values: [] }),
1600
- step: (state, record) => pushValue(state, readNumber(record, field)),
1601
- remove: (state, record) => removeValue(state, readNumber(record, field)),
1602
- finalize: (state) => {
1603
- if (state.values.length === 0) return null;
1604
- let out = state.values[0];
1605
- for (let i = 1; i < state.values.length; i++) {
1606
- const v = state.values[i];
1607
- if (v > out) out = v;
1608
- }
1609
- return out;
1610
- }
1611
- };
1612
- }
1613
- function readNumber(record, field) {
1614
- const value = readPath(record, field);
1615
- return typeof value === "number" && Number.isFinite(value) ? value : 0;
1616
- }
1617
-
1618
- // src/aggregate/aggregation.ts
1619
- function reduceRecords(records, spec) {
1620
- const state = {};
1621
- for (const key of Object.keys(spec)) {
1622
- state[key] = spec[key].init();
1623
- }
1624
- for (const record of records) {
1625
- for (const key of Object.keys(spec)) {
1626
- state[key] = spec[key].step(state[key], record);
1627
- }
1628
- }
1629
- const result = {};
1630
- for (const key of Object.keys(spec)) {
1631
- result[key] = spec[key].finalize(state[key]);
1632
- }
1633
- return result;
1634
- }
1635
- var LiveAggregationImpl = class {
1636
- constructor(recompute, upstreams) {
1637
- this.recompute = recompute;
1638
- try {
1639
- this.value = recompute();
1640
- this.error = void 0;
1641
- } catch (err) {
1642
- this.value = void 0;
1643
- this.error = err;
1644
- }
1645
- for (const upstream of upstreams) {
1646
- const unsub = upstream.subscribe(() => this.refresh());
1647
- this.unsubscribes.push(unsub);
1648
- }
1649
- }
1650
- recompute;
1651
- value;
1652
- error;
1653
- listeners = /* @__PURE__ */ new Set();
1654
- unsubscribes = [];
1655
- stopped = false;
1656
- refresh() {
1657
- if (this.stopped) return;
1658
- try {
1659
- this.value = this.recompute();
1660
- this.error = void 0;
1661
- } catch (err) {
1662
- this.error = err;
1663
- }
1664
- for (const listener of this.listeners) {
1665
- try {
1666
- listener();
1667
- } catch (err) {
1668
- console.warn("[noy-db] LiveAggregation listener threw:", err);
1669
- }
1670
- }
1671
- }
1672
- subscribe(cb) {
1673
- if (this.stopped) {
1674
- return () => {
1675
- };
1676
- }
1677
- this.listeners.add(cb);
1678
- return () => {
1679
- this.listeners.delete(cb);
1680
- };
1681
- }
1682
- stop() {
1683
- if (this.stopped) return;
1684
- this.stopped = true;
1685
- for (const unsub of this.unsubscribes) {
1686
- try {
1687
- unsub();
1688
- } catch (err) {
1689
- console.warn("[noy-db] LiveAggregation upstream unsubscribe threw:", err);
1690
- }
1691
- }
1692
- this.unsubscribes.length = 0;
1693
- this.listeners.clear();
1694
- }
1695
- };
1696
- var Aggregation = class {
1697
- constructor(executeRecords, spec, upstreams) {
1698
- this.executeRecords = executeRecords;
1699
- this.spec = spec;
1700
- this.upstreams = upstreams;
1701
- }
1702
- executeRecords;
1703
- spec;
1704
- upstreams;
1705
- /**
1706
- * Execute the query and reduce the results synchronously.
1707
- * Returns the reduced shape matching the spec — e.g. a spec of
1708
- * `{ total: sum('amount'), n: count() }` returns
1709
- * `{ total: number, n: number }`.
1710
- */
1711
- run() {
1712
- return reduceRecords(this.executeRecords(), this.spec);
1713
- }
1714
- /**
1715
- * Build a reactive `LiveAggregation<R>` that re-runs the reduction
1716
- * whenever any upstream source notifies of a change. The initial
1717
- * value is computed eagerly in the constructor, so consumers can
1718
- * read `live.value` immediately after calling `.live()`.
1719
- *
1720
- * Always call `live.stop()` when finished — it tears down the
1721
- * upstream subscriptions. Vue's `onUnmounted` is the canonical
1722
- * place.
1723
- *
1724
- * **Implementation note:** every upstream change triggers a full
1725
- * re-reduction. Incremental maintenance (O(1) per delta for
1726
- * sum/count/avg via the reducer protocol's `remove()` method) is a
1727
- * planned follow-up optimization — the protocol already supports
1728
- * it, but the executor doesn't drive it yet. Consumers get
1729
- * correct, reactive values today; future PRs can switch to
1730
- * delta-based maintenance without changing this API.
1731
- */
1732
- live() {
1733
- const recompute = () => reduceRecords(this.executeRecords(), this.spec);
1734
- return new LiveAggregationImpl(recompute, this.upstreams);
1735
- }
1736
- };
1737
- function buildLiveAggregation(recompute, upstreams) {
1738
- return new LiveAggregationImpl(recompute, upstreams);
1739
- }
1740
-
1741
- // src/aggregate/canonical-key.ts
1742
- function canonicalGroupKey(fields, row) {
1743
- const sorted = [...fields].sort();
1744
- const parts = [];
1745
- for (const name of sorted) {
1746
- const v = row[name];
1747
- const serialised = v === void 0 ? "undefined" : JSON.stringify(v);
1748
- parts.push(`${name}=${serialised}`);
1749
- }
1750
- return parts.join("|");
1751
- }
1752
-
1753
- // src/aggregate/groupby.ts
1754
- var GROUPBY_WARN_CARDINALITY = 1e4;
1755
- var GROUPBY_MAX_CARDINALITY = 1e5;
1756
- var warnedCardinalityFields = /* @__PURE__ */ new Set();
1757
- function warnCardinalityApproaching(fields, observed) {
1758
- const key = JSON.stringify([...fields].sort());
1759
- if (warnedCardinalityFields.has(key)) return;
1760
- warnedCardinalityFields.add(key);
1761
- const label = `[${fields.join(", ")}]`;
1762
- console.warn(
1763
- `[noy-db] .groupBy(${label}) produced ${observed} distinct groups, ${Math.round(observed / GROUPBY_MAX_CARDINALITY * 100)}% of the ${GROUPBY_MAX_CARDINALITY}-group ceiling. Narrow the query with .where() before grouping, or switch to a lower-cardinality field.`
1764
- );
1765
- }
1766
- function resetGroupByWarnings() {
1767
- warnedCardinalityFields.clear();
1768
- }
1769
- var GroupedQueryBase = class {
1770
- constructor(executeRecords, fieldOrFields, upstreams, dictLabelResolver) {
1771
- this.executeRecords = executeRecords;
1772
- this.upstreams = upstreams;
1773
- this.dictLabelResolver = dictLabelResolver;
1774
- this.fields = typeof fieldOrFields === "string" ? [fieldOrFields] : [...fieldOrFields];
1775
- }
1776
- executeRecords;
1777
- upstreams;
1778
- dictLabelResolver;
1779
- /**
1780
- * Field set this grouped query buckets on. Stored in declaration
1781
- * order — the same order is preserved on every result row by
1782
- * `groupAndReduce`. For the single-field constructor, this is
1783
- * `[field]`.
1784
- */
1785
- fields;
1786
- };
1787
- var GroupedQuery = class extends GroupedQueryBase {
1788
- /**
1789
- * Build a grouped aggregation. Returns a `GroupedAggregation`
1790
- * with `.run()`, `.runAsync()`, and `.live()` terminals — same shape
1791
- * as the non-grouped `.aggregate()` wrapper, just with an array
1792
- * result (one row per bucket) instead of a single reduced object.
1793
- */
1794
- aggregate(spec) {
1795
- return new GroupedAggregation(
1796
- this.executeRecords,
1797
- this.fields,
1798
- spec,
1799
- this.upstreams,
1800
- this.dictLabelResolver
1801
- );
1802
- }
1803
- };
1804
- var GroupedQueryN = class extends GroupedQueryBase {
1805
- aggregate(spec) {
1806
- return new GroupedAggregation(
1807
- this.executeRecords,
1808
- this.fields,
1809
- spec,
1810
- this.upstreams,
1811
- this.dictLabelResolver
1812
- );
1813
- }
1814
- };
1815
- function groupAndReduce(records, fieldOrFields, spec) {
1816
- const fields = typeof fieldOrFields === "string" ? [fieldOrFields] : fieldOrFields;
1817
- if (fields.length === 0) {
1818
- throw new Error(".groupBy() requires at least one field");
1819
- }
1820
- const buckets = /* @__PURE__ */ new Map();
1821
- const fieldLabel = fields.length === 1 ? fields[0] : `[${fields.join(", ")}]`;
1822
- for (const record of records) {
1823
- const keyValues = {};
1824
- for (const f of fields) {
1825
- keyValues[f] = readPath(record, f);
1826
- }
1827
- const dedupKey = canonicalGroupKey(fields, keyValues);
1828
- let bucket = buckets.get(dedupKey);
1829
- if (bucket === void 0) {
1830
- if (buckets.size >= GROUPBY_MAX_CARDINALITY) {
1831
- throw new GroupCardinalityError(
1832
- fieldLabel,
1833
- buckets.size + 1,
1834
- GROUPBY_MAX_CARDINALITY
1835
- );
1836
- }
1837
- bucket = { keyValues, records: [] };
1838
- buckets.set(dedupKey, bucket);
1839
- }
1840
- bucket.records.push(record);
1841
- }
1842
- if (buckets.size >= GROUPBY_WARN_CARDINALITY) {
1843
- warnCardinalityApproaching(fields, buckets.size);
1844
- }
1845
- const reducerKeys = Object.keys(spec);
1846
- const out = [];
1847
- for (const bucket of buckets.values()) {
1848
- const state = {};
1849
- for (const rk of reducerKeys) {
1850
- state[rk] = spec[rk].init();
1851
- }
1852
- for (const record of bucket.records) {
1853
- for (const rk of reducerKeys) {
1854
- state[rk] = spec[rk].step(state[rk], record);
1855
- }
1856
- }
1857
- const row = {};
1858
- for (const f of fields) {
1859
- row[f] = bucket.keyValues[f];
1860
- }
1861
- for (const rk of reducerKeys) {
1862
- row[rk] = spec[rk].finalize(state[rk]);
1863
- }
1864
- out.push(row);
1865
- }
1866
- return out;
1867
- }
1868
- var GroupedAggregation = class {
1869
- constructor(executeRecords, fields, spec, upstreams, dictLabelResolver) {
1870
- this.executeRecords = executeRecords;
1871
- this.spec = spec;
1872
- this.upstreams = upstreams;
1873
- this.dictLabelResolver = dictLabelResolver;
1874
- this.fields = typeof fields === "string" ? [fields] : [...fields];
1875
- }
1876
- executeRecords;
1877
- spec;
1878
- upstreams;
1879
- dictLabelResolver;
1880
- fields;
1881
- /** Execute the query, group, reduce, and return an array of rows. */
1882
- run() {
1883
- return groupAndReduce(this.executeRecords(), this.fields, this.spec);
1884
- }
1885
- /**
1886
- * Execute the query, group, reduce, and resolve `<field>Label` for
1887
- * each result row when the grouping field is a `dictKey` and a
1888
- * `locale` is provided. Returns `R[]` synchronously when
1889
- * no locale is specified (identical to `.run()`).
1890
- *
1891
- * The `<field>Label` field is appended to each row. Rows whose group
1892
- * key has no dictionary entry get `<field>Label: undefined`.
1893
- *
1894
- * Dict-label resolution is single-field only — multi-key groupings
1895
- * do not produce a `<field>Label`. The resolver is only attached
1896
- * by the builder when `fields.length === 1`.
1897
- */
1898
- async runAsync(opts) {
1899
- const rows = groupAndReduce(this.executeRecords(), this.fields, this.spec);
1900
- if (!opts?.locale || !this.dictLabelResolver || this.fields.length !== 1) return rows;
1901
- const resolve = this.dictLabelResolver;
1902
- const locale = opts.locale;
1903
- const fallback = opts.fallback;
1904
- const field = this.fields[0];
1905
- const labelKey = `${field}Label`;
1906
- return Promise.all(
1907
- rows.map(async (row) => {
1908
- const key = row[field];
1909
- if (typeof key !== "string") return row;
1910
- const label = await resolve(key, locale, fallback);
1911
- return { ...row, [labelKey]: label };
1912
- })
1913
- );
1914
- }
1915
- /**
1916
- * Build a reactive `LiveAggregation<R[]>` that re-runs the full
1917
- * group-and-reduce pipeline whenever any upstream source notifies
1918
- * of a change. Same error-isolation and idempotent-stop contract
1919
- * as `Aggregation.live()` — the implementation delegates to the
1920
- * same `LiveAggregationImpl` class by threading a fresh
1921
- * recompute closure through the existing constructor.
1922
- *
1923
- * uses naive full re-run on every change. Incremental
1924
- * per-bucket maintenance (apply `step` on inserted records,
1925
- * `remove` on deleted records, route by bucket key) is a future
1926
- * optimization — the reducer protocol admits it, but wiring
1927
- * delta-aware source subscriptions is a separate PR.
1928
- *
1929
- * Always call `live.stop()` when finished.
1930
- */
1931
- live() {
1932
- const recompute = () => groupAndReduce(this.executeRecords(), this.fields, this.spec);
1933
- return buildLiveAggregation(recompute, this.upstreams);
1934
- }
1935
- };
1936
-
1937
- // src/query/scan-builder.ts
1938
- var DEFAULT_SCAN_PAGE_SIZE = 100;
1939
- var ScanBuilder = class _ScanBuilder {
1940
- pageProvider;
1941
- pageSize;
1942
- clauses;
1943
- /**
1944
- * Zero-or-more join legs to apply per record as the stream flows.
1945
- * Each leg attaches the resolved right-side record (or null) under
1946
- * its alias. — streaming joins.
1947
- *
1948
- * Joins are evaluated AFTER clauses, so a `where()` filtered-out
1949
- * record never triggers a right-side lookup. This is the same
1950
- * ordering as `Query.toArray()` (clauses first, joins after) and
1951
- * keeps the streaming path from doing wasted work.
1952
- */
1953
- joins;
1954
- /**
1955
- * Join resolution context. Required for `.join()` to translate a
1956
- * field name into a target collection + ref mode and to resolve
1957
- * the right-side `JoinableSource`. Optional because tests
1958
- * construct ScanBuilder directly with synthetic page providers
1959
- * that don't know about ref() — calling `.join()` without a
1960
- * context throws with an actionable error.
1961
- */
1962
- joinContext;
1963
- constructor(pageProvider, pageSize = DEFAULT_SCAN_PAGE_SIZE, clauses = [], joins = [], joinContext) {
1964
- this.pageProvider = pageProvider;
1965
- this.pageSize = pageSize;
1966
- this.clauses = clauses;
1967
- this.joins = joins;
1968
- this.joinContext = joinContext;
1969
- }
1970
- /**
1971
- * Add a field comparison. Runs per record as the scan stream
1972
- * flows through, so non-matching records are dropped before they
1973
- * reach `.aggregate()` or the iteration consumer. Multiple
1974
- * `.where()` calls are AND-combined — same semantics as
1975
- * `Query.where()`.
1976
- *
1977
- * Clauses cannot use the secondary-index fast path here because
1978
- * the scan sources records from the adapter's paginator, not from
1979
- * the in-memory cache where indexes live. Index-accelerated scans
1980
- * are a future optimization — the current implementation
1981
- * evaluates clauses per record in O(1) per clause.
1982
- */
1983
- where(field, op, value) {
1984
- const clause = { type: "field", field, op, value };
1985
- return new _ScanBuilder(
1986
- this.pageProvider,
1987
- this.pageSize,
1988
- [...this.clauses, clause],
1989
- this.joins,
1990
- this.joinContext
1991
- );
1992
- }
1993
- /**
1994
- * Escape hatch: add an arbitrary predicate function. Same
1995
- * non-serializable caveat as `Query.filter()` — filter clauses
1996
- * don't round-trip through `toPlan()`. Prefer `.where()` when
1997
- * possible.
1998
- */
1999
- filter(fn) {
2000
- const clause = {
2001
- type: "filter",
2002
- fn
2003
- };
2004
- return new _ScanBuilder(
2005
- this.pageProvider,
2006
- this.pageSize,
2007
- [...this.clauses, clause],
2008
- this.joins,
2009
- this.joinContext
2010
- );
2011
- }
2012
- /**
2013
- * Resolve a `ref()`-declared foreign key per record as the scan
2014
- * stream flows, attaching the right-side record (or null) under
2015
- * `opts.as`. — streaming joins over `scan()`.
2016
- *
2017
- * ```ts
2018
- * for await (const inv of invoices.scan().join('clientId', { as: 'client' })) {
2019
- * await processInvoice(inv) // inv.client is attached
2020
- * }
2021
- *
2022
- * // Or terminate with .aggregate() for streaming joined aggregation
2023
- * const { total } = await invoices.scan()
2024
- * .where('status', '==', 'open')
2025
- * .join('clientId', { as: 'client' })
2026
- * .aggregate({ total: sum('amount') })
2027
- * ```
2028
- *
2029
- * **The key difference from eager `.join()`:** the LEFT
2030
- * side streams page-by-page from the adapter and is never
2031
- * materialized. Memory ceiling on the left is O(pageSize), not
2032
- * O(rowCount). This is what makes streaming joins suitable for
2033
- * collections that exceed the eager join's 50_000-row ceiling.
2034
- *
2035
- * **Right-side strategy** is auto-selected per leg:
2036
- * - **Indexed** — right source exposes `lookupById`, so each
2037
- * left row costs O(1). This is the common path for
2038
- * Collection right sides, which back `lookupById` with a Map
2039
- * lookup over the in-memory cache. The right collection must
2040
- * be in eager mode (the same constraint as eager join's
2041
- * `querySourceForJoin` from ).
2042
- * - **Hash** — right source has only `snapshot()`. Build a
2043
- * `Map<id, record>` once at iteration start, probe per left
2044
- * row. Same correctness, same per-row cost as the indexed
2045
- * path; the difference is the upfront cost of materializing
2046
- * the right side once.
2047
- *
2048
- * Both strategies hold the right side in memory for the duration
2049
- * of the iteration. The "streaming" property applies to the LEFT
2050
- * side only — true left-and-right streaming joins (where neither
2051
- * side fits in memory) require a sort-merge join planner that's
2052
- * out of scope for.
2053
- *
2054
- * **Ref-mode semantics** match eager `.join()` exactly:
2055
- * - `strict` → throws `DanglingReferenceError` mid-stream
2056
- * when a left record points at a non-existent right id.
2057
- * The throw aborts the async iterator — consumers should
2058
- * wrap the `for await` in try/catch if they want to recover.
2059
- * - `warn` → attaches `null` and emits a one-shot warning
2060
- * per unique dangling pair (deduped via the same warn
2061
- * channel as eager join).
2062
- * - `cascade` → attaches `null` silently. A delete-time mode;
2063
- * dangling refs at read time are mid-flight or pre-existing
2064
- * orphans, not a DSL error.
2065
- *
2066
- * Left records with null/undefined FK values attach `null`
2067
- * regardless of mode — same "no reference at all" policy as
2068
- * eager join and write-time `enforceRefsOnPut`.
2069
- *
2070
- * **Multi-FK chaining** is supported via repeated `.join()`
2071
- * calls: each leg resolves an independent ref. Each leg
2072
- * independently picks its right-side strategy and applies its
2073
- * own ref mode.
2074
- *
2075
- * **Joins are NOT applied** to a `.aggregate()` terminal that
2076
- * doesn't reference joined fields — wait, that's not quite
2077
- * right. The streaming path actually DOES apply joins before
2078
- * `.aggregate()` because the join attaches a field that the
2079
- * spec might reference. Unlike `Query.aggregate()` (which skips
2080
- * joins entirely as a projection-only short-circuit), the
2081
- * streaming aggregation can't know whether the spec touches a
2082
- * joined field, so it always applies joins. Consumers who want
2083
- * unjoined streaming aggregation should leave `.join()` off the
2084
- * chain — the chain is composable for a reason.
2085
- *
2086
- * constraint #1 — every JoinLeg carries `partitionScope:
2087
- * 'all'` plumbed through but never read by. Same seam as
2088
- * eager join.
2089
- */
2090
- join(field, opts) {
2091
- if (!this.joinContext) {
2092
- throw new Error(
2093
- `ScanBuilder.join() requires a join context. Use collection.scan() to construct a join-capable scan instead of the ScanBuilder constructor directly (the direct constructor is only used for tests with synthetic page providers).`
2094
- );
2095
- }
2096
- const descriptor = this.joinContext.resolveRef(field);
2097
- if (!descriptor) {
2098
- throw new Error(
2099
- `ScanBuilder.join(): no ref() declared for field "${field}" on collection "${this.joinContext.leftCollection}". Add refs: { ${field}: ref('<target-collection>') } to the collection options, then retry.`
2100
- );
2101
- }
2102
- const leg = {
2103
- field,
2104
- as: opts.as,
2105
- target: descriptor.target,
2106
- mode: descriptor.mode,
2107
- strategy: void 0,
2108
- maxRows: void 0,
2109
- // constraint #1 — always 'all' in, never read by
2110
- // the streaming executor. partition-aware scan joins
2111
- // will populate this from where() predicates without
2112
- // changing the planner shape.
2113
- partitionScope: "all"
2114
- };
2115
- return new _ScanBuilder(
2116
- this.pageProvider,
2117
- this.pageSize,
2118
- this.clauses,
2119
- [...this.joins, leg],
2120
- this.joinContext
2121
- );
2122
- }
2123
- /**
2124
- * Iterate the scan as an async iterable. Walks the page
2125
- * provider's cursors forward until exhaustion, applying every
2126
- * clause per record — only matching records are yielded.
2127
- *
2128
- * Backward-compatible with the previous async-generator `scan()`
2129
- * return type for `for await … of` consumers.
2130
- */
2131
- async *[Symbol.asyncIterator]() {
2132
- const joinResolvers = this.joins.length === 0 ? null : this.buildJoinResolvers();
2133
- let page = await this.pageProvider.listPage({ limit: this.pageSize });
2134
- while (true) {
2135
- for (const record of page.items) {
2136
- if (!this.recordMatches(record)) continue;
2137
- if (joinResolvers === null) {
2138
- yield record;
2139
- } else {
2140
- let attached = record;
2141
- for (const resolver of joinResolvers) {
2142
- attached = this.applyOneJoinStreaming(attached, resolver);
2143
- }
2144
- yield attached;
2145
- }
2146
- }
2147
- if (page.nextCursor === null) return;
2148
- page = await this.pageProvider.listPage({
2149
- cursor: page.nextCursor,
2150
- limit: this.pageSize
2151
- });
2152
- }
2153
- }
2154
- /**
2155
- * Per-leg right-side resolution state. Built once at iteration
2156
- * start and reused for every left record. Two strategies:
2157
- *
2158
- * - `lookupById`: present when the right source exposes the
2159
- * hook directly (typical Collection right side). Per-row
2160
- * cost is O(1).
2161
- * - `hashByPrimaryKey`: built from `snapshot()` when no
2162
- * lookupById. Per-row cost is O(1) after the upfront O(N)
2163
- * materialization. Same as eager join's hash strategy.
2164
- *
2165
- * `warnedKeys` is the per-leg dedup set for ref-mode 'warn'. We
2166
- * key on `field→target:refId` so the same dangling pair only
2167
- * warns once per iteration. The dedup is per-iteration, not
2168
- * per-process — a long-running scan that re-iterates would warn
2169
- * again, which is the desired behavior (the data may have
2170
- * changed between iterations).
2171
- */
2172
- buildJoinResolvers() {
2173
- if (!this.joinContext) {
2174
- throw new Error(
2175
- `ScanBuilder iterator: ${this.joins.length} join leg(s) present but no JoinContext attached. Use collection.scan() to construct a join-capable scan.`
2176
- );
2177
- }
2178
- const resolvers = [];
2179
- for (const leg of this.joins) {
2180
- const source = this.joinContext.resolveSource(leg.target);
2181
- if (!source) {
2182
- throw new Error(
2183
- `ScanBuilder.join() cannot resolve target collection "${leg.target}" (referenced from field "${leg.field}" on "${this.joinContext.leftCollection}"). Make sure the target collection has been opened via vault.collection() at least once before iterating the scan.`
2184
- );
2185
- }
2186
- let lookupById = null;
2187
- let hashByPrimaryKey = null;
2188
- if (source.lookupById) {
2189
- const fn = source.lookupById.bind(source);
2190
- lookupById = (id) => fn(id);
2191
- } else {
2192
- const map = /* @__PURE__ */ new Map();
2193
- for (const record of source.snapshot()) {
2194
- const rawId = readPath(record, "id");
2195
- const key = coerceRefKey2(rawId);
2196
- if (key !== null) map.set(key, record);
2197
- }
2198
- hashByPrimaryKey = map;
2199
- }
2200
- resolvers.push({
2201
- leg,
2202
- source,
2203
- lookupById,
2204
- hashByPrimaryKey,
2205
- warnedKeys: /* @__PURE__ */ new Set()
2206
- });
2207
- }
2208
- return resolvers;
2209
- }
2210
- /**
2211
- * Resolve a single join leg for one left record and return the
2212
- * left record with the joined field attached under
2213
- * `leg.as`. Pure function over `(left, resolver)`; never
2214
- * mutates the input.
2215
- *
2216
- * Ref-mode dispatch matches eager `applyJoins` from :
2217
- * - null/undefined FK → attach null silently (always allowed)
2218
- * - dangling FK + strict → throw `DanglingReferenceError`
2219
- * - dangling FK + warn → attach null, warn-once per pair
2220
- * - dangling FK + cascade → attach null silently
2221
- */
2222
- applyOneJoinStreaming(left, resolver) {
2223
- if (left === null || typeof left !== "object") {
2224
- return left;
2225
- }
2226
- const { leg } = resolver;
2227
- const rawId = readPath(left, leg.field);
2228
- const refKey = coerceRefKey2(rawId);
2229
- let right = void 0;
2230
- if (refKey !== null) {
2231
- if (resolver.lookupById !== null) {
2232
- right = resolver.lookupById(refKey);
2233
- } else if (resolver.hashByPrimaryKey !== null) {
2234
- right = resolver.hashByPrimaryKey.get(refKey);
2235
- }
2236
- }
2237
- const merged = {
2238
- ...left
2239
- };
2240
- if (right === void 0) {
2241
- if (refKey !== null && leg.mode === "strict") {
2242
- throw new DanglingReferenceError({
2243
- field: leg.field,
2244
- target: leg.target,
2245
- refId: refKey,
2246
- message: `ScanBuilder.join() strict dangling: record references "${leg.target}:${refKey}" via field "${leg.field}", but no such record exists. Use ref() mode 'warn' or 'cascade' if dangling refs are acceptable, or run vault.checkIntegrity() to find and fix the orphans.`
2247
- });
2248
- }
2249
- if (refKey !== null && leg.mode === "warn") {
2250
- const dedupKey = `${leg.field}\u2192${leg.target}:${refKey}`;
2251
- if (!resolver.warnedKeys.has(dedupKey)) {
2252
- resolver.warnedKeys.add(dedupKey);
2253
- console.warn(
2254
- `[noy-db] ScanBuilder.join() encountered dangling ref in 'warn' mode: field "${leg.field}" \u2192 "${leg.target}:${refKey}" not found. Attaching null.`
2255
- );
2256
- }
2257
- }
2258
- merged[leg.as] = null;
2259
- } else {
2260
- merged[leg.as] = right;
2261
- }
2262
- return merged;
2263
- }
2264
- /**
2265
- * Reduce the scan stream through a named set of reducers and
2266
- * return the final aggregated shape.
2267
- *
2268
- * Memory is O(reducers): one mutable state slot per spec key.
2269
- * Records flow through the pipeline one at a time via
2270
- * `for await` and are discarded after their `step()` is applied
2271
- * — never collected into an array. This is the distinguishing
2272
- * property from `Query.aggregate()`, which materializes the full
2273
- * match set first.
2274
- *
2275
- * Reuses the same reducer protocol as `Query.aggregate()`,
2276
- * so `count()`, `sum(field)`, `avg(field)`, `min(field)`,
2277
- * `max(field)` all work unchanged. The `{ seed }` parameter
2278
- * plumbing from constraint #2 is honored transparently — the
2279
- * factories ignore it in and the scan executor never
2280
- * touches the per-reducer state construction.
2281
- *
2282
- * **Returns a Promise**, unlike `Query.aggregate().run()` which
2283
- * is synchronous. The scan is inherently async because it walks
2284
- * adapter pages, so the terminal has to be too. Consumers
2285
- * destructure with await:
2286
- *
2287
- * ```ts
2288
- * const { total, n } = await invoices.scan()
2289
- * .where('year', '==', 2025)
2290
- * .aggregate({ total: sum('amount'), n: count() })
2291
- * ```
2292
- *
2293
- * **No `.live()` in.** `scan().aggregate().live()` would
2294
- * require reconciling an unbounded streaming iteration with a
2295
- * change-stream subscription — a design problem, not just a code
2296
- * one. Consumers with huge collections and live needs should
2297
- * narrow with `.where()` enough to fit in the 50k `query()`
2298
- * limit and use `query().aggregate().live()` instead.
2299
- */
2300
- async aggregate(spec) {
2301
- const keys = Object.keys(spec);
2302
- const state = {};
2303
- for (const key of keys) {
2304
- state[key] = spec[key].init();
2305
- }
2306
- for await (const record of this) {
2307
- for (const key of keys) {
2308
- state[key] = spec[key].step(state[key], record);
2309
- }
2310
- }
2311
- const result = {};
2312
- for (const key of keys) {
2313
- result[key] = spec[key].finalize(state[key]);
2314
- }
2315
- return result;
2316
- }
2317
- /**
2318
- * Evaluate the clause list against a single record. Linear in
2319
- * the clause count; short-circuits on first false. Clauses on a
2320
- * scan are always re-evaluated per record — no index-accelerated
2321
- * path, because the stream sources records from the adapter
2322
- * paginator, not from the in-memory cache where indexes live.
2323
- */
2324
- recordMatches(record) {
2325
- if (this.clauses.length === 0) return true;
2326
- for (const clause of this.clauses) {
2327
- if (!evaluateClause(record, clause)) return false;
2328
- }
2329
- return true;
2330
- }
2331
- };
2332
- function coerceRefKey2(value) {
2333
- if (value === null || value === void 0) return null;
2334
- if (typeof value === "string") return value;
2335
- if (typeof value === "number" || typeof value === "bigint") return String(value);
2336
- return null;
2337
- }
2338
- // Annotate the CommonJS export names for ESM import in node:
2339
- 0 && (module.exports = {
2340
- Aggregation,
2341
- CollectionIndexes,
2342
- CrossJoinSourceUnknownError,
2343
- CrossJoinTooLargeError,
2344
- DEFAULT_CROSS_JOIN_MAX_ROWS,
2345
- DEFAULT_JOIN_MAX_ROWS,
2346
- DanglingReferenceError,
2347
- GROUPBY_MAX_CARDINALITY,
2348
- GROUPBY_WARN_CARDINALITY,
2349
- GroupCardinalityError,
2350
- GroupedAggregation,
2351
- GroupedQuery,
2352
- GroupedQueryN,
2353
- IndexRequiredError,
2354
- IndexWriteFailureError,
2355
- JoinTooLargeError,
2356
- Query,
2357
- ScanBuilder,
2358
- applyJoins,
2359
- avg,
2360
- buildLiveAggregation,
2361
- buildLiveQuery,
2362
- count,
2363
- evaluateClause,
2364
- evaluateFieldClause,
2365
- executePlan,
2366
- groupAndReduce,
2367
- max,
2368
- min,
2369
- readPath,
2370
- reduceRecords,
2371
- resetGroupByWarnings,
2372
- resetJoinWarnings,
2373
- sum
2374
- });
2375
- //# sourceMappingURL=index.cjs.map