@nicia-ai/typegraph 0.42.1 → 0.44.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 (289) hide show
  1. package/dist/backend/drizzle/indexes.cjs +9 -9
  2. package/dist/backend/drizzle/indexes.d.cts +1 -1
  3. package/dist/backend/drizzle/indexes.d.ts +1 -1
  4. package/dist/backend/drizzle/indexes.js +5 -5
  5. package/dist/backend/index.cjs +50 -50
  6. package/dist/backend/index.d.cts +3 -3
  7. package/dist/backend/index.d.ts +3 -3
  8. package/dist/backend/index.js +11 -11
  9. package/dist/backend/postgres/index.cjs +26 -26
  10. package/dist/backend/postgres/index.d.cts +6 -5
  11. package/dist/backend/postgres/index.d.ts +6 -5
  12. package/dist/backend/postgres/index.js +13 -13
  13. package/dist/backend/postgres/pglite-store.cjs +33 -33
  14. package/dist/backend/postgres/pglite-store.cjs.map +1 -1
  15. package/dist/backend/postgres/pglite-store.d.cts +7 -7
  16. package/dist/backend/postgres/pglite-store.d.ts +7 -7
  17. package/dist/backend/postgres/pglite-store.js +29 -29
  18. package/dist/backend/postgres/pglite-store.js.map +1 -1
  19. package/dist/backend/postgres/pglite.cjs +15 -15
  20. package/dist/backend/postgres/pglite.d.cts +3 -2
  21. package/dist/backend/postgres/pglite.d.ts +3 -2
  22. package/dist/backend/postgres/pglite.js +14 -14
  23. package/dist/backend/sqlite/index.cjs +23 -23
  24. package/dist/backend/sqlite/index.d.cts +7 -6
  25. package/dist/backend/sqlite/index.d.ts +7 -6
  26. package/dist/backend/sqlite/index.js +11 -11
  27. package/dist/backend/sqlite/libsql.cjs +17 -17
  28. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  29. package/dist/backend/sqlite/libsql.d.cts +3 -2
  30. package/dist/backend/sqlite/libsql.d.ts +3 -2
  31. package/dist/backend/sqlite/libsql.js +13 -13
  32. package/dist/backend/sqlite/libsql.js.map +1 -1
  33. package/dist/backend/sqlite/local-store.cjs +34 -34
  34. package/dist/backend/sqlite/local-store.cjs.map +1 -1
  35. package/dist/backend/sqlite/local-store.d.cts +8 -7
  36. package/dist/backend/sqlite/local-store.d.ts +8 -7
  37. package/dist/backend/sqlite/local-store.js +30 -30
  38. package/dist/backend/sqlite/local-store.js.map +1 -1
  39. package/dist/backend/sqlite/local.cjs +16 -16
  40. package/dist/backend/sqlite/local.d.cts +3 -2
  41. package/dist/backend/sqlite/local.d.ts +3 -2
  42. package/dist/backend/sqlite/local.js +14 -14
  43. package/dist/{chunk-3RPQDGUE.cjs → chunk-2BIG7U6E.cjs} +5 -5
  44. package/dist/{chunk-3RPQDGUE.cjs.map → chunk-2BIG7U6E.cjs.map} +1 -1
  45. package/dist/{chunk-2OOY4OYT.js → chunk-2L54C2C2.js} +4 -4
  46. package/dist/{chunk-2OOY4OYT.js.map → chunk-2L54C2C2.js.map} +1 -1
  47. package/dist/{chunk-V2GZBPY2.cjs → chunk-2VLBGQBY.cjs} +310 -61
  48. package/dist/chunk-2VLBGQBY.cjs.map +1 -0
  49. package/dist/{chunk-RXOAXO3R.js → chunk-2WDD2NO3.js} +3 -3
  50. package/dist/{chunk-RXOAXO3R.js.map → chunk-2WDD2NO3.js.map} +1 -1
  51. package/dist/{chunk-2HKIID5K.js → chunk-2Y4IFKW7.js} +5 -5
  52. package/dist/{chunk-2HKIID5K.js.map → chunk-2Y4IFKW7.js.map} +1 -1
  53. package/dist/{chunk-ECU53PMN.cjs → chunk-3PRKZW6D.cjs} +5 -5
  54. package/dist/chunk-3PRKZW6D.cjs.map +1 -0
  55. package/dist/{chunk-2G6ZEGYO.js → chunk-46GDII45.js} +4 -4
  56. package/dist/{chunk-2G6ZEGYO.js.map → chunk-46GDII45.js.map} +1 -1
  57. package/dist/{chunk-OYJSYDIH.js → chunk-4MB3AQAQ.js} +13 -3
  58. package/dist/chunk-4MB3AQAQ.js.map +1 -0
  59. package/dist/chunk-4SZ6XPTG.cjs +12 -0
  60. package/dist/{chunk-VGMNGWBR.cjs.map → chunk-4SZ6XPTG.cjs.map} +1 -1
  61. package/dist/{chunk-FY4VY5EV.cjs → chunk-5MUSU4ZP.cjs} +20 -20
  62. package/dist/chunk-5MUSU4ZP.cjs.map +1 -0
  63. package/dist/{chunk-ZIRC2U6G.js → chunk-63KCKSSH.js} +78 -16
  64. package/dist/chunk-63KCKSSH.js.map +1 -0
  65. package/dist/{chunk-7Y6BV3TK.cjs → chunk-66UVLHQA.cjs} +100 -100
  66. package/dist/{chunk-7Y6BV3TK.cjs.map → chunk-66UVLHQA.cjs.map} +1 -1
  67. package/dist/{chunk-M4GYQF2H.js → chunk-6DCB664D.js} +7 -4
  68. package/dist/chunk-6DCB664D.js.map +1 -0
  69. package/dist/{chunk-OMQ2NBOR.cjs → chunk-6JZUSDY2.cjs} +27 -27
  70. package/dist/{chunk-OMQ2NBOR.cjs.map → chunk-6JZUSDY2.cjs.map} +1 -1
  71. package/dist/{chunk-Z3WIL6S3.js → chunk-7G32LIQM.js} +5 -5
  72. package/dist/{chunk-Z3WIL6S3.js.map → chunk-7G32LIQM.js.map} +1 -1
  73. package/dist/{chunk-2SO5I5AI.cjs → chunk-7V2FGGI2.cjs} +250 -198
  74. package/dist/chunk-7V2FGGI2.cjs.map +1 -0
  75. package/dist/{chunk-I73ATSAH.cjs → chunk-A2I2XO52.cjs} +4 -4
  76. package/dist/{chunk-I73ATSAH.cjs.map → chunk-A2I2XO52.cjs.map} +1 -1
  77. package/dist/{chunk-O2GZM7UK.cjs → chunk-A4PBRX4C.cjs} +7 -7
  78. package/dist/{chunk-O2GZM7UK.cjs.map → chunk-A4PBRX4C.cjs.map} +1 -1
  79. package/dist/{chunk-5P6IPIT6.cjs → chunk-ALFUGRYB.cjs} +75 -65
  80. package/dist/chunk-ALFUGRYB.cjs.map +1 -0
  81. package/dist/{chunk-NXIZL7ZZ.js → chunk-ATLN63JA.js} +6 -6
  82. package/dist/chunk-ATLN63JA.js.map +1 -0
  83. package/dist/{chunk-CUPJL6TS.js → chunk-B75XRV3O.js} +3 -3
  84. package/dist/{chunk-CUPJL6TS.js.map → chunk-B75XRV3O.js.map} +1 -1
  85. package/dist/{chunk-DP7KC6CL.js → chunk-BCP7LLOY.js} +754 -476
  86. package/dist/chunk-BCP7LLOY.js.map +1 -0
  87. package/dist/{chunk-RAWG2FEU.js → chunk-BEFM74L2.js} +264 -18
  88. package/dist/chunk-BEFM74L2.js.map +1 -0
  89. package/dist/{chunk-LQLVJWUH.js → chunk-BNUFUFAU.js} +7 -7
  90. package/dist/chunk-BNUFUFAU.js.map +1 -0
  91. package/dist/{chunk-KTBTSHU6.cjs → chunk-C4F7VJ5D.cjs} +13 -3
  92. package/dist/chunk-C4F7VJ5D.cjs.map +1 -0
  93. package/dist/{chunk-CVK4T34X.cjs → chunk-CPEL3YIR.cjs} +22 -22
  94. package/dist/{chunk-CVK4T34X.cjs.map → chunk-CPEL3YIR.cjs.map} +1 -1
  95. package/dist/{chunk-O3USVVWS.js → chunk-DK2S42XB.js} +3 -3
  96. package/dist/{chunk-O3USVVWS.js.map → chunk-DK2S42XB.js.map} +1 -1
  97. package/dist/{chunk-DMZEVJGL.cjs → chunk-EE7N5XXQ.cjs} +13 -13
  98. package/dist/{chunk-DMZEVJGL.cjs.map → chunk-EE7N5XXQ.cjs.map} +1 -1
  99. package/dist/{chunk-ZGOUVMVS.js → chunk-EFELJVLA.js} +5 -5
  100. package/dist/{chunk-ZGOUVMVS.js.map → chunk-EFELJVLA.js.map} +1 -1
  101. package/dist/chunk-EPTSMFH7.cjs +12 -0
  102. package/dist/{chunk-U3YRCZ5L.cjs.map → chunk-EPTSMFH7.cjs.map} +1 -1
  103. package/dist/{chunk-FSCJOTHF.cjs → chunk-EQ7JKLZO.cjs} +10 -10
  104. package/dist/{chunk-FSCJOTHF.cjs.map → chunk-EQ7JKLZO.cjs.map} +1 -1
  105. package/dist/{chunk-5Q3P6OIC.cjs → chunk-FGO5JFVJ.cjs} +12 -12
  106. package/dist/chunk-FGO5JFVJ.cjs.map +1 -0
  107. package/dist/{chunk-VC26BUNP.js → chunk-FMGEZBAQ.js} +5 -5
  108. package/dist/{chunk-VC26BUNP.js.map → chunk-FMGEZBAQ.js.map} +1 -1
  109. package/dist/{chunk-UZLEQFTV.js → chunk-FMMIX6N4.js} +4 -4
  110. package/dist/chunk-FMMIX6N4.js.map +1 -0
  111. package/dist/{chunk-5C75HQYQ.js → chunk-FRHHDHKH.js} +5 -5
  112. package/dist/{chunk-5C75HQYQ.js.map → chunk-FRHHDHKH.js.map} +1 -1
  113. package/dist/{chunk-EVFL2ZY5.js → chunk-FSXTPBRN.js} +63 -12
  114. package/dist/chunk-FSXTPBRN.js.map +1 -0
  115. package/dist/{chunk-TRC646QQ.cjs → chunk-GFRGG2US.cjs} +7 -7
  116. package/dist/{chunk-TRC646QQ.cjs.map → chunk-GFRGG2US.cjs.map} +1 -1
  117. package/dist/{chunk-UJRWOV5B.js → chunk-GWEDD3DH.js} +5 -5
  118. package/dist/{chunk-UJRWOV5B.js.map → chunk-GWEDD3DH.js.map} +1 -1
  119. package/dist/{chunk-AQR6BHB3.cjs → chunk-HJH3RMXG.cjs} +10 -10
  120. package/dist/{chunk-AQR6BHB3.cjs.map → chunk-HJH3RMXG.cjs.map} +1 -1
  121. package/dist/{chunk-F7TDKSVB.cjs → chunk-HOHAJ2NR.cjs} +4 -4
  122. package/dist/{chunk-F7TDKSVB.cjs.map → chunk-HOHAJ2NR.cjs.map} +1 -1
  123. package/dist/{chunk-YPVQYM3L.js → chunk-HOIFFY4M.js} +100 -20
  124. package/dist/chunk-HOIFFY4M.js.map +1 -0
  125. package/dist/{chunk-LDCWO5B6.js → chunk-IIMQJYAM.js} +3 -3
  126. package/dist/{chunk-LDCWO5B6.js.map → chunk-IIMQJYAM.js.map} +1 -1
  127. package/dist/{chunk-OM6RIOA5.cjs → chunk-IIT5K7SK.cjs} +13 -13
  128. package/dist/{chunk-OM6RIOA5.cjs.map → chunk-IIT5K7SK.cjs.map} +1 -1
  129. package/dist/{chunk-EQOQOT55.js → chunk-IJTLXNGJ.js} +5 -5
  130. package/dist/{chunk-EQOQOT55.js.map → chunk-IJTLXNGJ.js.map} +1 -1
  131. package/dist/{chunk-4XRP2N6B.js → chunk-JRP3VGHS.js} +3 -3
  132. package/dist/{chunk-4XRP2N6B.js.map → chunk-JRP3VGHS.js.map} +1 -1
  133. package/dist/{chunk-42XYPKZU.js → chunk-K3BUWSFR.js} +41 -3
  134. package/dist/chunk-K3BUWSFR.js.map +1 -0
  135. package/dist/{chunk-GT7NEXSU.js → chunk-KCO5EFJU.js} +3 -3
  136. package/dist/{chunk-GT7NEXSU.js.map → chunk-KCO5EFJU.js.map} +1 -1
  137. package/dist/{chunk-ARN3ZODS.cjs → chunk-KKYELPZ2.cjs} +6 -6
  138. package/dist/{chunk-ARN3ZODS.cjs.map → chunk-KKYELPZ2.cjs.map} +1 -1
  139. package/dist/{chunk-33PAKPED.cjs → chunk-MCHP7RHZ.cjs} +41 -41
  140. package/dist/{chunk-33PAKPED.cjs.map → chunk-MCHP7RHZ.cjs.map} +1 -1
  141. package/dist/{chunk-CDYRPI5U.js → chunk-MIJKEVV7.js} +4 -4
  142. package/dist/{chunk-CDYRPI5U.js.map → chunk-MIJKEVV7.js.map} +1 -1
  143. package/dist/{chunk-K2HHCWZO.cjs → chunk-NCX65HBY.cjs} +137 -108
  144. package/dist/chunk-NCX65HBY.cjs.map +1 -0
  145. package/dist/{chunk-6TJ6PKPS.cjs → chunk-NN3QSOVS.cjs} +27 -27
  146. package/dist/{chunk-6TJ6PKPS.cjs.map → chunk-NN3QSOVS.cjs.map} +1 -1
  147. package/dist/{chunk-F2KVJ6FF.cjs → chunk-OSZPLZIV.cjs} +179 -117
  148. package/dist/chunk-OSZPLZIV.cjs.map +1 -0
  149. package/dist/{chunk-UTTW2Q3M.cjs → chunk-OVUUTCPJ.cjs} +171 -133
  150. package/dist/chunk-OVUUTCPJ.cjs.map +1 -0
  151. package/dist/{chunk-FMPZPOUD.js → chunk-PAW2XUZN.js} +3 -3
  152. package/dist/{chunk-FMPZPOUD.js.map → chunk-PAW2XUZN.js.map} +1 -1
  153. package/dist/{chunk-5ZPRE4CV.cjs → chunk-PDGEXGS6.cjs} +204 -124
  154. package/dist/chunk-PDGEXGS6.cjs.map +1 -0
  155. package/dist/{chunk-CVNGKTHO.js → chunk-PHXITZE4.js} +4 -4
  156. package/dist/{chunk-CVNGKTHO.js.map → chunk-PHXITZE4.js.map} +1 -1
  157. package/dist/{chunk-ZPCKPLMX.cjs → chunk-QB6VMOJ2.cjs} +8 -8
  158. package/dist/{chunk-ZPCKPLMX.cjs.map → chunk-QB6VMOJ2.cjs.map} +1 -1
  159. package/dist/{chunk-5AERZSHC.cjs → chunk-QGKILWGZ.cjs} +4 -4
  160. package/dist/{chunk-5AERZSHC.cjs.map → chunk-QGKILWGZ.cjs.map} +1 -1
  161. package/dist/{chunk-ZOHCFYXE.js → chunk-QT6V3YRH.js} +3 -3
  162. package/dist/{chunk-ZOHCFYXE.js.map → chunk-QT6V3YRH.js.map} +1 -1
  163. package/dist/{chunk-XDMPDUKL.cjs → chunk-QYWINYEA.cjs} +9 -9
  164. package/dist/{chunk-XDMPDUKL.cjs.map → chunk-QYWINYEA.cjs.map} +1 -1
  165. package/dist/{chunk-3V6D5DEC.js → chunk-S4KQ5LV4.js} +3 -3
  166. package/dist/{chunk-3V6D5DEC.js.map → chunk-S4KQ5LV4.js.map} +1 -1
  167. package/dist/{chunk-6NB73BXV.js → chunk-SBPC5IP3.js} +40 -12
  168. package/dist/chunk-SBPC5IP3.js.map +1 -0
  169. package/dist/{chunk-HHBKGPEI.js → chunk-SQRD2CYF.js} +264 -21
  170. package/dist/chunk-SQRD2CYF.js.map +1 -0
  171. package/dist/{chunk-O7XVCLXW.cjs → chunk-ST3LPB2V.cjs} +324 -77
  172. package/dist/chunk-ST3LPB2V.cjs.map +1 -0
  173. package/dist/{chunk-FFQGI67R.cjs → chunk-STQ3BSED.cjs} +44 -44
  174. package/dist/{chunk-FFQGI67R.cjs.map → chunk-STQ3BSED.cjs.map} +1 -1
  175. package/dist/{chunk-JOYPNY33.js → chunk-TCRIQMBU.js} +9 -9
  176. package/dist/{chunk-JOYPNY33.js.map → chunk-TCRIQMBU.js.map} +1 -1
  177. package/dist/{chunk-ZP2KPDNN.js → chunk-TFMVL4QH.js} +3 -3
  178. package/dist/{chunk-ZP2KPDNN.js.map → chunk-TFMVL4QH.js.map} +1 -1
  179. package/dist/{chunk-4WYFRACU.js → chunk-TVLKA4AY.js} +3 -3
  180. package/dist/{chunk-4WYFRACU.js.map → chunk-TVLKA4AY.js.map} +1 -1
  181. package/dist/{chunk-X2XOQZT3.cjs → chunk-U5W4LKZV.cjs} +13 -9
  182. package/dist/chunk-U5W4LKZV.cjs.map +1 -0
  183. package/dist/{chunk-WYQILW5V.js → chunk-VITTKBWF.js} +43 -33
  184. package/dist/chunk-VITTKBWF.js.map +1 -0
  185. package/dist/{chunk-AO2WPYFZ.cjs → chunk-WBUFJ7BS.cjs} +4 -4
  186. package/dist/{chunk-AO2WPYFZ.cjs.map → chunk-WBUFJ7BS.cjs.map} +1 -1
  187. package/dist/{chunk-CI5NPLXX.js → chunk-XMYJY7NI.js} +3 -3
  188. package/dist/{chunk-CI5NPLXX.js.map → chunk-XMYJY7NI.js.map} +1 -1
  189. package/dist/{chunk-277UZV7X.cjs → chunk-XR4YZFKW.cjs} +1803 -1525
  190. package/dist/chunk-XR4YZFKW.cjs.map +1 -0
  191. package/dist/{chunk-5GV4JQNA.cjs → chunk-YNULOIR5.cjs} +43 -43
  192. package/dist/{chunk-5GV4JQNA.cjs.map → chunk-YNULOIR5.cjs.map} +1 -1
  193. package/dist/{chunk-ZBV4LQD2.cjs → chunk-ZTAJL4DT.cjs} +4 -4
  194. package/dist/{chunk-ZBV4LQD2.cjs.map → chunk-ZTAJL4DT.cjs.map} +1 -1
  195. package/dist/core/index.cjs +28 -28
  196. package/dist/core/index.d.cts +5 -5
  197. package/dist/core/index.d.ts +5 -5
  198. package/dist/core/index.js +8 -8
  199. package/dist/{ddl-Bc4Dl8fu.d.ts → ddl-D5369kOY.d.ts} +3 -3
  200. package/dist/{ddl-3unqC-kg.d.cts → ddl-eWg7hx6R.d.cts} +3 -3
  201. package/dist/{define-graph-Byslw2OO.d.cts → define-graph-DVF-oN1i.d.cts} +1 -1
  202. package/dist/{define-graph-DBFnc7u_.d.ts → define-graph-SvYXOl78.d.ts} +1 -1
  203. package/dist/graph-extension/index.cjs +20 -20
  204. package/dist/graph-extension/index.d.cts +4 -4
  205. package/dist/graph-extension/index.d.ts +4 -4
  206. package/dist/graph-extension/index.js +5 -5
  207. package/dist/graph-merge/index.cjs +104 -104
  208. package/dist/graph-merge/index.d.cts +9 -8
  209. package/dist/graph-merge/index.d.ts +9 -8
  210. package/dist/graph-merge/index.js +24 -24
  211. package/dist/{index-DQzVJBHa.d.ts → index-By89Sezh.d.ts} +37 -7
  212. package/dist/{index-DHXw7QAl.d.cts → index-DcQ3Sxs-.d.cts} +37 -7
  213. package/dist/index.cjs +210 -202
  214. package/dist/index.d.cts +13 -13
  215. package/dist/index.d.ts +13 -13
  216. package/dist/index.js +34 -34
  217. package/dist/indexes/index.cjs +13 -13
  218. package/dist/indexes/index.d.cts +4 -4
  219. package/dist/indexes/index.d.ts +4 -4
  220. package/dist/indexes/index.js +6 -6
  221. package/dist/interchange/index.cjs +49 -41
  222. package/dist/interchange/index.cjs.map +1 -1
  223. package/dist/interchange/index.d.cts +11 -11
  224. package/dist/interchange/index.d.ts +11 -11
  225. package/dist/interchange/index.js +23 -15
  226. package/dist/interchange/index.js.map +1 -1
  227. package/dist/{manager-Dl0-er1G.d.ts → manager-B0KjKE93.d.ts} +44 -6
  228. package/dist/{manager-U9_zopqr.d.cts → manager-Cn0NFIhN.d.cts} +44 -6
  229. package/dist/{materialize-indexes-BM3u0aXE.d.ts → materialize-indexes-BD4V3svD.d.ts} +1 -1
  230. package/dist/{materialize-indexes-DzMCetZe.d.cts → materialize-indexes-DVRhd5h4.d.cts} +1 -1
  231. package/dist/{postgres-C5-WMKFA.d.ts → postgres-DaEWvN4x.d.cts} +1 -1
  232. package/dist/{postgres-DpJqtbSX.d.cts → postgres-u0a0HN2D.d.ts} +1 -1
  233. package/dist/profiler/index.d.cts +10 -9
  234. package/dist/profiler/index.d.ts +10 -9
  235. package/dist/provenance/index.cjs +38 -38
  236. package/dist/provenance/index.cjs.map +1 -1
  237. package/dist/provenance/index.d.cts +7 -7
  238. package/dist/provenance/index.d.ts +7 -7
  239. package/dist/provenance/index.js +8 -8
  240. package/dist/provenance/index.js.map +1 -1
  241. package/dist/schema/index.cjs +41 -41
  242. package/dist/schema/index.d.cts +7 -7
  243. package/dist/schema/index.d.ts +7 -7
  244. package/dist/schema/index.js +14 -14
  245. package/dist/{searchable-B4mUXZT6.d.cts → searchable-BT7j9_IK.d.cts} +2 -2
  246. package/dist/{searchable-C7jmPNLT.d.ts → searchable-CnYEancP.d.ts} +2 -2
  247. package/dist/{sqlite-Da7jiYu9.d.cts → sqlite-BrMoSsI7.d.cts} +1 -1
  248. package/dist/{sqlite-Ch5tSYQY.d.ts → sqlite-CHhZUyO5.d.ts} +1 -1
  249. package/dist/{store-view-CNcOG8bQ.d.cts → store-view-Bvdku0Ht.d.ts} +199 -35
  250. package/dist/{store-view-6C2vTWqf.d.ts → store-view-w-md0nQ4.d.cts} +199 -35
  251. package/dist/{temporal-BtrTYTiB.d.ts → temporal--x9T8K4S.d.ts} +1 -1
  252. package/dist/{temporal-CMpigMCW.d.cts → temporal-BCORwUau.d.cts} +1 -1
  253. package/dist/{types-G4sVM-76.d.cts → types-6-WJmSD4.d.cts} +1 -1
  254. package/dist/{types-D2rU5Taq.d.ts → types-COODtTJU.d.ts} +1 -1
  255. package/dist/{types-Dh-EgT-w.d.ts → types-Cjvkj0jA.d.cts} +351 -12
  256. package/dist/{types-Dh-EgT-w.d.cts → types-Cjvkj0jA.d.ts} +351 -12
  257. package/dist/{where-B8Y21kig.d.ts → where-5xVawAwL.d.ts} +1 -1
  258. package/dist/{where-DbZ9XDOI.d.cts → where-CUQmCR6d.d.cts} +1 -1
  259. package/package.json +1 -1
  260. package/dist/chunk-277UZV7X.cjs.map +0 -1
  261. package/dist/chunk-2SO5I5AI.cjs.map +0 -1
  262. package/dist/chunk-42XYPKZU.js.map +0 -1
  263. package/dist/chunk-5P6IPIT6.cjs.map +0 -1
  264. package/dist/chunk-5Q3P6OIC.cjs.map +0 -1
  265. package/dist/chunk-5ZPRE4CV.cjs.map +0 -1
  266. package/dist/chunk-6NB73BXV.js.map +0 -1
  267. package/dist/chunk-DP7KC6CL.js.map +0 -1
  268. package/dist/chunk-ECU53PMN.cjs.map +0 -1
  269. package/dist/chunk-EVFL2ZY5.js.map +0 -1
  270. package/dist/chunk-F2KVJ6FF.cjs.map +0 -1
  271. package/dist/chunk-FY4VY5EV.cjs.map +0 -1
  272. package/dist/chunk-HHBKGPEI.js.map +0 -1
  273. package/dist/chunk-K2HHCWZO.cjs.map +0 -1
  274. package/dist/chunk-KTBTSHU6.cjs.map +0 -1
  275. package/dist/chunk-LQLVJWUH.js.map +0 -1
  276. package/dist/chunk-M4GYQF2H.js.map +0 -1
  277. package/dist/chunk-NXIZL7ZZ.js.map +0 -1
  278. package/dist/chunk-O7XVCLXW.cjs.map +0 -1
  279. package/dist/chunk-OYJSYDIH.js.map +0 -1
  280. package/dist/chunk-RAWG2FEU.js.map +0 -1
  281. package/dist/chunk-U3YRCZ5L.cjs +0 -12
  282. package/dist/chunk-UTTW2Q3M.cjs.map +0 -1
  283. package/dist/chunk-UZLEQFTV.js.map +0 -1
  284. package/dist/chunk-V2GZBPY2.cjs.map +0 -1
  285. package/dist/chunk-VGMNGWBR.cjs +0 -12
  286. package/dist/chunk-WYQILW5V.js.map +0 -1
  287. package/dist/chunk-X2XOQZT3.cjs.map +0 -1
  288. package/dist/chunk-YPVQYM3L.js.map +0 -1
  289. package/dist/chunk-ZIRC2U6G.js.map +0 -1
