@nicia-ai/typegraph 0.32.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (264) hide show
  1. package/README.md +51 -0
  2. package/dist/backend/postgres/index.cjs +36 -19
  3. package/dist/backend/postgres/index.d.cts +6 -6
  4. package/dist/backend/postgres/index.d.ts +6 -6
  5. package/dist/backend/postgres/index.js +14 -9
  6. package/dist/backend/postgres/pglite.cjs +18 -13
  7. package/dist/backend/postgres/pglite.cjs.map +1 -1
  8. package/dist/backend/postgres/pglite.d.cts +3 -3
  9. package/dist/backend/postgres/pglite.d.ts +3 -3
  10. package/dist/backend/postgres/pglite.js +14 -9
  11. package/dist/backend/postgres/pglite.js.map +1 -1
  12. package/dist/backend/sqlite/index.cjs +34 -17
  13. package/dist/backend/sqlite/index.d.cts +7 -7
  14. package/dist/backend/sqlite/index.d.ts +7 -7
  15. package/dist/backend/sqlite/index.js +13 -8
  16. package/dist/backend/sqlite/libsql.cjs +19 -14
  17. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  18. package/dist/backend/sqlite/libsql.d.cts +12 -5
  19. package/dist/backend/sqlite/libsql.d.ts +12 -5
  20. package/dist/backend/sqlite/libsql.js +15 -10
  21. package/dist/backend/sqlite/libsql.js.map +1 -1
  22. package/dist/backend/sqlite/local.cjs +19 -14
  23. package/dist/backend/sqlite/local.cjs.map +1 -1
  24. package/dist/backend/sqlite/local.d.cts +3 -3
  25. package/dist/backend/sqlite/local.d.ts +3 -3
  26. package/dist/backend/sqlite/local.js +14 -9
  27. package/dist/backend/sqlite/local.js.map +1 -1
  28. package/dist/chunk-2EBMPJBO.js +16 -0
  29. package/dist/chunk-2EBMPJBO.js.map +1 -0
  30. package/dist/{chunk-CFNT3ITG.cjs → chunk-2JXB3NYJ.cjs} +15 -35
  31. package/dist/chunk-2JXB3NYJ.cjs.map +1 -0
  32. package/dist/chunk-2MRAX3UE.js +105 -0
  33. package/dist/chunk-2MRAX3UE.js.map +1 -0
  34. package/dist/{chunk-2LAT5BIK.cjs → chunk-3BRVBQQD.cjs} +2328 -3131
  35. package/dist/chunk-3BRVBQQD.cjs.map +1 -0
  36. package/dist/chunk-3E7SNSIA.cjs +55 -0
  37. package/dist/chunk-3E7SNSIA.cjs.map +1 -0
  38. package/dist/{chunk-FDN43KXV.cjs → chunk-3Z6TW3CT.cjs} +20 -19
  39. package/dist/chunk-3Z6TW3CT.cjs.map +1 -0
  40. package/dist/{chunk-IJORSAC3.js → chunk-4DIBPQNJ.js} +6 -4
  41. package/dist/chunk-4DIBPQNJ.js.map +1 -0
  42. package/dist/chunk-4S2FXGBJ.js +9 -0
  43. package/dist/chunk-4S2FXGBJ.js.map +1 -0
  44. package/dist/chunk-5IQIX7LU.cjs +2070 -0
  45. package/dist/chunk-5IQIX7LU.cjs.map +1 -0
  46. package/dist/{chunk-CWFPJ3RC.js → chunk-6GNSY7AV.js} +3 -3
  47. package/dist/{chunk-CWFPJ3RC.js.map → chunk-6GNSY7AV.js.map} +1 -1
  48. package/dist/{chunk-LAZGHOZW.cjs → chunk-6HVOHZHS.cjs} +184 -117
  49. package/dist/chunk-6HVOHZHS.cjs.map +1 -0
  50. package/dist/chunk-6SCVW4AS.js +20 -0
  51. package/dist/chunk-6SCVW4AS.js.map +1 -0
  52. package/dist/chunk-A7SZZFAG.js +2010 -0
  53. package/dist/chunk-A7SZZFAG.js.map +1 -0
  54. package/dist/chunk-ACSVZPK7.cjs +21 -0
  55. package/dist/chunk-ACSVZPK7.cjs.map +1 -0
  56. package/dist/{chunk-MXE2U3EX.js → chunk-BVTWD66D.js} +4 -115
  57. package/dist/chunk-BVTWD66D.js.map +1 -0
  58. package/dist/{chunk-W4ZX2GCP.js → chunk-CHXTTSC6.js} +5 -39
  59. package/dist/chunk-CHXTTSC6.js.map +1 -0
  60. package/dist/{chunk-XQFAJVYW.js → chunk-CYX2JTDG.js} +124 -5
  61. package/dist/chunk-CYX2JTDG.js.map +1 -0
  62. package/dist/{chunk-PRMKPFN5.js → chunk-DEQFL35G.js} +4 -3
  63. package/dist/chunk-DEQFL35G.js.map +1 -0
  64. package/dist/chunk-DI74SMXS.cjs +29 -0
  65. package/dist/chunk-DI74SMXS.cjs.map +1 -0
  66. package/dist/{chunk-WWVV44DY.cjs → chunk-G6SOJEDI.cjs} +11 -11
  67. package/dist/{chunk-WWVV44DY.cjs.map → chunk-G6SOJEDI.cjs.map} +1 -1
  68. package/dist/{chunk-LM2IC4ZJ.cjs → chunk-GQANNXXT.cjs} +15 -14
  69. package/dist/chunk-GQANNXXT.cjs.map +1 -0
  70. package/dist/chunk-GZCNZ7QW.js +24 -0
  71. package/dist/chunk-GZCNZ7QW.js.map +1 -0
  72. package/dist/{chunk-KTIEB7VH.cjs → chunk-HK5SATYM.cjs} +35 -58
  73. package/dist/chunk-HK5SATYM.cjs.map +1 -0
  74. package/dist/chunk-HMFK4BXR.cjs +12 -0
  75. package/dist/{chunk-6ZR4QC3O.cjs.map → chunk-HMFK4BXR.cjs.map} +1 -1
  76. package/dist/chunk-ITE4IXAK.js +25 -0
  77. package/dist/chunk-ITE4IXAK.js.map +1 -0
  78. package/dist/chunk-JJRCLAUN.cjs +155 -0
  79. package/dist/chunk-JJRCLAUN.cjs.map +1 -0
  80. package/dist/{chunk-ZFWNO3GE.cjs → chunk-JQGIPGVL.cjs} +66 -2
  81. package/dist/chunk-JQGIPGVL.cjs.map +1 -0
  82. package/dist/{chunk-2BVHPOIG.js → chunk-K2TGS3EN.js} +105 -38
  83. package/dist/chunk-K2TGS3EN.js.map +1 -0
  84. package/dist/chunk-K34OPSJK.js +29 -0
  85. package/dist/chunk-K34OPSJK.js.map +1 -0
  86. package/dist/{chunk-YW7GHMF4.cjs → chunk-KGC4LY5T.cjs} +18 -17
  87. package/dist/chunk-KGC4LY5T.cjs.map +1 -0
  88. package/dist/{chunk-SB65GJNY.cjs → chunk-KNHYNQQ3.cjs} +111 -72
  89. package/dist/chunk-KNHYNQQ3.cjs.map +1 -0
  90. package/dist/{chunk-C4C4Q7A6.js → chunk-KUTNI6SI.js} +6 -21
  91. package/dist/chunk-KUTNI6SI.js.map +1 -0
  92. package/dist/{chunk-NDM5PXEH.js → chunk-LANHCOXB.js} +44 -11
  93. package/dist/chunk-LANHCOXB.js.map +1 -0
  94. package/dist/chunk-N6WTUSBV.cjs +23 -0
  95. package/dist/chunk-N6WTUSBV.cjs.map +1 -0
  96. package/dist/{chunk-73KASJGO.cjs → chunk-NAUA4PW5.cjs} +4 -28
  97. package/dist/chunk-NAUA4PW5.cjs.map +1 -0
  98. package/dist/chunk-QV245VMN.js +145 -0
  99. package/dist/chunk-QV245VMN.js.map +1 -0
  100. package/dist/{chunk-CEF2QOTO.js → chunk-RBV7YCQD.js} +4 -3
  101. package/dist/chunk-RBV7YCQD.js.map +1 -0
  102. package/dist/chunk-RHZWOJVA.cjs +109 -0
  103. package/dist/chunk-RHZWOJVA.cjs.map +1 -0
  104. package/dist/{chunk-6RMLO5O4.cjs → chunk-RRKQAKD6.cjs} +13 -11
  105. package/dist/chunk-RRKQAKD6.cjs.map +1 -0
  106. package/dist/{chunk-TUA3MEJJ.js → chunk-RY2VIWAM.js} +612 -564
  107. package/dist/chunk-RY2VIWAM.js.map +1 -0
  108. package/dist/{chunk-PIHXFF73.js → chunk-SHLY4MCM.js} +3 -3
  109. package/dist/{chunk-PIHXFF73.js.map → chunk-SHLY4MCM.js.map} +1 -1
  110. package/dist/{chunk-HFBRAOF7.js → chunk-T2DWPQNE.js} +103 -64
  111. package/dist/chunk-T2DWPQNE.js.map +1 -0
  112. package/dist/{chunk-WYTUF3QO.js → chunk-T46GR2VY.js} +3 -3
  113. package/dist/{chunk-WYTUF3QO.js.map → chunk-T46GR2VY.js.map} +1 -1
  114. package/dist/{chunk-EEYV6UOE.cjs → chunk-T6SPUYLX.cjs} +5 -43
  115. package/dist/chunk-T6SPUYLX.cjs.map +1 -0
  116. package/dist/{chunk-3QRBXYT5.cjs → chunk-TGJE22RM.cjs} +6 -6
  117. package/dist/{chunk-3QRBXYT5.cjs.map → chunk-TGJE22RM.cjs.map} +1 -1
  118. package/dist/{chunk-YL4F3CMD.cjs → chunk-TOTPVGOG.cjs} +105 -72
  119. package/dist/chunk-TOTPVGOG.cjs.map +1 -0
  120. package/dist/{chunk-3HQDMOBK.cjs → chunk-UJLOZYKT.cjs} +680 -636
  121. package/dist/chunk-UJLOZYKT.cjs.map +1 -0
  122. package/dist/chunk-UNNPKQUG.cjs +1390 -0
  123. package/dist/chunk-UNNPKQUG.cjs.map +1 -0
  124. package/dist/chunk-UR7W5YQK.js +18 -0
  125. package/dist/chunk-UR7W5YQK.js.map +1 -0
  126. package/dist/chunk-V3QNTB7Z.js +1351 -0
  127. package/dist/chunk-V3QNTB7Z.js.map +1 -0
  128. package/dist/{chunk-XKNAK27R.js → chunk-VCGO4V26.js} +4 -3
  129. package/dist/chunk-VCGO4V26.js.map +1 -0
  130. package/dist/{chunk-YQGLVWB2.cjs → chunk-WL2SG7ZV.cjs} +6 -122
  131. package/dist/chunk-WL2SG7ZV.cjs.map +1 -0
  132. package/dist/{chunk-WNORITK6.js → chunk-WLRIWYHQ.js} +2041 -2834
  133. package/dist/chunk-WLRIWYHQ.js.map +1 -0
  134. package/dist/{chunk-JKRKIEVA.cjs → chunk-WVC2Q2FD.cjs} +128 -6
  135. package/dist/chunk-WVC2Q2FD.cjs.map +1 -0
  136. package/dist/chunk-XLUNB2TZ.js +53 -0
  137. package/dist/chunk-XLUNB2TZ.js.map +1 -0
  138. package/dist/chunk-XXVEULWX.js +39 -0
  139. package/dist/chunk-XXVEULWX.js.map +1 -0
  140. package/dist/chunk-YAZE7QZR.cjs +32 -0
  141. package/dist/chunk-YAZE7QZR.cjs.map +1 -0
  142. package/dist/chunk-YC6PWTHY.cjs +44 -0
  143. package/dist/chunk-YC6PWTHY.cjs.map +1 -0
  144. package/dist/chunk-Z5HBYM7U.cjs +11 -0
  145. package/dist/chunk-Z5HBYM7U.cjs.map +1 -0
  146. package/dist/{chunk-454I6GDF.js → chunk-Z5XBMDXU.js} +63 -3
  147. package/dist/chunk-Z5XBMDXU.js.map +1 -0
  148. package/dist/{chunk-CAMMC3E4.cjs → chunk-ZP5WHI4C.cjs} +109 -81
  149. package/dist/chunk-ZP5WHI4C.cjs.map +1 -0
  150. package/dist/{chunk-YCV72E6L.js → chunk-ZURTTSCM.js} +4 -25
  151. package/dist/chunk-ZURTTSCM.js.map +1 -0
  152. package/dist/{chunk-7WW3WL6E.js → chunk-ZV5N4DBG.js} +49 -21
  153. package/dist/chunk-ZV5N4DBG.js.map +1 -0
  154. package/dist/chunk-ZY4GXIVN.cjs +32 -0
  155. package/dist/chunk-ZY4GXIVN.cjs.map +1 -0
  156. package/dist/{ddl-C8e8zDAE.d.ts → ddl-BrmPg61z.d.ts} +3 -3
  157. package/dist/{ddl-CwyG4HoQ.d.cts → ddl-j1-sH6lE.d.cts} +3 -3
  158. package/dist/{extension-types-D1k0inWU.d.cts → extension-types-YGFJPrzK.d.cts} +1 -1
  159. package/dist/{extension-types-D1k0inWU.d.ts → extension-types-YGFJPrzK.d.ts} +1 -1
  160. package/dist/graph-extension/index.cjs +18 -17
  161. package/dist/graph-extension/index.d.cts +4 -4
  162. package/dist/graph-extension/index.d.ts +4 -4
  163. package/dist/graph-extension/index.js +3 -2
  164. package/dist/graph-merge/index.cjs +295 -146
  165. package/dist/graph-merge/index.cjs.map +1 -1
  166. package/dist/graph-merge/index.d.cts +6 -6
  167. package/dist/graph-merge/index.d.ts +6 -6
  168. package/dist/graph-merge/index.js +173 -24
  169. package/dist/graph-merge/index.js.map +1 -1
  170. package/dist/{index-BEK0VtNB.d.ts → index-DGX6D9j1.d.ts} +2 -2
  171. package/dist/{index-C8sSTErx.d.cts → index-SEvUHDA6.d.cts} +2 -2
  172. package/dist/index.cjs +206 -172
  173. package/dist/index.cjs.map +1 -1
  174. package/dist/index.d.cts +25 -55
  175. package/dist/index.d.ts +25 -55
  176. package/dist/index.js +32 -22
  177. package/dist/index.js.map +1 -1
  178. package/dist/indexes/index.cjs +28 -25
  179. package/dist/indexes/index.d.cts +5 -5
  180. package/dist/indexes/index.d.ts +5 -5
  181. package/dist/indexes/index.js +10 -7
  182. package/dist/interchange/index.cjs +25 -16
  183. package/dist/interchange/index.d.cts +5 -5
  184. package/dist/interchange/index.d.ts +5 -5
  185. package/dist/interchange/index.js +12 -3
  186. package/dist/{manager-8htmuGr-.d.ts → manager-BZUeN_BU.d.ts} +2 -2
  187. package/dist/{manager-aVgxbGt-.d.cts → manager-ms9cKdc6.d.cts} +2 -2
  188. package/dist/{materialize-indexes-CAGhqPHQ.d.ts → materialize-indexes-CAkIYFV-.d.ts} +1 -1
  189. package/dist/{materialize-indexes-DEYkU-wr.d.cts → materialize-indexes-D20xNluI.d.cts} +1 -1
  190. package/dist/{postgres-Dhom7iiX.d.ts → postgres-BhpxGMC5.d.cts} +2651 -596
  191. package/dist/{postgres-jgXmD45C.d.cts → postgres-CWHLwNl1.d.ts} +2651 -596
  192. package/dist/profiler/index.cjs +5 -4
  193. package/dist/profiler/index.cjs.map +1 -1
  194. package/dist/profiler/index.d.cts +7 -7
  195. package/dist/profiler/index.d.ts +7 -7
  196. package/dist/profiler/index.js +3 -2
  197. package/dist/profiler/index.js.map +1 -1
  198. package/dist/provenance/index.cjs +591 -0
  199. package/dist/provenance/index.cjs.map +1 -0
  200. package/dist/provenance/index.d.cts +73 -0
  201. package/dist/provenance/index.d.ts +73 -0
  202. package/dist/provenance/index.js +589 -0
  203. package/dist/provenance/index.js.map +1 -0
  204. package/dist/schema/index.cjs +37 -32
  205. package/dist/schema/index.cjs.map +1 -1
  206. package/dist/schema/index.d.cts +7 -7
  207. package/dist/schema/index.d.ts +7 -7
  208. package/dist/schema/index.js +14 -9
  209. package/dist/schema/index.js.map +1 -1
  210. package/dist/{sqlite-DcQ_BCUW.d.cts → sqlite-CGu5SLsw.d.ts} +2726 -455
  211. package/dist/{sqlite-BfLsCEqO.d.ts → sqlite-XrDxNaa7.d.cts} +2726 -455
  212. package/dist/{store-view-pBOUrQte.d.ts → store-view-BlgnhEYf.d.ts} +467 -131
  213. package/dist/{store-view-lTcb_cnp.d.cts → store-view-D09po4H6.d.cts} +467 -131
  214. package/dist/{types-DGDiXAYc.d.ts → types-B1TbZJYS.d.ts} +2 -2
  215. package/dist/{types-Dk8r09KY.d.ts → types-D1Sqeyxy.d.ts} +161 -26
  216. package/dist/{types-5RQwzWXx.d.cts → types-DiE1AO7p.d.cts} +2 -2
  217. package/dist/{types-Dvmn-eal.d.cts → types-DkNnF-7K.d.cts} +161 -26
  218. package/dist/{where-Cx_glEEB.d.cts → where-DKjuofPr.d.cts} +2 -2
  219. package/dist/{where-CHZFELX0.d.ts → where-DrUIIWHb.d.ts} +2 -2
  220. package/package.json +8 -2
  221. package/dist/chunk-2BVHPOIG.js.map +0 -1
  222. package/dist/chunk-2LAT5BIK.cjs.map +0 -1
  223. package/dist/chunk-2YMGNYXY.js +0 -40
  224. package/dist/chunk-2YMGNYXY.js.map +0 -1
  225. package/dist/chunk-3HQDMOBK.cjs.map +0 -1
  226. package/dist/chunk-454I6GDF.js.map +0 -1
  227. package/dist/chunk-6G35I3VW.cjs +0 -40
  228. package/dist/chunk-6G35I3VW.cjs.map +0 -1
  229. package/dist/chunk-6RMLO5O4.cjs.map +0 -1
  230. package/dist/chunk-6ZR4QC3O.cjs +0 -12
  231. package/dist/chunk-73KASJGO.cjs.map +0 -1
  232. package/dist/chunk-7WW3WL6E.js.map +0 -1
  233. package/dist/chunk-C4C4Q7A6.js.map +0 -1
  234. package/dist/chunk-CAMMC3E4.cjs.map +0 -1
  235. package/dist/chunk-CEF2QOTO.js.map +0 -1
  236. package/dist/chunk-CFNT3ITG.cjs.map +0 -1
  237. package/dist/chunk-EEYV6UOE.cjs.map +0 -1
  238. package/dist/chunk-FDN43KXV.cjs.map +0 -1
  239. package/dist/chunk-HFBRAOF7.js.map +0 -1
  240. package/dist/chunk-IJORSAC3.js.map +0 -1
  241. package/dist/chunk-JKRKIEVA.cjs.map +0 -1
  242. package/dist/chunk-KTIEB7VH.cjs.map +0 -1
  243. package/dist/chunk-LAZGHOZW.cjs.map +0 -1
  244. package/dist/chunk-LM2IC4ZJ.cjs.map +0 -1
  245. package/dist/chunk-M6OC455F.js +0 -65
  246. package/dist/chunk-M6OC455F.js.map +0 -1
  247. package/dist/chunk-MXE2U3EX.js.map +0 -1
  248. package/dist/chunk-NDM5PXEH.js.map +0 -1
  249. package/dist/chunk-PRMKPFN5.js.map +0 -1
  250. package/dist/chunk-RP7YITHX.cjs +0 -70
  251. package/dist/chunk-RP7YITHX.cjs.map +0 -1
  252. package/dist/chunk-SAJSMR2B.js +0 -35
  253. package/dist/chunk-SAJSMR2B.js.map +0 -1
  254. package/dist/chunk-SB65GJNY.cjs.map +0 -1
  255. package/dist/chunk-TUA3MEJJ.js.map +0 -1
  256. package/dist/chunk-W4ZX2GCP.js.map +0 -1
  257. package/dist/chunk-WNORITK6.js.map +0 -1
  258. package/dist/chunk-XKNAK27R.js.map +0 -1
  259. package/dist/chunk-XQFAJVYW.js.map +0 -1
  260. package/dist/chunk-YCV72E6L.js.map +0 -1
  261. package/dist/chunk-YL4F3CMD.cjs.map +0 -1
  262. package/dist/chunk-YQGLVWB2.cjs.map +0 -1
  263. package/dist/chunk-YW7GHMF4.cjs.map +0 -1
  264. package/dist/chunk-ZFWNO3GE.cjs.map +0 -1
