@nicia-ai/typegraph 0.50.0 → 0.51.1

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 (326) hide show
  1. package/README.md +12 -0
  2. package/dist/backend/drizzle/indexes.cjs +10 -8
  3. package/dist/backend/drizzle/indexes.d.cts +1 -1
  4. package/dist/backend/drizzle/indexes.d.ts +1 -1
  5. package/dist/backend/drizzle/indexes.js +6 -4
  6. package/dist/backend/index.cjs +183 -50
  7. package/dist/backend/index.d.cts +90 -4
  8. package/dist/backend/index.d.ts +90 -4
  9. package/dist/backend/index.js +6 -9
  10. package/dist/backend/postgres/index.cjs +30 -28
  11. package/dist/backend/postgres/index.d.cts +7 -7
  12. package/dist/backend/postgres/index.d.ts +7 -7
  13. package/dist/backend/postgres/index.js +16 -14
  14. package/dist/backend/postgres/pglite-store.cjs +6 -62
  15. package/dist/backend/postgres/pglite-store.cjs.map +1 -1
  16. package/dist/backend/postgres/pglite-store.d.cts +8 -8
  17. package/dist/backend/postgres/pglite-store.d.ts +8 -8
  18. package/dist/backend/postgres/pglite-store.js +6 -62
  19. package/dist/backend/postgres/pglite-store.js.map +1 -1
  20. package/dist/backend/postgres/pglite.cjs +18 -16
  21. package/dist/backend/postgres/pglite.d.cts +3 -3
  22. package/dist/backend/postgres/pglite.d.ts +3 -3
  23. package/dist/backend/postgres/pglite.js +17 -15
  24. package/dist/backend/sqlite/index.cjs +27 -25
  25. package/dist/backend/sqlite/index.d.cts +7 -7
  26. package/dist/backend/sqlite/index.d.ts +7 -7
  27. package/dist/backend/sqlite/index.js +14 -12
  28. package/dist/backend/sqlite/libsql.cjs +21 -19
  29. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  30. package/dist/backend/sqlite/libsql.d.cts +3 -3
  31. package/dist/backend/sqlite/libsql.d.ts +3 -3
  32. package/dist/backend/sqlite/libsql.js +16 -14
  33. package/dist/backend/sqlite/libsql.js.map +1 -1
  34. package/dist/backend/sqlite/local-store.cjs +8 -64
  35. package/dist/backend/sqlite/local-store.cjs.map +1 -1
  36. package/dist/backend/sqlite/local-store.d.cts +8 -8
  37. package/dist/backend/sqlite/local-store.d.ts +8 -8
  38. package/dist/backend/sqlite/local-store.js +7 -64
  39. package/dist/backend/sqlite/local-store.js.map +1 -1
  40. package/dist/backend/sqlite/local.cjs +22 -19
  41. package/dist/backend/sqlite/local.d.cts +3 -3
  42. package/dist/backend/sqlite/local.d.ts +3 -3
  43. package/dist/backend/sqlite/local.js +18 -15
  44. package/dist/{chunk-TUVD4DFR.cjs → chunk-2CVDZCXH.cjs} +122 -51
  45. package/dist/chunk-2CVDZCXH.cjs.map +1 -0
  46. package/dist/{chunk-I5C6OTKR.js → chunk-2DWTBNSH.js} +3 -3
  47. package/dist/{chunk-I5C6OTKR.js.map → chunk-2DWTBNSH.js.map} +1 -1
  48. package/dist/{chunk-C76WFIVZ.cjs → chunk-2KCTP3U2.cjs} +180 -127
  49. package/dist/chunk-2KCTP3U2.cjs.map +1 -0
  50. package/dist/{chunk-BYBDM423.cjs → chunk-322TBTOQ.cjs} +48 -48
  51. package/dist/{chunk-BYBDM423.cjs.map → chunk-322TBTOQ.cjs.map} +1 -1
  52. package/dist/chunk-36SX6QXP.cjs +186 -0
  53. package/dist/chunk-36SX6QXP.cjs.map +1 -0
  54. package/dist/{chunk-H3XP6BAV.js → chunk-36VYWVQU.js} +3 -3
  55. package/dist/{chunk-H3XP6BAV.js.map → chunk-36VYWVQU.js.map} +1 -1
  56. package/dist/{chunk-VTJVMP4I.js → chunk-4DKY6RIU.js} +102 -31
  57. package/dist/chunk-4DKY6RIU.js.map +1 -0
  58. package/dist/chunk-4QKOZYMV.js +9 -0
  59. package/dist/chunk-4QKOZYMV.js.map +1 -0
  60. package/dist/{chunk-U3Z7XKAG.js → chunk-57JM6NW3.js} +8 -18
  61. package/dist/chunk-57JM6NW3.js.map +1 -0
  62. package/dist/{chunk-WCLMKNQE.cjs → chunk-5FVZSE3B.cjs} +1356 -1108
  63. package/dist/chunk-5FVZSE3B.cjs.map +1 -0
  64. package/dist/{chunk-XMY2SXOH.cjs → chunk-5WWEYV4H.cjs} +2208 -579
  65. package/dist/chunk-5WWEYV4H.cjs.map +1 -0
  66. package/dist/{chunk-WQBAQZHR.js → chunk-6NLYIMJO.js} +4 -4
  67. package/dist/{chunk-WQBAQZHR.js.map → chunk-6NLYIMJO.js.map} +1 -1
  68. package/dist/{chunk-G2TLHH6T.cjs → chunk-7B7I7YAW.cjs} +6 -6
  69. package/dist/{chunk-G2TLHH6T.cjs.map → chunk-7B7I7YAW.cjs.map} +1 -1
  70. package/dist/{chunk-EDLKIQRI.js → chunk-7G5IYROL.js} +6 -548
  71. package/dist/chunk-7G5IYROL.js.map +1 -0
  72. package/dist/{chunk-46UGOVRW.js → chunk-7QFRK6PU.js} +3 -7
  73. package/dist/chunk-7QFRK6PU.js.map +1 -0
  74. package/dist/chunk-A4C4NJ5U.cjs +12 -0
  75. package/dist/chunk-A4C4NJ5U.cjs.map +1 -0
  76. package/dist/{chunk-7CCMCMJO.cjs → chunk-AOGOC6JF.cjs} +77 -68
  77. package/dist/chunk-AOGOC6JF.cjs.map +1 -0
  78. package/dist/{chunk-TYGGUWMS.cjs → chunk-B3MN7EJR.cjs} +177 -137
  79. package/dist/chunk-B3MN7EJR.cjs.map +1 -0
  80. package/dist/{chunk-K6VKTBST.cjs → chunk-BZ5MVITP.cjs} +4 -4
  81. package/dist/{chunk-K6VKTBST.cjs.map → chunk-BZ5MVITP.cjs.map} +1 -1
  82. package/dist/{chunk-ZAQUKCUC.js → chunk-CBOD7TXH.js} +5 -5
  83. package/dist/{chunk-ZAQUKCUC.js.map → chunk-CBOD7TXH.js.map} +1 -1
  84. package/dist/{chunk-LLVOQOWE.cjs → chunk-CRZ56SZU.cjs} +6 -5
  85. package/dist/chunk-CRZ56SZU.cjs.map +1 -0
  86. package/dist/{chunk-ON47CBE4.cjs → chunk-D3GWARN7.cjs} +47 -47
  87. package/dist/{chunk-ON47CBE4.cjs.map → chunk-D3GWARN7.cjs.map} +1 -1
  88. package/dist/{chunk-W5SOCUBL.js → chunk-D3OUDFU7.js} +5 -5
  89. package/dist/{chunk-W5SOCUBL.js.map → chunk-D3OUDFU7.js.map} +1 -1
  90. package/dist/chunk-EKG2UXNX.cjs +23 -0
  91. package/dist/chunk-EKG2UXNX.cjs.map +1 -0
  92. package/dist/{chunk-2Q45FAIE.js → chunk-EVYW3532.js} +28 -19
  93. package/dist/chunk-EVYW3532.js.map +1 -0
  94. package/dist/{chunk-7PRMDZIA.cjs → chunk-FMMW3KX7.cjs} +21 -55
  95. package/dist/chunk-FMMW3KX7.cjs.map +1 -0
  96. package/dist/chunk-H2VWDQWC.cjs +571 -0
  97. package/dist/chunk-H2VWDQWC.cjs.map +1 -0
  98. package/dist/chunk-H4FY6OZK.js +13 -0
  99. package/dist/chunk-H4FY6OZK.js.map +1 -0
  100. package/dist/{chunk-OJHD3LXJ.cjs → chunk-H5IJSROF.cjs} +2 -8
  101. package/dist/chunk-H5IJSROF.cjs.map +1 -0
  102. package/dist/{chunk-U5EL6JUV.js → chunk-I5IOSA27.js} +101 -103
  103. package/dist/chunk-I5IOSA27.js.map +1 -0
  104. package/dist/{chunk-SHC7BCG5.cjs → chunk-I7YAY2VQ.cjs} +7 -7
  105. package/dist/{chunk-SHC7BCG5.cjs.map → chunk-I7YAY2VQ.cjs.map} +1 -1
  106. package/dist/chunk-IRCWIA3R.js +20 -0
  107. package/dist/chunk-IRCWIA3R.js.map +1 -0
  108. package/dist/chunk-IVQBLXBK.cjs +55 -0
  109. package/dist/chunk-IVQBLXBK.cjs.map +1 -0
  110. package/dist/{chunk-5PP4KRPV.js → chunk-IZD4HTCP.js} +5 -5
  111. package/dist/{chunk-5PP4KRPV.js.map → chunk-IZD4HTCP.js.map} +1 -1
  112. package/dist/{chunk-RDP6ZRSM.cjs → chunk-JQKMEKKW.cjs} +261 -204
  113. package/dist/chunk-JQKMEKKW.cjs.map +1 -0
  114. package/dist/chunk-JVA3KDEA.cjs +691 -0
  115. package/dist/chunk-JVA3KDEA.cjs.map +1 -0
  116. package/dist/{chunk-JG5XIJDY.js → chunk-K67P5DLL.js} +62 -22
  117. package/dist/chunk-K67P5DLL.js.map +1 -0
  118. package/dist/{chunk-MX7EKQPM.js → chunk-K6OZIHKI.js} +345 -97
  119. package/dist/chunk-K6OZIHKI.js.map +1 -0
  120. package/dist/{chunk-CS6JTQQ2.cjs → chunk-KACEYDYV.cjs} +94 -62
  121. package/dist/chunk-KACEYDYV.cjs.map +1 -0
  122. package/dist/{chunk-5OWHU7Z7.cjs → chunk-L6EVYIID.cjs} +248 -210
  123. package/dist/chunk-L6EVYIID.cjs.map +1 -0
  124. package/dist/{chunk-7OWE7WD6.js → chunk-LI4K2KEJ.js} +4 -4
  125. package/dist/{chunk-7OWE7WD6.js.map → chunk-LI4K2KEJ.js.map} +1 -1
  126. package/dist/chunk-LKZDQ2B4.js +1581 -0
  127. package/dist/chunk-LKZDQ2B4.js.map +1 -0
  128. package/dist/{chunk-45YZXI6X.cjs → chunk-LLFPQOBA.cjs} +27 -27
  129. package/dist/{chunk-45YZXI6X.cjs.map → chunk-LLFPQOBA.cjs.map} +1 -1
  130. package/dist/{chunk-ZRJTM7MT.js → chunk-LZMQ3SFK.js} +3 -3
  131. package/dist/{chunk-ZRJTM7MT.js.map → chunk-LZMQ3SFK.js.map} +1 -1
  132. package/dist/{chunk-DI6VC62F.js → chunk-M3VTS3F6.js} +3 -3
  133. package/dist/{chunk-DI6VC62F.js.map → chunk-M3VTS3F6.js.map} +1 -1
  134. package/dist/{chunk-MZ34E2GN.js → chunk-NBOS7BY3.js} +60 -21
  135. package/dist/chunk-NBOS7BY3.js.map +1 -0
  136. package/dist/{chunk-YA36ABIL.js → chunk-NGQDGL5X.js} +14 -48
  137. package/dist/chunk-NGQDGL5X.js.map +1 -0
  138. package/dist/{chunk-ZBFZGLZE.cjs → chunk-NLX5OWK7.cjs} +6 -2
  139. package/dist/chunk-NLX5OWK7.cjs.map +1 -0
  140. package/dist/chunk-NUQ2YFFH.cjs +1637 -0
  141. package/dist/chunk-NUQ2YFFH.cjs.map +1 -0
  142. package/dist/{chunk-TTCOPKUL.cjs → chunk-OGL4X4PH.cjs} +182 -184
  143. package/dist/chunk-OGL4X4PH.cjs.map +1 -0
  144. package/dist/{chunk-HY5BNOUN.cjs → chunk-OTNTGEXR.cjs} +4 -4
  145. package/dist/{chunk-HY5BNOUN.cjs.map → chunk-OTNTGEXR.cjs.map} +1 -1
  146. package/dist/chunk-OTWE63BW.js +53 -0
  147. package/dist/chunk-OTWE63BW.js.map +1 -0
  148. package/dist/chunk-PC5NGH5A.js +549 -0
  149. package/dist/chunk-PC5NGH5A.js.map +1 -0
  150. package/dist/{chunk-IPRP6TDL.cjs → chunk-PS3TUWJM.cjs} +7 -7
  151. package/dist/{chunk-IPRP6TDL.cjs.map → chunk-PS3TUWJM.cjs.map} +1 -1
  152. package/dist/{chunk-V76FGHY3.js → chunk-PVFFH7TL.js} +5 -5
  153. package/dist/{chunk-V76FGHY3.js.map → chunk-PVFFH7TL.js.map} +1 -1
  154. package/dist/chunk-QCD5JKU4.cjs +15 -0
  155. package/dist/chunk-QCD5JKU4.cjs.map +1 -0
  156. package/dist/{chunk-IRPYOHRC.js → chunk-QG5VEOKX.js} +6 -2
  157. package/dist/chunk-QG5VEOKX.js.map +1 -0
  158. package/dist/{chunk-2CYI5HRH.js → chunk-RI7RJH4G.js} +49 -17
  159. package/dist/chunk-RI7RJH4G.js.map +1 -0
  160. package/dist/{chunk-5LKOVCPP.js → chunk-RVUL2HXY.js} +6 -5
  161. package/dist/chunk-RVUL2HXY.js.map +1 -0
  162. package/dist/{chunk-WK23PGTP.cjs → chunk-S5GU4LUN.cjs} +11 -11
  163. package/dist/{chunk-WK23PGTP.cjs.map → chunk-S5GU4LUN.cjs.map} +1 -1
  164. package/dist/{chunk-S33YQEL7.js → chunk-SDPWO2Z5.js} +6 -6
  165. package/dist/{chunk-S33YQEL7.js.map → chunk-SDPWO2Z5.js.map} +1 -1
  166. package/dist/{chunk-6S3PTHL4.js → chunk-SLGGT2XD.js} +3 -3
  167. package/dist/{chunk-6S3PTHL4.js.map → chunk-SLGGT2XD.js.map} +1 -1
  168. package/dist/{chunk-HSEZ7X6Y.cjs → chunk-TIJUA4I6.cjs} +45 -45
  169. package/dist/{chunk-HSEZ7X6Y.cjs.map → chunk-TIJUA4I6.cjs.map} +1 -1
  170. package/dist/{chunk-CSNOYIB4.cjs → chunk-TM54OBHX.cjs} +13 -13
  171. package/dist/{chunk-CSNOYIB4.cjs.map → chunk-TM54OBHX.cjs.map} +1 -1
  172. package/dist/{chunk-MM3JHVKZ.cjs → chunk-TUWSVL6I.cjs} +4 -4
  173. package/dist/{chunk-MM3JHVKZ.cjs.map → chunk-TUWSVL6I.cjs.map} +1 -1
  174. package/dist/{chunk-2GIV5X4P.js → chunk-TYEYRCXL.js} +86 -33
  175. package/dist/chunk-TYEYRCXL.js.map +1 -0
  176. package/dist/{chunk-MJPZNEJZ.js → chunk-UKOVGCRN.js} +2095 -496
  177. package/dist/chunk-UKOVGCRN.js.map +1 -0
  178. package/dist/chunk-UYKDYE5D.cjs +12 -0
  179. package/dist/{chunk-KWNWG4RC.cjs.map → chunk-UYKDYE5D.cjs.map} +1 -1
  180. package/dist/{chunk-FX5ZW6PN.js → chunk-VAAC7L57.js} +95 -40
  181. package/dist/chunk-VAAC7L57.js.map +1 -0
  182. package/dist/{chunk-ISKCIQF2.cjs → chunk-VKHXYVN7.cjs} +14 -25
  183. package/dist/chunk-VKHXYVN7.cjs.map +1 -0
  184. package/dist/chunk-VUQZNUHU.js +171 -0
  185. package/dist/chunk-VUQZNUHU.js.map +1 -0
  186. package/dist/{chunk-K2XYLVVB.cjs → chunk-WDM5WQK4.cjs} +175 -136
  187. package/dist/chunk-WDM5WQK4.cjs.map +1 -0
  188. package/dist/{chunk-GVYVGGPJ.js → chunk-WFSYYU4W.js} +66 -28
  189. package/dist/chunk-WFSYYU4W.js.map +1 -0
  190. package/dist/{chunk-R7MRFE5P.js → chunk-WS5MT2UJ.js} +3 -3
  191. package/dist/{chunk-R7MRFE5P.js.map → chunk-WS5MT2UJ.js.map} +1 -1
  192. package/dist/chunk-XORONCV3.js +202 -0
  193. package/dist/chunk-XORONCV3.js.map +1 -0
  194. package/dist/chunk-ZGVTNKTX.cjs +217 -0
  195. package/dist/chunk-ZGVTNKTX.cjs.map +1 -0
  196. package/dist/core/index.cjs +20 -20
  197. package/dist/core/index.d.cts +4 -4
  198. package/dist/core/index.d.ts +4 -4
  199. package/dist/core/index.js +4 -4
  200. package/dist/{ddl-B49O7dB_.d.ts → ddl-BvcbgzHo.d.ts} +3 -3
  201. package/dist/{ddl-DcZG660s.d.cts → ddl-Ufebz5q5.d.cts} +3 -3
  202. package/dist/graph-extension/index.d.cts +2 -4
  203. package/dist/graph-extension/index.d.ts +2 -4
  204. package/dist/graph-merge/index.cjs +140 -125
  205. package/dist/graph-merge/index.cjs.map +1 -1
  206. package/dist/graph-merge/index.d.cts +8 -9
  207. package/dist/graph-merge/index.d.ts +8 -9
  208. package/dist/graph-merge/index.js +42 -27
  209. package/dist/graph-merge/index.js.map +1 -1
  210. package/dist/index.cjs +144 -143
  211. package/dist/index.cjs.map +1 -1
  212. package/dist/index.d.cts +11 -12
  213. package/dist/index.d.ts +11 -12
  214. package/dist/index.js +30 -29
  215. package/dist/index.js.map +1 -1
  216. package/dist/indexes/index.cjs +14 -12
  217. package/dist/indexes/index.d.cts +4 -4
  218. package/dist/indexes/index.d.ts +4 -4
  219. package/dist/indexes/index.js +7 -5
  220. package/dist/{ingestion-import-target-CI8OWIkM.d.ts → ingestion-import-target-CAs1OX-l.d.cts} +1 -1
  221. package/dist/{ingestion-import-target-DCpfM1PX.d.cts → ingestion-import-target-DCQSPfNx.d.ts} +1 -1
  222. package/dist/interchange/index.cjs +41 -39
  223. package/dist/interchange/index.cjs.map +1 -1
  224. package/dist/interchange/index.d.cts +8 -8
  225. package/dist/interchange/index.d.ts +8 -8
  226. package/dist/interchange/index.js +16 -14
  227. package/dist/interchange/index.js.map +1 -1
  228. package/dist/local-store-impl-JC7OBRAW.js +75 -0
  229. package/dist/local-store-impl-JC7OBRAW.js.map +1 -0
  230. package/dist/local-store-impl-UOS2LUIG.cjs +77 -0
  231. package/dist/local-store-impl-UOS2LUIG.cjs.map +1 -0
  232. package/dist/{manager-Cfg1ENj1.d.ts → manager-B68OrPR2.d.ts} +1 -2
  233. package/dist/{manager-D348fa6W.d.cts → manager-D_t7oK69.d.cts} +1 -2
  234. package/dist/pglite-store-impl-J5J5AA52.cjs +75 -0
  235. package/dist/pglite-store-impl-J5J5AA52.cjs.map +1 -0
  236. package/dist/pglite-store-impl-LDRH2DUH.js +73 -0
  237. package/dist/pglite-store-impl-LDRH2DUH.js.map +1 -0
  238. package/dist/{postgres-UStOycLI.d.ts → postgres-BPLSVyHM.d.ts} +1 -1
  239. package/dist/{postgres-CH1kkM5J.d.cts → postgres-CqvtFC2y.d.cts} +1 -1
  240. package/dist/profiler/index.d.cts +9 -9
  241. package/dist/profiler/index.d.ts +9 -9
  242. package/dist/provenance/index.cjs +33 -20
  243. package/dist/provenance/index.cjs.map +1 -1
  244. package/dist/provenance/index.d.cts +7 -7
  245. package/dist/provenance/index.d.ts +7 -7
  246. package/dist/provenance/index.js +24 -11
  247. package/dist/provenance/index.js.map +1 -1
  248. package/dist/{repair-validity-windows-aWX7VNvv.d.cts → repair-validity-windows-DEzCKAdy.d.cts} +7 -3
  249. package/dist/{repair-validity-windows-BtOEe2pS.d.ts → repair-validity-windows-GMdaS2AH.d.ts} +7 -3
  250. package/dist/resolve-D_H8MHtq.d.ts +1805 -0
  251. package/dist/resolve-WEW8gWws.d.cts +1805 -0
  252. package/dist/schema/index.cjs +42 -40
  253. package/dist/schema/index.d.cts +4 -6
  254. package/dist/schema/index.d.ts +4 -6
  255. package/dist/schema/index.js +15 -13
  256. package/dist/{searchable-z4BiFfHI.d.ts → searchable-C_UREI9K.d.ts} +1 -1
  257. package/dist/{searchable-C8-RrL3l.d.cts → searchable-ClgET_i7.d.cts} +1 -1
  258. package/dist/{sqlite-axLw5Lo5.d.ts → sqlite-D1mXO9Kp.d.cts} +2 -1
  259. package/dist/{sqlite-Cyx9j9o6.d.cts → sqlite-MZA3oZNB.d.ts} +2 -1
  260. package/dist/{store-CTfQ9taw.d.ts → store-CuFX7fCx.d.cts} +38 -41
  261. package/dist/{store-DR9J7JVB.d.cts → store-D-ZjXQpW.d.ts} +38 -41
  262. package/dist/{temporal-CBOrERz5.d.ts → temporal-CpyEiRY8.d.cts} +1 -1
  263. package/dist/{temporal-B4Ky4wzh.d.cts → temporal-y0Aep9Su.d.ts} +1 -1
  264. package/dist/{types-CWg4dTjj.d.ts → types-6yf0Vv-_.d.cts} +1672 -1
  265. package/dist/{types-CWg4dTjj.d.cts → types-6yf0Vv-_.d.ts} +1672 -1
  266. package/dist/{types-BScHXVM7.d.ts → types-DzJ4dlzk.d.cts} +1 -1
  267. package/dist/{types-BE921wRl.d.cts → types-_vVSB9k-.d.ts} +1 -1
  268. package/dist/{where-BWXUPV3C.d.ts → where-DuG2LCLe.d.ts} +1 -1
  269. package/dist/{where-CNtx1aLc.d.cts → where-Mhf_yyKX.d.cts} +1 -1
  270. package/package.json +5 -1
  271. package/dist/chunk-2CYI5HRH.js.map +0 -1
  272. package/dist/chunk-2GIV5X4P.js.map +0 -1
  273. package/dist/chunk-2Q45FAIE.js.map +0 -1
  274. package/dist/chunk-46UGOVRW.js.map +0 -1
  275. package/dist/chunk-5LKOVCPP.js.map +0 -1
  276. package/dist/chunk-5OWHU7Z7.cjs.map +0 -1
  277. package/dist/chunk-6LEOAIIB.js +0 -1160
  278. package/dist/chunk-6LEOAIIB.js.map +0 -1
  279. package/dist/chunk-7CCMCMJO.cjs.map +0 -1
  280. package/dist/chunk-7PRMDZIA.cjs.map +0 -1
  281. package/dist/chunk-C76WFIVZ.cjs.map +0 -1
  282. package/dist/chunk-CS6JTQQ2.cjs.map +0 -1
  283. package/dist/chunk-EDLKIQRI.js.map +0 -1
  284. package/dist/chunk-EH3JZJUM.cjs +0 -567
  285. package/dist/chunk-EH3JZJUM.cjs.map +0 -1
  286. package/dist/chunk-FX5ZW6PN.js.map +0 -1
  287. package/dist/chunk-GHZPZNFC.cjs +0 -132
  288. package/dist/chunk-GHZPZNFC.cjs.map +0 -1
  289. package/dist/chunk-GVYVGGPJ.js.map +0 -1
  290. package/dist/chunk-IHK5KA2Q.cjs +0 -262
  291. package/dist/chunk-IHK5KA2Q.cjs.map +0 -1
  292. package/dist/chunk-IRPYOHRC.js.map +0 -1
  293. package/dist/chunk-ISKCIQF2.cjs.map +0 -1
  294. package/dist/chunk-JG5XIJDY.js.map +0 -1
  295. package/dist/chunk-K2XYLVVB.cjs.map +0 -1
  296. package/dist/chunk-KWNWG4RC.cjs +0 -12
  297. package/dist/chunk-LLVOQOWE.cjs.map +0 -1
  298. package/dist/chunk-MJPZNEJZ.js.map +0 -1
  299. package/dist/chunk-MX7EKQPM.js.map +0 -1
  300. package/dist/chunk-MZ34E2GN.js.map +0 -1
  301. package/dist/chunk-OJHD3LXJ.cjs.map +0 -1
  302. package/dist/chunk-PALYTHGM.js +0 -114
  303. package/dist/chunk-PALYTHGM.js.map +0 -1
  304. package/dist/chunk-RDP6ZRSM.cjs.map +0 -1
  305. package/dist/chunk-S3SDEQMC.js +0 -532
  306. package/dist/chunk-S3SDEQMC.js.map +0 -1
  307. package/dist/chunk-TEC24ZDA.cjs +0 -1254
  308. package/dist/chunk-TEC24ZDA.cjs.map +0 -1
  309. package/dist/chunk-TP4NJTI3.cjs +0 -1192
  310. package/dist/chunk-TP4NJTI3.cjs.map +0 -1
  311. package/dist/chunk-TTCOPKUL.cjs.map +0 -1
  312. package/dist/chunk-TUVD4DFR.cjs.map +0 -1
  313. package/dist/chunk-TYGGUWMS.cjs.map +0 -1
  314. package/dist/chunk-U3Z7XKAG.js.map +0 -1
  315. package/dist/chunk-U5EL6JUV.js.map +0 -1
  316. package/dist/chunk-VTJVMP4I.js.map +0 -1
  317. package/dist/chunk-WCLMKNQE.cjs.map +0 -1
  318. package/dist/chunk-XMY2SXOH.cjs.map +0 -1
  319. package/dist/chunk-Y55DLLEG.js +0 -247
  320. package/dist/chunk-Y55DLLEG.js.map +0 -1
  321. package/dist/chunk-YA36ABIL.js.map +0 -1
  322. package/dist/chunk-ZBFZGLZE.cjs.map +0 -1
  323. package/dist/index-B0PrmE3K.d.cts +0 -1146
  324. package/dist/index-CwcXsL5R.d.ts +0 -1146
  325. package/dist/materialize-indexes-C9GG3O3C.d.ts +0 -266
  326. package/dist/materialize-indexes-CrSiW_lT.d.cts +0 -266
