@nicia-ai/typegraph 0.46.0 → 0.46.2

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 (267) hide show
  1. package/dist/backend/drizzle/indexes.cjs +9 -9
  2. package/dist/backend/drizzle/indexes.d.cts +1 -1
  3. package/dist/backend/drizzle/indexes.d.ts +1 -1
  4. package/dist/backend/drizzle/indexes.js +5 -5
  5. package/dist/backend/index.cjs +49 -49
  6. package/dist/backend/index.d.cts +3 -3
  7. package/dist/backend/index.d.ts +3 -3
  8. package/dist/backend/index.js +10 -10
  9. package/dist/backend/postgres/index.cjs +26 -26
  10. package/dist/backend/postgres/index.d.cts +6 -6
  11. package/dist/backend/postgres/index.d.ts +6 -6
  12. package/dist/backend/postgres/index.js +13 -13
  13. package/dist/backend/postgres/pglite-store.cjs +33 -33
  14. package/dist/backend/postgres/pglite-store.d.cts +8 -8
  15. package/dist/backend/postgres/pglite-store.d.ts +8 -8
  16. package/dist/backend/postgres/pglite-store.js +29 -29
  17. package/dist/backend/postgres/pglite.cjs +15 -15
  18. package/dist/backend/postgres/pglite.d.cts +3 -3
  19. package/dist/backend/postgres/pglite.d.ts +3 -3
  20. package/dist/backend/postgres/pglite.js +14 -14
  21. package/dist/backend/sqlite/index.cjs +23 -23
  22. package/dist/backend/sqlite/index.d.cts +6 -6
  23. package/dist/backend/sqlite/index.d.ts +6 -6
  24. package/dist/backend/sqlite/index.js +11 -11
  25. package/dist/backend/sqlite/libsql.cjs +18 -18
  26. package/dist/backend/sqlite/libsql.d.cts +3 -3
  27. package/dist/backend/sqlite/libsql.d.ts +3 -3
  28. package/dist/backend/sqlite/libsql.js +13 -13
  29. package/dist/backend/sqlite/local-store.cjs +34 -34
  30. package/dist/backend/sqlite/local-store.d.cts +8 -8
  31. package/dist/backend/sqlite/local-store.d.ts +8 -8
  32. package/dist/backend/sqlite/local-store.js +30 -30
  33. package/dist/backend/sqlite/local.cjs +16 -16
  34. package/dist/backend/sqlite/local.d.cts +3 -3
  35. package/dist/backend/sqlite/local.d.ts +3 -3
  36. package/dist/backend/sqlite/local.js +14 -14
  37. package/dist/{chunk-VCRRKBLN.cjs → chunk-2ZWM2RFH.cjs} +9 -9
  38. package/dist/{chunk-VCRRKBLN.cjs.map → chunk-2ZWM2RFH.cjs.map} +1 -1
  39. package/dist/{chunk-TTAITEPJ.cjs → chunk-32UETY6S.cjs} +26 -26
  40. package/dist/chunk-32UETY6S.cjs.map +1 -0
  41. package/dist/{chunk-JXA2ZP2Q.js → chunk-36LIJXWC.js} +4 -4
  42. package/dist/{chunk-JXA2ZP2Q.js.map → chunk-36LIJXWC.js.map} +1 -1
  43. package/dist/{chunk-Q7Q4WSLJ.cjs → chunk-5PDSCELM.cjs} +18 -14
  44. package/dist/chunk-5PDSCELM.cjs.map +1 -0
  45. package/dist/{chunk-775A4ZMN.js → chunk-5ZJOB5YS.js} +4 -4
  46. package/dist/{chunk-775A4ZMN.js.map → chunk-5ZJOB5YS.js.map} +1 -1
  47. package/dist/{chunk-J3WZ3FA2.js → chunk-62ZXBMSD.js} +24 -3
  48. package/dist/chunk-62ZXBMSD.js.map +1 -0
  49. package/dist/{chunk-7BQXPCGN.cjs → chunk-6BD6ZBKT.cjs} +10 -10
  50. package/dist/{chunk-7BQXPCGN.cjs.map → chunk-6BD6ZBKT.cjs.map} +1 -1
  51. package/dist/chunk-6LAXM4J2.cjs +12 -0
  52. package/dist/{chunk-VQH4VAWD.cjs.map → chunk-6LAXM4J2.cjs.map} +1 -1
  53. package/dist/{chunk-MSY7FSX4.js → chunk-72WUT4GG.js} +4 -4
  54. package/dist/{chunk-MSY7FSX4.js.map → chunk-72WUT4GG.js.map} +1 -1
  55. package/dist/chunk-73MWKDFK.cjs +12 -0
  56. package/dist/{chunk-A4OC4DVN.cjs.map → chunk-73MWKDFK.cjs.map} +1 -1
  57. package/dist/{chunk-BKCUOV7A.js → chunk-7TKNK32B.js} +5 -5
  58. package/dist/{chunk-BKCUOV7A.js.map → chunk-7TKNK32B.js.map} +1 -1
  59. package/dist/{chunk-JIVMTW7W.js → chunk-A2LJG5GM.js} +9 -9
  60. package/dist/{chunk-JIVMTW7W.js.map → chunk-A2LJG5GM.js.map} +1 -1
  61. package/dist/{chunk-XMQSEJCF.cjs → chunk-A4R3H7RU.cjs} +237 -237
  62. package/dist/{chunk-XMQSEJCF.cjs.map → chunk-A4R3H7RU.cjs.map} +1 -1
  63. package/dist/{chunk-RMQLSPA2.cjs → chunk-A7NMUYEL.cjs} +27 -27
  64. package/dist/{chunk-RMQLSPA2.cjs.map → chunk-A7NMUYEL.cjs.map} +1 -1
  65. package/dist/{chunk-U63GDNRC.cjs → chunk-AF3TWL5C.cjs} +4 -4
  66. package/dist/{chunk-U63GDNRC.cjs.map → chunk-AF3TWL5C.cjs.map} +1 -1
  67. package/dist/{chunk-XBYVV3MP.cjs → chunk-ANKOXPCC.cjs} +4 -4
  68. package/dist/chunk-ANKOXPCC.cjs.map +1 -0
  69. package/dist/{chunk-OH5E5KIO.js → chunk-AT3MLMJV.js} +10 -10
  70. package/dist/{chunk-OH5E5KIO.js.map → chunk-AT3MLMJV.js.map} +1 -1
  71. package/dist/{chunk-UV3SN74I.js → chunk-AU3IJNNP.js} +5 -5
  72. package/dist/{chunk-UV3SN74I.js.map → chunk-AU3IJNNP.js.map} +1 -1
  73. package/dist/{chunk-YAAM3M2S.cjs → chunk-BEB4OFZF.cjs} +10 -10
  74. package/dist/{chunk-YAAM3M2S.cjs.map → chunk-BEB4OFZF.cjs.map} +1 -1
  75. package/dist/{chunk-7GT72YHH.cjs → chunk-BQM5P2NO.cjs} +169 -167
  76. package/dist/chunk-BQM5P2NO.cjs.map +1 -0
  77. package/dist/{chunk-YWGVVALJ.js → chunk-BRN3RGD2.js} +3 -3
  78. package/dist/{chunk-YWGVVALJ.js.map → chunk-BRN3RGD2.js.map} +1 -1
  79. package/dist/{chunk-UDISNXDL.cjs → chunk-BZZI7B43.cjs} +47 -47
  80. package/dist/{chunk-UDISNXDL.cjs.map → chunk-BZZI7B43.cjs.map} +1 -1
  81. package/dist/{chunk-TQR4KBY2.cjs → chunk-C2ZP5YS6.cjs} +135 -133
  82. package/dist/chunk-C2ZP5YS6.cjs.map +1 -0
  83. package/dist/{chunk-PNN7RHVR.cjs → chunk-C4DYN2SD.cjs} +48 -48
  84. package/dist/{chunk-PNN7RHVR.cjs.map → chunk-C4DYN2SD.cjs.map} +1 -1
  85. package/dist/{chunk-XDF2UPEQ.cjs → chunk-C6KE2HSQ.cjs} +1364 -1311
  86. package/dist/chunk-C6KE2HSQ.cjs.map +1 -0
  87. package/dist/{chunk-LBJKZXDE.cjs → chunk-D6GCNNMK.cjs} +10 -10
  88. package/dist/{chunk-LBJKZXDE.cjs.map → chunk-D6GCNNMK.cjs.map} +1 -1
  89. package/dist/{chunk-JZUR7ZWE.js → chunk-DSAWGCMP.js} +3 -3
  90. package/dist/{chunk-JZUR7ZWE.js.map → chunk-DSAWGCMP.js.map} +1 -1
  91. package/dist/{chunk-U5SON7R2.cjs → chunk-DYPRZ53S.cjs} +27 -27
  92. package/dist/{chunk-U5SON7R2.cjs.map → chunk-DYPRZ53S.cjs.map} +1 -1
  93. package/dist/{chunk-YVWGEQJE.cjs → chunk-E4OSGBCM.cjs} +139 -133
  94. package/dist/chunk-E4OSGBCM.cjs.map +1 -0
  95. package/dist/{chunk-YDFDBE6D.js → chunk-EAMVXR5B.js} +4 -4
  96. package/dist/{chunk-YDFDBE6D.js.map → chunk-EAMVXR5B.js.map} +1 -1
  97. package/dist/{chunk-NQ6BRJBE.js → chunk-EDHV4CBU.js} +8 -8
  98. package/dist/{chunk-NQ6BRJBE.js.map → chunk-EDHV4CBU.js.map} +1 -1
  99. package/dist/{chunk-DCQVHAYQ.js → chunk-EDJDDY6H.js} +4 -4
  100. package/dist/{chunk-DCQVHAYQ.js.map → chunk-EDJDDY6H.js.map} +1 -1
  101. package/dist/{chunk-5262ZMTR.js → chunk-EJSYWAEV.js} +5 -5
  102. package/dist/{chunk-5262ZMTR.js.map → chunk-EJSYWAEV.js.map} +1 -1
  103. package/dist/{chunk-N3257XE6.cjs → chunk-F36KZDFX.cjs} +91 -91
  104. package/dist/{chunk-N3257XE6.cjs.map → chunk-F36KZDFX.cjs.map} +1 -1
  105. package/dist/{chunk-AKLS3BYZ.js → chunk-FA6Z7B5L.js} +3 -3
  106. package/dist/chunk-FA6Z7B5L.js.map +1 -0
  107. package/dist/{chunk-ASTI57H3.js → chunk-FCIZNUW5.js} +3 -3
  108. package/dist/{chunk-ASTI57H3.js.map → chunk-FCIZNUW5.js.map} +1 -1
  109. package/dist/{chunk-CBTIUB76.js → chunk-FSLTU57P.js} +3 -3
  110. package/dist/{chunk-CBTIUB76.js.map → chunk-FSLTU57P.js.map} +1 -1
  111. package/dist/{chunk-2LG2XB2M.js → chunk-FXNHZFZV.js} +3 -3
  112. package/dist/{chunk-2LG2XB2M.js.map → chunk-FXNHZFZV.js.map} +1 -1
  113. package/dist/{chunk-BSFJMMV3.cjs → chunk-GVAMRRZR.cjs} +4 -4
  114. package/dist/{chunk-BSFJMMV3.cjs.map → chunk-GVAMRRZR.cjs.map} +1 -1
  115. package/dist/{chunk-CNV4TXJG.js → chunk-GWUWRZXW.js} +3 -3
  116. package/dist/{chunk-CNV4TXJG.js.map → chunk-GWUWRZXW.js.map} +1 -1
  117. package/dist/{chunk-C23WSN5E.js → chunk-GWXXHOLU.js} +20 -14
  118. package/dist/chunk-GWXXHOLU.js.map +1 -0
  119. package/dist/{chunk-ONU3HIED.cjs → chunk-HNYLMPQQ.cjs} +68 -68
  120. package/dist/{chunk-ONU3HIED.cjs.map → chunk-HNYLMPQQ.cjs.map} +1 -1
  121. package/dist/{chunk-NMWDXFPH.js → chunk-IHRDX7K6.js} +4 -4
  122. package/dist/{chunk-NMWDXFPH.js.map → chunk-IHRDX7K6.js.map} +1 -1
  123. package/dist/{chunk-VGTJPTIC.js → chunk-JCNTKRAK.js} +5 -5
  124. package/dist/{chunk-VGTJPTIC.js.map → chunk-JCNTKRAK.js.map} +1 -1
  125. package/dist/{chunk-MXJDTH5B.cjs → chunk-JL5UEBWT.cjs} +45 -45
  126. package/dist/{chunk-MXJDTH5B.cjs.map → chunk-JL5UEBWT.cjs.map} +1 -1
  127. package/dist/{chunk-QLRESYPU.js → chunk-KA4L2NZ3.js} +14 -14
  128. package/dist/{chunk-QLRESYPU.js.map → chunk-KA4L2NZ3.js.map} +1 -1
  129. package/dist/{chunk-NI72YOJB.cjs → chunk-KCH7WQA5.cjs} +24 -2
  130. package/dist/chunk-KCH7WQA5.cjs.map +1 -0
  131. package/dist/{chunk-2NA5DYLO.cjs → chunk-KOAI3KIV.cjs} +4 -4
  132. package/dist/{chunk-2NA5DYLO.cjs.map → chunk-KOAI3KIV.cjs.map} +1 -1
  133. package/dist/{chunk-7VQXLT5O.js → chunk-KXSMF6PL.js} +101 -25
  134. package/dist/chunk-KXSMF6PL.js.map +1 -0
  135. package/dist/{chunk-WEVQJ5LH.js → chunk-LHYSY6SE.js} +6 -6
  136. package/dist/chunk-LHYSY6SE.js.map +1 -0
  137. package/dist/{chunk-WDGA7IYB.js → chunk-LNIWCQR4.js} +3 -3
  138. package/dist/{chunk-WDGA7IYB.js.map → chunk-LNIWCQR4.js.map} +1 -1
  139. package/dist/{chunk-XNSI2FJO.cjs → chunk-N3QTGPC7.cjs} +99 -99
  140. package/dist/{chunk-XNSI2FJO.cjs.map → chunk-N3QTGPC7.cjs.map} +1 -1
  141. package/dist/{chunk-K5ELX2GT.js → chunk-OZJCH7ZS.js} +3 -3
  142. package/dist/{chunk-K5ELX2GT.js.map → chunk-OZJCH7ZS.js.map} +1 -1
  143. package/dist/{chunk-62ZP23AW.cjs → chunk-PYKF7UIL.cjs} +13 -13
  144. package/dist/{chunk-62ZP23AW.cjs.map → chunk-PYKF7UIL.cjs.map} +1 -1
  145. package/dist/{chunk-PQBQG7IM.js → chunk-QOJ2L2AD.js} +3 -3
  146. package/dist/{chunk-PQBQG7IM.js.map → chunk-QOJ2L2AD.js.map} +1 -1
  147. package/dist/{chunk-XNLIZYRZ.cjs → chunk-QPOQX2DI.cjs} +235 -235
  148. package/dist/{chunk-XNLIZYRZ.cjs.map → chunk-QPOQX2DI.cjs.map} +1 -1
  149. package/dist/{chunk-NFCVHQ5P.cjs → chunk-QU7QLJA4.cjs} +26 -26
  150. package/dist/{chunk-NFCVHQ5P.cjs.map → chunk-QU7QLJA4.cjs.map} +1 -1
  151. package/dist/{chunk-DLNROMQ7.js → chunk-R7EWHKID.js} +7 -4
  152. package/dist/chunk-R7EWHKID.js.map +1 -0
  153. package/dist/{chunk-HFHTMECK.js → chunk-RFDEYLIK.js} +7 -7
  154. package/dist/{chunk-HFHTMECK.js.map → chunk-RFDEYLIK.js.map} +1 -1
  155. package/dist/{chunk-MUK4BU7K.cjs → chunk-RHDOAQCT.cjs} +200 -124
  156. package/dist/chunk-RHDOAQCT.cjs.map +1 -0
  157. package/dist/{chunk-YBFHZUXX.js → chunk-S3G5VLSW.js} +6 -6
  158. package/dist/{chunk-YBFHZUXX.js.map → chunk-S3G5VLSW.js.map} +1 -1
  159. package/dist/{chunk-M4BDU5RX.cjs → chunk-S7WIRFNS.cjs} +12 -12
  160. package/dist/{chunk-M4BDU5RX.cjs.map → chunk-S7WIRFNS.cjs.map} +1 -1
  161. package/dist/{chunk-T4XNKYXB.js → chunk-SXWLLQ3D.js} +4 -4
  162. package/dist/{chunk-T4XNKYXB.js.map → chunk-SXWLLQ3D.js.map} +1 -1
  163. package/dist/{chunk-NK5Q7UNE.cjs → chunk-TCT66A7N.cjs} +10 -10
  164. package/dist/{chunk-NK5Q7UNE.cjs.map → chunk-TCT66A7N.cjs.map} +1 -1
  165. package/dist/{chunk-3DHZCOT7.cjs → chunk-UTVQPZPN.cjs} +20 -20
  166. package/dist/{chunk-3DHZCOT7.cjs.map → chunk-UTVQPZPN.cjs.map} +1 -1
  167. package/dist/{chunk-CXBHOOIQ.cjs → chunk-WA64ZSCA.cjs} +11 -11
  168. package/dist/{chunk-CXBHOOIQ.cjs.map → chunk-WA64ZSCA.cjs.map} +1 -1
  169. package/dist/{chunk-QWX5YA3K.js → chunk-WEJHA7AD.js} +18 -16
  170. package/dist/chunk-WEJHA7AD.js.map +1 -0
  171. package/dist/{chunk-5UVRGXD3.js → chunk-WHS2Y43J.js} +5 -5
  172. package/dist/{chunk-5UVRGXD3.js.map → chunk-WHS2Y43J.js.map} +1 -1
  173. package/dist/{chunk-I5MOXA4H.js → chunk-WMKEGJG4.js} +3 -3
  174. package/dist/{chunk-I5MOXA4H.js.map → chunk-WMKEGJG4.js.map} +1 -1
  175. package/dist/{chunk-5763DULU.js → chunk-WYFB7BN3.js} +16 -14
  176. package/dist/chunk-WYFB7BN3.js.map +1 -0
  177. package/dist/{chunk-XQSCL77R.cjs → chunk-XBHRKLZU.cjs} +4 -4
  178. package/dist/{chunk-XQSCL77R.cjs.map → chunk-XBHRKLZU.cjs.map} +1 -1
  179. package/dist/{chunk-7Z5OR7KO.js → chunk-YQ4JONWE.js} +102 -49
  180. package/dist/chunk-YQ4JONWE.js.map +1 -0
  181. package/dist/{chunk-RJS7DECT.js → chunk-Z43KWLZF.js} +8 -8
  182. package/dist/{chunk-RJS7DECT.js.map → chunk-Z43KWLZF.js.map} +1 -1
  183. package/dist/{chunk-E4WNQBEF.cjs → chunk-ZBVZ7HXD.cjs} +12 -12
  184. package/dist/{chunk-E4WNQBEF.cjs.map → chunk-ZBVZ7HXD.cjs.map} +1 -1
  185. package/dist/{chunk-4UGOKMI5.cjs → chunk-ZHOAZD7Q.cjs} +161 -161
  186. package/dist/{chunk-4UGOKMI5.cjs.map → chunk-ZHOAZD7Q.cjs.map} +1 -1
  187. package/dist/{chunk-XCAGZAKP.cjs → chunk-ZIH42CRX.cjs} +7 -7
  188. package/dist/{chunk-XCAGZAKP.cjs.map → chunk-ZIH42CRX.cjs.map} +1 -1
  189. package/dist/core/index.cjs +27 -27
  190. package/dist/core/index.d.cts +4 -4
  191. package/dist/core/index.d.ts +4 -4
  192. package/dist/core/index.js +7 -7
  193. package/dist/{ddl-BJcOp4WZ.d.cts → ddl-mE07h_EM.d.cts} +3 -3
  194. package/dist/{ddl-BXfGHbPN.d.ts → ddl-opIn8DfX.d.ts} +3 -3
  195. package/dist/graph-extension/index.cjs +20 -20
  196. package/dist/graph-extension/index.d.cts +4 -4
  197. package/dist/graph-extension/index.d.ts +4 -4
  198. package/dist/graph-extension/index.js +4 -4
  199. package/dist/graph-merge/index.cjs +248 -248
  200. package/dist/graph-merge/index.d.cts +8 -8
  201. package/dist/graph-merge/index.d.ts +8 -8
  202. package/dist/graph-merge/index.js +24 -24
  203. package/dist/{index-DxaYCv8Y.d.cts → index-Deyu8IXL.d.ts} +20 -3
  204. package/dist/{index-BSHvKfok.d.ts → index-DrRS51Ld.d.cts} +20 -3
  205. package/dist/index.cjs +219 -215
  206. package/dist/index.d.cts +11 -11
  207. package/dist/index.d.ts +11 -11
  208. package/dist/index.js +34 -34
  209. package/dist/indexes/index.cjs +13 -13
  210. package/dist/indexes/index.d.cts +4 -4
  211. package/dist/indexes/index.d.ts +4 -4
  212. package/dist/indexes/index.js +6 -6
  213. package/dist/interchange/index.cjs +52 -52
  214. package/dist/interchange/index.d.cts +7 -7
  215. package/dist/interchange/index.d.ts +7 -7
  216. package/dist/interchange/index.js +16 -16
  217. package/dist/{manager-CfZAimti.d.ts → manager-DX983gJ0.d.ts} +2 -2
  218. package/dist/{manager-HGk6E_HW.d.cts → manager-ptr3JLRP.d.cts} +2 -2
  219. package/dist/{materialize-indexes-6A7dWGtb.d.cts → materialize-indexes-BXz77YqO.d.cts} +1 -1
  220. package/dist/{materialize-indexes-BMJP6Tms.d.ts → materialize-indexes-CpXoggWU.d.ts} +1 -1
  221. package/dist/{postgres-DFYWENdR.d.cts → postgres-DwgEXSPI.d.cts} +1 -1
  222. package/dist/{postgres-e7a9TdvR.d.ts → postgres-QdOMHTBz.d.ts} +1 -1
  223. package/dist/profiler/index.d.cts +9 -9
  224. package/dist/profiler/index.d.ts +9 -9
  225. package/dist/provenance/index.cjs +42 -42
  226. package/dist/provenance/index.d.cts +7 -7
  227. package/dist/provenance/index.d.ts +7 -7
  228. package/dist/provenance/index.js +9 -9
  229. package/dist/schema/index.cjs +44 -44
  230. package/dist/schema/index.d.cts +6 -6
  231. package/dist/schema/index.d.ts +6 -6
  232. package/dist/schema/index.js +17 -17
  233. package/dist/{searchable-9OQoPuRs.d.ts → searchable-BOUuA83f.d.ts} +1 -1
  234. package/dist/{searchable-CIje5XYD.d.cts → searchable-BrUh0pdc.d.cts} +1 -1
  235. package/dist/{sqlite-DerU5tc7.d.ts → sqlite-BfYcV61E.d.cts} +1 -1
  236. package/dist/{sqlite-DitnISa9.d.cts → sqlite-DK40XVR1.d.ts} +1 -1
  237. package/dist/{store-DawaWWjJ.d.ts → store-Bo1psfVZ.d.ts} +27 -8
  238. package/dist/{store-RwTJx8LX.d.cts → store-FTqBpuJD.d.cts} +27 -8
  239. package/dist/{temporal-Bn-Fi8FJ.d.cts → temporal-CXewwLTB.d.cts} +1 -1
  240. package/dist/{temporal-BtM4UALv.d.ts → temporal-DPtn0HOu.d.ts} +1 -1
  241. package/dist/{types-KFfk-8Ah.d.ts → types-CeT7xM4M.d.ts} +1 -1
  242. package/dist/{types-HkveCCx0.d.cts → types-Du78EvpN.d.cts} +7 -6
  243. package/dist/{types-HkveCCx0.d.ts → types-Du78EvpN.d.ts} +7 -6
  244. package/dist/{types-CoIx8HX5.d.cts → types-XR1nHERK.d.cts} +1 -1
  245. package/dist/{where--fk7_0kv.d.cts → where-CJsp-YUf.d.cts} +1 -1
  246. package/dist/{where-ws5hf-Ov.d.ts → where-CMbFiWwp.d.ts} +1 -1
  247. package/package.json +3 -3
  248. package/dist/chunk-5763DULU.js.map +0 -1
  249. package/dist/chunk-7GT72YHH.cjs.map +0 -1
  250. package/dist/chunk-7VQXLT5O.js.map +0 -1
  251. package/dist/chunk-7Z5OR7KO.js.map +0 -1
  252. package/dist/chunk-A4OC4DVN.cjs +0 -12
  253. package/dist/chunk-AKLS3BYZ.js.map +0 -1
  254. package/dist/chunk-C23WSN5E.js.map +0 -1
  255. package/dist/chunk-DLNROMQ7.js.map +0 -1
  256. package/dist/chunk-J3WZ3FA2.js.map +0 -1
  257. package/dist/chunk-MUK4BU7K.cjs.map +0 -1
  258. package/dist/chunk-NI72YOJB.cjs.map +0 -1
  259. package/dist/chunk-Q7Q4WSLJ.cjs.map +0 -1
  260. package/dist/chunk-QWX5YA3K.js.map +0 -1
  261. package/dist/chunk-TQR4KBY2.cjs.map +0 -1
  262. package/dist/chunk-TTAITEPJ.cjs.map +0 -1
  263. package/dist/chunk-VQH4VAWD.cjs +0 -12
  264. package/dist/chunk-WEVQJ5LH.js.map +0 -1
  265. package/dist/chunk-XBYVV3MP.cjs.map +0 -1
  266. package/dist/chunk-XDF2UPEQ.cjs.map +0 -1
  267. package/dist/chunk-YVWGEQJE.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/backend/drizzle/execution/sqlite-execution.ts","../src/backend/drizzle/sqlite.ts"],"names":["sql","executeCompiled","executeCompiledRun","executePreparedRunBatch","rows","chunk","tables","options"],"mappings":";;;;;;;;;;;;;AAoBA,IAAM,oCAAA,GAAuC,GAAA;AA8H7C,SAAS,eAAe,EAAA,EAA2C;AACjE,EAAA,MAAM,mBAAA,GAAsB,EAAA;AAC5B,EAAA,MAAM,kBAAA,GAAqB,mBAAA,CAAoB,OAAA,EAAS,WAAA,EAAa,IAAA;AACrE,EAAA,IAAI,uBAAuB,MAAA,EAAW;AACpC,IAAA,OAAO,kBAAA;AAAA,EACT;AAEA,EAAA,OAAO,mBAAA,CAAoB,CAAA,EAAG,OAAA,EAAS,WAAA,EAAa,IAAA;AACtD;AAEA,SAAS,0BAA0B,EAAA,EAAgC;AACjE,EAAA,OAAO,cAAA,CAAe,EAAE,CAAA,KAAM,iBAAA;AAChC;AAEA,SAAS,6BAA6B,EAAA,EAAgC;AACpE,E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AA;AAAA,IAC1B,gBAAgB,OAAA,CAAQ,cAAA;AAAA,IACxB,0BAA0B,OAAA,CAAQ,wBAAA;AAAA,IAClC,iBAAA,EAAmB;AAAA,GACpB,CAAA;AACH","file":"chunk-C23WSN5E.js","sourcesContent":["import { type SQL as DrizzleSql, sql } from \"drizzle-orm\";\nimport { type BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\nimport { isSqlFragment } from \"../../../query/sql-fragment\";\nimport {\n D1_MAX_BIND_PARAMETERS,\n DURABLE_OBJECT_MAX_BIND_PARAMETERS,\n MODERN_SQLITE_MAX_BIND_PARAMETERS,\n SQLITE_MAX_BIND_PARAMETERS,\n} from \"../../types\";\nimport { getOrCreateLru } from \"./lru\";\nimport {\n type CompiledSqlQuery,\n compileQueryWithDialect,\n type ExecutableSql,\n type PreparedSqlStatement,\n type SqlExecutionAdapter,\n toDrizzleSql,\n} from \"./types\";\n\nconst DEFAULT_PREPARED_STATEMENT_CACHE_MAX = 256;\n\ntype PreparedAllStatement = Readonly<{\n all: (...params: readonly unknown[]) => readonly unknown[];\n /**\n * Executes a statement that returns no rows. better-sqlite3 and\n * bun:sqlite both expose it; better-sqlite3 additionally REQUIRES it for\n * non-reader statements (`all()` on those throws).\n */\n run?: (...params: readonly unknown[]) => unknown;\n /**\n * better-sqlite3's \"does this statement return rows\" flag. bun:sqlite\n * has no equivalent; `undefined` is treated as non-reader on the run\n * path (bun's `run()` accepts any statement).\n */\n reader?: boolean;\n}>;\n\ntype SqliteClientWithPrepare = Readonly<{\n prepare: (sqlText: string) => PreparedAllStatement;\n}>;\n\ntype SqliteClientCarrier = Readonly<{ $client?: unknown }>;\n\ntype DurableObjectSqlApi = Readonly<{\n exec: (...args: readonly unknown[]) => unknown;\n}>;\n\n/**\n * Runtime shape of the Durable Object storage client exposed as\n * `drizzle(ctx.storage).$client`. Structural because Drizzle does not export\n * this client type and constructor names are not stable under bundling.\n */\nexport type DurableObjectStorageClient = Readonly<{\n sql: DurableObjectSqlApi;\n transaction: <Result>(run: () => Promise<Result>) => Promise<Result>;\n transactionSync: <Result>(run: () => Result) => Result;\n}>;\n\ntype SqliteHostedPlatform = \"d1\" | \"durable-object\";\n\ntype SessionLike = Readonly<{\n constructor?: Readonly<{\n name?: string;\n }>;\n}>;\n\ntype DatabaseWithSession = Readonly<{\n _?: Readonly<{\n session?: SessionLike;\n }>;\n session?: SessionLike;\n}>;\n\n/**\n * Controls how the backend manages SQLite transactions.\n *\n * - `\"sql\"`: TypeGraph issues BEGIN / COMMIT / ROLLBACK SQL directly on\n * the connection. Default for sync drivers (better-sqlite3,\n * bun:sqlite); also selected by `createLibsqlBackend` for\n * local `@libsql/client` connections (`file:` / `:memory:`),\n * whose `client.transaction()` permanently abandons the\n * current connection — fatal for an in-memory database.\n * - `\"drizzle\"`: Delegates to Drizzle's `db.transaction()` method.\n * Default for async drivers (remote libsql/Turso, sql.js).\n * - `\"do-sqlite\"`: Delegates to the Cloudflare Durable Objects async\n * storage transaction runner (`db.$client.transaction`,\n * i.e. `ctx.storage.transaction(async ...)`). Drizzle's\n * own `db.transaction()` on DO is\n * `ctx.storage.transactionSync` and cannot span `await`,\n * so it is deliberately not used. Auto-detected for\n * `drizzle(ctx.storage)` (#140).\n * - `\"none\"`: Transactions disabled. Default for Cloudflare D1\n * (`D1Database.batch` is transactional but not an\n * interactive runner — tracked separately).\n */\nexport type SqliteTransactionMode = \"sql\" | \"drizzle\" | \"none\" | \"do-sqlite\";\n\nexport type SqliteExecutionProfileHints = Readonly<{\n isSync?: boolean;\n transactionMode?: SqliteTransactionMode;\n}>;\n\ntype SqliteExecutionAdapterOptions = Readonly<{\n profileHints?: SqliteExecutionProfileHints;\n statementCacheMax?: number;\n}>;\n\nexport type AnySqliteDatabase = BaseSQLiteDatabase<\"sync\" | \"async\", unknown>;\n\nexport type SqliteExecutionProfile = Readonly<{\n /** Hosted runtime detected independently of caller-supplied hints. */\n hostedPlatform?: SqliteHostedPlatform;\n /** Platform ceiling that capability overrides may lower but never raise. */\n hardMaxBindParameters?: number;\n isSync: boolean;\n /**\n * Detected per-statement bound-parameter ceiling for this connection:\n * Cloudflare's documented D1 / Durable Objects cap, the probed\n * `SQLITE_MAX_VARIABLE_NUMBER` on synchronous drivers, or the conservative\n * 999 floor when the limit cannot be probed (async/remote drivers).\n */\n maxBindParameters: number;\n supportsCompiledExecution: boolean;\n transactionMode: SqliteTransactionMode;\n}>;\n\nexport type SqliteExecutionAdapter = Readonly<\n SqlExecutionAdapter & {\n clearStatementCache: () => void;\n profile: SqliteExecutionProfile;\n /**\n * Executes a compiled statement that returns no rows through the\n * prepared-statement cache. Present only on synchronous drivers with a\n * preparable client — the CRUD write path falls back to drizzle's\n * `db.run()` when absent.\n */\n executeCompiledRun?: (compiledQuery: CompiledSqlQuery) => Promise<void>;\n /** Rebinds one cached non-reader statement for every parameter row. */\n executePreparedRunBatch?: (\n sqlText: string,\n params: readonly (readonly unknown[])[],\n ) => Promise<void>;\n }\n>;\n\nfunction getSessionName(db: AnySqliteDatabase): string | undefined {\n const databaseWithSession = db as DatabaseWithSession;\n const primarySessionName = databaseWithSession.session?.constructor?.name;\n if (primarySessionName !== undefined) {\n return primarySessionName;\n }\n\n return databaseWithSession._?.session?.constructor?.name;\n}\n\nfunction isD1DatabaseBySessionName(db: AnySqliteDatabase): boolean {\n return getSessionName(db) === \"SQLiteD1Session\";\n}\n\nfunction isDurableObjectBySessionName(db: AnySqliteDatabase): boolean {\n const sessionName = getSessionName(db);\n // drizzle-orm/durable-sqlite's session class is `SQLiteDOSession`\n // (verified drizzle 0.45.x). `SQLiteDurableObjectSession` is kept as\n // a defensive alias against future drizzle renames.\n return (\n sessionName === \"SQLiteDOSession\" ||\n sessionName === \"SQLiteDurableObjectSession\"\n );\n}\n\nfunction isDurableObjectStorageClient(\n value: unknown,\n): value is DurableObjectStorageClient {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as Record<string, unknown>;\n const sqlApi = candidate[\"sql\"];\n return (\n typeof candidate[\"transaction\"] === \"function\" &&\n typeof candidate[\"transactionSync\"] === \"function\" &&\n typeof sqlApi === \"object\" &&\n sqlApi !== null &&\n typeof (sqlApi as Record<string, unknown>)[\"exec\"] === \"function\"\n );\n}\n\n/**\n * Returns the real Durable Object storage client when the Drizzle connection\n * exposes its distinctive async + sync transaction runners and SQL API.\n * Requiring the full shape avoids mistaking better-sqlite3's transaction\n * wrapper factory for the Durable Object async runner.\n */\nexport function getDurableObjectStorageClient(\n db: AnySqliteDatabase,\n): DurableObjectStorageClient | undefined {\n const client = (db as SqliteClientCarrier).$client;\n return isDurableObjectStorageClient(client) ? client : undefined;\n}\n\nfunction detectHostedPlatform(\n db: AnySqliteDatabase,\n): SqliteHostedPlatform | undefined {\n if (\n getDurableObjectStorageClient(db) !== undefined ||\n isDurableObjectBySessionName(db)\n ) {\n return \"durable-object\";\n }\n if (isD1DatabaseBySessionName(db)) return \"d1\";\n return undefined;\n}\n\nfunction isSyncDatabaseBySessionName(db: AnySqliteDatabase): boolean {\n const sessionName = getSessionName(db);\n return (\n sessionName === \"BetterSQLiteSession\" || sessionName === \"BunSQLiteSession\"\n );\n}\n\nfunction detectSyncProfile(\n db: AnySqliteDatabase,\n profileHints: SqliteExecutionProfileHints,\n hostedPlatform: SqliteHostedPlatform | undefined,\n): boolean {\n if (hostedPlatform === \"durable-object\") return true;\n if (hostedPlatform === \"d1\") return false;\n if (profileHints.isSync !== undefined) {\n return profileHints.isSync;\n }\n\n const sessionName = getSessionName(db);\n if (\n sessionName === \"BetterSQLiteSession\" ||\n sessionName === \"BunSQLiteSession\"\n ) {\n return true;\n }\n\n try {\n const probeResult = db.get(sql`SELECT 1 AS __typegraph_sync_probe__`);\n return !(probeResult instanceof Promise);\n } catch {\n return isSyncDatabaseBySessionName(db);\n }\n}\n\nfunction detectTransactionMode(\n profileHints: SqliteExecutionProfileHints,\n isSync: boolean,\n hostedPlatform: SqliteHostedPlatform | undefined,\n): SqliteTransactionMode {\n // Hosted platform identity is authoritative. A stale hint must not disable\n // Durable Object rollback or opt D1 into unsupported interactive writes.\n if (hostedPlatform === \"durable-object\") return \"do-sqlite\";\n if (hostedPlatform === \"d1\") return \"none\";\n if (profileHints.transactionMode !== undefined) {\n return profileHints.transactionMode;\n }\n // Neither D1 nor Durable Object SQLite supports raw BEGIN/COMMIT SQL\n // through Drizzle's db.run(), and Drizzle's own db.transaction() on\n // Durable Objects is `ctx.storage.transactionSync` (cannot span an\n // await). Durable Objects expose an async storage transaction runner\n // (`ctx.storage.transaction(async ...)`, surfaced by Drizzle as\n // `db.$client.transaction`) — route those through \"do-sqlite\" (#140).\n // D1 has no equivalent interactive runner (only batch); it stays\n // \"none\" pending a separate batch-mode investigation.\n if (isSync) return \"sql\";\n return \"drizzle\";\n}\n\n// SQLITE_MAX_VARIABLE_NUMBER's compiled-in default rose from 999 to 32,766\n// in SQLite 3.32.0. Builds that override the default list it in\n// `PRAGMA compile_options`; builds that keep it do not, so the version\n// decides the fallback.\nconst MAX_VARIABLE_NUMBER_COMPILE_OPTION = /^MAX_VARIABLE_NUMBER=(\\d+)$/;\nconst FIRST_MODERN_BIND_LIMIT_MAJOR = 3;\nconst FIRST_MODERN_BIND_LIMIT_MINOR = 32;\n\nfunction parseCompiledMaxVariableNumber(\n rows: readonly unknown[],\n): number | undefined {\n for (const row of rows) {\n if (typeof row !== \"object\" || row === null) continue;\n const option = (row as Record<string, unknown>)[\"compile_options\"];\n if (typeof option !== \"string\") continue;\n const match = MAX_VARIABLE_NUMBER_COMPILE_OPTION.exec(option);\n if (match !== null) return Number(match[1]);\n }\n return undefined;\n}\n\nfunction hasModernBindLimitByVersion(rows: readonly unknown[]): boolean {\n const first = rows[0];\n if (typeof first !== \"object\" || first === null) return false;\n const version = (first as Record<string, unknown>)[\"version\"];\n if (typeof version !== \"string\") return false;\n const [major = 0, minor = 0] = version.split(\".\").map(Number);\n if (!Number.isFinite(major) || !Number.isFinite(minor)) return false;\n return (\n major > FIRST_MODERN_BIND_LIMIT_MAJOR ||\n (major === FIRST_MODERN_BIND_LIMIT_MAJOR &&\n minor >= FIRST_MODERN_BIND_LIMIT_MINOR)\n );\n}\n\n/**\n * Resolves the connection's per-statement bound-parameter ceiling. Batch\n * chunk math derives from this value, so too high breaks batched writes at\n * runtime and too low wastes round trips (999 vs 32,766 is ~33× more\n * chunks per bulk insert).\n */\nfunction detectHardMaxBindParameters(\n transactionMode: SqliteTransactionMode,\n hostedPlatform: SqliteHostedPlatform | undefined,\n): number | undefined {\n if (hostedPlatform === \"durable-object\" || transactionMode === \"do-sqlite\") {\n return DURABLE_OBJECT_MAX_BIND_PARAMETERS;\n }\n if (hostedPlatform === \"d1\") return D1_MAX_BIND_PARAMETERS;\n return undefined;\n}\n\nfunction detectMaxBindParameters(\n sqliteClient: SqliteClientWithPrepare | undefined,\n hardMaxBindParameters: number | undefined,\n): number {\n if (hardMaxBindParameters !== undefined) return hardMaxBindParameters;\n if (sqliteClient === undefined) return SQLITE_MAX_BIND_PARAMETERS;\n try {\n const compiled = parseCompiledMaxVariableNumber(\n sqliteClient.prepare(\"PRAGMA compile_options\").all(),\n );\n if (compiled !== undefined) return compiled;\n const isModern = hasModernBindLimitByVersion(\n sqliteClient.prepare(\"SELECT sqlite_version() AS version\").all(),\n );\n return isModern ?\n MODERN_SQLITE_MAX_BIND_PARAMETERS\n : SQLITE_MAX_BIND_PARAMETERS;\n } catch {\n // A client that can't answer the probes keeps the conservative floor.\n return SQLITE_MAX_BIND_PARAMETERS;\n }\n}\n\n/**\n * The single spelling of \"this object prepares statements\": returns it as a\n * property bag when it does, `undefined` otherwise. Every driver predicate\n * below and {@link resolveSqliteClient} read it, so \"prepare-capable\" cannot\n * drift between the execution path and the serialized-resource marking.\n */\nfunction preparingClient(\n client: unknown,\n): Readonly<Record<string, unknown>> | undefined {\n if (typeof client !== \"object\" || client === null) return undefined;\n const candidate = client as Readonly<Record<string, unknown>>;\n return typeof candidate[\"prepare\"] === \"function\" ? candidate : undefined;\n}\n\n/** Whether every named member of `client` is a function. */\nfunction hasMethods(\n client: Readonly<Record<string, unknown>>,\n methods: readonly string[],\n): boolean {\n return methods.every((method) => typeof client[method] === \"function\");\n}\n\n/**\n * Whether a driver client is better-sqlite3's `Database`.\n *\n * `pragma` is the discriminator: better-sqlite3 exposes it as a method, and\n * none of the other prepare-capable SQLite clients (bun:sqlite, sql.js,\n * node:sqlite) has any counterpart. Duck-typed rather than `instanceof`, so\n * the native addon is never imported by this bundler-friendly module.\n */\nexport function isBetterSqlite3Client(client: unknown): boolean {\n const candidate = preparingClient(client);\n return candidate !== undefined && hasMethods(candidate, [\"pragma\"]);\n}\n\n/**\n * Whether a driver client is a `bun:sqlite` `Database` — what\n * `drizzle-orm/bun-sqlite` exposes as `$client`.\n *\n * ONE synchronous connection: every statement from every wrapper over it runs\n * on it, in order, exactly like better-sqlite3.\n *\n * Structural, never the session's constructor name (which bundlers rename):\n * verified against `bun-types` 1.3.x `bun:sqlite`, a `Database` carries\n * `query` (the cached-statement factory better-sqlite3 does not have),\n * `prepare`, `run`/`exec`, `serialize`, and a `filename` string — where\n * better-sqlite3 names that property `name` and sql.js has neither. The\n * combination is not satisfied by any other client this package can meet.\n */\nexport function isBunSqliteClient(client: unknown): boolean {\n const candidate = preparingClient(client);\n return (\n candidate !== undefined &&\n hasMethods(candidate, [\"query\", \"run\", \"exec\", \"serialize\"]) &&\n typeof candidate[\"filename\"] === \"string\"\n );\n}\n\n/**\n * Whether a driver client is a `sql.js` `Database` — what\n * `drizzle-orm/sql-js` takes as its client.\n *\n * ONE in-WASM database handle, executed synchronously in-process, so two\n * wrappers over it serialize exactly as two wrappers over one better-sqlite3\n * handle do.\n *\n * Structural evidence (verified against `@types/sql.js` 1.4.x): `export`\n * (dump the database to bytes) and `getRowsModified` are sql.js's own API and\n * exist on no other SQLite client — better-sqlite3 and bun:sqlite spell the\n * dump `serialize` and have no rows-modified method at all — alongside the\n * `prepare`/`exec`/`run` trio every driver has.\n */\nexport function isSqlJsClient(client: unknown): boolean {\n const candidate = preparingClient(client);\n return (\n candidate !== undefined &&\n hasMethods(candidate, [\"exec\", \"run\", \"export\", \"getRowsModified\"])\n );\n}\n\n/**\n * Returns the driver client a Drizzle SQLite database prepares statements on\n * for TypeGraph's COMPILED execution path, or `undefined` when it has none it\n * can drive.\n *\n * sql.js is excluded deliberately: its `prepare` returns a sql.js `Statement`\n * (`bind`/`step`/`getAsObject`/`free`) with no `all()`, so the compiled path's\n * `prepared.all(...params)` would throw on the first statement. Drizzle's own\n * sql-js session drives that statement shape correctly, so an excluded client\n * falls back to the Drizzle path and works instead of failing — the abstention\n * is what makes the advertised sql.js support real. Every other\n * prepare-capable client returns statements with `all()` (better-sqlite3,\n * bun:sqlite).\n */\nfunction resolveSqliteClient(\n db: AnySqliteDatabase,\n): SqliteClientWithPrepare | undefined {\n const sqliteClient = (db as SqliteClientCarrier).$client;\n if (preparingClient(sqliteClient) === undefined) return;\n if (isSqlJsClient(sqliteClient)) return;\n return sqliteClient as SqliteClientWithPrepare;\n}\n\nfunction getOrCreatePreparedStatement(\n cache: Map<string, PreparedAllStatement>,\n sqliteClient: SqliteClientWithPrepare,\n sqlText: string,\n cacheMax: number,\n): PreparedAllStatement {\n return getOrCreateLru(cache, sqlText, cacheMax, () =>\n sqliteClient.prepare(sqlText),\n );\n}\n\n// Uses unconditional `await` because Drizzle returns SQLiteRaw thenables\n// that fail `instanceof Promise` checks (drizzle-team/drizzle-orm#2275).\nasync function executeDrizzleQuery<TRow>(\n db: AnySqliteDatabase,\n query: DrizzleSql,\n): Promise<readonly TRow[]> {\n return await db.all(query);\n}\n\nfunction createPreparedStatementExecutor(\n sqliteClient: SqliteClientWithPrepare,\n cache: Map<string, PreparedAllStatement>,\n sqlText: string,\n cacheMax: number,\n): PreparedSqlStatement {\n return {\n execute<TRow>(params: readonly unknown[]): Promise<readonly TRow[]> {\n const preparedStatement = getOrCreatePreparedStatement(\n cache,\n sqliteClient,\n sqlText,\n cacheMax,\n );\n const rows = preparedStatement.all(...params);\n return Promise.resolve(rows as readonly TRow[]);\n },\n };\n}\n\nexport function createSqliteExecutionAdapter(\n db: AnySqliteDatabase,\n statementCacheMaxOrOptions: number | SqliteExecutionAdapterOptions = {},\n): SqliteExecutionAdapter {\n const options: SqliteExecutionAdapterOptions =\n typeof statementCacheMaxOrOptions === \"number\" ?\n { statementCacheMax: statementCacheMaxOrOptions }\n : statementCacheMaxOrOptions;\n const statementCacheMax =\n options.statementCacheMax ?? DEFAULT_PREPARED_STATEMENT_CACHE_MAX;\n const profileHints = options.profileHints ?? {};\n\n const hostedPlatform = detectHostedPlatform(db);\n const isSync = detectSyncProfile(db, profileHints, hostedPlatform);\n const sqliteClient = isSync ? resolveSqliteClient(db) : undefined;\n const transactionMode = detectTransactionMode(\n profileHints,\n isSync,\n hostedPlatform,\n );\n const hardMaxBindParameters = detectHardMaxBindParameters(\n transactionMode,\n hostedPlatform,\n );\n const maxBindParameters = detectMaxBindParameters(\n sqliteClient,\n hardMaxBindParameters,\n );\n\n const profile: SqliteExecutionProfile = {\n ...(hostedPlatform === undefined ? {} : { hostedPlatform }),\n ...(hardMaxBindParameters === undefined ? {} : { hardMaxBindParameters }),\n isSync,\n maxBindParameters,\n supportsCompiledExecution: sqliteClient !== undefined,\n transactionMode,\n };\n\n const compile = (query: ExecutableSql): CompiledSqlQuery =>\n compileQueryWithDialect(db, query, \"SQLite\");\n\n if (sqliteClient !== undefined) {\n const client = sqliteClient;\n const statementCache = new Map<string, PreparedAllStatement>();\n\n function executeCompiled<TRow>(\n compiledQuery: CompiledSqlQuery,\n ): Promise<readonly TRow[]> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n client,\n compiledQuery.sql,\n statementCacheMax,\n );\n const rows = preparedStatement.all(...compiledQuery.params);\n return Promise.resolve(rows as readonly TRow[]);\n }\n\n function executeCompiledRun(\n compiledQuery: CompiledSqlQuery,\n ): Promise<void> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n client,\n compiledQuery.sql,\n statementCacheMax,\n );\n // better-sqlite3 rejects run() on reader statements and all() on\n // non-reader statements, so pick by the statement's own flag; a\n // client without run() (or without the reader flag but returning\n // rows) drains through all() and discards.\n if (\n preparedStatement.run === undefined ||\n preparedStatement.reader === true\n ) {\n preparedStatement.all(...compiledQuery.params);\n } else {\n preparedStatement.run(...compiledQuery.params);\n }\n return Promise.resolve();\n }\n\n function executePreparedRunBatch(\n sqlText: string,\n parameterRows: readonly (readonly unknown[])[],\n ): Promise<void> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n client,\n sqlText,\n statementCacheMax,\n );\n if (preparedStatement.run === undefined) {\n throw new Error(\n \"Trusted SQLite import requires a prepared statement run() method.\",\n );\n }\n for (const params of parameterRows) {\n preparedStatement.run(...params);\n }\n return Promise.resolve();\n }\n\n return {\n clearStatementCache() {\n statementCache.clear();\n },\n compile,\n execute<TRow>(query: ExecutableSql): Promise<readonly TRow[]> {\n const compiledQuery = compile(query);\n return executeCompiled<TRow>(compiledQuery);\n },\n executeCompiled,\n executeCompiledRun,\n executePreparedRunBatch,\n prepare(sqlText: string): PreparedSqlStatement {\n return createPreparedStatementExecutor(\n client,\n statementCache,\n sqlText,\n statementCacheMax,\n );\n },\n profile,\n };\n }\n\n return {\n clearStatementCache() {\n // No-op: no statement cache in async/D1 mode\n },\n compile,\n execute<TRow>(query: ExecutableSql): Promise<readonly TRow[]> {\n return executeDrizzleQuery<TRow>(\n db,\n isSqlFragment(query) ? toDrizzleSql(query, \"sqlite\") : query,\n );\n },\n profile,\n };\n}\n","/**\n * SQLite backend adapter for TypeGraph.\n *\n * Works with any Drizzle SQLite database instance:\n * - better-sqlite3\n * - libsql / Turso\n * - Cloudflare D1\n * - bun:sqlite\n * - sql.js\n *\n * @example\n * ```typescript\n * import { drizzle } from \"drizzle-orm/better-sqlite3\";\n * import Database from \"better-sqlite3\";\n * import { createSqliteBackend, tables } from \"@nicia-ai/typegraph/adapters/drizzle/sqlite\";\n *\n * const sqlite = new Database(\"app.db\");\n * const db = drizzle(sqlite);\n * const backend = createSqliteBackend(db, { tables });\n * ```\n */\nimport {\n and,\n eq,\n getTableName,\n inArray,\n isNull,\n type SQL,\n sql,\n} from \"drizzle-orm\";\nimport { BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\nimport { BackendDisposedError, ConfigurationError } from \"../../errors\";\nimport type { ResolvedSqlTableNames } from \"../../query/compiler/schema\";\nimport {\n buildFulltextCapabilities,\n fts5Strategy,\n type FulltextStrategy,\n} from \"../../query/dialect/fulltext-strategy\";\nimport {\n assertVectorSearchLimit,\n buildVectorCapabilities,\n resolveEfSearchOverride,\n vectorSearchFrontierTuning,\n type VectorSlot,\n type VectorStrategy,\n} from \"../../query/dialect/vector-strategy\";\nimport {\n isSqlFragment,\n sql as portableSql,\n type SqlFragment,\n} from \"../../query/sql-fragment\";\nimport { type CompiledRowsSql } from \"../../query/sql-intent\";\nimport { chunk as chunkArray } from \"../../utils/array\";\nimport { requireDefined } from \"../../utils/presence\";\nimport {\n isMissingTableError,\n isSqliteNotAuthorizedError,\n} from \"../../utils/sql-errors\";\nimport { FIND_EDGES_ENDPOINT_FIXED_PARAM_COUNT } from \"../edge-endpoint-sets\";\nimport { buildLiveNodeCandidates } from \"../live-node-candidates\";\nimport {\n type AdapterBackend,\n type BackendCapabilities,\n type CommitSchemaVersionIfKindsEmptyResult,\n type CommitSchemaVersionParams,\n type ContributionDiagnostic,\n type ContributionMaterializationIdentity,\n type ContributionMaterializationRow,\n type ContributionProbeEntry,\n type ContributionRebuildResult,\n type ContributionRebuildScope,\n type ContributionRepairResult,\n type ContributionRepopulationStats,\n type CreateVectorIndexParams,\n type DeleteEmbeddingParams,\n type DeleteFulltextBatchParams,\n type DeleteFulltextParams,\n type DropVectorIndexParams,\n type FulltextSearchParams,\n type FulltextSearchResult,\n type GraphAnalyticsCapabilities,\n type GraphBackend,\n type HybridSearchParams,\n type HybridSearchRow,\n type IdentityTableNames,\n type IndexMaterializationRow,\n INTERNAL_TEMPORARY_WRITES,\n type InternalTransactionOptions,\n type KindRemovalRow,\n type LockSchemaVersionForWriteParams,\n normalizeGraphAnalyticsCapabilities,\n type RecordContributionMaterializationParams,\n type RecordIndexMaterializationParams,\n type RecordKindRemovalParams,\n type SchemaKindEmptinessProbe,\n type SchemaVersionRow,\n type SchemaWriteTransactionBackend,\n type SetActiveVersionParams,\n SQLITE_CAPABILITIES,\n SQLITE_MAX_BIND_PARAMETERS,\n type TransactionBackend,\n type TrustedImportOptions,\n type TrustedImportSession,\n type UpsertEmbeddingBatchParams,\n type UpsertEmbeddingParams,\n type UpsertFulltextBatchParams,\n type UpsertFulltextParams,\n type VectorSearchParams,\n type VectorSearchResult,\n} from \"../types\";\nimport {\n type AnySqliteDatabase,\n createSqliteExecutionAdapter,\n getDurableObjectStorageClient,\n isBetterSqlite3Client,\n isBunSqliteClient,\n isSqlJsClient,\n type SqliteExecutionAdapter,\n type SqliteExecutionProfile,\n type SqliteExecutionProfileHints,\n} from \"./execution/sqlite-execution\";\nimport { type ExecutableSql, toDrizzleSql } from \"./execution/types\";\nimport {\n EMBEDDING_UPSERT_PARAM_COUNT,\n mapVectorWriteError,\n vectorSlotFromCreateIndexParams,\n vectorSlotFromDropIndexParams,\n vectorSlotFromParams,\n} from \"./vector-runtime\";\nexport type { SqliteTransactionMode } from \"./execution/sqlite-execution\";\nimport {\n coerceNumericScore,\n createEdgeRowMapper,\n createNodeRowMapper,\n createSchemaVersionRowMapper,\n createUniqueRowMapper,\n nowIso,\n SQLITE_ROW_MAPPER_CONFIG,\n} from \"../row-mappers\";\nimport { markSerializedTransactionResource } from \"../transaction-resource\";\nimport {\n buildContributionInsertValues,\n buildContributionOnConflictSet,\n type ContributionMaterializer,\n contributionRebuildSupported,\n createContributionMaterializer,\n gateFulltext,\n gateFulltextMethods,\n mapContributionMaterializationRow,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS,\n} from \"./contribution-materializations\";\nimport {\n generateSqliteCreateTableSQL,\n generateSqliteDDL,\n sqliteContributions,\n} from \"./ddl\";\nimport {\n buildMaterializationInsertValues,\n buildMaterializationOnConflictSet,\n mapMaterializationRow,\n SQLITE_INDEX_MAT_TIMESTAMPS,\n} from \"./index-materializations\";\nimport {\n buildKindRemovalInsertValues,\n buildKindRemovalOnConflictSet,\n mapKindRemovalRow,\n SQLITE_KIND_REMOVAL_TIMESTAMPS,\n} from \"./kind-removals\";\nimport {\n assertActiveSchemaVersion,\n assertAdoptedDialect,\n commitSchemaVersionIfKindsEmpty,\n createCommonOperationBackend,\n type InternalOperationBackend,\n} from \"./operation-backend-core\";\nimport { mapHybridSearchRow } from \"./operations/hybrid\";\nimport {\n createSqliteOperationStrategy,\n tableExistsFromRow,\n} from \"./operations/strategy\";\nimport {\n createSqliteTables as buildSqliteTables,\n type SqliteTables,\n tables as defaultTables,\n} from \"./schema/sqlite\";\nimport {\n analyzeImportedTables,\n assertTrustedImportDatabaseEmpty,\n createSqliteTrustedImportSession,\n restoreSecondaryIndexes,\n suspendSqliteSecondaryIndexes,\n} from \"./trusted-import\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Options for creating a SQLite backend.\n */\nexport type SqliteBackendOptions = Readonly<{\n /**\n * Custom table definitions. Use createSqliteTables() to customize table names.\n * Defaults to standard TypeGraph table names.\n */\n tables?: SqliteTables;\n /**\n * Optional execution profile hints used to avoid runtime driver reflection.\n * Set `transactionMode: \"none\"` for drivers without transactions (e.g.\n * Cloudflare D1). Durable Objects (`drizzle(ctx.storage)`) auto-detect\n * `transactionMode: \"do-sqlite\"` and do not need a hint. Hosted platform\n * identity is authoritative when it conflicts with a stale hint.\n */\n executionProfile?: SqliteExecutionProfileHints;\n /**\n * Fulltext strategy override. Defaults to `fts5Strategy` (SQLite's\n * built-in FTS5 virtual table). Most users should leave this alone.\n */\n fulltext?: FulltextStrategy;\n /**\n * Vector strategy override. When present, the backend owns per-`(kind,\n * field)` typed storage through this strategy (DDL, upsert, delete,\n * similarity search, ANN index lifecycle) and advertises\n * `strategy.capabilities` as `capabilities.vector`. `createLibsqlBackend`\n * passes `libsqlVectorStrategy` unconditionally; `createLocalSqliteBackend`\n * passes `sqliteVecStrategy` when the extension loads. When absent the\n * backend exposes no vector capability and embedding values pass through\n * writes without being indexed — matching existing behavior for SQLite\n * connections without a vector extension.\n */\n vector?: VectorStrategy;\n /**\n * Override specific backend capabilities. Useful for custom SQLite builds\n * or tests that need to simulate an engine-level capability gap. Overrides\n * may lower, but cannot raise, a hosted platform's hard parameter ceiling.\n */\n capabilities?: Partial<BackendCapabilities>;\n}>;\n\nconst NODE_INSERT_PARAM_COUNT = 9;\nconst EDGE_INSERT_PARAM_COUNT = 12;\nconst GET_NODES_FIXED_PARAM_COUNT = 2;\nconst GET_EDGES_FIXED_PARAM_COUNT = 1;\nconst CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT = 3;\nconst FULLTEXT_UPSERT_PARAM_COUNT = 6;\nconst FULLTEXT_DELETE_FIXED_PARAM_COUNT = 2;\nconst UNIQUE_DELETE_FIXED_PARAM_COUNT = 2;\nconst UNIQUE_INSERT_PARAM_COUNT = 6;\n\n/**\n * `PRAGMA analysis_limit` value `refreshStatistics()` sets before running\n * `ANALYZE`. Unlike Postgres (whose `ANALYZE` always examines a bounded\n * sample sized off `default_statistics_target`), SQLite's `ANALYZE`\n * defaults to a full table/index scan — O(table size) per call. A caller\n * streaming a bulk load through repeated `bulkInsert()` calls (the only\n * practical pattern for a multi-million-row load) re-triggers\n * `refreshStatistics()` on every batch once that batch's row count crosses\n * `AUTO_REFRESH_STATISTICS_ROW_THRESHOLD`; without this bound, per-call\n * cost grows with total table size, integrating to O(n²) total load time.\n * 1000 is SQLite's own documented suggestion for large databases.\n */\nexport const SQLITE_ANALYZE_ROW_LIMIT = 1000;\n\n/**\n * Barrel keys (contribution logical names) of the four relations that hold\n * Operational Identity state: current assertions, recorded-time assertions,\n * the derived closure, and the derived separation relation.\n * `ensureIdentityTables()` scopes its idempotent CREATE TABLE / CREATE INDEX\n * to exactly these when identity is first enabled on an existing database.\n */\nconst IDENTITY_TABLE_LOGICAL_NAMES: ReadonlySet<string> = new Set([\n \"identityAssertions\",\n \"recordedIdentityAssertions\",\n \"identityClosure\",\n \"identitySeparation\",\n]);\n\n/**\n * Batch chunk sizes for the SQLite operation backend, derived from the\n * connection's bound-parameter budget. Keys mirror the operation backend's\n * `batchConfig`.\n */\nexport type SqliteBatchChunkSizes = Readonly<{\n checkUniqueBatchChunkSize: number;\n edgeInsertBatchSize: number;\n /** Rows per embedding batch upsert (5 binds per row). */\n embeddingUpsertBatchSize: number;\n /** Rows per fulltext batch upsert (6 binds per row on FTS5). */\n fulltextUpsertBatchSize: number;\n /** Node ids per fulltext batch delete (2 fixed binds + one per id). */\n fulltextDeleteChunkSize: number;\n /** Endpoint ids per `findEdgesByKind` `fromIds` / `toIds` statement. */\n findEdgesEndpointChunkSize: number;\n getEdgesChunkSize: number;\n getNodesChunkSize: number;\n nodeInsertBatchSize: number;\n /** Node ids per uniqueness-sidecar hard delete. */\n uniqueDeleteChunkSize: number;\n uniqueInsertBatchSize: number;\n}>;\n\n/**\n * Derives batch chunk sizes from a per-statement bound-parameter budget.\n * The budget varies by driver — better-sqlite3 compiles in 32,766, D1 caps\n * at ~100, undetectable async drivers keep the 999 floor — so chunk math is\n * computed per backend instance rather than fixed at module scope.\n */\nexport function computeSqliteBatchChunkSizes(\n maxBindParameters: number,\n): SqliteBatchChunkSizes {\n return {\n checkUniqueBatchChunkSize: Math.max(\n 1,\n maxBindParameters - CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT,\n ),\n embeddingUpsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / EMBEDDING_UPSERT_PARAM_COUNT),\n ),\n fulltextUpsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / FULLTEXT_UPSERT_PARAM_COUNT),\n ),\n fulltextDeleteChunkSize: Math.max(\n 1,\n maxBindParameters - FULLTEXT_DELETE_FIXED_PARAM_COUNT,\n ),\n edgeInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / EDGE_INSERT_PARAM_COUNT),\n ),\n findEdgesEndpointChunkSize: Math.max(\n 1,\n maxBindParameters - FIND_EDGES_ENDPOINT_FIXED_PARAM_COUNT,\n ),\n getEdgesChunkSize: Math.max(\n 1,\n maxBindParameters - GET_EDGES_FIXED_PARAM_COUNT,\n ),\n getNodesChunkSize: Math.max(\n 1,\n maxBindParameters - GET_NODES_FIXED_PARAM_COUNT,\n ),\n nodeInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / NODE_INSERT_PARAM_COUNT),\n ),\n uniqueDeleteChunkSize: Math.max(\n 1,\n maxBindParameters - UNIQUE_DELETE_FIXED_PARAM_COUNT,\n ),\n uniqueInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / UNIQUE_INSERT_PARAM_COUNT),\n ),\n };\n}\n\ntype SerializedExecutionQueue = Readonly<{\n dispose: () => void;\n runExclusive: <T>(task: () => Promise<T>) => Promise<T>;\n}>;\n\n// ============================================================\n// Utilities\n// ============================================================\n\nconst toNodeRow = createNodeRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toEdgeRow = createEdgeRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toUniqueRow = createUniqueRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toSchemaVersionRow = createSchemaVersionRowMapper(\n SQLITE_ROW_MAPPER_CONFIG,\n);\n\n/** A shared promise that never settles — used to absorb post-dispose work. */\nconst PENDING_FOREVER: Promise<never> = new Promise<never>(noop);\n\nfunction pendingForever<T>(): Promise<T> {\n return PENDING_FOREVER;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noop(): void {}\n\n/**\n * Tracks which serialized queue (if any) the current async execution is\n * running a task for, so a re-entrant submission — a root-backend operation\n * awaited from inside a transaction already occupying the same queue — can be\n * rejected with a typed error instead of deadlocking (the enclosing task holds\n * the queue slot until it completes, so the inner operation can never run).\n *\n * AsyncLocalStorage is loaded lazily and optionally: it is available on Node\n * and on Cloudflare workers with the `nodejs_als` compatibility flag, and a\n * runtime without it simply skips the detection (the queue behaves as before).\n */\ntype QueueTaskContext = Readonly<{\n getStore: () => unknown;\n run: <T>(store: object, callback: () => T) => T;\n}>;\n\nlet queueTaskContext: QueueTaskContext | undefined;\n\nasync function loadQueueTaskContext(): Promise<void> {\n try {\n const asyncHooks = await import(\"node:async_hooks\");\n queueTaskContext = new asyncHooks.AsyncLocalStorage<object>();\n } catch {\n // AsyncLocalStorage unavailable on this runtime: re-entrant submissions\n // stay undetected, matching the queue's previous behavior.\n }\n}\n\n// eslint-disable-next-line unicorn/prefer-top-level-await -- the dual CJS/ESM build cannot use top-level await\nvoid loadQueueTaskContext();\n\nfunction rejectReentrantQueueSubmission(): Promise<never> {\n return Promise.reject(\n new ConfigurationError(\n \"This operation was awaited from inside a transaction running on the \" +\n \"same SQLite backend and would deadlock: the transaction holds the \" +\n \"backend's serialized execution slot until it completes, so the \" +\n \"operation could never run.\",\n { backend: \"sqlite\", capability: \"concurrentRootAccess\" },\n {\n suggestion:\n \"Inside a store.transaction callback, use the transaction-scoped \" +\n \"context (tx.nodes / tx.edges / tx.backend) instead of the root \" +\n \"store or backend, or move the operation outside the transaction.\",\n },\n ),\n );\n}\n\nfunction createSerializedExecutionQueue(): SerializedExecutionQueue {\n let tail: Promise<unknown> = Promise.resolve();\n let disposed = false;\n // Unique per queue: a task running on THIS queue must not submit back to it,\n // but may freely submit to a different backend's queue.\n const taskMarker: object = {};\n\n function isDisposed(): boolean {\n return disposed;\n }\n\n return {\n dispose() {\n disposed = true;\n },\n\n runExclusive<T>(task: () => Promise<T>): Promise<T> {\n if (isDisposed()) return Promise.reject(new BackendDisposedError());\n if (queueTaskContext?.getStore() === taskMarker) {\n return rejectReentrantQueueSubmission();\n }\n\n // When disposed, runTask returns a never-settling promise so that no\n // rejection propagates through the 7+ async wrappers between this\n // queue and the store-level caller. A rejection here would become an\n // unhandled rejection if the caller abandoned the promise during\n // teardown — and JavaScript offers no way to `.catch()` a rejection\n // at the bottom of a chain without every async wrapper above it also\n // creating an independently-unhandled rejected promise.\n //\n // The tradeoff: an active caller whose operation was queued before\n // dispose() will see a permanently-pending promise rather than a\n // BackendDisposedError. Post-dispose submissions (the check above)\n // still reject immediately since the caller actively holds that\n // promise.\n const runTask = async (): Promise<T> => {\n if (isDisposed()) return pendingForever<T>();\n try {\n const context = queueTaskContext;\n return context === undefined ?\n await task()\n : await context.run(taskMarker, () => task());\n } catch (error) {\n if (isDisposed()) return pendingForever<T>();\n throw error;\n }\n };\n const result = tail.then(runTask, runTask);\n tail = result.then(\n () => 0,\n () => 0,\n );\n return result;\n },\n };\n}\n\nfunction runWithSerializedQueue<T>(\n queue: SerializedExecutionQueue | undefined,\n task: () => Promise<T>,\n): Promise<T> {\n if (queue === undefined) return task();\n return queue.runExclusive(task);\n}\n\n/** Every SQLite \"atomic transactions unavailable\" refusal shares this shape. */\nfunction throwSqliteTransactionsDisabled(message: string): never {\n throw new ConfigurationError(message, {\n backend: \"sqlite\",\n capability: \"transactions\",\n supportsTransactions: false,\n });\n}\n\nfunction buildSqliteCapabilities(\n options: Readonly<{\n fulltextStrategy: FulltextStrategy;\n vectorStrategy: VectorStrategy | undefined;\n transactionMode: SqliteExecutionAdapter[\"profile\"][\"transactionMode\"];\n maxBindParameters: number;\n }>,\n): BackendCapabilities {\n const base =\n options.transactionMode === \"none\" ?\n {\n ...SQLITE_CAPABILITIES,\n transactions: false,\n graphAnalytics: {\n ...(SQLITE_CAPABILITIES.graphAnalytics ?? {\n mathFunctions: false,\n }),\n supported: false,\n },\n }\n : SQLITE_CAPABILITIES;\n return {\n ...base,\n maxBindParameters: options.maxBindParameters,\n fulltext: buildFulltextCapabilities(options.fulltextStrategy),\n ...(options.vectorStrategy === undefined ?\n {}\n : { vector: buildVectorCapabilities(options.vectorStrategy) }),\n };\n}\n\nfunction resolveMaxBindParametersCapability(\n profile: SqliteExecutionProfile,\n override: number | undefined,\n): number {\n const requested = override ?? profile.maxBindParameters;\n return profile.hardMaxBindParameters === undefined ?\n requested\n : Math.min(requested, profile.hardMaxBindParameters);\n}\n\nfunction resolveSqliteGraphAnalyticsCapabilities(\n profile: SqliteExecutionProfile,\n override: GraphAnalyticsCapabilities | undefined,\n): GraphAnalyticsCapabilities {\n const requested = override ??\n SQLITE_CAPABILITIES.graphAnalytics ?? {\n supported: false,\n mathFunctions: false,\n };\n if (\n profile.transactionMode !== \"do-sqlite\" &&\n profile.transactionMode !== \"none\"\n ) {\n return requested;\n }\n return { ...requested, supported: false };\n}\n\n// ============================================================\n// Backend Factory\n// ============================================================\n\n/**\n * Creates a TypeGraph backend for SQLite databases.\n *\n * Works with any Drizzle SQLite instance regardless of the underlying driver.\n *\n * @param db - A Drizzle SQLite database instance\n * @param options - Backend configuration\n * @returns A GraphBackend implementation\n */\ntype CreateSqliteOperationBackendOptions = Readonly<{\n capabilities: GraphBackend[\"capabilities\"];\n db: AnySqliteDatabase;\n executionAdapter: SqliteExecutionAdapter;\n operationStrategy: ReturnType<typeof createSqliteOperationStrategy>;\n serializedQueue?: SerializedExecutionQueue;\n tableNames: ResolvedSqlTableNames;\n fulltextStrategy: FulltextStrategy;\n /**\n * Active vector strategy, or `undefined` when the connection has no\n * vector extension. When present, the backend exposes upsertEmbedding /\n * deleteEmbedding / vectorSearch / createVectorIndex / dropVectorIndex,\n * all routed through this strategy's per-`(kind, field)` storage.\n */\n vectorStrategy?: VectorStrategy | undefined;\n /**\n * Shared durable-marker materializer. The vector methods assert a\n * slot's marker (SELECT, never DDL) on the hot path and `createVectorIndex`\n * ensures it (privileged) — replacing the old in-process ensure-latch.\n * Shared across the outer backend and every transaction-scoped backend\n * so a slot's marker is resolved at most once per process.\n */\n contributionMaterializer: ContributionMaterializer;\n /** Whether this operation backend is bound to an explicit transaction. */\n transactionScoped: boolean;\n}>;\n\ntype CreateSqliteTransactionBackendOptions = Readonly<{\n capabilities: GraphBackend[\"capabilities\"];\n db: AnySqliteDatabase;\n executionAdapter?: SqliteExecutionAdapter;\n operationStrategy: ReturnType<typeof createSqliteOperationStrategy>;\n profileHints: SqliteExecutionProfileHints;\n tableNames: ResolvedSqlTableNames;\n fulltextStrategy: FulltextStrategy;\n /** Active vector strategy. See {@link CreateSqliteOperationBackendOptions}. */\n vectorStrategy?: VectorStrategy | undefined;\n /** Shared durable-marker materializer. See {@link CreateSqliteOperationBackendOptions}. */\n contributionMaterializer: ContributionMaterializer;\n}>;\n\nfunction createSqliteOperationBackend(\n options: CreateSqliteOperationBackendOptions,\n): InternalOperationBackend {\n const {\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n serializedQueue,\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n transactionScoped,\n } = options;\n\n // CRUD statements route through the execution adapter's compiled path on\n // synchronous drivers so a repeated operation shape re-binds parameters\n // against a cached prepared statement instead of re-preparing through\n // drizzle's session on every call. Async drivers (remote libsql, D1)\n // have no statement cache and keep the drizzle fallback.\n const compiledExecute = executionAdapter.executeCompiled;\n const compiledRun = executionAdapter.executeCompiledRun;\n\n function execGet<T>(query: ExecutableSql): Promise<T | undefined> {\n // Fallback uses db.all()[0], not db.get(): drizzle-team/drizzle-orm#1049\n // — db.get() crashes with the libsql driver when no rows match\n // (normalizeRow receives undefined).\n //\n // The fallback branches use `await` unconditionally rather than\n // `instanceof Promise` because Drizzle returns SQLiteRaw thenables\n // that are NOT Promise instances (drizzle-team/drizzle-orm#2275).\n return runWithSerializedQueue(serializedQueue, async () => {\n if (compiledExecute === undefined) {\n const rows = await executionAdapter.execute<T>(query);\n return rows[0];\n }\n const rows = await compiledExecute<T>(executionAdapter.compile(query));\n return rows[0];\n });\n }\n\n function execAll<T>(query: ExecutableSql): Promise<T[]> {\n return runWithSerializedQueue(serializedQueue, async () => {\n if (compiledExecute === undefined) {\n return [...(await executionAdapter.execute<T>(query))];\n }\n return [...(await compiledExecute<T>(executionAdapter.compile(query)))];\n });\n }\n\n function execRun(query: ExecutableSql): Promise<void> {\n return runWithSerializedQueue(serializedQueue, async () => {\n if (compiledRun === undefined) {\n await db.run(\n isSqlFragment(query) ? toDrizzleSql(query, \"sqlite\") : query,\n );\n return;\n }\n await compiledRun(executionAdapter.compile(query));\n });\n }\n\n const batchConfig = computeSqliteBatchChunkSizes(\n capabilities.maxBindParameters ?? SQLITE_MAX_BIND_PARAMETERS,\n );\n const commonBackend = createCommonOperationBackend({\n batchConfig,\n execution: {\n execAll,\n execGet,\n execRun,\n },\n nowIso,\n maxBindParameters:\n capabilities.maxBindParameters ?? SQLITE_MAX_BIND_PARAMETERS,\n operationStrategy,\n rowMappers: {\n toEdgeRow,\n toNodeRow,\n toSchemaVersionRow,\n toUniqueRow,\n },\n });\n\n const executeCompiled = executionAdapter.executeCompiled;\n const executeRawMethod: Pick<TransactionBackend, \"executeRaw\"> =\n executeCompiled === undefined ?\n {}\n : {\n executeRaw<T>(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executeCompiled<T>({ params, sql: sqlText }),\n );\n },\n };\n\n const vectorEmbeddingMethods =\n vectorStrategy === undefined ?\n {}\n : {\n async upsertEmbedding(params: UpsertEmbeddingParams): Promise<void> {\n const slot = vectorSlotFromParams(params);\n // Assert the slot's durable marker (SELECT, cached) — never DDL.\n // The per-field table is provisioned by the privileged migrator\n // (`createStoreWithSchema` → `materializeVectorContributions`).\n await contributionMaterializer.assertVectorSlot(slot);\n const statements = vectorStrategy.buildUpsert(slot, params, nowIso());\n try {\n for (const statement of statements) {\n await execRun(statement);\n }\n } catch (error) {\n throw mapVectorWriteError(error, params);\n }\n },\n async upsertEmbeddingBatch(\n params: UpsertEmbeddingBatchParams,\n ): Promise<void> {\n if (params.rows.length === 0) return;\n const slot = vectorSlotFromParams(params);\n // Same SELECT-only marker assert as the single-row path — never DDL.\n await contributionMaterializer.assertVectorSlot(slot);\n // Last-write-wins dedupe: a multi-row upsert cannot affect one\n // row twice.\n const rowsById = new Map(\n params.rows.map((row) => [row.nodeId, row] as const),\n );\n const rows = [...rowsById.values()];\n const timestamp = nowIso();\n try {\n for (const chunk of chunkArray(\n rows,\n batchConfig.embeddingUpsertBatchSize,\n )) {\n const statements =\n vectorStrategy.buildUpsertBatch === undefined ?\n chunk.flatMap((row) =>\n vectorStrategy.buildUpsert(\n slot,\n {\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n nodeId: row.nodeId,\n fieldPath: params.fieldPath,\n embedding: row.embedding,\n dimensions: params.dimensions,\n metric: params.metric,\n indexType: params.indexType,\n },\n timestamp,\n ),\n )\n : vectorStrategy.buildUpsertBatch(\n slot,\n { ...params, rows: chunk },\n timestamp,\n );\n for (const statement of statements) {\n await execRun(statement);\n }\n }\n } catch (error) {\n throw mapVectorWriteError(error, params);\n }\n },\n async deleteEmbedding(params: DeleteEmbeddingParams): Promise<void> {\n // Assert the slot's durable marker before deleting. A delete can\n // run before any embedding was ever written for the field (e.g. a\n // node hard-deleted having never carried one); the per-field table\n // was provisioned at boot, so the DELETE is a clean no-op against\n // an existing (possibly empty) table, matching the Postgres path\n // (where a DELETE on a missing relation would abort an enclosing\n // transaction). SELECT-only assert, never DDL.\n const slot = vectorSlotFromParams(params);\n await contributionMaterializer.assertVectorSlot(slot);\n const statements = vectorStrategy.buildDelete(slot, params);\n for (const statement of statements) {\n await execRun(statement);\n }\n },\n async deleteEmbeddingBatch(\n params: Omit<DeleteEmbeddingParams, \"nodeId\"> &\n Readonly<{ nodeIds: readonly string[] }>,\n ): Promise<void> {\n if (params.nodeIds.length === 0) return;\n const slot = vectorSlotFromParams(params);\n await contributionMaterializer.assertVectorSlot(slot);\n for (const nodeIds of chunkArray(\n [...new Set(params.nodeIds)],\n batchConfig.embeddingUpsertBatchSize,\n )) {\n const statements = vectorStrategy.buildDeleteBatch(slot, {\n ...params,\n nodeIds,\n });\n for (const statement of statements) await execRun(statement);\n }\n },\n async vectorSearch(\n params: VectorSearchParams,\n ): Promise<readonly VectorSearchResult[]> {\n assertVectorSearchLimit(params.limit);\n // Apply-or-refuse for the per-search ANN frontier. No SQLite engine\n // TypeGraph bundles has one (sqlite-vec's vec0 takes only `k`;\n // libSQL's `vector_top_k` takes only (index, query, k)), so the\n // shared predicate refuses `efSearch` here with the engine's own\n // reason instead of accepting it and searching as if it were never\n // passed. `undefined` — the overwhelmingly common case — returns\n // without touching anything.\n resolveEfSearchOverride({\n efSearch: params.efSearch,\n indexType: params.indexType,\n tuning: vectorSearchFrontierTuning(vectorStrategy),\n transactions: capabilities.transactions,\n dialect: \"SQLite\",\n engine: vectorStrategy.name,\n });\n // Deliberately NOT marker-gated: search is read-only (no DDL\n // hazard to gate), and its params carry the caller's runtime\n // metric override, which legitimately diverges from the\n // provisioned shape on strategies that bake the metric into the\n // DDL (sqlite-vec). An unprovisioned slot surfaces the engine's\n // missing-relation error — the same contract as a query-builder\n // `similarTo()` predicate; `createVerifiedStore` catches both at\n // attach.\n const slot = vectorSlotFromParams(params);\n const query = vectorStrategy.buildSearch(\n slot,\n params,\n // Store-compiled candidates (predicates + subclass + currency)\n // take precedence; the live-node default covers direct backend use.\n params.candidates ??\n buildLiveNodeCandidates(\n tableNames.nodes,\n params.graphId,\n params.nodeKind,\n nowIso(),\n ),\n );\n let rows: readonly { node_id: string; score: number }[];\n try {\n rows = await execAll<{ node_id: string; score: number }>(query);\n } catch (error) {\n // A query vector whose dimension no longer matches the stored\n // column surfaces the same typed error as the write path.\n throw mapVectorWriteError(error, params);\n }\n return rows.map((row) => ({\n nodeId: row.node_id,\n score: row.score,\n }));\n },\n // Single-statement hybrid needs ROW_NUMBER(); a capability profile\n // that disables window functions keeps the store's multi-statement\n // fallback by simply not exposing the member.\n ...(capabilities.windowFunctions ?\n {\n async hybridSearch(\n params: HybridSearchParams,\n ): Promise<readonly HybridSearchRow[]> {\n assertVectorSearchLimit(params.limit);\n // Source depths get the same boundary validation the\n // fallback path applies (vectorSearch validates its limit;\n // the fulltext depth is validated inside\n // buildFulltextSearch).\n assertVectorSearchLimit(params.vector.k);\n // The hybrid statement's vector leg carries the same option on\n // the same engine, so it takes the same refusal. This path built\n // its own `VectorSearchParams` and dropped\n // `params.vector.efSearch` while doing so — the silent ignore in\n // its second location.\n resolveEfSearchOverride({\n efSearch: params.vector.efSearch,\n indexType: params.vector.indexType,\n tuning: vectorSearchFrontierTuning(vectorStrategy),\n transactions: capabilities.transactions,\n dialect: \"SQLite\",\n engine: vectorStrategy.name,\n });\n const slot = vectorSlotFromParams({\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n fieldPath: params.vector.fieldPath,\n dimensions: params.vector.dimensions,\n metric: params.vector.metric,\n indexType: params.vector.indexType,\n });\n // Read-only, not marker-gated — see vectorSearch above.\n const candidates =\n params.candidates ??\n buildLiveNodeCandidates(\n tableNames.nodes,\n params.graphId,\n params.nodeKind,\n nowIso(),\n );\n const vectorParams: VectorSearchParams = {\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n fieldPath: params.vector.fieldPath,\n queryEmbedding: params.vector.queryEmbedding,\n metric: params.vector.metric,\n dimensions: params.vector.dimensions,\n indexType: params.vector.indexType,\n limit: params.vector.k,\n ...(params.vector.minScore === undefined ?\n {}\n : { minScore: params.vector.minScore }),\n };\n // The vector leg references the statement's shared\n // tg_hybrid_cand CTE; the actual candidates SQL is emitted\n // once by buildHybridSearch.\n const vectorSql = vectorStrategy.buildSearch(\n slot,\n vectorParams,\n portableSql.raw(\"SELECT node_id FROM tg_hybrid_cand\"),\n );\n const statement = operationStrategy.buildHybridSearch(\n { ...params, candidates },\n toDrizzleSql(vectorSql, \"sqlite\"),\n params.vector.metric === \"cosine\",\n );\n let raw: readonly Record<string, unknown>[];\n try {\n raw = await execAll<Record<string, unknown>>(statement);\n } catch (error) {\n throw mapVectorWriteError(error, vectorParams);\n }\n return raw.map((row) => mapHybridSearchRow(row, toNodeRow));\n },\n }\n : {}),\n };\n\n const operationBackend: InternalOperationBackend = {\n ...commonBackend,\n ...executeRawMethod,\n ...vectorEmbeddingMethods,\n /**\n * Transaction-scoped contribution marker stamp. Present so the\n * destructive rebuild can commit its marker with the DDL that\n * produced it; without it the stamp would land outside the\n * transaction and could survive a rolled-back drop.\n *\n * States the row outright rather than reusing the top-level upsert,\n * whose `materialized_at` COALESCE preserves an earlier success so a\n * failed re-attempt cannot erase it. A completed rebuild replaced the\n * storage, so the recorded timestamp must be the rebuild's.\n */\n async recordContributionMaterialization(\n params: RecordContributionMaterializationParams,\n ): Promise<void> {\n await execRun(\n operationStrategy.buildInsertContributionMaterialization(params),\n );\n },\n\n async deleteSchemaVectorSlotContribution(slot: VectorSlot): Promise<void> {\n if (vectorStrategy === undefined) return;\n for (const contribution of vectorStrategy.ownedTables(slot)) {\n await execRun(\n operationStrategy.buildDeleteContributionMaterialization({\n graphId: slot.graphId,\n logicalName: contribution.logicalName,\n owner: contribution.owner,\n tableName: contribution.tableName,\n }),\n );\n }\n contributionMaterializer.evictVectorSlot(slot);\n },\n capabilities,\n dialect: \"sqlite\",\n tableNames,\n fulltextStrategy,\n ...(vectorStrategy === undefined ? {} : { vectorStrategy }),\n\n async lockSchemaVersionForWrite(\n params: LockSchemaVersionForWriteParams,\n ): Promise<void> {\n if (!transactionScoped) {\n throw new ConfigurationError(\n \"The schema write fence requires an explicit SQLite transaction.\",\n {\n code: \"SCHEMA_WRITE_FENCE_TRANSACTION_REQUIRED\",\n graphId: params.graphId,\n },\n );\n }\n // An ordinary read suffices, unlike Postgres' `FOR SHARE` fence: SQLite\n // serializes writers through BEGIN IMMEDIATE, so no schema commit can be\n // mid-flight while this transaction holds the writer slot, and a SQLite\n // read has no post-wait row recheck that could drop the active row from\n // its own snapshot. An absent row here therefore always means the graph\n // genuinely has no active schema.\n const active = await commonBackend.getActiveSchema(params.graphId);\n assertActiveSchemaVersion(\n params.graphId,\n params.expectedVersion,\n active?.version ?? 0,\n );\n },\n\n async createVectorIndex(params: CreateVectorIndexParams): Promise<void> {\n if (vectorStrategy === undefined) return;\n const slot = vectorSlotFromCreateIndexParams(params);\n // Ensure the per-field table + its durable marker first (privileged,\n // idempotent), then create its ANN index. `ownedTables` already folds\n // the index DDL in, so the explicit `buildCreateIndex` step is\n // belt-and-suspenders for slots whose index intent changed after the\n // table was first materialized.\n await contributionMaterializer.ensureVectorSlot(slot);\n const indexStatement = vectorStrategy.buildCreateIndex?.(slot);\n if (indexStatement !== undefined) {\n await execRun(indexStatement);\n }\n },\n\n async dropVectorIndex(params: DropVectorIndexParams): Promise<void> {\n if (vectorStrategy === undefined) return;\n const slot = vectorSlotFromDropIndexParams(params);\n const dropStatement = vectorStrategy.buildDropIndex?.(slot);\n if (dropStatement === undefined) return;\n try {\n await execRun(dropStatement);\n } catch (error) {\n // The per-field table (and thus its index) may never have been\n // materialized; DROP INDEX IF EXISTS against a missing table errors\n // on some drivers, so treat that as already-dropped.\n if (!isMissingTableError(error)) throw error;\n }\n },\n\n // === Fulltext Operations ===\n\n async upsertFulltext(params: UpsertFulltextParams): Promise<void> {\n const timestamp = nowIso();\n const statements = operationStrategy.buildUpsertFulltext(\n params,\n timestamp,\n );\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async deleteFulltext(params: DeleteFulltextParams): Promise<void> {\n const statements = operationStrategy.buildDeleteFulltext(params);\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async upsertFulltextBatch(\n params: UpsertFulltextBatchParams,\n ): Promise<void> {\n if (params.rows.length === 0) return;\n const timestamp = nowIso();\n // The strategy emits ONE statement over every row it is given, so\n // the bind budget is enforced here — same contract as node/edge\n // batch inserts.\n for (const rows of chunkArray(\n params.rows,\n batchConfig.fulltextUpsertBatchSize,\n )) {\n const statements = operationStrategy.buildUpsertFulltextBatch(\n { ...params, rows },\n timestamp,\n );\n for (const stmt of statements) {\n await execRun(stmt);\n }\n }\n },\n\n async deleteFulltextBatch(\n params: DeleteFulltextBatchParams,\n ): Promise<void> {\n if (params.nodeIds.length === 0) return;\n for (const nodeIds of chunkArray(\n params.nodeIds,\n batchConfig.fulltextDeleteChunkSize,\n )) {\n const statements = operationStrategy.buildDeleteFulltextBatch({\n ...params,\n nodeIds,\n });\n for (const stmt of statements) {\n await execRun(stmt);\n }\n }\n },\n\n async fulltextSearch(\n params: FulltextSearchParams,\n ): Promise<readonly FulltextSearchResult[]> {\n const query = operationStrategy.buildFulltextSearch(params);\n const rows = await execAll<{\n node_id: string;\n score: number | string;\n snippet: string | null;\n }>(query);\n return rows.map((row, index) => ({\n nodeId: row.node_id,\n score: coerceNumericScore(row.score),\n rank: index + 1,\n ...(row.snippet === null ? {} : { snippet: row.snippet }),\n }));\n },\n\n // === Query Execution ===\n\n async execute<T>(query: CompiledRowsSql): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executionAdapter.execute<T>(query),\n );\n },\n\n compileSql(\n query: SqlFragment,\n ): Readonly<{ sql: string; params: readonly unknown[] }> {\n return executionAdapter.compile(query);\n },\n };\n\n return operationBackend;\n}\n\n/**\n * Whether a driver client is a LOCAL `@libsql/client`: one stable connection\n * that every statement from every wrapper over it runs on, in order.\n *\n * `protocol === \"file\"` is the client's own answer to \"am I local?\" — it covers\n * `file:` paths, `:memory:` databases, and an embedded replica's local file. A\n * REMOTE client (`http` / `ws`) opens an independent stream per transaction and\n * must never be treated as one serialized resource; refusing concurrent work\n * there would refuse work that succeeds. The libsql methods are required\n * alongside the protocol so an unrelated object that happens to carry\n * `protocol: \"file\"` is not adopted, and none of it imports `@libsql/client`,\n * which this bundler-friendly module must not depend on.\n *\n * Single owner of the local/remote distinction: `../sqlite/libsql.ts` picks its\n * transaction framing (raw BEGIN/COMMIT on the one local connection vs Drizzle's\n * per-stream `db.transaction()`) by asking here, so the framing and the\n * serialized-resource mark cannot drift apart.\n */\nexport function isLocalLibsqlClient(client: unknown): boolean {\n if (typeof client !== \"object\" || client === null) return false;\n const candidate = client as Readonly<Record<string, unknown>>;\n return (\n candidate[\"protocol\"] === \"file\" &&\n typeof candidate[\"execute\"] === \"function\" &&\n typeof candidate[\"batch\"] === \"function\" &&\n typeof candidate[\"executeMultiple\"] === \"function\"\n );\n}\n\n/**\n * Returns the single connection a Drizzle database serializes every statement\n * onto, if its driver is one we can positively identify as such.\n *\n * Five drivers qualify, each by its own named predicate — a driver is marked on\n * evidence of WHAT IT IS, never on the absence of a disqualifier:\n *\n * - **better-sqlite3** ({@link isBetterSqlite3Client}): a single, synchronous\n * connection, so an open transaction on one wrapper is an open transaction\n * for all of them.\n * - **bun:sqlite** ({@link isBunSqliteClient}): the same one synchronous\n * connection, reached through `drizzle-orm/bun-sqlite`.\n * - **sql.js** ({@link isSqlJsClient}): one in-WASM database handle; every\n * wrapper's statements run on it in order.\n * - **Cloudflare Durable Object storage** (`drizzle(ctx.storage)`): one storage\n * connection whose transaction frame is AMBIENT on the storage object rather\n * than a handle passed to the callback (see `runDoSqliteStorageTransaction`:\n * `transactionMode: \"do-sqlite\"` binds the OUTER `db`). A second wrapper's\n * writes therefore land inside the first\n * wrapper's open export snapshot, and because the DO backend reports\n * `capabilities.transactions: true` nothing else abstains for it. Identified by\n * {@link getDurableObjectStorageClient}, the same full-shape evidence the\n * transaction runner requires, so the framing and the mark cannot drift apart.\n * - **a local `@libsql/client`**: also one stable connection — which is exactly\n * why local clients frame transactions as raw BEGIN/COMMIT on it (see\n * {@link isLocalLibsqlClient}). libsql clients expose no `prepare`, so no\n * prepare-capable predicate can see them and the driver client is read\n * directly here.\n *\n * Unrecognized clients stay unmarked: SEPARATE connections to the same file are\n * genuinely concurrent under WAL and must not be treated as one serialized\n * resource, and a driver whose dispatch we cannot attribute proves nothing.\n * The full classification — marked, deliberately unmarked, and the remaining\n * gaps — is the inventory in `../transaction-resource.ts`.\n */\nfunction getSerializedSqliteConnection(\n db: AnySqliteDatabase,\n): object | undefined {\n const client = (db as Readonly<{ $client?: unknown }>).$client;\n if (\n isBetterSqlite3Client(client) ||\n isBunSqliteClient(client) ||\n isSqlJsClient(client)\n ) {\n return client as object;\n }\n // The storage object IS the serialized resource: every wrapper built over the\n // same `ctx.storage` shares its one connection and its ambient transaction.\n const storageClient = getDurableObjectStorageClient(db);\n if (storageClient !== undefined) return storageClient;\n return isLocalLibsqlClient(client) ? (client as object) : undefined;\n}\n\n/**\n * Whether two backends built over `client` would be treated as one serialized\n * connection. The marking predicate itself, exposed for the driver-shape unit\n * tests (mirrors `isSerializedPostgresClient`); production code reaches it only\n * through {@link createSqliteBackend}.\n */\nexport function isSerializedSqliteClient(client: unknown): boolean {\n return (\n getSerializedSqliteConnection({\n $client: client,\n } as unknown as AnySqliteDatabase) !== undefined\n );\n}\n\nexport function createSqliteBackend(\n db: AnySqliteDatabase,\n options: SqliteBackendOptions = {},\n): AdapterBackend<AnySqliteDatabase> {\n // Resolved before the backend exists so marking below is a lookup, never\n // work that could fail after wrappers already observed an unmarked backend.\n const serializedConnection = getSerializedSqliteConnection(db);\n const tables = options.tables ?? defaultTables;\n const fulltextStrategy = options.fulltext ?? fts5Strategy;\n const profileHints = options.executionProfile ?? {};\n const executionAdapter = createSqliteExecutionAdapter(db, { profileHints });\n const { isSync, transactionMode } = executionAdapter.profile;\n // The active vector strategy gates upsertEmbedding / deleteEmbedding /\n // vectorSearch and supplies the per-`(kind, field)` storage. Passed by\n // the caller that knows the connection's vector capability\n // (`createLibsqlBackend` always; `createLocalSqliteBackend` when the\n // extension loads); absent for plain SQLite drivers with no extension.\n const vectorStrategy = options.vector;\n const capabilityOverrides = options.capabilities ?? {};\n const declaredCapabilities = normalizeGraphAnalyticsCapabilities({\n ...buildSqliteCapabilities({\n fulltextStrategy,\n vectorStrategy,\n transactionMode,\n maxBindParameters: executionAdapter.profile.maxBindParameters,\n }),\n ...capabilityOverrides,\n maxBindParameters: resolveMaxBindParametersCapability(\n executionAdapter.profile,\n capabilityOverrides.maxBindParameters,\n ),\n graphAnalytics: resolveSqliteGraphAnalyticsCapabilities(\n executionAdapter.profile,\n capabilityOverrides.graphAnalytics,\n ),\n });\n // Derived last and not overridable: how far up the contribution health\n // ladder this backend goes is a structural fact about the wiring below\n // (durable markers, a catalog probe, a strategy that declares teardown\n // DDL, a transactional schema fence), and a caller who declared a\n // rebuild this backend cannot perform would be advertising a lie.\n const capabilities: BackendCapabilities = {\n ...declaredCapabilities,\n contributions: {\n supported: true,\n probe: true,\n rebuild: contributionRebuildSupported(\n fulltextStrategy,\n tables.fulltextTableName,\n declaredCapabilities.transactions,\n ),\n },\n };\n\n const tableNames: ResolvedSqlTableNames = {\n nodes: getTableName(tables.nodes),\n edges: getTableName(tables.edges),\n recordedNodes: getTableName(tables.recordedNodes),\n recordedEdges: getTableName(tables.recordedEdges),\n recordedClock: getTableName(tables.recordedClock),\n revisionOrigins: getTableName(tables.revisionOrigins),\n identityAssertions: getTableName(tables.identityAssertions),\n recordedIdentityAssertions: getTableName(tables.recordedIdentityAssertions),\n identityClosure: getTableName(tables.identityClosure),\n identitySeparation: getTableName(tables.identitySeparation),\n fulltext: tables.fulltextTableName,\n uniques: getTableName(tables.uniques),\n };\n // refreshStatistics() scopes ANALYZE to these — matching the Postgres\n // backend, which never touches unrelated tables sharing the database.\n // The recorded and identity relations are ANALYZEd separately under a\n // missing-table guard: a schema created before recorded-time history or\n // Operational Identity landed (bring-your-own-connection, no DDL re-run)\n // has no recorded_* / identity_* tables.\n const coreAnalyzeTables = [\n tableNames.nodes,\n tableNames.edges,\n tableNames.uniques,\n tableNames.fulltext,\n ];\n const guardedAnalyzeTables = [\n tableNames.recordedNodes,\n tableNames.recordedEdges,\n tableNames.recordedClock,\n tableNames.recordedIdentityAssertions,\n tableNames.identityAssertions,\n tableNames.identityClosure,\n tableNames.identitySeparation,\n ] as const;\n const operationStrategy = createSqliteOperationStrategy(\n tables,\n fulltextStrategy,\n );\n // Serialize top-level operations per backend on every transaction-capable\n // mode (\"sql\", \"drizzle\", \"do-sqlite\"). SQLite is single-writer, and two\n // concurrent `transaction()` calls on one connection open overlapping BEGINs\n // and collide with SQLITE_BUSY; the queue makes each top-level operation —\n // including a whole transaction — run to completion before the next starts.\n // A transaction's inner reads/writes run on the tx-scoped backend, which\n // does not carry the queue (see CreateSqliteTransactionBackendOptions);\n // awaiting a ROOT-backend operation from inside the transaction callback\n // would deadlock, so the queue rejects such re-entrant submissions with a\n // typed error (see rejectReentrantQueueSubmission). `none` drivers (D1 /\n // neon-http) have no transactions and manage their own concurrency, so they\n // stay unqueued.\n const serializedQueue =\n transactionMode === \"none\" ? undefined : createSerializedExecutionQueue();\n\n // Durable fulltext + vector materialization (#135): the dialect-specific\n // marker-table primitives. Orchestration (materialize / assert /\n // per-instance cache) lives once in `createContributionMaterializer`,\n // shared by the outer backend and every transaction-scoped backend so a\n // slot's marker is resolved at most once per process. Built before\n // `operations` so the operation backend's vector methods can assert/\n // ensure through it instead of issuing DDL on the hot path.\n const matTable = tables.contributionMaterializations;\n\n async function ensureContributionMaterializationsTableImpl(): Promise<void> {\n await db.run(sql.raw(generateSqliteCreateTableSQL(matTable)));\n }\n\n async function getContributionMaterializationRow(\n identity: ContributionMaterializationIdentity,\n ): Promise<ContributionMaterializationRow | undefined> {\n const rows = await db\n .select()\n .from(matTable)\n .where(\n and(\n eq(matTable.graphId, identity.graphId),\n eq(matTable.logicalName, identity.logicalName),\n eq(matTable.owner, identity.owner),\n eq(matTable.tableName, identity.tableName),\n ),\n );\n const row = rows[0];\n if (row === undefined) return undefined;\n return mapContributionMaterializationRow(\n row,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS.decode,\n );\n }\n\n async function getContributionMaterializationRows(\n graphId: string,\n ): Promise<readonly ContributionMaterializationRow[]> {\n const rows = await db\n .select()\n .from(matTable)\n .where(eq(matTable.graphId, graphId));\n return rows.map((row) =>\n mapContributionMaterializationRow(\n row,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS.decode,\n ),\n );\n }\n\n async function recordContributionMaterializationRow(\n params: RecordContributionMaterializationParams,\n ): Promise<void> {\n await db\n .insert(matTable)\n .values(\n buildContributionInsertValues(\n params,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: [\n matTable.graphId,\n matTable.logicalName,\n matTable.owner,\n matTable.tableName,\n ],\n set: buildContributionOnConflictSet(\n matTable.materializedAt,\n params.materializedAt,\n ),\n });\n }\n\n async function deleteContributionMaterializationRow(\n identity: ContributionMaterializationIdentity,\n ): Promise<void> {\n await db\n .delete(matTable)\n .where(\n and(\n eq(matTable.graphId, identity.graphId),\n eq(matTable.logicalName, identity.logicalName),\n eq(matTable.owner, identity.owner),\n eq(matTable.tableName, identity.tableName),\n ),\n );\n }\n\n /**\n * Uncached catalog probe backing `verifyContributions`. The shared\n * `createCachedTableExistence` wrapper is deliberately NOT used: this\n * diagnostic's whole job is to notice that a table confirmed present\n * earlier has since been dropped.\n */\n async function contributionTableExists(tableName: string): Promise<boolean> {\n const rows = await executionAdapter.execute<Record<string, unknown>>(\n operationStrategy.buildTableExists(tableName),\n );\n return tableExistsFromRow(rows[0]);\n }\n\n /**\n * The contribution descriptors for exactly the identity relations, under\n * caller-supplied physical names. Pure — nothing is executed here — and the\n * single owner of \"which DDL belongs to the identity relations\", shared by\n * `ensureIdentityTables` (which runs it) and `identityTableDdl` (which hands\n * it to a transaction).\n */\n function identityContributionsFor(\n identityTableNames: IdentityTableNames,\n ): ReturnType<typeof sqliteContributions> {\n const identityTables = buildSqliteTables({\n identityAssertions: identityTableNames.identityAssertions,\n recordedIdentityAssertions: identityTableNames.recordedIdentityAssertions,\n identityClosure: identityTableNames.identityClosure,\n identitySeparation: identityTableNames.identitySeparation,\n });\n return sqliteContributions(identityTables, fulltextStrategy).filter(\n (contribution) =>\n IDENTITY_TABLE_LOGICAL_NAMES.has(contribution.logicalName),\n );\n }\n\n const contributionMaterializer = createContributionMaterializer({\n dialect: \"sqlite\",\n fulltextStrategy,\n fulltextTableName: tables.fulltextTableName,\n vectorStrategy,\n execDdl: async (statement) => {\n await db.run(sql.raw(statement));\n },\n ensureMarkerTable: ensureContributionMaterializationsTableImpl,\n getMarkers: getContributionMaterializationRows,\n recordMarker: recordContributionMaterializationRow,\n deleteMarker: deleteContributionMaterializationRow,\n tableExists: contributionTableExists,\n // Withheld rather than wired-and-throwing when transactions are\n // disabled: the rebuild must refuse with its own typed error naming\n // the absent fence, matching `capabilities.contributions.rebuild`.\n // The graph id the materializer passes is unused — this backend's\n // schema lock is per connection, not per graph.\n ...(capabilities.transactions ?\n {\n schemaWriteTransaction: <T>(\n _graphId: string,\n fn: (tx: SchemaWriteTransactionBackend) => Promise<T>,\n ) => runSchemaWriteTransaction((target) => fn(target)),\n }\n : {}),\n });\n\n const operations = createSqliteOperationBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n transactionScoped: false,\n ...(serializedQueue === undefined ? {} : { serializedQueue }),\n });\n\n /**\n * #140: the `transactionMode: \"do-sqlite\"` primitive. Cloudflare\n * Durable Objects expose an async storage transaction runner —\n * `ctx.storage.transaction(async () => ...)`, surfaced by Drizzle as\n * `db.$client.transaction` — that rolls back SQL writes across\n * `await`. There is no Drizzle tx handle on DO: the storage\n * transaction is ambient on the object, so callers bind the *outer*\n * `db` (as the \"sql\" path binds the outer connection). Drizzle's own\n * `db.transaction()` here is `ctx.storage.transactionSync` and cannot\n * span an await, so it is deliberately not used. Shared by\n * `transaction()` (business writes) and `runSchemaWriteTransaction()`.\n * Ordinary schema-version commits are data-only; administrative removal\n * cleanup may execute transaction-scoped DDL.\n */\n function runDoSqliteStorageTransaction<T>(run: () => Promise<T>): Promise<T> {\n const storage = getDurableObjectStorageClient(db);\n if (storage === undefined) {\n throwSqliteTransactionsDisabled(\n \"transactionMode 'do-sqlite' requires a Drizzle Durable Objects \" +\n \"database (drizzle(ctx.storage)) whose `$client` exposes the SQL, \" +\n \"transactionSync, and async transaction runners.\",\n );\n }\n return runWithSerializedQueue(serializedQueue, () =>\n storage.transaction(run),\n );\n }\n\n /**\n * Executes a transaction-frame statement (BEGIN IMMEDIATE / COMMIT /\n * ROLLBACK) through the prepared-statement cache when the driver has one.\n * These are the hottest statements on the per-write path (every single\n * write is its own transaction). Local libsql also uses \"sql\" transaction\n * mode but is async (no compiled path) and keeps the drizzle fallback.\n */\n async function runFrameStatement(query: SQL): Promise<void> {\n const compiledRun = executionAdapter.executeCompiledRun;\n if (compiledRun === undefined) {\n await db.run(query);\n return;\n }\n await compiledRun(executionAdapter.compile(query));\n }\n\n /**\n * Rolls the manually framed transaction back on the failure path WITHOUT ever\n * throwing: the caller rethrows the original error immediately after.\n *\n * SQLite rolls a transaction back by itself on some errors (SQLITE_FULL,\n * SQLITE_IOERR, SQLITE_NOMEM), so by the time this runs the frame can already\n * be gone and the ROLLBACK fails with \"cannot rollback - no transaction is\n * active\". A bare `await ROLLBACK; throw error` replaces the caller's\n * actionable failure (\"disk image is malformed\") with that secondary one and\n * never reaches its own rethrow — the masking that `closeAfterFailure` and the\n * index-materialization claim release exist to prevent, applied here too.\n *\n * The two reasons a ROLLBACK can fail are NOT told apart here, deliberately.\n * SQLite reports the already-closed frame only as a message (\"cannot rollback\n * - no transaction is active\"), with no result code that distinguishes it, so\n * a classifier would have to match text through whatever wrapper the driver\n * applied — and it would buy nothing, because the handling is identical\n * either way: never mask the caller's error, always report. The report\n * therefore states both possibilities rather than asserting the benign one,\n * so an operator reading the log is not told \"nothing is leaked\" about a\n * failure that did leave the frame open. When it did, nothing here can close\n * it (the statement that would is the one that just failed) and the next\n * BEGIN on this connection fails loudly rather than silently joining it.\n */\n async function rollbackFrameQuietly(): Promise<void> {\n try {\n await runFrameStatement(sql`ROLLBACK`);\n } catch (rollbackError) {\n console.warn(\n \"typegraph: ROLLBACK failed while unwinding a failed SQLite \" +\n \"transaction; the original failure is the one thrown. Either the \" +\n \"frame was already closed (SQLite auto-rolls-back on SQLITE_FULL / \" +\n \"SQLITE_IOERR / SQLITE_NOMEM) and nothing is leaked, or it is still \" +\n \"open on this connection, in which case the next BEGIN here fails.\",\n rollbackError,\n );\n }\n }\n\n /**\n * Runs `fn` inside a SQLite write transaction (BEGIN IMMEDIATE) so that\n * the read-then-write inside `commitSchemaVersion` / `setActiveVersion`\n * is serialized against concurrent writers — a deferred BEGIN would let\n * two transactions race past the CAS read and one would later fail\n * with SQLITE_BUSY instead of producing a clean StaleVersionError.\n *\n * Refuses on `transactionMode: \"none\"`. The orphan-row crash window\n * cannot be eliminated without atomicity.\n */\n function runSchemaWriteTransaction<T>(\n fn: (tx: InternalOperationBackend) => Promise<T>,\n ): Promise<T> {\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\n \"Schema writes and removal cleanup require atomic transactions, \" +\n \"but this SQLite backend has transactions disabled. Configure a \" +\n \"driver that supports transactions (better-sqlite3, libsql, \" +\n \"bun:sqlite) to use schema commits.\",\n );\n }\n\n if (transactionMode === \"sql\") {\n return runWithSerializedQueue(serializedQueue, async () => {\n // Write-lock is held here, so the schema-write-capable\n // InternalOperationBackend is used intentionally (see its type).\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n await runFrameStatement(sql`BEGIN IMMEDIATE`);\n try {\n const result = await fn(txBackend);\n await runFrameStatement(sql`COMMIT`);\n return result;\n } catch (error) {\n await rollbackFrameQuietly();\n throw error;\n }\n });\n }\n\n if (transactionMode === \"do-sqlite\") {\n // No interactive lock-mode control on the DO storage runner; the\n // serialized queue (always present — DO is sync) provides the\n // single-writer ordering that \"immediate\" gives the other paths.\n // Raw txBackend (no `gateFulltext`, unlike the business\n // `transaction()` do-sqlite branch). Schema-version commits remain\n // data-only; administrative removal cleanup may use the target's\n // transaction-scoped DDL primitive.\n return runDoSqliteStorageTransaction(async () => {\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n return fn(txBackend);\n });\n }\n\n // transactionMode === \"drizzle\". Drizzle's sqlite-core transaction\n // accepts a `behavior` option that maps to BEGIN / BEGIN IMMEDIATE /\n // BEGIN EXCLUSIVE; \"immediate\" is what we need to acquire a reserved\n // write lock at the start of the transaction.\n return runWithSerializedQueue(\n serializedQueue,\n async () =>\n db.transaction(\n async (tx) => {\n const txBackend = createTransactionBackend({\n capabilities,\n db: tx,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n return fn(txBackend);\n },\n { behavior: \"immediate\" },\n ) as Promise<T>,\n );\n }\n\n // Shared by the \"drizzle\" branch of `transaction()` (TypeGraph opens\n // the tx) and `adoptTransaction()` (#134 — the caller already opened\n // it): bind a tx-scoped backend to the *literal* `tx` client and gate\n // fulltext on the durable marker (a cached SELECT, never DDL).\n function bindTransactionBackend(tx: AnySqliteDatabase): TransactionBackend {\n const txBackend = createTransactionBackend({\n capabilities,\n db: tx,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n return gateFulltext(txBackend, contributionMaterializer.assertInitialized);\n }\n\n const backend: AdapterBackend<AnySqliteDatabase> = {\n ...operations,\n\n ...((\n isSync &&\n transactionMode === \"sql\" &&\n executionAdapter.executePreparedRunBatch !== undefined\n ) ?\n {\n async trustedImport<T>(\n fn: (session: TrustedImportSession) => Promise<T>,\n options_?: TrustedImportOptions,\n ): Promise<T> {\n return backend.transaction(async (tx) => {\n if (options_?.schemaWrite !== undefined) {\n await requireDefined(tx.lockSchemaVersionForWrite)({\n ...options_.schemaWrite,\n });\n }\n await assertTrustedImportDatabaseEmpty(tx, tableNames);\n const indexDefinitions = await suspendSqliteSecondaryIndexes(\n tx,\n tableNames,\n );\n const result = await fn(\n createSqliteTrustedImportSession(executionAdapter, tableNames),\n );\n await restoreSecondaryIndexes(tx, indexDefinitions);\n await analyzeImportedTables(tx, tableNames);\n return result;\n });\n },\n }\n : {}),\n\n async bootstrapTables(): Promise<void> {\n const statements = generateSqliteDDL(tables, fulltextStrategy);\n for (const statement of statements) {\n await db.run(sql.raw(statement));\n }\n },\n\n async ensureRevisionOriginsTable(): Promise<void> {\n await db.run(\n sql.raw(generateSqliteCreateTableSQL(tables.revisionOrigins)),\n );\n },\n\n async ensureIdentityTables(\n identityTableNames,\n options,\n ): Promise<readonly string[]> {\n // First enablement of Operational Identity on an existing populated\n // database: createStore / createSqliteBackend run no DDL, so the four\n // identity relations the enablement preflight reads/writes may not\n // exist yet. Ensure them (and their indexes and CHECK constraints)\n // idempotently — CREATE TABLE / CREATE INDEX IF NOT EXISTS — reusing the same contribution\n // DDL bootstrapTables emits, scoped to the identity relations.\n const identityContributions =\n identityContributionsFor(identityTableNames);\n const missing = [] as string[];\n for (const contribution of identityContributions) {\n if (!(await contributionTableExists(contribution.tableName))) {\n missing.push(contribution.logicalName);\n }\n }\n // Preserve missing ledger storage on already-enabled graphs so a retry\n // cannot silently accept tables created empty by an earlier failed open.\n // First enablement opts into provisioning; when every table exists,\n // idempotent DDL still repairs missing secondary indexes.\n if (missing.length === 0 || options.provisionMissing) {\n for (const contribution of identityContributions) {\n for (const ddl of contribution.createDdl) {\n await db.run(sql.raw(ddl));\n }\n }\n }\n return missing;\n },\n\n identityTableDdl(identityTableNames): readonly string[] {\n return identityContributionsFor(identityTableNames).flatMap(\n (contribution) => [...contribution.createDdl],\n );\n },\n\n // Every fulltext-touching method asserts the durable marker instead\n // of lazily emitting DDL. Steady state performs zero ensure; an\n // uninitialized database throws `StoreNotInitializedError` rather\n // than self-healing (#135). Shared verbatim with the tx-scoped gate\n // via `gateFulltextMethods`.\n ...gateFulltextMethods(\n operations,\n contributionMaterializer.assertInitialized,\n ),\n\n async executeDdl(ddl: string): Promise<void> {\n await db.run(sql.raw(ddl));\n },\n\n async ensureIndexMaterializationsTable(): Promise<void> {\n await db.run(\n sql.raw(generateSqliteCreateTableSQL(tables.indexMaterializations)),\n );\n },\n\n async getIndexMaterialization(\n indexName: string,\n ): Promise<IndexMaterializationRow | undefined> {\n const t = tables.indexMaterializations;\n const rows = await db.select().from(t).where(eq(t.indexName, indexName));\n const row = rows[0];\n if (row === undefined) return undefined;\n return mapMaterializationRow(row, SQLITE_INDEX_MAT_TIMESTAMPS.decode);\n },\n\n async getIndexMaterializations(\n statusKeys: readonly string[],\n ): Promise<readonly IndexMaterializationRow[]> {\n if (statusKeys.length === 0) return [];\n const t = tables.indexMaterializations;\n const rows = await db\n .select()\n .from(t)\n .where(inArray(t.indexName, [...statusKeys]));\n return rows.map((row) =>\n mapMaterializationRow(row, SQLITE_INDEX_MAT_TIMESTAMPS.decode),\n );\n },\n\n async recordIndexMaterialization(\n params: RecordIndexMaterializationParams,\n ): Promise<void> {\n const t = tables.indexMaterializations;\n await db\n .insert(t)\n .values(\n buildMaterializationInsertValues(\n params,\n SQLITE_INDEX_MAT_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: t.indexName,\n set: buildMaterializationOnConflictSet(params.materializedAt),\n });\n },\n\n async ensureContributionMaterializationsTable(): Promise<void> {\n await ensureContributionMaterializationsTableImpl();\n },\n\n async getContributionMaterialization(\n identity: ContributionMaterializationIdentity,\n ): Promise<ContributionMaterializationRow | undefined> {\n return getContributionMaterializationRow(identity);\n },\n\n async recordContributionMaterialization(\n params: RecordContributionMaterializationParams,\n ): Promise<void> {\n await recordContributionMaterializationRow(params);\n },\n\n async assertRuntimeContributionsInitialized(\n graphId: string,\n ): Promise<void> {\n await contributionMaterializer.assertInitialized(graphId);\n },\n\n async ensureKindRemovalsTable(): Promise<void> {\n await db.run(sql.raw(generateSqliteCreateTableSQL(tables.kindRemovals)));\n },\n\n async getPendingKindRemovals(\n graphId: string,\n ): Promise<readonly KindRemovalRow[]> {\n const t = tables.kindRemovals;\n const rows = await db\n .select()\n .from(t)\n .where(and(eq(t.graphId, graphId), isNull(t.removedAt)));\n return rows.map((row) =>\n mapKindRemovalRow(row, SQLITE_KIND_REMOVAL_TIMESTAMPS.decode),\n );\n },\n\n async getAllKindRemovals(\n graphId: string,\n ): Promise<readonly KindRemovalRow[]> {\n const t = tables.kindRemovals;\n const rows = await db.select().from(t).where(eq(t.graphId, graphId));\n return rows.map((row) =>\n mapKindRemovalRow(row, SQLITE_KIND_REMOVAL_TIMESTAMPS.decode),\n );\n },\n\n async recordKindRemoval(params: RecordKindRemovalParams): Promise<void> {\n const t = tables.kindRemovals;\n await db\n .insert(t)\n .values(\n buildKindRemovalInsertValues(\n params,\n SQLITE_KIND_REMOVAL_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: [t.graphId, t.kindName, t.entity, t.schemaVersion],\n set: buildKindRemovalOnConflictSet(t.removedAt, params.removedAt),\n });\n },\n\n async ensureReconciliationMarkersTable(): Promise<void> {\n await db.run(\n sql.raw(generateSqliteCreateTableSQL(tables.reconciliationMarkers)),\n );\n },\n\n async ensureRuntimeContributions(graphId: string): Promise<void> {\n await contributionMaterializer.ensureRuntimeContributions(graphId);\n },\n\n /**\n * Superseded by `ensureRuntimeContributions(graphId)` (#129).\n * Retained as a thin back-compat wrapper for callers predating\n * #129; #135 routed it through the durable-marker writer.\n */\n async ensureFulltextTable(graphId: string): Promise<void> {\n await contributionMaterializer.ensureRuntimeContributions(graphId);\n },\n\n async verifyContributions(\n graphId: string,\n vectorSlots: readonly VectorSlot[],\n ): Promise<readonly ContributionDiagnostic[]> {\n return contributionMaterializer.verifyContributions(graphId, vectorSlots);\n },\n\n async repairContributions(\n graphId: string,\n vectorSlots: readonly VectorSlot[],\n ): Promise<ContributionRepairResult> {\n return contributionMaterializer.repairContributions(graphId, vectorSlots);\n },\n\n async probeContributions(\n graphId: string,\n vectorSlots: readonly VectorSlot[],\n ): Promise<readonly ContributionProbeEntry[]> {\n return contributionMaterializer.probeContributions(graphId, vectorSlots);\n },\n\n async rebuildContribution(\n graphId: string,\n scope: ContributionRebuildScope,\n repopulate: (\n target: TransactionBackend,\n ) => Promise<ContributionRepopulationStats>,\n ): Promise<ContributionRebuildResult> {\n return contributionMaterializer.rebuildContribution(\n graphId,\n scope,\n repopulate,\n );\n },\n\n // Vector counterparts of the runtime-contribution methods. Present\n // only when a vector strategy is wired (omitted on a plain SQLite\n // connection with no vector extension), mirroring the embedding/\n // search methods.\n ...(vectorStrategy === undefined ?\n {}\n : {\n async ensureVectorSlotContribution(\n slot: VectorSlot,\n options_?: Readonly<{ force?: boolean; onDrift?: \"throw\" | \"skip\" }>,\n ): Promise<void> {\n await contributionMaterializer.ensureVectorSlot(slot, options_);\n },\n\n async ensureVectorSlotContributions(\n slots: readonly VectorSlot[],\n options_?: Readonly<{ force?: boolean; onDrift?: \"throw\" | \"skip\" }>,\n ): Promise<void> {\n await contributionMaterializer.ensureVectorSlots(slots, options_);\n },\n\n async assertVectorSlotInitialized(slot: VectorSlot): Promise<void> {\n await contributionMaterializer.assertVectorSlot(slot);\n },\n\n async assertVectorSlotsInitialized(\n slots: readonly VectorSlot[],\n ): Promise<void> {\n await contributionMaterializer.assertVectorSlots(slots);\n },\n\n async deleteVectorSlotContribution(slot: VectorSlot): Promise<void> {\n await contributionMaterializer.dropVectorSlot(slot);\n },\n }),\n\n async getReconciliationMarker(\n graphId: string,\n ): Promise<number | undefined> {\n const t = tables.reconciliationMarkers;\n const rows = await db.select().from(t).where(eq(t.graphId, graphId));\n return rows[0]?.reconciledToVersion;\n },\n\n async setReconciliationMarker(\n graphId: string,\n version: number,\n ): Promise<void> {\n const t = tables.reconciliationMarkers;\n await db\n .insert(t)\n .values({ graphId, reconciledToVersion: version })\n .onConflictDoUpdate({\n target: t.graphId,\n set: { reconciledToVersion: version },\n });\n },\n\n async refreshStatistics(): Promise<void> {\n // `ANALYZE` populates `sqlite_stat1`. With no stat table, the\n // planner falls back to heuristics that, at least for FTS5\n // virtual-table queries and multi-column index selection, can be\n // an order of magnitude slower. Running it explicitly makes the\n // planner data-driven.\n //\n // Scoped to TypeGraph-managed tables only (matching the Postgres\n // backend) — a bare `ANALYZE` touches every table in the database\n // file, including unrelated ones sharing it. Bounded by\n // `analysis_limit` (see its doc comment) so cost stays roughly\n // constant per call regardless of table size — the value is a\n // fixed internal constant, not user input, so inlining it via\n // `sql.raw` is safe; SQLite's `PRAGMA` does not accept bound\n // parameters for its value.\n try {\n await db.run(\n toDrizzleSql(\n portableSql`PRAGMA analysis_limit = ${portableSql.raw(String(SQLITE_ANALYZE_ROW_LIMIT))}`,\n \"sqlite\",\n ),\n );\n } catch (error) {\n // Cloudflare D1 and Durable Object SQLite reject this performance-only\n // tuning PRAGMA through their authorizer. Continue with scoped ANALYZE,\n // which workerd permits, but keep every unexpected failure loud.\n if (!isSqliteNotAuthorizedError(error)) throw error;\n }\n for (const tableName of coreAnalyzeTables) {\n await db.run(\n toDrizzleSql(\n portableSql`ANALYZE ${portableSql.identifier(tableName)}`,\n \"sqlite\",\n ),\n );\n }\n // The recorded and identity relations may be absent on a schema\n // created before recorded-time history or Operational Identity landed\n // (bring-your-own-connection, no DDL re-run); ANALYZE on a missing\n // table errors, so skip those.\n for (const tableName of guardedAnalyzeTables) {\n try {\n await db.run(\n toDrizzleSql(\n portableSql`ANALYZE ${portableSql.identifier(tableName)}`,\n \"sqlite\",\n ),\n );\n } catch (error) {\n if (!isMissingTableError(error)) throw error;\n }\n }\n },\n\n async commitSchemaVersion(\n params: CommitSchemaVersionParams,\n ): Promise<SchemaVersionRow> {\n return runSchemaWriteTransaction((target) =>\n target.commitSchemaVersion(params),\n );\n },\n\n async commitSchemaVersionIfKindsEmpty(\n params: CommitSchemaVersionParams,\n probes: readonly SchemaKindEmptinessProbe[],\n ): Promise<CommitSchemaVersionIfKindsEmptyResult> {\n // BEGIN IMMEDIATE already owns SQLite's serialized writer slot, so the\n // counts and schema CAS below share the same ordinary-write fence.\n return runSchemaWriteTransaction((target) =>\n commitSchemaVersionIfKindsEmpty(target, params, probes),\n );\n },\n\n async commitSchemaVersionWithPreflight(\n params: CommitSchemaVersionParams,\n // The schema-write target, not the narrowed transaction backend: a\n // preflight may have to CREATE the storage it then fills, and that DDL\n // belongs in this transaction rather than before it.\n preflight: (target: SchemaWriteTransactionBackend) => Promise<void>,\n ): Promise<SchemaVersionRow> {\n return runSchemaWriteTransaction(async (target) => {\n await preflight(target);\n return target.commitSchemaVersion(params);\n });\n },\n\n async setActiveVersion(params: SetActiveVersionParams): Promise<void> {\n await runSchemaWriteTransaction((target) =>\n target.setActiveVersion(params),\n );\n },\n\n async schemaWriteTransaction<T>(\n _graphId: string,\n fn: (tx: SchemaWriteTransactionBackend) => Promise<T>,\n ): Promise<T> {\n return runSchemaWriteTransaction((target) => fn(target));\n },\n\n async transaction<T>(\n fn: (tx: TransactionBackend) => Promise<T>,\n options?: InternalTransactionOptions,\n ): Promise<T> {\n return backend.transactionWithNative((tx) => fn(tx), options);\n },\n\n async transactionWithNative<T>(\n fn: (tx: TransactionBackend, sql: AnySqliteDatabase) => Promise<T>,\n options?: InternalTransactionOptions,\n ): Promise<T> {\n const temporaryWrites =\n options?.temporaryWrites === INTERNAL_TEMPORARY_WRITES;\n if (temporaryWrites && options.accessMode !== \"read_only\") {\n throw new ConfigurationError(\n \"Temporary-write transactions must be semantically read-only.\",\n { dialect: \"sqlite\" },\n );\n }\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\n \"This SQLite backend does not support atomic transactions. \" +\n \"Operations within a transaction are not rolled back on failure. \" +\n \"Use backend.capabilities.transactions to check for transaction support, \" +\n \"or use individual operations with manual error handling.\",\n );\n }\n\n // #134/#135: NO DDL or ensure here. The tx-scoped backend\n // exposes raw fulltext methods without self-ensure wrappers; the\n // single gate is `Store.transaction()`, which asserts the durable\n // contribution marker (one cached SELECT) before this method is\n // reached. The caller's BEGIN never carries CREATE statements.\n if (transactionMode === \"sql\") {\n return runWithSerializedQueue(serializedQueue, async () => {\n // Not `bindTransactionBackend(...)`: this path frames the tx\n // with manual BEGIN/COMMIT on the *outer* `db`, so it must\n // reuse that connection's already-built `executionAdapter`\n // rather than synthesize a fresh one for a distinct handle.\n // Serves sync drivers AND local libsql connections: both keep\n // one stable connection, where raw BEGIN/COMMIT composes and\n // Drizzle's `db.transaction()` (which for libsql abandons the\n // client's connection — fatal for `:memory:`) must be avoided.\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n // Read-only multi-statement operations need one snapshot but must not\n // reserve SQLite's single writer slot. Business transactions retain\n // BEGIN IMMEDIATE so read-then-write cannot lose a lock-upgrade race.\n await runFrameStatement(\n options?.accessMode === \"read_only\" || temporaryWrites ?\n sql`BEGIN`\n : sql`BEGIN IMMEDIATE`,\n );\n\n try {\n const result = await fn(\n gateFulltext(\n txBackend,\n contributionMaterializer.assertInitialized,\n ),\n db,\n );\n await runFrameStatement(sql`COMMIT`);\n return result;\n } catch (error) {\n await rollbackFrameQuietly();\n throw error;\n }\n });\n }\n\n if (transactionMode === \"do-sqlite\") {\n return runDoSqliteStorageTransaction(async () =>\n fn(bindTransactionBackend(db), db),\n );\n }\n\n // transactionMode === \"drizzle\". Read-only work uses a deferred snapshot;\n // business transactions retain BEGIN IMMEDIATE for safe lock upgrades.\n return runWithSerializedQueue(\n serializedQueue,\n async () =>\n db.transaction(async (tx) => fn(bindTransactionBackend(tx), tx), {\n behavior:\n options?.accessMode === \"read_only\" || temporaryWrites ?\n \"deferred\"\n : \"immediate\",\n }) as Promise<T>,\n );\n },\n\n adoptTransaction(externalTx: AnySqliteDatabase): TransactionBackend {\n // #134: parity with Postgres. Cross-store atomicity needs real\n // rollback; on a \"none\" driver the caller's relational write\n // would commit with no way to undo the graph write. Refuse\n // loudly rather than silently degrade.\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\n \"Cross-store atomicity is unavailable on this SQLite backend: \" +\n \"transactions are disabled (transactionMode: 'none'). Adopting \" +\n \"an external transaction here would let the caller's relational \" +\n \"write commit with no way to roll back the graph write. \" +\n \"Configure a driver that supports transactions (better-sqlite3, \" +\n \"libsql, bun:sqlite).\",\n );\n }\n assertAdoptedDialect<AnySqliteDatabase>(\n externalTx,\n BaseSQLiteDatabase,\n \"sqlite\",\n );\n // serializedQueue is deliberately NOT applied to an adopted tx: a\n // sync better-sqlite3 driver runs the adopted statements on the\n // caller's stack, so wrapping a caller-driven tx in our queue\n // could deadlock against the caller's outer `db.transaction(...)`.\n return bindTransactionBackend(externalTx);\n },\n\n close(): Promise<void> {\n serializedQueue?.dispose();\n return Promise.resolve();\n },\n };\n\n // INVARIANT: mark before any wrapper can observe this backend — see\n // transaction-resource.ts.\n if (serializedConnection !== undefined) {\n markSerializedTransactionResource(backend, serializedConnection);\n }\n\n return backend;\n}\n\nfunction createTransactionBackend(\n options: CreateSqliteTransactionBackendOptions,\n): InternalOperationBackend {\n const txExecutionAdapter =\n options.executionAdapter ??\n createSqliteExecutionAdapter(options.db, {\n profileHints: options.profileHints,\n });\n\n // The transaction-scoped backend shares the outer backend's\n // contribution materializer: the per-field vector table is provisioned\n // (DDL) only by the privileged outer backend, so a tx-scoped vector op\n // only ASSERTS the durable marker (SELECT, never DDL) and can't poison\n // anything on rollback. The shared per-instance cache means a slot\n // confirmed once stays a pure `Set.has` inside every later transaction.\n return createSqliteOperationBackend({\n capabilities: options.capabilities,\n db: options.db,\n executionAdapter: txExecutionAdapter,\n operationStrategy: options.operationStrategy,\n tableNames: options.tableNames,\n fulltextStrategy: options.fulltextStrategy,\n vectorStrategy: options.vectorStrategy,\n contributionMaterializer: options.contributionMaterializer,\n transactionScoped: true,\n });\n}\n\n// Re-export schema utilities\nexport type { SqliteTableNames, SqliteTables } from \"./schema/sqlite\";\nexport { createSqliteTables, tables } from \"./schema/sqlite\";\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/date.ts","../src/core/temporal.ts"],"names":[],"mappings":";;;AA6EA,IAAM,0BAAA,GACJ,+CAAA;AAEF,IAAM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AA,CAAW,aAAa,MAAA,GAC3B,KAAA,GACA,GAAG,KAAK,CAAA,gBAAA,EAAmB,UAAA,CAAW,QAAA,CAAS,IAAI,CAAA,CAAA;AACzD;AAMO,SAAS,kBACd,UAAA,EACyB;AACzB,EAAA,MAAM,EAAE,IAAA,EAAM,IAAA,EAAK,GAAI,UAAA,CAAW,KAAA;AAClC,EAAA,OAAO;AAAA,IACL,YAAA,EAAc,IAAA;AAAA,IACd,GAAI,IAAA,KAAS,MAAA,IAAa,EAAE,IAAA,EAAK;AAAA,IACjC,GAAI,UAAA,CAAW,QAAA,KAAa,MAAA,GAC1B,KACA,EAAE,YAAA,EAAc,UAAA,CAAW,QAAA,CAAS,IAAA;AAAK,GAC7C;AACF","file":"chunk-DLNROMQ7.js","sourcesContent":["/**\n * Date encoding utilities for consistent storage.\n *\n * Contract: All dates are stored as ISO 8601 strings in UTC.\n * - Always includes milliseconds\n * - Always UTC (Z suffix)\n * - Sorts correctly as strings\n */\n\nimport {\n IMMUTABLE_VALIDITY_LOWER_BOUND_CODE,\n INVERTED_VALIDITY_WINDOW_CODE,\n ValidationError,\n} from \"../errors\";\n\n/**\n * ISO 8601 datetime pattern.\n * Matches formats like:\n * - 2024-01-15T10:30:00.000Z\n * - 2024-01-15T10:30:00Z\n * - 2024-01-15T10:30:00.123Z\n */\nconst ISO_DATE_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?Z$/;\n\n/**\n * Checks if a string is a valid ISO 8601 datetime.\n *\n * @param value - String to validate\n * @returns True if valid ISO 8601 datetime\n */\nexport function isValidIsoDate(value: string): boolean {\n if (!ISO_DATE_PATTERN.test(value)) {\n return false;\n }\n // Also check that Date parsing produces a valid date\n const date = new Date(value);\n return !Number.isNaN(date.getTime());\n}\n\n/**\n * Validates that a string is a valid ISO 8601 datetime.\n * Throws ValidationError if invalid.\n *\n * @param value - String to validate\n * @param fieldName - Name of field for error message\n * @returns The validated string\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function validateIsoDate(value: string, fieldName: string): string {\n if (!isValidIsoDate(value)) {\n throw new ValidationError(\n `Invalid ISO 8601 datetime for \"${fieldName}\": \"${value}\". ` +\n `Expected format: YYYY-MM-DDTHH:mm:ss.sssZ`,\n {\n issues: [\n {\n path: fieldName,\n message: `Invalid ISO 8601 datetime format. Expected: YYYY-MM-DDTHH:mm:ss.sssZ, got: \"${value}\"`,\n },\n ],\n },\n {\n suggestion: `Use a valid ISO 8601 UTC datetime like \"2024-01-15T10:30:00.000Z\"`,\n },\n );\n }\n return value;\n}\n\n/**\n * Strict canonical ISO 8601 pattern: fixed-width UTC with exactly\n * millisecond precision (`YYYY-MM-DDTHH:mm:ss.sssZ`). Unlike\n * {@link ISO_DATE_PATTERN}, which tolerates a missing or variable-width\n * fractional part, this is the only shape whose lexicographic text order\n * matches chronological order — avoiding cases like `\"...:00.1Z\"` (= `.100`)\n * sorting *after* `\"...:00.101Z\"`.\n */\nconst CANONICAL_ISO_DATE_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/;\n\nconst ZONELESS_DATETIME_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?$/;\nconst OFFSET_DATETIME_PATTERN =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?)(Z|[+-]\\d{2}(?::?\\d{2})?)$/i;\nconst DATE_ONLY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nfunction normalizedOffset(offset: string): string {\n if (offset.toUpperCase() === \"Z\") return \"Z\";\n if (/^[+-]\\d{2}$/.test(offset)) return `${offset}:00`;\n if (/^[+-]\\d{4}$/.test(offset)) {\n return `${offset.slice(0, 3)}:${offset.slice(3)}`;\n }\n return offset;\n}\n\nfunction databaseTimestampMilliseconds(value: string): number {\n if (ZONELESS_DATETIME_PATTERN.test(value)) {\n return Date.parse(`${value.replace(\" \", \"T\")}Z`);\n }\n const offsetMatch = OFFSET_DATETIME_PATTERN.exec(value);\n if (offsetMatch !== null) {\n const date = offsetMatch[1];\n const time = offsetMatch[2];\n const offset = offsetMatch[3];\n if (date === undefined || time === undefined || offset === undefined) {\n return Number.NaN;\n }\n return Date.parse(`${date}T${time}${normalizedOffset(offset)}`);\n }\n if (DATE_ONLY_PATTERN.test(value)) {\n return Date.parse(`${value}T00:00:00.000Z`);\n }\n return Number.NaN;\n}\n\n/**\n * Canonicalizes a database-driver timestamp without interpreting a zoneless\n * string in the host timezone. PostgreSQL drivers can return values such as\n * `2026-06-25 12:00:00`; TypeGraph treats that shape as UTC so the same stored\n * clock value cannot move across hosts or daylight-saving boundaries.\n *\n * Returns `undefined` for an unsupported or unrepresentable value so callers\n * can raise an error specific to their storage boundary.\n */\nexport function canonicalizeDatabaseTimestamp(\n value: unknown,\n): string | undefined {\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) return undefined;\n return value.toISOString();\n }\n if (typeof value !== \"string\") return undefined;\n const milliseconds = databaseTimestampMilliseconds(value);\n if (Number.isNaN(milliseconds)) return undefined;\n return new Date(milliseconds).toISOString();\n}\n\n/**\n * Checks if a string is a canonical UTC ISO 8601 datetime with fixed\n * millisecond width (`YYYY-MM-DDTHH:mm:ss.sssZ`).\n */\nexport function isCanonicalIsoDate(value: string): boolean {\n if (!CANONICAL_ISO_DATE_PATTERN.test(value)) return false;\n const date = new Date(value);\n return !Number.isNaN(date.getTime()) && date.toISOString() === value;\n}\n\n/**\n * Validates that a string is a canonical UTC ISO 8601 datetime with fixed\n * millisecond width. Stricter than {@link validateIsoDate} (which also\n * accepts missing or 1–2 digit milliseconds): required wherever the value\n * is compared **as text** against stored timestamps and must sort\n * chronologically — e.g. a temporal `asOf` coordinate, where a\n * variable-width value would mis-order and silently include or exclude the\n * wrong rows. Produce one with `new Date(value).toISOString()`.\n *\n * @param value - String to validate\n * @param fieldName - Name of field for error message\n * @returns The validated string\n * @throws ValidationError if not a canonical UTC ISO datetime\n */\nexport function validateCanonicalIsoDate(\n value: string,\n fieldName: string,\n): string {\n if (!isCanonicalIsoDate(value)) {\n throw new ValidationError(\n `Invalid canonical ISO 8601 datetime for \"${fieldName}\": \"${value}\". ` +\n `Expected fixed-width UTC: YYYY-MM-DDTHH:mm:ss.sssZ`,\n {\n issues: [\n {\n path: fieldName,\n message: `Expected canonical UTC ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ), got: \"${value}\"`,\n },\n ],\n },\n {\n suggestion: `Use a fixed-width UTC datetime like \"2024-01-15T10:30:00.000Z\" (e.g. new Date(value).toISOString()).`,\n },\n );\n }\n return value;\n}\n\n/**\n * Validates an optional canonical ISO date string. Returns `undefined` for an\n * absent value; otherwise enforces canonical fixed-width UTC ISO 8601 via\n * {@link validateCanonicalIsoDate}. Used for stored validity-window inputs\n * (`validFrom` / `validTo`) so every timestamp the temporal filters compare as\n * text is canonical and sorts chronologically — the same contract the `asOf`\n * read coordinate already enforces.\n */\nexport function validateOptionalCanonicalIsoDate(\n value: string | undefined,\n fieldName: string,\n): string | undefined {\n if (value === undefined) return undefined;\n return validateCanonicalIsoDate(value, fieldName);\n}\n\n/**\n * Whether a CANONICAL stated bound names the same instant a row already stores.\n *\n * The one comparison of a caller's bound against a stored one, so the coalesce\n * dirty check (\"would this write move the window?\") and the write guard (\"can\n * this stated bound be applied?\") can never disagree about what \"the same bound\"\n * means. Two copies of it did disagree — one comparing driver text, one\n * comparing instants — which is how a re-stated window wrote on one backend and\n * coalesced on the other.\n *\n * Only the STORED side is canonicalized. It arrives as the driver rendered it,\n * and the dialects do not render a timestamp the same way (SQLite returns the\n * written text; a Postgres driver may hand back a zoned string equivalent to the\n * canonical form without being identical to it). The stated side needs no\n * canonicalization because every write path validates it as canonical first —\n * which is a PRECONDITION here, not an assumption: a non-canonical stated bound\n * would compare unequal to an equivalent stored instant and must be rejected by\n * {@link validateCanonicalIsoDate} rather than silently treated as a mismatch.\n */\nexport function statedBoundMatchesStored(\n stated: string,\n stored: string | undefined,\n): boolean {\n return stated === canonicalizeDatabaseTimestamp(stored);\n}\n\n/**\n * Whether a stated validity window has NEGATIVE width — a row that stopped\n * being true before it started. The one comparison every window refusal is\n * built on, so paths that must report the fault through their own error type\n * (trusted import) decide it identically to the ones that throw a\n * `ValidationError`.\n *\n * PRECONDITION: both endpoints are canonical fixed-width UTC ISO 8601, which is\n * what makes a lexicographic compare a chronological one. Every caller\n * establishes that before comparing, with no exception: the paths that throw a\n * `ValidationError` reach this through {@link validateOptionalCanonicalIsoDate},\n * and trusted import — which skips schema validation for throughput —\n * format-checks the stated window fields of every streamed row against\n * {@link isCanonicalIsoDate} before reaching here. A bound read back from a row\n * needs no check of its own: it is canonical because the write that stored it\n * was held to this same contract — SQLite hands that text back verbatim, and the\n * PostgreSQL row mapper normalizes the driver's shape back to it. So no caller\n * can compare a value that would mis-sort, here or later against an `asOf`\n * coordinate.\n *\n * ZERO width (`validFrom === validTo`) is not inverted: it is what a\n * same-instant retraction produces at millisecond precision, and the store's own\n * output must round-trip.\n */\nexport function isInvertedValidityWindow(\n validFrom: string | undefined,\n validTo: string | undefined,\n): boolean {\n if (validFrom === undefined || validTo === undefined) return false;\n return validFrom > validTo;\n}\n\n/**\n * Refuses a `validTo` whose EFFECTIVE lower bound would invert the window. On an\n * in-place update the row's stored lower bound is the effective one and must stay\n * <= the new `validTo`; on a resurrection that RESETS `valid_from` it is the\n * write instant, so a lone past `validTo` would be born inverted.\n *\n * A ZERO-width window (`validTo === effectiveValidFrom`) is legal and stays\n * legal: it is what a same-instant retraction produces at millisecond\n * precision, and the identity-import window check sanctions it for the same\n * reason. Only NEGATIVE width refuses.\n *\n * Reached through {@link assertWritableValidityWindow} rather than called\n * directly, so no writer can check the effective bound without also checking a\n * stated pair.\n */\nfunction assertEffectiveValidityLowerBound(\n subject: string,\n effectiveValidFrom: string | undefined,\n validTo: string | undefined,\n): void {\n if (!isInvertedValidityWindow(effectiveValidFrom, validTo)) return;\n throw new ValidationError(\n `Inverted validity window for ${subject}: the effective validFrom \"${effectiveValidFrom}\" is after validTo \"${validTo}\".`,\n {\n issues: [\n {\n path: \"validTo\",\n code: INVERTED_VALIDITY_WINDOW_CODE,\n message: `Expected the effective validFrom <= validTo, got \"${effectiveValidFrom}\" > \"${validTo}\". The effective validFrom is the row's stored lower bound, or the write instant where the write stamps one.`,\n },\n ],\n },\n {\n suggestion:\n \"Provide both validFrom and validTo for a historical window, or drop validTo to keep the row current.\",\n },\n );\n}\n\n/**\n * Rejects an inverted validity window. `validFrom > validTo` describes a row\n * that stopped being true before it started, so no current-mode or `asOf` read\n * can ever observe it — the write succeeds and the row is then reachable only\n * through `includeEnded`, which reads as data loss rather than as the error it\n * is. Call this wherever both endpoints are supplied together; both are\n * canonical ISO 8601 by then, so a lexicographic compare is a chronological\n * compare.\n *\n * @param subject - Human-readable identification of the row, for the message\n * (e.g. `Person \"01H...\"`).\n * @throws ValidationError if both endpoints are present and out of order\n */\nexport function assertOrderedValidityWindow(\n subject: string,\n validFrom: string | undefined,\n validTo: string | undefined,\n): void {\n if (!isInvertedValidityWindow(validFrom, validTo)) return;\n throw new ValidationError(\n `Inverted validity window for ${subject}: validFrom \"${validFrom}\" is after validTo \"${validTo}\".`,\n {\n issues: [\n {\n path: \"validFrom\",\n code: INVERTED_VALIDITY_WINDOW_CODE,\n message: `Expected validFrom <= validTo, got \"${validFrom}\" > \"${validTo}\"`,\n },\n ],\n },\n {\n suggestion:\n \"Pass a validFrom at or before validTo, or omit validTo to leave the window open.\",\n },\n );\n}\n\n/**\n * What an UPDATE will do with the row's validity lower bound — the two facts the\n * write guard needs, stated by the writer that knows them.\n *\n * Every update path must decide `appliesStatedValidFrom` explicitly, because the\n * answer is not a property of the guard's other arguments: the same\n * `(validFrom, storedBound, validTo)` triple is a legal window restatement on a\n * resurrection and an unappliable bound on an in-place update.\n */\nexport type UpdateValidityLowerBound = Readonly<{\n /**\n * The bound the row will hold when the caller states no `validFrom`: the\n * stored `valid_from` for an in-place update, the write instant for a\n * resurrection that stamps a new one, `undefined` where there is no bound to\n * invert against.\n */\n effectiveValidFrom: string | undefined;\n /**\n * Whether the write STORES a stated `validFrom`. False for an in-place update\n * of a live row — `buildUpdateNode` / `buildUpdateEdge` rewrite `valid_from`\n * only on a resurrection — which is what makes a differing stated bound a\n * refusal rather than a silent drop.\n */\n appliesStatedValidFrom: boolean;\n /**\n * Whether `effectiveValidFrom` IS the row's stored `valid_from` — the value an\n * `expectedValidFrom` predicate would name — rather than a bound this write is\n * about to stamp itself.\n *\n * A node resurrection resets `valid_from` to the write instant and passes THAT\n * as the effective bound, so its verdict never looked at what the row holds and\n * a fence on the stored value would predicate the write on something nothing\n * read. An edge retains its bound through a resurrection, so its effective\n * bound is the stored one on both legs.\n */\n effectiveBoundIsStored: boolean;\n}>;\n\n/**\n * The `expectedValidFrom` predicate a write owes its verdict, shaped for\n * spreading straight into the backend's update params.\n *\n * `{}` means \"assert nothing\"; `{ expectedValidFrom: null }` means \"assert the\n * row still has NO lower bound\". The two are different claims and the object\n * form keeps them distinguishable at every call site — see\n * `UpdateNodeParams.expectedValidFrom`.\n */\nexport type ValidityLowerBoundFence = Readonly<{\n expectedValidFrom?: string | null;\n}>;\n\n/**\n * What {@link assertWritableValidityWindow} reports back about the verdict it\n * just reached — not about the window, but about what the verdict DEPENDED ON.\n *\n * THE SINGLE OWNER of the question \"must this write assert the row's stored\n * lower bound?\", and it answers by handing over the predicate ITSELF rather than\n * a flag a caller then turns into one. A write asserts every component its\n * verdict read (see `UpdateNodeParams.expectedValidFrom`), and which components\n * those are is decided by which branches the guard actually took — so a caller\n * that could still spell the fence on its own would eventually spell a different\n * one. Interchange import did exactly that: it asserted the probed\n * `valid_from` unconditionally, over-fencing props-only updates the store paths\n * (correctly) left unfenced. There is now nothing to re-derive.\n *\n * Too FEW assertions is a silent race; too many is a refusal of writes that are\n * legitimate. Both failures come from a second spelling.\n */\nexport type ValidityWindowVerdict = Readonly<{\n /**\n * The fence this verdict obliges the write to carry. Non-empty when the\n * verdict consulted the row's STORED `valid_from` — either by comparing a\n * stated bound against it, or by inverting a lone `validTo` against it — and\n * empty when the caller named no window at all, when the write applies the\n * bound it stated, or when the effective bound was one this write will stamp\n * rather than one the row holds. In those cases the verdict is independent of\n * what the row carries, and predicating the write on it would refuse a\n * concurrent recreate that changed nothing this decision looked at.\n */\n storedLowerBoundFence: ValidityLowerBoundFence;\n}>;\n\n/**\n * Refuses a stated `validFrom` the write would not apply.\n *\n * A live row's lower bound is HISTORY: it records when the row started being\n * true, and an in-place update never moves it. Accepting a bound that names a\n * different instant and then dropping it is the API lying — the caller's stated\n * window silently is not the stored one, while the write still spends a version\n * bump and a history row moving nothing. Restating the bound the row already\n * holds stays legal, so a caller that echoes a row's own window back (a merge\n * commit, a re-delivered upsert) is unaffected.\n *\n * Reached through {@link assertWritableValidityWindow} rather than called\n * directly, so no writer can accept a lower bound without declaring whether it\n * applies one.\n */\nfunction assertStatedLowerBoundIsApplicable(\n subject: string,\n statedValidFrom: string,\n storedValidFrom: string | undefined,\n): void {\n if (statedBoundMatchesStored(statedValidFrom, storedValidFrom)) return;\n const storedDescription =\n storedValidFrom === undefined ?\n \"the row has no lower bound\"\n : `the row's stored lower bound is \"${storedValidFrom}\"`;\n throw new ValidationError(\n `Unappliable validFrom for ${subject}: stated \"${statedValidFrom}\", but ${storedDescription} and the row is live.`,\n {\n issues: [\n {\n path: \"validFrom\",\n code: IMMUTABLE_VALIDITY_LOWER_BOUND_CODE,\n message: `A live row's lower bound is history and an in-place update never rewrites it, so \"${statedValidFrom}\" could not be applied.`,\n },\n ],\n },\n {\n suggestion:\n storedValidFrom === undefined ?\n \"Omit validFrom: this row has no lower bound to restate, and only a resurrection can give it one.\"\n : `Restate the stored bound (\"${storedValidFrom}\") or omit validFrom.`,\n },\n );\n}\n\n/**\n * THE window-ordering guard a valid-time UPDATE goes through, identically for\n * nodes and edges. Refuses a window of negative width — a row that stopped\n * being true before it started — whether the caller states both endpoints or\n * only the new end. Also refuses a stated lower bound the write cannot apply,\n * so no update accepts a `validFrom` it will ignore.\n *\n * Three checks, because the failures deserve different messages: the caller who\n * supplied both endpoints out of order gets told about the pair, the caller who\n * stated a lower bound this write cannot store gets told which bound the row\n * holds, and the caller whose lone `validTo` inverts against the bound the row\n * will actually carry gets told which bound that is.\n *\n * The stated pair is judged FIRST — an inverted pair is wrong whatever the row\n * holds — and the applicability of the lower bound before the effective-bound\n * check, so a caller is told their bound will not be stored rather than being\n * told about a bound they did not name.\n *\n * INSERTS use {@link assertOrderedValidityWindow} alone. An insert carrying a\n * lone historical `validTo` means \"born already ended\", and the write instant\n * the backend stamps as `valid_from` is a storage convention rather than a\n * caller assertion — the row is deliberately not current and is read back\n * through `includeEnded`. Only an UPDATE has a lower bound the caller can be\n * held to.\n *\n * @param subject - Human-readable identification of the row, for the message\n * (e.g. `Person \"01H...\"`).\n * @param validFrom - The caller's explicit lower bound, if any.\n * @param lowerBound - What the write will do with the row's lower bound; see\n * {@link UpdateValidityLowerBound}.\n * @returns {@link ValidityWindowVerdict} — the `expectedValidFrom` fence this\n * verdict obliges the write to carry, empty when it read no stored bound.\n * @throws ValidationError with issue code {@link INVERTED_VALIDITY_WINDOW_CODE}\n * or {@link IMMUTABLE_VALIDITY_LOWER_BOUND_CODE}\n */\nexport function assertWritableValidityWindow(\n subject: string,\n validFrom: string | undefined,\n lowerBound: UpdateValidityLowerBound,\n validTo: string | undefined,\n): ValidityWindowVerdict {\n assertOrderedValidityWindow(subject, validFrom, validTo);\n\n // The stated bound is COMPARED against the stored one only here — a write\n // that applies what the caller stated has nothing to compare it to.\n const comparedStatedBound =\n validFrom !== undefined && !lowerBound.appliesStatedValidFrom;\n if (comparedStatedBound) {\n assertStatedLowerBoundIsApplicable(\n subject,\n validFrom,\n lowerBound.effectiveValidFrom,\n );\n }\n\n assertEffectiveValidityLowerBound(\n subject,\n validFrom ?? lowerBound.effectiveValidFrom,\n validTo,\n );\n // ...and the inversion check falls back to the row's bound only when the\n // caller named an end without a start. Note this is true whether or not the\n // row HAS a bound: \"no lower bound to invert against\" is itself a reading of\n // the row, and a recreate that gives the row one changes the answer.\n const comparedStoredBoundAgainstEnd =\n validFrom === undefined && validTo !== undefined;\n\n const readEffectiveLowerBound =\n comparedStatedBound || comparedStoredBoundAgainstEnd;\n return {\n storedLowerBoundFence:\n readEffectiveLowerBound && lowerBound.effectiveBoundIsStored ?\n // eslint-disable-next-line unicorn/no-null -- `expectedValidFrom` distinguishes \"assert IS NULL\" (null) from \"assert nothing\" (an absent key); see UpdateNodeParams.\n { expectedValidFrom: lowerBound.effectiveValidFrom ?? null }\n : {},\n };\n}\n\n/**\n * Encodes a Date to an ISO 8601 string for storage.\n */\nexport function encodeDate(date: Date): string {\n return date.toISOString();\n}\n\n/**\n * Decodes an ISO 8601 string to a Date.\n * Validates the string format first.\n *\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function decodeDate(isoString: string): Date {\n validateIsoDate(isoString, \"date\");\n return new Date(isoString);\n}\n\n/**\n * Returns the current timestamp as an ISO string.\n */\nexport function nowIso(): string {\n return new Date().toISOString();\n}\n","/**\n * Shared temporal coordinate + validation.\n */\nimport { ValidationError } from \"../errors\";\nimport { validateCanonicalIsoDate } from \"../utils/date\";\nimport { type TemporalMode } from \"./types\";\n\nconst RECORDED_INSTANT_VERSION = \"r1\";\nconst RECORDED_REVISION_WIDTH = 16;\n/** Open interval ceiling for numeric recorded-revision columns. */\nexport const RECORDED_MAX_REVISION = Number.MAX_SAFE_INTEGER;\nconst RECORDED_INSTANT_PATTERN =\n /^r1:(\\d{16}):(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z)$/;\n\ndeclare const RECORDED_INSTANT_BRAND: unique symbol;\n\n/**\n * A versioned recorded-time anchor containing a fixed-width logical revision\n * and a canonical UTC physical timestamp:\n * `r1:0000000000000001:YYYY-MM-DDTHH:mm:ss.sssZ`.\n *\n * Logical revisions are strictly monotonic per graph and make every commit\n * addressable even when many commits share one wall-clock millisecond. The\n * timestamp is a non-decreasing physical wall-time high-water mark used by\n * diagonal valid-time reads. Same-millisecond commits repeat it; backward clock\n * corrections hold it at the previous value until wall time catches up. The\n * string is canonical and lexicographically ordered by revision, so it can\n * round-trip through plain string checkpoint columns without a custom\n * serializer.\n */\nexport type RecordedInstant = string & {\n readonly [RECORDED_INSTANT_BRAND]: \"RecordedInstant\";\n};\n\nexport type RecordedInstantParts = Readonly<{\n revision: number;\n recordedAt: string;\n}>;\n\nfunction invalidRecordedInstant(value: string, path: string): ValidationError {\n return new ValidationError(\n `${path} must be a canonical versioned recorded instant.`,\n {\n issues: [\n {\n path,\n message: `Expected ${RECORDED_INSTANT_VERSION}:<${RECORDED_REVISION_WIDTH}-digit revision>:YYYY-MM-DDTHH:mm:ss.sssZ, got \"${value}\"`,\n },\n ],\n },\n {\n suggestion:\n \"Persist the exact string returned by store.recordedNow(); migrate preview-schema checkpoints with migrateLegacyRecordedTime() and migrateRecordedAnchor().\",\n },\n );\n}\n\nexport function parseRecordedInstant(\n value: string,\n path = \"RecordedInstant\",\n): RecordedInstantParts {\n const match = RECORDED_INSTANT_PATTERN.exec(value);\n if (match === null) throw invalidRecordedInstant(value, path);\n const revisionText = match[1];\n const recordedAt = match[2];\n if (revisionText === undefined || recordedAt === undefined) {\n throw invalidRecordedInstant(value, path);\n }\n const revision = Number(revisionText);\n if (\n !Number.isSafeInteger(revision) ||\n revision < 1 ||\n revision >= RECORDED_MAX_REVISION\n ) {\n throw invalidRecordedInstant(value, path);\n }\n validateCanonicalIsoDate(recordedAt, path);\n return { revision, recordedAt };\n}\n\nexport function assertValidRecordedInstant(value: string, path: string): void {\n parseRecordedInstant(value, path);\n}\n\n/**\n * Splits an optional recorded anchor into the numeric revision that recorded\n * relations store their `recorded_from`/`recorded_to` boundaries as, and the\n * wall time that valid-time windows are measured against. Compilers that\n * consult both halves parse once through this instead of per predicate.\n */\nexport function optionalRecordedInstantParts(\n value: string | undefined,\n path = \"RecordedInstant\",\n): RecordedInstantParts | undefined {\n return value === undefined ? undefined : parseRecordedInstant(value, path);\n}\n\nexport function createRecordedInstant(\n revision: number,\n recordedAt: string,\n): RecordedInstant {\n if (\n !Number.isSafeInteger(revision) ||\n revision < 1 ||\n revision >= RECORDED_MAX_REVISION\n ) {\n throw new ValidationError(\n \"createRecordedInstant revision must be a valid recorded revision.\",\n {\n issues: [\n {\n path: \"createRecordedInstant.revision\",\n message: `Expected a safe integer from 1 through ${String(RECORDED_MAX_REVISION - 1)}, got ${String(revision)}`,\n },\n ],\n },\n );\n }\n const revisionText = revision\n .toString()\n .padStart(RECORDED_REVISION_WIDTH, \"0\");\n return asRecordedInstant(\n `${RECORDED_INSTANT_VERSION}:${revisionText}:${recordedAt}`,\n );\n}\n\n/**\n * Returns the canonical UTC wall-time component of a recorded anchor.\n *\n * The value is non-decreasing per graph, but it is not the commit-order key;\n * use the complete {@link RecordedInstant} when ordering or replaying commits.\n */\nexport function recordedInstantWallTime(instant: RecordedInstant): string {\n return parseRecordedInstant(instant).recordedAt;\n}\n\n/** Returns the strict per-graph logical revision carried by an anchor. */\nexport function recordedInstantRevision(instant: RecordedInstant): number {\n return parseRecordedInstant(instant).revision;\n}\n\n/**\n * Compares two recorded anchors by logical revision.\n *\n * Revisions are local to a graph, so only compare anchors produced by the same\n * graph. The physical wall-time component deliberately does not participate.\n */\nexport function compareRecordedInstants(\n left: RecordedInstant,\n right: RecordedInstant,\n): -1 | 0 | 1 {\n const leftRevision = recordedInstantRevision(left);\n const rightRevision = recordedInstantRevision(right);\n if (leftRevision < rightRevision) return -1;\n if (leftRevision > rightRevision) return 1;\n return 0;\n}\n\n/**\n * Brands a canonical versioned anchor string as a {@link RecordedInstant}.\n *\n * The escape hatch for an instant that round-trips through untyped storage:\n * captured from {@link Store.recordedNow}, persisted as a plain string, read\n * back, and replayed into `asOfRecorded`. Validates the canonical form eagerly —\n * the same check `asOfRecorded` applies — so a malformed value fails here, at the\n * brand site, rather than deeper in a read. Does *not* assert the instant is a\n * real captured commit; it only guarantees the value is well-formed enough to\n * compare correctly against the recorded relations.\n *\n * @throws {ValidationError} when `value` is not a canonical versioned anchor.\n */\nexport function asRecordedInstant(value: string): RecordedInstant {\n assertValidRecordedInstant(value, \"asRecordedInstant\");\n return value as RecordedInstant;\n}\n\n/**\n * The single opaque temporal coordinate every pinned read is resolved\n * against. It carries the valid-time axis plus an optional recorded/system-time\n * axis, so every surface can inject one coordinate object instead of threading\n * each temporal dimension separately.\n */\nexport type ReadCoordinate = Readonly<{\n /**\n * The valid-time axis: a resolved temporal mode and (only for `\"asOf\"`) the\n * instant it is pinned to.\n */\n valid: Readonly<{\n mode: TemporalMode;\n /** Defined only when `mode` is `\"asOf\"`. */\n asOf?: string;\n }>;\n /** The recorded/system-time axis. Defined only for recorded-pinned views. */\n recorded?: Readonly<{ asOf: RecordedInstant }>;\n}>;\n\n/**\n * Resolves and validates a `(mode, asOf)` pair into a {@link ReadCoordinate}.\n * Rejects an `asOf` paired with any non-`\"asOf\"` mode rather than silently\n * dropping it — pinning an instant is only meaningful in `\"asOf\"` mode, so a\n * `view({ mode: \"current\", asOf })` is a caller mistake, not a coordinate to\n * quietly discard. Then validates via {@link assertValidAsOf}.\n *\n * @param mode - The temporal mode to pin.\n * @param asOf - The supplied timestamp. Required for `\"asOf\"`; rejected for\n * every other mode.\n * @param suggestion - Caller-specific remediation hint for the\n * missing/invalid-timestamp case.\n */\nexport function resolveReadCoordinate(\n mode: TemporalMode,\n asOf: string | undefined,\n suggestion?: string,\n): ReadCoordinate {\n if (mode !== \"asOf\" && asOf !== undefined) {\n throw new ValidationError(\n `Temporal mode \"${mode}\" does not take an asOf timestamp.`,\n {\n issues: [\n {\n path: \"asOf\",\n message: `asOf is only valid with mode \"asOf\", not \"${mode}\"`,\n },\n ],\n },\n {\n suggestion:\n 'Pin an instant with store.asOf(timestamp) or store.view({ mode: \"asOf\", asOf }); drop asOf for other modes.',\n },\n );\n }\n assertValidAsOf(\n mode,\n asOf,\n suggestion === undefined ? undefined : { suggestion },\n );\n return { valid: asOf === undefined ? { mode } : { mode, asOf } };\n}\n\n/**\n * Adds a recorded/system-time pin to an existing valid-time coordinate.\n * Direct `store.asOfRecorded(T)` passes the diagonal valid-time coordinate\n * (`mode: \"asOf\", asOf: T`); `store.asOf(vt).asOfRecorded(rt)` passes the\n * already-resolved valid coordinate and adds the recorded sibling.\n */\nexport function withRecordedCoordinate(\n coordinate: ReadCoordinate,\n recordedAsOf: RecordedInstant,\n): ReadCoordinate {\n assertValidRecordedInstant(recordedAsOf, \"asOfRecorded\");\n return {\n ...coordinate,\n recorded: { asOf: recordedAsOf },\n };\n}\n\n/**\n * Validates the `asOf` coordinate of a temporal read: `\"asOf\"` mode\n * requires a timestamp, and any supplied timestamp must be a canonical\n * fixed-width UTC ISO-8601 string (`YYYY-MM-DDTHH:mm:ss.sssZ`). The latter\n * is load-bearing — temporal filters compare `asOf` against `valid_from` /\n * `valid_to` as text on SQLite, so a non-canonical value (date-only, an\n * offset, natural language, or variable-width / missing milliseconds like\n * `.1Z`) would sort and compare wrong rather than error. Reached only through\n * {@link resolveReadCoordinate}, which every temporal read entry point routes\n * through (direct reads, queries, subgraphs, algorithms, and StoreView), so\n * they all fail identically.\n *\n * @param mode - The resolved temporal mode.\n * @param asOf - The supplied timestamp (may be `undefined`).\n * @param options.suggestion - A caller-specific remediation hint for the\n * missing-timestamp case.\n *\n * @throws {ValidationError} when `mode` is `\"asOf\"` and `asOf` is missing, or\n * when any supplied `asOf` is not a canonical UTC ISO-8601 timestamp. The\n * canonical check runs for *every* mode that consumes `asOf`, so a\n * non-canonical value can never reach a text comparison.\n */\nfunction assertValidAsOf(\n mode: TemporalMode,\n asOf: string | undefined,\n options?: Readonly<{ suggestion?: string }>,\n): void {\n if (mode === \"asOf\" && asOf === undefined) {\n throw new ValidationError(\n 'Temporal mode \"asOf\" requires a timestamp',\n {\n issues: [\n { path: \"asOf\", message: \"Timestamp is required for asOf mode\" },\n ],\n },\n {\n suggestion:\n options?.suggestion ??\n 'Provide an ISO-8601 timestamp for asOf mode, e.g. \"2026-01-01T00:00:00.000Z\".',\n },\n );\n }\n if (asOf !== undefined) {\n validateCanonicalIsoDate(asOf, \"asOf\");\n }\n}\n\n/**\n * A human-readable description of a coordinate for error messages, e.g.\n * `mode \"current\"` or `mode \"asOf\" asOf 2026-01-01T00:00:00.000Z`. Shared by\n * every refusal path (the `StoreView` read-only / current-only / search facades\n * and the sealed-query builder) so they describe a coordinate identically — and\n * a future axis (recorded time) is reflected everywhere from one place.\n */\nexport function describeCoordinate(coordinate: ReadCoordinate): string {\n const { mode, asOf } = coordinate.valid;\n const valid =\n asOf === undefined ? `mode \"${mode}\"` : `mode \"${mode}\" asOf ${asOf}`;\n return coordinate.recorded === undefined ?\n valid\n : `${valid}, recorded asOf ${coordinate.recorded.asOf}`;\n}\n\n/**\n * The structured error-context fields describing a coordinate, shared by the\n * same refusal paths as {@link describeCoordinate}.\n */\nexport function coordinateContext(\n coordinate: ReadCoordinate,\n): Record<string, unknown> {\n const { mode, asOf } = coordinate.valid;\n return {\n temporalMode: mode,\n ...(asOf !== undefined && { asOf }),\n ...(coordinate.recorded === undefined ?\n {}\n : { recordedAsOf: coordinate.recorded.asOf }),\n };\n}\n"]}