@nicia-ai/typegraph 0.41.0 → 0.42.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 (265) hide show
  1. package/dist/backend/drizzle/indexes.cjs +9 -9
  2. package/dist/backend/drizzle/indexes.d.cts +1 -2
  3. package/dist/backend/drizzle/indexes.d.ts +1 -2
  4. package/dist/backend/drizzle/indexes.js +5 -5
  5. package/dist/backend/index.cjs +50 -50
  6. package/dist/backend/index.d.cts +3 -4
  7. package/dist/backend/index.d.ts +3 -4
  8. package/dist/backend/index.js +11 -11
  9. package/dist/backend/postgres/index.cjs +26 -26
  10. package/dist/backend/postgres/index.d.cts +5 -6
  11. package/dist/backend/postgres/index.d.ts +5 -6
  12. package/dist/backend/postgres/index.js +13 -13
  13. package/dist/backend/postgres/pglite-store.cjs +34 -34
  14. package/dist/backend/postgres/pglite-store.d.cts +7 -8
  15. package/dist/backend/postgres/pglite-store.d.ts +7 -8
  16. package/dist/backend/postgres/pglite-store.js +30 -30
  17. package/dist/backend/postgres/pglite.cjs +15 -15
  18. package/dist/backend/postgres/pglite.d.cts +2 -3
  19. package/dist/backend/postgres/pglite.d.ts +2 -3
  20. package/dist/backend/postgres/pglite.js +14 -14
  21. package/dist/backend/sqlite/index.cjs +23 -23
  22. package/dist/backend/sqlite/index.d.cts +5 -6
  23. package/dist/backend/sqlite/index.d.ts +5 -6
  24. package/dist/backend/sqlite/index.js +11 -11
  25. package/dist/backend/sqlite/libsql.cjs +17 -17
  26. package/dist/backend/sqlite/libsql.d.cts +2 -3
  27. package/dist/backend/sqlite/libsql.d.ts +2 -3
  28. package/dist/backend/sqlite/libsql.js +13 -13
  29. package/dist/backend/sqlite/local-store.cjs +35 -35
  30. package/dist/backend/sqlite/local-store.d.cts +7 -8
  31. package/dist/backend/sqlite/local-store.d.ts +7 -8
  32. package/dist/backend/sqlite/local-store.js +31 -31
  33. package/dist/backend/sqlite/local.cjs +16 -16
  34. package/dist/backend/sqlite/local.d.cts +2 -3
  35. package/dist/backend/sqlite/local.d.ts +2 -3
  36. package/dist/backend/sqlite/local.js +14 -14
  37. package/dist/{chunk-LOKG3KQV.cjs → chunk-277UZV7X.cjs} +1113 -1089
  38. package/dist/chunk-277UZV7X.cjs.map +1 -0
  39. package/dist/{chunk-2I3DNNBU.js → chunk-2G6ZEGYO.js} +4 -4
  40. package/dist/{chunk-2I3DNNBU.js.map → chunk-2G6ZEGYO.js.map} +1 -1
  41. package/dist/{chunk-76HE7DJP.js → chunk-2HKIID5K.js} +5 -5
  42. package/dist/{chunk-76HE7DJP.js.map → chunk-2HKIID5K.js.map} +1 -1
  43. package/dist/{chunk-QOHTVDHU.js → chunk-2OOY4OYT.js} +4 -4
  44. package/dist/{chunk-QOHTVDHU.js.map → chunk-2OOY4OYT.js.map} +1 -1
  45. package/dist/{chunk-UCHW2MGP.cjs → chunk-2SO5I5AI.cjs} +196 -196
  46. package/dist/{chunk-UCHW2MGP.cjs.map → chunk-2SO5I5AI.cjs.map} +1 -1
  47. package/dist/{chunk-LFFVD5ZR.cjs → chunk-33PAKPED.cjs} +41 -41
  48. package/dist/{chunk-LFFVD5ZR.cjs.map → chunk-33PAKPED.cjs.map} +1 -1
  49. package/dist/{chunk-QCKD3RCI.cjs → chunk-3RPQDGUE.cjs} +5 -5
  50. package/dist/{chunk-QCKD3RCI.cjs.map → chunk-3RPQDGUE.cjs.map} +1 -1
  51. package/dist/{chunk-PH4IJ3V5.js → chunk-3V6D5DEC.js} +3 -3
  52. package/dist/{chunk-PH4IJ3V5.js.map → chunk-3V6D5DEC.js.map} +1 -1
  53. package/dist/{chunk-Y5UC3IXF.js → chunk-42XYPKZU.js} +3 -3
  54. package/dist/{chunk-Y5UC3IXF.js.map → chunk-42XYPKZU.js.map} +1 -1
  55. package/dist/{chunk-XZA3Y4YH.js → chunk-4WYFRACU.js} +3 -3
  56. package/dist/{chunk-XZA3Y4YH.js.map → chunk-4WYFRACU.js.map} +1 -1
  57. package/dist/{chunk-AQVDAKXH.js → chunk-4XRP2N6B.js} +3 -3
  58. package/dist/{chunk-AQVDAKXH.js.map → chunk-4XRP2N6B.js.map} +1 -1
  59. package/dist/{chunk-PWXGB77L.cjs → chunk-5AERZSHC.cjs} +4 -4
  60. package/dist/{chunk-PWXGB77L.cjs.map → chunk-5AERZSHC.cjs.map} +1 -1
  61. package/dist/{chunk-K6CD6W5J.js → chunk-5C75HQYQ.js} +5 -5
  62. package/dist/{chunk-K6CD6W5J.js.map → chunk-5C75HQYQ.js.map} +1 -1
  63. package/dist/{chunk-2J5NMMVR.cjs → chunk-5GV4JQNA.cjs} +43 -43
  64. package/dist/{chunk-2J5NMMVR.cjs.map → chunk-5GV4JQNA.cjs.map} +1 -1
  65. package/dist/{chunk-KHNKYSGP.cjs → chunk-5P6IPIT6.cjs} +41 -41
  66. package/dist/{chunk-KHNKYSGP.cjs.map → chunk-5P6IPIT6.cjs.map} +1 -1
  67. package/dist/{chunk-M2RPZS7J.cjs → chunk-5Q3P6OIC.cjs} +12 -12
  68. package/dist/{chunk-M2RPZS7J.cjs.map → chunk-5Q3P6OIC.cjs.map} +1 -1
  69. package/dist/{chunk-QXKVUJLI.cjs → chunk-5ZPRE4CV.cjs} +206 -166
  70. package/dist/chunk-5ZPRE4CV.cjs.map +1 -0
  71. package/dist/{chunk-53BSOG3O.js → chunk-6NB73BXV.js} +11 -11
  72. package/dist/{chunk-53BSOG3O.js.map → chunk-6NB73BXV.js.map} +1 -1
  73. package/dist/{chunk-SE422RES.cjs → chunk-6TJ6PKPS.cjs} +27 -27
  74. package/dist/{chunk-SE422RES.cjs.map → chunk-6TJ6PKPS.cjs.map} +1 -1
  75. package/dist/{chunk-7WLEQIHA.cjs → chunk-7Y6BV3TK.cjs} +100 -100
  76. package/dist/{chunk-7WLEQIHA.cjs.map → chunk-7Y6BV3TK.cjs.map} +1 -1
  77. package/dist/{chunk-HP6LWBLB.cjs → chunk-AO2WPYFZ.cjs} +4 -4
  78. package/dist/{chunk-HP6LWBLB.cjs.map → chunk-AO2WPYFZ.cjs.map} +1 -1
  79. package/dist/{chunk-7UTUKH4E.cjs → chunk-AQR6BHB3.cjs} +10 -10
  80. package/dist/{chunk-7UTUKH4E.cjs.map → chunk-AQR6BHB3.cjs.map} +1 -1
  81. package/dist/{chunk-X4PVHAZ6.cjs → chunk-ARN3ZODS.cjs} +6 -6
  82. package/dist/{chunk-X4PVHAZ6.cjs.map → chunk-ARN3ZODS.cjs.map} +1 -1
  83. package/dist/{chunk-YYLMXERH.js → chunk-CDYRPI5U.js} +4 -4
  84. package/dist/{chunk-YYLMXERH.js.map → chunk-CDYRPI5U.js.map} +1 -1
  85. package/dist/{chunk-3LKL3S6X.js → chunk-CI5NPLXX.js} +3 -3
  86. package/dist/{chunk-3LKL3S6X.js.map → chunk-CI5NPLXX.js.map} +1 -1
  87. package/dist/{chunk-UUIBACKJ.js → chunk-CUPJL6TS.js} +3 -3
  88. package/dist/{chunk-UUIBACKJ.js.map → chunk-CUPJL6TS.js.map} +1 -1
  89. package/dist/{chunk-JZYMOHHM.cjs → chunk-CVK4T34X.cjs} +22 -22
  90. package/dist/{chunk-JZYMOHHM.cjs.map → chunk-CVK4T34X.cjs.map} +1 -1
  91. package/dist/{chunk-L3DDZUZP.js → chunk-CVNGKTHO.js} +4 -4
  92. package/dist/{chunk-L3DDZUZP.js.map → chunk-CVNGKTHO.js.map} +1 -1
  93. package/dist/{chunk-RW24SAHI.cjs → chunk-DMZEVJGL.cjs} +13 -13
  94. package/dist/{chunk-RW24SAHI.cjs.map → chunk-DMZEVJGL.cjs.map} +1 -1
  95. package/dist/{chunk-MQBF3XGY.js → chunk-DP7KC6CL.js} +47 -23
  96. package/dist/chunk-DP7KC6CL.js.map +1 -0
  97. package/dist/{chunk-QYDUCWD2.cjs → chunk-ECU53PMN.cjs} +4 -4
  98. package/dist/{chunk-QYDUCWD2.cjs.map → chunk-ECU53PMN.cjs.map} +1 -1
  99. package/dist/{chunk-SCTZRFW5.js → chunk-EQOQOT55.js} +5 -5
  100. package/dist/{chunk-SCTZRFW5.js.map → chunk-EQOQOT55.js.map} +1 -1
  101. package/dist/{chunk-JHK6NPFV.js → chunk-EVFL2ZY5.js} +9 -9
  102. package/dist/{chunk-JHK6NPFV.js.map → chunk-EVFL2ZY5.js.map} +1 -1
  103. package/dist/{chunk-SAMJLDGG.cjs → chunk-F2KVJ6FF.cjs} +112 -112
  104. package/dist/{chunk-SAMJLDGG.cjs.map → chunk-F2KVJ6FF.cjs.map} +1 -1
  105. package/dist/{chunk-NMQ6C6TS.cjs → chunk-F7TDKSVB.cjs} +4 -4
  106. package/dist/{chunk-NMQ6C6TS.cjs.map → chunk-F7TDKSVB.cjs.map} +1 -1
  107. package/dist/{chunk-HQRZEYYB.cjs → chunk-FFQGI67R.cjs} +44 -44
  108. package/dist/{chunk-HQRZEYYB.cjs.map → chunk-FFQGI67R.cjs.map} +1 -1
  109. package/dist/{chunk-YIRLBUNN.js → chunk-FMPZPOUD.js} +3 -3
  110. package/dist/{chunk-YIRLBUNN.js.map → chunk-FMPZPOUD.js.map} +1 -1
  111. package/dist/{chunk-LL5D5T5W.cjs → chunk-FSCJOTHF.cjs} +10 -10
  112. package/dist/{chunk-LL5D5T5W.cjs.map → chunk-FSCJOTHF.cjs.map} +1 -1
  113. package/dist/{chunk-2X73QTIC.cjs → chunk-FY4VY5EV.cjs} +20 -20
  114. package/dist/{chunk-2X73QTIC.cjs.map → chunk-FY4VY5EV.cjs.map} +1 -1
  115. package/dist/{chunk-3SHAUJRB.js → chunk-GT7NEXSU.js} +3 -3
  116. package/dist/{chunk-3SHAUJRB.js.map → chunk-GT7NEXSU.js.map} +1 -1
  117. package/dist/{chunk-W66YCXWT.js → chunk-HHBKGPEI.js} +11 -10
  118. package/dist/chunk-HHBKGPEI.js.map +1 -0
  119. package/dist/{chunk-CKFBZ4LV.cjs → chunk-I73ATSAH.cjs} +4 -4
  120. package/dist/{chunk-CKFBZ4LV.cjs.map → chunk-I73ATSAH.cjs.map} +1 -1
  121. package/dist/{chunk-ELA3V6UN.js → chunk-JOYPNY33.js} +9 -9
  122. package/dist/{chunk-ELA3V6UN.js.map → chunk-JOYPNY33.js.map} +1 -1
  123. package/dist/{chunk-YIX3BEBR.cjs → chunk-K2HHCWZO.cjs} +108 -108
  124. package/dist/{chunk-YIX3BEBR.cjs.map → chunk-K2HHCWZO.cjs.map} +1 -1
  125. package/dist/{chunk-SAFZ6JTI.cjs → chunk-KTBTSHU6.cjs} +19 -2
  126. package/dist/chunk-KTBTSHU6.cjs.map +1 -0
  127. package/dist/{chunk-KOI7UEI5.js → chunk-LDCWO5B6.js} +3 -3
  128. package/dist/{chunk-KOI7UEI5.js.map → chunk-LDCWO5B6.js.map} +1 -1
  129. package/dist/{chunk-I5CRUPKO.js → chunk-LQLVJWUH.js} +7 -7
  130. package/dist/{chunk-I5CRUPKO.js.map → chunk-LQLVJWUH.js.map} +1 -1
  131. package/dist/{chunk-6N7QBIWN.js → chunk-M4GYQF2H.js} +3 -3
  132. package/dist/{chunk-6N7QBIWN.js.map → chunk-M4GYQF2H.js.map} +1 -1
  133. package/dist/{chunk-ZE7E46IZ.js → chunk-NXIZL7ZZ.js} +6 -6
  134. package/dist/{chunk-ZE7E46IZ.js.map → chunk-NXIZL7ZZ.js.map} +1 -1
  135. package/dist/{chunk-XRU7V7FF.cjs → chunk-O2GZM7UK.cjs} +7 -7
  136. package/dist/{chunk-XRU7V7FF.cjs.map → chunk-O2GZM7UK.cjs.map} +1 -1
  137. package/dist/{chunk-ZE6NVENI.js → chunk-O3USVVWS.js} +3 -3
  138. package/dist/{chunk-ZE6NVENI.js.map → chunk-O3USVVWS.js.map} +1 -1
  139. package/dist/{chunk-UDS5DZNY.cjs → chunk-O7XVCLXW.cjs} +68 -67
  140. package/dist/chunk-O7XVCLXW.cjs.map +1 -0
  141. package/dist/{chunk-KLR77R5A.cjs → chunk-OM6RIOA5.cjs} +13 -13
  142. package/dist/{chunk-KLR77R5A.cjs.map → chunk-OM6RIOA5.cjs.map} +1 -1
  143. package/dist/{chunk-LLHMAHG4.cjs → chunk-OMQ2NBOR.cjs} +27 -27
  144. package/dist/{chunk-LLHMAHG4.cjs.map → chunk-OMQ2NBOR.cjs.map} +1 -1
  145. package/dist/{chunk-DPNA466P.js → chunk-OYJSYDIH.js} +19 -3
  146. package/dist/chunk-OYJSYDIH.js.map +1 -0
  147. package/dist/{chunk-V3S74J44.js → chunk-RAWG2FEU.js} +134 -22
  148. package/dist/chunk-RAWG2FEU.js.map +1 -0
  149. package/dist/{chunk-TAUGGLNQ.js → chunk-RXOAXO3R.js} +3 -3
  150. package/dist/{chunk-TAUGGLNQ.js.map → chunk-RXOAXO3R.js.map} +1 -1
  151. package/dist/{chunk-LLE25NRD.cjs → chunk-TRC646QQ.cjs} +7 -7
  152. package/dist/{chunk-LLE25NRD.cjs.map → chunk-TRC646QQ.cjs.map} +1 -1
  153. package/dist/chunk-U3YRCZ5L.cjs +12 -0
  154. package/dist/{chunk-IMQKXL4E.cjs.map → chunk-U3YRCZ5L.cjs.map} +1 -1
  155. package/dist/{chunk-ZVME6OSV.js → chunk-UJRWOV5B.js} +5 -5
  156. package/dist/{chunk-ZVME6OSV.js.map → chunk-UJRWOV5B.js.map} +1 -1
  157. package/dist/{chunk-HAQVISUF.cjs → chunk-UTTW2Q3M.cjs} +133 -133
  158. package/dist/{chunk-HAQVISUF.cjs.map → chunk-UTTW2Q3M.cjs.map} +1 -1
  159. package/dist/{chunk-L5ET7FYQ.js → chunk-UZLEQFTV.js} +3 -3
  160. package/dist/{chunk-L5ET7FYQ.js.map → chunk-UZLEQFTV.js.map} +1 -1
  161. package/dist/{chunk-JP5EICR6.cjs → chunk-V2GZBPY2.cjs} +179 -65
  162. package/dist/chunk-V2GZBPY2.cjs.map +1 -0
  163. package/dist/{chunk-BUZWMDNL.js → chunk-VC26BUNP.js} +5 -5
  164. package/dist/{chunk-BUZWMDNL.js.map → chunk-VC26BUNP.js.map} +1 -1
  165. package/dist/chunk-VGMNGWBR.cjs +12 -0
  166. package/dist/{chunk-5YBDB7UG.cjs.map → chunk-VGMNGWBR.cjs.map} +1 -1
  167. package/dist/{chunk-XMEYZYGE.js → chunk-WYQILW5V.js} +8 -8
  168. package/dist/{chunk-XMEYZYGE.js.map → chunk-WYQILW5V.js.map} +1 -1
  169. package/dist/{chunk-YX3H63VV.cjs → chunk-X2XOQZT3.cjs} +9 -9
  170. package/dist/{chunk-YX3H63VV.cjs.map → chunk-X2XOQZT3.cjs.map} +1 -1
  171. package/dist/{chunk-N2V3HJFV.cjs → chunk-XDMPDUKL.cjs} +9 -9
  172. package/dist/{chunk-N2V3HJFV.cjs.map → chunk-XDMPDUKL.cjs.map} +1 -1
  173. package/dist/{chunk-EFZ4S22A.js → chunk-YPVQYM3L.js} +107 -67
  174. package/dist/chunk-YPVQYM3L.js.map +1 -0
  175. package/dist/{chunk-5J4VNCUD.js → chunk-Z3WIL6S3.js} +5 -5
  176. package/dist/{chunk-5J4VNCUD.js.map → chunk-Z3WIL6S3.js.map} +1 -1
  177. package/dist/{chunk-MNURF4RF.cjs → chunk-ZBV4LQD2.cjs} +4 -4
  178. package/dist/{chunk-MNURF4RF.cjs.map → chunk-ZBV4LQD2.cjs.map} +1 -1
  179. package/dist/{chunk-YGX4PMG6.js → chunk-ZGOUVMVS.js} +5 -5
  180. package/dist/{chunk-YGX4PMG6.js.map → chunk-ZGOUVMVS.js.map} +1 -1
  181. package/dist/{chunk-QZYGZVUI.js → chunk-ZIRC2U6G.js} +11 -11
  182. package/dist/{chunk-QZYGZVUI.js.map → chunk-ZIRC2U6G.js.map} +1 -1
  183. package/dist/{chunk-6QP4QXBR.js → chunk-ZOHCFYXE.js} +3 -3
  184. package/dist/{chunk-6QP4QXBR.js.map → chunk-ZOHCFYXE.js.map} +1 -1
  185. package/dist/{chunk-VWEFXG73.js → chunk-ZP2KPDNN.js} +3 -3
  186. package/dist/{chunk-VWEFXG73.js.map → chunk-ZP2KPDNN.js.map} +1 -1
  187. package/dist/{chunk-NT6ILURI.cjs → chunk-ZPCKPLMX.cjs} +8 -8
  188. package/dist/{chunk-NT6ILURI.cjs.map → chunk-ZPCKPLMX.cjs.map} +1 -1
  189. package/dist/core/index.cjs +28 -28
  190. package/dist/core/index.d.cts +5 -6
  191. package/dist/core/index.d.ts +5 -6
  192. package/dist/core/index.js +8 -8
  193. package/dist/{ddl-BCXFRLWg.d.cts → ddl-3unqC-kg.d.cts} +3 -3
  194. package/dist/{ddl-ByLmGgn9.d.ts → ddl-Bc4Dl8fu.d.ts} +3 -3
  195. package/dist/{define-graph-BSviZubs.d.ts → define-graph-Byslw2OO.d.cts} +1 -2
  196. package/dist/{define-graph-XyJheaFm.d.cts → define-graph-DBFnc7u_.d.ts} +1 -2
  197. package/dist/graph-extension/index.cjs +20 -20
  198. package/dist/graph-extension/index.d.cts +4 -4
  199. package/dist/graph-extension/index.d.ts +4 -4
  200. package/dist/graph-extension/index.js +5 -5
  201. package/dist/graph-merge/index.cjs +105 -105
  202. package/dist/graph-merge/index.d.cts +8 -9
  203. package/dist/graph-merge/index.d.ts +8 -9
  204. package/dist/graph-merge/index.js +25 -25
  205. package/dist/{index-BD_3TCgh.d.ts → index-DHXw7QAl.d.cts} +19 -4
  206. package/dist/{index-BihFPsPu.d.cts → index-DQzVJBHa.d.ts} +19 -4
  207. package/dist/index.cjs +206 -202
  208. package/dist/index.d.cts +13 -15
  209. package/dist/index.d.ts +13 -15
  210. package/dist/index.js +35 -35
  211. package/dist/indexes/index.cjs +13 -13
  212. package/dist/indexes/index.d.cts +4 -5
  213. package/dist/indexes/index.d.ts +4 -5
  214. package/dist/indexes/index.js +6 -6
  215. package/dist/interchange/index.cjs +40 -40
  216. package/dist/interchange/index.d.cts +9 -10
  217. package/dist/interchange/index.d.ts +9 -10
  218. package/dist/interchange/index.js +14 -14
  219. package/dist/{manager-C7iC5bk_.d.ts → manager-Dl0-er1G.d.ts} +21 -156
  220. package/dist/{manager-Dm6MCYO7.d.cts → manager-U9_zopqr.d.cts} +21 -156
  221. package/dist/materialize-indexes-BM3u0aXE.d.ts +258 -0
  222. package/dist/materialize-indexes-DzMCetZe.d.cts +258 -0
  223. package/dist/{postgres-DZxwzCQ8.d.cts → postgres-C5-WMKFA.d.ts} +1 -1
  224. package/dist/{postgres-Cb6ceh4-.d.ts → postgres-DpJqtbSX.d.cts} +1 -1
  225. package/dist/profiler/index.d.cts +9 -10
  226. package/dist/profiler/index.d.ts +9 -10
  227. package/dist/provenance/index.cjs +39 -39
  228. package/dist/provenance/index.d.cts +7 -8
  229. package/dist/provenance/index.d.ts +7 -8
  230. package/dist/provenance/index.js +9 -9
  231. package/dist/schema/index.cjs +48 -39
  232. package/dist/schema/index.d.cts +7 -8
  233. package/dist/schema/index.d.ts +7 -8
  234. package/dist/schema/index.js +15 -14
  235. package/dist/{searchable-aUaKh3_r.d.cts → searchable-B4mUXZT6.d.cts} +2 -2
  236. package/dist/{searchable-Cet4Oztt.d.ts → searchable-C7jmPNLT.d.ts} +2 -2
  237. package/dist/{sqlite-Cb3Ilj9_.d.ts → sqlite-Ch5tSYQY.d.ts} +1 -1
  238. package/dist/{sqlite-Dxklpizv.d.cts → sqlite-Da7jiYu9.d.cts} +1 -1
  239. package/dist/{store-view-PCT7vTKH.d.cts → store-view-6C2vTWqf.d.ts} +8 -7
  240. package/dist/{store-view-BDjGFjpN.d.ts → store-view-CNcOG8bQ.d.cts} +8 -7
  241. package/dist/{temporal-CyFsSPe8.d.ts → temporal-BtrTYTiB.d.ts} +1 -1
  242. package/dist/{temporal-Dn_JADWY.d.cts → temporal-CMpigMCW.d.cts} +1 -1
  243. package/dist/{types-CFZiEEPh.d.ts → types-D2rU5Taq.d.ts} +1 -2
  244. package/dist/{types-D-vOo_pM.d.ts → types-Dh-EgT-w.d.cts} +569 -2
  245. package/dist/{types-ho4DJJb_.d.cts → types-Dh-EgT-w.d.ts} +569 -2
  246. package/dist/{types-CsaG00wS.d.cts → types-G4sVM-76.d.cts} +1 -2
  247. package/dist/{where-DLYaXa4L.d.ts → where-B8Y21kig.d.ts} +1 -2
  248. package/dist/{where-udes1WRA.d.cts → where-DbZ9XDOI.d.cts} +1 -2
  249. package/package.json +1 -1
  250. package/dist/chunk-5YBDB7UG.cjs +0 -12
  251. package/dist/chunk-DPNA466P.js.map +0 -1
  252. package/dist/chunk-EFZ4S22A.js.map +0 -1
  253. package/dist/chunk-IMQKXL4E.cjs +0 -12
  254. package/dist/chunk-JP5EICR6.cjs.map +0 -1
  255. package/dist/chunk-LOKG3KQV.cjs.map +0 -1
  256. package/dist/chunk-MQBF3XGY.js.map +0 -1
  257. package/dist/chunk-QXKVUJLI.cjs.map +0 -1
  258. package/dist/chunk-SAFZ6JTI.cjs.map +0 -1
  259. package/dist/chunk-UDS5DZNY.cjs.map +0 -1
  260. package/dist/chunk-V3S74J44.js.map +0 -1
  261. package/dist/chunk-W66YCXWT.js.map +0 -1
  262. package/dist/extension-types-BLEVH4SG.d.cts +0 -571
  263. package/dist/extension-types-BLEVH4SG.d.ts +0 -571
  264. package/dist/materialize-indexes-D4iei4Kp.d.ts +0 -90
  265. package/dist/materialize-indexes-ExQ6OrAh.d.cts +0 -90