@@ -1,262 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkNAUA4PW5_cjs = require('./chunk-NAUA4PW5.cjs');
4
- var chunkOJHD3LXJ_cjs = require('./chunk-OJHD3LXJ.cjs');
5
- var chunkX4GDXBOP_cjs = require('./chunk-X4GDXBOP.cjs');
6
-
7
- // src/query/compiler/schema.ts
8
- var SQL_SCHEMA_BRAND = chunkOJHD3LXJ_cjs.typeGraphGlobalSymbol("sql-schema-v1");
9
- var SqlSchema = class {
10
- };
11
- var SqlSchemaDescriptor = class extends SqlSchema {
12
- tables;
13
- nodesTable;
14
- edgesTable;
15
- recordedNodesTable;
16
- recordedEdgesTable;
17
- recordedClockTable;
18
- revisionOriginsTable;
19
- identityAssertionsTable;
20
- recordedIdentityAssertionsTable;
21
- identityClosureTable;
22
- identitySeparationTable;
23
- fulltextTable;
24
- constructor(fields) {
25
- super();
26
- Object.defineProperty(this, SQL_SCHEMA_BRAND, {
27
- configurable: false,
28
- enumerable: false,
29
- value: true,
30
- writable: false
31
- });
32
- this.tables = fields.tables;
33
- this.nodesTable = fields.nodesTable;
34
- this.edgesTable = fields.edgesTable;
35
- this.recordedNodesTable = fields.recordedNodesTable;
36
- this.recordedEdgesTable = fields.recordedEdgesTable;
37
- this.recordedClockTable = fields.recordedClockTable;
38
- this.revisionOriginsTable = fields.revisionOriginsTable;
39
- this.identityAssertionsTable = fields.identityAssertionsTable;
40
- this.recordedIdentityAssertionsTable = fields.recordedIdentityAssertionsTable;
41
- this.identityClosureTable = fields.identityClosureTable;
42
- this.identitySeparationTable = fields.identitySeparationTable;
43
- this.fulltextTable = fields.fulltextTable;
44
- Object.freeze(this);
45
- }
46
- };
47
- var DEFAULT_TABLE_NAMES = {
48
- nodes: "typegraph_nodes",
49
- edges: "typegraph_edges",
50
- recordedNodes: "typegraph_recorded_nodes",
51
- recordedEdges: "typegraph_recorded_edges",
52
- recordedClock: "typegraph_recorded_clock",
53
- revisionOrigins: "typegraph_revision_origins",
54
- identityAssertions: "typegraph_identity_assertions",
55
- recordedIdentityAssertions: "typegraph_recorded_identity_assertions",
56
- identityClosure: "typegraph_identity_closure",
57
- identitySeparation: "typegraph_identity_separation",
58
- fulltext: "typegraph_node_fulltext",
59
- uniques: "typegraph_node_uniques",
60
- edgeClaims: "typegraph_edge_claims"
61
- };
62
- function resolveTableNames(names) {
63
- return {
64
- nodes: names.nodes ?? DEFAULT_TABLE_NAMES.nodes,
65
- edges: names.edges ?? DEFAULT_TABLE_NAMES.edges,
66
- recordedNodes: names.recordedNodes ?? DEFAULT_TABLE_NAMES.recordedNodes,
67
- recordedEdges: names.recordedEdges ?? DEFAULT_TABLE_NAMES.recordedEdges,
68
- recordedClock: names.recordedClock ?? DEFAULT_TABLE_NAMES.recordedClock,
69
- revisionOrigins: names.revisionOrigins ?? DEFAULT_TABLE_NAMES.revisionOrigins,
70
- identityAssertions: names.identityAssertions ?? DEFAULT_TABLE_NAMES.identityAssertions,
71
- recordedIdentityAssertions: names.recordedIdentityAssertions ?? DEFAULT_TABLE_NAMES.recordedIdentityAssertions,
72
- identityClosure: names.identityClosure ?? DEFAULT_TABLE_NAMES.identityClosure,
73
- identitySeparation: names.identitySeparation ?? DEFAULT_TABLE_NAMES.identitySeparation,
74
- fulltext: names.fulltext ?? DEFAULT_TABLE_NAMES.fulltext,
75
- uniques: names.uniques ?? DEFAULT_TABLE_NAMES.uniques,
76
- edgeClaims: names.edgeClaims ?? DEFAULT_TABLE_NAMES.edgeClaims
77
- };
78
- }
79
- var VALID_IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_$]*$/i;
80
- function validateTableName(name, label) {
81
- if (!name || name.length === 0) {
82
- throw new chunkX4GDXBOP_cjs.ConfigurationError(`${label} table name cannot be empty`);
83
- }
84
- if (name.length > chunkNAUA4PW5_cjs.MAX_PG_IDENTIFIER_LENGTH) {
85
- throw new chunkX4GDXBOP_cjs.ConfigurationError(
86
- `${label} table name exceeds maximum length of ${chunkNAUA4PW5_cjs.MAX_PG_IDENTIFIER_LENGTH} characters`
87
- );
88
- }
89
- if (!VALID_IDENTIFIER_PATTERN.test(name)) {
90
- throw new chunkX4GDXBOP_cjs.ConfigurationError(
91
- `${label} table name "${name}" is not a valid SQL identifier. Table names must start with a letter or underscore and contain only letters, digits, underscores, or dollar signs.`
92
- );
93
- }
94
- }
95
- function freezeSqlSchema(fields) {
96
- return new SqlSchemaDescriptor(fields);
97
- }
98
- function isSqlSchema(schema) {
99
- if (typeof schema !== "object" || schema === null) return false;
100
- const candidate = schema;
101
- return candidate[SQL_SCHEMA_BRAND] === true && typeof candidate["tables"] === "object" && candidate["tables"] !== null && Object.isFrozen(candidate["tables"]) && chunkOJHD3LXJ_cjs.isSqlFragment(candidate["nodesTable"]) && chunkOJHD3LXJ_cjs.isSqlFragment(candidate["edgesTable"]) && chunkOJHD3LXJ_cjs.isSqlFragment(candidate["recordedNodesTable"]) && chunkOJHD3LXJ_cjs.isSqlFragment(candidate["recordedEdgesTable"]) && chunkOJHD3LXJ_cjs.isSqlFragment(candidate["recordedClockTable"]) && chunkOJHD3LXJ_cjs.isSqlFragment(candidate["revisionOriginsTable"]) && chunkOJHD3LXJ_cjs.isSqlFragment(candidate["fulltextTable"]) && Object.isFrozen(candidate);
102
- }
103
- function requireSqlSchema(schema, surface = "SqlSchema") {
104
- if (isSqlSchema(schema)) return schema;
105
- throw new chunkX4GDXBOP_cjs.ConfigurationError(
106
- `${surface} must be created with createSqlSchema(...).`,
107
- { code: "INVALID_SQL_SCHEMA", surface },
108
- {
109
- suggestion: "Pass the result of createSqlSchema(...) instead of a plain schema-shaped object."
110
- }
111
- );
112
- }
113
- function createSqlSchema(names = {}) {
114
- const tables = resolveTableNames(names);
115
- validateTableName(tables.nodes, "nodes");
116
- validateTableName(tables.edges, "edges");
117
- validateTableName(tables.recordedNodes, "recordedNodes");
118
- validateTableName(tables.recordedEdges, "recordedEdges");
119
- validateTableName(tables.recordedClock, "recordedClock");
120
- validateTableName(tables.revisionOrigins, "revisionOrigins");
121
- validateTableName(tables.identityAssertions, "identityAssertions");
122
- validateTableName(
123
- tables.recordedIdentityAssertions,
124
- "recordedIdentityAssertions"
125
- );
126
- validateTableName(tables.identityClosure, "identityClosure");
127
- validateTableName(tables.identitySeparation, "identitySeparation");
128
- validateTableName(tables.fulltext, "fulltext");
129
- validateTableName(tables.uniques, "uniques");
130
- validateTableName(tables.edgeClaims, "edgeClaims");
131
- return freezeSqlSchema({
132
- tables: Object.freeze(tables),
133
- nodesTable: chunkOJHD3LXJ_cjs.sql.identifier(tables.nodes),
134
- edgesTable: chunkOJHD3LXJ_cjs.sql.identifier(tables.edges),
135
- recordedNodesTable: chunkOJHD3LXJ_cjs.sql.identifier(tables.recordedNodes),
136
- recordedEdgesTable: chunkOJHD3LXJ_cjs.sql.identifier(tables.recordedEdges),
137
- recordedClockTable: chunkOJHD3LXJ_cjs.sql.identifier(tables.recordedClock),
138
- revisionOriginsTable: chunkOJHD3LXJ_cjs.sql.identifier(tables.revisionOrigins),
139
- identityAssertionsTable: chunkOJHD3LXJ_cjs.sql.identifier(tables.identityAssertions),
140
- recordedIdentityAssertionsTable: chunkOJHD3LXJ_cjs.sql.identifier(
141
- tables.recordedIdentityAssertions
142
- ),
143
- identityClosureTable: chunkOJHD3LXJ_cjs.sql.identifier(tables.identityClosure),
144
- identitySeparationTable: chunkOJHD3LXJ_cjs.sql.identifier(tables.identitySeparation),
145
- fulltextTable: chunkOJHD3LXJ_cjs.sql.identifier(tables.fulltext)
146
- });
147
- }
148
- var EXTERNAL_RECORDED_READ_SOURCE = chunkOJHD3LXJ_cjs.typeGraphGlobalSymbol(
149
- "external-recorded-read-source-v1"
150
- );
151
- var TYPEGRAPH_RECORDED_READ_SOURCE = chunkOJHD3LXJ_cjs.typeGraphGlobalSymbol(
152
- "typegraph-recorded-read-source-v1"
153
- );
154
- function recordedRelation(options) {
155
- const schema = requireSqlSchema(options.schema, "recordedRelation schema");
156
- return Object.freeze({
157
- source: "external",
158
- schema,
159
- [EXTERNAL_RECORDED_READ_SOURCE]: true
160
- });
161
- }
162
- function requireExternalRecordedReadSource(source) {
163
- if (source === void 0) return void 0;
164
- if (isExternalRecordedReadSource(source)) return source;
165
- throw new chunkX4GDXBOP_cjs.ConfigurationError(
166
- "recordedRead must be created with recordedRelation({ schema }).",
167
- { code: "INVALID_RECORDED_READ_SOURCE" },
168
- {
169
- suggestion: "Pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation. Use { history: true } when TypeGraph should capture writes."
170
- }
171
- );
172
- }
173
- function isExternalRecordedReadSource(source) {
174
- if (typeof source !== "object" || source === null) return false;
175
- const candidate = source;
176
- return candidate.source === "external" && candidate[EXTERNAL_RECORDED_READ_SOURCE] === true && isSqlSchema(candidate.schema) && Object.isFrozen(candidate);
177
- }
178
- function createRecordedReadBinding(schema) {
179
- const readSchema = requireSqlSchema(schema, "recorded read binding schema");
180
- return Object.freeze({
181
- source: "typegraph-capture",
182
- schema: readSchema,
183
- [TYPEGRAPH_RECORDED_READ_SOURCE]: true
184
- });
185
- }
186
- function requireRecordedReadBinding(binding, surface) {
187
- if (isRecordedReadBinding(binding)) return binding;
188
- if (binding !== void 0) {
189
- throw new chunkX4GDXBOP_cjs.ConfigurationError(
190
- "Recorded-time reads require a recorded read relation created by TypeGraph.",
191
- { code: "INVALID_RECORDED_READ_BINDING", surface },
192
- {
193
- suggestion: "Use createStore(graph, backend, { history: true }) or { recordedRead: recordedRelation({ schema }) } instead of passing a plain object."
194
- }
195
- );
196
- }
197
- throw new chunkX4GDXBOP_cjs.ConfigurationError(
198
- "Recorded-time reads require a recorded read relation.",
199
- { code: "RECORDED_READ_REQUIRES_BINDING", surface },
200
- {
201
- suggestion: "Create the store with createStore(graph, backend, { history: true }) to bind TypeGraph's built-in captured relation, or pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation."
202
- }
203
- );
204
- }
205
- function isTypeGraphRecordedReadSource(source) {
206
- if (typeof source !== "object" || source === null) return false;
207
- const candidate = source;
208
- return candidate.source === "typegraph-capture" && candidate[TYPEGRAPH_RECORDED_READ_SOURCE] === true && isSqlSchema(candidate.schema) && Object.isFrozen(candidate);
209
- }
210
- function isRecordedReadBinding(binding) {
211
- return isExternalRecordedReadSource(binding) || isTypeGraphRecordedReadSource(binding);
212
- }
213
- function recordedReadSqlSchema(binding) {
214
- const { schema } = requireRecordedReadBinding(
215
- binding,
216
- "recorded-read-schema"
217
- );
218
- return freezeSqlSchema({
219
- tables: schema.tables,
220
- nodesTable: schema.recordedNodesTable,
221
- edgesTable: schema.recordedEdgesTable,
222
- recordedNodesTable: schema.recordedNodesTable,
223
- recordedEdgesTable: schema.recordedEdgesTable,
224
- recordedClockTable: schema.recordedClockTable,
225
- revisionOriginsTable: schema.revisionOriginsTable,
226
- identityAssertionsTable: schema.identityAssertionsTable,
227
- recordedIdentityAssertionsTable: schema.recordedIdentityAssertionsTable,
228
- identityClosureTable: schema.identityClosureTable,
229
- identitySeparationTable: schema.identitySeparationTable,
230
- fulltextTable: schema.fulltextTable
231
- });
232
- }
233
- function recordedReadSchemaFor(schema, recordedAsOf, binding, surface) {
234
- const baseSchema = requireSqlSchema(schema, `${surface} schema`);
235
- if (recordedAsOf === void 0) return baseSchema;
236
- return recordedReadSqlSchema(requireRecordedReadBinding(binding, surface));
237
- }
238
- var DEFAULT_SQL_SCHEMA = createSqlSchema();
239
- function vectorSlotKey(nodeKind, fieldPath) {
240
- return `${nodeKind}\0${fieldPath}`;
241
- }
242
- var ALIAS_CTE_PREFIX = "cte_";
243
- var EMBEDDINGS_CTE_ALIAS = "cte_embeddings";
244
- var FULLTEXT_CTE_ALIAS = "cte_fulltext";
245
- var HYBRID_CANDIDATES_CTE_ALIAS = "cte_relevance_candidates";
246
-
247
- exports.ALIAS_CTE_PREFIX = ALIAS_CTE_PREFIX;
248
- exports.DEFAULT_SQL_SCHEMA = DEFAULT_SQL_SCHEMA;
249
- exports.EMBEDDINGS_CTE_ALIAS = EMBEDDINGS_CTE_ALIAS;
250
- exports.FULLTEXT_CTE_ALIAS = FULLTEXT_CTE_ALIAS;
251
- exports.HYBRID_CANDIDATES_CTE_ALIAS = HYBRID_CANDIDATES_CTE_ALIAS;
252
- exports.createRecordedReadBinding = createRecordedReadBinding;
253
- exports.createSqlSchema = createSqlSchema;
254
- exports.recordedReadSchemaFor = recordedReadSchemaFor;
255
- exports.recordedReadSqlSchema = recordedReadSqlSchema;
256
- exports.recordedRelation = recordedRelation;
257
- exports.requireExternalRecordedReadSource = requireExternalRecordedReadSource;
258
- exports.requireRecordedReadBinding = requireRecordedReadBinding;
259
- exports.requireSqlSchema = requireSqlSchema;
260
- exports.vectorSlotKey = vectorSlotKey;
261
- //# sourceMappingURL=chunk-IHK5KA2Q.cjs.map
262
- //# sourceMappingURL=chunk-IHK5KA2Q.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/query/compiler/schema.ts"],"names":["typeGraphGlobalSymbol","ConfigurationError","MAX_PG_IDENTIFIER_LENGTH","isSqlFragment","sql"],"mappings":";;;;;;;AAaA,IAAM,gBAAA,GAAkCA,wCAAsB,eAAe,CAAA;AAqGtE,IAAe,YAAf,MAAoD;AAc3D,CAAA;AAEA,IAAM,mBAAA,GAAN,cAAkC,SAAA,CAAU;AAAA,EAEjC,MAAA;AAAA,EACA,UAAA;AAAA,E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AA;AAAA,IAC3B,sBAAsB,MAAA,CAAO,oBAAA;AAAA,IAC7B,yBAAyB,MAAA,CAAO,uBAAA;AAAA,IAChC,iCAAiC,MAAA,CAAO,+BAAA;AAAA,IACxC,sBAAsB,MAAA,CAAO,oBAAA;AAAA,IAC7B,yBAAyB,MAAA,CAAO,uBAAA;AAAA,IAChC,eAAe,MAAA,CAAO;AAAA,GACvB,CAAA;AACH;AAOO,SAAS,qBAAA,CACd,MAAA,EACA,YAAA,EACA,OAAA,EACA,OAAA,EACW;AACX,EAAA,MAAM,UAAA,GAAa,gBAAA,CAAiB,MAAA,EAAQ,CAAA,EAAG,OAAO,CAAA,OAAA,CAAS,CAAA;AAC/D,EAAA,IAAI,YAAA,KAAiB,QAAW,OAAO,UAAA;AACvC,EAAA,OAAO,qBAAA,CAAsB,0BAAA,CAA2B,OAAA,EAAS,OAAO,CAAC,CAAA;AAC3E;AAKO,IAAM,qBAAgC,eAAA;AA0BtC,SAAS,aAAA,CAAc,UAAkB,SAAA,EAA2B;AACzE,EAAA,OAAO,CAAA,EAAG,QAAQ,CAAA,EAAA,EAAS,SAAS,CAAA,CAAA;AACtC;AAOO,IAAM,gBAAA,GAAmB;AACzB,IAAM,oBAAA,GAAuB;AAC7B,IAAM,kBAAA,GAAqB;AAC3B,IAAM,2BAAA,GAA8B","file":"chunk-IHK5KA2Q.cjs","sourcesContent":["/**\n * SQL Schema Configuration for Query Compilation\n *\n * Provides table and column identifiers that the query compiler uses.\n * This allows the compiler to work with custom table names instead of\n * hard-coded defaults.\n */\nimport { type VectorIndexType, type VectorMetric } from \"../../backend/types\";\nimport { MAX_PG_IDENTIFIER_LENGTH } from \"../../constants\";\nimport { ConfigurationError } from \"../../errors\";\nimport { typeGraphGlobalSymbol } from \"../../utils/global-symbol\";\nimport { isSqlFragment, sql, type SqlFragment } from \"../sql-fragment\";\n\nconst SQL_SCHEMA_BRAND: unique symbol = typeGraphGlobalSymbol(\"sql-schema-v1\");\n\n/**\n * Table names for TypeGraph SQL schema.\n *\n * Carries every customizable physical-table name the backend exposes,\n * including the secondary tables (`uniques`, `edgeClaims`) that the query compiler\n * itself doesn't reference but `materializeRemovals` and other\n * cleanup paths need to address by name. Backends without a\n * `uniques` table (custom embeddings-only stores) leave it as the\n * default — the cleanup path is a no-op for kinds with no unique\n * rows.\n */\nexport type SqlTableNames = Readonly<{\n /** Nodes table name (default: \"typegraph_nodes\") */\n nodes: string;\n /** Edges table name (default: \"typegraph_edges\") */\n edges: string;\n /** Recorded node relation table name (default: \"typegraph_recorded_nodes\") */\n recordedNodes?: string | undefined;\n /** Recorded edge relation table name (default: \"typegraph_recorded_edges\") */\n recordedEdges?: string | undefined;\n /** Recorded-time commit clock table name (default: \"typegraph_recorded_clock\") */\n recordedClock?: string | undefined;\n /** Durable per-graph revision-origin table name (default: \"typegraph_revision_origins\") */\n revisionOrigins?: string | undefined;\n /** Identity assertion ledger (default: \"typegraph_identity_assertions\") */\n identityAssertions?: string | undefined;\n /** Recorded identity assertion relation */\n recordedIdentityAssertions?: string | undefined;\n /** Derived current identity closure */\n identityClosure?: string | undefined;\n /** Derived separation relation over identity classes */\n identitySeparation?: string | undefined;\n /** Node fulltext table name (default: \"typegraph_node_fulltext\") */\n fulltext: string;\n /** Node uniques table name (default: \"typegraph_node_uniques\") */\n uniques: string;\n /** Edge cardinality claim table name (default: \"typegraph_edge_claims\") */\n edgeClaims?: string | undefined;\n}>;\n\nexport type ResolvedSqlTableNames = Readonly<{\n /** Nodes table name */\n nodes: string;\n /** Edges table name */\n edges: string;\n /** Recorded node relation table name */\n recordedNodes: string;\n /** Recorded edge relation table name */\n recordedEdges: string;\n /** Recorded-time commit clock table name */\n recordedClock: string;\n /** Durable per-graph revision-origin table name */\n revisionOrigins: string;\n identityAssertions: string;\n recordedIdentityAssertions: string;\n identityClosure: string;\n identitySeparation: string;\n /** Node fulltext table name */\n fulltext: string;\n /** Node uniques table name */\n uniques: string;\n /** Edge cardinality claim table name */\n edgeClaims: string;\n}>;\n\ntype SqlSchemaFields = Readonly<{\n /** Table names */\n tables: ResolvedSqlTableNames;\n /** Get a `SqlFragment` reference to the nodes table. */\n nodesTable: SqlFragment;\n /** Get a `SqlFragment` reference to the edges table. */\n edgesTable: SqlFragment;\n /** Get a `SqlFragment` reference to the recorded node relation. */\n recordedNodesTable: SqlFragment;\n /** Get a `SqlFragment` reference to the recorded edge relation. */\n recordedEdgesTable: SqlFragment;\n /** Get a `SqlFragment` reference to the recorded-time commit clock. */\n recordedClockTable: SqlFragment;\n /** Get a `SqlFragment` reference to the durable per-graph revision origins. */\n revisionOriginsTable: SqlFragment;\n /** Get a `SqlFragment` reference to the identity assertion ledger. */\n identityAssertionsTable: SqlFragment;\n /** Get a `SqlFragment` reference to the recorded identity assertion relation. */\n recordedIdentityAssertionsTable: SqlFragment;\n /** Get a `SqlFragment` reference to the derived identity closure. */\n identityClosureTable: SqlFragment;\n /** Get a `SqlFragment` reference to the derived identity separation relation. */\n identitySeparationTable: SqlFragment;\n /** Get a `SqlFragment` reference to the fulltext table. */\n fulltextTable: SqlFragment;\n}>;\n\n/**\n * SQL schema configuration for query compilation.\n * Contains table identifiers and utility methods for generating `SqlFragment` references.\n *\n * Branded and frozen by {@link createSqlSchema}; callers should not construct\n * schema-shaped objects by hand.\n */\nexport abstract class SqlSchema implements SqlSchemaFields {\n declare private readonly typeGraphSqlSchemaBrand: true;\n abstract readonly tables: ResolvedSqlTableNames;\n abstract readonly nodesTable: SqlFragment;\n abstract readonly edgesTable: SqlFragment;\n abstract readonly recordedNodesTable: SqlFragment;\n abstract readonly recordedEdgesTable: SqlFragment;\n abstract readonly recordedClockTable: SqlFragment;\n abstract readonly revisionOriginsTable: SqlFragment;\n abstract readonly identityAssertionsTable: SqlFragment;\n abstract readonly recordedIdentityAssertionsTable: SqlFragment;\n abstract readonly identityClosureTable: SqlFragment;\n abstract readonly identitySeparationTable: SqlFragment;\n abstract readonly fulltextTable: SqlFragment;\n}\n\nclass SqlSchemaDescriptor extends SqlSchema {\n declare readonly [SQL_SCHEMA_BRAND]: true;\n readonly tables: ResolvedSqlTableNames;\n readonly nodesTable: SqlFragment;\n readonly edgesTable: SqlFragment;\n readonly recordedNodesTable: SqlFragment;\n readonly recordedEdgesTable: SqlFragment;\n readonly recordedClockTable: SqlFragment;\n readonly revisionOriginsTable: SqlFragment;\n readonly identityAssertionsTable: SqlFragment;\n readonly recordedIdentityAssertionsTable: SqlFragment;\n readonly identityClosureTable: SqlFragment;\n readonly identitySeparationTable: SqlFragment;\n readonly fulltextTable: SqlFragment;\n\n constructor(fields: SqlSchemaFields) {\n super();\n Object.defineProperty(this, SQL_SCHEMA_BRAND, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n });\n this.tables = fields.tables;\n this.nodesTable = fields.nodesTable;\n this.edgesTable = fields.edgesTable;\n this.recordedNodesTable = fields.recordedNodesTable;\n this.recordedEdgesTable = fields.recordedEdgesTable;\n this.recordedClockTable = fields.recordedClockTable;\n this.revisionOriginsTable = fields.revisionOriginsTable;\n this.identityAssertionsTable = fields.identityAssertionsTable;\n this.recordedIdentityAssertionsTable =\n fields.recordedIdentityAssertionsTable;\n this.identityClosureTable = fields.identityClosureTable;\n this.identitySeparationTable = fields.identitySeparationTable;\n this.fulltextTable = fields.fulltextTable;\n Object.freeze(this);\n }\n}\n\n/**\n * Default table names matching the standard TypeGraph schema.\n */\nconst DEFAULT_TABLE_NAMES: ResolvedSqlTableNames = {\n nodes: \"typegraph_nodes\",\n edges: \"typegraph_edges\",\n recordedNodes: \"typegraph_recorded_nodes\",\n recordedEdges: \"typegraph_recorded_edges\",\n recordedClock: \"typegraph_recorded_clock\",\n revisionOrigins: \"typegraph_revision_origins\",\n identityAssertions: \"typegraph_identity_assertions\",\n recordedIdentityAssertions: \"typegraph_recorded_identity_assertions\",\n identityClosure: \"typegraph_identity_closure\",\n identitySeparation: \"typegraph_identity_separation\",\n fulltext: \"typegraph_node_fulltext\",\n uniques: \"typegraph_node_uniques\",\n edgeClaims: \"typegraph_edge_claims\",\n};\n\nfunction resolveTableNames(\n names: Partial<SqlTableNames>,\n): ResolvedSqlTableNames {\n return {\n nodes: names.nodes ?? DEFAULT_TABLE_NAMES.nodes,\n edges: names.edges ?? DEFAULT_TABLE_NAMES.edges,\n recordedNodes: names.recordedNodes ?? DEFAULT_TABLE_NAMES.recordedNodes,\n recordedEdges: names.recordedEdges ?? DEFAULT_TABLE_NAMES.recordedEdges,\n recordedClock: names.recordedClock ?? DEFAULT_TABLE_NAMES.recordedClock,\n revisionOrigins:\n names.revisionOrigins ?? DEFAULT_TABLE_NAMES.revisionOrigins,\n identityAssertions:\n names.identityAssertions ?? DEFAULT_TABLE_NAMES.identityAssertions,\n recordedIdentityAssertions:\n names.recordedIdentityAssertions ??\n DEFAULT_TABLE_NAMES.recordedIdentityAssertions,\n identityClosure:\n names.identityClosure ?? DEFAULT_TABLE_NAMES.identityClosure,\n identitySeparation:\n names.identitySeparation ?? DEFAULT_TABLE_NAMES.identitySeparation,\n fulltext: names.fulltext ?? DEFAULT_TABLE_NAMES.fulltext,\n uniques: names.uniques ?? DEFAULT_TABLE_NAMES.uniques,\n edgeClaims: names.edgeClaims ?? DEFAULT_TABLE_NAMES.edgeClaims,\n };\n}\n\n/**\n * Regex for valid SQL identifiers.\n * Must start with a letter or underscore.\n * Can contain letters, digits, underscores, and dollar signs.\n * Dollar signs are a PostgreSQL extension but commonly supported.\n */\nconst VALID_IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_$]*$/i;\n\n/**\n * Validates that a table name is a valid SQL identifier.\n *\n * @throws Error if the table name is invalid\n */\nfunction validateTableName(name: string, label: string): void {\n if (!name || name.length === 0) {\n throw new ConfigurationError(`${label} table name cannot be empty`);\n }\n if (name.length > MAX_PG_IDENTIFIER_LENGTH) {\n throw new ConfigurationError(\n `${label} table name exceeds maximum length of ${MAX_PG_IDENTIFIER_LENGTH} characters`,\n );\n }\n if (!VALID_IDENTIFIER_PATTERN.test(name)) {\n throw new ConfigurationError(\n `${label} table name \"${name}\" is not a valid SQL identifier. ` +\n `Table names must start with a letter or underscore and contain only letters, digits, underscores, or dollar signs.`,\n );\n }\n}\n\nfunction freezeSqlSchema(fields: SqlSchemaFields): SqlSchema {\n return new SqlSchemaDescriptor(fields);\n}\n\nfunction isSqlSchema(schema: unknown): schema is SqlSchema {\n if (typeof schema !== \"object\" || schema === null) return false;\n const candidate = schema as Record<PropertyKey, unknown>;\n return (\n candidate[SQL_SCHEMA_BRAND] === true &&\n typeof candidate[\"tables\"] === \"object\" &&\n candidate[\"tables\"] !== null &&\n Object.isFrozen(candidate[\"tables\"]) &&\n isSqlFragment(candidate[\"nodesTable\"]) &&\n isSqlFragment(candidate[\"edgesTable\"]) &&\n isSqlFragment(candidate[\"recordedNodesTable\"]) &&\n isSqlFragment(candidate[\"recordedEdgesTable\"]) &&\n isSqlFragment(candidate[\"recordedClockTable\"]) &&\n isSqlFragment(candidate[\"revisionOriginsTable\"]) &&\n isSqlFragment(candidate[\"fulltextTable\"]) &&\n Object.isFrozen(candidate)\n );\n}\n\nexport function requireSqlSchema(\n schema: unknown,\n surface = \"SqlSchema\",\n): SqlSchema {\n if (isSqlSchema(schema)) return schema;\n throw new ConfigurationError(\n `${surface} must be created with createSqlSchema(...).`,\n { code: \"INVALID_SQL_SCHEMA\", surface },\n {\n suggestion:\n \"Pass the result of createSqlSchema(...) instead of a plain schema-shaped object.\",\n },\n );\n}\n\n/**\n * Creates a SqlSchema configuration from table names.\n *\n * Table names are validated to ensure they are valid SQL identifiers.\n * This prevents SQL injection and ensures compatibility across databases.\n *\n * @param names - Optional custom table names (defaults to standard names)\n * @returns SqlSchema configuration for query compilation\n * @throws Error if any table name is invalid\n *\n * @example\n * ```typescript\n * // Use default table names\n * const schema = createSqlSchema();\n *\n * // Use custom table names\n * const schema = createSqlSchema({\n * nodes: \"myapp_nodes\",\n * edges: \"myapp_edges\",\n * fulltext: \"myapp_fulltext\",\n * });\n * ```\n */\nexport function createSqlSchema(names: Partial<SqlTableNames> = {}): SqlSchema {\n const tables = resolveTableNames(names);\n\n // Validate all table names\n validateTableName(tables.nodes, \"nodes\");\n validateTableName(tables.edges, \"edges\");\n validateTableName(tables.recordedNodes, \"recordedNodes\");\n validateTableName(tables.recordedEdges, \"recordedEdges\");\n validateTableName(tables.recordedClock, \"recordedClock\");\n validateTableName(tables.revisionOrigins, \"revisionOrigins\");\n validateTableName(tables.identityAssertions, \"identityAssertions\");\n validateTableName(\n tables.recordedIdentityAssertions,\n \"recordedIdentityAssertions\",\n );\n validateTableName(tables.identityClosure, \"identityClosure\");\n validateTableName(tables.identitySeparation, \"identitySeparation\");\n validateTableName(tables.fulltext, \"fulltext\");\n validateTableName(tables.uniques, \"uniques\");\n validateTableName(tables.edgeClaims, \"edgeClaims\");\n\n return freezeSqlSchema({\n tables: Object.freeze(tables),\n nodesTable: sql.identifier(tables.nodes),\n edgesTable: sql.identifier(tables.edges),\n recordedNodesTable: sql.identifier(tables.recordedNodes),\n recordedEdgesTable: sql.identifier(tables.recordedEdges),\n recordedClockTable: sql.identifier(tables.recordedClock),\n revisionOriginsTable: sql.identifier(tables.revisionOrigins),\n identityAssertionsTable: sql.identifier(tables.identityAssertions),\n recordedIdentityAssertionsTable: sql.identifier(\n tables.recordedIdentityAssertions,\n ),\n identityClosureTable: sql.identifier(tables.identityClosure),\n identitySeparationTable: sql.identifier(tables.identitySeparation),\n fulltextTable: sql.identifier(tables.fulltext),\n });\n}\n\n/**\n * The recorded/system-time relation a read coordinate may reconstruct from.\n *\n * TypeGraph's built-in capture relation is bound by `createStore(..., {\n * history: true })`. Hosts can also bind externally populated row-compatible\n * recorded relations through `recordedRelation({ schema })`. Keeping both as\n * explicit values separates the read contract from the write-capture mechanism\n * so future external/TMS-owned recorded relations can feed the same query\n * machinery without changing StoreView or ReadCoordinate.\n */\nconst EXTERNAL_RECORDED_READ_SOURCE: unique symbol = typeGraphGlobalSymbol(\n \"external-recorded-read-source-v1\",\n);\n\nexport type ExternalRecordedReadSource = Readonly<{\n source: \"external\";\n schema: SqlSchema;\n [EXTERNAL_RECORDED_READ_SOURCE]: true;\n}>;\n\ntype ExternalRecordedReadSourceCandidate = Readonly<{\n source?: unknown;\n schema?: unknown;\n [EXTERNAL_RECORDED_READ_SOURCE]?: unknown;\n}>;\n\nconst TYPEGRAPH_RECORDED_READ_SOURCE: unique symbol = typeGraphGlobalSymbol(\n \"typegraph-recorded-read-source-v1\",\n);\n\nexport type TypeGraphRecordedReadSource = Readonly<{\n source: \"typegraph-capture\";\n schema: SqlSchema;\n [TYPEGRAPH_RECORDED_READ_SOURCE]: true;\n}>;\n\ntype RecordedReadSource =\n ExternalRecordedReadSource | TypeGraphRecordedReadSource;\n\nexport type RecordedReadBinding = RecordedReadSource;\n\nexport type RecordedRelationOptions = Readonly<{\n schema: SqlSchema;\n}>;\n\nexport function recordedRelation(\n options: RecordedRelationOptions,\n): ExternalRecordedReadSource {\n const schema = requireSqlSchema(options.schema, \"recordedRelation schema\");\n return Object.freeze({\n source: \"external\",\n schema,\n [EXTERNAL_RECORDED_READ_SOURCE]: true as const,\n });\n}\n\nexport function requireExternalRecordedReadSource(\n source: unknown,\n): ExternalRecordedReadSource | undefined {\n if (source === undefined) return undefined;\n if (isExternalRecordedReadSource(source)) return source;\n throw new ConfigurationError(\n \"recordedRead must be created with recordedRelation({ schema }).\",\n { code: \"INVALID_RECORDED_READ_SOURCE\" },\n {\n suggestion:\n \"Pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation. Use { history: true } when TypeGraph should capture writes.\",\n },\n );\n}\n\nfunction isExternalRecordedReadSource(\n source: unknown,\n): source is ExternalRecordedReadSource {\n if (typeof source !== \"object\" || source === null) return false;\n const candidate = source as ExternalRecordedReadSourceCandidate;\n return (\n candidate.source === \"external\" &&\n candidate[EXTERNAL_RECORDED_READ_SOURCE] === true &&\n isSqlSchema(candidate.schema) &&\n Object.isFrozen(candidate)\n );\n}\n\nexport function createRecordedReadBinding(\n schema: SqlSchema,\n): TypeGraphRecordedReadSource {\n const readSchema = requireSqlSchema(schema, \"recorded read binding schema\");\n return Object.freeze({\n source: \"typegraph-capture\",\n schema: readSchema,\n [TYPEGRAPH_RECORDED_READ_SOURCE]: true as const,\n });\n}\n\nexport function requireRecordedReadBinding(\n binding: unknown,\n surface: string,\n): RecordedReadBinding {\n if (isRecordedReadBinding(binding)) return binding;\n if (binding !== undefined) {\n throw new ConfigurationError(\n \"Recorded-time reads require a recorded read relation created by TypeGraph.\",\n { code: \"INVALID_RECORDED_READ_BINDING\", surface },\n {\n suggestion:\n \"Use createStore(graph, backend, { history: true }) or { recordedRead: recordedRelation({ schema }) } instead of passing a plain object.\",\n },\n );\n }\n throw new ConfigurationError(\n \"Recorded-time reads require a recorded read relation.\",\n { code: \"RECORDED_READ_REQUIRES_BINDING\", surface },\n {\n suggestion:\n \"Create the store with createStore(graph, backend, { history: true }) to bind TypeGraph's built-in captured relation, or pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation.\",\n },\n );\n}\n\ntype TypeGraphRecordedReadSourceCandidate = Readonly<{\n source?: unknown;\n schema?: unknown;\n [TYPEGRAPH_RECORDED_READ_SOURCE]?: unknown;\n}>;\n\nfunction isTypeGraphRecordedReadSource(\n source: unknown,\n): source is TypeGraphRecordedReadSource {\n if (typeof source !== \"object\" || source === null) return false;\n const candidate = source as TypeGraphRecordedReadSourceCandidate;\n return (\n candidate.source === \"typegraph-capture\" &&\n candidate[TYPEGRAPH_RECORDED_READ_SOURCE] === true &&\n isSqlSchema(candidate.schema) &&\n Object.isFrozen(candidate)\n );\n}\n\nfunction isRecordedReadBinding(\n binding: unknown,\n): binding is RecordedReadBinding {\n return (\n isExternalRecordedReadSource(binding) ||\n isTypeGraphRecordedReadSource(binding)\n );\n}\n\n/**\n * Returns a schema view whose primary node/edge sources are the recorded-time\n * relations. The recorded relations are row-compatible with the live tables\n * for every column the query compiler, subgraph extractor, and algorithms\n * already read; the temporal filter adds the `recorded_from/to` predicate.\n */\nexport function recordedReadSqlSchema(binding: RecordedReadBinding): SqlSchema {\n const { schema } = requireRecordedReadBinding(\n binding,\n \"recorded-read-schema\",\n );\n return freezeSqlSchema({\n tables: schema.tables,\n nodesTable: schema.recordedNodesTable,\n edgesTable: schema.recordedEdgesTable,\n recordedNodesTable: schema.recordedNodesTable,\n recordedEdgesTable: schema.recordedEdgesTable,\n recordedClockTable: schema.recordedClockTable,\n revisionOriginsTable: schema.revisionOriginsTable,\n identityAssertionsTable: schema.identityAssertionsTable,\n recordedIdentityAssertionsTable: schema.recordedIdentityAssertionsTable,\n identityClosureTable: schema.identityClosureTable,\n identitySeparationTable: schema.identitySeparationTable,\n fulltextTable: schema.fulltextTable,\n });\n}\n\n/**\n * Resolves the read schema for a coordinate: the live schema when no recorded\n * pin is set, or the recorded-relation view when `recordedAsOf` is present. The\n * single place every read path decides whether to source the recorded tables.\n */\nexport function recordedReadSchemaFor(\n schema: SqlSchema,\n recordedAsOf: string | undefined,\n binding: RecordedReadBinding | undefined,\n surface: string,\n): SqlSchema {\n const baseSchema = requireSqlSchema(schema, `${surface} schema`);\n if (recordedAsOf === undefined) return baseSchema;\n return recordedReadSqlSchema(requireRecordedReadBinding(binding, surface));\n}\n\n/**\n * Default SqlSchema using standard TypeGraph table names.\n */\nexport const DEFAULT_SQL_SCHEMA: SqlSchema = createSqlSchema();\n\n/**\n * The compiler's resolved view of one declared embedding field — the\n * `(dimensions, metric, indexType)` a {@link VectorStrategy} needs to\n * name and scan the field's typed per-`(kind, field)` storage. Sourced\n * from the registered node schema's `embedding()` declaration when the\n * store builds its compile options.\n */\nexport type VectorSlotDescriptor = Readonly<{\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n}>;\n\n/**\n * Map of declared embedding slots keyed by {@link vectorSlotKey} -\n * `\"<nodeKind>\\0<fieldPath>\"` (NUL-separated). Carries every `(concrete kind,\n * fieldPath)` that declares an embedding field, so the compiler's\n * `field.similarTo(...)` CTE can UNION ALL the per-field tables for the\n * kinds in an alias that actually declare the field (only\n * `includeSubClasses` yields more than one).\n */\nexport type VectorSlotMap = ReadonlyMap<string, VectorSlotDescriptor>;\n\n/** NUL-delimited composite key for {@link VectorSlotMap}. */\nexport function vectorSlotKey(nodeKind: string, fieldPath: string): string {\n return `${nodeKind}\\u0000${fieldPath}`;\n}\n\n/**\n * CTE aliases used by the standard query emitter. Joining on these names\n * across multiple builder files is fragile when typed as raw strings —\n * import these constants instead.\n */\nexport const ALIAS_CTE_PREFIX = \"cte_\" as const;\nexport const EMBEDDINGS_CTE_ALIAS = \"cte_embeddings\" as const;\nexport const FULLTEXT_CTE_ALIAS = \"cte_fulltext\" as const;\nexport const HYBRID_CANDIDATES_CTE_ALIAS = \"cte_relevance_candidates\" as const;\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/backend/graph-backend-keys.ts","../src/backend/transaction-resource.ts","../src/backend/derive-backend.ts","../src/utils/sql-errors.ts","../src/schema/canonical.ts","../src/utils/array.ts"],"names":[],"mappings":";;;;AAgBO,IAAM,6BAAA,GAAgC;AAAA,EAC3C,SAAA;AAAA,EACA,cAAA;AAAA,EACA,YAAA;AAAA,EACA,kBAAA;AAAA,EACA,gBAAA;AAAA,EACA,YAAA;AAAA,EACA,oBAAA;AAAA,EACA,kBAAA;AAAA,EACA,2BAAA;AAAA,EACA,YAAA;AAAA,EACA,eAAA;AAAA,EACA,YAAA;AAAA,EACA,gBAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA,EACA,YAAA;AAAA,EACA,oBAAA;AAAA,EACA,kBAAA;AAAA,EACA,2BAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA,EACA,gBAAA;AAAA,EACA,kBAAA;AAAA,EACA,sBAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA,EACA,gBAAA;AAAA,EACA,mBAAA;AAAA,EACA,sBAAA;AAAA,EACA,iBAAA;AAAA,EACA,kBAAA;AAAA,EACA,iBAAA;AAAA,EACA,wBAAA;AAA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A,MAAM,KAAA,GAAQ,MAAA,CAAO,GAAA,CAAI,GAAG,KAAK,EAAC;AAClC,IAAA,KAAA,CAAM,KAAK,IAAI,CAAA;AACf,IAAA,MAAA,CAAO,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,EACvB;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-IRPYOHRC.js","sourcesContent":["import { type GraphBackend } from \"./types\";\n\n/**\n * Runtime allowlist for the portable GraphBackend port.\n *\n * Data only: the projection constructors that consume this allowlist live in\n * `derive-backend.ts`, the one seam that carries a backend's\n * serialized-resource audit.\n *\n * `satisfies` rejects misspelled/non-port keys. The coverage record below\n * rejects every newly added GraphBackend key until it is deliberately added\n * here, so a port expansion can neither leak through structural forwarding nor\n * silently disappear from a narrowed backend.\n *\n * @internal\n */\nexport const GRAPH_BACKEND_PROJECTION_KEYS = [\n \"dialect\",\n \"capabilities\",\n \"tableNames\",\n \"fulltextStrategy\",\n \"vectorStrategy\",\n \"insertNode\",\n \"insertNodeNoReturn\",\n \"insertNodesBatch\",\n \"insertNodesBatchReturning\",\n \"updateNode\",\n \"updateNodeSet\",\n \"deleteNode\",\n \"hardDeleteNode\",\n \"getNode\",\n \"getNodes\",\n \"insertEdge\",\n \"insertEdgeNoReturn\",\n \"insertEdgesBatch\",\n \"insertEdgesBatchReturning\",\n \"updateEdge\",\n \"deleteEdge\",\n \"hardDeleteEdge\",\n \"deleteEdgesBatch\",\n \"hardDeleteEdgesBatch\",\n \"getEdge\",\n \"getEdges\",\n \"countEdgesFrom\",\n \"edgeExistsBetween\",\n \"findEdgesConnectedTo\",\n \"findNodesByKind\",\n \"countNodesByKind\",\n \"findEdgesByKind\",\n \"findEdgesByEndpointSet\",\n \"findEdgesByHeterogeneousEndpointSet\",\n \"countEdgesByKind\",\n \"insertUnique\",\n \"insertUniqueBatch\",\n \"deleteUnique\",\n \"hardDeleteUniquesByNodeIds\",\n \"hardDeleteUniquesByConcreteKind\",\n \"checkUnique\",\n \"checkUniqueBatch\",\n \"claimEdgeCardinality\",\n \"claimEdgeCardinalityBatch\",\n \"purgeEdgeClaims\",\n \"readConstraintFenceViolations\",\n \"getActiveSchema\",\n \"getSchemaVersion\",\n \"commitSchemaVersion\",\n \"commitSchemaVersionIfKindsEmpty\",\n \"lockSchemaVersionForWrite\",\n \"commitSchemaVersionWithPreflight\",\n \"setActiveVersion\",\n \"schemaWriteTransaction\",\n \"upsertEmbedding\",\n \"upsertEmbeddingBatch\",\n \"deleteEmbedding\",\n \"deleteEmbeddingBatch\",\n \"vectorSearch\",\n \"createVectorIndex\",\n \"dropVectorIndex\",\n \"hybridSearch\",\n \"upsertFulltext\",\n \"deleteFulltext\",\n \"upsertFulltextBatch\",\n \"deleteFulltextBatch\",\n \"fulltextSearch\",\n \"ensureIndexMaterializationsTable\",\n \"ensureTrigramExtension\",\n \"ensureRevisionOriginsTable\",\n \"getIndexMaterialization\",\n \"getIndexMaterializations\",\n \"recordIndexMaterialization\",\n \"claimIndexMaterialization\",\n \"releaseIndexMaterializationClaim\",\n \"ensureContributionMaterializationsTable\",\n \"getContributionMaterialization\",\n \"recordContributionMaterialization\",\n \"assertRuntimeContributionsInitialized\",\n \"ensureKindRemovalsTable\",\n \"getPendingKindRemovals\",\n \"getAllKindRemovals\",\n \"recordKindRemoval\",\n \"ensureReconciliationMarkersTable\",\n \"ensureRuntimeContributions\",\n \"ensureVectorSlotContribution\",\n \"ensureVectorSlotContributions\",\n \"assertVectorSlotInitialized\",\n \"assertVectorSlotsInitialized\",\n \"deleteVectorSlotContribution\",\n \"verifyContributions\",\n \"repairContributions\",\n \"probeContributions\",\n \"rebuildContribution\",\n \"ensureFulltextTable\",\n \"ensureIdentityTables\",\n \"identityTableDdl\",\n \"getReconciliationMarker\",\n \"setReconciliationMarker\",\n \"clearGraph\",\n \"bootstrapTables\",\n \"refreshStatistics\",\n \"trustedImport\",\n \"execute\",\n \"executeStatement\",\n \"executeTemporaryStatement\",\n \"executeRaw\",\n \"compileSql\",\n \"executeDdl\",\n \"ensureExtension\",\n \"transaction\",\n \"close\",\n] as const satisfies readonly (keyof GraphBackend)[];\n\n/** @internal */\nexport type ProjectedGraphBackendKey =\n (typeof GRAPH_BACKEND_PROJECTION_KEYS)[number];\n\nconst MISSING_GRAPH_BACKEND_PROJECTION_KEYS: Record<\n Exclude<keyof GraphBackend, ProjectedGraphBackendKey>,\n never\n> = {};\nvoid MISSING_GRAPH_BACKEND_PROJECTION_KEYS;\n","/**\n * Ownership tracking for backends that serialize every statement onto ONE\n * database connection.\n *\n * Two facts are recorded here, and only these two:\n *\n * 1. **Which serialized resource a backend wrapper belongs to.** Distinct\n * `GraphBackend` objects (a second `createPostgresBackend(...)` over the same\n * client, a projection, an overlay, a managed-close wrapper) are not `===`,\n * yet their statements land on the same connection. Marking a backend with\n * the underlying client object — and inheriting that mark through every\n * decorator — makes \"these two wrappers cannot run a read transaction and a\n * write transaction at the same time\" answerable.\n *\n * Only backends whose driver is known to be single-connection are marked;\n * everything else is deliberately left unmarked, because a pooled connection\n * hands out an independent connection per checkout and refusing concurrent\n * work there would refuse legitimate work. The complete classification —\n * marked, deliberately unmarked, and known gaps — is the inventory at the\n * bottom of this doc.\n *\n * 2. **Which long-lived interchange stream currently holds that resource.** A\n * streaming export holds a read-only transaction on its connection for the\n * whole stream; a streaming import opens a write transaction per chunk on\n * that same connection for the whole stream. Any second long-lived stream on\n * the resource therefore either nests a transaction inside the first one\n * (`cannot start a transaction within a transaction`) or waits for a\n * connection that is never released — and that is true of ALL FOUR pairings,\n * not only the two cross-kind ones:\n *\n * | holder | second stream | outcome without the lease |\n * | --------------- | ---------------- | ---------------------------------- |\n * | export snapshot | import stream | import's chunk waits on the reader |\n * | import stream | export snapshot | export's read strands the import |\n * | import stream | import stream | nested BEGIN |\n * | export snapshot | export snapshot | nested BEGIN |\n *\n * So the lease is EXCLUSIVE, not refcounted: at most one stream of any kind\n * holds a given serialized resource, and at most one holds a transactional\n * SQLite backend object even when its resource is declared independent. The\n * second stream is refused with the holder's kind named (see\n * {@link acquireSerializedStreamLease}). Refcounting admitted the two\n * same-kind rows above, which then failed on the driver after chunks had\n * already committed.\n *\n * `\"import-stream\"` is the kind of EVERY long-lived import, not only the\n * chunk-streaming one: an in-memory `importGraph` and a `trustedImport`\n * session write through the same one connection over the same kind of window,\n * so they claim the same lease and are refused by the same holders.\n *\n * The check and the registration happen in ONE synchronous section inside\n * {@link acquireSerializedStreamLease} — there is no way for a caller to check\n * without claiming, so there is no window to get wrong. On a single-threaded\n * event loop a check with no `await` before its registration is atomic: two\n * long-lived streams cannot both observe a free resource, so no interleaving is\n * left where each waits for the other.\n *\n * Neither fact is a general concurrency model:\n *\n * - No attempt is made to detect shared connections we cannot see (two `pg`\n * Clients dialed at the same server, two better-sqlite3 handles on one file).\n * Those are genuinely independent connections and are correctly not refused.\n * - RESIDUAL GAP: the lease is keyed by serialized resource, so an UNMARKED\n * backend registers nothing and can hold nothing. A driver we cannot\n * positively identify as single-connection therefore keeps exactly today's\n * protection — the identity-based pre-flight in `importGraphStream`, which\n * only sees a stream that still names its own source backend — and an\n * export/import pair interleaved on such a connection can still wedge. Closing\n * that requires recognizing the driver, not more bookkeeping here.\n * - RESIDUAL GAP: a `transactions: false` export abstains entirely — it opens no\n * snapshot transaction, so `exportGraphStream` neither claims the lease nor\n * consults it: such an export is never refused and never refuses anyone.\n * A streaming import claims the lease whatever its backend reports,\n * because its writes still have to land somewhere an open snapshot is not.\n * The visible cost of that asymmetry is one conservative refusal: two\n * streaming imports through a MARKED but deliberately `transactionMode:\n * \"none\"` connection frame nothing and would in fact interleave harmlessly,\n * yet the second is refused. That is the deliberate trade — the alternative\n * (gating the import's claim on `capabilities.transactions` too) would stop a\n * real snapshot export from being refused mid-import on a mixed-profile\n * connection, which is the far likelier pairing.\n * - RESIDUAL GAP: the lease's population is INTERCHANGE STREAMS. Ordinary\n * long-lived frames on the same serialized connection — a `store.transaction`\n * held across awaits by application code, `schemaWriteTransaction` (the\n * provenance claim, the identity DDL fence), `store.evolve()` — neither hold\n * nor consult it, so one of those opening while an export snapshot is live\n * on the same connection blocks or wedges without a typed error, exactly as\n * any two of them always have. Representing every long-lived frame here is a\n * different, larger contract (a connection-wide frame lease); the streams\n * are covered because they are the pairing users actually compose.\n *\n * ## Inventory of serialized resources\n *\n * Every `GraphBackend` in this package is built by `createSqliteBackend` or\n * `createPostgresBackend` (the batteries-included factories — local\n * better-sqlite3, libSQL, PGlite — and every decorator go through one of them),\n * so those two factories are the only places a mark is applied, and this list is\n * the whole population. Predicates are named rather than line-cited so the\n * inventory stays greppable as the files move.\n *\n * MARKED — the factory resolves the resource before the backend object exists,\n * so no wrapper can observe it unmarked:\n *\n * - better-sqlite3 `Database` (`prepare` + `pragma`) — `createSqliteBackend` via\n * `getSerializedSqliteConnection`, which asks one named predicate per driver.\n * - bun:sqlite `Database` (`prepare` + `query` + `run`/`exec` + `serialize` +\n * a `filename` string) — same site, via `isBunSqliteClient`. One synchronous\n * connection, like better-sqlite3; `query` and `filename` are what separate\n * it structurally from better-sqlite3 (`pragma`, `name`), so the mark never\n * rests on a session's constructor name, which bundlers rename.\n * - sql.js `Database` (`prepare` + `exec` + `run` + `export` +\n * `getRowsModified`) — same site, via `isSqlJsClient`. One in-WASM handle\n * executed in-process; `export` and `getRowsModified` are sql.js's own API\n * and exist on no other SQLite client.\n * - Local `@libsql/client` (`protocol === \"file\"`: `file:` paths, `:memory:`,\n * an embedded replica's local file) — same site, via `isLocalLibsqlClient`.\n * - PGlite — `createPostgresBackend` via `getPgliteClient` (`query` +\n * `dumpDataDir`).\n * - Bare `pg` / `@neondatabase/serverless` `Client`, including a checked-out\n * `PoolClient` — same site, via `isBarePgClient`.\n * - `pg` / neon-serverless `Pool` capped at one connection — same site, via\n * `isSingleConnectionPgPool`, which asks `isSingleConnectionPgPoolCap` what a\n * cap of one looks like. pg-pool normalizes `max` (and the legacy `poolSize`)\n * into `options` without coercing either, so `{ max: 1 }`, `{ max: \"1\" }` and\n * `{ poolSize: \"1\" }` are one and the same one-connection pool, and all three\n * are marked.\n * - postgres-js capped at one connection — same site, via\n * `isSingleConnectionCallablePgClient`, which asks\n * `isSingleConnectionPostgresJsCap`. The client is CALLABLE, so it needed a\n * resolver arm of its own; `begin` reserves the sole connection, making an\n * export snapshot hold the connection every other wrapper writes through.\n * postgres-js resolves `max` from the options object, the URL query string and\n * `PGMAX` and coerces none of them, so `{ max: 1 }`, `?max=1` and `PGMAX=1`\n * are all marked. Requires postgres-js identity (`isPostgresJsClient`) as well\n * as the cap: a cap on a callable we cannot attribute to a known driver is not\n * evidence.\n * - Cloudflare Durable Object storage (`drizzle(ctx.storage)`) —\n * `createSqliteBackend` via `getDurableObjectStorageClient`, the same\n * full-shape evidence `transactionMode: \"do-sqlite\"` requires to run a\n * transaction. The storage transaction frame is AMBIENT on the storage object\n * (no tx handle exists on DO), so a second wrapper's writes land inside the\n * first wrapper's export snapshot; nothing else abstains, since the DO backend\n * reports `capabilities.transactions: true`.\n *\n * DELIBERATELY UNMARKED, by class — marking these would refuse work that\n * succeeds:\n *\n * - Pooled connections: a default-size `pg` / neon-serverless / `@vercel/postgres`\n * pool, postgres-js or Bun `SQL` at default size. Each checkout is an\n * independent connection.\n * - Session-less HTTP drivers: `neon-http`, Cloudflare D1, RDS Data API. Nothing\n * is held between statements, and the two that report\n * `capabilities.transactions: false` are additionally short-circuited by\n * {@link snapshotExportContention} before marking is consulted.\n * - Remote `@libsql/client` (`http` / `ws`): an independent stream per\n * transaction.\n * - Separate handles on one database (two `pg` Clients at one server, two\n * better-sqlite3 handles on one file): genuinely concurrent connections.\n * - Transaction-scoped backends (`transaction()`, `adoptTransaction`): the\n * caller's transaction already owns the connection and opens no second frame,\n * and the guards run on the root backend a Store holds. Decorators over a root\n * backend DO carry the verdict, via\n * {@link carryBackendResourceAudit}.\n *\n * KNOWN GAPS — serialized in fact, unmarked, so they keep only the\n * identity-based pre-flight in `importGraphStream` (which a `history: true`\n * store's overlay already defeats). Each is a coverage extension needing\n * positive evidence of the client shape, never a silent no-op. Every one of\n * them has the SAME sanctioned workaround until its shape is recognized: the\n * caller declares the connection with\n * `{ serializedResource: { mode: \"shared\", resource: client } }` (see\n * {@link SerializedResourceDeclaration}), which is a claim the caller can make\n * and this package cannot.\n *\n * - React Native / Expo SQLite drivers — `expo-sqlite` and `op-sqlite`. One\n * connection each, and both are genuinely serialized, but neither exposes a\n * plain `prepare` (`prepareAsync` / `prepareSync`, `prepareStatement`), so\n * none of the predicates above can see them and neither driver is installable\n * here to derive the shape from rather than guess it. Remaining #434 scope:\n * each needs its own positive shape, taken from the driver's own typings.\n * - `node:sqlite` `DatabaseSync`: UNREACHABLE through Drizzle today —\n * drizzle-orm 0.45.2 ships `bun-sqlite`, `sql-js`, `durable-sqlite`,\n * `expo-sqlite`, `op-sqlite`, `sqlite-proxy` and `better-sqlite3`, and no\n * `node-sqlite` entrypoint, so no `createSqliteBackend` call can be handed\n * one. Re-check when the Drizzle floor moves; nothing to mark until then.\n * - postgres-js given a NON-NUMERIC string cap other than one, e.g.\n * `postgres(url + \"?max=5\")`: `[...Array(options.max)]` (postgres@3.4.9\n * `src/index.js:65`) yields length 1 for any such string, so that client\n * really does open exactly one connection today and really can wedge a stream\n * pair. Unmarked on purpose — marking it would be marking on an upstream bug,\n * and the day postgres-js coerces `max` the same configuration becomes a\n * five-connection pool whose concurrent work we would then refuse. A caller on\n * that shape materializes the export or imports into an independent backend,\n * exactly as before this guard existed.\n * - Bun `SQL` (Postgres) built with `{ max: 1 }`: genuinely serialized, but\n * nothing in this package positively identifies that driver — there is no\n * Postgres equivalent of the SQLite driver shapes above — so `options.max`\n * there cannot be attributed to a driver whose dispatch we know. Marking it\n * needs a Bun-`SQL` discriminator first. Remaining #434 scope.\n * - Drivers we cannot identify at all (`sqlite-proxy`, `pg-proxy`, a bespoke\n * adapter): whether the far side serializes is unknowable from here, so they\n * fall under the residual gap above.\n */\nimport { ConfigurationError } from \"../errors\";\nimport { type GraphBackend } from \"./types\";\n\n/**\n * What we know about the connection a backend's statements land on.\n *\n * `independent` is a POSITIVE verdict — a factory looked and found statements\n * that can run on independent connections. It is not the same runtime state as\n * a backend nobody audited, which carries no record at all.\n */\nexport type BackendResourceAudit =\n | Readonly<{ kind: \"serialized\"; resource: object }>\n | Readonly<{\n kind: \"independent\";\n /** Stable key for the SQLite identity arm of an explicit declaration. */\n identityLeaseResource?: object;\n }>;\n\n/**\n * Declare the connection this backend serializes on, when TypeGraph cannot\n * detect it (Bun `SQL`, `expo-sqlite`, `op-sqlite`, `sqlite-proxy`, `pg-proxy`,\n * a postgres-js pool capped through a string the driver does not coerce — the\n * KNOWN GAPS in this module's inventory). Two wrappers that pass the same\n * object are treated as one serialized resource, exactly as two wrappers over a\n * detected client are.\n *\n * - `\"detect\"` (the default, and the same behavior as omitting the option):\n * whatever the factory's driver predicates find, and nothing else.\n * - `\"shared\"`: the given object IS the serialized resource. Refused with a\n * {@link ConfigurationError} when the factory detected a DIFFERENT resource —\n * silently overriding would let two wrappers over one handle be given two\n * different sentinels and quietly de-serialize a pair that really does share.\n * - `\"independent\"`: statements can run on independent connections. The\n * documented escape hatch for a mis-detection, so a user surprised by a\n * refusal is never stuck.\n *\n * SCOPE — read this before using `\"independent\"`: this option controls the\n * SHARED-RESOURCE arm of {@link snapshotExportContention} only. It cannot lift\n * the object-identity arm, under which ONE SQLite backend object exporting into\n * ITSELF is refused with `same-sqlite-backend`. That arm is a driver fact (one\n * handle, one open snapshot transaction), not a claim about connection\n * topology, so no declaration can make it false.\n *\n * That surviving arm is SQLITE-ONLY, deliberately: it is gated on\n * `dialect === \"sqlite\"`, so on Postgres a backend declared `\"independent\"`\n * exporting into ITSELF is not refused either — a Postgres client that hands\n * out independent connections is exactly what the declaration claims, and the\n * snapshot and the writes it contends with land on different ones.\n */\nexport type SerializedResourceDeclaration =\n | Readonly<{ mode: \"detect\" }>\n | Readonly<{ mode: \"shared\"; resource: object }>\n | Readonly<{ mode: \"independent\" }>;\n\nconst BACKEND_RESOURCE_AUDITS = new WeakMap<object, BackendResourceAudit>();\n\n/**\n * The kinds of long-lived interchange stream that hold a serialized connection\n * across many statements — the population the lease is exclusive over.\n */\nexport type SerializedStreamKind = \"export-snapshot\" | \"import-stream\";\n\n/**\n * The outcome of claiming a serialized resource for a long-lived stream: the\n * (idempotent) release and the resource the claim was registered under when it\n * succeeded, or the kind of stream already holding it when it did not.\n *\n * `resource` is the decision itself rather than a flag a caller re-derives\n * from the backend: `undefined` means nothing was registered, because the\n * backend runs on no known serialized resource.\n */\nexport type SerializedStreamLease =\n | Readonly<{\n acquired: true;\n resource: object | undefined;\n release: () => void;\n }>\n | Readonly<{ acquired: false; heldBy: SerializedStreamKind }>;\n\n/**\n * The one long-lived stream holding each serialized resource. An entry exists\n * only while that stream is in flight; its release deletes the key, so a\n * finished stream retains nothing and refuses nobody.\n */\nconst ACTIVE_SERIALIZED_STREAMS = new Map<object, SerializedStreamKind>();\n\n/** Whether two audits are the same verdict about the same connection. */\nfunction auditsAgree(\n left: BackendResourceAudit,\n right: BackendResourceAudit,\n): boolean {\n if (left.kind === \"serialized\") {\n return right.kind === \"serialized\" && left.resource === right.resource;\n }\n return (\n right.kind === \"independent\" &&\n left.identityLeaseResource === right.identityLeaseResource\n );\n}\n\n/** Names a verdict for the write-once refusal below. */\nfunction formatAudit(audit: BackendResourceAudit): string {\n return audit.kind === \"serialized\" ? \"serialized\" : \"independent\";\n}\n\n/**\n * The two objects a refused `\"shared\"` declaration could not reconcile: the one\n * the caller named and the one this package detected.\n */\nexport type SerializedResourceConflict = Readonly<{\n declared: object;\n detected: object;\n}>;\n\n/**\n * The handles behind each refusal, held OFF the error object on purpose.\n *\n * `TypeGraphError.toLogString()` `JSON.stringify`s `details`, and the\n * documented handler pattern is `console.error(error.toLogString())` — so a\n * driver handle in `details` writes whatever that driver stores into the\n * caller's logs, and a `pg.Pool` stores its `connectionString`, password\n * included. The refusal therefore carries only a DESCRIPTION of each side\n * (`declaredKind` / `detectedKind`), while the identities live here, reachable\n * by asking for them and by nothing that walks an error's own properties.\n */\nconst SERIALIZED_RESOURCE_CONFLICTS = new WeakMap<\n Error,\n SerializedResourceConflict\n>();\n\n/**\n * The two objects a serialized-resource refusal could not reconcile, or\n * `undefined` for any other error.\n *\n * @internal\n */\nexport function serializedResourceConflict(\n error: unknown,\n): SerializedResourceConflict | undefined {\n return error instanceof ConfigurationError ?\n SERIALIZED_RESOURCE_CONFLICTS.get(error)\n : undefined;\n}\n\n/**\n * How a refusal names one side of a conflict without publishing the handle:\n * the constructor name (`\"Database\"`, `\"BoundPool\"`, `\"Object\"`), which says\n * what KIND of thing each side is and carries no connection string.\n */\nfunction describeSerializedResource(resource: object): string {\n const constructorName = (\n resource as Readonly<{ constructor?: Readonly<{ name?: unknown }> }>\n ).constructor?.name;\n return typeof constructorName === \"string\" && constructorName !== \"\" ?\n constructorName\n : \"Object\";\n}\n\n/**\n * The verdict a backend factory records, from what its driver predicates\n * detected and what the caller declared.\n *\n * The single owner of \"what a {@link SerializedResourceDeclaration} means\":\n * both drizzle factories call it, so the two cannot drift about whether a\n * declaration wins, loses, or is refused.\n *\n * Applied or refused, never ignored:\n *\n * - `\"shared\"` naming the resource detection already found, or naming one on a\n * backend detection could not classify → recorded as that resource.\n * - `\"shared\"` naming a DIFFERENT resource than detection found → refused, so\n * two wrappers over one handle cannot be handed two different sentinels and\n * silently de-serialized.\n * - `\"independent\"` → recorded, whatever detection found. This is the escape\n * hatch, not a conflict: detection is a duck-type over driver internals and\n * the caller knows their topology.\n * - `\"detect\"` or absent → exactly what detection found.\n *\n * Called INSIDE the factory body before the backend object exists, so a\n * refusal happens before any object is published (CTA-3) and a caller can never\n * hold a backend whose declaration was rejected.\n *\n * @throws {ConfigurationError} `details.reason: \"serialized-resource-conflict\"`\n * when a `\"shared\"` declaration names a resource detection disagrees with. Its\n * `details` describe the two sides (`declaredKind` / `detectedKind`) rather\n * than carrying them, because `details` is logged verbatim; the handles\n * themselves come from {@link serializedResourceConflict}.\n * @internal\n */\nexport function resolveDeclaredBackendResource(\n detected: object | undefined,\n declaration: SerializedResourceDeclaration | undefined,\n): BackendResourceAudit {\n switch (declaration?.mode) {\n case \"shared\": {\n if (detected !== undefined && detected !== declaration.resource) {\n const refusal = new ConfigurationError(\n `serializedResource declared { mode: \"shared\" } naming an object ` +\n `that is not the connection this backend was detected to run on. ` +\n `Two wrappers over one connection must name the SAME object, or ` +\n `the guards that refuse a concurrent export/import pair on it stop ` +\n `seeing them as one resource.`,\n {\n reason: \"serialized-resource-conflict\",\n declaredKind: describeSerializedResource(declaration.resource),\n detectedKind: describeSerializedResource(detected),\n },\n {\n suggestion:\n `Declare the client TypeGraph already detected (or drop the ` +\n `declaration and let detection stand). Use ` +\n `{ mode: \"independent\" } if the detection is wrong and this ` +\n `backend really does run on its own connection.`,\n },\n );\n SERIALIZED_RESOURCE_CONFLICTS.set(refusal, {\n declared: declaration.resource,\n detected,\n });\n throw refusal;\n }\n return { kind: \"serialized\", resource: declaration.resource };\n }\n case \"independent\": {\n return { kind: \"independent\", identityLeaseResource: {} };\n }\n case \"detect\":\n case undefined: {\n return detected === undefined ?\n { kind: \"independent\" }\n : { kind: \"serialized\", resource: detected };\n }\n }\n}\n\n/**\n * Records what a backend factory found about the connection its backend runs\n * on.\n *\n * INVARIANT: recorded ONCE per backend, by the factory that built it, BEFORE\n * the backend object escapes the factory body. Derived backends (deriveBackend,\n * projectBackend, projectBackendWithout, projectGraphBackend,\n * wrapWithManagedClose) carry the verdict at construction time, so a wrapper\n * built before the audit lands is silently unaudited and evades the\n * import/clone guards.\n *\n * A second call with an equal verdict is a no-op. A second call with a\n * DIFFERENT verdict throws: the stream lease reads this value and closes over\n * the resource it claimed, so a verdict that changes under a live lease\n * de-serializes a pair that really does share a connection.\n *\n * The throw is an INTERNAL invariant assertion — no library path re-audits and\n * a user cannot reach this function — so it is a plain `TypeError` naming both\n * verdicts, matching the repo's internal-assertion spelling (`requireDefined`,\n * src/utils/presence.ts). Deliberately not a `ConfigurationError`: that type is\n * user-category and would route a library bug into user-facing handling.\n *\n * @internal\n */\nexport function auditBackendResource(\n backend: GraphBackend,\n audit: BackendResourceAudit,\n): void {\n const recorded = BACKEND_RESOURCE_AUDITS.get(backend);\n if (recorded !== undefined) {\n if (auditsAgree(recorded, audit)) return;\n throw new TypeError(\n `A backend's serialized-resource audit is written once: this backend ` +\n `was audited \"${formatAudit(recorded)}\" and a conflicting audit ` +\n `\"${formatAudit(audit)}\"${\n recorded.kind === \"serialized\" && audit.kind === \"serialized\" ?\n \" naming a different connection\"\n : \"\"\n } was attempted. The stream lease closes over the resource it claimed, ` +\n `so a verdict that changes under a live lease de-serializes a pair ` +\n `that really does share a connection.`,\n );\n }\n BACKEND_RESOURCE_AUDITS.set(backend, audit);\n}\n\n/**\n * Copies a base backend's verdict onto a backend derived from it, or nothing\n * when the base carries none.\n *\n * @internal The construction seam's carry. `src/backend/derive-backend.ts` is\n * the only module allowed to import it.\n */\nexport function carryBackendResourceAudit(derived: object, base: object): void {\n const audit = BACKEND_RESOURCE_AUDITS.get(base);\n if (audit !== undefined) BACKEND_RESOURCE_AUDITS.set(derived, audit);\n}\n\n/**\n * The verdict recorded for `backend`, or `undefined` when nobody audited it.\n *\n * A pure map read: the value is written once at construction, so two reads can\n * never disagree and a lease cannot have its premise changed under it.\n *\n * @internal\n */\nexport function resolveBackendAudit(\n backend: object,\n): BackendResourceAudit | undefined {\n return BACKEND_RESOURCE_AUDITS.get(backend);\n}\n\n/**\n * How a backend's connection was classified, as a single value.\n *\n * `\"unaudited\"` is NOT a verdict about the connection: it says nobody looked.\n * Two populations are legitimately unaudited and always will be —\n * transaction-scoped backends (`transaction()`, `adoptTransaction`), which are\n * built from an operations fragment rather than derived from a root backend,\n * and `GraphBackend`s users implement themselves. So `\"unaudited\"` on an\n * arbitrary object proves nothing; on a backend one of this package's factories\n * built, or on one derived from such a backend through `derive-backend.ts`, it\n * proves the construction bypassed the seam.\n */\nexport type BackendResourceProvenance =\n \"serialized\" | \"independent\" | \"unaudited\";\n\n/**\n * The classification of `backend`'s connection — the decision itself rather\n * than a flag every caller re-derives from {@link resolveBackendAudit}.\n *\n * @internal\n */\nexport function backendResourceProvenance(\n backend: object,\n): BackendResourceProvenance {\n return resolveBackendAudit(backend)?.kind ?? \"unaudited\";\n}\n\n/** Whether two backend wrappers cannot make snapshot reads and writes concurrently. */\nexport function sharesSerializedTransactionResource(\n left: GraphBackend,\n right: GraphBackend,\n): boolean {\n const leftAudit = resolveBackendAudit(left);\n if (leftAudit?.kind !== \"serialized\") return false;\n const rightAudit = resolveBackendAudit(right);\n // Resource identity, not audit-record identity: two audits naming the same\n // client object are the same connection however they were recorded.\n return (\n rightAudit?.kind === \"serialized\" &&\n leftAudit.resource === rightAudit.resource\n );\n}\n\n/** How a snapshot export on one backend contends with a write on another. */\nexport type SnapshotExportContention =\n \"same-sqlite-backend\" | \"shared-resource\";\n\n/**\n * Whether a snapshot export on `source` would hold the one connection `target`\n * writes through, and via which detector. `undefined` means no contention.\n *\n * The single owner of \"a snapshot export blocks this write\": the streaming\n * import guard, and the working-copy cloner that exists to pre-empt it, both\n * ask here rather than re-deriving the arms.\n *\n * - A `transactions: false` source (SQLite `transactionMode: \"none\"`, HTTP-only\n * Postgres drivers) exports statement by statement with nothing held open, so\n * sharing its connection is merely interleaving and is never contention.\n * - Object identity on a SQLite backend is checked FIRST, so a marked\n * better-sqlite3 backend exporting into itself reports the more specific\n * detector even though the shared-resource arm would also match.\n */\nexport function snapshotExportContention(\n source: GraphBackend,\n target: GraphBackend,\n): SnapshotExportContention | undefined {\n if (!source.capabilities.transactions) return undefined;\n if (source === target && source.dialect === \"sqlite\") {\n return \"same-sqlite-backend\";\n }\n if (sharesSerializedTransactionResource(source, target)) {\n return \"shared-resource\";\n }\n return undefined;\n}\n\n/**\n * Claims the serialized resource `backend` runs on for a long-lived stream of\n * `kind`, or reports which kind of stream already holds it.\n *\n * EXCLUSIVE: one stream per serialized resource, whatever its kind. Two exports\n * nest their snapshot transactions on the one connection exactly as an export\n * and an import do, so \"is a stream already running here\" — not \"is a stream of\n * the OTHER kind already running here\" — is the question the holder registry\n * answers.\n *\n * ONE SYNCHRONOUS SECTION, by construction: the lookup and the registration are\n * in this function's body with no `await` between them, and there is no separate\n * \"is it free?\" query a caller could read and then act on later. On a\n * single-threaded event loop that makes \"no other stream held this connection\n * when this one claimed it\" true for the whole stream, in whichever order two\n * streams start — the second one always finds the first's registration.\n *\n * A known serialized resource is the normal lease key. A transactional SQLite\n * backend audited `independent` instead uses its own identity: the declaration\n * can separate distinct wrappers, but cannot make two streams on ONE backend\n * object use different handles. An unaudited backend, and an independent\n * Postgres backend, registers nothing (see the residual gap in the module doc).\n *\n * The acquired arm reports the resource it registered under, so a caller reads\n * the decision instead of re-deriving it from the backend; `undefined` is the\n * no-op arm. The returned release is idempotent and deletes only its own\n * registration, so an already-released stream can never evict the next\n * stream's lease.\n */\nfunction streamLeaseResource(backend: GraphBackend): object | undefined {\n const audit = resolveBackendAudit(backend);\n if (audit?.kind === \"serialized\") return audit.resource;\n if (\n audit?.kind === \"independent\" &&\n audit.identityLeaseResource !== undefined &&\n backend.dialect === \"sqlite\" &&\n backend.capabilities.transactions\n ) {\n return audit.identityLeaseResource;\n }\n return undefined;\n}\n\nexport function acquireSerializedStreamLease(\n backend: GraphBackend,\n kind: SerializedStreamKind,\n): SerializedStreamLease {\n const resource = streamLeaseResource(backend);\n if (resource === undefined) {\n return {\n acquired: true,\n resource: undefined,\n release: () => {\n // Nothing was registered: this backend has no known serialized\n // resource, so there is nothing to give back.\n },\n };\n }\n const holder = ACTIVE_SERIALIZED_STREAMS.get(resource);\n if (holder !== undefined) return { acquired: false, heldBy: holder };\n ACTIVE_SERIALIZED_STREAMS.set(resource, kind);\n let released = false;\n return {\n acquired: true,\n resource,\n release: () => {\n if (released) return;\n released = true;\n ACTIVE_SERIALIZED_STREAMS.delete(resource);\n },\n };\n}\n","/**\n * The one construction seam for derived backends.\n *\n * Every backend the library builds FROM another backend — an overlay, an\n * allowlist projection, a narrowing-by-omission, a managed-close wrapper — is\n * built here, and every constructor in this module carries the source's\n * serialized-resource audit onto the object it returns. Raw `{ ...backend }`,\n * `Object.assign` and rest-omission construction build a NEW object the audit\n * does not follow, which is the defect this module exists to make unreachable:\n * a derived backend that lost its mark reads as unowned, and the import/clone\n * guards then let a read-and-write-through-one-connection stream proceed into a\n * deadlock.\n *\n * This is the only module that imports {@link carryBackendResourceAudit}.\n *\n * Naming convention this module's ratchet depends on: an identifier ending in\n * `Backend` denotes a whole backend object; a members fragment is named\n * `*Members`.\n */\nimport {\n GRAPH_BACKEND_PROJECTION_KEYS,\n type ProjectedGraphBackendKey,\n} from \"./graph-backend-keys\";\nimport { carryBackendResourceAudit } from \"./transaction-resource\";\nimport { type AdapterBackend, type GraphBackend } from \"./types\";\n\n/**\n * Rejects overlay members that are not members of the decorated backend, so a\n * misspelled override cannot silently add a property nothing forwards to.\n *\n * @internal\n */\nexport type ExactBackendOverlay<T extends object, O extends Partial<T>> = O &\n Readonly<Record<Exclude<keyof O, keyof T>, never>>;\n\n/**\n * Decorates a backend with overlay members without copying it.\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, and so the derived object carries the\n * source's serialized-resource audit. GraphBackend functions are receiver-free\n * by contract, so delegated methods are returned unchanged.\n *\n * `T` is bounded by `object`, not by the backend union — the same bound\n * {@link projectBackend} carries — so a PROJECTION is decorable too: the write\n * pipeline's read-only row-work target is what a batch's pending-aware\n * validation overlays. `ExactBackendOverlay` still rejects any key `T` does not\n * declare, so the looser bound cannot smuggle a member onto a surface that\n * withholds it.\n */\nexport function deriveBackend<\n T extends object,\n const O extends Partial<T> = Partial<T>,\n>(base: T, overrides: ExactBackendOverlay<T, O>): T {\n function hasOverlayProperty(property: PropertyKey): boolean {\n return Object.hasOwn(overrides, property);\n }\n\n const decoratedBackend = new Proxy(base, {\n get(targetObject, property) {\n if (hasOverlayProperty(property)) {\n return Reflect.get(overrides, property, overrides);\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(overrides),\n ]),\n ];\n },\n\n getOwnPropertyDescriptor(targetObject, property) {\n if (hasOverlayProperty(property)) {\n const descriptor = Reflect.getOwnPropertyDescriptor(\n overrides,\n property,\n );\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(overrides, property, value, overrides);\n }\n return Reflect.set(targetObject, property, value, targetObject);\n },\n\n defineProperty(targetObject, property, attributes) {\n if (hasOverlayProperty(property)) {\n return Reflect.defineProperty(overrides, property, attributes);\n }\n return Reflect.defineProperty(targetObject, property, attributes);\n },\n\n deleteProperty(targetObject, property) {\n if (hasOverlayProperty(property)) {\n return Reflect.deleteProperty(overrides, property);\n }\n return Reflect.deleteProperty(targetObject, property);\n },\n });\n carryBackendResourceAudit(decoratedBackend, base);\n return decoratedBackend;\n}\n\n/**\n * Copies exactly `keys` off `base` into a fresh object.\n *\n * Generic over the SOURCE's own type, so a structurally wider input keeps the\n * declared types of the members it does provide. Keys the source does not\n * carry stay absent rather than becoming `undefined` members.\n *\n * @internal\n */\nexport function projectBackend<\n TBackend extends object,\n const TKey extends keyof TBackend,\n>(base: TBackend, keys: readonly TKey[]): Readonly<Pick<TBackend, TKey>> {\n const entries = keys.flatMap((key) => {\n if (!Reflect.has(base, key)) return [];\n return [[key, Reflect.get(base, key)] as const];\n });\n\n // Keys are constrained to TBackend and values are copied from that same\n // object without reshaping. Optional members remain absent.\n const projection = Object.fromEntries(entries) as Readonly<\n Pick<TBackend, TKey>\n >;\n // A projection forwards every statement to the SAME connection as its source,\n // so it owns the same serialized transaction resource. Carrying here rather\n // than at each call site keeps the verdict attached through the projections\n // built deep inside the store (recorded-time capture, hooked query backends),\n // where an import guard would otherwise see an unaudited backend and let a\n // read-and-write-through-one-connection stream proceed into a deadlock.\n carryBackendResourceAudit(projection, base);\n return projection;\n}\n\n/**\n * Every key a derived backend must retain: the source's own keys — enumerable\n * or not, string or symbol — plus every key on its prototype chain up to, but\n * not including, `Object.prototype`.\n *\n * A class-implemented GraphBackend is a supported shape and keeps its methods\n * on the prototype, so `Reflect.ownKeys` alone would silently drop them.\n */\nfunction backendKeys<TBackend extends object>(\n base: TBackend,\n): readonly (keyof TBackend)[] {\n const keys = new Set<PropertyKey>();\n let current: object | undefined = base;\n while (current !== undefined && current !== Object.prototype) {\n for (const key of Reflect.ownKeys(current)) keys.add(key);\n current = Reflect.getPrototypeOf(current) ?? undefined;\n }\n // Every key was enumerated off `base` itself, so each one is a key of\n // TBackend at runtime; the compiler cannot narrow `PropertyKey` against an\n // unresolved type parameter.\n return [...keys] as unknown as readonly (keyof TBackend)[];\n}\n\n/**\n * Narrows a backend by omission — the seam replacement for\n * `const { omitted, ...rest } = backend`.\n *\n * Omits from the SOURCE's keys, so a structurally wider input (an\n * `AdapterBackend` with `transactionWithNative` / `adoptTransaction`) keeps\n * every member it had except the named ones.\n *\n * KEY RULE, deliberately NOT the rest destructure's rule: the retained set is\n * every own key (enumerable or not, string or symbol) PLUS every key on the\n * prototype chain up to — not including — `Object.prototype`, minus `omitted`.\n * A rest destructure copies only own ENUMERABLE keys and drops prototype\n * members; the declared `Omit<TBackend, TKey>` promises they survive, and\n * enumerating the prototype chain is what makes that promise true. Retaining\n * non-enumerable own keys is the other deliberate difference: a member hidden\n * behind a non-enumerable descriptor is still a member the wrapper forwards.\n *\n * @internal\n */\nexport function projectBackendWithout<\n TBackend extends object,\n const TKey extends keyof TBackend,\n>(base: TBackend, omitted: readonly TKey[]): Omit<TBackend, TKey> {\n const excluded = new Set<PropertyKey>(omitted);\n const retained = backendKeys(base).filter((key) => !excluded.has(key));\n return projectBackend(base, retained);\n}\n\n/**\n * Creates a runtime GraphBackend projection.\n *\n * Structurally wider inputs (for example AdapterBackend) lose every property\n * not named by the portable GraphBackend allowlist. Optional port members stay\n * absent when the source does not provide them.\n *\n * @internal\n */\nexport function projectGraphBackend(base: GraphBackend): GraphBackend {\n return projectBackend<GraphBackend, ProjectedGraphBackendKey>(\n base,\n GRAPH_BACKEND_PROJECTION_KEYS,\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 deriveBackend(backend, closeOverlay);\n}\n","/**\n * Cross-dialect detection of \"this relation does not exist yet\" errors.\n *\n * Shared so the schema bootstrap (`loadActiveSchemaWithBootstrap`) and\n * the durable contribution-materialization gate (#135) agree on what a\n * missing-table failure looks like, and — critically — so neither one\n * swallows a genuine system fault (connection/permission/driver error)\n * as a benign \"not bootstrapped yet\".\n *\n * Detection walks the error's `cause` chain because Drizzle (>= the\n * `DrizzleQueryError` era, drizzle-orm ≥ 0.36) wraps every failure from a\n * query-builder call (`db.select()`, `db.insert()`, …): the wrapper's\n * `.message` becomes the failed query text and the real driver error —\n * which carries both the missing-relation text and the SQLSTATE — is\n * preserved on `.cause`. node-postgres / postgres-js nest the pg error\n * one link deep; better-sqlite3 throws it unwrapped; raw `client.query()`\n * fast paths surface it directly. Walking the chain makes the check\n * wrapper- and driver-agnostic instead of only matching the outermost\n * `.message`, which on Postgres is just the SQL string.\n */\n\nimport { ConfigurationError } from \"../errors\";\n\nconst SQLITE_MISSING_TABLE_PATTERN = \"no such table\";\nconst SQLITE_GENERIC_ERROR_CODE = \"SQLITE_ERROR\";\nconst SQLITE_NOT_AUTHORIZED_CODE = \"SQLITE_AUTH\";\n\n/**\n * SQLite's EXTENDED result code for \"this read transaction cannot become a\n * write transaction\": the connection began a DEFERRED transaction, took a read\n * snapshot, and another connection has committed since. SQLite refuses the\n * upgrade because honoring it would let the writer act on a stale view; the\n * only recovery is `ROLLBACK` and a fresh transaction (SQLite's own rule — the\n * failure is not retryable in place).\n *\n * It is the one code that names the DEFERRED frame itself. A transaction opened\n * `BEGIN IMMEDIATE` holds the writer slot from the start and can never produce\n * it, and plain `SQLITE_BUSY` says something else entirely (\"another writer\n * holds the slot right now\"), so this code alone can be attributed to how the\n * transaction was begun. The numeric spelling is accepted for libSQL, which\n * surfaces only `rawCode`/`extendedCode` over a remote connection.\n */\nconst SQLITE_STALE_SNAPSHOT_CODE = \"SQLITE_BUSY_SNAPSHOT\";\nconst SQLITE_STALE_SNAPSHOT_EXTENDED_CODE = 517;\nconst DRIZZLE_QUERY_ERROR_PREFIX = \"Failed query:\";\nconst POSTGRES_UNDEFINED_RELATION_PATTERN =\n /\\b(?:relation|table)\\s+\"[^\"]+\"\\s+does not exist\\b/i;\n\n/**\n * SQLSTATE for PostgreSQL `undefined_table`. Preferred over the\n * human-readable message: it is locale-independent (the \"... does not\n * exist\" text is translated under a non-English `lc_messages`) and is\n * preserved on the underlying driver error even when Drizzle overwrites\n * `.message` with the query text.\n */\nconst POSTGRES_UNDEFINED_TABLE_CODE = \"42P01\";\nconst POSTGRES_UNIQUE_VIOLATION_CODE = \"23505\";\n\n/**\n * SQLSTATEs a racing IDEMPOTENT DDL statement loses with — the ones that mean\n * \"another session is committing the very thing this statement asks for\", not\n * \"this statement is wrong\".\n *\n * PostgreSQL's `IF NOT EXISTS` is not a concurrency primitive: the existence\n * check cannot see another session's uncommitted catalog rows, so the loser\n * waits for the winner and is then handed the conflict the winner's commit\n * produced — `unique_violation` (23505) from `pg_type`/`pg_class` for a racing\n * CREATE, `duplicate_column` (42701) for a racing `ALTER TABLE ... ADD COLUMN\n * IF NOT EXISTS`. Retrying once after that wait observes the committed object\n * and succeeds; a failure the retry cannot clear stays loud.\n */\nconst POSTGRES_CONCURRENT_DDL_RACE_SQL_STATES = [\n POSTGRES_UNIQUE_VIOLATION_CODE,\n \"42701\",\n] as const;\n\n/**\n * The one concurrent-DDL race PostgreSQL reports with no SQLSTATE of its own:\n * `heap_update` losing a catalog row to a concurrent updater raises\n * `elog(ERROR, \"tuple concurrently updated\")`, which carries the catch-all\n * `internal_error` (XX000).\n *\n * XX000 alone is far too broad to retry on — it covers genuine server faults —\n * so this shape is identified by SQLSTATE AND message together. Matching the\n * message is sound here specifically because `elog` emits it through\n * `errmsg_internal`, which is NOT run through gettext: unlike an `ereport`\n * message, it reads identically under every `lc_messages`.\n */\nconst POSTGRES_INTERNAL_ERROR_CODE = \"XX000\";\nconst POSTGRES_CONCURRENT_TUPLE_UPDATE_MESSAGE = \"tuple concurrently updated\";\n\n/**\n * PostgreSQL failures that mean a temporary table cannot be created here:\n * `read_only_sql_transaction` (a replica or otherwise read-only execution\n * context) and `insufficient_privilege` (a role without the database `TEMP`\n * privilege).\n */\nconst POSTGRES_TEMPORARY_TABLE_UNAVAILABLE_SQL_STATES = [\n \"25006\",\n \"42501\",\n] as const;\n\n/**\n * PostgreSQL failures that mean the read-write transaction hosting temporary\n * tables cannot even start. A standby rejects the read-write access mode in\n * the `BEGIN` itself with `feature_not_supported` (\"cannot set transaction\n * read-write mode during recovery\"), so the failure never reaches a\n * `CREATE TEMP TABLE`; a session pinned read-only by a proxy or by\n * `default_transaction_read_only` reports `read_only_sql_transaction`.\n */\nconst POSTGRES_READ_WRITE_REFUSED_SQL_STATES = [\"0A000\", \"25006\"] as const;\n\nexport type PostgresTemporaryTableUnavailableSqlState =\n (typeof POSTGRES_TEMPORARY_TABLE_UNAVAILABLE_SQL_STATES)[number];\n\nexport type PostgresReadWriteRefusedSqlState =\n (typeof POSTGRES_READ_WRITE_REFUSED_SQL_STATES)[number];\n\n/**\n * Yields an error and each error reachable by following `.cause`,\n * outermost first. `seen` guards the pathological cyclic-cause case so a\n * self-referential chain can't spin forever.\n *\n * The walk intentionally follows `.cause` through *non-`Error`* links, not just\n * `Error` instances: postgres-js surfaces its driver error as a plain object\n * (message + SQLSTATE `code`) on a Drizzle wrapper's `.cause`, so stopping at\n * the first non-`Error` link would miss it (see the postgres-js test). A plain\n * object is classified by its locale-independent SQLSTATE alone\n * ({@link isPostgresUndefinedTable}); the looser SQLite message substring is\n * consulted only for `Error` instances and raw strings\n * ({@link missingTableMessage}), so an unrelated object in a cause chain that\n * merely mentions one of those phrases is not mistaken for a missing table.\n */\nexport function* errorChain(error: unknown): Generator<unknown, void, void> {\n const seen = new Set<unknown>();\n let current: unknown = error;\n while (current !== undefined && current !== null && !seen.has(current)) {\n seen.add(current);\n yield current;\n current =\n canReadProperty(current) ? Reflect.get(current, \"cause\") : undefined;\n }\n}\n\nfunction canReadProperty(value: unknown): value is object {\n return (\n (typeof value === \"object\" && value !== null) || typeof value === \"function\"\n );\n}\n\n/**\n * Whether a single chain link is a PostgreSQL `undefined_table` failure,\n * identified by its SQLSTATE rather than a message substring.\n */\nfunction isPostgresUndefinedTable(link: unknown): boolean {\n return (\n canReadProperty(link) &&\n Reflect.get(link, \"code\") === POSTGRES_UNDEFINED_TABLE_CODE\n );\n}\n\nfunction messageProperty(link: unknown): string | undefined {\n if (typeof link === \"string\") return link;\n if (link instanceof Error) return link.message;\n const message =\n canReadProperty(link) ?\n (Reflect.get(link, \"message\") as unknown)\n : undefined;\n return typeof message === \"string\" ? message : undefined;\n}\n\nfunction errorMessage(link: unknown): string {\n return messageProperty(link) ?? String(link);\n}\n\n/**\n * The message a SQLite missing-table substring match may be tested against — but\n * only for `Error` instances and raw `string` links, never an arbitrary plain\n * object.\n *\n * Generic \"does not exist\" is deliberately not substring-matched: PostgreSQL uses\n * that phrase for undefined columns, functions, types, and relations. PostgreSQL\n * missing tables are classified by SQLSTATE 42P01 when available, or by the\n * narrower driver-message shape `relation/table \"...\" does not exist` when a\n * bring-your-own driver omits SQLSTATE. SQLite does not expose a portable\n * SQLSTATE here, so the narrow \"no such table\" engine message is still accepted.\n */\nfunction missingTableMessage(link: unknown): string | undefined {\n return typeof link === \"string\" || link instanceof Error ?\n messageProperty(link)\n : undefined;\n}\n\nfunction sqliteErrorCode(link: unknown): unknown {\n if (!canReadProperty(link)) return undefined;\n return Reflect.get(link, \"code\");\n}\n\n/**\n * Cloudflare D1 / Durable Objects may surface a missing-table failure as the\n * generic SQLite code with no detail. Accept the bare marker, but do not\n * substring-match detailed `SQLITE_ERROR: ...` failures: those include syntax\n * errors and bind-limit faults that must stay loud.\n */\nfunction isBareSqliteErrorMarker(link: unknown): boolean {\n const message = messageProperty(link);\n if (message === SQLITE_GENERIC_ERROR_CODE) return true;\n if (sqliteErrorCode(link) !== SQLITE_GENERIC_ERROR_CODE) return false;\n return (\n message === undefined ||\n message === SQLITE_GENERIC_ERROR_CODE ||\n message.includes(SQLITE_MISSING_TABLE_PATTERN)\n );\n}\n\nfunction isPostgresUndefinedRelationMessage(link: unknown): boolean {\n const message = errorMessage(link);\n if (message.startsWith(DRIZZLE_QUERY_ERROR_PREFIX)) return false;\n return POSTGRES_UNDEFINED_RELATION_PATTERN.test(message);\n}\n\n/**\n * Whether any link in the cause chain is a PostgreSQL \"insufficient\n * resources\" failure (SQLSTATE class 53: disk_full, out_of_memory,\n * configuration_limit_exceeded, ...). Parallel index builds surface\n * shared-memory exhaustion this way (53100 from dsm_impl_posix on hosts\n * with a small /dev/shm); callers retry such work with parallelism\n * disabled. Identified by the locale-independent 5-character SQLSTATE\n * prefix only — never by message text.\n */\nexport function isInsufficientResourcesError(error: unknown): boolean {\n for (const link of errorChain(error)) {\n if (!canReadProperty(link)) continue;\n const code: unknown = Reflect.get(link, \"code\");\n if (typeof code === \"string\" && code.length === 5 && code.startsWith(\"53\"))\n return true;\n }\n return false;\n}\n\nexport function isMissingTableError(error: unknown): boolean {\n // SQLSTATE 42P01 is locale-independent and structural, so it is honored on\n // *every* link — including a plain driver-error object reached only by walking\n // through a non-`Error` `.cause` (postgres-js).\n //\n // The SQLite message substring is honored only while every prior link in the\n // chain was an `Error` (or the top-level string) — the reach of the\n // pre-broadening walk, which stopped at the first non-`Error` `.cause`.\n let everyPriorLinkWasError = true;\n for (const link of errorChain(error)) {\n if (isPostgresUndefinedTable(link)) return true;\n if (isPostgresUndefinedRelationMessage(link)) return true;\n if (isBareSqliteErrorMarker(link)) return true;\n if (everyPriorLinkWasError) {\n const message = missingTableMessage(link);\n if (message?.includes(SQLITE_MISSING_TABLE_PATTERN) === true) {\n return true;\n }\n }\n if (!(link instanceof Error)) everyPriorLinkWasError = false;\n }\n return false;\n}\n\n/** Whether one chain link is the un-coded `tuple concurrently updated` race. */\nfunction isPostgresConcurrentTupleUpdate(link: unknown): boolean {\n if (!canReadProperty(link)) return false;\n if (Reflect.get(link, \"code\") !== POSTGRES_INTERNAL_ERROR_CODE) return false;\n return (\n messageProperty(link)?.includes(\n POSTGRES_CONCURRENT_TUPLE_UPDATE_MESSAGE,\n ) === true\n );\n}\n\n/**\n * Whether PostgreSQL refused an IDEMPOTENT DDL statement because another\n * session was concurrently committing the same catalog change — the single\n * owner of \"this DDL lost a race and is worth one retry\".\n *\n * Every idempotent-DDL site in the codebase classifies through this one\n * function: the Postgres backend's `executeConcurrentCreateDdl` (bootstrap\n * tables, contribution materialization, identity relations, the index\n * materialization table and its additive columns) and the identity\n * schema-transition retry. A second copy of the predicate would drift the\n * moment one site learned about a new race SQLSTATE — as `ALTER TABLE ... ADD\n * COLUMN IF NOT EXISTS` (42701) did (#445).\n *\n * Callers MUST use it only around DDL that is a no-op when the object already\n * exists. On any other statement 23505/42701 are real defects, and retrying\n * them would hide a duplicate write.\n */\nexport function isPostgresConcurrentDdlRaceError(error: unknown): boolean {\n for (const link of errorChain(error)) {\n if (!canReadProperty(link)) continue;\n if (\n isSqlStateIn(\n Reflect.get(link, \"code\"),\n POSTGRES_CONCURRENT_DDL_RACE_SQL_STATES,\n )\n ) {\n return true;\n }\n if (isPostgresConcurrentTupleUpdate(link)) return true;\n }\n return false;\n}\n\n/**\n * The PostgreSQL error fields naming the violated constraint and its relation.\n * Both spellings are read because the drivers disagree: node-postgres and\n * PGlite expose the protocol fields as `constraint` / `table`, while\n * postgres-js exposes them as `constraint_name` / `table_name`. Reading only\n * one spelling would silently classify nothing on the other driver.\n */\nconst POSTGRES_CONSTRAINT_FIELDS = [\"constraint\", \"constraint_name\"] as const;\nconst POSTGRES_RELATION_FIELDS = [\"table\", \"table_name\"] as const;\n\n/**\n * SQLite's EXTENDED result code for a primary-key duplicate, in both spellings a\n * driver reports it: the symbolic name (better-sqlite3 `code`, and the\n * `SqliteError` the libSQL client nests on its own error's `.cause`) and the\n * numeric value (libSQL `rawCode` / `extendedCode`, the only form a remote\n * connection surfaces).\n *\n * The extended code — not the base `SQLITE_CONSTRAINT` — is what makes the\n * classification possible at all: SQLite distinguishes a PRIMARY KEY duplicate\n * (1555) from any other unique-index duplicate (`SQLITE_CONSTRAINT_UNIQUE`,\n * 2067) in the code itself, so nothing has to read the message, which names the\n * columns rather than the constraint.\n */\nconst SQLITE_PRIMARY_KEY_VIOLATION_CODE = \"SQLITE_CONSTRAINT_PRIMARYKEY\";\nconst SQLITE_PRIMARY_KEY_VIOLATION_EXTENDED_CODE = 1555;\nconst SQLITE_EXTENDED_CODE_FIELDS = [\"rawCode\", \"extendedCode\"] as const;\n\n/**\n * A relation plus the names its PRIMARY KEY constraint can carry — how far a\n * duplicate-key classification is allowed to reach on an engine that reports the\n * violated constraint by name. See {@link isDuplicatePrimaryKeyError}.\n */\nexport type PrimaryKeyRelation = Readonly<{\n table: string;\n constraintNames: readonly string[];\n}>;\n\nfunction firstStringField(\n link: object,\n fields: readonly string[],\n): string | undefined {\n for (const field of fields) {\n const value: unknown = Reflect.get(link, field);\n if (typeof value === \"string\") return value;\n }\n return undefined;\n}\n\n/**\n * Whether PostgreSQL reported this link as a duplicate of `relation`'s PRIMARY\n * KEY: SQLSTATE, relation, and constraint name must all agree on the SAME link\n * (the driver error), so a 23505 raised by an unrelated statement deeper in the\n * chain cannot be attributed to this relation.\n */\nfunction isPostgresPrimaryKeyViolation(\n link: object,\n relation: PrimaryKeyRelation,\n): boolean {\n if (Reflect.get(link, \"code\") !== POSTGRES_UNIQUE_VIOLATION_CODE)\n return false;\n if (firstStringField(link, POSTGRES_RELATION_FIELDS) !== relation.table) {\n return false;\n }\n const constraint = firstStringField(link, POSTGRES_CONSTRAINT_FIELDS);\n return (\n constraint !== undefined && relation.constraintNames.includes(constraint)\n );\n}\n\n/**\n * Whether SQLite reported this link as a PRIMARY KEY duplicate. The relation is\n * not checked because SQLite does not report one — see\n * {@link isDuplicatePrimaryKeyError} for why the call site supplies that scope.\n */\nfunction isSqlitePrimaryKeyViolation(link: object): boolean {\n if (Reflect.get(link, \"code\") === SQLITE_PRIMARY_KEY_VIOLATION_CODE) {\n return true;\n }\n for (const field of SQLITE_EXTENDED_CODE_FIELDS) {\n const value: unknown = Reflect.get(link, field);\n if (\n typeof value === \"number\" &&\n value === SQLITE_PRIMARY_KEY_VIOLATION_EXTENDED_CODE\n ) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Whether the engine refused a statement because it duplicated a PRIMARY KEY —\n * on PostgreSQL, `relation`'s specifically.\n *\n * Classification is structural: SQLSTATE and SQLite extended result codes, plus\n * the PostgreSQL protocol's own constraint and relation fields. Never message\n * text, which is translated under a non-English `lc_messages`, is overwritten\n * with the query string by Drizzle's wrapper, and on SQLite names the key's\n * COLUMNS rather than the constraint. The `.cause` chain is walked because every\n * driver here nests the real error under at least one wrapper.\n *\n * Narrowing to the primary key is the whole point. A `unique: true` index\n * declaration materializes a UNIQUE INDEX on the same relation, and violating\n * THAT is a declared-uniqueness failure about the row's VALUES, not a duplicate\n * identity. PostgreSQL reports it under the index's own name and SQLite under a\n * different extended code, so it never matches here and keeps surfacing as it\n * did before.\n *\n * `relation` scopes the PostgreSQL arm, which is the one that can see a\n * constraint name. SQLite reports no relation at all, so its scope comes from\n * the CALL SITE instead: callers must invoke this only for a statement that\n * writes exactly one relation — the node or edge insert — where a primary-key\n * duplicate can only be that relation's. Applying it to a multi-relation\n * statement would attribute the wrong table's collision.\n */\nexport function isDuplicatePrimaryKeyError(\n error: unknown,\n relation: PrimaryKeyRelation,\n): boolean {\n for (const link of errorChain(error)) {\n if (!canReadProperty(link)) continue;\n if (isPostgresPrimaryKeyViolation(link, relation)) return true;\n if (isSqlitePrimaryKeyViolation(link)) return true;\n }\n return false;\n}\n\nfunction isSqlStateIn<SqlState extends string>(\n code: unknown,\n states: readonly SqlState[],\n): code is SqlState {\n const known: readonly string[] = states;\n return typeof code === \"string\" && known.includes(code);\n}\n\n/**\n * The first SQLSTATE in the error's cause chain that belongs to `states`. The\n * walk handles both direct driver errors and wrappers such as\n * DrizzleQueryError, which keeps the SQLSTATE-bearing error on `.cause`.\n */\nfunction matchSqlState<SqlState extends string>(\n error: unknown,\n states: readonly SqlState[],\n): SqlState | undefined {\n for (const link of errorChain(error)) {\n if (!canReadProperty(link)) continue;\n const code: unknown = Reflect.get(link, \"code\");\n if (isSqlStateIn(code, states)) return code;\n }\n return undefined;\n}\n\n/**\n * Returns the PostgreSQL SQLSTATE that prevented temporary-table creation.\n *\n * Callers must use this only at a `CREATE TEMP TABLE` execution seam: 42501\n * is otherwise a generic permission failure, and translating it elsewhere\n * would hide a different authorization problem.\n */\nexport function postgresTemporaryTableUnavailableSqlState(\n error: unknown,\n): PostgresTemporaryTableUnavailableSqlState | undefined {\n return matchSqlState(error, POSTGRES_TEMPORARY_TABLE_UNAVAILABLE_SQL_STATES);\n}\n\n/**\n * Returns the PostgreSQL SQLSTATE with which the server refused to open a\n * read-write transaction.\n *\n * Callers must use this only for a failure raised while opening such a\n * transaction — 0A000 is otherwise a generic \"unsupported feature\" report\n * that any statement can raise.\n */\nexport function postgresReadWriteRefusedSqlState(\n error: unknown,\n): PostgresReadWriteRefusedSqlState | undefined {\n return matchSqlState(error, POSTGRES_READ_WRITE_REFUSED_SQL_STATES);\n}\n\n/**\n * Whether SQLite rejected a statement through its authorizer. Cloudflare D1\n * and Durable Objects surface this as `not authorized: SQLITE_AUTH`, usually on\n * a Drizzle wrapper's `.cause`; native drivers may instead expose\n * `code: \"SQLITE_AUTH\"`. Both shapes are structural enough to distinguish from\n * an unrelated permission or connection failure.\n */\nexport function isSqliteNotAuthorizedError(error: unknown): boolean {\n for (const link of errorChain(error)) {\n if (sqliteErrorCode(link) === SQLITE_NOT_AUTHORIZED_CODE) return true;\n const message = messageProperty(link);\n if (\n message?.includes(SQLITE_NOT_AUTHORIZED_CODE) === true &&\n message.toLowerCase().includes(\"not authorized\")\n ) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Whether SQLite refused a write because the enclosing DEFERRED transaction's\n * read snapshot went stale before it could take the writer slot\n * ({@link SQLITE_STALE_SNAPSHOT_CODE}).\n *\n * Classified structurally — the extended result code in either spelling a\n * driver reports it (better-sqlite3's symbolic `code`, libSQL's numeric\n * `rawCode`/`extendedCode`) — and never by message: SQLite renders this as the\n * bare, indistinguishable \"database is locked\".\n */\nexport function isSqliteStaleSnapshotError(error: unknown): boolean {\n for (const link of errorChain(error)) {\n if (sqliteErrorCode(link) === SQLITE_STALE_SNAPSHOT_CODE) return true;\n if (!canReadProperty(link)) continue;\n for (const field of SQLITE_EXTENDED_CODE_FIELDS) {\n if (Reflect.get(link, field) === SQLITE_STALE_SNAPSHOT_EXTENDED_CODE) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction historyMissingRecordedRelationsError(\n details: Record<string, unknown>,\n cause: unknown,\n): ConfigurationError {\n return new ConfigurationError(\n \"history: true requires the recorded-time relations to exist, but a recorded relation is missing.\",\n details,\n {\n cause,\n suggestion:\n \"Create the recorded-time relations (typegraph_recorded_nodes, typegraph_recorded_edges, typegraph_recorded_clock) — e.g. re-run the generated migration SQL — on this database before enabling history capture.\",\n },\n );\n}\n\n/**\n * Converts missing recorded-relation failures into the actionable precondition\n * error used by construction-time history checks. Capture paths use this after\n * the live write has already succeeded inside the same transaction; recorded\n * read paths use it when query/schema swapping reaches a recorded table that\n * has not been materialized yet.\n */\nexport async function withRecordedRelationsPrecondition<T>(\n promise: Promise<T>,\n details: Record<string, unknown>,\n): Promise<T> {\n try {\n return await promise;\n } catch (error) {\n if (!isMissingTableError(error)) throw error;\n throw historyMissingRecordedRelationsError(\n { ...details, code: \"RECORDED_RELATIONS_MISSING\" },\n error,\n );\n }\n}\n\n/**\n * Engine \"vector dimension mismatch\" message shapes. pgvector:\n * `expected 384 dimensions, not 512`; libSQL / sqlite-vec surface a similar\n * `expected N … got/not M`. The first capture is the dimension the *stored*\n * column expects; the optional second is the dimension that was *attempted*.\n */\nconst DIMENSION_MISMATCH_PATTERN =\n /expected (\\d+) dimensions(?:[,\\s]+(?:not|got|but got|but)\\s*(\\d+))?/i;\n\n/**\n * Parses an engine vector-dimension-mismatch error into `{ expected, actual }`\n * by walking the `.cause` chain (drivers wrap the real error). `expected` is\n * the stored column's dimension; `actual` (when the message includes it) is the\n * attempted vector's dimension. Returns `undefined` for unrelated errors.\n */\nexport function parseDimensionMismatch(\n error: unknown,\n): { expected: number; actual: number | undefined } | undefined {\n for (const link of errorChain(error)) {\n const message = errorMessage(link);\n const match = DIMENSION_MISMATCH_PATTERN.exec(message);\n if (match) {\n return {\n expected: Number(match[1]),\n actual: match[2] === undefined ? undefined : Number(match[2]),\n };\n }\n }\n return undefined;\n}\n","/**\n * Canonical-form helpers for deterministic schema serialization.\n *\n * Used by both content-hashing (`computeSchemaHash`) and structural diffing\n * (`computeSchemaDiff`) to ensure that semantically-equivalent objects with\n * differently-ordered keys produce identical canonical strings.\n */\n\nimport { createDataKeyedBag } from \"../utils/object\";\n\n/**\n * `JSON.stringify` replacer that sorts object keys recursively.\n *\n * Apply via `JSON.stringify(value, sortedReplacer)` to obtain output in\n * which sibling keys at every depth appear in lexicographic order.\n *\n * Arrays are passed through unchanged — array order is semantically\n * meaningful and must not be normalized.\n *\n * The re-keyed object is null-prototype ({@link createDataKeyedBag}): every key\n * here is DATA — a kind name, a property name, a JSON-Schema keyword — and\n * `sorted[\"__proto__\"] = value` on a `{}` literal reaches the prototype setter\n * instead of creating an entry. The key would then be missing from the\n * canonical string, so a schema declaring such a property would hash and\n * compare equal to one that does not: `computeSchemaHash` would report\n * \"unchanged\" and `computeSchemaDiff` would find no change to migrate. Output\n * is byte-identical for every value without such a key, so no existing\n * schema's hash moves.\n */\nexport function sortedReplacer(_key: string, value: unknown): unknown {\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n const sorted = createDataKeyedBag<unknown>();\n for (const key of Object.keys(value).toSorted()) {\n sorted[key] = (value as Record<string, unknown>)[key];\n }\n return sorted;\n }\n return value;\n}\n\n/**\n * Compare two values for canonical-form equality.\n *\n * Returns `true` when both values produce identical JSON under `sortedReplacer`\n * — i.e., they have the same JSON structure regardless of object key order.\n * Used by diff machinery to detect semantic changes in JSON-shaped fields.\n *\n * Note: callers must handle `undefined` themselves — `JSON.stringify(undefined)`\n * returns `undefined`, so two `undefined` inputs would compare equal here, which\n * may or may not be the desired semantics depending on context.\n */\nexport function canonicalEqual(a: unknown, b: unknown): boolean {\n return (\n JSON.stringify(a, sortedReplacer) === JSON.stringify(b, sortedReplacer)\n );\n}\n","/**\n * Splits `items` into consecutive chunks of at most `size` elements.\n *\n * An empty input yields no chunks (`[]`), and an input that already fits in a\n * single chunk is returned without copying. Callers rely on the empty-input\n * behavior to skip work entirely rather than issue a statement with an empty\n * `IN ()` list.\n */\nexport function chunk<T>(\n items: readonly T[],\n size: number,\n): readonly (readonly T[])[] {\n // A non-positive, non-finite, or fractional size would make the slice loop\n // fail to advance correctly; fail loud rather than spin or emit empty chunks.\n // All current callers derive size from a positive integer bind-parameter\n // budget, so this only guards against a future regression.\n if (!Number.isSafeInteger(size) || size < 1) {\n throw new RangeError(`chunk size must be a positive integer, got: ${size}`);\n }\n if (items.length === 0) return [];\n if (items.length <= size) return [items];\n const chunks: T[][] = [];\n for (let start = 0; start < items.length; start += size) {\n chunks.push(items.slice(start, start + size));\n }\n return chunks;\n}\n\n/**\n * Groups items by a caller-supplied key while preserving input order within\n * each group.\n */\nexport function groupBy<T, K>(\n items: Iterable<T>,\n keyFor: (item: T) => K,\n): Map<K, T[]> {\n const groups = new Map<K, T[]>();\n for (const item of items) {\n const key = keyFor(item);\n const group = groups.get(key) ?? [];\n group.push(item);\n groups.set(key, group);\n }\n return groups;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/backend/sqlite/local-options.ts","../src/backend/sqlite/local.ts"],"names":["createRequire","Database","ConfigurationError","tables","drizzle","generateSqliteDDL","createSqliteBackend","sqliteVecStrategy","wrapWithManagedClose"],"mappings":";;;;;;;;;;;;;;;;;AA8BO,IAAM,4BAAA,GACX;AAAA,EACE,WAAA,EAAa,KAAA;AAAA,EACb,WAAA,EAAa,QAAA;AAAA,EACb,aAAA,EAAe,GAAA;AAAA,EACf,YAAA,EAAc,MAAA;AAAA,EACd,aAAA,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AO,OAAA,KAAY,QAAA,IACnB,OAAA,KAAY,IAAA,IACZ,UAAU,OAAA,IACV,OAAO,OAAA,CAAQ,IAAA,KAAS,UAAA,EACxB;AACA,MAAC,OAAA,CAAsD,KAAK,MAAM,CAAA;AAClE,MAAA,OAAO,IAAA;AAAA,IACT;AACA,IAAA,OAAO,KAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"chunk-ISKCIQF2.cjs","sourcesContent":["/** Journal modes accepted by local SQLite connections. */\nexport type LocalSqliteJournalMode =\n \"wal\" | \"delete\" | \"truncate\" | \"persist\" | \"memory\" | \"off\";\n\n/** Synchronous levels accepted by local SQLite connections. */\nexport type LocalSqliteSynchronousMode = \"off\" | \"normal\" | \"full\" | \"extra\";\n\n/** Connection pragmas applied when TypeGraph opens a local SQLite database. */\nexport type LocalSqlitePragmaOptions = Readonly<{\n /** `PRAGMA journal_mode`. Default: `\"wal\"` (no-op on `\":memory:\"`). */\n journalMode?: LocalSqliteJournalMode;\n /** `PRAGMA synchronous`. Default: `\"normal\"`. */\n synchronous?: LocalSqliteSynchronousMode;\n /** `PRAGMA busy_timeout`, in milliseconds. Default: `5000`. */\n busyTimeoutMs?: number;\n /**\n * `PRAGMA cache_size`, expressed as a negative KiB value. Positive values\n * mean pages in SQLite and are rejected to prevent accidental oversizing.\n */\n cacheSizeKib?: number | undefined;\n /** `PRAGMA mmap_size`, in non-negative bytes. */\n mmapSizeBytes?: number | undefined;\n /**\n * `PRAGMA wal_autocheckpoint`, in WAL pages. Use `0` to disable automatic\n * checkpoints and run them explicitly after controlled bulk loads.\n */\n walAutocheckpointPages?: number | undefined;\n}>;\n\n/** Defaults for TypeGraph-owned local SQLite connections. */\nexport const DEFAULT_LOCAL_SQLITE_PRAGMAS: Required<LocalSqlitePragmaOptions> =\n {\n journalMode: \"wal\",\n synchronous: \"normal\",\n busyTimeoutMs: 5000,\n cacheSizeKib: undefined,\n mmapSizeBytes: undefined,\n walAutocheckpointPages: undefined,\n };\n","/**\n * Local SQLite backend using better-sqlite3.\n *\n * This module depends on the `better-sqlite3` native addon and should only\n * be imported in Node.js environments. For bundler-friendly SQLite DDL\n * generation and Drizzle backend creation, import from `@nicia-ai/typegraph/adapters/drizzle/sqlite`.\n *\n * @example In-memory database (default)\n * ```typescript\n * import { createLocalSqliteBackend } from \"@nicia-ai/typegraph/adapters/drizzle/sqlite/local\";\n *\n * const { backend, db } = createLocalSqliteBackend();\n * const store = createStore(graph, backend);\n * ```\n *\n * @example File-based database for persistent local development\n * ```typescript\n * import { createLocalSqliteBackend } from \"@nicia-ai/typegraph/adapters/drizzle/sqlite/local\";\n *\n * const { backend, db } = createLocalSqliteBackend({ path: \"./dev.db\" });\n * const store = createStore(graph, backend);\n * ```\n */\nimport { createRequire } from \"node:module\";\n\nimport Database from \"better-sqlite3\";\nimport {\n type BetterSQLite3Database,\n drizzle,\n} from \"drizzle-orm/better-sqlite3\";\n\nimport { ConfigurationError } from \"../../errors\";\nimport { sqliteVecStrategy } from \"../../query/dialect/vector/sqlite-vec-strategy\";\nimport { wrapWithManagedClose } from \"../derive-backend\";\nimport { generateSqliteDDL } from \"../drizzle/ddl\";\nimport { type AnySqliteDatabase } from \"../drizzle/execution\";\nexport type { AnySqliteDatabase } from \"../drizzle/execution\";\nimport {\n createSqliteBackend,\n type SqliteTables,\n tables as defaultTables,\n} from \"../drizzle/sqlite\";\nimport {\n DEFAULT_LOCAL_SQLITE_PRAGMAS,\n type LocalSqliteJournalMode,\n type LocalSqlitePragmaOptions,\n type LocalSqliteSynchronousMode,\n} from \"./local-options\";\n\nexport {\n DEFAULT_LOCAL_SQLITE_PRAGMAS,\n type LocalSqliteJournalMode,\n type LocalSqlitePragmaOptions,\n type LocalSqliteSynchronousMode,\n} from \"./local-options\";\nimport { type AdapterBackend, type BackendCapabilities } from \"../types\";\n\nexport type {\n ContributionDiagnostic,\n ContributionDiagnosticState,\n ContributionRepairEntry,\n ContributionRepairResult,\n} from \"../types\";\n\nconst nodeRequire = createRequire(import.meta.url);\n\n// ============================================================\n// Native Addon Helpers\n// ============================================================\n\ntype NodeModuleVersionMismatch = Readonly<{\n compiled: number;\n required: number;\n}>;\n\nfunction getUnknownErrorMessage(error: unknown): string {\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\nfunction parseNodeModuleVersionMismatchMessage(\n message: string,\n): NodeModuleVersionMismatch | undefined {\n const regexp =\n /NODE_MODULE_VERSION (?<compiled>\\d+)[\\s\\S]*?NODE_MODULE_VERSION (?<required>\\d+)/;\n const match = regexp.exec(message);\n if (!match?.groups) return undefined;\n\n const compiled = Number(match.groups[\"compiled\"]);\n const required = Number(match.groups[\"required\"]);\n\n if (!Number.isFinite(compiled) || !Number.isFinite(required))\n return undefined;\n\n return { compiled, required };\n}\n\nfunction createDatabase(path: string): Database.Database {\n try {\n return new Database(path);\n } catch (error) {\n const message = getUnknownErrorMessage(error);\n const mismatch = parseNodeModuleVersionMismatchMessage(message);\n if (!mismatch) throw error;\n\n throw new ConfigurationError(\n [\n \"Failed to load better-sqlite3 native addon.\",\n `It was compiled for NODE_MODULE_VERSION ${mismatch.compiled}, but this Node.js runtime requires ${mismatch.required}.`,\n \"This usually happens after switching Node versions without rebuilding native dependencies.\",\n \"Rebuild with: pnpm rebuild better-sqlite3 (or npm rebuild better-sqlite3).\",\n ].join(\" \"),\n {\n nodeVersion: process.version,\n nodeModuleVersion: process.versions.modules,\n compiledNodeModuleVersion: mismatch.compiled,\n requiredNodeModuleVersion: mismatch.required,\n },\n { cause: error },\n );\n }\n}\n\n// ============================================================\n// Types\n// ============================================================\n\nconst LOCAL_SQLITE_JOURNAL_MODES: readonly LocalSqliteJournalMode[] = [\n \"wal\",\n \"delete\",\n \"truncate\",\n \"persist\",\n \"memory\",\n \"off\",\n];\n\nconst LOCAL_SQLITE_SYNCHRONOUS_MODES: readonly LocalSqliteSynchronousMode[] = [\n \"off\",\n \"normal\",\n \"full\",\n \"extra\",\n];\n\nconst SQLITE_MAX_WAL_AUTOCHECKPOINT_PAGES = 2_147_483_647;\n\nfunction applyConnectionPragmas(\n sqlite: Database.Database,\n pragmas: LocalSqlitePragmaOptions | false | undefined,\n): void {\n if (pragmas === false) return;\n const resolved: Required<LocalSqlitePragmaOptions> = {\n ...DEFAULT_LOCAL_SQLITE_PRAGMAS,\n ...pragmas,\n };\n\n // Runtime guards mirror the compile-time unions: pragma values are spliced\n // into pragma statements, so reject anything outside the allowlists rather\n // than forwarding it to SQLite.\n if (!LOCAL_SQLITE_JOURNAL_MODES.includes(resolved.journalMode)) {\n throw new ConfigurationError(\n `Invalid journalMode pragma: ${resolved.journalMode}. ` +\n `Expected one of: ${LOCAL_SQLITE_JOURNAL_MODES.join(\", \")}.`,\n { journalMode: resolved.journalMode },\n );\n }\n if (!LOCAL_SQLITE_SYNCHRONOUS_MODES.includes(resolved.synchronous)) {\n throw new ConfigurationError(\n `Invalid synchronous pragma: ${resolved.synchronous}. ` +\n `Expected one of: ${LOCAL_SQLITE_SYNCHRONOUS_MODES.join(\", \")}.`,\n { synchronous: resolved.synchronous },\n );\n }\n if (\n !Number.isSafeInteger(resolved.busyTimeoutMs) ||\n resolved.busyTimeoutMs < 0\n ) {\n throw new ConfigurationError(\n `Invalid busyTimeoutMs pragma: ${String(resolved.busyTimeoutMs)}. ` +\n \"Expected a non-negative integer number of milliseconds.\",\n { busyTimeoutMs: resolved.busyTimeoutMs },\n );\n }\n if (\n resolved.cacheSizeKib !== undefined &&\n (!Number.isSafeInteger(resolved.cacheSizeKib) || resolved.cacheSizeKib >= 0)\n ) {\n throw new ConfigurationError(\n `Invalid cacheSizeKib pragma: ${String(resolved.cacheSizeKib)}. ` +\n \"Expected a negative safe integer — SQLite's own cache_size pragma \" +\n \"interprets a positive value as a page count, not KiB, so a caller \" +\n 'who passes e.g. 131072 meaning \"131072 KiB\" silently gets ' +\n \"131072 pages (~512MiB at the default 4KiB page size) instead.\",\n { cacheSizeKib: resolved.cacheSizeKib },\n );\n }\n if (\n resolved.mmapSizeBytes !== undefined &&\n (!Number.isSafeInteger(resolved.mmapSizeBytes) ||\n resolved.mmapSizeBytes < 0)\n ) {\n throw new ConfigurationError(\n `Invalid mmapSizeBytes pragma: ${String(resolved.mmapSizeBytes)}. ` +\n \"Expected a non-negative safe integer number of bytes.\",\n { mmapSizeBytes: resolved.mmapSizeBytes },\n );\n }\n if (\n resolved.walAutocheckpointPages !== undefined &&\n (!Number.isSafeInteger(resolved.walAutocheckpointPages) ||\n resolved.walAutocheckpointPages < 0 ||\n resolved.walAutocheckpointPages > SQLITE_MAX_WAL_AUTOCHECKPOINT_PAGES)\n ) {\n throw new ConfigurationError(\n `Invalid walAutocheckpointPages pragma: ${String(resolved.walAutocheckpointPages)}. ` +\n `Expected an integer between 0 and ${SQLITE_MAX_WAL_AUTOCHECKPOINT_PAGES} ` +\n \"WAL pages (0 disables automatic checkpointing entirely).\",\n { walAutocheckpointPages: resolved.walAutocheckpointPages },\n );\n }\n\n // \":memory:\" databases always journal in memory; SQLite answers the WAL\n // request with \"memory\" instead of erroring, so no special-casing needed.\n sqlite.pragma(`journal_mode = ${resolved.journalMode}`);\n sqlite.pragma(`synchronous = ${resolved.synchronous}`);\n sqlite.pragma(`busy_timeout = ${resolved.busyTimeoutMs}`);\n if (resolved.cacheSizeKib !== undefined) {\n sqlite.pragma(`cache_size = ${resolved.cacheSizeKib}`);\n }\n if (resolved.mmapSizeBytes !== undefined) {\n sqlite.pragma(`mmap_size = ${resolved.mmapSizeBytes}`);\n }\n if (resolved.walAutocheckpointPages !== undefined) {\n sqlite.pragma(`wal_autocheckpoint = ${resolved.walAutocheckpointPages}`);\n }\n}\n\n/**\n * Options for creating a local SQLite backend.\n */\nexport type LocalSqliteBackendOptions = Readonly<{\n /**\n * Path to the SQLite database file.\n * Defaults to \":memory:\" for an in-memory database.\n */\n path?: string;\n\n /**\n * Connection pragmas applied at open. Defaults to\n * {@link DEFAULT_LOCAL_SQLITE_PRAGMAS} (WAL, `synchronous=NORMAL`, 5s busy\n * timeout, and SQLite's own tiny built-in page cache / disabled mmap\n * left untouched). Individual values merge over the defaults; pass\n * `false` to skip pragma configuration entirely and keep the driver\n * defaults (rollback journal, `synchronous=FULL`, and better-sqlite3's\n * own 5s busy timeout from its `timeout` constructor option). Set\n * `cacheSizeKib`/`mmapSizeBytes` explicitly once a database's working\n * set is known to exceed SQLite's 2MiB default cache — otherwise every\n * query pays a fresh disk read per page past that tiny working set. Set\n * `walAutocheckpointPages` explicitly for a bulk-insert-heavy workload —\n * SQLite's own default checkpoints every ~4MiB of WAL growth, which gets\n * more expensive as the database file grows over a large load.\n */\n pragmas?: LocalSqlitePragmaOptions | false;\n\n /**\n * Custom table definitions.\n * Defaults to standard TypeGraph table names.\n */\n tables?: SqliteTables;\n\n /**\n * Override specific backend capabilities — e.g. to simulate an engine-level\n * gap like missing SQL window functions in tests. Forwarded to\n * createSqliteBackend.\n */\n capabilities?: Partial<BackendCapabilities>;\n}>;\n\n/**\n * Result of creating a local SQLite backend.\n */\nexport type LocalSqliteBackendResult = Readonly<{\n /**\n * The GraphBackend instance for use with createStore.\n */\n backend: AdapterBackend<AnySqliteDatabase>;\n\n /**\n * The underlying Drizzle database instance.\n * Useful for direct SQL access or cleanup.\n */\n db: BetterSQLite3Database;\n}>;\n\n// ============================================================\n// Factory Function\n// ============================================================\n\n/**\n * Creates a SQLite backend with minimal configuration.\n *\n * This is a convenience function for local development and testing.\n * It handles database creation, schema migration, and backend setup.\n *\n * For production deployments or custom configurations, use createSqliteBackend\n * directly with your own Drizzle database instance.\n *\n * @param options - Configuration options\n * @returns Backend and database instances\n *\n * @example In-memory database (default)\n * ```typescript\n * const { backend } = createLocalSqliteBackend();\n * const store = createStore(graph, backend);\n * ```\n *\n * @example File-based database\n * ```typescript\n * const { backend, db } = createLocalSqliteBackend({ path: \"./data.db\" });\n * const store = createStore(graph, backend);\n * ```\n */\nexport function createLocalSqliteBackend(\n options: LocalSqliteBackendOptions = {},\n): LocalSqliteBackendResult {\n const path = options.path ?? \":memory:\";\n const tables = options.tables ?? defaultTables;\n\n const sqlite = createDatabase(path);\n try {\n applyConnectionPragmas(sqlite, options.pragmas);\n\n // Best-effort: load sqlite-vec so embedding fields are persisted to\n // per-`(kind, field)` `vec0` storage. Without it, nodes with\n // `embedding()` fields validate and insert but their vectors are silently\n // dropped. When the user has installed sqlite-vec as a peer dep we load\n // it and wire the strategy; otherwise we proceed without vector support.\n const hasSqliteVec = tryLoadSqliteVec(sqlite);\n\n const db = drizzle(sqlite);\n\n // Generate and execute DDL from schema\n const ddlStatements = generateSqliteDDL(tables);\n for (const statement of ddlStatements) {\n sqlite.exec(statement);\n }\n\n const backend = createSqliteBackend(db, {\n executionProfile: {\n isSync: true,\n },\n tables,\n ...(hasSqliteVec ? { vector: sqliteVecStrategy } : {}),\n capabilities: {\n ...options.capabilities,\n graphAnalytics: {\n supported:\n options.capabilities?.graphAnalytics?.supported ??\n options.capabilities?.transactions !== false,\n mathFunctions:\n options.capabilities?.graphAnalytics?.mathFunctions ?? true,\n },\n },\n });\n const managedBackend = wrapWithManagedClose(backend, () => {\n sqlite.close();\n });\n\n return { backend: managedBackend, db };\n } catch (error) {\n try {\n sqlite.close();\n } catch {\n // Preserve the provisioning error; a cleanup failure is secondary.\n }\n throw error;\n }\n}\n\nfunction tryLoadSqliteVec(sqlite: Database.Database): boolean {\n try {\n // `sqlite-vec` is an optional peer dep; resolved via createRequire so\n // bundlers don't mark it as a hard import. Node resolves the package\n // only when it's actually installed.\n const module_: unknown = nodeRequire(\"sqlite-vec\");\n if (\n typeof module_ === \"object\" &&\n module_ !== null &&\n \"load\" in module_ &&\n typeof module_.load === \"function\"\n ) {\n (module_ as { load: (db: Database.Database) => void }).load(sqlite);\n return true;\n }\n return false;\n } catch {\n return false;\n }\n}\nexport type { GraphIdentityConfig } from \"../../core/define-graph\";\n"]}