@nicia-ai/typegraph 0.50.0 → 0.51.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 (326) hide show
  1. package/README.md +12 -0
  2. package/dist/backend/drizzle/indexes.cjs +10 -8
  3. package/dist/backend/drizzle/indexes.d.cts +1 -1
  4. package/dist/backend/drizzle/indexes.d.ts +1 -1
  5. package/dist/backend/drizzle/indexes.js +6 -4
  6. package/dist/backend/index.cjs +183 -50
  7. package/dist/backend/index.d.cts +90 -4
  8. package/dist/backend/index.d.ts +90 -4
  9. package/dist/backend/index.js +6 -9
  10. package/dist/backend/postgres/index.cjs +30 -28
  11. package/dist/backend/postgres/index.d.cts +7 -7
  12. package/dist/backend/postgres/index.d.ts +7 -7
  13. package/dist/backend/postgres/index.js +16 -14
  14. package/dist/backend/postgres/pglite-store.cjs +6 -62
  15. package/dist/backend/postgres/pglite-store.cjs.map +1 -1
  16. package/dist/backend/postgres/pglite-store.d.cts +8 -8
  17. package/dist/backend/postgres/pglite-store.d.ts +8 -8
  18. package/dist/backend/postgres/pglite-store.js +6 -62
  19. package/dist/backend/postgres/pglite-store.js.map +1 -1
  20. package/dist/backend/postgres/pglite.cjs +18 -16
  21. package/dist/backend/postgres/pglite.d.cts +3 -3
  22. package/dist/backend/postgres/pglite.d.ts +3 -3
  23. package/dist/backend/postgres/pglite.js +17 -15
  24. package/dist/backend/sqlite/index.cjs +27 -25
  25. package/dist/backend/sqlite/index.d.cts +7 -7
  26. package/dist/backend/sqlite/index.d.ts +7 -7
  27. package/dist/backend/sqlite/index.js +14 -12
  28. package/dist/backend/sqlite/libsql.cjs +21 -19
  29. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  30. package/dist/backend/sqlite/libsql.d.cts +3 -3
  31. package/dist/backend/sqlite/libsql.d.ts +3 -3
  32. package/dist/backend/sqlite/libsql.js +16 -14
  33. package/dist/backend/sqlite/libsql.js.map +1 -1
  34. package/dist/backend/sqlite/local-store.cjs +8 -64
  35. package/dist/backend/sqlite/local-store.cjs.map +1 -1
  36. package/dist/backend/sqlite/local-store.d.cts +8 -8
  37. package/dist/backend/sqlite/local-store.d.ts +8 -8
  38. package/dist/backend/sqlite/local-store.js +7 -64
  39. package/dist/backend/sqlite/local-store.js.map +1 -1
  40. package/dist/backend/sqlite/local.cjs +22 -19
  41. package/dist/backend/sqlite/local.d.cts +3 -3
  42. package/dist/backend/sqlite/local.d.ts +3 -3
  43. package/dist/backend/sqlite/local.js +18 -15
  44. package/dist/{chunk-TUVD4DFR.cjs → chunk-2CVDZCXH.cjs} +122 -51
  45. package/dist/chunk-2CVDZCXH.cjs.map +1 -0
  46. package/dist/{chunk-I5C6OTKR.js → chunk-2DWTBNSH.js} +3 -3
  47. package/dist/{chunk-I5C6OTKR.js.map → chunk-2DWTBNSH.js.map} +1 -1
  48. package/dist/{chunk-C76WFIVZ.cjs → chunk-2KCTP3U2.cjs} +180 -127
  49. package/dist/chunk-2KCTP3U2.cjs.map +1 -0
  50. package/dist/{chunk-BYBDM423.cjs → chunk-322TBTOQ.cjs} +48 -48
  51. package/dist/{chunk-BYBDM423.cjs.map → chunk-322TBTOQ.cjs.map} +1 -1
  52. package/dist/chunk-36SX6QXP.cjs +186 -0
  53. package/dist/chunk-36SX6QXP.cjs.map +1 -0
  54. package/dist/{chunk-H3XP6BAV.js → chunk-36VYWVQU.js} +3 -3
  55. package/dist/{chunk-H3XP6BAV.js.map → chunk-36VYWVQU.js.map} +1 -1
  56. package/dist/{chunk-VTJVMP4I.js → chunk-4DKY6RIU.js} +102 -31
  57. package/dist/chunk-4DKY6RIU.js.map +1 -0
  58. package/dist/chunk-4QKOZYMV.js +9 -0
  59. package/dist/chunk-4QKOZYMV.js.map +1 -0
  60. package/dist/{chunk-U3Z7XKAG.js → chunk-57JM6NW3.js} +8 -18
  61. package/dist/chunk-57JM6NW3.js.map +1 -0
  62. package/dist/{chunk-XMY2SXOH.cjs → chunk-5WWEYV4H.cjs} +2208 -579
  63. package/dist/chunk-5WWEYV4H.cjs.map +1 -0
  64. package/dist/{chunk-WQBAQZHR.js → chunk-6NLYIMJO.js} +4 -4
  65. package/dist/{chunk-WQBAQZHR.js.map → chunk-6NLYIMJO.js.map} +1 -1
  66. package/dist/{chunk-G2TLHH6T.cjs → chunk-7B7I7YAW.cjs} +6 -6
  67. package/dist/{chunk-G2TLHH6T.cjs.map → chunk-7B7I7YAW.cjs.map} +1 -1
  68. package/dist/{chunk-EDLKIQRI.js → chunk-7G5IYROL.js} +6 -548
  69. package/dist/chunk-7G5IYROL.js.map +1 -0
  70. package/dist/{chunk-46UGOVRW.js → chunk-7QFRK6PU.js} +3 -7
  71. package/dist/chunk-7QFRK6PU.js.map +1 -0
  72. package/dist/chunk-A4C4NJ5U.cjs +12 -0
  73. package/dist/chunk-A4C4NJ5U.cjs.map +1 -0
  74. package/dist/{chunk-TYGGUWMS.cjs → chunk-B3MN7EJR.cjs} +177 -137
  75. package/dist/chunk-B3MN7EJR.cjs.map +1 -0
  76. package/dist/{chunk-K6VKTBST.cjs → chunk-BZ5MVITP.cjs} +4 -4
  77. package/dist/{chunk-K6VKTBST.cjs.map → chunk-BZ5MVITP.cjs.map} +1 -1
  78. package/dist/{chunk-R7MRFE5P.js → chunk-CAI6SMP6.js} +3 -3
  79. package/dist/{chunk-R7MRFE5P.js.map → chunk-CAI6SMP6.js.map} +1 -1
  80. package/dist/{chunk-ZAQUKCUC.js → chunk-CBOD7TXH.js} +5 -5
  81. package/dist/{chunk-ZAQUKCUC.js.map → chunk-CBOD7TXH.js.map} +1 -1
  82. package/dist/{chunk-LLVOQOWE.cjs → chunk-CRZ56SZU.cjs} +6 -5
  83. package/dist/chunk-CRZ56SZU.cjs.map +1 -0
  84. package/dist/{chunk-ON47CBE4.cjs → chunk-D3GWARN7.cjs} +47 -47
  85. package/dist/{chunk-ON47CBE4.cjs.map → chunk-D3GWARN7.cjs.map} +1 -1
  86. package/dist/{chunk-W5SOCUBL.js → chunk-D3OUDFU7.js} +5 -5
  87. package/dist/{chunk-W5SOCUBL.js.map → chunk-D3OUDFU7.js.map} +1 -1
  88. package/dist/chunk-EKG2UXNX.cjs +23 -0
  89. package/dist/chunk-EKG2UXNX.cjs.map +1 -0
  90. package/dist/{chunk-7PRMDZIA.cjs → chunk-FMMW3KX7.cjs} +21 -55
  91. package/dist/chunk-FMMW3KX7.cjs.map +1 -0
  92. package/dist/chunk-H2VWDQWC.cjs +571 -0
  93. package/dist/chunk-H2VWDQWC.cjs.map +1 -0
  94. package/dist/chunk-H4FY6OZK.js +13 -0
  95. package/dist/chunk-H4FY6OZK.js.map +1 -0
  96. package/dist/{chunk-OJHD3LXJ.cjs → chunk-H5IJSROF.cjs} +2 -8
  97. package/dist/chunk-H5IJSROF.cjs.map +1 -0
  98. package/dist/{chunk-U5EL6JUV.js → chunk-I5IOSA27.js} +101 -103
  99. package/dist/chunk-I5IOSA27.js.map +1 -0
  100. package/dist/{chunk-SHC7BCG5.cjs → chunk-I7YAY2VQ.cjs} +7 -7
  101. package/dist/{chunk-SHC7BCG5.cjs.map → chunk-I7YAY2VQ.cjs.map} +1 -1
  102. package/dist/chunk-IRCWIA3R.js +20 -0
  103. package/dist/chunk-IRCWIA3R.js.map +1 -0
  104. package/dist/chunk-IVQBLXBK.cjs +55 -0
  105. package/dist/chunk-IVQBLXBK.cjs.map +1 -0
  106. package/dist/{chunk-5PP4KRPV.js → chunk-IZD4HTCP.js} +5 -5
  107. package/dist/{chunk-5PP4KRPV.js.map → chunk-IZD4HTCP.js.map} +1 -1
  108. package/dist/{chunk-7CCMCMJO.cjs → chunk-JHRUZ73O.cjs} +75 -66
  109. package/dist/chunk-JHRUZ73O.cjs.map +1 -0
  110. package/dist/{chunk-RDP6ZRSM.cjs → chunk-JQKMEKKW.cjs} +261 -204
  111. package/dist/chunk-JQKMEKKW.cjs.map +1 -0
  112. package/dist/chunk-JVA3KDEA.cjs +691 -0
  113. package/dist/chunk-JVA3KDEA.cjs.map +1 -0
  114. package/dist/{chunk-JG5XIJDY.js → chunk-K67P5DLL.js} +62 -22
  115. package/dist/chunk-K67P5DLL.js.map +1 -0
  116. package/dist/{chunk-CS6JTQQ2.cjs → chunk-KACEYDYV.cjs} +94 -62
  117. package/dist/chunk-KACEYDYV.cjs.map +1 -0
  118. package/dist/{chunk-5OWHU7Z7.cjs → chunk-L6EVYIID.cjs} +248 -210
  119. package/dist/chunk-L6EVYIID.cjs.map +1 -0
  120. package/dist/{chunk-7OWE7WD6.js → chunk-LI4K2KEJ.js} +4 -4
  121. package/dist/{chunk-7OWE7WD6.js.map → chunk-LI4K2KEJ.js.map} +1 -1
  122. package/dist/chunk-LKZDQ2B4.js +1581 -0
  123. package/dist/chunk-LKZDQ2B4.js.map +1 -0
  124. package/dist/{chunk-45YZXI6X.cjs → chunk-LLFPQOBA.cjs} +27 -27
  125. package/dist/{chunk-45YZXI6X.cjs.map → chunk-LLFPQOBA.cjs.map} +1 -1
  126. package/dist/{chunk-ZRJTM7MT.js → chunk-LZMQ3SFK.js} +3 -3
  127. package/dist/{chunk-ZRJTM7MT.js.map → chunk-LZMQ3SFK.js.map} +1 -1
  128. package/dist/{chunk-DI6VC62F.js → chunk-M3VTS3F6.js} +3 -3
  129. package/dist/{chunk-DI6VC62F.js.map → chunk-M3VTS3F6.js.map} +1 -1
  130. package/dist/{chunk-MZ34E2GN.js → chunk-NBOS7BY3.js} +60 -21
  131. package/dist/chunk-NBOS7BY3.js.map +1 -0
  132. package/dist/{chunk-YA36ABIL.js → chunk-NGQDGL5X.js} +14 -48
  133. package/dist/chunk-NGQDGL5X.js.map +1 -0
  134. package/dist/{chunk-ZBFZGLZE.cjs → chunk-NLX5OWK7.cjs} +6 -2
  135. package/dist/chunk-NLX5OWK7.cjs.map +1 -0
  136. package/dist/chunk-NUQ2YFFH.cjs +1637 -0
  137. package/dist/chunk-NUQ2YFFH.cjs.map +1 -0
  138. package/dist/{chunk-TTCOPKUL.cjs → chunk-OGL4X4PH.cjs} +182 -184
  139. package/dist/chunk-OGL4X4PH.cjs.map +1 -0
  140. package/dist/{chunk-HY5BNOUN.cjs → chunk-OTNTGEXR.cjs} +4 -4
  141. package/dist/{chunk-HY5BNOUN.cjs.map → chunk-OTNTGEXR.cjs.map} +1 -1
  142. package/dist/chunk-OTWE63BW.js +53 -0
  143. package/dist/chunk-OTWE63BW.js.map +1 -0
  144. package/dist/chunk-PC5NGH5A.js +549 -0
  145. package/dist/chunk-PC5NGH5A.js.map +1 -0
  146. package/dist/{chunk-IPRP6TDL.cjs → chunk-PS3TUWJM.cjs} +7 -7
  147. package/dist/{chunk-IPRP6TDL.cjs.map → chunk-PS3TUWJM.cjs.map} +1 -1
  148. package/dist/{chunk-V76FGHY3.js → chunk-PVFFH7TL.js} +5 -5
  149. package/dist/{chunk-V76FGHY3.js.map → chunk-PVFFH7TL.js.map} +1 -1
  150. package/dist/chunk-QCD5JKU4.cjs +15 -0
  151. package/dist/chunk-QCD5JKU4.cjs.map +1 -0
  152. package/dist/{chunk-IRPYOHRC.js → chunk-QG5VEOKX.js} +6 -2
  153. package/dist/chunk-QG5VEOKX.js.map +1 -0
  154. package/dist/{chunk-MM3JHVKZ.cjs → chunk-QLLZM5I3.cjs} +4 -4
  155. package/dist/{chunk-MM3JHVKZ.cjs.map → chunk-QLLZM5I3.cjs.map} +1 -1
  156. package/dist/{chunk-MX7EKQPM.js → chunk-RCBG6YMT.js} +345 -97
  157. package/dist/chunk-RCBG6YMT.js.map +1 -0
  158. package/dist/{chunk-2CYI5HRH.js → chunk-RI7RJH4G.js} +49 -17
  159. package/dist/chunk-RI7RJH4G.js.map +1 -0
  160. package/dist/{chunk-5LKOVCPP.js → chunk-RVUL2HXY.js} +6 -5
  161. package/dist/chunk-RVUL2HXY.js.map +1 -0
  162. package/dist/{chunk-WK23PGTP.cjs → chunk-S5GU4LUN.cjs} +11 -11
  163. package/dist/{chunk-WK23PGTP.cjs.map → chunk-S5GU4LUN.cjs.map} +1 -1
  164. package/dist/{chunk-S33YQEL7.js → chunk-SDPWO2Z5.js} +6 -6
  165. package/dist/{chunk-S33YQEL7.js.map → chunk-SDPWO2Z5.js.map} +1 -1
  166. package/dist/{chunk-6S3PTHL4.js → chunk-SLGGT2XD.js} +3 -3
  167. package/dist/{chunk-6S3PTHL4.js.map → chunk-SLGGT2XD.js.map} +1 -1
  168. package/dist/{chunk-HSEZ7X6Y.cjs → chunk-TIJUA4I6.cjs} +45 -45
  169. package/dist/{chunk-HSEZ7X6Y.cjs.map → chunk-TIJUA4I6.cjs.map} +1 -1
  170. package/dist/{chunk-CSNOYIB4.cjs → chunk-TM54OBHX.cjs} +13 -13
  171. package/dist/{chunk-CSNOYIB4.cjs.map → chunk-TM54OBHX.cjs.map} +1 -1
  172. package/dist/{chunk-2GIV5X4P.js → chunk-TYEYRCXL.js} +86 -33
  173. package/dist/chunk-TYEYRCXL.js.map +1 -0
  174. package/dist/{chunk-MJPZNEJZ.js → chunk-UKOVGCRN.js} +2095 -496
  175. package/dist/chunk-UKOVGCRN.js.map +1 -0
  176. package/dist/chunk-UYKDYE5D.cjs +12 -0
  177. package/dist/{chunk-KWNWG4RC.cjs.map → chunk-UYKDYE5D.cjs.map} +1 -1
  178. package/dist/{chunk-FX5ZW6PN.js → chunk-VAAC7L57.js} +95 -40
  179. package/dist/chunk-VAAC7L57.js.map +1 -0
  180. package/dist/{chunk-ISKCIQF2.cjs → chunk-VKHXYVN7.cjs} +14 -25
  181. package/dist/chunk-VKHXYVN7.cjs.map +1 -0
  182. package/dist/chunk-VUQZNUHU.js +171 -0
  183. package/dist/chunk-VUQZNUHU.js.map +1 -0
  184. package/dist/{chunk-K2XYLVVB.cjs → chunk-WDM5WQK4.cjs} +175 -136
  185. package/dist/chunk-WDM5WQK4.cjs.map +1 -0
  186. package/dist/{chunk-GVYVGGPJ.js → chunk-WFSYYU4W.js} +66 -28
  187. package/dist/chunk-WFSYYU4W.js.map +1 -0
  188. package/dist/{chunk-WCLMKNQE.cjs → chunk-WRBV2FNH.cjs} +1356 -1108
  189. package/dist/chunk-WRBV2FNH.cjs.map +1 -0
  190. package/dist/chunk-XORONCV3.js +202 -0
  191. package/dist/chunk-XORONCV3.js.map +1 -0
  192. package/dist/{chunk-2Q45FAIE.js → chunk-YT2IVFAI.js} +26 -17
  193. package/dist/chunk-YT2IVFAI.js.map +1 -0
  194. package/dist/chunk-ZGVTNKTX.cjs +217 -0
  195. package/dist/chunk-ZGVTNKTX.cjs.map +1 -0
  196. package/dist/core/index.cjs +20 -20
  197. package/dist/core/index.d.cts +4 -4
  198. package/dist/core/index.d.ts +4 -4
  199. package/dist/core/index.js +4 -4
  200. package/dist/{ddl-B49O7dB_.d.ts → ddl-BvcbgzHo.d.ts} +3 -3
  201. package/dist/{ddl-DcZG660s.d.cts → ddl-Ufebz5q5.d.cts} +3 -3
  202. package/dist/graph-extension/index.d.cts +2 -4
  203. package/dist/graph-extension/index.d.ts +2 -4
  204. package/dist/graph-merge/index.cjs +140 -125
  205. package/dist/graph-merge/index.cjs.map +1 -1
  206. package/dist/graph-merge/index.d.cts +8 -9
  207. package/dist/graph-merge/index.d.ts +8 -9
  208. package/dist/graph-merge/index.js +42 -27
  209. package/dist/graph-merge/index.js.map +1 -1
  210. package/dist/index.cjs +144 -143
  211. package/dist/index.cjs.map +1 -1
  212. package/dist/index.d.cts +11 -12
  213. package/dist/index.d.ts +11 -12
  214. package/dist/index.js +30 -29
  215. package/dist/index.js.map +1 -1
  216. package/dist/indexes/index.cjs +14 -12
  217. package/dist/indexes/index.d.cts +4 -4
  218. package/dist/indexes/index.d.ts +4 -4
  219. package/dist/indexes/index.js +7 -5
  220. package/dist/{ingestion-import-target-CI8OWIkM.d.ts → ingestion-import-target-CAs1OX-l.d.cts} +1 -1
  221. package/dist/{ingestion-import-target-DCpfM1PX.d.cts → ingestion-import-target-DCQSPfNx.d.ts} +1 -1
  222. package/dist/interchange/index.cjs +41 -39
  223. package/dist/interchange/index.cjs.map +1 -1
  224. package/dist/interchange/index.d.cts +8 -8
  225. package/dist/interchange/index.d.ts +8 -8
  226. package/dist/interchange/index.js +16 -14
  227. package/dist/interchange/index.js.map +1 -1
  228. package/dist/local-store-impl-6DDTFM32.cjs +77 -0
  229. package/dist/local-store-impl-6DDTFM32.cjs.map +1 -0
  230. package/dist/local-store-impl-OXTOVU2J.js +75 -0
  231. package/dist/local-store-impl-OXTOVU2J.js.map +1 -0
  232. package/dist/{manager-Cfg1ENj1.d.ts → manager-B68OrPR2.d.ts} +1 -2
  233. package/dist/{manager-D348fa6W.d.cts → manager-D_t7oK69.d.cts} +1 -2
  234. package/dist/pglite-store-impl-6EMZGL7K.js +73 -0
  235. package/dist/pglite-store-impl-6EMZGL7K.js.map +1 -0
  236. package/dist/pglite-store-impl-GJG3Y7RP.cjs +75 -0
  237. package/dist/pglite-store-impl-GJG3Y7RP.cjs.map +1 -0
  238. package/dist/{postgres-UStOycLI.d.ts → postgres-BPLSVyHM.d.ts} +1 -1
  239. package/dist/{postgres-CH1kkM5J.d.cts → postgres-CqvtFC2y.d.cts} +1 -1
  240. package/dist/profiler/index.d.cts +9 -9
  241. package/dist/profiler/index.d.ts +9 -9
  242. package/dist/provenance/index.cjs +33 -20
  243. package/dist/provenance/index.cjs.map +1 -1
  244. package/dist/provenance/index.d.cts +7 -7
  245. package/dist/provenance/index.d.ts +7 -7
  246. package/dist/provenance/index.js +24 -11
  247. package/dist/provenance/index.js.map +1 -1
  248. package/dist/{repair-validity-windows-aWX7VNvv.d.cts → repair-validity-windows-DEzCKAdy.d.cts} +7 -3
  249. package/dist/{repair-validity-windows-BtOEe2pS.d.ts → repair-validity-windows-GMdaS2AH.d.ts} +7 -3
  250. package/dist/resolve-D_H8MHtq.d.ts +1805 -0
  251. package/dist/resolve-WEW8gWws.d.cts +1805 -0
  252. package/dist/schema/index.cjs +42 -40
  253. package/dist/schema/index.d.cts +4 -6
  254. package/dist/schema/index.d.ts +4 -6
  255. package/dist/schema/index.js +15 -13
  256. package/dist/{searchable-z4BiFfHI.d.ts → searchable-C_UREI9K.d.ts} +1 -1
  257. package/dist/{searchable-C8-RrL3l.d.cts → searchable-ClgET_i7.d.cts} +1 -1
  258. package/dist/{sqlite-axLw5Lo5.d.ts → sqlite-D1mXO9Kp.d.cts} +2 -1
  259. package/dist/{sqlite-Cyx9j9o6.d.cts → sqlite-MZA3oZNB.d.ts} +2 -1
  260. package/dist/{store-CTfQ9taw.d.ts → store-CuFX7fCx.d.cts} +38 -41
  261. package/dist/{store-DR9J7JVB.d.cts → store-D-ZjXQpW.d.ts} +38 -41
  262. package/dist/{temporal-CBOrERz5.d.ts → temporal-CpyEiRY8.d.cts} +1 -1
  263. package/dist/{temporal-B4Ky4wzh.d.cts → temporal-y0Aep9Su.d.ts} +1 -1
  264. package/dist/{types-CWg4dTjj.d.ts → types-6yf0Vv-_.d.cts} +1672 -1
  265. package/dist/{types-CWg4dTjj.d.cts → types-6yf0Vv-_.d.ts} +1672 -1
  266. package/dist/{types-BScHXVM7.d.ts → types-DzJ4dlzk.d.cts} +1 -1
  267. package/dist/{types-BE921wRl.d.cts → types-_vVSB9k-.d.ts} +1 -1
  268. package/dist/{where-BWXUPV3C.d.ts → where-DuG2LCLe.d.ts} +1 -1
  269. package/dist/{where-CNtx1aLc.d.cts → where-Mhf_yyKX.d.cts} +1 -1
  270. package/package.json +5 -1
  271. package/dist/chunk-2CYI5HRH.js.map +0 -1
  272. package/dist/chunk-2GIV5X4P.js.map +0 -1
  273. package/dist/chunk-2Q45FAIE.js.map +0 -1
  274. package/dist/chunk-46UGOVRW.js.map +0 -1
  275. package/dist/chunk-5LKOVCPP.js.map +0 -1
  276. package/dist/chunk-5OWHU7Z7.cjs.map +0 -1
  277. package/dist/chunk-6LEOAIIB.js +0 -1160
  278. package/dist/chunk-6LEOAIIB.js.map +0 -1
  279. package/dist/chunk-7CCMCMJO.cjs.map +0 -1
  280. package/dist/chunk-7PRMDZIA.cjs.map +0 -1
  281. package/dist/chunk-C76WFIVZ.cjs.map +0 -1
  282. package/dist/chunk-CS6JTQQ2.cjs.map +0 -1
  283. package/dist/chunk-EDLKIQRI.js.map +0 -1
  284. package/dist/chunk-EH3JZJUM.cjs +0 -567
  285. package/dist/chunk-EH3JZJUM.cjs.map +0 -1
  286. package/dist/chunk-FX5ZW6PN.js.map +0 -1
  287. package/dist/chunk-GHZPZNFC.cjs +0 -132
  288. package/dist/chunk-GHZPZNFC.cjs.map +0 -1
  289. package/dist/chunk-GVYVGGPJ.js.map +0 -1
  290. package/dist/chunk-IHK5KA2Q.cjs +0 -262
  291. package/dist/chunk-IHK5KA2Q.cjs.map +0 -1
  292. package/dist/chunk-IRPYOHRC.js.map +0 -1
  293. package/dist/chunk-ISKCIQF2.cjs.map +0 -1
  294. package/dist/chunk-JG5XIJDY.js.map +0 -1
  295. package/dist/chunk-K2XYLVVB.cjs.map +0 -1
  296. package/dist/chunk-KWNWG4RC.cjs +0 -12
  297. package/dist/chunk-LLVOQOWE.cjs.map +0 -1
  298. package/dist/chunk-MJPZNEJZ.js.map +0 -1
  299. package/dist/chunk-MX7EKQPM.js.map +0 -1
  300. package/dist/chunk-MZ34E2GN.js.map +0 -1
  301. package/dist/chunk-OJHD3LXJ.cjs.map +0 -1
  302. package/dist/chunk-PALYTHGM.js +0 -114
  303. package/dist/chunk-PALYTHGM.js.map +0 -1
  304. package/dist/chunk-RDP6ZRSM.cjs.map +0 -1
  305. package/dist/chunk-S3SDEQMC.js +0 -532
  306. package/dist/chunk-S3SDEQMC.js.map +0 -1
  307. package/dist/chunk-TEC24ZDA.cjs +0 -1254
  308. package/dist/chunk-TEC24ZDA.cjs.map +0 -1
  309. package/dist/chunk-TP4NJTI3.cjs +0 -1192
  310. package/dist/chunk-TP4NJTI3.cjs.map +0 -1
  311. package/dist/chunk-TTCOPKUL.cjs.map +0 -1
  312. package/dist/chunk-TUVD4DFR.cjs.map +0 -1
  313. package/dist/chunk-TYGGUWMS.cjs.map +0 -1
  314. package/dist/chunk-U3Z7XKAG.js.map +0 -1
  315. package/dist/chunk-U5EL6JUV.js.map +0 -1
  316. package/dist/chunk-VTJVMP4I.js.map +0 -1
  317. package/dist/chunk-WCLMKNQE.cjs.map +0 -1
  318. package/dist/chunk-XMY2SXOH.cjs.map +0 -1
  319. package/dist/chunk-Y55DLLEG.js +0 -247
  320. package/dist/chunk-Y55DLLEG.js.map +0 -1
  321. package/dist/chunk-YA36ABIL.js.map +0 -1
  322. package/dist/chunk-ZBFZGLZE.cjs.map +0 -1
  323. package/dist/index-B0PrmE3K.d.cts +0 -1146
  324. package/dist/index-CwcXsL5R.d.ts +0 -1146
  325. package/dist/materialize-indexes-C9GG3O3C.d.ts +0 -266
  326. package/dist/materialize-indexes-CrSiW_lT.d.cts +0 -266
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/identity/rebuild.ts","../src/identity/types.ts","../src/backend/migrate-vectors.ts"],"names":["embedding"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,eAAsB,uBAEpB,KAAA,EAAgC;AAChC,EAAA,MAAM,YAAA,CAAa,KAAK,CAAA,CAAE,sBAAA,EAAuB;AACnD;;;AC+CO,SAAS,sBAAsB,KAAA,EAAoC;AACxE,EAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACtB,IAAA,MAAM,IAAI,eAAA;AAAA,MACR,mDAAA;AAAA,MACA;AAAA,QACE,MAAA,EAAQ;AAAA,UACN;AAAA,YACE,IAAA,EAAM,uBAAA;AAAA,YACN,OAAA,EAAS;AAAA;AACX;AACF,OACF;AAAA,MACA;AAAA,QACE,UAAA,EAAY;AAAA;AACd,KACF;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;;;ACjBA,IAAM,kBAAA,GAAqB,GAAA;AAY3B,IAAM,mBAAA,GAAuC,wBAAA;AAC7C,IAAM,uBAAA,GACJ,4BAAA;AA8HF,eAAsB,wBACpB,OAAA,EACwC;AACxC,EAAA,MAAM;AAAA,IACJ,OAAA;A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,SAAS,CAAA,CAAA,EAAI,GAAA,CAAI,UAAU,CAAA,QAAA,EAC3C,GAAA,CAAI,QAAQ,CAAA,OAAA,EAAU,GAAA,CAAI,OAAO,CAAA,wCAAA;AAAA,KAE/C;AAAA,EACF;AACA,EAAA,KAAA,MAAW,CAAC,KAAA,EAAO,KAAK,CAAA,IAAK,MAAA,CAAO,SAAQ,EAAG;AAC7C,IAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,CAAC,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,EAAG;AACxD,MAAA,MAAM,IAAI,SAAA;AAAA,QACR,wBAAwB,GAAA,CAAI,SAAS,CAAA,CAAA,EAAI,GAAA,CAAI,UAAU,CAAA,QAAA,EAC3C,GAAA,CAAI,QAAQ,CAAA,OAAA,EAAU,IAAI,OAAO,CAAA,kCAAA,EACzB,KAAK,CAAA,EAAA,EAAK,MAAA,CAAO,KAAK,CAAC,CAAA,CAAA;AAAA,OAC7C;AAAA,IACF;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["import { type GraphDef, type GraphIdentityConfig } from \"../core/define-graph\";\nimport { storeRuntime } from \"../store/runtime-port\";\nimport { type Store } from \"../store/store\";\n\n/**\n * Rebuilds the derived current identity closure for an identity-enabled store.\n * This is a repair operation: it does not change graph revision or assertions.\n */\nexport async function rebuildIdentityClosure<\n G extends GraphDef & Readonly<{ identity: GraphIdentityConfig }>,\n>(store: Store<G>): Promise<void> {\n await storeRuntime(store).rebuildIdentityClosure();\n}\n","import {\n type AllNodeTypes,\n type GraphDef,\n type NodeKinds,\n} from \"../core/define-graph\";\nimport { ValidationError } from \"../errors\";\nimport {\n type DynamicNode,\n type DynamicNodeReference,\n type GraphNodeReference,\n type Node,\n type NodeRef,\n} from \"../store/types\";\n\n/**\n * The accepted *input* form for every identity facade method: a whole node or\n * a `{ kind, id }` pair for any compile-time graph kind, plus a proof-bearing\n * node or reference produced through the runtime collection lane. Runtime\n * values stay nominal so accepting them does not make an arbitrary\n * `{ kind: string, id: string }` object type-safe.\n *\n * Identity results use {@link IdentityNodeReference}, which honestly includes\n * runtime kinds because an evolved kind can belong to a class reached from a\n * compile-time node.\n */\nexport type IdentityNodeRefInput<G extends GraphDef> =\n NodeRef<AllNodeTypes<G>> | DynamicNode | DynamicNodeReference;\n\n/**\n * A node reference returned by Operational Identity.\n *\n * Identity classes can contain runtime-evolved kinds even when a read starts\n * from a compile-time node, so results honestly include both lanes.\n */\nexport type IdentityNodeReference<G extends GraphDef> =\n GraphNodeReference<G> | DynamicNodeReference;\n\n/** A hydrated compile-time or runtime identity member. */\nexport type IdentityNode<G extends GraphDef> =\n | {\n [K in NodeKinds<G>]: Node<G[\"nodes\"][K][\"type\"]>;\n }[NodeKinds<G>]\n | DynamicNode;\n\ndeclare const __identityAssertionId: unique symbol;\n\nexport type IdentityAssertionId = string &\n Readonly<{ [__identityAssertionId]: true }>;\n\n/**\n * Brands a non-empty string as an {@link IdentityAssertionId}.\n *\n * Use this when a persisted identity assertion id has round-tripped through\n * untyped storage or an external boundary and must be passed back to a\n * retraction surface such as `retractAssertion` or `bulkRetractAssertions`.\n * Mirrors the `asNodeId` / `asEdgeId` precedent.\n *\n * @throws {ValidationError} when `value` is empty.\n */\nexport function asIdentityAssertionId(value: string): IdentityAssertionId {\n if (value.length === 0) {\n throw new ValidationError(\n \"asIdentityAssertionId must be a non-empty string.\",\n {\n issues: [\n {\n path: \"asIdentityAssertionId\",\n message: \"Expected a non-empty string.\",\n },\n ],\n },\n {\n suggestion: \"Use a persisted identity assertion id value.\",\n },\n );\n }\n return value as IdentityAssertionId;\n}\n\n/**\n * What one assertion claims about a pair of nodes: `\"same\"` merges them into\n * one equivalence set, `\"different\"` records a disjointness that a later\n * `\"same\"` claim must not contradict.\n */\nexport type IdentityRelation = \"same\" | \"different\";\n\n/**\n * One persisted identity claim about an ordered pair of nodes. Returned by the\n * assertion writers and by `identity.assertionsOf(...)`; `validTo` is set when\n * the assertion has been retracted, so a historical read can still see it.\n */\nexport type IdentityAssertion<G extends GraphDef> = Readonly<{\n id: IdentityAssertionId;\n relation: IdentityRelation;\n a: IdentityNodeReference<G>;\n b: IdentityNodeReference<G>;\n validFrom: string;\n validTo?: string;\n}>;\n\n/** Result of an idempotent assertion write. */\nexport type IdentityAssertionResult<G extends GraphDef> = Readonly<{\n assertion: IdentityAssertion<G>;\n action: \"created\" | \"existing\";\n}>;\n\n/** The half-open effective-time window of an identity assertion. */\nexport type IdentityValidityWindow = Readonly<{\n validFrom?: string;\n validTo?: string;\n}>;\n\n/** One ordered node pair handed to `bulkAssertSame` / `bulkAssertDifferent`. */\nexport type IdentityPair<G extends GraphDef> = Readonly<{\n a: IdentityNodeRefInput<G>;\n b: IdentityNodeRefInput<G>;\n}> &\n IdentityValidityWindow;\n\n/**\n * The read half of the identity surface: equivalence-set membership,\n * representative selection, and the assertions behind them.\n *\n * Obtained from a read-only lens — `store.asOf(...).identity`,\n * `store.snapshot().identity` — where it answers at that view's coordinate.\n * The full read+write surface is {@link IdentityFacade}.\n */\nexport type IdentityReadFacade<G extends GraphDef> = Readonly<{\n representativeOf: (\n ref: IdentityNodeRefInput<G>,\n ) => Promise<IdentityNodeReference<G> | undefined>;\n membersOf: (\n ref: IdentityNodeRefInput<G>,\n ) => Promise<readonly IdentityNodeReference<G>[]>;\n nodesOf: (\n ref: IdentityNodeRefInput<G>,\n ) => Promise<readonly IdentityNode<G>[]>;\n areSame: (\n a: IdentityNodeRefInput<G>,\n b: IdentityNodeRefInput<G>,\n ) => Promise<boolean>;\n areDifferent: (\n a: IdentityNodeRefInput<G>,\n b: IdentityNodeRefInput<G>,\n ) => Promise<boolean>;\n assertionsOf: (\n ref: IdentityNodeRefInput<G>,\n ) => Promise<readonly IdentityAssertion<G>[]>;\n}>;\n\n/**\n * The full TypeGraph Identity Profile surface: {@link IdentityReadFacade} plus\n * the assertion writers and retractions.\n *\n * Obtained from `store.identity` or `tx.identity`, and present only on graphs\n * that declared `identity: { ... }` in `defineGraph`. Every writer is\n * idempotent — re-asserting an existing claim returns it with\n * `action: \"existing\"` rather than duplicating it.\n */\nexport type IdentityFacade<G extends GraphDef> = IdentityReadFacade<G> &\n Readonly<{\n assertSame: (\n a: IdentityNodeRefInput<G>,\n b: IdentityNodeRefInput<G>,\n window?: IdentityValidityWindow,\n ) => Promise<IdentityAssertionResult<G>>;\n assertDifferent: (\n a: IdentityNodeRefInput<G>,\n b: IdentityNodeRefInput<G>,\n window?: IdentityValidityWindow,\n ) => Promise<IdentityAssertionResult<G>>;\n bulkAssertSame: (\n pairs: readonly IdentityPair<G>[],\n ) => Promise<readonly IdentityAssertionResult<G>[]>;\n bulkAssertDifferent: (\n pairs: readonly IdentityPair<G>[],\n ) => Promise<readonly IdentityAssertionResult<G>[]>;\n retractAssertion: (\n id: IdentityAssertionId,\n ) => Promise<IdentityAssertion<G> | undefined>;\n retractSameAssertion: (\n a: IdentityNodeRefInput<G>,\n b: IdentityNodeRefInput<G>,\n ) => Promise<IdentityAssertion<G> | undefined>;\n retractDifferentAssertion: (\n a: IdentityNodeRefInput<G>,\n b: IdentityNodeRefInput<G>,\n ) => Promise<IdentityAssertion<G> | undefined>;\n bulkRetractAssertions: (\n ids: readonly IdentityAssertionId[],\n ) => Promise<readonly IdentityAssertion<G>[]>;\n }>;\n\n/**\n * The assertion-only write surface of the TypeGraph Identity Profile.\n *\n * This deliberately excludes reads and retractions so constrained staging\n * handles can accept incoming identity claims without exposing the broader\n * operational identity surface.\n */\nexport type IdentityAssertionWriteFacade<G extends GraphDef> = Pick<\n IdentityFacade<G>,\n \"assertSame\" | \"assertDifferent\" | \"bulkAssertSame\" | \"bulkAssertDifferent\"\n>;\n\n/**\n * Per-transaction identity write counts carried by a transaction receipt.\n * `total` is the sum of the three preceding counters.\n */\nexport type IdentityWriteSummary = Readonly<{\n sameAssertions: number;\n differentAssertions: number;\n retractions: number;\n total: number;\n}>;\n","/**\n * One-time offline migration: legacy shared embeddings table → per-field\n * strategy storage.\n *\n * ## What this is for\n *\n * The cross-backend vector cutover (#157) dropped the single shared\n * `typegraph_node_embeddings` table. Each\n * `VectorStrategy` now OWNS one typed, fixed-dimension structure per\n * `(nodeKind, fieldPath)` — the only layout that can be ANN-indexed on\n * libSQL and sqlite-vec, not just pgvector.\n *\n * Deployments that wrote embeddings under the old shared table before\n * upgrading still hold those rows. This utility drains them into the new\n * per-field storage **once**, during the upgrade, so existing embedded\n * data survives the cutover without re-embedding from source.\n *\n * It is an explicitly-run, offline step — not wired into `materializeIndexes`\n * or any boot path. Run it once after deploying the new version and before\n * (or alongside) the first `materializeIndexes()`, then drop the legacy\n * table at your leisure.\n *\n * ## How it works\n *\n * - Skips cleanly (returns a zero summary) when the legacy table is absent —\n * a fresh install, or a re-run after the table was dropped.\n * - Reads rows in keyset-paginated batches (never the whole table at once),\n * decoding the engine-native embedding column to a numeric array at the SQL\n * level: sqlite-vec stored a `vec_f32` blob (`vec_to_json` decodes it);\n * pgvector stored a native `vector` (`::text` yields a `[…]` literal).\n * - Re-inserts each row through `backend.upsertEmbedding`, which routes the\n * active strategy's `buildUpsert` and idempotently provisions the per-field\n * storage (the same `(nodeKind, fieldPath)` slot a fresh store write uses).\n * The migration stays graph-agnostic and execution-correct on both the\n * sync (better-sqlite3) and async (libsql / Postgres) backends — it does\n * not re-implement the backend's statement-execution glue.\n *\n * Idempotent and resumable: a partial run followed by a full run converges\n * to the same per-field tables, because every write is an upsert keyed by\n * `(graph_id, node_id)` in the strategy's owned storage.\n */\nimport {\n DEFAULT_EMBEDDING_INDEX_TYPE,\n DEFAULT_EMBEDDING_METRIC,\n type EmbeddingIndexType,\n type EmbeddingMetric,\n} from \"../core/embedding\";\nimport { EmbeddingDimensionChangedError } from \"../errors\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../query/sql-intent\";\nimport { createDataKeyedBag } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\nimport { isMissingTableError } from \"../utils/sql-errors\";\nimport { LEGACY_EMBEDDINGS_TABLE_NAME } from \"./drizzle/schema/sqlite\";\nimport { type GraphBackend } from \"./types\";\n\n/**\n * Default rows read per round-trip. Large enough to amortize round-trip\n * latency, small enough to bound peak memory regardless of table size.\n */\nconst DEFAULT_BATCH_SIZE = 500;\n\n/**\n * Metric / index type applied to a migrated field when no\n * {@link MigrateLegacyEmbeddingsOptions.resolveSlotConfig} is supplied (or\n * it returns `undefined`). Matches the defaults `embedding()` and\n * `resolveEmbeddingFields` apply, so a migrated field lands in storage shaped\n * identically to one written fresh through the store. Migrated data is only\n * ever brute-forceable until `materializeIndexes()` builds the ANN index, so\n * the index-type default governs only which ANN structure the per-field\n * storage DDL provisions, not the migration's correctness.\n */\nconst DEFAULT_SLOT_METRIC: EmbeddingMetric = DEFAULT_EMBEDDING_METRIC;\nconst DEFAULT_SLOT_INDEX_TYPE: EmbeddingIndexType =\n DEFAULT_EMBEDDING_INDEX_TYPE;\n\n/**\n * The resolved storage config for one `(nodeKind, fieldPath)` slot that the\n * legacy table did not record. The legacy shared table stored only the\n * vector and its dimension count — not the metric or index type — so a\n * caller that wants migrated fields to match a specific graph's `embedding()`\n * declarations supplies this resolver.\n */\nexport type LegacyEmbeddingSlotConfig = Readonly<{\n metric: EmbeddingMetric;\n indexType: EmbeddingIndexType;\n}>;\n\n/**\n * Options for {@link migrateLegacyEmbeddings}.\n */\nexport type MigrateLegacyEmbeddingsOptions = Readonly<{\n /**\n * The backend to migrate, wired with the destination `VectorStrategy`\n * (i.e. the post-cutover backend). Its `vectorStrategy` owns the per-field\n * storage rows are written into and its `upsertEmbedding` performs the\n * writes.\n */\n backend: GraphBackend;\n\n /**\n * Restrict the migration to a single graph. When omitted, every graph's\n * rows in the legacy table are migrated (the table is graph-scoped by its\n * `graph_id` column).\n */\n graphId?: string;\n\n /**\n * Resolves the metric / index type for a `(nodeKind, fieldPath)` slot the\n * legacy table didn't persist. Return `undefined` to fall back to the\n * cosine / hnsw defaults. Supply this (typically reading the graph's\n * `embedding()` declarations) when migrated fields must match a specific\n * metric — e.g. an `l2` field, which scores incorrectly under the cosine\n * default.\n */\n resolveSlotConfig?: (\n nodeKind: string,\n fieldPath: string,\n ) => LegacyEmbeddingSlotConfig | undefined;\n\n /** Rows read per round-trip. Defaults to {@link DEFAULT_BATCH_SIZE}. */\n batchSize?: number;\n\n /**\n * Physical name of the legacy table to drain. Defaults to\n * {@link LEGACY_EMBEDDINGS_TABLE_NAME}. Override only for a non-default\n * deployment that renamed the embeddings table.\n */\n legacyTableName?: string;\n}>;\n\n/**\n * Summary of a {@link migrateLegacyEmbeddings} run.\n */\nexport type MigrateLegacyEmbeddingsResult = Readonly<{\n /** Total embedding rows re-inserted into per-field storage. */\n migrated: number;\n /**\n * Per-`(nodeKind, fieldPath)` counts, keyed `\"<nodeKind>.<fieldPath>\"`\n * (the strategy's logical-slot key form). Empty when the legacy table was\n * absent or held no rows for the requested scope.\n */\n perField: Readonly<Record<string, number>>;\n /**\n * Rows skipped because their vector length didn't match the per-field\n * table's fixed dimension. The legacy shared column allowed mixed\n * dimensions for one `(nodeKind, fieldPath)` (e.g. an unmigrated model\n * change); the first migrated row fixes the typed table's dimension and\n * any differently-sized rows for that slot are skipped rather than aborting\n * the whole migration. Keyed `\"<nodeKind>.<fieldPath>\"`. Non-empty here\n * means those fields need a deliberate re-embed at a single dimension.\n */\n skippedDimensionMismatch: Readonly<Record<string, number>>;\n /**\n * Rows skipped because their legacy embedding could not be decoded into a\n * finite-number array — a corrupt value (e.g. a pgvector `vector` column\n * permits `NaN`/`Infinity`, which is not valid JSON). Keyed\n * `\"<nodeKind>.<fieldPath>\"`. Skipping + reporting keeps one bad row from\n * aborting the whole migration; non-empty here means those rows need manual\n * repair.\n */\n skippedDecodeError: Readonly<Record<string, number>>;\n /**\n * Whether the legacy table existed. `false` means the run was a clean\n * no-op (fresh install, or already-dropped table on a re-run).\n */\n legacyTablePresent: boolean;\n}>;\n\n/**\n * A single legacy embedding row, with the engine-native vector already\n * decoded to a JSON array string by the dialect-specific SELECT. The\n * legacy `dimensions` column is intentionally not read: the decoded array's\n * length is the authoritative fixed dimension for the destination slot, and\n * relying on it sidesteps the per-driver string/number coercion the legacy\n * integer column would otherwise need.\n */\ntype LegacyEmbeddingRow = Readonly<{\n graph_id: string;\n node_kind: string;\n node_id: string;\n field_path: string;\n /** JSON array text, e.g. `\"[0.1,0.2,0.3]\"` — decoded per dialect. */\n embedding_json: string;\n}>;\n\n/**\n * Re-inserts every embedding from the legacy shared\n * `typegraph_node_embeddings` table into the active\n * `backend.vectorStrategy`'s per-`(nodeKind, fieldPath)` storage.\n *\n * One-time, explicitly-run upgrade step for the shared-table → per-field\n * cutover (#157). Idempotent, batched, and a clean no-op when the legacy\n * table is absent. See the module doc comment for the full contract.\n *\n * @throws Error when the backend exposes no `vectorStrategy` /\n * `upsertEmbedding` (nothing to migrate *into*) — a configuration\n * error the caller must fix by wiring the destination strategy\n * before migrating.\n */\nexport async function migrateLegacyEmbeddings(\n options: MigrateLegacyEmbeddingsOptions,\n): Promise<MigrateLegacyEmbeddingsResult> {\n const {\n backend,\n graphId,\n resolveSlotConfig,\n batchSize = DEFAULT_BATCH_SIZE,\n legacyTableName = LEGACY_EMBEDDINGS_TABLE_NAME,\n } = options;\n\n if (\n backend.vectorStrategy === undefined ||\n backend.upsertEmbedding === undefined\n ) {\n throw new Error(\n \"migrateLegacyEmbeddings requires a backend wired with a vectorStrategy \" +\n \"(the destination per-field storage). Pass the post-cutover backend.\",\n );\n }\n if (!Number.isInteger(batchSize) || batchSize <= 0) {\n throw new RangeError(\n `batchSize must be a positive integer, got: ${batchSize}`,\n );\n }\n const upsertEmbedding = backend.upsertEmbedding;\n const ensureVectorSlotContribution = backend.ensureVectorSlotContribution;\n\n // Data-keyed: slot keys are built from a row's `node_kind` / `field_path`.\n const perField = createDataKeyedBag<number>();\n const skippedDimensionMismatch = createDataKeyedBag<number>();\n const skippedDecodeError = createDataKeyedBag<number>();\n // (kind, field) slots whose per-field table + durable marker this run has\n // already provisioned, mapped to the dimension the table was fixed at.\n // `upsertEmbedding` asserts the marker (#135) and no longer self-creates\n // the table, so this offline migration (privileged) provisions each slot\n // once — at the first row's dimension, which fixes the typed table just as\n // the original lazy write did. Differently-sized later rows for the same\n // slot are detected against this map and skipped BEFORE the upsert: the\n // marker assert would otherwise read the differently-dimensioned slot as\n // stale and abort the whole migration, and the ensure is deliberately not\n // re-run per row (that would trip the marker drift-guard).\n const ensuredSlots = new Map<string, number>();\n let migrated = 0;\n\n let cursor: LegacyRowCursor | undefined;\n for (;;) {\n let batch: readonly LegacyEmbeddingRow[];\n try {\n batch = await readLegacyBatch(backend, {\n legacyTableName,\n graphId,\n batchSize,\n after: cursor,\n });\n } catch (error) {\n // A missing legacy table is the expected \"nothing to migrate\" path on\n // the first read — surface it as a clean no-op, not a failure.\n if (cursor === undefined && isMissingTableError(error)) {\n return {\n migrated: 0,\n perField: {},\n skippedDimensionMismatch: {},\n skippedDecodeError: {},\n legacyTablePresent: false,\n };\n }\n throw error;\n }\n\n if (batch.length === 0) break;\n\n for (const row of batch) {\n const slotKey = `${row.node_kind}.${row.field_path}`;\n\n let embedding: readonly number[];\n try {\n embedding = decodeEmbeddingJson(row);\n } catch {\n // A corrupt legacy value (e.g. a pgvector `vector` column permits\n // NaN/Infinity, which is not valid JSON) is skipped + reported rather\n // than aborting the whole migration on one bad row.\n skippedDecodeError[slotKey] = (skippedDecodeError[slotKey] ?? 0) + 1;\n continue;\n }\n const config = resolveSlotConfig?.(row.node_kind, row.field_path);\n // The decoded length is the authoritative fixed dimension — the\n // strategy provisions its column type (e.g. `F32_BLOB(N)`) from it.\n const slot = {\n graphId: row.graph_id,\n nodeKind: row.node_kind,\n fieldPath: row.field_path,\n dimensions: embedding.length,\n metric: config?.metric ?? DEFAULT_SLOT_METRIC,\n indexType: config?.indexType ?? DEFAULT_SLOT_INDEX_TYPE,\n };\n\n // Provision the per-field table + durable marker before the first\n // write into this slot. Once per (graph, kind, field): the first row's\n // dimension fixes the table. Keyed by graph id too — the legacy table\n // is graph-scoped, so the same `kind.field` can recur across graphs.\n const ensuredKey = JSON.stringify([\n row.graph_id,\n row.node_kind,\n row.field_path,\n ]);\n if (\n ensureVectorSlotContribution !== undefined &&\n !ensuredSlots.has(ensuredKey)\n ) {\n await ensureVectorSlotContribution(slot);\n ensuredSlots.set(ensuredKey, slot.dimensions);\n }\n\n // The legacy shared column allowed mixed dimensions for one\n // (nodeKind, fieldPath); the per-field table is fixed at the first\n // migrated row's dimension. Skip a differently-sized row up front —\n // its slot would fail the marker assert as stale (different\n // signature), aborting the migration instead of skipping the row.\n const provisionedDimensions = ensuredSlots.get(ensuredKey);\n if (\n provisionedDimensions !== undefined &&\n provisionedDimensions !== embedding.length\n ) {\n skippedDimensionMismatch[slotKey] =\n (skippedDimensionMismatch[slotKey] ?? 0) + 1;\n continue;\n }\n\n try {\n await upsertEmbedding({ ...slot, nodeId: row.node_id, embedding });\n } catch (error) {\n // The legacy shared column allowed mixed dimensions for one\n // (nodeKind, fieldPath); the per-field table is fixed at the first\n // migrated row's dimension, so a differently-sized row is skipped and\n // reported rather than aborting the whole migration.\n if (error instanceof EmbeddingDimensionChangedError) {\n skippedDimensionMismatch[slotKey] =\n (skippedDimensionMismatch[slotKey] ?? 0) + 1;\n continue;\n }\n throw error;\n }\n\n migrated += 1;\n perField[slotKey] = (perField[slotKey] ?? 0) + 1;\n }\n\n if (batch.length < batchSize) break;\n const last = requireDefined(batch.at(-1));\n cursor = {\n graphId: last.graph_id,\n nodeKind: last.node_kind,\n nodeId: last.node_id,\n fieldPath: last.field_path,\n };\n }\n\n // SPREAD at the boundary. The three maps are null-prototype accumulators\n // because their keys are slot names built from row data; that protection is\n // internal, and returning the bags as-is handed a caller three maps with no\n // `toString` and `instanceof Object === false` — while the early\n // \"nothing to migrate\" return above hands back `{}` literals, so the same\n // exported function answered with two different kinds of object depending on\n // whether the legacy table existed. Spread copies own properties with\n // CreateDataProperty, so a `__proto__` slot key survives as an own key.\n return {\n migrated,\n perField: { ...perField },\n skippedDimensionMismatch: { ...skippedDimensionMismatch },\n skippedDecodeError: { ...skippedDecodeError },\n legacyTablePresent: true,\n };\n}\n\n/**\n * Composite keyset cursor over the legacy table's primary key\n * `(graph_id, node_kind, node_id, field_path)`. Stable under concurrent\n * writes and immune to OFFSET drift, so a batched walk reads every row once.\n */\ntype LegacyRowCursor = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n}>;\n\ntype ReadLegacyBatchParams = Readonly<{\n legacyTableName: string;\n graphId: string | undefined;\n batchSize: number;\n after: LegacyRowCursor | undefined;\n}>;\n\n/**\n * Reads one keyset-paginated batch of legacy rows, ordered by the primary\n * key, with the engine-native embedding column decoded to a JSON array\n * string by the dialect.\n */\nasync function readLegacyBatch(\n backend: GraphBackend,\n params: ReadLegacyBatchParams,\n): Promise<readonly LegacyEmbeddingRow[]> {\n const table = sql.identifier(params.legacyTableName);\n const embeddingJson = legacyEmbeddingDecodeExpression(backend);\n\n const conditions: SqlFragment[] = [];\n if (params.graphId !== undefined) {\n conditions.push(sql`\"graph_id\" = ${params.graphId}`);\n }\n if (params.after !== undefined) {\n conditions.push(keysetAfterCondition(params.after));\n }\n\n const whereClause =\n conditions.length === 0 ?\n sql``\n : sql` WHERE ${sql.join(conditions, sql` AND `)}`;\n\n const query = sql`\n SELECT\n \"graph_id\" AS graph_id,\n \"node_kind\" AS node_kind,\n \"node_id\" AS node_id,\n \"field_path\" AS field_path,\n ${embeddingJson} AS embedding_json\n FROM ${table}${whereClause}\n ORDER BY \"graph_id\" ASC, \"node_kind\" ASC, \"node_id\" ASC, \"field_path\" ASC\n LIMIT ${params.batchSize}\n `;\n\n return backend.execute<LegacyEmbeddingRow>(asCompiledRowsSql(query));\n}\n\n/**\n * The strict `>` comparison over the composite primary key, expressed as\n * the standard lexicographic OR-chain so it works on every dialect (SQLite\n * supports row-value comparison, but Postgres + SQLite both accept this\n * portable form).\n */\nfunction keysetAfterCondition(after: LegacyRowCursor): SqlFragment {\n return sql`\n (\n \"graph_id\" > ${after.graphId}\n OR (\"graph_id\" = ${after.graphId} AND \"node_kind\" > ${after.nodeKind})\n OR (\"graph_id\" = ${after.graphId} AND \"node_kind\" = ${after.nodeKind} AND \"node_id\" > ${after.nodeId})\n OR (\n \"graph_id\" = ${after.graphId}\n AND \"node_kind\" = ${after.nodeKind}\n AND \"node_id\" = ${after.nodeId}\n AND \"field_path\" > ${after.fieldPath}\n )\n )\n `;\n}\n\n/**\n * The SQL expression that decodes the legacy engine-native embedding column\n * into a JSON array string `embedding_json`. The single dialect branch in\n * this whole module: the legacy storage formats are genuinely engine-\n * specific, and there is no longer a strategy abstraction over the *legacy*\n * table to delegate to.\n */\nfunction legacyEmbeddingDecodeExpression(backend: GraphBackend): SqlFragment {\n switch (backend.dialect) {\n case \"sqlite\": {\n // Legacy SQLite embeddings were written via `vec_f32('[…]')`\n // (sqlite-vec binary). `vec_to_json` is its inverse, yielding the\n // JSON array text. Requires sqlite-vec on the connection — which the\n // legacy write path also required, so any deployment with legacy rows\n // has it loaded.\n return sql`vec_to_json(\"embedding\")`;\n }\n case \"postgres\": {\n // pgvector's native `vector` casts to its `[…]` text literal, which is\n // valid JSON for `JSON.parse`.\n return sql`\"embedding\"::text`;\n }\n default: {\n const _exhaustive: never = backend.dialect;\n throw new Error(\n `migrateLegacyEmbeddings does not support dialect: ${String(_exhaustive)}`,\n );\n }\n }\n}\n\n/**\n * Parses a decoded `embedding_json` array, asserting it is a non-empty array\n * of finite numbers. A bad decode (wrong type, NaN) names the offending row\n * loudly instead of writing a corrupt vector into per-field storage.\n */\nfunction decodeEmbeddingJson(row: LegacyEmbeddingRow): readonly number[] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(row.embedding_json) as unknown;\n } catch (error) {\n throw new Error(\n `Failed to decode legacy embedding for ${row.node_kind}.${row.field_path} ` +\n `(graph ${row.graph_id}, node ${row.node_id}): not valid JSON.`,\n { cause: error },\n );\n }\n if (!Array.isArray(parsed) || parsed.length === 0) {\n throw new Error(\n `Legacy embedding for ${row.node_kind}.${row.field_path} ` +\n `(graph ${row.graph_id}, node ${row.node_id}) decoded to a non-array ` +\n `or empty value.`,\n );\n }\n for (const [index, value] of parsed.entries()) {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new TypeError(\n `Legacy embedding for ${row.node_kind}.${row.field_path} ` +\n `(graph ${row.graph_id}, node ${row.node_id}) has a non-finite ` +\n `value at index ${index}: ${String(value)}.`,\n );\n }\n }\n return parsed as readonly number[];\n}\n"]}
1
+ {"version":3,"sources":["../src/identity/rebuild.ts","../src/identity/types.ts","../src/backend/migrate-vectors.ts"],"names":["embedding"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,eAAsB,uBAEpB,KAAA,EAAgC;AAChC,EAAA,MAAM,YAAA,CAAa,KAAK,CAAA,CAAE,sBAAA,EAAuB;AACnD;;;AC+CO,SAAS,sBAAsB,KAAA,EAAoC;AACxE,EAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACtB,IAAA,MAAM,IAAI,eAAA;AAAA,MACR,mDAAA;AAAA,MACA;AAAA,QACE,MAAA,EAAQ;AAAA,UACN;AAAA,YACE,IAAA,EAAM,uBAAA;AAAA,YACN,OAAA,EAAS;AAAA;AACX;AACF,OACF;AAAA,MACA;AAAA,QACE,UAAA,EAAY;AAAA;AACd,KACF;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;;;ACjBA,IAAM,kBAAA,GAAqB,GAAA;AAY3B,IAAM,mBAAA,GAAuC,wBAAA;AAC7C,IAAM,uBAAA,GACJ,4BAAA;AA8HF,eAAsB,wBACpB,OAAA,EACwC;AACxC,EAAA,MAAM;AAAA,IACJ,OAAA;AAAA,IACA,OAAA;AAAA,IACA,iBAAA;AAAA,IACA,SAAA,GAAY,kBAAA;AAAA,IACZ,eAAA,GAAkB;AAAA,GACpB,GAAI,OA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I,OAAO,CAAA,wCAAA;AAAA,KAE/C;AAAA,EACF;AACA,EAAA,KAAA,MAAW,CAAC,KAAA,EAAO,KAAK,CAAA,IAAK,MAAA,CAAO,SAAQ,EAAG;AAC7C,IAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,CAAC,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,EAAG;AACxD,MAAA,MAAM,IAAI,SAAA;AAAA,QACR,wBAAwB,GAAA,CAAI,SAAS,CAAA,CAAA,EAAI,GAAA,CAAI,UAAU,CAAA,QAAA,EAC3C,GAAA,CAAI,QAAQ,CAAA,OAAA,EAAU,IAAI,OAAO,CAAA,kCAAA,EACzB,KAAK,CAAA,EAAA,EAAK,MAAA,CAAO,KAAK,CAAC,CAAA,CAAA;AAAA,OAC7C;AAAA,IACF;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["import { type GraphDef, type GraphIdentityConfig } from \"../core/define-graph\";\nimport { storeRuntime } from \"../store/runtime-port\";\nimport { type Store } from \"../store/store\";\n\n/**\n * Rebuilds the derived current identity closure for an identity-enabled store.\n * This is a repair operation: it does not change graph revision or assertions.\n */\nexport async function rebuildIdentityClosure<\n G extends GraphDef & Readonly<{ identity: GraphIdentityConfig }>,\n>(store: Store<G>): Promise<void> {\n await storeRuntime(store).rebuildIdentityClosure();\n}\n","import {\n type AllNodeTypes,\n type GraphDef,\n type NodeKinds,\n} from \"../core/define-graph\";\nimport { ValidationError } from \"../errors\";\nimport {\n type DynamicNode,\n type DynamicNodeReference,\n type GraphNodeReference,\n type Node,\n type NodeRef,\n} from \"../store/types\";\n\n/**\n * The accepted *input* form for every identity facade method: a whole node or\n * a `{ kind, id }` pair for any compile-time graph kind, plus a proof-bearing\n * node or reference produced through the runtime collection lane. Runtime\n * values stay nominal so accepting them does not make an arbitrary\n * `{ kind: string, id: string }` object type-safe.\n *\n * Identity results use {@link IdentityNodeReference}, which honestly includes\n * runtime kinds because an evolved kind can belong to a class reached from a\n * compile-time node.\n */\nexport type IdentityNodeRefInput<G extends GraphDef> =\n NodeRef<AllNodeTypes<G>> | DynamicNode | DynamicNodeReference;\n\n/**\n * A node reference returned by Operational Identity.\n *\n * Identity classes can contain runtime-evolved kinds even when a read starts\n * from a compile-time node, so results honestly include both lanes.\n */\nexport type IdentityNodeReference<G extends GraphDef> =\n GraphNodeReference<G> | DynamicNodeReference;\n\n/** A hydrated compile-time or runtime identity member. */\nexport type IdentityNode<G extends GraphDef> =\n | {\n [K in NodeKinds<G>]: Node<G[\"nodes\"][K][\"type\"]>;\n }[NodeKinds<G>]\n | DynamicNode;\n\ndeclare const __identityAssertionId: unique symbol;\n\nexport type IdentityAssertionId = string &\n Readonly<{ [__identityAssertionId]: true }>;\n\n/**\n * Brands a non-empty string as an {@link IdentityAssertionId}.\n *\n * Use this when a persisted identity assertion id has round-tripped through\n * untyped storage or an external boundary and must be passed back to a\n * retraction surface such as `retractAssertion` or `bulkRetractAssertions`.\n * Mirrors the `asNodeId` / `asEdgeId` precedent.\n *\n * @throws {ValidationError} when `value` is empty.\n */\nexport function asIdentityAssertionId(value: string): IdentityAssertionId {\n if (value.length === 0) {\n throw new ValidationError(\n \"asIdentityAssertionId must be a non-empty string.\",\n {\n issues: [\n {\n path: \"asIdentityAssertionId\",\n message: \"Expected a non-empty string.\",\n },\n ],\n },\n {\n suggestion: \"Use a persisted identity assertion id value.\",\n },\n );\n }\n return value as IdentityAssertionId;\n}\n\n/**\n * What one assertion claims about a pair of nodes: `\"same\"` merges them into\n * one equivalence set, `\"different\"` records a disjointness that a later\n * `\"same\"` claim must not contradict.\n */\nexport type IdentityRelation = \"same\" | \"different\";\n\n/**\n * One persisted identity claim about an ordered pair of nodes. Returned by the\n * assertion writers and by `identity.assertionsOf(...)`; `validTo` is set when\n * the assertion has been retracted, so a historical read can still see it.\n */\nexport type IdentityAssertion<G extends GraphDef> = Readonly<{\n id: IdentityAssertionId;\n relation: IdentityRelation;\n a: IdentityNodeReference<G>;\n b: IdentityNodeReference<G>;\n validFrom: string;\n validTo?: string;\n}>;\n\n/** Result of an idempotent assertion write. */\nexport type IdentityAssertionResult<G extends GraphDef> = Readonly<{\n assertion: IdentityAssertion<G>;\n action: \"created\" | \"existing\";\n}>;\n\n/** The half-open effective-time window of an identity assertion. */\nexport type IdentityValidityWindow = Readonly<{\n validFrom?: string;\n validTo?: string;\n}>;\n\n/** One ordered node pair handed to `bulkAssertSame` / `bulkAssertDifferent`. */\nexport type IdentityPair<G extends GraphDef> = Readonly<{\n a: IdentityNodeRefInput<G>;\n b: IdentityNodeRefInput<G>;\n}> &\n IdentityValidityWindow;\n\n/**\n * The read half of the identity surface: equivalence-set membership,\n * representative selection, and the assertions behind them.\n *\n * Obtained from a read-only lens — `store.asOf(...).identity`,\n * `store.snapshot().identity` — where it answers at that view's coordinate.\n * The full read+write surface is {@link IdentityFacade}.\n */\nexport type IdentityReadFacade<G extends GraphDef> = Readonly<{\n representativeOf: (\n ref: IdentityNodeRefInput<G>,\n ) => Promise<IdentityNodeReference<G> | undefined>;\n membersOf: (\n ref: IdentityNodeRefInput<G>,\n ) => Promise<readonly IdentityNodeReference<G>[]>;\n nodesOf: (\n ref: IdentityNodeRefInput<G>,\n ) => Promise<readonly IdentityNode<G>[]>;\n areSame: (\n a: IdentityNodeRefInput<G>,\n b: IdentityNodeRefInput<G>,\n ) => Promise<boolean>;\n areDifferent: (\n a: IdentityNodeRefInput<G>,\n b: IdentityNodeRefInput<G>,\n ) => Promise<boolean>;\n assertionsOf: (\n ref: IdentityNodeRefInput<G>,\n ) => Promise<readonly IdentityAssertion<G>[]>;\n}>;\n\n/**\n * The full TypeGraph Identity Profile surface: {@link IdentityReadFacade} plus\n * the assertion writers and retractions.\n *\n * Obtained from `store.identity` or `tx.identity`, and present only on graphs\n * that declared `identity: { ... }` in `defineGraph`. Every writer is\n * idempotent — re-asserting an existing claim returns it with\n * `action: \"existing\"` rather than duplicating it.\n */\nexport type IdentityFacade<G extends GraphDef> = IdentityReadFacade<G> &\n Readonly<{\n assertSame: (\n a: IdentityNodeRefInput<G>,\n b: IdentityNodeRefInput<G>,\n window?: IdentityValidityWindow,\n ) => Promise<IdentityAssertionResult<G>>;\n assertDifferent: (\n a: IdentityNodeRefInput<G>,\n b: IdentityNodeRefInput<G>,\n window?: IdentityValidityWindow,\n ) => Promise<IdentityAssertionResult<G>>;\n bulkAssertSame: (\n pairs: readonly IdentityPair<G>[],\n ) => Promise<readonly IdentityAssertionResult<G>[]>;\n bulkAssertDifferent: (\n pairs: readonly IdentityPair<G>[],\n ) => Promise<readonly IdentityAssertionResult<G>[]>;\n retractAssertion: (\n id: IdentityAssertionId,\n ) => Promise<IdentityAssertion<G> | undefined>;\n retractSameAssertion: (\n a: IdentityNodeRefInput<G>,\n b: IdentityNodeRefInput<G>,\n ) => Promise<IdentityAssertion<G> | undefined>;\n retractDifferentAssertion: (\n a: IdentityNodeRefInput<G>,\n b: IdentityNodeRefInput<G>,\n ) => Promise<IdentityAssertion<G> | undefined>;\n bulkRetractAssertions: (\n ids: readonly IdentityAssertionId[],\n ) => Promise<readonly IdentityAssertion<G>[]>;\n }>;\n\n/**\n * The assertion-only write surface of the TypeGraph Identity Profile.\n *\n * This deliberately excludes reads and retractions so constrained staging\n * handles can accept incoming identity claims without exposing the broader\n * operational identity surface.\n */\nexport type IdentityAssertionWriteFacade<G extends GraphDef> = Pick<\n IdentityFacade<G>,\n \"assertSame\" | \"assertDifferent\" | \"bulkAssertSame\" | \"bulkAssertDifferent\"\n>;\n\n/**\n * Per-transaction identity write counts carried by a transaction receipt.\n * `total` is the sum of the three preceding counters.\n */\nexport type IdentityWriteSummary = Readonly<{\n sameAssertions: number;\n differentAssertions: number;\n retractions: number;\n total: number;\n}>;\n","/**\n * One-time offline migration: legacy shared embeddings table → per-field\n * strategy storage.\n *\n * ## What this is for\n *\n * The cross-backend vector cutover (#157) dropped the single shared\n * `typegraph_node_embeddings` table. Each\n * `VectorStrategy` now OWNS one typed, fixed-dimension structure per\n * `(nodeKind, fieldPath)` — the only layout that can be ANN-indexed on\n * libSQL and sqlite-vec, not just pgvector.\n *\n * Deployments that wrote embeddings under the old shared table before\n * upgrading still hold those rows. This utility drains them into the new\n * per-field storage **once**, during the upgrade, so existing embedded\n * data survives the cutover without re-embedding from source.\n *\n * It is an explicitly-run, offline step — not wired into `materializeIndexes`\n * or any boot path. Run it once after deploying the new version and before\n * (or alongside) the first `materializeIndexes()`, then drop the legacy\n * table at your leisure.\n *\n * ## How it works\n *\n * - Skips cleanly (returns a zero summary) when the legacy table is absent —\n * a fresh install, or a re-run after the table was dropped.\n * - Reads rows in keyset-paginated batches (never the whole table at once),\n * decoding the engine-native embedding column to a numeric array at the SQL\n * level: sqlite-vec stored a `vec_f32` blob (`vec_to_json` decodes it);\n * pgvector stored a native `vector` (`::text` yields a `[…]` literal).\n * - Re-inserts each row through `backend.upsertEmbedding`, which routes the\n * active strategy's `buildUpsert` and idempotently provisions the per-field\n * storage (the same `(nodeKind, fieldPath)` slot a fresh store write uses).\n * The migration stays graph-agnostic and execution-correct on both the\n * sync (better-sqlite3) and async (libsql / Postgres) backends — it does\n * not re-implement the backend's statement-execution glue.\n *\n * Idempotent and resumable: a partial run followed by a full run converges\n * to the same per-field tables, because every write is an upsert keyed by\n * `(graph_id, node_id)` in the strategy's owned storage.\n */\nimport {\n DEFAULT_EMBEDDING_INDEX_TYPE,\n DEFAULT_EMBEDDING_METRIC,\n type EmbeddingIndexType,\n type EmbeddingMetric,\n} from \"../core/embedding\";\nimport { EmbeddingDimensionChangedError } from \"../errors\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../query/sql-intent\";\nimport { createDataKeyedBag } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\nimport { isMissingTableError } from \"../utils/sql-errors\";\nimport { LEGACY_EMBEDDINGS_TABLE_NAME } from \"./table-names\";\nimport { type GraphBackend } from \"./types\";\n\n/**\n * Default rows read per round-trip. Large enough to amortize round-trip\n * latency, small enough to bound peak memory regardless of table size.\n */\nconst DEFAULT_BATCH_SIZE = 500;\n\n/**\n * Metric / index type applied to a migrated field when no\n * {@link MigrateLegacyEmbeddingsOptions.resolveSlotConfig} is supplied (or\n * it returns `undefined`). Matches the defaults `embedding()` and\n * `resolveEmbeddingFields` apply, so a migrated field lands in storage shaped\n * identically to one written fresh through the store. Migrated data is only\n * ever brute-forceable until `materializeIndexes()` builds the ANN index, so\n * the index-type default governs only which ANN structure the per-field\n * storage DDL provisions, not the migration's correctness.\n */\nconst DEFAULT_SLOT_METRIC: EmbeddingMetric = DEFAULT_EMBEDDING_METRIC;\nconst DEFAULT_SLOT_INDEX_TYPE: EmbeddingIndexType =\n DEFAULT_EMBEDDING_INDEX_TYPE;\n\n/**\n * The resolved storage config for one `(nodeKind, fieldPath)` slot that the\n * legacy table did not record. The legacy shared table stored only the\n * vector and its dimension count — not the metric or index type — so a\n * caller that wants migrated fields to match a specific graph's `embedding()`\n * declarations supplies this resolver.\n */\nexport type LegacyEmbeddingSlotConfig = Readonly<{\n metric: EmbeddingMetric;\n indexType: EmbeddingIndexType;\n}>;\n\n/**\n * Options for {@link migrateLegacyEmbeddings}.\n */\nexport type MigrateLegacyEmbeddingsOptions = Readonly<{\n /**\n * The backend to migrate, wired with the destination `VectorStrategy`\n * (i.e. the post-cutover backend). Its `vectorStrategy` owns the per-field\n * storage rows are written into and its `upsertEmbedding` performs the\n * writes.\n */\n backend: GraphBackend;\n\n /**\n * Restrict the migration to a single graph. When omitted, every graph's\n * rows in the legacy table are migrated (the table is graph-scoped by its\n * `graph_id` column).\n */\n graphId?: string;\n\n /**\n * Resolves the metric / index type for a `(nodeKind, fieldPath)` slot the\n * legacy table didn't persist. Return `undefined` to fall back to the\n * cosine / hnsw defaults. Supply this (typically reading the graph's\n * `embedding()` declarations) when migrated fields must match a specific\n * metric — e.g. an `l2` field, which scores incorrectly under the cosine\n * default.\n */\n resolveSlotConfig?: (\n nodeKind: string,\n fieldPath: string,\n ) => LegacyEmbeddingSlotConfig | undefined;\n\n /** Rows read per round-trip. Defaults to {@link DEFAULT_BATCH_SIZE}. */\n batchSize?: number;\n\n /**\n * Physical name of the legacy table to drain. Defaults to\n * {@link LEGACY_EMBEDDINGS_TABLE_NAME}. Override only for a non-default\n * deployment that renamed the embeddings table.\n */\n legacyTableName?: string;\n}>;\n\n/**\n * Summary of a {@link migrateLegacyEmbeddings} run.\n */\nexport type MigrateLegacyEmbeddingsResult = Readonly<{\n /** Total embedding rows re-inserted into per-field storage. */\n migrated: number;\n /**\n * Per-`(nodeKind, fieldPath)` counts, keyed `\"<nodeKind>.<fieldPath>\"`\n * (the strategy's logical-slot key form). Empty when the legacy table was\n * absent or held no rows for the requested scope.\n */\n perField: Readonly<Record<string, number>>;\n /**\n * Rows skipped because their vector length didn't match the per-field\n * table's fixed dimension. The legacy shared column allowed mixed\n * dimensions for one `(nodeKind, fieldPath)` (e.g. an unmigrated model\n * change); the first migrated row fixes the typed table's dimension and\n * any differently-sized rows for that slot are skipped rather than aborting\n * the whole migration. Keyed `\"<nodeKind>.<fieldPath>\"`. Non-empty here\n * means those fields need a deliberate re-embed at a single dimension.\n */\n skippedDimensionMismatch: Readonly<Record<string, number>>;\n /**\n * Rows skipped because their legacy embedding could not be decoded into a\n * finite-number array — a corrupt value (e.g. a pgvector `vector` column\n * permits `NaN`/`Infinity`, which is not valid JSON). Keyed\n * `\"<nodeKind>.<fieldPath>\"`. Skipping + reporting keeps one bad row from\n * aborting the whole migration; non-empty here means those rows need manual\n * repair.\n */\n skippedDecodeError: Readonly<Record<string, number>>;\n /**\n * Whether the legacy table existed. `false` means the run was a clean\n * no-op (fresh install, or already-dropped table on a re-run).\n */\n legacyTablePresent: boolean;\n}>;\n\n/**\n * A single legacy embedding row, with the engine-native vector already\n * decoded to a JSON array string by the dialect-specific SELECT. The\n * legacy `dimensions` column is intentionally not read: the decoded array's\n * length is the authoritative fixed dimension for the destination slot, and\n * relying on it sidesteps the per-driver string/number coercion the legacy\n * integer column would otherwise need.\n */\ntype LegacyEmbeddingRow = Readonly<{\n graph_id: string;\n node_kind: string;\n node_id: string;\n field_path: string;\n /** JSON array text, e.g. `\"[0.1,0.2,0.3]\"` — decoded per dialect. */\n embedding_json: string;\n}>;\n\n/**\n * Re-inserts every embedding from the legacy shared\n * `typegraph_node_embeddings` table into the active\n * `backend.vectorStrategy`'s per-`(nodeKind, fieldPath)` storage.\n *\n * One-time, explicitly-run upgrade step for the shared-table → per-field\n * cutover (#157). Idempotent, batched, and a clean no-op when the legacy\n * table is absent. See the module doc comment for the full contract.\n *\n * @throws Error when the backend exposes no `vectorStrategy` /\n * `upsertEmbedding` (nothing to migrate *into*) — a configuration\n * error the caller must fix by wiring the destination strategy\n * before migrating.\n */\nexport async function migrateLegacyEmbeddings(\n options: MigrateLegacyEmbeddingsOptions,\n): Promise<MigrateLegacyEmbeddingsResult> {\n const {\n backend,\n graphId,\n resolveSlotConfig,\n batchSize = DEFAULT_BATCH_SIZE,\n legacyTableName = LEGACY_EMBEDDINGS_TABLE_NAME,\n } = options;\n\n if (\n backend.vectorStrategy === undefined ||\n backend.upsertEmbedding === undefined\n ) {\n throw new Error(\n \"migrateLegacyEmbeddings requires a backend wired with a vectorStrategy \" +\n \"(the destination per-field storage). Pass the post-cutover backend.\",\n );\n }\n if (!Number.isInteger(batchSize) || batchSize <= 0) {\n throw new RangeError(\n `batchSize must be a positive integer, got: ${batchSize}`,\n );\n }\n const upsertEmbedding = backend.upsertEmbedding;\n const ensureVectorSlotContribution = backend.ensureVectorSlotContribution;\n\n // Data-keyed: slot keys are built from a row's `node_kind` / `field_path`.\n const perField = createDataKeyedBag<number>();\n const skippedDimensionMismatch = createDataKeyedBag<number>();\n const skippedDecodeError = createDataKeyedBag<number>();\n // (kind, field) slots whose per-field table + durable marker this run has\n // already provisioned, mapped to the dimension the table was fixed at.\n // `upsertEmbedding` asserts the marker (#135) and no longer self-creates\n // the table, so this offline migration (privileged) provisions each slot\n // once — at the first row's dimension, which fixes the typed table just as\n // the original lazy write did. Differently-sized later rows for the same\n // slot are detected against this map and skipped BEFORE the upsert: the\n // marker assert would otherwise read the differently-dimensioned slot as\n // stale and abort the whole migration, and the ensure is deliberately not\n // re-run per row (that would trip the marker drift-guard).\n const ensuredSlots = new Map<string, number>();\n let migrated = 0;\n\n let cursor: LegacyRowCursor | undefined;\n for (;;) {\n let batch: readonly LegacyEmbeddingRow[];\n try {\n batch = await readLegacyBatch(backend, {\n legacyTableName,\n graphId,\n batchSize,\n after: cursor,\n });\n } catch (error) {\n // A missing legacy table is the expected \"nothing to migrate\" path on\n // the first read — surface it as a clean no-op, not a failure.\n if (cursor === undefined && isMissingTableError(error)) {\n return {\n migrated: 0,\n perField: {},\n skippedDimensionMismatch: {},\n skippedDecodeError: {},\n legacyTablePresent: false,\n };\n }\n throw error;\n }\n\n if (batch.length === 0) break;\n\n for (const row of batch) {\n const slotKey = `${row.node_kind}.${row.field_path}`;\n\n let embedding: readonly number[];\n try {\n embedding = decodeEmbeddingJson(row);\n } catch {\n // A corrupt legacy value (e.g. a pgvector `vector` column permits\n // NaN/Infinity, which is not valid JSON) is skipped + reported rather\n // than aborting the whole migration on one bad row.\n skippedDecodeError[slotKey] = (skippedDecodeError[slotKey] ?? 0) + 1;\n continue;\n }\n const config = resolveSlotConfig?.(row.node_kind, row.field_path);\n // The decoded length is the authoritative fixed dimension — the\n // strategy provisions its column type (e.g. `F32_BLOB(N)`) from it.\n const slot = {\n graphId: row.graph_id,\n nodeKind: row.node_kind,\n fieldPath: row.field_path,\n dimensions: embedding.length,\n metric: config?.metric ?? DEFAULT_SLOT_METRIC,\n indexType: config?.indexType ?? DEFAULT_SLOT_INDEX_TYPE,\n };\n\n // Provision the per-field table + durable marker before the first\n // write into this slot. Once per (graph, kind, field): the first row's\n // dimension fixes the table. Keyed by graph id too — the legacy table\n // is graph-scoped, so the same `kind.field` can recur across graphs.\n const ensuredKey = JSON.stringify([\n row.graph_id,\n row.node_kind,\n row.field_path,\n ]);\n if (\n ensureVectorSlotContribution !== undefined &&\n !ensuredSlots.has(ensuredKey)\n ) {\n await ensureVectorSlotContribution(slot);\n ensuredSlots.set(ensuredKey, slot.dimensions);\n }\n\n // The legacy shared column allowed mixed dimensions for one\n // (nodeKind, fieldPath); the per-field table is fixed at the first\n // migrated row's dimension. Skip a differently-sized row up front —\n // its slot would fail the marker assert as stale (different\n // signature), aborting the migration instead of skipping the row.\n const provisionedDimensions = ensuredSlots.get(ensuredKey);\n if (\n provisionedDimensions !== undefined &&\n provisionedDimensions !== embedding.length\n ) {\n skippedDimensionMismatch[slotKey] =\n (skippedDimensionMismatch[slotKey] ?? 0) + 1;\n continue;\n }\n\n try {\n await upsertEmbedding({ ...slot, nodeId: row.node_id, embedding });\n } catch (error) {\n // The legacy shared column allowed mixed dimensions for one\n // (nodeKind, fieldPath); the per-field table is fixed at the first\n // migrated row's dimension, so a differently-sized row is skipped and\n // reported rather than aborting the whole migration.\n if (error instanceof EmbeddingDimensionChangedError) {\n skippedDimensionMismatch[slotKey] =\n (skippedDimensionMismatch[slotKey] ?? 0) + 1;\n continue;\n }\n throw error;\n }\n\n migrated += 1;\n perField[slotKey] = (perField[slotKey] ?? 0) + 1;\n }\n\n if (batch.length < batchSize) break;\n const last = requireDefined(batch.at(-1));\n cursor = {\n graphId: last.graph_id,\n nodeKind: last.node_kind,\n nodeId: last.node_id,\n fieldPath: last.field_path,\n };\n }\n\n // SPREAD at the boundary. The three maps are null-prototype accumulators\n // because their keys are slot names built from row data; that protection is\n // internal, and returning the bags as-is handed a caller three maps with no\n // `toString` and `instanceof Object === false` — while the early\n // \"nothing to migrate\" return above hands back `{}` literals, so the same\n // exported function answered with two different kinds of object depending on\n // whether the legacy table existed. Spread copies own properties with\n // CreateDataProperty, so a `__proto__` slot key survives as an own key.\n return {\n migrated,\n perField: { ...perField },\n skippedDimensionMismatch: { ...skippedDimensionMismatch },\n skippedDecodeError: { ...skippedDecodeError },\n legacyTablePresent: true,\n };\n}\n\n/**\n * Composite keyset cursor over the legacy table's primary key\n * `(graph_id, node_kind, node_id, field_path)`. Stable under concurrent\n * writes and immune to OFFSET drift, so a batched walk reads every row once.\n */\ntype LegacyRowCursor = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n}>;\n\ntype ReadLegacyBatchParams = Readonly<{\n legacyTableName: string;\n graphId: string | undefined;\n batchSize: number;\n after: LegacyRowCursor | undefined;\n}>;\n\n/**\n * Reads one keyset-paginated batch of legacy rows, ordered by the primary\n * key, with the engine-native embedding column decoded to a JSON array\n * string by the dialect.\n */\nasync function readLegacyBatch(\n backend: GraphBackend,\n params: ReadLegacyBatchParams,\n): Promise<readonly LegacyEmbeddingRow[]> {\n const table = sql.identifier(params.legacyTableName);\n const embeddingJson = legacyEmbeddingDecodeExpression(backend);\n\n const conditions: SqlFragment[] = [];\n if (params.graphId !== undefined) {\n conditions.push(sql`\"graph_id\" = ${params.graphId}`);\n }\n if (params.after !== undefined) {\n conditions.push(keysetAfterCondition(params.after));\n }\n\n const whereClause =\n conditions.length === 0 ?\n sql``\n : sql` WHERE ${sql.join(conditions, sql` AND `)}`;\n\n const query = sql`\n SELECT\n \"graph_id\" AS graph_id,\n \"node_kind\" AS node_kind,\n \"node_id\" AS node_id,\n \"field_path\" AS field_path,\n ${embeddingJson} AS embedding_json\n FROM ${table}${whereClause}\n ORDER BY \"graph_id\" ASC, \"node_kind\" ASC, \"node_id\" ASC, \"field_path\" ASC\n LIMIT ${params.batchSize}\n `;\n\n return backend.execute<LegacyEmbeddingRow>(asCompiledRowsSql(query));\n}\n\n/**\n * The strict `>` comparison over the composite primary key, expressed as\n * the standard lexicographic OR-chain so it works on every dialect (SQLite\n * supports row-value comparison, but Postgres + SQLite both accept this\n * portable form).\n */\nfunction keysetAfterCondition(after: LegacyRowCursor): SqlFragment {\n return sql`\n (\n \"graph_id\" > ${after.graphId}\n OR (\"graph_id\" = ${after.graphId} AND \"node_kind\" > ${after.nodeKind})\n OR (\"graph_id\" = ${after.graphId} AND \"node_kind\" = ${after.nodeKind} AND \"node_id\" > ${after.nodeId})\n OR (\n \"graph_id\" = ${after.graphId}\n AND \"node_kind\" = ${after.nodeKind}\n AND \"node_id\" = ${after.nodeId}\n AND \"field_path\" > ${after.fieldPath}\n )\n )\n `;\n}\n\n/**\n * The SQL expression that decodes the legacy engine-native embedding column\n * into a JSON array string `embedding_json`. The single dialect branch in\n * this whole module: the legacy storage formats are genuinely engine-\n * specific, and there is no longer a strategy abstraction over the *legacy*\n * table to delegate to.\n */\nfunction legacyEmbeddingDecodeExpression(backend: GraphBackend): SqlFragment {\n switch (backend.dialect) {\n case \"sqlite\": {\n // Legacy SQLite embeddings were written via `vec_f32('[…]')`\n // (sqlite-vec binary). `vec_to_json` is its inverse, yielding the\n // JSON array text. Requires sqlite-vec on the connection — which the\n // legacy write path also required, so any deployment with legacy rows\n // has it loaded.\n return sql`vec_to_json(\"embedding\")`;\n }\n case \"postgres\": {\n // pgvector's native `vector` casts to its `[…]` text literal, which is\n // valid JSON for `JSON.parse`.\n return sql`\"embedding\"::text`;\n }\n default: {\n const _exhaustive: never = backend.dialect;\n throw new Error(\n `migrateLegacyEmbeddings does not support dialect: ${String(_exhaustive)}`,\n );\n }\n }\n}\n\n/**\n * Parses a decoded `embedding_json` array, asserting it is a non-empty array\n * of finite numbers. A bad decode (wrong type, NaN) names the offending row\n * loudly instead of writing a corrupt vector into per-field storage.\n */\nfunction decodeEmbeddingJson(row: LegacyEmbeddingRow): readonly number[] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(row.embedding_json) as unknown;\n } catch (error) {\n throw new Error(\n `Failed to decode legacy embedding for ${row.node_kind}.${row.field_path} ` +\n `(graph ${row.graph_id}, node ${row.node_id}): not valid JSON.`,\n { cause: error },\n );\n }\n if (!Array.isArray(parsed) || parsed.length === 0) {\n throw new Error(\n `Legacy embedding for ${row.node_kind}.${row.field_path} ` +\n `(graph ${row.graph_id}, node ${row.node_id}) decoded to a non-array ` +\n `or empty value.`,\n );\n }\n for (const [index, value] of parsed.entries()) {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new TypeError(\n `Legacy embedding for ${row.node_kind}.${row.field_path} ` +\n `(graph ${row.graph_id}, node ${row.node_id}) has a non-finite ` +\n `value at index ${index}: ${String(value)}.`,\n );\n }\n }\n return parsed as readonly number[];\n}\n"]}
@@ -1,13 +1,15 @@
1
1
  'use strict';
2
2
 
3
3
  var chunkUWG5GX6E_cjs = require('../chunk-UWG5GX6E.cjs');
4
- var chunkCSNOYIB4_cjs = require('../chunk-CSNOYIB4.cjs');
5
- var chunkSHC7BCG5_cjs = require('../chunk-SHC7BCG5.cjs');
6
- var chunkHY5BNOUN_cjs = require('../chunk-HY5BNOUN.cjs');
4
+ var chunkTM54OBHX_cjs = require('../chunk-TM54OBHX.cjs');
5
+ var chunkI7YAY2VQ_cjs = require('../chunk-I7YAY2VQ.cjs');
6
+ var chunkOTNTGEXR_cjs = require('../chunk-OTNTGEXR.cjs');
7
7
  require('../chunk-ZY4GXIVN.cjs');
8
+ require('../chunk-JVA3KDEA.cjs');
9
+ require('../chunk-A4C4NJ5U.cjs');
8
10
  require('../chunk-NAUA4PW5.cjs');
9
- require('../chunk-TEC24ZDA.cjs');
10
- require('../chunk-OJHD3LXJ.cjs');
11
+ require('../chunk-H2VWDQWC.cjs');
12
+ require('../chunk-H5IJSROF.cjs');
11
13
  require('../chunk-7EO3TCQB.cjs');
12
14
  require('../chunk-RT5ZY4XA.cjs');
13
15
  require('../chunk-HAHNRASW.cjs');
@@ -39,31 +41,31 @@ Object.defineProperty(exports, "toDeclaredIndexes", {
39
41
  });
40
42
  Object.defineProperty(exports, "generateEdgeIndexDDL", {
41
43
  enumerable: true,
42
- get: function () { return chunkCSNOYIB4_cjs.generateEdgeIndexDDL; }
44
+ get: function () { return chunkTM54OBHX_cjs.generateEdgeIndexDDL; }
43
45
  });
44
46
  Object.defineProperty(exports, "generateIndexDDL", {
45
47
  enumerable: true,
46
- get: function () { return chunkCSNOYIB4_cjs.generateIndexDDL; }
48
+ get: function () { return chunkTM54OBHX_cjs.generateIndexDDL; }
47
49
  });
48
50
  Object.defineProperty(exports, "generateNodeIndexDDL", {
49
51
  enumerable: true,
50
- get: function () { return chunkCSNOYIB4_cjs.generateNodeIndexDDL; }
52
+ get: function () { return chunkTM54OBHX_cjs.generateNodeIndexDDL; }
51
53
  });
52
54
  Object.defineProperty(exports, "SYSTEM_INDEX_DECLARATIONS", {
53
55
  enumerable: true,
54
- get: function () { return chunkSHC7BCG5_cjs.SYSTEM_INDEX_DECLARATIONS; }
56
+ get: function () { return chunkI7YAY2VQ_cjs.SYSTEM_INDEX_DECLARATIONS; }
55
57
  });
56
58
  Object.defineProperty(exports, "generateSystemIndexDDL", {
57
59
  enumerable: true,
58
- get: function () { return chunkSHC7BCG5_cjs.generateSystemIndexDDL; }
60
+ get: function () { return chunkI7YAY2VQ_cjs.generateSystemIndexDDL; }
59
61
  });
60
62
  Object.defineProperty(exports, "defineEdgeIndex", {
61
63
  enumerable: true,
62
- get: function () { return chunkHY5BNOUN_cjs.defineEdgeIndex; }
64
+ get: function () { return chunkOTNTGEXR_cjs.defineEdgeIndex; }
63
65
  });
64
66
  Object.defineProperty(exports, "defineNodeIndex", {
65
67
  enumerable: true,
66
- get: function () { return chunkHY5BNOUN_cjs.defineNodeIndex; }
68
+ get: function () { return chunkOTNTGEXR_cjs.defineNodeIndex; }
67
69
  });
68
70
  //# sourceMappingURL=index.cjs.map
69
71
  //# sourceMappingURL=index.cjs.map
@@ -1,7 +1,7 @@
1
- import { ag as EdgeIndexDeclaration, ce as SqlDialect, bQ as RelationalIndexDeclaration, bB as NodeIndexDeclaration, I as IndexDeclaration } from '../types-CWg4dTjj.cjs';
2
- export { dm as EdgeIndexConfig, ah as EdgeIndexDirection, dn as EdgeIndexWhereBuilder, bd as IndexOrigin, be as IndexScope, bf as IndexWhereExpression, dp as IndexWhereFieldBuilder, dq as IndexWhereInput, dr as NodeIndexConfig, ds as NodeIndexWhereBuilder, co as SystemColumnName, cM as VectorIndexDeclaration, cN as VectorIndexImplementation, cO as VectorIndexMetric, cP as VectorIndexParams } from '../types-CWg4dTjj.cjs';
3
- export { S as SYSTEM_INDEX_DECLARATIONS, a as SystemIndexDeclaration, b as SystemIndexTable, c as andWhere, d as defineEdgeIndex, e as defineNodeIndex, g as generateSystemIndexDDL, n as notWhere, o as orWhere } from '../where-CNtx1aLc.cjs';
4
- import { D as DeclaredIndex } from '../types-BE921wRl.cjs';
1
+ import { ap as EdgeIndexDeclaration, cn as SqlDialect, bZ as RelationalIndexDeclaration, bF as NodeIndexDeclaration, I as IndexDeclaration } from '../types-6yf0Vv-_.cjs';
2
+ export { dz as EdgeIndexConfig, aq as EdgeIndexDirection, dA as EdgeIndexWhereBuilder, bj as IndexOrigin, bk as IndexScope, bl as IndexWhereExpression, dB as IndexWhereFieldBuilder, dC as IndexWhereInput, dD as NodeIndexConfig, dE as NodeIndexWhereBuilder, cx as SystemColumnName, cU as VectorIndexDeclaration, cV as VectorIndexImplementation, cW as VectorIndexMetric, cX as VectorIndexParams } from '../types-6yf0Vv-_.cjs';
3
+ export { S as SYSTEM_INDEX_DECLARATIONS, a as SystemIndexDeclaration, b as SystemIndexTable, c as andWhere, d as defineEdgeIndex, e as defineNodeIndex, g as generateSystemIndexDDL, n as notWhere, o as orWhere } from '../where-Mhf_yyKX.cjs';
4
+ import { D as DeclaredIndex } from '../types-DzJ4dlzk.cjs';
5
5
  import 'zod';
6
6
 
7
7
  type GenerateIndexDdlOptions = Readonly<{
@@ -1,7 +1,7 @@
1
- import { ag as EdgeIndexDeclaration, ce as SqlDialect, bQ as RelationalIndexDeclaration, bB as NodeIndexDeclaration, I as IndexDeclaration } from '../types-CWg4dTjj.js';
2
- export { dm as EdgeIndexConfig, ah as EdgeIndexDirection, dn as EdgeIndexWhereBuilder, bd as IndexOrigin, be as IndexScope, bf as IndexWhereExpression, dp as IndexWhereFieldBuilder, dq as IndexWhereInput, dr as NodeIndexConfig, ds as NodeIndexWhereBuilder, co as SystemColumnName, cM as VectorIndexDeclaration, cN as VectorIndexImplementation, cO as VectorIndexMetric, cP as VectorIndexParams } from '../types-CWg4dTjj.js';
3
- export { S as SYSTEM_INDEX_DECLARATIONS, a as SystemIndexDeclaration, b as SystemIndexTable, c as andWhere, d as defineEdgeIndex, e as defineNodeIndex, g as generateSystemIndexDDL, n as notWhere, o as orWhere } from '../where-BWXUPV3C.js';
4
- import { D as DeclaredIndex } from '../types-BScHXVM7.js';
1
+ import { ap as EdgeIndexDeclaration, cn as SqlDialect, bZ as RelationalIndexDeclaration, bF as NodeIndexDeclaration, I as IndexDeclaration } from '../types-6yf0Vv-_.js';
2
+ export { dz as EdgeIndexConfig, aq as EdgeIndexDirection, dA as EdgeIndexWhereBuilder, bj as IndexOrigin, bk as IndexScope, bl as IndexWhereExpression, dB as IndexWhereFieldBuilder, dC as IndexWhereInput, dD as NodeIndexConfig, dE as NodeIndexWhereBuilder, cx as SystemColumnName, cU as VectorIndexDeclaration, cV as VectorIndexImplementation, cW as VectorIndexMetric, cX as VectorIndexParams } from '../types-6yf0Vv-_.js';
3
+ export { S as SYSTEM_INDEX_DECLARATIONS, a as SystemIndexDeclaration, b as SystemIndexTable, c as andWhere, d as defineEdgeIndex, e as defineNodeIndex, g as generateSystemIndexDDL, n as notWhere, o as orWhere } from '../where-DuG2LCLe.js';
4
+ import { D as DeclaredIndex } from '../types-_vVSB9k-.js';
5
5
  import 'zod';
6
6
 
7
7
  type GenerateIndexDdlOptions = Readonly<{
@@ -1,11 +1,13 @@
1
1
  export { andWhere, notWhere, orWhere, toDeclaredIndex, toDeclaredIndexes } from '../chunk-QZ7A6HBM.js';
2
- export { generateEdgeIndexDDL, generateIndexDDL, generateNodeIndexDDL } from '../chunk-WQBAQZHR.js';
3
- export { SYSTEM_INDEX_DECLARATIONS, generateSystemIndexDDL } from '../chunk-H3XP6BAV.js';
4
- export { defineEdgeIndex, defineNodeIndex } from '../chunk-ZRJTM7MT.js';
2
+ export { generateEdgeIndexDDL, generateIndexDDL, generateNodeIndexDDL } from '../chunk-6NLYIMJO.js';
3
+ export { SYSTEM_INDEX_DECLARATIONS, generateSystemIndexDDL } from '../chunk-36VYWVQU.js';
4
+ export { defineEdgeIndex, defineNodeIndex } from '../chunk-LZMQ3SFK.js';
5
5
  import '../chunk-K34OPSJK.js';
6
+ import '../chunk-7G5IYROL.js';
7
+ import '../chunk-4QKOZYMV.js';
6
8
  import '../chunk-2EBMPJBO.js';
7
- import '../chunk-EDLKIQRI.js';
8
- import '../chunk-46UGOVRW.js';
9
+ import '../chunk-PC5NGH5A.js';
10
+ import '../chunk-7QFRK6PU.js';
9
11
  import '../chunk-AMKPPFUO.js';
10
12
  import '../chunk-W6OG3HDG.js';
11
13
  import '../chunk-PC2UBAUB.js';
@@ -1,4 +1,4 @@
1
- import { dk as GraphDef } from './types-CWg4dTjj.js';
1
+ import { d as GraphDef } from './types-6yf0Vv-_.cjs';
2
2
 
3
3
  /**
4
4
  * Private capability bridge from an opaque ingestion branch to interchange.
@@ -1,4 +1,4 @@
1
- import { dk as GraphDef } from './types-CWg4dTjj.cjs';
1
+ import { d as GraphDef } from './types-6yf0Vv-_.js';
2
2
 
3
3
  /**
4
4
  * Private capability bridge from an opaque ingestion branch to interchange.
@@ -1,21 +1,23 @@
1
1
  'use strict';
2
2
 
3
- var chunkCS6JTQQ2_cjs = require('../chunk-CS6JTQQ2.cjs');
4
- require('../chunk-C76WFIVZ.cjs');
5
- var chunkTUVD4DFR_cjs = require('../chunk-TUVD4DFR.cjs');
6
- require('../chunk-7PRMDZIA.cjs');
7
- require('../chunk-5OWHU7Z7.cjs');
8
- require('../chunk-RDP6ZRSM.cjs');
9
- var chunkZBFZGLZE_cjs = require('../chunk-ZBFZGLZE.cjs');
10
- require('../chunk-IHK5KA2Q.cjs');
11
- require('../chunk-GHZPZNFC.cjs');
12
- require('../chunk-G2TLHH6T.cjs');
13
- require('../chunk-LLVOQOWE.cjs');
3
+ var chunkKACEYDYV_cjs = require('../chunk-KACEYDYV.cjs');
4
+ require('../chunk-2KCTP3U2.cjs');
5
+ var chunk2CVDZCXH_cjs = require('../chunk-2CVDZCXH.cjs');
6
+ require('../chunk-FMMW3KX7.cjs');
7
+ require('../chunk-L6EVYIID.cjs');
8
+ require('../chunk-JQKMEKKW.cjs');
9
+ var chunkNLX5OWK7_cjs = require('../chunk-NLX5OWK7.cjs');
10
+ require('../chunk-ZGVTNKTX.cjs');
11
+ require('../chunk-NUQ2YFFH.cjs');
12
+ require('../chunk-7B7I7YAW.cjs');
13
+ require('../chunk-CRZ56SZU.cjs');
14
14
  require('../chunk-DWUDZ66O.cjs');
15
15
  var chunkM5MSP3BI_cjs = require('../chunk-M5MSP3BI.cjs');
16
+ require('../chunk-JVA3KDEA.cjs');
17
+ require('../chunk-A4C4NJ5U.cjs');
16
18
  require('../chunk-NAUA4PW5.cjs');
17
- require('../chunk-TEC24ZDA.cjs');
18
- require('../chunk-OJHD3LXJ.cjs');
19
+ require('../chunk-H2VWDQWC.cjs');
20
+ require('../chunk-H5IJSROF.cjs');
19
21
  require('../chunk-RT5ZY4XA.cjs');
20
22
  var chunkHAHNRASW_cjs = require('../chunk-HAHNRASW.cjs');
21
23
  require('../chunk-VLBTRXA2.cjs');
@@ -261,7 +263,7 @@ async function consumeTrustedChunks(store, session, chunks) {
261
263
  }
262
264
  async function trustedImportGraphStream(store, chunks) {
263
265
  rejectUnsupportedStoreFeatures(store);
264
- const backend = chunkTUVD4DFR_cjs.storeBackend(store);
266
+ const backend = chunk2CVDZCXH_cjs.storeBackend(store);
265
267
  const trustedImport = backend.trustedImport;
266
268
  if (trustedImport === void 0) {
267
269
  throw new chunkX4GDXBOP_cjs.TrustedImportError(
@@ -270,10 +272,10 @@ async function trustedImportGraphStream(store, chunks) {
270
272
  { dialect: backend.dialect }
271
273
  );
272
274
  }
273
- const sourceBackend = Symbol.asyncIterator in chunks ? chunkCS6JTQQ2_cjs.exportStreamBackend(chunks) : void 0;
274
- const contention = sourceBackend === void 0 ? void 0 : chunkZBFZGLZE_cjs.snapshotExportContention(sourceBackend, backend);
275
+ const sourceBackend = Symbol.asyncIterator in chunks ? chunkKACEYDYV_cjs.exportStreamBackend(chunks) : void 0;
276
+ const contention = sourceBackend === void 0 ? void 0 : chunkNLX5OWK7_cjs.snapshotExportContention(sourceBackend, backend);
275
277
  if (contention !== void 0) {
276
- throw chunkCS6JTQQ2_cjs.serializedStreamRefusal({
278
+ throw chunkKACEYDYV_cjs.serializedStreamRefusal({
277
279
  graphId: store.graphId,
278
280
  requested: "import-stream",
279
281
  heldBy: "export-snapshot",
@@ -287,7 +289,7 @@ async function trustedImportGraphStream(store, chunks) {
287
289
  expectedVersion: schemaVersion
288
290
  }
289
291
  };
290
- return chunkCS6JTQQ2_cjs.withImportStreamLease(
292
+ return chunkKACEYDYV_cjs.withImportStreamLease(
291
293
  store,
292
294
  () => trustedImport(
293
295
  (session) => consumeTrustedChunks(store, session, chunks),
@@ -316,87 +318,87 @@ function trustedImportGraph(store, data) {
316
318
 
317
319
  Object.defineProperty(exports, "ConflictStrategySchema", {
318
320
  enumerable: true,
319
- get: function () { return chunkCS6JTQQ2_cjs.ConflictStrategySchema; }
321
+ get: function () { return chunkKACEYDYV_cjs.ConflictStrategySchema; }
320
322
  });
321
323
  Object.defineProperty(exports, "ExportOptionsSchema", {
322
324
  enumerable: true,
323
- get: function () { return chunkCS6JTQQ2_cjs.ExportOptionsSchema; }
325
+ get: function () { return chunkKACEYDYV_cjs.ExportOptionsSchema; }
324
326
  });
325
327
  Object.defineProperty(exports, "ExportStreamOptionsSchema", {
326
328
  enumerable: true,
327
- get: function () { return chunkCS6JTQQ2_cjs.ExportStreamOptionsSchema; }
329
+ get: function () { return chunkKACEYDYV_cjs.ExportStreamOptionsSchema; }
328
330
  });
329
331
  Object.defineProperty(exports, "FORMAT_VERSION", {
330
332
  enumerable: true,
331
- get: function () { return chunkCS6JTQQ2_cjs.FORMAT_VERSION; }
333
+ get: function () { return chunkKACEYDYV_cjs.FORMAT_VERSION; }
332
334
  });
333
335
  Object.defineProperty(exports, "GraphDataHeaderSchema", {
334
336
  enumerable: true,
335
- get: function () { return chunkCS6JTQQ2_cjs.GraphDataHeaderSchema; }
337
+ get: function () { return chunkKACEYDYV_cjs.GraphDataHeaderSchema; }
336
338
  });
337
339
  Object.defineProperty(exports, "GraphDataSchema", {
338
340
  enumerable: true,
339
- get: function () { return chunkCS6JTQQ2_cjs.GraphDataSchema; }
341
+ get: function () { return chunkKACEYDYV_cjs.GraphDataSchema; }
340
342
  });
341
343
  Object.defineProperty(exports, "GraphDataSourceSchema", {
342
344
  enumerable: true,
343
- get: function () { return chunkCS6JTQQ2_cjs.GraphDataSourceSchema; }
345
+ get: function () { return chunkKACEYDYV_cjs.GraphDataSourceSchema; }
344
346
  });
345
347
  Object.defineProperty(exports, "GraphInterchangeChunkSchema", {
346
348
  enumerable: true,
347
- get: function () { return chunkCS6JTQQ2_cjs.GraphInterchangeChunkSchema; }
349
+ get: function () { return chunkKACEYDYV_cjs.GraphInterchangeChunkSchema; }
348
350
  });
349
351
  Object.defineProperty(exports, "IdentityInterchangeModeSchema", {
350
352
  enumerable: true,
351
- get: function () { return chunkCS6JTQQ2_cjs.IdentityInterchangeModeSchema; }
353
+ get: function () { return chunkKACEYDYV_cjs.IdentityInterchangeModeSchema; }
352
354
  });
353
355
  Object.defineProperty(exports, "ImportErrorSchema", {
354
356
  enumerable: true,
355
- get: function () { return chunkCS6JTQQ2_cjs.ImportErrorSchema; }
357
+ get: function () { return chunkKACEYDYV_cjs.ImportErrorSchema; }
356
358
  });
357
359
  Object.defineProperty(exports, "ImportOptionsSchema", {
358
360
  enumerable: true,
359
- get: function () { return chunkCS6JTQQ2_cjs.ImportOptionsSchema; }
361
+ get: function () { return chunkKACEYDYV_cjs.ImportOptionsSchema; }
360
362
  });
361
363
  Object.defineProperty(exports, "ImportResultSchema", {
362
364
  enumerable: true,
363
- get: function () { return chunkCS6JTQQ2_cjs.ImportResultSchema; }
365
+ get: function () { return chunkKACEYDYV_cjs.ImportResultSchema; }
364
366
  });
365
367
  Object.defineProperty(exports, "InterchangeEdgeSchema", {
366
368
  enumerable: true,
367
- get: function () { return chunkCS6JTQQ2_cjs.InterchangeEdgeSchema; }
369
+ get: function () { return chunkKACEYDYV_cjs.InterchangeEdgeSchema; }
368
370
  });
369
371
  Object.defineProperty(exports, "InterchangeIdentityAssertionSchema", {
370
372
  enumerable: true,
371
- get: function () { return chunkCS6JTQQ2_cjs.InterchangeIdentityAssertionSchema; }
373
+ get: function () { return chunkKACEYDYV_cjs.InterchangeIdentityAssertionSchema; }
372
374
  });
373
375
  Object.defineProperty(exports, "InterchangeIdentitySchema", {
374
376
  enumerable: true,
375
- get: function () { return chunkCS6JTQQ2_cjs.InterchangeIdentitySchema; }
377
+ get: function () { return chunkKACEYDYV_cjs.InterchangeIdentitySchema; }
376
378
  });
377
379
  Object.defineProperty(exports, "InterchangeNodeSchema", {
378
380
  enumerable: true,
379
- get: function () { return chunkCS6JTQQ2_cjs.InterchangeNodeSchema; }
381
+ get: function () { return chunkKACEYDYV_cjs.InterchangeNodeSchema; }
380
382
  });
381
383
  Object.defineProperty(exports, "UnknownPropertyStrategySchema", {
382
384
  enumerable: true,
383
- get: function () { return chunkCS6JTQQ2_cjs.UnknownPropertyStrategySchema; }
385
+ get: function () { return chunkKACEYDYV_cjs.UnknownPropertyStrategySchema; }
384
386
  });
385
387
  Object.defineProperty(exports, "exportGraph", {
386
388
  enumerable: true,
387
- get: function () { return chunkCS6JTQQ2_cjs.exportGraph; }
389
+ get: function () { return chunkKACEYDYV_cjs.exportGraph; }
388
390
  });
389
391
  Object.defineProperty(exports, "exportGraphStream", {
390
392
  enumerable: true,
391
- get: function () { return chunkCS6JTQQ2_cjs.exportGraphStream; }
393
+ get: function () { return chunkKACEYDYV_cjs.exportGraphStream; }
392
394
  });
393
395
  Object.defineProperty(exports, "importGraph", {
394
396
  enumerable: true,
395
- get: function () { return chunkCS6JTQQ2_cjs.importGraph; }
397
+ get: function () { return chunkKACEYDYV_cjs.importGraph; }
396
398
  });
397
399
  Object.defineProperty(exports, "importGraphStream", {
398
400
  enumerable: true,
399
- get: function () { return chunkCS6JTQQ2_cjs.importGraphStream; }
401
+ get: function () { return chunkKACEYDYV_cjs.importGraphStream; }
400
402
  });
401
403
  exports.trustedImportGraph = trustedImportGraph;
402
404
  exports.trustedImportGraphStream = trustedImportGraphStream;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/interchange/trusted-import.ts"],"names":["TrustedImportError","getSearchableFields","resolveGraphVectorSlots","isCanonicalIsoDate","isInvertedValidityWindow","storeBackend","exportStreamBackend","snapshotExportContention","serializedStreamRefusal","withImportStreamLease"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAS,+BACP,KAAA,EACM;AACN,EAAA,IAAI,MAAM,cAAA,EAAgB;AACxB,IAAA,MAAM,IAAIA,oCAAA;AAAA,MACR,gEAAA;AAAA,MACA,qBAAA;AAAA,MACA,EAAE,OAAA,EAAS,KAAA,CAAM,OAAA;AAAQ,KAC3B;AAAA,EACF;AACA,EAAA,IAAI,MAAM,uBAAA,EAAyB;AACjC,IAAA,MAAM,IAAIA,oCAAA;AAAA,MACR,oDAAA;AAAA,MACA,+BAAA;AAAA,MACA,EAAE,OAAA,EAAS,KAAA,CAAM,OAAA;AAAQ,KAC3B;AAAA,EACF;AACA,EAAA,IAAI,KAAA,CAAM,KAAA,CAAM,QAAA,KAAa,MAAA,EAAW;AACtC,IAAA,MAAM,IAAIA,oCAAA;AAAA,MACR,8EAAA;AAAA,MACA,sBAAA;AAAA,MACA,EAAE,OAAA,EAAS,KAAA,CAAM,OAAA;AAAQ,KAC3B;AAAA,EACF;AAEA,EAAA,MAAM,WAAA,GAAc,OAAO,MAAA,CAAO,KAAA,CAAM,MAAM,KAAK,CAAA,CAChD,OAAO,CAAC,YAAA,KAAA,CAAkB,aAAa,MAAA,EAAQ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EJ,EAAA,OAAOC,uCAAA;AAAA,IAAsB,KAAA;AAAA,IAAO,MAClC,aAAA;AAAA,MACE,CAAC,OAAA,KAAY,oBAAA,CAAqB,KAAA,EAAO,SAAS,MAAM,CAAA;AAAA,MACxD;AAAA;AACF,GACF;AACF;AAEA,UAAU,gBAAgB,IAAA,EAAkD;AAC1E,EAAA,MAAM,EAAE,KAAA,EAAO,KAAA,EAAO,QAAA,EAAU,GAAG,QAAO,GAAI,IAAA;AAC9C,EAAA,MAAM;AAAA,IACJ,IAAA,EAAM,QAAA;AAAA,IACN,MAAA,EACE,QAAA,KAAa,MAAA,GAAY,MAAA,GACvB;AAAA,MACE,GAAG,MAAA;AAAA,MACH,UAAU,EAAE,OAAA,EAAS,SAAS,OAAA,EAAS,IAAA,EAAM,SAAS,IAAA;AAAK;AAC7D,GAEN;AACA,EAAA,MAAM,EAAE,IAAA,EAAM,OAAA,EAAS,KAAA,EAAM;AAC7B,EAAA,MAAM,EAAE,IAAA,EAAM,OAAA,EAAS,KAAA,EAAM;AAC7B,EAAA,IAAI,aAAa,MAAA,EAAW;AAC1B,IAAA,MAAM,EAAE,IAAA,EAAM,UAAA,EAAY,UAAA,EAAY,SAAS,UAAA,EAAW;AAAA,EAC5D;AACF;AAGO,SAAS,kBAAA,CACd,OACA,IAAA,EAC8B;AAC9B,EAAA,OAAO,wBAAA,CAAyB,KAAA,EAAO,eAAA,CAAgB,IAAI,CAAC,CAAA;AAC9D","file":"index.cjs","sourcesContent":["import { snapshotExportContention } from \"../backend/transaction-resource\";\nimport type {\n InsertEdgeParams,\n InsertNodeParams,\n TrustedImportOptions,\n TrustedImportSession,\n} from \"../backend/types\";\nimport type { GraphDef } from \"../core/define-graph\";\nimport { resolveGraphVectorSlots } from \"../core/embedding\";\nimport { getSearchableFields } from \"../core/searchable\";\nimport { TrustedImportError } from \"../errors\";\nimport { storeBackend } from \"../store/runtime-port\";\nimport type { Store } from \"../store/store\";\nimport { isCanonicalIsoDate, isInvertedValidityWindow } from \"../utils/date\";\nimport { serializedStreamRefusal, withImportStreamLease } from \"./import\";\nimport { exportStreamBackend } from \"./stream-source\";\nimport type {\n GraphData,\n GraphInterchangeChunk,\n InterchangeEdge,\n InterchangeNode,\n} from \"./types\";\n\n/** Counts committed by a trusted initial import. */\nexport type TrustedImportResult = Readonly<{\n nodes: number;\n edges: number;\n}>;\n\nfunction rejectUnsupportedStoreFeatures<G extends GraphDef>(\n store: Store<G>,\n): void {\n if (store.historyEnabled) {\n throw new TrustedImportError(\n \"Trusted import does not support recorded-time history capture.\",\n \"history_unsupported\",\n { graphId: store.graphId },\n );\n }\n if (store.revisionTrackingEnabled) {\n throw new TrustedImportError(\n \"Trusted import does not support revision tracking.\",\n \"revision_tracking_unsupported\",\n { graphId: store.graphId },\n );\n }\n if (store.graph.identity !== undefined) {\n throw new TrustedImportError(\n \"Trusted import does not maintain Operational Identity assertions or closure.\",\n \"identity_unsupported\",\n { graphId: store.graphId },\n );\n }\n\n const uniqueKinds = Object.values(store.graph.nodes)\n .filter((registration) => (registration.unique?.length ?? 0) > 0)\n .map((registration) => registration.type.kind);\n if (uniqueKinds.length > 0) {\n throw new TrustedImportError(\n \"Trusted import does not maintain node uniqueness sidecars.\",\n \"uniqueness_unsupported\",\n { graphId: store.graphId, nodeKinds: uniqueKinds },\n );\n }\n\n const searchableKinds = Object.values(store.graph.nodes)\n .filter(\n (registration) =>\n getSearchableFields(registration.type.schema).length > 0,\n )\n .map((registration) => registration.type.kind);\n if (searchableKinds.length > 0) {\n throw new TrustedImportError(\n \"Trusted import does not maintain fulltext sidecars.\",\n \"fulltext_unsupported\",\n { graphId: store.graphId, nodeKinds: searchableKinds },\n );\n }\n\n const vectorSlots = resolveGraphVectorSlots(store.graph);\n if (vectorSlots.length > 0) {\n throw new TrustedImportError(\n \"Trusted import does not maintain vector sidecars.\",\n \"vector_unsupported\",\n {\n graphId: store.graphId,\n fields: vectorSlots.map((slot) => `${slot.nodeKind}.${slot.fieldPath}`),\n },\n );\n }\n}\n\nfunction invalidStream(message: string): TrustedImportError {\n return new TrustedImportError(message, \"invalid_stream\");\n}\n\n/** The stated validity window of a streamed node or edge. */\ntype StatedValidityWindow = Readonly<{\n validFrom?: string | null | undefined;\n validTo?: string | undefined;\n}>;\n\ntype ValidityWindowField = \"validFrom\" | \"validTo\";\n\n/** A stated window field that is not canonical, with the offending value. */\ntype NonCanonicalWindow = Readonly<{\n field: ValidityWindowField;\n value: string;\n}>;\n\n/**\n * The first window field of `entity` stating a timestamp that is not canonical\n * fixed-width UTC ISO 8601 — with the offending value — or `undefined` when\n * every stated one is canonical.\n *\n * A trusted stream is never re-parsed, so this is the only place its timestamps\n * are held to the format the rest of the system assumes. It is deliberately\n * format-ONLY — the same {@link isCanonicalIsoDate} decision the untrusted\n * path's schema and the store's own write validation make, and nothing more —\n * because a non-canonical instant is not merely ugly: every temporal filter\n * compares these values AS TEXT against an `asOf` coordinate, so a variable-width\n * one (`...:00.1Z`, an offset, date-only) mis-sorts and silently includes or\n * excludes the wrong rows once stored, and it would mis-decide the negative-width\n * check below on the way in. Two field tests per row costs about a microsecond\n * against the ~4µs an in-memory SQLite row already costs — the price of the\n * stream's ordering claims meaning anything.\n *\n * An absent field states nothing, and a `null` validFrom is a confirmed\n * open-left window (see {@link nodeParams}) — neither is a timestamp to check.\n */\nfunction nonCanonicalWindowOf(\n entity: StatedValidityWindow,\n): NonCanonicalWindow | undefined {\n const { validFrom, validTo } = entity;\n if (typeof validFrom === \"string\" && !isCanonicalIsoDate(validFrom)) {\n return { field: \"validFrom\", value: validFrom };\n }\n if (typeof validTo === \"string\" && !isCanonicalIsoDate(validTo)) {\n return { field: \"validTo\", value: validTo };\n }\n return undefined;\n}\n\n/**\n * The first entity in `entities` stating a non-canonical window timestamp, with\n * the offending field and value. Allocates only on the failing path, so a clean\n * chunk pays one predicate per stated timestamp and nothing else.\n */\nfunction findNonCanonicalWindow<Entity extends StatedValidityWindow>(\n entities: readonly Entity[],\n): (NonCanonicalWindow & Readonly<{ entity: Entity }>) | undefined {\n for (const entity of entities) {\n const nonCanonical = nonCanonicalWindowOf(entity);\n if (nonCanonical !== undefined) return { entity, ...nonCanonical };\n }\n return undefined;\n}\n\n/** The refusal message for a non-canonical window timestamp on `subject`. */\nfunction nonCanonicalWindowMessage(\n subject: string,\n field: ValidityWindowField,\n value: string,\n): string {\n return (\n `Non-canonical ${field} in trusted import: ${subject} states \"${value}\". ` +\n `Expected canonical fixed-width UTC ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ), ` +\n `which is what makes a stored timestamp sort chronologically against an asOf ` +\n `coordinate. Convert with new Date(value).toISOString().`\n );\n}\n\n/**\n * An entity whose stated window has negative width. Trusted import writes\n * straight to SQL and skips schema validation for throughput, but a row that\n * stopped being true before it started is a stream SHAPE fault rather than a\n * policy check: it is unobservable at every `asOf` coordinate, and no later\n * write repairs it. `null` validFrom is a confirmed open-left window, so there\n * is no lower bound to invert against; zero width is legal (see\n * {@link isInvertedValidityWindow}).\n *\n * Only ever reached for a chunk whose timestamps {@link findNonCanonicalWindow}\n * has already accepted, which is what makes the lexicographic compare inside a\n * chronological one.\n */\nfunction hasInvertedWindow(entity: StatedValidityWindow): boolean {\n return isInvertedValidityWindow(\n entity.validFrom ?? undefined,\n entity.validTo,\n );\n}\n\nfunction nodeParams(graphId: string, node: InterchangeNode): InsertNodeParams {\n return {\n graphId,\n kind: node.kind,\n id: node.id,\n props: node.properties,\n ...(node.validFrom === undefined ? {} : { validFrom: node.validFrom }),\n ...(node.validTo === undefined ? {} : { validTo: node.validTo }),\n };\n}\n\nfunction edgeParams(graphId: string, edge: InterchangeEdge): InsertEdgeParams {\n return {\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: edge.properties,\n ...(edge.validFrom === undefined ? {} : { validFrom: edge.validFrom }),\n ...(edge.validTo === undefined ? {} : { validTo: edge.validTo }),\n };\n}\n\nasync function consumeTrustedChunks<G extends GraphDef>(\n store: Store<G>,\n session: TrustedImportSession,\n chunks:\n AsyncIterable<GraphInterchangeChunk> | Iterable<GraphInterchangeChunk>,\n): Promise<TrustedImportResult> {\n const nodeKinds = new Set(\n Object.values(store.graph.nodes).map(\n (registration) => registration.type.kind,\n ),\n );\n const edgeKinds = new Set(\n Object.values(store.graph.edges).map(\n (registration) => registration.type.kind,\n ),\n );\n let receivedHeader = false;\n let receivedEdges = false;\n let nodeCount = 0;\n let edgeCount = 0;\n\n for await (const chunk of chunks) {\n switch (chunk.type) {\n case \"header\": {\n if (receivedHeader) {\n throw invalidStream(\n \"Trusted graph interchange stream emitted more than one header.\",\n );\n }\n if (chunk.header.identity !== undefined) {\n throw invalidStream(\n \"Trusted graph interchange import does not support identity data. \" +\n \"Use importGraphStream() for an identity export.\",\n );\n }\n receivedHeader = true;\n break;\n }\n case \"nodes\": {\n if (!receivedHeader) {\n throw invalidStream(\n \"Trusted graph interchange stream must start with a header.\",\n );\n }\n if (receivedEdges) {\n throw invalidStream(\n \"Trusted graph interchange stream cannot emit nodes after edges.\",\n );\n }\n const unknownKind = chunk.nodes.find(\n (node) => !nodeKinds.has(node.kind),\n )?.kind;\n if (unknownKind !== undefined) {\n throw invalidStream(\n `Unknown node kind in trusted import: ${unknownKind}`,\n );\n }\n const nonCanonicalNode = findNonCanonicalWindow(chunk.nodes);\n if (nonCanonicalNode !== undefined) {\n const { entity, field, value } = nonCanonicalNode;\n throw invalidStream(\n nonCanonicalWindowMessage(\n `${entity.kind} \"${entity.id}\"`,\n field,\n value,\n ),\n );\n }\n const invertedNode = chunk.nodes.find((node) =>\n hasInvertedWindow(node),\n );\n if (invertedNode !== undefined) {\n throw invalidStream(\n `Inverted validity window in trusted import: ${invertedNode.kind} \"${invertedNode.id}\" ends at ` +\n `\"${String(invertedNode.validTo)}\", before its validFrom \"${String(invertedNode.validFrom)}\".`,\n );\n }\n await session.insertNodes(\n chunk.nodes.map((node) => nodeParams(store.graphId, node)),\n );\n nodeCount += chunk.nodes.length;\n break;\n }\n case \"edges\": {\n if (!receivedHeader) {\n throw invalidStream(\n \"Trusted graph interchange stream must start with a header.\",\n );\n }\n receivedEdges = true;\n const invalidEdge = chunk.edges.find(\n (edge) =>\n !edgeKinds.has(edge.kind) ||\n !nodeKinds.has(edge.from.kind) ||\n !nodeKinds.has(edge.to.kind),\n );\n if (invalidEdge !== undefined) {\n throw invalidStream(\n `Unknown edge or endpoint kind in trusted import: ${invalidEdge.kind}`,\n );\n }\n const nonCanonicalEdge = findNonCanonicalWindow(chunk.edges);\n if (nonCanonicalEdge !== undefined) {\n const { entity, field, value } = nonCanonicalEdge;\n throw invalidStream(\n nonCanonicalWindowMessage(\n `${entity.kind} edge \"${entity.id}\"`,\n field,\n value,\n ),\n );\n }\n const invertedEdge = chunk.edges.find((edge) =>\n hasInvertedWindow(edge),\n );\n if (invertedEdge !== undefined) {\n throw invalidStream(\n `Inverted validity window in trusted import: ${invertedEdge.kind} edge \"${invertedEdge.id}\" ends at ` +\n `\"${String(invertedEdge.validTo)}\", before its validFrom \"${String(invertedEdge.validFrom)}\".`,\n );\n }\n await session.insertEdges(\n chunk.edges.map((edge) => edgeParams(store.graphId, edge)),\n );\n edgeCount += chunk.edges.length;\n break;\n }\n case \"identity\": {\n // The trusted session writes only the node and edge relations, so it\n // has no way to persist assertions or materialize the derived closure.\n // Refuse rather than drop identity truth from an identity-enabled\n // export: `importGraph` / `importGraphStream` carry it correctly.\n throw invalidStream(\n \"Trusted graph interchange import does not support identity assertions. \" +\n \"Use importGraphStream() for an export that carries identity truth.\",\n );\n }\n }\n }\n\n if (!receivedHeader) {\n throw invalidStream(\n \"Trusted graph interchange stream ended before emitting a header.\",\n );\n }\n return { nodes: nodeCount, edges: edgeCount };\n}\n\n/**\n * Atomically imports a header-first stream into a fresh, dedicated database.\n *\n * This is an intentionally trusted path. It checks stream ordering and kind\n * names, but it does not validate properties, references, cardinality, or\n * conflicts. The caller must guarantee those invariants. Use\n * {@link importGraphStream} for untrusted data.\n *\n * Trusted of the DATA, not of the connection: this holds ONE write transaction\n * open for the entire stream, which makes it a long-lived import holder exactly\n * like {@link importGraphStream}, and it is guarded the same way — the source\n * stream's own backend is checked against the target before the first chunk, and\n * the target connection's exclusive stream lease is held for the whole import.\n * `trustedImportGraphStream(target, exportGraphStream(source))` over one\n * serialized connection is therefore refused with the shared typed\n * {@link ConfigurationError} (codes and `details.heldBy` / `details.requested`\n * as documented on `importGraphStream`) rather than reaching the driver as a\n * nested BEGIN.\n */\nexport async function trustedImportGraphStream<G extends GraphDef>(\n store: Store<G>,\n chunks:\n AsyncIterable<GraphInterchangeChunk> | Iterable<GraphInterchangeChunk>,\n): Promise<TrustedImportResult> {\n rejectUnsupportedStoreFeatures(store);\n const backend = storeBackend(store);\n const trustedImport = backend.trustedImport;\n if (trustedImport === undefined) {\n throw new TrustedImportError(\n `The ${backend.dialect} backend does not support trusted import.`,\n \"backend_unsupported\",\n { dialect: backend.dialect },\n );\n }\n // The same pre-flight `importGraphStream` runs, through the same owner of\n // \"would this export hold the connection that write needs\": a synchronous\n // iterable was materialized by its producer and holds nothing, so only an\n // async stream can name a source backend.\n const sourceBackend =\n Symbol.asyncIterator in chunks ? exportStreamBackend(chunks) : undefined;\n const contention =\n sourceBackend === undefined ? undefined : (\n snapshotExportContention(sourceBackend, backend)\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 schemaVersion = store.introspect().schemaVersion;\n const options: TrustedImportOptions | undefined =\n schemaVersion === undefined ? undefined : (\n {\n schemaWrite: {\n graphId: store.graphId,\n expectedVersion: schemaVersion,\n },\n }\n );\n return withImportStreamLease(store, () =>\n trustedImport(\n (session) => consumeTrustedChunks(store, session, chunks),\n options,\n ),\n );\n}\n\nfunction* graphDataChunks(data: GraphData): Iterable<GraphInterchangeChunk> {\n const { nodes, edges, identity, ...header } = data;\n yield {\n type: \"header\",\n header:\n identity === undefined ? header : (\n {\n ...header,\n identity: { profile: identity.profile, mode: identity.mode },\n }\n ),\n };\n yield { type: \"nodes\", nodes };\n yield { type: \"edges\", edges };\n if (identity !== undefined) {\n yield { type: \"identity\", assertions: identity.assertions };\n }\n}\n\n/** In-memory convenience wrapper around {@link trustedImportGraphStream}. */\nexport function trustedImportGraph<G extends GraphDef>(\n store: Store<G>,\n data: GraphData,\n): Promise<TrustedImportResult> {\n return trustedImportGraphStream(store, graphDataChunks(data));\n}\n"]}
1
+ {"version":3,"sources":["../../src/interchange/trusted-import.ts"],"names":["TrustedImportError","getSearchableFields","resolveGraphVectorSlots","isCanonicalIsoDate","isInvertedValidityWindow","storeBackend","exportStreamBackend","snapshotExportContention","serializedStreamRefusal","withImportStreamLease"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAS,+BACP,KAAA,EACM;AACN,EAAA,IAAI,MAAM,cAAA,EAAgB;AACxB,IAAA,MAAM,IAAIA,oCAAA;AAAA,MACR,gEAAA;AAAA,MACA,qBAAA;AAAA,MACA,EAAE,OAAA,EAAS,KAAA,CAAM,OAAA;AAAQ,KAC3B;AAAA,EACF;AACA,EAAA,IAAI,MAAM,uBAAA,EAAyB;AACjC,IAAA,MAAM,IAAIA,oCAAA;AAAA,MACR,oDAAA;AAAA,MACA,+BAAA;AAAA,MACA,EAAE,OAAA,EAAS,KAAA,CAAM,OAAA;AAAQ,KAC3B;AAAA,EACF;AACA,EAAA,IAAI,KAAA,CAAM,KAAA,CAAM,QAAA,KAAa,MAAA,EAAW;AACtC,IAAA,MAAM,IAAIA,oCAAA;AAAA,MACR,8EAAA;AAAA,MACA,sBAAA;AAAA,MACA,EAAE,OAAA,EAAS,KAAA,CAAM,OAAA;AAAQ,KAC3B;AAAA,EACF;AAEA,EAAA,MAAM,WAAA,GAAc,OAAO,MAAA,CAAO,KAAA,CAAM,MAAM,KAAK,CAAA,CAChD,OAAO,CAAC,YAAA,KAAA,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AiB;AAAA;AACnB,GACF;AAEJ,EAAA,OAAOC,uCAAA;AAAA,IAAsB,KAAA;AAAA,IAAO,MAClC,aAAA;AAAA,MACE,CAAC,OAAA,KAAY,oBAAA,CAAqB,KAAA,EAAO,SAAS,MAAM,CAAA;AAAA,MACxD;AAAA;AACF,GACF;AACF;AAEA,UAAU,gBAAgB,IAAA,EAAkD;AAC1E,EAAA,MAAM,EAAE,KAAA,EAAO,KAAA,EAAO,QAAA,EAAU,GAAG,QAAO,GAAI,IAAA;AAC9C,EAAA,MAAM;AAAA,IACJ,IAAA,EAAM,QAAA;AAAA,IACN,MAAA,EACE,QAAA,KAAa,MAAA,GAAY,MAAA,GACvB;AAAA,MACE,GAAG,MAAA;AAAA,MACH,UAAU,EAAE,OAAA,EAAS,SAAS,OAAA,EAAS,IAAA,EAAM,SAAS,IAAA;AAAK;AAC7D,GAEN;AACA,EAAA,MAAM,EAAE,IAAA,EAAM,OAAA,EAAS,KAAA,EAAM;AAC7B,EAAA,MAAM,EAAE,IAAA,EAAM,OAAA,EAAS,KAAA,EAAM;AAC7B,EAAA,IAAI,aAAa,MAAA,EAAW;AAC1B,IAAA,MAAM,EAAE,IAAA,EAAM,UAAA,EAAY,UAAA,EAAY,SAAS,UAAA,EAAW;AAAA,EAC5D;AACF;AAGO,SAAS,kBAAA,CACd,OACA,IAAA,EAC8B;AAC9B,EAAA,OAAO,wBAAA,CAAyB,KAAA,EAAO,eAAA,CAAgB,IAAI,CAAC,CAAA;AAC9D","file":"index.cjs","sourcesContent":["import { snapshotExportContention } from \"../backend/transaction-resource\";\nimport type {\n InsertEdgeParams,\n InsertNodeParams,\n TrustedImportOptions,\n TrustedImportSession,\n} from \"../backend/types\";\nimport type { GraphDef } from \"../core/define-graph\";\nimport { resolveGraphVectorSlots } from \"../core/embedding\";\nimport { getSearchableFields } from \"../core/searchable\";\nimport { TrustedImportError } from \"../errors\";\nimport { storeBackend } from \"../store/runtime-port\";\nimport type { Store } from \"../store/store\";\nimport { isCanonicalIsoDate, isInvertedValidityWindow } from \"../utils/date\";\nimport { serializedStreamRefusal, withImportStreamLease } from \"./import\";\nimport { exportStreamBackend } from \"./stream-source\";\nimport type {\n GraphData,\n GraphInterchangeChunk,\n InterchangeEdge,\n InterchangeNode,\n} from \"./types\";\n\n/** Counts committed by a trusted initial import. */\nexport type TrustedImportResult = Readonly<{\n nodes: number;\n edges: number;\n}>;\n\nfunction rejectUnsupportedStoreFeatures<G extends GraphDef>(\n store: Store<G>,\n): void {\n if (store.historyEnabled) {\n throw new TrustedImportError(\n \"Trusted import does not support recorded-time history capture.\",\n \"history_unsupported\",\n { graphId: store.graphId },\n );\n }\n if (store.revisionTrackingEnabled) {\n throw new TrustedImportError(\n \"Trusted import does not support revision tracking.\",\n \"revision_tracking_unsupported\",\n { graphId: store.graphId },\n );\n }\n if (store.graph.identity !== undefined) {\n throw new TrustedImportError(\n \"Trusted import does not maintain Operational Identity assertions or closure.\",\n \"identity_unsupported\",\n { graphId: store.graphId },\n );\n }\n\n const uniqueKinds = Object.values(store.graph.nodes)\n .filter((registration) => (registration.unique?.length ?? 0) > 0)\n .map((registration) => registration.type.kind);\n if (uniqueKinds.length > 0) {\n throw new TrustedImportError(\n \"Trusted import does not maintain node uniqueness sidecars.\",\n \"uniqueness_unsupported\",\n { graphId: store.graphId, nodeKinds: uniqueKinds },\n );\n }\n\n const searchableKinds = Object.values(store.graph.nodes)\n .filter(\n (registration) =>\n getSearchableFields(registration.type.schema).length > 0,\n )\n .map((registration) => registration.type.kind);\n if (searchableKinds.length > 0) {\n throw new TrustedImportError(\n \"Trusted import does not maintain fulltext sidecars.\",\n \"fulltext_unsupported\",\n { graphId: store.graphId, nodeKinds: searchableKinds },\n );\n }\n\n const vectorSlots = resolveGraphVectorSlots(store.graph);\n if (vectorSlots.length > 0) {\n throw new TrustedImportError(\n \"Trusted import does not maintain vector sidecars.\",\n \"vector_unsupported\",\n {\n graphId: store.graphId,\n fields: vectorSlots.map((slot) => `${slot.nodeKind}.${slot.fieldPath}`),\n },\n );\n }\n}\n\nfunction invalidStream(message: string): TrustedImportError {\n return new TrustedImportError(message, \"invalid_stream\");\n}\n\n/** The stated validity window of a streamed node or edge. */\ntype StatedValidityWindow = Readonly<{\n validFrom?: string | null | undefined;\n validTo?: string | undefined;\n}>;\n\ntype ValidityWindowField = \"validFrom\" | \"validTo\";\n\n/** A stated window field that is not canonical, with the offending value. */\ntype NonCanonicalWindow = Readonly<{\n field: ValidityWindowField;\n value: string;\n}>;\n\n/**\n * The first window field of `entity` stating a timestamp that is not canonical\n * fixed-width UTC ISO 8601 — with the offending value — or `undefined` when\n * every stated one is canonical.\n *\n * A trusted stream is never re-parsed, so this is the only place its timestamps\n * are held to the format the rest of the system assumes. It is deliberately\n * format-ONLY — the same {@link isCanonicalIsoDate} decision the untrusted\n * path's schema and the store's own write validation make, and nothing more —\n * because a non-canonical instant is not merely ugly: every temporal filter\n * compares these values AS TEXT against an `asOf` coordinate, so a variable-width\n * one (`...:00.1Z`, an offset, date-only) mis-sorts and silently includes or\n * excludes the wrong rows once stored, and it would mis-decide the negative-width\n * check below on the way in. Two field tests per row costs about a microsecond\n * against the ~4µs an in-memory SQLite row already costs — the price of the\n * stream's ordering claims meaning anything.\n *\n * An absent field states nothing, and a `null` validFrom is a confirmed\n * open-left window (see {@link nodeParams}) — neither is a timestamp to check.\n */\nfunction nonCanonicalWindowOf(\n entity: StatedValidityWindow,\n): NonCanonicalWindow | undefined {\n const { validFrom, validTo } = entity;\n if (typeof validFrom === \"string\" && !isCanonicalIsoDate(validFrom)) {\n return { field: \"validFrom\", value: validFrom };\n }\n if (typeof validTo === \"string\" && !isCanonicalIsoDate(validTo)) {\n return { field: \"validTo\", value: validTo };\n }\n return undefined;\n}\n\n/**\n * The first entity in `entities` stating a non-canonical window timestamp, with\n * the offending field and value. Allocates only on the failing path, so a clean\n * chunk pays one predicate per stated timestamp and nothing else.\n */\nfunction findNonCanonicalWindow<Entity extends StatedValidityWindow>(\n entities: readonly Entity[],\n): (NonCanonicalWindow & Readonly<{ entity: Entity }>) | undefined {\n for (const entity of entities) {\n const nonCanonical = nonCanonicalWindowOf(entity);\n if (nonCanonical !== undefined) return { entity, ...nonCanonical };\n }\n return undefined;\n}\n\n/** The refusal message for a non-canonical window timestamp on `subject`. */\nfunction nonCanonicalWindowMessage(\n subject: string,\n field: ValidityWindowField,\n value: string,\n): string {\n return (\n `Non-canonical ${field} in trusted import: ${subject} states \"${value}\". ` +\n `Expected canonical fixed-width UTC ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ), ` +\n `which is what makes a stored timestamp sort chronologically against an asOf ` +\n `coordinate. Convert with new Date(value).toISOString().`\n );\n}\n\n/**\n * An entity whose stated window has negative width. Trusted import writes\n * straight to SQL and skips schema validation for throughput, but a row that\n * stopped being true before it started is a stream SHAPE fault rather than a\n * policy check: it is unobservable at every `asOf` coordinate, and no later\n * write repairs it. `null` validFrom is a confirmed open-left window, so there\n * is no lower bound to invert against; zero width is legal (see\n * {@link isInvertedValidityWindow}).\n *\n * Only ever reached for a chunk whose timestamps {@link findNonCanonicalWindow}\n * has already accepted, which is what makes the lexicographic compare inside a\n * chronological one.\n */\nfunction hasInvertedWindow(entity: StatedValidityWindow): boolean {\n return isInvertedValidityWindow(\n entity.validFrom ?? undefined,\n entity.validTo,\n );\n}\n\nfunction nodeParams(graphId: string, node: InterchangeNode): InsertNodeParams {\n return {\n graphId,\n kind: node.kind,\n id: node.id,\n props: node.properties,\n ...(node.validFrom === undefined ? {} : { validFrom: node.validFrom }),\n ...(node.validTo === undefined ? {} : { validTo: node.validTo }),\n };\n}\n\nfunction edgeParams(graphId: string, edge: InterchangeEdge): InsertEdgeParams {\n return {\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: edge.properties,\n ...(edge.validFrom === undefined ? {} : { validFrom: edge.validFrom }),\n ...(edge.validTo === undefined ? {} : { validTo: edge.validTo }),\n };\n}\n\nasync function consumeTrustedChunks<G extends GraphDef>(\n store: Store<G>,\n session: TrustedImportSession,\n chunks:\n AsyncIterable<GraphInterchangeChunk> | Iterable<GraphInterchangeChunk>,\n): Promise<TrustedImportResult> {\n const nodeKinds = new Set(\n Object.values(store.graph.nodes).map(\n (registration) => registration.type.kind,\n ),\n );\n const edgeKinds = new Set(\n Object.values(store.graph.edges).map(\n (registration) => registration.type.kind,\n ),\n );\n let receivedHeader = false;\n let receivedEdges = false;\n let nodeCount = 0;\n let edgeCount = 0;\n\n for await (const chunk of chunks) {\n switch (chunk.type) {\n case \"header\": {\n if (receivedHeader) {\n throw invalidStream(\n \"Trusted graph interchange stream emitted more than one header.\",\n );\n }\n if (chunk.header.identity !== undefined) {\n throw invalidStream(\n \"Trusted graph interchange import does not support identity data. \" +\n \"Use importGraphStream() for an identity export.\",\n );\n }\n receivedHeader = true;\n break;\n }\n case \"nodes\": {\n if (!receivedHeader) {\n throw invalidStream(\n \"Trusted graph interchange stream must start with a header.\",\n );\n }\n if (receivedEdges) {\n throw invalidStream(\n \"Trusted graph interchange stream cannot emit nodes after edges.\",\n );\n }\n const unknownKind = chunk.nodes.find(\n (node) => !nodeKinds.has(node.kind),\n )?.kind;\n if (unknownKind !== undefined) {\n throw invalidStream(\n `Unknown node kind in trusted import: ${unknownKind}`,\n );\n }\n const nonCanonicalNode = findNonCanonicalWindow(chunk.nodes);\n if (nonCanonicalNode !== undefined) {\n const { entity, field, value } = nonCanonicalNode;\n throw invalidStream(\n nonCanonicalWindowMessage(\n `${entity.kind} \"${entity.id}\"`,\n field,\n value,\n ),\n );\n }\n const invertedNode = chunk.nodes.find((node) =>\n hasInvertedWindow(node),\n );\n if (invertedNode !== undefined) {\n throw invalidStream(\n `Inverted validity window in trusted import: ${invertedNode.kind} \"${invertedNode.id}\" ends at ` +\n `\"${String(invertedNode.validTo)}\", before its validFrom \"${String(invertedNode.validFrom)}\".`,\n );\n }\n await session.insertNodes(\n chunk.nodes.map((node) => nodeParams(store.graphId, node)),\n );\n nodeCount += chunk.nodes.length;\n break;\n }\n case \"edges\": {\n if (!receivedHeader) {\n throw invalidStream(\n \"Trusted graph interchange stream must start with a header.\",\n );\n }\n receivedEdges = true;\n const invalidEdge = chunk.edges.find(\n (edge) =>\n !edgeKinds.has(edge.kind) ||\n !nodeKinds.has(edge.from.kind) ||\n !nodeKinds.has(edge.to.kind),\n );\n if (invalidEdge !== undefined) {\n throw invalidStream(\n `Unknown edge or endpoint kind in trusted import: ${invalidEdge.kind}`,\n );\n }\n const nonCanonicalEdge = findNonCanonicalWindow(chunk.edges);\n if (nonCanonicalEdge !== undefined) {\n const { entity, field, value } = nonCanonicalEdge;\n throw invalidStream(\n nonCanonicalWindowMessage(\n `${entity.kind} edge \"${entity.id}\"`,\n field,\n value,\n ),\n );\n }\n const invertedEdge = chunk.edges.find((edge) =>\n hasInvertedWindow(edge),\n );\n if (invertedEdge !== undefined) {\n throw invalidStream(\n `Inverted validity window in trusted import: ${invertedEdge.kind} edge \"${invertedEdge.id}\" ends at ` +\n `\"${String(invertedEdge.validTo)}\", before its validFrom \"${String(invertedEdge.validFrom)}\".`,\n );\n }\n await session.insertEdges(\n chunk.edges.map((edge) => edgeParams(store.graphId, edge)),\n );\n edgeCount += chunk.edges.length;\n break;\n }\n case \"identity\": {\n // The trusted session writes only the node and edge relations, so it\n // has no way to persist assertions or materialize the derived closure.\n // Refuse rather than drop identity truth from an identity-enabled\n // export: `importGraph` / `importGraphStream` carry it correctly.\n throw invalidStream(\n \"Trusted graph interchange import does not support identity assertions. \" +\n \"Use importGraphStream() for an export that carries identity truth.\",\n );\n }\n }\n }\n\n if (!receivedHeader) {\n throw invalidStream(\n \"Trusted graph interchange stream ended before emitting a header.\",\n );\n }\n return { nodes: nodeCount, edges: edgeCount };\n}\n\n/**\n * Atomically imports a header-first stream into a fresh, dedicated database.\n *\n * This is an intentionally trusted path. It checks stream ordering and kind\n * names, but it does not validate properties, references, cardinality, or\n * conflicts. The caller must guarantee those invariants. Use\n * {@link importGraphStream} for untrusted data.\n *\n * Trusted of the DATA, not of the connection: this holds ONE write transaction\n * open for the entire stream, which makes it a long-lived import holder exactly\n * like {@link importGraphStream}, and it is guarded the same way — the source\n * stream's own backend is checked against the target before the first chunk, and\n * the target connection's exclusive stream lease is held for the whole import.\n * `trustedImportGraphStream(target, exportGraphStream(source))` over one\n * serialized connection is therefore refused with the shared typed\n * {@link ConfigurationError} (codes and `details.heldBy` / `details.requested`\n * as documented on `importGraphStream`) rather than reaching the driver as a\n * nested BEGIN.\n */\nexport async function trustedImportGraphStream<G extends GraphDef>(\n store: Store<G>,\n chunks:\n AsyncIterable<GraphInterchangeChunk> | Iterable<GraphInterchangeChunk>,\n): Promise<TrustedImportResult> {\n rejectUnsupportedStoreFeatures(store);\n const backend = storeBackend(store);\n const trustedImport = backend.trustedImport;\n if (trustedImport === undefined) {\n throw new TrustedImportError(\n `The ${backend.dialect} backend does not support trusted import.`,\n \"backend_unsupported\",\n { dialect: backend.dialect },\n );\n }\n // The same pre-flight `importGraphStream` runs, through the same owner of\n // \"would this export hold the connection that write needs\": a synchronous\n // iterable was materialized by its producer and holds nothing, so only an\n // async stream can name a source backend.\n const sourceBackend =\n Symbol.asyncIterator in chunks ? exportStreamBackend(chunks) : undefined;\n const contention =\n sourceBackend === undefined ? undefined : (\n snapshotExportContention(sourceBackend, backend)\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 schemaVersion = store.introspect().schemaVersion;\n const options: TrustedImportOptions | undefined =\n schemaVersion === undefined ? undefined : (\n {\n schemaWrite: {\n graphId: store.graphId,\n expectedVersion: schemaVersion,\n },\n }\n );\n return withImportStreamLease(store, () =>\n trustedImport(\n (session) => consumeTrustedChunks(store, session, chunks),\n options,\n ),\n );\n}\n\nfunction* graphDataChunks(data: GraphData): Iterable<GraphInterchangeChunk> {\n const { nodes, edges, identity, ...header } = data;\n yield {\n type: \"header\",\n header:\n identity === undefined ? header : (\n {\n ...header,\n identity: { profile: identity.profile, mode: identity.mode },\n }\n ),\n };\n yield { type: \"nodes\", nodes };\n yield { type: \"edges\", edges };\n if (identity !== undefined) {\n yield { type: \"identity\", assertions: identity.assertions };\n }\n}\n\n/** In-memory convenience wrapper around {@link trustedImportGraphStream}. */\nexport function trustedImportGraph<G extends GraphDef>(\n store: Store<G>,\n data: GraphData,\n): Promise<TrustedImportResult> {\n return trustedImportGraphStream(store, graphDataChunks(data));\n}\n"]}