@@ -285,6 +285,22 @@ var SchemaMismatchError = class extends TypeGraphError {
285
285
  this.name = "SchemaMismatchError";
286
286
  }
287
287
  };
288
+ var MIGRATION_FAILURE_REASONS = [
289
+ /**
290
+ * The persisted schema is behind the code graph. Raised on the
291
+ * least-privilege runtime path, which cannot run DDL — a privileged
292
+ * migrator must advance the schema first. Inspect `details.diff`
293
+ * (`hasBreakingChanges`) to tell an additive change from an incompatible
294
+ * one.
295
+ */
296
+ "schema-behind",
297
+ /** Breaking changes were detected while `throwOnBreaking` was set. */
298
+ "breaking-change",
299
+ /** No active schema version exists for the graph. */
300
+ "no-active-version",
301
+ /** The requested schema version does not exist for the graph. */
302
+ "version-not-found"
303
+ ];
288
304
  var MigrationError = class extends TypeGraphError {
289
305
  constructor(message, details, options) {
290
306
  super(message, "MIGRATION_ERROR", {
@@ -608,6 +624,7 @@ exports.EndpointNotFoundError = EndpointNotFoundError;
608
624
  exports.GraphAlgorithmConvergenceError = GraphAlgorithmConvergenceError;
609
625
  exports.InvalidEdgeWeightError = InvalidEdgeWeightError;
610
626
  exports.KindNotFoundError = KindNotFoundError;
627
+ exports.MIGRATION_FAILURE_REASONS = MIGRATION_FAILURE_REASONS;
611
628
  exports.MigrationError = MigrationError;
612
629
  exports.NodeConstraintNotFoundError = NodeConstraintNotFoundError;
613
630
  exports.NodeIndexNotFoundError = NodeIndexNotFoundError;
@@ -632,5 +649,5 @@ exports.isRecordedCaptureGuardError = isRecordedCaptureGuardError;
632
649
  exports.isSystemError = isSystemError;
633
650
  exports.isTypeGraphError = isTypeGraphError;
634
651
  exports.isUserRecoverable = isUserRecoverable;
635
- //# sourceMappingURL=chunk-SAFZ6JTI.cjs.map
636
- //# sourceMappingURL=chunk-SAFZ6JTI.cjs.map
652
+ //# sourceMappingURL=chunk-KTBTSHU6.cjs.map
653
+ //# sourceMappingURL=chunk-KTBTSHU6.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors/index.ts"],"names":[],"mappings":";;;AA0DA,SAAS,YAAY,KAAA,EAAwB;AAC3C,EAAA,IAAI,iBAAiB,KAAA,EAAO;AAC1B,IAAA,OAAO,KAAA,CAAM,SAAS,KAAA,CAAM,OAAA;AAAA,EAC9B;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,IACE,OAAO,UAAU,QAAA,IACjB,OAAO,UAAU,SAAA,IACjB,OAAO,UAAU,QAAA,EACjB;AACA,IAAA,OAAO,OAAO,KAAK,CAAA;AAAA,EACrB;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,MAAM,WAAA,IAAe,QAAA;AAAA,EAC9B;AACA,EAAA,IAAI,UAAU,MAAA,EAAW;AACvB,IAAA,OAAO,eAAA;AA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AAA;AACvD;AAKO,SAAS,mBAAmB,KAAA,EAAoC;AACrE,EAAA,OAAO,gBAAA,CAAiB,KAAK,CAAA,GAAI,KAAA,CAAM,UAAA,GAAa,MAAA;AACtD","file":"chunk-KTBTSHU6.cjs","sourcesContent":["/**\n * TypeGraph Error Hierarchy\n *\n * All errors extend TypeGraphError with:\n * - `code`: Machine-readable error code for programmatic handling\n * - `category`: Classification for error handling strategies\n * - `suggestion`: Optional recovery guidance for users\n * - `details`: Structured context about the error\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({ name: \"\" });\n * } catch (error) {\n * if (isTypeGraphError(error)) {\n * console.error(error.toUserMessage());\n * if (isUserRecoverable(error)) {\n * // Show to user for correction\n * }\n * }\n * }\n * ```\n */\n\nimport type { KindEntity } from \"../core/types\";\nimport type { SchemaDiff } from \"../schema/migration\";\n// Type-only import: `materialize-indexes.ts` value-imports\n// `ConfigurationError` from this file, but type-only imports are erased\n// at runtime so this back-edge does not create a value cycle.\nimport type { MaterializeIndexesResult } from \"../store/materialize-indexes\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Error category for programmatic handling.\n *\n * - `user`: Caused by invalid input or incorrect usage. Recoverable by fixing input.\n * - `constraint`: Business rule or schema constraint violation. Recoverable by changing data.\n * - `system`: Internal error or infrastructure issue. May require investigation or retry.\n */\nexport type ErrorCategory = \"user\" | \"constraint\" | \"system\";\n\n/**\n * Options for TypeGraphError constructor.\n */\nexport type TypeGraphErrorOptions = Readonly<{\n /** Structured context about the error */\n details?: Record<string, unknown>;\n /** Error category for handling strategies */\n category: ErrorCategory;\n /** Recovery guidance for users */\n suggestion?: string;\n /** Underlying cause of the error */\n cause?: unknown;\n}>;\n\nfunction formatCause(cause: unknown): string {\n if (cause instanceof Error) {\n return cause.stack ?? cause.message;\n }\n if (typeof cause === \"string\") {\n return cause;\n }\n if (\n typeof cause === \"number\" ||\n typeof cause === \"boolean\" ||\n typeof cause === \"bigint\"\n ) {\n return String(cause);\n }\n if (typeof cause === \"symbol\") {\n return cause.description ?? \"Symbol\";\n }\n if (cause === undefined) {\n return \"Unknown cause\";\n }\n\n try {\n return JSON.stringify(cause);\n } catch (error) {\n return `Unserializable cause: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`;\n }\n}\n\n// ============================================================\n// Base Error\n// ============================================================\n\n/**\n * Base error class for all TypeGraph errors.\n *\n * Provides structured error information for both programmatic handling\n * and user-friendly messages.\n */\nexport class TypeGraphError extends Error {\n /** Machine-readable error code (e.g., \"VALIDATION_ERROR\") */\n readonly code: string;\n\n /** Error category for handling strategies */\n readonly category: ErrorCategory;\n\n /** Structured context about the error */\n readonly details: Readonly<Record<string, unknown>>;\n\n /** Recovery guidance for users */\n readonly suggestion?: string;\n\n constructor(message: string, code: string, options: TypeGraphErrorOptions) {\n super(message, options.cause ? { cause: options.cause } : undefined);\n this.name = \"TypeGraphError\";\n this.code = code;\n this.category = options.category;\n this.details = Object.freeze(options.details ?? {});\n if (options.suggestion !== undefined) {\n this.suggestion = options.suggestion;\n }\n }\n\n /**\n * Returns a user-friendly error message with suggestion if available.\n */\n toUserMessage(): string {\n if (this.suggestion) {\n return `${this.message}\\n\\nSuggestion: ${this.suggestion}`;\n }\n return this.message;\n }\n\n /**\n * Returns a detailed string representation for logging.\n */\n toLogString(): string {\n const lines = [\n `[${this.code}] ${this.message}`,\n ` Category: ${this.category}`,\n ];\n\n if (this.suggestion) {\n lines.push(` Suggestion: ${this.suggestion}`);\n }\n\n const detailKeys = Object.keys(this.details);\n if (detailKeys.length > 0) {\n lines.push(` Details: ${JSON.stringify(this.details)}`);\n }\n\n if (this.cause) {\n lines.push(` Cause: ${formatCause(this.cause)}`);\n }\n\n return lines.join(\"\\n\");\n }\n}\n\n// ============================================================\n// Validation Errors (category: \"user\")\n// ============================================================\n\n/**\n * Validation issue from Zod or custom validation.\n */\nexport type ValidationIssue = Readonly<{\n /** Path to the invalid field (e.g., \"address.city\") */\n path: string;\n /** Human-readable error message */\n message: string;\n /** Zod error code if from Zod validation */\n code?: string;\n}>;\n\n/**\n * Details for ValidationError.\n */\nexport type ValidationErrorDetails = Readonly<{\n /** Type of entity being validated */\n entityType?: KindEntity;\n /** Kind/type name of the entity */\n kind?: string;\n /** Operation being performed */\n operation?: \"create\" | \"update\";\n /** Entity ID if updating */\n id?: string;\n /** Individual validation issues */\n issues: readonly ValidationIssue[];\n}>;\n\n/**\n * Thrown when schema validation fails during node or edge operations.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({ email: \"invalid\" });\n * } catch (error) {\n * if (error instanceof ValidationError) {\n * console.log(error.details.issues);\n * // [{ path: \"email\", message: \"Invalid email\" }]\n * }\n * }\n * ```\n */\nexport class ValidationError extends TypeGraphError {\n declare readonly details: ValidationErrorDetails;\n\n constructor(\n message: string,\n details: ValidationErrorDetails,\n options?: { cause?: unknown; suggestion?: string },\n ) {\n const fieldList =\n details.issues.length > 0 ?\n details.issues.map((index) => index.path || \"(root)\").join(\", \")\n : \"unknown\";\n\n super(message, \"VALIDATION_ERROR\", {\n details,\n category: \"user\",\n suggestion:\n options?.suggestion ??\n `Check the following fields: ${fieldList}. See error.details.issues for specific validation failures.`,\n cause: options?.cause,\n });\n this.name = \"ValidationError\";\n }\n}\n\n// ============================================================\n// Not Found Errors (category: \"user\")\n// ============================================================\n\n/**\n * Details for NodeNotFoundError.\n */\nexport type NodeNotFoundErrorDetails = Readonly<{\n kind: string;\n id: string;\n}>;\n\n/**\n * Thrown when a node is not found.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.get(\"nonexistent-id\");\n * } catch (error) {\n * if (error instanceof NodeNotFoundError) {\n * console.log(error.details.kind, error.details.id);\n * }\n * }\n * ```\n */\nexport class NodeNotFoundError extends TypeGraphError {\n declare readonly details: NodeNotFoundErrorDetails;\n\n constructor(kind: string, id: string, options?: { cause?: unknown }) {\n super(`Node not found: ${kind}/${id}`, \"NODE_NOT_FOUND\", {\n details: { kind, id },\n category: \"user\",\n suggestion: `Verify the node ID \"${id}\" exists and has not been deleted.`,\n cause: options?.cause,\n });\n this.name = \"NodeNotFoundError\";\n }\n}\n\n/**\n * Details for EdgeNotFoundError.\n */\nexport type EdgeNotFoundErrorDetails = Readonly<{\n kind: string;\n id: string;\n}>;\n\n/**\n * Thrown when an edge is not found.\n */\nexport class EdgeNotFoundError extends TypeGraphError {\n declare readonly details: EdgeNotFoundErrorDetails;\n\n constructor(kind: string, id: string, options?: { cause?: unknown }) {\n super(`Edge not found: ${kind}/${id}`, \"EDGE_NOT_FOUND\", {\n details: { kind, id },\n category: \"user\",\n suggestion: `Verify the edge ID \"${id}\" exists and has not been deleted.`,\n cause: options?.cause,\n });\n this.name = \"EdgeNotFoundError\";\n }\n}\n\n/**\n * Details for KindNotFoundError.\n */\nexport type KindNotFoundErrorDetails = Readonly<{\n kindName: string;\n entity: KindEntity;\n graphId?: string;\n}>;\n\n/**\n * Thrown when an operation references a kind that isn't registered on\n * the graph — `getNodeCollectionOrThrow` against an unknown kind, a\n * `materializeIndexes({ kinds })` filter naming a missing kind, an\n * extension referencing an unresolved endpoint, search facade typos,\n * etc. Carries the offending `kindName` and `entity` plus the host\n * `graphId` so logs are unambiguous when multiple stores share a\n * process.\n */\nexport class KindNotFoundError extends TypeGraphError {\n declare readonly details: KindNotFoundErrorDetails;\n readonly kindName: string;\n readonly entity: KindEntity;\n\n constructor(\n kindName: string,\n entity: KindEntity,\n options?: Readonly<{\n graphId?: string;\n suggestion?: string;\n cause?: unknown;\n }>,\n ) {\n const where =\n options?.graphId === undefined ? \"\" : ` on graph \"${options.graphId}\"`;\n super(\n `${entity === \"node\" ? \"Node\" : \"Edge\"} kind \"${kindName}\" is not registered${where}.`,\n \"KIND_NOT_FOUND\",\n {\n details: {\n kindName,\n entity,\n ...(options?.graphId === undefined ?\n {}\n : { graphId: options.graphId }),\n },\n category: \"user\",\n suggestion:\n options?.suggestion ??\n \"Compile-time kinds come from defineGraph; extension kinds appear after store.evolve() returns. Check store.introspect() for the registered set.\",\n cause: options?.cause,\n },\n );\n this.name = \"KindNotFoundError\";\n this.kindName = kindName;\n this.entity = entity;\n }\n}\n\n/**\n * Details for NodeConstraintNotFoundError.\n */\nexport type NodeConstraintNotFoundErrorDetails = Readonly<{\n constraintName: string;\n kind: string;\n}>;\n\n/**\n * Thrown when a uniqueness constraint name is not found on a node kind.\n */\nexport class NodeConstraintNotFoundError extends TypeGraphError {\n declare readonly details: NodeConstraintNotFoundErrorDetails;\n\n constructor(\n constraintName: string,\n kind: string,\n options?: { cause?: unknown },\n ) {\n super(\n `Constraint not found: \"${constraintName}\" on node kind \"${kind}\"`,\n \"CONSTRAINT_NOT_FOUND\",\n {\n details: { constraintName, kind },\n category: \"user\",\n suggestion: `Verify the constraint name \"${constraintName}\" is defined in the unique constraints for \"${kind}\".`,\n cause: options?.cause,\n },\n );\n this.name = \"NodeConstraintNotFoundError\";\n }\n}\n\n/**\n * Details for NodeIndexNotFoundError.\n */\nexport type NodeIndexNotFoundErrorDetails = Readonly<{\n indexName: string;\n kind: string;\n}>;\n\n/**\n * Thrown when a declared node index name is not found on a node kind.\n */\nexport class NodeIndexNotFoundError extends TypeGraphError {\n declare readonly details: NodeIndexNotFoundErrorDetails;\n\n constructor(indexName: string, kind: string, options?: { cause?: unknown }) {\n super(\n `Index not found: \"${indexName}\" on node kind \"${kind}\"`,\n \"INDEX_NOT_FOUND\",\n {\n details: { indexName, kind },\n category: \"user\",\n suggestion: `Verify the index name \"${indexName}\" is declared via defineNodeIndex for \"${kind}\" and passed to defineGraph({ indexes }).`,\n cause: options?.cause,\n },\n );\n this.name = \"NodeIndexNotFoundError\";\n }\n}\n\n// ============================================================\n// Constraint Errors (category: \"constraint\")\n// ============================================================\n\n/**\n * Details for EndpointNotFoundError.\n */\nexport type EndpointNotFoundErrorDetails = Readonly<{\n edgeKind: string;\n endpoint: \"from\" | \"to\";\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * Thrown when edge endpoint node does not exist or is deleted.\n */\nexport class EndpointNotFoundError extends TypeGraphError {\n declare readonly details: EndpointNotFoundErrorDetails;\n\n constructor(\n details: EndpointNotFoundErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Endpoint node not found for edge \"${details.edgeKind}\": ${details.nodeKind}/${details.nodeId} (${details.endpoint})`,\n \"ENDPOINT_NOT_FOUND\",\n {\n details,\n category: \"constraint\",\n suggestion: `Ensure the ${details.endpoint} node exists before creating the edge.`,\n cause: options?.cause,\n },\n );\n this.name = \"EndpointNotFoundError\";\n }\n}\n\n/**\n * Details for EndpointError.\n */\nexport type EndpointErrorDetails = Readonly<{\n edgeKind: string;\n endpoint: \"from\" | \"to\";\n actualKind: string;\n expectedKinds: readonly string[];\n}>;\n\n/**\n * Thrown when edge endpoint has wrong node type.\n */\nexport class EndpointError extends TypeGraphError {\n declare readonly details: EndpointErrorDetails;\n\n constructor(details: EndpointErrorDetails, options?: { cause?: unknown }) {\n const expected = details.expectedKinds.join(\" | \");\n super(\n `Invalid ${details.endpoint} endpoint for edge \"${details.edgeKind}\": got \"${details.actualKind}\", expected ${expected}`,\n \"ENDPOINT_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion: `Use a node of type ${expected} as the ${details.endpoint} endpoint.`,\n cause: options?.cause,\n },\n );\n this.name = \"EndpointError\";\n }\n}\n\n/**\n * Details for UniquenessError.\n */\nexport type UniquenessErrorDetails = Readonly<{\n constraintName: string;\n kind: string;\n existingId: string;\n newId: string;\n fields: readonly string[];\n}>;\n\n/**\n * Thrown when uniqueness constraint is violated.\n */\nexport class UniquenessError extends TypeGraphError {\n declare readonly details: UniquenessErrorDetails;\n\n constructor(details: UniquenessErrorDetails, options?: { cause?: unknown }) {\n const fieldList = details.fields.join(\", \");\n super(\n `Uniqueness violation on \"${details.kind}\": constraint \"${details.constraintName}\" (fields: ${fieldList}) conflicts with existing node ${details.existingId}`,\n \"UNIQUENESS_VIOLATION\",\n {\n details,\n category: \"constraint\",\n suggestion: `Change the values for fields [${fieldList}] to be unique, or update the existing node ${details.existingId} instead.`,\n cause: options?.cause,\n },\n );\n this.name = \"UniquenessError\";\n }\n}\n\n/**\n * Details for CardinalityError.\n */\nexport type CardinalityErrorDetails = Readonly<{\n edgeKind: string;\n fromKind: string;\n fromId: string;\n cardinality: string;\n existingCount: number;\n}>;\n\n/**\n * Thrown when cardinality constraint is violated.\n */\nexport class CardinalityError extends TypeGraphError {\n declare readonly details: CardinalityErrorDetails;\n\n constructor(details: CardinalityErrorDetails, options?: { cause?: unknown }) {\n super(\n `Cardinality violation: \"${details.edgeKind}\" from ${details.fromKind}/${details.fromId} allows \"${details.cardinality}\" but ${details.existingCount} edge(s) already exist`,\n \"CARDINALITY_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion:\n details.cardinality === \"one\" || details.cardinality === \"unique\" ?\n `Delete the existing edge before creating a new one, or use cardinality \"many\".`\n : `Check if the cardinality constraint \"${details.cardinality}\" is correct for your use case.`,\n cause: options?.cause,\n },\n );\n this.name = \"CardinalityError\";\n }\n}\n\n/**\n * Details for DisjointError.\n */\nexport type DisjointErrorDetails = Readonly<{\n nodeId: string;\n attemptedKind: string;\n conflictingKind: string;\n}>;\n\n/**\n * Thrown when disjointness constraint is violated.\n *\n * Disjoint types cannot share the same ID - a node cannot be both\n * a Person and an Organization if they are declared disjoint.\n */\nexport class DisjointError extends TypeGraphError {\n declare readonly details: DisjointErrorDetails;\n\n constructor(details: DisjointErrorDetails, options?: { cause?: unknown }) {\n super(\n `Disjoint constraint violation: cannot create ${details.attemptedKind} with ID \"${details.nodeId}\" - conflicts with existing ${details.conflictingKind}`,\n \"DISJOINT_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion: `Use a different ID for the new ${details.attemptedKind} node, or delete the existing ${details.conflictingKind}/${details.nodeId} first.`,\n cause: options?.cause,\n },\n );\n this.name = \"DisjointError\";\n }\n}\n\n/**\n * Details for RestrictedDeleteError.\n */\nexport type RestrictedDeleteErrorDetails = Readonly<{\n nodeKind: string;\n nodeId: string;\n edgeCount: number;\n edgeKinds: readonly string[];\n}>;\n\n/**\n * Thrown when deletion is blocked due to existing edges (restrict behavior).\n */\nexport class RestrictedDeleteError extends TypeGraphError {\n declare readonly details: RestrictedDeleteErrorDetails;\n\n constructor(\n details: RestrictedDeleteErrorDetails,\n options?: { cause?: unknown },\n ) {\n const edgeList = details.edgeKinds.join(\", \");\n super(\n `Cannot delete ${details.nodeKind}/${details.nodeId}: ${details.edgeCount} connected edge(s) exist (${edgeList})`,\n \"RESTRICTED_DELETE\",\n {\n details,\n category: \"constraint\",\n suggestion: `Delete the connected edges first, or change onDelete behavior to \"cascade\" (auto-delete edges) or \"disconnect\" (soft-delete edges).`,\n cause: options?.cause,\n },\n );\n this.name = \"RestrictedDeleteError\";\n }\n}\n\n// ============================================================\n// Concurrency Errors (category: \"system\")\n// ============================================================\n\n/**\n * Details for VersionConflictError.\n */\nexport type VersionConflictErrorDetails = Readonly<{\n kind: string;\n id: string;\n expectedVersion: number;\n actualVersion: number;\n}>;\n\n/**\n * Thrown when optimistic locking detects a concurrent modification.\n *\n * This occurs when two operations try to update the same entity simultaneously.\n * The operation with the stale version fails.\n */\nexport class VersionConflictError extends TypeGraphError {\n declare readonly details: VersionConflictErrorDetails;\n\n constructor(\n details: VersionConflictErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Version conflict on ${details.kind}/${details.id}: expected version ${details.expectedVersion}, found ${details.actualVersion}`,\n \"VERSION_CONFLICT\",\n {\n details,\n category: \"system\",\n suggestion: `Fetch the latest version of the entity and retry the operation. This error indicates concurrent modification.`,\n cause: options?.cause,\n },\n );\n this.name = \"VersionConflictError\";\n }\n}\n\n// ============================================================\n// Schema Errors (category: \"system\")\n// ============================================================\n\n/**\n * Details for SchemaMismatchError.\n */\nexport type SchemaMismatchErrorDetails = Readonly<{\n graphId: string;\n expectedHash: string;\n actualHash: string;\n}>;\n\n/**\n * Thrown when the schema in code doesn't match the schema in the database.\n */\nexport class SchemaMismatchError extends TypeGraphError {\n declare readonly details: SchemaMismatchErrorDetails;\n\n constructor(\n details: SchemaMismatchErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema mismatch for graph \"${details.graphId}\": code schema differs from database schema`,\n \"SCHEMA_MISMATCH\",\n {\n details,\n category: \"system\",\n suggestion: `Run schema migration to update the database, or use createStoreWithSchema() for automatic migration.`,\n cause: options?.cause,\n },\n );\n this.name = \"SchemaMismatchError\";\n }\n}\n\n/**\n * Details for MigrationError.\n */\n/**\n * Why a migration operation failed. A stable discriminant so callers can\n * branch on the outcome instead of matching the message text, which is free\n * to be reworded in any release.\n */\nexport const MIGRATION_FAILURE_REASONS = [\n /**\n * The persisted schema is behind the code graph. Raised on the\n * least-privilege runtime path, which cannot run DDL — a privileged\n * migrator must advance the schema first. Inspect `details.diff`\n * (`hasBreakingChanges`) to tell an additive change from an incompatible\n * one.\n */\n \"schema-behind\",\n /** Breaking changes were detected while `throwOnBreaking` was set. */\n \"breaking-change\",\n /** No active schema version exists for the graph. */\n \"no-active-version\",\n /** The requested schema version does not exist for the graph. */\n \"version-not-found\",\n] as const;\n\nexport type MigrationFailureReason = (typeof MIGRATION_FAILURE_REASONS)[number];\n\nexport type MigrationErrorDetails = Readonly<{\n graphId: string;\n fromVersion: number;\n toVersion: number;\n /** Stable discriminant for the failure — branch on this, not the message. */\n reason: MigrationFailureReason;\n /**\n * The structured diff behind the failure, when one was computed\n * (`schema-behind` and `breaking-change`). Carries per-change `severity`\n * alongside `hasChanges` / `hasBreakingChanges`, so a caller can decide\n * \"additive → proceed, incompatible → ask the user\" without re-querying.\n */\n diff?: SchemaDiff;\n}>;\n\n/**\n * Thrown when schema migration fails.\n */\nexport class MigrationError extends TypeGraphError {\n declare readonly details: MigrationErrorDetails;\n\n constructor(\n message: string,\n details: MigrationErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(message, \"MIGRATION_ERROR\", {\n details,\n category: \"system\",\n suggestion: `Review the schema changes and ensure they are backwards compatible, or implement a data migration.`,\n cause: options?.cause,\n });\n this.name = \"MigrationError\";\n }\n}\n\n/**\n * Details for EagerMaterializationError.\n */\nexport type EagerMaterializationErrorDetails = Readonly<{\n graphId: string;\n failedIndexNames: readonly string[];\n}>;\n\n/**\n * Thrown by `Store.evolve(extension, { eager })` when the schema\n * commit succeeded but the follow-on `materializeIndexes()` produced\n * one or more failed entries.\n *\n * Recovery: the schema commit is NOT rolled back. The new `Store` is\n * fully constructed and (when `options.ref` was supplied) `ref.current`\n * already points to it — the caller can read the new store via the ref\n * and decide how to handle the failed indexes (retry, skip, alert).\n * The full `MaterializeIndexesResult` is attached as `.materialization`.\n *\n * @example\n * ```ts\n * const ref = { current: store };\n * try {\n * await store.evolve(extension, { ref, eager: {} });\n * } catch (error) {\n * if (error instanceof EagerMaterializationError) {\n * // schema is committed; ref.current is the new store\n * log.warn(\n * { failed: error.failedIndexNames },\n * \"indexes did not materialize; will retry\",\n * );\n * await ref.current.materializeIndexes();\n * } else {\n * throw error;\n * }\n * }\n * ```\n */\nexport class EagerMaterializationError extends TypeGraphError {\n declare readonly details: EagerMaterializationErrorDetails;\n\n /**\n * The full materialization result, including successful and failed\n * entries. Same shape as `Store.materializeIndexes()` returns.\n */\n readonly materialization: MaterializeIndexesResult;\n\n constructor(materialization: MaterializeIndexesResult, graphId: string) {\n const names = collectFailedIndexNames(materialization);\n super(\n `Eager materialization failed for ${names.length} index(es) on graph \"${graphId}\": ${names.join(\", \")}. The schema commit succeeded; the new Store is available via the ref handle (when supplied) and the failed indexes can be retried via store.materializeIndexes().`,\n \"EAGER_MATERIALIZATION_FAILED\",\n {\n details: { graphId, failedIndexNames: names },\n category: \"system\",\n suggestion: `Inspect error.materialization for per-index errors. Each failure preserves any prior successful materialization timestamp; the schema is committed regardless.`,\n },\n );\n this.name = \"EagerMaterializationError\";\n this.materialization = materialization;\n }\n\n /**\n * Names of just the indexes that failed — derived from\n * `materialization.results` so the two views can never disagree.\n */\n get failedIndexNames(): readonly string[] {\n return collectFailedIndexNames(this.materialization);\n }\n}\n\nfunction collectFailedIndexNames(\n materialization: MaterializeIndexesResult,\n): readonly string[] {\n const names: string[] = [];\n for (const entry of materialization.results) {\n if (entry.status === \"failed\") names.push(entry.indexName);\n }\n return names;\n}\n\n/**\n * Details for StaleVersionError. `actual` is `0` when no active version\n * exists yet (initial-commit race where another writer initialized first).\n */\nexport type StaleVersionErrorDetails = Readonly<{\n graphId: string;\n expected: number;\n actual: number;\n}>;\n\n/**\n * Thrown by `commitSchemaVersion` and `setActiveVersion` when the\n * caller's view of the active schema version is out of date — another\n * writer has already advanced it.\n *\n * Recovery: re-read the active version with `getActiveSchema(graphId)`,\n * recompute against the new baseline, and retry. This is a routine\n * concurrency signal, not a bug.\n */\nexport class StaleVersionError extends TypeGraphError {\n declare readonly details: StaleVersionErrorDetails;\n\n constructor(\n details: StaleVersionErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema version was advanced by another writer for graph \"${details.graphId}\": expected active version ${details.expected}, actual is ${details.actual}`,\n \"STALE_SCHEMA_VERSION\",\n {\n details,\n category: \"system\",\n suggestion: `Re-read the active schema version, recompute the new version against that baseline, and retry the commit.`,\n cause: options?.cause,\n },\n );\n this.name = \"StaleVersionError\";\n }\n}\n\n/**\n * Details for SchemaContentConflictError.\n */\nexport type SchemaContentConflictErrorDetails = Readonly<{\n graphId: string;\n version: number;\n existingHash: string;\n incomingHash: string;\n}>;\n\n/**\n * Thrown by `commitSchemaVersion` when a row already exists at the\n * target version with a *different* schema hash — i.e. two writers\n * committed materially different schemas at the same version number.\n *\n * Distinct from `StaleVersionError`: this is not a refetch-and-retry\n * situation, it's a content disagreement that needs operator\n * intervention. Typically caused by inconsistent application\n * deployments writing schemas that hash differently.\n */\nexport class SchemaContentConflictError extends TypeGraphError {\n declare readonly details: SchemaContentConflictErrorDetails;\n\n constructor(\n details: SchemaContentConflictErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema content conflict for graph \"${details.graphId}\" at version ${details.version}: existing hash ${details.existingHash} differs from incoming hash ${details.incomingHash}`,\n \"SCHEMA_CONTENT_CONFLICT\",\n {\n details,\n category: \"system\",\n suggestion: `Two writers committed different schemas at the same version. Reconcile the application deployments so they produce the same canonical schema, then retry.`,\n cause: options?.cause,\n },\n );\n this.name = \"SchemaContentConflictError\";\n }\n}\n\n// ============================================================\n// Configuration Errors (category: \"user\")\n// ============================================================\n\n/**\n * Thrown when graph configuration is invalid.\n *\n * This includes invalid schema definitions, ontology conflicts,\n * and other configuration issues detected at graph creation time.\n */\nexport class ConfigurationError extends TypeGraphError {\n constructor(\n message: string,\n details: Record<string, unknown> = {},\n options?: { cause?: unknown; suggestion?: string },\n ) {\n super(message, \"CONFIGURATION_ERROR\", {\n details,\n category: \"user\",\n suggestion:\n options?.suggestion ?? `Review your graph definition for errors.`,\n cause: options?.cause,\n });\n this.name = \"ConfigurationError\";\n }\n}\n\n/**\n * Thrown when an iterative graph algorithm exhausts its caller-visible round\n * budget before reaching its convergence predicate.\n */\nexport class GraphAlgorithmConvergenceError extends TypeGraphError {\n constructor(\n algorithm: string,\n maxIterations: number,\n options: Readonly<{ oscillating?: boolean }> = {},\n ) {\n const oscillating = options.oscillating === true;\n super(\n oscillating ?\n `${algorithm} entered a periodic label oscillation and can never converge.`\n : `${algorithm} did not converge within ${maxIterations} iterations.`,\n \"GRAPH_ALGORITHM_CONVERGENCE_ERROR\",\n {\n details: {\n algorithm,\n maxIterations,\n ...(oscillating ? { oscillating } : {}),\n },\n category: \"user\",\n suggestion:\n oscillating ?\n 'Pass onMaxIterations: \"return\" to accept the fixed-round labeling, or exclude the oscillating component from the selection.'\n : \"Increase maxIterations or reduce the selected graph before retrying.\",\n },\n );\n this.name = \"GraphAlgorithmConvergenceError\";\n }\n}\n\n/** Stable reasons a weighted traversal can reject an edge's weight value. */\nexport type InvalidEdgeWeightReason =\n \"missing\" | \"negative\" | \"non_numeric\" | \"out_of_range\";\n\n/** Details for InvalidEdgeWeightError. */\nexport type InvalidEdgeWeightErrorDetails = Readonly<{\n /** Id of the first offending edge, in binary-collation order. */\n edgeId: string;\n /** Kind of the offending edge. */\n edgeKind: string;\n /** The audited weight property. */\n property: string;\n /** Why the weight was rejected. */\n reason: InvalidEdgeWeightReason;\n /** The offending value, when one was present and renderable. */\n value?: string;\n}>;\n\nconst EDGE_WEIGHT_REASONS: Readonly<\n Record<\n InvalidEdgeWeightReason,\n Readonly<{ message: string; suggestion: string }>\n >\n> = {\n missing: {\n message: \"has no value for weight property\",\n suggestion:\n \"Set the property on every selected edge, or provide defaultWeight for edges without it.\",\n },\n negative: {\n message: \"has a negative value for weight property\",\n suggestion:\n \"Weighted traversal requires non-negative weights; repair the edge data before retrying.\",\n },\n non_numeric: {\n message: \"has a non-numeric value for weight property\",\n suggestion:\n \"Store the weight property as a JSON number on every selected edge before retrying.\",\n },\n out_of_range: {\n message: \"has a value outside the supported range for weight property\",\n suggestion:\n \"Keep weight magnitudes within the range weightedShortestPath documents (large enough to be a normal IEEE 754 double, small enough that path sums cannot overflow).\",\n },\n};\n\n/**\n * Thrown when a weighted graph algorithm finds an edge whose weight property\n * violates the weighted-traversal contract (missing without a default,\n * non-numeric, or negative). Raised before any traversal rounds run, so a\n * weighted call either observes a fully valid weight domain or fails fast.\n */\nexport class InvalidEdgeWeightError extends TypeGraphError {\n declare readonly details: InvalidEdgeWeightErrorDetails;\n\n constructor(details: InvalidEdgeWeightErrorDetails) {\n super(\n `Edge '${details.edgeId}' (kind '${details.edgeKind}') ${EDGE_WEIGHT_REASONS[details.reason].message} '${details.property}'${\n details.value === undefined ? \"\" : ` (value: ${details.value})`\n }.`,\n \"INVALID_EDGE_WEIGHT\",\n {\n details: { ...details },\n category: \"user\",\n suggestion: EDGE_WEIGHT_REASONS[details.reason].suggestion,\n },\n );\n this.name = \"InvalidEdgeWeightError\";\n }\n}\n\n/** Thrown when an operation requires a backend capability it does not expose. */\nexport class UnsupportedBackendCapabilityError extends TypeGraphError {\n constructor(\n operation: string,\n capability: string,\n details: Readonly<Record<string, unknown>> = {},\n suggestion?: string,\n ) {\n super(\n `${operation} requires backend capability '${capability}'.`,\n \"UNSUPPORTED_BACKEND_CAPABILITY\",\n {\n details: { operation, capability, ...details },\n category: \"user\",\n suggestion:\n suggestion ??\n \"Use a backend that advertises this capability before invoking the operation.\",\n },\n );\n this.name = \"UnsupportedBackendCapabilityError\";\n }\n}\n\n/** Stable reasons an intentionally trusted initial import can be rejected. */\nexport type TrustedImportErrorReason =\n | \"backend_unsupported\"\n | \"database_not_empty\"\n | \"fulltext_unsupported\"\n | \"history_unsupported\"\n | \"invalid_stream\"\n | \"revision_tracking_unsupported\"\n | \"uniqueness_unsupported\"\n | \"vector_unsupported\";\n\n/** Thrown when the trusted initial-import contract is unavailable or violated. */\nexport class TrustedImportError extends TypeGraphError {\n constructor(\n message: string,\n reason: TrustedImportErrorReason,\n details: Readonly<Record<string, unknown>> = {},\n options?: Readonly<{ cause?: unknown; suggestion?: string }>,\n ) {\n super(message, \"TRUSTED_IMPORT_ERROR\", {\n details: { ...details, reason },\n category: \"user\",\n suggestion:\n options?.suggestion ??\n \"Use the validating bulk or interchange import APIs unless every trusted-import precondition is satisfied.\",\n cause: options?.cause,\n });\n this.name = \"TrustedImportError\";\n }\n}\n\n/**\n * The stable `details.code` values raised by the recorded-capture guards on a\n * history- or revision-tracked store. These are the sanctioned branch points\n * for a portable caller that must pick a transaction strategy without\n * substring-matching {@link ConfigurationError} messages.\n *\n * - `RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION`: `store.withTransaction`\n * was called on a history-enabled store, which has no flush point before the\n * caller commits — use `store.withRecordedTransaction` instead.\n * - `RECORDED_CAPTURE_RAW_SQL_DISABLED`: a raw SQL escape (`tx.sql`,\n * `backend.executeStatement`/`executeDdl`) was reached on a history-enabled\n * store, where it would bypass recorded-time capture.\n * - `REVISION_TRACKING_RAW_SQL_DISABLED`: the same raw SQL escape on a\n * revision-tracked store, where it would bypass the revision anchor.\n *\n * @see isRecordedCaptureGuardError\n */\nexport const RECORDED_CAPTURE_GUARD_CODES = [\n \"RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION\",\n \"RECORDED_CAPTURE_RAW_SQL_DISABLED\",\n \"REVISION_TRACKING_RAW_SQL_DISABLED\",\n] as const;\n\n/** A stable, branchable code raised by a recorded-capture guard. */\nexport type RecordedCaptureGuardCode =\n (typeof RECORDED_CAPTURE_GUARD_CODES)[number];\n\n/**\n * A {@link ConfigurationError} narrowed to carry a {@link RecordedCaptureGuardCode}\n * in `details.code` — the shape {@link isRecordedCaptureGuardError} guarantees.\n * `C` narrows `details.code` to a single code when the guard was called with a\n * specific one; it defaults to the full union.\n */\nexport type RecordedCaptureGuardError<\n C extends RecordedCaptureGuardCode = RecordedCaptureGuardCode,\n> = ConfigurationError & Readonly<{ details: Readonly<{ code: C }> }>;\n\nfunction isRecordedCaptureGuardCode(\n value: unknown,\n): value is RecordedCaptureGuardCode {\n // Widen the readonly tuple so `includes` accepts an `unknown` needle.\n return (RECORDED_CAPTURE_GUARD_CODES as readonly unknown[]).includes(value);\n}\n\n/**\n * Type guard for the recorded-capture guard errors, so a portable caller can\n * branch on the invariant a store enforced instead of substring-matching the\n * message. Pass `code` to narrow to a single guard; omit it to match any.\n *\n * Distinguishes \"history capture forbids raw SQL here\" from \"this backend has\n * no transactions\" (the latter carries no guard code — see\n * `TransactionContext.sqlAvailability` for the capability discriminant).\n *\n * Passing `code` also narrows `details.code` to that literal on the guarded\n * branch, so a caller can read the payload without re-checking.\n *\n * @example\n * ```typescript\n * // `withTransaction` is a compile error on a history-enabled store, so widen\n * // to the base Store surface to reach the runtime guard this branches on.\n * const store: Store<typeof graph> = historyStore;\n * try {\n * store.withTransaction(externalTx);\n * } catch (error) {\n * if (\n * isRecordedCaptureGuardError(\n * error,\n * \"RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION\",\n * )\n * ) {\n * // error.details.code is now the literal, not the union.\n * await historyStore.withRecordedTransaction(externalTx, run);\n * } else {\n * throw error;\n * }\n * }\n * ```\n */\nexport function isRecordedCaptureGuardError<C extends RecordedCaptureGuardCode>(\n error: unknown,\n code: C,\n): error is RecordedCaptureGuardError<C>;\nexport function isRecordedCaptureGuardError(\n error: unknown,\n): error is RecordedCaptureGuardError;\nexport function isRecordedCaptureGuardError(\n error: unknown,\n code?: RecordedCaptureGuardCode,\n): error is RecordedCaptureGuardError {\n if (!(error instanceof ConfigurationError)) return false;\n const actual = error.details[\"code\"];\n if (!isRecordedCaptureGuardCode(actual)) return false;\n return code === undefined || actual === code;\n}\n\n/**\n * Why a store's strategy-owned storage is not usable on the current\n * connection. Drives the {@link StoreNotInitializedError} message and\n * is surfaced in `details.reason` for programmatic handling.\n *\n * - `missing`: no durable materialization marker exists — the database\n * was never initialized for this graph's runtime contributions.\n * - `stale`: a marker exists but its recorded signature no longer\n * matches the resolved contribution DDL (strategy swap or DDL drift).\n * The hot path refuses rather than silently re-materializing.\n * - `failed`: the most recent boot-time materialization attempt\n * recorded an error. Boot may retry; the hot path refuses.\n */\nexport type StoreNotInitializedReason = \"missing\" | \"stale\" | \"failed\";\n\nconst STORE_NOT_INITIALIZED_REASON_PHRASE: Readonly<\n Record<StoreNotInitializedReason, string>\n> = {\n missing: \"is not initialized\",\n stale: \"is stale (recorded materialization signature no longer matches)\",\n failed: \"failed its last initialization attempt\",\n};\n\n/**\n * Details for StoreNotInitializedError. `graphId`/`reason` are always\n * present; callers may merge additional context (e.g. `logicalName`) via\n * `options.details`.\n */\nexport type StoreNotInitializedErrorDetails = Readonly<{\n graphId: string;\n reason: StoreNotInitializedReason;\n}> &\n Readonly<Record<string, unknown>>;\n\n/**\n * Thrown when a fulltext- or vector-dependent operation runs against a\n * connection whose strategy-owned storage has not been durably materialized.\n *\n * `createStore()` is a synchronous, zero-I/O attach: it never creates\n * tables, repairs DDL, or writes materialization markers. The durable\n * marker is written exclusively by the async boot path\n * (`createStoreWithSchema`). When a fulltext or embedding read/write — or\n * an adopted/business transaction — observes no valid marker, it refuses\n * loudly here instead of lazily emitting DDL on the hot path.\n */\nexport class StoreNotInitializedError extends TypeGraphError {\n declare readonly details: StoreNotInitializedErrorDetails;\n\n // `graphId`/`reason` are positional and required: both are\n // load-bearing for the message and for programmatic handling via\n // `details.reason`. Caller `details` merge underneath — spread first\n // so `graphId`/`reason` win and can't be clobbered by an\n // accidentally-colliding extra key.\n constructor(\n graphId: string,\n reason: StoreNotInitializedReason,\n options?: {\n cause?: unknown;\n details?: Readonly<Record<string, unknown>> &\n Readonly<{ graphId?: never; reason?: never }>;\n },\n ) {\n super(\n `${storageLabelFromLogicalName(options?.details?.[\"logicalName\"])} for ` +\n `graph \"${graphId}\" ${STORE_NOT_INITIALIZED_REASON_PHRASE[reason]}. ` +\n storeNotInitializedAction(reason, options?.details?.[\"logicalName\"]),\n \"STORE_NOT_INITIALIZED\",\n {\n details: { ...options?.details, graphId, reason },\n category: \"user\",\n suggestion:\n isStaleVectorSlot(reason, options?.details?.[\"logicalName\"]) ?\n \"The field's declared shape (e.g. its dimension) changed after \" +\n \"its storage was provisioned. Run store.reembedVectorField(\" +\n \"kind, fieldPath) to recreate the storage at the new shape and \" +\n \"re-embed.\"\n : \"Call createStoreWithSchema(graph, backend) once at application \" +\n \"startup. createStore() attaches to an already-initialized \" +\n \"database and does not materialize storage itself.\",\n cause: options?.cause,\n },\n );\n this.name = \"StoreNotInitializedError\";\n }\n}\n\nconst VECTOR_LOGICAL_NAME_PREFIX = \"vector:\";\n\n/**\n * A stale VECTOR slot is its own failure mode: the storage exists but was\n * provisioned at a different shape (the declared dimension changed), and\n * the fix is `store.reembedVectorField`, not a re-run of\n * `createStoreWithSchema` (whose boot pass deliberately skips drifted\n * slots). Drives the action sentence and the suggestion.\n */\nfunction isStaleVectorSlot(\n reason: StoreNotInitializedReason,\n logicalName: unknown,\n): boolean {\n return (\n reason === \"stale\" &&\n typeof logicalName === \"string\" &&\n logicalName.startsWith(VECTOR_LOGICAL_NAME_PREFIX)\n );\n}\n\n/** The actionable trailing sentence of the error message, per failure mode. */\nfunction storeNotInitializedAction(\n reason: StoreNotInitializedReason,\n logicalName: unknown,\n): string {\n if (isStaleVectorSlot(reason, logicalName)) {\n return (\n `The declared shape changed after provisioning — run ` +\n `store.reembedVectorField(kind, fieldPath) to recreate the storage ` +\n `at the new shape.`\n );\n }\n return (\n `Run createStoreWithSchema(graph, backend) during application boot, ` +\n `outside request handlers and adopted transactions, before using createStore().`\n );\n}\n\n/**\n * Human label for the un-materialized storage, derived from the\n * contribution `logicalName`: fulltext keeps \"fulltext storage\"; a vector\n * slot (\"vector:&lt;kind&gt;.&lt;field&gt;\") reads as `vector storage\n * \"&lt;kind&gt;.&lt;field&gt;\"` so the message names the exact embedding\n * field. Falls back to a neutral phrase when no logical name is supplied.\n */\nfunction storageLabelFromLogicalName(logicalName: unknown): string {\n if (typeof logicalName !== \"string\") return \"runtime storage\";\n if (logicalName.startsWith(VECTOR_LOGICAL_NAME_PREFIX)) {\n return `vector storage \"${logicalName.slice(VECTOR_LOGICAL_NAME_PREFIX.length)}\"`;\n }\n if (logicalName === \"fulltext\") return \"fulltext storage\";\n return `\"${logicalName}\" storage`;\n}\n\n// ============================================================\n// Database Errors (category: \"system\")\n// ============================================================\n\n/**\n * Details for DatabaseOperationError.\n */\nexport type DatabaseOperationErrorDetails = Readonly<{\n operation: string;\n entity: string;\n}>;\n\n/**\n * Thrown when a database operation fails unexpectedly.\n *\n * This indicates a system-level failure in the database backend,\n * not a user-recoverable error.\n */\nexport class DatabaseOperationError extends TypeGraphError {\n declare readonly details: DatabaseOperationErrorDetails;\n\n constructor(\n message: string,\n details: DatabaseOperationErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(message, \"DATABASE_OPERATION_ERROR\", {\n details,\n category: \"system\",\n suggestion: `This is a system-level database error. Check the database connection and retry the operation. If the problem persists, investigate the underlying cause.`,\n cause: options?.cause,\n });\n this.name = \"DatabaseOperationError\";\n }\n}\n\n// ============================================================\n// Vector / Embedding Errors (category: \"user\")\n// ============================================================\n\n/**\n * Details for EmbeddingDimensionChangedError.\n */\nexport type EmbeddingDimensionChangedErrorDetails = Readonly<{\n kind: string;\n fieldPath: string;\n declaredDimensions?: number;\n storedDimensions?: number;\n}>;\n\n/**\n * Thrown when an embedding field's declared dimension no longer matches the\n * dimension of its materialized per-field storage — i.e. a field's\n * `embedding(N)` was changed to `embedding(M)`. The stored vectors are invalid\n * under the new dimension and cannot be converted, only recomputed, so this is\n * a deliberate app-driven migration: call\n * `store.reembedVectorField(kind, fieldPath, ...)` to recreate the storage at\n * the new dimension and re-embed existing rows.\n */\nexport class EmbeddingDimensionChangedError extends TypeGraphError {\n declare readonly details: EmbeddingDimensionChangedErrorDetails;\n\n constructor(\n message: string,\n details: EmbeddingDimensionChangedErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(message, \"EMBEDDING_DIMENSION_CHANGED\", {\n details,\n category: \"user\",\n suggestion: `Run store.reembedVectorField(\"${details.kind}\", \"${details.fieldPath}\", { embed }) to recreate the field's storage at the new dimension and re-embed existing rows.`,\n cause: options?.cause,\n });\n this.name = \"EmbeddingDimensionChangedError\";\n }\n}\n\n// ============================================================\n// Query Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a query predicate cannot be compiled for the target database.\n */\nexport class UnsupportedPredicateError extends TypeGraphError {\n constructor(\n message: string,\n details: Readonly<Record<string, unknown>> = {},\n options?: { cause?: unknown; suggestion?: string },\n ) {\n super(message, \"UNSUPPORTED_PREDICATE\", {\n details,\n category: \"system\",\n suggestion:\n options?.suggestion ??\n `This predicate may not be supported by your database backend. Check the documentation for supported predicates.`,\n cause: options?.cause,\n });\n this.name = \"UnsupportedPredicateError\";\n }\n}\n\n// ============================================================\n// Compiler Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a compiler invariant is violated.\n *\n * This indicates a bug in the query compiler — the compiler reached\n * a state that should be unreachable. These errors are not user-recoverable.\n */\nexport class CompilerInvariantError extends TypeGraphError {\n constructor(\n message: string,\n details?: Readonly<Record<string, unknown>>,\n options?: { cause?: unknown },\n ) {\n super(message, \"COMPILER_INVARIANT_ERROR\", {\n details: details ?? {},\n category: \"system\",\n suggestion: `This is an internal compiler error. Please report it as a bug with the query that triggered it.`,\n cause: options?.cause,\n });\n this.name = \"CompilerInvariantError\";\n }\n}\n\n// ============================================================\n// Lifecycle Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when an operation is attempted on a backend that has been disposed.\n *\n * This typically occurs during runtime teardown — for example, when a\n * Cloudflare Workers test runner resets Durable Object storage while\n * the TypeGraph backend still has queued operations.\n */\nexport class BackendDisposedError extends TypeGraphError {\n constructor(options?: { cause?: unknown }) {\n super(\n \"Backend has been disposed — the underlying database connection is no longer available\",\n \"BACKEND_DISPOSED\",\n {\n category: \"system\",\n suggestion:\n \"Ensure all store operations complete before calling backend.close(). \" +\n \"In test environments, await store teardown before resetting the database.\",\n cause: options?.cause,\n },\n );\n this.name = \"BackendDisposedError\";\n }\n}\n\n/**\n * Thrown when a statement is issued on a transaction-scoped backend after\n * its transaction boundary has already returned.\n *\n * The usual source is a callback that lets work escape it. `Promise.all`\n * rejects on its first rejection while its siblings keep running, so\n *\n * ```typescript\n * await store.transaction(async (tx) => {\n * await Promise.all([tx.nodes.Doc.create(a), tx.nodes.Doc.create(b)]);\n * });\n * ```\n *\n * leaves `b`'s remaining statements in flight when `a` fails. Those\n * statements have nowhere safe to go: the driver is about to emit `ROLLBACK`\n * on the same pinned connection and then hand it back to the pool, where a\n * late arrival would execute inside somebody else's transaction. TypeGraph\n * refuses them here instead.\n *\n * The error is normally invisible — `Promise.all` has already rejected with\n * the original failure, and discards this one.\n */\nexport class TransactionClosedError extends TypeGraphError {\n constructor(options?: { cause?: unknown }) {\n super(\n \"Statement issued on a transaction-scoped backend after its transaction \" +\n \"boundary returned. The connection has been released; the statement was not run.\",\n \"TRANSACTION_CLOSED\",\n {\n category: \"user\",\n suggestion:\n \"Await every write started inside store.transaction(...) before the \" +\n \"callback returns. Prefer awaiting a Promise.allSettled(...) over a \" +\n \"Promise.all(...) whose rejection would orphan its siblings.\",\n cause: options?.cause,\n },\n );\n this.name = \"TransactionClosedError\";\n }\n}\n\n// ============================================================\n// Utility Functions\n// ============================================================\n\n/**\n * Type guard for TypeGraphError.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({});\n * } catch (error) {\n * if (isTypeGraphError(error)) {\n * console.log(error.code, error.category);\n * }\n * }\n * ```\n */\nexport function isTypeGraphError(error: unknown): error is TypeGraphError {\n return error instanceof TypeGraphError;\n}\n\n/**\n * Check if error is recoverable by user action (user or constraint error).\n *\n * User-recoverable errors can typically be resolved by:\n * - Fixing invalid input data\n * - Using different IDs or values\n * - Deleting conflicting data first\n *\n * @example\n * ```typescript\n * if (isUserRecoverable(error)) {\n * showErrorToUser(error.toUserMessage());\n * } else {\n * logAndAlertOps(error);\n * }\n * ```\n */\nexport function isUserRecoverable(error: unknown): boolean {\n if (!isTypeGraphError(error)) return false;\n return error.category === \"user\" || error.category === \"constraint\";\n}\n\n/**\n * Check if error indicates a system/infrastructure issue.\n *\n * System errors typically require:\n * - Retry logic (for transient failures)\n * - Investigation (for persistent failures)\n * - Ops team notification\n */\nexport function isSystemError(error: unknown): boolean {\n return isTypeGraphError(error) && error.category === \"system\";\n}\n\n/**\n * Check if error is a constraint violation.\n */\nexport function isConstraintError(error: unknown): boolean {\n return isTypeGraphError(error) && error.category === \"constraint\";\n}\n\n/**\n * Extract suggestion from error if available.\n */\nexport function getErrorSuggestion(error: unknown): string | undefined {\n return isTypeGraphError(error) ? error.suggestion : undefined;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { KindRegistry, validateImpliesEndpointCompatibility } from './chunk-V3S74J44.js';
1
+ import { KindRegistry, validateImpliesEndpointCompatibility } from './chunk-RAWG2FEU.js';
2
2
 
3
3
  // src/schema/deserializer.ts
4
4
  function deserializeSchema(schema) {
@@ -77,5 +77,5 @@ function simpleRecordToMap(record) {
77
77
  }
78
78
 
79
79
  export { deserializeSchema };
80
- //# sourceMappingURL=chunk-KOI7UEI5.js.map
81
- //# sourceMappingURL=chunk-KOI7UEI5.js.map
80
+ //# sourceMappingURL=chunk-LDCWO5B6.js.map
81
+ //# sourceMappingURL=chunk-LDCWO5B6.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schema/deserializer.ts"],"names":[],"mappings":";;;AAiFO,SAAS,kBACd,MAAA,EACoB;AACpB,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA;AAC1C,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA;AAC1C,EAAA,MAAM,aAAA,GAAgB,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,SAAS,SAAS,CAAA;AAE3D,EAAA,OAAO;AAAA,IACL,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,aAAa,MAAA,CAAO,WAAA;AAAA,IAEpB,OAAA,EAAS,CAAC,IAAA,KAAS,MAAA,CAAO,MAAM,IAAI,CAAA;AAAA,IACpC,cAAc,MAAM,SAAA;AAAA,IAEpB,OAAA,EAAS,CAAC,IAAA,KAAS,MAAA,CAAO,MAAM,IAAI,CAAA;AAAA,IACpC,cAAc,MAAM,SAAA;AAAA,IAEpB,aAAa,CAAC,IAAA,KAAS,MAAA,CAAO,QAAA,CAAS,UAAU,IAAI,CAAA;AAAA,IACrD,kBAAkB,MAAM,aAAA;AAAA,IAExB,YAAA,EAAc,MAAM,MAAA,CAAO,QAAA,CAAS,SAAA;AAAA,IACpC,WAAA,EAAa,MAAM,MAAA,CAAO,QAAA,CAAS,QAAA;AAAA,IAEnC,WAAA,EAAa,MAAM,MAAA,CAAO,QAAA;AAAA,IAC1B,QAAQ,MAAM,MAAA;AAAA,IAEd,aAAA,EAAe,MAAM,yBAAA,CAA0B,MAAM;AAAA,GACvD;AACF;AAWA,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AAA,IACA,cAAA;AAAA,IACA,YAAA;AAAA,IACA,uBAAA;AAAA,IACA;AAAA,GACD,CAAA;AAED,EAAA,oCAAA;AAAA,IACE,sBAAA,CAAuB,OAAO,KAAK,CAAA;AAAA,IACnC;AAAA,GACF;AAEA,EAAA,OAAO,QAAA;AACT;AASA,SAAS,uBACP,KAAA,EACwC;AACxC,EAAA,MAAM,MAAA,uBAAa,GAAA,EAA+B;AAClD,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,GAAG,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AAC/C,IAAA,MAAA,CAAO,GAAA,CAAI,MAAM,EAAE,IAAA,EAAM,IAAI,SAAA,EAAW,EAAA,EAAI,GAAA,CAAI,OAAA,EAAS,CAAA;AAAA,EAC3D;AACA,EAAA,OAAO,MAAA;AACT;AAKA,SAAS,YACP,MAAA,EAC0C;AAC1C,EAAA,MAAM,MAAA,uBAAa,GAAA,EAAyB;AAC5C,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,MAAM,KAAK,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,EAAG;AAClD,IAAA,MAAA,CAAO,GAAA,CAAI,GAAA,EAAK,IAAI,GAAA,CAAI,MAAM,CAAC,CAAA;AAAA,EACjC;AACA,EAAA,OAAO,MAAA;AACT;AAKA,SAAS,kBACP,MAAA,EAC6B;AAC7B,EAAA,OAAO,IAAI,GAAA,CAAI,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAC,CAAA;AACvC","file":"chunk-KOI7UEI5.js","sourcesContent":["/**\n * Schema deserializer for loading stored schemas.\n *\n * Reconstructs runtime objects from SerializedSchema.\n * Note: Zod schemas cannot be fully reconstructed from JSON Schema,\n * so this provides access to the serialized data for introspection.\n */\nimport { KindRegistry } from \"../registry/kind-registry\";\nimport {\n type EdgeEndpointKinds,\n validateImpliesEndpointCompatibility,\n} from \"../registry/validate-implies\";\nimport {\n type SerializedClosures,\n type SerializedEdgeDef,\n type SerializedMetaEdge,\n type SerializedNodeDef,\n type SerializedOntologyRelation,\n type SerializedSchema,\n} from \"./types\";\n\n// ============================================================\n// Deserialized Schema\n// ============================================================\n\n/**\n * A deserialized schema provides read-only access to schema metadata.\n *\n * Note: Unlike the original GraphDef, this does not include Zod schemas\n * since those cannot be reconstructed from JSON Schema. Use this for\n * introspection and metadata access only.\n */\nexport type DeserializedSchema = Readonly<{\n graphId: string;\n version: number;\n generatedAt: string;\n\n /** Get node definition by name */\n getNode: (name: string) => SerializedNodeDef | undefined;\n\n /** Get all node names */\n getNodeNames: () => readonly string[];\n\n /** Get edge definition by name */\n getEdge: (name: string) => SerializedEdgeDef | undefined;\n\n /** Get all edge names */\n getEdgeNames: () => readonly string[];\n\n /** Get meta-edge definition by name */\n getMetaEdge: (name: string) => SerializedMetaEdge | undefined;\n\n /** Get all meta-edge names */\n getMetaEdgeNames: () => readonly string[];\n\n /** Get all ontology relations */\n getRelations: () => readonly SerializedOntologyRelation[];\n\n /** Get precomputed closures */\n getClosures: () => SerializedClosures;\n\n /** Get graph defaults */\n getDefaults: () => SerializedSchema[\"defaults\"];\n\n /** Get the raw serialized schema */\n getRaw: () => SerializedSchema;\n\n /** Build a KindRegistry from the closures */\n buildRegistry: () => KindRegistry;\n}>;\n\n// ============================================================\n// Deserialization\n// ============================================================\n\n/**\n * Deserializes a SerializedSchema into a DeserializedSchema.\n *\n * @param schema - The serialized schema to deserialize\n * @returns A deserialized schema with accessor methods\n */\nexport function deserializeSchema(\n schema: SerializedSchema,\n): DeserializedSchema {\n const nodeNames = Object.keys(schema.nodes);\n const edgeNames = Object.keys(schema.edges);\n const metaEdgeNames = Object.keys(schema.ontology.metaEdges);\n\n return {\n graphId: schema.graphId,\n version: schema.version,\n generatedAt: schema.generatedAt,\n\n getNode: (name) => schema.nodes[name],\n getNodeNames: () => nodeNames,\n\n getEdge: (name) => schema.edges[name],\n getEdgeNames: () => edgeNames,\n\n getMetaEdge: (name) => schema.ontology.metaEdges[name],\n getMetaEdgeNames: () => metaEdgeNames,\n\n getRelations: () => schema.ontology.relations,\n getClosures: () => schema.ontology.closures,\n\n getDefaults: () => schema.defaults,\n getRaw: () => schema,\n\n buildRegistry: () => buildRegistryFromClosures(schema),\n };\n}\n\n// ============================================================\n// Registry Building\n// ============================================================\n\n/**\n * Builds a KindRegistry from serialized closures.\n *\n * This allows query execution without recomputing closures.\n */\nfunction buildRegistryFromClosures(schema: SerializedSchema): KindRegistry {\n const { closures } = schema.ontology;\n\n // Convert Record<string, string[]> back to Map<string, Set<string>>\n const subClassAncestors = recordToMap(closures.subClassAncestors);\n const subClassDescendants = recordToMap(closures.subClassDescendants);\n const broaderClosure = recordToMap(closures.broaderClosure);\n const narrowerClosure = recordToMap(closures.narrowerClosure);\n const equivalenceSets = recordToMap(closures.equivalenceSets);\n const partOfClosure = recordToMap(closures.partOfClosure);\n const hasPartClosure = recordToMap(closures.hasPartClosure);\n const iriToKind = simpleRecordToMap(closures.iriToKind);\n const disjointPairs = new Set(closures.disjointPairs);\n const edgeInverses = simpleRecordToMap(closures.edgeInverses);\n const edgeImplicationsClosure = recordToMap(closures.edgeImplicationsClosure);\n const edgeImplyingClosure = recordToMap(closures.edgeImplyingClosure);\n\n // Build empty node/edge kind maps (we don't have the actual Zod schemas)\n const nodeKinds = new Map();\n const edgeKinds = new Map();\n\n const registry = new KindRegistry(nodeKinds, edgeKinds, {\n subClassAncestors,\n subClassDescendants,\n broaderClosure,\n narrowerClosure,\n equivalenceSets,\n iriToKind,\n disjointPairs,\n partOfClosure,\n hasPartClosure,\n edgeInverses,\n edgeImplicationsClosure,\n edgeImplyingClosure,\n });\n\n validateImpliesEndpointCompatibility(\n buildEdgeEndpointKinds(schema.edges),\n registry,\n );\n\n return registry;\n}\n\n/**\n * Maps each edge kind's serialized definition to its domain/range kind\n * names, for `validateImpliesEndpointCompatibility`. A `Map` (rather than\n * the plain `schema.edges` object) so a lookup for an edge kind literally\n * named \"toString\" or another `Object.prototype` member can't resolve to\n * an inherited member instead of `undefined`.\n */\nfunction buildEdgeEndpointKinds(\n edges: Record<string, SerializedEdgeDef>,\n): ReadonlyMap<string, EdgeEndpointKinds> {\n const result = new Map<string, EdgeEndpointKinds>();\n for (const [kind, def] of Object.entries(edges)) {\n result.set(kind, { from: def.fromKinds, to: def.toKinds });\n }\n return result;\n}\n\n/**\n * Converts Record<string, string[]> to Map<string, Set<string>>.\n */\nfunction recordToMap(\n record: Record<string, readonly string[]>,\n): ReadonlyMap<string, ReadonlySet<string>> {\n const result = new Map<string, Set<string>>();\n for (const [key, values] of Object.entries(record)) {\n result.set(key, new Set(values));\n }\n return result;\n}\n\n/**\n * Converts Record<string, string> to Map<string, string>.\n */\nfunction simpleRecordToMap(\n record: Record<string, string>,\n): ReadonlyMap<string, string> {\n return new Map(Object.entries(record));\n}\n"]}
1
+ {"version":3,"sources":["../src/schema/deserializer.ts"],"names":[],"mappings":";;;AAiFO,SAAS,kBACd,MAAA,EACoB;AACpB,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA;AAC1C,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA;AAC1C,EAAA,MAAM,aAAA,GAAgB,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,SAAS,SAAS,CAAA;AAE3D,EAAA,OAAO;AAAA,IACL,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,aAAa,MAAA,CAAO,WAAA;AAAA,IAEpB,OAAA,EAAS,CAAC,IAAA,KAAS,MAAA,CAAO,MAAM,IAAI,CAAA;AAAA,IACpC,cAAc,MAAM,SAAA;AAAA,IAEpB,OAAA,EAAS,CAAC,IAAA,KAAS,MAAA,CAAO,MAAM,IAAI,CAAA;AAAA,IACpC,cAAc,MAAM,SAAA;AAAA,IAEpB,aAAa,CAAC,IAAA,KAAS,MAAA,CAAO,QAAA,CAAS,U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A,CAAQ,MAAM,CAAC,CAAA;AACvC","file":"chunk-LDCWO5B6.js","sourcesContent":["/**\n * Schema deserializer for loading stored schemas.\n *\n * Reconstructs runtime objects from SerializedSchema.\n * Note: Zod schemas cannot be fully reconstructed from JSON Schema,\n * so this provides access to the serialized data for introspection.\n */\nimport { KindRegistry } from \"../registry/kind-registry\";\nimport {\n type EdgeEndpointKinds,\n validateImpliesEndpointCompatibility,\n} from \"../registry/validate-implies\";\nimport {\n type SerializedClosures,\n type SerializedEdgeDef,\n type SerializedMetaEdge,\n type SerializedNodeDef,\n type SerializedOntologyRelation,\n type SerializedSchema,\n} from \"./types\";\n\n// ============================================================\n// Deserialized Schema\n// ============================================================\n\n/**\n * A deserialized schema provides read-only access to schema metadata.\n *\n * Note: Unlike the original GraphDef, this does not include Zod schemas\n * since those cannot be reconstructed from JSON Schema. Use this for\n * introspection and metadata access only.\n */\nexport type DeserializedSchema = Readonly<{\n graphId: string;\n version: number;\n generatedAt: string;\n\n /** Get node definition by name */\n getNode: (name: string) => SerializedNodeDef | undefined;\n\n /** Get all node names */\n getNodeNames: () => readonly string[];\n\n /** Get edge definition by name */\n getEdge: (name: string) => SerializedEdgeDef | undefined;\n\n /** Get all edge names */\n getEdgeNames: () => readonly string[];\n\n /** Get meta-edge definition by name */\n getMetaEdge: (name: string) => SerializedMetaEdge | undefined;\n\n /** Get all meta-edge names */\n getMetaEdgeNames: () => readonly string[];\n\n /** Get all ontology relations */\n getRelations: () => readonly SerializedOntologyRelation[];\n\n /** Get precomputed closures */\n getClosures: () => SerializedClosures;\n\n /** Get graph defaults */\n getDefaults: () => SerializedSchema[\"defaults\"];\n\n /** Get the raw serialized schema */\n getRaw: () => SerializedSchema;\n\n /** Build a KindRegistry from the closures */\n buildRegistry: () => KindRegistry;\n}>;\n\n// ============================================================\n// Deserialization\n// ============================================================\n\n/**\n * Deserializes a SerializedSchema into a DeserializedSchema.\n *\n * @param schema - The serialized schema to deserialize\n * @returns A deserialized schema with accessor methods\n */\nexport function deserializeSchema(\n schema: SerializedSchema,\n): DeserializedSchema {\n const nodeNames = Object.keys(schema.nodes);\n const edgeNames = Object.keys(schema.edges);\n const metaEdgeNames = Object.keys(schema.ontology.metaEdges);\n\n return {\n graphId: schema.graphId,\n version: schema.version,\n generatedAt: schema.generatedAt,\n\n getNode: (name) => schema.nodes[name],\n getNodeNames: () => nodeNames,\n\n getEdge: (name) => schema.edges[name],\n getEdgeNames: () => edgeNames,\n\n getMetaEdge: (name) => schema.ontology.metaEdges[name],\n getMetaEdgeNames: () => metaEdgeNames,\n\n getRelations: () => schema.ontology.relations,\n getClosures: () => schema.ontology.closures,\n\n getDefaults: () => schema.defaults,\n getRaw: () => schema,\n\n buildRegistry: () => buildRegistryFromClosures(schema),\n };\n}\n\n// ============================================================\n// Registry Building\n// ============================================================\n\n/**\n * Builds a KindRegistry from serialized closures.\n *\n * This allows query execution without recomputing closures.\n */\nfunction buildRegistryFromClosures(schema: SerializedSchema): KindRegistry {\n const { closures } = schema.ontology;\n\n // Convert Record<string, string[]> back to Map<string, Set<string>>\n const subClassAncestors = recordToMap(closures.subClassAncestors);\n const subClassDescendants = recordToMap(closures.subClassDescendants);\n const broaderClosure = recordToMap(closures.broaderClosure);\n const narrowerClosure = recordToMap(closures.narrowerClosure);\n const equivalenceSets = recordToMap(closures.equivalenceSets);\n const partOfClosure = recordToMap(closures.partOfClosure);\n const hasPartClosure = recordToMap(closures.hasPartClosure);\n const iriToKind = simpleRecordToMap(closures.iriToKind);\n const disjointPairs = new Set(closures.disjointPairs);\n const edgeInverses = simpleRecordToMap(closures.edgeInverses);\n const edgeImplicationsClosure = recordToMap(closures.edgeImplicationsClosure);\n const edgeImplyingClosure = recordToMap(closures.edgeImplyingClosure);\n\n // Build empty node/edge kind maps (we don't have the actual Zod schemas)\n const nodeKinds = new Map();\n const edgeKinds = new Map();\n\n const registry = new KindRegistry(nodeKinds, edgeKinds, {\n subClassAncestors,\n subClassDescendants,\n broaderClosure,\n narrowerClosure,\n equivalenceSets,\n iriToKind,\n disjointPairs,\n partOfClosure,\n hasPartClosure,\n edgeInverses,\n edgeImplicationsClosure,\n edgeImplyingClosure,\n });\n\n validateImpliesEndpointCompatibility(\n buildEdgeEndpointKinds(schema.edges),\n registry,\n );\n\n return registry;\n}\n\n/**\n * Maps each edge kind's serialized definition to its domain/range kind\n * names, for `validateImpliesEndpointCompatibility`. A `Map` (rather than\n * the plain `schema.edges` object) so a lookup for an edge kind literally\n * named \"toString\" or another `Object.prototype` member can't resolve to\n * an inherited member instead of `undefined`.\n */\nfunction buildEdgeEndpointKinds(\n edges: Record<string, SerializedEdgeDef>,\n): ReadonlyMap<string, EdgeEndpointKinds> {\n const result = new Map<string, EdgeEndpointKinds>();\n for (const [kind, def] of Object.entries(edges)) {\n result.set(kind, { from: def.fromKinds, to: def.toKinds });\n }\n return result;\n}\n\n/**\n * Converts Record<string, string[]> to Map<string, Set<string>>.\n */\nfunction recordToMap(\n record: Record<string, readonly string[]>,\n): ReadonlyMap<string, ReadonlySet<string>> {\n const result = new Map<string, Set<string>>();\n for (const [key, values] of Object.entries(record)) {\n result.set(key, new Set(values));\n }\n return result;\n}\n\n/**\n * Converts Record<string, string> to Map<string, string>.\n */\nfunction simpleRecordToMap(\n record: Record<string, string>,\n): ReadonlyMap<string, string> {\n return new Map(Object.entries(record));\n}\n"]}
@@ -1,8 +1,8 @@
1
- import { createSqliteBackend } from './chunk-QZYGZVUI.js';
2
- import { sqliteVecStrategy } from './chunk-BUZWMDNL.js';
3
- import { tables2, generateSqliteDDL } from './chunk-5J4VNCUD.js';
4
- import { wrapWithManagedClose } from './chunk-L5ET7FYQ.js';
5
- import { ConfigurationError } from './chunk-DPNA466P.js';
1
+ import { createSqliteBackend } from './chunk-ZIRC2U6G.js';
2
+ import { sqliteVecStrategy } from './chunk-VC26BUNP.js';
3
+ import { tables2, generateSqliteDDL } from './chunk-Z3WIL6S3.js';
4
+ import { wrapWithManagedClose } from './chunk-UZLEQFTV.js';
5
+ import { ConfigurationError } from './chunk-OYJSYDIH.js';
6
6
  import { createRequire } from 'module';
7
7
  import Database from 'better-sqlite3';
8
8
  import { drizzle } from 'drizzle-orm/better-sqlite3';
@@ -179,5 +179,5 @@ function tryLoadSqliteVec(sqlite) {
179
179
  }
180
180
 
181
181
  export { DEFAULT_LOCAL_SQLITE_PRAGMAS, createLocalSqliteBackend };
182
- //# sourceMappingURL=chunk-I5CRUPKO.js.map
183
- //# sourceMappingURL=chunk-I5CRUPKO.js.map
182
+ //# sourceMappingURL=chunk-LQLVJWUH.js.map
183
+ //# sourceMappingURL=chunk-LQLVJWUH.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/backend/sqlite/local-options.ts","../src/backend/sqlite/local.ts"],"names":["tables"],"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,EAAe,MAAA;AAAA,EACf,sBAAA,EAAwB;AAC1B;;;ACsBF,IAAM,WAAA,GAAc,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AAWjD,SAAS,uBAAuB,KAAA,EAAwB;AACtD,EAAA,IAAI,KAAA,YAAiB,KAAA,EAAO,OAAO,KAAA,CAAM,OAAA;AACzC,EAAA,OAAO,OAAO,KAAK,CAAA;AACrB;AAEA,SAAS,sCACP,OAAA,EACuC;AACvC,EAAA,MAAM,MAAA,GACJ,kFAAA;AACF,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA;AACjC,EAAA,IAAI,CAAC,KAAA,EAAO,MAAA,EAAQ,OAAO,MAAA;AAE3B,EAAA,MAAM,QAAA,GAAW,MAAA,CAAO,KAAA,CAAM,MAAA,CAAO,UAAU,CAAC,CAAA;AAChD,EAAA,MAAM,QAAA,GAAW,MAAA,CAAO,KAA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AQ,YAAA,EAAc,gBAAgB,SAAA,IACtC,OAAA,CAAQ,cAAc,YAAA,KAAiB,KAAA;AAAA,UACzC,aAAA,EACE,OAAA,CAAQ,YAAA,EAAc,cAAA,EAAgB,aAAA,IAAiB;AAAA;AAC3D;AACF,KACD,CAAA;AACD,IAAA,MAAM,cAAA,GAAiB,oBAAA,CAAqB,OAAA,EAAS,MAAM;AACzD,MAAA,MAAA,CAAO,KAAA,EAAM;AAAA,IACf,CAAC,CAAA;AAED,IAAA,OAAO,EAAE,OAAA,EAAS,cAAA,EAAgB,EAAA,EAAG;AAAA,EACvC,SAAS,KAAA,EAAO;AACd,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,KAAA,EAAM;AAAA,IACf,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,MAAM,KAAA;AAAA,EACR;AACF;AAEA,SAAS,iBAAiB,MAAA,EAAoC;AAC5D,EAAA,IAAI;AAIF,IAAA,MAAM,OAAA,GAAmB,YAAY,YAAY,CAAA;AACjD,IAAA,IACE,OAAO,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-I5CRUPKO.js","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 { 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 {\n type AdapterBackend,\n type BackendCapabilities,\n wrapWithManagedClose,\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}\n"]}
1
+ {"version":3,"sources":["../src/backend/sqlite/local-options.ts","../src/backend/sqlite/local.ts"],"names":["tables"],"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,EAAe,MAAA;AAAA,EACf,sBAAA,EAAwB;AAC1B;;;ACsBF,IAAM,WAAA,GAAc,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AAWjD,SAAS,uBAAuB,KAAA,EAAwB;AACtD,EAAA,IAAI,KAAA,YAAiB,KAAA,EAAO,OAAO,KAAA,CAAM,OAAA;AACzC,EAAA,OAAO,OAAO,KAAK,CAAA;AACrB;AAEA,SAAS,sCACP,OAAA,EACuC;AACvC,EAAA,MAAM,MAAA,GACJ,kFAAA;AACF,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA;AACjC,EAAA,IAAI,CAAC,KAAA,EAAO,MAAA,EAAQ,OAAO,MAAA;AAE3B,EAAA,MAAM,QAAA,GAAW,MAAA,CAAO,KAAA,CAAM,MAAA,CAAO,UAAU,CAAC,CAAA;AACh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QACX,cAAA,EAAgB;AAAA,UACd,WACE,OAAA,CAAQ,YAAA,EAAc,gBAAgB,SAAA,IACtC,OAAA,CAAQ,cAAc,YAAA,KAAiB,KAAA;AAAA,UACzC,aAAA,EACE,OAAA,CAAQ,YAAA,EAAc,cAAA,EAAgB,aAAA,IAAiB;AAAA;AAC3D;AACF,KACD,CAAA;AACD,IAAA,MAAM,cAAA,GAAiB,oBAAA,CAAqB,OAAA,EAAS,MAAM;AACzD,MAAA,MAAA,CAAO,KAAA,EAAM;AAAA,IACf,CAAC,CAAA;AAED,IAAA,OAAO,EAAE,OAAA,EAAS,cAAA,EAAgB,EAAA,EAAG;AAAA,EACvC,SAAS,KAAA,EAAO;AACd,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,KAAA,EAAM;AAAA,IACf,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,MAAM,KAAA;AAAA,EACR;AACF;AAEA,SAAS,iBAAiB,MAAA,EAAoC;AAC5D,EAAA,IAAI;AAIF,IAAA,MAAM,OAAA,GAAmB,YAAY,YAAY,CAAA;AACjD,IAAA,IACE,OAAO,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-LQLVJWUH.js","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 { 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 {\n type AdapterBackend,\n type BackendCapabilities,\n wrapWithManagedClose,\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}\n"]}
@@ -1,4 +1,4 @@
1
- import { ConfigurationError } from './chunk-DPNA466P.js';
1
+ import { ConfigurationError } from './chunk-OYJSYDIH.js';
2
2
 
3
3
  // src/utils/global-symbol.ts
4
4
  function typeGraphGlobalSymbol(name) {
@@ -312,5 +312,5 @@ var LIKE_ESCAPE_CHARACTER = "\\";
312
312
  var likeEscapeClause = sql`ESCAPE '\\'`;
313
313
 
314
314
  export { LIKE_ESCAPE_CHARACTER, Placeholder, annIndexScanTypes, asCompiledRowsSql, asCompiledSelectSql, asCompiledStatementSql, asCompiledTemporaryStatementSql, bindSqlValue, getSqlDialectProfile, inlineSqlStringLiteral, isRawExecutable, isSqlFragment, isSqlPlaceholder, likeEscapeClause, markAnnIndexScan, markForceCustomPlan, renderPostgres, renderSql, renderSqlInline, renderSqlite, shouldForceCustomPlan, sql, throwUnsupportedSqlChunk, typeGraphGlobalSymbol };
315
- //# sourceMappingURL=chunk-6N7QBIWN.js.map
316
- //# sourceMappingURL=chunk-6N7QBIWN.js.map
315
+ //# sourceMappingURL=chunk-M4GYQF2H.js.map
316
+ //# sourceMappingURL=chunk-M4GYQF2H.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/global-symbol.ts","../src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B,IAAA,CAAK,KAAK,CAAC,CAAA;AACvC,QAAA;AAAA,MACF;AAAA,MACA,KAAK,WAAA,EAAa;AAChB,QAAA,KAAA,CAAM,IAAA,CAAK,aAAA,CAAc,IAAA,CAAK,KAAA,EAAO,OAAO,CAAC,CAAA;AAC7C,QAAA;AAAA,MACF;AAAA,MACA,KAAK,aAAA,EAAe;AAClB,QAAA,MAAM,IAAI,kBAAA;AAAA,UACR,CAAA,0CAAA,EAA6C,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA,CAAA,CAAA;AAAA,UAC5D,EAAE,aAAA,EAAe,IAAA,CAAK,KAAA,CAAM,IAAA;AAAK,SACnC;AAAA,MACF;AAAA,MACA,SAAS;AACP,QAAA,wBAAA,CAAyB,IAAI,CAAA;AAAA,MAC/B;AAAA;AACF,EACF;AAEA,EAAA,OAAO,KAAA,CAAM,KAAK,EAAE,CAAA;AACtB;;;ACvWO,IAAM,qBAAA,GAAwB;AAQ9B,IAAM,gBAAA,GAAgC,GAAA,CAAA,WAAA","file":"chunk-6N7QBIWN.js","sourcesContent":["type TypeGraphGlobalSymbolName =\n | \"sql-fragment\"\n | \"sql-placeholder\"\n | \"sql-intent-registry\"\n | \"internal-temporary-writes-v1\"\n | \"external-recorded-read-source-v1\"\n | \"sql-schema-v1\"\n | \"store-runtime-v1\"\n | \"typegraph-recorded-read-source-v1\"\n | \"transaction-runtime-v1\";\n\n/** Returns a process-wide symbol shared across ESM/CJS package instances. */\nexport function typeGraphGlobalSymbol<TSymbol extends symbol>(\n name: TypeGraphGlobalSymbolName,\n): TSymbol {\n return Symbol.for(`@nicia-ai/typegraph/${name}`) as TSymbol;\n}\n","import { type SqlDialect } from \"./types\";\n\nexport type SqlDialectProfile = Readonly<{\n bindValue: (value: unknown) => unknown;\n booleanLiteralString: (value: boolean) => string;\n placeholder: (index: number) => string;\n}>;\n\nconst SQL_DIALECT_PROFILES = {\n postgres: {\n bindValue: (value: unknown) => value,\n booleanLiteralString: (value: boolean) => (value ? \"TRUE\" : \"FALSE\"),\n placeholder: (index: number) => `$${index}`,\n },\n sqlite: {\n bindValue: (value: unknown) =>\n typeof value === \"boolean\" ?\n value ? 1\n : 0\n : value,\n booleanLiteralString: (value: boolean) => (value ? \"1\" : \"0\"),\n placeholder: () => \"?\",\n },\n} satisfies Record<SqlDialect, SqlDialectProfile>;\n\nconst SQL_STRING_LITERAL_RENDERERS = {\n postgres: (value: string) => {\n if (value.includes(\"\\\\\")) {\n return `E'${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"'\", \"''\")}'`;\n }\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n },\n sqlite: (value: string) => `'${value.replaceAll(\"'\", \"''\")}'`,\n} satisfies Record<SqlDialect, (value: string) => string>;\n\n/** Returns the primitive rendering and binding rules for a SQL dialect. */\nexport function getSqlDialectProfile(dialect: SqlDialect): SqlDialectProfile {\n return SQL_DIALECT_PROFILES[dialect];\n}\n\n/** Maps a JavaScript value to the representation expected by a SQL driver. */\nexport function bindSqlValue(value: unknown, dialect: SqlDialect): unknown {\n if (value instanceof Date) return value.toISOString();\n return getSqlDialectProfile(dialect).bindValue(value);\n}\n\n/** Renders one SQL string literal using the dialect's escaping rules. */\nexport function inlineSqlStringLiteral(\n value: string,\n dialect: SqlDialect,\n): string {\n return SQL_STRING_LITERAL_RENDERERS[dialect](value);\n}\n","import { typeGraphGlobalSymbol } from \"../utils/global-symbol\";\nimport { type SqlFragment } from \"./sql-fragment\";\n\ndeclare const SqlIntentBrand: unique symbol;\n\nexport type SqlIntent = \"rows\" | \"statement\" | \"temporary-statement\";\n\nexport type IntentSql<I extends SqlIntent> = SqlFragment &\n Readonly<{ [SqlIntentBrand]: I }>;\n\nexport type CompiledRowsSql = IntentSql<\"rows\">;\nexport type CompiledSelectSql = CompiledRowsSql;\nexport type CompiledStatementSql = IntentSql<\"statement\">;\nexport type CompiledTemporaryStatementSql = IntentSql<\"temporary-statement\">;\n\nexport function asCompiledRowsSql(query: SqlFragment): CompiledRowsSql {\n return query as CompiledRowsSql;\n}\n\nexport function asCompiledSelectSql(query: SqlFragment): CompiledSelectSql {\n return asCompiledRowsSql(query);\n}\n\nexport function asCompiledStatementSql(\n query: SqlFragment,\n): CompiledStatementSql {\n return query as CompiledStatementSql;\n}\n\n/**\n * Marks an internal statement that may write only connection-local temporary\n * state. This is intentionally separate from the public raw-statement intent:\n * history-enabled stores block arbitrary raw writes but iterative graph\n * operations still need to manage ephemeral working tables.\n */\nexport function asCompiledTemporaryStatementSql(\n query: SqlFragment,\n): CompiledTemporaryStatementSql {\n return query as CompiledTemporaryStatementSql;\n}\n\n/**\n * Statements whose good plan depends on the bound parameter values —\n * e.g. an id-array membership filter where the array cardinality varies\n * per call. PostgreSQL's prepared-statement machinery switches to a\n * generic (parameter-blind) plan after five executions, which for these\n * statements is catastrophically wrong (measured 21ms -> 310ms on the\n * subgraph edge fetch). Marked statements are executed unnamed so every\n * call is planned against the actual parameters; the re-parse cost is\n * ~1ms, the generic-plan cliff it avoids is 10-300ms.\n */\ntype SqlIntentRegistry = Readonly<{\n annIndexScanQueries: WeakMap<SqlFragment, readonly string[]>;\n forceCustomPlanQueries: WeakSet<SqlFragment>;\n}>;\n\nconst SQL_INTENT_REGISTRY: unique symbol = typeGraphGlobalSymbol(\n \"sql-intent-registry\",\n);\nconst globalWithSqlIntentRegistry = globalThis as typeof globalThis &\n Readonly<{\n [SQL_INTENT_REGISTRY]?: SqlIntentRegistry;\n }>;\nconst sqlIntentRegistry =\n globalWithSqlIntentRegistry[SQL_INTENT_REGISTRY] ??\n (() => {\n const registry: SqlIntentRegistry = {\n annIndexScanQueries: new WeakMap(),\n forceCustomPlanQueries: new WeakSet(),\n };\n Object.defineProperty(globalWithSqlIntentRegistry, SQL_INTENT_REGISTRY, {\n configurable: false,\n enumerable: false,\n value: registry,\n writable: false,\n });\n return registry;\n })();\n\nexport function markForceCustomPlan(query: SqlFragment): void {\n sqlIntentRegistry.forceCustomPlanQueries.add(query);\n}\n\nexport function shouldForceCustomPlan(query: SqlFragment): boolean {\n return sqlIntentRegistry.forceCustomPlanQueries.has(query);\n}\n\n/**\n * Statements whose plan includes an engine ANN index scan (the inline\n * `.similarTo(..., { approximate: true })` branch). The PostgreSQL\n * backend wraps their execution with the same pgvector GUC overrides\n * the search facade applies (`hnsw.iterative_scan = strict_order` /\n * `ivfflat.iterative_scan = relaxed_order` on pgvector >= 0.8), so a\n * filtered approximate query keeps scanning past the default ef_search\n * frontier instead of starving. Carries the slot index types so the\n * backend knows which GUCs apply. Backends without GUC semantics\n * ignore the brand.\n */\nexport function markAnnIndexScan(\n query: SqlFragment,\n indexTypes: readonly string[],\n): void {\n sqlIntentRegistry.annIndexScanQueries.set(query, indexTypes);\n}\n\nexport function annIndexScanTypes(\n query: SqlFragment,\n): readonly string[] | undefined {\n return sqlIntentRegistry.annIndexScanQueries.get(query);\n}\n\n/** @internal Copies execution semantics when immutable fragments are composed. */\nexport function copySqlIntents(\n target: SqlFragment,\n sources: readonly SqlFragment[],\n): void {\n if (sources.some((source) => shouldForceCustomPlan(source))) {\n markForceCustomPlan(target);\n }\n\n const indexTypes = new Set<string>();\n for (const source of sources) {\n for (const indexType of annIndexScanTypes(source) ?? []) {\n indexTypes.add(indexType);\n }\n }\n if (indexTypes.size > 0) markAnnIndexScan(target, [...indexTypes]);\n}\n\n/**\n * Whether a compiled statement can be run as raw text (`executeRaw`) without\n * losing execution semantics. Both brands above ride on the SQL *object* and\n * are honored only by `backend.execute`: the force-custom-plan flag makes\n * PostgreSQL re-plan against the actual parameters (opposed to reusing a\n * cached statement), and the ANN-scan brand drives the pgvector iterative-scan\n * GUC wrapper. A statement carrying either must not be flattened to text and\n * cached — callers fall back to `backend.execute`. Keeping this predicate\n * beside the brands means a future brand updates one place, not every caller.\n */\nexport function isRawExecutable(query: SqlFragment): boolean {\n return (\n !shouldForceCustomPlan(query) && annIndexScanTypes(query) === undefined\n );\n}\n","import { ConfigurationError } from \"../errors\";\nimport { typeGraphGlobalSymbol } from \"../utils/global-symbol\";\nimport {\n bindSqlValue,\n getSqlDialectProfile,\n inlineSqlStringLiteral,\n} from \"./dialect/profile\";\nimport { type SqlDialect } from \"./dialect/types\";\nimport { copySqlIntents } from \"./sql-intent\";\n\n/** Nominal identity shared by every package entrypoint. */\nconst SQL_FRAGMENT_BRAND: unique symbol = typeGraphGlobalSymbol(\"sql-fragment\");\nconst SQL_PLACEHOLDER_BRAND: unique symbol =\n typeGraphGlobalSymbol(\"sql-placeholder\");\n\nexport type SqlTextChunk = Readonly<{\n kind: \"text\";\n value: string;\n}>;\n\nexport type SqlParameterChunk = Readonly<{\n kind: \"parameter\";\n value: unknown;\n}>;\n\nexport type SqlIdentifierChunk = Readonly<{\n kind: \"identifier\";\n value: string;\n}>;\n\nexport type SqlPlaceholderChunk = Readonly<{\n kind: \"placeholder\";\n value: Placeholder;\n}>;\n\n/** One immutable unit in a database-independent SQL fragment. */\nexport type SqlChunk =\n SqlTextChunk | SqlParameterChunk | SqlIdentifierChunk | SqlPlaceholderChunk;\n\n/**\n * An immutable, database-independent SQL expression.\n *\n * Fragments contain syntax and bound values as separate nodes. A database\n * adapter renders the same fragment with its native placeholder convention at\n * the final execution boundary.\n */\nexport type SqlFragment = Readonly<{\n [SQL_FRAGMENT_BRAND]: true;\n append: (fragment: SqlFragment) => SqlFragment;\n chunks: readonly SqlChunk[];\n}>;\n\n/** A named value resolved when a prepared statement is executed. */\nexport class Placeholder {\n readonly [SQL_PLACEHOLDER_BRAND] = true as const;\n readonly name: string;\n\n constructor(name: string) {\n this.name = name;\n Object.freeze(this);\n }\n}\n\nclass SqlFragmentValue implements SqlFragment {\n readonly [SQL_FRAGMENT_BRAND] = true as const;\n\n readonly chunks: readonly SqlChunk[];\n\n constructor(chunks: readonly SqlChunk[]) {\n this.chunks = Object.freeze([...chunks]);\n Object.freeze(this);\n }\n\n append(fragment: SqlFragment): SqlFragment {\n return createFragment(\n [...this.chunks, ...getChunks(fragment)],\n [this, fragment],\n );\n }\n}\n\nfunction createFragment(\n chunks: readonly SqlChunk[],\n intentSources: readonly SqlFragment[] = [],\n): SqlFragment {\n const fragment = new SqlFragmentValue(chunks);\n copySqlIntents(fragment, intentSources);\n return fragment;\n}\n\nfunction getChunks(fragment: SqlFragment): readonly SqlChunk[] {\n if (!isSqlFragment(fragment)) {\n throw new ConfigurationError(\n \"Expected a SQL fragment created by TypeGraph's sql helper\",\n );\n }\n return fragment.chunks;\n}\n\n/** Returns whether a value is a TypeGraph-owned SQL fragment. */\nexport function isSqlFragment(value: unknown): value is SqlFragment {\n return (\n typeof value === \"object\" &&\n value !== null &&\n SQL_FRAGMENT_BRAND in value &&\n value[SQL_FRAGMENT_BRAND] === true &&\n \"chunks\" in value &&\n Array.isArray(value.chunks) &&\n \"append\" in value &&\n typeof value.append === \"function\"\n );\n}\n\n/** Returns whether a value is a TypeGraph named SQL placeholder. */\nexport function isSqlPlaceholder(value: unknown): value is Placeholder {\n return (\n typeof value === \"object\" &&\n value !== null &&\n SQL_PLACEHOLDER_BRAND in value &&\n value[SQL_PLACEHOLDER_BRAND] === true &&\n \"name\" in value &&\n typeof value.name === \"string\"\n );\n}\n\n/** @internal Enforces exhaustive handling at every fragment boundary. */\nexport function throwUnsupportedSqlChunk(chunk: never): never {\n throw new ConfigurationError(\"Unsupported SQL fragment chunk\", { chunk });\n}\n\nfunction textNode(value: string): SqlTextChunk {\n return Object.freeze({ kind: \"text\", value });\n}\n\nfunction parameterNode(value: unknown): SqlParameterChunk {\n return Object.freeze({ kind: \"parameter\", value });\n}\n\nfunction identifierNode(value: string): SqlIdentifierChunk {\n return Object.freeze({ kind: \"identifier\", value });\n}\n\nfunction placeholderNode(value: Placeholder): SqlPlaceholderChunk {\n return Object.freeze({ kind: \"placeholder\", value });\n}\n\nfunction templateSql(\n strings: TemplateStringsArray,\n ...values: readonly unknown[]\n): SqlFragment {\n const chunks: SqlChunk[] = [];\n const intentSources: SqlFragment[] = [];\n\n for (const [index, text] of strings.entries()) {\n if (text.length > 0) chunks.push(textNode(text));\n\n if (index >= values.length) continue;\n const value = values[index];\n if (isSqlFragment(value)) {\n chunks.push(...getChunks(value));\n intentSources.push(value);\n } else if (isSqlPlaceholder(value)) {\n chunks.push(placeholderNode(value));\n } else {\n chunks.push(parameterNode(value));\n }\n }\n\n return createFragment(chunks, intentSources);\n}\n\nfunction rawSql(value: string): SqlFragment {\n return createFragment(value.length === 0 ? [] : [textNode(value)]);\n}\n\nfunction identifierSql(value: string): SqlFragment {\n return createFragment([identifierNode(value)]);\n}\n\nfunction joinSql(\n fragments: readonly SqlFragment[],\n separator: SqlFragment = EMPTY_SQL,\n): SqlFragment {\n const chunks: SqlChunk[] = [];\n const intentSources: SqlFragment[] = [separator];\n\n for (const [index, fragment] of fragments.entries()) {\n if (index > 0) chunks.push(...getChunks(separator));\n chunks.push(...getChunks(fragment));\n intentSources.push(fragment);\n }\n\n return createFragment(chunks, intentSources);\n}\n\nfunction placeholderSql(name: string): SqlFragment {\n return createFragment([placeholderNode(new Placeholder(name))]);\n}\n\nconst EMPTY_SQL = createFragment([]);\n\n/** TypeGraph's database-independent SQL template and composition helpers. */\nexport type SqlTag = Readonly<{\n empty: () => SqlFragment;\n identifier: (value: string) => SqlFragment;\n join: (\n fragments: readonly SqlFragment[],\n separator?: SqlFragment,\n ) => SqlFragment;\n placeholder: (name: string) => SqlFragment;\n raw: (value: string) => SqlFragment;\n}> &\n ((\n strings: TemplateStringsArray,\n ...values: readonly unknown[]\n ) => SqlFragment);\n\n/** TypeGraph's database-independent SQL template and composition helpers. */\nexport const sql: SqlTag = Object.assign(templateSql, {\n empty: function empty(): SqlFragment {\n return EMPTY_SQL;\n },\n identifier: identifierSql,\n join: joinSql,\n placeholder: placeholderSql,\n raw: rawSql,\n});\n\n/** A rendered statement and its ordered bound parameters. */\nexport type RenderedSql = Readonly<{\n sql: string;\n params: readonly unknown[];\n}>;\n\nfunction quotedIdentifier(identifier: string): string {\n return `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction resolvedPlaceholder(\n placeholder: Placeholder,\n bindings: Readonly<Record<string, unknown>> | undefined,\n dialect: SqlDialect,\n): unknown {\n if (bindings === undefined) return placeholder;\n\n if (!Object.hasOwn(bindings, placeholder.name)) {\n throw new ConfigurationError(\n `Missing binding for parameter \"${placeholder.name}\"`,\n { parameterName: placeholder.name },\n );\n }\n return bindSqlValue(bindings[placeholder.name], dialect);\n}\n\n/**\n * Renders a fragment for a database adapter.\n *\n * Named placeholders remain in `params` when `bindings` is omitted, allowing\n * a prepared template to resolve them later. Passing `bindings` resolves every\n * placeholder eagerly.\n */\nexport function renderSql(\n fragment: SqlFragment,\n dialect: SqlDialect,\n bindings?: Readonly<Record<string, unknown>>,\n): RenderedSql {\n const parts: string[] = [];\n const params: unknown[] = [];\n const profile = getSqlDialectProfile(dialect);\n\n for (const node of getChunks(fragment)) {\n switch (node.kind) {\n case \"text\": {\n parts.push(node.value);\n break;\n }\n case \"identifier\": {\n parts.push(quotedIdentifier(node.value));\n break;\n }\n case \"parameter\": {\n params.push(bindSqlValue(node.value, dialect));\n parts.push(profile.placeholder(params.length));\n break;\n }\n case \"placeholder\": {\n params.push(resolvedPlaceholder(node.value, bindings, dialect));\n parts.push(profile.placeholder(params.length));\n break;\n }\n default: {\n throwUnsupportedSqlChunk(node);\n }\n }\n }\n\n return Object.freeze({\n sql: parts.join(\"\"),\n params: Object.freeze(params),\n });\n}\n\n/** Renders a fragment using SQLite's `?` placeholders. */\nexport function renderSqlite(\n fragment: SqlFragment,\n bindings?: Readonly<Record<string, unknown>>,\n): RenderedSql {\n return renderSql(fragment, \"sqlite\", bindings);\n}\n\n/** Renders a fragment using PostgreSQL's numbered placeholders. */\nexport function renderPostgres(\n fragment: SqlFragment,\n bindings?: Readonly<Record<string, unknown>>,\n): RenderedSql {\n return renderSql(fragment, \"postgres\", bindings);\n}\n\nfunction inlineLiteral(value: unknown, dialect: SqlDialect): string {\n if (value === undefined || value === null) return \"NULL\";\n if (typeof value === \"string\") return inlineSqlStringLiteral(value, dialect);\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new ConfigurationError(\"Cannot inline a non-finite SQL number\", {\n value,\n });\n }\n return String(value);\n }\n if (typeof value === \"bigint\") return String(value);\n if (typeof value === \"boolean\") {\n return getSqlDialectProfile(dialect).booleanLiteralString(value);\n }\n if (value instanceof Date) {\n return inlineSqlStringLiteral(value.toISOString(), dialect);\n }\n\n throw new ConfigurationError(\"Cannot inline this SQL parameter value\", {\n value,\n });\n}\n\n/**\n * Renders a fragment with safe scalar literals instead of bound parameters.\n *\n * This is intentionally limited to DDL paths whose drivers cannot bind values.\n * Application queries should always use {@link renderSql}.\n */\nexport function renderSqlInline(\n fragment: SqlFragment,\n dialect: SqlDialect,\n): string {\n const parts: string[] = [];\n\n for (const node of getChunks(fragment)) {\n switch (node.kind) {\n case \"text\": {\n parts.push(node.value);\n break;\n }\n case \"identifier\": {\n parts.push(quotedIdentifier(node.value));\n break;\n }\n case \"parameter\": {\n parts.push(inlineLiteral(node.value, dialect));\n break;\n }\n case \"placeholder\": {\n throw new ConfigurationError(\n `Cannot inline unresolved SQL placeholder \"${node.value.name}\"`,\n { parameterName: node.value.name },\n );\n }\n default: {\n throwUnsupportedSqlChunk(node);\n }\n }\n }\n\n return parts.join(\"\");\n}\n","/**\n * Shared LIKE-escape clause for the query compiler.\n *\n * The compiler builds `contains` / `startsWith` / `endsWith` patterns by\n * escaping the literal `%`, `_`, and `\\` in user input with a backslash (see\n * the pattern builders in `compiler/predicates.ts`). For that escaping to take\n * effect the emitted `LIKE` / `ILIKE` must declare backslash as its escape\n * character. PostgreSQL's default LIKE escape is already backslash, so this\n * clause is a no-op there; SQLite has *no* default escape character, so without\n * it an escaped `\\%` matches a literal backslash followed by any character —\n * silently diverging from Postgres. Emitting it on every compiled predicate\n * makes the two backends match by construction.\n */\nimport { sql, type SqlFragment } from \"../sql-fragment\";\n\n/**\n * The backslash escape character used by the JS pattern builder\n * (`compileStringPattern` in `compiler/predicates.ts`) to prefix the literal\n * `%`, `_`, and `\\` in user input. It must match the character declared by\n * {@link likeEscapeClause}: the builder prefixes wildcards with this character,\n * and the clause tells SQL to treat it as the escape. Both are backslash.\n */\nexport const LIKE_ESCAPE_CHARACTER = \"\\\\\";\n\n/**\n * `ESCAPE '\\'` clause appended to every compiled `LIKE` / `ILIKE` predicate,\n * declaring {@link LIKE_ESCAPE_CHARACTER} as the escape character. The single\n * backslash inside the quotes is a literal in both PostgreSQL (with\n * `standard_conforming_strings`, the default) and SQLite.\n */\nexport const likeEscapeClause: SqlFragment = sql`ESCAPE '\\\\'`;\n"]}
1
+ {"version":3,"sources":["../src/utils/global-symbol.ts","../src/query/dialect/profile.ts","../src/query/sql-intent.ts","../src/query/sql-fragment.ts","../src/query/dialect/like-escape.ts"],"names":[],"mappings":";;;AAYO,SAAS,sBACd,IAAA,EACS;AACT,EAAA,uBAAO,MAAA,CAAO,GAAA,CAAI,CAAA,oBAAA,EAAuB,IAAI,CAAA,CAAE,CAAA;AACjD;;;ACRA,IAAM,oBAAA,GAAuB;AAAA,EAC3B,QAAA,EAAU;AAAA,IACR,SAAA,EAAW,CAAC,KAAA,KAAmB,KAAA;AAAA,IAC/B,oBAAA,EAAsB,CAAC,KAAA,KAAoB,KAAA,GAAQ,MAAA,GAAS,OAAA;AAAA,IAC5D,WAAA,EAAa,CAAC,KAAA,KAAkB,CAAA,CAAA,EAAI,KAAK,CAAA;AAAA,GAC3C;AAAA,EACA,MAAA,EAAQ;AAAA,IACN,SAAA,EAAW,CAAC,KAAA,KACV,OAAO,UAAU,SAAA,GACf,KAAA,GAAQ,IACN,CAAA,GACF,KAAA;AAAA,IACJ,oBAAA,EAAsB,CAAC,KAAA,KAAoB,KAAA,GAAQ,GAAA,GAAM,GAAA;AAAA,IACzD,aAAa,MAAM;AAAA;AAEvB,CAAA;AAEA,IAAM,4BAAA,GAA+B;AAAA,EACnC,QAAA,EAAU,CAAC,KAAA,KAAkB;AAC3B,IAAA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,EAAA,MAAM,IAAI,mBAAmB,wCAAA,EAA0C;AAAA,IACrE;AAAA,GACD,CAAA;AACH;AAQO,SAAS,eAAA,CACd,UACA,OAAA,EACQ;AACR,EAAA,MAAM,QAAkB,EAAC;AAEzB,EAAA,KAAA,MAAW,IAAA,IAAQ,SAAA,CAAU,QAAQ,CAAA,EAAG;AACtC,IAAA,QAAQ,KAAK,IAAA;AAAM,MACjB,KAAK,MAAA,EAAQ;AACX,QAAA,KAAA,CAAM,IAAA,CAAK,KAAK,KAAK,CAAA;AACrB,QAAA;AAAA,MACF;AAAA,MACA,KAAK,YAAA,EAAc;AACjB,QAAA,KAAA,CAAM,IAAA,CAAK,gBAAA,CAAiB,IAAA,CAAK,KAAK,CAAC,CAAA;AACvC,QAAA;AAAA,MACF;AAAA,MACA,KAAK,WAAA,EAAa;AAChB,QAAA,KAAA,CAAM,IAAA,CAAK,aAAA,CAAc,IAAA,CAAK,KAAA,EAAO,OAAO,CAAC,CAAA;AAC7C,QAAA;AAAA,MACF;AAAA,MACA,KAAK,aAAA,EAAe;AAClB,QAAA,MAAM,IAAI,kBAAA;AAAA,UACR,CAAA,0CAAA,EAA6C,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA,CAAA,CAAA;AAAA,UAC5D,EAAE,aAAA,EAAe,IAAA,CAAK,KAAA,CAAM,IAAA;AAAK,SACnC;AAAA,MACF;AAAA,MACA,SAAS;AACP,QAAA,wBAAA,CAAyB,IAAI,CAAA;AAAA,MAC/B;AAAA;AACF,EACF;AAEA,EAAA,OAAO,KAAA,CAAM,KAAK,EAAE,CAAA;AACtB;;;ACvWO,IAAM,qBAAA,GAAwB;AAQ9B,IAAM,gBAAA,GAAgC,GAAA,CAAA,WAAA","file":"chunk-M4GYQF2H.js","sourcesContent":["type TypeGraphGlobalSymbolName =\n | \"sql-fragment\"\n | \"sql-placeholder\"\n | \"sql-intent-registry\"\n | \"internal-temporary-writes-v1\"\n | \"external-recorded-read-source-v1\"\n | \"sql-schema-v1\"\n | \"store-runtime-v1\"\n | \"typegraph-recorded-read-source-v1\"\n | \"transaction-runtime-v1\";\n\n/** Returns a process-wide symbol shared across ESM/CJS package instances. */\nexport function typeGraphGlobalSymbol<TSymbol extends symbol>(\n name: TypeGraphGlobalSymbolName,\n): TSymbol {\n return Symbol.for(`@nicia-ai/typegraph/${name}`) as TSymbol;\n}\n","import { type SqlDialect } from \"./types\";\n\nexport type SqlDialectProfile = Readonly<{\n bindValue: (value: unknown) => unknown;\n booleanLiteralString: (value: boolean) => string;\n placeholder: (index: number) => string;\n}>;\n\nconst SQL_DIALECT_PROFILES = {\n postgres: {\n bindValue: (value: unknown) => value,\n booleanLiteralString: (value: boolean) => (value ? \"TRUE\" : \"FALSE\"),\n placeholder: (index: number) => `$${index}`,\n },\n sqlite: {\n bindValue: (value: unknown) =>\n typeof value === \"boolean\" ?\n value ? 1\n : 0\n : value,\n booleanLiteralString: (value: boolean) => (value ? \"1\" : \"0\"),\n placeholder: () => \"?\",\n },\n} satisfies Record<SqlDialect, SqlDialectProfile>;\n\nconst SQL_STRING_LITERAL_RENDERERS = {\n postgres: (value: string) => {\n if (value.includes(\"\\\\\")) {\n return `E'${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"'\", \"''\")}'`;\n }\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n },\n sqlite: (value: string) => `'${value.replaceAll(\"'\", \"''\")}'`,\n} satisfies Record<SqlDialect, (value: string) => string>;\n\n/** Returns the primitive rendering and binding rules for a SQL dialect. */\nexport function getSqlDialectProfile(dialect: SqlDialect): SqlDialectProfile {\n return SQL_DIALECT_PROFILES[dialect];\n}\n\n/** Maps a JavaScript value to the representation expected by a SQL driver. */\nexport function bindSqlValue(value: unknown, dialect: SqlDialect): unknown {\n if (value instanceof Date) return value.toISOString();\n return getSqlDialectProfile(dialect).bindValue(value);\n}\n\n/** Renders one SQL string literal using the dialect's escaping rules. */\nexport function inlineSqlStringLiteral(\n value: string,\n dialect: SqlDialect,\n): string {\n return SQL_STRING_LITERAL_RENDERERS[dialect](value);\n}\n","import { typeGraphGlobalSymbol } from \"../utils/global-symbol\";\nimport { type SqlFragment } from \"./sql-fragment\";\n\ndeclare const SqlIntentBrand: unique symbol;\n\nexport type SqlIntent = \"rows\" | \"statement\" | \"temporary-statement\";\n\nexport type IntentSql<I extends SqlIntent> = SqlFragment &\n Readonly<{ [SqlIntentBrand]: I }>;\n\nexport type CompiledRowsSql = IntentSql<\"rows\">;\nexport type CompiledSelectSql = CompiledRowsSql;\nexport type CompiledStatementSql = IntentSql<\"statement\">;\nexport type CompiledTemporaryStatementSql = IntentSql<\"temporary-statement\">;\n\nexport function asCompiledRowsSql(query: SqlFragment): CompiledRowsSql {\n return query as CompiledRowsSql;\n}\n\nexport function asCompiledSelectSql(query: SqlFragment): CompiledSelectSql {\n return asCompiledRowsSql(query);\n}\n\nexport function asCompiledStatementSql(\n query: SqlFragment,\n): CompiledStatementSql {\n return query as CompiledStatementSql;\n}\n\n/**\n * Marks an internal statement that may write only connection-local temporary\n * state. This is intentionally separate from the public raw-statement intent:\n * history-enabled stores block arbitrary raw writes but iterative graph\n * operations still need to manage ephemeral working tables.\n */\nexport function asCompiledTemporaryStatementSql(\n query: SqlFragment,\n): CompiledTemporaryStatementSql {\n return query as CompiledTemporaryStatementSql;\n}\n\n/**\n * Statements whose good plan depends on the bound parameter values —\n * e.g. an id-array membership filter where the array cardinality varies\n * per call. PostgreSQL's prepared-statement machinery switches to a\n * generic (parameter-blind) plan after five executions, which for these\n * statements is catastrophically wrong (measured 21ms -> 310ms on the\n * subgraph edge fetch). Marked statements are executed unnamed so every\n * call is planned against the actual parameters; the re-parse cost is\n * ~1ms, the generic-plan cliff it avoids is 10-300ms.\n */\ntype SqlIntentRegistry = Readonly<{\n annIndexScanQueries: WeakMap<SqlFragment, readonly string[]>;\n forceCustomPlanQueries: WeakSet<SqlFragment>;\n}>;\n\nconst SQL_INTENT_REGISTRY: unique symbol = typeGraphGlobalSymbol(\n \"sql-intent-registry\",\n);\nconst globalWithSqlIntentRegistry = globalThis as typeof globalThis &\n Readonly<{\n [SQL_INTENT_REGISTRY]?: SqlIntentRegistry;\n }>;\nconst sqlIntentRegistry =\n globalWithSqlIntentRegistry[SQL_INTENT_REGISTRY] ??\n (() => {\n const registry: SqlIntentRegistry = {\n annIndexScanQueries: new WeakMap(),\n forceCustomPlanQueries: new WeakSet(),\n };\n Object.defineProperty(globalWithSqlIntentRegistry, SQL_INTENT_REGISTRY, {\n configurable: false,\n enumerable: false,\n value: registry,\n writable: false,\n });\n return registry;\n })();\n\nexport function markForceCustomPlan(query: SqlFragment): void {\n sqlIntentRegistry.forceCustomPlanQueries.add(query);\n}\n\nexport function shouldForceCustomPlan(query: SqlFragment): boolean {\n return sqlIntentRegistry.forceCustomPlanQueries.has(query);\n}\n\n/**\n * Statements whose plan includes an engine ANN index scan (the inline\n * `.similarTo(..., { approximate: true })` branch). The PostgreSQL\n * backend wraps their execution with the same pgvector GUC overrides\n * the search facade applies (`hnsw.iterative_scan = strict_order` /\n * `ivfflat.iterative_scan = relaxed_order` on pgvector >= 0.8), so a\n * filtered approximate query keeps scanning past the default ef_search\n * frontier instead of starving. Carries the slot index types so the\n * backend knows which GUCs apply. Backends without GUC semantics\n * ignore the brand.\n */\nexport function markAnnIndexScan(\n query: SqlFragment,\n indexTypes: readonly string[],\n): void {\n sqlIntentRegistry.annIndexScanQueries.set(query, indexTypes);\n}\n\nexport function annIndexScanTypes(\n query: SqlFragment,\n): readonly string[] | undefined {\n return sqlIntentRegistry.annIndexScanQueries.get(query);\n}\n\n/** @internal Copies execution semantics when immutable fragments are composed. */\nexport function copySqlIntents(\n target: SqlFragment,\n sources: readonly SqlFragment[],\n): void {\n if (sources.some((source) => shouldForceCustomPlan(source))) {\n markForceCustomPlan(target);\n }\n\n const indexTypes = new Set<string>();\n for (const source of sources) {\n for (const indexType of annIndexScanTypes(source) ?? []) {\n indexTypes.add(indexType);\n }\n }\n if (indexTypes.size > 0) markAnnIndexScan(target, [...indexTypes]);\n}\n\n/**\n * Whether a compiled statement can be run as raw text (`executeRaw`) without\n * losing execution semantics. Both brands above ride on the SQL *object* and\n * are honored only by `backend.execute`: the force-custom-plan flag makes\n * PostgreSQL re-plan against the actual parameters (opposed to reusing a\n * cached statement), and the ANN-scan brand drives the pgvector iterative-scan\n * GUC wrapper. A statement carrying either must not be flattened to text and\n * cached — callers fall back to `backend.execute`. Keeping this predicate\n * beside the brands means a future brand updates one place, not every caller.\n */\nexport function isRawExecutable(query: SqlFragment): boolean {\n return (\n !shouldForceCustomPlan(query) && annIndexScanTypes(query) === undefined\n );\n}\n","import { ConfigurationError } from \"../errors\";\nimport { typeGraphGlobalSymbol } from \"../utils/global-symbol\";\nimport {\n bindSqlValue,\n getSqlDialectProfile,\n inlineSqlStringLiteral,\n} from \"./dialect/profile\";\nimport { type SqlDialect } from \"./dialect/types\";\nimport { copySqlIntents } from \"./sql-intent\";\n\n/** Nominal identity shared by every package entrypoint. */\nconst SQL_FRAGMENT_BRAND: unique symbol = typeGraphGlobalSymbol(\"sql-fragment\");\nconst SQL_PLACEHOLDER_BRAND: unique symbol =\n typeGraphGlobalSymbol(\"sql-placeholder\");\n\nexport type SqlTextChunk = Readonly<{\n kind: \"text\";\n value: string;\n}>;\n\nexport type SqlParameterChunk = Readonly<{\n kind: \"parameter\";\n value: unknown;\n}>;\n\nexport type SqlIdentifierChunk = Readonly<{\n kind: \"identifier\";\n value: string;\n}>;\n\nexport type SqlPlaceholderChunk = Readonly<{\n kind: \"placeholder\";\n value: Placeholder;\n}>;\n\n/** One immutable unit in a database-independent SQL fragment. */\nexport type SqlChunk =\n SqlTextChunk | SqlParameterChunk | SqlIdentifierChunk | SqlPlaceholderChunk;\n\n/**\n * An immutable, database-independent SQL expression.\n *\n * Fragments contain syntax and bound values as separate nodes. A database\n * adapter renders the same fragment with its native placeholder convention at\n * the final execution boundary.\n */\nexport type SqlFragment = Readonly<{\n [SQL_FRAGMENT_BRAND]: true;\n append: (fragment: SqlFragment) => SqlFragment;\n chunks: readonly SqlChunk[];\n}>;\n\n/** A named value resolved when a prepared statement is executed. */\nexport class Placeholder {\n readonly [SQL_PLACEHOLDER_BRAND] = true as const;\n readonly name: string;\n\n constructor(name: string) {\n this.name = name;\n Object.freeze(this);\n }\n}\n\nclass SqlFragmentValue implements SqlFragment {\n readonly [SQL_FRAGMENT_BRAND] = true as const;\n\n readonly chunks: readonly SqlChunk[];\n\n constructor(chunks: readonly SqlChunk[]) {\n this.chunks = Object.freeze([...chunks]);\n Object.freeze(this);\n }\n\n append(fragment: SqlFragment): SqlFragment {\n return createFragment(\n [...this.chunks, ...getChunks(fragment)],\n [this, fragment],\n );\n }\n}\n\nfunction createFragment(\n chunks: readonly SqlChunk[],\n intentSources: readonly SqlFragment[] = [],\n): SqlFragment {\n const fragment = new SqlFragmentValue(chunks);\n copySqlIntents(fragment, intentSources);\n return fragment;\n}\n\nfunction getChunks(fragment: SqlFragment): readonly SqlChunk[] {\n if (!isSqlFragment(fragment)) {\n throw new ConfigurationError(\n \"Expected a SQL fragment created by TypeGraph's sql helper\",\n );\n }\n return fragment.chunks;\n}\n\n/** Returns whether a value is a TypeGraph-owned SQL fragment. */\nexport function isSqlFragment(value: unknown): value is SqlFragment {\n return (\n typeof value === \"object\" &&\n value !== null &&\n SQL_FRAGMENT_BRAND in value &&\n value[SQL_FRAGMENT_BRAND] === true &&\n \"chunks\" in value &&\n Array.isArray(value.chunks) &&\n \"append\" in value &&\n typeof value.append === \"function\"\n );\n}\n\n/** Returns whether a value is a TypeGraph named SQL placeholder. */\nexport function isSqlPlaceholder(value: unknown): value is Placeholder {\n return (\n typeof value === \"object\" &&\n value !== null &&\n SQL_PLACEHOLDER_BRAND in value &&\n value[SQL_PLACEHOLDER_BRAND] === true &&\n \"name\" in value &&\n typeof value.name === \"string\"\n );\n}\n\n/** @internal Enforces exhaustive handling at every fragment boundary. */\nexport function throwUnsupportedSqlChunk(chunk: never): never {\n throw new ConfigurationError(\"Unsupported SQL fragment chunk\", { chunk });\n}\n\nfunction textNode(value: string): SqlTextChunk {\n return Object.freeze({ kind: \"text\", value });\n}\n\nfunction parameterNode(value: unknown): SqlParameterChunk {\n return Object.freeze({ kind: \"parameter\", value });\n}\n\nfunction identifierNode(value: string): SqlIdentifierChunk {\n return Object.freeze({ kind: \"identifier\", value });\n}\n\nfunction placeholderNode(value: Placeholder): SqlPlaceholderChunk {\n return Object.freeze({ kind: \"placeholder\", value });\n}\n\nfunction templateSql(\n strings: TemplateStringsArray,\n ...values: readonly unknown[]\n): SqlFragment {\n const chunks: SqlChunk[] = [];\n const intentSources: SqlFragment[] = [];\n\n for (const [index, text] of strings.entries()) {\n if (text.length > 0) chunks.push(textNode(text));\n\n if (index >= values.length) continue;\n const value = values[index];\n if (isSqlFragment(value)) {\n chunks.push(...getChunks(value));\n intentSources.push(value);\n } else if (isSqlPlaceholder(value)) {\n chunks.push(placeholderNode(value));\n } else {\n chunks.push(parameterNode(value));\n }\n }\n\n return createFragment(chunks, intentSources);\n}\n\nfunction rawSql(value: string): SqlFragment {\n return createFragment(value.length === 0 ? [] : [textNode(value)]);\n}\n\nfunction identifierSql(value: string): SqlFragment {\n return createFragment([identifierNode(value)]);\n}\n\nfunction joinSql(\n fragments: readonly SqlFragment[],\n separator: SqlFragment = EMPTY_SQL,\n): SqlFragment {\n const chunks: SqlChunk[] = [];\n const intentSources: SqlFragment[] = [separator];\n\n for (const [index, fragment] of fragments.entries()) {\n if (index > 0) chunks.push(...getChunks(separator));\n chunks.push(...getChunks(fragment));\n intentSources.push(fragment);\n }\n\n return createFragment(chunks, intentSources);\n}\n\nfunction placeholderSql(name: string): SqlFragment {\n return createFragment([placeholderNode(new Placeholder(name))]);\n}\n\nconst EMPTY_SQL = createFragment([]);\n\n/** TypeGraph's database-independent SQL template and composition helpers. */\nexport type SqlTag = Readonly<{\n empty: () => SqlFragment;\n identifier: (value: string) => SqlFragment;\n join: (\n fragments: readonly SqlFragment[],\n separator?: SqlFragment,\n ) => SqlFragment;\n placeholder: (name: string) => SqlFragment;\n raw: (value: string) => SqlFragment;\n}> &\n ((\n strings: TemplateStringsArray,\n ...values: readonly unknown[]\n ) => SqlFragment);\n\n/** TypeGraph's database-independent SQL template and composition helpers. */\nexport const sql: SqlTag = Object.assign(templateSql, {\n empty: function empty(): SqlFragment {\n return EMPTY_SQL;\n },\n identifier: identifierSql,\n join: joinSql,\n placeholder: placeholderSql,\n raw: rawSql,\n});\n\n/** A rendered statement and its ordered bound parameters. */\nexport type RenderedSql = Readonly<{\n sql: string;\n params: readonly unknown[];\n}>;\n\nfunction quotedIdentifier(identifier: string): string {\n return `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction resolvedPlaceholder(\n placeholder: Placeholder,\n bindings: Readonly<Record<string, unknown>> | undefined,\n dialect: SqlDialect,\n): unknown {\n if (bindings === undefined) return placeholder;\n\n if (!Object.hasOwn(bindings, placeholder.name)) {\n throw new ConfigurationError(\n `Missing binding for parameter \"${placeholder.name}\"`,\n { parameterName: placeholder.name },\n );\n }\n return bindSqlValue(bindings[placeholder.name], dialect);\n}\n\n/**\n * Renders a fragment for a database adapter.\n *\n * Named placeholders remain in `params` when `bindings` is omitted, allowing\n * a prepared template to resolve them later. Passing `bindings` resolves every\n * placeholder eagerly.\n */\nexport function renderSql(\n fragment: SqlFragment,\n dialect: SqlDialect,\n bindings?: Readonly<Record<string, unknown>>,\n): RenderedSql {\n const parts: string[] = [];\n const params: unknown[] = [];\n const profile = getSqlDialectProfile(dialect);\n\n for (const node of getChunks(fragment)) {\n switch (node.kind) {\n case \"text\": {\n parts.push(node.value);\n break;\n }\n case \"identifier\": {\n parts.push(quotedIdentifier(node.value));\n break;\n }\n case \"parameter\": {\n params.push(bindSqlValue(node.value, dialect));\n parts.push(profile.placeholder(params.length));\n break;\n }\n case \"placeholder\": {\n params.push(resolvedPlaceholder(node.value, bindings, dialect));\n parts.push(profile.placeholder(params.length));\n break;\n }\n default: {\n throwUnsupportedSqlChunk(node);\n }\n }\n }\n\n return Object.freeze({\n sql: parts.join(\"\"),\n params: Object.freeze(params),\n });\n}\n\n/** Renders a fragment using SQLite's `?` placeholders. */\nexport function renderSqlite(\n fragment: SqlFragment,\n bindings?: Readonly<Record<string, unknown>>,\n): RenderedSql {\n return renderSql(fragment, \"sqlite\", bindings);\n}\n\n/** Renders a fragment using PostgreSQL's numbered placeholders. */\nexport function renderPostgres(\n fragment: SqlFragment,\n bindings?: Readonly<Record<string, unknown>>,\n): RenderedSql {\n return renderSql(fragment, \"postgres\", bindings);\n}\n\nfunction inlineLiteral(value: unknown, dialect: SqlDialect): string {\n if (value === undefined || value === null) return \"NULL\";\n if (typeof value === \"string\") return inlineSqlStringLiteral(value, dialect);\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new ConfigurationError(\"Cannot inline a non-finite SQL number\", {\n value,\n });\n }\n return String(value);\n }\n if (typeof value === \"bigint\") return String(value);\n if (typeof value === \"boolean\") {\n return getSqlDialectProfile(dialect).booleanLiteralString(value);\n }\n if (value instanceof Date) {\n return inlineSqlStringLiteral(value.toISOString(), dialect);\n }\n\n throw new ConfigurationError(\"Cannot inline this SQL parameter value\", {\n value,\n });\n}\n\n/**\n * Renders a fragment with safe scalar literals instead of bound parameters.\n *\n * This is intentionally limited to DDL paths whose drivers cannot bind values.\n * Application queries should always use {@link renderSql}.\n */\nexport function renderSqlInline(\n fragment: SqlFragment,\n dialect: SqlDialect,\n): string {\n const parts: string[] = [];\n\n for (const node of getChunks(fragment)) {\n switch (node.kind) {\n case \"text\": {\n parts.push(node.value);\n break;\n }\n case \"identifier\": {\n parts.push(quotedIdentifier(node.value));\n break;\n }\n case \"parameter\": {\n parts.push(inlineLiteral(node.value, dialect));\n break;\n }\n case \"placeholder\": {\n throw new ConfigurationError(\n `Cannot inline unresolved SQL placeholder \"${node.value.name}\"`,\n { parameterName: node.value.name },\n );\n }\n default: {\n throwUnsupportedSqlChunk(node);\n }\n }\n }\n\n return parts.join(\"\");\n}\n","/**\n * Shared LIKE-escape clause for the query compiler.\n *\n * The compiler builds `contains` / `startsWith` / `endsWith` patterns by\n * escaping the literal `%`, `_`, and `\\` in user input with a backslash (see\n * the pattern builders in `compiler/predicates.ts`). For that escaping to take\n * effect the emitted `LIKE` / `ILIKE` must declare backslash as its escape\n * character. PostgreSQL's default LIKE escape is already backslash, so this\n * clause is a no-op there; SQLite has *no* default escape character, so without\n * it an escaped `\\%` matches a literal backslash followed by any character —\n * silently diverging from Postgres. Emitting it on every compiled predicate\n * makes the two backends match by construction.\n */\nimport { sql, type SqlFragment } from \"../sql-fragment\";\n\n/**\n * The backslash escape character used by the JS pattern builder\n * (`compileStringPattern` in `compiler/predicates.ts`) to prefix the literal\n * `%`, `_`, and `\\` in user input. It must match the character declared by\n * {@link likeEscapeClause}: the builder prefixes wildcards with this character,\n * and the clause tells SQL to treat it as the escape. Both are backslash.\n */\nexport const LIKE_ESCAPE_CHARACTER = \"\\\\\";\n\n/**\n * `ESCAPE '\\'` clause appended to every compiled `LIKE` / `ILIKE` predicate,\n * declaring {@link LIKE_ESCAPE_CHARACTER} as the escape character. The single\n * backslash inside the quotes is a literal in both PostgreSQL (with\n * `standard_conforming_strings`, the default) and SQLite.\n */\nexport const likeEscapeClause: SqlFragment = sql`ESCAPE '\\\\'`;\n"]}
@@ -1,7 +1,7 @@
1
- import { createPostgresBackend } from './chunk-EFZ4S22A.js';
2
- import { tables, generatePostgresMigrationSQL, generatePostgresDDL } from './chunk-5J4VNCUD.js';
3
- import { wrapWithManagedClose, closeAfterFailure } from './chunk-L5ET7FYQ.js';
4
- import { ConfigurationError } from './chunk-DPNA466P.js';
1
+ import { createPostgresBackend } from './chunk-YPVQYM3L.js';
2
+ import { tables, generatePostgresMigrationSQL, generatePostgresDDL } from './chunk-Z3WIL6S3.js';
3
+ import { wrapWithManagedClose, closeAfterFailure } from './chunk-UZLEQFTV.js';
4
+ import { ConfigurationError } from './chunk-OYJSYDIH.js';
5
5
  import { PGlite } from '@electric-sql/pglite';
6
6
  import { drizzle } from 'drizzle-orm/pglite';
7
7
 
@@ -43,5 +43,5 @@ async function createLocalPgliteBackend(options = {}) {
43
43
  }
44
44
 
45
45
  export { createLocalPgliteBackend };
46
- //# sourceMappingURL=chunk-ZE7E46IZ.js.map
47
- //# sourceMappingURL=chunk-ZE7E46IZ.js.map
46
+ //# sourceMappingURL=chunk-NXIZL7ZZ.js.map
47
+ //# sourceMappingURL=chunk-NXIZL7ZZ.js.map