@nicia-ai/typegraph 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/README.md +12 -10
  2. package/dist/backend/drizzle/indexes.cjs +32 -0
  3. package/dist/backend/drizzle/indexes.cjs.map +1 -0
  4. package/dist/backend/drizzle/indexes.d.cts +43 -0
  5. package/dist/backend/drizzle/indexes.d.ts +43 -0
  6. package/dist/backend/drizzle/indexes.js +11 -0
  7. package/dist/backend/drizzle/indexes.js.map +1 -0
  8. package/dist/backend/index.cjs +161 -0
  9. package/dist/backend/index.cjs.map +1 -0
  10. package/dist/backend/index.d.cts +3 -0
  11. package/dist/backend/index.d.ts +3 -0
  12. package/dist/backend/index.js +8 -0
  13. package/dist/backend/index.js.map +1 -0
  14. package/dist/backend/postgres/index.cjs +32 -28
  15. package/dist/backend/postgres/index.d.cts +13 -12
  16. package/dist/backend/postgres/index.d.ts +13 -12
  17. package/dist/backend/postgres/index.js +19 -15
  18. package/dist/backend/postgres/pglite-store.cjs +67 -0
  19. package/dist/backend/postgres/pglite-store.cjs.map +1 -0
  20. package/dist/backend/postgres/pglite-store.d.cts +38 -0
  21. package/dist/backend/postgres/pglite-store.d.ts +38 -0
  22. package/dist/backend/postgres/pglite-store.js +65 -0
  23. package/dist/backend/postgres/pglite-store.js.map +1 -0
  24. package/dist/backend/postgres/pglite.cjs +25 -50
  25. package/dist/backend/postgres/pglite.cjs.map +1 -1
  26. package/dist/backend/postgres/pglite.d.cts +10 -9
  27. package/dist/backend/postgres/pglite.d.ts +10 -9
  28. package/dist/backend/postgres/pglite.js +20 -52
  29. package/dist/backend/postgres/pglite.js.map +1 -1
  30. package/dist/backend/sqlite/index.cjs +29 -25
  31. package/dist/backend/sqlite/index.d.cts +11 -11
  32. package/dist/backend/sqlite/index.d.ts +11 -11
  33. package/dist/backend/sqlite/index.js +17 -13
  34. package/dist/backend/sqlite/libsql.cjs +23 -19
  35. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  36. package/dist/backend/sqlite/libsql.d.cts +9 -10
  37. package/dist/backend/sqlite/libsql.d.ts +9 -10
  38. package/dist/backend/sqlite/libsql.js +19 -15
  39. package/dist/backend/sqlite/libsql.js.map +1 -1
  40. package/dist/backend/sqlite/local-store.cjs +72 -0
  41. package/dist/backend/sqlite/local-store.cjs.map +1 -0
  42. package/dist/backend/sqlite/local-store.d.cts +42 -0
  43. package/dist/backend/sqlite/local-store.d.ts +42 -0
  44. package/dist/backend/sqlite/local-store.js +67 -0
  45. package/dist/backend/sqlite/local-store.js.map +1 -0
  46. package/dist/backend/sqlite/local.cjs +28 -183
  47. package/dist/backend/sqlite/local.cjs.map +1 -1
  48. package/dist/backend/sqlite/local.d.cts +8 -81
  49. package/dist/backend/sqlite/local.d.ts +8 -81
  50. package/dist/backend/sqlite/local.js +20 -180
  51. package/dist/backend/sqlite/local.js.map +1 -1
  52. package/dist/chunk-2EBMPJBO.js +16 -0
  53. package/dist/chunk-2EBMPJBO.js.map +1 -0
  54. package/dist/{chunk-NBP2WTJW.cjs → chunk-2SL7OGPR.cjs} +2900 -1597
  55. package/dist/chunk-2SL7OGPR.cjs.map +1 -0
  56. package/dist/chunk-35S6P5ZU.js +27 -0
  57. package/dist/chunk-35S6P5ZU.js.map +1 -0
  58. package/dist/chunk-3LKL3S6X.js +50 -0
  59. package/dist/chunk-3LKL3S6X.js.map +1 -0
  60. package/dist/chunk-6G5CQ6JX.js +47 -0
  61. package/dist/chunk-6G5CQ6JX.js.map +1 -0
  62. package/dist/chunk-6XDBRDZE.js +312 -0
  63. package/dist/chunk-6XDBRDZE.js.map +1 -0
  64. package/dist/chunk-764JHTLT.cjs +15 -0
  65. package/dist/chunk-764JHTLT.cjs.map +1 -0
  66. package/dist/chunk-76HE7DJP.js +68 -0
  67. package/dist/chunk-76HE7DJP.js.map +1 -0
  68. package/dist/{chunk-VGDDG3XJ.cjs → chunk-7M3NACL3.cjs} +12 -12
  69. package/dist/{chunk-VGDDG3XJ.cjs.map → chunk-7M3NACL3.cjs.map} +1 -1
  70. package/dist/{chunk-NXQFATMF.cjs → chunk-7VLCN3JB.cjs} +153 -123
  71. package/dist/chunk-7VLCN3JB.cjs.map +1 -0
  72. package/dist/{chunk-552KNYQJ.js → chunk-A2FGSWMQ.js} +1907 -607
  73. package/dist/chunk-A2FGSWMQ.js.map +1 -0
  74. package/dist/chunk-AOL64O4Z.js +165 -0
  75. package/dist/chunk-AOL64O4Z.js.map +1 -0
  76. package/dist/{chunk-27SSDCEP.cjs → chunk-B63IFHXR.cjs} +53 -74
  77. package/dist/chunk-B63IFHXR.cjs.map +1 -0
  78. package/dist/{chunk-3XXGYU62.cjs → chunk-BKAKAVRW.cjs} +56 -53
  79. package/dist/chunk-BKAKAVRW.cjs.map +1 -0
  80. package/dist/{chunk-YTSN73ND.js → chunk-BQITNFQJ.js} +3 -3
  81. package/dist/{chunk-YTSN73ND.js.map → chunk-BQITNFQJ.js.map} +1 -1
  82. package/dist/{chunk-NUIG3BCV.cjs → chunk-CQC6VBAF.cjs} +93 -155
  83. package/dist/chunk-CQC6VBAF.cjs.map +1 -0
  84. package/dist/{chunk-6EEO3OVU.cjs → chunk-CWX77JB4.cjs} +22 -59
  85. package/dist/chunk-CWX77JB4.cjs.map +1 -0
  86. package/dist/{chunk-UGZUAYAR.js → chunk-D7PG5D5K.js} +4 -3
  87. package/dist/chunk-D7PG5D5K.js.map +1 -0
  88. package/dist/chunk-DDCIXXOO.js +9 -0
  89. package/dist/chunk-DDCIXXOO.js.map +1 -0
  90. package/dist/chunk-DDCYVIVV.cjs +44 -0
  91. package/dist/chunk-DDCYVIVV.cjs.map +1 -0
  92. package/dist/{chunk-XPCZADMT.cjs → chunk-DOVMTPKE.cjs} +89 -27
  93. package/dist/chunk-DOVMTPKE.cjs.map +1 -0
  94. package/dist/{chunk-5PNMDJ7J.js → chunk-DPNA466P.js} +14 -9
  95. package/dist/chunk-DPNA466P.js.map +1 -0
  96. package/dist/{chunk-BYPOGQWK.js → chunk-DRACN6XG.js} +6 -4
  97. package/dist/chunk-DRACN6XG.js.map +1 -0
  98. package/dist/chunk-E6TXEISH.cjs +175 -0
  99. package/dist/chunk-E6TXEISH.cjs.map +1 -0
  100. package/dist/{chunk-TKT2XHED.js → chunk-E6YZRKMM.js} +13 -12
  101. package/dist/chunk-E6YZRKMM.js.map +1 -0
  102. package/dist/{chunk-3C2RYI6L.cjs → chunk-EOJFGECD.cjs} +11 -11
  103. package/dist/chunk-EOJFGECD.cjs.map +1 -0
  104. package/dist/{chunk-XWV4JT34.js → chunk-ERZ4QPQX.js} +27 -22
  105. package/dist/chunk-ERZ4QPQX.js.map +1 -0
  106. package/dist/{chunk-DFVLCOP6.js → chunk-EZH7FNUS.js} +3 -3
  107. package/dist/{chunk-DFVLCOP6.js.map → chunk-EZH7FNUS.js.map} +1 -1
  108. package/dist/{chunk-WWFHO375.cjs → chunk-FJMPR3OH.cjs} +4 -3
  109. package/dist/chunk-FJMPR3OH.cjs.map +1 -0
  110. package/dist/chunk-FMNUSGZ4.cjs +12 -0
  111. package/dist/chunk-FMNUSGZ4.cjs.map +1 -0
  112. package/dist/{chunk-K3Q3LJY3.js → chunk-G32AO634.js} +201 -100
  113. package/dist/chunk-G32AO634.js.map +1 -0
  114. package/dist/{chunk-EXU3RASM.js → chunk-G3CSQLLT.js} +20 -474
  115. package/dist/chunk-G3CSQLLT.js.map +1 -0
  116. package/dist/chunk-GNPGGLAE.cjs +212 -0
  117. package/dist/chunk-GNPGGLAE.cjs.map +1 -0
  118. package/dist/{chunk-QARBLBXT.cjs → chunk-GUUWKPTK.cjs} +7 -7
  119. package/dist/{chunk-QARBLBXT.cjs.map → chunk-GUUWKPTK.cjs.map} +1 -1
  120. package/dist/chunk-GYA4JRP5.js +31 -0
  121. package/dist/chunk-GYA4JRP5.js.map +1 -0
  122. package/dist/chunk-I6FX7AAG.js +39 -0
  123. package/dist/chunk-I6FX7AAG.js.map +1 -0
  124. package/dist/chunk-IMQKXL4E.cjs +12 -0
  125. package/dist/{chunk-QSXTWU4U.cjs.map → chunk-IMQKXL4E.cjs.map} +1 -1
  126. package/dist/chunk-J6IJARLG.js +94 -0
  127. package/dist/chunk-J6IJARLG.js.map +1 -0
  128. package/dist/{chunk-W63OVYY4.js → chunk-K34OPSJK.js} +3 -3
  129. package/dist/{chunk-W63OVYY4.js.map → chunk-K34OPSJK.js.map} +1 -1
  130. package/dist/{chunk-TGOMW4MB.cjs → chunk-KCLZHYPU.cjs} +110 -109
  131. package/dist/chunk-KCLZHYPU.cjs.map +1 -0
  132. package/dist/{chunk-XGPUQ56G.js → chunk-KFLXWVUJ.js} +4 -38
  133. package/dist/chunk-KFLXWVUJ.js.map +1 -0
  134. package/dist/{chunk-3DS7Z4T4.cjs → chunk-LZ3TVJY4.cjs} +44 -43
  135. package/dist/chunk-LZ3TVJY4.cjs.map +1 -0
  136. package/dist/{chunk-UXLSNRYL.js → chunk-MTNEGGM2.js} +4 -4
  137. package/dist/chunk-MTNEGGM2.js.map +1 -0
  138. package/dist/{chunk-IP3CGGPA.cjs → chunk-N2V3HJFV.cjs} +92 -185
  139. package/dist/chunk-N2V3HJFV.cjs.map +1 -0
  140. package/dist/chunk-NAUA4PW5.cjs +28 -0
  141. package/dist/chunk-NAUA4PW5.cjs.map +1 -0
  142. package/dist/chunk-NMQ6C6TS.cjs +61 -0
  143. package/dist/chunk-NMQ6C6TS.cjs.map +1 -0
  144. package/dist/{chunk-2N6EOBTH.cjs → chunk-NPWACFQJ.cjs} +58 -53
  145. package/dist/chunk-NPWACFQJ.cjs.map +1 -0
  146. package/dist/{chunk-5KEQ74YU.cjs → chunk-NT6ILURI.cjs} +9 -86
  147. package/dist/chunk-NT6ILURI.cjs.map +1 -0
  148. package/dist/chunk-NU23DUSJ.cjs +192 -0
  149. package/dist/chunk-NU23DUSJ.cjs.map +1 -0
  150. package/dist/{chunk-WOJMKB3N.cjs → chunk-NWYCOFEZ.cjs} +1677 -308
  151. package/dist/chunk-NWYCOFEZ.cjs.map +1 -0
  152. package/dist/{chunk-3GH67G4Z.cjs → chunk-O5H62ZWJ.cjs} +4 -42
  153. package/dist/chunk-O5H62ZWJ.cjs.map +1 -0
  154. package/dist/{chunk-3SLPDKHQ.js → chunk-PH4IJ3V5.js} +5 -77
  155. package/dist/chunk-PH4IJ3V5.js.map +1 -0
  156. package/dist/chunk-PWXGB77L.cjs +56 -0
  157. package/dist/chunk-PWXGB77L.cjs.map +1 -0
  158. package/dist/chunk-PZHC5GCD.js +193 -0
  159. package/dist/chunk-PZHC5GCD.js.map +1 -0
  160. package/dist/chunk-QMQLUA66.js +12 -0
  161. package/dist/chunk-QMQLUA66.js.map +1 -0
  162. package/dist/{chunk-5WWVZMVX.js → chunk-QZ7A6HBM.js} +2 -2
  163. package/dist/{chunk-5WWVZMVX.js.map → chunk-QZ7A6HBM.js.map} +1 -1
  164. package/dist/{chunk-VKGKDOKR.js → chunk-RQPRCEIO.js} +1539 -206
  165. package/dist/chunk-RQPRCEIO.js.map +1 -0
  166. package/dist/chunk-RW24SAHI.cjs +74 -0
  167. package/dist/chunk-RW24SAHI.cjs.map +1 -0
  168. package/dist/{chunk-BVRDGYXQ.cjs → chunk-SAFZ6JTI.cjs} +14 -9
  169. package/dist/chunk-SAFZ6JTI.cjs.map +1 -0
  170. package/dist/{chunk-L7HQ2OSI.js → chunk-SCTZRFW5.js} +87 -166
  171. package/dist/chunk-SCTZRFW5.js.map +1 -0
  172. package/dist/{chunk-5KPNWT6X.js → chunk-SDHV2MWU.js} +24 -45
  173. package/dist/chunk-SDHV2MWU.js.map +1 -0
  174. package/dist/chunk-SVJ5GEXW.cjs +45 -0
  175. package/dist/chunk-SVJ5GEXW.cjs.map +1 -0
  176. package/dist/chunk-SVUKGWSN.cjs +102 -0
  177. package/dist/chunk-SVUKGWSN.cjs.map +1 -0
  178. package/dist/chunk-TAUGGLNQ.js +59 -0
  179. package/dist/chunk-TAUGGLNQ.js.map +1 -0
  180. package/dist/{chunk-J4IUSYFF.js → chunk-TE5ZA4VX.js} +69 -27
  181. package/dist/chunk-TE5ZA4VX.js.map +1 -0
  182. package/dist/{chunk-A42GCBGX.cjs → chunk-TRF4EBJT.cjs} +6 -4
  183. package/dist/chunk-TRF4EBJT.cjs.map +1 -0
  184. package/dist/{chunk-KQJ54OG5.js → chunk-U4JDJKPD.js} +19 -56
  185. package/dist/chunk-U4JDJKPD.js.map +1 -0
  186. package/dist/chunk-UH2USOMG.cjs +627 -0
  187. package/dist/chunk-UH2USOMG.cjs.map +1 -0
  188. package/dist/{chunk-RCVLFTCT.js → chunk-UPXDVI3T.js} +13 -12
  189. package/dist/chunk-UPXDVI3T.js.map +1 -0
  190. package/dist/{chunk-5VQM6VWP.cjs → chunk-UWG5GX6E.cjs} +2 -2
  191. package/dist/{chunk-5VQM6VWP.cjs.map → chunk-UWG5GX6E.cjs.map} +1 -1
  192. package/dist/{chunk-3RWZPJKV.js → chunk-VBH7ZXSZ.js} +21 -78
  193. package/dist/chunk-VBH7ZXSZ.js.map +1 -0
  194. package/dist/{chunk-K5UBVGJN.js → chunk-VDYA2HMS.js} +6 -6
  195. package/dist/{chunk-K5UBVGJN.js.map → chunk-VDYA2HMS.js.map} +1 -1
  196. package/dist/chunk-X4PVHAZ6.cjs +83 -0
  197. package/dist/chunk-X4PVHAZ6.cjs.map +1 -0
  198. package/dist/{chunk-UYQMBBWJ.js → chunk-X6CNEA32.js} +23 -20
  199. package/dist/chunk-X6CNEA32.js.map +1 -0
  200. package/dist/chunk-X6RDQ5NB.cjs +335 -0
  201. package/dist/chunk-X6RDQ5NB.cjs.map +1 -0
  202. package/dist/chunk-XD6X7O5R.js +184 -0
  203. package/dist/chunk-XD6X7O5R.js.map +1 -0
  204. package/dist/{chunk-DIQ3AV5W.cjs → chunk-XFY73JWD.cjs} +324 -224
  205. package/dist/chunk-XFY73JWD.cjs.map +1 -0
  206. package/dist/{chunk-DEFQM7JU.cjs → chunk-XRU7V7FF.cjs} +7 -7
  207. package/dist/{chunk-DEFQM7JU.cjs.map → chunk-XRU7V7FF.cjs.map} +1 -1
  208. package/dist/{chunk-TPF25IG6.js → chunk-XZA3Y4YH.js} +3 -3
  209. package/dist/{chunk-TPF25IG6.js.map → chunk-XZA3Y4YH.js.map} +1 -1
  210. package/dist/chunk-Y7M44XEK.js +462 -0
  211. package/dist/chunk-Y7M44XEK.js.map +1 -0
  212. package/dist/{chunk-RRSNR3TP.js → chunk-YIRLBUNN.js} +3 -3
  213. package/dist/{chunk-RRSNR3TP.js.map → chunk-YIRLBUNN.js.map} +1 -1
  214. package/dist/{chunk-IXGYRP2P.js → chunk-YJDSPA5E.js} +79 -49
  215. package/dist/chunk-YJDSPA5E.js.map +1 -0
  216. package/dist/{chunk-JBNOGRKW.cjs → chunk-YLINFV7Z.cjs} +157 -115
  217. package/dist/chunk-YLINFV7Z.cjs.map +1 -0
  218. package/dist/{chunk-QERAIDRJ.js → chunk-Z2PPIVOO.js} +82 -22
  219. package/dist/chunk-Z2PPIVOO.js.map +1 -0
  220. package/dist/chunk-Z5QHVL5U.cjs +12 -0
  221. package/dist/chunk-Z5QHVL5U.cjs.map +1 -0
  222. package/dist/chunk-ZDH3DX3C.cjs +30 -0
  223. package/dist/chunk-ZDH3DX3C.cjs.map +1 -0
  224. package/dist/chunk-ZE6NVENI.js +77 -0
  225. package/dist/chunk-ZE6NVENI.js.map +1 -0
  226. package/dist/chunk-ZHX4KEM7.cjs +49 -0
  227. package/dist/chunk-ZHX4KEM7.cjs.map +1 -0
  228. package/dist/chunk-ZKZAIX42.cjs +479 -0
  229. package/dist/chunk-ZKZAIX42.cjs.map +1 -0
  230. package/dist/{chunk-TEDRJXOG.cjs → chunk-ZY4GXIVN.cjs} +5 -5
  231. package/dist/{chunk-TEDRJXOG.cjs.map → chunk-ZY4GXIVN.cjs.map} +1 -1
  232. package/dist/core/index.cjs +117 -0
  233. package/dist/core/index.cjs.map +1 -0
  234. package/dist/core/index.d.cts +225 -0
  235. package/dist/core/index.d.ts +225 -0
  236. package/dist/core/index.js +12 -0
  237. package/dist/core/index.js.map +1 -0
  238. package/dist/{ddl-CS0KUVwB.d.ts → ddl-Dx3Z0_WC.d.ts} +3 -3
  239. package/dist/{ddl-BD-ZfKeX.d.cts → ddl-J6sDyABg.d.cts} +3 -3
  240. package/dist/define-graph-CzEvA_8F.d.cts +174 -0
  241. package/dist/define-graph-DRo9xpYN.d.ts +174 -0
  242. package/dist/{extension-types-BM2ACfYO.d.cts → extension-types-BLEVH4SG.d.cts} +1 -1
  243. package/dist/{extension-types-BM2ACfYO.d.ts → extension-types-BLEVH4SG.d.ts} +1 -1
  244. package/dist/graph-extension/index.cjs +21 -19
  245. package/dist/graph-extension/index.d.cts +4 -4
  246. package/dist/graph-extension/index.d.ts +4 -4
  247. package/dist/graph-extension/index.js +6 -4
  248. package/dist/graph-merge/index.cjs +265 -214
  249. package/dist/graph-merge/index.cjs.map +1 -1
  250. package/dist/graph-merge/index.d.cts +8 -89
  251. package/dist/graph-merge/index.d.ts +8 -89
  252. package/dist/graph-merge/index.js +141 -90
  253. package/dist/graph-merge/index.js.map +1 -1
  254. package/dist/{index-BeacbPoe.d.ts → index-BD_3TCgh.d.ts} +6 -4
  255. package/dist/{index-BPM59vsg.d.cts → index-BihFPsPu.d.cts} +6 -4
  256. package/dist/{fulltext-strategy-C27vXaeB.d.cts → index-Bq7vSPHy.d.ts} +3195 -2646
  257. package/dist/{fulltext-strategy-DebsMrqg.d.ts → index-CrFL_ENI.d.cts} +3195 -2646
  258. package/dist/index.cjs +326 -315
  259. package/dist/index.cjs.map +1 -1
  260. package/dist/index.d.cts +59 -240
  261. package/dist/index.d.ts +59 -240
  262. package/dist/index.js +46 -79
  263. package/dist/index.js.map +1 -1
  264. package/dist/indexes/index.cjs +26 -38
  265. package/dist/indexes/index.d.cts +6 -41
  266. package/dist/indexes/index.d.ts +6 -41
  267. package/dist/indexes/index.js +14 -10
  268. package/dist/interchange/index.cjs +48 -39
  269. package/dist/interchange/index.cjs.map +1 -1
  270. package/dist/interchange/index.d.cts +7 -8
  271. package/dist/interchange/index.d.ts +7 -8
  272. package/dist/interchange/index.js +23 -14
  273. package/dist/interchange/index.js.map +1 -1
  274. package/dist/local-options-CZ1BnIoF.d.cts +29 -0
  275. package/dist/local-options-CZ1BnIoF.d.ts +29 -0
  276. package/dist/{manager-D00_NXvT.d.ts → manager-CASfhmzV.d.ts} +4 -173
  277. package/dist/{manager-nU1vTJLy.d.cts → manager-nCEJiYBb.d.cts} +4 -173
  278. package/dist/{materialize-indexes-zK2J_flP.d.ts → materialize-indexes-D4iei4Kp.d.ts} +1 -1
  279. package/dist/{materialize-indexes-CuR3gAZb.d.cts → materialize-indexes-ExQ6OrAh.d.cts} +1 -1
  280. package/dist/{postgres-IaBA4RgE.d.ts → postgres-Cl1ZAN1G.d.ts} +1 -1
  281. package/dist/{postgres-YrYmPlaU.d.cts → postgres-DMgIKQU-.d.cts} +1 -1
  282. package/dist/postgres-execution-fKW0qRiN.d.cts +14 -0
  283. package/dist/postgres-execution-fKW0qRiN.d.ts +14 -0
  284. package/dist/profiler/index.cjs +9 -8
  285. package/dist/profiler/index.cjs.map +1 -1
  286. package/dist/profiler/index.d.cts +9 -17
  287. package/dist/profiler/index.d.ts +9 -17
  288. package/dist/profiler/index.js +8 -7
  289. package/dist/profiler/index.js.map +1 -1
  290. package/dist/provenance/index.cjs +61 -55
  291. package/dist/provenance/index.cjs.map +1 -1
  292. package/dist/provenance/index.d.cts +7 -8
  293. package/dist/provenance/index.d.ts +7 -8
  294. package/dist/provenance/index.js +34 -28
  295. package/dist/provenance/index.js.map +1 -1
  296. package/dist/schema/index.cjs +46 -37
  297. package/dist/schema/index.cjs.map +1 -1
  298. package/dist/schema/index.d.cts +8 -10
  299. package/dist/schema/index.d.ts +8 -10
  300. package/dist/schema/index.js +22 -13
  301. package/dist/schema/index.js.map +1 -1
  302. package/dist/{sqlite-BUOHPx7p.d.ts → sqlite-BDkW39aa.d.cts} +1 -1
  303. package/dist/{sqlite-Pp8O19WE.d.cts → sqlite-CYfhvESj.d.ts} +1 -1
  304. package/dist/sqlite-execution-DwbE2a9y.d.cts +32 -0
  305. package/dist/sqlite-execution-DwbE2a9y.d.ts +32 -0
  306. package/dist/{store-view-X96Rd00T.d.cts → store-view-BoHqdHjB.d.cts} +394 -1393
  307. package/dist/{store-view-ANL6mTph.d.ts → store-view-Ctq-3OHy.d.ts} +394 -1393
  308. package/dist/temporal-BC_NQV5Y.d.cts +281 -0
  309. package/dist/temporal-DqtOEo_B.d.ts +281 -0
  310. package/dist/{types-r-Zyq2Hz.d.cts → types-COq3-vMC.d.cts} +2 -2
  311. package/dist/{types-wsvuBgPK.d.ts → types-CUevi_D1.d.ts} +2 -2
  312. package/dist/{where-CJOpJj3a.d.ts → where-BdE_cYtx.d.ts} +5 -5
  313. package/dist/{where-K3uBP33l.d.cts → where-C92TXCzT.d.cts} +5 -5
  314. package/package.json +37 -6
  315. package/dist/chunk-27SSDCEP.cjs.map +0 -1
  316. package/dist/chunk-2N6EOBTH.cjs.map +0 -1
  317. package/dist/chunk-3C2RYI6L.cjs.map +0 -1
  318. package/dist/chunk-3DS7Z4T4.cjs.map +0 -1
  319. package/dist/chunk-3GH67G4Z.cjs.map +0 -1
  320. package/dist/chunk-3RWZPJKV.js.map +0 -1
  321. package/dist/chunk-3SLPDKHQ.js.map +0 -1
  322. package/dist/chunk-3XXGYU62.cjs.map +0 -1
  323. package/dist/chunk-44TA22QT.js +0 -1478
  324. package/dist/chunk-44TA22QT.js.map +0 -1
  325. package/dist/chunk-552KNYQJ.js.map +0 -1
  326. package/dist/chunk-5KEQ74YU.cjs.map +0 -1
  327. package/dist/chunk-5KPNWT6X.js.map +0 -1
  328. package/dist/chunk-5PNMDJ7J.js.map +0 -1
  329. package/dist/chunk-6EEO3OVU.cjs.map +0 -1
  330. package/dist/chunk-7YSP4V4R.cjs +0 -69
  331. package/dist/chunk-7YSP4V4R.cjs.map +0 -1
  332. package/dist/chunk-A42GCBGX.cjs.map +0 -1
  333. package/dist/chunk-BVRDGYXQ.cjs.map +0 -1
  334. package/dist/chunk-BYPOGQWK.js.map +0 -1
  335. package/dist/chunk-CUHM5CWJ.cjs +0 -12
  336. package/dist/chunk-CUHM5CWJ.cjs.map +0 -1
  337. package/dist/chunk-DIQ3AV5W.cjs.map +0 -1
  338. package/dist/chunk-EXU3RASM.js.map +0 -1
  339. package/dist/chunk-IP3CGGPA.cjs.map +0 -1
  340. package/dist/chunk-IPSVVTWT.cjs +0 -1540
  341. package/dist/chunk-IPSVVTWT.cjs.map +0 -1
  342. package/dist/chunk-IXGYRP2P.js.map +0 -1
  343. package/dist/chunk-J4IUSYFF.js.map +0 -1
  344. package/dist/chunk-JBNOGRKW.cjs.map +0 -1
  345. package/dist/chunk-K3Q3LJY3.js.map +0 -1
  346. package/dist/chunk-KQJ54OG5.js.map +0 -1
  347. package/dist/chunk-L7HQ2OSI.js.map +0 -1
  348. package/dist/chunk-M6VES7V6.js +0 -239
  349. package/dist/chunk-M6VES7V6.js.map +0 -1
  350. package/dist/chunk-NBP2WTJW.cjs.map +0 -1
  351. package/dist/chunk-NUIG3BCV.cjs.map +0 -1
  352. package/dist/chunk-NXQFATMF.cjs.map +0 -1
  353. package/dist/chunk-OHMP6N2J.js +0 -47
  354. package/dist/chunk-OHMP6N2J.js.map +0 -1
  355. package/dist/chunk-QERAIDRJ.js.map +0 -1
  356. package/dist/chunk-QSXTWU4U.cjs +0 -12
  357. package/dist/chunk-RCVLFTCT.js.map +0 -1
  358. package/dist/chunk-TGOMW4MB.cjs.map +0 -1
  359. package/dist/chunk-TKT2XHED.js.map +0 -1
  360. package/dist/chunk-UGZUAYAR.js.map +0 -1
  361. package/dist/chunk-UXLSNRYL.js.map +0 -1
  362. package/dist/chunk-UYQMBBWJ.js.map +0 -1
  363. package/dist/chunk-VKGKDOKR.js.map +0 -1
  364. package/dist/chunk-VL2V6PEN.cjs +0 -261
  365. package/dist/chunk-VL2V6PEN.cjs.map +0 -1
  366. package/dist/chunk-WOJMKB3N.cjs.map +0 -1
  367. package/dist/chunk-WWFHO375.cjs.map +0 -1
  368. package/dist/chunk-XGPUQ56G.js.map +0 -1
  369. package/dist/chunk-XGU7DZDA.cjs +0 -1095
  370. package/dist/chunk-XGU7DZDA.cjs.map +0 -1
  371. package/dist/chunk-XPCZADMT.cjs.map +0 -1
  372. package/dist/chunk-XWV4JT34.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/backend/types.ts","../src/query/sql-intent.ts","../src/query/compiler/temporal.ts","../src/query/subquery-utils.ts","../src/query/predicates.ts","../src/query/compiler/predicates.ts","../src/query/compiler/predicate-utils.ts","../src/utils/array.ts","../src/utils/presence.ts"],"names":["nowIso","sql","ConfigurationError","expr","UnsupportedPredicateError","resolveFieldTypeInfoAtJsonPointer","jsonPointer","joinJsonPointers","normalizeJsonPointer","qualifier","normalizeValueType","literal","LIKE_ESCAPE_CHARACTER","pattern","likeEscapeClause","left","opSql","arrayField","predicate","CompilerInvariantError"],"mappings":";;;;;;;;;;AA+NO,SAAS,oCACd,YAAA,EACqB;AACrB,EAAA,IACE,YAAA,CAAa,cAAA,EAAgB,SAAA,KAAc,IAAA,IAC1C,YAAA,CAAa,gBACZ,YAAA,CAAa,eAAA,IACb,YAAA,CAAa,SAAA,KAAc,KAAA,EAC7B;AACA,IAAA,OAAO,YAAA;AAAA,EACT;AACA,EAAA,OAAO;AAAA,IACL,GAAG,YAAA;AAAA,IACH,gBAAgB,EAAE,GAAG,YAAA,CAAa,cAAA,EAAgB,WAAW,KAAA;AAAM,GACrE;AACF;AAiBO,SAAS,iBAAiB,KAAA,EAA0C;AACzE,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,GACnB,IAAA,CAAK,KAAA,CAAM,KAAK,CAAA,GACjB,KAAA;AACN;AAGO,SAAS,mBAAmB,KAAA,EAAyB;AAC1D,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,GAAW,KAAA,GAAQ,IAA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,MAAA,CAAO,aAAA,CAAc,IAAI,CAAA,IAAK,OAAO,CAAA,EAAG;AAC3C,IAAA,MAAM,IAAI,UAAA,CAAW,CAAA,4CAAA,EAA+C,IAAI,CAAA,CAAE,CAAA;AAAA,EAC5E;AACA,EAAA,IAAI,KAAA,CAAM,MAAA,KAAW,CAAA,EAAG,OAAO,EAAC;AAChC,EAAA,IAAI,KAAA,CAAM,MAAA,IAAU,IAAA,EAAM,OAAO,CAAC,KAAK,CAAA;AACvC,EAAA,MAAM,SAAgB,EAAC;AACvB,EAAA,KAAA,IAAS,QAAQ,CAAA,EAAG,KAAA,GAAQ,KAAA,CAAM,MAAA,EAAQ,SAAS,IAAA,EAAM;AACvD,IAAA,MAAA,CAAO,KAAK,KAAA,CAAM,KAAA,CAAM,KAAA,EAAO,KAAA,GAAQ,IAAI,CAAC,CAAA;AAAA,EAC9C;AACA,EAAA,OAAO,MAAA;AACT;AAMO,SAAS,OAAA,CACd,OACA,MAAA,EACa;AACb,EAAA,MAAM,MAAA,uBAAa,GAAA,EAAY;AAC/B,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,MAAM,GAAA,GAAM,OAAO,IAAI,CAAA;AACvB,IAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,GAAA,CAAI,GAAG,KAAK,EAAC;AAClC,IAAA,KAAA,CAAM,KAAK,IAAI,CAAA;AACf,IAAA,MAAA,CAAO,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,EACvB;AACA,EAAA,OAAO,MAAA;AACT;;;ACzCO,SAAS,UAAU,KAAA,EAAyB;AACjD,EAAA,OAAO,KAAA,KAAU,QAAQ,KAAA,KAAU,MAAA;AACrC","file":"chunk-IPSVVTWT.cjs","sourcesContent":["/**\n * Backend interface types for TypeGraph storage.\n *\n * The backend abstracts database operations, allowing different\n * SQL implementations (SQLite, PostgreSQL) behind a common interface.\n */\nimport { type SQL } from \"drizzle-orm\";\n\nimport {\n type IndexEntity,\n type KindEntity,\n type TemporalMode,\n} from \"../core/types\";\nimport { type SqlTableNames } from \"../query/compiler/schema\";\nimport { type FulltextStrategy } from \"../query/dialect/fulltext-strategy\";\nimport {\n type VectorSlot,\n type VectorStrategy,\n} from \"../query/dialect/vector-strategy\";\nimport {\n type CompiledRowsSql,\n type CompiledStatementSql,\n type CompiledTemporaryStatementSql,\n} from \"../query/sql-intent\";\nimport { type SerializedSchema } from \"../schema/types\";\nimport {\n type AnyPgDatabase,\n type AnySqliteDatabase,\n} from \"./drizzle/execution\";\n\n// ============================================================\n// Vector Search Types\n// ============================================================\n\n/**\n * Supported vector similarity metrics.\n */\nexport type VectorMetric = \"cosine\" | \"l2\" | \"inner_product\";\n\n/**\n * Supported vector index types.\n */\nexport type VectorIndexType = \"hnsw\" | \"ivfflat\" | \"none\";\n\n/**\n * The mechanism a strategy uses to combine a row filter with an *approximate*\n * (ANN) vector search.\n *\n * Every approximate search TypeGraph issues carries at least one filter: the\n * liveness predicate that excludes soft-deleted and out-of-validity rows. Add\n * a `.where(...)` predicate and it narrows further. Engines differ in where\n * they apply it relative to the index traversal:\n *\n * - `\"filter-pushdown\"` — the filter constrains the ANN candidate set itself.\n * sqlite-vec's `vec0` KNN accepts primary-key `IN (SELECT …)` pushdown.\n * - `\"iterative-scan\"` — the engine re-enters the index, gathering more\n * candidates until `LIMIT` rows survive the filter *or* it hits its own scan\n * bound. pgvector >= 0.8 (`hnsw.iterative_scan` / `ivfflat.iterative_scan`,\n * applied automatically by the backend).\n * - `\"post-filter\"` — the engine retrieves a fixed multiple of the page from\n * the ANN index and applies the filter afterwards. libSQL's DiskANN\n * `vector_top_k` is a table function with no filter pushdown, so this is the\n * only shape available to it.\n *\n * This names what the strategy *asks the engine to do*. Whether the engine can\n * honor it — and whether honoring it is enough to fill a page — is\n * {@link FilteredApproximateSearch.guaranteesFullPage}.\n */\nexport type FilteredApproximateSearchMode =\n \"filter-pushdown\" | \"iterative-scan\" | \"post-filter\";\n\n/**\n * How a filtered approximate (ANN) vector search behaves, and whether it can\n * silently return fewer rows than `limit` while more matches exist.\n *\n * Read `guaranteesFullPage` — not `mode` — to decide whether a short page is\n * possible. Only `\"filter-pushdown\"` guarantees a full page:\n *\n * - **sqlite-vec** pushes the filter into the KNN. Exact.\n * - **pgvector** re-enters the index, but the iterative scan stops at\n * `hnsw.max_scan_tuples` / `ivfflat.max_probes`, and on **pgvector < 0.8**\n * there is no iterative scan at all — the backend detects that at runtime,\n * warns once, and the search stays `ef_search`-bounded, behaving like\n * `\"post-filter\"`. Neither case is visible in a statically-declared `mode`,\n * which is exactly why the guarantee is a separate field.\n * - **libSQL** over-fetches a fixed multiple of the page and filters\n * afterwards, so it under-fills once more than that headroom is filtered out.\n *\n * A store with heavy tombstone drift — routine in a temporal store — is what\n * turns a short page from a theoretical caveat into an observed one. Exact\n * (`approximate: false`) searches are unaffected on every engine: they scan, so\n * the filter reaches every row.\n */\nexport type FilteredApproximateSearch = Readonly<{\n mode: FilteredApproximateSearchMode;\n /**\n * `true` only when a filtered approximate search is guaranteed to return\n * `limit` rows whenever `limit` matching rows exist — no engine-side scan\n * bound, no version dependence, no over-fetch headroom to exhaust.\n */\n guaranteesFullPage: boolean;\n}>;\n\n/**\n * Vector search capabilities.\n */\nexport type VectorCapabilities = Readonly<{\n /** Whether the backend supports vector operations */\n supported: boolean;\n /** Supported similarity metrics */\n metrics: readonly VectorMetric[];\n /** Supported index types */\n indexTypes: readonly VectorIndexType[];\n /** Maximum dimensions supported */\n maxDimensions: number;\n /**\n * How a filtered approximate search bounds recall — and whether it can\n * silently return a short page. See {@link FilteredApproximateSearch}.\n *\n * Required, so a new vector strategy cannot omit the declaration and inherit\n * an engine promise it does not keep.\n */\n filteredApproximateSearch: FilteredApproximateSearch;\n}>;\n\n// ============================================================\n// Fulltext Search Types\n// ============================================================\n\n/**\n * Query modes for fulltext search.\n *\n * - \"websearch\": Google-style syntax (quoted phrases, +required, -excluded).\n * Postgres: `websearch_to_tsquery`. SQLite: translated to FTS5 MATCH.\n * - \"phrase\": treats the whole query as a phrase.\n * Postgres: `phraseto_tsquery`. SQLite: FTS5 `\"...\"` phrase.\n * - \"plain\": splits on whitespace and ANDs terms.\n * Postgres: `plainto_tsquery`. SQLite: default FTS5 AND.\n * - \"raw\": dialect-native syntax passed through unchanged.\n */\nexport type FulltextQueryMode = \"websearch\" | \"phrase\" | \"plain\" | \"raw\";\n\n/**\n * Fulltext search capabilities declared by a backend.\n */\nexport type FulltextCapabilities = Readonly<{\n /** Whether the backend supports fulltext operations */\n supported: boolean;\n /**\n * Language / tokenizer names understood by this backend.\n * Postgres: installed regconfigs (english, simple, ...).\n * SQLite FTS5: tokenizer names (unicode61, porter, trigram).\n */\n languages: readonly string[];\n /** Whether phrase queries are supported. */\n phraseQueries: boolean;\n /** Whether prefix (`foo*`) queries are supported. */\n prefixQueries: boolean;\n /** Whether highlighting / snippets are supported. */\n highlighting: boolean;\n}>;\n\n/**\n * Whole-graph analytics capabilities declared by a backend.\n *\n * `supported` means the backend can pin one transactional connection while\n * an algorithm creates, updates, and drops session-local temporary state.\n * `mathFunctions` records whether transcendental SQL functions needed by\n * deferred algorithms such as MCL/spectral are available; exact WCC does not\n * require them.\n */\nexport type GraphAnalyticsCapabilities = Readonly<{\n supported: boolean;\n mathFunctions: boolean;\n}>;\n\n// ============================================================\n// SQL Dialect & Capabilities\n// ============================================================\n\nimport { type SqlDialect } from \"../query/dialect/types\";\n\nexport type { SqlDialect } from \"../query/dialect/types\";\n\n/**\n * Backend capabilities that vary by dialect.\n */\nexport type BackendCapabilities = Readonly<{\n /** Whether the backend supports atomic transactions (D1 does not) */\n transactions: boolean;\n /** Whether the backend supports SQL window functions such as ROW_NUMBER() */\n windowFunctions: boolean;\n /**\n * Whether the backend's `execute()` supports `UPDATE … RETURNING`. Absent or\n * `true` means supported (every engine TypeGraph ships — SQLite ≥ 3.35,\n * PostgreSQL ≥ 8.2 — supports it). A custom backend whose engine cannot run\n * `RETURNING` must set this to `false` so recorded-time history capture\n * (`history: true`), which relies on `UPDATE … RETURNING` on its hot path,\n * is refused up front instead of failing mid-flush.\n */\n returning?: boolean;\n /**\n * Maximum number of bound parameters the engine accepts in one statement.\n * SQLite defaults to 999 (raisable at compile time via\n * `SQLITE_MAX_VARIABLE_NUMBER`), while hosted SQLite runtimes may impose a\n * lower platform ceiling; PostgreSQL's wire protocol caps it at 65535.\n * Recorded-time capture and recorded point reads size their multi-row\n * statements to this ceiling — the same budget the backend's own batched\n * inserts use — instead of a conservative dialect-blind constant. Custom\n * runtimes can override a detected or probed limit here, but hosted platform\n * hard ceilings may only be lowered. Absent means the recorded-time fallback\n * budget applies.\n */\n maxBindParameters?: number;\n /** Vector search capabilities (undefined if not configured) */\n vector?: VectorCapabilities | undefined;\n /** Fulltext search capabilities (undefined if not configured) */\n fulltext?: FulltextCapabilities | undefined;\n /** Whole-graph analytics capabilities (undefined when unavailable). */\n graphAnalytics?: GraphAnalyticsCapabilities | undefined;\n}>;\n\n/** Keeps session-scoped analytics honest when a required SQL feature is absent. */\nexport function normalizeGraphAnalyticsCapabilities(\n capabilities: BackendCapabilities,\n): BackendCapabilities {\n if (\n capabilities.graphAnalytics?.supported !== true ||\n (capabilities.transactions &&\n capabilities.windowFunctions &&\n capabilities.returning !== false)\n ) {\n return capabilities;\n }\n return {\n ...capabilities,\n graphAnalytics: { ...capabilities.graphAnalytics, supported: false },\n };\n}\n\n// ============================================================\n// Row Types (Database Records)\n// ============================================================\n\n/**\n * A node/edge row's `props` column as the driver returned it: SQLite always\n * yields the JSON text; PostgreSQL drivers yield the jsonb value already\n * parsed. Keeping the driver's shape avoids a per-row\n * parse→stringify→re-parse round trip on the PostgreSQL read path —\n * consumers normalize through {@link rowPropsToObject} /\n * {@link rowPropsToJsonText} at the point of use.\n */\nexport type RowProps = string | Readonly<Record<string, unknown>>;\n\n/** The row's props as an object, parsing only when the driver gave text. */\nexport function rowPropsToObject(props: RowProps): Record<string, unknown> {\n return typeof props === \"string\" ?\n (JSON.parse(props) as Record<string, unknown>)\n : props;\n}\n\n/** The row's props as JSON text, serializing only when the driver gave an object. */\nexport function rowPropsToJsonText(props: RowProps): string {\n return typeof props === \"string\" ? props : JSON.stringify(props);\n}\n\n/**\n * A row from the typegraph_nodes table.\n */\nexport type NodeRow = Readonly<{\n graph_id: string;\n kind: string;\n id: string;\n props: RowProps;\n version: number;\n valid_from: string | undefined;\n valid_to: string | undefined;\n created_at: string;\n updated_at: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A {@link NodeRow} proven live (not soft-deleted). Functions that must only\n * ever touch live rows — the live-row update pipeline, soft delete — take\n * this type so a caller holding a possibly-tombstoned row is forced through\n * {@link isLiveNodeRow} first, instead of silently running live-row side\n * effects (uniqueness reservations, embedding/fulltext sync) for a row that\n * stays invisible.\n */\nexport type LiveNodeRow = NodeRow & Readonly<{ deleted_at: undefined }>;\n\n/**\n * A {@link NodeRow} proven soft-deleted. A resurrect targets exactly this\n * shape; see {@link isTombstonedNodeRow}.\n */\nexport type TombstonedNodeRow = NodeRow & Readonly<{ deleted_at: string }>;\n\nexport function isLiveNodeRow(row: NodeRow): row is LiveNodeRow {\n return row.deleted_at === undefined;\n}\n\nexport function isTombstonedNodeRow(row: NodeRow): row is TombstonedNodeRow {\n return row.deleted_at !== undefined;\n}\n\n/**\n * The read-only slice of a backend. Give this type to code that is\n * semantically a read — probes, gates, support-graph loads — so a read path\n * structurally CANNOT open a write transaction, mutate rows, or execute raw\n * SQL: those members do not exist on the type. Extend the pick as read paths\n * need more of the read surface.\n */\nexport type GraphReadBackend = Pick<\n GraphBackend,\n | \"dialect\"\n | \"getNode\"\n | \"getEdge\"\n | \"findNodesByKind\"\n | \"findEdgesByKind\"\n | \"findEdgesConnectedTo\"\n>;\n\n/**\n * A row from the typegraph_edges table.\n */\nexport type EdgeRow = Readonly<{\n graph_id: string;\n id: string;\n kind: string;\n from_kind: string;\n from_id: string;\n to_kind: string;\n to_id: string;\n props: RowProps;\n valid_from: string | undefined;\n valid_to: string | undefined;\n created_at: string;\n updated_at: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_node_uniques table.\n */\nexport type UniqueRow = Readonly<{\n graph_id: string;\n node_kind: string;\n constraint_name: string;\n key: string;\n node_id: string;\n concrete_kind: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_schema_versions table.\n */\nexport type SchemaVersionRow = Readonly<{\n graph_id: string;\n version: number;\n schema_hash: string;\n schema_doc: string; // JSON string\n created_at: string;\n is_active: boolean;\n}>;\n\n// ============================================================\n// Insert Parameters\n// ============================================================\n\n/**\n * Parameters for inserting a node.\n */\nexport type InsertNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n /**\n * Omitted (`undefined`): defaults to the insert's creation timestamp.\n * `null`: preserves an explicit open-left validity window (no lower\n * bound) — used by interchange import to round-trip a row that was\n * already NULL, instead of re-stamping it to the import's own timestamp.\n */\n validFrom?: string | null;\n validTo?: string;\n}>;\n\n/**\n * Parameters for updating a node.\n */\nexport type UpdateNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validTo?: string;\n incrementVersion?: boolean;\n /** If true, clears deleted_at (un-deletes the node). Used by upsert. */\n clearDeleted?: boolean;\n}>;\n\n/**\n * Parameters for deleting a node (soft delete).\n */\nexport type DeleteNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n}>;\n\n/**\n * Parameters for inserting an edge.\n */\nexport type InsertEdgeParams = Readonly<{\n graphId: string;\n id: string;\n kind: string;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n props: Readonly<Record<string, unknown>>;\n /**\n * Omitted (`undefined`): defaults to the insert's creation timestamp.\n * `null`: preserves an explicit open-left validity window (no lower\n * bound) — used by interchange import to round-trip a row that was\n * already NULL, instead of re-stamping it to the import's own timestamp.\n */\n validFrom?: string | null;\n validTo?: string;\n}>;\n\n/**\n * Write-only session exposed inside {@link GraphBackend.trustedImport}.\n *\n * The caller has accepted the trusted-import contract: properties, endpoint\n * references, uniqueness, and cardinality are not validated. Backends may\n * therefore use engine-native ingestion primitives that bypass the normal\n * store write pipeline.\n */\nexport type TrustedImportSession = Readonly<{\n insertNodes: (params: readonly InsertNodeParams[]) => Promise<void>;\n insertEdges: (params: readonly InsertEdgeParams[]) => Promise<void>;\n}>;\n\n/**\n * Parameters for updating an edge.\n */\nexport type UpdateEdgeParams = Readonly<{\n graphId: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validTo?: string;\n clearDeleted?: boolean;\n}>;\n\n/**\n * Parameters for deleting an edge (soft delete).\n */\nexport type DeleteEdgeParams = Readonly<{\n graphId: string;\n id: string;\n}>;\n\n/**\n * Parameters for hard deleting a node (permanent removal).\n */\nexport type HardDeleteNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n}>;\n\n/**\n * Parameters for hard deleting an edge (permanent removal).\n */\nexport type HardDeleteEdgeParams = Readonly<{\n graphId: string;\n id: string;\n}>;\n\n/** Parameters for a batched edge delete (soft or hard). */\nexport type DeleteEdgesBatchParams = Readonly<{\n graphId: string;\n ids: readonly string[];\n}>;\n\n// ============================================================\n// Embedding Parameters\n// ============================================================\n\n/**\n * Parameters for inserting or updating an embedding.\n *\n * `dimensions`, `metric`, and `indexType` together resolve the slot's\n * typed per-`(nodeKind, fieldPath)` storage (the strategy needs the fixed\n * dimension for the column type, and the metric/index type to address the\n * right ANN structure). The store populates them from the schema's\n * `embedding()` declaration via `getEmbeddingDimensions()` /\n * `getEmbeddingIndex()`; the backend constructs a `VectorSlot` from them\n * and stays graph-agnostic.\n */\nexport type UpsertEmbeddingParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n embedding: readonly number[];\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n}>;\n\n/**\n * One row of a batched embedding upsert.\n */\ntype UpsertEmbeddingBatchRow = Readonly<{\n nodeId: string;\n embedding: readonly number[];\n}>;\n\n/**\n * Parameters for a batched embedding upsert. Homogeneous per vector slot:\n * one graph, one node kind, one field, many nodes. Duplicate `nodeId`\n * values within a batch are deduplicated last-write-wins by the backend\n * (a multi-row upsert cannot affect one row twice).\n */\nexport type UpsertEmbeddingBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n rows: readonly UpsertEmbeddingBatchRow[];\n}>;\n\n/**\n * Parameters for deleting an embedding.\n *\n * `dimensions` / `metric` / `indexType` mirror {@link UpsertEmbeddingParams}\n * so the backend can resolve the slot's typed per-`(nodeKind, fieldPath)`\n * storage and idempotently ensure it exists before the DELETE. That\n * matters because a delete can run before any embedding was ever written\n * (e.g. a node hard-deleted having never carried one), and on Postgres a\n * DELETE against a missing relation inside a transaction aborts the whole\n * transaction. The store populates them from the schema's `embedding()`\n * declaration, exactly as for upserts.\n */\nexport type DeleteEmbeddingParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n}>;\n\n/**\n * Parameters for vector similarity search.\n */\nexport type VectorSearchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n queryEmbedding: readonly number[];\n metric: VectorMetric;\n /**\n * Fixed vector dimension `N` for the searched `(nodeKind, fieldPath)`\n * slot. The store populates it from the schema's `embedding()`\n * declaration via `getEmbeddingDimensions()`; the backend uses it to\n * construct the `VectorSlot` whose typed storage the strategy scans.\n */\n dimensions: number;\n /**\n * Index type materialized for this slot. `\"none\"` means brute-force\n * only; otherwise the strategy may route through its ANN structure.\n * The store populates it from `getEmbeddingIndex()`.\n */\n indexType: VectorIndexType;\n limit: number;\n minScore?: number;\n /**\n * Subquery of eligible node ids (single column, exposed as `node_id`).\n * When present, the search statement computes top-k over this candidate\n * set — the store passes its compiled current-read query here so\n * `where` predicates push down into the search SQL. Exact on engines\n * whose search form takes the filter inside retrieval (pgvector,\n * sqlite-vec, tsvector, FTS5); libSQL's DiskANN cannot pre-filter, so\n * it post-filters an over-fetched ANN set and recall against the\n * candidate set is bounded by that headroom. When absent, the backend\n * restricts to CURRENT nodes of the kind — non-tombstoned AND inside\n * their validity window — matching a `current` read.\n */\n candidates?: SQL;\n /**\n * Rows to skip AFTER ranking (pagination). The engine fetches\n * `limit + offset` ranked candidates and discards the first `offset`.\n */\n offset?: number;\n /**\n * HNSW search frontier for this query (pgvector `hnsw.ef_search`).\n * Sizes the dynamic candidate list the index scan maintains: higher\n * trades latency for recall. The floor for the over-fetch to fill its\n * candidate set is `efSearch >= limit`; ~2–4× is the high-recall\n * target. Applied transaction-locally (`SET LOCAL`) on the Postgres\n * HNSW path only. No-op on backends without an HNSW frontier knob\n * (sqlite-vec) and ignored — with a one-time warning — on Postgres\n * backends without transactions (e.g. `drizzle-orm/neon-http`).\n */\n efSearch?: number;\n}>;\n\n/**\n * Result from a vector similarity search.\n */\nexport type VectorSearchResult = Readonly<{\n nodeId: string;\n /**\n * Cosine metric returns similarity score (higher is better).\n * L2 and inner_product return raw distance (lower is better).\n */\n score: number;\n}>;\n\n/**\n * Parameters for a single-statement hybrid (vector + fulltext, RRF-fused)\n * search. The store facade resolves every default before calling — the\n * per-source candidate depths (`k`), the fusion constants, and the shared\n * `candidates` subquery — so the backend composes SQL without policy.\n */\nexport type HybridSearchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n vector: Readonly<{\n fieldPath: string;\n queryEmbedding: readonly number[];\n metric: VectorMetric;\n dimensions: number;\n indexType: VectorIndexType;\n /** Candidate depth of the vector source (rows entering fusion). */\n k: number;\n minScore?: number;\n efSearch?: number;\n }>;\n fulltext: Readonly<{\n query: string;\n mode?: FulltextQueryMode;\n language?: string;\n /** Candidate depth of the fulltext source (rows entering fusion). */\n k: number;\n minScore?: number;\n includeSnippets?: boolean;\n }>;\n fusion: Readonly<{\n /** RRF rank constant (`1 / (k + rank)`). */\n k: number;\n vectorWeight: number;\n fulltextWeight: number;\n }>;\n /** Fused rows to return after `offset`. */\n limit: number;\n /** Fused rows to skip (rank-relative pagination). */\n offset?: number;\n /** See {@link VectorSearchParams.candidates}; applies to both sources. */\n candidates?: SQL;\n}>;\n\n/**\n * One fused hybrid hit, hydrated in the same statement: the node row\n * rides along so the caller needs no follow-up id fetch.\n */\nexport type HybridSearchRow = Readonly<{\n node: NodeRow;\n fusedScore: number;\n vectorRank?: number;\n vectorScore?: number;\n fulltextRank?: number;\n fulltextScore?: number;\n snippet?: string;\n}>;\n\n/**\n * Parameters for creating a vector index.\n */\nexport type CreateVectorIndexParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n /** Index-specific parameters */\n indexParams?: Readonly<{\n /** HNSW: max connections per layer */\n m?: number;\n /** HNSW: construction search depth */\n efConstruction?: number;\n /** IVFFlat: number of lists */\n lists?: number;\n }>;\n /**\n * Build the index without taking an `AccessExclusiveLock` on live\n * tables (Postgres `CREATE INDEX CONCURRENTLY`). Mirrors the\n * `concurrent` flag the relational DDL path uses inside\n * `materializeIndexes()`. Cannot be set inside a transaction —\n * callers (`materializeIndexes()`) run at top level. Backends that\n * don't have a CONCURRENTLY equivalent (SQLite) ignore this flag.\n */\n concurrent?: boolean;\n}>;\n\n/**\n * Parameters for dropping a vector index.\n */\nexport type DropVectorIndexParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n}>;\n\n// ============================================================\n// Fulltext Parameters\n// ============================================================\n\n/**\n * Parameters for inserting or updating a fulltext entry.\n *\n * One row per node. Callers concatenate the searchable fields into\n * `content` so a single MATCH query can find terms spread across fields.\n *\n * Note: `createFulltextIndex` / `dropFulltextIndex` were removed as\n * dead code in #PR_E. The fulltext table's canonical index (Postgres\n * GIN on `tsv`, SQLite FTS5 virtual table) is created with the table\n * itself by `bootstrapTables` per the active `FulltextStrategy`;\n * per-kind fulltext indexes are an \"advanced strategy\" surface that\n * doesn't fit the relational-style declaration model and is reserved\n * for future work.\n */\nexport type UpsertFulltextParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n content: string;\n language: string;\n}>;\n\n/**\n * Parameters for deleting a single fulltext entry.\n */\nexport type DeleteFulltextParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * A single row in a fulltext batch upsert.\n */\nexport type FulltextBatchRow = Readonly<{\n nodeId: string;\n content: string;\n language: string;\n}>;\n\n/**\n * Parameters for a batched fulltext upsert.\n *\n * Homogeneous: one graph, one node kind, many nodes. Duplicate `nodeId`\n * values within a single batch are deduplicated last-write-wins by the\n * builders before SQL generation — Postgres `ON CONFLICT` errors on\n * repeated conflict keys in one statement, and SQLite `DELETE + INSERT`\n * would create duplicate virtual-table rows otherwise.\n */\nexport type UpsertFulltextBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n rows: readonly FulltextBatchRow[];\n}>;\n\n/**\n * Parameters for a batched fulltext delete.\n */\nexport type DeleteFulltextBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeIds: readonly string[];\n}>;\n\n/**\n * Parameters for fulltext search.\n */\nexport type FulltextSearchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n /** The user-supplied query string. */\n query: string;\n /** How to parse `query`. Default: \"websearch\". */\n mode?: FulltextQueryMode;\n /**\n * Language for query parsing. The store facade resolves the kind's\n * declared language and passes it here, so the tsquery is a plan-time\n * constant (GIN-servable); when absent the backend falls back to the\n * per-row language column.\n * Postgres: passed as the regconfig to `to_tsquery` / `websearch_to_tsquery`.\n * SQLite: informational only (FTS5 tokenizer is fixed at table-create time).\n */\n language?: string;\n /** Max rows to return. */\n limit: number;\n /** Minimum rank to include (backend-dependent units). */\n minScore?: number;\n /** Whether to return a highlighted snippet per match. */\n includeSnippets?: boolean;\n /**\n * Subquery of eligible node ids (single column). When present, the\n * search statement computes top-k over this candidate set — the store\n * passes its compiled current-read query here so `where` predicates,\n * subclass expansion, and valid-time currency all push down into the\n * search SQL. Exact on engines whose search form takes the filter\n * inside retrieval (pgvector, sqlite-vec, tsvector, FTS5); libSQL's\n * DiskANN cannot pre-filter, so it post-filters an over-fetched ANN\n * set and recall against the candidate set is bounded by that\n * headroom. When absent, the backend restricts to CURRENT nodes of\n * the kind — non-tombstoned AND inside their validity window —\n * matching a `current` read.\n */\n candidates?: SQL;\n /**\n * Rows to skip AFTER ranking (pagination). The engine fetches\n * `limit + offset` ranked candidates and discards the first `offset`.\n */\n offset?: number;\n}>;\n\n/**\n * Result from a fulltext search.\n *\n * Score semantics differ by backend; prefer `rank` (1-based) when fusing\n * with another source via RRF.\n */\nexport type FulltextSearchResult = Readonly<{\n nodeId: string;\n /**\n * Backend-native relevance score.\n * Postgres: `ts_rank_cd` (higher is better).\n * SQLite FTS5: negated `bm25()` (higher is better; FTS5 returns lower-is-better).\n */\n score: number;\n /** 1-based rank within the result set, suitable for RRF. */\n rank: number;\n /** Highlighted snippet of the content (if `includeSnippets` was set). */\n snippet?: string;\n}>;\n\n/**\n * Parameters for creating a fulltext index.\n *\n * The canonical index (Postgres GIN on `tsv`, SQLite FTS5 virtual table)\n * is created when the fulltext table itself is created. This is reserved\n * for advanced per-kind specializations.\n */\n\n// ============================================================\n// Index Materialization Status\n// ============================================================\n\n/**\n * Per-deployment record for a single declared index.\n *\n * Identified by `indexName` because SQL index names are physical,\n * database-global identifiers — `graphId` is provenance, not identity.\n * `materializedAt` is null until the first successful CREATE INDEX\n * completes; `lastAttemptedAt` is always set, even on failure.\n */\n/**\n * Parameters for atomically claiming an index build (see\n * `claimIndexMaterialization`). The declaration fields ride along so a\n * fresh claim row is honest while the build is in flight.\n */\nexport type ClaimIndexMaterializationParams = Readonly<{\n indexName: string;\n graphId: string;\n entity: IndexEntity;\n kind: string;\n signature: string;\n schemaVersion: number;\n /** Opaque claim identity; release is token-guarded. */\n token: string;\n /** A claim older than this is stale and may be taken over. */\n leaseMs: number;\n}>;\n\n/** Parameters for releasing a build claim (token-guarded). */\nexport type ReleaseIndexMaterializationClaimParams = Readonly<{\n indexName: string;\n token: string;\n}>;\n\nexport type IndexMaterializationRow = Readonly<{\n indexName: string;\n graphId: string;\n entity: IndexEntity;\n kind: string;\n signature: string;\n schemaVersion: number;\n materializedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Parameters for upserting a materialization attempt.\n *\n * On success: pass `materializedAt` (ISO timestamp) and undefined `error`.\n * On failure: pass undefined `materializedAt` (preserve any existing\n * timestamp from a prior success) and the error message.\n */\nexport type RecordIndexMaterializationParams = Readonly<{\n indexName: string;\n graphId: string;\n entity: IndexEntity;\n kind: string;\n signature: string;\n schemaVersion: number;\n attemptedAt: string;\n /** ISO timestamp on success; undefined on failure (preserves existing). */\n materializedAt: string | undefined;\n /** Error message on failure; undefined on success (clears existing). */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Contribution Materializations (#135 — durable strategy-owned\n// storage marker, sibling of index materializations)\n// ============================================================\n\n/**\n * Durable identity of a strategy-owned table contribution (#129),\n * scoped to a graph. This is the primary key of\n * `typegraph_contribution_materializations`.\n *\n * `logicalName` is the stable slot (\"fulltext\"); `owner` is the\n * producing strategy (\"tsvector\" / \"fts5\"); `tableName` is the resolved\n * physical name (custom per-deployment names must be distinguishable).\n * `graphId` is part of identity here — unlike the index status table\n * where the physical index name is database-global, two graphs can each\n * own a logically-identical fulltext contribution.\n */\nexport type ContributionMaterializationIdentity = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n}>;\n\n/**\n * Per-deployment record that a strategy-owned contribution has been\n * durably materialized against this database.\n *\n * `signature` is intentionally NOT part of the identity: a row with the\n * same identity but a different signature means \"materialized artifact\n * is stale/drifted\" — a loud error on the hot path, never a silent\n * re-materialize. `materializedAt` is undefined until the first\n * successful materialization; `lastAttemptedAt` is always set.\n */\nexport type ContributionMaterializationRow = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n signature: string;\n materializedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Parameters for upserting a contribution-materialization attempt.\n * Same success/failure contract as\n * {@link RecordIndexMaterializationParams}: on failure pass undefined\n * `materializedAt` so a prior successful timestamp is preserved via\n * COALESCE, and the error message.\n */\nexport type RecordContributionMaterializationParams = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n signature: string;\n attemptedAt: string;\n /** ISO timestamp on success; undefined on failure (preserves existing). */\n materializedAt: string | undefined;\n /** Error message on failure; undefined on success (clears existing). */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Kind Removals (data-cleanup status)\n// ============================================================\n\n/**\n * One row of the per-deployment `typegraph_kind_removals` table:\n * a graph-extension kind that has been removed from the schema and whose\n * data may or may not have been cleaned up yet.\n */\nexport type KindRemovalRow = Readonly<{\n graphId: string;\n kindName: string;\n entity: KindEntity;\n schemaVersion: number;\n /** ISO timestamp when the data-cleanup pass succeeded; undefined while pending. */\n removedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Upsert payload for a kind-removal status row. On removal-commit:\n * pass `removedAt: undefined` (the pending state). On successful\n * data-cleanup: pass `removedAt` set and `error: undefined`. On\n * cleanup failure: pass `removedAt: undefined` (preserves any prior\n * timestamp from a partial success on a different replica) and the\n * error message.\n */\nexport type RecordKindRemovalParams = Readonly<{\n graphId: string;\n kindName: string;\n entity: KindEntity;\n schemaVersion: number;\n attemptedAt: string;\n /** ISO timestamp on success; undefined while pending or on failure. */\n removedAt: string | undefined;\n /** Error message on failure; undefined on success or while pending. */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Query Types\n// ============================================================\n\n/** @internal Capability token for connection-local temporary writes. */\nexport const INTERNAL_TEMPORARY_WRITES = Symbol(\n \"typegraph.internalTemporaryWrites\",\n);\n\n/**\n * Transaction options.\n */\nexport type TransactionOptions = Readonly<{\n /** Transaction isolation level (if supported) */\n isolationLevel?:\n \"read_uncommitted\" | \"read_committed\" | \"repeatable_read\" | \"serializable\";\n /**\n * Transaction access mode (if supported). `read_only` is intended for\n * multi-statement reads that need one snapshot and must not perform writes.\n */\n accessMode?: \"read_only\" | \"read_write\";\n /**\n * @internal Permit writes only to connection-local temporary state. The\n * iterative-operation primitive uses this when an engine rejects temporary\n * DDL in a read-only transaction.\n */\n temporaryWrites?: typeof INTERNAL_TEMPORARY_WRITES;\n}>;\n\n/**\n * A caller-owned, already-open Drizzle transaction handle that a\n * TypeGraph store can adopt so both layers commit/rollback together.\n *\n * The literal client the caller's transaction runs on — a `PgDatabase`\n * transaction (node-postgres / `neon-serverless` Pool) or a\n * `BaseSQLiteDatabase` connection. Async drivers obtain it from\n * `db.transaction(async (tx) => …)`; synchronous `better-sqlite3` (whose\n * driver rejects an `async` transaction callback) passes the connection\n * itself under an explicit `BEGIN`/`COMMIT`/`ROLLBACK`. Passing it to\n * {@link GraphBackend.adoptTransaction} threads that *literal* client\n * through TypeGraph's SQL, so graph writes and the caller's own\n * relational writes share one Postgres/SQLite transaction (#134).\n */\nexport type AdoptedTransaction = AnyPgDatabase | AnySqliteDatabase;\n\n// ============================================================\n// Backend Interface\n// ============================================================\n\n/**\n * The GraphBackend interface abstracts database operations.\n *\n * Implementations should provide:\n * - SQLite backend via better-sqlite3 or libsql\n * - PostgreSQL backend via pg or postgres\n */\nexport type GraphBackend = Readonly<{\n /** The SQL dialect */\n dialect: SqlDialect;\n /** Backend capabilities */\n capabilities: BackendCapabilities;\n /** Table names used by this backend (for query schema auto-derivation) */\n tableNames?: SqlTableNames | undefined;\n /**\n * Optional fulltext strategy override. When present, both the compiler\n * (for `$fulltext.matches()` in query builder) and backend-direct\n * search paths use this instead of the dialect's default strategy —\n * allowing a Postgres backend to ship pg_trgm, ParadeDB, pgroonga etc.\n * When absent, the dialect's default strategy is used.\n */\n fulltextStrategy?: FulltextStrategy | undefined;\n /**\n * Optional vector strategy this backend is wired with. The query\n * compiler reads it (via `compileQuery` options) to emit per-`(kind,\n * field)` relevance scans for `field.similarTo(...)` predicates, and\n * the index-materialization / removal paths read its deterministic\n * `tableName(...)` to address the right physical per-field storage.\n * `undefined` when the backend has no vector support (e.g. a generic\n * SQLite backend without sqlite-vec).\n */\n vectorStrategy?: VectorStrategy | undefined;\n\n // === Node Operations ===\n insertNode: (params: InsertNodeParams) => Promise<NodeRow>;\n insertNodeNoReturn?: (params: InsertNodeParams) => Promise<void>;\n insertNodesBatch?: (params: readonly InsertNodeParams[]) => Promise<void>;\n insertNodesBatchReturning?: (\n params: readonly InsertNodeParams[],\n ) => Promise<readonly NodeRow[]>;\n updateNode: (params: UpdateNodeParams) => Promise<NodeRow>;\n deleteNode: (params: DeleteNodeParams) => Promise<void>;\n hardDeleteNode: (params: HardDeleteNodeParams) => Promise<void>;\n getNode: (\n graphId: string,\n kind: string,\n id: string,\n ) => Promise<NodeRow | undefined>;\n getNodes?: (\n graphId: string,\n kind: string,\n ids: readonly string[],\n ) => Promise<readonly NodeRow[]>;\n\n // === Edge Operations ===\n insertEdge: (params: InsertEdgeParams) => Promise<EdgeRow>;\n insertEdgeNoReturn?: (params: InsertEdgeParams) => Promise<void>;\n insertEdgesBatch?: (params: readonly InsertEdgeParams[]) => Promise<void>;\n insertEdgesBatchReturning?: (\n params: readonly InsertEdgeParams[],\n ) => Promise<readonly EdgeRow[]>;\n updateEdge: (params: UpdateEdgeParams) => Promise<EdgeRow>;\n deleteEdge: (params: DeleteEdgeParams) => Promise<void>;\n hardDeleteEdge: (params: HardDeleteEdgeParams) => Promise<void>;\n /**\n * Batched {@link deleteEdge}: one soft-delete statement per bind-budget\n * chunk instead of one per edge. Optional — cascade deletes fall back to\n * the per-edge form when unset. Same per-row semantics (idempotent on\n * already-tombstoned rows).\n */\n deleteEdgesBatch?: (params: DeleteEdgesBatchParams) => Promise<void>;\n /** Batched {@link hardDeleteEdge}; see {@link deleteEdgesBatch}. */\n hardDeleteEdgesBatch?: (params: DeleteEdgesBatchParams) => Promise<void>;\n getEdge: (graphId: string, id: string) => Promise<EdgeRow | undefined>;\n getEdges?: (\n graphId: string,\n ids: readonly string[],\n ) => Promise<readonly EdgeRow[]>;\n\n // === Edge Cardinality Operations ===\n countEdgesFrom: (params: CountEdgesFromParams) => Promise<number>;\n edgeExistsBetween: (params: EdgeExistsBetweenParams) => Promise<boolean>;\n\n // === Edge Query Operations ===\n findEdgesConnectedTo: (\n params: FindEdgesConnectedToParams,\n ) => Promise<readonly EdgeRow[]>;\n\n // === Collection Query Operations ===\n findNodesByKind: (\n params: FindNodesByKindParams,\n ) => Promise<readonly NodeRow[]>;\n countNodesByKind: (params: CountNodesByKindParams) => Promise<number>;\n findEdgesByKind: (\n params: FindEdgesByKindParams,\n ) => Promise<readonly EdgeRow[]>;\n countEdgesByKind: (params: CountEdgesByKindParams) => Promise<number>;\n\n // === Unique Constraint Operations ===\n insertUnique: (params: InsertUniqueParams) => Promise<void>;\n /**\n * Batched variant of `insertUnique`: one multi-row statement per chunk\n * with the same per-entry conflict semantics (throws `UniquenessError`\n * for the first entry whose key a different live node holds). Optional —\n * callers fall back to per-entry `insertUnique` when unset.\n */\n insertUniqueBatch?: (entries: readonly InsertUniqueParams[]) => Promise<void>;\n deleteUnique: (params: DeleteUniqueParams) => Promise<void>;\n checkUnique: (params: CheckUniqueParams) => Promise<UniqueRow | undefined>;\n checkUniqueBatch?: (\n params: CheckUniqueBatchParams,\n ) => Promise<readonly UniqueRow[]>;\n\n // === Schema Operations ===\n getActiveSchema: (graphId: string) => Promise<SchemaVersionRow | undefined>;\n getSchemaVersion: (\n graphId: string,\n version: number,\n ) => Promise<SchemaVersionRow | undefined>;\n /**\n * Atomically inserts a new schema version and activates it as a single\n * transactional unit, with optimistic compare-and-swap on the currently\n * active version.\n *\n * - If `expected.kind === \"active\"` and the actual active version\n * differs, throws `StaleVersionError` (caller should refetch and\n * retry).\n * - If a row already exists at `params.version` with the same\n * `schemaHash`, returns it idempotently — reactivating it if it was\n * left inactive by an earlier crashed commit.\n * - If a row already exists at `params.version` with a different\n * `schemaHash`, throws `SchemaContentConflictError`.\n *\n * Requires `capabilities.transactions === true`. On non-transactional\n * backends (e.g. Cloudflare D1, drizzle-orm/neon-http) this method\n * throws `ConfigurationError` rather than running with degraded\n * atomicity that would silently re-introduce the orphan-row crash\n * window the primitive exists to eliminate.\n */\n commitSchemaVersion: (\n params: CommitSchemaVersionParams,\n ) => Promise<SchemaVersionRow>;\n /**\n * Atomically flips the active schema pointer to an existing version,\n * with optimistic compare-and-swap on the currently active version.\n * Used by `rollbackSchema` and any other \"promote/demote existing\n * version\" workflow. Throws `StaleVersionError` on CAS mismatch and\n * `MigrationError` if the target version row does not exist.\n *\n * Same transactional requirements as `commitSchemaVersion`.\n */\n setActiveVersion: (params: SetActiveVersionParams) => Promise<void>;\n\n // === Embedding Operations (optional - depends on vector capabilities) ===\n upsertEmbedding?: (params: UpsertEmbeddingParams) => Promise<void>;\n /**\n * Batched variant of `upsertEmbedding` for one vector slot. Optional —\n * callers fall back to per-row `upsertEmbedding` when unset.\n */\n upsertEmbeddingBatch?: (params: UpsertEmbeddingBatchParams) => Promise<void>;\n deleteEmbedding?: (params: DeleteEmbeddingParams) => Promise<void>;\n /**\n * KNN search over one `(nodeKind, fieldPath)` slot. Top-k is computed\n * over CURRENT nodes only — non-tombstoned AND inside their validity\n * window, matching a `current` read — so index drift (embedding rows\n * whose node was deleted or expired outside the store pipeline) can\n * neither surface nor crowd current rows out of the top-k. Custom\n * backends implementing this member must honor the same contract. Exact on pgvector >= 0.8 (HNSW via\n * `hnsw.iterative_scan = strict_order`; IVFFlat via\n * `ivfflat.iterative_scan = relaxed_order` plus a re-sort of the\n * bounded set; probe-bounded below 0.8) and sqlite-vec;\n * libSQL's DiskANN over-fetches 4x and post-filters (recall bounded by\n * that headroom).\n */\n vectorSearch?: (\n params: VectorSearchParams,\n ) => Promise<readonly VectorSearchResult[]>;\n createVectorIndex?: (params: CreateVectorIndexParams) => Promise<void>;\n dropVectorIndex?: (params: DropVectorIndexParams) => Promise<void>;\n /**\n * Single-statement hybrid search: both sources, RRF fusion, liveness\n * join, and node hydration composed into ONE statement — replacing the\n * facade's two search round trips plus id-hydration fetch. Optional;\n * the store falls back to the multi-statement path when unset (custom\n * backends, engines without window functions). Same liveness contract\n * as `vectorSearch` / `fulltextSearch`.\n */\n hybridSearch?: (\n params: HybridSearchParams,\n ) => Promise<readonly HybridSearchRow[]>;\n\n // === Fulltext Operations (optional - depends on fulltext capabilities) ===\n upsertFulltext?: (params: UpsertFulltextParams) => Promise<void>;\n deleteFulltext?: (params: DeleteFulltextParams) => Promise<void>;\n /**\n * Batched variant of `upsertFulltext`. Optional — callers fall back to\n * per-row `upsertFulltext` when unset.\n */\n upsertFulltextBatch?: (params: UpsertFulltextBatchParams) => Promise<void>;\n /**\n * Batched variant of `deleteFulltext`. Optional — callers fall back to\n * per-row `deleteFulltext` when unset.\n */\n deleteFulltextBatch?: (params: DeleteFulltextBatchParams) => Promise<void>;\n /**\n * Ranked fulltext search over one node kind. Like `vectorSearch`, top-k\n * is computed over CURRENT nodes only — non-tombstoned AND inside their\n * validity window (exact on both engines — plain WHERE, no top-k table\n * function involved). Custom backends implementing this member must\n * honor the same contract.\n */\n fulltextSearch?: (\n params: FulltextSearchParams,\n ) => Promise<readonly FulltextSearchResult[]>;\n\n // === Index Materialization (used by store.materializeIndexes) ===\n /**\n * Idempotently ensure ONLY the `typegraph_index_materializations`\n * table exists — separate from `bootstrapTables` so that\n * `materializeIndexes` doesn't pull in the full base-table DDL set\n * just to access the status table.\n *\n * Why focused: `bootstrapTables` issues 20+ `CREATE TABLE / CREATE\n * INDEX IF NOT EXISTS` statements covering every base table. Two\n * concurrent calls (e.g. two replicas of the same `schema_doc` both\n * starting up and calling `materializeIndexes`) race on\n * Postgres SHARE locks and DEADLOCK. Restricting the ensure-step to\n * the single status table eliminates the cross-table race entirely\n * — concurrent `CREATE TABLE IF NOT EXISTS` for one specific table\n * is well-behaved on Postgres.\n */\n ensureIndexMaterializationsTable?: () => Promise<void>;\n\n /**\n * Idempotently ensure ONLY the `typegraph_revision_origins` table exists.\n *\n * Revision-tracked stores use this per-graph, durable random origin together\n * with the recorded clock to prevent two independent stores with coincident\n * timestamps from sharing a merge base anchor. It is focused rather than\n * using `bootstrapTables` so existing deployments can adopt revision anchors\n * without replaying all base-table DDL during a merge read.\n */\n ensureRevisionOriginsTable?: () => Promise<void>;\n\n /**\n * Look up a recorded materialization for a declared index by its\n * physical SQL index name. Returns `undefined` if no row exists.\n */\n getIndexMaterialization?: (\n indexName: string,\n ) => Promise<IndexMaterializationRow | undefined>;\n /**\n * Bulk variant of `getIndexMaterialization`: load every recorded\n * materialization whose `indexName` (status key) is in `statusKeys`,\n * in a single round-trip. Returned rows are unordered — callers index\n * by `indexName`. Optional; consumers fall back to per-key\n * `getIndexMaterialization` when unset.\n */\n getIndexMaterializations?: (\n statusKeys: readonly string[],\n ) => Promise<readonly IndexMaterializationRow[]>;\n /**\n * Upsert a materialization attempt — success or failure. Failure rows\n * preserve any prior `materializedAt` so the historical successful\n * timestamp survives across error windows.\n */\n recordIndexMaterialization?: (\n params: RecordIndexMaterializationParams,\n ) => Promise<void>;\n /**\n * Atomically claims the build of one index across every materializer\n * (process- and pool-safe: the status row's own atomicity is the mutex).\n * Returns true when this caller now holds the claim. Backends whose\n * index builds cannot deadlock across callers (SQLite: engine-level\n * write serialization, no CONCURRENTLY) omit it; `materializeIndexes`\n * then builds without a claim, exactly as before.\n */\n claimIndexMaterialization?: (\n params: ClaimIndexMaterializationParams,\n ) => Promise<boolean>;\n /** Releases a claim taken by `claimIndexMaterialization` (token-guarded). */\n releaseIndexMaterializationClaim?: (\n params: ReleaseIndexMaterializationClaimParams,\n ) => Promise<void>;\n\n // === Contribution Materialization (#135 — durable strategy-owned\n // storage marker, sibling of the index status table) ===\n\n /**\n * Idempotently ensure ONLY the\n * `typegraph_contribution_materializations` table exists. Same\n * focused-bootstrap rationale as `ensureIndexMaterializationsTable`:\n * a single `CREATE TABLE IF NOT EXISTS` is concurrency-safe under\n * replica startup, where the full `bootstrapTables` set risks a\n * Postgres SHARE-lock deadlock.\n */\n ensureContributionMaterializationsTable?: () => Promise<void>;\n\n /**\n * Look up the durable materialization marker for one strategy-owned\n * contribution identity. Returns `undefined` when no row exists\n * (\"never initialized\").\n */\n getContributionMaterialization?: (\n identity: ContributionMaterializationIdentity,\n ) => Promise<ContributionMaterializationRow | undefined>;\n\n /**\n * Upsert a contribution-materialization attempt — success or failure.\n * Failure rows preserve any prior `materializedAt` via COALESCE so a\n * later failed re-attempt doesn't erase the historical success.\n */\n recordContributionMaterialization?: (\n params: RecordContributionMaterializationParams,\n ) => Promise<void>;\n\n /**\n * Resolve (once per backend instance, cached) and assert the durable\n * materialization markers for every `runtimeEnsure` contribution this\n * backend's strategy declares, for `graphId`. Throws\n * `StoreNotInitializedError` when a marker is missing, stale\n * (signature drift), or recorded a failed last attempt.\n *\n * This is the single read-side gate the fulltext hot-path wrappers\n * and `store.transaction()` consult. It performs ZERO DDL and ZERO\n * marker writes — initialization is the exclusive job of the async\n * boot path (`createStoreWithSchema` → `ensureRuntimeContributions`).\n */\n assertRuntimeContributionsInitialized?: (graphId: string) => Promise<void>;\n\n // === Kind Removal Status ===\n\n /**\n * Bootstraps the per-deployment `typegraph_kind_removals` table so\n * `store.removeKinds()` and `store.materializeRemovals()` can persist\n * removal status. Mirrors the focused-bootstrap rationale documented\n * on `ensureIndexMaterializationsTable` — the full `bootstrapTables`\n * touches every base table and risks Postgres SHARE-lock deadlock\n * under concurrent replica startup.\n */\n ensureKindRemovalsTable?: () => Promise<void>;\n\n /**\n * List graph-extension kind removals whose data-cleanup pass has not yet\n * succeeded for this `graphId`. Returns rows with\n * `removedAt: undefined`. Order is unspecified; callers materialize\n * one-at-a-time and don't depend on it.\n */\n getPendingKindRemovals?: (\n graphId: string,\n ) => Promise<readonly KindRemovalRow[]>;\n\n /**\n * List ALL kind-removal rows for a `graphId` — pending and completed.\n * Used by `materializeRemovals()` reconciliation to detect rows that\n * are missing entirely (the `removeKinds()` crash window) versus\n * already completed. Without this distinction the reconciler would\n * have to upsert every expected historical removal on every call,\n * churning `last_attempted_at` on rows that long since succeeded.\n * Order is unspecified.\n */\n getAllKindRemovals?: (graphId: string) => Promise<readonly KindRemovalRow[]>;\n\n /**\n * Upsert a kind-removal status row. `removedAt: undefined` records\n * the pending state at schema-commit time; `removedAt: <iso>`\n * marks the data cleanup successful. The COALESCE rule on `removedAt`\n * mirrors `recordIndexMaterialization` so a later failure doesn't\n * clobber the historical successful timestamp from another replica.\n */\n recordKindRemoval?: (params: RecordKindRemovalParams) => Promise<void>;\n\n // === Reconciliation Watermark ===\n\n /**\n * Bootstraps the per-deployment `typegraph_reconciliation_markers`\n * table so `materializeRemovals()` can persist reconciliation\n * progress. Same focused-bootstrap rationale as the other status\n * tables — full `bootstrapTables` risks Postgres SHARE-lock\n * deadlock under concurrent replica startup.\n */\n ensureReconciliationMarkersTable?: () => Promise<void>;\n\n // === Table Contributions (#129) ===\n\n /**\n * Materializes every contribution flagged `runtimeEnsure` — the\n * strategy-owned runtime tables (fulltext today) that drizzle-kit-\n * managed setups don't create. Called once after a successful schema\n * load. Deliberately scoped: base/drizzle-visible tables are\n * `runtimeEnsure: false`, so this does not regress startup into\n * broad DDL/probing across every table.\n *\n * The canonical durable-marker writer (#135): for each runtime\n * contribution it short-circuits when the marker already records a\n * matching signature, otherwise runs the idempotent `createDdl` and\n * records the marker (success or failure) keyed by `graphId`.\n */\n ensureRuntimeContributions?: (graphId: string) => Promise<void>;\n\n /**\n * Privileged materializer for one embedding `(kind, field)` slot's\n * `ownedTables` contribution(s): creates the per-field vector table and\n * records its durable marker, idempotently. The vector counterpart of\n * `ensureRuntimeContributions` — vectors are per-`(kind, field)` and\n * graph-derived, so the store enumerates slots (via\n * `resolveEmbeddingFields`) and uses the batch counterpart at boot under\n * the privileged role. Pass `{ force: true }` to overwrite the marker\n * at the current signature, bypassing the drift-guard — the sanctioned\n * path `store.reembedVectorField()` uses after recreating storage at a\n * new dimension. Pass `{ onDrift: \"skip\" }` to leave an\n * already-provisioned slot whose shape has since changed untouched\n * (warn + no-op) instead of refusing — the boot/evolve path, so a\n * declared dimension change never blocks startup before the operator\n * can run `reembedVectorField`. Present only on backends wired with a\n * vector strategy.\n */\n ensureVectorSlotContribution?: (\n slot: VectorSlot,\n options?: Readonly<{ force?: boolean; onDrift?: \"throw\" | \"skip\" }>,\n ) => Promise<void>;\n\n /**\n * Batch form of `ensureVectorSlotContribution`, used by privileged boot to\n * resolve every slot's durable markers with one graph-scoped query. The\n * singular method remains available for re-embedding and compatibility.\n */\n ensureVectorSlotContributions?: (\n slots: readonly VectorSlot[],\n options?: Readonly<{ force?: boolean; onDrift?: \"throw\" | \"skip\" }>,\n ) => Promise<void>;\n\n /**\n * SELECT-only gate for one embedding `(kind, field)` slot: asserts the\n * durable marker(s) for the slot's `ownedTables` contribution(s),\n * cached per backend instance. Throws `StoreNotInitializedError` when\n * the slot is missing, stale (signature drift), or recorded a failed\n * last attempt. The vector counterpart of\n * `assertRuntimeContributionsInitialized`, consulted by the verified\n * runtime attach. Performs ZERO DDL and ZERO writes. Present only on\n * backends wired with a vector strategy.\n */\n assertVectorSlotInitialized?: (slot: VectorSlot) => Promise<void>;\n\n /**\n * Batch form of `assertVectorSlotInitialized`, used by verified attach to\n * resolve every slot's durable markers with one graph-scoped query.\n */\n assertVectorSlotsInitialized?: (\n slots: readonly VectorSlot[],\n ) => Promise<void>;\n\n /**\n * Forget one embedding `(kind, field)` slot's durable contribution\n * marker(s). Called after the slot's per-field table is dropped\n * (vector-field reclaim) so a later `ensureVectorSlotContribution`\n * re-creates the table instead of trusting an orphaned \"initialized\"\n * marker. Does NOT drop the table itself (the caller already did).\n * Present only on backends wired with a vector strategy.\n */\n deleteVectorSlotContribution?: (slot: VectorSlot) => Promise<void>;\n\n /**\n * Bootstraps the fulltext storage table the active `FulltextStrategy`\n * owns. Same focused-bootstrap rationale as the other `ensure*Table`\n * methods: idempotent and concurrency-safe under replica startup.\n *\n * Superseded by `ensureRuntimeContributions()` (#129); retained as\n * a thin back-compat wrapper for backends/callers predating #129. Not\n * machine-`@deprecated` because the manager still calls it as the\n * pre-#129 fallback. #135 removed the remaining hot-path callers and\n * routed this through the durable-marker writer.\n */\n ensureFulltextTable?: (graphId: string) => Promise<void>;\n\n /**\n * Read the high-water mark schema version for which\n * `materializeRemovals` reconciliation has already verified history\n * for `graphId`. Returns `undefined` when no marker has been\n * recorded yet. Used to skip already-checked transitions in the\n * recovery walk.\n */\n getReconciliationMarker?: (graphId: string) => Promise<number | undefined>;\n\n /**\n * Persist the reconciliation high-water mark for `graphId`. Called\n * after `materializeRemovals` completes a clean walk; subsequent\n * calls walk only versions newer than this marker. Idempotent\n * upsert by `graphId`.\n */\n setReconciliationMarker?: (graphId: string, version: number) => Promise<void>;\n\n // === Graph Lifecycle ===\n /**\n * Hard-deletes all data for a graph (nodes, edges, uniques, embeddings, schema versions).\n * Intended for import-replacement workflows. No hooks, no per-row logic.\n */\n clearGraph: (graphId: string) => Promise<void>;\n\n /**\n * Creates the base TypeGraph tables if they don't already exist.\n *\n * Called automatically by `createStoreWithSchema()` when a fresh database\n * is detected. Users who manage DDL themselves via `createStore()` never\n * hit this path.\n */\n bootstrapTables?: () => Promise<void>;\n\n /**\n * Refreshes the backend's query-planner statistics.\n *\n * Call this once after a large initial import or bulk backfill. Without\n * up-to-date statistics, the planner can pick suboptimal execution plans\n * — on PostgreSQL this is the difference between a 0.5ms and a 5ms\n * forward traversal; on SQLite it's the difference between 0.9ms and\n * 23ms fulltext search. Autovacuum / background statistics collection\n * will catch up eventually, but calling this explicitly after a bulk\n * load gives you correct latencies immediately.\n *\n * Implementations:\n * - SQLite runs `ANALYZE`, which populates `sqlite_stat1`\n * - PostgreSQL runs `ANALYZE` on the TypeGraph-managed tables\n *\n * Safe to call at any time; costs a few tens of milliseconds on the\n * sizes this library is designed for.\n */\n refreshStatistics: () => Promise<void>;\n\n /**\n * Runs an intentionally trusted, all-or-nothing initial import.\n *\n * Optional because only backends that can pin one transaction and use a\n * native high-throughput write path expose it. Implementations must reject\n * a database whose TypeGraph node or edge tables already contain rows. They\n * may temporarily remove rebuildable secondary indexes, but must restore\n * them before committing. Any callback, insert, or rebuild failure rolls the\n * entire operation back.\n *\n * This is a top-level-only lifecycle operation and is deliberately absent\n * from {@link TransactionBackend}.\n */\n trustedImport?: <T>(\n fn: (session: TrustedImportSession) => Promise<T>,\n ) => Promise<T>;\n\n // === Query Execution ===\n execute: <T>(query: CompiledRowsSql) => Promise<readonly T[]>;\n\n /**\n * Execute a non-row-returning SQL statement bound to this backend or\n * transaction. Optional because custom backends may only expose the public\n * row-returning query path; features that need statement execution must\n * capability-check and fail loudly.\n */\n executeStatement?: (query: CompiledStatementSql) => Promise<void>;\n\n /**\n * Execute an internally compiled statement against connection-local\n * temporary state. History wrappers preserve this path because it cannot\n * mutate graph or history tables; callers cannot construct its branded\n * input through the public API.\n */\n executeTemporaryStatement?: (\n query: CompiledTemporaryStatementSql,\n ) => Promise<void>;\n\n /** Execute pre-compiled SQL text with bound parameters. Available on sync SQLite and pg backends. */\n executeRaw?: <T>(\n sqlText: string,\n params: readonly unknown[],\n ) => Promise<readonly T[]>;\n\n /** Compile a Drizzle SQL object to { sql, params } without executing. */\n compileSql?: (\n query: SQL,\n ) => Readonly<{ sql: string; params: readonly unknown[] }>;\n\n /**\n * Execute a DDL statement that returns no rows (CREATE INDEX,\n * CREATE TABLE, ALTER TABLE, etc.). Separate from `executeRaw`\n * because some drivers (better-sqlite3) require `.run()` for DDL\n * and `.all()` for queries — the ambiguity can't be resolved by\n * inspecting the SQL string portably.\n *\n * Postgres path can use this for `CREATE INDEX CONCURRENTLY`, which\n * cannot run inside a transaction. Implementations must execute the\n * statement outside `transaction(...)`.\n */\n executeDdl?: (ddl: string) => Promise<void>;\n\n // === Transaction ===\n /**\n * `fn` receives the tx-scoped backend and the raw Drizzle handle\n * **bound to that same transaction** (`AdoptedTransaction`). The\n * store surfaces the second argument as `TransactionContext.sql` so\n * callers can write their own relational tables inside the\n * graph-owned transaction. Implementations MUST pass the *exact*\n * handle the tx-scoped backend writes through (the Postgres/libsql\n * tx handle; for better-sqlite3 / do-sqlite the bound connection),\n * never a fresh one.\n *\n * The tx-scoped backend serializes the statements *it* issues onto the\n * pinned connection, but the raw handle bypasses that queue. It is the\n * caller's responsibility not to run raw statements concurrently with graph\n * writes (or with each other) on the shared connection — a constraint\n * inherent to a single-connection transaction, not something this method can\n * enforce over a handle it does not mediate.\n */\n transaction: <T>(\n fn: (tx: TransactionBackend, sql: AdoptedTransaction) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<T>;\n\n /**\n * Adopt a caller-owned, already-open transaction (#134).\n *\n * Returns a transaction-scoped backend bound to the *exact*\n * `externalTx` client, reusing this backend's already-resolved\n * schema/strategy config — no `createStoreWithSchema` / `evolve` /\n * `migrateSchema`, and **no DDL inside the caller's business\n * transaction**. The caller owns `BEGIN`/`COMMIT`/`ROLLBACK`; this\n * method neither opens nor closes a transaction. Async drivers\n * (node-postgres, `neon-serverless` Pool, libsql) wrap with\n * `db.transaction(async …)`; synchronous `better-sqlite3` must instead\n * issue explicit `BEGIN`/`COMMIT`/`ROLLBACK` (its driver rejects an\n * `async` transaction callback).\n *\n * Optional and presence-detected like the other capability-scoped\n * members: only the Drizzle Postgres/SQLite backends provide it.\n * Implementations MUST throw (not silently degrade) when\n * `capabilities.transactions` is `false` — a non-atomic fallback is\n * safe for graph-only writes but dangerous for cross-store flows,\n * where the caller's relational write *would* still commit.\n *\n * Fulltext stays safe by construction: the returned backend's\n * fulltext methods assert the durable materialization marker (a\n * cached SELECT, never DDL) at point of use and throw\n * `StoreNotInitializedError` on a missing/stale/failed marker rather\n * than migrating mid-transaction. Prefer booting the parent store via\n * `createStoreWithSchema` so that assertion is a warm-cache no-op.\n */\n adoptTransaction?: (externalTx: AdoptedTransaction) => TransactionBackend;\n\n // === Lifecycle ===\n close: () => Promise<void>;\n}>;\n\nexport type BackendIdentity = Pick<\n GraphBackend,\n | \"dialect\"\n | \"capabilities\"\n | \"tableNames\"\n | \"fulltextStrategy\"\n | \"vectorStrategy\"\n>;\n\nexport type NodeEntityReadBackend = Pick<\n GraphBackend,\n \"getNode\" | \"getNodes\" | \"findNodesByKind\" | \"countNodesByKind\"\n>;\n\nexport type NodeEntityWriteBackend = Pick<\n GraphBackend,\n | \"insertNode\"\n | \"insertNodeNoReturn\"\n | \"insertNodesBatch\"\n | \"insertNodesBatchReturning\"\n | \"updateNode\"\n | \"deleteNode\"\n | \"hardDeleteNode\"\n>;\n\nexport type EdgeEntityReadBackend = Pick<\n GraphBackend,\n | \"getEdge\"\n | \"getEdges\"\n | \"countEdgesFrom\"\n | \"edgeExistsBetween\"\n | \"findEdgesConnectedTo\"\n | \"findEdgesByKind\"\n | \"countEdgesByKind\"\n>;\n\nexport type EdgeEntityWriteBackend = Pick<\n GraphBackend,\n | \"insertEdge\"\n | \"insertEdgeNoReturn\"\n | \"insertEdgesBatch\"\n | \"insertEdgesBatchReturning\"\n | \"updateEdge\"\n | \"deleteEdge\"\n | \"deleteEdgesBatch\"\n | \"hardDeleteEdge\"\n | \"hardDeleteEdgesBatch\"\n>;\n\nexport type GraphEntityReadBackend = NodeEntityReadBackend &\n EdgeEntityReadBackend;\n\nexport type GraphEntityWriteBackend = NodeEntityWriteBackend &\n EdgeEntityWriteBackend;\n\nexport type UniqueConstraintBackend = Pick<\n GraphBackend,\n | \"insertUnique\"\n | \"insertUniqueBatch\"\n | \"deleteUnique\"\n | \"checkUnique\"\n | \"checkUniqueBatch\"\n>;\n\nexport type SchemaReadBackend = Pick<\n GraphBackend,\n \"getActiveSchema\" | \"getSchemaVersion\"\n>;\n\nexport type SchemaCommitBackend = Pick<\n GraphBackend,\n \"commitSchemaVersion\" | \"setActiveVersion\"\n>;\n\nexport type VectorOperationBackend = Pick<\n GraphBackend,\n | \"upsertEmbedding\"\n | \"upsertEmbeddingBatch\"\n | \"deleteEmbedding\"\n | \"vectorSearch\"\n | \"createVectorIndex\"\n | \"dropVectorIndex\"\n>;\n\nexport type FulltextOperationBackend = Pick<\n GraphBackend,\n | \"upsertFulltext\"\n | \"deleteFulltext\"\n | \"upsertFulltextBatch\"\n | \"deleteFulltextBatch\"\n | \"fulltextSearch\"\n>;\n\nexport type IndexMaterializationBackend = Pick<\n GraphBackend,\n | \"ensureIndexMaterializationsTable\"\n | \"getIndexMaterialization\"\n | \"getIndexMaterializations\"\n | \"recordIndexMaterialization\"\n>;\n\nexport type ContributionMaterializationBackend = Pick<\n GraphBackend,\n | \"ensureContributionMaterializationsTable\"\n | \"getContributionMaterialization\"\n | \"recordContributionMaterialization\"\n | \"assertRuntimeContributionsInitialized\"\n | \"ensureRuntimeContributions\"\n | \"ensureFulltextTable\"\n>;\n\nexport type RemovalMaterializationBackend = Pick<\n GraphBackend,\n | \"ensureKindRemovalsTable\"\n | \"getPendingKindRemovals\"\n | \"getAllKindRemovals\"\n | \"recordKindRemoval\"\n | \"ensureReconciliationMarkersTable\"\n | \"getReconciliationMarker\"\n | \"setReconciliationMarker\"\n>;\n\nexport type GraphLifecycleBackend = Pick<\n GraphBackend,\n \"clearGraph\" | \"bootstrapTables\"\n>;\n\nexport type QueryExecutionBackend = Pick<GraphBackend, \"execute\">;\n\nexport type RawQueryExecutionBackend = Pick<\n GraphBackend,\n \"executeRaw\" | \"compileSql\"\n>;\n\nexport type RawStatementExecutionBackend = Pick<\n GraphBackend,\n \"executeStatement\" | \"executeTemporaryStatement\" | \"executeDdl\"\n>;\n\nexport type BackendMaintenance = Pick<GraphBackend, \"refreshStatistics\">;\n\nexport type BackendTransactions = Pick<\n GraphBackend,\n \"transaction\" | \"adoptTransaction\"\n>;\n\nexport type BackendLifecycle = Pick<GraphBackend, \"close\">;\n\n/**\n * Transaction backend — a backend scoped to a transaction.\n *\n * This is an explicit facet composition, not `Omit<GraphBackend, ...>`.\n * New top-level-only backend methods therefore do not silently appear on\n * transaction-scoped backends. `commitSchemaVersion`, `setActiveVersion`,\n * `refreshStatistics`, `transaction`, `adoptTransaction`, and `close` stay\n * deliberately absent: their guarantees depend on the top-level backend or\n * lifecycle owner rather than an already-open transaction.\n */\nexport type TransactionBackend = Readonly<\n BackendIdentity &\n GraphEntityReadBackend &\n GraphEntityWriteBackend &\n UniqueConstraintBackend &\n SchemaReadBackend &\n VectorOperationBackend &\n FulltextOperationBackend &\n IndexMaterializationBackend &\n ContributionMaterializationBackend &\n RemovalMaterializationBackend &\n GraphLifecycleBackend &\n QueryExecutionBackend &\n RawQueryExecutionBackend &\n RawStatementExecutionBackend\n>;\n\ntype ExactBackendOverlay<T extends object, O extends Partial<T>> = O &\n Readonly<Record<Exclude<keyof O, keyof T>, never>>;\n\n// ============================================================\n// Managed Backend Helper\n// ============================================================\n\n/**\n * Overlays selected backend methods without copying the backend object.\n *\n * Backend wrappers use this instead of object spread so custom class/proxy\n * backends keep prototype methods, getters, private fields, and non-enumerable\n * members. Delegated target methods are bound to the original target, while\n * overlay methods keep the overlay object as their receiver.\n */\nexport function createBackendOverlay<\n T extends object,\n const O extends Partial<T> = Partial<T>,\n>(target: T, overlay: ExactBackendOverlay<T, O>): T {\n const boundTargetMethods = new Map<PropertyKey, unknown>();\n\n function hasOverlayProperty(property: PropertyKey): boolean {\n return Object.hasOwn(overlay, property);\n }\n\n function targetValue(targetObject: T, property: PropertyKey): unknown {\n const value = Reflect.get(targetObject, property, targetObject);\n if (typeof value !== \"function\") return value;\n\n const cached = boundTargetMethods.get(property);\n if (cached !== undefined) return cached;\n\n const method = value as (this: T, ...args: unknown[]) => unknown;\n const bound = method.bind(targetObject);\n boundTargetMethods.set(property, bound);\n return bound;\n }\n\n return new Proxy(target, {\n get(targetObject, property) {\n if (hasOverlayProperty(property)) {\n return Reflect.get(overlay, property, overlay);\n }\n return targetValue(targetObject, property);\n },\n\n has(targetObject, property) {\n return (\n hasOverlayProperty(property) || Reflect.has(targetObject, property)\n );\n },\n\n ownKeys(targetObject) {\n return [\n ...new Set([\n ...Reflect.ownKeys(targetObject),\n ...Reflect.ownKeys(overlay),\n ]),\n ];\n },\n\n getOwnPropertyDescriptor(targetObject, property) {\n if (hasOverlayProperty(property)) {\n const descriptor = Reflect.getOwnPropertyDescriptor(overlay, property);\n if (descriptor === undefined) return;\n return { ...descriptor, configurable: true };\n }\n return Reflect.getOwnPropertyDescriptor(targetObject, property);\n },\n\n set(targetObject, property, value) {\n if (hasOverlayProperty(property)) {\n return Reflect.set(overlay, property, value, overlay);\n }\n return Reflect.set(targetObject, property, value, targetObject);\n },\n\n defineProperty(targetObject, property, attributes) {\n if (hasOverlayProperty(property)) {\n return Reflect.defineProperty(overlay, property, attributes);\n }\n return Reflect.defineProperty(targetObject, property, attributes);\n },\n\n deleteProperty(targetObject, property) {\n if (hasOverlayProperty(property)) {\n return Reflect.deleteProperty(overlay, property);\n }\n return Reflect.deleteProperty(targetObject, property);\n },\n });\n}\n\n/**\n * Wraps a GraphBackend with idempotent close that also runs a teardown\n * callback (e.g. closing the underlying database connection).\n */\nexport function wrapWithManagedClose(\n backend: GraphBackend,\n teardown: () => void | Promise<void>,\n): GraphBackend {\n let isClosed = false;\n return createBackendOverlay(backend, {\n async close(): Promise<void> {\n if (isClosed) return;\n isClosed = true;\n await backend.close();\n await teardown();\n },\n });\n}\n\n/**\n * Runs `fn` inside a transaction when given a top-level backend that supports\n * one, falling through to a direct invocation otherwise. Lets call sites benefit\n * from atomicity on backends that have transactions while staying functional on\n * backends that don't (Cloudflare D1, `drizzle-orm/neon-http` over HTTP), and\n * avoids opening nested transactions when the caller already holds a\n * transaction-scoped backend. The single-statement race window is already\n * implicit on any backend that reports `transactions: false`; callers that\n * cannot tolerate it must branch on the capability themselves.\n *\n * Pass `fallback` only when the toplevel backend method would recurse\n * — pass the operation-level backend so the no-tx path doesn't loop\n * back through the same toplevel method.\n */\nexport async function runOptionallyInTransaction<T>(\n backend: GraphBackend | TransactionBackend,\n fn: (target: GraphBackend | TransactionBackend) => Promise<T>,\n fallback?: GraphBackend | TransactionBackend,\n): Promise<T> {\n if (\"transaction\" in backend && backend.capabilities.transactions) {\n return backend.transaction((tx) => fn(tx));\n }\n return fn(fallback ?? backend);\n}\n\n// ============================================================\n// Additional Parameter Types\n// ============================================================\n\n/**\n * Parameters for inserting a unique constraint entry.\n */\nexport type InsertUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n nodeId: string;\n concreteKind: string;\n}>;\n\n/**\n * Parameters for deleting a unique constraint entry.\n */\nexport type DeleteUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n}>;\n\n/**\n * Parameters for checking a unique constraint.\n */\nexport type CheckUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n /** If true, also returns soft-deleted entries. Used by get-or-create operations. */\n includeDeleted?: boolean;\n}>;\n\n/**\n * Parameters for batch-checking unique constraints.\n */\nexport type CheckUniqueBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n keys: readonly string[];\n /** If true, also returns soft-deleted entries. Used by get-or-create operations. */\n includeDeleted?: boolean;\n}>;\n\n/**\n * Parameters for inserting a schema version.\n *\n * Used internally by backend implementations. Public callers go through\n * `commitSchemaVersion`, which handles the insert + activate atomically\n * with CAS guarantees.\n */\nexport type InsertSchemaParams = Readonly<{\n graphId: string;\n version: number;\n schemaHash: string;\n schemaDoc: SerializedSchema;\n isActive: boolean;\n}>;\n\n/**\n * The caller's claim about the currently-active schema version, used as\n * the optimistic compare-and-swap guard for `commitSchemaVersion`.\n *\n * - `{ kind: \"initial\" }` — caller is committing the first-ever version\n * for this graph and asserts no active version exists yet.\n * - `{ kind: \"active\", version: N }` — caller observed version N as\n * active and is committing version N+1 against that baseline. The\n * commit fails with `StaleVersionError` if some other writer has\n * advanced or rolled back the pointer in the meantime.\n *\n * Tagged-union form (rather than a magic `version: 0` sentinel) because\n * the two cases have materially different semantics: the initial path\n * skips the \"deactivate prior\" UPDATE, and the no-active-row state is\n * a *valid* expected state, not an out-of-band signal.\n */\nexport type CommitSchemaVersionExpected =\n Readonly<{ kind: \"initial\" }> | Readonly<{ kind: \"active\"; version: number }>;\n\n/**\n * Parameters for `commitSchemaVersion`.\n */\nexport type CommitSchemaVersionParams = Readonly<{\n graphId: string;\n /** CAS guard — see `CommitSchemaVersionExpected`. */\n expected: CommitSchemaVersionExpected;\n /** The new version to insert and activate. */\n version: number;\n schemaHash: string;\n schemaDoc: SerializedSchema;\n}>;\n\n/**\n * Parameters for `setActiveVersion`.\n *\n * Flips the active pointer from `expected` to `version` for an existing\n * row. CAS prevents overwriting a concurrent rollback or commit.\n */\nexport type SetActiveVersionParams = Readonly<{\n graphId: string;\n /** CAS guard. Same semantics as `commitSchemaVersion.expected`. */\n expected: CommitSchemaVersionExpected;\n /** The version to mark active. Must already exist. */\n version: number;\n}>;\n\n/**\n * Parameters for counting edges from a source node.\n */\nexport type CountEdgesFromParams = Readonly<{\n graphId: string;\n edgeKind: string;\n fromKind: string;\n fromId: string;\n /** If true, only count edges where valid_to IS NULL */\n activeOnly?: boolean;\n}>;\n\n/**\n * Parameters for checking if an edge exists between two nodes.\n */\nexport type EdgeExistsBetweenParams = Readonly<{\n graphId: string;\n edgeKind: string;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n}>;\n\n/**\n * Parameters for finding edges connected to a node.\n */\nexport type FindEdgesConnectedToParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * Parameters for finding nodes by kind.\n */\nexport type FindNodesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n /** Max rows to return. */\n limit?: number;\n /** Offset. Present for backward compat; rebuild uses `after` instead. */\n offset?: number;\n /** If true, exclude deleted nodes. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n /**\n * Stable ordering for keyset pagination. Default: \"created_at\" (existing\n * behavior). Rebuild should use \"id\" for iteration that is stable under\n * concurrent writes and shared timestamps.\n */\n orderBy?: \"id\" | \"created_at\";\n /**\n * Keyset cursor. Returns rows strictly greater (by `orderBy`) than this\n * value. When `orderBy: \"id\"`, compared lexicographically. Mutually\n * exclusive with `offset` — callers pick one.\n */\n after?: string;\n}>;\n\n/**\n * Parameters for counting nodes by kind.\n */\nexport type CountNodesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n /** If true, exclude deleted nodes. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n/**\n * Parameters for finding edges by kind.\n */\nexport type FindEdgesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n fromKind?: string;\n fromId?: string;\n toKind?: string;\n toId?: string;\n limit?: number;\n offset?: number;\n /** If true, exclude deleted edges. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n /**\n * Stable ordering for keyset pagination. Default: \"created_at\" (existing\n * behavior). Use \"id\" for iteration that is stable under shared `created_at`\n * timestamps — the offset path orders by the NON-unique `created_at`, so a\n * full enumeration must page by the unique `id` to avoid skipping a row at a\n * page boundary. Mirrors {@link FindNodesByKindParams.orderBy}.\n */\n orderBy?: \"id\" | \"created_at\";\n /**\n * Keyset cursor. Returns rows strictly greater (by `orderBy`) than this value.\n * When `orderBy: \"id\"`, compared lexicographically. Mutually exclusive with\n * `offset` — callers pick one. Mirrors {@link FindNodesByKindParams.after}.\n */\n after?: string;\n}>;\n\n/**\n * Parameters for counting edges by kind.\n */\nexport type CountEdgesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n fromKind?: string;\n fromId?: string;\n toKind?: string;\n toId?: string;\n /** If true, exclude deleted edges. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n// ============================================================\n// Default Capabilities\n// ============================================================\n\n/**\n * Conservative per-statement bound-parameter floor for SQLite. The\n * compiled-in `SQLITE_MAX_VARIABLE_NUMBER` defaulted to 999 before SQLite\n * 3.32.0; drivers whose real ceiling cannot be probed (async/remote\n * connections) keep this floor. Single source of truth for\n * {@link SQLITE_CAPABILITIES} and the SQLite backend's batch math fallback.\n */\nexport const SQLITE_MAX_BIND_PARAMETERS = 999;\n\n/**\n * `SQLITE_MAX_VARIABLE_NUMBER` default since SQLite 3.32.0 (better-sqlite3\n * also compiles it in explicitly). Used when a synchronous driver's probe\n * confirms a modern build.\n */\nexport const MODERN_SQLITE_MAX_BIND_PARAMETERS = 32_766;\n\n/**\n * Cloudflare D1's documented per-statement bound-parameter ceiling. Far\n * below the classic SQLite floor, so D1 detection must cap the budget or\n * batched writes fail at runtime.\n */\nexport const D1_MAX_BIND_PARAMETERS = 100;\n\n/**\n * Cloudflare SQLite-backed Durable Objects' documented per-statement\n * bound-parameter ceiling. The resolved `do-sqlite` execution profile must\n * advertise this limit so every capability-driven batch path stays below it.\n */\nexport const DURABLE_OBJECT_MAX_BIND_PARAMETERS = 100;\n\n/**\n * PostgreSQL's wire-protocol bound-parameter ceiling (a 16-bit count). Single\n * source of truth for {@link POSTGRES_CAPABILITIES} and the Postgres backend's\n * batch math.\n */\nexport const POSTGRES_MAX_BIND_PARAMETERS = 65_535;\n\n/**\n * Default capabilities for SQLite.\n */\nexport const SQLITE_CAPABILITIES: BackendCapabilities = {\n transactions: true, // SQLite supports transactions\n windowFunctions: true, // SQLite has supported window functions since 3.25.0\n returning: true, // SQLite has supported RETURNING since 3.35.0\n maxBindParameters: SQLITE_MAX_BIND_PARAMETERS,\n // Generic SQLite builds do not guarantee ENABLE_MATH_FUNCTIONS. The local\n // better-sqlite3 factory overrides this flag for its bundled build contract.\n graphAnalytics: { supported: true, mathFunctions: false },\n};\n\n/**\n * Default capabilities for PostgreSQL.\n */\nexport const POSTGRES_CAPABILITIES: BackendCapabilities = {\n transactions: true, // PostgreSQL supports transactions\n windowFunctions: true, // PostgreSQL supports ROW_NUMBER() and related windows\n returning: true, // PostgreSQL has supported RETURNING since 8.2\n maxBindParameters: POSTGRES_MAX_BIND_PARAMETERS,\n graphAnalytics: { supported: true, mathFunctions: true },\n};\n","import { type SQL } from \"drizzle-orm\";\n\ndeclare const SqlIntentBrand: unique symbol;\n\nexport type SqlIntent = \"rows\" | \"statement\" | \"temporary-statement\";\n\nexport type IntentSql<I extends SqlIntent> = SQL &\n Readonly<{ [SqlIntentBrand]: I }>;\n\nexport type CompiledRowsSql = IntentSql<\"rows\">;\nexport type CompiledSelectSql = CompiledRowsSql;\nexport type CompiledStatementSql = IntentSql<\"statement\">;\nexport type CompiledTemporaryStatementSql = IntentSql<\"temporary-statement\">;\n\nexport function asCompiledRowsSql(query: SQL): CompiledRowsSql {\n return query as CompiledRowsSql;\n}\n\nexport function asCompiledSelectSql(query: SQL): CompiledSelectSql {\n return asCompiledRowsSql(query);\n}\n\nexport function asCompiledStatementSql(query: SQL): CompiledStatementSql {\n return query as CompiledStatementSql;\n}\n\n/**\n * Marks an internal statement that may write only connection-local temporary\n * state. This is intentionally separate from the public raw-statement intent:\n * history-enabled stores block arbitrary raw writes but iterative graph\n * operations still need to manage ephemeral working tables.\n */\nexport function asCompiledTemporaryStatementSql(\n query: SQL,\n): CompiledTemporaryStatementSql {\n return query as CompiledTemporaryStatementSql;\n}\n\n/**\n * Statements whose good plan depends on the bound parameter values —\n * e.g. an id-array membership filter where the array cardinality varies\n * per call. PostgreSQL's prepared-statement machinery switches to a\n * generic (parameter-blind) plan after five executions, which for these\n * statements is catastrophically wrong (measured 21ms -> 310ms on the\n * subgraph edge fetch). Marked statements are executed unnamed so every\n * call is planned against the actual parameters; the re-parse cost is\n * ~1ms, the generic-plan cliff it avoids is 10-300ms.\n */\nconst forceCustomPlanQueries = new WeakSet<SQL>();\n\nexport function markForceCustomPlan(query: SQL): void {\n forceCustomPlanQueries.add(query);\n}\n\nexport function shouldForceCustomPlan(query: SQL): boolean {\n return forceCustomPlanQueries.has(query);\n}\n\n/**\n * Statements whose plan includes an engine ANN index scan (the inline\n * `.similarTo(..., { approximate: true })` branch). The PostgreSQL\n * backend wraps their execution with the same pgvector GUC overrides\n * the search facade applies (`hnsw.iterative_scan = strict_order` /\n * `ivfflat.iterative_scan = relaxed_order` on pgvector >= 0.8), so a\n * filtered approximate query keeps scanning past the default ef_search\n * frontier instead of starving. Carries the slot index types so the\n * backend knows which GUCs apply. Backends without GUC semantics\n * ignore the brand.\n */\nconst annIndexScanQueries = new WeakMap<SQL, readonly string[]>();\n\nexport function markAnnIndexScan(\n query: SQL,\n indexTypes: readonly string[],\n): void {\n annIndexScanQueries.set(query, indexTypes);\n}\n\nexport function annIndexScanTypes(query: SQL): readonly string[] | undefined {\n return annIndexScanQueries.get(query);\n}\n\n/**\n * Whether a compiled statement can be run as raw text (`executeRaw`) without\n * losing execution semantics. Both brands above ride on the SQL *object* and\n * are honored only by `backend.execute`: the force-custom-plan flag makes\n * PostgreSQL re-plan against the actual parameters (opposed to reusing a\n * cached statement), and the ANN-scan brand drives the pgvector iterative-scan\n * GUC wrapper. A statement carrying either must not be flattened to text and\n * cached — callers fall back to `backend.execute`. Keeping this predicate\n * beside the brands means a future brand updates one place, not every caller.\n */\nexport function isRawExecutable(query: SQL): boolean {\n return (\n !shouldForceCustomPlan(query) && annIndexScanTypes(query) === undefined\n );\n}\n","/**\n * Temporal Filter Compilation\n *\n * Generates SQL clauses for temporal filtering based on valid_from/valid_to\n * and deleted_at timestamps. Consolidates the previously duplicated temporal\n * filter functions into a single, parameterized implementation.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport { type TemporalMode } from \"../../core/types\";\nimport { nowIso } from \"../../utils/date\";\n\n/**\n * The instant every `currentReadInstant()` inside {@link withPinnedReadInstant}\n * returns. Compilation is synchronous and single-threaded, so this dynamic\n * scope needs no async-context machinery: nothing can interleave between the\n * assignment and the `finally` that clears it.\n */\nlet pinnedReadInstant: string | undefined;\n\n/**\n * Compiles `emit` with one shared \"current\" instant.\n *\n * A set operation is a single statement whose operands are compiled\n * independently, so each operand would otherwise sample its own `nowIso()`.\n * Two instants microseconds apart mean the two halves of an `INTERSECT` or\n * `EXCEPT` disagree about whether a row created between them is current — the\n * one thing a compound SELECT, evaluated against one snapshot, must never do.\n *\n * Re-entrant: a nested set operation keeps the outer pin rather than resampling.\n */\nexport function withPinnedReadInstant<T>(emit: () => T): T {\n if (pinnedReadInstant !== undefined) return emit();\n pinnedReadInstant = nowIso();\n try {\n return emit();\n } finally {\n pinnedReadInstant = undefined;\n }\n}\n\n/**\n * The \"current\" valid-time read instant, bound as a parameter — the\n * APPLICATION clock (`nowIso()`), NOT the database clock (`NOW()`).\n *\n * `valid_from` is stamped from the application clock on write, so a \"current\"\n * read must compare against the same clock. Comparing `valid_from` (app clock)\n * against the database `NOW()` would hide a freshly-created row from an\n * immediately-following current read whenever the app server's clock runs\n * ahead of the database server's clock — a read-after-write consistency\n * violation on Postgres (issue #242; SQLite is single-process so it was never\n * exposed). This binds the same clock the facade search-currency filter\n * (`liveNodeIdsSubquery`) and the recorded/logical clock already use, and the\n * same form the `asOf` predicate uses (a bound ISO instant), so it needs no\n * dialect-specific expression.\n *\n * Samples the clock per call unless a {@link withPinnedReadInstant} scope is\n * open, in which case every call in that scope binds the same instant.\n */\nexport function currentReadInstant(): SQL {\n return sql`${pinnedReadInstant ?? nowIso()}`;\n}\n\n/**\n * How a \"current\" valid-time read instant is emitted into compiled SQL:\n *\n * - `\"literal\"` — bound as a concrete value at compile time\n * ({@link currentReadInstant}). The instant is frozen into the compiled\n * statement, so the statement must be recompiled to observe a newer \"now\".\n * - `\"placeholder\"` — bound as a reserved execution-time placeholder\n * ({@link currentReadInstantPlaceholder}). The statement can be compiled\n * once and reused across executions, filling a fresh instant each call.\n *\n * Defaults to `\"literal\"` everywhere except the query builder's compiled\n * template cache, which opts into `\"placeholder\"` so a reused/prepared query\n * never freezes \"now\" the way a cached literal would (the #246 regression).\n */\nexport type ReadInstantMode = \"literal\" | \"placeholder\";\n\n/**\n * Reserved Drizzle placeholder name for the \"current\" valid-time read instant.\n * The query builder's template cache fills it with a fresh application-clock\n * value on every execution. The `__typegraph_` prefix keeps it disjoint from\n * every user `param()` name.\n */\nexport const CURRENT_READ_INSTANT_PLACEHOLDER =\n \"__typegraph_current_read_instant__\";\n\n/**\n * The \"current\" read instant as a reserved execution-time placeholder rather\n * than a frozen value. Compiles to the same SQL text as\n * {@link currentReadInstant} (a bound parameter), but leaves the value unbound\n * so one compiled statement can be reused across executions with a fresh\n * instant filled in per call. See {@link CURRENT_READ_INSTANT_PLACEHOLDER}.\n */\nfunction currentReadInstantPlaceholder(): SQL {\n return sql`${sql.placeholder(CURRENT_READ_INSTANT_PLACEHOLDER)}`;\n}\n\n/** Emits the \"current\" read instant for the requested {@link ReadInstantMode}. */\nexport function currentReadInstantFor(mode: ReadInstantMode): SQL {\n return mode === \"placeholder\" ?\n currentReadInstantPlaceholder()\n : currentReadInstant();\n}\n\n/**\n * Temporal filter options.\n */\nexport type TemporalFilterOptions = Readonly<{\n /** The temporal mode to apply */\n mode: TemporalMode;\n /** Timestamp for asOf queries (required when mode is \"asOf\") */\n asOf?: string | undefined;\n /** Optional table alias prefix for column references */\n tableAlias?: string | undefined;\n /** Optional execution-time current timestamp SQL expression */\n currentTimestamp?: SQL | undefined;\n /** Recorded/system-time timestamp for recorded-pinned reads. */\n recordedAsOf?: string | undefined;\n}>;\n\n/**\n * Compiles a temporal filter to SQL.\n *\n * This is the unified temporal filter function that handles all temporal modes\n * and optional table alias prefixes. It replaces the previous three separate\n * functions (compileTemporalFilter, compileEdgeTemporalFilter, compileNodeTemporalFilter).\n *\n * @param options - Temporal filter configuration\n * @returns SQL clause for the temporal filter\n *\n * @example\n * ```typescript\n * // Without table alias (for CTEs)\n * compileTemporalFilter({ mode: \"current\" })\n * // → deleted_at IS NULL AND (valid_from IS NULL OR ...) AND ...\n *\n * // With table alias (for JOINs)\n * compileTemporalFilter({ mode: \"current\", tableAlias: \"e\" })\n * // → e.deleted_at IS NULL AND (e.valid_from IS NULL OR ...) AND ...\n *\n * // AsOf mode\n * compileTemporalFilter({ mode: \"asOf\", asOf: \"2024-01-01T00:00:00.000Z\" })\n * // → deleted_at IS NULL AND (valid_from IS NULL OR valid_from <= '2024-01-01...') AND ...\n * ```\n */\nexport function compileTemporalFilter(options: TemporalFilterOptions): SQL {\n const { mode, asOf, tableAlias, currentTimestamp, recordedAsOf } = options;\n\n // Build column references with optional prefix\n const prefix = tableAlias ? sql.raw(`${tableAlias}.`) : sql.raw(\"\");\n const deletedAt = sql`${prefix}deleted_at`;\n const validFrom = sql`${prefix}valid_from`;\n const validTo = sql`${prefix}valid_to`;\n\n const validFilter = (() => {\n switch (mode) {\n case \"current\": {\n // When pinned to a recorded instant, \"current\" valid-time means\n // valid-current *as of that recorded instant* — not the wall clock at\n // read time. Pinning here collapses\n // view({mode:'current'}).asOfRecorded(rt) to the diagonal\n // store.asOfRecorded(rt) and stops silently dropping rows that were\n // valid-current when recorded but ended before the read.\n const now =\n recordedAsOf === undefined ?\n (currentTimestamp ?? currentReadInstant())\n : sql`${recordedAsOf}`;\n return sql`${deletedAt} IS NULL AND (${validFrom} IS NULL OR ${validFrom} <= ${now}) AND (${validTo} IS NULL OR ${validTo} > ${now})`;\n }\n\n case \"asOf\": {\n if (asOf === undefined) {\n throw new Error(\n `asOf timestamp is required for temporal mode \"asOf\"`,\n );\n }\n const timestamp = asOf;\n return sql`${deletedAt} IS NULL AND (${validFrom} IS NULL OR ${validFrom} <= ${timestamp}) AND (${validTo} IS NULL OR ${validTo} > ${timestamp})`;\n }\n\n case \"includeEnded\": {\n // Include records that have ended but not been deleted\n return sql`${deletedAt} IS NULL`;\n }\n\n case \"includeTombstones\": {\n // Include everything, no filter\n return sql.raw(\"1=1\");\n }\n }\n })();\n\n if (recordedAsOf === undefined) return validFilter;\n\n const recordedFrom = sql`${prefix}recorded_from`;\n const recordedTo = sql`${prefix}recorded_to`;\n return sql`(${validFilter}) AND ${recordedFrom} <= ${recordedAsOf} AND ${recordedAsOf} < ${recordedTo}`;\n}\n\n/**\n * Extracts temporal options from a query AST.\n *\n * @param ast - Query AST with temporalMode\n * @param tableAlias - Optional table alias for column references\n * @returns TemporalFilterOptions for use with compileTemporalFilter\n */\nexport function extractTemporalOptions(\n ast: {\n temporalMode: { mode: TemporalMode; asOf?: string };\n recordedAsOf?: string;\n },\n tableAlias?: string,\n): TemporalFilterOptions {\n return {\n mode: ast.temporalMode.mode,\n asOf: ast.temporalMode.asOf,\n recordedAsOf: ast.recordedAsOf,\n tableAlias,\n };\n}\n","/**\n * Shared utilities for subquery projection shape and type handling.\n */\nimport { type AggregateExpr, type QueryAst, type ValueType } from \"./ast\";\n\n/**\n * Normalizes a value type by treating \"unknown\" as undefined.\n */\nfunction normalizeValueType(valueType?: ValueType): ValueType | undefined {\n if (valueType === undefined || valueType === \"unknown\") {\n return undefined;\n }\n return valueType;\n}\n\n/**\n * Returns true when the type cannot be compared with IN/NOT IN.\n */\nexport function isUnsupportedInSubqueryValueType(\n valueType?: ValueType,\n): boolean {\n const normalized = normalizeValueType(valueType);\n return (\n normalized === \"array\" ||\n normalized === \"object\" ||\n normalized === \"embedding\"\n );\n}\n\n/**\n * Returns true when two value types are compatible for IN/NOT IN.\n *\n * Unknown types are treated as compatible (deferred to runtime) to preserve\n * flexibility for untyped fields.\n */\nexport function isInSubqueryTypeCompatible(\n left?: ValueType,\n right?: ValueType,\n): boolean {\n const normalizedLeft = normalizeValueType(left);\n const normalizedRight = normalizeValueType(right);\n\n if (normalizedLeft === undefined || normalizedRight === undefined) {\n return true;\n }\n\n return normalizedLeft === normalizedRight;\n}\n\n/**\n * Resolves the value type produced by an aggregate projection.\n */\nfunction getAggregateValueType(\n aggregate: AggregateExpr,\n): ValueType | undefined {\n switch (aggregate.function) {\n case \"count\":\n case \"countDistinct\":\n case \"sum\":\n case \"avg\": {\n return \"number\";\n }\n case \"min\":\n case \"max\": {\n return normalizeValueType(aggregate.field.valueType);\n }\n }\n}\n\n/**\n * Returns effective projected column value types for a subquery.\n *\n * If selective fields are present, they represent the effective projection.\n * Otherwise, falls back to the explicit projection fields.\n */\nfunction getProjectedValueTypes(\n subquery: QueryAst,\n): readonly (ValueType | undefined)[] {\n if (subquery.selectiveFields && subquery.selectiveFields.length > 0) {\n return subquery.selectiveFields.map((field) =>\n normalizeValueType(field.valueType),\n );\n }\n\n return subquery.projection.fields.map((field) => {\n if (field.source.__type === \"aggregate\") {\n return getAggregateValueType(field.source);\n }\n return normalizeValueType(field.source.valueType);\n });\n}\n\n/**\n * Returns the effective number of columns projected by a subquery.\n */\nexport function getSubqueryColumnCount(subquery: QueryAst): number {\n return getProjectedValueTypes(subquery).length;\n}\n\n/**\n * Returns the value type when a subquery projects exactly one column.\n */\nexport function getSingleSubqueryColumnValueType(\n subquery: QueryAst,\n): ValueType | undefined {\n const valueTypes = getProjectedValueTypes(subquery);\n if (valueTypes.length !== 1) {\n return undefined;\n }\n return valueTypes[0];\n}\n","/**\n * Predicate builders for TypeGraph queries.\n *\n * Provides a fluent API for building type-safe predicates.\n */\nimport { type FulltextQueryMode } from \"../backend/types\";\nimport { type NullCheckOp } from \"../core/types\";\nimport { ConfigurationError, UnsupportedPredicateError } from \"../errors\";\nimport {\n type ArrayOp,\n type ArrayPredicate,\n type BetweenPredicate,\n type ComparisonOp,\n type ComparisonPredicate,\n type ExistsSubquery,\n type FieldRef,\n type FulltextMatchPredicate,\n type InSubquery,\n type LiteralValue,\n type NullPredicate,\n type ObjectOp,\n type ObjectPredicate,\n type ParameterRef,\n type PredicateExpression,\n type QueryAst,\n type StringOp,\n type StringPredicate,\n type ValueType,\n type VectorMetricType,\n type VectorSimilarityPredicate,\n} from \"./ast\";\nimport { CURRENT_READ_INSTANT_PLACEHOLDER } from \"./compiler/temporal\";\nimport { resolveFieldTypeInfoAtJsonPointer } from \"./field-type-info\";\nimport {\n joinJsonPointers,\n type JsonPointer,\n jsonPointer,\n type JsonPointerInput,\n type JsonPointerSegment,\n normalizeJsonPointer,\n type ResolveJsonPointer,\n type ResolveJsonPointerSegments,\n} from \"./json-pointer\";\nimport { type FieldTypeInfo } from \"./schema-introspector\";\nimport {\n getSingleSubqueryColumnValueType,\n getSubqueryColumnCount,\n isInSubqueryTypeCompatible,\n isUnsupportedInSubqueryValueType,\n} from \"./subquery-utils\";\n\n// ============================================================\n// Predicate Builder\n// ============================================================\n\n/**\n * A chainable predicate that can be combined with AND/OR.\n */\nexport type Predicate = Readonly<{\n __expr: PredicateExpression;\n and: (other: Predicate) => Predicate;\n or: (other: Predicate) => Predicate;\n not: () => Predicate;\n}>;\n\n/**\n * Creates a predicate wrapper with chainable methods.\n */\nfunction predicate(expr: PredicateExpression): Predicate {\n return {\n __expr: expr,\n and: (other: Predicate): Predicate =>\n predicate({\n __type: \"and\",\n predicates: [expr, other.__expr],\n }),\n or: (other: Predicate): Predicate =>\n predicate({\n __type: \"or\",\n predicates: [expr, other.__expr],\n }),\n not: (): Predicate =>\n predicate({\n __type: \"not\",\n predicate: expr,\n }),\n };\n}\n\n// ============================================================\n// Parameter References\n// ============================================================\n\n/**\n * Creates a named parameter reference for prepared queries.\n *\n * Use with `query.prepare()` to create reusable parameterized queries.\n * Only supported in scalar comparison positions (eq, neq, gt, etc.),\n * string operations, and between bounds. Not supported in `in()`/`notIn()`.\n *\n * @example\n * ```typescript\n * const prepared = store.query()\n * .from(\"Person\", \"p\")\n * .whereNode(\"p\", (p) => p.name.eq(param(\"name\")))\n * .select((ctx) => ctx.p)\n * .prepare();\n *\n * const results = await prepared.execute({ name: \"Alice\" });\n * ```\n */\n// eslint-disable-next-line unicorn/name-replacements -- concise public API\nexport function param(name: string): ParameterRef {\n // The compiled template fills this reserved placeholder with the current read\n // instant, so a user param of the same name would be silently overwritten by\n // the wall clock (see fillTemplateParams). Reject it up front.\n if (name === CURRENT_READ_INSTANT_PLACEHOLDER) {\n throw new ConfigurationError(\n `Parameter name \"${name}\" is reserved for internal use`,\n { parameterName: name },\n );\n }\n return { __type: \"parameter\", name };\n}\n\n/**\n * Type guard for ParameterRef values.\n */\nexport function isParameterRef(value: unknown): value is ParameterRef {\n if (typeof value !== \"object\" || value === null) return false;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- runtime guard for untyped input\n return (value as ParameterRef).__type === \"parameter\";\n}\n\n// ============================================================\n// Field Builder\n// ============================================================\n\n/**\n * A typed field builder for creating predicates.\n */\ntype FieldBuilder<T> =\n [T] extends [string] ? StringFieldBuilder\n : [T] extends [number] ? NumberFieldBuilder\n : [T] extends [boolean] ? BooleanFieldBuilder\n : [T] extends [Date] ? DateFieldBuilder\n : [T] extends [readonly (infer U)[]] ? ArrayFieldBuilder<U>\n : [T] extends [Record<string, unknown>] ? ObjectFieldBuilder<T>\n : BaseFieldBuilder;\n\n/**\n * Base field operations available on all types.\n */\ntype BaseFieldBuilder = Readonly<{\n eq: (value: unknown) => Predicate;\n neq: (value: unknown) => Predicate;\n isNull: () => Predicate;\n isNotNull: () => Predicate;\n in: (values: readonly unknown[]) => Predicate;\n notIn: (values: readonly unknown[]) => Predicate;\n}>;\n\n/**\n * Options for the `$fulltext.matches()` predicate.\n *\n * Note the term glossary used throughout TypeGraph search:\n * - **`k`** (the positional argument on `.matches(query, k)`) is the\n * per-predicate top-k cap applied inside the fulltext CTE.\n * - **`limit`** (on store-level `search.fulltext` / `search.hybrid` and\n * on the query builder) is the final result count returned to the\n * caller after any fusion.\n */\ntype MatchesOptions = Readonly<{\n /**\n * Parse mode for the query string. Default: \"websearch\".\n *\n * - \"websearch\": Google-style syntax (quoted phrases, `-excluded`, `OR`).\n * Postgres: `websearch_to_tsquery`. SQLite: translated to FTS5 MATCH.\n * - \"phrase\": treats the whole query as a phrase.\n * - \"plain\": splits on whitespace and ANDs terms.\n * - \"raw\": dialect-native syntax passed through unchanged.\n */\n mode?: FulltextQueryMode;\n /**\n * Language override for query parsing. Default: the kind's declared\n * language when every kind in the alias shares one (a plan-time\n * constant, so PostgreSQL can serve the match from the GIN index);\n * mixed-language subclass aliases fall back to the per-row language\n * column.\n */\n language?: string;\n /** Minimum relevance score to include. */\n minScore?: number;\n}>;\n\n/**\n * String-specific field operations.\n *\n * Fulltext match is exposed on `n.$fulltext.matches(...)` at the node\n * level (gated by `searchable()` declarations in the schema), not on\n * individual string fields.\n */\ntype StringFieldBuilder = BaseFieldBuilder &\n Readonly<{\n gt: (value: string | ParameterRef) => Predicate;\n gte: (value: string | ParameterRef) => Predicate;\n lt: (value: string | ParameterRef) => Predicate;\n lte: (value: string | ParameterRef) => Predicate;\n contains: (pattern: string | ParameterRef) => Predicate;\n startsWith: (pattern: string | ParameterRef) => Predicate;\n endsWith: (pattern: string | ParameterRef) => Predicate;\n like: (pattern: string | ParameterRef) => Predicate;\n ilike: (pattern: string | ParameterRef) => Predicate;\n }>;\n\n/**\n * Number-specific field operations.\n */\ntype NumberFieldBuilder = BaseFieldBuilder &\n Readonly<{\n gt: (value: number | ParameterRef) => Predicate;\n gte: (value: number | ParameterRef) => Predicate;\n lt: (value: number | ParameterRef) => Predicate;\n lte: (value: number | ParameterRef) => Predicate;\n between: (\n lower: number | ParameterRef,\n upper: number | ParameterRef,\n ) => Predicate;\n }>;\n\n/**\n * Boolean-specific field operations.\n */\ntype BooleanFieldBuilder = BaseFieldBuilder;\n\n/**\n * Date-specific field operations.\n */\ntype DateFieldBuilder = BaseFieldBuilder &\n Readonly<{\n gt: (value: Date | string | ParameterRef) => Predicate;\n gte: (value: Date | string | ParameterRef) => Predicate;\n lt: (value: Date | string | ParameterRef) => Predicate;\n lte: (value: Date | string | ParameterRef) => Predicate;\n between: (\n lower: Date | string | ParameterRef,\n upper: Date | string | ParameterRef,\n ) => Predicate;\n }>;\n\ntype ScalarValue = string | number | boolean | Date;\n\ntype ArrayPredicateOps<T> =\n [T] extends [ScalarValue] ?\n Readonly<{\n /** Check if array contains a specific value */\n contains: (value: T) => Predicate;\n /** Check if array contains all specified values */\n containsAll: (values: readonly T[]) => Predicate;\n /** Check if array contains any of the specified values (overlaps) */\n containsAny: (values: readonly T[]) => Predicate;\n }>\n : Readonly<Record<string, never>>;\n\n/**\n * Array-specific field operations.\n */\ntype ArrayFieldBuilder<T = unknown> = BaseFieldBuilder &\n Readonly<{\n /** Check if array is empty */\n isEmpty: () => Predicate;\n /** Check if array is not empty */\n isNotEmpty: () => Predicate;\n /** Check if array length equals a value */\n lengthEq: (length: number) => Predicate;\n /** Check if array length is greater than a value */\n lengthGt: (length: number) => Predicate;\n /** Check if array length is greater than or equal to a value */\n lengthGte: (length: number) => Predicate;\n /** Check if array length is less than a value */\n lengthLt: (length: number) => Predicate;\n /** Check if array length is less than or equal to a value */\n lengthLte: (length: number) => Predicate;\n }> &\n ArrayPredicateOps<T>;\n\n/**\n * Object/JSON-specific field operations.\n */\ntype ResolvedPointerInput<T, Pointer> =\n Pointer extends string ? ResolveJsonPointer<T, Pointer>\n : Pointer extends readonly JsonPointerSegment[] ?\n ResolveJsonPointerSegments<T, Pointer>\n : unknown;\n\n/**\n * Resolves the type of a nested key access on an object type.\n * Returns ObjectFieldBuilder for nested objects, FieldBuilder for scalars.\n */\ntype NestedFieldBuilder<T, K extends keyof T> =\n NonNullable<T[K]> extends Record<string, unknown> ?\n ObjectFieldBuilder<NonNullable<T[K]>>\n : FieldBuilder<T[K]>;\n\ntype ObjectFieldBuilder<\n T extends Record<string, unknown> = Record<string, unknown>,\n> = BaseFieldBuilder &\n Readonly<{\n /** Access a nested field by key for fluent chaining */\n get: <K extends keyof T & string>(key: K) => NestedFieldBuilder<T, K>;\n /** Check if object has a specific key at root level */\n hasKey: (key: string) => Predicate;\n /** Check if object has a nested path (JSON Pointer) */\n hasPath: <P extends JsonPointerInput<T>>(pointer: P) => Predicate;\n /** Check if value at path equals a value */\n pathEquals: <P extends JsonPointerInput<T>>(\n pointer: P,\n value: string | number | boolean | Date,\n ) => Predicate;\n /** Check if value at path (array) contains a value */\n pathContains: <P extends JsonPointerInput<T>>(\n pointer: P,\n value: string | number | boolean | Date,\n ) => Predicate;\n /** Check if value at path is null */\n pathIsNull: <P extends JsonPointerInput<T>>(pointer: P) => Predicate;\n /** Check if value at path is not null */\n pathIsNotNull: <P extends JsonPointerInput<T>>(pointer: P) => Predicate;\n /** Access a nested field to get a typed field builder */\n field: <P extends JsonPointerInput<T>>(\n pointer: P,\n ) => FieldBuilder<ResolvedPointerInput<T, P>>;\n }>;\n\n/**\n * Options for the similarTo method.\n */\nexport type SimilarToOptions = Readonly<{\n /** Similarity metric to use. Default: \"cosine\" */\n metric?: VectorMetricType;\n /**\n * Minimum similarity score to include results.\n * For cosine: 0-1 where 1 is identical.\n * For L2: maximum distance to include.\n * For inner_product: minimum inner product value.\n */\n minScore?: number;\n /**\n * Opt into approximate retrieval: each declaring kind's candidates come\n * from the engine's native ANN structure (pgvector HNSW/IVFFlat scans,\n * vec0 `MATCH … k=`, libSQL `vector_top_k`) instead of an exact\n * distance scan. This is a SEMANTIC change — results are subject to the\n * index's recall, and predicates composed alongside constrain the ANN\n * candidate set (exact on pgvector/vec0; bounded by over-fetch on\n * libSQL). A slot declared with `indexType: \"none\"` falls back to the\n * exact scan. Default: exact.\n */\n approximate?: boolean;\n}>;\n\n/**\n * Embedding-specific field operations for vector similarity search.\n */\ntype EmbeddingFieldBuilder = BaseFieldBuilder &\n Readonly<{\n /**\n * Find nodes with similar embeddings.\n * Returns results ordered by similarity (most similar first).\n *\n * @param queryEmbedding - The embedding vector to compare against\n * @param k - Maximum number of results to return (top-k)\n * @param options - Optional configuration (metric, minScore)\n *\n * @example\n * ```typescript\n * store.query()\n * .from(\"Document\", \"d\")\n * .whereNode(\"d\", (d) =>\n * d.embedding.similarTo(queryVector, 10, { metric: \"cosine\" })\n * )\n * .select((ctx) => ({ doc: ctx.d }))\n * .execute()\n * ```\n */\n similarTo: (\n queryEmbedding: readonly number[],\n k: number,\n options?: SimilarToOptions,\n ) => Predicate;\n }>;\n\n// ============================================================\n// Field Builder Factory\n// ============================================================\n\n/**\n * Creates a field reference.\n */\ntype FieldRefOptions = Readonly<{\n jsonPointer?: JsonPointer | undefined;\n valueType?: ValueType | undefined;\n elementType?: ValueType | undefined;\n}>;\n\nexport function fieldRef(\n alias: string,\n path: readonly string[],\n options?: FieldRefOptions,\n): FieldRef {\n return {\n __type: \"field_ref\",\n alias,\n path,\n ...(options?.jsonPointer !== undefined && {\n jsonPointer: options.jsonPointer,\n }),\n ...(options?.valueType !== undefined && { valueType: options.valueType }),\n ...(options?.elementType !== undefined && {\n elementType: options.elementType,\n }),\n };\n}\n\nfunction coerceLiteralValue(value: unknown): string | number | boolean | Date {\n if (value instanceof Date) {\n return value;\n }\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n throw new Error(`Unsupported literal value type: ${typeof value}`);\n}\n\nfunction inferLiteralValueType(value: string | number | boolean): ValueType {\n if (typeof value === \"string\") {\n return \"string\";\n }\n if (typeof value === \"number\") {\n return \"number\";\n }\n return \"boolean\";\n}\n\n/**\n * Creates a literal value.\n */\nfunction literal(value: string | number | boolean | Date): LiteralValue {\n if (value instanceof Date) {\n return { __type: \"literal\", value: value.toISOString(), valueType: \"date\" };\n }\n const valueType = inferLiteralValueType(value);\n return {\n __type: \"literal\",\n value,\n valueType,\n };\n}\n\n/**\n * Creates a comparison predicate.\n */\nfunction comparison(\n op: ComparisonOp,\n field: FieldRef,\n value: unknown,\n): Predicate {\n if (isParameterRef(value)) {\n const expr: ComparisonPredicate = {\n __type: \"comparison\",\n op,\n left: field,\n right: value,\n };\n return predicate(expr);\n }\n const coercedValue = coerceLiteralValue(value);\n const expr: ComparisonPredicate = {\n __type: \"comparison\",\n op,\n left: field,\n right: literal(coercedValue),\n };\n return predicate(expr);\n}\n\n/**\n * Creates an IN comparison predicate.\n */\nfunction inComparison(\n op: \"in\" | \"notIn\",\n field: FieldRef,\n values: readonly unknown[],\n): Predicate {\n const literals = values.map((value) => literal(coerceLiteralValue(value)));\n const expr: ComparisonPredicate = {\n __type: \"comparison\",\n op,\n left: field,\n right: literals,\n };\n return predicate(expr);\n}\n\n/**\n * Creates a string operation predicate.\n */\nfunction stringOp(\n op: StringOp,\n field: FieldRef,\n pattern: string | ParameterRef,\n): Predicate {\n if (isParameterRef(pattern)) {\n const expr: StringPredicate = {\n __type: \"string_op\",\n op,\n field,\n pattern,\n };\n return predicate(expr);\n }\n const expr: StringPredicate = {\n __type: \"string_op\",\n op,\n field,\n pattern,\n };\n return predicate(expr);\n}\n\n/**\n * Creates a null check predicate.\n */\nfunction nullCheck(op: NullCheckOp, field: FieldRef): Predicate {\n const expr: NullPredicate = {\n __type: \"null_check\",\n op,\n field,\n };\n return predicate(expr);\n}\n\n/**\n * Creates a between predicate.\n */\nfunction between(\n field: FieldRef,\n lower: string | number | boolean | Date | ParameterRef,\n upper: string | number | boolean | Date | ParameterRef,\n): Predicate {\n const expr: BetweenPredicate = {\n __type: \"between\",\n field,\n lower: isParameterRef(lower) ? lower : literal(lower),\n upper: isParameterRef(upper) ? upper : literal(upper),\n };\n return predicate(expr);\n}\n\n/**\n * Creates a base field builder with common operations.\n */\nfunction baseFieldBuilder(field: FieldRef): BaseFieldBuilder {\n return {\n eq: (value) => comparison(\"eq\", field, value),\n neq: (value) => comparison(\"neq\", field, value),\n isNull: () => nullCheck(\"isNull\", field),\n isNotNull: () => nullCheck(\"isNotNull\", field),\n in: (values) => inComparison(\"in\", field, values),\n notIn: (values) => inComparison(\"notIn\", field, values),\n };\n}\n\n/**\n * Creates a string field builder.\n *\n * Fulltext match is not a string-field operation — use\n * `n.$fulltext.matches(...)` at the node level. `searchable()`\n * declarations determine which node kinds expose `$fulltext`.\n */\nexport function stringField(field: FieldRef): StringFieldBuilder {\n return {\n ...baseFieldBuilder(field),\n gt: (value) => comparison(\"gt\", field, value),\n gte: (value) => comparison(\"gte\", field, value),\n lt: (value) => comparison(\"lt\", field, value),\n lte: (value) => comparison(\"lte\", field, value),\n contains: (pattern) => stringOp(\"contains\", field, pattern),\n startsWith: (pattern) => stringOp(\"startsWith\", field, pattern),\n endsWith: (pattern) => stringOp(\"endsWith\", field, pattern),\n like: (pattern) => stringOp(\"like\", field, pattern),\n ilike: (pattern) => stringOp(\"ilike\", field, pattern),\n };\n}\n\n/**\n * Default top-k for `$fulltext.matches()` when the caller does not pass\n * one. Large enough to leave headroom for downstream `.and()` filters,\n * small enough to keep latency reasonable on any dialect.\n */\nconst DEFAULT_FULLTEXT_MATCH_K = 50;\n\n/**\n * Node-level fulltext accessor. Always present on the `NodeAccessor`\n * type — a runtime check throws a clear error if the node kind has no\n * `searchable()` fields. `k` is the top-k cap applied inside the\n * fulltext CTE; defaults to `DEFAULT_FULLTEXT_MATCH_K`. Use a larger\n * value when feeding the result into RRF (`.fuseWith()` /\n * `store.search.hybrid()`).\n */\nexport type FulltextAccessor = Readonly<{\n matches: (query: string, k?: number, options?: MatchesOptions) => Predicate;\n}>;\n\n/**\n * Creates a node-level fulltext accessor. The runtime check throws for\n * aliases whose node kind has no `searchable()` content, catching the\n * case where the field tag was dropped (e.g. by a schema refactor)\n * after the query was written.\n */\nexport function createFulltextAccessor(\n alias: string,\n hasSearchableField: () => boolean,\n): FulltextAccessor {\n return {\n matches: (query, k, options) => {\n if (!hasSearchableField()) {\n throw new UnsupportedPredicateError(\n `Cannot call .$fulltext.matches() on alias \"${alias}\" — its ` +\n `node kind has no fields declared with searchable(). Add at ` +\n `least one: \\`title: searchable({ language: \"english\" })\\`.`,\n );\n }\n return fulltextMatch(\n fieldRef(alias, [\"$fulltext\"]),\n query,\n k ?? DEFAULT_FULLTEXT_MATCH_K,\n options,\n );\n },\n };\n}\n\n/**\n * Creates a fulltext match predicate.\n */\nfunction fulltextMatch(\n field: FieldRef,\n query: string,\n limit: number,\n options?: MatchesOptions,\n): Predicate {\n if (!Number.isFinite(limit) || limit <= 0) {\n throw new UnsupportedPredicateError(\n `matches() limit must be a positive finite number, got ${String(limit)}`,\n );\n }\n const expr: FulltextMatchPredicate = {\n __type: \"fulltext_match\",\n field,\n query,\n mode: options?.mode ?? \"websearch\",\n limit,\n ...(options?.language === undefined ? {} : { language: options.language }),\n ...(options?.minScore === undefined ? {} : { minScore: options.minScore }),\n };\n return predicate(expr);\n}\n\n/**\n * Creates a number field builder.\n */\nexport function numberField(field: FieldRef): NumberFieldBuilder {\n return {\n ...baseFieldBuilder(field),\n gt: (value) => comparison(\"gt\", field, value),\n gte: (value) => comparison(\"gte\", field, value),\n lt: (value) => comparison(\"lt\", field, value),\n lte: (value) => comparison(\"lte\", field, value),\n between: (lower, upper) => between(field, lower, upper),\n };\n}\n\n/**\n * Creates a date field builder.\n */\nexport function dateField(field: FieldRef): DateFieldBuilder {\n return {\n ...baseFieldBuilder(field),\n gt: (value) => comparison(\"gt\", field, value),\n gte: (value) => comparison(\"gte\", field, value),\n lt: (value) => comparison(\"lt\", field, value),\n lte: (value) => comparison(\"lte\", field, value),\n between: (lower, upper) => between(field, lower, upper),\n };\n}\n\n/**\n * Creates a base field builder (for booleans, enums, and unknown types).\n * Only provides the fundamental operations: eq, neq, isNull, isNotNull, in, notIn.\n */\nexport function baseField(field: FieldRef): BaseFieldBuilder {\n return baseFieldBuilder(field);\n}\n\n/**\n * Creates an array operation predicate.\n */\nfunction arrayOp(\n op: ArrayOp,\n field: FieldRef,\n values?: readonly unknown[],\n length?: number,\n): Predicate {\n const expr: ArrayPredicate = {\n __type: \"array_op\",\n op,\n field,\n ...(values !== undefined && {\n values: values.map((value) => literal(coerceLiteralValue(value))),\n }),\n ...(length !== undefined && { length }),\n };\n return predicate(expr);\n}\n\n/**\n * Creates an array field builder.\n */\nexport function arrayField<T = unknown>(field: FieldRef): ArrayFieldBuilder<T> {\n // The type assertion is needed because ArrayFieldBuilder conditionally includes\n // contains/containsAll/containsAny based on whether T extends ScalarValue.\n // At runtime we always provide them - they just won't type-check if T isn't scalar.\n return {\n ...baseFieldBuilder(field),\n contains: (value: T) => arrayOp(\"contains\", field, [value]),\n containsAll: (values: readonly T[]) =>\n arrayOp(\"containsAll\", field, values),\n containsAny: (values: readonly T[]) =>\n arrayOp(\"containsAny\", field, values),\n isEmpty: () => arrayOp(\"isEmpty\", field),\n isNotEmpty: () => arrayOp(\"isNotEmpty\", field),\n lengthEq: (length: number) => arrayOp(\"lengthEq\", field, undefined, length),\n lengthGt: (length: number) => arrayOp(\"lengthGt\", field, undefined, length),\n lengthGte: (length: number) =>\n arrayOp(\"lengthGte\", field, undefined, length),\n lengthLt: (length: number) => arrayOp(\"lengthLt\", field, undefined, length),\n lengthLte: (length: number) =>\n arrayOp(\"lengthLte\", field, undefined, length),\n } as unknown as ArrayFieldBuilder<T>;\n}\n\n/**\n * Creates a vector similarity predicate.\n */\nfunction vectorSimilarity(\n field: FieldRef,\n queryEmbedding: readonly number[],\n limit: number,\n options?: SimilarToOptions,\n): Predicate {\n const expr: VectorSimilarityPredicate = {\n __type: \"vector_similarity\",\n field,\n queryEmbedding,\n // Leave metric unset when the caller didn't specify one, so the compiler\n // resolves the field's declared metric per kind. Defaulting to \"cosine\"\n // here would mis-rank l2/inner_product fields and bypass their ANN index.\n ...(options?.metric !== undefined && { metric: options.metric }),\n limit,\n ...(options?.minScore !== undefined && { minScore: options.minScore }),\n ...(options?.approximate !== undefined && {\n approximate: options.approximate,\n }),\n };\n return predicate(expr);\n}\n\n/**\n * Creates an embedding field builder for vector similarity search.\n */\nexport function embeddingField(field: FieldRef): EmbeddingFieldBuilder {\n return {\n ...baseFieldBuilder(field),\n similarTo: (queryEmbedding, k, options) =>\n vectorSimilarity(field, queryEmbedding, k, options),\n };\n}\n\nexport function buildFieldBuilderForTypeInfo(\n field: FieldRef,\n typeInfo: FieldTypeInfo | undefined,\n): BaseFieldBuilder {\n if (!typeInfo) {\n return baseField(field);\n }\n\n switch (typeInfo.valueType) {\n case \"string\": {\n return stringField(field);\n }\n case \"number\": {\n return numberField(field);\n }\n case \"boolean\": {\n return baseField(field);\n }\n case \"date\": {\n return dateField(field);\n }\n case \"array\": {\n return arrayField(field);\n }\n case \"object\": {\n return objectField(field, { typeInfo });\n }\n case \"embedding\": {\n return embeddingField(field);\n }\n case \"unknown\": {\n return baseField(field);\n }\n }\n}\n\nfunction resolvePointerTypeInfo(\n typeInfo: FieldTypeInfo | undefined,\n pointer: JsonPointer,\n): FieldTypeInfo | undefined {\n return resolveFieldTypeInfoAtJsonPointer(typeInfo, pointer);\n}\n\n/**\n * Creates an object operation predicate.\n */\ntype ObjectPredicateOptions = Readonly<{\n valueType?: ValueType;\n elementType?: ValueType;\n}>;\n\nfunction objectOp(\n op: ObjectOp,\n field: FieldRef,\n pointer: JsonPointer,\n value?: unknown,\n options?: ObjectPredicateOptions,\n): Predicate {\n const expr: ObjectPredicate = {\n __type: \"object_op\",\n op,\n field,\n pointer,\n ...(value !== undefined && {\n value: literal(coerceLiteralValue(value)),\n }),\n ...(options?.valueType !== undefined && { valueType: options.valueType }),\n ...(options?.elementType !== undefined && {\n elementType: options.elementType,\n }),\n };\n return predicate(expr);\n}\n\n/**\n * Creates an object/JSON field builder.\n */\ntype ObjectFieldOptions = Readonly<{\n typeInfo?: FieldTypeInfo;\n}>;\n\nexport function objectField<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(field: FieldRef, options?: ObjectFieldOptions): ObjectFieldBuilder<T> {\n const basePointer = field.jsonPointer;\n\n return {\n ...baseFieldBuilder(field),\n get: <K extends keyof T & string>(key: K) => {\n const pointer = jsonPointer([key]);\n const nestedPointer = joinJsonPointers(basePointer, pointer);\n const resolved = resolvePointerTypeInfo(options?.typeInfo, pointer);\n const nestedRef = fieldRef(field.alias, field.path, {\n jsonPointer: nestedPointer,\n ...(resolved?.valueType !== undefined && {\n valueType: resolved.valueType,\n }),\n ...(resolved?.elementType !== undefined && {\n elementType: resolved.elementType,\n }),\n });\n return buildFieldBuilderForTypeInfo(nestedRef, resolved) as ReturnType<\n ObjectFieldBuilder<T>[\"get\"]\n >;\n },\n hasKey: (key) => {\n const pointer = jsonPointer([key]);\n resolvePointerTypeInfo(options?.typeInfo, pointer);\n return objectOp(\"hasKey\", field, pointer);\n },\n hasPath: <P extends JsonPointerInput<T>>(pointer: P) => {\n const normalized = normalizeJsonPointer(pointer as JsonPointerInput<T>);\n resolvePointerTypeInfo(options?.typeInfo, normalized);\n return objectOp(\"hasPath\", field, normalized);\n },\n pathEquals: <P extends JsonPointerInput<T>>(\n pointer: P,\n value: string | number | boolean | Date,\n ) => {\n const normalized = normalizeJsonPointer(pointer as JsonPointerInput<T>);\n const resolved = resolvePointerTypeInfo(options?.typeInfo, normalized);\n if (\n resolved &&\n (resolved.valueType === \"array\" || resolved.valueType === \"object\")\n ) {\n throw new Error(\"pathEquals is only supported for scalar JSON values\");\n }\n const predicateOptions: ObjectPredicateOptions | undefined =\n resolved?.valueType === undefined ?\n undefined\n : { valueType: resolved.valueType };\n return objectOp(\"pathEquals\", field, normalized, value, predicateOptions);\n },\n pathContains: <P extends JsonPointerInput<T>>(\n pointer: P,\n value: string | number | boolean | Date,\n ) => {\n const normalized = normalizeJsonPointer(pointer as JsonPointerInput<T>);\n const resolved = resolvePointerTypeInfo(options?.typeInfo, normalized);\n if (resolved && resolved.valueType !== \"array\") {\n throw new Error(\"pathContains is only supported for JSON array values\");\n }\n const predicateOptions: ObjectPredicateOptions | undefined =\n resolved?.elementType === undefined ?\n undefined\n : { elementType: resolved.elementType };\n return objectOp(\n \"pathContains\",\n field,\n normalized,\n value,\n predicateOptions,\n );\n },\n pathIsNull: <P extends JsonPointerInput<T>>(pointer: P) => {\n const normalized = normalizeJsonPointer(pointer as JsonPointerInput<T>);\n const resolved = resolvePointerTypeInfo(options?.typeInfo, normalized);\n const predicateOptions: ObjectPredicateOptions | undefined =\n resolved?.valueType === undefined ?\n undefined\n : { valueType: resolved.valueType };\n return objectOp(\n \"pathIsNull\",\n field,\n normalized,\n undefined,\n predicateOptions,\n );\n },\n pathIsNotNull: <P extends JsonPointerInput<T>>(pointer: P) => {\n const normalized = normalizeJsonPointer(pointer as JsonPointerInput<T>);\n const resolved = resolvePointerTypeInfo(options?.typeInfo, normalized);\n const predicateOptions: ObjectPredicateOptions | undefined =\n resolved?.valueType === undefined ?\n undefined\n : { valueType: resolved.valueType };\n return objectOp(\n \"pathIsNotNull\",\n field,\n normalized,\n undefined,\n predicateOptions,\n );\n },\n field: <P extends JsonPointerInput<T>>(pointer: P) => {\n const normalized = normalizeJsonPointer(pointer as JsonPointerInput<T>);\n const nestedPointer = joinJsonPointers(basePointer, normalized);\n const resolved = resolvePointerTypeInfo(options?.typeInfo, normalized);\n const nestedRef = fieldRef(field.alias, field.path, {\n jsonPointer: nestedPointer,\n ...(resolved?.valueType !== undefined && {\n valueType: resolved.valueType,\n }),\n ...(resolved?.elementType !== undefined && {\n elementType: resolved.elementType,\n }),\n });\n return buildFieldBuilderForTypeInfo(nestedRef, resolved) as FieldBuilder<\n ResolvedPointerInput<T, P>\n >;\n },\n };\n}\n\n// ============================================================\n// Subquery Predicates\n// ============================================================\n\n/**\n * Creates an EXISTS subquery predicate.\n * Returns true if the subquery returns at least one row.\n *\n * @param subquery - The subquery AST to check for existence\n *\n * @example\n * ```typescript\n * // Find persons who have at least one order\n * query\n * .from(\"Person\", \"p\")\n * .whereNode(\"p\", () =>\n * exists(\n * query.from(\"Order\", \"o\")\n * .whereNode(\"o\", (o) => o.customerId.eq(field(\"p.id\")))\n * .select((ctx) => ({ id: ctx.o.id }))\n * .toAst()\n * )\n * )\n * ```\n */\nexport function exists(subquery: QueryAst): Predicate {\n const expr: ExistsSubquery = {\n __type: \"exists\",\n subquery,\n negated: false,\n };\n return predicate(expr);\n}\n\n/**\n * Creates a NOT EXISTS subquery predicate.\n * Returns true if the subquery returns no rows.\n *\n * @param subquery - The subquery AST to check for non-existence\n */\nexport function notExists(subquery: QueryAst): Predicate {\n const expr: ExistsSubquery = {\n __type: \"exists\",\n subquery,\n negated: true,\n };\n return predicate(expr);\n}\n\n/**\n * Creates an IN subquery predicate.\n * Returns true if the field value is in the subquery results.\n *\n * @param field - The field to check\n * @param subquery - The subquery AST that returns a single column\n *\n * @example\n * ```typescript\n * // Find persons whose ID is in the VIP list\n * query\n * .from(\"Person\", \"p\")\n * .where(() =>\n * inSubquery(\n * fieldRef(\"p\", [\"id\"]),\n * query.from(\"VIPMember\", \"v\")\n * .aggregate({\n * id: fieldRef(\"v\", [\"props\", \"personId\"], { valueType: \"string\" }),\n * })\n * .toAst()\n * )\n * )\n * ```\n */\nexport function inSubquery(field: FieldRef, subquery: QueryAst): Predicate {\n assertSingleColumnSubquery(subquery);\n assertCompatibleSubqueryValueTypes(field, subquery);\n const expr: InSubquery = {\n __type: \"in_subquery\",\n field,\n subquery,\n negated: false,\n };\n return predicate(expr);\n}\n\n/**\n * Creates a NOT IN subquery predicate.\n * Returns true if the field value is not in the subquery results.\n *\n * @param field - The field to check\n * @param subquery - The subquery AST that returns a single column\n */\nexport function notInSubquery(field: FieldRef, subquery: QueryAst): Predicate {\n assertSingleColumnSubquery(subquery);\n assertCompatibleSubqueryValueTypes(field, subquery);\n const expr: InSubquery = {\n __type: \"in_subquery\",\n field,\n subquery,\n negated: true,\n };\n return predicate(expr);\n}\n\n/**\n * Ensures IN/NOT IN subqueries project exactly one column.\n */\nfunction assertSingleColumnSubquery(subquery: QueryAst): void {\n const columnCount = getSubqueryColumnCount(subquery);\n if (columnCount === 1) return;\n\n throw new UnsupportedPredicateError(\n `IN/NOT IN subquery must project exactly 1 column, but got ${columnCount}`,\n { subqueryColumnCount: columnCount },\n {\n suggestion:\n \"Use aggregate() with exactly one projected field for scalar IN/NOT IN subqueries.\",\n },\n );\n}\n\n/**\n * Ensures IN/NOT IN subquery and field value types are compatible when known.\n */\nfunction assertCompatibleSubqueryValueTypes(\n field: FieldRef,\n subquery: QueryAst,\n): void {\n const fieldValueType = field.valueType;\n const subqueryValueType = getSingleSubqueryColumnValueType(subquery);\n const resolvedValueType = fieldValueType ?? subqueryValueType;\n\n if (isUnsupportedInSubqueryValueType(resolvedValueType)) {\n throw new UnsupportedPredicateError(\n `IN/NOT IN subquery does not support ${String(resolvedValueType)} values`,\n { valueType: resolvedValueType },\n {\n suggestion:\n \"Use scalar fields (string/number/boolean/date) in IN/NOT IN predicates.\",\n },\n );\n }\n\n if (isInSubqueryTypeCompatible(fieldValueType, subqueryValueType)) {\n return;\n }\n\n throw new UnsupportedPredicateError(\n `IN/NOT IN type mismatch: field type \"${String(fieldValueType)}\" does not match subquery column type \"${String(subqueryValueType)}\"`,\n {\n fieldValueType,\n subqueryValueType,\n },\n );\n}\n","/**\n * Predicate Expression Compilation\n *\n * Compiles predicate AST nodes to SQL using dialect adapters.\n * Handles comparisons, string operations, null checks, array/object predicates,\n * and subqueries.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport { UnsupportedPredicateError } from \"../../errors\";\nimport {\n type ArrayPredicate,\n type ExistsSubquery,\n type FieldRef,\n type FulltextMatchPredicate,\n type InSubquery,\n type LiteralValue,\n type ObjectPredicate,\n type ParameterRef,\n type PredicateExpression,\n type QueryAst,\n type ValueType,\n type VectorSimilarityPredicate,\n} from \"../ast\";\nimport {\n LIKE_ESCAPE_CHARACTER,\n likeEscapeClause,\n} from \"../dialect/like-escape\";\nimport { type DialectAdapter } from \"../dialect/types\";\nimport { type VectorStrategy } from \"../dialect/vector-strategy\";\nimport {\n joinJsonPointers,\n type JsonPointer,\n jsonPointer,\n} from \"../json-pointer\";\nimport { isParameterRef } from \"../predicates\";\nimport {\n getSingleSubqueryColumnValueType,\n getSubqueryColumnCount,\n isInSubqueryTypeCompatible,\n isUnsupportedInSubqueryValueType,\n} from \"../subquery-utils\";\nimport { type SqlSchema, type VectorSlotMap } from \"./schema\";\nimport { type ReadInstantMode } from \"./temporal\";\n\nconst COMPARISON_OP_SQL: Record<string, string> = {\n eq: \"=\",\n neq: \"!=\",\n gt: \">\",\n gte: \">=\",\n lt: \"<\",\n lte: \"<=\",\n};\n\n// ============================================================\n// Field Reference Compilation\n// ============================================================\n\n/**\n * Compiles a field reference to a base column name.\n *\n * @param field - The field reference to compile\n * @param cteAlias - Optional CTE alias for main query context (e.g., \"cte_p\")\n * @param cteColumnPrefix - Optional prefix for CTE WHERE context:\n * - undefined: Use aliased column names (e.g., \"p_props\")\n * - \"\": Use raw column names (e.g., \"props\") for start CTE\n * - \"n\": Use table-qualified names (e.g., \"n.props\") for traversal CTE\n */\nexport function compileFieldColumn(\n field: FieldRef,\n cteAlias?: string,\n cteColumnPrefix?: string,\n): SQL {\n // When cteColumnPrefix is defined (including empty string), use raw column names\n // This is for CTE WHERE clauses which operate on raw table columns\n if (cteColumnPrefix !== undefined) {\n const qualifier = cteColumnPrefix === \"\" ? \"\" : `${cteColumnPrefix}.`;\n\n if (field.path.length === 1 && field.path[0] === \"id\") {\n return sql.raw(`${qualifier}id`);\n }\n if (field.path.length === 1 && field.path[0] === \"kind\") {\n return sql.raw(`${qualifier}kind`);\n }\n if (field.path.length > 0 && field.path[0] === \"props\") {\n return sql.raw(`${qualifier}props`);\n }\n\n return sql.raw(`${qualifier}${field.path.join(\"_\")}`);\n }\n\n // Default behavior: use aliased column names (e.g., \"p_props\")\n const prefix = field.alias;\n const qualifier = cteAlias ? `${cteAlias}.` : \"\";\n\n if (field.path.length === 1 && field.path[0] === \"id\") {\n return sql.raw(`${qualifier}${prefix}_id`);\n }\n if (field.path.length === 1 && field.path[0] === \"kind\") {\n return sql.raw(`${qualifier}${prefix}_kind`);\n }\n if (field.path.length > 0 && field.path[0] === \"props\") {\n return sql.raw(`${qualifier}${prefix}_props`);\n }\n\n return sql.raw(`${qualifier}${prefix}_${field.path.join(\"_\")}`);\n}\n\n/**\n * Gets the JSON pointer for a field reference.\n */\nexport function getFieldPointer(field: FieldRef): JsonPointer | undefined {\n if (field.jsonPointer !== undefined) {\n return field.jsonPointer;\n }\n\n if (field.path.length > 1 && field.path[0] === \"props\") {\n return jsonPointer(field.path.slice(1));\n }\n\n return undefined;\n}\n\n/**\n * Checks if a field reference points to a JSON props column.\n */\nfunction isJsonField(field: FieldRef): boolean {\n return field.path.length > 0 && field.path[0] === \"props\";\n}\n\n/**\n * Normalizes a value type, treating \"unknown\" as undefined.\n */\nfunction normalizeValueType(\n valueType: ValueType | undefined,\n): ValueType | undefined {\n if (!valueType || valueType === \"unknown\") {\n return undefined;\n }\n return valueType;\n}\n\n/**\n * Compiles a field reference to SQL with appropriate type extraction.\n */\nexport function compileFieldValue(\n field: FieldRef,\n dialect: DialectAdapter,\n valueType?: ValueType,\n cteAlias?: string,\n pointerOverride?: JsonPointer,\n cteColumnPrefix?: string,\n): SQL {\n const resolved = normalizeValueType(valueType);\n const column = compileFieldColumn(field, cteAlias, cteColumnPrefix);\n\n if (!isJsonField(field)) {\n return column;\n }\n\n const pointer = pointerOverride ?? getFieldPointer(field);\n if (!pointer || pointer === \"\") {\n return column;\n }\n\n switch (resolved) {\n case \"number\": {\n return dialect.jsonExtractNumber(column, pointer);\n }\n case \"boolean\": {\n return dialect.jsonExtractBoolean(column, pointer);\n }\n case \"date\": {\n return dialect.jsonExtractDate(column, pointer);\n }\n case \"array\":\n case \"object\":\n case \"embedding\": {\n // Embeddings are stored in a separate table, but if we need to\n // extract from JSON, treat like a regular JSON value\n return dialect.jsonExtract(column, pointer);\n }\n case \"string\":\n case \"unknown\":\n case undefined: {\n return dialect.jsonExtractText(column, pointer);\n }\n }\n}\n\n/**\n * Compiles a field reference for text comparison.\n */\nfunction compileFieldTextValue(\n field: FieldRef,\n dialect: DialectAdapter,\n cteAlias?: string,\n pointerOverride?: JsonPointer,\n cteColumnPrefix?: string,\n): SQL {\n const column = compileFieldColumn(field, cteAlias, cteColumnPrefix);\n if (!isJsonField(field)) {\n return column;\n }\n\n const pointer = pointerOverride ?? getFieldPointer(field);\n if (!pointer || pointer === \"\") {\n return column;\n }\n\n return dialect.jsonExtractText(column, pointer);\n}\n\n/**\n * Compiles a field reference for JSON value extraction.\n */\nfunction compileFieldJsonValue(\n field: FieldRef,\n dialect: DialectAdapter,\n cteAlias?: string,\n pointerOverride?: JsonPointer,\n cteColumnPrefix?: string,\n): SQL {\n const column = compileFieldColumn(field, cteAlias, cteColumnPrefix);\n if (!isJsonField(field)) {\n return column;\n }\n\n const pointer = pointerOverride ?? getFieldPointer(field);\n if (!pointer || pointer === \"\") {\n return column;\n }\n\n return dialect.jsonExtract(column, pointer);\n}\n\n// ============================================================\n// Value Type Resolution\n// ============================================================\n\n/**\n * Resolves literal value types from an array of literals.\n */\nfunction resolveLiteralValueTypes(\n literals: readonly LiteralValue[],\n): ValueType | undefined {\n const resolved = new Set<ValueType>();\n\n for (const literal of literals) {\n const valueType = normalizeValueType(literal.valueType);\n if (valueType) {\n resolved.add(valueType);\n }\n }\n\n if (resolved.size > 1) {\n throw new UnsupportedPredicateError(\n \"Mixed literal value types are not supported in predicates\",\n { valueTypes: [...resolved] },\n );\n }\n\n return resolved.values().next().value;\n}\n\n/**\n * Resolves the value type for a comparison predicate.\n */\nfunction resolveComparisonValueType(\n field: FieldRef,\n right: LiteralValue | readonly LiteralValue[] | ParameterRef,\n): ValueType | undefined {\n if (isParameterRef(right)) {\n return (\n normalizeValueType(right.valueType) ?? normalizeValueType(field.valueType)\n );\n }\n const literals = Array.isArray(right) ? right : [right];\n const literalType = resolveLiteralValueTypes(literals);\n const fieldType = normalizeValueType(field.valueType);\n\n // Date fields compared with string literals should use date type\n if (fieldType === \"date\" && literalType === \"string\") {\n return fieldType;\n }\n\n if (literalType) {\n return literalType;\n }\n\n return fieldType;\n}\n\n/**\n * Resolves value type with preference for explicit type.\n */\nfunction resolvePredicateValueType(\n preferred: ValueType | undefined,\n literal: LiteralValue | undefined,\n): ValueType | undefined {\n const normalizedPreferred = normalizeValueType(preferred);\n if (normalizedPreferred) {\n return normalizedPreferred;\n }\n\n return literal ? normalizeValueType(literal.valueType) : undefined;\n}\n\n// ============================================================\n// Value Conversion\n// ============================================================\n\n/**\n * Converts a literal value for SQL binding.\n * Delegates to dialect adapter for proper type conversion (e.g., boolean → 0/1 for SQLite).\n */\nfunction convertValueForSql(value: unknown, dialect: DialectAdapter): unknown {\n return dialect.bindValue(value);\n}\n\n// ============================================================\n// String Pattern Compilation\n// ============================================================\n\n/**\n * Compiles a string pattern for LIKE operations.\n */\nfunction compileStringPattern(op: string, pattern: string): string {\n // Escape the escape character first so the wildcards we prefix below aren't\n // double-escaped, then neutralize the LIKE wildcards. Mirrors\n // escapeLikePatternParameter for the parameterized path. The emitted\n // LIKE/ILIKE declares this same character as its ESCAPE (see likeEscapeClause).\n const escaped = pattern\n .replaceAll(\n LIKE_ESCAPE_CHARACTER,\n `${LIKE_ESCAPE_CHARACTER}${LIKE_ESCAPE_CHARACTER}`,\n )\n .replaceAll(\"%\", `${LIKE_ESCAPE_CHARACTER}%`)\n .replaceAll(\"_\", `${LIKE_ESCAPE_CHARACTER}_`);\n\n switch (op) {\n case \"contains\": {\n return `%${escaped}%`;\n }\n case \"startsWith\": {\n return `${escaped}%`;\n }\n case \"endsWith\": {\n return `%${escaped}`;\n }\n case \"like\":\n case \"ilike\": {\n return pattern;\n }\n default: {\n return escaped;\n }\n }\n}\n\n/**\n * Escapes wildcard characters in a SQL pattern parameter. Mirrors\n * `compileStringPattern`'s escaping for the literal-pattern path, both driven\n * by the same {@link LIKE_ESCAPE_CHARACTER} so they can't drift apart.\n */\nfunction escapeLikePatternParameter(parameter: SQL): SQL {\n const doubledEscape = `${LIKE_ESCAPE_CHARACTER}${LIKE_ESCAPE_CHARACTER}`;\n return sql`REPLACE(REPLACE(REPLACE(${parameter}, ${LIKE_ESCAPE_CHARACTER}, ${doubledEscape}), '%', ${`${LIKE_ESCAPE_CHARACTER}%`}), '_', ${`${LIKE_ESCAPE_CHARACTER}_`})`;\n}\n\n/**\n * Builds a SQL pattern expression for parameterized string operations.\n */\nfunction compileParameterizedStringPattern(op: string, parameter: SQL): SQL {\n switch (op) {\n case \"contains\": {\n const escaped = escapeLikePatternParameter(parameter);\n return sql`'%' || ${escaped} || '%'`;\n }\n case \"startsWith\": {\n const escaped = escapeLikePatternParameter(parameter);\n return sql`${escaped} || '%'`;\n }\n case \"endsWith\": {\n const escaped = escapeLikePatternParameter(parameter);\n return sql`'%' || ${escaped}`;\n }\n case \"like\":\n case \"ilike\": {\n return parameter;\n }\n default: {\n return escapeLikePatternParameter(parameter);\n }\n }\n}\n\n// ============================================================\n// Predicate Compilation\n// ============================================================\n\n/**\n * Compiler context passed to recursive compilation functions.\n *\n * When compiling predicates inside CTE WHERE clauses, `cteColumnPrefix` specifies\n * how to reference columns:\n * - undefined: Use aliased column names (e.g., \"p_props\") - for main query context\n * - \"\": Use raw column names (e.g., \"props\") - for start CTE WHERE clause\n * - \"n\": Use table-qualified names (e.g., \"n.props\") - for traversal CTE WHERE clause\n */\nexport type PredicateCompilerContext = Readonly<{\n dialect: DialectAdapter;\n schema: SqlSchema;\n compileQuery: (ast: QueryAst, graphId: string) => SQL;\n cteColumnPrefix?: string;\n /**\n * Active vector strategy for `field.similarTo(...)` compilation. When\n * present, the embeddings CTE scans the strategy's per-`(kind, field)`\n * tables and uses its `distanceExpression`; absent on backends without\n * vector support (the vector pass rejects the predicate before the CTE\n * builder runs).\n */\n vectorStrategy?: VectorStrategy;\n /**\n * Whether the active backend supports SQL window functions such as\n * `ROW_NUMBER()`.\n */\n windowFunctions: boolean;\n /**\n * Declared embedding slots `(kind, fieldPath) -> {dimensions, metric,\n * indexType}`. The embeddings CTE consults it to know which kinds in\n * an alias actually declare the field — only those get a per-field\n * table scan in the UNION ALL.\n */\n vectorSlots?: VectorSlotMap;\n /** Per-kind declared fulltext language for constant-tsquery parsing. */\n fulltextLanguages?: ReadonlyMap<string, string>;\n /**\n * Mutable collector: the emitter records each ANN slot index type it\n * compiles an engine-form branch for, and the compiler entry brands\n * the finished statement with them (see markAnnIndexScan).\n */\n annIndexTypes?: Set<string>;\n /**\n * How the temporal pass emits the \"current\" read instant. Threaded from\n * {@link CompileQueryOptions.readInstant} so the standard and recursive\n * pipelines can compile a reusable placeholder statement for the query\n * builder's template cache. Absent means `\"literal\"`.\n */\n readInstant?: ReadInstantMode;\n}>;\n\n/**\n * Compiles a predicate expression to SQL.\n */\nexport function compilePredicateExpression(\n expr: PredicateExpression,\n ctx: PredicateCompilerContext,\n): SQL {\n const { dialect } = ctx;\n\n const cteColumnPrefix = ctx.cteColumnPrefix;\n\n switch (expr.__type) {\n case \"comparison\": {\n return compileComparisonPredicate(expr, dialect, cteColumnPrefix);\n }\n\n case \"string_op\": {\n const field = compileFieldTextValue(\n expr.field,\n dialect,\n undefined,\n undefined,\n cteColumnPrefix,\n );\n\n if (isParameterRef(expr.pattern)) {\n const placeholder = sql`${sql.placeholder(expr.pattern.name)}`;\n const pattern = compileParameterizedStringPattern(expr.op, placeholder);\n if (\n expr.op === \"ilike\" ||\n expr.op === \"contains\" ||\n expr.op === \"startsWith\" ||\n expr.op === \"endsWith\"\n ) {\n return dialect.ilike(field, pattern);\n }\n return sql`${field} LIKE ${pattern} ${likeEscapeClause}`;\n }\n\n const pattern = compileStringPattern(expr.op, expr.pattern);\n // Use case-insensitive matching for contains, startsWith, endsWith, and ilike\n // This ensures consistent behavior across PostgreSQL (case-sensitive LIKE)\n // and SQLite (case-insensitive LIKE for ASCII)\n if (\n expr.op === \"ilike\" ||\n expr.op === \"contains\" ||\n expr.op === \"startsWith\" ||\n expr.op === \"endsWith\"\n ) {\n return dialect.ilike(field, pattern);\n }\n // Use case-sensitive LIKE only for explicit 'like' operator. The ESCAPE\n // clause must match the parameterized path (above) and dialect.ilike so a\n // raw '\\%' / '\\_' in a user pattern is a literal on SQLite too, not just\n // on Postgres (whose default LIKE escape is already backslash).\n return sql`${field} LIKE ${pattern} ${likeEscapeClause}`;\n }\n\n case \"null_check\": {\n const field = compileFieldTextValue(\n expr.field,\n dialect,\n undefined,\n undefined,\n cteColumnPrefix,\n );\n return expr.op === \"isNull\" ?\n sql`${field} IS NULL`\n : sql`${field} IS NOT NULL`;\n }\n\n case \"between\": {\n const lowerIsParam = isParameterRef(expr.lower);\n const upperIsParam = isParameterRef(expr.upper);\n\n // Resolve value type from non-param bounds\n const boundsForType: LiteralValue[] = [];\n if (!lowerIsParam) boundsForType.push(expr.lower);\n if (!upperIsParam) boundsForType.push(expr.upper);\n\n const valueType =\n boundsForType.length > 0 ?\n resolveComparisonValueType(expr.field, boundsForType)\n : normalizeValueType(expr.field.valueType);\n\n if (valueType === \"array\" || valueType === \"object\") {\n throw new UnsupportedPredicateError(\n \"Between comparisons are not supported for JSON arrays or objects\",\n );\n }\n const field = compileFieldValue(\n expr.field,\n dialect,\n valueType,\n undefined,\n undefined,\n cteColumnPrefix,\n );\n const lower =\n lowerIsParam ?\n sql.placeholder(expr.lower.name)\n : convertValueForSql(expr.lower.value, dialect);\n const upper =\n upperIsParam ?\n sql.placeholder(expr.upper.name)\n : convertValueForSql(expr.upper.value, dialect);\n return sql`${field} BETWEEN ${lower} AND ${upper}`;\n }\n\n case \"and\": {\n const parts = expr.predicates.map((p) =>\n compilePredicateExpression(p, ctx),\n );\n return sql`(${sql.join(parts, sql` AND `)})`;\n }\n\n case \"or\": {\n const parts = expr.predicates.map((p) =>\n compilePredicateExpression(p, ctx),\n );\n return sql`(${sql.join(parts, sql` OR `)})`;\n }\n\n case \"not\": {\n const inner = compilePredicateExpression(expr.predicate, ctx);\n return sql`NOT (${inner})`;\n }\n\n case \"array_op\": {\n return compileArrayPredicate(expr, dialect, cteColumnPrefix);\n }\n\n case \"object_op\": {\n return compileObjectPredicate(expr, dialect, cteColumnPrefix);\n }\n\n case \"aggregate_comparison\": {\n return compileAggregatePredicate(expr, dialect);\n }\n\n case \"exists\": {\n return compileExistsSubquery(expr, ctx);\n }\n\n case \"in_subquery\": {\n return compileInSubquery(expr, ctx);\n }\n\n case \"vector_similarity\":\n case \"fulltext_match\": {\n // Structural predicates — handled by the main compiler via JOINs,\n // ORDER BY, and LIMIT. Compile to 1=1 so they compose safely with\n // surrounding AND branches.\n return STRUCTURAL_PREDICATE_NOOP;\n }\n }\n}\n\nconst STRUCTURAL_PREDICATE_NOOP = sql.raw(\"1=1\");\n\n/**\n * Compiles a comparison predicate.\n */\nfunction compileComparisonPredicate(\n expr: {\n __type: \"comparison\";\n op: string;\n left: FieldRef;\n right: LiteralValue | readonly LiteralValue[] | ParameterRef;\n },\n dialect: DialectAdapter,\n cteColumnPrefix?: string,\n): SQL {\n // Handle ParameterRef on the right side\n if (isParameterRef(expr.right)) {\n const parameterValueType =\n normalizeValueType(expr.right.valueType) ??\n normalizeValueType(expr.left.valueType);\n const left = compileFieldValue(\n expr.left,\n dialect,\n parameterValueType,\n undefined,\n undefined,\n cteColumnPrefix,\n );\n const opSql = COMPARISON_OP_SQL[expr.op];\n if (!opSql) {\n throw new UnsupportedPredicateError(\n `Comparison operation \"${expr.op}\" is not supported for parameterized predicates`,\n );\n }\n return sql`${left} ${sql.raw(opSql)} ${sql.placeholder(expr.right.name)}`;\n }\n\n const valueType = resolveComparisonValueType(expr.left, expr.right);\n\n if (valueType === \"array\" || valueType === \"object\") {\n throw new UnsupportedPredicateError(\n `Comparison operation \"${expr.op}\" is not supported for ${valueType} values`,\n );\n }\n\n const left = compileFieldValue(\n expr.left,\n dialect,\n valueType,\n undefined,\n undefined,\n cteColumnPrefix,\n );\n\n if (expr.op === \"in\" || expr.op === \"notIn\") {\n const values: readonly LiteralValue[] =\n Array.isArray(expr.right) ? expr.right : [expr.right as LiteralValue];\n if (values.length === 0) {\n return expr.op === \"in\" ? sql.raw(\"1=0\") : sql.raw(\"1=1\");\n }\n const convertedValues = values.map((value) =>\n convertValueForSql(value.value, dialect),\n );\n return dialect.inList(left, convertedValues, expr.op === \"notIn\");\n }\n\n // For single-value comparisons, extract the literal value\n const right = expr.right;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- Type narrowing with Array.isArray\n const rightValue: LiteralValue = Array.isArray(right) ? right[0]! : right;\n\n const convertedRight = convertValueForSql(rightValue.value, dialect);\n const opSql = COMPARISON_OP_SQL[expr.op];\n if (!opSql) {\n throw new UnsupportedPredicateError(\n `Comparison operation \"${expr.op}\" is not supported`,\n );\n }\n return sql`${left} ${sql.raw(opSql)} ${convertedRight}`;\n}\n\n/**\n * Compiles an array predicate.\n */\nfunction compileArrayPredicate(\n expr: ArrayPredicate,\n dialect: DialectAdapter,\n cteColumnPrefix?: string,\n): SQL {\n const field = compileFieldJsonValue(\n expr.field,\n dialect,\n undefined,\n undefined,\n cteColumnPrefix,\n );\n const values =\n expr.values?.map((v) => convertValueForSql(v.value, dialect)) ?? [];\n\n switch (expr.op) {\n case \"isEmpty\": {\n return sql`(${field} IS NULL OR ${dialect.jsonArrayLength(field)} = 0)`;\n }\n case \"isNotEmpty\": {\n return sql`(${field} IS NOT NULL AND ${dialect.jsonArrayLength(field)} > 0)`;\n }\n case \"lengthEq\": {\n return sql`${dialect.jsonArrayLength(field)} = ${expr.length}`;\n }\n case \"lengthGt\": {\n return sql`${dialect.jsonArrayLength(field)} > ${expr.length}`;\n }\n case \"lengthGte\": {\n return sql`${dialect.jsonArrayLength(field)} >= ${expr.length}`;\n }\n case \"lengthLt\": {\n return sql`${dialect.jsonArrayLength(field)} < ${expr.length}`;\n }\n case \"lengthLte\": {\n return sql`${dialect.jsonArrayLength(field)} <= ${expr.length}`;\n }\n case \"contains\": {\n const value = values[0];\n if (value === undefined) {\n return sql.raw(\"1=0\");\n }\n return dialect.jsonArrayContains(field, value);\n }\n case \"containsAll\": {\n return dialect.jsonArrayContainsAll(field, values);\n }\n case \"containsAny\": {\n return dialect.jsonArrayContainsAny(field, values);\n }\n }\n}\n\n/**\n * Compiles an object/JSON predicate.\n */\nfunction compileObjectPredicate(\n expr: ObjectPredicate,\n dialect: DialectAdapter,\n cteColumnPrefix?: string,\n): SQL {\n const basePointer = getFieldPointer(expr.field);\n const pointer = joinJsonPointers(basePointer, expr.pointer);\n const column = compileFieldColumn(expr.field, undefined, cteColumnPrefix);\n\n switch (expr.op) {\n case \"hasKey\":\n case \"hasPath\": {\n return dialect.jsonHasPath(column, pointer);\n }\n\n case \"pathEquals\": {\n if (!expr.value) {\n throw new UnsupportedPredicateError(\n \"pathEquals requires a comparison value\",\n );\n }\n const valueType = resolvePredicateValueType(expr.valueType, expr.value);\n if (valueType === \"array\" || valueType === \"object\") {\n throw new UnsupportedPredicateError(\n \"pathEquals is not supported for JSON arrays or objects\",\n );\n }\n const left = compileFieldValue(\n expr.field,\n dialect,\n valueType,\n undefined,\n pointer,\n cteColumnPrefix,\n );\n return sql`${left} = ${convertValueForSql(expr.value.value, dialect)}`;\n }\n\n case \"pathContains\": {\n if (!expr.value) {\n throw new UnsupportedPredicateError(\n \"pathContains requires a comparison value\",\n );\n }\n const arrayField = compileFieldJsonValue(\n expr.field,\n dialect,\n undefined,\n pointer,\n cteColumnPrefix,\n );\n return dialect.jsonArrayContains(\n arrayField,\n convertValueForSql(expr.value.value, dialect),\n );\n }\n\n case \"pathIsNull\": {\n return dialect.jsonPathIsNull(column, pointer);\n }\n\n case \"pathIsNotNull\": {\n return dialect.jsonPathIsNotNull(column, pointer);\n }\n }\n}\n\n/**\n * AggregateExpr structure from AST.\n */\ntype AggregateExprInput = Readonly<{\n __type: \"aggregate\";\n function: string;\n field: FieldRef;\n}>;\n\n/**\n * Compiles an aggregate comparison predicate.\n */\nfunction compileAggregatePredicate(\n expr: {\n __type: \"aggregate_comparison\";\n op: string;\n aggregate: AggregateExprInput;\n value: LiteralValue;\n },\n dialect: DialectAdapter,\n): SQL {\n const aggregate = compileAggregateExpr(expr.aggregate, dialect);\n\n const op = COMPARISON_OP_SQL[expr.op];\n if (!op) {\n throw new UnsupportedPredicateError(\n `Comparison operation \"${expr.op}\" is not supported for aggregate predicates`,\n );\n }\n\n const convertedValue = convertValueForSql(expr.value.value, dialect);\n return sql`${aggregate} ${sql.raw(op)} ${convertedValue}`;\n}\n\n/**\n * Compiles an aggregate expression.\n */\nfunction compileAggregateExpr(\n expr: AggregateExprInput,\n dialect: DialectAdapter,\n): SQL {\n const cteAlias = `cte_${expr.field.alias}`;\n const field = compileFieldValue(\n expr.field,\n dialect,\n expr.field.valueType,\n cteAlias,\n );\n\n switch (expr.function) {\n case \"count\": {\n return sql`COUNT(${field})`;\n }\n case \"countDistinct\": {\n return sql`COUNT(DISTINCT ${field})`;\n }\n case \"sum\": {\n return sql`SUM(${field})`;\n }\n case \"avg\": {\n return sql`AVG(${field})`;\n }\n case \"min\": {\n return sql`MIN(${field})`;\n }\n case \"max\": {\n return sql`MAX(${field})`;\n }\n default: {\n throw new UnsupportedPredicateError(\n `Unknown aggregate function: ${expr.function}`,\n );\n }\n }\n}\n\n/**\n * Compiles an EXISTS subquery predicate.\n */\nfunction compileExistsSubquery(\n expr: ExistsSubquery,\n ctx: PredicateCompilerContext,\n): SQL {\n if (expr.subquery.graphId === undefined) {\n throw new UnsupportedPredicateError(\"EXISTS subquery must have a graphId\");\n }\n const subSql = ctx.compileQuery(expr.subquery, expr.subquery.graphId);\n return expr.negated ? sql`NOT EXISTS (${subSql})` : sql`EXISTS (${subSql})`;\n}\n\n/**\n * Compiles an IN subquery predicate.\n */\nfunction compileInSubquery(\n expr: InSubquery,\n ctx: PredicateCompilerContext,\n): SQL {\n const subqueryColumnCount = getSubqueryColumnCount(expr.subquery);\n if (subqueryColumnCount !== 1) {\n throw new UnsupportedPredicateError(\n `IN/NOT IN subquery must project exactly 1 column, but got ${subqueryColumnCount}`,\n { subqueryColumnCount },\n );\n }\n\n const fieldValueType = normalizeValueType(expr.field.valueType);\n const subqueryValueType = getSingleSubqueryColumnValueType(expr.subquery);\n const resolvedValueType = fieldValueType ?? subqueryValueType;\n\n if (isUnsupportedInSubqueryValueType(resolvedValueType)) {\n throw new UnsupportedPredicateError(\n `IN/NOT IN subquery does not support ${String(resolvedValueType)} values`,\n { valueType: resolvedValueType },\n );\n }\n\n if (!isInSubqueryTypeCompatible(fieldValueType, subqueryValueType)) {\n throw new UnsupportedPredicateError(\n `IN/NOT IN type mismatch: field type \"${String(fieldValueType)}\" does not match subquery column type \"${String(subqueryValueType)}\"`,\n {\n fieldValueType,\n subqueryValueType,\n },\n );\n }\n\n const valueType = fieldValueType ?? subqueryValueType;\n if (expr.subquery.graphId === undefined) {\n throw new UnsupportedPredicateError(\n \"IN/NOT IN subquery must have a graphId\",\n );\n }\n const fieldSql = compileFieldValue(\n expr.field,\n ctx.dialect,\n valueType,\n undefined,\n undefined,\n ctx.cteColumnPrefix,\n );\n const subSql = ctx.compileQuery(expr.subquery, expr.subquery.graphId);\n return expr.negated ?\n sql`${fieldSql} NOT IN (${subSql})`\n : sql`${fieldSql} IN (${subSql})`;\n}\n\n/**\n * Compiles a vector similarity predicate.\n *\n * Vector similarity predicates require special handling at the query compilation\n * level to handle:\n * - JOIN to embeddings table\n * - ORDER BY distance ASC\n * - LIMIT k\n *\n * This function handles the minScore filter if present. The main query compiler\n * must detect vector_similarity predicates and set up the appropriate JOINs\n * and ordering.\n */\n\n// ============================================================\n// Structural Predicate Extraction\n// ============================================================\n\n/**\n * Extracts all instances of a \"structural\" predicate (one that rewrites\n * the query into JOIN + ORDER BY + LIMIT, rather than acting as a\n * boolean WHERE clause). Both `vector_similarity` and `fulltext_match`\n * have the same placement rules: top-level or under AND only — nesting\n * under OR/NOT is rejected because the rewrite is incompatible with\n * disjunction and negation.\n */\nfunction extractStructuralPredicates<T extends PredicateExpression>(\n predicates: readonly { expression: PredicateExpression }[],\n isMatch: (expr: PredicateExpression) => expr is T,\n rejectionMessage: string,\n): T[] {\n const results: T[] = [];\n\n function visit(expr: PredicateExpression, inDisallowedBranch: boolean): void {\n if (isMatch(expr)) {\n if (inDisallowedBranch) {\n throw new UnsupportedPredicateError(rejectionMessage);\n }\n results.push(expr);\n return;\n }\n switch (expr.__type) {\n case \"and\": {\n for (const child of expr.predicates) visit(child, inDisallowedBranch);\n return;\n }\n case \"or\": {\n for (const child of expr.predicates) visit(child, true);\n return;\n }\n case \"not\": {\n visit(expr.predicate, true);\n return;\n }\n case \"comparison\":\n case \"string_op\":\n case \"null_check\":\n case \"between\":\n case \"array_op\":\n case \"object_op\":\n case \"aggregate_comparison\":\n case \"exists\":\n case \"in_subquery\":\n case \"vector_similarity\":\n case \"fulltext_match\": {\n return;\n }\n }\n }\n\n for (const pred of predicates) visit(pred.expression, false);\n return results;\n}\n\nexport function extractVectorSimilarityPredicates(\n predicates: readonly { expression: PredicateExpression }[],\n): VectorSimilarityPredicate[] {\n return extractStructuralPredicates(\n predicates,\n (expr): expr is VectorSimilarityPredicate =>\n expr.__type === \"vector_similarity\",\n \"Vector similarity predicates cannot be nested under OR or NOT. \" +\n \"Use top-level AND combinations instead.\",\n );\n}\n\nexport function extractFulltextMatchPredicates(\n predicates: readonly { expression: PredicateExpression }[],\n): FulltextMatchPredicate[] {\n return extractStructuralPredicates(\n predicates,\n (expr): expr is FulltextMatchPredicate => expr.__type === \"fulltext_match\",\n \"Fulltext match predicates cannot be nested under OR or NOT. \" +\n \"Use top-level AND combinations instead.\",\n );\n}\n\n// ============================================================\n// Exports for aggregate compilation\n// ============================================================\n\nexport { compileAggregateExpr };\n","import { type SQL, sql } from \"drizzle-orm\";\n\nimport type { KindEntity } from \"../../core/types\";\nimport { CompilerInvariantError } from \"../../errors\";\nimport {\n type FulltextMatchPredicate,\n type NodePredicate,\n type QueryAst,\n type VectorSimilarityPredicate,\n} from \"../ast\";\nimport {\n compilePredicateExpression,\n type PredicateCompilerContext,\n} from \"./predicates\";\n\nconst EMPTY_PREDICATES: readonly NodePredicate[] = [];\n\n/**\n * Builds a comma-separated bound-parameter list for an `IN (...)` clause. Each\n * value is parameterized, never interpolated.\n */\nexport function sqlValueList(values: readonly string[]): SQL {\n return sql.join(\n values.map((value) => sql`${value}`),\n sql`, `,\n );\n}\n\nexport type PredicateIndex = Readonly<{\n byAliasAndType: ReadonlyMap<string, readonly NodePredicate[]>;\n}>;\n\nfunction buildPredicateIndexKey(alias: string, targetType: KindEntity): string {\n return `${alias}\\u0000${targetType}`;\n}\n\nfunction resolvePredicateTargetType(predicate: NodePredicate): KindEntity {\n return predicate.targetType === \"edge\" ? \"edge\" : \"node\";\n}\n\nexport function buildPredicateIndex(ast: QueryAst): PredicateIndex {\n const byAliasAndType = new Map<string, NodePredicate[]>();\n for (const predicate of ast.predicates) {\n const key = buildPredicateIndexKey(\n predicate.targetAlias,\n resolvePredicateTargetType(predicate),\n );\n const existing = byAliasAndType.get(key);\n if (existing === undefined) {\n byAliasAndType.set(key, [predicate]);\n } else {\n existing.push(predicate);\n }\n }\n return { byAliasAndType };\n}\n\nexport function getPredicatesForAlias(\n predicateIndex: PredicateIndex,\n alias: string,\n targetType: KindEntity,\n): readonly NodePredicate[] {\n return (\n predicateIndex.byAliasAndType.get(\n buildPredicateIndexKey(alias, targetType),\n ) ?? EMPTY_PREDICATES\n );\n}\n\nexport function compilePredicateClauses(\n predicates: readonly NodePredicate[],\n predicateContext: PredicateCompilerContext,\n): SQL[] {\n return predicates.map((predicate) =>\n compilePredicateExpression(predicate.expression, predicateContext),\n );\n}\n\nexport function compileKindFilter(column: SQL, kinds: readonly string[]): SQL {\n if (kinds.length === 0) {\n return sql`1 = 0`;\n }\n if (kinds.length === 1) {\n return sql`${column} = ${kinds[0]}`;\n }\n return sql`${column} IN (${sqlValueList(kinds)})`;\n}\n\nexport function getNodeKindsForAlias(\n ast: QueryAst,\n alias: string,\n): readonly string[] {\n if (alias === ast.start.alias) {\n return ast.start.kinds;\n }\n\n for (const traversal of ast.traversals) {\n if (traversal.nodeAlias === alias) {\n return traversal.nodeKinds;\n }\n }\n\n throw new CompilerInvariantError(`Unknown traversal source alias: ${alias}`);\n}\n\n/**\n * Returns the shared alias when a hybrid (vector + fulltext) query has\n * both predicates targeting the same alias — that's the case where the\n * emitter can fuse ranks via `HYBRID_CANDIDATES_CTE_ALIAS` / RRF.\n * Returns `undefined` when either predicate is missing or the two\n * predicates target different aliases.\n */\nexport function getHybridTargetAlias(\n vectorPredicate: VectorSimilarityPredicate | undefined,\n fulltextPredicate: FulltextMatchPredicate | undefined,\n): string | undefined {\n if (!vectorPredicate || !fulltextPredicate) return undefined;\n return vectorPredicate.field.alias === fulltextPredicate.field.alias ?\n vectorPredicate.field.alias\n : undefined;\n}\n","/**\n * Splits `items` into consecutive chunks of at most `size` elements.\n *\n * An empty input yields no chunks (`[]`), and an input that already fits in a\n * single chunk is returned without copying. Callers rely on the empty-input\n * behavior to skip work entirely rather than issue a statement with an empty\n * `IN ()` list.\n */\nexport function chunk<T>(\n items: readonly T[],\n size: number,\n): readonly (readonly T[])[] {\n // A non-positive, non-finite, or fractional size would make the slice loop\n // fail to advance correctly; fail loud rather than spin or emit empty chunks.\n // All current callers derive size from a positive integer bind-parameter\n // budget, so this only guards against a future regression.\n if (!Number.isSafeInteger(size) || size < 1) {\n throw new RangeError(`chunk size must be a positive integer, got: ${size}`);\n }\n if (items.length === 0) return [];\n if (items.length <= size) return [items];\n const chunks: T[][] = [];\n for (let start = 0; start < items.length; start += size) {\n chunks.push(items.slice(start, start + size));\n }\n return chunks;\n}\n\n/**\n * Groups items by a caller-supplied key while preserving input order within\n * each group.\n */\nexport function groupBy<T, K>(\n items: Iterable<T>,\n keyFor: (item: T) => K,\n): Map<K, T[]> {\n const groups = new Map<K, T[]>();\n for (const item of items) {\n const key = keyFor(item);\n const group = groups.get(key) ?? [];\n group.push(item);\n groups.set(key, group);\n }\n return groups;\n}\n","/**\n * Predicate for values that are materially present in database rows.\n */\nexport function isPresent(value: unknown): boolean {\n return value !== null && value !== undefined;\n}\n"]}