@@ -1,35 +0,0 @@
1
- // src/backend/types.ts
2
- function wrapWithManagedClose(backend, teardown) {
3
- let isClosed = false;
4
- return {
5
- ...backend,
6
- async close() {
7
- if (isClosed) return;
8
- isClosed = true;
9
- await backend.close();
10
- await teardown();
11
- }
12
- };
13
- }
14
- async function runOptionallyInTransaction(backend, fn, fallback) {
15
- if (!backend.capabilities.transactions) {
16
- return fn(fallback ?? backend);
17
- }
18
- return backend.transaction((tx) => fn(tx));
19
- }
20
- var SQLITE_CAPABILITIES = {
21
- transactions: true,
22
- // SQLite supports transactions
23
- windowFunctions: true
24
- // SQLite has supported window functions since 3.25.0
25
- };
26
- var POSTGRES_CAPABILITIES = {
27
- transactions: true,
28
- // PostgreSQL supports transactions
29
- windowFunctions: true
30
- // PostgreSQL supports ROW_NUMBER() and related windows
31
- };
32
-
33
- export { POSTGRES_CAPABILITIES, SQLITE_CAPABILITIES, runOptionallyInTransaction, wrapWithManagedClose };
34
- //# sourceMappingURL=chunk-SAJSMR2B.js.map
35
- //# sourceMappingURL=chunk-SAJSMR2B.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/backend/types.ts"],"names":[],"mappings":";AAkrCO,SAAS,oBAAA,CACd,SACA,QAAA,EACc;AACd,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,GAAG,OAAA;AAAA,IACH,MAAM,KAAA,GAAuB;AAC3B,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,MAAM,QAAQ,KAAA,EAAM;AACpB,MAAA,MAAM,QAAA,EAAS;AAAA,IACjB;AAAA,GACF;AACF;AAeA,eAAsB,0BAAA,CACpB,OAAA,EACA,EAAA,EACA,QAAA,EACY;AACZ,EAAA,IAAI,CAAC,OAAA,CAAQ,YAAA,CAAa,YAAA,EAAc;AACtC,IAAA,OAAO,EAAA,CAAG,YAAY,OAAO,CAAA;AAAA,EAC/B;AACA,EAAA,OAAO,QAAQ,WAAA,CAAY,CAAC,EAAA,KAAO,EAAA,CAAG,EAAE,CAAC,CAAA;AAC3C;AA0PO,IAAM,mBAAA,GAA2C;AAAA,EACtD,YAAA,EAAc,IAAA;AAAA;AAAA,EACd,eAAA,EAAiB;AAAA;AACnB;AAKO,IAAM,qBAAA,GAA6C;AAAA,EACxD,YAAA,EAAc,IAAA;AAAA;AAAA,EACd,eAAA,EAAiB;AAAA;AACnB","file":"chunk-SAJSMR2B.js","sourcesContent":["/**\n * Backend interface types for TypeGraph storage.\n *\n * The backend abstracts database operations, allowing different\n * SQL implementations (SQLite, PostgreSQL) behind a common interface.\n */\nimport { type SQL } from \"drizzle-orm\";\n\nimport {\n type IndexEntity,\n type KindEntity,\n type TemporalMode,\n} from \"../core/types\";\nimport { type SqlTableNames } from \"../query/compiler/schema\";\nimport { type FulltextStrategy } from \"../query/dialect/fulltext-strategy\";\nimport { type VectorStrategy } from \"../query/dialect/vector-strategy\";\nimport { type SerializedSchema } from \"../schema/types\";\nimport {\n type AnyPgDatabase,\n type AnySqliteDatabase,\n} from \"./drizzle/execution\";\n\n// ============================================================\n// Vector Search Types\n// ============================================================\n\n/**\n * Supported vector similarity metrics.\n */\nexport type VectorMetric = \"cosine\" | \"l2\" | \"inner_product\";\n\n/**\n * Supported vector index types.\n */\nexport type VectorIndexType = \"hnsw\" | \"ivfflat\" | \"none\";\n\n/**\n * Vector search capabilities.\n */\nexport type VectorCapabilities = Readonly<{\n /** Whether the backend supports vector operations */\n supported: boolean;\n /** Supported similarity metrics */\n metrics: readonly VectorMetric[];\n /** Supported index types */\n indexTypes: readonly VectorIndexType[];\n /** Maximum dimensions supported */\n maxDimensions: number;\n}>;\n\n// ============================================================\n// Fulltext Search Types\n// ============================================================\n\n/**\n * Query modes for fulltext search.\n *\n * - \"websearch\": Google-style syntax (quoted phrases, +required, -excluded).\n * Postgres: `websearch_to_tsquery`. SQLite: translated to FTS5 MATCH.\n * - \"phrase\": treats the whole query as a phrase.\n * Postgres: `phraseto_tsquery`. SQLite: FTS5 `\"...\"` phrase.\n * - \"plain\": splits on whitespace and ANDs terms.\n * Postgres: `plainto_tsquery`. SQLite: default FTS5 AND.\n * - \"raw\": dialect-native syntax passed through unchanged.\n */\nexport type FulltextQueryMode = \"websearch\" | \"phrase\" | \"plain\" | \"raw\";\n\n/**\n * Fulltext search capabilities declared by a backend.\n */\nexport type FulltextCapabilities = Readonly<{\n /** Whether the backend supports fulltext operations */\n supported: boolean;\n /**\n * Language / tokenizer names understood by this backend.\n * Postgres: installed regconfigs (english, simple, ...).\n * SQLite FTS5: tokenizer names (unicode61, porter, trigram).\n */\n languages: readonly string[];\n /** Whether phrase queries are supported. */\n phraseQueries: boolean;\n /** Whether prefix (`foo*`) queries are supported. */\n prefixQueries: boolean;\n /** Whether highlighting / snippets are supported. */\n highlighting: boolean;\n}>;\n\n// ============================================================\n// SQL Dialect & Capabilities\n// ============================================================\n\nimport { type SqlDialect } from \"../query/dialect/types\";\n\nexport type { SqlDialect } from \"../query/dialect/types\";\n\n/**\n * Backend capabilities that vary by dialect.\n */\nexport type BackendCapabilities = Readonly<{\n /** Whether the backend supports atomic transactions (D1 does not) */\n transactions: boolean;\n /** Whether the backend supports SQL window functions such as ROW_NUMBER() */\n windowFunctions: boolean;\n /** Vector search capabilities (undefined if not configured) */\n vector?: VectorCapabilities | undefined;\n /** Fulltext search capabilities (undefined if not configured) */\n fulltext?: FulltextCapabilities | undefined;\n}>;\n\n// ============================================================\n// Row Types (Database Records)\n// ============================================================\n\n/**\n * A row from the typegraph_nodes table.\n */\nexport type NodeRow = Readonly<{\n graph_id: string;\n kind: string;\n id: string;\n props: string; // JSON string\n version: number;\n valid_from: string | undefined;\n valid_to: string | undefined;\n created_at: string;\n updated_at: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_edges table.\n */\nexport type EdgeRow = Readonly<{\n graph_id: string;\n id: string;\n kind: string;\n from_kind: string;\n from_id: string;\n to_kind: string;\n to_id: string;\n props: string; // JSON string\n valid_from: string | undefined;\n valid_to: string | undefined;\n created_at: string;\n updated_at: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_node_uniques table.\n */\nexport type UniqueRow = Readonly<{\n graph_id: string;\n node_kind: string;\n constraint_name: string;\n key: string;\n node_id: string;\n concrete_kind: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_schema_versions table.\n */\nexport type SchemaVersionRow = Readonly<{\n graph_id: string;\n version: number;\n schema_hash: string;\n schema_doc: string; // JSON string\n created_at: string;\n is_active: boolean;\n}>;\n\n// ============================================================\n// Insert Parameters\n// ============================================================\n\n/**\n * Parameters for inserting a node.\n */\nexport type InsertNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validFrom?: string;\n validTo?: string;\n}>;\n\n/**\n * Parameters for updating a node.\n */\nexport type UpdateNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validTo?: string;\n incrementVersion?: boolean;\n /** If true, clears deleted_at (un-deletes the node). Used by upsert. */\n clearDeleted?: boolean;\n}>;\n\n/**\n * Parameters for deleting a node (soft delete).\n */\nexport type DeleteNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n}>;\n\n/**\n * Parameters for inserting an edge.\n */\nexport type InsertEdgeParams = Readonly<{\n graphId: string;\n id: string;\n kind: string;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n props: Readonly<Record<string, unknown>>;\n validFrom?: string;\n validTo?: string;\n}>;\n\n/**\n * Parameters for updating an edge.\n */\nexport type UpdateEdgeParams = Readonly<{\n graphId: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validTo?: string;\n clearDeleted?: boolean;\n}>;\n\n/**\n * Parameters for deleting an edge (soft delete).\n */\nexport type DeleteEdgeParams = Readonly<{\n graphId: string;\n id: string;\n}>;\n\n/**\n * Parameters for hard deleting a node (permanent removal).\n */\nexport type HardDeleteNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n}>;\n\n/**\n * Parameters for hard deleting an edge (permanent removal).\n */\nexport type HardDeleteEdgeParams = Readonly<{\n graphId: string;\n id: string;\n}>;\n\n// ============================================================\n// Embedding Parameters\n// ============================================================\n\n/**\n * Parameters for inserting or updating an embedding.\n *\n * `dimensions`, `metric`, and `indexType` together resolve the slot's\n * typed per-`(nodeKind, fieldPath)` storage (the strategy needs the fixed\n * dimension for the column type, and the metric/index type to address the\n * right ANN structure). The store populates them from the schema's\n * `embedding()` declaration via `getEmbeddingDimensions()` /\n * `getEmbeddingIndex()`; the backend constructs a `VectorSlot` from them\n * and stays graph-agnostic.\n */\nexport type UpsertEmbeddingParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n embedding: readonly number[];\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n}>;\n\n/**\n * Parameters for deleting an embedding.\n *\n * `dimensions` / `metric` / `indexType` mirror {@link UpsertEmbeddingParams}\n * so the backend can resolve the slot's typed per-`(nodeKind, fieldPath)`\n * storage and idempotently ensure it exists before the DELETE. That\n * matters because a delete can run before any embedding was ever written\n * (e.g. a node hard-deleted having never carried one), and on Postgres a\n * DELETE against a missing relation inside a transaction aborts the whole\n * transaction. The store populates them from the schema's `embedding()`\n * declaration, exactly as for upserts.\n */\nexport type DeleteEmbeddingParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n}>;\n\n/**\n * Parameters for vector similarity search.\n */\nexport type VectorSearchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n queryEmbedding: readonly number[];\n metric: VectorMetric;\n /**\n * Fixed vector dimension `N` for the searched `(nodeKind, fieldPath)`\n * slot. The store populates it from the schema's `embedding()`\n * declaration via `getEmbeddingDimensions()`; the backend uses it to\n * construct the `VectorSlot` whose typed storage the strategy scans.\n */\n dimensions: number;\n /**\n * Index type materialized for this slot. `\"none\"` means brute-force\n * only; otherwise the strategy may route through its ANN structure.\n * The store populates it from `getEmbeddingIndex()`.\n */\n indexType: VectorIndexType;\n limit: number;\n minScore?: number;\n /**\n * HNSW search frontier for this query (pgvector `hnsw.ef_search`).\n * Sizes the dynamic candidate list the index scan maintains: higher\n * trades latency for recall. The floor for the over-fetch to fill its\n * candidate set is `efSearch >= limit`; ~2–4× is the high-recall\n * target. Applied transaction-locally (`SET LOCAL`) on the Postgres\n * HNSW path only. No-op on backends without an HNSW frontier knob\n * (sqlite-vec) and ignored — with a one-time warning — on Postgres\n * backends without transactions (e.g. `drizzle-orm/neon-http`).\n */\n efSearch?: number;\n}>;\n\n/**\n * Result from a vector similarity search.\n */\nexport type VectorSearchResult = Readonly<{\n nodeId: string;\n /**\n * Cosine metric returns similarity score (higher is better).\n * L2 and inner_product return raw distance (lower is better).\n */\n score: number;\n}>;\n\n/**\n * Parameters for creating a vector index.\n */\nexport type CreateVectorIndexParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n /** Index-specific parameters */\n indexParams?: Readonly<{\n /** HNSW: max connections per layer */\n m?: number;\n /** HNSW: construction search depth */\n efConstruction?: number;\n /** IVFFlat: number of lists */\n lists?: number;\n }>;\n /**\n * Build the index without taking an `AccessExclusiveLock` on live\n * tables (Postgres `CREATE INDEX CONCURRENTLY`). Mirrors the\n * `concurrent` flag the relational DDL path uses inside\n * `materializeIndexes()`. Cannot be set inside a transaction —\n * callers (`materializeIndexes()`) run at top level. Backends that\n * don't have a CONCURRENTLY equivalent (SQLite) ignore this flag.\n */\n concurrent?: boolean;\n}>;\n\n/**\n * Parameters for dropping a vector index.\n */\nexport type DropVectorIndexParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n}>;\n\n// ============================================================\n// Fulltext Parameters\n// ============================================================\n\n/**\n * Parameters for inserting or updating a fulltext entry.\n *\n * One row per node. Callers concatenate the searchable fields into\n * `content` so a single MATCH query can find terms spread across fields.\n *\n * Note: `createFulltextIndex` / `dropFulltextIndex` were removed as\n * dead code in #PR_E. The fulltext table's canonical index (Postgres\n * GIN on `tsv`, SQLite FTS5 virtual table) is created with the table\n * itself by `bootstrapTables` per the active `FulltextStrategy`;\n * per-kind fulltext indexes are an \"advanced strategy\" surface that\n * doesn't fit the relational-style declaration model and is reserved\n * for future work.\n */\nexport type UpsertFulltextParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n content: string;\n language: string;\n}>;\n\n/**\n * Parameters for deleting a single fulltext entry.\n */\nexport type DeleteFulltextParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * A single row in a fulltext batch upsert.\n */\nexport type FulltextBatchRow = Readonly<{\n nodeId: string;\n content: string;\n language: string;\n}>;\n\n/**\n * Parameters for a batched fulltext upsert.\n *\n * Homogeneous: one graph, one node kind, many nodes. Duplicate `nodeId`\n * values within a single batch are deduplicated last-write-wins by the\n * builders before SQL generation — Postgres `ON CONFLICT` errors on\n * repeated conflict keys in one statement, and SQLite `DELETE + INSERT`\n * would create duplicate virtual-table rows otherwise.\n */\nexport type UpsertFulltextBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n rows: readonly FulltextBatchRow[];\n}>;\n\n/**\n * Parameters for a batched fulltext delete.\n */\nexport type DeleteFulltextBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeIds: readonly string[];\n}>;\n\n/**\n * Parameters for fulltext search.\n */\nexport type FulltextSearchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n /** The user-supplied query string. */\n query: string;\n /** How to parse `query`. Default: \"websearch\". */\n mode?: FulltextQueryMode;\n /**\n * Language override. Default: per-row language (as stored at insert time).\n * Postgres: passed as the regconfig to `to_tsquery` / `websearch_to_tsquery`.\n * SQLite: informational only (FTS5 tokenizer is fixed at table-create time).\n */\n language?: string;\n /** Max rows to return. */\n limit: number;\n /** Minimum rank to include (backend-dependent units). */\n minScore?: number;\n /** Whether to return a highlighted snippet per match. */\n includeSnippets?: boolean;\n}>;\n\n/**\n * Result from a fulltext search.\n *\n * Score semantics differ by backend; prefer `rank` (1-based) when fusing\n * with another source via RRF.\n */\nexport type FulltextSearchResult = Readonly<{\n nodeId: string;\n /**\n * Backend-native relevance score.\n * Postgres: `ts_rank_cd` (higher is better).\n * SQLite FTS5: negated `bm25()` (higher is better; FTS5 returns lower-is-better).\n */\n score: number;\n /** 1-based rank within the result set, suitable for RRF. */\n rank: number;\n /** Highlighted snippet of the content (if `includeSnippets` was set). */\n snippet?: string;\n}>;\n\n/**\n * Parameters for creating a fulltext index.\n *\n * The canonical index (Postgres GIN on `tsv`, SQLite FTS5 virtual table)\n * is created when the fulltext table itself is created. This is reserved\n * for advanced per-kind specializations.\n */\n\n// ============================================================\n// Index Materialization Status\n// ============================================================\n\n/**\n * Per-deployment record for a single declared index.\n *\n * Identified by `indexName` because SQL index names are physical,\n * database-global identifiers — `graphId` is provenance, not identity.\n * `materializedAt` is null until the first successful CREATE INDEX\n * completes; `lastAttemptedAt` is always set, even on failure.\n */\nexport type IndexMaterializationRow = Readonly<{\n indexName: string;\n graphId: string;\n entity: IndexEntity;\n kind: string;\n signature: string;\n schemaVersion: number;\n materializedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Parameters for upserting a materialization attempt.\n *\n * On success: pass `materializedAt` (ISO timestamp) and undefined `error`.\n * On failure: pass undefined `materializedAt` (preserve any existing\n * timestamp from a prior success) and the error message.\n */\nexport type RecordIndexMaterializationParams = Readonly<{\n indexName: string;\n graphId: string;\n entity: IndexEntity;\n kind: string;\n signature: string;\n schemaVersion: number;\n attemptedAt: string;\n /** ISO timestamp on success; undefined on failure (preserves existing). */\n materializedAt: string | undefined;\n /** Error message on failure; undefined on success (clears existing). */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Contribution Materializations (#135 — durable strategy-owned\n// storage marker, sibling of index materializations)\n// ============================================================\n\n/**\n * Durable identity of a strategy-owned table contribution (#129),\n * scoped to a graph. This is the primary key of\n * `typegraph_contribution_materializations`.\n *\n * `logicalName` is the stable slot (\"fulltext\"); `owner` is the\n * producing strategy (\"tsvector\" / \"fts5\"); `tableName` is the resolved\n * physical name (custom per-deployment names must be distinguishable).\n * `graphId` is part of identity here — unlike the index status table\n * where the physical index name is database-global, two graphs can each\n * own a logically-identical fulltext contribution.\n */\nexport type ContributionMaterializationIdentity = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n}>;\n\n/**\n * Per-deployment record that a strategy-owned contribution has been\n * durably materialized against this database.\n *\n * `signature` is intentionally NOT part of the identity: a row with the\n * same identity but a different signature means \"materialized artifact\n * is stale/drifted\" — a loud error on the hot path, never a silent\n * re-materialize. `materializedAt` is undefined until the first\n * successful materialization; `lastAttemptedAt` is always set.\n */\nexport type ContributionMaterializationRow = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n signature: string;\n materializedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Parameters for upserting a contribution-materialization attempt.\n * Same success/failure contract as\n * {@link RecordIndexMaterializationParams}: on failure pass undefined\n * `materializedAt` so a prior successful timestamp is preserved via\n * COALESCE, and the error message.\n */\nexport type RecordContributionMaterializationParams = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n signature: string;\n attemptedAt: string;\n /** ISO timestamp on success; undefined on failure (preserves existing). */\n materializedAt: string | undefined;\n /** Error message on failure; undefined on success (clears existing). */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Kind Removals (data-cleanup status)\n// ============================================================\n\n/**\n * One row of the per-deployment `typegraph_kind_removals` table:\n * a graph-extension kind that has been removed from the schema and whose\n * data may or may not have been cleaned up yet.\n */\nexport type KindRemovalRow = Readonly<{\n graphId: string;\n kindName: string;\n entity: KindEntity;\n schemaVersion: number;\n /** ISO timestamp when the data-cleanup pass succeeded; undefined while pending. */\n removedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Upsert payload for a kind-removal status row. On removal-commit:\n * pass `removedAt: undefined` (the pending state). On successful\n * data-cleanup: pass `removedAt` set and `error: undefined`. On\n * cleanup failure: pass `removedAt: undefined` (preserves any prior\n * timestamp from a partial success on a different replica) and the\n * error message.\n */\nexport type RecordKindRemovalParams = Readonly<{\n graphId: string;\n kindName: string;\n entity: KindEntity;\n schemaVersion: number;\n attemptedAt: string;\n /** ISO timestamp on success; undefined while pending or on failure. */\n removedAt: string | undefined;\n /** Error message on failure; undefined on success or while pending. */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Query Types\n// ============================================================\n\n/**\n * Transaction options.\n */\nexport type TransactionOptions = Readonly<{\n /** Transaction isolation level (if supported) */\n isolationLevel?:\n | \"read_uncommitted\"\n | \"read_committed\"\n | \"repeatable_read\"\n | \"serializable\";\n}>;\n\n/**\n * A caller-owned, already-open Drizzle transaction handle that a\n * TypeGraph store can adopt so both layers commit/rollback together.\n *\n * The literal client the caller's transaction runs on — a `PgDatabase`\n * transaction (node-postgres / `neon-serverless` Pool) or a\n * `BaseSQLiteDatabase` connection. Async drivers obtain it from\n * `db.transaction(async (tx) => …)`; synchronous `better-sqlite3` (whose\n * driver rejects an `async` transaction callback) passes the connection\n * itself under an explicit `BEGIN`/`COMMIT`/`ROLLBACK`. Passing it to\n * {@link GraphBackend.adoptTransaction} threads that *literal* client\n * through TypeGraph's SQL, so graph writes and the caller's own\n * relational writes share one Postgres/SQLite transaction (#134).\n */\nexport type AdoptedTransaction = AnyPgDatabase | AnySqliteDatabase;\n\n// ============================================================\n// Backend Interface\n// ============================================================\n\n/**\n * Transaction backend — a backend scoped to a transaction.\n *\n * `commitSchemaVersion` and `setActiveVersion` are intentionally omitted:\n * the atomicity / CAS guarantees of those primitives depend on\n * dialect-specific write-locking (BEGIN IMMEDIATE on SQLite,\n * `pg_advisory_xact_lock` on Postgres) acquired by the top-level\n * backend wrappers, not the transaction itself. Calling them from a\n * user-supplied `backend.transaction(...)` callback would bypass that\n * locking and silently weaken the orphan-row crash window the primitive\n * exists to eliminate. Schema commits go through the top-level backend\n * methods only.\n */\nexport type TransactionBackend = Omit<\n GraphBackend,\n | \"transaction\"\n | \"adoptTransaction\"\n | \"close\"\n | \"refreshStatistics\"\n | \"commitSchemaVersion\"\n | \"setActiveVersion\"\n>;\n\n/**\n * The GraphBackend interface abstracts database operations.\n *\n * Implementations should provide:\n * - SQLite backend via better-sqlite3 or libsql\n * - PostgreSQL backend via pg or postgres\n */\nexport type GraphBackend = Readonly<{\n /** The SQL dialect */\n dialect: SqlDialect;\n /** Backend capabilities */\n capabilities: BackendCapabilities;\n /** Table names used by this backend (for query schema auto-derivation) */\n tableNames?: SqlTableNames | undefined;\n /**\n * Optional fulltext strategy override. When present, both the compiler\n * (for `$fulltext.matches()` in query builder) and backend-direct\n * search paths use this instead of the dialect's default strategy —\n * allowing a Postgres backend to ship pg_trgm, ParadeDB, pgroonga etc.\n * When absent, the dialect's default strategy is used.\n */\n fulltextStrategy?: FulltextStrategy | undefined;\n /**\n * Optional vector strategy this backend is wired with. The query\n * compiler reads it (via `compileQuery` options) to emit per-`(kind,\n * field)` relevance scans for `field.similarTo(...)` predicates, and\n * the index-materialization / removal paths read its deterministic\n * `tableName(...)` to address the right physical per-field storage.\n * `undefined` when the backend has no vector support (e.g. a generic\n * SQLite backend without sqlite-vec).\n */\n vectorStrategy?: VectorStrategy | undefined;\n\n // === Node Operations ===\n insertNode: (params: InsertNodeParams) => Promise<NodeRow>;\n insertNodeNoReturn?: (params: InsertNodeParams) => Promise<void>;\n insertNodesBatch?: (params: readonly InsertNodeParams[]) => Promise<void>;\n insertNodesBatchReturning?: (\n params: readonly InsertNodeParams[],\n ) => Promise<readonly NodeRow[]>;\n updateNode: (params: UpdateNodeParams) => Promise<NodeRow>;\n deleteNode: (params: DeleteNodeParams) => Promise<void>;\n hardDeleteNode: (params: HardDeleteNodeParams) => Promise<void>;\n getNode: (\n graphId: string,\n kind: string,\n id: string,\n ) => Promise<NodeRow | undefined>;\n getNodes?: (\n graphId: string,\n kind: string,\n ids: readonly string[],\n ) => Promise<readonly NodeRow[]>;\n\n // === Edge Operations ===\n insertEdge: (params: InsertEdgeParams) => Promise<EdgeRow>;\n insertEdgeNoReturn?: (params: InsertEdgeParams) => Promise<void>;\n insertEdgesBatch?: (params: readonly InsertEdgeParams[]) => Promise<void>;\n insertEdgesBatchReturning?: (\n params: readonly InsertEdgeParams[],\n ) => Promise<readonly EdgeRow[]>;\n updateEdge: (params: UpdateEdgeParams) => Promise<EdgeRow>;\n deleteEdge: (params: DeleteEdgeParams) => Promise<void>;\n hardDeleteEdge: (params: HardDeleteEdgeParams) => Promise<void>;\n getEdge: (graphId: string, id: string) => Promise<EdgeRow | undefined>;\n getEdges?: (\n graphId: string,\n ids: readonly string[],\n ) => Promise<readonly EdgeRow[]>;\n\n // === Edge Cardinality Operations ===\n countEdgesFrom: (params: CountEdgesFromParams) => Promise<number>;\n edgeExistsBetween: (params: EdgeExistsBetweenParams) => Promise<boolean>;\n\n // === Edge Query Operations ===\n findEdgesConnectedTo: (\n params: FindEdgesConnectedToParams,\n ) => Promise<readonly EdgeRow[]>;\n\n // === Collection Query Operations ===\n findNodesByKind: (\n params: FindNodesByKindParams,\n ) => Promise<readonly NodeRow[]>;\n countNodesByKind: (params: CountNodesByKindParams) => Promise<number>;\n findEdgesByKind: (\n params: FindEdgesByKindParams,\n ) => Promise<readonly EdgeRow[]>;\n countEdgesByKind: (params: CountEdgesByKindParams) => Promise<number>;\n\n // === Unique Constraint Operations ===\n insertUnique: (params: InsertUniqueParams) => Promise<void>;\n deleteUnique: (params: DeleteUniqueParams) => Promise<void>;\n checkUnique: (params: CheckUniqueParams) => Promise<UniqueRow | undefined>;\n checkUniqueBatch?: (\n params: CheckUniqueBatchParams,\n ) => Promise<readonly UniqueRow[]>;\n\n // === Schema Operations ===\n getActiveSchema: (graphId: string) => Promise<SchemaVersionRow | undefined>;\n getSchemaVersion: (\n graphId: string,\n version: number,\n ) => Promise<SchemaVersionRow | undefined>;\n /**\n * Atomically inserts a new schema version and activates it as a single\n * transactional unit, with optimistic compare-and-swap on the currently\n * active version.\n *\n * - If `expected.kind === \"active\"` and the actual active version\n * differs, throws `StaleVersionError` (caller should refetch and\n * retry).\n * - If a row already exists at `params.version` with the same\n * `schemaHash`, returns it idempotently — reactivating it if it was\n * left inactive by an earlier crashed commit.\n * - If a row already exists at `params.version` with a different\n * `schemaHash`, throws `SchemaContentConflictError`.\n *\n * Requires `capabilities.transactions === true`. On non-transactional\n * backends (e.g. Cloudflare D1, drizzle-orm/neon-http) this method\n * throws `ConfigurationError` rather than running with degraded\n * atomicity that would silently re-introduce the orphan-row crash\n * window the primitive exists to eliminate.\n */\n commitSchemaVersion: (\n params: CommitSchemaVersionParams,\n ) => Promise<SchemaVersionRow>;\n /**\n * Atomically flips the active schema pointer to an existing version,\n * with optimistic compare-and-swap on the currently active version.\n * Used by `rollbackSchema` and any other \"promote/demote existing\n * version\" workflow. Throws `StaleVersionError` on CAS mismatch and\n * `MigrationError` if the target version row does not exist.\n *\n * Same transactional requirements as `commitSchemaVersion`.\n */\n setActiveVersion: (params: SetActiveVersionParams) => Promise<void>;\n\n // === Embedding Operations (optional - depends on vector capabilities) ===\n upsertEmbedding?: (params: UpsertEmbeddingParams) => Promise<void>;\n deleteEmbedding?: (params: DeleteEmbeddingParams) => Promise<void>;\n vectorSearch?: (\n params: VectorSearchParams,\n ) => Promise<readonly VectorSearchResult[]>;\n createVectorIndex?: (params: CreateVectorIndexParams) => Promise<void>;\n dropVectorIndex?: (params: DropVectorIndexParams) => Promise<void>;\n\n // === Fulltext Operations (optional - depends on fulltext capabilities) ===\n upsertFulltext?: (params: UpsertFulltextParams) => Promise<void>;\n deleteFulltext?: (params: DeleteFulltextParams) => Promise<void>;\n /**\n * Batched variant of `upsertFulltext`. Optional — callers fall back to\n * per-row `upsertFulltext` when unset.\n */\n upsertFulltextBatch?: (params: UpsertFulltextBatchParams) => Promise<void>;\n /**\n * Batched variant of `deleteFulltext`. Optional — callers fall back to\n * per-row `deleteFulltext` when unset.\n */\n deleteFulltextBatch?: (params: DeleteFulltextBatchParams) => Promise<void>;\n fulltextSearch?: (\n params: FulltextSearchParams,\n ) => Promise<readonly FulltextSearchResult[]>;\n\n // === Index Materialization (used by store.materializeIndexes) ===\n /**\n * Idempotently ensure ONLY the `typegraph_index_materializations`\n * table exists — separate from `bootstrapTables` so that\n * `materializeIndexes` doesn't pull in the full base-table DDL set\n * just to access the status table.\n *\n * Why focused: `bootstrapTables` issues 20+ `CREATE TABLE / CREATE\n * INDEX IF NOT EXISTS` statements covering every base table. Two\n * concurrent calls (e.g. two replicas of the same `schema_doc` both\n * starting up and calling `materializeIndexes`) race on\n * Postgres SHARE locks and DEADLOCK. Restricting the ensure-step to\n * the single status table eliminates the cross-table race entirely\n * — concurrent `CREATE TABLE IF NOT EXISTS` for one specific table\n * is well-behaved on Postgres.\n */\n ensureIndexMaterializationsTable?: () => Promise<void>;\n\n /**\n * Look up a recorded materialization for a declared index by its\n * physical SQL index name. Returns `undefined` if no row exists.\n */\n getIndexMaterialization?: (\n indexName: string,\n ) => Promise<IndexMaterializationRow | undefined>;\n /**\n * Bulk variant of `getIndexMaterialization`: load every recorded\n * materialization whose `indexName` (status key) is in `statusKeys`,\n * in a single round-trip. Returned rows are unordered — callers index\n * by `indexName`. Optional; consumers fall back to per-key\n * `getIndexMaterialization` when unset.\n */\n getIndexMaterializations?: (\n statusKeys: readonly string[],\n ) => Promise<readonly IndexMaterializationRow[]>;\n /**\n * Upsert a materialization attempt — success or failure. Failure rows\n * preserve any prior `materializedAt` so the historical successful\n * timestamp survives across error windows.\n */\n recordIndexMaterialization?: (\n params: RecordIndexMaterializationParams,\n ) => Promise<void>;\n\n // === Contribution Materialization (#135 — durable strategy-owned\n // storage marker, sibling of the index status table) ===\n\n /**\n * Idempotently ensure ONLY the\n * `typegraph_contribution_materializations` table exists. Same\n * focused-bootstrap rationale as `ensureIndexMaterializationsTable`:\n * a single `CREATE TABLE IF NOT EXISTS` is concurrency-safe under\n * replica startup, where the full `bootstrapTables` set risks a\n * Postgres SHARE-lock deadlock.\n */\n ensureContributionMaterializationsTable?: () => Promise<void>;\n\n /**\n * Look up the durable materialization marker for one strategy-owned\n * contribution identity. Returns `undefined` when no row exists\n * (\"never initialized\").\n */\n getContributionMaterialization?: (\n identity: ContributionMaterializationIdentity,\n ) => Promise<ContributionMaterializationRow | undefined>;\n\n /**\n * Upsert a contribution-materialization attempt — success or failure.\n * Failure rows preserve any prior `materializedAt` via COALESCE so a\n * later failed re-attempt doesn't erase the historical success.\n */\n recordContributionMaterialization?: (\n params: RecordContributionMaterializationParams,\n ) => Promise<void>;\n\n /**\n * Resolve (once per backend instance, cached) and assert the durable\n * materialization markers for every `runtimeEnsure` contribution this\n * backend's strategy declares, for `graphId`. Throws\n * `StoreNotInitializedError` when a marker is missing, stale\n * (signature drift), or recorded a failed last attempt.\n *\n * This is the single read-side gate the fulltext hot-path wrappers\n * and `store.transaction()` consult. It performs ZERO DDL and ZERO\n * marker writes — initialization is the exclusive job of the async\n * boot path (`createStoreWithSchema` → `ensureRuntimeContributions`).\n */\n assertRuntimeContributionsInitialized?: (graphId: string) => Promise<void>;\n\n // === Kind Removal Status ===\n\n /**\n * Bootstraps the per-deployment `typegraph_kind_removals` table so\n * `store.removeKinds()` and `store.materializeRemovals()` can persist\n * removal status. Mirrors the focused-bootstrap rationale documented\n * on `ensureIndexMaterializationsTable` — the full `bootstrapTables`\n * touches every base table and risks Postgres SHARE-lock deadlock\n * under concurrent replica startup.\n */\n ensureKindRemovalsTable?: () => Promise<void>;\n\n /**\n * List graph-extension kind removals whose data-cleanup pass has not yet\n * succeeded for this `graphId`. Returns rows with\n * `removedAt: undefined`. Order is unspecified; callers materialize\n * one-at-a-time and don't depend on it.\n */\n getPendingKindRemovals?: (\n graphId: string,\n ) => Promise<readonly KindRemovalRow[]>;\n\n /**\n * List ALL kind-removal rows for a `graphId` — pending and completed.\n * Used by `materializeRemovals()` reconciliation to detect rows that\n * are missing entirely (the `removeKinds()` crash window) versus\n * already completed. Without this distinction the reconciler would\n * have to upsert every expected historical removal on every call,\n * churning `last_attempted_at` on rows that long since succeeded.\n * Order is unspecified.\n */\n getAllKindRemovals?: (graphId: string) => Promise<readonly KindRemovalRow[]>;\n\n /**\n * Upsert a kind-removal status row. `removedAt: undefined` records\n * the pending state at schema-commit time; `removedAt: <iso>`\n * marks the data cleanup successful. The COALESCE rule on `removedAt`\n * mirrors `recordIndexMaterialization` so a later failure doesn't\n * clobber the historical successful timestamp from another replica.\n */\n recordKindRemoval?: (params: RecordKindRemovalParams) => Promise<void>;\n\n // === Reconciliation Watermark ===\n\n /**\n * Bootstraps the per-deployment `typegraph_reconciliation_markers`\n * table so `materializeRemovals()` can persist reconciliation\n * progress. Same focused-bootstrap rationale as the other status\n * tables — full `bootstrapTables` risks Postgres SHARE-lock\n * deadlock under concurrent replica startup.\n */\n ensureReconciliationMarkersTable?: () => Promise<void>;\n\n // === Table Contributions (#129) ===\n\n /**\n * Materializes every contribution flagged `runtimeEnsure` — the\n * strategy-owned runtime tables (fulltext today) that drizzle-kit-\n * managed setups don't create. Called once after a successful schema\n * load. Deliberately scoped: base/drizzle-visible tables are\n * `runtimeEnsure: false`, so this does not regress startup into\n * broad DDL/probing across every table.\n *\n * The canonical durable-marker writer (#135): for each runtime\n * contribution it short-circuits when the marker already records a\n * matching signature, otherwise runs the idempotent `createDdl` and\n * records the marker (success or failure) keyed by `graphId`.\n */\n ensureRuntimeContributions?: (graphId: string) => Promise<void>;\n\n /**\n * Bootstraps the fulltext storage table the active `FulltextStrategy`\n * owns. Same focused-bootstrap rationale as the other `ensure*Table`\n * methods: idempotent and concurrency-safe under replica startup.\n *\n * Superseded by `ensureRuntimeContributions()` (#129); retained as\n * a thin back-compat wrapper for backends/callers predating #129. Not\n * machine-`@deprecated` because the manager still calls it as the\n * pre-#129 fallback. #135 removed the remaining hot-path callers and\n * routed this through the durable-marker writer.\n */\n ensureFulltextTable?: (graphId: string) => Promise<void>;\n\n /**\n * Read the high-water mark schema version for which\n * `materializeRemovals` reconciliation has already verified history\n * for `graphId`. Returns `undefined` when no marker has been\n * recorded yet. Used to skip already-checked transitions in the\n * recovery walk.\n */\n getReconciliationMarker?: (graphId: string) => Promise<number | undefined>;\n\n /**\n * Persist the reconciliation high-water mark for `graphId`. Called\n * after `materializeRemovals` completes a clean walk; subsequent\n * calls walk only versions newer than this marker. Idempotent\n * upsert by `graphId`.\n */\n setReconciliationMarker?: (graphId: string, version: number) => Promise<void>;\n\n // === Graph Lifecycle ===\n /**\n * Hard-deletes all data for a graph (nodes, edges, uniques, embeddings, schema versions).\n * Intended for import-replacement workflows. No hooks, no per-row logic.\n */\n clearGraph: (graphId: string) => Promise<void>;\n\n /**\n * Creates the base TypeGraph tables if they don't already exist.\n *\n * Called automatically by `createStoreWithSchema()` when a fresh database\n * is detected. Users who manage DDL themselves via `createStore()` never\n * hit this path.\n */\n bootstrapTables?: () => Promise<void>;\n\n /**\n * Refreshes the backend's query-planner statistics.\n *\n * Call this once after a large initial import or bulk backfill. Without\n * up-to-date statistics, the planner can pick suboptimal execution plans\n * — on PostgreSQL this is the difference between a 0.5ms and a 5ms\n * forward traversal; on SQLite it's the difference between 0.9ms and\n * 23ms fulltext search. Autovacuum / background statistics collection\n * will catch up eventually, but calling this explicitly after a bulk\n * load gives you correct latencies immediately.\n *\n * Implementations:\n * - SQLite runs `ANALYZE`, which populates `sqlite_stat1`\n * - PostgreSQL runs `ANALYZE` on the TypeGraph-managed tables\n *\n * Safe to call at any time; costs a few tens of milliseconds on the\n * sizes this library is designed for.\n */\n refreshStatistics: () => Promise<void>;\n\n // === Query Execution ===\n execute: <T>(query: SQL) => Promise<readonly T[]>;\n\n /** Execute pre-compiled SQL text with bound parameters. Available on sync SQLite and pg backends. */\n executeRaw?: <T>(\n sqlText: string,\n params: readonly unknown[],\n ) => Promise<readonly T[]>;\n\n /** Compile a Drizzle SQL object to { sql, params } without executing. */\n compileSql?: (\n query: SQL,\n ) => Readonly<{ sql: string; params: readonly unknown[] }>;\n\n /**\n * Execute a DDL statement that returns no rows (CREATE INDEX,\n * CREATE TABLE, ALTER TABLE, etc.). Separate from `executeRaw`\n * because some drivers (better-sqlite3) require `.run()` for DDL\n * and `.all()` for queries — the ambiguity can't be resolved by\n * inspecting the SQL string portably.\n *\n * Postgres path can use this for `CREATE INDEX CONCURRENTLY`, which\n * cannot run inside a transaction. Implementations must execute the\n * statement outside `transaction(...)`.\n */\n executeDdl?: (ddl: string) => Promise<void>;\n\n // === Transaction ===\n /**\n * `fn` receives the tx-scoped backend and the raw Drizzle handle\n * **bound to that same transaction** (`AdoptedTransaction`). The\n * store surfaces the second argument as `TransactionContext.sql` so\n * callers can write their own relational tables inside the\n * graph-owned transaction. Implementations MUST pass the *exact*\n * handle the tx-scoped backend writes through (the Postgres/libsql\n * tx handle; for better-sqlite3 / do-sqlite the bound connection),\n * never a fresh one.\n */\n transaction: <T>(\n fn: (tx: TransactionBackend, sql: AdoptedTransaction) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<T>;\n\n /**\n * Adopt a caller-owned, already-open transaction (#134).\n *\n * Returns a transaction-scoped backend bound to the *exact*\n * `externalTx` client, reusing this backend's already-resolved\n * schema/strategy config — no `createStoreWithSchema` / `evolve` /\n * `migrateSchema`, and **no DDL inside the caller's business\n * transaction**. The caller owns `BEGIN`/`COMMIT`/`ROLLBACK`; this\n * method neither opens nor closes a transaction. Async drivers\n * (node-postgres, `neon-serverless` Pool, libsql) wrap with\n * `db.transaction(async …)`; synchronous `better-sqlite3` must instead\n * issue explicit `BEGIN`/`COMMIT`/`ROLLBACK` (its driver rejects an\n * `async` transaction callback).\n *\n * Optional and presence-detected like the other capability-scoped\n * members: only the Drizzle Postgres/SQLite backends provide it.\n * Implementations MUST throw (not silently degrade) when\n * `capabilities.transactions` is `false` — a non-atomic fallback is\n * safe for graph-only writes but dangerous for cross-store flows,\n * where the caller's relational write *would* still commit.\n *\n * Fulltext stays safe by construction: the returned backend's\n * fulltext methods assert the durable materialization marker (a\n * cached SELECT, never DDL) at point of use and throw\n * `StoreNotInitializedError` on a missing/stale/failed marker rather\n * than migrating mid-transaction. Prefer booting the parent store via\n * `createStoreWithSchema` so that assertion is a warm-cache no-op.\n */\n adoptTransaction?: (externalTx: AdoptedTransaction) => TransactionBackend;\n\n // === Lifecycle ===\n close: () => Promise<void>;\n}>;\n\n// ============================================================\n// Managed Backend Helper\n// ============================================================\n\n/**\n * Wraps a GraphBackend with idempotent close that also runs a teardown\n * callback (e.g. closing the underlying database connection).\n */\nexport function wrapWithManagedClose(\n backend: GraphBackend,\n teardown: () => void | Promise<void>,\n): GraphBackend {\n let isClosed = false;\n return {\n ...backend,\n async close(): Promise<void> {\n if (isClosed) return;\n isClosed = true;\n await backend.close();\n await teardown();\n },\n };\n}\n\n/**\n * Runs `fn` inside a transaction when the backend supports one, falling\n * through to a direct invocation otherwise. Lets call sites benefit from\n * atomicity on backends that have transactions while staying functional\n * on backends that don't (Cloudflare D1, `drizzle-orm/neon-http` over\n * HTTP). The single-statement race window is already implicit on any\n * backend that reports `transactions: false`; callers that cannot\n * tolerate it must branch on the capability themselves.\n *\n * Pass `fallback` only when the toplevel backend method would recurse\n * — pass the operation-level backend so the no-tx path doesn't loop\n * back through the same toplevel method.\n */\nexport async function runOptionallyInTransaction<T>(\n backend: GraphBackend,\n fn: (target: GraphBackend | TransactionBackend) => Promise<T>,\n fallback?: GraphBackend | TransactionBackend,\n): Promise<T> {\n if (!backend.capabilities.transactions) {\n return fn(fallback ?? backend);\n }\n return backend.transaction((tx) => fn(tx));\n}\n\n// ============================================================\n// Additional Parameter Types\n// ============================================================\n\n/**\n * Parameters for inserting a unique constraint entry.\n */\nexport type InsertUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n nodeId: string;\n concreteKind: string;\n}>;\n\n/**\n * Parameters for deleting a unique constraint entry.\n */\nexport type DeleteUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n}>;\n\n/**\n * Parameters for checking a unique constraint.\n */\nexport type CheckUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n /** If true, also returns soft-deleted entries. Used by get-or-create operations. */\n includeDeleted?: boolean;\n}>;\n\n/**\n * Parameters for batch-checking unique constraints.\n */\nexport type CheckUniqueBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n keys: readonly string[];\n /** If true, also returns soft-deleted entries. Used by get-or-create operations. */\n includeDeleted?: boolean;\n}>;\n\n/**\n * Parameters for inserting a schema version.\n *\n * Used internally by backend implementations. Public callers go through\n * `commitSchemaVersion`, which handles the insert + activate atomically\n * with CAS guarantees.\n */\nexport type InsertSchemaParams = Readonly<{\n graphId: string;\n version: number;\n schemaHash: string;\n schemaDoc: SerializedSchema;\n isActive: boolean;\n}>;\n\n/**\n * The caller's claim about the currently-active schema version, used as\n * the optimistic compare-and-swap guard for `commitSchemaVersion`.\n *\n * - `{ kind: \"initial\" }` — caller is committing the first-ever version\n * for this graph and asserts no active version exists yet.\n * - `{ kind: \"active\", version: N }` — caller observed version N as\n * active and is committing version N+1 against that baseline. The\n * commit fails with `StaleVersionError` if some other writer has\n * advanced or rolled back the pointer in the meantime.\n *\n * Tagged-union form (rather than a magic `version: 0` sentinel) because\n * the two cases have materially different semantics: the initial path\n * skips the \"deactivate prior\" UPDATE, and the no-active-row state is\n * a *valid* expected state, not an out-of-band signal.\n */\nexport type CommitSchemaVersionExpected =\n | Readonly<{ kind: \"initial\" }>\n | Readonly<{ kind: \"active\"; version: number }>;\n\n/**\n * Parameters for `commitSchemaVersion`.\n */\nexport type CommitSchemaVersionParams = Readonly<{\n graphId: string;\n /** CAS guard — see `CommitSchemaVersionExpected`. */\n expected: CommitSchemaVersionExpected;\n /** The new version to insert and activate. */\n version: number;\n schemaHash: string;\n schemaDoc: SerializedSchema;\n}>;\n\n/**\n * Parameters for `setActiveVersion`.\n *\n * Flips the active pointer from `expected` to `version` for an existing\n * row. CAS prevents overwriting a concurrent rollback or commit.\n */\nexport type SetActiveVersionParams = Readonly<{\n graphId: string;\n /** CAS guard. Same semantics as `commitSchemaVersion.expected`. */\n expected: CommitSchemaVersionExpected;\n /** The version to mark active. Must already exist. */\n version: number;\n}>;\n\n/**\n * Parameters for counting edges from a source node.\n */\nexport type CountEdgesFromParams = Readonly<{\n graphId: string;\n edgeKind: string;\n fromKind: string;\n fromId: string;\n /** If true, only count edges where valid_to IS NULL */\n activeOnly?: boolean;\n}>;\n\n/**\n * Parameters for checking if an edge exists between two nodes.\n */\nexport type EdgeExistsBetweenParams = Readonly<{\n graphId: string;\n edgeKind: string;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n}>;\n\n/**\n * Parameters for finding edges connected to a node.\n */\nexport type FindEdgesConnectedToParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * Parameters for finding nodes by kind.\n */\nexport type FindNodesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n /** Max rows to return. */\n limit?: number;\n /** Offset. Present for backward compat; rebuild uses `after` instead. */\n offset?: number;\n /** If true, exclude deleted nodes. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n /**\n * Stable ordering for keyset pagination. Default: \"created_at\" (existing\n * behavior). Rebuild should use \"id\" for iteration that is stable under\n * concurrent writes and shared timestamps.\n */\n orderBy?: \"id\" | \"created_at\";\n /**\n * Keyset cursor. Returns rows strictly greater (by `orderBy`) than this\n * value. When `orderBy: \"id\"`, compared lexicographically. Mutually\n * exclusive with `offset` — callers pick one.\n */\n after?: string;\n}>;\n\n/**\n * Parameters for counting nodes by kind.\n */\nexport type CountNodesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n /** If true, exclude deleted nodes. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n/**\n * Parameters for finding edges by kind.\n */\nexport type FindEdgesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n fromKind?: string;\n fromId?: string;\n toKind?: string;\n toId?: string;\n limit?: number;\n offset?: number;\n /** If true, exclude deleted edges. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n /**\n * Stable ordering for keyset pagination. Default: \"created_at\" (existing\n * behavior). Use \"id\" for iteration that is stable under shared `created_at`\n * timestamps — the offset path orders by the NON-unique `created_at`, so a\n * full enumeration must page by the unique `id` to avoid skipping a row at a\n * page boundary. Mirrors {@link FindNodesByKindParams.orderBy}.\n */\n orderBy?: \"id\" | \"created_at\";\n /**\n * Keyset cursor. Returns rows strictly greater (by `orderBy`) than this value.\n * When `orderBy: \"id\"`, compared lexicographically. Mutually exclusive with\n * `offset` — callers pick one. Mirrors {@link FindNodesByKindParams.after}.\n */\n after?: string;\n}>;\n\n/**\n * Parameters for counting edges by kind.\n */\nexport type CountEdgesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n fromKind?: string;\n fromId?: string;\n toKind?: string;\n toId?: string;\n /** If true, exclude deleted edges. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n// ============================================================\n// Default Capabilities\n// ============================================================\n\n/**\n * Default capabilities for SQLite.\n */\nexport const SQLITE_CAPABILITIES: BackendCapabilities = {\n transactions: true, // SQLite supports transactions\n windowFunctions: true, // SQLite has supported window functions since 3.25.0\n};\n\n/**\n * Default capabilities for PostgreSQL.\n */\nexport const POSTGRES_CAPABILITIES: BackendCapabilities = {\n transactions: true, // PostgreSQL supports transactions\n windowFunctions: true, // PostgreSQL supports ROW_NUMBER() and related windows\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/interchange/types.ts","../src/interchange/export.ts","../src/interchange/import.ts"],"names":["z","isCanonicalIsoDate","getNodeKinds","getEdgeKinds","nowIso","validateOptionalCanonicalIsoDate","result"],"mappings":";;;;;AAqBO,IAAM,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ACpD,CAAC,CAAA,CACA,IAAA,CAAK,IAAI,CAAA;AACd;AAMA,SAAS,WAAA,CAAY,MAAc,EAAA,EAAoB;AACrD,EAAA,OAAO,CAAA,EAAG,IAAI,CAAA,CAAA,EAAI,EAAE,CAAA,CAAA;AACtB","file":"chunk-SB65GJNY.cjs","sourcesContent":["/**\n * Graph interchange format types.\n *\n * Defines Zod schemas for importing and exporting graph data.\n * The format is designed to be:\n * - JSON-serializable for API transport\n * - Validated via Zod at runtime\n * - Exportable as JSON Schema for LLM/API documentation\n */\nimport { z } from \"zod\";\n\nimport { isCanonicalIsoDate } from \"../utils/date\";\n\n// ============================================================\n// Format Version\n// ============================================================\n\n/**\n * Current interchange format version.\n * Increment for breaking changes to the format.\n */\nexport const FORMAT_VERSION = \"1.0\" as const;\n\n/**\n * A stored validity-window timestamp (`validFrom` / `validTo`). Must be a\n * canonical fixed-width UTC ISO-8601 string (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the\n * same contract `create` / `update` enforce — because temporal filters compare\n * it as text against the `asOf` read coordinate, and a variable-width value\n * (date-only, offset, missing/variable milliseconds) would mis-sort and\n * silently include or exclude the wrong rows. Convert non-canonical inputs with\n * `new Date(value).toISOString()`.\n */\nconst ValidityTimestampSchema = z.iso\n .datetime()\n .refine((value) => isCanonicalIsoDate(value), {\n message:\n \"Expected canonical UTC ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ); convert with new Date(value).toISOString().\",\n });\n\n// ============================================================\n// Node Interchange\n// ============================================================\n\n/**\n * Interchange format for a node.\n *\n * Properties are stored as a record to allow schema-agnostic transport.\n * Validation against the actual schema happens during import.\n */\nexport const InterchangeNodeSchema = z.object({\n kind: z.string().min(1),\n id: z.string().min(1),\n properties: z.record(z.string(), z.unknown()),\n validFrom: ValidityTimestampSchema.optional(),\n validTo: ValidityTimestampSchema.optional(),\n meta: z\n .object({\n version: z.number().int().positive().optional(),\n createdAt: z.iso.datetime().optional(),\n updatedAt: z.iso.datetime().optional(),\n })\n .optional(),\n});\n\nexport type InterchangeNode = z.infer<typeof InterchangeNodeSchema>;\n\n// ============================================================\n// Edge Interchange\n// ============================================================\n\n/**\n * Interchange format for an edge.\n *\n * Endpoint references are objects with kind and id, rather than\n * composite strings, for clarity and type safety.\n */\nexport const InterchangeEdgeSchema = z.object({\n kind: z.string().min(1),\n id: z.string().min(1),\n from: z.object({\n kind: z.string().min(1),\n id: z.string().min(1),\n }),\n to: z.object({\n kind: z.string().min(1),\n id: z.string().min(1),\n }),\n properties: z.record(z.string(), z.unknown()).default({}),\n validFrom: ValidityTimestampSchema.optional(),\n validTo: ValidityTimestampSchema.optional(),\n meta: z\n .object({\n createdAt: z.iso.datetime().optional(),\n updatedAt: z.iso.datetime().optional(),\n })\n .optional(),\n});\n\nexport type InterchangeEdge = z.infer<typeof InterchangeEdgeSchema>;\n\n// ============================================================\n// Import Configuration\n// ============================================================\n\n/**\n * Strategy for handling conflicts when a node/edge ID already exists.\n *\n * - `skip`: Keep existing, ignore incoming\n * - `update`: Merge incoming properties into existing\n * - `error`: Throw an error on conflict\n */\nexport const ConflictStrategySchema = z.enum([\"skip\", \"update\", \"error\"]);\nexport type ConflictStrategy = z.infer<typeof ConflictStrategySchema>;\n\n/**\n * Strategy for handling properties not defined in the schema.\n *\n * - `error`: Throw a validation error\n * - `strip`: Remove unknown properties silently\n * - `allow`: Pass through to storage (relies on backend behavior)\n */\nexport const UnknownPropertyStrategySchema = z.enum([\n \"error\",\n \"strip\",\n \"allow\",\n]);\nexport type UnknownPropertyStrategy = z.infer<\n typeof UnknownPropertyStrategySchema\n>;\n\n/**\n * Options for importing graph data.\n */\nexport const ImportOptionsSchema = z.object({\n /** How to handle existing nodes/edges with the same ID */\n onConflict: ConflictStrategySchema,\n /** How to handle properties not in the schema */\n onUnknownProperty: UnknownPropertyStrategySchema.default(\"error\"),\n /** Whether to validate that edge endpoints exist */\n validateReferences: z.boolean().default(true),\n /** Number of items to process in each batch */\n batchSize: z.number().int().positive().default(100),\n});\n\nexport type ImportOptions = z.infer<typeof ImportOptionsSchema>;\n\n// ============================================================\n// Graph Data Source\n// ============================================================\n\n/**\n * Source metadata for graph data.\n *\n * Uses discriminated union to capture different origin types:\n * - `typegraph-export`: Exported from a TypeGraph store\n * - `external`: From a third-party system\n */\nexport const GraphDataSourceSchema = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"typegraph-export\"),\n graphId: z.string(),\n schemaVersion: z.number().int().positive(),\n }),\n z.object({\n type: z.literal(\"external\"),\n description: z.string().optional(),\n }),\n]);\n\nexport type GraphDataSource = z.infer<typeof GraphDataSourceSchema>;\n\n// ============================================================\n// Graph Data Envelope\n// ============================================================\n\n/**\n * Complete graph data interchange format.\n *\n * The envelope contains metadata about the data source and format version,\n * plus arrays of nodes and edges to import.\n */\nexport const GraphDataSchema = z.object({\n formatVersion: z.literal(FORMAT_VERSION),\n exportedAt: z.iso.datetime(),\n source: GraphDataSourceSchema,\n nodes: z.array(InterchangeNodeSchema),\n edges: z.array(InterchangeEdgeSchema),\n});\n\nexport type GraphData = z.infer<typeof GraphDataSchema>;\n\n// ============================================================\n// Import Result\n// ============================================================\n\n/**\n * An error that occurred during import.\n */\nexport const ImportErrorSchema = z.object({\n entityType: z.enum([\"node\", \"edge\"]),\n kind: z.string(),\n id: z.string(),\n error: z.string(),\n});\n\nexport type ImportError = z.infer<typeof ImportErrorSchema>;\n\n/**\n * Result of an import operation.\n *\n * Contains counts of created/updated/skipped entities and any errors.\n */\nexport const ImportResultSchema = z.object({\n success: z.boolean(),\n nodes: z.object({\n created: z.number().int().nonnegative(),\n updated: z.number().int().nonnegative(),\n skipped: z.number().int().nonnegative(),\n }),\n edges: z.object({\n created: z.number().int().nonnegative(),\n updated: z.number().int().nonnegative(),\n skipped: z.number().int().nonnegative(),\n }),\n errors: z.array(ImportErrorSchema),\n});\n\nexport type ImportResult = z.infer<typeof ImportResultSchema>;\n\n// ============================================================\n// Export Options\n// ============================================================\n\n/**\n * Options for exporting graph data.\n */\nexport const ExportOptionsSchema = z.object({\n /** Filter to specific node kinds (undefined = all) */\n nodeKinds: z.array(z.string()).optional(),\n /** Filter to specific edge kinds (undefined = all) */\n edgeKinds: z.array(z.string()).optional(),\n /** Include temporal fields (validFrom, validTo) */\n includeTemporal: z.boolean().default(false),\n /** Include metadata (version, timestamps) */\n includeMeta: z.boolean().default(false),\n /** Include soft-deleted records */\n includeDeleted: z.boolean().default(false),\n});\n\n/** Export options with defaults applied (output type) */\nexport type ExportOptions = z.infer<typeof ExportOptionsSchema>;\n\n/** Export options as accepted by exportGraph (input type with optional defaults) */\nexport type ExportOptionsInput = z.input<typeof ExportOptionsSchema>;\n","/**\n * Graph data export functionality.\n *\n * Exports nodes and edges from a store to the interchange format.\n */\nimport { type GraphBackend } from \"../backend/types\";\nimport {\n getEdgeKinds,\n getNodeKinds,\n type GraphDef,\n} from \"../core/define-graph\";\nimport { type Store } from \"../store/store\";\nimport { nowIso } from \"../utils/date\";\nimport {\n type ExportOptionsInput,\n FORMAT_VERSION,\n type GraphData,\n type InterchangeEdge,\n type InterchangeNode,\n} from \"./types\";\n\n// ============================================================\n// Export Function\n// ============================================================\n\n/**\n * Export graph data from a store.\n *\n * @param store - The graph store to export from\n * @param options - Export configuration\n * @returns Graph data in interchange format\n *\n * @example\n * ```typescript\n * const data = await exportGraph(store, {\n * nodeKinds: [\"Person\", \"Organization\"],\n * includeMeta: true,\n * });\n *\n * // Write to file\n * await fs.writeFile(\"backup.json\", JSON.stringify(data, null, 2));\n * ```\n */\nexport async function exportGraph<G extends GraphDef>(\n store: Store<G>,\n options?: ExportOptionsInput,\n): Promise<GraphData> {\n const options_ = {\n nodeKinds: options?.nodeKinds,\n edgeKinds: options?.edgeKinds,\n includeTemporal: options?.includeTemporal ?? false,\n includeMeta: options?.includeMeta ?? false,\n includeDeleted: options?.includeDeleted ?? false,\n };\n\n const graph = store.graph;\n const graphId = store.graphId;\n const backend = store.backend;\n\n // Determine which kinds to export\n const nodeKindsToExport = options_.nodeKinds ?? getNodeKinds(graph);\n const edgeKindsToExport = options_.edgeKinds ?? getEdgeKinds(graph);\n\n // Export nodes\n const nodes: InterchangeNode[] = [];\n for (const kind of nodeKindsToExport) {\n const kindNodes = await exportNodesOfKind(backend, graphId, kind, options_);\n nodes.push(...kindNodes);\n }\n\n // Export edges\n const edges: InterchangeEdge[] = [];\n for (const kind of edgeKindsToExport) {\n const kindEdges = await exportEdgesOfKind(backend, graphId, kind, options_);\n edges.push(...kindEdges);\n }\n\n // Get current schema version\n const schemaVersion = await backend.getActiveSchema(graphId);\n\n return {\n formatVersion: FORMAT_VERSION,\n exportedAt: nowIso(),\n source: {\n type: \"typegraph-export\",\n graphId,\n schemaVersion: schemaVersion?.version ?? 1,\n },\n nodes,\n edges,\n };\n}\n\n// ============================================================\n// Node Export\n// ============================================================\n\ntype ExportOptions_ = Readonly<{\n includeTemporal: boolean;\n includeMeta: boolean;\n includeDeleted: boolean;\n}>;\n\nasync function exportNodesOfKind(\n backend: GraphBackend,\n graphId: string,\n kind: string,\n options: ExportOptions_,\n): Promise<InterchangeNode[]> {\n const rows = await backend.findNodesByKind({\n graphId,\n kind,\n excludeDeleted: !options.includeDeleted,\n });\n\n return rows.map((row) => {\n const node: InterchangeNode = {\n kind: row.kind,\n id: row.id,\n properties: JSON.parse(row.props) as Record<string, unknown>,\n };\n\n if (options.includeTemporal) {\n if (row.valid_from) {\n (node as { validFrom?: string }).validFrom = row.valid_from;\n }\n if (row.valid_to) {\n (node as { validTo?: string }).validTo = row.valid_to;\n }\n }\n\n if (options.includeMeta) {\n (node as { meta?: InterchangeNode[\"meta\"] }).meta = {\n version: row.version,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n }\n\n return node;\n });\n}\n\n// ============================================================\n// Edge Export\n// ============================================================\n\nasync function exportEdgesOfKind(\n backend: GraphBackend,\n graphId: string,\n kind: string,\n options: ExportOptions_,\n): Promise<InterchangeEdge[]> {\n const rows = await backend.findEdgesByKind({\n graphId,\n kind,\n excludeDeleted: !options.includeDeleted,\n });\n\n return rows.map((row) => {\n const edge: InterchangeEdge = {\n kind: row.kind,\n id: row.id,\n from: {\n kind: row.from_kind,\n id: row.from_id,\n },\n to: {\n kind: row.to_kind,\n id: row.to_id,\n },\n properties: JSON.parse(row.props) as Record<string, unknown>,\n };\n\n if (options.includeTemporal) {\n if (row.valid_from) {\n (edge as { validFrom?: string }).validFrom = row.valid_from;\n }\n if (row.valid_to) {\n (edge as { validTo?: string }).validTo = row.valid_to;\n }\n }\n\n if (options.includeMeta) {\n (edge as { meta?: InterchangeEdge[\"meta\"] }).meta = {\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n }\n\n return edge;\n });\n}\n","/**\n * Graph data import functionality.\n *\n * Imports nodes and edges from the interchange format into a store,\n * with configurable conflict resolution and validation.\n */\nimport type { z } from \"zod\";\n\nimport { type GraphBackend, type TransactionBackend } from \"../backend/types\";\nimport {\n getEdgeKinds,\n getNodeKinds,\n type GraphDef,\n} from \"../core/define-graph\";\nimport { type EdgeRegistration, type NodeRegistration } from \"../core/types\";\nimport { type Store } from \"../store/store\";\nimport { validateOptionalCanonicalIsoDate } from \"../utils/date\";\nimport {\n type GraphData,\n type ImportError,\n type ImportOptions,\n type ImportResult,\n type InterchangeEdge,\n type InterchangeNode,\n type UnknownPropertyStrategy,\n} from \"./types\";\n\n// ============================================================\n// Import Function\n// ============================================================\n\n/**\n * Import graph data into a store.\n *\n * Nodes are imported first to satisfy edge reference validation.\n * The import runs within a transaction for atomicity when supported.\n *\n * @param store - The graph store to import into\n * @param data - Graph data in interchange format\n * @param options - Import configuration\n * @returns Import statistics and any errors\n *\n * @example\n * ```typescript\n * const result = await importGraph(store, data, {\n * onConflict: \"update\",\n * onUnknownProperty: \"strip\",\n * });\n *\n * console.log(`Created ${result.nodes.created} nodes`);\n * ```\n */\nexport async function importGraph<G extends GraphDef>(\n store: Store<G>,\n data: GraphData,\n options: ImportOptions,\n): Promise<ImportResult> {\n const result: ImportResult = {\n success: true,\n nodes: { created: 0, updated: 0, skipped: 0 },\n edges: { created: 0, updated: 0, skipped: 0 },\n errors: [],\n };\n\n const errors: ImportError[] = [];\n const graph = store.graph;\n const graphId = store.graphId;\n const backend = store.backend;\n\n // Build lookup maps for schema validation\n const nodeSchemas = buildNodeSchemaMap(graph);\n const edgeSchemas = buildEdgeSchemaMap(graph);\n\n // Track imported node IDs for reference validation\n const importedNodeIds = new Set<string>();\n\n // Process in transaction if supported\n if (backend.capabilities.transactions) {\n await backend.transaction(async (tx) => {\n await processNodes(\n tx,\n graphId,\n data.nodes,\n nodeSchemas,\n options,\n result,\n errors,\n importedNodeIds,\n );\n await processEdges(\n tx,\n graphId,\n data.edges,\n edgeSchemas,\n nodeSchemas,\n options,\n result,\n errors,\n importedNodeIds,\n );\n });\n } else {\n await processNodes(\n backend,\n graphId,\n data.nodes,\n nodeSchemas,\n options,\n result,\n errors,\n importedNodeIds,\n );\n await processEdges(\n backend,\n graphId,\n data.edges,\n edgeSchemas,\n nodeSchemas,\n options,\n result,\n errors,\n importedNodeIds,\n );\n }\n\n return {\n ...result,\n success: errors.length === 0,\n errors,\n };\n}\n\n// ============================================================\n// Schema Maps\n// ============================================================\n\ntype NodeSchemaEntry = Readonly<{\n registration: NodeRegistration;\n schema: z.ZodObject<z.ZodRawShape>;\n}>;\n\ntype EdgeSchemaEntry = Readonly<{\n registration: EdgeRegistration;\n schema: z.ZodObject<z.ZodRawShape>;\n fromKinds: ReadonlySet<string>;\n toKinds: ReadonlySet<string>;\n}>;\n\nfunction buildNodeSchemaMap(\n graph: GraphDef,\n): ReadonlyMap<string, NodeSchemaEntry> {\n const map = new Map<string, NodeSchemaEntry>();\n\n for (const kindName of getNodeKinds(graph)) {\n const registration = graph.nodes[kindName] as NodeRegistration;\n map.set(kindName, {\n registration,\n schema: registration.type.schema,\n });\n }\n\n return map;\n}\n\nfunction buildEdgeSchemaMap(\n graph: GraphDef,\n): ReadonlyMap<string, EdgeSchemaEntry> {\n const map = new Map<string, EdgeSchemaEntry>();\n\n for (const kindName of getEdgeKinds(graph)) {\n const registration = graph.edges[kindName] as EdgeRegistration;\n map.set(kindName, {\n registration,\n schema: registration.type.schema,\n fromKinds: new Set(registration.from.map((node) => node.kind)),\n toKinds: new Set(registration.to.map((node) => node.kind)),\n });\n }\n\n return map;\n}\n\n// ============================================================\n// Node Processing\n// ============================================================\n\nasync function processNodes(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n nodes: readonly InterchangeNode[],\n schemas: ReadonlyMap<string, NodeSchemaEntry>,\n options: ImportOptions,\n result: ImportResult,\n errors: ImportError[],\n importedNodeIds: Set<string>,\n): Promise<void> {\n const batchSize = options.batchSize;\n\n for (let index = 0; index < nodes.length; index += batchSize) {\n const batch = nodes.slice(index, index + batchSize);\n\n for (const node of batch) {\n const importResult = await processNode(\n backend,\n graphId,\n node,\n schemas,\n options,\n );\n\n switch (importResult.status) {\n case \"created\": {\n result.nodes.created++;\n importedNodeIds.add(makeNodeKey(node.kind, node.id));\n break;\n }\n case \"updated\": {\n result.nodes.updated++;\n importedNodeIds.add(makeNodeKey(node.kind, node.id));\n break;\n }\n case \"skipped\": {\n result.nodes.skipped++;\n // Still track as available for edge references\n importedNodeIds.add(makeNodeKey(node.kind, node.id));\n break;\n }\n case \"error\": {\n errors.push({\n entityType: \"node\",\n kind: node.kind,\n id: node.id,\n error: importResult.error,\n });\n break;\n }\n }\n }\n }\n}\n\ntype ProcessResult =\n | { status: \"created\" }\n | { status: \"updated\" }\n | { status: \"skipped\" }\n | { status: \"error\"; error: string };\n\n/**\n * Validates an entity's validity-window timestamps against the canonical\n * fixed-width UTC ISO-8601 contract that `create` / `update` enforce, so no\n * import write path can persist a non-canonical `valid_from` / `valid_to` that\n * later mis-sorts as text against an `asOf` read coordinate. The interchange\n * schema enforces the same contract at the parse boundary, but `importGraph`\n * accepts a pre-typed `GraphData` and does not re-parse it, so this is the\n * guarantee for callers that bypass the schema. Returns a per-row error message\n * (recorded in the import result) instead of throwing, so one malformed row\n * does not abort the whole import.\n */\nfunction validateValidityWindow(\n entity: Readonly<{\n validFrom?: string | undefined;\n validTo?: string | undefined;\n }>,\n): string | undefined {\n try {\n validateOptionalCanonicalIsoDate(entity.validFrom, \"validFrom\");\n validateOptionalCanonicalIsoDate(entity.validTo, \"validTo\");\n return undefined;\n } catch (error) {\n return error instanceof Error ? error.message : String(error);\n }\n}\n\nasync function processNode(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n node: InterchangeNode,\n schemas: ReadonlyMap<string, NodeSchemaEntry>,\n options: ImportOptions,\n): Promise<ProcessResult> {\n // Validate kind exists\n const schemaEntry = schemas.get(node.kind);\n if (!schemaEntry) {\n return { status: \"error\", error: `Unknown node kind: ${node.kind}` };\n }\n\n // Validate and transform properties\n const propsResult = validateProperties(\n node.properties,\n schemaEntry.schema,\n options.onUnknownProperty,\n );\n\n if (!propsResult.success) {\n return { status: \"error\", error: propsResult.error };\n }\n\n const validityError = validateValidityWindow(node);\n if (validityError !== undefined) {\n return { status: \"error\", error: validityError };\n }\n\n // Check if node already exists\n const existing = await backend.getNode(graphId, node.kind, node.id);\n\n if (existing) {\n switch (options.onConflict) {\n case \"skip\": {\n return { status: \"skipped\" };\n }\n case \"error\": {\n return {\n status: \"error\",\n error: `Node already exists: ${node.kind}:${node.id}`,\n };\n }\n case \"update\": {\n await backend.updateNode({\n graphId,\n kind: node.kind,\n id: node.id,\n props: propsResult.data,\n incrementVersion: true,\n ...(node.validTo !== undefined && { validTo: node.validTo }),\n });\n return { status: \"updated\" };\n }\n }\n }\n\n // Create new node\n await backend.insertNode({\n graphId,\n kind: node.kind,\n id: node.id,\n props: propsResult.data,\n ...(node.validFrom !== undefined && { validFrom: node.validFrom }),\n ...(node.validTo !== undefined && { validTo: node.validTo }),\n });\n\n return { status: \"created\" };\n}\n\n// ============================================================\n// Edge Processing\n// ============================================================\n\nasync function processEdges(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n edges: readonly InterchangeEdge[],\n edgeSchemas: ReadonlyMap<string, EdgeSchemaEntry>,\n nodeSchemas: ReadonlyMap<string, NodeSchemaEntry>,\n options: ImportOptions,\n result: ImportResult,\n errors: ImportError[],\n importedNodeIds: Set<string>,\n): Promise<void> {\n const batchSize = options.batchSize;\n\n for (let index = 0; index < edges.length; index += batchSize) {\n const batch = edges.slice(index, index + batchSize);\n\n for (const edge of batch) {\n const importResult = await processEdge(\n backend,\n graphId,\n edge,\n edgeSchemas,\n nodeSchemas,\n options,\n importedNodeIds,\n );\n\n switch (importResult.status) {\n case \"created\": {\n result.edges.created++;\n break;\n }\n case \"updated\": {\n result.edges.updated++;\n break;\n }\n case \"skipped\": {\n result.edges.skipped++;\n break;\n }\n case \"error\": {\n errors.push({\n entityType: \"edge\",\n kind: edge.kind,\n id: edge.id,\n error: importResult.error,\n });\n break;\n }\n }\n }\n }\n}\n\nasync function processEdge(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n edge: InterchangeEdge,\n edgeSchemas: ReadonlyMap<string, EdgeSchemaEntry>,\n nodeSchemas: ReadonlyMap<string, NodeSchemaEntry>,\n options: ImportOptions,\n importedNodeIds: Set<string>,\n): Promise<ProcessResult> {\n // Validate edge kind exists\n const schemaEntry = edgeSchemas.get(edge.kind);\n if (!schemaEntry) {\n return { status: \"error\", error: `Unknown edge kind: ${edge.kind}` };\n }\n\n // Validate endpoint kinds\n if (!nodeSchemas.has(edge.from.kind)) {\n return {\n status: \"error\",\n error: `Unknown from node kind: ${edge.from.kind}`,\n };\n }\n if (!nodeSchemas.has(edge.to.kind)) {\n return { status: \"error\", error: `Unknown to node kind: ${edge.to.kind}` };\n }\n\n // Validate endpoint kinds are allowed for this edge type\n if (!schemaEntry.fromKinds.has(edge.from.kind)) {\n return {\n status: \"error\",\n error: `Edge ${edge.kind} does not allow from kind: ${edge.from.kind}`,\n };\n }\n if (!schemaEntry.toKinds.has(edge.to.kind)) {\n return {\n status: \"error\",\n error: `Edge ${edge.kind} does not allow to kind: ${edge.to.kind}`,\n };\n }\n\n // Validate references exist (in DB or in import batch)\n if (options.validateReferences) {\n const fromKey = makeNodeKey(edge.from.kind, edge.from.id);\n const toKey = makeNodeKey(edge.to.kind, edge.to.id);\n\n // Check import batch first, then DB\n if (!importedNodeIds.has(fromKey)) {\n const fromExists = await backend.getNode(\n graphId,\n edge.from.kind,\n edge.from.id,\n );\n if (!fromExists) {\n return {\n status: \"error\",\n error: `From node not found: ${edge.from.kind}:${edge.from.id}`,\n };\n }\n }\n\n if (!importedNodeIds.has(toKey)) {\n const toExists = await backend.getNode(graphId, edge.to.kind, edge.to.id);\n if (!toExists) {\n return {\n status: \"error\",\n error: `To node not found: ${edge.to.kind}:${edge.to.id}`,\n };\n }\n }\n }\n\n // Validate and transform properties\n const propsResult = validateProperties(\n edge.properties,\n schemaEntry.schema,\n options.onUnknownProperty,\n );\n\n if (!propsResult.success) {\n return { status: \"error\", error: propsResult.error };\n }\n\n const validityError = validateValidityWindow(edge);\n if (validityError !== undefined) {\n return { status: \"error\", error: validityError };\n }\n\n // Check if edge already exists\n const existing = await backend.getEdge(graphId, edge.id);\n\n if (existing) {\n switch (options.onConflict) {\n case \"skip\": {\n return { status: \"skipped\" };\n }\n case \"error\": {\n return { status: \"error\", error: `Edge already exists: ${edge.id}` };\n }\n case \"update\": {\n await backend.updateEdge({\n graphId,\n id: edge.id,\n props: propsResult.data,\n ...(edge.validTo !== undefined && { validTo: edge.validTo }),\n });\n return { status: \"updated\" };\n }\n }\n }\n\n // Create new edge\n await backend.insertEdge({\n graphId,\n id: edge.id,\n kind: edge.kind,\n fromKind: edge.from.kind,\n fromId: edge.from.id,\n toKind: edge.to.kind,\n toId: edge.to.id,\n props: propsResult.data,\n ...(edge.validFrom !== undefined && { validFrom: edge.validFrom }),\n ...(edge.validTo !== undefined && { validTo: edge.validTo }),\n });\n\n return { status: \"created\" };\n}\n\n// ============================================================\n// Property Validation\n// ============================================================\n\ntype ValidationResult =\n | { success: true; data: Record<string, unknown> }\n | { success: false; error: string };\n\nfunction validateProperties(\n properties: Record<string, unknown>,\n schema: z.ZodObject<z.ZodRawShape>,\n unknownStrategy: UnknownPropertyStrategy,\n): ValidationResult {\n try {\n // Get the schema's known keys\n const knownKeys = new Set(Object.keys(schema.shape));\n\n // Check for unknown properties\n const unknownKeys = Object.keys(properties).filter(\n (key) => !knownKeys.has(key),\n );\n\n if (unknownKeys.length > 0) {\n switch (unknownStrategy) {\n case \"error\": {\n return {\n success: false,\n error: `Unknown properties: ${unknownKeys.join(\", \")}`,\n };\n }\n case \"strip\": {\n // Remove unknown properties\n const stripped: Record<string, unknown> = {};\n for (const key of knownKeys) {\n if (key in properties) {\n stripped[key] = properties[key];\n }\n }\n // Validate stripped properties\n const result = schema.safeParse(stripped);\n if (!result.success) {\n return {\n success: false,\n error: formatZodError(result.error),\n };\n }\n return {\n success: true,\n data: result.data,\n };\n }\n case \"allow\": {\n // Validate but allow extra properties through\n const result = schema.safeParse(properties);\n if (!result.success) {\n return {\n success: false,\n error: formatZodError(result.error),\n };\n }\n // Return original properties (including unknown ones)\n return { success: true, data: properties };\n }\n }\n }\n\n // No unknown properties - standard validation\n const result = schema.safeParse(properties);\n if (!result.success) {\n return { success: false, error: formatZodError(result.error) };\n }\n\n return { success: true, data: result.data };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { success: false, error: `Validation error: ${message}` };\n }\n}\n\nfunction formatZodError(error: z.ZodError): string {\n return error.issues\n .map((issue) => {\n const path = issue.path.join(\".\");\n return path ? `${path}: ${issue.message}` : issue.message;\n })\n .join(\"; \");\n}\n\n// ============================================================\n// Helpers\n// ============================================================\n\nfunction makeNodeKey(kind: string, id: string): string {\n return `${kind}:${id}`;\n}\n"]}