@nicia-ai/typegraph 0.33.0 → 0.35.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 (284) hide show
  1. package/README.md +20 -0
  2. package/dist/backend/postgres/index.cjs +30 -26
  3. package/dist/backend/postgres/index.d.cts +39 -7
  4. package/dist/backend/postgres/index.d.ts +39 -7
  5. package/dist/backend/postgres/index.js +17 -13
  6. package/dist/backend/postgres/pglite.cjs +22 -18
  7. package/dist/backend/postgres/pglite.cjs.map +1 -1
  8. package/dist/backend/postgres/pglite.d.cts +4 -4
  9. package/dist/backend/postgres/pglite.d.ts +4 -4
  10. package/dist/backend/postgres/pglite.js +17 -13
  11. package/dist/backend/postgres/pglite.js.map +1 -1
  12. package/dist/backend/sqlite/index.cjs +26 -23
  13. package/dist/backend/sqlite/index.d.cts +8 -8
  14. package/dist/backend/sqlite/index.d.ts +8 -8
  15. package/dist/backend/sqlite/index.js +14 -11
  16. package/dist/backend/sqlite/libsql.cjs +21 -17
  17. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  18. package/dist/backend/sqlite/libsql.d.cts +13 -6
  19. package/dist/backend/sqlite/libsql.d.ts +13 -6
  20. package/dist/backend/sqlite/libsql.js +17 -13
  21. package/dist/backend/sqlite/libsql.js.map +1 -1
  22. package/dist/backend/sqlite/local.cjs +102 -18
  23. package/dist/backend/sqlite/local.cjs.map +1 -1
  24. package/dist/backend/sqlite/local.d.cts +95 -5
  25. package/dist/backend/sqlite/local.d.ts +95 -5
  26. package/dist/backend/sqlite/local.js +96 -13
  27. package/dist/backend/sqlite/local.js.map +1 -1
  28. package/dist/{chunk-JHOBXD7O.js → chunk-3TWF3SH4.js} +332 -64
  29. package/dist/chunk-3TWF3SH4.js.map +1 -0
  30. package/dist/chunk-4JEZZJ6S.cjs +1271 -0
  31. package/dist/chunk-4JEZZJ6S.cjs.map +1 -0
  32. package/dist/{chunk-I4W7MKVG.cjs → chunk-4TOD4LBZ.cjs} +249 -294
  33. package/dist/chunk-4TOD4LBZ.cjs.map +1 -0
  34. package/dist/chunk-55MZDDZV.js +239 -0
  35. package/dist/chunk-55MZDDZV.js.map +1 -0
  36. package/dist/{chunk-LM2IC4ZJ.cjs → chunk-5A6FNS6N.cjs} +75 -19
  37. package/dist/chunk-5A6FNS6N.cjs.map +1 -0
  38. package/dist/{chunk-FDN43KXV.cjs → chunk-5AQIKK56.cjs} +65 -24
  39. package/dist/chunk-5AQIKK56.cjs.map +1 -0
  40. package/dist/{chunk-IZ4PCL47.js → chunk-5SEGFTZX.js} +4 -66
  41. package/dist/chunk-5SEGFTZX.js.map +1 -0
  42. package/dist/{chunk-CWFPJ3RC.js → chunk-6FR2MMS6.js} +7 -7
  43. package/dist/chunk-6FR2MMS6.js.map +1 -0
  44. package/dist/chunk-7YSP4V4R.cjs +69 -0
  45. package/dist/chunk-7YSP4V4R.cjs.map +1 -0
  46. package/dist/chunk-A42GCBGX.cjs +28 -0
  47. package/dist/chunk-A42GCBGX.cjs.map +1 -0
  48. package/dist/chunk-ACSVZPK7.cjs +21 -0
  49. package/dist/chunk-ACSVZPK7.cjs.map +1 -0
  50. package/dist/{chunk-OIE2UPVG.cjs → chunk-BLZDPRXT.cjs} +52 -21
  51. package/dist/chunk-BLZDPRXT.cjs.map +1 -0
  52. package/dist/chunk-BYPOGQWK.js +25 -0
  53. package/dist/chunk-BYPOGQWK.js.map +1 -0
  54. package/dist/{chunk-NG5N7R45.cjs → chunk-CK5BVQOW.cjs} +325 -213
  55. package/dist/chunk-CK5BVQOW.cjs.map +1 -0
  56. package/dist/chunk-CTTSDJLY.cjs +261 -0
  57. package/dist/chunk-CTTSDJLY.cjs.map +1 -0
  58. package/dist/chunk-CUHM5CWJ.cjs +12 -0
  59. package/dist/chunk-CUHM5CWJ.cjs.map +1 -0
  60. package/dist/chunk-CZQ3FO2Q.js +2320 -0
  61. package/dist/chunk-CZQ3FO2Q.js.map +1 -0
  62. package/dist/{chunk-CFNT3ITG.cjs → chunk-D7ZEOS56.cjs} +25 -52
  63. package/dist/chunk-D7ZEOS56.cjs.map +1 -0
  64. package/dist/chunk-DFVLCOP6.js +10 -0
  65. package/dist/chunk-DFVLCOP6.js.map +1 -0
  66. package/dist/chunk-DI74SMXS.cjs +29 -0
  67. package/dist/chunk-DI74SMXS.cjs.map +1 -0
  68. package/dist/{chunk-KY5SDVA7.cjs → chunk-EM3CWPND.cjs} +442 -113
  69. package/dist/chunk-EM3CWPND.cjs.map +1 -0
  70. package/dist/chunk-EMF62TZG.cjs +1176 -0
  71. package/dist/chunk-EMF62TZG.cjs.map +1 -0
  72. package/dist/chunk-EOLERH7Y.cjs +40 -0
  73. package/dist/chunk-EOLERH7Y.cjs.map +1 -0
  74. package/dist/{chunk-3QRBXYT5.cjs → chunk-FACJJWGF.cjs} +24 -6
  75. package/dist/chunk-FACJJWGF.cjs.map +1 -0
  76. package/dist/{chunk-KTIEB7VH.cjs → chunk-FL472AMI.cjs} +49 -165
  77. package/dist/chunk-FL472AMI.cjs.map +1 -0
  78. package/dist/{chunk-4RBAJVEC.cjs → chunk-FN35DLCN.cjs} +31 -9
  79. package/dist/chunk-FN35DLCN.cjs.map +1 -0
  80. package/dist/{chunk-C4C4Q7A6.js → chunk-FPIZFYHE.js} +12 -35
  81. package/dist/chunk-FPIZFYHE.js.map +1 -0
  82. package/dist/{chunk-XKNAK27R.js → chunk-FRV5Q5IO.js} +64 -8
  83. package/dist/chunk-FRV5Q5IO.js.map +1 -0
  84. package/dist/{chunk-K5P5OZXS.js → chunk-G6Q5UM7U.js} +2 -2
  85. package/dist/{chunk-K5P5OZXS.js.map → chunk-G6Q5UM7U.js.map} +1 -1
  86. package/dist/chunk-GSQ6NPH6.cjs +100 -0
  87. package/dist/chunk-GSQ6NPH6.cjs.map +1 -0
  88. package/dist/chunk-GUR2FNB5.cjs +12 -0
  89. package/dist/{chunk-6ZR4QC3O.cjs.map → chunk-GUR2FNB5.cjs.map} +1 -1
  90. package/dist/{chunk-ZFWNO3GE.cjs → chunk-H7YNSMA7.cjs} +107 -2
  91. package/dist/chunk-H7YNSMA7.cjs.map +1 -0
  92. package/dist/{chunk-GYVBEZAO.js → chunk-I7ZUZKFD.js} +47 -19
  93. package/dist/chunk-I7ZUZKFD.js.map +1 -0
  94. package/dist/chunk-ITE4IXAK.js +25 -0
  95. package/dist/chunk-ITE4IXAK.js.map +1 -0
  96. package/dist/{chunk-D3EWZ67S.cjs → chunk-J7WFGBJR.cjs} +3372 -4970
  97. package/dist/chunk-J7WFGBJR.cjs.map +1 -0
  98. package/dist/{chunk-PYD3UCDU.js → chunk-JBTOYDMN.js} +202 -251
  99. package/dist/chunk-JBTOYDMN.js.map +1 -0
  100. package/dist/{chunk-XVUJY72M.js → chunk-K3PPLHY7.js} +234 -118
  101. package/dist/chunk-K3PPLHY7.js.map +1 -0
  102. package/dist/{chunk-454I6GDF.js → chunk-KBGQIPRQ.js} +102 -3
  103. package/dist/chunk-KBGQIPRQ.js.map +1 -0
  104. package/dist/chunk-KMI7LYAF.js +1252 -0
  105. package/dist/chunk-KMI7LYAF.js.map +1 -0
  106. package/dist/{chunk-JIEJCTDS.cjs → chunk-LGEALRC6.cjs} +21 -4
  107. package/dist/chunk-LGEALRC6.cjs.map +1 -0
  108. package/dist/{chunk-TQOYM4LN.js → chunk-MP2JQKSG.js} +21 -5
  109. package/dist/chunk-MP2JQKSG.js.map +1 -0
  110. package/dist/{chunk-3642VBVC.cjs → chunk-O7UN7OXA.cjs} +389 -121
  111. package/dist/chunk-O7UN7OXA.cjs.map +1 -0
  112. package/dist/chunk-OHMP6N2J.js +47 -0
  113. package/dist/chunk-OHMP6N2J.js.map +1 -0
  114. package/dist/{chunk-6NRFUHMS.js → chunk-OR5ZA5WP.js} +135 -24
  115. package/dist/chunk-OR5ZA5WP.js.map +1 -0
  116. package/dist/{chunk-PRMKPFN5.js → chunk-Q5TEXCTB.js} +61 -6
  117. package/dist/chunk-Q5TEXCTB.js.map +1 -0
  118. package/dist/chunk-QNKSQTKQ.js +1312 -0
  119. package/dist/chunk-QNKSQTKQ.js.map +1 -0
  120. package/dist/{chunk-YCV72E6L.js → chunk-QOTI55H7.js} +7 -116
  121. package/dist/chunk-QOTI55H7.js.map +1 -0
  122. package/dist/{chunk-QBYTJSAY.js → chunk-QWEUYILR.js} +99 -34
  123. package/dist/chunk-QWEUYILR.js.map +1 -0
  124. package/dist/{chunk-OS6KS3HV.js → chunk-RGP33ZJ5.js} +485 -82
  125. package/dist/chunk-RGP33ZJ5.js.map +1 -0
  126. package/dist/chunk-RGPG7EOJ.js +94 -0
  127. package/dist/chunk-RGPG7EOJ.js.map +1 -0
  128. package/dist/{chunk-WWVV44DY.cjs → chunk-S55OV6PW.cjs} +15 -15
  129. package/dist/chunk-S55OV6PW.cjs.map +1 -0
  130. package/dist/{chunk-3E7SNSIA.cjs → chunk-SJDMVITW.cjs} +4 -4
  131. package/dist/{chunk-3E7SNSIA.cjs.map → chunk-SJDMVITW.cjs.map} +1 -1
  132. package/dist/{chunk-XLUNB2TZ.js → chunk-SNXVDZAJ.js} +3 -3
  133. package/dist/{chunk-XLUNB2TZ.js.map → chunk-SNXVDZAJ.js.map} +1 -1
  134. package/dist/{chunk-CEF2QOTO.js → chunk-T2WUSPDA.js} +49 -8
  135. package/dist/chunk-T2WUSPDA.js.map +1 -0
  136. package/dist/{chunk-YW7GHMF4.cjs → chunk-TCOCYN2P.cjs} +75 -20
  137. package/dist/chunk-TCOCYN2P.cjs.map +1 -0
  138. package/dist/{chunk-FLRCVI2G.cjs → chunk-TDXIBCGY.cjs} +2 -2
  139. package/dist/{chunk-FLRCVI2G.cjs.map → chunk-TDXIBCGY.cjs.map} +1 -1
  140. package/dist/chunk-TEDRJXOG.cjs +32 -0
  141. package/dist/chunk-TEDRJXOG.cjs.map +1 -0
  142. package/dist/{chunk-WLP6TKFB.js → chunk-UES55P7G.js} +2809 -4398
  143. package/dist/chunk-UES55P7G.js.map +1 -0
  144. package/dist/{chunk-EF3Z645U.cjs → chunk-UMDVATGY.cjs} +6 -72
  145. package/dist/chunk-UMDVATGY.cjs.map +1 -0
  146. package/dist/chunk-UR7W5YQK.js +18 -0
  147. package/dist/chunk-UR7W5YQK.js.map +1 -0
  148. package/dist/chunk-UT3S4SEN.js +31 -0
  149. package/dist/chunk-UT3S4SEN.js.map +1 -0
  150. package/dist/{chunk-3IR2GEMJ.cjs → chunk-UUT7UN2N.cjs} +149 -38
  151. package/dist/chunk-UUT7UN2N.cjs.map +1 -0
  152. package/dist/{chunk-PIHXFF73.js → chunk-UZV3AZKF.js} +21 -3
  153. package/dist/chunk-UZV3AZKF.js.map +1 -0
  154. package/dist/{chunk-DJYRRDHA.js → chunk-VHMPG6UL.js} +29 -7
  155. package/dist/chunk-VHMPG6UL.js.map +1 -0
  156. package/dist/{chunk-MBLXCV2Y.cjs → chunk-VPYHY3LJ.cjs} +111 -43
  157. package/dist/chunk-VPYHY3LJ.cjs.map +1 -0
  158. package/dist/{chunk-WYTUF3QO.js → chunk-VSPCZAXF.js} +3 -3
  159. package/dist/{chunk-WYTUF3QO.js.map → chunk-VSPCZAXF.js.map} +1 -1
  160. package/dist/chunk-W63OVYY4.js +29 -0
  161. package/dist/chunk-W63OVYY4.js.map +1 -0
  162. package/dist/{chunk-UPDMJEW6.js → chunk-WDBCBWC4.js} +356 -30
  163. package/dist/chunk-WDBCBWC4.js.map +1 -0
  164. package/dist/chunk-WJT7OU7E.cjs +1334 -0
  165. package/dist/chunk-WJT7OU7E.cjs.map +1 -0
  166. package/dist/chunk-XOX22WHL.cjs +2383 -0
  167. package/dist/chunk-XOX22WHL.cjs.map +1 -0
  168. package/dist/{ddl-CVnHJcar.d.ts → ddl-C2rZ-Aen.d.ts} +4 -4
  169. package/dist/{ddl-Dxt_fBHr.d.cts → ddl-CZz7a0E8.d.cts} +4 -4
  170. package/dist/{extension-types-YGFJPrzK.d.cts → extension-types-ixRpJVUp.d.cts} +24 -1
  171. package/dist/{extension-types-YGFJPrzK.d.ts → extension-types-ixRpJVUp.d.ts} +24 -1
  172. package/dist/{types-DGylBhWo.d.ts → fulltext-strategy-B57yvC5Q.d.ts} +2558 -2125
  173. package/dist/{types-C_UnQOQp.d.cts → fulltext-strategy-CDkSSYhq.d.cts} +2558 -2125
  174. package/dist/graph-extension/index.cjs +21 -19
  175. package/dist/graph-extension/index.d.cts +4 -4
  176. package/dist/graph-extension/index.d.ts +4 -4
  177. package/dist/graph-extension/index.js +6 -4
  178. package/dist/graph-merge/index.cjs +408 -169
  179. package/dist/graph-merge/index.cjs.map +1 -1
  180. package/dist/graph-merge/index.d.cts +63 -33
  181. package/dist/graph-merge/index.d.ts +63 -33
  182. package/dist/graph-merge/index.js +286 -47
  183. package/dist/graph-merge/index.js.map +1 -1
  184. package/dist/{index-DGX6D9j1.d.ts → index-6CSUAq-x.d.ts} +234 -93
  185. package/dist/{index-SEvUHDA6.d.cts → index-Bks_3HHK.d.cts} +234 -93
  186. package/dist/index.cjs +240 -211
  187. package/dist/index.cjs.map +1 -1
  188. package/dist/index.d.cts +11 -11
  189. package/dist/index.d.ts +11 -11
  190. package/dist/index.js +35 -27
  191. package/dist/index.js.map +1 -1
  192. package/dist/indexes/index.cjs +28 -27
  193. package/dist/indexes/index.d.cts +5 -5
  194. package/dist/indexes/index.d.ts +5 -5
  195. package/dist/indexes/index.js +10 -9
  196. package/dist/interchange/index.cjs +47 -17
  197. package/dist/interchange/index.d.cts +126 -12
  198. package/dist/interchange/index.d.ts +126 -12
  199. package/dist/interchange/index.js +14 -4
  200. package/dist/{manager-BYl_zyZR.d.cts → manager-DwQi8eV0.d.cts} +9 -2
  201. package/dist/{manager-C0_r0ALf.d.ts → manager-ejUCB52T.d.ts} +9 -2
  202. package/dist/{materialize-indexes-D20xNluI.d.cts → materialize-indexes-B4e9360H.d.cts} +20 -4
  203. package/dist/{materialize-indexes-CAkIYFV-.d.ts → materialize-indexes-te9TPMMJ.d.ts} +20 -4
  204. package/dist/{postgres-_9psmVGm.d.cts → postgres-CfEqsRMp.d.cts} +152 -1
  205. package/dist/{postgres-MzBPkYzq.d.ts → postgres-DQ5R6rzV.d.ts} +152 -1
  206. package/dist/profiler/index.cjs +11 -11
  207. package/dist/profiler/index.d.cts +7 -7
  208. package/dist/profiler/index.d.ts +7 -7
  209. package/dist/profiler/index.js +4 -4
  210. package/dist/provenance/index.cjs +590 -0
  211. package/dist/provenance/index.cjs.map +1 -0
  212. package/dist/provenance/index.d.cts +73 -0
  213. package/dist/provenance/index.d.ts +73 -0
  214. package/dist/provenance/index.js +588 -0
  215. package/dist/provenance/index.js.map +1 -0
  216. package/dist/schema/index.cjs +55 -38
  217. package/dist/schema/index.cjs.map +1 -1
  218. package/dist/schema/index.d.cts +57 -57
  219. package/dist/schema/index.d.ts +57 -57
  220. package/dist/schema/index.js +30 -13
  221. package/dist/schema/index.js.map +1 -1
  222. package/dist/{sqlite-gm44dShb.d.ts → sqlite-D7zBinNR.d.cts} +92 -1
  223. package/dist/{sqlite-BfksSb45.d.cts → sqlite-DvQndLky.d.ts} +92 -1
  224. package/dist/{store-view-FfE5_7eo.d.ts → store-view-BSpqvAxK.d.cts} +445 -46
  225. package/dist/{store-view-9jQ2rPum.d.cts → store-view-CKbHFRnn.d.ts} +445 -46
  226. package/dist/{types-B6mhrcLv.d.cts → types-Bv9DcS_E.d.cts} +2 -2
  227. package/dist/{types-CdWxK-nD.d.ts → types-CoxuV7EJ.d.ts} +2 -2
  228. package/dist/{where-Bpp2ul_z.d.cts → where-7RKFOsXt.d.ts} +2 -2
  229. package/dist/{where-BsEXraKW.d.ts → where-DdMIXOtH.d.cts} +2 -2
  230. package/package.json +21 -14
  231. package/dist/chunk-2YMGNYXY.js +0 -40
  232. package/dist/chunk-2YMGNYXY.js.map +0 -1
  233. package/dist/chunk-3642VBVC.cjs.map +0 -1
  234. package/dist/chunk-3EUKJEQ3.js +0 -77
  235. package/dist/chunk-3EUKJEQ3.js.map +0 -1
  236. package/dist/chunk-3IR2GEMJ.cjs.map +0 -1
  237. package/dist/chunk-3QRBXYT5.cjs.map +0 -1
  238. package/dist/chunk-454I6GDF.js.map +0 -1
  239. package/dist/chunk-4RBAJVEC.cjs.map +0 -1
  240. package/dist/chunk-6NRFUHMS.js.map +0 -1
  241. package/dist/chunk-6ZR4QC3O.cjs +0 -12
  242. package/dist/chunk-73KASJGO.cjs +0 -52
  243. package/dist/chunk-73KASJGO.cjs.map +0 -1
  244. package/dist/chunk-BF3ZDEUE.cjs +0 -773
  245. package/dist/chunk-BF3ZDEUE.cjs.map +0 -1
  246. package/dist/chunk-C4C4Q7A6.js.map +0 -1
  247. package/dist/chunk-CEF2QOTO.js.map +0 -1
  248. package/dist/chunk-CFNT3ITG.cjs.map +0 -1
  249. package/dist/chunk-CWFPJ3RC.js.map +0 -1
  250. package/dist/chunk-D3EWZ67S.cjs.map +0 -1
  251. package/dist/chunk-DJYRRDHA.js.map +0 -1
  252. package/dist/chunk-EF3Z645U.cjs.map +0 -1
  253. package/dist/chunk-FDN43KXV.cjs.map +0 -1
  254. package/dist/chunk-GYVBEZAO.js.map +0 -1
  255. package/dist/chunk-HTGDWIDE.cjs +0 -89
  256. package/dist/chunk-HTGDWIDE.cjs.map +0 -1
  257. package/dist/chunk-I4W7MKVG.cjs.map +0 -1
  258. package/dist/chunk-IZ4PCL47.js.map +0 -1
  259. package/dist/chunk-JHOBXD7O.js.map +0 -1
  260. package/dist/chunk-JIEJCTDS.cjs.map +0 -1
  261. package/dist/chunk-KTIEB7VH.cjs.map +0 -1
  262. package/dist/chunk-KY5SDVA7.cjs.map +0 -1
  263. package/dist/chunk-LM2IC4ZJ.cjs.map +0 -1
  264. package/dist/chunk-MBLXCV2Y.cjs.map +0 -1
  265. package/dist/chunk-NG5N7R45.cjs.map +0 -1
  266. package/dist/chunk-OIE2UPVG.cjs.map +0 -1
  267. package/dist/chunk-OS6KS3HV.js.map +0 -1
  268. package/dist/chunk-PIHXFF73.js.map +0 -1
  269. package/dist/chunk-PRMKPFN5.js.map +0 -1
  270. package/dist/chunk-PYD3UCDU.js.map +0 -1
  271. package/dist/chunk-QBYTJSAY.js.map +0 -1
  272. package/dist/chunk-SPT5JMME.js +0 -610
  273. package/dist/chunk-SPT5JMME.js.map +0 -1
  274. package/dist/chunk-SST7XDY6.cjs +0 -624
  275. package/dist/chunk-SST7XDY6.cjs.map +0 -1
  276. package/dist/chunk-TQOYM4LN.js.map +0 -1
  277. package/dist/chunk-UPDMJEW6.js.map +0 -1
  278. package/dist/chunk-WLP6TKFB.js.map +0 -1
  279. package/dist/chunk-WWVV44DY.cjs.map +0 -1
  280. package/dist/chunk-XKNAK27R.js.map +0 -1
  281. package/dist/chunk-XVUJY72M.js.map +0 -1
  282. package/dist/chunk-YCV72E6L.js.map +0 -1
  283. package/dist/chunk-YW7GHMF4.cjs.map +0 -1
  284. package/dist/chunk-ZFWNO3GE.cjs.map +0 -1
