@nicia-ai/typegraph 0.45.0 → 0.46.1
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.
- package/dist/backend/drizzle/indexes.cjs +11 -11
- package/dist/backend/drizzle/indexes.d.cts +1 -1
- package/dist/backend/drizzle/indexes.d.ts +1 -1
- package/dist/backend/drizzle/indexes.js +7 -7
- package/dist/backend/index.cjs +53 -54
- package/dist/backend/index.d.cts +3 -3
- package/dist/backend/index.d.ts +3 -3
- package/dist/backend/index.js +13 -14
- package/dist/backend/postgres/index.cjs +29 -30
- package/dist/backend/postgres/index.d.cts +7 -7
- package/dist/backend/postgres/index.d.ts +7 -7
- package/dist/backend/postgres/index.js +16 -17
- package/dist/backend/postgres/pglite-store.cjs +48 -42
- package/dist/backend/postgres/pglite-store.cjs.map +1 -1
- package/dist/backend/postgres/pglite-store.d.cts +15 -9
- package/dist/backend/postgres/pglite-store.d.ts +15 -9
- package/dist/backend/postgres/pglite-store.js +44 -38
- package/dist/backend/postgres/pglite-store.js.map +1 -1
- package/dist/backend/postgres/pglite.cjs +18 -19
- package/dist/backend/postgres/pglite.d.cts +4 -4
- package/dist/backend/postgres/pglite.d.ts +4 -4
- package/dist/backend/postgres/pglite.js +17 -18
- package/dist/backend/sqlite/index.cjs +26 -27
- package/dist/backend/sqlite/index.d.cts +6 -6
- package/dist/backend/sqlite/index.d.ts +6 -6
- package/dist/backend/sqlite/index.js +14 -15
- package/dist/backend/sqlite/libsql.cjs +21 -22
- package/dist/backend/sqlite/libsql.cjs.map +1 -1
- package/dist/backend/sqlite/libsql.d.cts +15 -8
- package/dist/backend/sqlite/libsql.d.ts +15 -8
- package/dist/backend/sqlite/libsql.js +17 -18
- package/dist/backend/sqlite/libsql.js.map +1 -1
- package/dist/backend/sqlite/local-store.cjs +49 -43
- package/dist/backend/sqlite/local-store.cjs.map +1 -1
- package/dist/backend/sqlite/local-store.d.cts +15 -10
- package/dist/backend/sqlite/local-store.d.ts +15 -10
- package/dist/backend/sqlite/local-store.js +45 -39
- package/dist/backend/sqlite/local-store.js.map +1 -1
- package/dist/backend/sqlite/local.cjs +19 -20
- package/dist/backend/sqlite/local.d.cts +3 -3
- package/dist/backend/sqlite/local.d.ts +3 -3
- package/dist/backend/sqlite/local.js +17 -18
- package/dist/{chunk-S3ZRKJHY.js → chunk-2LG2XB2M.js} +3 -3
- package/dist/{chunk-S3ZRKJHY.js.map → chunk-2LG2XB2M.js.map} +1 -1
- package/dist/{chunk-7PF2L3H6.cjs → chunk-2NA5DYLO.cjs} +4 -4
- package/dist/{chunk-7PF2L3H6.cjs.map → chunk-2NA5DYLO.cjs.map} +1 -1
- package/dist/chunk-2Z2Z3ZD6.js +58 -0
- package/dist/chunk-2Z2Z3ZD6.js.map +1 -0
- package/dist/{chunk-VVQM4CZD.cjs → chunk-3DHZCOT7.cjs} +20 -20
- package/dist/{chunk-VVQM4CZD.cjs.map → chunk-3DHZCOT7.cjs.map} +1 -1
- package/dist/{chunk-JXUTCSXX.cjs → chunk-4UGOKMI5.cjs} +250 -158
- package/dist/chunk-4UGOKMI5.cjs.map +1 -0
- package/dist/{chunk-RFRM3Q5K.js → chunk-5262ZMTR.js} +14 -5
- package/dist/chunk-5262ZMTR.js.map +1 -0
- package/dist/{chunk-QRNYDV5Z.js → chunk-5763DULU.js} +214 -69
- package/dist/chunk-5763DULU.js.map +1 -0
- package/dist/{chunk-BGYJW37L.js → chunk-5UVRGXD3.js} +277 -7
- package/dist/chunk-5UVRGXD3.js.map +1 -0
- package/dist/{chunk-QR24DJDF.cjs → chunk-62ZP23AW.cjs} +15 -15
- package/dist/{chunk-QR24DJDF.cjs.map → chunk-62ZP23AW.cjs.map} +1 -1
- package/dist/{chunk-ZI6VQSZA.cjs → chunk-65E3XWGF.cjs} +724 -577
- package/dist/chunk-65E3XWGF.cjs.map +1 -0
- package/dist/{chunk-S4KQ5LV4.js → chunk-775A4ZMN.js} +40 -6
- package/dist/chunk-775A4ZMN.js.map +1 -0
- package/dist/{chunk-J2ICGNHO.cjs → chunk-7BQXPCGN.cjs} +830 -169
- package/dist/chunk-7BQXPCGN.cjs.map +1 -0
- package/dist/{chunk-FJMPR3OH.cjs → chunk-7EO3TCQB.cjs} +33 -7
- package/dist/chunk-7EO3TCQB.cjs.map +1 -0
- package/dist/{chunk-DXEEHSGN.js → chunk-7VQXLT5O.js} +436 -43
- package/dist/chunk-7VQXLT5O.js.map +1 -0
- package/dist/chunk-A4OC4DVN.cjs +12 -0
- package/dist/{chunk-4SZ6XPTG.cjs.map → chunk-A4OC4DVN.cjs.map} +1 -1
- package/dist/{chunk-TDXIBCGY.cjs → chunk-A7J2YDDI.cjs} +5 -3
- package/dist/chunk-A7J2YDDI.cjs.map +1 -0
- package/dist/{chunk-55ITBQJI.js → chunk-AKLS3BYZ.js} +56 -5
- package/dist/chunk-AKLS3BYZ.js.map +1 -0
- package/dist/{chunk-D7PG5D5K.js → chunk-AMKPPFUO.js} +32 -6
- package/dist/chunk-AMKPPFUO.js.map +1 -0
- package/dist/{chunk-WUFASQUO.js → chunk-ASTI57H3.js} +3 -3
- package/dist/{chunk-WUFASQUO.js.map → chunk-ASTI57H3.js.map} +1 -1
- package/dist/{chunk-4QIKLIGG.js → chunk-BKCUOV7A.js} +15 -5
- package/dist/chunk-BKCUOV7A.js.map +1 -0
- package/dist/{chunk-JQXSZHF2.cjs → chunk-BSFJMMV3.cjs} +134 -7
- package/dist/chunk-BSFJMMV3.cjs.map +1 -0
- package/dist/{chunk-4GUTQPVO.js → chunk-C23WSN5E.js} +185 -24
- package/dist/chunk-C23WSN5E.js.map +1 -0
- package/dist/{chunk-QLUXRWKL.js → chunk-CBTIUB76.js} +3 -3
- package/dist/{chunk-QLUXRWKL.js.map → chunk-CBTIUB76.js.map} +1 -1
- package/dist/chunk-CMWHLBVN.cjs +2082 -0
- package/dist/chunk-CMWHLBVN.cjs.map +1 -0
- package/dist/{chunk-QB6VMOJ2.cjs → chunk-CXBHOOIQ.cjs} +45 -10
- package/dist/chunk-CXBHOOIQ.cjs.map +1 -0
- package/dist/{chunk-FL5UQRES.js → chunk-DCQVHAYQ.js} +5 -5
- package/dist/{chunk-FL5UQRES.js.map → chunk-DCQVHAYQ.js.map} +1 -1
- package/dist/chunk-DTVWX77L.cjs +3432 -0
- package/dist/chunk-DTVWX77L.cjs.map +1 -0
- package/dist/chunk-DYATYRY4.js +47 -0
- package/dist/chunk-DYATYRY4.js.map +1 -0
- package/dist/chunk-E4WNQBEF.cjs +217 -0
- package/dist/chunk-E4WNQBEF.cjs.map +1 -0
- package/dist/{chunk-G6Q5UM7U.js → chunk-FWJKWH6U.js} +5 -3
- package/dist/chunk-FWJKWH6U.js.map +1 -0
- package/dist/chunk-GF3KXUTW.js +3393 -0
- package/dist/chunk-GF3KXUTW.js.map +1 -0
- package/dist/{chunk-VTN3C3CH.js → chunk-HFHTMECK.js} +7 -7
- package/dist/{chunk-VTN3C3CH.js.map → chunk-HFHTMECK.js.map} +1 -1
- package/dist/{chunk-FLEQ2HBK.js → chunk-I5MOXA4H.js} +20 -14
- package/dist/chunk-I5MOXA4H.js.map +1 -0
- package/dist/{chunk-4MB3AQAQ.js → chunk-J3WZ3FA2.js} +77 -3
- package/dist/chunk-J3WZ3FA2.js.map +1 -0
- package/dist/{chunk-UR7W5YQK.js → chunk-JBQQ7THH.js} +5 -3
- package/dist/chunk-JBQQ7THH.js.map +1 -0
- package/dist/{chunk-TKP5T34P.js → chunk-JXA2ZP2Q.js} +6 -16
- package/dist/chunk-JXA2ZP2Q.js.map +1 -0
- package/dist/{chunk-GYA4JRP5.js → chunk-JXXDZTMN.js} +2 -2
- package/dist/chunk-JXXDZTMN.js.map +1 -0
- package/dist/chunk-JZUR7ZWE.js +254 -0
- package/dist/chunk-JZUR7ZWE.js.map +1 -0
- package/dist/{chunk-42PYUGLS.js → chunk-K5ELX2GT.js} +108 -8
- package/dist/chunk-K5ELX2GT.js.map +1 -0
- package/dist/{chunk-Q6EDCUXV.js → chunk-L65OU2U3.js} +556 -204
- package/dist/chunk-L65OU2U3.js.map +1 -0
- package/dist/{chunk-D54WH24V.cjs → chunk-LBJKZXDE.cjs} +115 -13
- package/dist/chunk-LBJKZXDE.cjs.map +1 -0
- package/dist/{chunk-FQ7ZPOTZ.js → chunk-LGHCOKTT.js} +637 -493
- package/dist/chunk-LGHCOKTT.js.map +1 -0
- package/dist/chunk-M3WP7RQZ.js +736 -0
- package/dist/chunk-M3WP7RQZ.js.map +1 -0
- package/dist/{chunk-4MEWSUVM.cjs → chunk-M4BDU5RX.cjs} +12 -12
- package/dist/chunk-M4BDU5RX.cjs.map +1 -0
- package/dist/chunk-MCLYU6BN.cjs +332 -0
- package/dist/chunk-MCLYU6BN.cjs.map +1 -0
- package/dist/{chunk-MIJKEVV7.js → chunk-MSY7FSX4.js} +37 -4
- package/dist/chunk-MSY7FSX4.js.map +1 -0
- package/dist/{chunk-H7VE3FL4.cjs → chunk-MUK4BU7K.cjs} +519 -125
- package/dist/chunk-MUK4BU7K.cjs.map +1 -0
- package/dist/{chunk-D56XG4EI.cjs → chunk-MXJDTH5B.cjs} +56 -45
- package/dist/chunk-MXJDTH5B.cjs.map +1 -0
- package/dist/{chunk-5EKPX6QU.js → chunk-MZLPX2R7.js} +8 -9
- package/dist/chunk-MZLPX2R7.js.map +1 -0
- package/dist/chunk-N66HCGCY.cjs +57 -0
- package/dist/chunk-N66HCGCY.cjs.map +1 -0
- package/dist/{chunk-CPEL3YIR.cjs → chunk-NFCVHQ5P.cjs} +55 -22
- package/dist/chunk-NFCVHQ5P.cjs.map +1 -0
- package/dist/{chunk-C4F7VJ5D.cjs → chunk-NI72YOJB.cjs} +84 -2
- package/dist/chunk-NI72YOJB.cjs.map +1 -0
- package/dist/{chunk-BNS75YNF.cjs → chunk-NK5Q7UNE.cjs} +10 -20
- package/dist/chunk-NK5Q7UNE.cjs.map +1 -0
- package/dist/{chunk-TKORQCG4.js → chunk-NLI2AVEF.js} +386 -862
- package/dist/chunk-NLI2AVEF.js.map +1 -0
- package/dist/{chunk-YMTXMPV6.js → chunk-NMWDXFPH.js} +4 -4
- package/dist/{chunk-YMTXMPV6.js.map → chunk-NMWDXFPH.js.map} +1 -1
- package/dist/{chunk-J7LXTUTP.cjs → chunk-PF6F5NLJ.cjs} +604 -1094
- package/dist/chunk-PF6F5NLJ.cjs.map +1 -0
- package/dist/{chunk-NAAMUYMS.cjs → chunk-PNN7RHVR.cjs} +58 -48
- package/dist/chunk-PNN7RHVR.cjs.map +1 -0
- package/dist/{chunk-YOALGKRE.cjs → chunk-PNTCATDE.cjs} +3528 -1763
- package/dist/chunk-PNTCATDE.cjs.map +1 -0
- package/dist/{chunk-6DCB664D.js → chunk-PQBQG7IM.js} +3 -3
- package/dist/{chunk-6DCB664D.js.map → chunk-PQBQG7IM.js.map} +1 -1
- package/dist/{chunk-UCQ3BFSY.cjs → chunk-PT7RIRIZ.cjs} +684 -332
- package/dist/chunk-PT7RIRIZ.cjs.map +1 -0
- package/dist/{chunk-ACSVZPK7.cjs → chunk-PWLJ77UV.cjs} +5 -3
- package/dist/chunk-PWLJ77UV.cjs.map +1 -0
- package/dist/chunk-Q3G6A4I3.cjs +755 -0
- package/dist/chunk-Q3G6A4I3.cjs.map +1 -0
- package/dist/{chunk-Z3WO6MND.cjs → chunk-RMQLSPA2.cjs} +297 -27
- package/dist/chunk-RMQLSPA2.cjs.map +1 -0
- package/dist/{chunk-SJDMVITW.cjs → chunk-RT5ZY4XA.cjs} +6 -5
- package/dist/chunk-RT5ZY4XA.cjs.map +1 -0
- package/dist/{chunk-ID4WXTKL.js → chunk-S6PW7VV5.js} +2382 -617
- package/dist/chunk-S6PW7VV5.js.map +1 -0
- package/dist/{chunk-4GUBTVPV.js → chunk-T4XNKYXB.js} +780 -126
- package/dist/chunk-T4XNKYXB.js.map +1 -0
- package/dist/{chunk-YDWLUT5V.cjs → chunk-TQR4KBY2.cjs} +323 -178
- package/dist/chunk-TQR4KBY2.cjs.map +1 -0
- package/dist/{chunk-OOA273IJ.cjs → chunk-U5SON7R2.cjs} +27 -27
- package/dist/{chunk-OOA273IJ.cjs.map → chunk-U5SON7R2.cjs.map} +1 -1
- package/dist/{chunk-IX64T5OL.cjs → chunk-U63GDNRC.cjs} +32 -26
- package/dist/chunk-U63GDNRC.cjs.map +1 -0
- package/dist/{chunk-WDBXJOU5.cjs → chunk-UDISNXDL.cjs} +56 -47
- package/dist/chunk-UDISNXDL.cjs.map +1 -0
- package/dist/{chunk-EFEOOCJ3.js → chunk-UV3SN74I.js} +5 -5
- package/dist/{chunk-EFEOOCJ3.js.map → chunk-UV3SN74I.js.map} +1 -1
- package/dist/{chunk-U5W4LKZV.cjs → chunk-VCRRKBLN.cjs} +9 -9
- package/dist/{chunk-U5W4LKZV.cjs.map → chunk-VCRRKBLN.cjs.map} +1 -1
- package/dist/{chunk-ISLPNELU.js → chunk-VGTJPTIC.js} +16 -5
- package/dist/chunk-VGTJPTIC.js.map +1 -0
- package/dist/chunk-VLT6PEWR.cjs +60 -0
- package/dist/chunk-VLT6PEWR.cjs.map +1 -0
- package/dist/chunk-VQH4VAWD.cjs +12 -0
- package/dist/{chunk-B3F2D3SP.cjs.map → chunk-VQH4VAWD.cjs.map} +1 -1
- package/dist/{chunk-SNXVDZAJ.js → chunk-W6OG3HDG.js} +5 -4
- package/dist/chunk-W6OG3HDG.js.map +1 -0
- package/dist/chunk-WDGA7IYB.js +207 -0
- package/dist/chunk-WDGA7IYB.js.map +1 -0
- package/dist/chunk-WQZLUGVR.js +2057 -0
- package/dist/chunk-WQZLUGVR.js.map +1 -0
- package/dist/{chunk-EKFUG4G7.cjs → chunk-XBYVV3MP.cjs} +60 -5
- package/dist/chunk-XBYVV3MP.cjs.map +1 -0
- package/dist/{chunk-5GAONX5G.cjs → chunk-XCAGZAKP.cjs} +7 -7
- package/dist/{chunk-5GAONX5G.cjs.map → chunk-XCAGZAKP.cjs.map} +1 -1
- package/dist/chunk-XL7SLCXS.js +309 -0
- package/dist/chunk-XL7SLCXS.js.map +1 -0
- package/dist/{chunk-SVJ5GEXW.cjs → chunk-XUO3KQFO.cjs} +2 -2
- package/dist/chunk-XUO3KQFO.cjs.map +1 -0
- package/dist/{chunk-F4NHQHEZ.cjs → chunk-YAAM3M2S.cjs} +10 -10
- package/dist/{chunk-F4NHQHEZ.cjs.map → chunk-YAAM3M2S.cjs.map} +1 -1
- package/dist/{chunk-RUQS6M7G.js → chunk-YBFHZUXX.js} +6 -6
- package/dist/chunk-YBFHZUXX.js.map +1 -0
- package/dist/{chunk-KMXWZLQX.cjs → chunk-YBQOHKHN.cjs} +99 -100
- package/dist/chunk-YBQOHKHN.cjs.map +1 -0
- package/dist/{chunk-PVUI6KGR.js → chunk-YDFDBE6D.js} +93 -6
- package/dist/chunk-YDFDBE6D.js.map +1 -0
- package/dist/{chunk-P7GTYOLB.cjs → chunk-YVWGEQJE.cjs} +297 -135
- package/dist/chunk-YVWGEQJE.cjs.map +1 -0
- package/dist/{chunk-QT6V3YRH.js → chunk-YWGVVALJ.js} +3 -3
- package/dist/{chunk-QT6V3YRH.js.map → chunk-YWGVVALJ.js.map} +1 -1
- package/dist/core/index.cjs +40 -40
- package/dist/core/index.d.cts +4 -5
- package/dist/core/index.d.ts +4 -5
- package/dist/core/index.js +8 -8
- package/dist/{ddl-BG4J805L.d.cts → ddl-BJcOp4WZ.d.cts} +3 -3
- package/dist/{ddl-CgiS9QLj.d.ts → ddl-BXfGHbPN.d.ts} +3 -3
- package/dist/graph-extension/index.cjs +26 -22
- package/dist/graph-extension/index.d.cts +16 -6
- package/dist/graph-extension/index.d.ts +16 -6
- package/dist/graph-extension/index.js +7 -7
- package/dist/graph-merge/index.cjs +2459 -654
- package/dist/graph-merge/index.cjs.map +1 -1
- package/dist/graph-merge/index.d.cts +170 -33
- package/dist/graph-merge/index.d.ts +170 -33
- package/dist/graph-merge/index.js +2269 -467
- package/dist/graph-merge/index.js.map +1 -1
- package/dist/{index-C3y_98iN.d.cts → index-BSHvKfok.d.ts} +221 -10
- package/dist/{index-BBxZCUdu.d.ts → index-DxaYCv8Y.d.cts} +221 -10
- package/dist/index.cjs +330 -268
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +590 -576
- package/dist/index.d.ts +590 -576
- package/dist/index.js +73 -49
- package/dist/index.js.map +1 -1
- package/dist/indexes/index.cjs +17 -17
- package/dist/indexes/index.d.cts +4 -4
- package/dist/indexes/index.d.ts +4 -4
- package/dist/indexes/index.js +10 -10
- package/dist/interchange/index.cjs +165 -51
- package/dist/interchange/index.cjs.map +1 -1
- package/dist/interchange/index.d.cts +261 -16
- package/dist/interchange/index.d.ts +261 -16
- package/dist/interchange/index.js +128 -25
- package/dist/interchange/index.js.map +1 -1
- package/dist/{manager-YoLEfcc1.d.ts → manager-CfZAimti.d.ts} +36 -5
- package/dist/{manager-KS7CGQQT.d.cts → manager-HGk6E_HW.d.cts} +36 -5
- package/dist/{materialize-indexes-Bhhyb1B3.d.ts → materialize-indexes-6A7dWGtb.d.cts} +10 -2
- package/dist/{materialize-indexes-OHRWypW6.d.cts → materialize-indexes-BMJP6Tms.d.ts} +10 -2
- package/dist/{postgres-DpkW3R5Y.d.cts → postgres-DFYWENdR.d.cts} +1961 -439
- package/dist/{postgres-DwqyIniy.d.ts → postgres-e7a9TdvR.d.ts} +1961 -439
- package/dist/profiler/index.cjs +15 -15
- package/dist/profiler/index.d.cts +9 -10
- package/dist/profiler/index.d.ts +9 -10
- package/dist/profiler/index.js +4 -4
- package/dist/provenance/index.cjs +46 -48
- package/dist/provenance/index.cjs.map +1 -1
- package/dist/provenance/index.d.cts +7 -7
- package/dist/provenance/index.d.ts +7 -7
- package/dist/provenance/index.js +12 -14
- package/dist/provenance/index.js.map +1 -1
- package/dist/schema/index.cjs +50 -48
- package/dist/schema/index.d.cts +9 -16
- package/dist/schema/index.d.ts +9 -16
- package/dist/schema/index.js +23 -21
- package/dist/{searchable-DLWEfC4a.d.ts → searchable-9OQoPuRs.d.ts} +1 -2
- package/dist/{searchable-CIZL8Hyw.d.cts → searchable-CIje5XYD.d.cts} +1 -2
- package/dist/{sqlite-DY0WODUK.d.cts → sqlite-DerU5tc7.d.ts} +2029 -347
- package/dist/{sqlite-L-VIRzqA.d.ts → sqlite-DitnISa9.d.cts} +2029 -347
- package/dist/{store-view-A85FFRnk.d.cts → store-B0h6x7wo.d.cts} +1289 -767
- package/dist/{store-view-66p92IPi.d.ts → store-ClQ-MZQS.d.ts} +1289 -767
- package/dist/{temporal-BNbjXqer.d.cts → temporal-Bn-Fi8FJ.d.cts} +1 -1
- package/dist/{temporal-Bob6Nfbp.d.ts → temporal-BtM4UALv.d.ts} +1 -1
- package/dist/{types-DeORZhxn.d.cts → types-CoIx8HX5.d.cts} +1 -1
- package/dist/{types-Ch9a0Dx6.d.ts → types-HkveCCx0.d.cts} +726 -5
- package/dist/{types-Ch9a0Dx6.d.cts → types-HkveCCx0.d.ts} +726 -5
- package/dist/{types-ClCzT-dT.d.ts → types-KFfk-8Ah.d.ts} +1 -1
- package/dist/{where-DPw52ksb.d.cts → where--fk7_0kv.d.cts} +1 -1
- package/dist/{where-kWUZPvEA.d.ts → where-ws5hf-Ov.d.ts} +1 -1
- package/package.json +3 -3
- package/dist/chunk-2L54C2C2.js +0 -144
- package/dist/chunk-2L54C2C2.js.map +0 -1
- package/dist/chunk-35S6P5ZU.js +0 -27
- package/dist/chunk-35S6P5ZU.js.map +0 -1
- package/dist/chunk-42PYUGLS.js.map +0 -1
- package/dist/chunk-4GUBTVPV.js.map +0 -1
- package/dist/chunk-4GUTQPVO.js.map +0 -1
- package/dist/chunk-4MB3AQAQ.js.map +0 -1
- package/dist/chunk-4MEWSUVM.cjs.map +0 -1
- package/dist/chunk-4QIKLIGG.js.map +0 -1
- package/dist/chunk-4SZ6XPTG.cjs +0 -12
- package/dist/chunk-55ITBQJI.js.map +0 -1
- package/dist/chunk-5EKPX6QU.js.map +0 -1
- package/dist/chunk-6RYPD3NJ.cjs +0 -1282
- package/dist/chunk-6RYPD3NJ.cjs.map +0 -1
- package/dist/chunk-764JHTLT.cjs +0 -15
- package/dist/chunk-764JHTLT.cjs.map +0 -1
- package/dist/chunk-ACSVZPK7.cjs.map +0 -1
- package/dist/chunk-B3F2D3SP.cjs +0 -12
- package/dist/chunk-BGYJW37L.js.map +0 -1
- package/dist/chunk-BNS75YNF.cjs.map +0 -1
- package/dist/chunk-C4F7VJ5D.cjs.map +0 -1
- package/dist/chunk-CBKG6HEP.js +0 -1263
- package/dist/chunk-CBKG6HEP.js.map +0 -1
- package/dist/chunk-CPEL3YIR.cjs.map +0 -1
- package/dist/chunk-D54WH24V.cjs.map +0 -1
- package/dist/chunk-D56XG4EI.cjs.map +0 -1
- package/dist/chunk-D7PG5D5K.js.map +0 -1
- package/dist/chunk-DI74SMXS.cjs +0 -29
- package/dist/chunk-DI74SMXS.cjs.map +0 -1
- package/dist/chunk-DK2S42XB.js +0 -77
- package/dist/chunk-DK2S42XB.js.map +0 -1
- package/dist/chunk-DRACN6XG.js +0 -27
- package/dist/chunk-DRACN6XG.js.map +0 -1
- package/dist/chunk-DXEEHSGN.js.map +0 -1
- package/dist/chunk-EKFUG4G7.cjs.map +0 -1
- package/dist/chunk-EQ7JKLZO.cjs +0 -157
- package/dist/chunk-EQ7JKLZO.cjs.map +0 -1
- package/dist/chunk-FJMPR3OH.cjs.map +0 -1
- package/dist/chunk-FLEQ2HBK.js.map +0 -1
- package/dist/chunk-FQ7ZPOTZ.js.map +0 -1
- package/dist/chunk-G6Q5UM7U.js.map +0 -1
- package/dist/chunk-GYA4JRP5.js.map +0 -1
- package/dist/chunk-H7VE3FL4.cjs.map +0 -1
- package/dist/chunk-ID4WXTKL.js.map +0 -1
- package/dist/chunk-ISLPNELU.js.map +0 -1
- package/dist/chunk-ITE4IXAK.js +0 -25
- package/dist/chunk-ITE4IXAK.js.map +0 -1
- package/dist/chunk-IX64T5OL.cjs.map +0 -1
- package/dist/chunk-J2ICGNHO.cjs.map +0 -1
- package/dist/chunk-J7LXTUTP.cjs.map +0 -1
- package/dist/chunk-JQXSZHF2.cjs.map +0 -1
- package/dist/chunk-JXUTCSXX.cjs.map +0 -1
- package/dist/chunk-KCO5EFJU.js +0 -79
- package/dist/chunk-KCO5EFJU.js.map +0 -1
- package/dist/chunk-KKYELPZ2.cjs +0 -83
- package/dist/chunk-KKYELPZ2.cjs.map +0 -1
- package/dist/chunk-KMXWZLQX.cjs.map +0 -1
- package/dist/chunk-MIJKEVV7.js.map +0 -1
- package/dist/chunk-NAAMUYMS.cjs.map +0 -1
- package/dist/chunk-P7GTYOLB.cjs.map +0 -1
- package/dist/chunk-PVUI6KGR.js.map +0 -1
- package/dist/chunk-Q6EDCUXV.js.map +0 -1
- package/dist/chunk-QB6VMOJ2.cjs.map +0 -1
- package/dist/chunk-QC4MCOFV.cjs +0 -83
- package/dist/chunk-QC4MCOFV.cjs.map +0 -1
- package/dist/chunk-QMQLUA66.js +0 -12
- package/dist/chunk-QMQLUA66.js.map +0 -1
- package/dist/chunk-QRNYDV5Z.js.map +0 -1
- package/dist/chunk-RFRM3Q5K.js.map +0 -1
- package/dist/chunk-RUQS6M7G.js.map +0 -1
- package/dist/chunk-S4KQ5LV4.js.map +0 -1
- package/dist/chunk-SJDMVITW.cjs.map +0 -1
- package/dist/chunk-SNXVDZAJ.js.map +0 -1
- package/dist/chunk-SVJ5GEXW.cjs.map +0 -1
- package/dist/chunk-TDXIBCGY.cjs.map +0 -1
- package/dist/chunk-TKORQCG4.js.map +0 -1
- package/dist/chunk-TKP5T34P.js.map +0 -1
- package/dist/chunk-TRF4EBJT.cjs +0 -30
- package/dist/chunk-TRF4EBJT.cjs.map +0 -1
- package/dist/chunk-UCQ3BFSY.cjs.map +0 -1
- package/dist/chunk-UR7W5YQK.js.map +0 -1
- package/dist/chunk-V34A6R5V.js +0 -134
- package/dist/chunk-V34A6R5V.js.map +0 -1
- package/dist/chunk-WDAVPX46.js +0 -81
- package/dist/chunk-WDAVPX46.js.map +0 -1
- package/dist/chunk-WDBXJOU5.cjs.map +0 -1
- package/dist/chunk-YDWLUT5V.cjs.map +0 -1
- package/dist/chunk-YOALGKRE.cjs.map +0 -1
- package/dist/chunk-Z3WO6MND.cjs.map +0 -1
- package/dist/chunk-ZDH3DX3C.cjs +0 -30
- package/dist/chunk-ZDH3DX3C.cjs.map +0 -1
- package/dist/chunk-ZI6VQSZA.cjs.map +0 -1
- package/dist/chunk-ZTAJL4DT.cjs +0 -85
- package/dist/chunk-ZTAJL4DT.cjs.map +0 -1
- package/dist/define-graph-BGrJahvp.d.ts +0 -173
- package/dist/define-graph-alREY2wj.d.cts +0 -173
|
@@ -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,EAAA,MAAM,WAAA,GAAc,eAAe,EAAE,CAAA;AAIrC,EAAA,OACE,WAAA,KAAgB,qBAChB,WAAA,KAAgB,4BAAA;AAEpB;AAEA,SAAS,6BACP,KAAA,EACqC;AACrC,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,MAAM,OAAO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,gBAAA,IACR,4BAAA,CAA6B,QAAQ,EAAA,EAAI;AAAA,IACvC,cAAc,OAAA,CAAQ;AAAA,GACvB,CAAA;AAQH,EAAA,OAAO,4BAAA,CAA6B;AAAA,IAClC,cAAc,OAAA,CAAQ,YAAA;AAAA,IACtB,IAAI,OAAA,CAAQ,EAAA;AAAA,IACZ,gBAAA,EAAkB,kBAAA;AAAA,IAClB,mBAAmB,OAAA,CAAQ,iBAAA;AAAA,IAC3B,YAAY,OAAA,CAAQ,UAAA;AAAA,IACpB,kBAAkB,OAAA,CAAQ,gBAAA;AAAA,IAC1B,gBAAgB,OAAA,CAAQ,cAAA;AAAA,IACxB,0BAA0B,OAAA,CAAQ,wBAAA;AAAA,IAClC,iBAAA,EAAmB;AAAA,GACpB,CAAA;AACH","file":"chunk-4GUTQPVO.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\nfunction resolveSqliteClient(\n db: AnySqliteDatabase,\n): SqliteClientWithPrepare | undefined {\n const sqliteClient = (db as SqliteClientCarrier).$client;\n if (typeof sqliteClient !== \"object\" || sqliteClient === null) return;\n const candidate = sqliteClient as Record<string, unknown>;\n if (typeof candidate[\"prepare\"] !== \"function\") 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 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 ContributionRepairResult,\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 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 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 {\n buildContributionInsertValues,\n buildContributionOnConflictSet,\n type ContributionMaterializer,\n createContributionMaterializer,\n gateFulltext,\n gateFulltextMethods,\n mapContributionMaterializationRow,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS,\n} from \"./contribution-materializations\";\nimport { generateSqliteCreateTableSQL, generateSqliteDDL } 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 { type SqliteTables, tables as defaultTables } 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 * 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 // 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 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 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 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\nexport function createSqliteBackend(\n db: AnySqliteDatabase,\n options: SqliteBackendOptions = {},\n): AdapterBackend<AnySqliteDatabase> {\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 capabilities = 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\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 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 relations are ANALYZEd separately under a missing-table\n // guard: a schema created before recorded-time history landed\n // (bring-your-own-connection, no DDL re-run) has no recorded_* tables.\n const coreAnalyzeTables = [\n tableNames.nodes,\n tableNames.edges,\n tableNames.uniques,\n tableNames.fulltext,\n ];\n const recordedAnalyzeTables = [\n tableNames.recordedNodes,\n tableNames.recordedEdges,\n tableNames.recordedClock,\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 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 });\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 * 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 runFrameStatement(sql`ROLLBACK`);\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 // 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 // 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 relations may be absent on a schema created before\n // recorded-time history landed (bring-your-own-connection, no DDL\n // re-run); ANALYZE on a missing table errors, so skip those.\n for (const tableName of recordedAnalyzeTables) {\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 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 runFrameStatement(sql`ROLLBACK`);\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 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/errors/index.ts"],"names":[],"mappings":";AA0DA,SAAS,YAAY,KAAA,EAAwB;AAC3C,EAAA,IAAI,iBAAiB,KAAA,EAAO;AAC1B,IAAA,OAAO,KAAA,CAAM,SAAS,KAAA,CAAM,OAAA;AAAA,EAC9B;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,IACE,OAAO,UAAU,QAAA,IACjB,OAAO,UAAU,SAAA,IACjB,OAAO,UAAU,QAAA,EACjB;AACA,IAAA,OAAO,OAAO,KAAK,CAAA;AAAA,EACrB;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,MAAM,WAAA,IAAe,QAAA;AAAA,EAC9B;AACA,EAAA,IAAI,UAAU,MAAA,EAAW;AACvB,IAAA,OAAO,eAAA;AAAA,EACT;AAEA,EAAA,I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,CAAiB,KAAK,CAAA,IAAK,KAAA,CAAM,QAAA,KAAa,YAAA;AACvD;AAKO,SAAS,mBAAmB,KAAA,EAAoC;AACrE,EAAA,OAAO,gBAAA,CAAiB,KAAK,CAAA,GAAI,KAAA,CAAM,UAAA,GAAa,MAAA;AACtD","file":"chunk-4MB3AQAQ.js","sourcesContent":["/**\n * TypeGraph Error Hierarchy\n *\n * All errors extend TypeGraphError with:\n * - `code`: Machine-readable error code for programmatic handling\n * - `category`: Classification for error handling strategies\n * - `suggestion`: Optional recovery guidance for users\n * - `details`: Structured context about the error\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({ name: \"\" });\n * } catch (error) {\n * if (isTypeGraphError(error)) {\n * console.error(error.toUserMessage());\n * if (isUserRecoverable(error)) {\n * // Show to user for correction\n * }\n * }\n * }\n * ```\n */\n\nimport type { KindEntity } from \"../core/types\";\nimport type { SchemaDiff } from \"../schema/migration\";\n// Type-only import: `materialize-indexes.ts` value-imports\n// `ConfigurationError` from this file, but type-only imports are erased\n// at runtime so this back-edge does not create a value cycle.\nimport type { MaterializeIndexesResult } from \"../store/materialize-indexes\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Error category for programmatic handling.\n *\n * - `user`: Caused by invalid input or incorrect usage. Recoverable by fixing input.\n * - `constraint`: Business rule or schema constraint violation. Recoverable by changing data.\n * - `system`: Internal error or infrastructure issue. May require investigation or retry.\n */\nexport type ErrorCategory = \"user\" | \"constraint\" | \"system\";\n\n/**\n * Options for TypeGraphError constructor.\n */\nexport type TypeGraphErrorOptions = Readonly<{\n /** Structured context about the error */\n details?: Record<string, unknown>;\n /** Error category for handling strategies */\n category: ErrorCategory;\n /** Recovery guidance for users */\n suggestion?: string;\n /** Underlying cause of the error */\n cause?: unknown;\n}>;\n\nfunction formatCause(cause: unknown): string {\n if (cause instanceof Error) {\n return cause.stack ?? cause.message;\n }\n if (typeof cause === \"string\") {\n return cause;\n }\n if (\n typeof cause === \"number\" ||\n typeof cause === \"boolean\" ||\n typeof cause === \"bigint\"\n ) {\n return String(cause);\n }\n if (typeof cause === \"symbol\") {\n return cause.description ?? \"Symbol\";\n }\n if (cause === undefined) {\n return \"Unknown cause\";\n }\n\n try {\n return JSON.stringify(cause);\n } catch (error) {\n return `Unserializable cause: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`;\n }\n}\n\n// ============================================================\n// Base Error\n// ============================================================\n\n/**\n * Base error class for all TypeGraph errors.\n *\n * Provides structured error information for both programmatic handling\n * and user-friendly messages.\n */\nexport class TypeGraphError extends Error {\n /** Machine-readable error code (e.g., \"VALIDATION_ERROR\") */\n readonly code: string;\n\n /** Error category for handling strategies */\n readonly category: ErrorCategory;\n\n /** Structured context about the error */\n readonly details: Readonly<Record<string, unknown>>;\n\n /** Recovery guidance for users */\n readonly suggestion?: string;\n\n constructor(message: string, code: string, options: TypeGraphErrorOptions) {\n super(message, options.cause ? { cause: options.cause } : undefined);\n this.name = \"TypeGraphError\";\n this.code = code;\n this.category = options.category;\n this.details = Object.freeze(options.details ?? {});\n if (options.suggestion !== undefined) {\n this.suggestion = options.suggestion;\n }\n }\n\n /**\n * Returns a user-friendly error message with suggestion if available.\n */\n toUserMessage(): string {\n if (this.suggestion) {\n return `${this.message}\\n\\nSuggestion: ${this.suggestion}`;\n }\n return this.message;\n }\n\n /**\n * Returns a detailed string representation for logging.\n */\n toLogString(): string {\n const lines = [\n `[${this.code}] ${this.message}`,\n ` Category: ${this.category}`,\n ];\n\n if (this.suggestion) {\n lines.push(` Suggestion: ${this.suggestion}`);\n }\n\n const detailKeys = Object.keys(this.details);\n if (detailKeys.length > 0) {\n lines.push(` Details: ${JSON.stringify(this.details)}`);\n }\n\n if (this.cause) {\n lines.push(` Cause: ${formatCause(this.cause)}`);\n }\n\n return lines.join(\"\\n\");\n }\n}\n\n// ============================================================\n// Validation Errors (category: \"user\")\n// ============================================================\n\n/**\n * Validation issue from Zod or custom validation.\n */\nexport type ValidationIssue = Readonly<{\n /** Path to the invalid field (e.g., \"address.city\") */\n path: string;\n /** Human-readable error message */\n message: string;\n /** Zod error code if from Zod validation */\n code?: string;\n}>;\n\n/**\n * Details for ValidationError.\n */\nexport type ValidationErrorDetails = Readonly<{\n /** Type of entity being validated */\n entityType?: KindEntity;\n /** Kind/type name of the entity */\n kind?: string;\n /** Operation being performed */\n operation?: \"create\" | \"update\";\n /** Entity ID if updating */\n id?: string;\n /** Individual validation issues */\n issues: readonly ValidationIssue[];\n}>;\n\n/**\n * Thrown when schema validation fails during node or edge operations.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({ email: \"invalid\" });\n * } catch (error) {\n * if (error instanceof ValidationError) {\n * console.log(error.details.issues);\n * // [{ path: \"email\", message: \"Invalid email\" }]\n * }\n * }\n * ```\n */\nexport class ValidationError extends TypeGraphError {\n declare readonly details: ValidationErrorDetails;\n\n constructor(\n message: string,\n details: ValidationErrorDetails,\n options?: { cause?: unknown; suggestion?: string },\n ) {\n const fieldList =\n details.issues.length > 0 ?\n details.issues.map((index) => index.path || \"(root)\").join(\", \")\n : \"unknown\";\n\n super(message, \"VALIDATION_ERROR\", {\n details,\n category: \"user\",\n suggestion:\n options?.suggestion ??\n `Check the following fields: ${fieldList}. See error.details.issues for specific validation failures.`,\n cause: options?.cause,\n });\n this.name = \"ValidationError\";\n }\n}\n\n// ============================================================\n// Not Found Errors (category: \"user\")\n// ============================================================\n\n/**\n * Details for NodeNotFoundError.\n */\nexport type NodeNotFoundErrorDetails = Readonly<{\n kind: string;\n id: string;\n}>;\n\n/**\n * Thrown when a node is not found.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.get(\"nonexistent-id\");\n * } catch (error) {\n * if (error instanceof NodeNotFoundError) {\n * console.log(error.details.kind, error.details.id);\n * }\n * }\n * ```\n */\nexport class NodeNotFoundError extends TypeGraphError {\n declare readonly details: NodeNotFoundErrorDetails;\n\n constructor(kind: string, id: string, options?: { cause?: unknown }) {\n super(`Node not found: ${kind}/${id}`, \"NODE_NOT_FOUND\", {\n details: { kind, id },\n category: \"user\",\n suggestion: `Verify the node ID \"${id}\" exists and has not been deleted.`,\n cause: options?.cause,\n });\n this.name = \"NodeNotFoundError\";\n }\n}\n\n/**\n * Details for EdgeNotFoundError.\n */\nexport type EdgeNotFoundErrorDetails = Readonly<{\n kind: string;\n id: string;\n}>;\n\n/**\n * Thrown when an edge is not found.\n */\nexport class EdgeNotFoundError extends TypeGraphError {\n declare readonly details: EdgeNotFoundErrorDetails;\n\n constructor(kind: string, id: string, options?: { cause?: unknown }) {\n super(`Edge not found: ${kind}/${id}`, \"EDGE_NOT_FOUND\", {\n details: { kind, id },\n category: \"user\",\n suggestion: `Verify the edge ID \"${id}\" exists and has not been deleted.`,\n cause: options?.cause,\n });\n this.name = \"EdgeNotFoundError\";\n }\n}\n\n/**\n * Details for KindNotFoundError.\n */\nexport type KindNotFoundErrorDetails = Readonly<{\n kindName: string;\n entity: KindEntity;\n graphId?: string;\n}>;\n\n/**\n * Thrown when an operation references a kind that isn't registered on\n * the graph — `getNodeCollectionOrThrow` against an unknown kind, a\n * `materializeIndexes({ kinds })` filter naming a missing kind, an\n * extension referencing an unresolved endpoint, search facade typos,\n * etc. Carries the offending `kindName` and `entity` plus the host\n * `graphId` so logs are unambiguous when multiple stores share a\n * process.\n */\nexport class KindNotFoundError extends TypeGraphError {\n declare readonly details: KindNotFoundErrorDetails;\n readonly kindName: string;\n readonly entity: KindEntity;\n\n constructor(\n kindName: string,\n entity: KindEntity,\n options?: Readonly<{\n graphId?: string;\n suggestion?: string;\n cause?: unknown;\n }>,\n ) {\n const where =\n options?.graphId === undefined ? \"\" : ` on graph \"${options.graphId}\"`;\n super(\n `${entity === \"node\" ? \"Node\" : \"Edge\"} kind \"${kindName}\" is not registered${where}.`,\n \"KIND_NOT_FOUND\",\n {\n details: {\n kindName,\n entity,\n ...(options?.graphId === undefined ?\n {}\n : { graphId: options.graphId }),\n },\n category: \"user\",\n suggestion:\n options?.suggestion ??\n \"Compile-time kinds come from defineGraph; extension kinds appear after store.evolve() returns. Check store.introspect() for the registered set.\",\n cause: options?.cause,\n },\n );\n this.name = \"KindNotFoundError\";\n this.kindName = kindName;\n this.entity = entity;\n }\n}\n\n/**\n * Details for NodeConstraintNotFoundError.\n */\nexport type NodeConstraintNotFoundErrorDetails = Readonly<{\n constraintName: string;\n kind: string;\n}>;\n\n/**\n * Thrown when a uniqueness constraint name is not found on a node kind.\n */\nexport class NodeConstraintNotFoundError extends TypeGraphError {\n declare readonly details: NodeConstraintNotFoundErrorDetails;\n\n constructor(\n constraintName: string,\n kind: string,\n options?: { cause?: unknown },\n ) {\n super(\n `Constraint not found: \"${constraintName}\" on node kind \"${kind}\"`,\n \"CONSTRAINT_NOT_FOUND\",\n {\n details: { constraintName, kind },\n category: \"user\",\n suggestion: `Verify the constraint name \"${constraintName}\" is defined in the unique constraints for \"${kind}\".`,\n cause: options?.cause,\n },\n );\n this.name = \"NodeConstraintNotFoundError\";\n }\n}\n\n/**\n * Details for NodeIndexNotFoundError.\n */\nexport type NodeIndexNotFoundErrorDetails = Readonly<{\n indexName: string;\n kind: string;\n}>;\n\n/**\n * Thrown when a declared node index name is not found on a node kind.\n */\nexport class NodeIndexNotFoundError extends TypeGraphError {\n declare readonly details: NodeIndexNotFoundErrorDetails;\n\n constructor(indexName: string, kind: string, options?: { cause?: unknown }) {\n super(\n `Index not found: \"${indexName}\" on node kind \"${kind}\"`,\n \"INDEX_NOT_FOUND\",\n {\n details: { indexName, kind },\n category: \"user\",\n suggestion: `Verify the index name \"${indexName}\" is declared via defineNodeIndex for \"${kind}\" and passed to defineGraph({ indexes }).`,\n cause: options?.cause,\n },\n );\n this.name = \"NodeIndexNotFoundError\";\n }\n}\n\n// ============================================================\n// Constraint Errors (category: \"constraint\")\n// ============================================================\n\n/**\n * Details for EndpointNotFoundError.\n */\nexport type EndpointNotFoundErrorDetails = Readonly<{\n edgeKind: string;\n endpoint: \"from\" | \"to\";\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * Thrown when edge endpoint node does not exist or is deleted.\n */\nexport class EndpointNotFoundError extends TypeGraphError {\n declare readonly details: EndpointNotFoundErrorDetails;\n\n constructor(\n details: EndpointNotFoundErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Endpoint node not found for edge \"${details.edgeKind}\": ${details.nodeKind}/${details.nodeId} (${details.endpoint})`,\n \"ENDPOINT_NOT_FOUND\",\n {\n details,\n category: \"constraint\",\n suggestion: `Ensure the ${details.endpoint} node exists before creating the edge.`,\n cause: options?.cause,\n },\n );\n this.name = \"EndpointNotFoundError\";\n }\n}\n\n/**\n * Details for EndpointError.\n */\nexport type EndpointErrorDetails = Readonly<{\n edgeKind: string;\n endpoint: \"from\" | \"to\";\n actualKind: string;\n expectedKinds: readonly string[];\n}>;\n\n/**\n * Thrown when edge endpoint has wrong node type.\n */\nexport class EndpointError extends TypeGraphError {\n declare readonly details: EndpointErrorDetails;\n\n constructor(details: EndpointErrorDetails, options?: { cause?: unknown }) {\n const expected = details.expectedKinds.join(\" | \");\n super(\n `Invalid ${details.endpoint} endpoint for edge \"${details.edgeKind}\": got \"${details.actualKind}\", expected ${expected}`,\n \"ENDPOINT_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion: `Use a node of type ${expected} as the ${details.endpoint} endpoint.`,\n cause: options?.cause,\n },\n );\n this.name = \"EndpointError\";\n }\n}\n\n/**\n * Details for UniquenessError.\n */\nexport type UniquenessErrorDetails = Readonly<{\n constraintName: string;\n kind: string;\n existingId: string;\n newId: string;\n fields: readonly string[];\n}>;\n\n/**\n * Thrown when uniqueness constraint is violated.\n */\nexport class UniquenessError extends TypeGraphError {\n declare readonly details: UniquenessErrorDetails;\n\n constructor(details: UniquenessErrorDetails, options?: { cause?: unknown }) {\n const fieldList = details.fields.join(\", \");\n super(\n `Uniqueness violation on \"${details.kind}\": constraint \"${details.constraintName}\" (fields: ${fieldList}) conflicts with existing node ${details.existingId}`,\n \"UNIQUENESS_VIOLATION\",\n {\n details,\n category: \"constraint\",\n suggestion: `Change the values for fields [${fieldList}] to be unique, or update the existing node ${details.existingId} instead.`,\n cause: options?.cause,\n },\n );\n this.name = \"UniquenessError\";\n }\n}\n\n/**\n * Details for CardinalityError.\n */\nexport type CardinalityErrorDetails = Readonly<{\n edgeKind: string;\n fromKind: string;\n fromId: string;\n cardinality: string;\n existingCount: number;\n}>;\n\n/**\n * Thrown when cardinality constraint is violated.\n */\nexport class CardinalityError extends TypeGraphError {\n declare readonly details: CardinalityErrorDetails;\n\n constructor(details: CardinalityErrorDetails, options?: { cause?: unknown }) {\n super(\n `Cardinality violation: \"${details.edgeKind}\" from ${details.fromKind}/${details.fromId} allows \"${details.cardinality}\" but ${details.existingCount} edge(s) already exist`,\n \"CARDINALITY_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion:\n details.cardinality === \"one\" || details.cardinality === \"unique\" ?\n `Delete the existing edge before creating a new one, or use cardinality \"many\".`\n : `Check if the cardinality constraint \"${details.cardinality}\" is correct for your use case.`,\n cause: options?.cause,\n },\n );\n this.name = \"CardinalityError\";\n }\n}\n\n/**\n * Details for DisjointError.\n */\nexport type DisjointErrorDetails = Readonly<{\n nodeId: string;\n attemptedKind: string;\n conflictingKind: string;\n}>;\n\n/**\n * Thrown when disjointness constraint is violated.\n *\n * Disjoint types cannot share the same ID - a node cannot be both\n * a Person and an Organization if they are declared disjoint.\n */\nexport class DisjointError extends TypeGraphError {\n declare readonly details: DisjointErrorDetails;\n\n constructor(details: DisjointErrorDetails, options?: { cause?: unknown }) {\n super(\n `Disjoint constraint violation: cannot create ${details.attemptedKind} with ID \"${details.nodeId}\" - conflicts with existing ${details.conflictingKind}`,\n \"DISJOINT_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion: `Use a different ID for the new ${details.attemptedKind} node, or delete the existing ${details.conflictingKind}/${details.nodeId} first.`,\n cause: options?.cause,\n },\n );\n this.name = \"DisjointError\";\n }\n}\n\n/**\n * Details for RestrictedDeleteError.\n */\nexport type RestrictedDeleteErrorDetails = Readonly<{\n nodeKind: string;\n nodeId: string;\n edgeCount: number;\n edgeKinds: readonly string[];\n}>;\n\n/**\n * Thrown when deletion is blocked due to existing edges (restrict behavior).\n */\nexport class RestrictedDeleteError extends TypeGraphError {\n declare readonly details: RestrictedDeleteErrorDetails;\n\n constructor(\n details: RestrictedDeleteErrorDetails,\n options?: { cause?: unknown },\n ) {\n const edgeList = details.edgeKinds.join(\", \");\n super(\n `Cannot delete ${details.nodeKind}/${details.nodeId}: ${details.edgeCount} connected edge(s) exist (${edgeList})`,\n \"RESTRICTED_DELETE\",\n {\n details,\n category: \"constraint\",\n suggestion: `Delete the connected edges first, or change onDelete behavior to \"cascade\" (auto-delete edges) or \"disconnect\" (soft-delete edges).`,\n cause: options?.cause,\n },\n );\n this.name = \"RestrictedDeleteError\";\n }\n}\n\n// ============================================================\n// Concurrency Errors (category: \"system\")\n// ============================================================\n\n/**\n * Details for VersionConflictError.\n */\nexport type VersionConflictErrorDetails = Readonly<{\n kind: string;\n id: string;\n expectedVersion: number;\n actualVersion: number;\n}>;\n\n/**\n * Thrown when optimistic locking detects a concurrent modification.\n *\n * This occurs when two operations try to update the same entity simultaneously.\n * The operation with the stale version fails.\n */\nexport class VersionConflictError extends TypeGraphError {\n declare readonly details: VersionConflictErrorDetails;\n\n constructor(\n details: VersionConflictErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Version conflict on ${details.kind}/${details.id}: expected version ${details.expectedVersion}, found ${details.actualVersion}`,\n \"VERSION_CONFLICT\",\n {\n details,\n category: \"system\",\n suggestion: `Fetch the latest version of the entity and retry the operation. This error indicates concurrent modification.`,\n cause: options?.cause,\n },\n );\n this.name = \"VersionConflictError\";\n }\n}\n\n// ============================================================\n// Schema Errors (category: \"system\")\n// ============================================================\n\n/**\n * Details for SchemaMismatchError.\n */\nexport type SchemaMismatchErrorDetails = Readonly<{\n graphId: string;\n expectedHash: string;\n actualHash: string;\n}>;\n\n/**\n * Thrown when the schema in code doesn't match the schema in the database.\n */\nexport class SchemaMismatchError extends TypeGraphError {\n declare readonly details: SchemaMismatchErrorDetails;\n\n constructor(\n details: SchemaMismatchErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema mismatch for graph \"${details.graphId}\": code schema differs from database schema`,\n \"SCHEMA_MISMATCH\",\n {\n details,\n category: \"system\",\n suggestion: `Run schema migration to update the database, or use createStoreWithSchema() for automatic migration.`,\n cause: options?.cause,\n },\n );\n this.name = \"SchemaMismatchError\";\n }\n}\n\n/**\n * Details for MigrationError.\n */\n/**\n * Why a migration operation failed. A stable discriminant so callers can\n * branch on the outcome instead of matching the message text, which is free\n * to be reworded in any release.\n */\nexport const MIGRATION_FAILURE_REASONS = [\n /**\n * The persisted schema is behind the code graph. Raised on the\n * least-privilege runtime path, which cannot run DDL — a privileged\n * migrator must advance the schema first. Inspect `details.diff`\n * (`hasBreakingChanges`) to tell an additive change from an incompatible\n * one.\n */\n \"schema-behind\",\n /** Breaking changes were detected while `throwOnBreaking` was set. */\n \"breaking-change\",\n /** No active schema version exists for the graph. */\n \"no-active-version\",\n /** The requested schema version does not exist for the graph. */\n \"version-not-found\",\n /**\n * The schema about to be committed drops node or edge kinds that still\n * hold rows. Committing would make those rows unreachable, and the next\n * `materializeRemovals()` — which re-derives removals from schema history —\n * would delete them. Inspect `details.droppedKinds` for the names. Use\n * `Store.removeKinds()`, the removal path that queues cleanup explicitly,\n * or pass `discardDroppedKindRows` to `migrateSchema` if losing the rows is\n * the intent.\n */\n \"kind-removal\",\n] as const;\n\nexport type MigrationFailureReason = (typeof MIGRATION_FAILURE_REASONS)[number];\n\n/**\n * Structured context for a {@link MigrationError}, discriminated on `reason`.\n *\n * Modelled as a union rather than one shape with optional fields so the\n * payload a reason promises is the payload it must carry: narrowing on\n * `reason === \"kind-removal\"` gives you a non-optional `droppedKinds`, and the\n * constructor cannot be handed a `kind-removal` without one.\n *\n * The common fields are repeated per member rather than factored into a shared\n * base alias, which would be a hoisted-unexported symbol on the public\n * entrypoint.\n */\nexport type MigrationErrorDetails =\n | Readonly<{\n graphId: string;\n fromVersion: number;\n toVersion: number;\n /** Stable discriminant — branch on this, not the message. */\n reason: \"schema-behind\" | \"breaking-change\";\n /**\n * The structured diff behind the failure. Carries per-change `severity`\n * alongside `hasChanges` / `hasBreakingChanges`, so a caller can decide\n * \"additive → proceed, incompatible → ask the user\" without re-querying.\n */\n diff?: SchemaDiff;\n }>\n | Readonly<{\n graphId: string;\n fromVersion: number;\n toVersion: number;\n reason: \"no-active-version\" | \"version-not-found\";\n }>\n | Readonly<{\n graphId: string;\n fromVersion: number;\n toVersion: number;\n reason: \"kind-removal\";\n /**\n * The dropped kinds that still held rows, and so caused the refusal. A\n * kind the commit drops but that is already empty is permitted and does\n * NOT appear here. Both lists are sorted; at least one is non-empty.\n */\n droppedKinds: Readonly<{\n nodes: readonly string[];\n edges: readonly string[];\n }>;\n }>;\n\n/**\n * Thrown when schema migration fails.\n */\nexport class MigrationError extends TypeGraphError {\n declare readonly details: MigrationErrorDetails;\n\n constructor(\n message: string,\n details: MigrationErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(message, \"MIGRATION_ERROR\", {\n details,\n category: \"system\",\n suggestion: `Review the schema changes and ensure they are backwards compatible, or implement a data migration.`,\n cause: options?.cause,\n });\n this.name = \"MigrationError\";\n }\n}\n\n/**\n * Details for EagerMaterializationError.\n */\nexport type EagerMaterializationErrorDetails = Readonly<{\n graphId: string;\n failedIndexNames: readonly string[];\n}>;\n\n/**\n * Thrown by `Store.evolve(extension, { eager })` when the schema\n * commit succeeded but the follow-on `materializeIndexes()` produced\n * one or more failed entries.\n *\n * Recovery: the schema commit is NOT rolled back. The new `Store` is\n * fully constructed and (when `options.ref` was supplied) `ref.current`\n * already points to it — the caller can read the new store via the ref\n * and decide how to handle the failed indexes (retry, skip, alert).\n * The full `MaterializeIndexesResult` is attached as `.materialization`.\n *\n * @example\n * ```ts\n * const ref = { current: store };\n * try {\n * await store.evolve(extension, { ref, eager: {} });\n * } catch (error) {\n * if (error instanceof EagerMaterializationError) {\n * // schema is committed; ref.current is the new store\n * log.warn(\n * { failed: error.failedIndexNames },\n * \"indexes did not materialize; will retry\",\n * );\n * await ref.current.materializeIndexes();\n * } else {\n * throw error;\n * }\n * }\n * ```\n */\nexport class EagerMaterializationError extends TypeGraphError {\n declare readonly details: EagerMaterializationErrorDetails;\n\n /**\n * The full materialization result, including successful and failed\n * entries. Same shape as `Store.materializeIndexes()` returns.\n */\n readonly materialization: MaterializeIndexesResult;\n\n constructor(materialization: MaterializeIndexesResult, graphId: string) {\n const names = collectFailedIndexNames(materialization);\n super(\n `Eager materialization failed for ${names.length} index(es) on graph \"${graphId}\": ${names.join(\", \")}. The schema commit succeeded; the new Store is available via the ref handle (when supplied) and the failed indexes can be retried via store.materializeIndexes().`,\n \"EAGER_MATERIALIZATION_FAILED\",\n {\n details: { graphId, failedIndexNames: names },\n category: \"system\",\n suggestion: `Inspect error.materialization for per-index errors. Each failure preserves any prior successful materialization timestamp; the schema is committed regardless.`,\n },\n );\n this.name = \"EagerMaterializationError\";\n this.materialization = materialization;\n }\n\n /**\n * Names of just the indexes that failed — derived from\n * `materialization.results` so the two views can never disagree.\n */\n get failedIndexNames(): readonly string[] {\n return collectFailedIndexNames(this.materialization);\n }\n}\n\nfunction collectFailedIndexNames(\n materialization: MaterializeIndexesResult,\n): readonly string[] {\n const names: string[] = [];\n for (const entry of materialization.results) {\n if (entry.status === \"failed\") names.push(entry.indexName);\n }\n return names;\n}\n\n/**\n * Details for StaleVersionError. `actual` is `0` when no active version\n * exists yet (initial-commit race where another writer initialized first).\n */\nexport type StaleVersionErrorDetails = Readonly<{\n graphId: string;\n expected: number;\n actual: number;\n}>;\n\n/**\n * Thrown by `commitSchemaVersion` and `setActiveVersion` when the\n * caller's view of the active schema version is out of date — another\n * writer has already advanced it.\n *\n * Recovery: re-read the active version with `getActiveSchema(graphId)`,\n * recompute against the new baseline, and retry. This is a routine\n * concurrency signal, not a bug.\n */\nexport class StaleVersionError extends TypeGraphError {\n declare readonly details: StaleVersionErrorDetails;\n\n constructor(\n details: StaleVersionErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema version was advanced by another writer for graph \"${details.graphId}\": expected active version ${details.expected}, actual is ${details.actual}`,\n \"STALE_SCHEMA_VERSION\",\n {\n details,\n category: \"system\",\n suggestion: `Re-read the active schema version, recompute the new version against that baseline, and retry the commit.`,\n cause: options?.cause,\n },\n );\n this.name = \"StaleVersionError\";\n }\n}\n\n/**\n * Details for SchemaContentConflictError.\n */\nexport type SchemaContentConflictErrorDetails = Readonly<{\n graphId: string;\n version: number;\n existingHash: string;\n incomingHash: string;\n}>;\n\n/**\n * Thrown by `commitSchemaVersion` when a row already exists at the\n * target version with a *different* schema hash — i.e. two writers\n * committed materially different schemas at the same version number.\n *\n * Distinct from `StaleVersionError`: this is not a refetch-and-retry\n * situation, it's a content disagreement that needs operator\n * intervention. Typically caused by inconsistent application\n * deployments writing schemas that hash differently.\n */\nexport class SchemaContentConflictError extends TypeGraphError {\n declare readonly details: SchemaContentConflictErrorDetails;\n\n constructor(\n details: SchemaContentConflictErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema content conflict for graph \"${details.graphId}\" at version ${details.version}: existing hash ${details.existingHash} differs from incoming hash ${details.incomingHash}`,\n \"SCHEMA_CONTENT_CONFLICT\",\n {\n details,\n category: \"system\",\n suggestion: `Two writers committed different schemas at the same version. Reconcile the application deployments so they produce the same canonical schema, then retry.`,\n cause: options?.cause,\n },\n );\n this.name = \"SchemaContentConflictError\";\n }\n}\n\n// ============================================================\n// Configuration Errors (category: \"user\")\n// ============================================================\n\n/**\n * Thrown when graph configuration is invalid.\n *\n * This includes invalid schema definitions, ontology conflicts,\n * and other configuration issues detected at graph creation time.\n */\nexport class ConfigurationError extends TypeGraphError {\n constructor(\n message: string,\n details: Record<string, unknown> = {},\n options?: { cause?: unknown; suggestion?: string },\n ) {\n super(message, \"CONFIGURATION_ERROR\", {\n details,\n category: \"user\",\n suggestion:\n options?.suggestion ?? `Review your graph definition for errors.`,\n cause: options?.cause,\n });\n this.name = \"ConfigurationError\";\n }\n}\n\n/**\n * Thrown when an iterative graph algorithm exhausts its caller-visible round\n * budget before reaching its convergence predicate.\n */\nexport class GraphAlgorithmConvergenceError extends TypeGraphError {\n constructor(\n algorithm: string,\n maxIterations: number,\n options: Readonly<{ oscillating?: boolean }> = {},\n ) {\n const oscillating = options.oscillating === true;\n super(\n oscillating ?\n `${algorithm} entered a periodic label oscillation and can never converge.`\n : `${algorithm} did not converge within ${maxIterations} iterations.`,\n \"GRAPH_ALGORITHM_CONVERGENCE_ERROR\",\n {\n details: {\n algorithm,\n maxIterations,\n ...(oscillating ? { oscillating } : {}),\n },\n category: \"user\",\n suggestion:\n oscillating ?\n 'Pass onMaxIterations: \"return\" to accept the fixed-round labeling, or exclude the oscillating component from the selection.'\n : \"Increase maxIterations or reduce the selected graph before retrying.\",\n },\n );\n this.name = \"GraphAlgorithmConvergenceError\";\n }\n}\n\n/** Stable reasons a weighted traversal can reject an edge's weight value. */\nexport type InvalidEdgeWeightReason =\n \"missing\" | \"negative\" | \"non_numeric\" | \"out_of_range\";\n\n/** Details for InvalidEdgeWeightError. */\nexport type InvalidEdgeWeightErrorDetails = Readonly<{\n /** Id of the first offending edge, in binary-collation order. */\n edgeId: string;\n /** Kind of the offending edge. */\n edgeKind: string;\n /** The audited weight property. */\n property: string;\n /** Why the weight was rejected. */\n reason: InvalidEdgeWeightReason;\n /** The offending value, when one was present and renderable. */\n value?: string;\n}>;\n\nconst EDGE_WEIGHT_REASONS: Readonly<\n Record<\n InvalidEdgeWeightReason,\n Readonly<{ message: string; suggestion: string }>\n >\n> = {\n missing: {\n message: \"has no value for weight property\",\n suggestion:\n \"Set the property on every selected edge, or provide defaultWeight for edges without it.\",\n },\n negative: {\n message: \"has a negative value for weight property\",\n suggestion:\n \"Weighted traversal requires non-negative weights; repair the edge data before retrying.\",\n },\n non_numeric: {\n message: \"has a non-numeric value for weight property\",\n suggestion:\n \"Store the weight property as a JSON number on every selected edge before retrying.\",\n },\n out_of_range: {\n message: \"has a value outside the supported range for weight property\",\n suggestion:\n \"Keep weight magnitudes within the range weightedShortestPath documents (large enough to be a normal IEEE 754 double, small enough that path sums cannot overflow).\",\n },\n};\n\n/**\n * Thrown when a weighted graph algorithm finds an edge whose weight property\n * violates the weighted-traversal contract (missing without a default,\n * non-numeric, or negative). Raised before any traversal rounds run, so a\n * weighted call either observes a fully valid weight domain or fails fast.\n */\nexport class InvalidEdgeWeightError extends TypeGraphError {\n declare readonly details: InvalidEdgeWeightErrorDetails;\n\n constructor(details: InvalidEdgeWeightErrorDetails) {\n super(\n `Edge '${details.edgeId}' (kind '${details.edgeKind}') ${EDGE_WEIGHT_REASONS[details.reason].message} '${details.property}'${\n details.value === undefined ? \"\" : ` (value: ${details.value})`\n }.`,\n \"INVALID_EDGE_WEIGHT\",\n {\n details: { ...details },\n category: \"user\",\n suggestion: EDGE_WEIGHT_REASONS[details.reason].suggestion,\n },\n );\n this.name = \"InvalidEdgeWeightError\";\n }\n}\n\n/** Thrown when an operation requires a backend capability it does not expose. */\nexport class UnsupportedBackendCapabilityError extends TypeGraphError {\n constructor(\n operation: string,\n capability: string,\n details: Readonly<Record<string, unknown>> = {},\n suggestion?: string,\n ) {\n super(\n `${operation} requires backend capability '${capability}'.`,\n \"UNSUPPORTED_BACKEND_CAPABILITY\",\n {\n details: { operation, capability, ...details },\n category: \"user\",\n suggestion:\n suggestion ??\n \"Use a backend that advertises this capability before invoking the operation.\",\n },\n );\n this.name = \"UnsupportedBackendCapabilityError\";\n }\n}\n\n/** Stable reasons an intentionally trusted initial import can be rejected. */\nexport type TrustedImportErrorReason =\n | \"backend_unsupported\"\n | \"database_not_empty\"\n | \"fulltext_unsupported\"\n | \"history_unsupported\"\n | \"invalid_stream\"\n | \"revision_tracking_unsupported\"\n | \"uniqueness_unsupported\"\n | \"vector_unsupported\";\n\n/** Thrown when the trusted initial-import contract is unavailable or violated. */\nexport class TrustedImportError extends TypeGraphError {\n constructor(\n message: string,\n reason: TrustedImportErrorReason,\n details: Readonly<Record<string, unknown>> = {},\n options?: Readonly<{ cause?: unknown; suggestion?: string }>,\n ) {\n super(message, \"TRUSTED_IMPORT_ERROR\", {\n details: { ...details, reason },\n category: \"user\",\n suggestion:\n options?.suggestion ??\n \"Use the validating bulk or interchange import APIs unless every trusted-import precondition is satisfied.\",\n cause: options?.cause,\n });\n this.name = \"TrustedImportError\";\n }\n}\n\n/**\n * The stable `details.code` values raised by the recorded-capture guards on a\n * history- or revision-tracked store. These are the sanctioned branch points\n * for a portable caller that must pick a transaction strategy without\n * substring-matching {@link ConfigurationError} messages.\n *\n * - `RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION`: `store.withTransaction`\n * was called on a history-enabled store, which has no flush point before the\n * caller commits — use `store.withRecordedTransaction` instead.\n * - `RECORDED_CAPTURE_RAW_SQL_DISABLED`: a raw SQL escape (`tx.sql`,\n * `backend.executeStatement`/`executeDdl`) was reached on a history-enabled\n * store, where it would bypass recorded-time capture.\n * - `REVISION_TRACKING_RAW_SQL_DISABLED`: the same raw SQL escape on a\n * revision-tracked store, where it would bypass the revision anchor.\n *\n * @see isRecordedCaptureGuardError\n */\nexport const RECORDED_CAPTURE_GUARD_CODES = [\n \"RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION\",\n \"RECORDED_CAPTURE_RAW_SQL_DISABLED\",\n \"REVISION_TRACKING_RAW_SQL_DISABLED\",\n] as const;\n\n/** A stable, branchable code raised by a recorded-capture guard. */\nexport type RecordedCaptureGuardCode =\n (typeof RECORDED_CAPTURE_GUARD_CODES)[number];\n\n/**\n * A {@link ConfigurationError} narrowed to carry a {@link RecordedCaptureGuardCode}\n * in `details.code` — the shape {@link isRecordedCaptureGuardError} guarantees.\n * `C` narrows `details.code` to a single code when the guard was called with a\n * specific one; it defaults to the full union.\n */\nexport type RecordedCaptureGuardError<\n C extends RecordedCaptureGuardCode = RecordedCaptureGuardCode,\n> = ConfigurationError & Readonly<{ details: Readonly<{ code: C }> }>;\n\nfunction isRecordedCaptureGuardCode(\n value: unknown,\n): value is RecordedCaptureGuardCode {\n // Widen the readonly tuple so `includes` accepts an `unknown` needle.\n return (RECORDED_CAPTURE_GUARD_CODES as readonly unknown[]).includes(value);\n}\n\n/**\n * Type guard for the recorded-capture guard errors, so a portable caller can\n * branch on the invariant a store enforced instead of substring-matching the\n * message. Pass `code` to narrow to a single guard; omit it to match any.\n *\n * Distinguishes \"history capture forbids raw SQL here\" from \"this backend has\n * no transactions\" (the latter carries no guard code — see\n * `TransactionContext.sqlAvailability` for the capability discriminant).\n *\n * Passing `code` also narrows `details.code` to that literal on the guarded\n * branch, so a caller can read the payload without re-checking.\n *\n * @example\n * ```typescript\n * // `withTransaction` is a compile error on a history-enabled store, so widen\n * // to the base Store surface to reach the runtime guard this branches on.\n * const store: Store<typeof graph> = historyStore;\n * try {\n * store.withTransaction(externalTx);\n * } catch (error) {\n * if (\n * isRecordedCaptureGuardError(\n * error,\n * \"RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION\",\n * )\n * ) {\n * // error.details.code is now the literal, not the union.\n * await historyStore.withRecordedTransaction(externalTx, run);\n * } else {\n * throw error;\n * }\n * }\n * ```\n */\nexport function isRecordedCaptureGuardError<C extends RecordedCaptureGuardCode>(\n error: unknown,\n code: C,\n): error is RecordedCaptureGuardError<C>;\nexport function isRecordedCaptureGuardError(\n error: unknown,\n): error is RecordedCaptureGuardError;\nexport function isRecordedCaptureGuardError(\n error: unknown,\n code?: RecordedCaptureGuardCode,\n): error is RecordedCaptureGuardError {\n if (!(error instanceof ConfigurationError)) return false;\n const actual = error.details[\"code\"];\n if (!isRecordedCaptureGuardCode(actual)) return false;\n return code === undefined || actual === code;\n}\n\n/**\n * Why a store's strategy-owned storage is not usable on the current\n * connection. Drives the {@link StoreNotInitializedError} message and\n * is surfaced in `details.reason` for programmatic handling.\n *\n * - `missing`: no durable materialization marker exists — the database\n * was never initialized for this graph's runtime contributions.\n * - `stale`: a marker exists but its recorded signature no longer\n * matches the resolved contribution DDL (strategy swap or DDL drift).\n * The hot path refuses rather than silently re-materializing.\n * - `failed`: the most recent boot-time materialization attempt\n * recorded an error. Boot may retry; the hot path refuses.\n */\nexport type StoreNotInitializedReason = \"missing\" | \"stale\" | \"failed\";\n\nconst STORE_NOT_INITIALIZED_REASON_PHRASE: Readonly<\n Record<StoreNotInitializedReason, string>\n> = {\n missing: \"is not initialized\",\n stale: \"is stale (recorded materialization signature no longer matches)\",\n failed: \"failed its last initialization attempt\",\n};\n\n/**\n * Details for StoreNotInitializedError. `graphId`/`reason` are always\n * present; callers may merge additional context (e.g. `logicalName`) via\n * `options.details`.\n */\nexport type StoreNotInitializedErrorDetails = Readonly<{\n graphId: string;\n reason: StoreNotInitializedReason;\n}> &\n Readonly<Record<string, unknown>>;\n\n/**\n * Thrown when a fulltext- or vector-dependent operation runs against a\n * connection whose strategy-owned storage has not been durably materialized.\n *\n * `createStore()` is a synchronous, zero-I/O attach: it never creates\n * tables, repairs DDL, or writes materialization markers. The durable\n * marker is written exclusively by the async boot path\n * (`createStoreWithSchema`). When a fulltext or embedding read/write — or\n * an adopted/business transaction — observes no valid marker, it refuses\n * loudly here instead of lazily emitting DDL on the hot path.\n */\nexport class StoreNotInitializedError extends TypeGraphError {\n declare readonly details: StoreNotInitializedErrorDetails;\n\n // `graphId`/`reason` are positional and required: both are\n // load-bearing for the message and for programmatic handling via\n // `details.reason`. Caller `details` merge underneath — spread first\n // so `graphId`/`reason` win and can't be clobbered by an\n // accidentally-colliding extra key.\n constructor(\n graphId: string,\n reason: StoreNotInitializedReason,\n options?: {\n cause?: unknown;\n details?: Readonly<Record<string, unknown>> &\n Readonly<{ graphId?: never; reason?: never }>;\n },\n ) {\n super(\n `${storageLabelFromLogicalName(options?.details?.[\"logicalName\"])} for ` +\n `graph \"${graphId}\" ${STORE_NOT_INITIALIZED_REASON_PHRASE[reason]}. ` +\n storeNotInitializedAction(reason, options?.details?.[\"logicalName\"]),\n \"STORE_NOT_INITIALIZED\",\n {\n details: { ...options?.details, graphId, reason },\n category: \"user\",\n suggestion:\n isStaleVectorSlot(reason, options?.details?.[\"logicalName\"]) ?\n \"The field's declared shape (e.g. its dimension) changed after \" +\n \"its storage was provisioned. Run store.reembedVectorField(\" +\n \"kind, fieldPath) to recreate the storage at the new shape and \" +\n \"re-embed.\"\n : \"Call createStoreWithSchema(graph, backend) once at application \" +\n \"startup. createStore() attaches to an already-initialized \" +\n \"database and does not materialize storage itself.\",\n cause: options?.cause,\n },\n );\n this.name = \"StoreNotInitializedError\";\n }\n}\n\nconst VECTOR_LOGICAL_NAME_PREFIX = \"vector:\";\n\n/**\n * A stale VECTOR slot is its own failure mode: the storage exists but was\n * provisioned at a different shape (the declared dimension changed), and\n * the fix is `store.reembedVectorField`, not a re-run of\n * `createStoreWithSchema` (whose boot pass deliberately skips drifted\n * slots). Drives the action sentence and the suggestion.\n */\nfunction isStaleVectorSlot(\n reason: StoreNotInitializedReason,\n logicalName: unknown,\n): boolean {\n return (\n reason === \"stale\" &&\n typeof logicalName === \"string\" &&\n logicalName.startsWith(VECTOR_LOGICAL_NAME_PREFIX)\n );\n}\n\n/** The actionable trailing sentence of the error message, per failure mode. */\nfunction storeNotInitializedAction(\n reason: StoreNotInitializedReason,\n logicalName: unknown,\n): string {\n if (isStaleVectorSlot(reason, logicalName)) {\n return (\n `The declared shape changed after provisioning — run ` +\n `store.reembedVectorField(kind, fieldPath) to recreate the storage ` +\n `at the new shape.`\n );\n }\n return (\n `Run createStoreWithSchema(graph, backend) during application boot, ` +\n `outside request handlers and adopted transactions, before using createStore().`\n );\n}\n\n/**\n * Human label for the un-materialized storage, derived from the\n * contribution `logicalName`: fulltext keeps \"fulltext storage\"; a vector\n * slot (\"vector:<kind>.<field>\") reads as `vector storage\n * \"<kind>.<field>\"` so the message names the exact embedding\n * field. Falls back to a neutral phrase when no logical name is supplied.\n */\nfunction storageLabelFromLogicalName(logicalName: unknown): string {\n if (typeof logicalName !== \"string\") return \"runtime storage\";\n if (logicalName.startsWith(VECTOR_LOGICAL_NAME_PREFIX)) {\n return `vector storage \"${logicalName.slice(VECTOR_LOGICAL_NAME_PREFIX.length)}\"`;\n }\n if (logicalName === \"fulltext\") return \"fulltext storage\";\n return `\"${logicalName}\" storage`;\n}\n\n// ============================================================\n// Database Errors (category: \"system\")\n// ============================================================\n\n/**\n * Details for DatabaseOperationError.\n */\nexport type DatabaseOperationErrorDetails = Readonly<{\n operation: string;\n entity: string;\n}>;\n\n/**\n * Thrown when a database operation fails unexpectedly.\n *\n * This indicates a system-level failure in the database backend,\n * not a user-recoverable error.\n */\nexport class DatabaseOperationError extends TypeGraphError {\n declare readonly details: DatabaseOperationErrorDetails;\n\n constructor(\n message: string,\n details: DatabaseOperationErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(message, \"DATABASE_OPERATION_ERROR\", {\n details,\n category: \"system\",\n suggestion: `This is a system-level database error. Check the database connection and retry the operation. If the problem persists, investigate the underlying cause.`,\n cause: options?.cause,\n });\n this.name = \"DatabaseOperationError\";\n }\n}\n\n// ============================================================\n// Vector / Embedding Errors (category: \"user\")\n// ============================================================\n\n/**\n * Details for EmbeddingDimensionChangedError.\n */\nexport type EmbeddingDimensionChangedErrorDetails = Readonly<{\n kind: string;\n fieldPath: string;\n declaredDimensions?: number;\n storedDimensions?: number;\n}>;\n\n/**\n * Thrown when an embedding field's declared dimension no longer matches the\n * dimension of its materialized per-field storage — i.e. a field's\n * `embedding(N)` was changed to `embedding(M)`. The stored vectors are invalid\n * under the new dimension and cannot be converted, only recomputed, so this is\n * a deliberate app-driven migration: call\n * `store.reembedVectorField(kind, fieldPath, ...)` to recreate the storage at\n * the new dimension and re-embed existing rows.\n */\nexport class EmbeddingDimensionChangedError extends TypeGraphError {\n declare readonly details: EmbeddingDimensionChangedErrorDetails;\n\n constructor(\n message: string,\n details: EmbeddingDimensionChangedErrorDetails,\n options?: { cause?: unknown },\n ) {\n super(message, \"EMBEDDING_DIMENSION_CHANGED\", {\n details,\n category: \"user\",\n suggestion: `Run store.reembedVectorField(\"${details.kind}\", \"${details.fieldPath}\", { embed }) to recreate the field's storage at the new dimension and re-embed existing rows.`,\n cause: options?.cause,\n });\n this.name = \"EmbeddingDimensionChangedError\";\n }\n}\n\n// ============================================================\n// Query Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a query predicate cannot be compiled for the target database.\n */\nexport class UnsupportedPredicateError extends TypeGraphError {\n constructor(\n message: string,\n details: Readonly<Record<string, unknown>> = {},\n options?: { cause?: unknown; suggestion?: string },\n ) {\n super(message, \"UNSUPPORTED_PREDICATE\", {\n details,\n category: \"system\",\n suggestion:\n options?.suggestion ??\n `This predicate may not be supported by your database backend. Check the documentation for supported predicates.`,\n cause: options?.cause,\n });\n this.name = \"UnsupportedPredicateError\";\n }\n}\n\n// ============================================================\n// Compiler Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a compiler invariant is violated.\n *\n * This indicates a bug in the query compiler — the compiler reached\n * a state that should be unreachable. These errors are not user-recoverable.\n */\nexport class CompilerInvariantError extends TypeGraphError {\n constructor(\n message: string,\n details?: Readonly<Record<string, unknown>>,\n options?: { cause?: unknown },\n ) {\n super(message, \"COMPILER_INVARIANT_ERROR\", {\n details: details ?? {},\n category: \"system\",\n suggestion: `This is an internal compiler error. Please report it as a bug with the query that triggered it.`,\n cause: options?.cause,\n });\n this.name = \"CompilerInvariantError\";\n }\n}\n\n// ============================================================\n// Lifecycle Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when an operation is attempted on a backend that has been disposed.\n *\n * This typically occurs during runtime teardown — for example, when a\n * Cloudflare Workers test runner resets Durable Object storage while\n * the TypeGraph backend still has queued operations.\n */\nexport class BackendDisposedError extends TypeGraphError {\n constructor(options?: { cause?: unknown }) {\n super(\n \"Backend has been disposed — the underlying database connection is no longer available\",\n \"BACKEND_DISPOSED\",\n {\n category: \"system\",\n suggestion:\n \"Ensure all store operations complete before calling backend.close(). \" +\n \"In test environments, await store teardown before resetting the database.\",\n cause: options?.cause,\n },\n );\n this.name = \"BackendDisposedError\";\n }\n}\n\n/**\n * Thrown when a statement is issued on a transaction-scoped backend after\n * its transaction boundary has already returned.\n *\n * The usual source is a callback that lets work escape it. `Promise.all`\n * rejects on its first rejection while its siblings keep running, so\n *\n * ```typescript\n * await store.transaction(async (tx) => {\n * await Promise.all([tx.nodes.Doc.create(a), tx.nodes.Doc.create(b)]);\n * });\n * ```\n *\n * leaves `b`'s remaining statements in flight when `a` fails. Those\n * statements have nowhere safe to go: the driver is about to emit `ROLLBACK`\n * on the same pinned connection and then hand it back to the pool, where a\n * late arrival would execute inside somebody else's transaction. TypeGraph\n * refuses them here instead.\n *\n * The error is normally invisible — `Promise.all` has already rejected with\n * the original failure, and discards this one.\n */\nexport class TransactionClosedError extends TypeGraphError {\n constructor(options?: { cause?: unknown }) {\n super(\n \"Statement issued on a transaction-scoped backend after its transaction \" +\n \"boundary returned. The connection has been released; the statement was not run.\",\n \"TRANSACTION_CLOSED\",\n {\n category: \"user\",\n suggestion:\n \"Await every write started inside store.transaction(...) before the \" +\n \"callback returns. Prefer awaiting a Promise.allSettled(...) over a \" +\n \"Promise.all(...) whose rejection would orphan its siblings.\",\n cause: options?.cause,\n },\n );\n this.name = \"TransactionClosedError\";\n }\n}\n\n// ============================================================\n// Utility Functions\n// ============================================================\n\n/**\n * Type guard for TypeGraphError.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({});\n * } catch (error) {\n * if (isTypeGraphError(error)) {\n * console.log(error.code, error.category);\n * }\n * }\n * ```\n */\nexport function isTypeGraphError(error: unknown): error is TypeGraphError {\n return error instanceof TypeGraphError;\n}\n\n/**\n * Check if error is recoverable by user action (user or constraint error).\n *\n * User-recoverable errors can typically be resolved by:\n * - Fixing invalid input data\n * - Using different IDs or values\n * - Deleting conflicting data first\n *\n * @example\n * ```typescript\n * if (isUserRecoverable(error)) {\n * showErrorToUser(error.toUserMessage());\n * } else {\n * logAndAlertOps(error);\n * }\n * ```\n */\nexport function isUserRecoverable(error: unknown): boolean {\n if (!isTypeGraphError(error)) return false;\n return error.category === \"user\" || error.category === \"constraint\";\n}\n\n/**\n * Check if error indicates a system/infrastructure issue.\n *\n * System errors typically require:\n * - Retry logic (for transient failures)\n * - Investigation (for persistent failures)\n * - Ops team notification\n */\nexport function isSystemError(error: unknown): boolean {\n return isTypeGraphError(error) && error.category === \"system\";\n}\n\n/**\n * Check if error is a constraint violation.\n */\nexport function isConstraintError(error: unknown): boolean {\n return isTypeGraphError(error) && error.category === \"constraint\";\n}\n\n/**\n * Extract suggestion from error if available.\n */\nexport function getErrorSuggestion(error: unknown): string | undefined {\n return isTypeGraphError(error) ? error.suggestion : undefined;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/backend/postgres/pglite.ts"],"names":["ConfigurationError","tables","PGlite","generatePostgresMigrationSQL","generatePostgresDDL","drizzle","createPostgresBackend","wrapWithManagedClose","closeAfterFailure"],"mappings":";;;;;;;;;AAuIA,eAAe,4BAAA,GAAmD;AAChE,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,GAAU,MAAM,OAAO,+BAA+B,CAAA;AAC5D,IAAA,OAAO,OAAA,CAAQ,MAAA;AAAA,EACjB,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,IAAIA,oCAAA;AAAA,MACR,2PAAA;AAAA,MAIA,EAAE,OAAA,EAAS,QAAA,EAAU,UAAA,EAAY,+BAAA,EAAgC;AAAA,MACjE,EAAE,OAAO,KAAA;AAAM,KACjB;AAAA,EACF;AACF;AAoBA,eAAsB,wBAAA,CACpB,OAAA,GAAqC,EAAC,EACH;AACnC,EAAA,MAAMC,OAAAA,GAAS,QAAQ,MAAA,IAAUA,wBAAA;AAMjC,EAAA,MAAM,eAAA,GACJ,QAAQ,MAAA,KAAW,KAAA,GACjB,SACC,OAAA,CAAQ,MAAA,IAAW,MAAM,4BAAA,EAA6B;AAC3D,EAAA,MAAM,gBAAgB,eAAA,KAAoB,MAAA;AAO1C,EAAA,MAAM,MAAA,GAAS,MAAMC,aAAA,CAAO,MAAA,CAAO;AAAA,IACjC,GAAI,QAAQ,OAAA,KAAY,MAAA,GAAY,EAAC,GAAI,EAAE,OAAA,EAAS,OAAA,CAAQ,OAAA,EAAQ;AAAA,IACpE,GAAI,eAAA,KAAoB,MAAA,GACtB,EAAC,GACD,EAAE,UAAA,EAAY,EAAE,MAAA,EAAQ,eAAA,EAAgB;AAAE,GAC7C,CAAA;AAED,EAAA,IAAI;AAGF,IAAA,MAAM,YAAA,GACJ,gBACEC,8CAAA,CAA6BF,OAAM,IACnCG,qCAAA,CAAoBH,OAAM,CAAA,CAAE,IAAA,CAAK,MAAM,CAAA;AAC3C,IAAA,MAAM,MAAA,CAAO,KAAK,YAAY,CAAA;AAE9B,IAAA,MAAM,EAAA,GAAKI,iBAAQ,MAAM,CAAA;AACzB,IAAA,MAAM,OAAA,GAAUC,wCAAsB,EAAA,EAAI;AAAA,MACxC,MAAA,EAAAL,OAAAA;AAAA,MACA,GAAI,aAAA,GAAgB,EAAC,GAAI,EAAE,QAAQ,KAAA;AAAM,KAC1C,CAAA;AACD,IAAA,MAAM,cAAA,GAAiBM,sCAAA,CAAqB,OAAA,EAAS,YAAY;AAC/D,MAAA,MAAM,OAAO,KAAA,EAAM;AAAA,IACrB,CAAC,CAAA;AAED,IAAA,OAAO,EAAE,OAAA,EAAS,cAAA,EAAgB,EAAA,EAAI,MAAA,EAAO;AAAA,EAC/C,SAAS,KAAA,EAAO;AACd,IAAA,OAAOC,mCAAA,CAAkB,QAAQ,KAAK,CAAA;AAAA,EACxC;AACF","file":"chunk-4MEWSUVM.cjs","sourcesContent":["/**\n * Local PGlite backend — Postgres-in-WASM, running in-process.\n *\n * [PGlite](https://pglite.dev/) is a full Postgres compiled to WebAssembly\n * that runs inside the Node/Bun/Deno/browser process with no server and no\n * native addon. This is the batteries-included Postgres analog of\n * `createLocalSqliteBackend`: it constructs a PGlite instance, loads the\n * pgvector extension, runs the schema DDL, and returns a ready\n * `{ backend, db }` pair whose `close()` disposes the engine.\n *\n * `@electric-sql/pglite` is an optional peer dependency. Vector support\n * additionally needs `@electric-sql/pglite-pgvector` (PGlite ≥ 0.5 ships\n * pgvector as a separate package). Install what you need:\n *\n * ```bash\n * pnpm add @electric-sql/pglite @electric-sql/pglite-pgvector\n * ```\n *\n * @example In-memory database (default, vector enabled)\n * ```typescript\n * import { createLocalPgliteBackend } from \"@nicia-ai/typegraph/adapters/drizzle/postgres/pglite\";\n *\n * const { backend } = await createLocalPgliteBackend();\n * const store = createStore(graph, backend);\n * ```\n *\n * @example Persistent on-disk database\n * ```typescript\n * const { backend, db } = await createLocalPgliteBackend({ dataDir: \"./pgdata\" });\n * ```\n *\n * @example No vector support (skip the pgvector extension)\n * ```typescript\n * const { backend } = await createLocalPgliteBackend({ vector: false });\n * ```\n *\n * PGlite is single-connection and serial: there is no pooling, so concurrent\n * `store.transaction()` calls queue rather than run in parallel.\n */\nimport { type Extension, PGlite } from \"@electric-sql/pglite\";\nimport { drizzle, type PgliteDatabase } from \"drizzle-orm/pglite\";\n\nimport { ConfigurationError } from \"../../errors\";\nimport {\n generatePostgresDDL,\n generatePostgresMigrationSQL,\n} from \"../drizzle/ddl\";\nimport { type AnyPgTransaction } from \"../drizzle/execution\";\nexport type { AnyPgDatabase, AnyPgTransaction } from \"../drizzle/execution\";\nimport {\n createPostgresBackend,\n type PostgresTables,\n tables as defaultTables,\n} from \"../drizzle/postgres\";\nimport {\n type AdapterBackend,\n closeAfterFailure,\n wrapWithManagedClose,\n} from \"../types\";\nexport type {\n ContributionDiagnostic,\n ContributionDiagnosticState,\n ContributionRepairEntry,\n ContributionRepairResult,\n} from \"../types\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Options for creating a local PGlite backend.\n */\nexport type LocalPgliteBackendOptions = Readonly<{\n /**\n * PGlite data directory. Omit for an in-memory database (the default).\n * Accepts any PGlite data-dir spec: a filesystem path (`\"./pgdata\"`),\n * `\"memory://\"`, or a browser/runtime-specific scheme such as\n * `\"idb://my-db\"`.\n */\n dataDir?: string;\n\n /**\n * Custom table definitions. Defaults to standard TypeGraph table names.\n */\n tables?: PostgresTables;\n\n /**\n * Controls the pgvector stack:\n *\n * - **omitted (default)** — load pgvector from `@electric-sql/pglite-pgvector`\n * and run `CREATE EXTENSION vector`, so embedding fields work out of the\n * box. Throws a {@link ConfigurationError} if the package isn't installed.\n * - **`false`** — skip the extension entirely; the backend advertises no\n * vector capability (mirroring a SQLite connection without sqlite-vec).\n * Use when a graph carries no embeddings, or to avoid the extension dep.\n * - **a PGlite `Extension`** — bring your own pgvector build or custom\n * extension packaging. Decouples this helper from a specific pgvector\n * package version.\n */\n vector?: false | Extension;\n}>;\n\n/**\n * Result of creating a local PGlite backend.\n */\nexport type LocalPgliteBackendResult = Readonly<{\n /**\n * The GraphBackend instance for use with createStore. Its `close()`\n * disposes the underlying PGlite engine.\n */\n backend: AdapterBackend<AnyPgTransaction>;\n\n /**\n * The underlying Drizzle database instance. Useful for direct SQL access.\n */\n db: PgliteDatabase;\n\n /**\n * The raw PGlite instance, for engine-specific operations such as\n * `dumpDataDir()` / `clone()` not surfaced through Drizzle.\n */\n client: PGlite;\n}>;\n\n// ============================================================\n// Vector extension loading\n// ============================================================\n\n/**\n * Dynamically loads the default pgvector extension from\n * `@electric-sql/pglite-pgvector`. Kept as a runtime import so the package\n * stays an optional peer dependency — callers using `vector: false` or\n * supplying their own extension never need it installed.\n */\nasync function loadDefaultPgvectorExtension(): Promise<Extension> {\n try {\n const module_ = await import(\"@electric-sql/pglite-pgvector\");\n return module_.vector;\n } catch (error) {\n throw new ConfigurationError(\n \"createLocalPgliteBackend needs the pgvector extension but \" +\n \"`@electric-sql/pglite-pgvector` could not be loaded. Install it \" +\n \"(`pnpm add @electric-sql/pglite-pgvector`), pass your own `vector` \" +\n \"extension, or set `vector: false` to disable vector support.\",\n { backend: \"pglite\", dependency: \"@electric-sql/pglite-pgvector\" },\n { cause: error },\n );\n }\n}\n\n// ============================================================\n// Factory Function\n// ============================================================\n\n/**\n * Creates a TypeGraph backend backed by an in-process PGlite database.\n *\n * Constructs the PGlite engine (loading pgvector unless disabled), executes\n * the schema DDL, and wires the standard Postgres backend. The returned\n * backend owns the engine: call `backend.close()` to dispose it.\n *\n * For production Postgres, or a PGlite instance you construct yourself,\n * use `createPostgresBackend` directly with your own Drizzle database — the\n * execution fast path detects PGlite and routes it correctly.\n *\n * @param options - Configuration options\n * @returns Backend, Drizzle database, and raw PGlite client\n */\nexport async function createLocalPgliteBackend(\n options: LocalPgliteBackendOptions = {},\n): Promise<LocalPgliteBackendResult> {\n const tables = options.tables ?? defaultTables;\n\n // pgvector lives in the WASM instance, so the extension must be passed at\n // construction — `CREATE EXTENSION vector` alone can't pull it in. An\n // explicitly supplied extension wins; `false` disables; otherwise load the\n // default package.\n const vectorExtension =\n options.vector === false ?\n undefined\n : (options.vector ?? (await loadDefaultPgvectorExtension()));\n const vectorEnabled = vectorExtension !== undefined;\n\n // Construct via the single options-object form (passing `dataDir` as a\n // field), not the positional `create(dataDir, options)` overload: with a\n // leading `undefined` dataDir, that overload silently drops `extensions`\n // (\"extension vector is not available\"). The options form loads them for\n // both the in-memory and on-disk cases.\n const client = await PGlite.create({\n ...(options.dataDir === undefined ? {} : { dataDir: options.dataDir }),\n ...(vectorExtension === undefined ?\n {}\n : { extensions: { vector: vectorExtension } }),\n });\n\n try {\n // `exec` runs a multi-statement batch (DDL + the pgvector `CREATE\n // EXTENSION` when enabled) in one round trip.\n const migrationSql =\n vectorEnabled ?\n generatePostgresMigrationSQL(tables)\n : generatePostgresDDL(tables).join(\"\\n\\n\");\n await client.exec(migrationSql);\n\n const db = drizzle(client);\n const backend = createPostgresBackend(db, {\n tables,\n ...(vectorEnabled ? {} : { vector: false }),\n });\n const managedBackend = wrapWithManagedClose(backend, async () => {\n await client.close();\n });\n\n return { backend: managedBackend, db, client };\n } catch (error) {\n return closeAfterFailure(client, error);\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/query/dialect/vector/sqlite-vec-strategy.ts"],"names":["conditions"],"mappings":";;;;;AA6EA,IAAM,YAAA,GAAe,QAAA;AAOrB,IAAM,yBAAA,GAA4B,GAAA;AAElC,IAAM,uBAAA,GAA8C;AAAA,EAClD,SAAA,EAAW,IAAA;AAAA,EACX,OAAA,EAAS,CAAC,QAAA,EAAU,IAAI,CAAA;AAAA;AAAA;AAAA;AAAA,EAIxB,UAAA,EAAY,CAAC,MAAA,EAAQ,MAAM,CAAA;AAAA,EAC3B,aAAA,EAAe,yBAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKf,yBAAA,EAA2B;AAAA,IACzB,IAAA,EAAM,iBAAA;AAAA,IACN,kBAAA,EAAoB;AAAA;AAExB,CAAA;AAGA,SAAS,aAAa,IAAA,EAA2B;AAC/C,EAAA,OAAO,KAAK,SAAA,KAAc,MAAA;AAC5B;AAGA,SAAS,qBAAqB,MAAA,EAA8B;AAC1D,EAAA,QAAQ,MAAA;AAAQ,IACd,KAAK,QAAA,EAAU;AACb,MAAA,OAAO,QAAA;AAAA,IACT;AAAA,IACA,KAAK,IAAA,EAAM;AACT,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,IACA,KAAK,eAAA,EAAiB;AACpB,MAAA,MAAM,IAAI,KAAA;AAAA,QACR;AAAA,OACF;AAAA,IACF;AAAA,IACA,SAAS;AACP,MAAA,MAAM,WAAA,GAAqB,MAAA;AAC3B,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,2BAAA,EAA8B,MAAA,CAAO,WAAW,CAAC,CAAA,CAAE,CAAA;AAAA,IACrE;AAAA;AAEJ;AAQA,SAAS,aAAA,CACP,WACA,IAAA,EACa;AACb,EAAA,qBAAA,CAAsB,WAAW,IAAI,CAAA;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ACF","file":"chunk-4QIKLIGG.js","sourcesContent":["/**\n * sqlite-vec strategy — real `vec0` KNN for local SQLite.\n *\n * This upgrades `createLocalSqliteBackend` (better-sqlite3 + the sqlite-vec\n * extension) from the legacy brute-force-on-a-shared-table model to genuine\n * approximate-nearest-neighbor search on per-`(nodeKind, fieldPath)` storage.\n *\n * ## Storage choice: a `vec0` virtual table per field\n *\n * Each slot is backed by its own `vec0` virtual table:\n *\n * ```sql\n * CREATE VIRTUAL TABLE tg_vec_<kind>_<field> USING vec0(\n * node_id TEXT PRIMARY KEY,\n * graph_id TEXT PARTITION KEY,\n * +created_at TEXT,\n * +updated_at TEXT,\n * embedding float[<N>] distance_metric=<cosine|l2>\n * );\n * ```\n *\n * Verified against the installed `sqlite-vec` `v0.1.9`:\n *\n * - **vec0 over a plain `vec_f32` BLOB column.** The shipped option (a) — a\n * `vec0` virtual table — is chosen over option (b) — a regular table whose\n * `vec_f32` BLOB column is brute-forced — because vec0 is the *only* form\n * that gives local SQLite a real ANN index (today's code only ever\n * brute-forces). vec0 indexes inline (the virtual table *is* the index), so\n * there is no separate `CREATE INDEX` step.\n * - **KNN with partition-correct filtering.** `WHERE embedding MATCH vec_f32(q)\n * AND k = ? AND graph_id = ?` returns the nearest `k`, ordered by `distance`,\n * scoped to one graph — a near vector in another `graph_id` partition does\n * not leak. This is strictly better than libSQL's table-global `vector_top_k`\n * (which over-fetches for multi-graph correctness): vec0's `PARTITION KEY`\n * makes the per-graph KNN exact.\n * - **One table serves both read paths.** The same `embedding` column answers\n * the compiler's brute-force `distanceExpression` (`vec_distance_cosine` /\n * `vec_distance_l2` over the column, `ORDER BY … LIMIT`, no `MATCH`), so the\n * `.where(field.similarTo(...))` CTE path needs no second structure.\n * - **`k` and `LIMIT` are mutually exclusive** in a vec0 `MATCH` query, so the\n * ANN path uses `k = <limit>` with no `LIMIT`, and the brute-force path uses\n * `LIMIT <limit>` with no `MATCH`.\n * - **No `ON CONFLICT` / `INSERT OR REPLACE`** on a vec0 primary key, so upsert\n * is `DELETE` + `INSERT` (atomic under the caller's outer transaction),\n * mirroring the FTS5 strategy.\n *\n * Metric support is `cosine` + `l2` (no `inner_product` — sqlite-vec has no\n * `vec_distance_ip`), advertised as data on `capabilities`. The table's\n * `distance_metric` is fixed at creation from the slot's metric, alongside its\n * fixed dimension `N`.\n *\n * The libSQL and pgvector siblings implement the same `VectorStrategy`\n * contract for their engines.\n */\nimport { type StrategyTableContribution } from \"../../../backend/table-contribution\";\nimport {\n type DeleteEmbeddingParams,\n type UpsertEmbeddingBatchParams,\n type UpsertEmbeddingParams,\n type VectorCapabilities,\n type VectorMetric,\n type VectorSearchParams,\n} from \"../../../backend/types\";\nimport { sql, type SqlFragment } from \"../../sql-fragment\";\nimport {\n assertFiniteEmbedding,\n quoteIdentifier,\n VECTOR_CONTRIBUTION_PREFIX,\n vectorMinScoreCondition,\n vectorPhysicalName,\n vectorScoreExpression,\n type VectorSlot,\n type VectorStrategy,\n} from \"../vector-strategy\";\nimport { vectorPageClause } from \"./pagination\";\n\n/** Physical-name prefix for the per-field `vec0` virtual table. */\nconst TABLE_PREFIX = \"tg_vec\";\n\n/**\n * sqlite-vec stores each dimension as a 32-bit float; `float[N]` accepts\n * large `N`, but we advertise the same conservative ceiling the legacy\n * SQLite path used so capability discovery is stable across the swap.\n */\nconst SQLITE_VEC_MAX_DIMENSIONS = 8000;\n\nconst SQLITE_VEC_CAPABILITIES: VectorCapabilities = {\n supported: true,\n metrics: [\"cosine\", \"l2\"],\n // vec0 always indexes inline, so the portable ANN intent (\"hnsw\", the\n // `embedding()` default) is honored by real KNN; \"none\" stays brute-force.\n // Both map to the same vec0 table — only `buildSearch` differs.\n indexTypes: [\"hnsw\", \"none\"],\n maxDimensions: SQLITE_VEC_MAX_DIMENSIONS,\n // vec0's KNN accepts primary-key `IN (SELECT …)` pushdown (verified on\n // sqlite-vec v0.1.9), so the candidate filter constrains the KNN itself and\n // a filtered search returns `k` live rows — no over-fetch, no scan bound, no\n // under-fill. The only bundled engine that can promise a full page.\n filteredApproximateSearch: {\n mode: \"filter-pushdown\",\n guaranteesFullPage: true,\n },\n};\n\n/** Whether a slot's declared index type maps to vec0's `MATCH … k =` KNN. */\nfunction usesAnnIndex(slot: VectorSlot): boolean {\n return slot.indexType === \"hnsw\";\n}\n\n/** vec0 `distance_metric` token accepted in the virtual-table definition. */\nfunction sqliteVecMetricToken(metric: VectorMetric): string {\n switch (metric) {\n case \"cosine\": {\n return \"cosine\";\n }\n case \"l2\": {\n return \"l2\";\n }\n case \"inner_product\": {\n throw new Error(\n \"sqlite-vec does not support inner_product. Use 'cosine' or 'l2'.\",\n );\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);\n }\n }\n}\n\n/**\n * Formats an embedding as the bound JSON argument to `vec_f32(...)`. The\n * value rides as a parameter (not interpolated) — `vec_f32` parses the JSON\n * array into the packed float blob. Finiteness is validated first so a\n * NaN/Infinity names its index before JSON.stringify masks it as `null`.\n */\nfunction vecF32Literal(\n embedding: readonly number[],\n name: string,\n): SqlFragment {\n assertFiniteEmbedding(embedding, name);\n return sql`vec_f32(${JSON.stringify(embedding)})`;\n}\n\nfunction distanceExpression(\n embeddingColumn: SqlFragment,\n queryEmbedding: readonly number[],\n metric: VectorMetric,\n): SqlFragment {\n const query = vecF32Literal(queryEmbedding, \"queryEmbedding\");\n switch (metric) {\n case \"cosine\": {\n return sql`vec_distance_cosine(${embeddingColumn}, ${query})`;\n }\n case \"l2\": {\n return sql`vec_distance_l2(${embeddingColumn}, ${query})`;\n }\n case \"inner_product\": {\n throw new Error(\n \"sqlite-vec does not support inner_product. Use 'cosine' or 'l2'.\",\n );\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);\n }\n }\n}\n\nfunction tableName(\n graphId: string,\n nodeKind: string,\n fieldPath: string,\n): string {\n return vectorPhysicalName(TABLE_PREFIX, graphId, nodeKind, fieldPath);\n}\n\nexport const sqliteVecStrategy: VectorStrategy = {\n name: \"sqlite-vec\",\n capabilities: SQLITE_VEC_CAPABILITIES,\n\n tableName,\n\n ownedTables(slot): readonly StrategyTableContribution[] {\n const table = tableName(slot.graphId, slot.nodeKind, slot.fieldPath);\n const name = quoteIdentifier(table);\n const metric = sqliteVecMetricToken(slot.metric);\n\n // vec0 virtual tables cannot be modeled as a Drizzle table, so this is a\n // raw-ddl contribution — emitted verbatim and invisible to drizzle-kit.\n // `graph_id` is a PARTITION KEY so per-graph KNN is exact; `created_at` /\n // `updated_at` are auxiliary (`+`) columns (stored, not filtered on). The\n // virtual table *is* the index — no separate CREATE INDEX is emitted.\n return [\n {\n logicalName: `${VECTOR_CONTRIBUTION_PREFIX}:${slot.nodeKind}.${slot.fieldPath}`,\n owner: \"sqlite-vec\",\n tableName: table,\n createDdl: [\n `CREATE VIRTUAL TABLE IF NOT EXISTS ${name} USING vec0(\n node_id TEXT PRIMARY KEY,\n graph_id TEXT PARTITION KEY,\n +created_at TEXT,\n +updated_at TEXT,\n embedding float[${slot.dimensions}] distance_metric=${metric}\n);`,\n ],\n runtimeEnsure: true,\n },\n ];\n },\n\n buildUpsert(\n slot,\n params: UpsertEmbeddingParams,\n timestamp,\n ): readonly SqlFragment[] {\n const table = sql.identifier(\n tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n const value = vecF32Literal(params.embedding, \"embedding\");\n // vec0 rejects ON CONFLICT / INSERT OR REPLACE on its primary key —\n // emulate upsert with DELETE + INSERT, atomic under the caller's\n // outer transaction (mirrors the FTS5 fulltext strategy).\n return [\n sql`\n DELETE FROM ${table}\n WHERE \"node_id\" = ${params.nodeId} AND \"graph_id\" = ${params.graphId}\n `,\n sql`\n INSERT INTO ${table} (\"node_id\", \"graph_id\", \"created_at\", \"updated_at\", \"embedding\")\n VALUES (${params.nodeId}, ${params.graphId}, ${timestamp}, ${timestamp}, ${value})\n `,\n ];\n },\n\n buildUpsertBatch(\n slot,\n params: UpsertEmbeddingBatchParams,\n timestamp,\n ): readonly SqlFragment[] {\n const table = sql.identifier(\n tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n // Same DELETE + INSERT upsert emulation as buildUpsert, in multi-row\n // form: one IN-list delete, one multi-row insert.\n const nodeIds = sql.join(\n params.rows.map((row) => sql`${row.nodeId}`),\n sql`, `,\n );\n const valueRows = sql.join(\n params.rows.map(\n (row) =>\n sql`(${row.nodeId}, ${params.graphId}, ${timestamp}, ${timestamp}, ${vecF32Literal(row.embedding, \"embedding\")})`,\n ),\n sql`, `,\n );\n return [\n sql`\n DELETE FROM ${table}\n WHERE \"graph_id\" = ${params.graphId} AND \"node_id\" IN (${nodeIds})\n `,\n sql`\n INSERT INTO ${table} (\"node_id\", \"graph_id\", \"created_at\", \"updated_at\", \"embedding\")\n VALUES ${valueRows}\n `,\n ];\n },\n\n buildDelete(slot, params: DeleteEmbeddingParams): readonly SqlFragment[] {\n const table = sql.identifier(\n tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n return [\n sql`\n DELETE FROM ${table}\n WHERE \"node_id\" = ${params.nodeId} AND \"graph_id\" = ${params.graphId}\n `,\n ];\n },\n\n buildDeleteBatch(\n slot,\n params: Omit<DeleteEmbeddingParams, \"nodeId\"> &\n Readonly<{ nodeIds: readonly string[] }>,\n ): readonly SqlFragment[] {\n if (params.nodeIds.length === 0) return [];\n const table = sql.identifier(\n tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n return [\n sql`DELETE FROM ${table} WHERE \"graph_id\" = ${params.graphId} AND \"node_id\" IN (${sql.join(\n params.nodeIds.map((nodeId) => sql`${nodeId}`),\n sql`, `,\n )})`,\n ];\n },\n\n // vec0's KNN is brute force in C — exact by construction (the\n // \"index\" is a partitioned scan, not a graph) — and the non-indexed\n // fallback below is a plain SQL scan. The compiler may therefore\n // route the NON-approximate `.similarTo()` branch through this form.\n searchIsExact: true,\n\n buildSearch(\n slot,\n params: VectorSearchParams,\n candidates?: SqlFragment,\n ): SqlFragment {\n const table = sql.identifier(\n tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n const embeddingColumn = sql`${table}.\"embedding\"`;\n const distance = distanceExpression(\n embeddingColumn,\n params.queryEmbedding,\n params.metric,\n );\n const score = vectorScoreExpression(distance, params.metric);\n\n if (usesAnnIndex(slot)) {\n // vec0 KNN. `k` and `LIMIT` are mutually exclusive in a MATCH query, so\n // bound `k = limit` and omit LIMIT. `graph_id` filters by the partition\n // key (exact, no recall loss). Order by vec0's own `distance` column —\n // the recomputed `distance` expression is reused only for score/minScore\n // so the math matches the brute-force path and the shared helpers.\n const query = vecF32Literal(params.queryEmbedding, \"queryEmbedding\");\n // `k` covers the requested page: vec0 has no OFFSET inside a MATCH\n // query, so fetch `limit + offset` neighbors and page in a wrapper.\n const knnK = params.limit + (params.offset ?? 0);\n const conditions: SqlFragment[] = [\n sql`${table}.\"embedding\" MATCH ${query}`,\n sql`k = ${knnK}`,\n sql`${table}.\"graph_id\" = ${params.graphId}`,\n ];\n if (params.minScore !== undefined) {\n conditions.push(\n vectorMinScoreCondition(distance, params.metric, params.minScore),\n );\n }\n // vec0 KNN accepts primary-key `IN (SELECT ...)` pushdown (verified on\n // sqlite-vec v0.1.9): the filter constrains the KNN candidate set\n // itself, so `k` live results come back — exact, no over-fetch.\n if (candidates !== undefined) {\n conditions.push(sql`${table}.\"node_id\" IN (${candidates})`);\n }\n const knnBody = sql`\n SELECT ${table}.\"node_id\" AS node_id, ${score} AS score\n FROM ${table}\n WHERE ${sql.join(conditions, sql` AND `)}\n ORDER BY distance ASC\n `;\n if (params.offset === undefined || params.offset === 0) {\n return knnBody;\n }\n // MATERIALIZED fences the page wrapper: SQLite would otherwise\n // flatten the subquery and push the outer LIMIT into the vec0 MATCH\n // query, which rejects `k = ?` and LIMIT together.\n return sql`\n WITH knn_page AS MATERIALIZED (${knnBody})\n SELECT node_id, score FROM knn_page\n LIMIT ${params.limit} OFFSET ${params.offset}\n `;\n }\n\n // Brute-force scan: no MATCH, so LIMIT is allowed (and required).\n const conditions: SqlFragment[] = [\n sql`${table}.\"graph_id\" = ${params.graphId}`,\n ];\n if (candidates !== undefined) {\n conditions.push(sql`${table}.\"node_id\" IN (${candidates})`);\n }\n if (params.minScore !== undefined) {\n conditions.push(\n vectorMinScoreCondition(distance, params.metric, params.minScore),\n );\n }\n const pageClause = vectorPageClause(params.limit, params.offset);\n return sql`\n SELECT ${table}.\"node_id\" AS node_id, ${score} AS score\n FROM ${table}\n WHERE ${sql.join(conditions, sql` AND `)}\n ORDER BY ${distance} ASC\n ${pageClause}\n `;\n },\n\n distanceExpression(embeddingColumn, queryEmbedding, metric) {\n return distanceExpression(embeddingColumn, queryEmbedding, metric);\n },\n\n // vec0 indexes inline (the virtual table is the index), so there is no\n // standalone ANN index to create or drop — both return undefined.\n buildCreateIndex(): SqlFragment | undefined {\n return undefined;\n },\n\n buildDropIndex(): SqlFragment | undefined {\n return undefined;\n },\n\n buildDropStorage(slot): readonly string[] {\n const table = quoteIdentifier(\n tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n // Dropping the vec0 virtual table removes its backing shadow tables too.\n return [`DROP TABLE IF EXISTS ${table}`];\n },\n};\n"]}
|