@nicia-ai/typegraph 0.44.0 → 0.46.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 (392) hide show
  1. package/dist/backend/drizzle/indexes.cjs +11 -11
  2. package/dist/backend/drizzle/indexes.d.cts +1 -1
  3. package/dist/backend/drizzle/indexes.d.ts +1 -1
  4. package/dist/backend/drizzle/indexes.js +7 -7
  5. package/dist/backend/index.cjs +53 -54
  6. package/dist/backend/index.d.cts +3 -3
  7. package/dist/backend/index.d.ts +3 -3
  8. package/dist/backend/index.js +13 -14
  9. package/dist/backend/postgres/index.cjs +29 -30
  10. package/dist/backend/postgres/index.d.cts +7 -7
  11. package/dist/backend/postgres/index.d.ts +7 -7
  12. package/dist/backend/postgres/index.js +16 -17
  13. package/dist/backend/postgres/pglite-store.cjs +48 -43
  14. package/dist/backend/postgres/pglite-store.cjs.map +1 -1
  15. package/dist/backend/postgres/pglite-store.d.cts +15 -9
  16. package/dist/backend/postgres/pglite-store.d.ts +15 -9
  17. package/dist/backend/postgres/pglite-store.js +44 -39
  18. package/dist/backend/postgres/pglite-store.js.map +1 -1
  19. package/dist/backend/postgres/pglite.cjs +18 -19
  20. package/dist/backend/postgres/pglite.d.cts +4 -4
  21. package/dist/backend/postgres/pglite.d.ts +4 -4
  22. package/dist/backend/postgres/pglite.js +17 -18
  23. package/dist/backend/sqlite/index.cjs +26 -27
  24. package/dist/backend/sqlite/index.d.cts +6 -6
  25. package/dist/backend/sqlite/index.d.ts +6 -6
  26. package/dist/backend/sqlite/index.js +14 -15
  27. package/dist/backend/sqlite/libsql.cjs +21 -22
  28. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  29. package/dist/backend/sqlite/libsql.d.cts +15 -8
  30. package/dist/backend/sqlite/libsql.d.ts +15 -8
  31. package/dist/backend/sqlite/libsql.js +17 -18
  32. package/dist/backend/sqlite/libsql.js.map +1 -1
  33. package/dist/backend/sqlite/local-store.cjs +49 -44
  34. package/dist/backend/sqlite/local-store.cjs.map +1 -1
  35. package/dist/backend/sqlite/local-store.d.cts +15 -10
  36. package/dist/backend/sqlite/local-store.d.ts +15 -10
  37. package/dist/backend/sqlite/local-store.js +45 -40
  38. package/dist/backend/sqlite/local-store.js.map +1 -1
  39. package/dist/backend/sqlite/local.cjs +19 -20
  40. package/dist/backend/sqlite/local.d.cts +3 -3
  41. package/dist/backend/sqlite/local.d.ts +3 -3
  42. package/dist/backend/sqlite/local.js +17 -18
  43. package/dist/{chunk-XMYJY7NI.js → chunk-2LG2XB2M.js} +3 -3
  44. package/dist/{chunk-XMYJY7NI.js.map → chunk-2LG2XB2M.js.map} +1 -1
  45. package/dist/{chunk-QGKILWGZ.cjs → chunk-2NA5DYLO.cjs} +4 -4
  46. package/dist/{chunk-QGKILWGZ.cjs.map → chunk-2NA5DYLO.cjs.map} +1 -1
  47. package/dist/{chunk-5MUSU4ZP.cjs → chunk-3DHZCOT7.cjs} +20 -20
  48. package/dist/chunk-3DHZCOT7.cjs.map +1 -0
  49. package/dist/{chunk-OVUUTCPJ.cjs → chunk-4UGOKMI5.cjs} +268 -150
  50. package/dist/chunk-4UGOKMI5.cjs.map +1 -0
  51. package/dist/{chunk-FRHHDHKH.js → chunk-5262ZMTR.js} +26 -5
  52. package/dist/chunk-5262ZMTR.js.map +1 -0
  53. package/dist/{chunk-HOIFFY4M.js → chunk-5763DULU.js} +248 -76
  54. package/dist/chunk-5763DULU.js.map +1 -0
  55. package/dist/{chunk-7G32LIQM.js → chunk-5UVRGXD3.js} +277 -7
  56. package/dist/chunk-5UVRGXD3.js.map +1 -0
  57. package/dist/{chunk-IIT5K7SK.cjs → chunk-62ZP23AW.cjs} +15 -15
  58. package/dist/{chunk-IIT5K7SK.cjs.map → chunk-62ZP23AW.cjs.map} +1 -1
  59. package/dist/{chunk-S4KQ5LV4.js → chunk-775A4ZMN.js} +40 -6
  60. package/dist/chunk-775A4ZMN.js.map +1 -0
  61. package/dist/{chunk-QYWINYEA.cjs → chunk-7BQXPCGN.cjs} +830 -170
  62. package/dist/chunk-7BQXPCGN.cjs.map +1 -0
  63. package/dist/{chunk-FJMPR3OH.cjs → chunk-7EO3TCQB.cjs} +33 -7
  64. package/dist/chunk-7EO3TCQB.cjs.map +1 -0
  65. package/dist/chunk-7GT72YHH.cjs +1979 -0
  66. package/dist/chunk-7GT72YHH.cjs.map +1 -0
  67. package/dist/{chunk-SQRD2CYF.js → chunk-7VQXLT5O.js} +717 -76
  68. package/dist/chunk-7VQXLT5O.js.map +1 -0
  69. package/dist/{chunk-BCP7LLOY.js → chunk-7Z5OR7KO.js} +2706 -625
  70. package/dist/chunk-7Z5OR7KO.js.map +1 -0
  71. package/dist/chunk-A4OC4DVN.cjs +12 -0
  72. package/dist/{chunk-4SZ6XPTG.cjs.map → chunk-A4OC4DVN.cjs.map} +1 -1
  73. package/dist/{chunk-TDXIBCGY.cjs → chunk-A7J2YDDI.cjs} +5 -3
  74. package/dist/chunk-A7J2YDDI.cjs.map +1 -0
  75. package/dist/{chunk-FMMIX6N4.js → chunk-AKLS3BYZ.js} +56 -5
  76. package/dist/chunk-AKLS3BYZ.js.map +1 -0
  77. package/dist/{chunk-D7PG5D5K.js → chunk-AMKPPFUO.js} +32 -6
  78. package/dist/chunk-AMKPPFUO.js.map +1 -0
  79. package/dist/{chunk-PAW2XUZN.js → chunk-ASTI57H3.js} +3 -3
  80. package/dist/{chunk-PAW2XUZN.js.map → chunk-ASTI57H3.js.map} +1 -1
  81. package/dist/{chunk-FMGEZBAQ.js → chunk-BKCUOV7A.js} +27 -5
  82. package/dist/chunk-BKCUOV7A.js.map +1 -0
  83. package/dist/chunk-BSFJMMV3.cjs +268 -0
  84. package/dist/chunk-BSFJMMV3.cjs.map +1 -0
  85. package/dist/{chunk-63KCKSSH.js → chunk-C23WSN5E.js} +209 -24
  86. package/dist/chunk-C23WSN5E.js.map +1 -0
  87. package/dist/{chunk-JRP3VGHS.js → chunk-CBTIUB76.js} +3 -3
  88. package/dist/{chunk-JRP3VGHS.js.map → chunk-CBTIUB76.js.map} +1 -1
  89. package/dist/chunk-CNV4TXJG.js +58 -0
  90. package/dist/chunk-CNV4TXJG.js.map +1 -0
  91. package/dist/{chunk-QB6VMOJ2.cjs → chunk-CXBHOOIQ.cjs} +45 -10
  92. package/dist/chunk-CXBHOOIQ.cjs.map +1 -0
  93. package/dist/{chunk-46GDII45.js → chunk-DCQVHAYQ.js} +5 -5
  94. package/dist/{chunk-46GDII45.js.map → chunk-DCQVHAYQ.js.map} +1 -1
  95. package/dist/chunk-DLNROMQ7.js +306 -0
  96. package/dist/chunk-DLNROMQ7.js.map +1 -0
  97. package/dist/chunk-DYATYRY4.js +47 -0
  98. package/dist/chunk-DYATYRY4.js.map +1 -0
  99. package/dist/chunk-E4WNQBEF.cjs +217 -0
  100. package/dist/chunk-E4WNQBEF.cjs.map +1 -0
  101. package/dist/{chunk-G6Q5UM7U.js → chunk-FWJKWH6U.js} +5 -3
  102. package/dist/chunk-FWJKWH6U.js.map +1 -0
  103. package/dist/{chunk-BNUFUFAU.js → chunk-HFHTMECK.js} +7 -7
  104. package/dist/chunk-HFHTMECK.js.map +1 -0
  105. package/dist/{chunk-TFMVL4QH.js → chunk-I5MOXA4H.js} +20 -14
  106. package/dist/chunk-I5MOXA4H.js.map +1 -0
  107. package/dist/{chunk-4MB3AQAQ.js → chunk-J3WZ3FA2.js} +77 -3
  108. package/dist/chunk-J3WZ3FA2.js.map +1 -0
  109. package/dist/{chunk-UR7W5YQK.js → chunk-JBQQ7THH.js} +5 -3
  110. package/dist/chunk-JBQQ7THH.js.map +1 -0
  111. package/dist/chunk-JIVMTW7W.js +3393 -0
  112. package/dist/chunk-JIVMTW7W.js.map +1 -0
  113. package/dist/{chunk-2Y4IFKW7.js → chunk-JXA2ZP2Q.js} +6 -17
  114. package/dist/chunk-JXA2ZP2Q.js.map +1 -0
  115. package/dist/{chunk-GYA4JRP5.js → chunk-JXXDZTMN.js} +2 -2
  116. package/dist/chunk-JXXDZTMN.js.map +1 -0
  117. package/dist/chunk-JZUR7ZWE.js +254 -0
  118. package/dist/chunk-JZUR7ZWE.js.map +1 -0
  119. package/dist/chunk-K5ELX2GT.js +248 -0
  120. package/dist/chunk-K5ELX2GT.js.map +1 -0
  121. package/dist/chunk-LBJKZXDE.cjs +257 -0
  122. package/dist/chunk-LBJKZXDE.cjs.map +1 -0
  123. package/dist/{chunk-FGO5JFVJ.cjs → chunk-M4BDU5RX.cjs} +12 -12
  124. package/dist/{chunk-FGO5JFVJ.cjs.map → chunk-M4BDU5RX.cjs.map} +1 -1
  125. package/dist/{chunk-MIJKEVV7.js → chunk-MSY7FSX4.js} +37 -4
  126. package/dist/chunk-MSY7FSX4.js.map +1 -0
  127. package/dist/{chunk-ST3LPB2V.cjs → chunk-MUK4BU7K.cjs} +788 -146
  128. package/dist/chunk-MUK4BU7K.cjs.map +1 -0
  129. package/dist/{chunk-MCHP7RHZ.cjs → chunk-MXJDTH5B.cjs} +64 -41
  130. package/dist/chunk-MXJDTH5B.cjs.map +1 -0
  131. package/dist/{chunk-2VLBGQBY.cjs → chunk-N3257XE6.cjs} +724 -577
  132. package/dist/chunk-N3257XE6.cjs.map +1 -0
  133. package/dist/chunk-N66HCGCY.cjs +57 -0
  134. package/dist/chunk-N66HCGCY.cjs.map +1 -0
  135. package/dist/{chunk-CPEL3YIR.cjs → chunk-NFCVHQ5P.cjs} +55 -22
  136. package/dist/chunk-NFCVHQ5P.cjs.map +1 -0
  137. package/dist/{chunk-C4F7VJ5D.cjs → chunk-NI72YOJB.cjs} +84 -2
  138. package/dist/chunk-NI72YOJB.cjs.map +1 -0
  139. package/dist/{chunk-EE7N5XXQ.cjs → chunk-NK5Q7UNE.cjs} +10 -21
  140. package/dist/chunk-NK5Q7UNE.cjs.map +1 -0
  141. package/dist/{chunk-PHXITZE4.js → chunk-NMWDXFPH.js} +4 -4
  142. package/dist/{chunk-PHXITZE4.js.map → chunk-NMWDXFPH.js.map} +1 -1
  143. package/dist/{chunk-FSXTPBRN.js → chunk-NQ6BRJBE.js} +416 -850
  144. package/dist/chunk-NQ6BRJBE.js.map +1 -0
  145. package/dist/chunk-OH5E5KIO.js +2057 -0
  146. package/dist/chunk-OH5E5KIO.js.map +1 -0
  147. package/dist/chunk-ONU3HIED.cjs +2082 -0
  148. package/dist/chunk-ONU3HIED.cjs.map +1 -0
  149. package/dist/{chunk-STQ3BSED.cjs → chunk-PNN7RHVR.cjs} +66 -44
  150. package/dist/chunk-PNN7RHVR.cjs.map +1 -0
  151. package/dist/{chunk-6DCB664D.js → chunk-PQBQG7IM.js} +3 -3
  152. package/dist/{chunk-6DCB664D.js.map → chunk-PQBQG7IM.js.map} +1 -1
  153. package/dist/{chunk-ACSVZPK7.cjs → chunk-PWLJ77UV.cjs} +5 -3
  154. package/dist/chunk-PWLJ77UV.cjs.map +1 -0
  155. package/dist/chunk-Q7Q4WSLJ.cjs +328 -0
  156. package/dist/chunk-Q7Q4WSLJ.cjs.map +1 -0
  157. package/dist/{chunk-BEFM74L2.js → chunk-QLRESYPU.js} +637 -493
  158. package/dist/chunk-QLRESYPU.js.map +1 -0
  159. package/dist/{chunk-SBPC5IP3.js → chunk-QWX5YA3K.js} +784 -202
  160. package/dist/chunk-QWX5YA3K.js.map +1 -0
  161. package/dist/{chunk-TCRIQMBU.js → chunk-RJS7DECT.js} +8 -9
  162. package/dist/chunk-RJS7DECT.js.map +1 -0
  163. package/dist/{chunk-6JZUSDY2.cjs → chunk-RMQLSPA2.cjs} +297 -27
  164. package/dist/chunk-RMQLSPA2.cjs.map +1 -0
  165. package/dist/{chunk-SJDMVITW.cjs → chunk-RT5ZY4XA.cjs} +6 -5
  166. package/dist/chunk-RT5ZY4XA.cjs.map +1 -0
  167. package/dist/{chunk-IJTLXNGJ.js → chunk-T4XNKYXB.js} +780 -127
  168. package/dist/chunk-T4XNKYXB.js.map +1 -0
  169. package/dist/{chunk-PDGEXGS6.cjs → chunk-TQR4KBY2.cjs} +354 -182
  170. package/dist/chunk-TQR4KBY2.cjs.map +1 -0
  171. package/dist/chunk-TTAITEPJ.cjs +755 -0
  172. package/dist/chunk-TTAITEPJ.cjs.map +1 -0
  173. package/dist/{chunk-NN3QSOVS.cjs → chunk-U5SON7R2.cjs} +27 -27
  174. package/dist/{chunk-NN3QSOVS.cjs.map → chunk-U5SON7R2.cjs.map} +1 -1
  175. package/dist/{chunk-A2I2XO52.cjs → chunk-U63GDNRC.cjs} +32 -26
  176. package/dist/chunk-U63GDNRC.cjs.map +1 -0
  177. package/dist/{chunk-YNULOIR5.cjs → chunk-UDISNXDL.cjs} +64 -43
  178. package/dist/chunk-UDISNXDL.cjs.map +1 -0
  179. package/dist/{chunk-GWEDD3DH.js → chunk-UV3SN74I.js} +5 -5
  180. package/dist/{chunk-GWEDD3DH.js.map → chunk-UV3SN74I.js.map} +1 -1
  181. package/dist/{chunk-U5W4LKZV.cjs → chunk-VCRRKBLN.cjs} +9 -9
  182. package/dist/{chunk-U5W4LKZV.cjs.map → chunk-VCRRKBLN.cjs.map} +1 -1
  183. package/dist/{chunk-EFELJVLA.js → chunk-VGTJPTIC.js} +28 -5
  184. package/dist/chunk-VGTJPTIC.js.map +1 -0
  185. package/dist/chunk-VQH4VAWD.cjs +12 -0
  186. package/dist/{chunk-EPTSMFH7.cjs.map → chunk-VQH4VAWD.cjs.map} +1 -1
  187. package/dist/{chunk-SNXVDZAJ.js → chunk-W6OG3HDG.js} +5 -4
  188. package/dist/chunk-W6OG3HDG.js.map +1 -0
  189. package/dist/chunk-WDGA7IYB.js +207 -0
  190. package/dist/chunk-WDGA7IYB.js.map +1 -0
  191. package/dist/chunk-WEVQJ5LH.js +736 -0
  192. package/dist/chunk-WEVQJ5LH.js.map +1 -0
  193. package/dist/{chunk-3PRKZW6D.cjs → chunk-XBYVV3MP.cjs} +60 -5
  194. package/dist/chunk-XBYVV3MP.cjs.map +1 -0
  195. package/dist/{chunk-GFRGG2US.cjs → chunk-XCAGZAKP.cjs} +7 -7
  196. package/dist/{chunk-GFRGG2US.cjs.map → chunk-XCAGZAKP.cjs.map} +1 -1
  197. package/dist/{chunk-XR4YZFKW.cjs → chunk-XDF2UPEQ.cjs} +3864 -1783
  198. package/dist/chunk-XDF2UPEQ.cjs.map +1 -0
  199. package/dist/{chunk-7V2FGGI2.cjs → chunk-XMQSEJCF.cjs} +632 -1080
  200. package/dist/chunk-XMQSEJCF.cjs.map +1 -0
  201. package/dist/chunk-XNLIZYRZ.cjs +3432 -0
  202. package/dist/chunk-XNLIZYRZ.cjs.map +1 -0
  203. package/dist/{chunk-66UVLHQA.cjs → chunk-XNSI2FJO.cjs} +99 -100
  204. package/dist/chunk-XNSI2FJO.cjs.map +1 -0
  205. package/dist/chunk-XQSCL77R.cjs +60 -0
  206. package/dist/chunk-XQSCL77R.cjs.map +1 -0
  207. package/dist/{chunk-SVJ5GEXW.cjs → chunk-XUO3KQFO.cjs} +2 -2
  208. package/dist/chunk-XUO3KQFO.cjs.map +1 -0
  209. package/dist/{chunk-HJH3RMXG.cjs → chunk-YAAM3M2S.cjs} +10 -10
  210. package/dist/{chunk-HJH3RMXG.cjs.map → chunk-YAAM3M2S.cjs.map} +1 -1
  211. package/dist/{chunk-ATLN63JA.js → chunk-YBFHZUXX.js} +6 -6
  212. package/dist/{chunk-ATLN63JA.js.map → chunk-YBFHZUXX.js.map} +1 -1
  213. package/dist/{chunk-K3BUWSFR.js → chunk-YDFDBE6D.js} +119 -6
  214. package/dist/chunk-YDFDBE6D.js.map +1 -0
  215. package/dist/{chunk-OSZPLZIV.cjs → chunk-YVWGEQJE.cjs} +318 -132
  216. package/dist/chunk-YVWGEQJE.cjs.map +1 -0
  217. package/dist/{chunk-QT6V3YRH.js → chunk-YWGVVALJ.js} +3 -3
  218. package/dist/{chunk-QT6V3YRH.js.map → chunk-YWGVVALJ.js.map} +1 -1
  219. package/dist/core/index.cjs +40 -41
  220. package/dist/core/index.d.cts +4 -5
  221. package/dist/core/index.d.ts +4 -5
  222. package/dist/core/index.js +8 -9
  223. package/dist/{ddl-eWg7hx6R.d.cts → ddl-BJcOp4WZ.d.cts} +3 -3
  224. package/dist/{ddl-D5369kOY.d.ts → ddl-BXfGHbPN.d.ts} +3 -3
  225. package/dist/graph-extension/index.cjs +26 -23
  226. package/dist/graph-extension/index.d.cts +16 -6
  227. package/dist/graph-extension/index.d.ts +16 -6
  228. package/dist/graph-extension/index.js +7 -8
  229. package/dist/graph-merge/index.cjs +2459 -655
  230. package/dist/graph-merge/index.cjs.map +1 -1
  231. package/dist/graph-merge/index.d.cts +170 -33
  232. package/dist/graph-merge/index.d.ts +170 -33
  233. package/dist/graph-merge/index.js +2269 -468
  234. package/dist/graph-merge/index.js.map +1 -1
  235. package/dist/{index-By89Sezh.d.ts → index-BSHvKfok.d.ts} +221 -10
  236. package/dist/{index-DcQ3Sxs-.d.cts → index-DxaYCv8Y.d.cts} +221 -10
  237. package/dist/index.cjs +330 -269
  238. package/dist/index.cjs.map +1 -1
  239. package/dist/index.d.cts +590 -576
  240. package/dist/index.d.ts +590 -576
  241. package/dist/index.js +73 -50
  242. package/dist/index.js.map +1 -1
  243. package/dist/indexes/index.cjs +17 -17
  244. package/dist/indexes/index.d.cts +4 -4
  245. package/dist/indexes/index.d.ts +4 -4
  246. package/dist/indexes/index.js +10 -10
  247. package/dist/interchange/index.cjs +165 -50
  248. package/dist/interchange/index.cjs.map +1 -1
  249. package/dist/interchange/index.d.cts +261 -16
  250. package/dist/interchange/index.d.ts +261 -16
  251. package/dist/interchange/index.js +128 -24
  252. package/dist/interchange/index.js.map +1 -1
  253. package/dist/{manager-B0KjKE93.d.ts → manager-CfZAimti.d.ts} +36 -5
  254. package/dist/{manager-Cn0NFIhN.d.cts → manager-HGk6E_HW.d.cts} +36 -5
  255. package/dist/{materialize-indexes-BD4V3svD.d.ts → materialize-indexes-6A7dWGtb.d.cts} +10 -2
  256. package/dist/{materialize-indexes-DVRhd5h4.d.cts → materialize-indexes-BMJP6Tms.d.ts} +10 -2
  257. package/dist/{postgres-DaEWvN4x.d.cts → postgres-DFYWENdR.d.cts} +1961 -439
  258. package/dist/{postgres-u0a0HN2D.d.ts → postgres-e7a9TdvR.d.ts} +1961 -439
  259. package/dist/profiler/index.cjs +15 -15
  260. package/dist/profiler/index.d.cts +9 -10
  261. package/dist/profiler/index.d.ts +9 -10
  262. package/dist/profiler/index.js +4 -4
  263. package/dist/provenance/index.cjs +46 -48
  264. package/dist/provenance/index.cjs.map +1 -1
  265. package/dist/provenance/index.d.cts +7 -7
  266. package/dist/provenance/index.d.ts +7 -7
  267. package/dist/provenance/index.js +12 -14
  268. package/dist/provenance/index.js.map +1 -1
  269. package/dist/schema/index.cjs +50 -49
  270. package/dist/schema/index.d.cts +9 -16
  271. package/dist/schema/index.d.ts +9 -16
  272. package/dist/schema/index.js +23 -22
  273. package/dist/{searchable-CnYEancP.d.ts → searchable-9OQoPuRs.d.ts} +1 -2
  274. package/dist/{searchable-BT7j9_IK.d.cts → searchable-CIje5XYD.d.cts} +1 -2
  275. package/dist/{sqlite-BrMoSsI7.d.cts → sqlite-DerU5tc7.d.ts} +2029 -347
  276. package/dist/{sqlite-CHhZUyO5.d.ts → sqlite-DitnISa9.d.cts} +2029 -347
  277. package/dist/{store-view-Bvdku0Ht.d.ts → store-DawaWWjJ.d.ts} +3145 -2556
  278. package/dist/{store-view-w-md0nQ4.d.cts → store-RwTJx8LX.d.cts} +3145 -2556
  279. package/dist/{temporal-BCORwUau.d.cts → temporal-Bn-Fi8FJ.d.cts} +1 -1
  280. package/dist/{temporal--x9T8K4S.d.ts → temporal-BtM4UALv.d.ts} +1 -1
  281. package/dist/{types-6-WJmSD4.d.cts → types-CoIx8HX5.d.cts} +1 -1
  282. package/dist/{types-Cjvkj0jA.d.ts → types-HkveCCx0.d.cts} +866 -21
  283. package/dist/{types-Cjvkj0jA.d.cts → types-HkveCCx0.d.ts} +866 -21
  284. package/dist/{types-COODtTJU.d.ts → types-KFfk-8Ah.d.ts} +1 -1
  285. package/dist/{where-CUQmCR6d.d.cts → where--fk7_0kv.d.cts} +1 -1
  286. package/dist/{where-5xVawAwL.d.ts → where-ws5hf-Ov.d.ts} +1 -1
  287. package/package.json +1 -1
  288. package/dist/chunk-2BIG7U6E.cjs +0 -83
  289. package/dist/chunk-2BIG7U6E.cjs.map +0 -1
  290. package/dist/chunk-2L54C2C2.js +0 -144
  291. package/dist/chunk-2L54C2C2.js.map +0 -1
  292. package/dist/chunk-2VLBGQBY.cjs.map +0 -1
  293. package/dist/chunk-2WDD2NO3.js +0 -59
  294. package/dist/chunk-2WDD2NO3.js.map +0 -1
  295. package/dist/chunk-2Y4IFKW7.js.map +0 -1
  296. package/dist/chunk-35S6P5ZU.js +0 -27
  297. package/dist/chunk-35S6P5ZU.js.map +0 -1
  298. package/dist/chunk-3PRKZW6D.cjs.map +0 -1
  299. package/dist/chunk-4MB3AQAQ.js.map +0 -1
  300. package/dist/chunk-4SZ6XPTG.cjs +0 -12
  301. package/dist/chunk-5MUSU4ZP.cjs.map +0 -1
  302. package/dist/chunk-63KCKSSH.js.map +0 -1
  303. package/dist/chunk-66UVLHQA.cjs.map +0 -1
  304. package/dist/chunk-6JZUSDY2.cjs.map +0 -1
  305. package/dist/chunk-764JHTLT.cjs +0 -15
  306. package/dist/chunk-764JHTLT.cjs.map +0 -1
  307. package/dist/chunk-7G32LIQM.js.map +0 -1
  308. package/dist/chunk-7V2FGGI2.cjs.map +0 -1
  309. package/dist/chunk-A2I2XO52.cjs.map +0 -1
  310. package/dist/chunk-A4PBRX4C.cjs +0 -100
  311. package/dist/chunk-A4PBRX4C.cjs.map +0 -1
  312. package/dist/chunk-ACSVZPK7.cjs.map +0 -1
  313. package/dist/chunk-ALFUGRYB.cjs +0 -1282
  314. package/dist/chunk-ALFUGRYB.cjs.map +0 -1
  315. package/dist/chunk-B75XRV3O.js +0 -125
  316. package/dist/chunk-B75XRV3O.js.map +0 -1
  317. package/dist/chunk-BCP7LLOY.js.map +0 -1
  318. package/dist/chunk-BEFM74L2.js.map +0 -1
  319. package/dist/chunk-BNUFUFAU.js.map +0 -1
  320. package/dist/chunk-C4F7VJ5D.cjs.map +0 -1
  321. package/dist/chunk-CPEL3YIR.cjs.map +0 -1
  322. package/dist/chunk-D7PG5D5K.js.map +0 -1
  323. package/dist/chunk-DI74SMXS.cjs +0 -29
  324. package/dist/chunk-DI74SMXS.cjs.map +0 -1
  325. package/dist/chunk-DK2S42XB.js +0 -77
  326. package/dist/chunk-DK2S42XB.js.map +0 -1
  327. package/dist/chunk-DRACN6XG.js +0 -27
  328. package/dist/chunk-DRACN6XG.js.map +0 -1
  329. package/dist/chunk-EE7N5XXQ.cjs.map +0 -1
  330. package/dist/chunk-EFELJVLA.js.map +0 -1
  331. package/dist/chunk-EPTSMFH7.cjs +0 -12
  332. package/dist/chunk-EQ7JKLZO.cjs +0 -157
  333. package/dist/chunk-EQ7JKLZO.cjs.map +0 -1
  334. package/dist/chunk-FJMPR3OH.cjs.map +0 -1
  335. package/dist/chunk-FMGEZBAQ.js.map +0 -1
  336. package/dist/chunk-FMMIX6N4.js.map +0 -1
  337. package/dist/chunk-FRHHDHKH.js.map +0 -1
  338. package/dist/chunk-FSXTPBRN.js.map +0 -1
  339. package/dist/chunk-G6Q5UM7U.js.map +0 -1
  340. package/dist/chunk-GYA4JRP5.js.map +0 -1
  341. package/dist/chunk-HOHAJ2NR.cjs +0 -61
  342. package/dist/chunk-HOHAJ2NR.cjs.map +0 -1
  343. package/dist/chunk-HOIFFY4M.js.map +0 -1
  344. package/dist/chunk-IIMQJYAM.js +0 -81
  345. package/dist/chunk-IIMQJYAM.js.map +0 -1
  346. package/dist/chunk-IJTLXNGJ.js.map +0 -1
  347. package/dist/chunk-ITE4IXAK.js +0 -25
  348. package/dist/chunk-ITE4IXAK.js.map +0 -1
  349. package/dist/chunk-K3BUWSFR.js.map +0 -1
  350. package/dist/chunk-KCO5EFJU.js +0 -79
  351. package/dist/chunk-KCO5EFJU.js.map +0 -1
  352. package/dist/chunk-KKYELPZ2.cjs +0 -83
  353. package/dist/chunk-KKYELPZ2.cjs.map +0 -1
  354. package/dist/chunk-MCHP7RHZ.cjs.map +0 -1
  355. package/dist/chunk-MIJKEVV7.js.map +0 -1
  356. package/dist/chunk-NCX65HBY.cjs +0 -1396
  357. package/dist/chunk-NCX65HBY.cjs.map +0 -1
  358. package/dist/chunk-OSZPLZIV.cjs.map +0 -1
  359. package/dist/chunk-OVUUTCPJ.cjs.map +0 -1
  360. package/dist/chunk-PDGEXGS6.cjs.map +0 -1
  361. package/dist/chunk-QB6VMOJ2.cjs.map +0 -1
  362. package/dist/chunk-QMQLUA66.js +0 -12
  363. package/dist/chunk-QMQLUA66.js.map +0 -1
  364. package/dist/chunk-QYWINYEA.cjs.map +0 -1
  365. package/dist/chunk-S4KQ5LV4.js.map +0 -1
  366. package/dist/chunk-SBPC5IP3.js.map +0 -1
  367. package/dist/chunk-SJDMVITW.cjs.map +0 -1
  368. package/dist/chunk-SNXVDZAJ.js.map +0 -1
  369. package/dist/chunk-SQRD2CYF.js.map +0 -1
  370. package/dist/chunk-ST3LPB2V.cjs.map +0 -1
  371. package/dist/chunk-STQ3BSED.cjs.map +0 -1
  372. package/dist/chunk-SVJ5GEXW.cjs.map +0 -1
  373. package/dist/chunk-TCRIQMBU.js.map +0 -1
  374. package/dist/chunk-TDXIBCGY.cjs.map +0 -1
  375. package/dist/chunk-TFMVL4QH.js.map +0 -1
  376. package/dist/chunk-TRF4EBJT.cjs +0 -30
  377. package/dist/chunk-TRF4EBJT.cjs.map +0 -1
  378. package/dist/chunk-TVLKA4AY.js +0 -94
  379. package/dist/chunk-TVLKA4AY.js.map +0 -1
  380. package/dist/chunk-UR7W5YQK.js.map +0 -1
  381. package/dist/chunk-VITTKBWF.js +0 -1263
  382. package/dist/chunk-VITTKBWF.js.map +0 -1
  383. package/dist/chunk-WBUFJ7BS.cjs +0 -131
  384. package/dist/chunk-WBUFJ7BS.cjs.map +0 -1
  385. package/dist/chunk-XR4YZFKW.cjs.map +0 -1
  386. package/dist/chunk-YNULOIR5.cjs.map +0 -1
  387. package/dist/chunk-ZDH3DX3C.cjs +0 -30
  388. package/dist/chunk-ZDH3DX3C.cjs.map +0 -1
  389. package/dist/chunk-ZTAJL4DT.cjs +0 -85
  390. package/dist/chunk-ZTAJL4DT.cjs.map +0 -1
  391. package/dist/define-graph-DVF-oN1i.d.cts +0 -173
  392. package/dist/define-graph-SvYXOl78.d.ts +0 -173
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/interchange/types.ts","../src/interchange/stream-source.ts","../src/interchange/import.ts","../src/interchange/export.ts"],"names":["z","isCanonicalIsoDate","acquireSerializedStreamLease","storeBackend","storeRuntime","runInWriteTransaction","snapshotExportContention","ConfigurationError","ValidationError","NodeNotFoundError","IdentityContradictionError","IDENTITY_IMPORT_FAILED_ASSERTION","IDENTITY_IMPORT_PROGRESS","getNodeKinds","getEdgeKinds","createNodeBatchValidationBackend","primeBatchValidationCaches","isLiveNodeRow","rowPropsToObject","checkUniquenessConstraints","applyNodeInsertSideEffectsBatch","UniquenessError","applyNodeUpdate","DatabaseOperationError","INVERTED_VALIDITY_WINDOW_CODE","IMMUTABLE_VALIDITY_LOWER_BOUND_CODE","validateOptionalCanonicalIsoDate","assertOrderedValidityWindow","assertWritableValidityWindow","applyNodeInsertSideEffects","validateEdgeEndpoints","createDataKeyedBag","hasOwnKey","result","encodeTupleKey","ExportStreamCancelledError","nowIso","requireDefined","take","push"],"mappings":";;;;;;;;;;;;;AA4BO,IAAM,cAAA,GAAiB;AAQ9B,IAAM,8BAA8BA,KAAA,CAAE,IAAA,CAAK,CAAC,KAAA,EAAO,KAAK,CAAC,CAAA;AAWzD,IAAM,uBAAA,GAA0BA,KAAA,CAAE,GAAA,CAC/B,QAAA,EAAS,CACT,OAAO,CAAC,KAAA,KAAUC,oCAAA,CAAmB,KAAK,CAAA,EAAG;AAAA,EAC5C,OAAA,EACE;AACJ,CAAC,CAAA;AAYI,IAAM,qBAAA,GAAwBD,MAAE,MAAA,C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,SAAA;AACpD,QAAA,IAAI,IAAI,QAAA,EAAU;AAChB,UAAC,IAAA,CAA8B,UAAU,GAAA,CAAI,QAAA;AAAA,QAC/C;AAAA,MACF;AAEA,MAAA,IAAI,QAAQ,WAAA,EAAa;AACvB,QAAC,KAA4C,IAAA,GAAO;AAAA,UAClD,WAAW,GAAA,CAAI,UAAA;AAAA,UACf,WAAW,GAAA,CAAI;AAAA,SACjB;AAAA,MACF;AAEA,MAAA,OAAO,IAAA;AAAA,IACT,CAAC,CAAA;AACD,IAAA,MAAM,EAAE,IAAA,EAAM,OAAA,EAAS,KAAA,EAAM;AAC7B,IAAA,IAAI,IAAA,CAAK,MAAA,GAAS,OAAA,CAAQ,SAAA,EAAW;AACrC,IAAA,KAAA,GAAQmB,gCAAA,CAAe,IAAA,CAAK,EAAA,CAAG,EAAE,CAAC,CAAA,CAAE,EAAA;AAAA,EACtC;AACF","file":"chunk-ONU3HIED.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 — the value every export writes.\n *\n * Read-side compatibility policy: the format is versioned separately from what\n * it *accepts*. A 1.0 document is a structurally valid 2.0 document — the only\n * 2.0 addition is the optional `identity` section — so import and\n * {@link GraphDataSchema} accept both `\"1.0\"` and `\"2.0\"` (see\n * {@link AcceptedFormatVersionSchema}), while exports keep writing this\n * constant. Bump this only when exports must emit a new version; add the old\n * value to the accepted set rather than dropping read compatibility.\n */\nexport const FORMAT_VERSION = \"2.0\" as const;\n\n/**\n * Format versions accepted on the read side (import + `GraphDataSchema.parse`).\n * A pre-existing 1.0 export is a valid 2.0 document (the 2.0 change is the\n * additive optional `identity` section), so both validate; exports always write\n * {@link FORMAT_VERSION}.\n */\nconst AcceptedFormatVersionSchema = z.enum([\"1.0\", \"2.0\"]);\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 /**\n * `undefined` (key absent): not requested (`includeTemporal: false`) —\n * import defaults it to the import's own creation timestamp. `null`:\n * requested and confirmed the row has no lower bound (e.g. a legacy row\n * predating the \"omitted validFrom defaults to creation time\" fix) —\n * import preserves that open-left validity instead of re-stamping it.\n */\n validFrom: ValidityTimestampSchema.nullable().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 /** See {@link InterchangeNodeSchema}'s `validFrom` for the null/undefined contract. */\n validFrom: ValidityTimestampSchema.nullable().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// Operational Identity Interchange\n// ============================================================\n\nexport const IdentityInterchangeModeSchema = z.enum([\"state\", \"archival\"]);\nexport type IdentityInterchangeMode = z.infer<\n typeof IdentityInterchangeModeSchema\n>;\n\nexport const InterchangeIdentityAssertionSchema = z.object({\n id: z.string().min(1),\n relation: z.enum([\"same\", \"different\"]),\n a: z.object({ kind: z.string().min(1), id: z.string().min(1) }),\n b: z.object({ kind: z.string().min(1), id: z.string().min(1) }),\n validFrom: ValidityTimestampSchema,\n validTo: ValidityTimestampSchema.optional(),\n /**\n * The node whose soft-delete cascade ended this assertion — the ledger's\n * stored cause, carried so an `archival` round-trip preserves WHY each\n * ending happened and not merely that it did. Absent on open rows and on\n * explicit retractions; when present it names one of `a` / `b` and requires\n * `validTo`. Import rejects both violations with an attributed error.\n */\n endedBy: z\n .object({ kind: z.string().min(1), id: z.string().min(1) })\n .optional(),\n});\nexport type InterchangeIdentityAssertion = z.infer<\n typeof InterchangeIdentityAssertionSchema\n>;\n\nexport const InterchangeIdentitySchema = z.object({\n profile: z.literal(\"typegraph-identity-v1\"),\n mode: IdentityInterchangeModeSchema,\n assertions: z.array(InterchangeIdentityAssertionSchema),\n});\nexport type InterchangeIdentity = z.infer<typeof InterchangeIdentitySchema>;\n\nconst InterchangeIdentityHeaderSchema = InterchangeIdentitySchema.omit({\n assertions: true,\n});\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 /**\n * Number of items to process in each batch. Each batch pays fixed\n * per-round-trip costs (existence probe, unique check, one multi-row\n * insert), so undersized batches dominate import time on client/server\n * engines: measured on PostgreSQL, 20k nodes + 5k edges import in\n * 1,515ms at 100 vs 781ms at 1,000. Above ~1,000 the multi-row insert\n * itself dominates and larger batches stop paying; SQLite is\n * insensitive to the value (in-process, no round trips). The backend\n * further splits inserts by its bind-parameter budget, so a large\n * batch never overruns driver limits.\n */\n batchSize: z.number().int().positive().default(1000),\n /**\n * Refresh planner statistics (ANALYZE) after an import that created or\n * updated rows. Bulk loads otherwise run against stale statistics until\n * the engine catches up on its own. Default: true.\n */\n refreshStatistics: z.boolean().optional(),\n /**\n * How a streamed import reacts when one chunk reports entity-level errors.\n * `abort` is the safe default: earlier chunks are already committed, so\n * callers must not mistake a partial stream for a successful retryable load.\n * `continue` is reserved for explicit best-effort ingestion.\n */\n onStreamChunkError: z.enum([\"abort\", \"continue\"]).default(\"abort\"),\n});\n\n/**\n * Caller-facing options: fields with schema defaults are optional.\n * `importGraph` parses these once at its boundary; internal stages\n * consume {@link ResolvedImportOptions} with every default applied.\n */\nexport type ImportOptions = z.input<typeof ImportOptionsSchema>;\n\n/** {@link ImportOptions} after schema parsing — all defaults resolved. */\nexport type ResolvedImportOptions = 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: AcceptedFormatVersionSchema,\n exportedAt: z.iso.datetime(),\n source: GraphDataSourceSchema,\n nodes: z.array(InterchangeNodeSchema),\n edges: z.array(InterchangeEdgeSchema),\n identity: InterchangeIdentitySchema.optional(),\n});\n\nexport type GraphData = z.infer<typeof GraphDataSchema>;\n\n/** The metadata envelope emitted before streamed graph entities. */\nexport const GraphDataHeaderSchema = GraphDataSchema.omit({\n nodes: true,\n edges: true,\n identity: true,\n}).extend({\n identity: InterchangeIdentityHeaderSchema.optional(),\n});\n\nexport type GraphDataHeader = z.infer<typeof GraphDataHeaderSchema>;\n\n/**\n * One bounded unit in the streamed interchange protocol. Nodes always precede\n * edges, so an importer can validate endpoints from rows already written to its\n * target without retaining all prior nodes in memory.\n */\nexport const GraphInterchangeChunkSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"header\"), header: GraphDataHeaderSchema }),\n z.object({ type: z.literal(\"nodes\"), nodes: z.array(InterchangeNodeSchema) }),\n z.object({ type: z.literal(\"edges\"), edges: z.array(InterchangeEdgeSchema) }),\n z.object({\n type: z.literal(\"identity\"),\n assertions: z.array(InterchangeIdentityAssertionSchema),\n }),\n]);\n\nexport type GraphInterchangeChunk = z.infer<typeof GraphInterchangeChunkSchema>;\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\", \"identity\"]),\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 identity: z.object({\n created: 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 /** Operational Identity export mode. Defaults to current state only. */\n identityMode: IdentityInterchangeModeSchema.default(\"state\"),\n /**\n * Cancels the export: whatever it had opened is settled — on a backend with\n * `capabilities.transactions` that means its repeatable-read snapshot is\n * rolled back and the serialized connection's stream lease released; on one\n * without, there is no transaction and no lease, and the remaining reads are\n * simply abandoned. Either way the consumer is rejected with an\n * `ExportStreamCancelledError` (`code:\n * \"INTERCHANGE_EXPORT_STREAM_ABORTED\"`), whose message states which of the\n * two happened, carrying the signal's own `reason` as `cause`. Aborting\n * before the first read refuses the export outright: nothing is opened and\n * nothing claimed.\n *\n * On `exportGraph` this is a convenience — the call rejects instead of\n * running to completion. On {@link exportGraphStream} it is the ONLY\n * contract-grade way to stop a stream a consumer will not finish pulling:\n * an async generator's `finally` does not run on garbage collection, so a\n * consumer that pulls `next()` and then drops the iterator — the\n * `Promise.race([iterator.next(), timeout])` pattern — otherwise holds the\n * snapshot transaction, and with it the connection's exclusive stream lease,\n * until the process exits. `break` / `throw` out of a `for await` and an\n * explicit `iterator.return()` settle the stream cooperatively and need no\n * signal; a race that abandons the iterator needs one.\n */\n signal: z.instanceof(AbortSignal).optional(),\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/**\n * Export options for {@link exportGraphStream}. `batchSize` bounds the number\n * of node or edge entities retained for one yielded chunk.\n */\nexport const ExportStreamOptionsSchema = ExportOptionsSchema.extend({\n batchSize: z.number().int().positive().default(1000),\n});\n\nexport type ExportStreamOptions = z.infer<typeof ExportStreamOptionsSchema>;\nexport type ExportStreamOptionsInput = z.input<\n typeof ExportStreamOptionsSchema\n>;\n","import { type GraphBackend } from \"../backend/types\";\nimport { type GraphInterchangeChunk } from \"./types\";\n\nconst EXPORT_STREAM_BACKENDS = new WeakMap<\n AsyncIterable<GraphInterchangeChunk>,\n GraphBackend\n>();\n\nexport function markExportStreamBackend(\n stream: AsyncIterable<GraphInterchangeChunk>,\n backend: GraphBackend,\n): AsyncIterable<GraphInterchangeChunk> {\n EXPORT_STREAM_BACKENDS.set(stream, backend);\n return stream;\n}\n\nexport function exportStreamBackend(\n stream: AsyncIterable<GraphInterchangeChunk>,\n): GraphBackend | undefined {\n return EXPORT_STREAM_BACKENDS.get(stream);\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 *\n * ## A write asserts EVERY component its verdict read\n *\n * `onConflict: \"update\"` is a read-then-write pair: this module PROBES the\n * stored row, decides from what it finds, and then writes. Under PostgreSQL\n * READ COMMITTED a concurrent `hardDelete` + recreate re-resolves the probed key\n * between those two statements, so any part of the verdict that is not restated\n * in the UPDATE's own `WHERE` is a decision that can land on a row it was never\n * computed for — and the import reports success, because the write did affect a\n * row. The failure is invisible and only appears under a race, which is why it\n * has taken three rounds to enumerate:\n *\n * - the edge's KIND — the probe is keyed on `(graph_id, id)` alone, so the row\n * under an id may be a different edge entirely;\n * - the edge's ENDPOINTS — kind is not an identity, and an upsert that resolved\n * an edge BY its endpoints must say so;\n * - the effective `valid_from` of BOTH entities — {@link\n * validateUpdateValidityWindow} decides from the stored lower bound, so a\n * recreate carrying a different one turns that verdict into a write that\n * ignores the document's `validFrom` or persists `valid_to < valid_from`.\n *\n * The rest of what these legs read, and where each is asserted:\n *\n * - the row EXISTS (the `getNode` / `getEdge` probe): restated as the\n * `(graph_id, kind, id)` / `(graph_id, id)` predicate every UPDATE carries.\n * - the row is LIVE (`isLiveNodeRow` / `deleted_at === undefined`, which is what\n * routes a tombstone to `skipped` instead of to the update): restated as the\n * `deleted_at IS NULL` conjunction on the non-resurrecting UPDATE leg. Import\n * never resurrects, so it never builds the `IS NOT NULL` leg.\n * - `onConflict: \"skip\"` / `\"error\"`: verdict-independent by construction —\n * they write nothing.\n * - the row's PROPS, read as the `oldProps` side of the uniqueness diff: the\n * ONE input with no portable SQL predicate behind it (a props blob is TEXT on\n * SQLite and `jsonb` on PostgreSQL, and neither comparison is stable under\n * key reordering). It is bounded rather than asserted: the sidecar writes now\n * run AFTER the primary update returns a row (see `applyNodeUpdate`), so a\n * verdict-invalidating recreate that changes the lower bound takes the\n * sidecars with it. The residual window is a recreate that reproduces the\n * probed `valid_from` exactly while changing props — noted here so the next\n * round starts from the list rather than from the symptom.\n */\nimport type { z } from \"zod\";\n\nimport {\n acquireSerializedStreamLease,\n type SerializedStreamKind,\n type SnapshotExportContention,\n snapshotExportContention,\n} from \"../backend/transaction-resource\";\nimport {\n type GraphBackend,\n isLiveNodeRow,\n type LiveNodeRow,\n rowPropsToObject,\n type TransactionBackend,\n} from \"../backend/types\";\nimport { validateEdgeEndpoints } from \"../constraints\";\nimport {\n getEdgeKinds,\n getNodeKinds,\n type GraphDef,\n} from \"../core/define-graph\";\nimport {\n type EdgeRegistration,\n type NodeRegistration,\n type UniqueConstraint,\n} from \"../core/types\";\nimport {\n ConfigurationError,\n DatabaseOperationError,\n IdentityContradictionError,\n IMMUTABLE_VALIDITY_LOWER_BOUND_CODE,\n INVERTED_VALIDITY_WINDOW_CODE,\n NodeNotFoundError,\n UniquenessError,\n ValidationError,\n} from \"../errors\";\nimport {\n IDENTITY_IMPORT_FAILED_ASSERTION,\n IDENTITY_IMPORT_PROGRESS,\n} from \"../identity/service\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport {\n createNodeBatchValidationBackend,\n type NodeCreateDraft,\n primeBatchValidationCaches,\n} from \"../store/operations/node-operations\";\nimport {\n applyNodeInsertSideEffects,\n applyNodeInsertSideEffectsBatch,\n applyNodeUpdate,\n type NodeWriteContext,\n} from \"../store/operations/node-write-pipeline\";\nimport { runInWriteTransaction } from \"../store/operations/write-transaction\";\nimport { type GraphWriteLock } from \"../store/recorded-capture/clock\";\nimport { storeBackend, storeRuntime } from \"../store/runtime-port\";\nimport { type Store } from \"../store/store\";\nimport { checkUniquenessConstraints } from \"../store/uniqueness\";\nimport {\n assertOrderedValidityWindow,\n assertWritableValidityWindow,\n validateOptionalCanonicalIsoDate,\n type ValidityLowerBoundFence,\n} from \"../utils/date\";\nimport { createDataKeyedBag, hasOwnKey } from \"../utils/object\";\nimport { encodeTupleKey } from \"../utils/tuple-key\";\nimport { exportStreamBackend } from \"./stream-source\";\nimport {\n type GraphData,\n type GraphDataHeader,\n GraphDataHeaderSchema,\n type GraphInterchangeChunk,\n type ImportError,\n type ImportOptions,\n ImportOptionsSchema,\n type ImportResult,\n type InterchangeEdge,\n type InterchangeIdentityAssertion,\n InterchangeIdentitySchema,\n type InterchangeNode,\n type ResolvedImportOptions,\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 * Refused with a typed {@link ConfigurationError} when the target writes through\n * a serialized database connection another long-lived interchange operation\n * holds — the same refusal, codes and `details.heldBy` / `details.requested` as\n * {@link importGraphStream}. Hand-rolling a stream as `for await (const chunk of\n * exportGraphStream(source)) await importGraph(target, ...)` on one such\n * connection is therefore refused on the first chunk instead of nesting a write\n * transaction inside the export's open snapshot.\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 rawOptions: ImportOptions,\n): Promise<ImportResult> {\n // Parse ONCE at the public boundary: schema defaults (batchSize, ...)\n // only exist after parsing, and every internal stage reads them\n // directly.\n const options = ImportOptionsSchema.parse(rawOptions);\n return withImportStreamLease(store, () =>\n importGraphData(store, data, options),\n );\n}\n\n/**\n * Claims the target connection's exclusive stream lease for the whole of `run`,\n * or refuses with the holder named.\n *\n * GRANULARITY: an in-memory import is not one long-lived transaction — it is a\n * write transaction followed by a best-effort statistics refresh — but it IS one\n * long-lived operation on the connection, and it faces exactly the hazard the\n * streaming guard exists for: an export snapshot holding the single connection\n * this import must write on, or opening midway through it. A lease for the whole\n * call is the simplest claim that covers every write the call makes, so that is\n * what it takes.\n *\n * Claimed at each PUBLIC boundary that writes a whole import — this function's\n * own {@link importGraph} and `trustedImportGraphStream` — and nowhere else.\n * {@link importGraphStream} already holds the lease for its chunk loop and calls\n * {@link importGraphData} directly, so a per-chunk import is never refused by\n * the stream that issued it.\n */\nexport async function withImportStreamLease<G extends GraphDef, T>(\n store: Store<G>,\n run: () => Promise<T>,\n): Promise<T> {\n const lease = acquireSerializedStreamLease(\n storeBackend(store),\n \"import-stream\",\n );\n if (!lease.acquired) {\n throw serializedStreamRefusal({\n graphId: store.graphId,\n requested: \"import-stream\",\n heldBy: lease.heldBy,\n });\n }\n try {\n return await run();\n } finally {\n lease.release();\n }\n}\n\nasync function importGraphData<G extends GraphDef>(\n store: Store<G>,\n data: GraphData,\n options: ResolvedImportOptions,\n): Promise<ImportResult> {\n // Reject an identity payload aimed at an identity-disabled graph, and\n // runtime-validate the (bounded) identity section, BEFORE any entity write —\n // see assertIdentityImportSupported / validateIdentitySection.\n assertIdentityImportSupported(store, data.identity !== undefined);\n validateIdentitySection(data.identity);\n\n const result = emptyImportResult();\n\n const errors: ImportError[] = [];\n const graph = store.graph;\n const graphId = store.graphId;\n const backend = storeBackend(store);\n const runtime = storeRuntime(store);\n const registry = store.registry;\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 // One transaction on a transactional backend; runs directly otherwise, with\n // the per-graph write lock taken before any row work — see\n // runInWriteTransaction for the shared lock-before-rows contract every\n // writer follows.\n await runInWriteTransaction(\n {\n graphId,\n schemaVersion: store.introspect().schemaVersion,\n historyEnabled: store.historyEnabled,\n revisionTrackingEnabled: store.revisionTrackingEnabled,\n revisionSchema: store.revisionSchema,\n },\n backend,\n async (target, lock) => {\n await runtime.lockIdentityImportTarget(target);\n await processNodes(\n target,\n graphId,\n registry,\n data.nodes,\n nodeSchemas,\n options,\n result,\n errors,\n importedNodeIds,\n lock,\n );\n await runtime.foldImportedIdentityNodes(\n target,\n data.nodes\n .filter((node) =>\n importedNodeIds.has(makeNodeKey(node.kind, node.id)),\n )\n .map((node) => ({ kind: node.kind, id: node.id })),\n );\n await processEdges(\n target,\n graphId,\n registry,\n data.edges,\n edgeSchemas,\n nodeSchemas,\n options,\n result,\n errors,\n importedNodeIds,\n );\n if (data.identity !== undefined) {\n await importIdentitySection(\n runtime,\n target,\n graphId,\n data.identity,\n result,\n errors,\n );\n }\n },\n );\n\n // A bulk load runs against stale planner statistics until ANALYZE runs\n // (documented regressions: 0.5ms → 5ms traversals on Postgres, 0.9ms →\n // 23ms fulltext on SQLite), so a mutating import refreshes them once,\n // after the transaction commits.\n //\n // Best-effort: by this point the import is committed, so a failed\n // statistics refresh must not convert the completed (non-atomic on some\n // backends, non-retryable) import into a thrown failure — it degrades to\n // a warning, and the caller can run `store.refreshStatistics()`.\n await refreshStatisticsAfterImport(store, options, result, \"importGraph\");\n\n return {\n ...result,\n success: errors.length === 0,\n errors,\n };\n}\n\n/**\n * Imports a header-first stream of bounded interchange chunks.\n *\n * Each chunk is committed through the same implementation as an in-memory\n * {@link importGraph}, so validation and conflict semantics stay identical; the\n * chunk calls skip only that function's own lease claim, which this loop already\n * holds on their behalf.\n * Chunks are individually atomic on transactional backends; a consumer needing\n * all-or-nothing behavior can import into a disposable working-copy backend and\n * publish it only after this function succeeds.\n *\n * Nodes must precede edges. Once a node chunk commits, edge validation reads the\n * target store rather than retaining every imported node id in memory.\n *\n * Refused with a typed {@link ConfigurationError} when the target writes through\n * a serialized database connection that another long-lived interchange stream\n * already holds — either because this stream came from a snapshot export on that\n * connection, or because ANY export snapshot or streaming import holds it when\n * the first chunk arrives (which covers a stream the caller has wrapped). The\n * error's `details.heldBy` names the holder's kind and `details.code` the\n * condition: `INTERCHANGE_SHARED_SERIALIZED_BACKEND_SNAPSHOT` (or\n * `INTERCHANGE_SAME_SQLITE_BACKEND_SNAPSHOT`) behind an export snapshot,\n * `INTERCHANGE_SERIALIZED_IMPORT_IN_PROGRESS` behind another import.\n *\n * Once accepted, the import holds that connection's one stream lease for the\n * whole call — every chunk AND the trailing statistics refresh, which is a\n * write like any other — so any export snapshot or second import that tries to\n * start while a write of this import is still to come is the side refused, and\n * this import keeps running instead of stalling against a transaction it can\n * never write past.\n *\n * Connections we cannot observe are not detected: two clients dialed at one\n * server, or two SQLite handles on one file, are independent and are not\n * refused. Neither is a connection whose driver we cannot positively identify as\n * single-connection — see the residual gap documented in\n * `backend/transaction-resource.ts`.\n */\nexport async function importGraphStream<G extends GraphDef>(\n store: Store<G>,\n chunks: AsyncIterable<GraphInterchangeChunk>,\n rawOptions: ImportOptions,\n): Promise<ImportResult> {\n const options = ImportOptionsSchema.parse(rawOptions);\n const sourceBackend = exportStreamBackend(chunks);\n const targetBackend = storeBackend(store);\n // Whether this export would hold the connection the import writes through is\n // decided by the single owner of that predicate — including the\n // `transactions: false` abstention, where nothing is held open and refusing\n // would refuse work that succeeds.\n const contention =\n sourceBackend === undefined ? undefined : (\n snapshotExportContention(sourceBackend, targetBackend)\n );\n if (contention !== undefined) {\n throw serializedStreamRefusal({\n graphId: store.graphId,\n requested: \"import-stream\",\n heldBy: \"export-snapshot\",\n detector: contention,\n });\n }\n const result = emptyImportResult();\n let header: GraphDataHeader | undefined;\n let receivedEdges = false;\n let receivedIdentity = false;\n let releaseImportLease: (() => void) | undefined;\n\n try {\n for await (const chunk of chunks) {\n // The pre-flight check above needs the stream to still identify its source\n // backend, which any user wrapper (a delegating generator, `Readable.from`,\n // a tee) erases. By the time the FIRST chunk arrives the export's snapshot\n // transaction is already open and the registry says so itself, so a wrapped\n // stream fails the same way an unwrapped one does instead of stalling\n // behind a transaction that cannot end until this loop does.\n //\n // The claim is EXCLUSIVE and its check-and-register is one synchronous\n // section inside `acquireSerializedStreamLease`, so the two long-lived\n // streams can never both conclude the connection was free — and the\n // holder it reports may be an export snapshot OR another streaming\n // import, which nests its chunk transactions inside this one's just as\n // fatally. Whoever gets here second is refused; an export starting\n // mid-import is refused by `exportGraphStream` claiming the same lease, so\n // an import whose earlier chunks are already committed is never aborted\n // for someone else's stream. Nothing between the claim and the assignment\n // can throw, so the `finally` below owns every release path.\n if (releaseImportLease === undefined) {\n const lease = acquireSerializedStreamLease(\n targetBackend,\n \"import-stream\",\n );\n if (!lease.acquired) {\n throw serializedStreamRefusal({\n graphId: store.graphId,\n requested: \"import-stream\",\n heldBy: lease.heldBy,\n });\n }\n releaseImportLease = lease.release;\n }\n switch (chunk.type) {\n case \"header\": {\n if (header !== undefined) {\n throw new Error(\n \"Graph interchange stream emitted more than one header.\",\n );\n }\n // The header is bounded, so validate it at the runtime stream\n // boundary. In particular, an invalid identity profile/mode must not\n // slip through merely because the stream's identity assertion chunk is\n // empty.\n validateStreamHeader(chunk.header);\n // Reject an identity-bearing header aimed at an identity-disabled\n // graph before any chunk is processed, matching importGraph's guard.\n assertIdentityImportSupported(\n store,\n chunk.header.identity !== undefined,\n );\n header = chunk.header;\n break;\n }\n case \"nodes\": {\n if (header === undefined) {\n throw new Error(\n \"Graph interchange stream must start with a header.\",\n );\n }\n if (receivedEdges || receivedIdentity) {\n throw new Error(\n `Graph interchange stream cannot emit nodes after ${\n receivedEdges ? \"edges\" : \"identity assertions\"\n }.`,\n );\n }\n if (chunk.nodes.length === 0) break;\n mergeImportResult(\n result,\n await importGraphData(\n store,\n graphDataForChunk(header, chunk.nodes, [], []),\n {\n ...options,\n refreshStatistics: false,\n },\n ),\n );\n throwIfStreamChunkFailed(result, options);\n break;\n }\n case \"edges\": {\n if (header === undefined) {\n throw new Error(\n \"Graph interchange stream must start with a header.\",\n );\n }\n if (receivedIdentity) {\n throw new Error(\n \"Graph interchange stream cannot emit edges after identity assertions.\",\n );\n }\n receivedEdges = true;\n if (chunk.edges.length === 0) break;\n mergeImportResult(\n result,\n await importGraphData(\n store,\n graphDataForChunk(header, [], chunk.edges, []),\n {\n ...options,\n refreshStatistics: false,\n },\n ),\n );\n throwIfStreamChunkFailed(result, options);\n break;\n }\n case \"identity\": {\n if (header === undefined) {\n throw new Error(\n \"Graph interchange stream must start with a header.\",\n );\n }\n if (header.identity === undefined) {\n throw new Error(\n \"Graph interchange stream emitted identity rows without an identity header.\",\n );\n }\n receivedIdentity = true;\n if (chunk.assertions.length === 0) break;\n mergeImportResult(\n result,\n await importGraphData(\n store,\n graphDataForChunk(header, [], [], chunk.assertions),\n { ...options, refreshStatistics: false },\n ),\n );\n throwIfStreamChunkFailed(result, options);\n break;\n }\n }\n }\n if (header === undefined) {\n throw new Error(\n \"Graph interchange stream ended before emitting a header.\",\n );\n }\n // The trailing ANALYZE is a WRITE on the target connection, exactly like\n // the chunks were, so it belongs inside the lease rather than after it.\n // Releasing at the end of the chunk loop instead left this write outside\n // every guard: on a serialized connection an export snapshot opening in\n // that window takes the one connection ANALYZE has to run on and does not\n // give it back until the export ends, and the refresh's best-effort\n // handling swallowed the result as a warning. The lease now spans every\n // write this call makes — the same span `withImportStreamLease` gives\n // `importGraph`, whose refresh has always been inside it.\n await refreshStatisticsAfterImport(\n store,\n options,\n result,\n \"importGraphStream\",\n );\n } finally {\n // One release for every exit — the loop's, the missing-header throw, and\n // the refresh's — so \"the lease lives exactly as long as the writes\" holds\n // on the error paths too.\n releaseImportLease?.();\n }\n return { ...result, success: result.errors.length === 0 };\n}\n\n/**\n * The single owner of the refusal raised when two long-lived interchange streams\n * would run on one serialized database connection — from the import's pre-flight\n * check on the stream's own backend, from its mid-stream claim, and from\n * `exportGraphStream`'s claim alike, so every path states the same detected\n * condition in the same vocabulary.\n *\n * The CODE names the condition — which kind of stream holds the connection —\n * rather than which side was refused. `INTERCHANGE_SAME_SQLITE_BACKEND_SNAPSHOT`\n * is not a second condition: it reports that the object-identity DETECTOR\n * answered (one SQLite backend exporting into itself), which is worth telling\n * apart because the fix differs — pass a second backend, rather than await\n * whatever else is running. `details.heldBy`\n * and `details.requested` then say which pairing was actually refused, so a\n * same-kind refusal (import behind import, export behind export) is never\n * reported as something it is not:\n *\n * | holder | code |\n * | --------------- | --------------------------------------------- |\n * | export snapshot | `INTERCHANGE_SHARED_SERIALIZED_BACKEND_SNAPSHOT` (or `INTERCHANGE_SAME_SQLITE_BACKEND_SNAPSHOT` when the object-identity detector answered) |\n * | import stream | `INTERCHANGE_SERIALIZED_IMPORT_IN_PROGRESS` |\n *\n * Every message describes exactly what is detected. None claims anything about\n * connections we cannot observe (two clients dialed at the same server, two\n * SQLite handles on one file), which are independent and are not refused.\n */\nexport function serializedStreamRefusal(\n input: Readonly<{\n graphId: string;\n requested: SerializedStreamKind;\n heldBy: SerializedStreamKind;\n /**\n * Which detector found the holding export snapshot, when the import's\n * pre-flight — not the lease — is what answered. Only\n * `\"same-sqlite-backend\"` changes the code, because only that detector\n * identifies a distinguishable situation for the caller: the source and the\n * target are the same SQLite backend object, which no ordering can fix.\n */\n detector?: SnapshotExportContention;\n }>,\n): ConfigurationError {\n const { graphId, requested, heldBy, detector } = input;\n const code =\n heldBy === \"import-stream\" ? SERIALIZED_IMPORT_IN_PROGRESS_CODE\n : detector === \"same-sqlite-backend\" ?\n \"INTERCHANGE_SAME_SQLITE_BACKEND_SNAPSHOT\"\n : \"INTERCHANGE_SHARED_SERIALIZED_BACKEND_SNAPSHOT\";\n const { message, suggestion } = serializedStreamRefusalText(\n requested,\n heldBy,\n );\n return new ConfigurationError(\n message,\n { code, graphId, requested, heldBy },\n { suggestion },\n );\n}\n\n/**\n * The refusal code for \"a streaming import holds the connection this stream\n * needs\", in either of the two orders it can be discovered.\n */\nconst SERIALIZED_IMPORT_IN_PROGRESS_CODE =\n \"INTERCHANGE_SERIALIZED_IMPORT_IN_PROGRESS\";\n\n/**\n * What each of the four pairings actually does to the one connection. Each\n * message names both streams, because \"a stream already holds this connection\"\n * is not actionable without knowing which one.\n */\nfunction serializedStreamRefusalText(\n requested: SerializedStreamKind,\n heldBy: SerializedStreamKind,\n): Readonly<{ message: string; suggestion: string }> {\n if (heldBy === \"export-snapshot\") {\n return requested === \"import-stream\" ?\n {\n message:\n \"A snapshot export cannot be streamed into a target that writes through the same serialized database connection: the export's read transaction holds that connection open for the whole stream, so this import can never take the writer slot it needs.\",\n suggestion:\n \"Export to a file first, or import the stream into an independent backend.\",\n }\n : {\n message:\n \"A snapshot export cannot open on a serialized database connection while another snapshot export is streaming from it: the second export's read transaction would have to nest inside the first one on the single connection they share.\",\n suggestion:\n \"Await the export already in flight before starting the next one, or export from an independent backend.\",\n };\n }\n return requested === \"export-snapshot\" ?\n {\n message:\n \"A snapshot export cannot open on a serialized database connection while a streaming import is writing through it: the export's read transaction would hold the one connection the import's next chunk has to write on.\",\n suggestion:\n \"Await the import before exporting, or export from an independent backend.\",\n }\n : {\n message:\n \"A streaming import cannot open on a serialized database connection while another streaming import is writing through it: the two imports commit their chunks on the single connection they share, so the second one's chunk transaction would have to nest inside the first one's.\",\n suggestion:\n \"Await the import already in flight before starting the next one, or import into an independent backend.\",\n };\n}\n\nfunction throwIfStreamChunkFailed(\n result: ImportResult,\n options: ResolvedImportOptions,\n): void {\n if (options.onStreamChunkError === \"continue\" || result.errors.length === 0) {\n return;\n }\n throw new Error(\n \"Graph interchange stream aborted after a chunk reported import errors. \" +\n 'Earlier chunks remain committed; use onStreamChunkError: \"continue\" for best-effort ingestion.',\n );\n}\n\n/**\n * Rejects an identity payload aimed at an identity-disabled graph BEFORE any\n * entity write. The internal identity import coordinator raises the same\n * typed `ConfigurationError` (code `IDENTITY_IMPORT_REQUIRES_PROFILE`), but only\n * after `processNodes`/`processEdges` have run — a partial write on a\n * non-transactional backend — and only for a NON-empty assertions array (an\n * empty envelope short-circuits and silently succeeds there). This guard fires\n * first and regardless of assertion count.\n */\nfunction assertIdentityImportSupported<G extends GraphDef>(\n store: Store<G>,\n hasIdentitySection: boolean,\n): void {\n if (hasIdentitySection && store.graph.identity === undefined) {\n throw new ConfigurationError(\n \"Cannot import identity assertions into an identity-disabled graph.\",\n { code: \"IDENTITY_IMPORT_REQUIRES_PROFILE\", graphId: store.graphId },\n );\n }\n}\n\n/**\n * Runtime-validates just the identity section of an otherwise pre-typed\n * `GraphData`. {@link importGraph} deliberately trusts the type for the\n * (potentially graph-sized) node and edge arrays to preserve its per-row\n * performance, but a JS caller can still smuggle an out-of-domain `relation` or\n * a non-canonical timestamp straight into SQL — which SQLite accepts and\n * PostgreSQL rejects, a backend-parity divergence. The identity section is\n * bounded, so parsing only it closes that gap without the whole-envelope cost.\n */\nfunction validateIdentitySection(identity: GraphData[\"identity\"]): void {\n if (identity === undefined) return;\n const parsed = InterchangeIdentitySchema.safeParse(identity);\n if (parsed.success) return;\n throw new ValidationError(\n `Invalid identity interchange section: ${parsed.error.message}`,\n {\n issues: parsed.error.issues.map((issue) => ({\n path: issue.path.join(\".\"),\n message: issue.message,\n code: issue.code,\n })),\n },\n { cause: parsed.error },\n );\n}\n\n/**\n * An identity assertion is neither a node nor an edge, so it carries its own\n * `entityType`. The identity analogue of a node or edge kind is the relation\n * asserted, and the entity id is the assertion id. A failure that cannot be\n * attributed to a document assertion — which the coordinator's own error\n * details should always allow — falls back to naming the target graph, so the\n * entry still reaches the caller rather than being dropped or rethrown.\n */\nconst IDENTITY_IMPORT_ERROR_ENTITY_TYPE = \"identity\";\nconst IDENTITY_IMPORT_ERROR_PATH = \"identity.assertions\";\nconst UNATTRIBUTED_IDENTITY_ERROR_KIND = \"assertion\";\nconst IDENTITY_IMPORT_ID_CONFLICT_CODE = \"IDENTITY_IMPORT_ID_CONFLICT\";\n\nfunction identityImportError(\n assertion: InterchangeIdentityAssertion | undefined,\n graphId: string,\n message: string,\n): ImportError {\n const path =\n assertion === undefined ?\n IDENTITY_IMPORT_ERROR_PATH\n : `${IDENTITY_IMPORT_ERROR_PATH}[${assertion.id}]`;\n return {\n entityType: IDENTITY_IMPORT_ERROR_ENTITY_TYPE,\n kind: assertion?.relation ?? UNATTRIBUTED_IDENTITY_ERROR_KIND,\n id: assertion?.id ?? graphId,\n error: `${path}: ${message}`,\n };\n}\n\nfunction isIdConflictError(error: unknown): error is ConfigurationError {\n return (\n error instanceof ConfigurationError &&\n error.details[\"code\"] === IDENTITY_IMPORT_ID_CONFLICT_CODE\n );\n}\n\nfunction touchesRef(\n assertion: InterchangeIdentityAssertion,\n ref: Readonly<{ kind: string; id: string }>,\n): boolean {\n return (\n (assertion.a.kind === ref.kind && assertion.a.id === ref.id) ||\n (assertion.b.kind === ref.kind && assertion.b.id === ref.id)\n );\n}\n\n/**\n * Converts a per-document identity failure into an {@link ImportError}, or\n * returns `undefined` for anything that is not one — a configuration or\n * programming fault must still propagate.\n */\nfunction asIdentityImportError(\n assertions: readonly InterchangeIdentityAssertion[],\n graphId: string,\n error: unknown,\n): ImportError | undefined {\n // The coordinator tags the error with the id of the assertion it was\n // APPLYING — exact attribution. The endpoint heuristics below are only the\n // fallback for an untagged error: they pick the first assertion touching\n // the endpoints, which is wrong whenever an earlier assertion over the same\n // pair succeeded.\n const tagged = taggedAssertion(assertions, error);\n if (error instanceof NodeNotFoundError) {\n const ref = error.details;\n const assertion =\n tagged ?? assertions.find((candidate) => touchesRef(candidate, ref));\n return identityImportError(assertion, graphId, error.message);\n }\n if (error instanceof IdentityContradictionError) {\n const { a, b } = error.details;\n const assertion =\n tagged ??\n assertions.find(\n (candidate) => touchesRef(candidate, a) && touchesRef(candidate, b),\n );\n return identityImportError(assertion, graphId, error.message);\n }\n if (isIdConflictError(error)) {\n const assertion = assertions.find(\n (candidate) => candidate.id === error.details[\"assertionId\"],\n );\n return identityImportError(assertion, graphId, error.message);\n }\n if (isIdentityAssertionValidationError(error)) {\n const issue = error.details.issues[0];\n const message =\n issue === undefined ?\n error.message\n : `${error.message} (${issue.message})`;\n return identityImportError(\n assertions.find((candidate) => candidate.id === issue?.assertionId),\n graphId,\n message,\n );\n }\n return undefined;\n}\n\n/**\n * The assertion the coordinator tagged onto the error via\n * `IDENTITY_IMPORT_FAILED_ASSERTION` — exact, structural attribution for any\n * error shape.\n */\nfunction taggedAssertion(\n assertions: readonly InterchangeIdentityAssertion[],\n error: unknown,\n): InterchangeIdentityAssertion | undefined {\n if (typeof error !== \"object\" || error === null) return undefined;\n const id = (error as Record<PropertyKey, unknown>)[\n IDENTITY_IMPORT_FAILED_ASSERTION\n ];\n if (typeof id !== \"string\") return undefined;\n return assertions.find((candidate) => candidate.id === id);\n}\n\n/**\n * A `ValidationError` the identity import coordinator raised about assertion\n * CONTENT (ended rows in state mode, out-of-bounds validity windows, unknown\n * kinds, unnormalized pairs, self-assertions). Every issue it emits is pathed\n * at `identity.assertions` and carries the offending assertion's id\n * structurally in `assertionId` — attribution never parses the\n * human-readable message. A validation error shaped any other way is a\n * document-shape or programming fault and must still propagate.\n */\nfunction isIdentityAssertionValidationError(\n error: unknown,\n): error is ValidationError {\n return (\n error instanceof ValidationError &&\n error.details.issues.length > 0 &&\n error.details.issues.every(\n (issue) =>\n issue.path === \"identity.assertions\" && issue.assertionId !== undefined,\n )\n );\n}\n\n/**\n * Applies the identity section, recording a per-document failure in\n * `result.errors` instead of aborting the whole import.\n *\n * {@link importGraph} promises `{ success: false, errors }` for content the\n * target rejects, and the node and edge paths honor that by recording the\n * offending row and moving on. The identity coordinator instead throws, so a\n * missing endpoint, a contradiction against the target graph, or a reused\n * assertion id escaped the transaction and turned a rejected assertion into a\n * thrown import — discarding the valid node and edge work alongside it.\n *\n * Assertions the coordinator applied before the failing one stay committed,\n * exactly as rows accepted before a failing node do. The tagged error carries\n * the coordinator's completed counts so the returned result describes those\n * durable partial effects accurately.\n */\nasync function importIdentitySection<G extends GraphDef>(\n runtime: ReturnType<typeof storeRuntime<G>>,\n target: GraphBackend | TransactionBackend,\n graphId: string,\n identity: NonNullable<GraphData[\"identity\"]>,\n result: ImportResult,\n errors: ImportError[],\n): Promise<void> {\n try {\n const summary = await runtime.importIdentityAssertionsAtTarget(\n target,\n identity.assertions,\n identity.mode,\n );\n result.identity.created += summary.created;\n result.identity.skipped += summary.skipped;\n } catch (error) {\n const entry = asIdentityImportError(identity.assertions, graphId, error);\n if (entry === undefined) throw error;\n const progress = identityImportProgress(error);\n result.identity.created += progress.created;\n result.identity.skipped += progress.skipped;\n errors.push(entry);\n }\n}\n\nfunction identityImportProgress(\n error: unknown,\n): Readonly<{ created: number; skipped: number }> {\n if (typeof error !== \"object\" || error === null) {\n return { created: 0, skipped: 0 };\n }\n const progress = (error as Record<PropertyKey, unknown>)[\n IDENTITY_IMPORT_PROGRESS\n ];\n if (\n typeof progress !== \"object\" ||\n progress === null ||\n !(\"created\" in progress) ||\n typeof progress.created !== \"number\" ||\n !(\"skipped\" in progress) ||\n typeof progress.skipped !== \"number\"\n ) {\n return { created: 0, skipped: 0 };\n }\n return { created: progress.created, skipped: progress.skipped };\n}\n\nfunction validateStreamHeader(header: GraphDataHeader): void {\n const parsed = GraphDataHeaderSchema.safeParse(header);\n if (parsed.success) return;\n throw new ValidationError(\n `Invalid graph interchange stream header: ${parsed.error.message}`,\n {\n issues: parsed.error.issues.map((issue) => ({\n path: issue.path.join(\".\"),\n message: issue.message,\n code: issue.code,\n })),\n },\n { cause: parsed.error },\n );\n}\n\nfunction emptyImportResult(): ImportResult {\n return {\n success: true,\n nodes: { created: 0, updated: 0, skipped: 0 },\n edges: { created: 0, updated: 0, skipped: 0 },\n identity: { created: 0, skipped: 0 },\n errors: [],\n };\n}\n\nfunction graphDataForChunk(\n header: GraphDataHeader,\n nodes: GraphData[\"nodes\"],\n edges: GraphData[\"edges\"],\n assertions: readonly InterchangeIdentityAssertion[],\n): GraphData {\n const { identity, ...headerWithoutIdentity } = header;\n return {\n ...headerWithoutIdentity,\n nodes,\n edges,\n ...(identity === undefined ?\n {}\n : {\n identity: { ...identity, assertions: [...assertions] },\n }),\n };\n}\nfunction mergeImportResult(target: ImportResult, source: ImportResult): void {\n target.nodes.created += source.nodes.created;\n target.nodes.updated += source.nodes.updated;\n target.nodes.skipped += source.nodes.skipped;\n target.edges.created += source.edges.created;\n target.edges.updated += source.edges.updated;\n target.edges.skipped += source.edges.skipped;\n target.identity.created += source.identity.created;\n target.identity.skipped += source.identity.skipped;\n target.errors.push(...source.errors);\n}\n\n/**\n * Refreshes planner statistics after a mutating import.\n *\n * CALLED UNDER THE TARGET CONNECTION'S STREAM LEASE by every surface: ANALYZE\n * is a write, and a write that runs outside the lease can be stranded by an\n * export snapshot that takes the one connection it needs. `importGraph` holds\n * the lease through {@link withImportStreamLease} for its whole call;\n * `importGraphStream` holds its chunk-loop lease across this call too.\n *\n * Best-effort: by this point the import is committed, so a failed statistics\n * refresh must not convert the completed (non-atomic on some backends,\n * non-retryable) import into a thrown failure — it degrades to a warning, and\n * the caller can run `store.refreshStatistics()`.\n */\nasync function refreshStatisticsAfterImport<G extends GraphDef>(\n store: Store<G>,\n options: ResolvedImportOptions,\n result: ImportResult,\n surface: \"importGraph\" | \"importGraphStream\",\n): Promise<void> {\n const mutationCount =\n result.nodes.created +\n result.nodes.updated +\n result.edges.created +\n result.edges.updated +\n result.identity.created;\n if ((options.refreshStatistics ?? true) && mutationCount > 0) {\n try {\n await store.refreshStatistics();\n } catch (error) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.warn === \"function\"\n ) {\n console.warn(\n `[typegraph] ${surface} committed its rows but the follow-up ` +\n \"statistics refresh failed; run store.refreshStatistics() to \" +\n \"give the planner fresh statistics.\",\n error,\n );\n }\n }\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}>;\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 });\n }\n\n return map;\n}\n\n// ============================================================\n// Node Processing\n// ============================================================\n\nasync function processNodes(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n registry: KindRegistry,\n nodes: readonly InterchangeNode[],\n schemas: ReadonlyMap<string, NodeSchemaEntry>,\n options: ResolvedImportOptions,\n result: ImportResult,\n errors: ImportError[],\n importedNodeIds: Set<string>,\n lock: GraphWriteLock,\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 await processNodeSlice(\n backend,\n graphId,\n registry,\n batch,\n schemas,\n options,\n result,\n errors,\n importedNodeIds,\n lock,\n );\n }\n}\n\nfunction recordNodeOutcome(\n node: InterchangeNode,\n outcome: ProcessResult,\n result: ImportResult,\n errors: ImportError[],\n importedNodeIds: Set<string>,\n): void {\n switch (outcome.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 // A live skipped row is still a valid edge endpoint; a tombstone\n // is not.\n if (outcome.liveTarget) {\n importedNodeIds.add(makeNodeKey(node.kind, node.id));\n }\n break;\n }\n case \"error\": {\n errors.push({\n entityType: \"node\",\n kind: node.kind,\n id: node.id,\n error: outcome.error,\n });\n break;\n }\n }\n}\n\ntype NodeImportCandidate = Readonly<{\n node: InterchangeNode;\n schemaEntry: NodeSchemaEntry;\n props: Record<string, unknown>;\n draft: NodeCreateDraft;\n}>;\n\n/**\n * Processes one batchSize slice of nodes with batched round trips:\n * one `getNodes` per kind for existence, one `checkUniqueBatch` per\n * (constraint, kind) for uniqueness pre-checks (both priming the shared\n * batch validation caches), then one multi-row insert and one batched\n * side-effect pass for the accepted creates. Per-row semantics are\n * unchanged — conflicts route by `onConflict`, a uniqueness conflict is a\n * per-row error entry, and rows repeating an id already seen in the slice\n * defer to the per-row path after the flush (so they observe the first\n * occurrence's row exactly as the sequential implementation did).\n */\nasync function processNodeSlice(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n registry: KindRegistry,\n batch: readonly InterchangeNode[],\n schemas: ReadonlyMap<string, NodeSchemaEntry>,\n options: ResolvedImportOptions,\n result: ImportResult,\n errors: ImportError[],\n importedNodeIds: Set<string>,\n lock: GraphWriteLock,\n): Promise<void> {\n const record = (node: InterchangeNode, outcome: ProcessResult): void => {\n recordNodeOutcome(node, outcome, result, errors, importedNodeIds);\n };\n\n // Pass 1 (synchronous): kind + property + validity validation, and\n // in-slice duplicate deferral.\n const candidates: NodeImportCandidate[] = [];\n const deferred: InterchangeNode[] = [];\n const seenKeys = new Set<string>();\n for (const node of batch) {\n const schemaEntry = schemas.get(node.kind);\n if (!schemaEntry) {\n record(node, {\n status: \"error\",\n error: `Unknown node kind: ${node.kind}`,\n });\n continue;\n }\n const propsResult = validateProperties(\n node.properties,\n schemaEntry.schema,\n options.onUnknownProperty,\n );\n if (!propsResult.success) {\n record(node, { status: \"error\", error: propsResult.error });\n continue;\n }\n const validityError = validateValidityWindow(node);\n if (validityError !== undefined) {\n record(node, { status: \"error\", error: validityError });\n continue;\n }\n const key = makeNodeKey(node.kind, node.id);\n if (seenKeys.has(key)) {\n deferred.push(node);\n continue;\n }\n seenKeys.add(key);\n candidates.push({\n node,\n schemaEntry,\n props: propsResult.data,\n draft: {\n kind: node.kind,\n id: node.id,\n // Interchange rows always carry an explicit id.\n idProvided: true,\n nodeKind: schemaEntry.registration.type,\n uniqueConstraints: schemaEntry.registration.unique ?? [],\n validatedProps: propsResult.data,\n // NodeCreateDraft.validFrom is string | undefined (never null) — it\n // only feeds batch validation-cache priming, which never inspects\n // it, so normalizing the explicit-NULL sentinel away here is inert.\n // The actual insert (buildImportInsertParams) reads node.validFrom\n // directly and preserves the null.\n validFrom: node.validFrom ?? undefined,\n validTo: node.validTo,\n },\n });\n }\n\n // Prime the validation caches with batched reads, then route each row\n // against memory in input order.\n const {\n backend: validationBackend,\n registerPendingNode,\n registerPendingUniqueEntries,\n registerAppliedNodeUpdate,\n seedNodeRow,\n seedUniqueRow,\n } = createNodeBatchValidationBackend(graphId, registry, backend);\n await primeBatchValidationCaches(\n { graphId, registry },\n candidates.map((candidate) => candidate.draft),\n backend,\n { seedNodeRow, seedUniqueRow },\n );\n\n const writeContext = { graphId, registry, lock };\n const accepted: NodeImportCandidate[] = [];\n for (const candidate of candidates) {\n const { node, schemaEntry, props } = candidate;\n const uniqueConstraints = schemaEntry.registration.unique ?? [];\n const existing = await validationBackend.getNode(\n graphId,\n node.kind,\n node.id,\n );\n\n if (existing) {\n switch (options.onConflict) {\n case \"skip\": {\n record(node, {\n status: \"skipped\",\n liveTarget: isLiveNodeRow(existing),\n });\n break;\n }\n case \"error\": {\n record(node, {\n status: \"error\",\n error: `Node already exists: ${node.kind}:${node.id}`,\n });\n break;\n }\n case \"update\": {\n if (!isLiveNodeRow(existing)) {\n // Import never resurrects a tombstone — see processNode.\n record(node, { status: \"skipped\", liveTarget: false });\n break;\n }\n const updateWindow = validateUpdateValidityWindow(\n node,\n existing.valid_from,\n );\n if (!updateWindow.ok) {\n record(node, { status: \"error\", error: updateWindow.error });\n break;\n }\n const updateError = await updateImportedNode(\n writeContext,\n // The pending-aware overlay, not the raw backend: the update's\n // uniqueness pre-check must see a unique value already reserved by\n // an unflushed create EARLIER in this slice, so it degrades to a\n // per-row error exactly as the sequential path does — rather than\n // claiming the key on the real backend and colliding with that\n // create at flush (which would throw and roll back the whole\n // import). Writes still delegate to the real backend.\n validationBackend,\n node,\n {\n existing,\n schema: schemaEntry.registration.type.schema,\n validatedProps: props,\n uniqueConstraints,\n windowFence: updateWindow.value,\n },\n );\n if (updateError === undefined) {\n // The update mutated the real backend's uniqueness rows directly;\n // reconcile the shared prime caches so a later create in this\n // slice sees the post-update reservation state (matching the\n // sequential path). See registerAppliedNodeUpdate.\n registerAppliedNodeUpdate(\n node.kind,\n node.id,\n rowPropsToObject(existing.props),\n props,\n uniqueConstraints,\n );\n }\n record(\n node,\n updateError === undefined ?\n { status: \"updated\" }\n : { status: \"error\", error: updateError },\n );\n break;\n }\n }\n continue;\n }\n\n const uniquenessResult = await catchUniquenessError(() =>\n checkUniquenessConstraints(\n { graphId, registry, backend: validationBackend },\n node.kind,\n node.id,\n props,\n uniqueConstraints,\n ),\n );\n if (!uniquenessResult.ok) {\n record(node, { status: \"error\", error: uniquenessResult.error });\n continue;\n }\n\n registerPendingNode(buildImportInsertParams(graphId, candidate));\n registerPendingUniqueEntries(node.kind, node.id, props, uniqueConstraints);\n accepted.push(candidate);\n }\n\n // Flush the accepted creates: one multi-row insert, then the batched\n // side effects (uniqueness entries, fulltext, embeddings).\n if (accepted.length > 0) {\n const insertParamsList = accepted.map((candidate) =>\n buildImportInsertParams(graphId, candidate),\n );\n if (backend.insertNodesBatch === undefined) {\n for (const params of insertParamsList) {\n await backend.insertNode(params);\n }\n } else {\n await backend.insertNodesBatch(insertParamsList);\n }\n await applyNodeInsertSideEffectsBatch(\n writeContext,\n accepted.map((candidate) => ({\n kind: candidate.node.kind,\n id: candidate.node.id,\n schema: candidate.schemaEntry.registration.type.schema,\n props: candidate.props,\n uniqueConstraints: candidate.schemaEntry.registration.unique ?? [],\n })),\n backend,\n );\n for (const candidate of accepted) {\n record(candidate.node, { status: \"created\" });\n }\n }\n\n // In-slice duplicate ids run per-row AFTER the flush so they observe the\n // first occurrence's committed row, exactly as the sequential path did.\n for (const node of deferred) {\n record(\n node,\n await processNode(\n backend,\n graphId,\n registry,\n node,\n schemas,\n options,\n lock,\n ),\n );\n }\n}\n\nfunction buildImportInsertParams(\n graphId: string,\n candidate: NodeImportCandidate,\n): Parameters<GraphBackend[\"insertNode\"]>[0] {\n const { node, props } = candidate;\n return {\n graphId,\n kind: node.kind,\n id: node.id,\n props,\n ...(node.validFrom !== undefined && { validFrom: node.validFrom }),\n ...(node.validTo !== undefined && { validTo: node.validTo }),\n };\n}\n\ntype ProcessResult =\n | { status: \"created\" }\n | { status: \"updated\" }\n /**\n * `liveTarget` distinguishes \"skipped because a LIVE row already exists\"\n * (a valid edge endpoint) from \"skipped because the row is a tombstone\"\n * (which must NOT be recorded as available — a live edge pointing at a\n * soft-deleted node violates the endpoint-liveness invariant the\n * collection API enforces).\n */\n | { status: \"skipped\"; liveTarget: boolean }\n | { status: \"error\"; error: string };\n\n/**\n * What a guard hands back when its refusal is a PER-ROW fact: either the value\n * the guard produced, or the message recorded against that row while the import\n * keeps going. Shared by the uniqueness guard and the window guard so the two\n * per-row recoveries have one shape.\n */\ntype PerRowGuardResult<T> =\n Readonly<{ ok: true; value: T }> | Readonly<{ ok: false; error: string }>;\n\n/**\n * Runs `fn` and reports a `UniquenessError` as a per-row result instead of\n * letting it abort the whole import — the same recovery both the node\n * uniqueness pre-check and the update path need. Any other error still\n * propagates.\n */\nasync function catchUniquenessError<T>(\n fn: () => Promise<T>,\n): Promise<PerRowGuardResult<T>> {\n try {\n return { ok: true, value: await fn() };\n } catch (error) {\n if (error instanceof UniquenessError) {\n return { ok: false, error: error.message };\n }\n throw error;\n }\n}\n\n/**\n * The stable prefix on every per-row refusal caused by an import UPDATE whose\n * target stopped matching the row this import made its decision from.\n *\n * The node counterpart of {@link EDGE_IDENTITY_CONFLICT_CODE}. Nodes need no\n * identity code — their probe is kind-scoped and they have no endpoints — but\n * they do share the temporal half of the class: the update verdict is computed\n * from the PROBED row's `valid_from`, and a concurrent hard delete + recreate\n * can replace it between the probe and the write.\n */\nconst NODE_UPDATE_TARGET_CHANGED_CODE =\n \"INTERCHANGE_NODE_UPDATE_TARGET_CHANGED\";\n\n/**\n * Updates an existing node under the effective validity lower bound this import\n * checked it carries, and reports a write that landed on nothing as a per-row\n * error.\n *\n * THE SINGLE OWNER of the node update leg, called by both the batched slice and\n * the sequential fallback, so the assertion cannot be threaded through one and\n * forgotten on the other.\n *\n * The `windowFence` is what makes the import's own window check\n * ({@link validateUpdateValidityWindow}) binding rather than advisory. When that\n * check reads the STORED `valid_from` — because the document stated a lower\n * bound to compare against it, or a lone `validTo` to invert against it — it\n * hands back an `expectedValidFrom` predicate, and a read-then-write pair keyed\n * on `(graph_id, kind, id)` alone would otherwise re-resolve that key between the\n * two under PostgreSQL READ COMMITTED: a concurrent hard delete + recreate could\n * leave the write applying a verdict computed for a row that no longer exists —\n * the document's `validFrom` silently ignored, or a `valid_to` persisted below\n * the new row's `valid_from`. The fence puts the bound in the UPDATE's own\n * `WHERE`.\n *\n * A document naming NEITHER bound gets an empty fence, and that is the point: its\n * verdict never looked at the row's lower bound, so a recreate that moved the\n * bound changed nothing this write decided, and refusing the props update would\n * refuse a write the equivalent `store.nodes.*.update` performs. The\n * `deleted_at IS NULL` fence of the live-row update still applies.\n */\nasync function updateImportedNode(\n writeContext: NodeWriteContext,\n backend: GraphBackend | TransactionBackend,\n node: InterchangeNode,\n args: Readonly<{\n existing: LiveNodeRow;\n schema: z.ZodType;\n validatedProps: Record<string, unknown>;\n uniqueConstraints: readonly UniqueConstraint[];\n windowFence: ValidityLowerBoundFence;\n }>,\n): Promise<string | undefined> {\n try {\n const result = await catchUniquenessError(() =>\n applyNodeUpdate(\n writeContext,\n {\n existing: args.existing,\n schema: args.schema,\n validatedProps: args.validatedProps,\n uniqueConstraints: args.uniqueConstraints,\n ...args.windowFence,\n ...(node.validTo !== undefined && { validTo: node.validTo }),\n },\n backend,\n ),\n );\n return result.ok ? undefined : result.error;\n } catch (error) {\n if (\n !(error instanceof DatabaseOperationError) ||\n error.details.reason !== \"no_row_returned\"\n ) {\n throw error;\n }\n return (\n `${NODE_UPDATE_TARGET_CHANGED_CODE}: Node \"${node.kind}:${node.id}\" was ` +\n \"not updated: no live node matching the id and the validity bound this \" +\n \"import checked remained when the write ran, so the row changed or was \" +\n \"removed after it was checked. Re-export the source and retry.\"\n );\n }\n}\n\n/**\n * The stable prefix on every per-row refusal caused by an incoming edge naming\n * an id that a DIFFERENT edge already occupies, so a caller can recognize the\n * condition without parsing prose — the same `CODE: message` idiom the validity\n * window refusals use.\n *\n * ONE code for the whole immutable-identity class — kind AND endpoints — rather\n * than a second code for endpoint mismatches. The condition is a single fact\n * (\"the row under this id is not the edge this document describes\"), the\n * recovery is a single action (\"give it a distinct id, or import it under the\n * identity the stored row carries\"), and a caller that had to match two prefixes\n * to catch one condition would eventually match only one. The message names\n * which components differ; the prefix says what class of thing went wrong.\n *\n * The token still reads `…_KIND_CONFLICT` because it is a PUBLISHED, branchable\n * prefix (documented in `interchange.md`) and renaming it would silently break\n * every caller filtering on it; the constant is named for what it now covers.\n */\nconst EDGE_IDENTITY_CONFLICT_CODE = \"INTERCHANGE_EDGE_KIND_CONFLICT\";\n\n/** The immutable identity of a stored edge, as the probe reports it. */\ntype StoredEdgeIdentity = Readonly<{\n kind: string;\n from_kind: string;\n from_id: string;\n to_kind: string;\n to_id: string;\n}>;\n\n/**\n * Whether an existing row is actually the edge this document is describing.\n *\n * THE SINGLE OWNER of that decision, consulted by both edge-import paths (the\n * batched slice and the per-row fallback) before ANY conflict strategy runs.\n *\n * Edge ids are graph-global while every interchange edge states a kind AND both\n * endpoints, and the existence probe (`getEdge` / `getEdges`) is keyed on\n * `(graph_id, id)` alone — so an incoming edge whose id is already taken by a\n * DIFFERENT edge finds that row and, without this check, was treated as the same\n * edge by all three strategies: `update` wrote the incoming props onto the other\n * row with nothing in `result.errors`, and `skip` counted the document's edge as\n * already present when nothing matching was ever there. Both are silent, and the\n * id is unique per graph, so the incoming edge cannot be created under it\n * either. Reporting is the only honest outcome.\n *\n * Compares the FULL immutable identity — kind and all four endpoint components —\n * not kind alone. Kind is not an identity: an id already held by an edge of the\n * same kind pointing somewhere else is just as much \"not this edge\", and a\n * kind-only comparison reported `updated: 1` while overwriting that row's props\n * and silently retaining its old endpoints (endpoints are immutable, so the\n * document's stated `from`/`to` were simply discarded). Every component is\n * checked because every component is immutable for a given row.\n *\n * Deliberately checked ABOVE the `onConflict` switch rather than inside each\n * arm: the question \"is this the same edge?\" is prior to \"what do we do about\n * the same edge?\", and answering it per-arm is how two of the three arms came\n * to answer it differently.\n *\n * Nodes need no equivalent: their probe is `getNode(graphId, kind, id)`, which\n * is kind-scoped, and a node has no endpoints — so a cross-kind id collision\n * simply reads as absent there.\n */\nfunction edgeIdentityConflict(\n edge: InterchangeEdge,\n existing: StoredEdgeIdentity,\n): string | undefined {\n const differences = [\n ...(existing.kind === edge.kind ?\n []\n : [`kind \"${existing.kind}\" (document states \"${edge.kind}\")`]),\n ...((\n existing.from_kind === edge.from.kind && existing.from_id === edge.from.id\n ) ?\n []\n : [\n `from \"${existing.from_kind}:${existing.from_id}\" (document states ` +\n `\"${edge.from.kind}:${edge.from.id}\")`,\n ]),\n ...(existing.to_kind === edge.to.kind && existing.to_id === edge.to.id ?\n []\n : [\n `to \"${existing.to_kind}:${existing.to_id}\" (document states ` +\n `\"${edge.to.kind}:${edge.to.id}\")`,\n ]),\n ];\n if (differences.length === 0) return undefined;\n return (\n `${EDGE_IDENTITY_CONFLICT_CODE}: Edge \"${edge.id}\" already exists with a ` +\n `different immutable identity — ${differences.join(\"; \")}. Edge ids are ` +\n \"unique per graph, so the incoming edge can neither update nor be created \" +\n \"under that id. Give it a distinct id, or import it under the identity the \" +\n \"stored row already carries.\"\n );\n}\n\n/**\n * Updates an existing edge under the full immutable identity the caller checked\n * it carries, and reports a write that landed on nothing as a per-row error.\n *\n * All five identity components are stated so the predicate lives in the UPDATE's\n * own `WHERE` — the contract on {@link UpdateEdgeParams}, and the only placement\n * a concurrent hard-delete-and-recreate cannot slip past, because a\n * read-then-write pair keyed on `(graph_id, id)` alone re-resolves that id\n * between the probe and the write under PostgreSQL READ COMMITTED. Omitting them\n * made the import's own identity check advisory: correct until raced.\n *\n * The endpoints move together with `kind` rather than being left out because\n * they are \"less likely\" to be raced: the window is the same window, and this\n * import HAS checked all five against a row it read, which is exactly the\n * precondition {@link UpdateEdgeParams} states for asserting them.\n *\n * The effective `valid_from` joins them for a DIFFERENT reason, and the doc on\n * {@link UpdateEdgeParams.expectedValidFrom} spells it out: the five identity\n * components are asserted because they are immutable, the bound because it is\n * NOT. {@link validateUpdateValidityWindow} decides from the row's stored\n * `valid_from` — whether the document may state a lower bound this update will\n * not apply, and whether its `validTo` sits above the bound the row keeps — so a\n * recreate that satisfies all five identity components while carrying a\n * different bound would still land a verdict computed for a row that is gone.\n *\n * Which is why the bound arrives as the guard's own `windowFence` rather than as\n * a value this function re-derives: it is present exactly when the verdict read\n * it. A document naming neither `validFrom` nor `validTo` read nothing, so it is\n * fenced on identity alone and a recreate that only moved the bound no longer\n * refuses its props update.\n *\n * When the predicate does match nothing, the backend reports it as a\n * `no_row_returned` {@link DatabaseOperationError}. By then this import has\n * already checked the identity against a row it read, so reaching here means the\n * target changed underneath us — a per-row fact about one edge, not a reason to\n * abort an import whose earlier rows are already written.\n */\nasync function updateImportedEdge(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n edge: InterchangeEdge,\n props: Readonly<Record<string, unknown>>,\n windowFence: ValidityLowerBoundFence,\n): Promise<string | undefined> {\n try {\n await backend.updateEdge({\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,\n ...windowFence,\n ...(edge.validTo !== undefined && { validTo: edge.validTo }),\n });\n return undefined;\n } catch (error) {\n if (\n !(error instanceof DatabaseOperationError) ||\n error.details.reason !== \"no_row_returned\"\n ) {\n throw error;\n }\n return (\n `${EDGE_IDENTITY_CONFLICT_CODE}: Edge \"${edge.id}\" of kind \"${edge.kind}\" ` +\n `from \"${edge.from.kind}:${edge.from.id}\" to \"${edge.to.kind}:${edge.to.id}\" ` +\n \"was not updated: no live edge matching the identity and the validity \" +\n \"bound this import checked remained when the write ran, so the row \" +\n \"changed or was removed after it was checked. Re-export the source and \" +\n \"retry.\"\n );\n }\n}\n\n/**\n * Runs a window guard and reports its refusal as a per-row error message\n * (recorded in the import result) instead of throwing, so one malformed row does\n * not abort the whole import. On success the guard's own verdict comes back, so\n * a write leg fences on what the guard decided rather than on a second spelling\n * of it. A window refusal that carries a stable issue code —\n * {@link INVERTED_VALIDITY_WINDOW_CODE} or\n * {@link IMMUTABLE_VALIDITY_LOWER_BOUND_CODE} — is prefixed with it, so the\n * refusal is recognizable without parsing prose.\n */\nfunction windowResultOf<T>(assert: () => T): PerRowGuardResult<T> {\n try {\n return { ok: true, value: assert() };\n } catch (error) {\n if (error instanceof ValidationError) {\n const coded = error.details.issues.find(\n (issue) =>\n issue.code === INVERTED_VALIDITY_WINDOW_CODE ||\n issue.code === IMMUTABLE_VALIDITY_LOWER_BOUND_CODE,\n );\n if (coded !== undefined) {\n return { ok: false, error: `${coded.code}: ${error.message}` };\n }\n }\n return {\n ok: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/** {@link windowResultOf} for a guard whose only output is its refusal. */\nfunction windowErrorOf(assert: () => void): string | undefined {\n const result = windowResultOf(assert);\n return result.ok ? undefined : result.error;\n}\n\n/**\n * Validates an entity's validity window against the two contracts `create` /\n * `update` enforce: canonical fixed-width UTC ISO-8601 timestamps, so no import\n * write path can persist a `valid_from` / `valid_to` that later mis-sorts as\n * text against an `asOf` read coordinate, and non-negative window WIDTH, so no\n * import document can persist a row that stopped being true before it started.\n * Import writes straight to the backend rather than through the store\n * operations layer, so it carries its own copy of both — this is the only place\n * the guarantee exists for an imported row.\n *\n * The interchange schema enforces the timestamp contract at the parse boundary,\n * but `importGraph` accepts a pre-typed `GraphData` and does not re-parse it, so\n * this is also the guarantee for callers that bypass the schema.\n *\n * This is the INSERT-shaped half, judged before the existence probe so a\n * malformed document is refused whether or not the row already exists. The\n * update legs additionally call {@link validateUpdateValidityWindow}, which\n * needs the row.\n */\nfunction validateValidityWindow(\n entity: Readonly<{\n kind: string;\n id: string;\n validFrom?: string | null | undefined;\n validTo?: string | undefined;\n }>,\n): string | undefined {\n return windowErrorOf(() => {\n // null is a confirmed open-left window (see InterchangeNodeSchema's\n // validFrom doc), not a value to format-check — treat it like\n // \"not provided\" here, same as the canonical-date validator does.\n validateOptionalCanonicalIsoDate(\n entity.validFrom ?? undefined,\n \"validFrom\",\n );\n validateOptionalCanonicalIsoDate(entity.validTo, \"validTo\");\n // On an INSERT only a stated pair is judged — a lone historical validTo\n // means \"born already ended\", exactly as it does on `create` (see\n // assertWritableValidityWindow). `null` is a confirmed open-left window and\n // is not a lower bound at all.\n assertOrderedValidityWindow(\n `${entity.kind} \"${entity.id}\"`,\n entity.validFrom ?? undefined,\n entity.validTo,\n );\n });\n}\n\n/**\n * The UPDATE-shaped half, for `onConflict: \"update\"` against a row that already\n * exists. All four update legs — batched and sequential, nodes and edges — send\n * the document's `validTo` to an in-place update of a LIVE row while its stored\n * `valid_from` stays put, so the document's end is held to that bound exactly as\n * `store.nodes.*.update` holds a caller's. Without this an import could still\n * write the inverted row the direct update path refuses, and the insert-shaped\n * check above cannot see it: such a document may state no `validFrom` at all.\n *\n * The document's `validFrom` is judged here for the same reason: import never\n * sends it on an update, so a document stating a bound that differs from the\n * row's is stating one the write will not apply. That is refused per row —\n * `onConflict: \"update\"` re-importing a document whose rows were created at a\n * different instant now reports those rows instead of silently updating their\n * props under a bound it ignored. `null` is a confirmed open-left window rather\n * than a stated bound (see `InterchangeNodeSchema`'s `validFrom`) and asserts\n * nothing.\n *\n * Returns the guard's own {@link ValidityLowerBoundFence}, which all four update\n * legs carry verbatim into their write. Import used to assert the probed\n * `valid_from` unconditionally instead — a second spelling of a decision the\n * verdict owns — which refused a props-only document (one naming neither bound)\n * whenever a concurrent recreate moved a bound this verdict never looked at.\n */\nfunction validateUpdateValidityWindow(\n entity: Readonly<{\n kind: string;\n id: string;\n validFrom?: string | null | undefined;\n validTo?: string | undefined;\n }>,\n storedValidFrom: string | undefined,\n): PerRowGuardResult<ValidityLowerBoundFence> {\n const verdict = windowResultOf(() =>\n assertWritableValidityWindow(\n `${entity.kind} \"${entity.id}\"`,\n entity.validFrom ?? undefined,\n {\n effectiveValidFrom: storedValidFrom,\n appliesStatedValidFrom: false,\n // Import updates a LIVE row in place, so the effective bound is always\n // the one the row already stores.\n effectiveBoundIsStored: true,\n },\n entity.validTo,\n ),\n );\n return verdict.ok ?\n { ok: true, value: verdict.value.storedLowerBoundFence }\n : verdict;\n}\n\nasync function processNode(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n registry: KindRegistry,\n node: InterchangeNode,\n schemas: ReadonlyMap<string, NodeSchemaEntry>,\n options: ResolvedImportOptions,\n lock: GraphWriteLock,\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 const { registration } = schemaEntry;\n const uniqueConstraints = registration.unique ?? [];\n const writeContext = { graphId, registry, lock };\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\", liveTarget: isLiveNodeRow(existing) };\n }\n case \"error\": {\n return {\n status: \"error\",\n error: `Node already exists: ${node.kind}:${node.id}`,\n };\n }\n case \"update\": {\n if (!isLiveNodeRow(existing)) {\n // A soft-deleted node is not updatable: import never resurrects a\n // tombstone, and running the live-row update pipeline here would\n // recreate uniqueness/embedding/fulltext rows for a node that\n // stays invisible — a uniqueness reservation held by a tombstoned\n // node would block live creates of the same value.\n return { status: \"skipped\", liveTarget: false };\n }\n const updateWindow = validateUpdateValidityWindow(\n node,\n existing.valid_from,\n );\n if (!updateWindow.ok) {\n return { status: \"error\", error: updateWindow.error };\n }\n // Route through the shared write step so the update maintains\n // uniqueness entries, embeddings, and fulltext — the collection API's\n // integrity, which a raw backend.updateNode would skip. Both per-row\n // recoveries below are safe to catch and commit past because every\n // `UniquenessError` `applyNodeUpdate` can raise comes from its plan or\n // its claim, both of which precede the row write (and the claim\n // compensates itself), and a write that landed on nothing wrote nothing\n // by definition.\n const updateError = await updateImportedNode(\n writeContext,\n backend,\n node,\n {\n existing,\n schema: registration.type.schema,\n validatedProps: propsResult.data,\n uniqueConstraints,\n windowFence: updateWindow.value,\n },\n );\n if (updateError !== undefined) {\n return { status: \"error\", error: updateError };\n }\n return { status: \"updated\" };\n }\n }\n }\n\n // Create new node. Pre-check uniqueness (as the collection create does) so a\n // conflict is a per-row error rather than an orphaned node row, then apply the\n // integrity side effects the raw backend.insertNode would otherwise bypass.\n const uniquenessResult = await catchUniquenessError(() =>\n checkUniquenessConstraints(\n { graphId, registry, backend },\n node.kind,\n node.id,\n propsResult.data,\n uniqueConstraints,\n ),\n );\n if (!uniquenessResult.ok) {\n return { status: \"error\", error: uniquenessResult.error };\n }\n\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 await applyNodeInsertSideEffects(\n writeContext,\n {\n kind: node.kind,\n id: node.id,\n schema: registration.type.schema,\n props: propsResult.data,\n uniqueConstraints,\n },\n backend,\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 registry: KindRegistry,\n edges: readonly InterchangeEdge[],\n edgeSchemas: ReadonlyMap<string, EdgeSchemaEntry>,\n nodeSchemas: ReadonlyMap<string, NodeSchemaEntry>,\n options: ResolvedImportOptions,\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 await processEdgeSlice(\n backend,\n graphId,\n registry,\n batch,\n edgeSchemas,\n nodeSchemas,\n options,\n result,\n errors,\n importedNodeIds,\n );\n }\n}\n\nfunction recordEdgeOutcome(\n edge: InterchangeEdge,\n outcome: ProcessResult,\n result: ImportResult,\n errors: ImportError[],\n): void {\n switch (outcome.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: outcome.error,\n });\n break;\n }\n }\n}\n\ntype EdgeImportCandidate = Readonly<{\n edge: InterchangeEdge;\n props: Record<string, unknown>;\n}>;\n\n/**\n * Processes one batchSize slice of edges with batched round trips: one\n * `getNodes` per endpoint kind for reference liveness, one `getEdges` for\n * existence, and one multi-row insert for the accepted creates. Per-row\n * semantics are unchanged; duplicate ids within a slice defer to the\n * per-row path after the flush.\n */\nasync function processEdgeSlice(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n registry: KindRegistry,\n batch: readonly InterchangeEdge[],\n edgeSchemas: ReadonlyMap<string, EdgeSchemaEntry>,\n nodeSchemas: ReadonlyMap<string, NodeSchemaEntry>,\n options: ResolvedImportOptions,\n result: ImportResult,\n errors: ImportError[],\n importedNodeIds: Set<string>,\n): Promise<void> {\n const record = (edge: InterchangeEdge, outcome: ProcessResult): void => {\n recordEdgeOutcome(edge, outcome, result, errors);\n };\n\n // Pass 1 (synchronous): kind, endpoint-kind, endpoint-assignability,\n // property, and validity validation, plus in-slice duplicate deferral.\n const candidates: EdgeImportCandidate[] = [];\n const deferred: InterchangeEdge[] = [];\n const seenIds = new Set<string>();\n for (const edge of batch) {\n const schemaEntry = edgeSchemas.get(edge.kind);\n if (!schemaEntry) {\n record(edge, {\n status: \"error\",\n error: `Unknown edge kind: ${edge.kind}`,\n });\n continue;\n }\n if (!nodeSchemas.has(edge.from.kind)) {\n record(edge, {\n status: \"error\",\n error: `Unknown from node kind: ${edge.from.kind}`,\n });\n continue;\n }\n if (!nodeSchemas.has(edge.to.kind)) {\n record(edge, {\n status: \"error\",\n error: `Unknown to node kind: ${edge.to.kind}`,\n });\n continue;\n }\n const endpointError = validateEdgeEndpoints(\n edge.kind,\n edge.from.kind,\n edge.to.kind,\n schemaEntry.registration,\n registry,\n );\n if (endpointError !== undefined) {\n record(edge, { status: \"error\", error: endpointError.message });\n continue;\n }\n const propsResult = validateProperties(\n edge.properties,\n schemaEntry.schema,\n options.onUnknownProperty,\n );\n if (!propsResult.success) {\n record(edge, { status: \"error\", error: propsResult.error });\n continue;\n }\n const validityError = validateValidityWindow(edge);\n if (validityError !== undefined) {\n record(edge, { status: \"error\", error: validityError });\n continue;\n }\n if (seenIds.has(edge.id)) {\n deferred.push(edge);\n continue;\n }\n seenIds.add(edge.id);\n candidates.push({ edge, props: propsResult.data });\n }\n\n // Batch the endpoint-liveness reads: one getNodes per endpoint kind for\n // every key the import itself didn't create. Falls back to per-row\n // getNode inside the routing loop when the backend lacks getNodes.\n const liveEndpointKeys = new Set<string>();\n const checkedEndpointKeys = new Set<string>();\n if (options.validateReferences && backend.getNodes !== undefined) {\n const idsByKind = new Map<string, Set<string>>();\n for (const { edge } of candidates) {\n for (const endpoint of [edge.from, edge.to]) {\n const key = makeNodeKey(endpoint.kind, endpoint.id);\n if (importedNodeIds.has(key) || checkedEndpointKeys.has(key)) continue;\n checkedEndpointKeys.add(key);\n const ids = idsByKind.get(endpoint.kind) ?? new Set<string>();\n ids.add(endpoint.id);\n idsByKind.set(endpoint.kind, ids);\n }\n }\n for (const [kind, ids] of idsByKind) {\n const rows = await backend.getNodes(graphId, kind, [...ids]);\n for (const row of rows) {\n if (isLiveNodeRow(row)) {\n liveEndpointKeys.add(makeNodeKey(kind, row.id));\n }\n }\n }\n }\n\n const endpointIsLive = async (endpoint: {\n kind: string;\n id: string;\n }): Promise<boolean> => {\n const key = makeNodeKey(endpoint.kind, endpoint.id);\n if (importedNodeIds.has(key)) return true;\n if (checkedEndpointKeys.has(key)) return liveEndpointKeys.has(key);\n const row = await backend.getNode(graphId, endpoint.kind, endpoint.id);\n return row !== undefined && isLiveNodeRow(row);\n };\n\n // Batch the existence reads. Falls back to per-row getEdge when the\n // backend lacks getEdges.\n const existingById = new Map<\n string,\n Awaited<ReturnType<GraphBackend[\"getEdge\"]>>\n >();\n if (candidates.length > 0 && backend.getEdges !== undefined) {\n const rows = await backend.getEdges(\n graphId,\n candidates.map((candidate) => candidate.edge.id),\n );\n for (const row of rows) {\n existingById.set(row.id, row);\n }\n for (const { edge } of candidates) {\n if (!existingById.has(edge.id)) existingById.set(edge.id, undefined);\n }\n }\n\n const accepted: EdgeImportCandidate[] = [];\n for (const candidate of candidates) {\n const { edge, props } = candidate;\n\n if (options.validateReferences) {\n if (!(await endpointIsLive(edge.from))) {\n record(edge, {\n status: \"error\",\n error: `From node not found: ${edge.from.kind}:${edge.from.id}`,\n });\n continue;\n }\n if (!(await endpointIsLive(edge.to))) {\n record(edge, {\n status: \"error\",\n error: `To node not found: ${edge.to.kind}:${edge.to.id}`,\n });\n continue;\n }\n }\n\n const existing =\n existingById.has(edge.id) ?\n existingById.get(edge.id)\n : await backend.getEdge(graphId, edge.id);\n\n if (existing) {\n // Prior to every strategy: a row occupying this id under a different\n // immutable identity is not this edge, and none of the three arms may\n // treat it as one.\n const identityConflict = edgeIdentityConflict(edge, existing);\n if (identityConflict !== undefined) {\n record(edge, { status: \"error\", error: identityConflict });\n continue;\n }\n switch (options.onConflict) {\n case \"skip\": {\n record(edge, {\n status: \"skipped\",\n liveTarget: existing.deleted_at === undefined,\n });\n break;\n }\n case \"error\": {\n record(edge, {\n status: \"error\",\n error: `Edge already exists: ${edge.id}`,\n });\n break;\n }\n case \"update\": {\n if (existing.deleted_at !== undefined) {\n record(edge, { status: \"skipped\", liveTarget: false });\n break;\n }\n const updateWindow = validateUpdateValidityWindow(\n edge,\n existing.valid_from,\n );\n if (!updateWindow.ok) {\n record(edge, { status: \"error\", error: updateWindow.error });\n break;\n }\n const updateError = await updateImportedEdge(\n backend,\n graphId,\n edge,\n props,\n updateWindow.value,\n );\n if (updateError !== undefined) {\n record(edge, { status: \"error\", error: updateError });\n break;\n }\n record(edge, { status: \"updated\" });\n break;\n }\n }\n continue;\n }\n\n accepted.push(candidate);\n }\n\n if (accepted.length > 0) {\n const insertParamsList = accepted.map(({ edge, props }) => ({\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,\n ...(edge.validFrom !== undefined && { validFrom: edge.validFrom }),\n ...(edge.validTo !== undefined && { validTo: edge.validTo }),\n }));\n if (backend.insertEdgesBatch === undefined) {\n for (const params of insertParamsList) {\n await backend.insertEdge(params);\n }\n } else {\n await backend.insertEdgesBatch(insertParamsList);\n }\n for (const candidate of accepted) {\n record(candidate.edge, { status: \"created\" });\n }\n }\n\n for (const edge of deferred) {\n record(\n edge,\n await processEdge(\n backend,\n graphId,\n registry,\n edge,\n edgeSchemas,\n nodeSchemas,\n options,\n importedNodeIds,\n ),\n );\n }\n}\n\nasync function processEdge(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n registry: KindRegistry,\n edge: InterchangeEdge,\n edgeSchemas: ReadonlyMap<string, EdgeSchemaEntry>,\n nodeSchemas: ReadonlyMap<string, NodeSchemaEntry>,\n options: ResolvedImportOptions,\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 exist\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. Uses the shared,\n // subclass-aware check (registry.isAssignableTo) that the collection API uses,\n // so an edge whose endpoint is a subclass of a declared kind — legal in the\n // store and emitted verbatim by export — imports cleanly instead of being\n // rejected by an exact-kind comparison.\n const endpointError = validateEdgeEndpoints(\n edge.kind,\n edge.from.kind,\n edge.to.kind,\n schemaEntry.registration,\n registry,\n );\n if (endpointError !== undefined) {\n return { status: \"error\", error: endpointError.message };\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. The DB row must be LIVE: getNode\n // returns tombstones, and inserting an edge whose endpoint is\n // soft-deleted would bypass the endpoint-liveness invariant the\n // collection API enforces.\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 === undefined || !isLiveNodeRow(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 === undefined || !isLiveNodeRow(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 // Same prior question as the batched path, answered by the same owner.\n const identityConflict = edgeIdentityConflict(edge, existing);\n if (identityConflict !== undefined) {\n return { status: \"error\", error: identityConflict };\n }\n switch (options.onConflict) {\n case \"skip\": {\n return {\n status: \"skipped\",\n liveTarget: existing.deleted_at === undefined,\n };\n }\n case \"error\": {\n return { status: \"error\", error: `Edge already exists: ${edge.id}` };\n }\n case \"update\": {\n // Same contract as nodes: import never resurrects a tombstone, and\n // the backend's update targets live rows only.\n if (existing.deleted_at !== undefined) {\n return { status: \"skipped\", liveTarget: false };\n }\n const updateWindow = validateUpdateValidityWindow(\n edge,\n existing.valid_from,\n );\n if (!updateWindow.ok) {\n return { status: \"error\", error: updateWindow.error };\n }\n const updateError = await updateImportedEdge(\n backend,\n graphId,\n edge,\n propsResult.data,\n updateWindow.value,\n );\n if (updateError !== undefined) {\n return { status: \"error\", error: updateError };\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 // Data-keyed: `knownKeys` are schema-declared property names.\n const stripped = createDataKeyedBag<unknown>();\n for (const key of knownKeys) {\n if (hasOwnKey(properties, key)) {\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 the known fields, then return the ORIGINAL properties\n // verbatim — unknown keys preserved, known values byte-for-byte.\n // Exported data already carries post-transform values, so\n // re-applying schema transforms here would corrupt every\n // export→import round trip whose transforms are not idempotent.\n // \"allow\" is the fidelity-preserving strategy; \"strip\" (and the\n // create path) remain the normalizing ones.\n const result = schema.safeParse(properties);\n if (!result.success) {\n return {\n success: false,\n error: formatZodError(result.error),\n };\n }\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 encodeTupleKey([kind, id]);\n}\n","/**\n * Graph data export functionality.\n *\n * Exports nodes and edges from a store to the interchange format.\n */\nimport { acquireSerializedStreamLease } from \"../backend/transaction-resource\";\nimport {\n type GraphBackend,\n rowPropsToObject,\n type TransactionBackend,\n} from \"../backend/types\";\nimport {\n getEdgeKinds,\n getNodeKinds,\n type GraphDef,\n} from \"../core/define-graph\";\nimport { ExportStreamCancelledError } from \"../errors\";\nimport { storeBackend, storeRuntime } from \"../store/runtime-port\";\nimport { type Store } from \"../store/store\";\nimport { nowIso } from \"../utils/date\";\nimport { requireDefined } from \"../utils/presence\";\nimport { serializedStreamRefusal } from \"./import\";\nimport { markExportStreamBackend } from \"./stream-source\";\nimport {\n type ExportOptionsInput,\n type ExportStreamOptionsInput,\n ExportStreamOptionsSchema,\n FORMAT_VERSION,\n type GraphData,\n type GraphDataHeader,\n type GraphInterchangeChunk,\n type InterchangeEdge,\n type InterchangeIdentityAssertion,\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 nodes: InterchangeNode[] = [];\n const edges: InterchangeEdge[] = [];\n const identityAssertions: InterchangeIdentityAssertion[] = [];\n let header: GraphDataHeader | undefined;\n for await (const chunk of exportGraphStream(store, options)) {\n switch (chunk.type) {\n case \"header\": {\n header = chunk.header;\n break;\n }\n case \"nodes\": {\n nodes.push(...chunk.nodes);\n break;\n }\n case \"edges\": {\n edges.push(...chunk.edges);\n break;\n }\n case \"identity\": {\n identityAssertions.push(...chunk.assertions);\n break;\n }\n }\n }\n if (header === undefined) {\n throw new Error(\"Graph export stream ended before emitting its header.\");\n }\n const { identity, ...headerWithoutIdentity } = header;\n return {\n ...headerWithoutIdentity,\n nodes,\n edges,\n ...(identity === undefined ?\n {}\n : {\n identity: { ...identity, assertions: identityAssertions },\n }),\n };\n}\n\n/**\n * Exports a graph as bounded node and edge chunks. The stream always yields one\n * header, then every node chunk, then every edge chunk. Consumers that write to\n * a network, file, or fresh working copy can process one chunk at a time rather\n * than materializing a graph-sized {@link GraphData} value.\n *\n * ## One snapshot, WHERE THE BACKEND HAS TRANSACTIONS\n *\n * On a backend reporting `capabilities.transactions`, the whole export —\n * header, every node page, every edge page, every identity page — is read\n * inside ONE `repeatable_read` / `read_only` transaction, so a slow consumer\n * still gets one point in time rather than a mixture of the graph as it was at\n * the first chunk and as it is at the last.\n *\n * A backend WITHOUT transactions (SQLite `transactionMode: \"none\"`, the\n * session-less HTTP Postgres drivers) opens no such transaction: its export\n * paginates statement by statement, and a write committed mid-stream can appear\n * in the pages that follow. There is no way to offer the guarantee on an engine\n * that cannot frame the reads, so it is a declared capability gap rather than\n * something the stream pretends to. Callers needing a coherent export from such\n * a backend must quiesce writes for its duration.\n *\n * ## Stopping a stream you will not finish\n *\n * While a transactional stream is open it holds that snapshot transaction, and\n * on a serialized connection it holds the connection's one EXCLUSIVE stream\n * lease with it. Every cooperative exit settles both, because each runs the\n * generator's `finally`: `break` or `throw` out of a `for await`, and an\n * explicit `iterator.return()`. (A non-transactional stream holds neither, so\n * it has nothing to strand — but it still owes its consumer an answer, which\n * the same cancellation path gives it.)\n *\n * A consumer that pulls `next()` and then simply DROPS the iterator has no\n * cooperative exit — async-generator `finally` blocks do not run on garbage\n * collection — so it must pass {@link ExportOptions.signal} and abort it.\n * Without that, the snapshot transaction stays open for the life of the\n * process and every later interchange stream on that connection is refused on\n * behalf of a stream nobody is reading.\n *\n * ### Why there is no garbage-collection safety net (#429)\n *\n * A `FinalizationRegistry` on the iterable cannot close this: it is not merely\n * unreliable here, it can never fire. The producer is interruptible in exactly\n * one place — it is parked in {@link RendezvousChannel.push} waiting for the\n * consumer, not in the database — so any cleanup state capable of settling an\n * abandoned stream has to reach that channel. A registry holds its held value\n * STRONGLY, and holding anything that reaches the channel's scope keeps the\n * abandoned generator permanently reachable: measured on Node 24, publishing\n * just `channel.abort` is enough to stop the stream being collected, while\n * publishing an unrelated object is not. The net's own bookkeeping would\n * therefore be what kept the entry from ever firing — a safety promise that\n * reads as protection and is not there. The signal is the mechanism, and it is\n * a contract rather than a hint.\n */\nexport function exportGraphStream<G extends GraphDef>(\n store: Store<G>,\n options?: ExportStreamOptionsInput,\n): AsyncIterable<GraphInterchangeChunk> {\n const backend = storeBackend(store);\n return markExportStreamBackend(\n exportGraphStreamFromBackend(store, backend, options),\n backend,\n );\n}\n\nasync function* exportGraphStreamFromBackend<G extends GraphDef>(\n store: Store<G>,\n backend: GraphBackend,\n options?: ExportStreamOptionsInput,\n): AsyncIterable<GraphInterchangeChunk> {\n const resolved = ExportStreamOptionsSchema.parse(options ?? {});\n const signal = resolved.signal;\n const channel = createRendezvousChannel<GraphInterchangeChunk>();\n const abortStream = (): void => {\n channel.abort(\n exportStreamCancelled(\n \"mid-stream\",\n store.graphId,\n signal,\n backend.capabilities.transactions,\n ),\n );\n };\n const unsubscribeFromSignal = (): void => {\n signal?.removeEventListener(\"abort\", abortStream);\n };\n // REGISTER, THEN RE-CHECK — and in that order, because the two halves cover\n // different instants and neither covers both:\n //\n // - The listener covers every abort from now on, including one raised\n // SYNCHRONOUSLY by the driver inside `backend.transaction(...)` below. That\n // is the window this ordering exists for: subscribing after that call\n // returned meant such an abort was delivered to nobody — an `AbortSignal`\n // does not replay `abort` to a listener that arrives late — and the export\n // went on holding its snapshot and its lease with `signal.aborted === true`.\n // - The re-check covers an abort that already happened, which the event will\n // never deliver at all. It is not ceremonial: `parse` above reads the\n // caller's options object, and a getter on it can abort the controller\n // before this line is reached.\n //\n // Nothing between them can yield, so there is no instant at which an abort is\n // neither seen by the re-check nor delivered to the listener.\n signal?.addEventListener(\"abort\", abortStream, { once: true });\n if (signal?.aborted === true) {\n // Nothing has been claimed or opened yet, so this stream is over before it\n // started rather than cancelled in flight — and it must leave no listener\n // on a signal the caller may hold for the rest of the process.\n unsubscribeFromSignal();\n throw exportStreamCancelled(\n \"before-open\",\n store.graphId,\n signal,\n backend.capabilities.transactions,\n );\n }\n const produce = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<void> => {\n await produceExportChunks(store, target, resolved, (chunk) =>\n channel.push(chunk),\n );\n };\n /**\n * Opens the snapshot and wires the producer, or gives back EVERYTHING this\n * stream has taken and rethrows.\n *\n * On a serialized backend the snapshot transaction holds the single\n * connection for the whole stream. Claiming that connection's one stream\n * lease for the duration makes a concurrent import — or a SECOND export,\n * whose snapshot transaction would nest inside this one just as fatally —\n * be refused rather than left to wait for a slot that cannot free up. This is\n * what the stream's consumer identity cannot answer once a caller wraps the\n * iterable. And if another stream already holds that connection, THIS side is\n * the one refused: it is the stream that started second. The claim is\n * deliberately inside the generator body: it must begin when the transaction\n * opens (first pull), not when the iterable is constructed.\n *\n * Two things can stop the stream before it starts, and both give back what\n * they took. The lease refusal takes nothing but the signal subscription made\n * above. `backend.transaction(...)` is a driver call, and a driver can reject\n * SYNCHRONOUSLY — a closed handle, a pool that refuses the checkout — before\n * any promise exists; the release is installed on the promise it returns, so\n * a synchronous throw would otherwise skip it and strand the lease for the\n * life of the process, refusing every later stream on that connection on\n * behalf of one that never ran a statement.\n */\n const beginProducer = (): Promise<void> => {\n try {\n const releaseSnapshotExport =\n backend.capabilities.transactions ?\n claimSnapshotExportLeaseOrRefuse(store.graphId, backend)\n : () => {\n // No snapshot transaction is opened here, so nothing was claimed:\n // a non-transactional export holds nothing against a concurrent\n // stream.\n };\n try {\n const started =\n backend.capabilities.transactions ?\n backend.transaction((target) => produce(target), {\n isolationLevel: \"repeatable_read\",\n accessMode: \"read_only\",\n })\n : produce(backend);\n return started.then(\n () => {\n releaseSnapshotExport();\n channel.finish();\n },\n (error: unknown) => {\n releaseSnapshotExport();\n channel.fail(error);\n },\n );\n } catch (error) {\n releaseSnapshotExport();\n throw error;\n }\n } catch (error) {\n unsubscribeFromSignal();\n throw error;\n }\n };\n const producer = beginProducer();\n\n try {\n for (;;) {\n const delivery = await channel.take();\n if (delivery === undefined) return;\n yield delivery.value;\n delivery.acknowledge();\n }\n } finally {\n // Unsubscribe FIRST: this stream is settling through a cooperative path, so\n // an abort arriving during the teardown below must not publish a terminal\n // error in place of the clean end the consumer is owed — and a signal the\n // caller reuses for its next export must not still reach this one, nor keep\n // this generator's scope alive for as long as the caller holds it.\n unsubscribeFromSignal();\n channel.cancel();\n await producer;\n }\n}\n\n/**\n * How far the stream had got when the abort landed. Every phase ends the same\n * way for the caller — nothing is held, start a new export — so they share one\n * error class and ONE `code`; only the message differs, because a refusal that\n * claimed nothing must not claim to have rolled anything back.\n *\n * - `before-open` — the abort was already visible when the stream was asked for\n * its first chunk. No transaction was opened and no lease claimed, whatever\n * the backend can do.\n * - `mid-stream` — the abort arrived from the moment the stream began opening\n * onward, INCLUDING synchronously inside `backend.transaction(...)`. What was\n * given back depends on what was taken, which is why this phase needs the\n * backend's capability to describe itself honestly.\n */\ntype ExportAbortPhase = \"before-open\" | \"mid-stream\";\n\n/**\n * The single owner of the error an aborted export stream reports, so the\n * pre-flight refusal and the mid-stream abort state the same condition in the\n * same vocabulary — one code, the signal's own reason as `cause`, and a message\n * that is true of the phase AND of the backend it describes.\n *\n * `framed` is `backend.capabilities.transactions`. A non-transactional export\n * opened no snapshot and claimed no lease, so telling its consumer that a\n * snapshot was rolled back and a connection released would describe work that\n * never happened — and would hide the thing that consumer actually needs to\n * know, which is that the chunks it did receive were never one point in time.\n */\nfunction exportStreamCancelled(\n phase: ExportAbortPhase,\n graphId: string,\n signal: AbortSignal | undefined,\n framed: boolean,\n): ExportStreamCancelledError {\n const message =\n phase === \"before-open\" ?\n \"The graph export stream was aborted through its AbortSignal before it opened: no snapshot transaction was started and no database connection claimed.\"\n : framed ?\n \"The graph export stream was aborted through its AbortSignal: its repeatable-read snapshot has been rolled back and the connection it held released.\"\n : \"The graph export stream was aborted through its AbortSignal: its remaining reads were abandoned. This backend does not support transactions, so the export held no snapshot and no connection — and the chunks already delivered were never guaranteed to agree with one another.\";\n const cause: unknown = signal?.reason;\n // The suggestion must be capability-aware for the same reason the message is:\n // the class default claims a snapshot rollback, which is false on the\n // non-transactional arm and for a stream that never opened.\n const suggestion =\n phase === \"before-open\" ?\n \"Start a new export; the aborted one claimed nothing.\"\n : framed ?\n \"Start a new export; the aborted one released its snapshot transaction and the connection it held.\"\n : \"Start a new export; nothing was held, but discard the chunks already delivered unless partial, mutually-inconsistent data is acceptable.\";\n return new ExportStreamCancelledError(\n message,\n { graphId },\n {\n suggestion,\n ...(cause === undefined ? {} : { cause }),\n },\n );\n}\n\n/**\n * Claims the serialized connection for this export's snapshot transaction, or\n * refuses because another long-lived stream — a streaming import, or another\n * snapshot export — is already using it.\n *\n * The check and the claim are one synchronous section inside\n * {@link acquireSerializedStreamLease}, which offers no way to ask without\n * claiming. On a single-threaded event loop that makes \"no other stream held\n * this connection when the snapshot opened\" true for the whole stream: nobody\n * can slip a claim in between, and two streams cannot both conclude the\n * connection was free.\n *\n * Only called when the backend is transactional: a `transactionMode: \"none\"`\n * export holds nothing open, interleaves harmlessly, and must not be refused —\n * nor refuse anyone.\n */\nfunction claimSnapshotExportLeaseOrRefuse(\n graphId: string,\n backend: GraphBackend,\n): () => void {\n const lease = acquireSerializedStreamLease(backend, \"export-snapshot\");\n if (!lease.acquired) {\n throw serializedStreamRefusal({\n graphId,\n requested: \"export-snapshot\",\n heldBy: lease.heldBy,\n });\n }\n return lease.release;\n}\n\nasync function produceExportChunks<G extends GraphDef>(\n store: Store<G>,\n backend: GraphBackend | TransactionBackend,\n options: ExportOptions_ & Readonly<{ batchSize: number }>,\n emit: (chunk: GraphInterchangeChunk) => Promise<void>,\n): Promise<void> {\n const graphId = store.graphId;\n const nodeKinds = options.nodeKinds ?? getNodeKinds(store.graph);\n const edgeKinds = options.edgeKinds ?? getEdgeKinds(store.graph);\n const schemaVersion = await backend.getActiveSchema(graphId);\n\n await emit({\n type: \"header\",\n header: {\n formatVersion: FORMAT_VERSION,\n exportedAt: nowIso(),\n source: {\n type: \"typegraph-export\",\n graphId,\n schemaVersion: schemaVersion?.version ?? 1,\n },\n ...(store.graph.identity === undefined ?\n {}\n : {\n identity: {\n profile: \"typegraph-identity-v1\" as const,\n mode: options.identityMode,\n },\n }),\n },\n });\n\n for (const kind of nodeKinds) {\n for await (const chunk of exportNodeChunks(\n backend,\n graphId,\n kind,\n options,\n )) {\n await emit(chunk);\n }\n }\n for (const kind of edgeKinds) {\n for await (const chunk of exportEdgeChunks(\n backend,\n graphId,\n kind,\n options,\n )) {\n await emit(chunk);\n }\n }\n if (store.graph.identity === undefined) return;\n\n let after: string | undefined;\n for (;;) {\n const page = await storeRuntime(store).readIdentityAssertionPageAtTarget(\n backend,\n options.identityMode,\n {\n ...(options.nodeKinds === undefined ? {} : { nodeKinds }),\n includeDeleted: options.includeDeleted,\n ...(after === undefined ? {} : { after }),\n limit: options.batchSize,\n },\n );\n if (page.assertions.length > 0) {\n await emit({ type: \"identity\", assertions: [...page.assertions] });\n }\n if (page.done) return;\n after = requireDefined(page.nextAfter);\n }\n}\n\ntype ExportOptions_ = Readonly<{\n includeTemporal: boolean;\n includeMeta: boolean;\n includeDeleted: boolean;\n identityMode: \"state\" | \"archival\";\n nodeKinds?: readonly string[] | undefined;\n edgeKinds?: readonly string[] | undefined;\n}>;\n\ntype RendezvousDelivery<T> = Readonly<{\n value: T;\n acknowledge: () => void;\n}>;\n\ntype RendezvousChannel<T> = Readonly<{\n push: (value: T) => Promise<void>;\n take: () => Promise<RendezvousDelivery<T> | undefined>;\n finish: () => void;\n fail: (error: unknown) => void;\n /** The consumer left through a cooperative path; the stream simply ends. */\n cancel: () => void;\n /**\n * Nobody is coming back for this stream. Unwinds the producer — which rolls\n * the snapshot transaction back and releases the connection's lease on its\n * way out — AND makes `error` the channel's terminal state, so a consumer\n * that is waiting on `next()`, or that asks again later, is told why rather\n * than handed a silent end of stream it would read as a complete export.\n */\n abort: (error: Error) => void;\n}>;\n\nfunction createRendezvousChannel<T>(): RendezvousChannel<T> {\n type PendingPush = Readonly<{\n delivery: RendezvousDelivery<T>;\n reject: (error: unknown) => void;\n }>;\n type PendingTake = Readonly<{\n resolve: (delivery: RendezvousDelivery<T> | undefined) => void;\n reject: (error: unknown) => void;\n }>;\n\n const consumerCancelledError = new Error(\"Export stream consumer cancelled.\");\n let pendingPush: PendingPush | undefined;\n let pendingTake: PendingTake | undefined;\n let inFlightReject: ((error: unknown) => void) | undefined;\n let terminal: Readonly<{ error?: Error }> | undefined;\n /**\n * Why the producer is being torn down, once something decided to tear it\n * down — a cooperative consumer exit ({@link cancel}) or a cancellation\n * ({@link abort}).\n *\n * The single owner of \"this stream is unwinding\": it is what every pending\n * and future push rejects with, so the producer always unwinds through one\n * rejection whichever side started it, and it is how {@link fail} recognizes\n * the failure this channel caused itself.\n */\n let producerUnwindError: Error | undefined;\n\n function push(value: T): Promise<void> {\n if (producerUnwindError !== undefined) {\n return Promise.reject(producerUnwindError);\n }\n if (terminal !== undefined || pendingPush !== undefined) {\n return Promise.reject(\n new Error(\"Cannot push to a completed or occupied export channel.\"),\n );\n }\n return new Promise<void>((resolve, reject) => {\n const delivery = {\n value,\n acknowledge: () => {\n inFlightReject = undefined;\n resolve();\n },\n };\n if (pendingTake !== undefined) {\n const take = pendingTake;\n pendingTake = undefined;\n inFlightReject = reject;\n take.resolve(delivery);\n return;\n }\n pendingPush = { delivery, reject };\n });\n }\n\n function take(): Promise<RendezvousDelivery<T> | undefined> {\n if (pendingPush !== undefined) {\n const push = pendingPush;\n pendingPush = undefined;\n inFlightReject = push.reject;\n return Promise.resolve(push.delivery);\n }\n if (terminal !== undefined) {\n return terminal.error === undefined ?\n Promise.resolve(undefined)\n : Promise.reject(terminal.error);\n }\n if (pendingTake !== undefined) {\n return Promise.reject(\n new Error(\"Export channel already has a consumer.\"),\n );\n }\n return new Promise<RendezvousDelivery<T> | undefined>((resolve, reject) => {\n pendingTake = { resolve, reject };\n });\n }\n\n function finish(): void {\n if (producerUnwindError !== undefined) return;\n terminal = {};\n if (pendingTake !== undefined) {\n const take = pendingTake;\n pendingTake = undefined;\n take.resolve(undefined);\n }\n }\n\n function fail(error: unknown): void {\n // The producer failed with the very rejection this channel handed it in\n // order to unwind: that is this channel's own doing, not a new outcome to\n // report. Compared against a DEFINED unwind error only — a producer that\n // rejects with `undefined` is a real failure and must still reach the\n // consumer.\n if (producerUnwindError !== undefined && error === producerUnwindError) {\n return;\n }\n // An abort already published the terminal state the consumer must see; the\n // producer's own unwinding failure must not overwrite it.\n if (terminal !== undefined) return;\n const exportError =\n error instanceof Error ? error : (\n new Error(\"Graph export failed.\", { cause: error })\n );\n terminal = { error: exportError };\n if (pendingTake !== undefined) {\n const take = pendingTake;\n pendingTake = undefined;\n take.reject(exportError);\n }\n }\n\n function cancel(): void {\n if (producerUnwindError !== undefined) return;\n producerUnwindError = consumerCancelledError;\n if (pendingPush !== undefined) {\n const push = pendingPush;\n pendingPush = undefined;\n push.reject(consumerCancelledError);\n }\n if (inFlightReject !== undefined) {\n const reject = inFlightReject;\n inFlightReject = undefined;\n reject(consumerCancelledError);\n }\n if (pendingTake !== undefined) {\n const take = pendingTake;\n pendingTake = undefined;\n take.resolve(undefined);\n }\n }\n\n function abort(error: Error): void {\n // Nothing is held any more, so this abort has nothing to take back and must\n // not restate the outcome. The two arms are NOT alike in how they are\n // reached:\n //\n // - `terminal !== undefined` IS reachable. The producer settles\n // (`finish`/`fail`) and resolves the consumer's pending take, but the\n // generator only resumes to run its `finally` — and unsubscribe — in a\n // later microtask. An abort landing in that window finds the outcome\n // already published and must leave it alone: the export really did end\n // the way `terminal` says, and the consumer has already been handed that\n // answer.\n // - `producerUnwindError !== undefined` is defensive. `cancel()` sets it\n // from the generator's `finally`, which unsubscribes BEFORE calling it,\n // and the listener is `{ once: true }`, so there is no path today that\n // calls `abort` twice or calls it after `cancel`.\n if (terminal !== undefined || producerUnwindError !== undefined) return;\n producerUnwindError = error;\n terminal = { error };\n if (pendingPush !== undefined) {\n const push = pendingPush;\n pendingPush = undefined;\n push.reject(error);\n }\n if (inFlightReject !== undefined) {\n const reject = inFlightReject;\n inFlightReject = undefined;\n reject(error);\n }\n if (pendingTake !== undefined) {\n const take = pendingTake;\n pendingTake = undefined;\n take.reject(error);\n }\n }\n\n return { push, take, finish, fail, cancel, abort };\n}\n\n// ============================================================\n// Node Export\n// ============================================================\n\nasync function* exportNodeChunks(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n kind: string,\n options: ExportOptions_ & Readonly<{ batchSize: number }>,\n): AsyncIterable<GraphInterchangeChunk> {\n let after: string | undefined;\n for (;;) {\n const rows = await backend.findNodesByKind({\n graphId,\n kind,\n excludeDeleted: !options.includeDeleted,\n orderBy: \"id\",\n limit: options.batchSize,\n ...(after === undefined ? {} : { after }),\n });\n if (rows.length === 0) return;\n const nodes = rows.map((row) => {\n const node: InterchangeNode = {\n kind: row.kind,\n id: row.id,\n properties: rowPropsToObject(row.props),\n };\n\n if (options.includeTemporal) {\n // validFrom is always emitted (as `null` when the row has no lower\n // bound) so import can tell \"confirmed open-left\" apart from \"not\n // requested\" and preserve it instead of defaulting to import time —\n // see the schema doc on InterchangeNodeSchema.validFrom. validTo has\n // no such ambiguity (it was never defaulted), so it stays gated.\n // `null` (not `undefined`) is the wire-protocol signal here — JSON has\n // no other way to say \"explicitly cleared\" vs. \"field absent\".\n const validFrom =\n // eslint-disable-next-line unicorn/no-null\n row.valid_from ?? null;\n (node as { validFrom?: string | null }).validFrom = validFrom;\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 yield { type: \"nodes\", nodes };\n if (rows.length < options.batchSize) return;\n after = requireDefined(rows.at(-1)).id;\n }\n}\n\n// ============================================================\n// Edge Export\n// ============================================================\n\nasync function* exportEdgeChunks(\n backend: GraphBackend | TransactionBackend,\n graphId: string,\n kind: string,\n options: ExportOptions_ & Readonly<{ batchSize: number }>,\n): AsyncIterable<GraphInterchangeChunk> {\n let after: string | undefined;\n for (;;) {\n const rows = await backend.findEdgesByKind({\n graphId,\n kind,\n excludeDeleted: !options.includeDeleted,\n orderBy: \"id\",\n limit: options.batchSize,\n ...(after === undefined ? {} : { after }),\n });\n if (rows.length === 0) return;\n const edges = 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: rowPropsToObject(row.props),\n };\n\n if (options.includeTemporal) {\n // See exportNodesOfKind's validFrom comment: always emitted (as\n // `null` when open-left) so import can distinguish \"confirmed no\n // lower bound\" from \"not requested\".\n const validFrom =\n // eslint-disable-next-line unicorn/no-null\n row.valid_from ?? null;\n (edge as { validFrom?: string | null }).validFrom = validFrom;\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 yield { type: \"edges\", edges };\n if (rows.length < options.batchSize) return;\n after = requireDefined(rows.at(-1)).id;\n }\n}\n"]}