@@ -1,12 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkXDMPDUKL_cjs = require('./chunk-XDMPDUKL.cjs');
4
-
5
- // src/graph-extension/define-graph-extension.ts
6
- function defineGraphExtension(input) {
7
- return chunkXDMPDUKL_cjs.unwrap(chunkXDMPDUKL_cjs.validateGraphExtension(input, { strict: true }));
8
- }
9
-
10
- exports.defineGraphExtension = defineGraphExtension;
11
- //# sourceMappingURL=chunk-U3YRCZ5L.cjs.map
12
- //# sourceMappingURL=chunk-U3YRCZ5L.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/backend/table-contribution.ts","../src/query/dialect/fulltext-strategy.ts","../src/query/dialect/vector-strategy.ts","../src/query/dialect/postgres.ts","../src/query/dialect/sqlite.ts","../src/query/dialect/index.ts","../src/indexes/compiler.ts"],"names":["sql","requireDefined","quoteIdentifier","parseJsonPointer","inlineSqlStringLiteral","likeEscapeClause","getSqlDialectProfile","jsonPointer"],"mappings":";;;;;;;AA+CO,IAAM,0BAAA,GAA6B;AAGnC,IAAM,uBAAA,GAA0B;;;ACrBhC,IAAM,kBAAA,GAAmD;AAAA,EAC9D,WAAA;AAAA,EACA,QAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF;AAMO,SAAS,0BACd,QAAA,EACsB;AACtB,EAAA,OAAO;AAAA,IACL,SAAA,EAAW,IAAA;AAAA,IACX,WAAW,QAAA,CAAS,SAAA;AAAA,IACpB,aAAA,EAAe,QAAA,CAAS,cAAA,CAAe,QAAA,CAAS,QAAQ,CAAA;AAAA,IACxD,eAAe,QAAA,CAAS,cAAA;AAAA,IACxB,cAAc,QAAA,CAAS;AAAA,GACzB;AACF;AAkKA,SAAS,gBAAgB,IAAA,EAAsB;AAC7C,EAAA,OAAO,CAAA,CAAA,EAAI,IAAA,CAAK,UAAA,CAAW,GAAA,EAAK,IAAI,CAAC,CAAA,CAAA,CAAA;AACvC;AAEA,SAAS,eAAe,SAAA,EAAgC;AACtD,EAAA,OAAOA,qBAAA,CAAA,EAAMA,qBAAA,CAAI,UAAA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EAAM;AACT,MAAA,OAAOA,qBAAA,CAAA,CAAA,CAAA;AAAA,IACT;AAAA,IACA,KAAK,KAAA,EAAO;AACV,MAAA,OAAOA,qBAAA,CAAA,EAAA,CAAA;AAAA,IACT;AAAA;AAEJ;AAEA,SAAS,oBAAoB,KAAA,EAAuB;AAClD,EAAA,OAAO,CAAA,CAAA,EAAI,KAAA,CAAM,UAAA,CAAW,GAAA,EAAK,IAAI,CAAC,CAAA,CAAA,CAAA;AACxC","file":"chunk-UTTW2Q3M.cjs","sourcesContent":["/**\n * Unified table-contribution contract (#129).\n *\n * Every table TypeGraph owns — whether modeled as a Drizzle table or\n * emitted as strategy-owned raw DDL — is described by a single\n * {@link TableContribution} shape. This is the one place that answers\n * \"what tables does this backend/strategy own?\", replacing the\n * previously split surfaces (Drizzle named exports, tables-factory\n * recursion, strategy raw DDL, per-table `ensureXTable` methods).\n *\n * Lives in the neutral `backend/` layer (sibling of `backend/types.ts`,\n * which `query/dialect` already depends on) and is deliberately\n * Drizzle-free, so declaring contributions does not pull the concrete\n * Drizzle backend runtime into the query/dialect layer.\n *\n * ## Identity vs. signature (prerequisite for #135)\n *\n * #135 (durable fulltext/contribution materialization) needs to make\n * \"not materialized\" vs. \"materialized but stale\" a decidable, durable\n * fact instead of an in-memory per-backend latch. That requires two\n * conceptually separate things, and #129's job is only to make both\n * *derivable* from the contract:\n *\n * - **Materialization identity** — `owner` + `logicalName` +\n * resolved physical `tableName`. Keying on `logicalName` alone is\n * insufficient: custom per-deployment table names must be\n * distinguishable, otherwise two deployments with different physical\n * names would collide on one durable marker. (#135 additionally\n * scopes this by `graphId` at persistence time.)\n * - **Drift signature** — a hash of the strategy identity/version,\n * the resolved table name(s), and the normalized `createDdl`. #129\n * guarantees `createDdl` is deterministic for a given resolved\n * configuration so the hash #135 computes is meaningful.\n *\n * The signature is intentionally **not** eagerly carried on the\n * contribution: hashing is async (Web Crypto, see `utils/hash`) and\n * #135 already owns signature persistence the same way\n * `materializeIndexes` does for declared indexes.\n */\n\n/**\n * `logicalName` of the strategy-owned fulltext slot. Used as a logic\n * discriminant (latch routing, runtime-ensure) across the strategies\n * and both backends — a shared constant so a strategy declaring a\n * different name fails loudly at the call site instead of silently\n * skipping the latched fulltext path.\n */\nexport const FULLTEXT_CONTRIBUTION_NAME = \"fulltext\";\n\n/** `owner` of core/base schema tables (not strategy-owned). */\nexport const BASE_CONTRIBUTION_OWNER = \"base\";\n\n/**\n * A single table TypeGraph owns.\n */\nexport type TableContribution = Readonly<{\n /**\n * Stable, graph- and deployment-independent identity for the logical\n * slot this contribution fills (e.g. `\"fulltext\"`). NOT the physical\n * table name. Stable across table-name overrides and across strategy\n * swaps of the *same* logical slot, so #135's durable marker can\n * survive both.\n */\n logicalName: string;\n /**\n * Identifies the producer of this contribution (e.g. a strategy id\n * like `\"tsvector\"` / `\"fts5\"`, or `\"base\"` for core schema tables).\n * Part of the #135 materialization identity and an input to the\n * drift signature — a strategy swap on the same `logicalName` is a\n * legitimate, detectable drift, not a silent reuse.\n */\n owner: string;\n /**\n * Resolved physical table name after any per-deployment name\n * override. Part of the #135 materialization identity (custom names\n * must be distinguishable) and used by diagnostics / the focused\n * bootstrap ensure.\n */\n tableName: string;\n /**\n * Idempotent (`CREATE ... IF NOT EXISTS`) statements that\n * materialize this contribution's table **and its supporting\n * indexes**. Running the full list is how the runtime ensure\n * self-heals partial states (table present, index missing) — it is\n * not a probe-and-skip. Deterministic for a given resolved\n * configuration: the canonical normalized input to #135's drift\n * signature.\n */\n createDdl: readonly string[];\n /**\n * When `true`, the post-schema-load focused ensure\n * (`loadActiveSchemaWithBootstrap`) materializes this contribution\n * on every successful schema load.\n *\n * **Invariant: only strategy-declared contributions may set this.**\n * Core/base tables are always `false` — they are created by\n * drizzle-kit / `bootstrapTables`. This is what lets the boot path\n * derive runtime contributions straight from the strategy\n * (`fulltextStrategy.ownedTables`) without walking — and generating\n * DDL for — every base table.\n */\n runtimeEnsure: boolean;\n}>;\n\n/**\n * A table a {@link FulltextStrategy} declares it owns. An alias, not a\n * distinct shape: a strategy's declaration is already authoritative\n * (no resolution step). The name documents the producer role.\n */\nexport type StrategyTableContribution = TableContribution;\n","/**\n * Fulltext Strategy — pluggable DDL + SQL generation for a dialect's\n * fulltext stack. A strategy owns every SQL statement that touches its\n * backing table: DDL, upsert (single + batch), delete (single + batch),\n * MATCH condition, rank expression, and snippet expression.\n *\n * A dialect picks one as its default; `createPostgresBackend` /\n * `createSqliteBackend` accept an override for alternate Postgres stacks\n * (pg_trgm, ParadeDB/pg_search, pgroonga) to swap the entire fulltext\n * pipeline without forking TypeGraph.\n */\nimport {\n FULLTEXT_CONTRIBUTION_NAME,\n type StrategyTableContribution,\n} from \"../../backend/table-contribution\";\nimport {\n type DeleteFulltextBatchParams,\n type DeleteFulltextParams,\n type FulltextBatchRow,\n type FulltextCapabilities,\n type FulltextQueryMode,\n type UpsertFulltextBatchParams,\n type UpsertFulltextParams,\n} from \"../../backend/types\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\n\n/**\n * Every `FulltextQueryMode` both shipped strategies accept.\n */\nexport const ALL_FULLTEXT_MODES: readonly FulltextQueryMode[] = [\n \"websearch\",\n \"phrase\",\n \"plain\",\n \"raw\",\n] as const;\n\n/**\n * Derives the `FulltextCapabilities` backends advertise from the active\n * strategy, so the two never drift.\n */\nexport function buildFulltextCapabilities(\n strategy: FulltextStrategy,\n): FulltextCapabilities {\n return {\n supported: true,\n languages: strategy.languages,\n phraseQueries: strategy.supportedModes.includes(\"phrase\"),\n prefixQueries: strategy.supportsPrefix,\n highlighting: strategy.supportsSnippets,\n };\n}\n\n/**\n * A pluggable fulltext implementation. Each strategy is expected to be\n * self-contained: given a table name, a query string, and a parse mode,\n * it emits every SQL statement the compiler and backend need — DDL,\n * reads, and writes. No out-of-band conventions across layers.\n */\nexport type FulltextStrategy = Readonly<{\n /** Human-readable identifier used in error messages and telemetry. */\n name: string;\n\n /**\n * Parse modes this strategy can translate. Callers validate against\n * this list before emitting SQL; a mode outside the set means the\n * strategy rejects the query at compile time.\n */\n supportedModes: readonly FulltextQueryMode[];\n\n /**\n * Whether the strategy can emit a per-row highlighted snippet. When\n * false, `snippetExpression` returns a literal `NULL` so callers can\n * leave the `snippet` column in place without a branch.\n */\n supportsSnippets: boolean;\n\n /**\n * Whether the strategy supports prefix queries (`foo*`). Used to\n * populate `BackendCapabilities.fulltext.prefixQueries`. A strategy\n * may support prefix queries via dedicated syntax without advertising\n * \"raw\" mode (and vice-versa).\n */\n supportsPrefix: boolean;\n\n /**\n * Whether a per-query `language` override is honored. Postgres' tsvector\n * accepts any installed regconfig at query time; SQLite FTS5's tokenizer\n * is fixed at table-create time, so the override is silently ignored.\n * Callers may surface a warning when the user passes `language` to a\n * strategy that doesn't honor it.\n */\n supportsLanguageOverride: boolean;\n\n /**\n * Languages / tokenizer names understood by the strategy. Advisory — a\n * runtime backend like Postgres may accept other installed regconfigs.\n * Used to populate `BackendCapabilities.fulltext.languages`.\n */\n languages: readonly string[];\n\n /**\n * Emits the WHERE-side MATCH expression.\n *\n * @example\n * tsvector: `\"typegraph_node_fulltext\".\"tsv\" @@ websearch_to_tsquery('english', 'cats')`\n * fts5: `\"typegraph_node_fulltext\" MATCH '\"cats\"'`\n */\n matchCondition: (\n this: void,\n tableName: string,\n query: string,\n mode: FulltextQueryMode,\n language?: string,\n ) => SqlFragment;\n\n /**\n * Emits the relevance expression. Higher values = more relevant. The\n * compiler orders by this expression DESC, and both builder and\n * backend-direct paths use the same form so their top-k results agree.\n */\n rankExpression: (\n this: void,\n tableName: string,\n query: string,\n mode: FulltextQueryMode,\n language?: string,\n ) => SqlFragment;\n\n /**\n * Emits a per-row highlighted snippet expression, or `NULL` when\n * `supportsSnippets` is false. Snippet markup is `<mark>…</mark>` in\n * both shipped strategies so consumers can apply one stylesheet.\n */\n snippetExpression: (\n this: void,\n tableName: string,\n query: string,\n mode: FulltextQueryMode,\n language?: string,\n ) => SqlFragment;\n\n /**\n * The tables this strategy owns, as Drizzle-free, already\n * authoritative `TableContribution`s (`logicalName`, `owner`,\n * resolved `tableName`, idempotent `createDdl` for the table **and\n * its supporting indexes**, `runtimeEnsure`). A strategy never\n * constructs a Drizzle table itself; drizzle-kit visibility, when\n * applicable, is the schema barrel's responsibility (the default\n * Postgres strategy's `schema/postgres.ts` exports a matching\n * `tables.fulltext` — a non-default strategy must export its own).\n *\n * Replaces the former `generateDdl(tableName)`: DDL is now one field\n * of a contribution rather than the strategy's whole storage\n * surface. (Public API change — see #129.)\n */\n ownedTables: (\n this: void,\n primaryTableName: string,\n ) => readonly StrategyTableContribution[];\n\n /**\n * Emits the statements that upsert a single fulltext row. Returns one\n * or more statements — some backends (SQLite FTS5) cannot emulate\n * upsert in a single statement and need DELETE + INSERT.\n */\n buildUpsert: (\n this: void,\n tableName: string,\n params: UpsertFulltextParams,\n timestamp: string,\n ) => readonly SqlFragment[];\n\n /**\n * Emits the statements that upsert many fulltext rows at once. Input\n * rows are expected to be de-duplicated last-write-wins by the\n * strategy if the underlying SQL statement cannot tolerate duplicate\n * conflict keys. Returns `[]` when `params.rows` is empty.\n */\n buildBatchUpsert: (\n this: void,\n tableName: string,\n params: UpsertFulltextBatchParams,\n timestamp: string,\n ) => readonly SqlFragment[];\n\n /**\n * Emits the statements that delete a single fulltext row. Normally a\n * single PK-scoped DELETE, but strategies that maintain auxiliary\n * indexes (delete-triggered external stores, ParadeDB-style secondary\n * structures) may need more.\n */\n buildDelete: (\n this: void,\n tableName: string,\n params: DeleteFulltextParams,\n ) => readonly SqlFragment[];\n\n /**\n * Emits the statements that delete many fulltext rows at once. Returns\n * `[]` when `params.nodeIds` is empty.\n */\n buildBatchDelete: (\n this: void,\n tableName: string,\n params: DeleteFulltextBatchParams,\n ) => readonly SqlFragment[];\n}>;\n\n// ============================================================\n// Internal helpers\n// ============================================================\n\nfunction quoteIdentifier(name: string): string {\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction tsvectorColumn(tableName: string): SqlFragment {\n return sql`${sql.identifier(tableName)}.\"tsv\"`;\n}\n\n/**\n * Dedupes batch rows last-write-wins by nodeId. Returns a plain array\n * in insertion order of the last occurrence of each id. Shared by both\n * shipped strategies.\n */\nfunction dedupeFulltextBatchRows(\n rows: readonly FulltextBatchRow[],\n): FulltextBatchRow[] {\n const seen = new Map<string, FulltextBatchRow>();\n for (const row of rows) seen.set(row.nodeId, row);\n return [...seen.values()];\n}\n\nfunction buildPkScopedDelete(\n tableName: string,\n params: DeleteFulltextParams,\n): SqlFragment {\n const table = sql.identifier(tableName);\n return sql`\n DELETE FROM ${table}\n WHERE \"graph_id\" = ${params.graphId}\n AND \"node_kind\" = ${params.nodeKind}\n AND \"node_id\" = ${params.nodeId}\n `;\n}\n\nfunction buildPkScopedBatchDelete(\n tableName: string,\n params: DeleteFulltextBatchParams,\n): SqlFragment | undefined {\n if (params.nodeIds.length === 0) return undefined;\n const unique = [...new Set(params.nodeIds)];\n const table = sql.identifier(tableName);\n return sql`\n DELETE FROM ${table}\n WHERE \"graph_id\" = ${params.graphId}\n AND \"node_kind\" = ${params.nodeKind}\n AND \"node_id\" IN (${sql.join(\n unique.map((id) => sql`${id}`),\n sql`, `,\n )})\n `;\n}\n\n// ============================================================\n// tsvector strategy (PostgreSQL built-in)\n// ============================================================\n\nfunction postgresTsquery(\n mode: FulltextQueryMode,\n query: string,\n language: string | undefined,\n): SqlFragment {\n // The `language` column is already `regconfig`, so the non-override\n // path references the column directly. The per-query override path\n // still arrives as a bound text parameter and needs the cast.\n const langExpr: SqlFragment =\n language === undefined ? sql`\"language\"` : sql`${language}::regconfig`;\n switch (mode) {\n case \"websearch\": {\n return sql`websearch_to_tsquery(${langExpr}, ${query})`;\n }\n case \"phrase\": {\n return sql`phraseto_tsquery(${langExpr}, ${query})`;\n }\n case \"plain\": {\n return sql`plainto_tsquery(${langExpr}, ${query})`;\n }\n case \"raw\": {\n return sql`to_tsquery(${langExpr}, ${query})`;\n }\n default: {\n const _exhaustive: never = mode;\n throw new Error(`Unsupported fulltext mode: ${String(_exhaustive)}`);\n }\n }\n}\n\nexport const tsvectorStrategy: FulltextStrategy = {\n name: \"tsvector\",\n supportedModes: ALL_FULLTEXT_MODES,\n supportsSnippets: true,\n // `raw` mode exposes `foo:*` prefix-match syntax to callers.\n supportsPrefix: true,\n supportsLanguageOverride: true,\n // Canonical Postgres stemmers; every stock install ships these plus a\n // few others. Runtime `to_tsvector` accepts any installed regconfig\n // name — this list is advisory for capability discovery.\n languages: [\n \"simple\",\n \"english\",\n \"french\",\n \"german\",\n \"italian\",\n \"portuguese\",\n \"russian\",\n \"spanish\",\n \"swedish\",\n ] as const,\n\n matchCondition(tableName, query, mode, language) {\n const q = postgresTsquery(mode, query, language);\n return sql`${tsvectorColumn(tableName)} @@ ${q}`;\n },\n\n rankExpression(tableName, query, mode, language) {\n const q = postgresTsquery(mode, query, language);\n return sql`ts_rank_cd(${tsvectorColumn(tableName)}, ${q})`;\n },\n\n snippetExpression(_tableName, query, mode, language) {\n const langExpr: SqlFragment =\n language === undefined ? sql`\"language\"` : sql`${language}::regconfig`;\n const q = postgresTsquery(mode, query, language);\n return sql`ts_headline(${langExpr}, \"content\", ${q}, 'StartSel=<mark>,StopSel=</mark>,MaxFragments=1,MinWords=5,MaxWords=30,ShortWord=3')`;\n },\n\n ownedTables(primaryTableName) {\n const name = quoteIdentifier(primaryTableName);\n const gin = quoteIdentifier(`${primaryTableName}_tsv_idx`);\n const kind = quoteIdentifier(`${primaryTableName}_kind_idx`);\n // `language` is `regconfig` so `to_tsvector(\"language\", \"content\")`\n // is an immutable expression — Postgres can then compute `tsv` as a\n // GENERATED STORED column and own the `content → tsv` invariant.\n // (The text→regconfig cast happens once at INSERT time against the\n // bound parameter, which is fine because it's not inside the\n // generated expression.)\n const createDdl = [\n `CREATE TABLE IF NOT EXISTS ${name} (\n \"graph_id\" TEXT NOT NULL,\n \"node_kind\" TEXT NOT NULL,\n \"node_id\" TEXT NOT NULL,\n \"content\" TEXT NOT NULL,\n \"language\" regconfig NOT NULL,\n \"tsv\" tsvector NOT NULL\n GENERATED ALWAYS AS (to_tsvector(\"language\", \"content\")) STORED,\n \"updated_at\" TIMESTAMPTZ NOT NULL,\n PRIMARY KEY (\"graph_id\", \"node_kind\", \"node_id\")\n);`,\n `CREATE INDEX IF NOT EXISTS ${gin} ON ${name} USING GIN (\"tsv\");`,\n `CREATE INDEX IF NOT EXISTS ${kind} ON ${name} (\"graph_id\", \"node_kind\");`,\n ];\n // drizzle-kit visibility for this default strategy comes from\n // `schema/postgres.ts` exporting the matching `tables.fulltext`\n // pgTable through the barrel — one object, not two. `runtimeEnsure`\n // because drizzle-kit-managed setups create every base table except\n // this strategy-owned one.\n return [\n {\n logicalName: FULLTEXT_CONTRIBUTION_NAME,\n owner: \"tsvector\",\n tableName: primaryTableName,\n createDdl,\n runtimeEnsure: true,\n },\n ];\n },\n\n buildUpsert(tableName, params, timestamp) {\n const table = sql.identifier(tableName);\n // `tsv` is a GENERATED STORED column — Postgres computes it from\n // `content` + `language`, so it must not appear in the column list\n // or the ON CONFLICT update set.\n return [\n sql`\n INSERT INTO ${table} (\"graph_id\", \"node_kind\", \"node_id\", \"content\", \"language\", \"updated_at\")\n VALUES (\n ${params.graphId}, ${params.nodeKind}, ${params.nodeId},\n ${params.content}, ${params.language}::regconfig,\n ${timestamp}\n )\n ON CONFLICT (\"graph_id\", \"node_kind\", \"node_id\")\n DO UPDATE SET\n \"content\" = EXCLUDED.\"content\",\n \"language\" = EXCLUDED.\"language\",\n \"updated_at\" = EXCLUDED.\"updated_at\"\n `,\n ];\n },\n\n buildBatchUpsert(tableName, params, timestamp) {\n const rows = dedupeFulltextBatchRows(params.rows);\n if (rows.length === 0) return [];\n\n const table = sql.identifier(tableName);\n const valueTuples = rows.map(\n (row) => sql`\n (\n ${params.graphId}, ${params.nodeKind}, ${row.nodeId},\n ${row.content}, ${row.language}::regconfig,\n ${timestamp}\n )\n `,\n );\n\n return [\n sql`\n INSERT INTO ${table} (\"graph_id\", \"node_kind\", \"node_id\", \"content\", \"language\", \"updated_at\")\n VALUES ${sql.join(valueTuples, sql`, `)}\n ON CONFLICT (\"graph_id\", \"node_kind\", \"node_id\")\n DO UPDATE SET\n \"content\" = EXCLUDED.\"content\",\n \"language\" = EXCLUDED.\"language\",\n \"updated_at\" = EXCLUDED.\"updated_at\"\n `,\n ];\n },\n\n buildDelete(tableName, params) {\n return [buildPkScopedDelete(tableName, params)];\n },\n\n buildBatchDelete(tableName, params) {\n const stmt = buildPkScopedBatchDelete(tableName, params);\n return stmt === undefined ? [] : [stmt];\n },\n};\n\n// ============================================================\n// FTS5 strategy (SQLite)\n// ============================================================\n\nfunction translateToFts5Query(query: string, mode: FulltextQueryMode): string {\n switch (mode) {\n case \"phrase\": {\n return `\"${query.replaceAll('\"', '\"\"')}\"`;\n }\n case \"plain\": {\n return query\n .trim()\n .split(/\\s+/u)\n .filter((token) => token.length > 0)\n .map((token) => `\"${token.replaceAll('\"', '\"\"')}\"`)\n .join(\" \");\n }\n case \"websearch\": {\n return translateWebsearchToFts5(query);\n }\n case \"raw\": {\n return query;\n }\n default: {\n const _exhaustive: never = mode;\n throw new Error(`Unsupported fulltext mode: ${String(_exhaustive)}`);\n }\n }\n}\n\nfunction translateWebsearchToFts5(query: string): string {\n const tokens: string[] = [];\n let index = 0;\n\n function skipWhitespace(): void {\n while (index < query.length && /\\s/u.test(query[index] ?? \"\")) {\n index += 1;\n }\n }\n\n function readPhrase(): string {\n index += 1;\n let content = \"\";\n while (index < query.length && query[index] !== '\"') {\n content += query[index] ?? \"\";\n index += 1;\n }\n if (query[index] === '\"') index += 1;\n return `\"${content.replaceAll('\"', '\"\"')}\"`;\n }\n\n function readBareTerm(): string {\n let term = \"\";\n while (index < query.length && !/\\s/u.test(query[index] ?? \"\")) {\n term += query[index] ?? \"\";\n index += 1;\n }\n return term;\n }\n\n while (index < query.length) {\n skipWhitespace();\n if (index >= query.length) break;\n const ch = query[index];\n if (ch === '\"') {\n tokens.push(readPhrase());\n continue;\n }\n if (ch === \"-\") {\n index += 1;\n const term =\n query[index] === '\"' ?\n readPhrase()\n : `\"${readBareTerm().replaceAll('\"', '\"\"')}\"`;\n tokens.push(`NOT ${term}`);\n continue;\n }\n if (ch === \"+\") {\n index += 1;\n continue;\n }\n const bare = readBareTerm();\n if (bare.length === 0) continue;\n if (bare.toUpperCase() === \"OR\") {\n tokens.push(\"OR\");\n continue;\n }\n tokens.push(`\"${bare.replaceAll('\"', '\"\"')}\"`);\n }\n\n if (tokens.length > 0 && tokens[0]?.startsWith(\"NOT \")) {\n tokens.shift();\n }\n\n return tokens.join(\" \");\n}\n\nexport const fts5Strategy: FulltextStrategy = {\n name: \"fts5\",\n supportedModes: ALL_FULLTEXT_MODES,\n supportsSnippets: true,\n // FTS5 supports `foo*` prefix matching natively.\n supportsPrefix: true,\n // FTS5 tokenizer is fixed at table-create time; per-row / per-query\n // language metadata is stored but not consulted.\n supportsLanguageOverride: false,\n // The built-in tokenizer is `porter unicode61 remove_diacritics 2`; the\n // `language` field on searchable() is recorded for future use but not\n // applied at query time.\n languages: [\"porter\", \"unicode61\", \"trigram\"] as const,\n\n matchCondition(tableName, query, mode, _language) {\n const matchExpression = translateToFts5Query(query, mode);\n return sql`${sql.identifier(tableName)} MATCH ${matchExpression}`;\n },\n\n rankExpression(tableName, _query, _mode, _language) {\n // FTS5 bm25() returns a negative score where lower = more relevant.\n // Negate so callers see higher = better (uniform with tsvector).\n return sql`-bm25(${sql.identifier(tableName)})`;\n },\n\n snippetExpression(tableName, _query, _mode, _language) {\n return sql`snippet(${sql.identifier(tableName)}, -1, '<mark>', '</mark>', '…', 20)`;\n },\n\n ownedTables(primaryTableName) {\n const name = quoteIdentifier(primaryTableName);\n // FTS5 virtual tables cannot be modeled as a Drizzle table, so this\n // contribution is raw-ddl: emitted verbatim and invisible to\n // drizzle-kit. `runtimeEnsure` because no drizzle-kit-managed setup\n // can create it.\n return [\n {\n logicalName: FULLTEXT_CONTRIBUTION_NAME,\n owner: \"fts5\",\n tableName: primaryTableName,\n createDdl: [\n `CREATE VIRTUAL TABLE IF NOT EXISTS ${name} USING fts5(\n graph_id UNINDEXED,\n node_kind UNINDEXED,\n node_id UNINDEXED,\n language UNINDEXED,\n updated_at UNINDEXED,\n content,\n tokenize='porter unicode61 remove_diacritics 2'\n);`,\n ],\n runtimeEnsure: true,\n },\n ];\n },\n\n buildUpsert(tableName, params, timestamp) {\n const table = sql.identifier(tableName);\n // FTS5 virtual tables don't support ON CONFLICT — emulate with\n // DELETE + INSERT, atomic under the caller's outer transaction.\n return [\n sql`\n DELETE FROM ${table}\n WHERE \"graph_id\" = ${params.graphId}\n AND \"node_kind\" = ${params.nodeKind}\n AND \"node_id\" = ${params.nodeId}\n `,\n sql`\n INSERT INTO ${table} (graph_id, node_kind, node_id, content, language, updated_at)\n VALUES (${params.graphId}, ${params.nodeKind}, ${params.nodeId}, ${params.content}, ${params.language}, ${timestamp})\n `,\n ];\n },\n\n buildBatchUpsert(tableName, params, timestamp) {\n const rows = dedupeFulltextBatchRows(params.rows);\n if (rows.length === 0) return [];\n\n const table = sql.identifier(tableName);\n const nodeIds = rows.map((row) => row.nodeId);\n\n const deleteStmt = sql`\n DELETE FROM ${table}\n WHERE \"graph_id\" = ${params.graphId}\n AND \"node_kind\" = ${params.nodeKind}\n AND \"node_id\" IN (${sql.join(\n nodeIds.map((id) => sql`${id}`),\n sql`, `,\n )})\n `;\n\n const valueTuples = rows.map(\n (row) => sql`\n (\n ${params.graphId}, ${params.nodeKind}, ${row.nodeId},\n ${row.content}, ${row.language}, ${timestamp}\n )\n `,\n );\n\n const insertStmt = sql`\n INSERT INTO ${table} (graph_id, node_kind, node_id, content, language, updated_at)\n VALUES ${sql.join(valueTuples, sql`, `)}\n `;\n\n return [deleteStmt, insertStmt];\n },\n\n buildDelete(tableName, params) {\n return [buildPkScopedDelete(tableName, params)];\n },\n\n buildBatchDelete(tableName, params) {\n const stmt = buildPkScopedBatchDelete(tableName, params);\n return stmt === undefined ? [] : [stmt];\n },\n};\n","/**\n * Vector Strategy — pluggable storage + SQL generation for a backend's\n * vector stack. The sibling of {@link FulltextStrategy}: a strategy owns\n * every statement that touches its embedding storage — the per-field DDL,\n * upsert, delete, similarity search, and (optional) ANN index lifecycle —\n * plus the capability advertisement and the distance/score expressions the\n * query compiler splices into its relevance CTE.\n *\n * ## Why a strategy, and why per-(kind, field) storage\n *\n * The spike behind #157 established that \"real\" ANN on every engine we\n * support converges on a\n * **typed, fixed-dimension structure per `(nodeKind, fieldPath)`**:\n *\n * - pgvector: a `vector(N)` column + HNSW/IVFFlat;\n * - libSQL native: an `F32_BLOB(N)` column + `libsql_vector_idx` +\n * `vector_top_k` (a plain `BLOB` or dimensionless `F32_BLOB` is rejected\n * by the index — the dimension must live in the column type);\n * - sqlite-vec: a `vec0(embedding float[N])` virtual table.\n *\n * The legacy single shared `typegraph_node_embeddings` table (one generic\n * column holding mixed-dimension vectors) can only ever be brute-forced;\n * pgvector was the sole engine that hid this, because its index supplies the\n * dimension via a `::vector(N)` cast expression. So storage is the\n * strategy's to own, slot by slot, rather than a fixed global table.\n *\n * Brute force remains a legitimate, capability-advertised mode (libSQL's\n * `vector_distance_cos` over a column with no index, sqlite-vec's\n * `vec_distance_cosine`): a strategy whose `capabilities.indexTypes` is\n * `[\"none\"]` simply never emits an ANN index and `buildSearch` always scans.\n */\nimport { type StrategyTableContribution } from \"../../backend/table-contribution\";\nimport {\n type DeleteEmbeddingParams,\n type UpsertEmbeddingBatchParams,\n type UpsertEmbeddingParams,\n type VectorCapabilities,\n type VectorIndexType,\n type VectorMetric,\n type VectorSearchParams,\n} from \"../../backend/types\";\nimport { requireDefined } from \"../../utils/presence\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\n\n/**\n * `logicalName` prefix of a strategy-owned vector slot. Each\n * `(nodeKind, fieldPath)` pair fills one logical vector slot; the full\n * logical name is `${VECTOR_CONTRIBUTION_PREFIX}:${nodeKind}.${fieldPath}`,\n * stable across table-name overrides and strategy swaps so #135's durable\n * materialization marker survives both.\n */\nexport const VECTOR_CONTRIBUTION_PREFIX = \"vector\";\n\n/**\n * The resolved identity of one embedding field's storage in a graph —\n * everything a strategy needs to DDL, address, and index it.\n *\n * Graph-scoped: each `(graphId, nodeKind, fieldPath)` gets its own physical\n * table. TypeGraph supports many graphs per physical database, and the same\n * `(kind, field)` can carry different embedding dimensions across graphs — a\n * shared per-`(kind, field)` table would collide on the fixed column type\n * (`vector(N)` / `F32_BLOB(N)`). Graph-scoping also makes libSQL's\n * table-global `vector_top_k` per-graph-exact (no cross-graph recall bleed).\n */\nexport type VectorSlot = Readonly<{\n /** Graph the embedding belongs to — scopes the physical table. */\n graphId: string;\n /** Node kind owning the embedding field (e.g. `\"Document\"`). */\n nodeKind: string;\n /** Dot-path of the embedding field within the node props (e.g. `\"embedding\"`). */\n fieldPath: string;\n /** Fixed vector dimension `N` for this field — carried into the column type. */\n dimensions: number;\n /** Distance metric the field's index is built for. */\n metric: VectorMetric;\n /**\n * Index type to materialize. `\"none\"` means brute-force only (no ANN\n * index emitted); the strategy still stores and searches the field.\n */\n indexType: VectorIndexType;\n /**\n * Optional ANN index tuning carried into the index DDL (pgvector\n * `m`/`ef_construction`/`lists`). Present on the create-index / re-embed\n * paths (resolved from the field's `embedding()` declaration); omitted on\n * the write/search ensure paths, where the strategy falls back to defaults.\n */\n indexParams?: Readonly<{\n m?: number;\n efConstruction?: number;\n lists?: number;\n }>;\n}>;\n\n/**\n * Derives the `VectorCapabilities` a backend advertises from its active\n * strategy, so the two never drift (mirrors `buildFulltextCapabilities`).\n * The strategy is the single source of truth; there are no per-call-site\n * `SQLITE_VECTOR_*` constants.\n */\nexport function buildVectorCapabilities(\n strategy: VectorStrategy,\n): VectorCapabilities {\n return strategy.capabilities;\n}\n\n/**\n * A pluggable vector implementation. Each strategy is self-contained:\n * given a {@link VectorSlot}, it emits every statement the backend and\n * compiler need — per-field storage DDL, writes, similarity search, ANN\n * index lifecycle — and advertises exactly the metrics and index types it\n * can honor. Adding the Nth backend is one of these objects; no core edits.\n */\nexport type VectorStrategy = Readonly<{\n /** Human-readable identifier used in error messages and telemetry. */\n name: string;\n\n /**\n * The metrics, index types, and dimension ceiling this strategy honors —\n * advertised verbatim as `backend.capabilities.vector`. Asymmetry across\n * engines is legitimate and explicit here (pgvector has `inner_product`;\n * libSQL/sqlite-vec do not), never a silent runtime failure.\n */\n capabilities: VectorCapabilities;\n\n /**\n * Deterministic physical table (or virtual-table) name backing a field in\n * a graph. The compiler references this to scan the right per-field storage,\n * and the backend uses it to route upserts/deletes. Must be a stable,\n * collision-safe SQL identifier derived from `(graphId, nodeKind, fieldPath)`.\n */\n tableName: (\n this: void,\n graphId: string,\n nodeKind: string,\n fieldPath: string,\n ) => string;\n\n /**\n * The per-field storage this strategy owns for `slot`, as Drizzle-free\n * `StrategyTableContribution`s (resolved `tableName`, deterministic\n * idempotent `createDdl` for the table **and** its ANN index when the\n * slot's `indexType` warrants one, `runtimeEnsure`). Rides the #129/#135\n * table-contribution + durable-materialization machinery exactly as the\n * FTS5 / tsvector virtual tables do — these are materialized per graph by\n * `materializeIndexes()`, not by global `bootstrapTables`.\n */\n ownedTables: (\n this: void,\n slot: VectorSlot,\n ) => readonly StrategyTableContribution[];\n\n /**\n * Emits the statement(s) that upsert a single embedding into the slot's\n * storage. Multiple statements are allowed for engines that cannot upsert\n * a vector in one statement (e.g. a `vec0` virtual table → DELETE+INSERT).\n */\n buildUpsert: (\n this: void,\n slot: VectorSlot,\n params: UpsertEmbeddingParams,\n timestamp: string,\n ) => readonly SqlFragment[];\n\n /**\n * Emits the statement(s) that upsert MANY embeddings into the slot's\n * storage in multi-row form. Optional — the backend falls back to one\n * {@link buildUpsert} per row when unset. The backend guarantees the\n * rows carry distinct `nodeId`s and fit the connection's bound-parameter\n * budget (it chunks before calling).\n */\n buildUpsertBatch?: (\n this: void,\n slot: VectorSlot,\n params: UpsertEmbeddingBatchParams,\n timestamp: string,\n ) => readonly SqlFragment[];\n\n /** Emits the statement(s) that delete a single embedding from the slot. */\n buildDelete: (\n this: void,\n slot: VectorSlot,\n params: DeleteEmbeddingParams,\n ) => readonly SqlFragment[];\n\n /**\n * Raw DDL statement(s) that drop the slot's entire physical storage\n * (table + ANN index, and any engine-managed shadow tables). Used by the\n * destructive `store.reembedVectorField()` path to recreate a field's\n * storage at a new dimension. Returned as raw strings (like\n * `ownedTables(...).createDdl`) for `backend.executeDdl`; must be idempotent\n * (`IF EXISTS`).\n */\n buildDropStorage: (this: void, slot: VectorSlot) => readonly string[];\n\n /**\n * Emits the similarity-search query for the `backend.vectorSearch` path,\n * returning rows shaped `{ node_id, score }` ordered best-first. The\n * strategy picks brute-force vs ANN based on whether `slot.indexType`\n * materialized an index — the caller never branches. `score` follows the\n * shared convention (cosine → similarity `1 - distance`; l2 /\n * inner_product → raw distance), so `coerceVectorScore` / fusion stay\n * dialect-neutral.\n *\n * `candidates`, when provided, is a subquery yielding the node ids\n * eligible to appear in results (the backend passes its live-node-ids\n * subquery so top-k is computed over live rows in SQL — see\n * `liveNodeIdsSubquery`). Strategies whose ANN form cannot take the\n * filter directly must over-fetch and post-filter, documenting the\n * recall bound. A custom strategy that ignores the argument keeps the\n * pre-pushdown behavior: tombstoned ids are dropped after top-k during\n * hydration, so results can shrink below `limit` under index drift.\n */\n buildSearch: (\n this: void,\n slot: VectorSlot,\n params: VectorSearchParams,\n candidates?: SqlFragment,\n ) => SqlFragment;\n\n /**\n * True when {@link buildSearch} returns EXACT rankings — a brute-force\n * engine form, not an approximate index (sqlite-vec's vec0 KNN scans\n * every row in C). The query compiler then routes the NON-approximate\n * `.similarTo()` branch through `buildSearch` too: same results as the\n * SQL distance scan, at engine speed (measured 489ms -> 113ms at 50k\n * on the SQLite lane). Leave false/absent when the engine form is or\n * can be approximate (pgvector planner rewrites, libSQL DiskANN):\n * exactness of the default path is a semantic guarantee.\n */\n searchIsExact?: boolean;\n\n /**\n * The distance expression over the slot's embedding column, used by the\n * **query compiler** to splice vector relevance into its CTE. This is the\n * one genuinely engine-specific fragment (`vec_distance_cosine` vs\n * `<=>` vs `vector_distance_cos`); the surrounding score / minScore /\n * ORDER BY math is shared (see {@link vectorScoreExpression} etc.).\n *\n * `embeddingColumn` is the already-qualified column SQL; `queryEmbedding`\n * is formatted by the strategy into its engine's literal form.\n */\n distanceExpression: (\n this: void,\n embeddingColumn: SqlFragment,\n queryEmbedding: readonly number[],\n metric: VectorMetric,\n ) => SqlFragment;\n\n /**\n * Emits the ANN index creation statement for a slot, or `undefined` when\n * indexing is inline (vec0) or unsupported (brute-force-only strategies).\n * Invoked through `backend.createVectorIndex` during `materializeIndexes`.\n */\n buildCreateIndex?: (\n this: void,\n slot: VectorSlot,\n options?: Readonly<{ concurrent?: boolean }>,\n ) => SqlFragment | undefined;\n\n /** Emits the ANN index drop statement, or `undefined` when not applicable. */\n buildDropIndex?: (this: void, slot: VectorSlot) => SqlFragment | undefined;\n}>;\n\n// ============================================================\n// Shared, dialect-neutral expression math\n// ============================================================\n//\n// These transforms are identical across pgvector / sqlite-vec / libSQL —\n// only `distanceExpression` differs — so they live once here and are reused\n// by both `buildSearch` implementations and the compiler CTE builder.\n\n/**\n * Converts a distance expression into a score expression (higher = better).\n * Cosine distance is mapped to similarity (`1 - d`); l2 and inner_product\n * are returned as-is (lower distance already ranks better, ordered ASC).\n */\nexport function vectorScoreExpression(\n distanceExpression: SqlFragment,\n metric: VectorMetric,\n): SqlFragment {\n switch (metric) {\n case \"cosine\": {\n return sql`(1 - (${distanceExpression}))`;\n }\n case \"l2\":\n case \"inner_product\": {\n return distanceExpression;\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);\n }\n }\n}\n\n/**\n * Builds the `minScore` WHERE condition against a distance expression,\n * translating the score threshold back into the metric's distance space.\n */\nexport function vectorMinScoreCondition(\n distanceExpression: SqlFragment,\n metric: VectorMetric,\n minScore: number,\n): SqlFragment {\n // Validate against the RESOLVED metric — both the compiler's relevance CTE\n // and the backend search path funnel here, so an out-of-range floor (e.g. a\n // cosine minScore of 5 → `distance <= 1 - 5`, which matches nothing) is\n // rejected loudly instead of silently returning zero rows.\n assertVectorMinScore(minScore, metric);\n switch (metric) {\n case \"cosine\": {\n return sql`${distanceExpression} <= ${1 - minScore}`;\n }\n case \"l2\": {\n return sql`${distanceExpression} <= ${minScore}`;\n }\n case \"inner_product\": {\n return sql`${distanceExpression} <= ${-minScore}`;\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);\n }\n }\n}\n\n/**\n * Validates that every value in an embedding is a finite number. Shared by\n * strategies so a NaN/Infinity is reported with the offending index before\n * it reaches engine-specific literal formatting (which would mask it).\n */\nexport function assertFiniteEmbedding(\n embedding: readonly number[],\n name: string,\n): void {\n for (const [index, value] of embedding.entries()) {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new TypeError(\n `${name}[${index}] must be a finite number, got: ${value}`,\n );\n }\n }\n}\n\n/**\n * Validates a vector-search `limit` is a positive integer. Enforced by the\n * backend's `vectorSearch` (defense in depth — the store boundary also\n * checks) so a direct backend call with `limit: 0` fails loudly instead of\n * silently scanning nothing.\n */\nexport function assertVectorSearchLimit(limit: number): void {\n if (!Number.isInteger(limit) || limit <= 0) {\n throw new RangeError(\n `vectorSearch limit must be a positive integer, got: ${limit}`,\n );\n }\n}\n\n/**\n * Validates a `minScore` floor against its (resolved) metric: it must be finite,\n * and for cosine it must lie in [-1, 1] (a cosine score is the `1 - distance`\n * similarity). Shared by the store facade, the compiler's relevance CTE\n * ({@link vectorMinScoreCondition}), and the backend search path so every entry\n * point rejects the same out-of-range floor instead of silently returning none.\n */\nexport function assertVectorMinScore(\n minScore: number,\n metric: VectorMetric,\n label = \"minScore\",\n): void {\n if (!Number.isFinite(minScore)) {\n throw new RangeError(`${label} must be a finite number, got: ${minScore}`);\n }\n if (metric === \"cosine\" && Math.abs(minScore) > 1) {\n throw new RangeError(\n `${label} for the cosine metric must be between -1 and 1, got: ${minScore}`,\n );\n }\n}\n\n// ============================================================\n// Shared physical naming\n// ============================================================\n\n/**\n * pgvector inherits Postgres' 63-byte identifier ceiling; SQLite/libSQL are\n * far more generous, so the smallest common cap keeps one naming scheme\n * across every strategy.\n */\nconst MAX_VECTOR_IDENTIFIER_LENGTH = 63;\n\nfunction sanitizeIdentifierPart(value: string): string {\n return value.toLowerCase().replaceAll(/[^a-z0-9_]/g, \"_\");\n}\n\n/**\n * Deterministic 8-char hash for collision-safe truncation of over-long\n * identifiers. Self-contained so the strategy layer has no backend-runtime\n * dependency.\n */\nexport function shortHash(input: string): string {\n let h1 = 0xde_ad_be_ef;\n let h2 = 0x41_c6_ce_57;\n for (let index = 0; index < input.length; index++) {\n const ch = requireDefined(input.codePointAt(index));\n h1 = Math.imul(h1 ^ ch, 0x9e_37_79_b1);\n h2 = Math.imul(h2 ^ ch, 0x5f_35_64_95);\n }\n h1 =\n Math.imul(h1 ^ (h1 >>> 16), 0x85_eb_ca_6b) ^\n Math.imul(h2 ^ (h2 >>> 13), 0xc2_b2_ae_35);\n h2 =\n Math.imul(h2 ^ (h2 >>> 16), 0x85_eb_ca_6b) ^\n Math.imul(h1 ^ (h1 >>> 13), 0xc2_b2_ae_35);\n const hi = (h2 >>> 0).toString(16).padStart(8, \"0\");\n const lo = (h1 >>> 0).toString(16).padStart(8, \"0\");\n return `${hi}${lo}`.slice(0, 8);\n}\n\n/**\n * Deterministic per-`(graphId, nodeKind, fieldPath)` physical name. Shared by\n * every strategy's `tableName`, by index naming, and by the compiler's\n * per-field table resolution so all three agree on which physical object backs\n * a field in a graph. Truncated with a hash suffix past the 63-char ceiling;\n * the hash covers all three parts, so truncation stays collision-safe even\n * when long graph ids dominate the prefix.\n *\n * @example `vectorPhysicalName(\"tg_vec\", \"g1\", \"Document\", \"embedding\")`\n * → `\"tg_vec_g1_document_embedding_<hash8>\"`\n */\nexport function vectorPhysicalName(\n prefix: string,\n graphId: string,\n nodeKind: string,\n fieldPath: string,\n): string {\n const readable = `${prefix}_${sanitizeIdentifierPart(graphId)}_${sanitizeIdentifierPart(nodeKind)}_${sanitizeIdentifierPart(fieldPath)}`;\n // Always suffix a hash of the EXACT (graphId, nodeKind, fieldPath) tuple.\n // Sanitization is lossy (case-folding, every non-`[a-z0-9_]` char → `_`) and\n // the `_` join is ambiguous, so distinct fields can share a readable part —\n // e.g. (\"a_b\",\"c\") vs (\"a\",\"b_c\"), or \"Doc-A\" vs \"Doc_A\" vs \"doc\". The hash\n // keeps their physical tables distinct so writes/searches never cross fields.\n const hash = shortHash(JSON.stringify([graphId, nodeKind, fieldPath]));\n const full = `${readable}_${hash}`;\n if (full.length <= MAX_VECTOR_IDENTIFIER_LENGTH) return full;\n // Over the ceiling: truncate the readable part, always keep the hash.\n return `${readable.slice(0, MAX_VECTOR_IDENTIFIER_LENGTH - 1 - hash.length)}_${hash}`;\n}\n\n/**\n * Double-quote a SQL identifier, escaping embedded quotes. Dialect-neutral\n * (both SQLite and Postgres use `\"...\"`), so the three vector strategies share\n * one implementation for quoting their per-field table / index names.\n */\nexport function quoteIdentifier(name: string): string {\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n}\n","/**\n * PostgreSQL Dialect Adapter\n *\n * Implements dialect-specific SQL generation for PostgreSQL databases.\n * Uses PostgreSQL's native JSONB operators for JSON operations.\n */\nimport { type JsonPointer, parseJsonPointer } from \"../json-pointer\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\nimport { tsvectorStrategy } from \"./fulltext-strategy\";\nimport { likeEscapeClause } from \"./like-escape\";\nimport { getSqlDialectProfile, inlineSqlStringLiteral } from \"./profile\";\nimport { type DialectAdapter } from \"./types\";\n\n/**\n * Escapes a string for use in a PostgreSQL string literal, independent of\n * server configuration.\n *\n * A plain `'…'` literal is only safe when the value contains no backslash:\n * under the legacy `standard_conforming_strings = off` setting, backslashes\n * act as escape characters inside regular literals, so a value ending in\n * `\\` could swallow the closing quote and change how the statement parses.\n * Values containing a backslash therefore use the `E'…'` form — where\n * backslash is an escape character under BOTH settings — with backslashes\n * and quotes doubled. Backslash-free values keep the plain form so the\n * emitted SQL text (which callers rely on being identical across clauses)\n * is unchanged for the common case.\n */\n/**\n * Converts a JSON pointer to PostgreSQL's text array path.\n *\n * Uses raw SQL (non-parameterized) to ensure the same expression text\n * is generated when the same field is used in multiple clauses (SELECT, GROUP BY).\n * Pointers usually come from schema definitions, but some (e.g. a weighted\n * traversal's `weightProperty`) are runtime strings — safe either way\n * because the shared PostgreSQL literal renderer escapes independently of server\n * configuration.\n *\n * @example\n * \"/name\" → ARRAY['name']\n * \"/items/0\" → ARRAY['items', '0']\n * \"/a/b/c\" → ARRAY['a', 'b', 'c']\n */\nfunction toPostgresPath(pointer: JsonPointer): SqlFragment {\n if (!pointer || pointer === \"\" || pointer === \"/\") {\n return sql.raw(\"ARRAY[]::text[]\");\n }\n\n const segments = parseJsonPointer(pointer);\n if (segments.length === 0) {\n return sql.raw(\"ARRAY[]::text[]\");\n }\n\n // Use raw SQL for path segments to ensure identical SQL text\n // when the same field is used in multiple clauses (e.g., SELECT and GROUP BY)\n const escapedSegments = segments\n .map((segment) => inlineSqlStringLiteral(segment, \"postgres\"))\n .join(\", \");\n return sql.raw(`ARRAY[${escapedSegments}]`);\n}\n\n/**\n * PostgreSQL dialect adapter implementation.\n */\nexport const postgresDialect: DialectAdapter = {\n name: \"postgres\",\n capabilities: {\n standardQueryStrategy: \"cte_project\",\n recursiveQueryStrategy: \"recursive_cte\",\n materializeIntermediateTraversalCtes: false,\n emitNotMaterializedHint: true,\n forceRecursiveWorktableOuterJoinOrder: false,\n vectorPredicateStrategy: \"native\",\n vectorMetrics: [\"cosine\", \"l2\", \"inner_product\"] as const,\n supportsFulltext: true,\n },\n\n binaryText(expression) {\n return sql`${expression} COLLATE \"C\"`;\n },\n\n analyzeTemporaryTable(table) {\n return sql`ANALYZE ${table}`;\n },\n\n setTransactionWorkingMemory(workingMemory) {\n // The parameterizable form of `SET LOCAL work_mem`: is_local => true\n // scopes the override to the current transaction, matching the pgvector\n // iterative-scan GUC handling elsewhere in the backend.\n return sql`SELECT set_config('work_mem', ${workingMemory}, true)`;\n },\n\n // ============================================================\n // JSON Path Operations\n // ============================================================\n\n compilePath(pointer) {\n return toPostgresPath(pointer);\n },\n\n jsonExtract(column, pointer) {\n // #> returns JSONB value at path\n const path = toPostgresPath(pointer);\n return sql`${column} #> ${path}`;\n },\n\n jsonExtractText(column, pointer) {\n // #>> returns text value at path\n const path = toPostgresPath(pointer);\n return sql`${column} #>> ${path}`;\n },\n\n jsonExtractNumber(column, pointer) {\n // Extract as text then cast to numeric\n const path = toPostgresPath(pointer);\n return sql`(${column} #>> ${path})::numeric`;\n },\n\n jsonExtractDouble(column, pointer) {\n // float8, not ::numeric — decimal arithmetic would diverge from\n // SQLite's binary doubles when values accumulate.\n const path = toPostgresPath(pointer);\n return sql`(${column} #>> ${path})::double precision`;\n },\n\n jsonExtractBoolean(column, pointer) {\n // Extract as text then cast to boolean\n const path = toPostgresPath(pointer);\n return sql`(${column} #>> ${path})::boolean`;\n },\n\n jsonExtractDate(column, pointer) {\n // Extract as text then cast to timestamptz\n const path = toPostgresPath(pointer);\n return sql`(${column} #>> ${path})::timestamptz`;\n },\n\n // ============================================================\n // JSON Array Operations\n // ============================================================\n\n jsonArrayLength(column) {\n return sql`jsonb_array_length(${column})`;\n },\n\n jsonArrayContains(column, value) {\n // @> checks if left contains right\n const jsonValue = JSON.stringify([value]);\n return sql`${column} @> ${jsonValue}::jsonb`;\n },\n\n jsonArrayContainsAll(column, values) {\n if (values.length === 0) {\n return sql.raw(\"1=1\");\n }\n\n // @> with full array checks all values\n const jsonValue = JSON.stringify(values);\n return sql`${column} @> ${jsonValue}::jsonb`;\n },\n\n jsonArrayContainsAny(column, values) {\n if (values.length === 0) {\n return sql.raw(\"1=0\");\n }\n\n // Check each value with @> and OR them together\n // PostgreSQL doesn't have a native \"overlaps\" for jsonb arrays\n const conditions = values.map((value) => {\n const jsonValue = JSON.stringify([value]);\n return sql`${column} @> ${jsonValue}::jsonb`;\n });\n return sql`(${sql.join(conditions, sql` OR `)})`;\n },\n\n // ============================================================\n // JSON Object Operations\n // ============================================================\n\n jsonHasPath(column, pointer) {\n const path = toPostgresPath(pointer);\n return sql`${column} #> ${path} IS NOT NULL`;\n },\n\n jsonPathIsNull(column, pointer) {\n const path = toPostgresPath(pointer);\n // Type-based, not the `#>> path = 'null'` text comparison this used to\n // be: `#>>` renders a JSON null as SQL NULL (making the old form\n // three-valued, so `.pathIsNull()` silently missed stored JSON nulls) and\n // renders the JSON *string* \"null\" as the same text 'null' (falsely\n // matching it). jsonb_typeof distinguishes both, and COALESCE maps a\n // missing path to TRUE, keeping the predicate two-valued.\n return sql`COALESCE(jsonb_typeof(${column} #> ${path}) = 'null', TRUE)`;\n },\n\n jsonPathIsNumber(column, pointer) {\n const path = toPostgresPath(pointer);\n // jsonb_typeof returns NULL for a missing path; COALESCE keeps the\n // predicate two-valued so negations don't silently drop rows.\n return sql`COALESCE(jsonb_typeof(${column} #> ${path}) = 'number', FALSE)`;\n },\n\n jsonPathIsNotNull(column, pointer) {\n const path = toPostgresPath(pointer);\n // Mirror image of jsonPathIsNull; COALESCE maps a missing path to FALSE.\n return sql`COALESCE(jsonb_typeof(${column} #> ${path}) <> 'null', FALSE)`;\n },\n\n // ============================================================\n // Comparison Operations\n // ============================================================\n\n nullSafeEquals(left, right) {\n return sql`${left} IS NOT DISTINCT FROM ${right}`;\n },\n\n inList(left, values, negated) {\n const operator = negated ? sql.raw(\"NOT IN\") : sql.raw(\"IN\");\n const placeholders = values.map((value) => sql`${value}`);\n return sql`${left} ${operator} (${sql.join(placeholders, sql`, `)})`;\n },\n\n // ============================================================\n // String Operations\n // ============================================================\n\n ilike(column, pattern) {\n // PostgreSQL has native ILIKE operator. Declaring backslash as the escape\n // character is a no-op (it is the LIKE default) but keeps the emitted SQL\n // identical in intent to SQLite, which has no default escape character.\n return sql`${column} ILIKE ${pattern} ${likeEscapeClause}`;\n },\n\n // ============================================================\n // Set Operations\n // ============================================================\n\n wrapSetOperationOperand(inner) {\n // PostgreSQL allows a complete SELECT (incl. its own WITH) as a\n // parenthesized compound operand.\n return sql`(${inner})`;\n },\n\n // ============================================================\n // Recursive CTE Path Operations\n // ============================================================\n\n initializePath(nodeId) {\n // PostgreSQL uses text arrays: ARRAY[id]\n return sql`ARRAY[${nodeId}]`;\n },\n\n extendPath(currentPath, nodeId) {\n // Array concatenation: path || id\n return sql`${currentPath} || ${nodeId}`;\n },\n\n cycleCheck(nodeId, path) {\n // Check that id is NOT in array path\n // Returns TRUE if no cycle (id not in array)\n return sql`${nodeId} != ALL(${path})`;\n },\n\n // ============================================================\n // Value Binding & Literals\n // ============================================================\n\n bindValue(value) {\n return getSqlDialectProfile(\"postgres\").bindValue(value);\n },\n\n booleanLiteral(value) {\n return sql.raw(\n getSqlDialectProfile(\"postgres\").booleanLiteralString(value),\n );\n },\n\n booleanLiteralString(value) {\n return getSqlDialectProfile(\"postgres\").booleanLiteralString(value);\n },\n\n quoteIdentifier(name) {\n // PostgreSQL uses double quotes, escape embedded quotes by doubling\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n },\n\n // ============================================================\n // Vector Operations\n // ============================================================\n\n // Compile-time gate for `field.similarTo(...)`; the active\n // `VectorStrategy` (pgvector) owns the distance SQL.\n supportsVectors: true,\n\n // ============================================================\n // Fulltext Operations\n // ============================================================\n\n fulltext: tsvectorStrategy,\n};\n","/**\n * SQLite Dialect Adapter\n *\n * Implements dialect-specific SQL generation for SQLite databases.\n * Uses SQLite's JSON1 extension for JSON operations.\n */\nimport { type JsonPointer, parseJsonPointer } from \"../json-pointer\";\nimport { sql } from \"../sql-fragment\";\nimport { fts5Strategy } from \"./fulltext-strategy\";\nimport { likeEscapeClause } from \"./like-escape\";\nimport { getSqlDialectProfile } from \"./profile\";\nimport { type DialectAdapter } from \"./types\";\n\n/**\n * Escapes a string for use in a SQLite string literal.\n * SQLite uses single quotes and escapes embedded single quotes by doubling them.\n */\nfunction escapeSqliteLiteral(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\n/**\n * Converts a JSON pointer to SQLite's JSON path syntax.\n *\n * @example\n * \"/name\" → \"$.\\\"name\\\"\"\n * \"/items/0\" → \"$.\\\"items\\\"[0]\"\n * \"/a/b/c\" → \"$.\\\"a\\\".\\\"b\\\".\\\"c\\\"\"\n */\nfunction toSqlitePath(pointer: JsonPointer): string {\n if (!pointer || pointer === \"\" || pointer === \"/\") {\n return \"$\";\n }\n\n const segments = parseJsonPointer(pointer);\n const parts: string[] = [\"$\"];\n\n for (const segment of segments) {\n if (isArrayIndex(segment)) {\n parts.push(`[${segment}]`);\n } else {\n // Quote the key to handle special characters\n parts.push(`.${JSON.stringify(segment)}`);\n }\n }\n\n return parts.join(\"\");\n}\n\n/**\n * Checks if a JSON pointer segment is an array index.\n */\nfunction isArrayIndex(segment: string): boolean {\n return /^\\d+$/.test(segment);\n}\n\n/**\n * SQLite dialect adapter implementation.\n */\nexport const sqliteDialect: DialectAdapter = {\n name: \"sqlite\",\n capabilities: {\n standardQueryStrategy: \"cte_project\",\n recursiveQueryStrategy: \"recursive_cte\",\n materializeIntermediateTraversalCtes: true,\n emitNotMaterializedHint: false,\n forceRecursiveWorktableOuterJoinOrder: true,\n vectorPredicateStrategy: \"native\",\n vectorMetrics: [\"cosine\", \"l2\"] as const,\n supportsFulltext: true,\n },\n\n binaryText(expression) {\n return expression;\n },\n\n analyzeTemporaryTable(): undefined {\n return;\n },\n\n setTransactionWorkingMemory(): undefined {\n // SQLite has no per-transaction working-memory budget to raise.\n return;\n },\n\n // ============================================================\n // JSON Path Operations\n // ============================================================\n\n compilePath(pointer) {\n // Use raw SQL to ensure the path is a literal, which allows expression\n // indexes on json_extract(...) to be used by the query planner.\n return sql.raw(escapeSqliteLiteral(toSqlitePath(pointer)));\n },\n\n jsonExtract(column, pointer) {\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n jsonExtractText(column, pointer) {\n // SQLite's json_extract returns the native JSON type, which works\n // for text comparisons. For explicit text, we use the same function.\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n jsonExtractNumber(column, pointer) {\n // SQLite json_extract returns numbers natively when the value is numeric\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n jsonExtractDouble(column, pointer) {\n // json_extract already yields INTEGER/REAL affinity for JSON numbers,\n // and SQLite arithmetic on those values is IEEE 754 double.\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n jsonExtractBoolean(column, pointer) {\n // SQLite json_extract returns 0/1 for boolean values\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n jsonExtractDate(column, pointer) {\n // SQLite stores dates as ISO strings, json_extract returns them as text\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n // ============================================================\n // JSON Array Operations\n // ============================================================\n\n jsonArrayLength(column) {\n return sql`json_array_length(${column})`;\n },\n\n jsonArrayContains(column, value) {\n return sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE json_each.value = ${value})`;\n },\n\n jsonArrayContainsAll(column, values) {\n if (values.length === 0) {\n return sql.raw(\"1=1\");\n }\n const packedValues = JSON.stringify(values);\n return sql`\n NOT EXISTS (\n SELECT 1 FROM json_each(${packedValues}) AS tg_required\n WHERE NOT EXISTS (\n SELECT 1 FROM json_each(${column}) AS tg_actual\n WHERE tg_actual.value = tg_required.value\n )\n )\n `;\n },\n\n jsonArrayContainsAny(column, values) {\n if (values.length === 0) {\n return sql.raw(\"1=0\");\n }\n const packedValues = JSON.stringify(values);\n return sql`\n EXISTS (\n SELECT 1\n FROM json_each(${column}) AS tg_actual\n JOIN json_each(${packedValues}) AS tg_wanted\n ON tg_actual.value = tg_wanted.value\n )\n `;\n },\n\n // ============================================================\n // JSON Object Operations\n // ============================================================\n\n jsonHasPath(column, pointer) {\n const path = toSqlitePath(pointer);\n return sql`json_type(${column}, ${sql.raw(escapeSqliteLiteral(path))}) IS NOT NULL`;\n },\n\n jsonPathIsNull(column, pointer) {\n const path = toSqlitePath(pointer);\n const pathSql = sql.raw(escapeSqliteLiteral(path));\n return sql`COALESCE(json_type(${column}, ${pathSql}) = 'null', 1)`;\n },\n\n jsonPathIsNumber(column, pointer) {\n const path = toSqlitePath(pointer);\n const pathSql = sql.raw(escapeSqliteLiteral(path));\n // json_type returns NULL for a missing path; COALESCE keeps the\n // predicate two-valued so negations don't silently drop rows.\n return sql`COALESCE(json_type(${column}, ${pathSql}) IN ('integer', 'real'), 0)`;\n },\n\n jsonPathIsNotNull(column, pointer) {\n const path = toSqlitePath(pointer);\n const pathSql = sql.raw(escapeSqliteLiteral(path));\n return sql`COALESCE(json_type(${column}, ${pathSql}) <> 'null', 0)`;\n },\n\n // ============================================================\n // Comparison Operations\n // ============================================================\n\n nullSafeEquals(left, right) {\n // SQLite's IS operator is null-safe equality (equivalent to = for\n // non-null operands, TRUE when both sides are NULL).\n return sql`${left} IS ${right}`;\n },\n\n inList(left, values, negated) {\n const operator = negated ? sql.raw(\"NOT IN\") : sql.raw(\"IN\");\n const packedValues = JSON.stringify(values);\n return sql`${left} ${operator} (SELECT value FROM json_each(${packedValues}))`;\n },\n\n // ============================================================\n // String Operations\n // ============================================================\n\n ilike(column, pattern) {\n // SQLite LIKE is case-insensitive for ASCII by default, but we use\n // LOWER() for consistency with non-ASCII characters. SQLite has no default\n // LIKE escape character, so declare backslash explicitly to honor the\n // escaping the compiler applies to the pattern (parity with Postgres).\n return sql`LOWER(${column}) LIKE LOWER(${pattern}) ${likeEscapeClause}`;\n },\n\n // ============================================================\n // Set Operations\n // ============================================================\n\n wrapSetOperationOperand(inner) {\n // SQLite forbids parenthesized compound operands, but a FROM-subquery may\n // carry its own WITH clause, so wrap each operand as a subquery.\n return sql`SELECT * FROM (${inner})`;\n },\n\n // ============================================================\n // Recursive CTE Path Operations\n // ============================================================\n\n initializePath(nodeId) {\n // SQLite uses string-based paths with delimiters: '|id|'\n return sql`'|' || ${nodeId} || '|'`;\n },\n\n extendPath(currentPath, nodeId) {\n // Append: path || id || '|'\n return sql`${currentPath} || ${nodeId} || '|'`;\n },\n\n cycleCheck(nodeId, path) {\n // Check that id is NOT in path using INSTR\n // Returns TRUE if no cycle (id not found in path)\n return sql`INSTR(${path}, '|' || ${nodeId} || '|') = 0`;\n },\n\n // ============================================================\n // Value Binding & Literals\n // ============================================================\n\n bindValue(value) {\n return getSqlDialectProfile(\"sqlite\").bindValue(value);\n },\n\n booleanLiteral(value) {\n return sql.raw(getSqlDialectProfile(\"sqlite\").booleanLiteralString(value));\n },\n\n booleanLiteralString(value) {\n return getSqlDialectProfile(\"sqlite\").booleanLiteralString(value);\n },\n\n quoteIdentifier(name) {\n // SQLite uses double quotes (or backticks), escape embedded quotes by doubling\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n },\n\n // ============================================================\n // Vector Operations\n // ============================================================\n\n // Compile-time gate for `field.similarTo(...)`; the active\n // `VectorStrategy` (sqlite-vec / libSQL-native) owns the distance SQL.\n supportsVectors: true,\n\n // ============================================================\n // Fulltext Operations\n // ============================================================\n\n fulltext: fts5Strategy,\n};\n","/**\n * SQL Dialect Module\n *\n * Provides dialect adapters for different SQL databases.\n * Use `getDialect()` to get the appropriate adapter for a dialect name.\n */\n\nexport type { FulltextStrategy } from \"./fulltext-strategy\";\nexport {\n ALL_FULLTEXT_MODES,\n buildFulltextCapabilities,\n fts5Strategy,\n tsvectorStrategy,\n} from \"./fulltext-strategy\";\nexport { postgresDialect } from \"./postgres\";\nexport { sqliteDialect } from \"./sqlite\";\nexport type {\n DialectAdapter,\n DialectCapabilities,\n DialectRecursiveQueryStrategy,\n DialectStandardQueryStrategy,\n DialectVectorPredicateStrategy,\n SqlDialect,\n} from \"./types\";\nexport {\n buildVectorCapabilities,\n type VectorSlot,\n type VectorStrategy,\n} from \"./vector-strategy\";\n\nimport { postgresDialect } from \"./postgres\";\nimport { sqliteDialect } from \"./sqlite\";\nimport { type DialectAdapter, type SqlDialect } from \"./types\";\n\n/**\n * Map of dialect names to their adapters.\n */\nconst DIALECT_ADAPTERS: Record<SqlDialect, DialectAdapter> = {\n sqlite: sqliteDialect,\n postgres: postgresDialect,\n};\n\n/**\n * Gets the dialect adapter for a given dialect name.\n *\n * @param dialect - The dialect name (\"sqlite\" or \"postgres\")\n * @returns The dialect adapter\n *\n * @example\n * ```typescript\n * const adapter = getDialect(\"postgres\");\n * const sql = adapter.jsonExtract(column, \"/name\");\n * ```\n */\nexport function getDialect(dialect: SqlDialect): DialectAdapter {\n return DIALECT_ADAPTERS[dialect];\n}\n\n/**\n * Default dialect used when none is specified.\n */\nexport const DEFAULT_DIALECT: SqlDialect = \"sqlite\";\n","import { type ValueType } from \"../query/ast\";\nimport { getDialect } from \"../query/dialect\";\nimport { type SqlDialect } from \"../query/dialect/types\";\nimport { type JsonPointer, jsonPointer } from \"../query/json-pointer\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport {\n type EdgeIndexDeclaration,\n type IndexWhereExpression,\n type IndexWhereLiteral,\n type IndexWhereOp,\n type IndexWhereOperand,\n type NodeIndexDeclaration,\n type SystemColumnName,\n} from \"./types\";\n\n// ============================================================\n// Public Types\n// ============================================================\n\nexport type IndexCompilationContext = Readonly<{\n dialect: SqlDialect;\n propsColumn: SqlFragment;\n systemColumn: (column: SystemColumnName) => SqlFragment;\n}>;\n\ntype CompiledIndexKeys = Readonly<{\n /** SQL expressions in index key order */\n keys: readonly SqlFragment[];\n}>;\n\n// ============================================================\n// Index Key Compilation\n// ============================================================\n\nexport function compileNodeIndexKeys(\n index: NodeIndexDeclaration,\n dialect: SqlDialect,\n propsColumn: SqlFragment,\n systemColumn: (column: SystemColumnName) => SqlFragment,\n): CompiledIndexKeys {\n const adapter = getDialect(dialect);\n const keys: SqlFragment[] = [];\n\n const systemColumns = [\n ...getNodeScopeColumns(index.scope),\n ...(index.keySystemColumns ?? []),\n ];\n for (const column of systemColumns) {\n keys.push(systemColumn(column));\n }\n\n const allPointers = [...index.fields, ...index.coveringFields];\n const allValueTypes = [\n ...index.fieldValueTypes,\n ...index.coveringFieldValueTypes,\n ];\n\n for (const [pointerIndex, pointer] of allPointers.entries()) {\n const valueType = allValueTypes[pointerIndex];\n const extracted = compileIndexKeyValue(\n adapter,\n propsColumn,\n pointer,\n valueType,\n );\n keys.push(sql`(${extracted})`);\n }\n\n return { keys };\n}\n\nexport function compileEdgeIndexKeys(\n index: EdgeIndexDeclaration,\n dialect: SqlDialect,\n propsColumn: SqlFragment,\n systemColumn: (column: SystemColumnName) => SqlFragment,\n): CompiledIndexKeys {\n const adapter = getDialect(dialect);\n const keys: SqlFragment[] = [];\n\n for (const column of getEdgeScopeColumns(index.scope, index.direction)) {\n keys.push(systemColumn(column));\n }\n\n const allPointers = [...index.fields, ...index.coveringFields];\n const allValueTypes = [\n ...index.fieldValueTypes,\n ...index.coveringFieldValueTypes,\n ];\n\n for (const [pointerIndex, pointer] of allPointers.entries()) {\n const valueType = allValueTypes[pointerIndex];\n const extracted = compileIndexKeyValue(\n adapter,\n propsColumn,\n pointer,\n valueType,\n );\n keys.push(sql`(${extracted})`);\n }\n\n return { keys };\n}\n\n/**\n * Compiles the per-field key-extraction expressions for a node index's\n * **lookup keys** — `index.fields` only, excluding scope columns and\n * `coveringFields` (which are index payload, not part of the lookup key).\n *\n * Each expression is the exact extraction the index DDL builds for that\n * field (via the shared {@link compileIndexKeyValue}), so a runtime lookup\n * predicate stays byte-identical to the materialized index expression —\n * the single source of truth that lets the planner use the physical index.\n */\nexport function compileNodeIndexFieldKeys(\n index: NodeIndexDeclaration,\n ctx: IndexCompilationContext,\n): readonly SqlFragment[] {\n const adapter = getDialect(ctx.dialect);\n const keys: SqlFragment[] = [];\n for (const [position, pointer] of index.fields.entries()) {\n const extracted = compileIndexKeyValue(\n adapter,\n ctx.propsColumn,\n pointer,\n index.fieldValueTypes[position],\n );\n keys.push(sql`(${extracted})`);\n }\n return keys;\n}\n\nfunction compileIndexKeyValue(\n dialect: ReturnType<typeof getDialect>,\n propsColumn: SqlFragment,\n pointer: JsonPointer,\n valueType: ValueType | undefined,\n): SqlFragment {\n switch (valueType) {\n case \"number\": {\n return dialect.jsonExtractNumber(propsColumn, pointer);\n }\n case \"boolean\": {\n return dialect.jsonExtractBoolean(propsColumn, pointer);\n }\n case \"date\": {\n return dialect.jsonExtractDate(propsColumn, pointer);\n }\n case \"string\":\n case \"unknown\":\n case undefined: {\n return dialect.jsonExtractText(propsColumn, pointer);\n }\n case \"array\":\n case \"object\":\n case \"embedding\": {\n // For advanced index types (GIN/json), callers should use dialect.jsonExtract\n // or index the props column directly. We keep this as a conservative fallback.\n return dialect.jsonExtract(propsColumn, pointer);\n }\n }\n}\n\nexport function getNodeScopeColumns(\n scope: NodeIndexDeclaration[\"scope\"],\n): readonly SystemColumnName[] {\n switch (scope) {\n case \"graphAndKind\": {\n return [\"graph_id\", \"kind\"];\n }\n case \"graph\": {\n return [\"graph_id\"];\n }\n case \"none\": {\n return [];\n }\n }\n}\n\nfunction getEdgeScopeColumns(\n scope: EdgeIndexDeclaration[\"scope\"],\n direction: EdgeIndexDeclaration[\"direction\"],\n): readonly SystemColumnName[] {\n const base =\n scope === \"graphAndKind\" ? ([\"graph_id\", \"kind\"] as const)\n : scope === \"graph\" ? ([\"graph_id\"] as const)\n : ([] as const);\n\n if (direction === \"out\") {\n return [...base, \"from_id\"];\n }\n if (direction === \"in\") {\n return [...base, \"to_id\"];\n }\n return [...base];\n}\n\n// ============================================================\n// WHERE Clause Compilation\n// ============================================================\n\nfunction isIndexWhereLiteralList(\n value: IndexWhereLiteral | readonly IndexWhereLiteral[],\n): value is readonly IndexWhereLiteral[] {\n return Array.isArray(value);\n}\n\nexport function compileIndexWhere(\n ctx: IndexCompilationContext,\n expression: IndexWhereExpression,\n): SqlFragment {\n switch (expression.__type) {\n case \"index_where_and\": {\n return sql`(${sql.join(\n expression.predicates.map((p) => compileIndexWhere(ctx, p)),\n sql` AND `,\n )})`;\n }\n case \"index_where_or\": {\n return sql`(${sql.join(\n expression.predicates.map((p) => compileIndexWhere(ctx, p)),\n sql` OR `,\n )})`;\n }\n case \"index_where_not\": {\n return sql`(NOT ${compileIndexWhere(ctx, expression.predicate)})`;\n }\n case \"index_where_null_check\": {\n const operand = compileIndexWhereOperand(ctx, expression.operand);\n return expression.op === \"isNull\" ?\n sql`${operand} IS NULL`\n : sql`${operand} IS NOT NULL`;\n }\n case \"index_where_comparison\": {\n const left = compileIndexWhereOperand(ctx, expression.left);\n\n const right = expression.right;\n if (isIndexWhereLiteralList(right)) {\n if (expression.op !== \"in\" && expression.op !== \"notIn\") {\n throw new Error(\n `Operator \"${expression.op}\" does not support list comparison in index WHERE clause`,\n );\n }\n const values = right.map((literal) =>\n compileIndexWhereLiteral(ctx.dialect, literal),\n );\n const operator = expression.op === \"in\" ? sql`IN` : sql`NOT IN`;\n return sql`${left} ${operator} (${sql.join(values, sql`, `)})`;\n }\n\n if (expression.op === \"in\" || expression.op === \"notIn\") {\n throw new Error(\n `Operator \"${expression.op}\" requires a list of values in index WHERE clause`,\n );\n }\n\n const rightLiteral = compileIndexWhereLiteral(ctx.dialect, right);\n const opSql = compileComparisonOperator(expression.op);\n return sql`${left} ${opSql} ${rightLiteral}`;\n }\n }\n}\n\nfunction compileIndexWhereOperand(\n ctx: IndexCompilationContext,\n operand: IndexWhereOperand,\n): SqlFragment {\n if (operand.__type === \"index_operand_system\") {\n return ctx.systemColumn(operand.column);\n }\n\n const adapter = getDialect(ctx.dialect);\n const pointer = jsonPointer([operand.field]);\n\n switch (operand.valueType) {\n case \"number\": {\n return adapter.jsonExtractNumber(ctx.propsColumn, pointer);\n }\n case \"boolean\": {\n return adapter.jsonExtractBoolean(ctx.propsColumn, pointer);\n }\n case \"date\": {\n return adapter.jsonExtractDate(ctx.propsColumn, pointer);\n }\n case \"array\":\n case \"object\":\n case \"embedding\": {\n return adapter.jsonExtract(ctx.propsColumn, pointer);\n }\n case \"string\":\n case \"unknown\":\n case undefined: {\n return adapter.jsonExtractText(ctx.propsColumn, pointer);\n }\n }\n}\n\nfunction compileIndexWhereLiteral(\n dialect: SqlDialect,\n literal: IndexWhereLiteral,\n): SqlFragment {\n switch (literal.valueType) {\n case \"string\":\n case \"date\": {\n return sql.raw(escapeStringLiteral(literal.value.toString()));\n }\n case \"number\": {\n return sql.raw(literal.value.toString());\n }\n case \"boolean\": {\n return getDialect(dialect).booleanLiteral(literal.value as boolean);\n }\n case \"array\":\n case \"object\":\n case \"embedding\":\n case \"unknown\": {\n return sql.raw(escapeStringLiteral(literal.value.toString()));\n }\n }\n}\n\ntype ComparisonIndexWhereOp = Exclude<IndexWhereOp, \"in\" | \"notIn\">;\n\nfunction compileComparisonOperator(op: ComparisonIndexWhereOp): SqlFragment {\n switch (op) {\n case \"eq\": {\n return sql`=`;\n }\n case \"neq\": {\n return sql`<>`;\n }\n case \"gt\": {\n return sql`>`;\n }\n case \"gte\": {\n return sql`>=`;\n }\n case \"lt\": {\n return sql`<`;\n }\n case \"lte\": {\n return sql`<=`;\n }\n }\n}\n\nfunction escapeStringLiteral(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/backend/types.ts"],"names":[],"mappings":";;;AA2NO,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,I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AAA,EACY;AACZ,EAAA,IAAI,aAAA,IAAiB,OAAA,IAAW,OAAA,CAAQ,YAAA,CAAa,YAAA,EAAc;AACjE,IAAA,OAAO,QAAQ,WAAA,CAAY,CAAC,EAAA,KAAO,EAAA,CAAG,EAAE,CAAC,CAAA;AAAA,EAC3C;AACA,EAAA,OAAO,EAAA,CAAG,YAAY,OAAO,CAAA;AAC/B;AA6PO,IAAM,0BAAA,GAA6B;AAOnC,IAAM,iCAAA,GAAoC;AAO1C,IAAM,sBAAA,GAAyB;AAO/B,IAAM,kCAAA,GAAqC;AAO3C,IAAM,4BAAA,GAA+B;AAKrC,IAAM,mBAAA,GAA2C,OAAO,MAAA,CAAO;AAAA,EACpE,YAAA,EAAc,IAAA;AAAA;AAAA,EACd,eAAA,EAAiB,IAAA;AAAA;AAAA,EACjB,SAAA,EAAW,IAAA;AAAA;AAAA,EACX,iBAAA,EAAmB,0BAAA;AAAA;AAAA;AAAA,EAGnB,cAAA,EAAgB,OAAO,MAAA,CAAO,EAAE,WAAW,IAAA,EAAM,aAAA,EAAe,OAAO;AACzE,CAAC;AAKM,IAAM,qBAAA,GAA6C,OAAO,MAAA,CAAO;AAAA,EACtE,YAAA,EAAc,IAAA;AAAA;AAAA,EACd,eAAA,EAAiB,IAAA;AAAA;AAAA,EACjB,SAAA,EAAW,IAAA;AAAA;AAAA,EACX,iBAAA,EAAmB,4BAAA;AAAA,EACnB,cAAA,EAAgB,OAAO,MAAA,CAAO,EAAE,WAAW,IAAA,EAAM,aAAA,EAAe,MAAM;AACxE,CAAC","file":"chunk-UZLEQFTV.js","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 {\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 { type SqlFragment } from \"../query/sql-fragment\";\nimport {\n type CompiledRowsSql,\n type CompiledStatementSql,\n type CompiledTemporaryStatementSql,\n} from \"../query/sql-intent\";\nimport { type SerializedSchema } from \"../schema/types\";\nimport { typeGraphGlobalSymbol } from \"../utils/global-symbol\";\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 */\nexport type 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?: SqlFragment;\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 `SqlFragment` values 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?: SqlFragment;\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?: SqlFragment;\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: unique symbol = typeGraphGlobalSymbol(\n \"internal-temporary-writes-v1\",\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\n/** @internal Transaction options available only to TypeGraph-owned execution. */\nexport type InternalTransactionOptions = TransactionOptions &\n Readonly<{\n /**\n * Permit writes only to connection-local temporary state. The iterative\n * operation primitive uses this when an engine rejects temporary DDL in a\n * read-only transaction.\n */\n temporaryWrites?: typeof INTERNAL_TEMPORARY_WRITES;\n }>;\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 *\n * Every function is receiver-free (`this: void`). Implementations must close\n * over their state instead of reading `this`, which makes saved optional\n * capabilities and other detached port calls safe by construction.\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: (this: void, params: InsertNodeParams) => Promise<NodeRow>;\n insertNodeNoReturn?: (this: void, params: InsertNodeParams) => Promise<void>;\n insertNodesBatch?: (\n this: void,\n params: readonly InsertNodeParams[],\n ) => Promise<void>;\n insertNodesBatchReturning?: (\n this: void,\n params: readonly InsertNodeParams[],\n ) => Promise<readonly NodeRow[]>;\n updateNode: (this: void, params: UpdateNodeParams) => Promise<NodeRow>;\n deleteNode: (this: void, params: DeleteNodeParams) => Promise<void>;\n hardDeleteNode: (this: void, params: HardDeleteNodeParams) => Promise<void>;\n getNode: (\n this: void,\n graphId: string,\n kind: string,\n id: string,\n ) => Promise<NodeRow | undefined>;\n getNodes?: (\n this: void,\n graphId: string,\n kind: string,\n ids: readonly string[],\n ) => Promise<readonly NodeRow[]>;\n\n // === Edge Operations ===\n insertEdge: (this: void, params: InsertEdgeParams) => Promise<EdgeRow>;\n insertEdgeNoReturn?: (this: void, params: InsertEdgeParams) => Promise<void>;\n insertEdgesBatch?: (\n this: void,\n params: readonly InsertEdgeParams[],\n ) => Promise<void>;\n insertEdgesBatchReturning?: (\n this: void,\n params: readonly InsertEdgeParams[],\n ) => Promise<readonly EdgeRow[]>;\n updateEdge: (this: void, params: UpdateEdgeParams) => Promise<EdgeRow>;\n deleteEdge: (this: void, params: DeleteEdgeParams) => Promise<void>;\n hardDeleteEdge: (this: void, 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?: (\n this: void,\n params: DeleteEdgesBatchParams,\n ) => Promise<void>;\n /** Batched {@link hardDeleteEdge}; see {@link deleteEdgesBatch}. */\n hardDeleteEdgesBatch?: (\n this: void,\n params: DeleteEdgesBatchParams,\n ) => Promise<void>;\n getEdge: (\n this: void,\n graphId: string,\n id: string,\n ) => Promise<EdgeRow | undefined>;\n getEdges?: (\n this: void,\n graphId: string,\n ids: readonly string[],\n ) => Promise<readonly EdgeRow[]>;\n\n // === Edge Cardinality Operations ===\n countEdgesFrom: (this: void, params: CountEdgesFromParams) => Promise<number>;\n edgeExistsBetween: (\n this: void,\n params: EdgeExistsBetweenParams,\n ) => Promise<boolean>;\n\n // === Edge Query Operations ===\n findEdgesConnectedTo: (\n this: void,\n params: FindEdgesConnectedToParams,\n ) => Promise<readonly EdgeRow[]>;\n\n // === Collection Query Operations ===\n findNodesByKind: (\n this: void,\n params: FindNodesByKindParams,\n ) => Promise<readonly NodeRow[]>;\n countNodesByKind: (\n this: void,\n params: CountNodesByKindParams,\n ) => Promise<number>;\n findEdgesByKind: (\n this: void,\n params: FindEdgesByKindParams,\n ) => Promise<readonly EdgeRow[]>;\n countEdgesByKind: (\n this: void,\n params: CountEdgesByKindParams,\n ) => Promise<number>;\n\n // === Unique Constraint Operations ===\n insertUnique: (this: void, 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?: (\n this: void,\n entries: readonly InsertUniqueParams[],\n ) => Promise<void>;\n deleteUnique: (this: void, params: DeleteUniqueParams) => Promise<void>;\n checkUnique: (\n this: void,\n params: CheckUniqueParams,\n ) => Promise<UniqueRow | undefined>;\n checkUniqueBatch?: (\n this: void,\n params: CheckUniqueBatchParams,\n ) => Promise<readonly UniqueRow[]>;\n\n // === Schema Operations ===\n getActiveSchema: (\n this: void,\n graphId: string,\n ) => Promise<SchemaVersionRow | undefined>;\n getSchemaVersion: (\n this: void,\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 this: void,\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: (\n this: void,\n params: SetActiveVersionParams,\n ) => Promise<void>;\n\n // === Embedding Operations (optional - depends on vector capabilities) ===\n upsertEmbedding?: (\n this: void,\n params: UpsertEmbeddingParams,\n ) => 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?: (\n this: void,\n params: UpsertEmbeddingBatchParams,\n ) => Promise<void>;\n deleteEmbedding?: (\n this: void,\n params: DeleteEmbeddingParams,\n ) => 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 this: void,\n params: VectorSearchParams,\n ) => Promise<readonly VectorSearchResult[]>;\n createVectorIndex?: (\n this: void,\n params: CreateVectorIndexParams,\n ) => Promise<void>;\n dropVectorIndex?: (\n this: void,\n params: DropVectorIndexParams,\n ) => 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 this: void,\n params: HybridSearchParams,\n ) => Promise<readonly HybridSearchRow[]>;\n\n // === Fulltext Operations (optional - depends on fulltext capabilities) ===\n upsertFulltext?: (this: void, params: UpsertFulltextParams) => Promise<void>;\n deleteFulltext?: (this: void, params: DeleteFulltextParams) => Promise<void>;\n /**\n * Batched variant of `upsertFulltext`. Optional — callers fall back to\n * per-row `upsertFulltext` when unset.\n */\n upsertFulltextBatch?: (\n this: void,\n params: UpsertFulltextBatchParams,\n ) => Promise<void>;\n /**\n * Batched variant of `deleteFulltext`. Optional — callers fall back to\n * per-row `deleteFulltext` when unset.\n */\n deleteFulltextBatch?: (\n this: void,\n params: DeleteFulltextBatchParams,\n ) => 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 this: void,\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?: (this: void) => 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?: (this: void) => 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 this: void,\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 this: void,\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 this: void,\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 this: void,\n params: ClaimIndexMaterializationParams,\n ) => Promise<boolean>;\n /** Releases a claim taken by `claimIndexMaterialization` (token-guarded). */\n releaseIndexMaterializationClaim?: (\n this: void,\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?: (this: void) => 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 this: void,\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 this: void,\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?: (\n this: void,\n graphId: string,\n ) => 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?: (this: void) => 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 this: void,\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?: (\n this: void,\n graphId: string,\n ) => 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?: (\n this: void,\n params: RecordKindRemovalParams,\n ) => 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?: (this: void) => 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?: (this: void, 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 this: void,\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 this: void,\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?: (this: void, 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 this: void,\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?: (\n this: void,\n slot: VectorSlot,\n ) => 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?: (this: void, 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?: (\n this: void,\n graphId: string,\n ) => 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?: (\n this: void,\n graphId: string,\n version: number,\n ) => 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: (this: void, 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?: (this: void) => 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: (this: void) => 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 this: void,\n fn: (session: TrustedImportSession) => Promise<T>,\n ) => Promise<T>;\n\n // === Query Execution ===\n execute: <T>(this: void, 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?: (this: void, 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 this: void,\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 this: void,\n sqlText: string,\n params: readonly unknown[],\n ) => Promise<readonly T[]>;\n\n /** Compile a TypeGraph `SqlFragment` to `{ sql, params }` without executing. */\n compileSql?: (\n this: void,\n query: SqlFragment,\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?: (this: void, ddl: string) => Promise<void>;\n\n // === Transaction ===\n /** Runs TypeGraph operations inside a backend-owned transaction. */\n transaction: <T>(\n this: void,\n fn: (tx: TransactionBackend) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<T>;\n\n // === Lifecycle ===\n close: (this: void) => Promise<void>;\n}>;\n\n/**\n * Adapter-native transaction interoperability layered on top of the portable\n * TypeGraph backend. Only adapter entrypoints expose this capability.\n */\nexport type AdapterBackend<TNativeTransaction> = GraphBackend &\n Readonly<{\n /**\n * Runs TypeGraph operations and exposes the exact adapter-native handle\n * bound to the same transaction.\n */\n transactionWithNative: <T>(\n this: void,\n fn: (\n tx: TransactionBackend,\n nativeTransaction: TNativeTransaction,\n ) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<T>;\n /** Adopts a caller-owned, already-open adapter transaction. */\n adoptTransaction: (\n this: void,\n externalTransaction: TNativeTransaction,\n ) => TransactionBackend;\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 SqlCompilationBackend = Pick<GraphBackend, \"compileSql\">;\n\nexport type RawStatementExecutionBackend = Pick<\n GraphBackend,\n \"executeStatement\" | \"executeTemporaryStatement\" | \"executeDdl\"\n>;\n\nexport type BackendMaintenance = Pick<GraphBackend, \"refreshStatistics\">;\n\nexport type BackendTransactions = Pick<GraphBackend, \"transaction\">;\n\nexport type AdapterBackendTransactions<TNativeTransaction> = Pick<\n AdapterBackend<TNativeTransaction>,\n \"transactionWithNative\" | \"adoptTransaction\"\n>;\n\nexport type BackendLifecycle = Pick<GraphBackend, \"close\">;\n\n/**\n * Read-oriented transaction projection exposed by portable transaction\n * contexts. It preserves snapshot-aware graph reads and TypeGraph-compiled\n * row queries while excluding graph writes, arbitrary raw SQL, DDL,\n * transaction adoption, and lifecycle control.\n */\nexport type TransactionReadBackend = Readonly<\n BackendIdentity &\n GraphEntityReadBackend &\n SchemaReadBackend &\n QueryExecutionBackend &\n SqlCompilationBackend\n>;\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\n/**\n * Builds the actual runtime projection exposed as `TransactionContext.backend`.\n * This is an explicit object rather than a type-only narrowing so portable\n * callers cannot discover write or arbitrary-SQL methods on the underlying\n * transaction backend at runtime.\n *\n * @internal\n */\nexport function createTransactionReadBackend(\n backend: TransactionBackend,\n): TransactionReadBackend {\n const getNodes = backend.getNodes;\n const getEdges = backend.getEdges;\n const compileSql = backend.compileSql;\n\n return Object.freeze({\n dialect: backend.dialect,\n capabilities: backend.capabilities,\n ...(backend.tableNames === undefined ?\n {}\n : { tableNames: backend.tableNames }),\n ...(backend.fulltextStrategy === undefined ?\n {}\n : { fulltextStrategy: backend.fulltextStrategy }),\n ...(backend.vectorStrategy === undefined ?\n {}\n : { vectorStrategy: backend.vectorStrategy }),\n getNode: (graphId, kind, id) => backend.getNode(graphId, kind, id),\n ...(getNodes === undefined ?\n {}\n : {\n getNodes: (graphId: string, kind: string, ids: readonly string[]) =>\n getNodes(graphId, kind, ids),\n }),\n getEdge: (graphId, id) => backend.getEdge(graphId, id),\n ...(getEdges === undefined ?\n {}\n : {\n getEdges: (graphId: string, ids: readonly string[]) =>\n getEdges(graphId, ids),\n }),\n countEdgesFrom: (params) => backend.countEdgesFrom(params),\n edgeExistsBetween: (params) => backend.edgeExistsBetween(params),\n findEdgesConnectedTo: (params) => backend.findEdgesConnectedTo(params),\n findNodesByKind: (params) => backend.findNodesByKind(params),\n countNodesByKind: (params) => backend.countNodesByKind(params),\n findEdgesByKind: (params) => backend.findEdgesByKind(params),\n countEdgesByKind: (params) => backend.countEdgesByKind(params),\n getActiveSchema: (graphId) => backend.getActiveSchema(graphId),\n getSchemaVersion: (graphId, version) =>\n backend.getSchemaVersion(graphId, version),\n execute: <T>(query: CompiledRowsSql) => backend.execute<T>(query),\n ...(compileSql === undefined ?\n {}\n : { compileSql: (query: SqlFragment) => compileSql(query) }),\n });\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 * This is a decoration primitive: every non-overridden target property remains\n * reachable. Never use it to narrow a capability surface; construct an\n * explicit allowlist projection first, then decorate that projection.\n *\n * Backend wrappers use this instead of object spread so proxy backends keep\n * getters and non-enumerable members. GraphBackend functions are receiver-free\n * by contract, so delegated methods are returned unchanged.\n */\nexport function createBackendOverlay<\n T extends GraphBackend | TransactionBackend,\n const O extends Partial<T> = Partial<T>,\n>(target: T, overlay: ExactBackendOverlay<T, O>): T {\n function hasOverlayProperty(property: PropertyKey): boolean {\n return Object.hasOwn(overlay, property);\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 Reflect.get(targetObject, property, targetObject);\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<TNativeTransaction>(\n backend: AdapterBackend<TNativeTransaction>,\n teardown: () => void | Promise<void>,\n): AdapterBackend<TNativeTransaction>;\nexport function wrapWithManagedClose(\n backend: GraphBackend,\n teardown: () => void | Promise<void>,\n): GraphBackend;\nexport function wrapWithManagedClose(\n backend: GraphBackend,\n teardown: () => void | Promise<void>,\n): GraphBackend {\n let backendClosed = false;\n let teardownComplete = false;\n let closeInFlight: Promise<void> | undefined;\n\n async function closeManagedResources(): Promise<void> {\n const errors: unknown[] = [];\n if (!backendClosed) {\n try {\n await backend.close();\n backendClosed = true;\n } catch (error) {\n errors.push(error);\n }\n }\n if (!teardownComplete) {\n try {\n await teardown();\n teardownComplete = true;\n } catch (error) {\n errors.push(error);\n }\n }\n\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) {\n throw new AggregateError(\n errors,\n \"The backend and its managed resource both failed to close.\",\n );\n }\n }\n\n const closeOverlay: Pick<GraphBackend, \"close\"> = {\n async close(): Promise<void> {\n if (backendClosed && teardownComplete) return;\n closeInFlight ??= closeManagedResources().finally(() => {\n closeInFlight = undefined;\n });\n await closeInFlight;\n },\n };\n return createBackendOverlay(backend, closeOverlay);\n}\n\n/**\n * Closes an owned resource after provisioning fails without replacing the\n * original domain error with a secondary cleanup failure.\n */\nexport async function closeAfterFailure(\n resource: Readonly<{ close: () => void | Promise<void> }>,\n provisioningError: unknown,\n): Promise<never> {\n try {\n await resource.close();\n } catch {\n // The provisioning failure remains the actionable error. Managed close is\n // retryable when the resource is returned, but a failed factory has no\n // handle it can safely expose for a second attempt.\n }\n throw provisioningError;\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 = Object.freeze({\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: Object.freeze({ supported: true, mathFunctions: false }),\n});\n\n/**\n * Default capabilities for PostgreSQL.\n */\nexport const POSTGRES_CAPABILITIES: BackendCapabilities = Object.freeze({\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: Object.freeze({ supported: true, mathFunctions: true }),\n});\n"]}