@@ -0,0 +1,2320 @@
1
+ import { asCompiledRowsSql, asCompiledStatementSql } from './chunk-UT3S4SEN.js';
2
+ import { createBackendOverlay, isPresent, rowPropsToObject, groupBy, chunk, sqlValueList, rowPropsToJsonText } from './chunk-JBTOYDMN.js';
3
+ import { validateCanonicalIsoDate, withRecordedRelationsPrecondition, nowIso } from './chunk-I7ZUZKFD.js';
4
+ import { MAX_PG_IDENTIFIER_LENGTH, sqlNull } from './chunk-OHMP6N2J.js';
5
+ import { resolveEmbeddingFields, getSearchableFields, DEFAULT_SEARCHABLE_LANGUAGE } from './chunk-KBGQIPRQ.js';
6
+ import { ConfigurationError, ValidationError, CardinalityError, EndpointError, DisjointError, UniquenessError, RestrictedDeleteError } from './chunk-MP2JQKSG.js';
7
+ import { sql } from 'drizzle-orm';
8
+ import { nanoid } from 'nanoid';
9
+
10
+ // src/core/temporal.ts
11
+ var RECORDED_MAX = "9999-12-31T23:59:59.999Z";
12
+ function assertValidRecordedInstant(value, path) {
13
+ validateCanonicalIsoDate(value, path);
14
+ if (value >= RECORDED_MAX) {
15
+ throw new ValidationError(
16
+ `${path} must be before the recorded-time open sentinel ${RECORDED_MAX}.`,
17
+ {
18
+ issues: [
19
+ {
20
+ path,
21
+ message: `Expected a timestamp before ${RECORDED_MAX}, got "${value}"`
22
+ }
23
+ ]
24
+ },
25
+ {
26
+ suggestion: "Use a real recorded-time commit instant, not the open-interval sentinel."
27
+ }
28
+ );
29
+ }
30
+ }
31
+ function asRecordedInstant(value) {
32
+ assertValidRecordedInstant(value, "asRecordedInstant");
33
+ return value;
34
+ }
35
+ function resolveReadCoordinate(mode, asOf, suggestion) {
36
+ if (mode !== "asOf" && asOf !== void 0) {
37
+ throw new ValidationError(
38
+ `Temporal mode "${mode}" does not take an asOf timestamp.`,
39
+ {
40
+ issues: [
41
+ {
42
+ path: "asOf",
43
+ message: `asOf is only valid with mode "asOf", not "${mode}"`
44
+ }
45
+ ]
46
+ },
47
+ {
48
+ suggestion: 'Pin an instant with store.asOf(timestamp) or store.view({ mode: "asOf", asOf }); drop asOf for other modes.'
49
+ }
50
+ );
51
+ }
52
+ assertValidAsOf(
53
+ mode,
54
+ asOf,
55
+ suggestion === void 0 ? void 0 : { suggestion }
56
+ );
57
+ return { valid: asOf === void 0 ? { mode } : { mode, asOf } };
58
+ }
59
+ function withRecordedCoordinate(coordinate, recordedAsOf) {
60
+ assertValidRecordedInstant(recordedAsOf, "asOfRecorded");
61
+ return {
62
+ ...coordinate,
63
+ recorded: { asOf: recordedAsOf }
64
+ };
65
+ }
66
+ function assertValidAsOf(mode, asOf, options) {
67
+ if (mode === "asOf" && asOf === void 0) {
68
+ throw new ValidationError(
69
+ 'Temporal mode "asOf" requires a timestamp',
70
+ {
71
+ issues: [
72
+ { path: "asOf", message: "Timestamp is required for asOf mode" }
73
+ ]
74
+ },
75
+ {
76
+ suggestion: options?.suggestion ?? 'Provide an ISO-8601 timestamp for asOf mode, e.g. "2026-01-01T00:00:00.000Z".'
77
+ }
78
+ );
79
+ }
80
+ if (asOf !== void 0) {
81
+ validateCanonicalIsoDate(asOf, "asOf");
82
+ }
83
+ }
84
+ function describeCoordinate(coordinate) {
85
+ const { mode, asOf } = coordinate.valid;
86
+ const valid = asOf === void 0 ? `mode "${mode}"` : `mode "${mode}" asOf ${asOf}`;
87
+ return coordinate.recorded === void 0 ? valid : `${valid}, recorded asOf ${coordinate.recorded.asOf}`;
88
+ }
89
+ function coordinateContext(coordinate) {
90
+ const { mode, asOf } = coordinate.valid;
91
+ return {
92
+ temporalMode: mode,
93
+ ...asOf !== void 0 && { asOf },
94
+ ...coordinate.recorded === void 0 ? {} : { recordedAsOf: coordinate.recorded.asOf }
95
+ };
96
+ }
97
+ var SqlSchemaDescriptor = class {
98
+ // Private field gives SqlSchema nominal identity; runtime checks use instanceof.
99
+ #brand = true;
100
+ tables;
101
+ nodesTable;
102
+ edgesTable;
103
+ recordedNodesTable;
104
+ recordedEdgesTable;
105
+ recordedClockTable;
106
+ revisionOriginsTable;
107
+ fulltextTable;
108
+ constructor(fields) {
109
+ this.tables = fields.tables;
110
+ this.nodesTable = fields.nodesTable;
111
+ this.edgesTable = fields.edgesTable;
112
+ this.recordedNodesTable = fields.recordedNodesTable;
113
+ this.recordedEdgesTable = fields.recordedEdgesTable;
114
+ this.recordedClockTable = fields.recordedClockTable;
115
+ this.revisionOriginsTable = fields.revisionOriginsTable;
116
+ this.fulltextTable = fields.fulltextTable;
117
+ void this.#brand;
118
+ Object.freeze(this);
119
+ }
120
+ };
121
+ var DEFAULT_TABLE_NAMES = {
122
+ nodes: "typegraph_nodes",
123
+ edges: "typegraph_edges",
124
+ recordedNodes: "typegraph_recorded_nodes",
125
+ recordedEdges: "typegraph_recorded_edges",
126
+ recordedClock: "typegraph_recorded_clock",
127
+ revisionOrigins: "typegraph_revision_origins",
128
+ fulltext: "typegraph_node_fulltext",
129
+ uniques: "typegraph_node_uniques"
130
+ };
131
+ function resolveTableNames(names) {
132
+ return {
133
+ nodes: names.nodes ?? DEFAULT_TABLE_NAMES.nodes,
134
+ edges: names.edges ?? DEFAULT_TABLE_NAMES.edges,
135
+ recordedNodes: names.recordedNodes ?? DEFAULT_TABLE_NAMES.recordedNodes,
136
+ recordedEdges: names.recordedEdges ?? DEFAULT_TABLE_NAMES.recordedEdges,
137
+ recordedClock: names.recordedClock ?? DEFAULT_TABLE_NAMES.recordedClock,
138
+ revisionOrigins: names.revisionOrigins ?? DEFAULT_TABLE_NAMES.revisionOrigins,
139
+ fulltext: names.fulltext ?? DEFAULT_TABLE_NAMES.fulltext,
140
+ uniques: names.uniques ?? DEFAULT_TABLE_NAMES.uniques
141
+ };
142
+ }
143
+ var VALID_IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_$]*$/i;
144
+ function validateTableName(name, label) {
145
+ if (!name || name.length === 0) {
146
+ throw new ConfigurationError(`${label} table name cannot be empty`);
147
+ }
148
+ if (name.length > MAX_PG_IDENTIFIER_LENGTH) {
149
+ throw new ConfigurationError(
150
+ `${label} table name exceeds maximum length of ${MAX_PG_IDENTIFIER_LENGTH} characters`
151
+ );
152
+ }
153
+ if (!VALID_IDENTIFIER_PATTERN.test(name)) {
154
+ throw new ConfigurationError(
155
+ `${label} table name "${name}" is not a valid SQL identifier. Table names must start with a letter or underscore and contain only letters, digits, underscores, or dollar signs.`
156
+ );
157
+ }
158
+ }
159
+ function quoteIdentifier(name) {
160
+ return `"${name.replaceAll('"', '""')}"`;
161
+ }
162
+ function freezeSqlSchema(fields) {
163
+ return new SqlSchemaDescriptor(fields);
164
+ }
165
+ function isSqlSchema(schema) {
166
+ return schema instanceof SqlSchemaDescriptor && Object.isFrozen(schema);
167
+ }
168
+ function requireSqlSchema(schema, surface = "SqlSchema") {
169
+ if (isSqlSchema(schema)) return schema;
170
+ throw new ConfigurationError(
171
+ `${surface} must be created with createSqlSchema(...).`,
172
+ { code: "INVALID_SQL_SCHEMA", surface },
173
+ {
174
+ suggestion: "Pass the result of createSqlSchema(...) instead of a plain schema-shaped object."
175
+ }
176
+ );
177
+ }
178
+ function createSqlSchema(names = {}) {
179
+ const tables = resolveTableNames(names);
180
+ validateTableName(tables.nodes, "nodes");
181
+ validateTableName(tables.edges, "edges");
182
+ validateTableName(tables.recordedNodes, "recordedNodes");
183
+ validateTableName(tables.recordedEdges, "recordedEdges");
184
+ validateTableName(tables.recordedClock, "recordedClock");
185
+ validateTableName(tables.revisionOrigins, "revisionOrigins");
186
+ validateTableName(tables.fulltext, "fulltext");
187
+ validateTableName(tables.uniques, "uniques");
188
+ return freezeSqlSchema({
189
+ tables: Object.freeze(tables),
190
+ nodesTable: sql.raw(quoteIdentifier(tables.nodes)),
191
+ edgesTable: sql.raw(quoteIdentifier(tables.edges)),
192
+ recordedNodesTable: sql.raw(quoteIdentifier(tables.recordedNodes)),
193
+ recordedEdgesTable: sql.raw(quoteIdentifier(tables.recordedEdges)),
194
+ recordedClockTable: sql.raw(quoteIdentifier(tables.recordedClock)),
195
+ revisionOriginsTable: sql.raw(quoteIdentifier(tables.revisionOrigins)),
196
+ fulltextTable: sql.raw(quoteIdentifier(tables.fulltext))
197
+ });
198
+ }
199
+ var EXTERNAL_RECORDED_READ_SOURCE = /* @__PURE__ */ Symbol(
200
+ "ExternalRecordedReadSource"
201
+ );
202
+ var TYPEGRAPH_RECORDED_READ_SOURCE = /* @__PURE__ */ Symbol(
203
+ "TypeGraphRecordedReadSource"
204
+ );
205
+ function recordedRelation(options) {
206
+ const schema = requireSqlSchema(options.schema, "recordedRelation schema");
207
+ return Object.freeze({
208
+ source: "external",
209
+ schema,
210
+ [EXTERNAL_RECORDED_READ_SOURCE]: true
211
+ });
212
+ }
213
+ function requireExternalRecordedReadSource(source) {
214
+ if (source === void 0) return void 0;
215
+ if (isExternalRecordedReadSource(source)) return source;
216
+ throw new ConfigurationError(
217
+ "recordedRead must be created with recordedRelation({ schema }).",
218
+ { code: "INVALID_RECORDED_READ_SOURCE" },
219
+ {
220
+ suggestion: "Pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation. Use { history: true } when TypeGraph should capture writes."
221
+ }
222
+ );
223
+ }
224
+ function isExternalRecordedReadSource(source) {
225
+ if (typeof source !== "object" || source === null) return false;
226
+ const candidate = source;
227
+ return candidate.source === "external" && candidate[EXTERNAL_RECORDED_READ_SOURCE] === true && isSqlSchema(candidate.schema) && Object.isFrozen(candidate);
228
+ }
229
+ function createRecordedReadBinding(schema) {
230
+ const readSchema = requireSqlSchema(schema, "recorded read binding schema");
231
+ return Object.freeze({
232
+ source: "typegraph-capture",
233
+ schema: readSchema,
234
+ [TYPEGRAPH_RECORDED_READ_SOURCE]: true
235
+ });
236
+ }
237
+ function requireRecordedReadBinding(binding, surface) {
238
+ if (isRecordedReadBinding(binding)) return binding;
239
+ if (binding !== void 0) {
240
+ throw new ConfigurationError(
241
+ "Recorded-time reads require a recorded read relation created by TypeGraph.",
242
+ { code: "INVALID_RECORDED_READ_BINDING", surface },
243
+ {
244
+ suggestion: "Use createStore(graph, backend, { history: true }) or { recordedRead: recordedRelation({ schema }) } instead of passing a plain object."
245
+ }
246
+ );
247
+ }
248
+ throw new ConfigurationError(
249
+ "Recorded-time reads require a recorded read relation.",
250
+ { code: "RECORDED_READ_REQUIRES_BINDING", surface },
251
+ {
252
+ suggestion: "Create the store with createStore(graph, backend, { history: true }) to bind TypeGraph's built-in captured relation, or pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation."
253
+ }
254
+ );
255
+ }
256
+ function isTypeGraphRecordedReadSource(source) {
257
+ if (typeof source !== "object" || source === null) return false;
258
+ const candidate = source;
259
+ return candidate.source === "typegraph-capture" && candidate[TYPEGRAPH_RECORDED_READ_SOURCE] === true && isSqlSchema(candidate.schema) && Object.isFrozen(candidate);
260
+ }
261
+ function isRecordedReadBinding(binding) {
262
+ return isExternalRecordedReadSource(binding) || isTypeGraphRecordedReadSource(binding);
263
+ }
264
+ function recordedReadSqlSchema(binding) {
265
+ const { schema } = requireRecordedReadBinding(
266
+ binding,
267
+ "recorded-read-schema"
268
+ );
269
+ return freezeSqlSchema({
270
+ tables: schema.tables,
271
+ nodesTable: schema.recordedNodesTable,
272
+ edgesTable: schema.recordedEdgesTable,
273
+ recordedNodesTable: schema.recordedNodesTable,
274
+ recordedEdgesTable: schema.recordedEdgesTable,
275
+ recordedClockTable: schema.recordedClockTable,
276
+ revisionOriginsTable: schema.revisionOriginsTable,
277
+ fulltextTable: schema.fulltextTable
278
+ });
279
+ }
280
+ function recordedReadSchemaFor(schema, recordedAsOf, binding, surface) {
281
+ const baseSchema = requireSqlSchema(schema, `${surface} schema`);
282
+ if (recordedAsOf === void 0) return baseSchema;
283
+ return recordedReadSqlSchema(requireRecordedReadBinding(binding, surface));
284
+ }
285
+ var DEFAULT_SQL_SCHEMA = createSqlSchema();
286
+ function vectorSlotKey(nodeKind, fieldPath) {
287
+ return `${nodeKind}\0${fieldPath}`;
288
+ }
289
+ var ALIAS_CTE_PREFIX = "cte_";
290
+ var EMBEDDINGS_CTE_ALIAS = "cte_embeddings";
291
+ var FULLTEXT_CTE_ALIAS = "cte_fulltext";
292
+ var HYBRID_CANDIDATES_CTE_ALIAS = "cte_relevance_candidates";
293
+ function generateId() {
294
+ return nanoid();
295
+ }
296
+ function requireRecordedSchema(target) {
297
+ if (target.tableNames === void 0) {
298
+ throw new ConfigurationError(
299
+ "Recorded-time capture requires the backend to expose tableNames.",
300
+ { dialect: target.dialect },
301
+ {
302
+ suggestion: "Use a built-in SQLite/PostgreSQL backend, or set tableNames on the custom backend so recorded-time capture targets the configured relations."
303
+ }
304
+ );
305
+ }
306
+ return createSqlSchema(target.tableNames);
307
+ }
308
+ function requireCaptureStatements(target) {
309
+ if (target.executeStatement === void 0) {
310
+ throw new ConfigurationError(
311
+ "Recorded-time capture requires backend.executeStatement support on the transaction backend.",
312
+ { dialect: target.dialect },
313
+ {
314
+ suggestion: "Use the built-in SQLite/PostgreSQL backends or provide executeStatement on the custom backend's transaction target."
315
+ }
316
+ );
317
+ }
318
+ }
319
+ async function executeStatement(target, query) {
320
+ requireCaptureStatements(target);
321
+ await target.executeStatement(asCompiledStatementSql(query));
322
+ }
323
+ function unsupportedPostgresIsolationError(isolationLevel) {
324
+ return new ConfigurationError(
325
+ "Recorded-time capture on PostgreSQL requires read_committed isolation.",
326
+ { isolationLevel: isolationLevel ?? "unknown" },
327
+ {
328
+ suggestion: "Omit the transaction isolation option or use read_committed. PostgreSQL repeatable_read/serializable snapshots cannot safely allocate the per-graph recorded clock inside the captured transaction."
329
+ }
330
+ );
331
+ }
332
+ function isSupportedRecordedIsolationLevel(isolationLevel) {
333
+ return isolationLevel === void 0 || isolationLevel === "read_committed" || isolationLevel === "read_uncommitted";
334
+ }
335
+ function assertRequestedRecordedIsolation(backend, options) {
336
+ if (backend.dialect !== "postgres") return;
337
+ const isolationLevel = options?.isolationLevel;
338
+ if (isSupportedRecordedIsolationLevel(isolationLevel)) return;
339
+ throw unsupportedPostgresIsolationError(isolationLevel);
340
+ }
341
+ function normalizeIsolationLevel(value) {
342
+ if (typeof value !== "string") return void 0;
343
+ return value.replaceAll(" ", "_").toLowerCase();
344
+ }
345
+ async function assertRecordedCaptureTransactionIsolation(target) {
346
+ if (target.dialect !== "postgres") return;
347
+ const rows = await target.execute(
348
+ asCompiledRowsSql(sql`
349
+ SELECT current_setting('transaction_isolation') AS transaction_isolation
350
+ `)
351
+ );
352
+ const isolationLevel = normalizeIsolationLevel(
353
+ rows[0]?.transaction_isolation
354
+ );
355
+ if (isSupportedRecordedIsolationLevel(isolationLevel)) return;
356
+ throw unsupportedPostgresIsolationError(isolationLevel);
357
+ }
358
+ function recordedCaptureRequiresCallbackTransactionError(details) {
359
+ return new ConfigurationError(
360
+ "withTransaction() has no recorded-time capture flush point when history is enabled.",
361
+ details,
362
+ {
363
+ suggestion: "Use store.withRecordedTransaction(externalTx, async (tx) => ...) so TypeGraph can flush capture before the caller commits."
364
+ }
365
+ );
366
+ }
367
+ function historyUnsafeRawWriteError(surface) {
368
+ return new ConfigurationError(
369
+ `${surface} is not available when history capture is enabled because raw SQL writes bypass recorded-time capture.`,
370
+ { code: "RECORDED_CAPTURE_RAW_SQL_DISABLED" },
371
+ {
372
+ suggestion: "Run graph writes through store.nodes/store.edges (or tx.nodes/tx.edges inside a transaction), or perform raw relational writes outside a history-enabled TypeGraph store."
373
+ }
374
+ );
375
+ }
376
+ function revisionTrackingUnsafeRawWriteError(surface) {
377
+ return new ConfigurationError(
378
+ `${surface} is not available when revision tracking is enabled because raw SQL writes bypass the revision anchor.`,
379
+ { code: "REVISION_TRACKING_RAW_SQL_DISABLED" },
380
+ {
381
+ suggestion: "Run graph writes through store.nodes/store.edges (or tx.nodes/tx.edges inside a transaction), so TypeGraph can advance the revision anchor."
382
+ }
383
+ );
384
+ }
385
+ function failHistoryUnsafeSqlRef() {
386
+ throw historyUnsafeRawWriteError("tx.sql");
387
+ }
388
+ function failRevisionTrackingUnsafeSqlRef() {
389
+ throw revisionTrackingUnsafeRawWriteError("tx.sql");
390
+ }
391
+ function createHistoryUnsafeSqlRef() {
392
+ return createUnsafeSqlRef(failHistoryUnsafeSqlRef);
393
+ }
394
+ function createRevisionTrackingUnsafeSqlRef() {
395
+ return createUnsafeSqlRef(failRevisionTrackingUnsafeSqlRef);
396
+ }
397
+ function createUnsafeSqlRef(fail) {
398
+ return new Proxy(
399
+ function unsafeSqlRef() {
400
+ return fail();
401
+ },
402
+ {
403
+ get() {
404
+ return fail();
405
+ },
406
+ apply() {
407
+ return fail();
408
+ },
409
+ set() {
410
+ return fail();
411
+ },
412
+ defineProperty() {
413
+ return fail();
414
+ },
415
+ deleteProperty() {
416
+ return fail();
417
+ },
418
+ // Enumeration / inspection traps too, so spreading (`{...tx.sql}`),
419
+ // `Object.keys`, `in`, and prototype reads also fail loudly rather than
420
+ // silently yielding an empty object that reads as "no raw handle".
421
+ has() {
422
+ return fail();
423
+ },
424
+ ownKeys() {
425
+ return fail();
426
+ },
427
+ getOwnPropertyDescriptor() {
428
+ return fail();
429
+ },
430
+ getPrototypeOf() {
431
+ return fail();
432
+ }
433
+ }
434
+ );
435
+ }
436
+ function rawWriteGuards(target, prefix) {
437
+ return {
438
+ ...target.executeStatement === void 0 ? {} : {
439
+ executeStatement(_query) {
440
+ return Promise.reject(
441
+ historyUnsafeRawWriteError(`${prefix}.executeStatement`)
442
+ );
443
+ }
444
+ },
445
+ ...target.executeDdl === void 0 ? {} : {
446
+ executeDdl(_ddl) {
447
+ return Promise.reject(
448
+ historyUnsafeRawWriteError(`${prefix}.executeDdl`)
449
+ );
450
+ }
451
+ }
452
+ };
453
+ }
454
+ function assertCapturableBackend(backend) {
455
+ if (!backend.capabilities.transactions) {
456
+ throw new ConfigurationError(
457
+ "history: true requires a backend with transaction support.",
458
+ { dialect: backend.dialect },
459
+ {
460
+ suggestion: "Use a transactional SQLite/PostgreSQL backend or disable recorded-time capture for this store."
461
+ }
462
+ );
463
+ }
464
+ if (backend.executeStatement === void 0) {
465
+ throw new ConfigurationError(
466
+ "history: true requires a backend that supports executeStatement.",
467
+ { dialect: backend.dialect },
468
+ {
469
+ suggestion: "Use a built-in SQLite/PostgreSQL backend, or implement executeStatement on the custom backend so recorded-time capture can write history rows."
470
+ }
471
+ );
472
+ }
473
+ if (backend.capabilities.returning === false) {
474
+ throw new ConfigurationError(
475
+ "history: true requires a backend that supports UPDATE \u2026 RETURNING.",
476
+ { dialect: backend.dialect },
477
+ {
478
+ suggestion: "Use a built-in SQLite/PostgreSQL backend, or run recorded-time capture on a backend whose engine supports UPDATE \u2026 RETURNING \u2014 capture closes recorded intervals with a RETURNING statement on its hot path."
479
+ }
480
+ );
481
+ }
482
+ if (backend.tableNames === void 0) {
483
+ throw new ConfigurationError(
484
+ "history: true requires a backend that exposes tableNames.",
485
+ { dialect: backend.dialect },
486
+ {
487
+ suggestion: "Use a built-in SQLite/PostgreSQL backend, or set tableNames on the custom backend so recorded-time capture can resolve the recorded relations instead of silently falling back to defaults."
488
+ }
489
+ );
490
+ }
491
+ }
492
+ function assertRevisionTrackableBackend(backend) {
493
+ if (!backend.capabilities.transactions) {
494
+ throw new ConfigurationError(
495
+ "revisionTracking: true requires a backend with transaction support.",
496
+ { dialect: backend.dialect },
497
+ {
498
+ suggestion: "Use a transactional SQLite/PostgreSQL backend or leave revision tracking disabled."
499
+ }
500
+ );
501
+ }
502
+ if (backend.executeStatement === void 0) {
503
+ throw new ConfigurationError(
504
+ "revisionTracking: true requires a backend that supports executeStatement.",
505
+ { dialect: backend.dialect },
506
+ {
507
+ suggestion: "Use a built-in SQLite/PostgreSQL backend, or implement executeStatement so TypeGraph can advance the revision clock."
508
+ }
509
+ );
510
+ }
511
+ if (backend.tableNames === void 0) {
512
+ throw new ConfigurationError(
513
+ "revisionTracking: true requires a backend that exposes tableNames.",
514
+ { dialect: backend.dialect },
515
+ {
516
+ suggestion: "Use a built-in SQLite/PostgreSQL backend, or set tableNames so TypeGraph can address the revision clock relation."
517
+ }
518
+ );
519
+ }
520
+ if (backend.ensureRevisionOriginsTable === void 0) {
521
+ throw new ConfigurationError(
522
+ "revisionTracking: true requires a backend that can bootstrap revision origins.",
523
+ { dialect: backend.dialect },
524
+ {
525
+ suggestion: "Use a built-in SQLite/PostgreSQL backend, or implement ensureRevisionOriginsTable so TypeGraph can durably namespace revision anchors."
526
+ }
527
+ );
528
+ }
529
+ }
530
+
531
+ // src/store/recorded-capture/clock.ts
532
+ var RECORDED_MIN = "1970-01-01T00:00:00.000Z";
533
+ var RECORDED_MAX_TIME = new Date(RECORDED_MAX).getTime();
534
+ var RECORDED_CLOCK_ADVISORY_LOCK_NAMESPACE = "typegraph:recorded-clock";
535
+ var RECORDED_GRAPH_WRITE_ADVISORY_LOCK_NAMESPACE = "typegraph:recorded-graph-write";
536
+ function graphAdvisoryLockSql(namespace, graphId) {
537
+ return sql`
538
+ SELECT pg_advisory_xact_lock(
539
+ hashtext(${namespace}),
540
+ hashtext(${graphId})
541
+ )
542
+ `;
543
+ }
544
+ function recordedClockAdvisoryLockSql(graphId) {
545
+ return graphAdvisoryLockSql(RECORDED_CLOCK_ADVISORY_LOCK_NAMESPACE, graphId);
546
+ }
547
+ function recordedGraphWriteAdvisoryLockSql(graphId) {
548
+ return graphAdvisoryLockSql(
549
+ RECORDED_GRAPH_WRITE_ADVISORY_LOCK_NAMESPACE,
550
+ graphId
551
+ );
552
+ }
553
+ var GRAPH_WRITE_LOCK_EVIDENCE = Object.freeze({});
554
+ function graphWriteLockEvidence() {
555
+ return GRAPH_WRITE_LOCK_EVIDENCE;
556
+ }
557
+ function uncapturedGraphWriteLock() {
558
+ return graphWriteLockEvidence();
559
+ }
560
+ function createRecordedGraphLockMemo() {
561
+ return /* @__PURE__ */ new Map();
562
+ }
563
+ var recordedGraphLockMemos = /* @__PURE__ */ new WeakMap();
564
+ function registerRecordedGraphLockMemo(backend, memo) {
565
+ recordedGraphLockMemos.set(backend, memo);
566
+ }
567
+ async function acquireRecordedGraphWriteLock(target, graphId) {
568
+ await target.execute(
569
+ asCompiledRowsSql(recordedGraphWriteAdvisoryLockSql(graphId))
570
+ );
571
+ }
572
+ async function lockRecordedGraphWrite(target, graphId, memo) {
573
+ if (target.dialect !== "postgres") return graphWriteLockEvidence();
574
+ const effectiveMemo = memo ?? recordedGraphLockMemos.get(target);
575
+ if (effectiveMemo === void 0) {
576
+ await acquireRecordedGraphWriteLock(target, graphId);
577
+ return graphWriteLockEvidence();
578
+ }
579
+ let pending = effectiveMemo.get(graphId);
580
+ if (pending === void 0) {
581
+ pending = acquireRecordedGraphWriteLock(target, graphId).catch(
582
+ (error) => {
583
+ effectiveMemo.delete(graphId);
584
+ throw error;
585
+ }
586
+ );
587
+ effectiveMemo.set(graphId, pending);
588
+ }
589
+ await pending;
590
+ return graphWriteLockEvidence();
591
+ }
592
+ function failInvalidClockTimestamp(value) {
593
+ throw new ConfigurationError(
594
+ "Recorded clock row contained an invalid timestamp",
595
+ { value }
596
+ );
597
+ }
598
+ var ZONELESS_DATETIME_PATTERN = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
599
+ var OFFSET_DATETIME_PATTERN = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)(Z|[+-]\d{2}(?::?\d{2})?)$/i;
600
+ function normalizeOffsetDesignator(offset) {
601
+ if (offset.toUpperCase() === "Z") return "Z";
602
+ if (/^[+-]\d{2}$/.test(offset)) return `${offset}:00`;
603
+ if (/^[+-]\d{4}$/.test(offset)) {
604
+ return `${offset.slice(0, 3)}:${offset.slice(3)}`;
605
+ }
606
+ return offset;
607
+ }
608
+ function clockTimestampMs(value) {
609
+ if (ZONELESS_DATETIME_PATTERN.test(value)) {
610
+ return Date.parse(`${value.replace(" ", "T")}Z`);
611
+ }
612
+ const offsetMatch = OFFSET_DATETIME_PATTERN.exec(value);
613
+ if (offsetMatch) {
614
+ const [, date, time, offset] = offsetMatch;
615
+ return Date.parse(`${date}T${time}${normalizeOffsetDesignator(offset)}`);
616
+ }
617
+ return Date.parse(value);
618
+ }
619
+ function toCanonicalIso(value) {
620
+ if (value instanceof Date) {
621
+ if (Number.isNaN(value.getTime())) return failInvalidClockTimestamp(value);
622
+ return value.toISOString();
623
+ }
624
+ if (typeof value === "string") {
625
+ const timestamp = clockTimestampMs(value);
626
+ if (Number.isNaN(timestamp)) return failInvalidClockTimestamp(value);
627
+ return new Date(timestamp).toISOString();
628
+ }
629
+ return failInvalidClockTimestamp(value);
630
+ }
631
+ function nextRecordedCommitTime(previous) {
632
+ const wallTime = Date.parse(nowIso());
633
+ return previous === void 0 ? wallTime : Math.max(wallTime, Date.parse(previous) + 1);
634
+ }
635
+ async function readRecordedClock(target, schema, graphId) {
636
+ const rows = await target.execute(
637
+ asCompiledRowsSql(sql`
638
+ SELECT recorded_at
639
+ FROM ${schema.recordedClockTable}
640
+ WHERE graph_id = ${graphId}
641
+ `)
642
+ );
643
+ const first = rows[0];
644
+ return first === void 0 ? void 0 : toCanonicalIso(first.recorded_at);
645
+ }
646
+ async function readRevisionOrigin(target, schema, graphId) {
647
+ const rows = await target.execute(
648
+ asCompiledRowsSql(sql`
649
+ SELECT origin
650
+ FROM ${schema.revisionOriginsTable}
651
+ WHERE graph_id = ${graphId}
652
+ `)
653
+ );
654
+ const first = rows[0];
655
+ if (first === void 0) return void 0;
656
+ if (typeof first.origin !== "string" || first.origin.length === 0) {
657
+ throw new ConfigurationError(
658
+ "Revision origin row contained an invalid origin",
659
+ { graphId, origin: first.origin }
660
+ );
661
+ }
662
+ return first.origin;
663
+ }
664
+ async function ensureRevisionOrigin(target, schema, graphId) {
665
+ const ensureTable = target.ensureRevisionOriginsTable;
666
+ if (ensureTable === void 0) {
667
+ throw new ConfigurationError(
668
+ "Revision tracking requires a backend that can bootstrap revision origins.",
669
+ { dialect: target.dialect },
670
+ {
671
+ suggestion: "Use a built-in SQLite/PostgreSQL backend, or implement ensureRevisionOriginsTable on the custom backend."
672
+ }
673
+ );
674
+ }
675
+ await ensureTable();
676
+ const existing = await readRevisionOrigin(target, schema, graphId);
677
+ if (existing !== void 0) return existing;
678
+ await executeStatement(
679
+ target,
680
+ sql`
681
+ INSERT INTO ${schema.revisionOriginsTable} (graph_id, origin)
682
+ VALUES (${graphId}, ${generateId()})
683
+ ON CONFLICT (graph_id) DO NOTHING
684
+ `
685
+ );
686
+ const origin = await readRevisionOrigin(target, schema, graphId);
687
+ if (origin !== void 0) return origin;
688
+ throw new ConfigurationError(
689
+ "Revision origin was not persisted after initialization.",
690
+ { graphId, dialect: target.dialect }
691
+ );
692
+ }
693
+ async function writeRecordedClock(target, schema, graphId, recordedAt) {
694
+ await executeStatement(
695
+ target,
696
+ sql`
697
+ INSERT INTO ${schema.recordedClockTable} (graph_id, recorded_at)
698
+ VALUES (${graphId}, ${recordedAt})
699
+ ON CONFLICT (graph_id) DO UPDATE SET recorded_at = ${recordedAt}
700
+ `
701
+ );
702
+ }
703
+ async function lockRecordedClock(target, schema, graphId, ownsWriteLock) {
704
+ if (target.dialect === "postgres") {
705
+ await target.execute(
706
+ asCompiledRowsSql(recordedClockAdvisoryLockSql(graphId))
707
+ );
708
+ return;
709
+ }
710
+ if (ownsWriteLock) return;
711
+ await executeStatement(
712
+ target,
713
+ sql`
714
+ INSERT INTO ${schema.recordedClockTable} (graph_id, recorded_at)
715
+ VALUES (${graphId}, ${RECORDED_MIN})
716
+ ON CONFLICT (graph_id) DO UPDATE SET recorded_at = recorded_at
717
+ `
718
+ );
719
+ }
720
+ async function allocateRecordedCommit(target, schema, graphId, ownsWriteLock, previousRevision) {
721
+ await lockRecordedClock(target, schema, graphId, ownsWriteLock);
722
+ const previous = previousRevision ?? await readRecordedClock(target, schema, graphId);
723
+ const recordedCommitTime = nextRecordedCommitTime(previous);
724
+ if (!Number.isFinite(recordedCommitTime) || recordedCommitTime >= RECORDED_MAX_TIME) {
725
+ throw new ConfigurationError(
726
+ `Recorded commit clock reached the open sentinel ${RECORDED_MAX}`,
727
+ { graphId, recordedCommitTime },
728
+ {
729
+ suggestion: "Use a graph with a normal recorded-time clock; the open sentinel is reserved for relation intervals."
730
+ }
731
+ );
732
+ }
733
+ const recordedCommit = new Date(recordedCommitTime).toISOString();
734
+ await writeRecordedClock(target, schema, graphId, recordedCommit);
735
+ return recordedCommit;
736
+ }
737
+ async function advanceRevisionClock(target, schema, graphId, ownsWriteLock, previousRevision) {
738
+ return allocateRecordedCommit(
739
+ target,
740
+ schema,
741
+ graphId,
742
+ ownsWriteLock,
743
+ previousRevision
744
+ );
745
+ }
746
+
747
+ // src/store/insert-dispatch.ts
748
+ function nodeInsertDispatch(backend) {
749
+ return {
750
+ one: (params) => backend.insertNode(params),
751
+ oneNoReturn: backend.insertNodeNoReturn === void 0 ? void 0 : (params) => backend.insertNodeNoReturn(params),
752
+ batch: backend.insertNodesBatch === void 0 ? void 0 : (params) => backend.insertNodesBatch(params),
753
+ batchReturning: backend.insertNodesBatchReturning === void 0 ? void 0 : (params) => backend.insertNodesBatchReturning(params)
754
+ };
755
+ }
756
+ function edgeInsertDispatch(backend) {
757
+ return {
758
+ one: (params) => backend.insertEdge(params),
759
+ oneNoReturn: backend.insertEdgeNoReturn === void 0 ? void 0 : (params) => backend.insertEdgeNoReturn(params),
760
+ batch: backend.insertEdgesBatch === void 0 ? void 0 : (params) => backend.insertEdgesBatch(params),
761
+ batchReturning: backend.insertEdgesBatchReturning === void 0 ? void 0 : (params) => backend.insertEdgesBatchReturning(params)
762
+ };
763
+ }
764
+ async function runInsertNoReturn(dispatch, params) {
765
+ if (dispatch.oneNoReturn !== void 0) {
766
+ await dispatch.oneNoReturn(params);
767
+ return;
768
+ }
769
+ await dispatch.one(params);
770
+ }
771
+ async function runInsertBatch(dispatch, params) {
772
+ if (params.length === 0) return;
773
+ if (dispatch.batch !== void 0) {
774
+ await dispatch.batch(params);
775
+ return;
776
+ }
777
+ for (const insertParams of params) {
778
+ await runInsertNoReturn(dispatch, insertParams);
779
+ }
780
+ }
781
+ async function runInsertBatchReturning(dispatch, params) {
782
+ if (dispatch.batchReturning !== void 0) {
783
+ return dispatch.batchReturning(params);
784
+ }
785
+ const rows = [];
786
+ for (const insertParams of params) {
787
+ rows.push(await dispatch.one(insertParams));
788
+ }
789
+ return rows;
790
+ }
791
+
792
+ // src/store/row-fetch.ts
793
+ async function getRowsByIds(ids, policy) {
794
+ const rowsById = /* @__PURE__ */ new Map();
795
+ if (ids.length === 0) return rowsById;
796
+ if (policy.batch !== void 0) {
797
+ const rows2 = await policy.batch(ids);
798
+ for (const row of rows2) {
799
+ rowsById.set(row.id, row);
800
+ }
801
+ return rowsById;
802
+ }
803
+ const uniqueIds = [...new Set(ids)];
804
+ const rows = await Promise.all(uniqueIds.map((id) => policy.one(id)));
805
+ for (const row of rows) {
806
+ if (row !== void 0) rowsById.set(row.id, row);
807
+ }
808
+ return rowsById;
809
+ }
810
+
811
+ // src/store/edge-fetch.ts
812
+ async function getEdgeRowsByIds(backend, graphId, ids) {
813
+ return getRowsByIds(ids, {
814
+ batch: backend.getEdges === void 0 ? void 0 : (batchIds) => backend.getEdges(graphId, batchIds),
815
+ one: (id) => backend.getEdge(graphId, id)
816
+ });
817
+ }
818
+
819
+ // src/store/node-fetch.ts
820
+ async function getNodeRowsByIds(backend, graphId, kind, ids) {
821
+ return getRowsByIds(ids, {
822
+ batch: backend.getNodes === void 0 ? void 0 : (batchIds) => backend.getNodes(graphId, kind, batchIds),
823
+ one: (id) => backend.getNode(graphId, kind, id)
824
+ });
825
+ }
826
+ var RECORDED_HISTORY_META = "{}";
827
+ var RECORDED_NODE_COLUMNS = [
828
+ "history_id",
829
+ "graph_id",
830
+ "kind",
831
+ "id",
832
+ "props",
833
+ "version",
834
+ "valid_from",
835
+ "valid_to",
836
+ "created_at",
837
+ "updated_at",
838
+ "deleted_at",
839
+ "recorded_from",
840
+ "recorded_to",
841
+ "op",
842
+ "schema_version",
843
+ "tx_id",
844
+ "meta"
845
+ ];
846
+ var RECORDED_EDGE_COLUMNS = [
847
+ "history_id",
848
+ "graph_id",
849
+ "id",
850
+ "kind",
851
+ "from_kind",
852
+ "from_id",
853
+ "to_kind",
854
+ "to_id",
855
+ "props",
856
+ "valid_from",
857
+ "valid_to",
858
+ "created_at",
859
+ "updated_at",
860
+ "deleted_at",
861
+ "recorded_from",
862
+ "recorded_to",
863
+ "op",
864
+ "schema_version",
865
+ "tx_id",
866
+ "meta"
867
+ ];
868
+ var RECORDED_NODE_COLUMN_LIST = sql.raw(RECORDED_NODE_COLUMNS.join(", "));
869
+ var RECORDED_EDGE_COLUMN_LIST = sql.raw(RECORDED_EDGE_COLUMNS.join(", "));
870
+ var RECORDED_BIND_PARAM_BUDGET = 900;
871
+ function recordedBindParamBudget(target) {
872
+ const budget = target.capabilities.maxBindParameters ?? RECORDED_BIND_PARAM_BUDGET;
873
+ if (!Number.isSafeInteger(budget) || budget < 1) {
874
+ throw new ConfigurationError(
875
+ `backend capabilities.maxBindParameters must be a positive integer, got: ${String(budget)}`,
876
+ {
877
+ code: "INVALID_BACKEND_CAPABILITY",
878
+ capability: "maxBindParameters",
879
+ value: budget
880
+ }
881
+ );
882
+ }
883
+ return budget;
884
+ }
885
+ function recordedChunkSize(target, columnCount) {
886
+ const budget = recordedBindParamBudget(target);
887
+ return Math.max(1, Math.floor(budget / columnCount));
888
+ }
889
+ function recordedCommonCells() {
890
+ return {
891
+ history_id: () => sql`${generateId()}`,
892
+ graph_id: (row) => sql`${row.graph_id}`,
893
+ id: (row) => sql`${row.id}`,
894
+ kind: (row) => sql`${row.kind}`,
895
+ props: (row) => sql`${rowPropsToJsonText(row.props)}`,
896
+ valid_from: (row) => sql`${sqlNull(row.valid_from)}`,
897
+ valid_to: (row) => sql`${sqlNull(row.valid_to)}`,
898
+ created_at: (row) => sql`${row.created_at}`,
899
+ updated_at: (row) => sql`${row.updated_at}`,
900
+ deleted_at: (row) => sql`${sqlNull(row.deleted_at)}`,
901
+ recorded_from: (_row, recordedCommit) => sql`${recordedCommit}`,
902
+ recorded_to: () => sql`${RECORDED_MAX}`,
903
+ op: (_row, _recordedCommit, operation) => sql`${operation}`,
904
+ schema_version: () => sql`NULL`,
905
+ tx_id: () => sql`NULL`,
906
+ meta: () => sql`${RECORDED_HISTORY_META}`
907
+ };
908
+ }
909
+ var recordedNodeCells = {
910
+ ...recordedCommonCells(),
911
+ version: (row) => sql`${row.version}`
912
+ };
913
+ var recordedEdgeCells = {
914
+ ...recordedCommonCells(),
915
+ from_kind: (row) => sql`${row.from_kind}`,
916
+ from_id: (row) => sql`${row.from_id}`,
917
+ to_kind: (row) => sql`${row.to_kind}`,
918
+ to_id: (row) => sql`${row.to_id}`
919
+ };
920
+ function recordedValuesTuple(columns, cells, row, recordedCommit, operation) {
921
+ const tuple = columns.map(
922
+ (column) => cells[column](row, recordedCommit, operation)
923
+ );
924
+ return sql`(${sql.join(tuple, sql`, `)})`;
925
+ }
926
+ async function insertRecordedRows(target, table, columnList, columns, cells, inserts, recordedCommit) {
927
+ if (inserts.length === 0) return;
928
+ const values = inserts.map(
929
+ (insert) => recordedValuesTuple(
930
+ columns,
931
+ cells,
932
+ insert.row,
933
+ recordedCommit,
934
+ insert.operation
935
+ )
936
+ );
937
+ await executeStatement(
938
+ target,
939
+ sql`
940
+ INSERT INTO ${table} (${columnList})
941
+ VALUES ${sql.join(values, sql`, `)}
942
+ `
943
+ );
944
+ }
945
+ function recordedNodeChunkSize(target) {
946
+ return recordedChunkSize(target, RECORDED_NODE_COLUMNS.length);
947
+ }
948
+ function recordedEdgeChunkSize(target) {
949
+ return recordedChunkSize(target, RECORDED_EDGE_COLUMNS.length);
950
+ }
951
+ function insertRecordedNodeRows(target, table, inserts, recordedCommit) {
952
+ return insertRecordedRows(
953
+ target,
954
+ table,
955
+ RECORDED_NODE_COLUMN_LIST,
956
+ RECORDED_NODE_COLUMNS,
957
+ recordedNodeCells,
958
+ inserts,
959
+ recordedCommit
960
+ );
961
+ }
962
+ function insertRecordedEdgeRows(target, table, inserts, recordedCommit) {
963
+ return insertRecordedRows(
964
+ target,
965
+ table,
966
+ RECORDED_EDGE_COLUMN_LIST,
967
+ RECORDED_EDGE_COLUMNS,
968
+ recordedEdgeCells,
969
+ inserts,
970
+ recordedCommit
971
+ );
972
+ }
973
+
974
+ // src/store/recorded-capture/flush.ts
975
+ function entityKey(entity) {
976
+ switch (entity.entity) {
977
+ case "node": {
978
+ return `node\0${entity.graphId}\0${entity.kind}\0${entity.id}`;
979
+ }
980
+ case "edge": {
981
+ return `edge\0${entity.graphId}\0${entity.id}`;
982
+ }
983
+ }
984
+ }
985
+ async function closeOpenReturning(target, table, graphId, ids, recordedCommit, kind) {
986
+ const kindFilter = kind === void 0 ? sql`` : sql`AND kind = ${kind}`;
987
+ const rows = await target.execute(
988
+ asCompiledRowsSql(sql`
989
+ UPDATE ${table}
990
+ SET recorded_to = ${recordedCommit}
991
+ WHERE graph_id = ${graphId}
992
+ ${kindFilter}
993
+ AND recorded_to = ${RECORDED_MAX}
994
+ AND id IN (${sqlValueList(ids)})
995
+ RETURNING id, deleted_at
996
+ `)
997
+ );
998
+ return new Map(rows.map((row) => [row.id, isPresent(row.deleted_at)]));
999
+ }
1000
+ function recordedOp(hadOpenRow, priorRowWasTombstone, after) {
1001
+ if (isPresent(after.deleted_at)) return "delete";
1002
+ if (!hadOpenRow || priorRowWasTombstone) return "create";
1003
+ return "update";
1004
+ }
1005
+ function groupNodesByKind(entities) {
1006
+ const byKind = /* @__PURE__ */ new Map();
1007
+ for (const entity of entities) {
1008
+ const group = byKind.get(entity.kind) ?? [];
1009
+ group.push(entity);
1010
+ byKind.set(entity.kind, group);
1011
+ }
1012
+ return byKind;
1013
+ }
1014
+ async function resolveAfterImages(entities, readMissing) {
1015
+ const afterById = /* @__PURE__ */ new Map();
1016
+ const needRead = [];
1017
+ for (const entity of entities) {
1018
+ if (entity.afterImage === void 0) {
1019
+ needRead.push(entity.id);
1020
+ } else {
1021
+ afterById.set(entity.id, entity.afterImage);
1022
+ }
1023
+ }
1024
+ if (needRead.length > 0) {
1025
+ for (const [id, row] of await readMissing(needRead)) afterById.set(id, row);
1026
+ }
1027
+ return afterById;
1028
+ }
1029
+ function recordedInsertsFor(afterById, closed) {
1030
+ return [...afterById.values()].map((row) => ({
1031
+ row,
1032
+ operation: recordedOp(closed.has(row.id), closed.get(row.id) ?? false, row)
1033
+ }));
1034
+ }
1035
+ async function flushNodes(target, schema, graphId, entities, recordedCommit) {
1036
+ const chunkSize = recordedNodeChunkSize(target);
1037
+ for (const [kind, group] of groupNodesByKind(entities)) {
1038
+ for (const entityChunk of chunk(group, chunkSize)) {
1039
+ const ids = entityChunk.map((entity) => entity.id);
1040
+ const closed = await closeOpenReturning(
1041
+ target,
1042
+ schema.recordedNodesTable,
1043
+ graphId,
1044
+ ids,
1045
+ recordedCommit,
1046
+ kind
1047
+ );
1048
+ const afterById = await resolveAfterImages(
1049
+ entityChunk,
1050
+ (missing) => getNodeRowsByIds(target, graphId, kind, missing)
1051
+ );
1052
+ await insertRecordedNodeRows(
1053
+ target,
1054
+ schema.recordedNodesTable,
1055
+ recordedInsertsFor(afterById, closed),
1056
+ recordedCommit
1057
+ );
1058
+ }
1059
+ }
1060
+ }
1061
+ async function flushEdges(target, schema, graphId, entities, recordedCommit) {
1062
+ const chunkSize = recordedEdgeChunkSize(target);
1063
+ for (const entityChunk of chunk(entities, chunkSize)) {
1064
+ const ids = entityChunk.map((entity) => entity.id);
1065
+ const closed = await closeOpenReturning(
1066
+ target,
1067
+ schema.recordedEdgesTable,
1068
+ graphId,
1069
+ ids,
1070
+ recordedCommit
1071
+ );
1072
+ const afterById = await resolveAfterImages(
1073
+ entityChunk,
1074
+ (missing) => getEdgeRowsByIds(target, graphId, missing)
1075
+ );
1076
+ await insertRecordedEdgeRows(
1077
+ target,
1078
+ schema.recordedEdgesTable,
1079
+ recordedInsertsFor(afterById, closed),
1080
+ recordedCommit
1081
+ );
1082
+ }
1083
+ }
1084
+ async function closeOpenByKind(target, table, graphId, kind, recordedCommit) {
1085
+ await executeStatement(
1086
+ target,
1087
+ sql`
1088
+ UPDATE ${table}
1089
+ SET recorded_to = ${recordedCommit}
1090
+ WHERE graph_id = ${graphId}
1091
+ AND kind = ${kind}
1092
+ AND recorded_to = ${RECORDED_MAX}
1093
+ `
1094
+ );
1095
+ }
1096
+ async function closeOpenEdgesByNodeKind(target, schema, graphId, nodeKind, recordedCommit) {
1097
+ await executeStatement(
1098
+ target,
1099
+ sql`
1100
+ UPDATE ${schema.recordedEdgesTable}
1101
+ SET recorded_to = ${recordedCommit}
1102
+ WHERE graph_id = ${graphId}
1103
+ AND (from_kind = ${nodeKind} OR to_kind = ${nodeKind})
1104
+ AND recorded_to = ${RECORDED_MAX}
1105
+ `
1106
+ );
1107
+ }
1108
+ async function closeRecordedHardDeletedKind(target, schema, graphId, removal, ownsWriteLock) {
1109
+ const recordedCommit = await allocateRecordedCommit(
1110
+ target,
1111
+ schema,
1112
+ graphId,
1113
+ ownsWriteLock
1114
+ );
1115
+ if (removal.entity === "node") {
1116
+ await closeOpenByKind(
1117
+ target,
1118
+ schema.recordedNodesTable,
1119
+ graphId,
1120
+ removal.kind,
1121
+ recordedCommit
1122
+ );
1123
+ await closeOpenEdgesByNodeKind(
1124
+ target,
1125
+ schema,
1126
+ graphId,
1127
+ removal.kind,
1128
+ recordedCommit
1129
+ );
1130
+ return;
1131
+ }
1132
+ await closeOpenByKind(
1133
+ target,
1134
+ schema.recordedEdgesTable,
1135
+ graphId,
1136
+ removal.kind,
1137
+ recordedCommit
1138
+ );
1139
+ }
1140
+ async function queryConnectedEdgeIds(target, schema, params) {
1141
+ const rows = await target.execute(
1142
+ asCompiledRowsSql(sql`
1143
+ SELECT id
1144
+ FROM ${schema.edgesTable}
1145
+ WHERE graph_id = ${params.graphId}
1146
+ AND (
1147
+ (from_kind = ${params.kind} AND from_id = ${params.id})
1148
+ OR (to_kind = ${params.kind} AND to_id = ${params.id})
1149
+ )
1150
+ `)
1151
+ );
1152
+ return rows.map((row) => row.id);
1153
+ }
1154
+
1155
+ // src/store/recorded-capture.ts
1156
+ var RECORDED_FLUSH_OBSERVER = /* @__PURE__ */ Symbol("typegraph.recordedFlushObserver");
1157
+ function readRecordedFlushObserver(options) {
1158
+ return options?.[RECORDED_FLUSH_OBSERVER];
1159
+ }
1160
+ function stripRecordedFlushObserver(options) {
1161
+ if (options === void 0) return void 0;
1162
+ const { [RECORDED_FLUSH_OBSERVER]: _observer, ...backendOptions } = options;
1163
+ return backendOptions;
1164
+ }
1165
+ function withRecordedFlushObserver(options, observer) {
1166
+ return {
1167
+ ...stripRecordedFlushObserver(options),
1168
+ [RECORDED_FLUSH_OBSERVER]: observer
1169
+ };
1170
+ }
1171
+ function nodeIdentityKey(graphId, kind, id) {
1172
+ return `${graphId}\0${kind}\0${id}`;
1173
+ }
1174
+ function nodeParamsIdentityKey(params) {
1175
+ return nodeIdentityKey(params.graphId, params.kind, params.id);
1176
+ }
1177
+ function nodeRowIdentityKey(row) {
1178
+ return nodeIdentityKey(row.graph_id, row.kind, row.id);
1179
+ }
1180
+ function edgeIdentityKey(graphId, id) {
1181
+ return `${graphId}\0${id}`;
1182
+ }
1183
+ function edgeParamsIdentityKey(params) {
1184
+ return edgeIdentityKey(params.graphId, params.id);
1185
+ }
1186
+ function edgeRowIdentityKey(row) {
1187
+ return edgeIdentityKey(row.graph_id, row.id);
1188
+ }
1189
+ function createRecordedCaptureSession() {
1190
+ const touched = /* @__PURE__ */ new Map();
1191
+ let sealed = false;
1192
+ function touch(entity) {
1193
+ if (sealed) {
1194
+ throw new ConfigurationError(
1195
+ "Recorded-time capture session is sealed: a graph write happened after the transaction's capture was flushed.",
1196
+ { entity: entity.entity, graphId: entity.graphId, id: entity.id },
1197
+ {
1198
+ suggestion: "Perform all writes inside the withRecordedTransaction callback; do not reuse the transaction context after it returns."
1199
+ }
1200
+ );
1201
+ }
1202
+ touched.set(entityKey(entity), entity);
1203
+ }
1204
+ return {
1205
+ touchNode(graphId, kind, id, afterImage) {
1206
+ touch({ entity: "node", graphId, kind, id, afterImage });
1207
+ },
1208
+ touchEdge(graphId, id, afterImage) {
1209
+ touch({ entity: "edge", graphId, id, afterImage });
1210
+ },
1211
+ async flush(target, schema, ownsWriteLock) {
1212
+ if (sealed) {
1213
+ throw new ConfigurationError(
1214
+ "Recorded-time capture session was already flushed.",
1215
+ {},
1216
+ {
1217
+ suggestion: "A capture scope flushes once at its terminal point; do not flush it twice."
1218
+ }
1219
+ );
1220
+ }
1221
+ sealed = true;
1222
+ if (touched.size === 0) return /* @__PURE__ */ new Map();
1223
+ const recordedByGraph = /* @__PURE__ */ new Map();
1224
+ const byGraph = groupBy(touched.values(), (entity) => entity.graphId);
1225
+ for (const [graphId, entities] of byGraph) {
1226
+ const recordedCommit = await allocateRecordedCommit(
1227
+ target,
1228
+ schema,
1229
+ graphId,
1230
+ ownsWriteLock
1231
+ );
1232
+ recordedByGraph.set(graphId, recordedCommit);
1233
+ const nodes = entities.filter(
1234
+ (entity) => entity.entity === "node"
1235
+ );
1236
+ const edges = entities.filter(
1237
+ (entity) => entity.entity === "edge"
1238
+ );
1239
+ await flushNodes(target, schema, graphId, nodes, recordedCommit);
1240
+ await flushEdges(target, schema, graphId, edges, recordedCommit);
1241
+ }
1242
+ touched.clear();
1243
+ return recordedByGraph;
1244
+ }
1245
+ };
1246
+ }
1247
+ function createRecordedTransactionBackend(target, session, schema) {
1248
+ const nodeDispatch = nodeInsertDispatch(target);
1249
+ const edgeDispatch = edgeInsertDispatch(target);
1250
+ const graphLocks = createRecordedGraphLockMemo();
1251
+ async function lockGraph(graphId) {
1252
+ await lockRecordedGraphWrite(target, graphId, graphLocks);
1253
+ }
1254
+ async function lockGraphs(params) {
1255
+ const graphIds = [
1256
+ ...new Set(params.map((parameter) => parameter.graphId))
1257
+ ].toSorted();
1258
+ for (const graphId of graphIds) {
1259
+ await lockRecordedGraphWrite(target, graphId, graphLocks);
1260
+ }
1261
+ }
1262
+ const overlay = createBackendOverlay(target, {
1263
+ ...rawWriteGuards(target, "tx.backend"),
1264
+ async insertNode(params) {
1265
+ await lockGraph(params.graphId);
1266
+ const row = await target.insertNode(params);
1267
+ session.touchNode(params.graphId, params.kind, params.id, row);
1268
+ return row;
1269
+ },
1270
+ ...target.insertNodeNoReturn === void 0 ? {} : {
1271
+ async insertNodeNoReturn(params) {
1272
+ await lockGraph(params.graphId);
1273
+ await runInsertNoReturn(nodeDispatch, params);
1274
+ session.touchNode(params.graphId, params.kind, params.id);
1275
+ }
1276
+ },
1277
+ ...target.insertNodesBatch === void 0 ? {} : {
1278
+ async insertNodesBatch(params) {
1279
+ await lockGraphs(params);
1280
+ await runInsertBatch(nodeDispatch, params);
1281
+ for (const node of params) {
1282
+ session.touchNode(node.graphId, node.kind, node.id);
1283
+ }
1284
+ }
1285
+ },
1286
+ ...target.insertNodesBatchReturning === void 0 ? {} : {
1287
+ async insertNodesBatchReturning(params) {
1288
+ await lockGraphs(params);
1289
+ const rows = await runInsertBatchReturning(nodeDispatch, params);
1290
+ const rowsByIdentity = new Map(
1291
+ rows.map((row) => [nodeRowIdentityKey(row), row])
1292
+ );
1293
+ for (const node of params) {
1294
+ session.touchNode(
1295
+ node.graphId,
1296
+ node.kind,
1297
+ node.id,
1298
+ rowsByIdentity.get(nodeParamsIdentityKey(node))
1299
+ );
1300
+ }
1301
+ return rows;
1302
+ }
1303
+ },
1304
+ async updateNode(params) {
1305
+ await lockGraph(params.graphId);
1306
+ const row = await target.updateNode(params);
1307
+ session.touchNode(params.graphId, params.kind, params.id, row);
1308
+ return row;
1309
+ },
1310
+ async deleteNode(params) {
1311
+ await lockGraph(params.graphId);
1312
+ await target.deleteNode(params);
1313
+ session.touchNode(params.graphId, params.kind, params.id);
1314
+ },
1315
+ async hardDeleteNode(params) {
1316
+ await lockGraph(params.graphId);
1317
+ const connectedEdgeIds = await queryConnectedEdgeIds(
1318
+ target,
1319
+ schema,
1320
+ params
1321
+ );
1322
+ await target.hardDeleteNode(params);
1323
+ session.touchNode(params.graphId, params.kind, params.id);
1324
+ for (const edgeId of connectedEdgeIds) {
1325
+ session.touchEdge(params.graphId, edgeId);
1326
+ }
1327
+ },
1328
+ async insertEdge(params) {
1329
+ await lockGraph(params.graphId);
1330
+ const row = await target.insertEdge(params);
1331
+ session.touchEdge(params.graphId, params.id, row);
1332
+ return row;
1333
+ },
1334
+ ...target.insertEdgeNoReturn === void 0 ? {} : {
1335
+ async insertEdgeNoReturn(params) {
1336
+ await lockGraph(params.graphId);
1337
+ await runInsertNoReturn(edgeDispatch, params);
1338
+ session.touchEdge(params.graphId, params.id);
1339
+ }
1340
+ },
1341
+ ...target.insertEdgesBatch === void 0 ? {} : {
1342
+ async insertEdgesBatch(params) {
1343
+ await lockGraphs(params);
1344
+ await runInsertBatch(edgeDispatch, params);
1345
+ for (const edge of params) {
1346
+ session.touchEdge(edge.graphId, edge.id);
1347
+ }
1348
+ }
1349
+ },
1350
+ ...target.insertEdgesBatchReturning === void 0 ? {} : {
1351
+ async insertEdgesBatchReturning(params) {
1352
+ await lockGraphs(params);
1353
+ const rows = await runInsertBatchReturning(edgeDispatch, params);
1354
+ const rowsByIdentity = new Map(
1355
+ rows.map((row) => [edgeRowIdentityKey(row), row])
1356
+ );
1357
+ for (const edge of params) {
1358
+ session.touchEdge(
1359
+ edge.graphId,
1360
+ edge.id,
1361
+ rowsByIdentity.get(edgeParamsIdentityKey(edge))
1362
+ );
1363
+ }
1364
+ return rows;
1365
+ }
1366
+ },
1367
+ async updateEdge(params) {
1368
+ await lockGraph(params.graphId);
1369
+ const row = await target.updateEdge(params);
1370
+ session.touchEdge(params.graphId, params.id, row);
1371
+ return row;
1372
+ },
1373
+ async deleteEdge(params) {
1374
+ await lockGraph(params.graphId);
1375
+ await target.deleteEdge(params);
1376
+ session.touchEdge(params.graphId, params.id);
1377
+ },
1378
+ async hardDeleteEdge(params) {
1379
+ await lockGraph(params.graphId);
1380
+ await target.hardDeleteEdge(params);
1381
+ session.touchEdge(params.graphId, params.id);
1382
+ },
1383
+ ...target.deleteEdgesBatch === void 0 ? {} : {
1384
+ async deleteEdgesBatch(params) {
1385
+ await lockGraph(params.graphId);
1386
+ await target.deleteEdgesBatch(params);
1387
+ for (const id of params.ids) {
1388
+ session.touchEdge(params.graphId, id);
1389
+ }
1390
+ }
1391
+ },
1392
+ ...target.hardDeleteEdgesBatch === void 0 ? {} : {
1393
+ async hardDeleteEdgesBatch(params) {
1394
+ await lockGraph(params.graphId);
1395
+ await target.hardDeleteEdgesBatch(params);
1396
+ for (const id of params.ids) {
1397
+ session.touchEdge(params.graphId, id);
1398
+ }
1399
+ }
1400
+ }
1401
+ });
1402
+ registerRecordedGraphLockMemo(overlay, graphLocks);
1403
+ return overlay;
1404
+ }
1405
+ function createRecordedTransactionScope(target, schema, ownsWriteLock = false) {
1406
+ requireCaptureStatements(target);
1407
+ const session = createRecordedCaptureSession();
1408
+ const resolvedSchema = schema ?? requireRecordedSchema(target);
1409
+ return {
1410
+ backend: createRecordedTransactionBackend(target, session, resolvedSchema),
1411
+ async flush() {
1412
+ return withRecordedRelationsPrecondition(
1413
+ session.flush(target, resolvedSchema, ownsWriteLock),
1414
+ { dialect: target.dialect, surface: "capture-flush" }
1415
+ );
1416
+ }
1417
+ };
1418
+ }
1419
+ async function runCapturedAutocommit(backend, schema, fn, options) {
1420
+ assertRequestedRecordedIsolation(backend, options);
1421
+ return backend.transaction(async (target) => {
1422
+ await assertRecordedCaptureTransactionIsolation(target);
1423
+ const scope = createRecordedTransactionScope(target, schema, true);
1424
+ const result = await fn(scope.backend);
1425
+ await scope.flush();
1426
+ return result;
1427
+ }, options);
1428
+ }
1429
+ function createRecordedBackend(backend, schema) {
1430
+ assertCapturableBackend(backend);
1431
+ const capture = (fn) => runCapturedAutocommit(backend, schema, fn);
1432
+ return createBackendOverlay(backend, {
1433
+ ...rawWriteGuards(backend, "backend"),
1434
+ async insertNode(params) {
1435
+ return capture((target) => target.insertNode(params));
1436
+ },
1437
+ ...backend.insertNodeNoReturn === void 0 ? {} : {
1438
+ async insertNodeNoReturn(params) {
1439
+ await capture(
1440
+ (target) => runInsertNoReturn(nodeInsertDispatch(target), params)
1441
+ );
1442
+ }
1443
+ },
1444
+ ...backend.insertNodesBatch === void 0 ? {} : {
1445
+ async insertNodesBatch(params) {
1446
+ await capture(
1447
+ (target) => runInsertBatch(nodeInsertDispatch(target), params)
1448
+ );
1449
+ }
1450
+ },
1451
+ ...backend.insertNodesBatchReturning === void 0 ? {} : {
1452
+ async insertNodesBatchReturning(params) {
1453
+ return capture(
1454
+ (target) => runInsertBatchReturning(nodeInsertDispatch(target), params)
1455
+ );
1456
+ }
1457
+ },
1458
+ async updateNode(params) {
1459
+ return capture((target) => target.updateNode(params));
1460
+ },
1461
+ async deleteNode(params) {
1462
+ await capture((target) => target.deleteNode(params));
1463
+ },
1464
+ async hardDeleteNode(params) {
1465
+ await capture((target) => target.hardDeleteNode(params));
1466
+ },
1467
+ async insertEdge(params) {
1468
+ return capture((target) => target.insertEdge(params));
1469
+ },
1470
+ ...backend.insertEdgeNoReturn === void 0 ? {} : {
1471
+ async insertEdgeNoReturn(params) {
1472
+ await capture(
1473
+ (target) => runInsertNoReturn(edgeInsertDispatch(target), params)
1474
+ );
1475
+ }
1476
+ },
1477
+ ...backend.insertEdgesBatch === void 0 ? {} : {
1478
+ async insertEdgesBatch(params) {
1479
+ await capture(
1480
+ (target) => runInsertBatch(edgeInsertDispatch(target), params)
1481
+ );
1482
+ }
1483
+ },
1484
+ ...backend.insertEdgesBatchReturning === void 0 ? {} : {
1485
+ async insertEdgesBatchReturning(params) {
1486
+ return capture(
1487
+ (target) => runInsertBatchReturning(edgeInsertDispatch(target), params)
1488
+ );
1489
+ }
1490
+ },
1491
+ async updateEdge(params) {
1492
+ return capture((target) => target.updateEdge(params));
1493
+ },
1494
+ async deleteEdge(params) {
1495
+ await capture((target) => target.deleteEdge(params));
1496
+ },
1497
+ async hardDeleteEdge(params) {
1498
+ await capture((target) => target.hardDeleteEdge(params));
1499
+ },
1500
+ ...backend.deleteEdgesBatch === void 0 ? {} : {
1501
+ async deleteEdgesBatch(params) {
1502
+ await capture((target) => target.deleteEdgesBatch(params));
1503
+ }
1504
+ },
1505
+ ...backend.hardDeleteEdgesBatch === void 0 ? {} : {
1506
+ async hardDeleteEdgesBatch(params) {
1507
+ await capture((target) => target.hardDeleteEdgesBatch(params));
1508
+ }
1509
+ },
1510
+ async transaction(fn, options) {
1511
+ const observer = readRecordedFlushObserver(options);
1512
+ const backendOptions = stripRecordedFlushObserver(options);
1513
+ assertRequestedRecordedIsolation(backend, backendOptions);
1514
+ return backend.transaction(async (target) => {
1515
+ await assertRecordedCaptureTransactionIsolation(target);
1516
+ const scope = createRecordedTransactionScope(target, schema, true);
1517
+ const result = await fn(scope.backend, createHistoryUnsafeSqlRef());
1518
+ const instants = await scope.flush();
1519
+ observer?.(instants);
1520
+ return result;
1521
+ }, backendOptions);
1522
+ },
1523
+ ...backend.adoptTransaction === void 0 ? {} : {
1524
+ adoptTransaction(externalTx) {
1525
+ throw recordedCaptureRequiresCallbackTransactionError({
1526
+ externalTxType: typeof externalTx
1527
+ });
1528
+ }
1529
+ }
1530
+ });
1531
+ }
1532
+
1533
+ // src/store/embedding-sync.ts
1534
+ var embeddingFieldsCache = /* @__PURE__ */ new WeakMap();
1535
+ function getEmbeddingFields(schema) {
1536
+ const cached = embeddingFieldsCache.get(schema);
1537
+ if (cached) return cached;
1538
+ const fields = resolveEmbeddingFields(schema);
1539
+ embeddingFieldsCache.set(schema, fields);
1540
+ return fields;
1541
+ }
1542
+ async function syncEmbeddings(ctx, schema, props) {
1543
+ const { backend } = ctx;
1544
+ if (!backend.upsertEmbedding || !backend.deleteEmbedding) {
1545
+ return;
1546
+ }
1547
+ const embeddingFields = getEmbeddingFields(schema);
1548
+ if (embeddingFields.length === 0) {
1549
+ return;
1550
+ }
1551
+ for (const field of embeddingFields) {
1552
+ const value = props[field.fieldPath];
1553
+ if (isValidEmbeddingValue(value)) {
1554
+ await backend.upsertEmbedding({
1555
+ graphId: ctx.graphId,
1556
+ nodeKind: ctx.nodeKind,
1557
+ nodeId: ctx.nodeId,
1558
+ fieldPath: field.fieldPath,
1559
+ embedding: value,
1560
+ dimensions: field.dimensions,
1561
+ metric: field.metric,
1562
+ indexType: field.indexType
1563
+ });
1564
+ } else if (value === void 0) {
1565
+ await backend.deleteEmbedding({
1566
+ graphId: ctx.graphId,
1567
+ nodeKind: ctx.nodeKind,
1568
+ nodeId: ctx.nodeId,
1569
+ fieldPath: field.fieldPath,
1570
+ dimensions: field.dimensions,
1571
+ metric: field.metric,
1572
+ indexType: field.indexType
1573
+ });
1574
+ }
1575
+ }
1576
+ }
1577
+ async function syncEmbeddingsBatchForKind(args, schema, items) {
1578
+ const { graphId, nodeKind, backend } = args;
1579
+ if (!backend.upsertEmbedding || !backend.deleteEmbedding) {
1580
+ return;
1581
+ }
1582
+ const embeddingFields = getEmbeddingFields(schema);
1583
+ if (embeddingFields.length === 0) {
1584
+ return;
1585
+ }
1586
+ for (const field of embeddingFields) {
1587
+ const rows = [];
1588
+ const deletionIds = [];
1589
+ for (const item of items) {
1590
+ const value = item.props[field.fieldPath];
1591
+ if (isValidEmbeddingValue(value)) {
1592
+ rows.push({ nodeId: item.nodeId, embedding: value });
1593
+ } else if (value === void 0) {
1594
+ deletionIds.push(item.nodeId);
1595
+ }
1596
+ }
1597
+ if (rows.length > 0) {
1598
+ if (backend.upsertEmbeddingBatch === void 0) {
1599
+ for (const row of rows) {
1600
+ await backend.upsertEmbedding({
1601
+ graphId,
1602
+ nodeKind,
1603
+ nodeId: row.nodeId,
1604
+ fieldPath: field.fieldPath,
1605
+ embedding: row.embedding,
1606
+ dimensions: field.dimensions,
1607
+ metric: field.metric,
1608
+ indexType: field.indexType
1609
+ });
1610
+ }
1611
+ } else {
1612
+ await backend.upsertEmbeddingBatch({
1613
+ graphId,
1614
+ nodeKind,
1615
+ fieldPath: field.fieldPath,
1616
+ dimensions: field.dimensions,
1617
+ metric: field.metric,
1618
+ indexType: field.indexType,
1619
+ rows
1620
+ });
1621
+ }
1622
+ }
1623
+ for (const nodeId of deletionIds) {
1624
+ await backend.deleteEmbedding({
1625
+ graphId,
1626
+ nodeKind,
1627
+ nodeId,
1628
+ fieldPath: field.fieldPath,
1629
+ dimensions: field.dimensions,
1630
+ metric: field.metric,
1631
+ indexType: field.indexType
1632
+ });
1633
+ }
1634
+ }
1635
+ }
1636
+ async function deleteNodeEmbeddings(ctx, schema) {
1637
+ const { backend } = ctx;
1638
+ if (!backend.deleteEmbedding) {
1639
+ return;
1640
+ }
1641
+ const embeddingFields = getEmbeddingFields(schema);
1642
+ if (embeddingFields.length === 0) {
1643
+ return;
1644
+ }
1645
+ for (const field of embeddingFields) {
1646
+ await backend.deleteEmbedding({
1647
+ graphId: ctx.graphId,
1648
+ nodeKind: ctx.nodeKind,
1649
+ nodeId: ctx.nodeId,
1650
+ fieldPath: field.fieldPath,
1651
+ dimensions: field.dimensions,
1652
+ metric: field.metric,
1653
+ indexType: field.indexType
1654
+ });
1655
+ }
1656
+ }
1657
+ function isValidEmbeddingValue(value) {
1658
+ if (!Array.isArray(value)) {
1659
+ return false;
1660
+ }
1661
+ return value.every((n) => typeof n === "number" && Number.isFinite(n));
1662
+ }
1663
+
1664
+ // src/store/fulltext-sync.ts
1665
+ var FIELD_SEPARATOR = "\n";
1666
+ function resolveCombinedLanguage(fields) {
1667
+ return fields[0]?.metadata.language ?? DEFAULT_SEARCHABLE_LANGUAGE;
1668
+ }
1669
+ function computeFulltextContent(schema, props) {
1670
+ const searchableFields = getSearchableFields(schema);
1671
+ if (searchableFields.length === 0) return void 0;
1672
+ const parts = [];
1673
+ for (const field of searchableFields) {
1674
+ const value = props[field.fieldPath];
1675
+ if (typeof value === "string" && value.length > 0) {
1676
+ parts.push(value);
1677
+ }
1678
+ }
1679
+ if (parts.length === 0) return void 0;
1680
+ return {
1681
+ content: parts.join(FIELD_SEPARATOR),
1682
+ language: resolveCombinedLanguage(searchableFields)
1683
+ };
1684
+ }
1685
+ async function syncFulltext(ctx, schema, props) {
1686
+ const { backend } = ctx;
1687
+ if (!backend.upsertFulltext || !backend.deleteFulltext) {
1688
+ return;
1689
+ }
1690
+ const computed = computeFulltextContent(schema, props);
1691
+ if (computed !== void 0) {
1692
+ await backend.upsertFulltext({
1693
+ graphId: ctx.graphId,
1694
+ nodeKind: ctx.nodeKind,
1695
+ nodeId: ctx.nodeId,
1696
+ content: computed.content,
1697
+ language: computed.language
1698
+ });
1699
+ return;
1700
+ }
1701
+ if (getSearchableFields(schema).length === 0) return;
1702
+ await backend.deleteFulltext({
1703
+ graphId: ctx.graphId,
1704
+ nodeKind: ctx.nodeKind,
1705
+ nodeId: ctx.nodeId
1706
+ });
1707
+ }
1708
+ async function syncFulltextBatchForKind(args, schema, items) {
1709
+ const { graphId, nodeKind, backend } = args;
1710
+ if (!backend.upsertFulltext || !backend.deleteFulltext) {
1711
+ return;
1712
+ }
1713
+ const rows = [];
1714
+ const emptyContentIds = [];
1715
+ const hasSearchableFields = getSearchableFields(schema).length > 0;
1716
+ for (const item of items) {
1717
+ const computed = computeFulltextContent(schema, item.props);
1718
+ if (computed !== void 0) {
1719
+ rows.push({
1720
+ nodeId: item.nodeId,
1721
+ content: computed.content,
1722
+ language: computed.language
1723
+ });
1724
+ } else if (hasSearchableFields) {
1725
+ emptyContentIds.push(item.nodeId);
1726
+ }
1727
+ }
1728
+ if (rows.length > 0) {
1729
+ if (backend.upsertFulltextBatch === void 0) {
1730
+ for (const row of rows) {
1731
+ await backend.upsertFulltext({
1732
+ graphId,
1733
+ nodeKind,
1734
+ nodeId: row.nodeId,
1735
+ content: row.content,
1736
+ language: row.language
1737
+ });
1738
+ }
1739
+ } else {
1740
+ await backend.upsertFulltextBatch({ graphId, nodeKind, rows });
1741
+ }
1742
+ }
1743
+ if (emptyContentIds.length > 0) {
1744
+ if (backend.deleteFulltextBatch === void 0) {
1745
+ for (const nodeId of emptyContentIds) {
1746
+ await backend.deleteFulltext({ graphId, nodeKind, nodeId });
1747
+ }
1748
+ } else {
1749
+ await backend.deleteFulltextBatch({
1750
+ graphId,
1751
+ nodeKind,
1752
+ nodeIds: emptyContentIds
1753
+ });
1754
+ }
1755
+ }
1756
+ }
1757
+ async function deleteNodeFulltext(ctx, schema) {
1758
+ const { backend } = ctx;
1759
+ if (!backend.deleteFulltext) {
1760
+ return;
1761
+ }
1762
+ if (getSearchableFields(schema).length === 0) {
1763
+ return;
1764
+ }
1765
+ await backend.deleteFulltext({
1766
+ graphId: ctx.graphId,
1767
+ nodeKind: ctx.nodeKind,
1768
+ nodeId: ctx.nodeId
1769
+ });
1770
+ }
1771
+
1772
+ // src/constraints/index.ts
1773
+ var UNIQUE_KEY_SEPARATOR = "";
1774
+ var UNIQUE_KEY_NULL_MARKER = "";
1775
+ function computeUniqueKey(props, fields, collation) {
1776
+ const values = fields.map((field) => {
1777
+ const value = props[field];
1778
+ if (value === void 0 || value === null) {
1779
+ return UNIQUE_KEY_NULL_MARKER;
1780
+ }
1781
+ const stringValue = typeof value === "string" ? value : typeof value === "number" || typeof value === "boolean" ? value.toString() : JSON.stringify(value);
1782
+ return collation === "caseInsensitive" ? stringValue.toLowerCase() : stringValue;
1783
+ });
1784
+ return values.join(UNIQUE_KEY_SEPARATOR);
1785
+ }
1786
+ function checkWherePredicate(constraint, props) {
1787
+ if (!constraint.where) {
1788
+ return true;
1789
+ }
1790
+ const predicateBuilder = buildPredicateContext(props);
1791
+ const predicate = constraint.where(predicateBuilder);
1792
+ return evaluatePredicate(predicate, props);
1793
+ }
1794
+ function buildPredicateContext(props) {
1795
+ const context = {};
1796
+ for (const key of Object.keys(props)) {
1797
+ context[key] = {
1798
+ isNull: () => ({
1799
+ __type: "unique_predicate",
1800
+ field: key,
1801
+ op: "isNull"
1802
+ }),
1803
+ isNotNull: () => ({
1804
+ __type: "unique_predicate",
1805
+ field: key,
1806
+ op: "isNotNull"
1807
+ })
1808
+ };
1809
+ }
1810
+ return context;
1811
+ }
1812
+ function evaluatePredicate(predicate, props) {
1813
+ if (typeof predicate !== "object" || predicate === null || !("__type" in predicate)) {
1814
+ return true;
1815
+ }
1816
+ const pred = predicate;
1817
+ if (pred.__type !== "unique_predicate") {
1818
+ return true;
1819
+ }
1820
+ const value = props[pred.field];
1821
+ if (pred.op === "isNull") {
1822
+ return value === null || value === void 0;
1823
+ }
1824
+ return isPresent(value);
1825
+ }
1826
+ function getKindsForUniquenessCheck(baseKind, scope, registry) {
1827
+ if (scope === "kind") {
1828
+ return [baseKind];
1829
+ }
1830
+ const root = findRootAncestor(baseKind, registry);
1831
+ return registry.expandSubClasses(root);
1832
+ }
1833
+ function findRootAncestor(kind, registry) {
1834
+ const ancestors = registry.getAncestors(kind);
1835
+ if (ancestors.size === 0) {
1836
+ return kind;
1837
+ }
1838
+ for (const ancestor of ancestors) {
1839
+ if (registry.getAncestors(ancestor).size === 0) {
1840
+ return ancestor;
1841
+ }
1842
+ }
1843
+ const firstAncestor = [...ancestors][0];
1844
+ return firstAncestor ? findRootAncestor(firstAncestor, registry) : kind;
1845
+ }
1846
+ function checkCardinality(edgeKind, fromKind, fromId, cardinality, existingEdgeCount, hasActiveEdge) {
1847
+ switch (cardinality) {
1848
+ case "many": {
1849
+ return void 0;
1850
+ }
1851
+ case "one": {
1852
+ if (existingEdgeCount > 0) {
1853
+ return new CardinalityError({
1854
+ edgeKind,
1855
+ fromKind,
1856
+ fromId,
1857
+ cardinality: "one",
1858
+ existingCount: existingEdgeCount
1859
+ });
1860
+ }
1861
+ return void 0;
1862
+ }
1863
+ case "unique": {
1864
+ return void 0;
1865
+ }
1866
+ case "oneActive": {
1867
+ if (hasActiveEdge) {
1868
+ return new CardinalityError({
1869
+ edgeKind,
1870
+ fromKind,
1871
+ fromId,
1872
+ cardinality: "oneActive",
1873
+ existingCount: 1
1874
+ });
1875
+ }
1876
+ return void 0;
1877
+ }
1878
+ }
1879
+ }
1880
+ function checkUniqueEdge(edgeKind, fromKind, fromId, _toKind, _toId, existingCount) {
1881
+ if (existingCount > 0) {
1882
+ return new CardinalityError({
1883
+ edgeKind,
1884
+ fromKind,
1885
+ fromId,
1886
+ cardinality: "unique",
1887
+ existingCount
1888
+ });
1889
+ }
1890
+ return void 0;
1891
+ }
1892
+ function validateEdgeEndpoints(edgeKind, fromKind, toKind, registration, registry) {
1893
+ const validFromKinds = registration.from.map((node) => node.kind);
1894
+ if (!registry.isAssignableToAny(fromKind, validFromKinds)) {
1895
+ return new EndpointError({
1896
+ edgeKind,
1897
+ endpoint: "from",
1898
+ actualKind: fromKind,
1899
+ expectedKinds: validFromKinds
1900
+ });
1901
+ }
1902
+ const validToKinds = registration.to.map((node) => node.kind);
1903
+ if (!registry.isAssignableToAny(toKind, validToKinds)) {
1904
+ return new EndpointError({
1905
+ edgeKind,
1906
+ endpoint: "to",
1907
+ actualKind: toKind,
1908
+ expectedKinds: validToKinds
1909
+ });
1910
+ }
1911
+ return void 0;
1912
+ }
1913
+ function checkDisjointness(nodeId, nodeKind, existingKinds, registry) {
1914
+ for (const existingKind of existingKinds) {
1915
+ if (registry.areDisjoint(nodeKind, existingKind)) {
1916
+ return new DisjointError({
1917
+ nodeId,
1918
+ attemptedKind: nodeKind,
1919
+ conflictingKind: existingKind
1920
+ });
1921
+ }
1922
+ }
1923
+ return void 0;
1924
+ }
1925
+
1926
+ // src/store/uniqueness.ts
1927
+ function createUniquenessContext(graphId, registry, backend) {
1928
+ return { graphId, registry, backend };
1929
+ }
1930
+ async function checkUniquenessConstraints(ctx, kind, id, props, constraints) {
1931
+ for (const constraint of constraints) {
1932
+ if (!checkWherePredicate(constraint, props)) {
1933
+ continue;
1934
+ }
1935
+ const key = computeUniqueKey(
1936
+ props,
1937
+ constraint.fields,
1938
+ constraint.collation
1939
+ );
1940
+ const kindsToCheck = getKindsForUniquenessCheck(
1941
+ kind,
1942
+ constraint.scope,
1943
+ ctx.registry
1944
+ );
1945
+ for (const kindToCheck of kindsToCheck) {
1946
+ const existing = await ctx.backend.checkUnique({
1947
+ graphId: ctx.graphId,
1948
+ nodeKind: kindToCheck,
1949
+ constraintName: constraint.name,
1950
+ key
1951
+ });
1952
+ if (existing && existing.node_id !== id) {
1953
+ throw new UniquenessError({
1954
+ constraintName: constraint.name,
1955
+ kind: kindToCheck,
1956
+ existingId: existing.node_id,
1957
+ newId: id,
1958
+ fields: constraint.fields
1959
+ });
1960
+ }
1961
+ }
1962
+ }
1963
+ }
1964
+ async function insertUniquenessEntries(ctx, kind, id, props, constraints) {
1965
+ for (const constraint of constraints) {
1966
+ if (!checkWherePredicate(constraint, props)) {
1967
+ continue;
1968
+ }
1969
+ const key = computeUniqueKey(
1970
+ props,
1971
+ constraint.fields,
1972
+ constraint.collation
1973
+ );
1974
+ await ctx.backend.insertUnique({
1975
+ graphId: ctx.graphId,
1976
+ nodeKind: kind,
1977
+ constraintName: constraint.name,
1978
+ key,
1979
+ nodeId: id,
1980
+ concreteKind: kind
1981
+ });
1982
+ }
1983
+ }
1984
+ async function insertUniquenessEntriesBatch(ctx, items) {
1985
+ const entries = [];
1986
+ for (const item of items) {
1987
+ for (const constraint of item.constraints) {
1988
+ if (!checkWherePredicate(constraint, item.props)) {
1989
+ continue;
1990
+ }
1991
+ entries.push({
1992
+ graphId: ctx.graphId,
1993
+ nodeKind: item.kind,
1994
+ constraintName: constraint.name,
1995
+ key: computeUniqueKey(
1996
+ item.props,
1997
+ constraint.fields,
1998
+ constraint.collation
1999
+ ),
2000
+ nodeId: item.id,
2001
+ concreteKind: item.kind
2002
+ });
2003
+ }
2004
+ }
2005
+ if (entries.length === 0) return;
2006
+ if (ctx.backend.insertUniqueBatch !== void 0) {
2007
+ await ctx.backend.insertUniqueBatch(entries);
2008
+ return;
2009
+ }
2010
+ for (const entry of entries) {
2011
+ await ctx.backend.insertUnique(entry);
2012
+ }
2013
+ }
2014
+ async function deleteUniquenessEntries(ctx, kind, props, constraints) {
2015
+ for (const constraint of constraints) {
2016
+ if (!checkWherePredicate(constraint, props)) {
2017
+ continue;
2018
+ }
2019
+ const key = computeUniqueKey(
2020
+ props,
2021
+ constraint.fields,
2022
+ constraint.collation
2023
+ );
2024
+ await ctx.backend.deleteUnique({
2025
+ graphId: ctx.graphId,
2026
+ nodeKind: kind,
2027
+ constraintName: constraint.name,
2028
+ key
2029
+ });
2030
+ }
2031
+ }
2032
+ async function updateUniquenessEntries(ctx, kind, id, oldProps, newProps, constraints) {
2033
+ const pending = [];
2034
+ for (const constraint of constraints) {
2035
+ const oldApplies = checkWherePredicate(constraint, oldProps);
2036
+ const newApplies = checkWherePredicate(constraint, newProps);
2037
+ const oldKey = oldApplies ? computeUniqueKey(oldProps, constraint.fields, constraint.collation) : void 0;
2038
+ const newKey = newApplies ? computeUniqueKey(newProps, constraint.fields, constraint.collation) : void 0;
2039
+ if (!oldApplies && !newApplies) {
2040
+ continue;
2041
+ }
2042
+ if (oldApplies && newApplies && oldKey === newKey) {
2043
+ continue;
2044
+ }
2045
+ if (newApplies && newKey !== void 0) {
2046
+ const kindsToCheck = getKindsForUniquenessCheck(
2047
+ kind,
2048
+ constraint.scope,
2049
+ ctx.registry
2050
+ );
2051
+ for (const kindToCheck of kindsToCheck) {
2052
+ const existing = await ctx.backend.checkUnique({
2053
+ graphId: ctx.graphId,
2054
+ nodeKind: kindToCheck,
2055
+ constraintName: constraint.name,
2056
+ key: newKey
2057
+ });
2058
+ if (existing && existing.node_id !== id) {
2059
+ throw new UniquenessError({
2060
+ constraintName: constraint.name,
2061
+ kind: kindToCheck,
2062
+ existingId: existing.node_id,
2063
+ newId: id,
2064
+ fields: constraint.fields
2065
+ });
2066
+ }
2067
+ }
2068
+ }
2069
+ pending.push({ constraintName: constraint.name, oldKey, newKey });
2070
+ }
2071
+ for (const mutation of pending) {
2072
+ if (mutation.oldKey !== void 0) {
2073
+ await ctx.backend.deleteUnique({
2074
+ graphId: ctx.graphId,
2075
+ nodeKind: kind,
2076
+ constraintName: mutation.constraintName,
2077
+ key: mutation.oldKey
2078
+ });
2079
+ }
2080
+ }
2081
+ for (const mutation of pending) {
2082
+ if (mutation.newKey !== void 0) {
2083
+ await ctx.backend.insertUnique({
2084
+ graphId: ctx.graphId,
2085
+ nodeKind: kind,
2086
+ constraintName: mutation.constraintName,
2087
+ key: mutation.newKey,
2088
+ nodeId: id,
2089
+ concreteKind: kind
2090
+ });
2091
+ }
2092
+ }
2093
+ }
2094
+
2095
+ // src/store/operations/node-write-pipeline.ts
2096
+ function createNodeWriteContext(graphId, registry, lock) {
2097
+ return { graphId, registry, lock };
2098
+ }
2099
+ function uniquenessContext(ctx, backend) {
2100
+ return createUniquenessContext(ctx.graphId, ctx.registry, backend);
2101
+ }
2102
+ function nodeSyncContext(ctx, kind, id, backend) {
2103
+ return { graphId: ctx.graphId, nodeKind: kind, nodeId: id, backend };
2104
+ }
2105
+ async function enforceNodeDeleteBehavior(ctx, args, backend, policy) {
2106
+ if (policy?.enforceDeleteBehavior === false) return;
2107
+ const behavior = args.onDelete ?? "restrict";
2108
+ const connectedEdges = await backend.findEdgesConnectedTo({
2109
+ graphId: ctx.graphId,
2110
+ nodeKind: args.kind,
2111
+ nodeId: args.id
2112
+ });
2113
+ if (connectedEdges.length === 0) return;
2114
+ switch (behavior) {
2115
+ case "restrict": {
2116
+ throw new RestrictedDeleteError({
2117
+ nodeKind: args.kind,
2118
+ nodeId: args.id,
2119
+ edgeCount: connectedEdges.length,
2120
+ edgeKinds: [...new Set(connectedEdges.map((edge) => edge.kind))]
2121
+ });
2122
+ }
2123
+ case "cascade":
2124
+ case "disconnect": {
2125
+ const batchDelete = args.mode === "hard" ? backend.hardDeleteEdgesBatch : backend.deleteEdgesBatch;
2126
+ if (batchDelete !== void 0) {
2127
+ await batchDelete.call(backend, {
2128
+ graphId: ctx.graphId,
2129
+ ids: connectedEdges.map((edge) => edge.id)
2130
+ });
2131
+ break;
2132
+ }
2133
+ for (const edge of connectedEdges) {
2134
+ await (args.mode === "hard" ? backend.hardDeleteEdge({ graphId: ctx.graphId, id: edge.id }) : backend.deleteEdge({ graphId: ctx.graphId, id: edge.id }));
2135
+ }
2136
+ break;
2137
+ }
2138
+ }
2139
+ }
2140
+ async function applyNodeInsertSideEffects(ctx, args, backend) {
2141
+ await insertUniquenessEntries(
2142
+ uniquenessContext(ctx, backend),
2143
+ args.kind,
2144
+ args.id,
2145
+ args.props,
2146
+ args.uniqueConstraints
2147
+ );
2148
+ await Promise.all([
2149
+ syncEmbeddings(
2150
+ nodeSyncContext(ctx, args.kind, args.id, backend),
2151
+ args.schema,
2152
+ args.props
2153
+ ),
2154
+ syncFulltext(
2155
+ nodeSyncContext(ctx, args.kind, args.id, backend),
2156
+ args.schema,
2157
+ args.props
2158
+ )
2159
+ ]);
2160
+ }
2161
+ async function applyNodeInsertSideEffectsBatch(ctx, items, backend) {
2162
+ if (items.length === 0) return;
2163
+ await insertUniquenessEntriesBatch(
2164
+ uniquenessContext(ctx, backend),
2165
+ items.map((item) => ({
2166
+ kind: item.kind,
2167
+ id: item.id,
2168
+ props: item.props,
2169
+ constraints: item.uniqueConstraints
2170
+ }))
2171
+ );
2172
+ const byKind = /* @__PURE__ */ new Map();
2173
+ for (const item of items) {
2174
+ const group = byKind.get(item.kind) ?? { schema: item.schema, rows: [] };
2175
+ group.rows.push({ nodeId: item.id, props: item.props });
2176
+ byKind.set(item.kind, group);
2177
+ }
2178
+ await Promise.all(
2179
+ [...byKind.entries()].flatMap(([kind, group]) => {
2180
+ const syncArguments = { graphId: ctx.graphId, nodeKind: kind, backend };
2181
+ return [
2182
+ syncEmbeddingsBatchForKind(syncArguments, group.schema, group.rows),
2183
+ syncFulltextBatchForKind(syncArguments, group.schema, group.rows)
2184
+ ];
2185
+ })
2186
+ );
2187
+ }
2188
+ function parseRowProps(row) {
2189
+ return rowPropsToObject(row.props);
2190
+ }
2191
+ async function applyNodeUpdate(ctx, args, backend) {
2192
+ const { kind, id } = args.existing;
2193
+ if (args.existing.deleted_at === void 0) {
2194
+ await updateUniquenessEntries(
2195
+ uniquenessContext(ctx, backend),
2196
+ kind,
2197
+ id,
2198
+ parseRowProps(args.existing),
2199
+ args.validatedProps,
2200
+ args.uniqueConstraints
2201
+ );
2202
+ } else {
2203
+ await checkUniquenessConstraints(
2204
+ uniquenessContext(ctx, backend),
2205
+ kind,
2206
+ id,
2207
+ args.validatedProps,
2208
+ args.uniqueConstraints
2209
+ );
2210
+ await insertUniquenessEntries(
2211
+ uniquenessContext(ctx, backend),
2212
+ kind,
2213
+ id,
2214
+ args.validatedProps,
2215
+ args.uniqueConstraints
2216
+ );
2217
+ }
2218
+ const updateParams = {
2219
+ graphId: ctx.graphId,
2220
+ kind,
2221
+ id,
2222
+ props: args.validatedProps,
2223
+ incrementVersion: true
2224
+ };
2225
+ if (args.validTo !== void 0) updateParams.validTo = args.validTo;
2226
+ if (args.clearDeleted) updateParams.clearDeleted = true;
2227
+ const row = await backend.updateNode(updateParams);
2228
+ await Promise.all([
2229
+ syncEmbeddings(
2230
+ nodeSyncContext(ctx, kind, id, backend),
2231
+ args.schema,
2232
+ args.validatedProps
2233
+ ),
2234
+ syncFulltext(
2235
+ nodeSyncContext(ctx, kind, id, backend),
2236
+ args.schema,
2237
+ args.validatedProps
2238
+ )
2239
+ ]);
2240
+ return row;
2241
+ }
2242
+ async function applyNodeSoftDelete(ctx, args, backend, policy) {
2243
+ const { kind, id } = args.existing;
2244
+ await enforceNodeDeleteBehavior(
2245
+ ctx,
2246
+ { kind, id, mode: "soft", onDelete: args.onDelete },
2247
+ backend,
2248
+ policy
2249
+ );
2250
+ await backend.deleteNode({
2251
+ graphId: ctx.graphId,
2252
+ kind,
2253
+ id
2254
+ });
2255
+ await deleteUniquenessEntries(
2256
+ uniquenessContext(ctx, backend),
2257
+ kind,
2258
+ parseRowProps(args.existing),
2259
+ args.uniqueConstraints
2260
+ );
2261
+ await deleteNodeEmbeddings(
2262
+ nodeSyncContext(ctx, kind, id, backend),
2263
+ args.schema
2264
+ );
2265
+ await deleteNodeFulltext(
2266
+ nodeSyncContext(ctx, kind, id, backend),
2267
+ args.schema
2268
+ );
2269
+ }
2270
+ async function applyNodeHardDelete(ctx, args, backend) {
2271
+ await enforceNodeDeleteBehavior(
2272
+ ctx,
2273
+ { kind: args.kind, id: args.id, mode: "hard", onDelete: args.onDelete },
2274
+ backend
2275
+ );
2276
+ await backend.hardDeleteNode({
2277
+ graphId: ctx.graphId,
2278
+ kind: args.kind,
2279
+ id: args.id
2280
+ });
2281
+ await deleteNodeEmbeddings(
2282
+ nodeSyncContext(ctx, args.kind, args.id, backend),
2283
+ args.schema
2284
+ );
2285
+ }
2286
+ async function applyNodeResurrect(ctx, args, backend) {
2287
+ const { kind, id } = args.existing;
2288
+ const props = parseRowProps(args.existing);
2289
+ await checkUniquenessConstraints(
2290
+ uniquenessContext(ctx, backend),
2291
+ kind,
2292
+ id,
2293
+ props,
2294
+ args.uniqueConstraints
2295
+ );
2296
+ await insertUniquenessEntries(
2297
+ uniquenessContext(ctx, backend),
2298
+ kind,
2299
+ id,
2300
+ props,
2301
+ args.uniqueConstraints
2302
+ );
2303
+ const row = await backend.updateNode({
2304
+ graphId: ctx.graphId,
2305
+ kind,
2306
+ id,
2307
+ props,
2308
+ incrementVersion: true,
2309
+ clearDeleted: true
2310
+ });
2311
+ await Promise.all([
2312
+ syncEmbeddings(nodeSyncContext(ctx, kind, id, backend), args.schema, props),
2313
+ syncFulltext(nodeSyncContext(ctx, kind, id, backend), args.schema, props)
2314
+ ]);
2315
+ return row;
2316
+ }
2317
+
2318
+ export { ALIAS_CTE_PREFIX, DEFAULT_SQL_SCHEMA, EMBEDDINGS_CTE_ALIAS, FULLTEXT_CTE_ALIAS, HYBRID_CANDIDATES_CTE_ALIAS, advanceRevisionClock, applyNodeHardDelete, applyNodeInsertSideEffects, applyNodeInsertSideEffectsBatch, applyNodeResurrect, applyNodeSoftDelete, applyNodeUpdate, asRecordedInstant, assertRecordedCaptureTransactionIsolation, assertRevisionTrackableBackend, assertValidRecordedInstant, checkCardinality, checkDisjointness, checkUniqueEdge, checkUniquenessConstraints, checkWherePredicate, closeRecordedHardDeletedKind, computeFulltextContent, computeUniqueKey, coordinateContext, createHistoryUnsafeSqlRef, createNodeWriteContext, createRecordedBackend, createRecordedReadBinding, createRecordedTransactionScope, createRevisionTrackingUnsafeSqlRef, createSqlSchema, createUniquenessContext, describeCoordinate, edgeInsertDispatch, ensureRevisionOrigin, generateId, getEdgeRowsByIds, getEmbeddingFields, getKindsForUniquenessCheck, getNodeRowsByIds, lockRecordedGraphWrite, nodeInsertDispatch, readRecordedClock, readRevisionOrigin, recordedBindParamBudget, recordedCaptureRequiresCallbackTransactionError, recordedReadSchemaFor, recordedReadSqlSchema, recordedRelation, requireExternalRecordedReadSource, requireRecordedReadBinding, requireSqlSchema, resolveReadCoordinate, runInsertBatch, runInsertBatchReturning, runInsertNoReturn, uncapturedGraphWriteLock, validateEdgeEndpoints, vectorSlotKey, withRecordedCoordinate, withRecordedFlushObserver };
2319
+ //# sourceMappingURL=chunk-CZQ3FO2Q.js.map
2320
+ //# sourceMappingURL=chunk-CZQ3FO2Q.js.map