@nicia-ai/typegraph 0.37.0 → 0.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -10
- package/dist/backend/drizzle/indexes.cjs +32 -0
- package/dist/backend/drizzle/indexes.cjs.map +1 -0
- package/dist/backend/drizzle/indexes.d.cts +43 -0
- package/dist/backend/drizzle/indexes.d.ts +43 -0
- package/dist/backend/drizzle/indexes.js +11 -0
- package/dist/backend/drizzle/indexes.js.map +1 -0
- package/dist/backend/index.cjs +161 -0
- package/dist/backend/index.cjs.map +1 -0
- package/dist/backend/index.d.cts +3 -0
- package/dist/backend/index.d.ts +3 -0
- package/dist/backend/index.js +8 -0
- package/dist/backend/index.js.map +1 -0
- package/dist/backend/postgres/index.cjs +32 -28
- package/dist/backend/postgres/index.d.cts +13 -12
- package/dist/backend/postgres/index.d.ts +13 -12
- package/dist/backend/postgres/index.js +19 -15
- package/dist/backend/postgres/pglite-store.cjs +67 -0
- package/dist/backend/postgres/pglite-store.cjs.map +1 -0
- package/dist/backend/postgres/pglite-store.d.cts +38 -0
- package/dist/backend/postgres/pglite-store.d.ts +38 -0
- package/dist/backend/postgres/pglite-store.js +65 -0
- package/dist/backend/postgres/pglite-store.js.map +1 -0
- package/dist/backend/postgres/pglite.cjs +25 -50
- package/dist/backend/postgres/pglite.cjs.map +1 -1
- package/dist/backend/postgres/pglite.d.cts +10 -9
- package/dist/backend/postgres/pglite.d.ts +10 -9
- package/dist/backend/postgres/pglite.js +20 -52
- package/dist/backend/postgres/pglite.js.map +1 -1
- package/dist/backend/sqlite/index.cjs +29 -25
- package/dist/backend/sqlite/index.d.cts +11 -11
- package/dist/backend/sqlite/index.d.ts +11 -11
- package/dist/backend/sqlite/index.js +17 -13
- package/dist/backend/sqlite/libsql.cjs +23 -19
- package/dist/backend/sqlite/libsql.cjs.map +1 -1
- package/dist/backend/sqlite/libsql.d.cts +9 -10
- package/dist/backend/sqlite/libsql.d.ts +9 -10
- package/dist/backend/sqlite/libsql.js +19 -15
- package/dist/backend/sqlite/libsql.js.map +1 -1
- package/dist/backend/sqlite/local-store.cjs +72 -0
- package/dist/backend/sqlite/local-store.cjs.map +1 -0
- package/dist/backend/sqlite/local-store.d.cts +42 -0
- package/dist/backend/sqlite/local-store.d.ts +42 -0
- package/dist/backend/sqlite/local-store.js +67 -0
- package/dist/backend/sqlite/local-store.js.map +1 -0
- package/dist/backend/sqlite/local.cjs +28 -183
- package/dist/backend/sqlite/local.cjs.map +1 -1
- package/dist/backend/sqlite/local.d.cts +8 -81
- package/dist/backend/sqlite/local.d.ts +8 -81
- package/dist/backend/sqlite/local.js +20 -180
- package/dist/backend/sqlite/local.js.map +1 -1
- package/dist/chunk-2EBMPJBO.js +16 -0
- package/dist/chunk-2EBMPJBO.js.map +1 -0
- package/dist/{chunk-NBP2WTJW.cjs → chunk-2SL7OGPR.cjs} +2900 -1597
- package/dist/chunk-2SL7OGPR.cjs.map +1 -0
- package/dist/chunk-35S6P5ZU.js +27 -0
- package/dist/chunk-35S6P5ZU.js.map +1 -0
- package/dist/chunk-3LKL3S6X.js +50 -0
- package/dist/chunk-3LKL3S6X.js.map +1 -0
- package/dist/chunk-6G5CQ6JX.js +47 -0
- package/dist/chunk-6G5CQ6JX.js.map +1 -0
- package/dist/chunk-6XDBRDZE.js +312 -0
- package/dist/chunk-6XDBRDZE.js.map +1 -0
- package/dist/chunk-764JHTLT.cjs +15 -0
- package/dist/chunk-764JHTLT.cjs.map +1 -0
- package/dist/chunk-76HE7DJP.js +68 -0
- package/dist/chunk-76HE7DJP.js.map +1 -0
- package/dist/{chunk-VGDDG3XJ.cjs → chunk-7M3NACL3.cjs} +12 -12
- package/dist/{chunk-VGDDG3XJ.cjs.map → chunk-7M3NACL3.cjs.map} +1 -1
- package/dist/{chunk-NXQFATMF.cjs → chunk-7VLCN3JB.cjs} +153 -123
- package/dist/chunk-7VLCN3JB.cjs.map +1 -0
- package/dist/{chunk-552KNYQJ.js → chunk-A2FGSWMQ.js} +1907 -607
- package/dist/chunk-A2FGSWMQ.js.map +1 -0
- package/dist/chunk-AOL64O4Z.js +165 -0
- package/dist/chunk-AOL64O4Z.js.map +1 -0
- package/dist/{chunk-27SSDCEP.cjs → chunk-B63IFHXR.cjs} +53 -74
- package/dist/chunk-B63IFHXR.cjs.map +1 -0
- package/dist/{chunk-3XXGYU62.cjs → chunk-BKAKAVRW.cjs} +56 -53
- package/dist/chunk-BKAKAVRW.cjs.map +1 -0
- package/dist/{chunk-YTSN73ND.js → chunk-BQITNFQJ.js} +3 -3
- package/dist/{chunk-YTSN73ND.js.map → chunk-BQITNFQJ.js.map} +1 -1
- package/dist/{chunk-NUIG3BCV.cjs → chunk-CQC6VBAF.cjs} +93 -155
- package/dist/chunk-CQC6VBAF.cjs.map +1 -0
- package/dist/{chunk-6EEO3OVU.cjs → chunk-CWX77JB4.cjs} +22 -59
- package/dist/chunk-CWX77JB4.cjs.map +1 -0
- package/dist/{chunk-UGZUAYAR.js → chunk-D7PG5D5K.js} +4 -3
- package/dist/chunk-D7PG5D5K.js.map +1 -0
- package/dist/chunk-DDCIXXOO.js +9 -0
- package/dist/chunk-DDCIXXOO.js.map +1 -0
- package/dist/chunk-DDCYVIVV.cjs +44 -0
- package/dist/chunk-DDCYVIVV.cjs.map +1 -0
- package/dist/{chunk-XPCZADMT.cjs → chunk-DOVMTPKE.cjs} +89 -27
- package/dist/chunk-DOVMTPKE.cjs.map +1 -0
- package/dist/{chunk-5PNMDJ7J.js → chunk-DPNA466P.js} +14 -9
- package/dist/chunk-DPNA466P.js.map +1 -0
- package/dist/{chunk-BYPOGQWK.js → chunk-DRACN6XG.js} +6 -4
- package/dist/chunk-DRACN6XG.js.map +1 -0
- package/dist/chunk-E6TXEISH.cjs +175 -0
- package/dist/chunk-E6TXEISH.cjs.map +1 -0
- package/dist/{chunk-TKT2XHED.js → chunk-E6YZRKMM.js} +13 -12
- package/dist/chunk-E6YZRKMM.js.map +1 -0
- package/dist/{chunk-3C2RYI6L.cjs → chunk-EOJFGECD.cjs} +11 -11
- package/dist/chunk-EOJFGECD.cjs.map +1 -0
- package/dist/{chunk-XWV4JT34.js → chunk-ERZ4QPQX.js} +27 -22
- package/dist/chunk-ERZ4QPQX.js.map +1 -0
- package/dist/{chunk-DFVLCOP6.js → chunk-EZH7FNUS.js} +3 -3
- package/dist/{chunk-DFVLCOP6.js.map → chunk-EZH7FNUS.js.map} +1 -1
- package/dist/{chunk-WWFHO375.cjs → chunk-FJMPR3OH.cjs} +4 -3
- package/dist/chunk-FJMPR3OH.cjs.map +1 -0
- package/dist/chunk-FMNUSGZ4.cjs +12 -0
- package/dist/chunk-FMNUSGZ4.cjs.map +1 -0
- package/dist/{chunk-K3Q3LJY3.js → chunk-G32AO634.js} +201 -100
- package/dist/chunk-G32AO634.js.map +1 -0
- package/dist/{chunk-EXU3RASM.js → chunk-G3CSQLLT.js} +20 -474
- package/dist/chunk-G3CSQLLT.js.map +1 -0
- package/dist/chunk-GNPGGLAE.cjs +212 -0
- package/dist/chunk-GNPGGLAE.cjs.map +1 -0
- package/dist/{chunk-QARBLBXT.cjs → chunk-GUUWKPTK.cjs} +7 -7
- package/dist/{chunk-QARBLBXT.cjs.map → chunk-GUUWKPTK.cjs.map} +1 -1
- package/dist/chunk-GYA4JRP5.js +31 -0
- package/dist/chunk-GYA4JRP5.js.map +1 -0
- package/dist/chunk-I6FX7AAG.js +39 -0
- package/dist/chunk-I6FX7AAG.js.map +1 -0
- package/dist/chunk-IMQKXL4E.cjs +12 -0
- package/dist/{chunk-QSXTWU4U.cjs.map → chunk-IMQKXL4E.cjs.map} +1 -1
- package/dist/chunk-J6IJARLG.js +94 -0
- package/dist/chunk-J6IJARLG.js.map +1 -0
- package/dist/{chunk-W63OVYY4.js → chunk-K34OPSJK.js} +3 -3
- package/dist/{chunk-W63OVYY4.js.map → chunk-K34OPSJK.js.map} +1 -1
- package/dist/{chunk-TGOMW4MB.cjs → chunk-KCLZHYPU.cjs} +110 -109
- package/dist/chunk-KCLZHYPU.cjs.map +1 -0
- package/dist/{chunk-XGPUQ56G.js → chunk-KFLXWVUJ.js} +4 -38
- package/dist/chunk-KFLXWVUJ.js.map +1 -0
- package/dist/{chunk-3DS7Z4T4.cjs → chunk-LZ3TVJY4.cjs} +44 -43
- package/dist/chunk-LZ3TVJY4.cjs.map +1 -0
- package/dist/{chunk-UXLSNRYL.js → chunk-MTNEGGM2.js} +4 -4
- package/dist/chunk-MTNEGGM2.js.map +1 -0
- package/dist/{chunk-IP3CGGPA.cjs → chunk-N2V3HJFV.cjs} +92 -185
- package/dist/chunk-N2V3HJFV.cjs.map +1 -0
- package/dist/chunk-NAUA4PW5.cjs +28 -0
- package/dist/chunk-NAUA4PW5.cjs.map +1 -0
- package/dist/chunk-NMQ6C6TS.cjs +61 -0
- package/dist/chunk-NMQ6C6TS.cjs.map +1 -0
- package/dist/{chunk-2N6EOBTH.cjs → chunk-NPWACFQJ.cjs} +58 -53
- package/dist/chunk-NPWACFQJ.cjs.map +1 -0
- package/dist/{chunk-5KEQ74YU.cjs → chunk-NT6ILURI.cjs} +9 -86
- package/dist/chunk-NT6ILURI.cjs.map +1 -0
- package/dist/chunk-NU23DUSJ.cjs +192 -0
- package/dist/chunk-NU23DUSJ.cjs.map +1 -0
- package/dist/{chunk-WOJMKB3N.cjs → chunk-NWYCOFEZ.cjs} +1677 -308
- package/dist/chunk-NWYCOFEZ.cjs.map +1 -0
- package/dist/{chunk-3GH67G4Z.cjs → chunk-O5H62ZWJ.cjs} +4 -42
- package/dist/chunk-O5H62ZWJ.cjs.map +1 -0
- package/dist/{chunk-3SLPDKHQ.js → chunk-PH4IJ3V5.js} +5 -77
- package/dist/chunk-PH4IJ3V5.js.map +1 -0
- package/dist/chunk-PWXGB77L.cjs +56 -0
- package/dist/chunk-PWXGB77L.cjs.map +1 -0
- package/dist/chunk-PZHC5GCD.js +193 -0
- package/dist/chunk-PZHC5GCD.js.map +1 -0
- package/dist/chunk-QMQLUA66.js +12 -0
- package/dist/chunk-QMQLUA66.js.map +1 -0
- package/dist/{chunk-5WWVZMVX.js → chunk-QZ7A6HBM.js} +2 -2
- package/dist/{chunk-5WWVZMVX.js.map → chunk-QZ7A6HBM.js.map} +1 -1
- package/dist/{chunk-VKGKDOKR.js → chunk-RQPRCEIO.js} +1539 -206
- package/dist/chunk-RQPRCEIO.js.map +1 -0
- package/dist/chunk-RW24SAHI.cjs +74 -0
- package/dist/chunk-RW24SAHI.cjs.map +1 -0
- package/dist/{chunk-BVRDGYXQ.cjs → chunk-SAFZ6JTI.cjs} +14 -9
- package/dist/chunk-SAFZ6JTI.cjs.map +1 -0
- package/dist/{chunk-L7HQ2OSI.js → chunk-SCTZRFW5.js} +87 -166
- package/dist/chunk-SCTZRFW5.js.map +1 -0
- package/dist/{chunk-5KPNWT6X.js → chunk-SDHV2MWU.js} +24 -45
- package/dist/chunk-SDHV2MWU.js.map +1 -0
- package/dist/chunk-SVJ5GEXW.cjs +45 -0
- package/dist/chunk-SVJ5GEXW.cjs.map +1 -0
- package/dist/chunk-SVUKGWSN.cjs +102 -0
- package/dist/chunk-SVUKGWSN.cjs.map +1 -0
- package/dist/chunk-TAUGGLNQ.js +59 -0
- package/dist/chunk-TAUGGLNQ.js.map +1 -0
- package/dist/{chunk-J4IUSYFF.js → chunk-TE5ZA4VX.js} +69 -27
- package/dist/chunk-TE5ZA4VX.js.map +1 -0
- package/dist/{chunk-A42GCBGX.cjs → chunk-TRF4EBJT.cjs} +6 -4
- package/dist/chunk-TRF4EBJT.cjs.map +1 -0
- package/dist/{chunk-KQJ54OG5.js → chunk-U4JDJKPD.js} +19 -56
- package/dist/chunk-U4JDJKPD.js.map +1 -0
- package/dist/chunk-UH2USOMG.cjs +627 -0
- package/dist/chunk-UH2USOMG.cjs.map +1 -0
- package/dist/{chunk-RCVLFTCT.js → chunk-UPXDVI3T.js} +13 -12
- package/dist/chunk-UPXDVI3T.js.map +1 -0
- package/dist/{chunk-5VQM6VWP.cjs → chunk-UWG5GX6E.cjs} +2 -2
- package/dist/{chunk-5VQM6VWP.cjs.map → chunk-UWG5GX6E.cjs.map} +1 -1
- package/dist/{chunk-3RWZPJKV.js → chunk-VBH7ZXSZ.js} +21 -78
- package/dist/chunk-VBH7ZXSZ.js.map +1 -0
- package/dist/{chunk-K5UBVGJN.js → chunk-VDYA2HMS.js} +6 -6
- package/dist/{chunk-K5UBVGJN.js.map → chunk-VDYA2HMS.js.map} +1 -1
- package/dist/chunk-X4PVHAZ6.cjs +83 -0
- package/dist/chunk-X4PVHAZ6.cjs.map +1 -0
- package/dist/{chunk-UYQMBBWJ.js → chunk-X6CNEA32.js} +23 -20
- package/dist/chunk-X6CNEA32.js.map +1 -0
- package/dist/chunk-X6RDQ5NB.cjs +335 -0
- package/dist/chunk-X6RDQ5NB.cjs.map +1 -0
- package/dist/chunk-XD6X7O5R.js +184 -0
- package/dist/chunk-XD6X7O5R.js.map +1 -0
- package/dist/{chunk-DIQ3AV5W.cjs → chunk-XFY73JWD.cjs} +324 -224
- package/dist/chunk-XFY73JWD.cjs.map +1 -0
- package/dist/{chunk-DEFQM7JU.cjs → chunk-XRU7V7FF.cjs} +7 -7
- package/dist/{chunk-DEFQM7JU.cjs.map → chunk-XRU7V7FF.cjs.map} +1 -1
- package/dist/{chunk-TPF25IG6.js → chunk-XZA3Y4YH.js} +3 -3
- package/dist/{chunk-TPF25IG6.js.map → chunk-XZA3Y4YH.js.map} +1 -1
- package/dist/chunk-Y7M44XEK.js +462 -0
- package/dist/chunk-Y7M44XEK.js.map +1 -0
- package/dist/{chunk-RRSNR3TP.js → chunk-YIRLBUNN.js} +3 -3
- package/dist/{chunk-RRSNR3TP.js.map → chunk-YIRLBUNN.js.map} +1 -1
- package/dist/{chunk-IXGYRP2P.js → chunk-YJDSPA5E.js} +79 -49
- package/dist/chunk-YJDSPA5E.js.map +1 -0
- package/dist/{chunk-JBNOGRKW.cjs → chunk-YLINFV7Z.cjs} +157 -115
- package/dist/chunk-YLINFV7Z.cjs.map +1 -0
- package/dist/{chunk-QERAIDRJ.js → chunk-Z2PPIVOO.js} +82 -22
- package/dist/chunk-Z2PPIVOO.js.map +1 -0
- package/dist/chunk-Z5QHVL5U.cjs +12 -0
- package/dist/chunk-Z5QHVL5U.cjs.map +1 -0
- package/dist/chunk-ZDH3DX3C.cjs +30 -0
- package/dist/chunk-ZDH3DX3C.cjs.map +1 -0
- package/dist/chunk-ZE6NVENI.js +77 -0
- package/dist/chunk-ZE6NVENI.js.map +1 -0
- package/dist/chunk-ZHX4KEM7.cjs +49 -0
- package/dist/chunk-ZHX4KEM7.cjs.map +1 -0
- package/dist/chunk-ZKZAIX42.cjs +479 -0
- package/dist/chunk-ZKZAIX42.cjs.map +1 -0
- package/dist/{chunk-TEDRJXOG.cjs → chunk-ZY4GXIVN.cjs} +5 -5
- package/dist/{chunk-TEDRJXOG.cjs.map → chunk-ZY4GXIVN.cjs.map} +1 -1
- package/dist/core/index.cjs +117 -0
- package/dist/core/index.cjs.map +1 -0
- package/dist/core/index.d.cts +225 -0
- package/dist/core/index.d.ts +225 -0
- package/dist/core/index.js +12 -0
- package/dist/core/index.js.map +1 -0
- package/dist/{ddl-CS0KUVwB.d.ts → ddl-Dx3Z0_WC.d.ts} +3 -3
- package/dist/{ddl-BD-ZfKeX.d.cts → ddl-J6sDyABg.d.cts} +3 -3
- package/dist/define-graph-CzEvA_8F.d.cts +174 -0
- package/dist/define-graph-DRo9xpYN.d.ts +174 -0
- package/dist/{extension-types-BM2ACfYO.d.cts → extension-types-BLEVH4SG.d.cts} +1 -1
- package/dist/{extension-types-BM2ACfYO.d.ts → extension-types-BLEVH4SG.d.ts} +1 -1
- package/dist/graph-extension/index.cjs +21 -19
- package/dist/graph-extension/index.d.cts +4 -4
- package/dist/graph-extension/index.d.ts +4 -4
- package/dist/graph-extension/index.js +6 -4
- package/dist/graph-merge/index.cjs +265 -214
- package/dist/graph-merge/index.cjs.map +1 -1
- package/dist/graph-merge/index.d.cts +8 -89
- package/dist/graph-merge/index.d.ts +8 -89
- package/dist/graph-merge/index.js +141 -90
- package/dist/graph-merge/index.js.map +1 -1
- package/dist/{index-BeacbPoe.d.ts → index-BD_3TCgh.d.ts} +6 -4
- package/dist/{index-BPM59vsg.d.cts → index-BihFPsPu.d.cts} +6 -4
- package/dist/{fulltext-strategy-C27vXaeB.d.cts → index-Bq7vSPHy.d.ts} +3195 -2646
- package/dist/{fulltext-strategy-DebsMrqg.d.ts → index-CrFL_ENI.d.cts} +3195 -2646
- package/dist/index.cjs +326 -315
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +59 -240
- package/dist/index.d.ts +59 -240
- package/dist/index.js +46 -79
- package/dist/index.js.map +1 -1
- package/dist/indexes/index.cjs +26 -38
- package/dist/indexes/index.d.cts +6 -41
- package/dist/indexes/index.d.ts +6 -41
- package/dist/indexes/index.js +14 -10
- package/dist/interchange/index.cjs +48 -39
- package/dist/interchange/index.cjs.map +1 -1
- package/dist/interchange/index.d.cts +7 -8
- package/dist/interchange/index.d.ts +7 -8
- package/dist/interchange/index.js +23 -14
- package/dist/interchange/index.js.map +1 -1
- package/dist/local-options-CZ1BnIoF.d.cts +29 -0
- package/dist/local-options-CZ1BnIoF.d.ts +29 -0
- package/dist/{manager-D00_NXvT.d.ts → manager-CASfhmzV.d.ts} +4 -173
- package/dist/{manager-nU1vTJLy.d.cts → manager-nCEJiYBb.d.cts} +4 -173
- package/dist/{materialize-indexes-zK2J_flP.d.ts → materialize-indexes-D4iei4Kp.d.ts} +1 -1
- package/dist/{materialize-indexes-CuR3gAZb.d.cts → materialize-indexes-ExQ6OrAh.d.cts} +1 -1
- package/dist/{postgres-IaBA4RgE.d.ts → postgres-Cl1ZAN1G.d.ts} +1 -1
- package/dist/{postgres-YrYmPlaU.d.cts → postgres-DMgIKQU-.d.cts} +1 -1
- package/dist/postgres-execution-fKW0qRiN.d.cts +14 -0
- package/dist/postgres-execution-fKW0qRiN.d.ts +14 -0
- package/dist/profiler/index.cjs +9 -8
- package/dist/profiler/index.cjs.map +1 -1
- package/dist/profiler/index.d.cts +9 -17
- package/dist/profiler/index.d.ts +9 -17
- package/dist/profiler/index.js +8 -7
- package/dist/profiler/index.js.map +1 -1
- package/dist/provenance/index.cjs +61 -55
- package/dist/provenance/index.cjs.map +1 -1
- package/dist/provenance/index.d.cts +7 -8
- package/dist/provenance/index.d.ts +7 -8
- package/dist/provenance/index.js +34 -28
- package/dist/provenance/index.js.map +1 -1
- package/dist/schema/index.cjs +46 -37
- package/dist/schema/index.cjs.map +1 -1
- package/dist/schema/index.d.cts +8 -10
- package/dist/schema/index.d.ts +8 -10
- package/dist/schema/index.js +22 -13
- package/dist/schema/index.js.map +1 -1
- package/dist/{sqlite-BUOHPx7p.d.ts → sqlite-BDkW39aa.d.cts} +1 -1
- package/dist/{sqlite-Pp8O19WE.d.cts → sqlite-CYfhvESj.d.ts} +1 -1
- package/dist/sqlite-execution-DwbE2a9y.d.cts +32 -0
- package/dist/sqlite-execution-DwbE2a9y.d.ts +32 -0
- package/dist/{store-view-X96Rd00T.d.cts → store-view-BoHqdHjB.d.cts} +394 -1393
- package/dist/{store-view-ANL6mTph.d.ts → store-view-Ctq-3OHy.d.ts} +394 -1393
- package/dist/temporal-BC_NQV5Y.d.cts +281 -0
- package/dist/temporal-DqtOEo_B.d.ts +281 -0
- package/dist/{types-r-Zyq2Hz.d.cts → types-COq3-vMC.d.cts} +2 -2
- package/dist/{types-wsvuBgPK.d.ts → types-CUevi_D1.d.ts} +2 -2
- package/dist/{where-CJOpJj3a.d.ts → where-BdE_cYtx.d.ts} +5 -5
- package/dist/{where-K3uBP33l.d.cts → where-C92TXCzT.d.cts} +5 -5
- package/package.json +37 -6
- package/dist/chunk-27SSDCEP.cjs.map +0 -1
- package/dist/chunk-2N6EOBTH.cjs.map +0 -1
- package/dist/chunk-3C2RYI6L.cjs.map +0 -1
- package/dist/chunk-3DS7Z4T4.cjs.map +0 -1
- package/dist/chunk-3GH67G4Z.cjs.map +0 -1
- package/dist/chunk-3RWZPJKV.js.map +0 -1
- package/dist/chunk-3SLPDKHQ.js.map +0 -1
- package/dist/chunk-3XXGYU62.cjs.map +0 -1
- package/dist/chunk-44TA22QT.js +0 -1478
- package/dist/chunk-44TA22QT.js.map +0 -1
- package/dist/chunk-552KNYQJ.js.map +0 -1
- package/dist/chunk-5KEQ74YU.cjs.map +0 -1
- package/dist/chunk-5KPNWT6X.js.map +0 -1
- package/dist/chunk-5PNMDJ7J.js.map +0 -1
- package/dist/chunk-6EEO3OVU.cjs.map +0 -1
- package/dist/chunk-7YSP4V4R.cjs +0 -69
- package/dist/chunk-7YSP4V4R.cjs.map +0 -1
- package/dist/chunk-A42GCBGX.cjs.map +0 -1
- package/dist/chunk-BVRDGYXQ.cjs.map +0 -1
- package/dist/chunk-BYPOGQWK.js.map +0 -1
- package/dist/chunk-CUHM5CWJ.cjs +0 -12
- package/dist/chunk-CUHM5CWJ.cjs.map +0 -1
- package/dist/chunk-DIQ3AV5W.cjs.map +0 -1
- package/dist/chunk-EXU3RASM.js.map +0 -1
- package/dist/chunk-IP3CGGPA.cjs.map +0 -1
- package/dist/chunk-IPSVVTWT.cjs +0 -1540
- package/dist/chunk-IPSVVTWT.cjs.map +0 -1
- package/dist/chunk-IXGYRP2P.js.map +0 -1
- package/dist/chunk-J4IUSYFF.js.map +0 -1
- package/dist/chunk-JBNOGRKW.cjs.map +0 -1
- package/dist/chunk-K3Q3LJY3.js.map +0 -1
- package/dist/chunk-KQJ54OG5.js.map +0 -1
- package/dist/chunk-L7HQ2OSI.js.map +0 -1
- package/dist/chunk-M6VES7V6.js +0 -239
- package/dist/chunk-M6VES7V6.js.map +0 -1
- package/dist/chunk-NBP2WTJW.cjs.map +0 -1
- package/dist/chunk-NUIG3BCV.cjs.map +0 -1
- package/dist/chunk-NXQFATMF.cjs.map +0 -1
- package/dist/chunk-OHMP6N2J.js +0 -47
- package/dist/chunk-OHMP6N2J.js.map +0 -1
- package/dist/chunk-QERAIDRJ.js.map +0 -1
- package/dist/chunk-QSXTWU4U.cjs +0 -12
- package/dist/chunk-RCVLFTCT.js.map +0 -1
- package/dist/chunk-TGOMW4MB.cjs.map +0 -1
- package/dist/chunk-TKT2XHED.js.map +0 -1
- package/dist/chunk-UGZUAYAR.js.map +0 -1
- package/dist/chunk-UXLSNRYL.js.map +0 -1
- package/dist/chunk-UYQMBBWJ.js.map +0 -1
- package/dist/chunk-VKGKDOKR.js.map +0 -1
- package/dist/chunk-VL2V6PEN.cjs +0 -261
- package/dist/chunk-VL2V6PEN.cjs.map +0 -1
- package/dist/chunk-WOJMKB3N.cjs.map +0 -1
- package/dist/chunk-WWFHO375.cjs.map +0 -1
- package/dist/chunk-XGPUQ56G.js.map +0 -1
- package/dist/chunk-XGU7DZDA.cjs +0 -1095
- package/dist/chunk-XGU7DZDA.cjs.map +0 -1
- package/dist/chunk-XPCZADMT.cjs.map +0 -1
- package/dist/chunk-XWV4JT34.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/types.ts","../src/indexes/auto-derive.ts","../src/core/define-graph.ts","../src/errors/validation.ts"],"names":["ValidationError","getEmbeddingIndex","isEmbeddingSchema","ConfigurationError"],"mappings":";;;;;;AAyCO,IAAM,eAAA,GAAkB;AAGxB,IAAM,eAAA,GAAkB;AAQ/B,SAAS,gBAAA,CAAiB,OAAe,IAAA,EAAoB;AAC3D,EAAA,IAAI,KAAA,CAAM,SAAS,CAAA,EAAG;AACpB,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,IAAIA,iCAAA;AAAA,IACR,GAAG,IAAI,CAAA,4BAAA,CAAA;AAAA,IACP;AAAA,MACE,MAAA,EAAQ;AAAA,QACN;AAAA,UACE,IAAA;AAAA,UACA,OAAA,EAAS;AAAA;AACX;AACF,KACF;AAAA,IACA;AAAA,MACE,UAAA,EACE;AAAA;AACJ,GACF;AACF;AAkFO,SAAS,SACd,KAAA,EACW;AACX,EAAA,gBAAA,CAAiB,OAAO,UA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ACA,MAAA,EACA,OAAA,EACiB;AACjB,EAAA,OAAO,IAAIA,kCAAgB,OAAA,EAAS;AAAA,IAClC,GAAI,OAAA,EAAS,UAAA,KAAe,MAAA,IAAa;AAAA,MACvC,YAAY,OAAA,CAAQ;AAAA,KACtB;AAAA,IACA,GAAI,OAAA,EAAS,IAAA,KAAS,UAAa,EAAE,IAAA,EAAM,QAAQ,IAAA,EAAK;AAAA,IACxD,GAAI,OAAA,EAAS,SAAA,KAAc,UAAa,EAAE,SAAA,EAAW,QAAQ,SAAA,EAAU;AAAA,IACvE,GAAI,OAAA,EAAS,EAAA,KAAO,UAAa,EAAE,EAAA,EAAI,QAAQ,EAAA,EAAG;AAAA,IAClD;AAAA,GACD,CAAA;AACH","file":"chunk-5KEQ74YU.cjs","sourcesContent":["import { type z } from \"zod\";\n\nimport { ValidationError } from \"../errors\";\n\n// ============================================================\n// Cross-cutting Discriminators\n// ============================================================\n\n/**\n * Which side of the bipartite graph a kind lives on. Used everywhere a\n * function takes \"the entity that owns a kind\" — error metadata,\n * extension classifiers, removal queues, schema diffs.\n */\nexport type KindEntity = \"node\" | \"edge\";\n\n/**\n * Which physical surface an index targets. Vector indexes don't own a\n * kind directly (they back a per-`(kind, field)` typed embedding table\n * owned by the active `VectorStrategy`), but they participate in the same\n * materialization and diff pipelines, so they share this discriminator.\n *\n * `\"system\"` marks TypeGraph's own base-relation indexes\n * (`SYSTEM_INDEX_DECLARATIONS`) — graph-independent, but materialized and\n * status-tracked through the same pipeline; their status rows carry the\n * relation key (e.g. `\"recordedNodes\"`) in the `kind` column.\n */\nexport type IndexEntity = \"node\" | \"edge\" | \"vector\" | \"system\";\n\n/**\n * Field-level null-check operations that round-trip through persisted\n * documents (unique-constraint where clauses, index where clauses,\n * graph-extension where clauses, IsNullPredicate). Consolidated so a\n * single rename or extension touches one site.\n */\nexport type NullCheckOp = \"isNull\" | \"isNotNull\";\n\n// ============================================================\n// Brand Keys for Nominal Typing\n// ============================================================\n\n/** Brand key for NodeType */\nexport const NODE_TYPE_BRAND = \"__nodeType\" as const;\n\n/** Brand key for EdgeType */\nexport const EDGE_TYPE_BRAND = \"__edgeType\" as const;\n\n/** Brand symbol for NodeId */\ndeclare const __nodeId: unique symbol;\n\n/** Brand symbol for EdgeId */\ndeclare const __edgeId: unique symbol;\n\nfunction assertNonEmptyId(value: string, path: string): void {\n if (value.length > 0) {\n return;\n }\n\n throw new ValidationError(\n `${path} must be a non-empty string.`,\n {\n issues: [\n {\n path,\n message: \"Expected a non-empty string.\",\n },\n ],\n },\n {\n suggestion:\n \"Use a persisted node or edge id value, or let TypeGraph generate an id on create.\",\n },\n );\n}\n\n// ============================================================\n// Node Type\n// ============================================================\n\n/**\n * Any JSON-serializable value.\n *\n * Mirrors the JSON wire format: primitives, arrays, and string-keyed objects.\n * `null` is included because the JSON spec requires it for \"no value here\";\n * this is the one place in the public API that uses `null` over `undefined`.\n */\nexport type JsonValue =\n | null\n | string\n | number\n | boolean\n | readonly JsonValue[]\n | Readonly<{ [key: string]: JsonValue }>;\n\n/**\n * Consumer-owned per-kind annotations.\n *\n * Stable labels attached to a node or edge kind at definition time — UI hints,\n * audit policy, provenance pointers, tooling annotations.\n *\n * **Consumer-owned, fully.** TypeGraph never reads, validates, or interprets\n * values in this field. Consumers own the entire namespace; there are no\n * reserved keys or extension prefixes. Future library-owned per-kind state,\n * if needed, will use a separate sibling field rather than carving out keys\n * here.\n *\n * **Annotations participate in schema hashing.** Any change to an annotation\n * value (or adding/removing an annotation key) bumps the canonical schema\n * hash and is reported as a `safe`-severity diff by `getSchemaChanges`. If\n * you don't want versioning for a piece of state, do not put it here.\n *\n * Values must be JSON-serializable — `bigint`, `function`, `symbol`, `undefined`,\n * `Date`, and other class instances are rejected at definition time so they can\n * never silently break schema hashing or storage round-trips.\n */\nexport type KindAnnotations = Readonly<Record<string, JsonValue>>;\n\n/**\n * A node type definition.\n *\n * Created via `defineNode()`. Represents a type of node in the graph\n * with an associated Zod schema for properties.\n */\nexport type NodeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n [NODE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n annotations: KindAnnotations | undefined;\n}>;\n\n/**\n * Branded node ID type.\n *\n * Prevents mixing IDs from different node types at compile time.\n */\nexport type NodeId<N extends NodeType> = string &\n Readonly<{\n [__nodeId]: N;\n }>;\n\n/**\n * Brands a non-empty string as a {@link NodeId}.\n *\n * Use this when a persisted node id has round-tripped through untyped storage\n * or an external boundary and must be passed back to read/update/delete\n * surfaces such as `getById`, `getByIds`, `update`, or `delete`.\n * Write surfaces that mint or claim ids, such as `create({ id })` and\n * `upsertById`, intentionally accept plain strings.\n *\n * @throws {ValidationError} when `value` is empty.\n */\nexport function asNodeId<N extends NodeType = NodeType>(\n value: string,\n): NodeId<N> {\n assertNonEmptyId(value, \"asNodeId\");\n return value as NodeId<N>;\n}\n\n/**\n * Infer the props type from a NodeType.\n */\nexport type NodeProps<N extends NodeType> = z.infer<N[\"schema\"]>;\n\n// ============================================================\n// Edge Type\n// ============================================================\n\n/**\n * An edge type definition.\n *\n * Created via `defineEdge()`. Represents a type of edge in the graph\n * with an optional Zod schema for properties.\n *\n * Optionally includes `from` and `to` arrays that define the allowed\n * source and target node types (domain and range constraints).\n */\nexport type EdgeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n From extends readonly NodeType[] | undefined = undefined,\n To extends readonly NodeType[] | undefined = undefined,\n> = Readonly<{\n [EDGE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n annotations: KindAnnotations | undefined;\n from: From;\n to: To;\n}>;\n\n/**\n * Base edge type for use in constraints - accepts any from/to configuration.\n */\nexport type AnyEdgeType = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[] | undefined,\n readonly NodeType[] | undefined\n>;\n\n/**\n * An edge type that has both from and to constraints defined.\n * Can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport type EdgeTypeWithEndpoints = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[],\n readonly NodeType[]\n>;\n\n/**\n * Branded edge ID type.\n *\n * Prevents mixing IDs from different edge types at compile time.\n */\nexport type EdgeId<E extends AnyEdgeType = AnyEdgeType> = string &\n Readonly<{\n [__edgeId]: E;\n }>;\n\n/**\n * Brands a non-empty string as an {@link EdgeId}.\n *\n * Use this when a persisted edge id has round-tripped through untyped storage\n * or an external boundary and must be passed back to read/update/delete\n * surfaces such as `getById`, `getByIds`, `update`, or `delete`.\n * Write surfaces that mint ids intentionally accept plain strings.\n *\n * @throws {ValidationError} when `value` is empty.\n */\nexport function asEdgeId<E extends AnyEdgeType = AnyEdgeType>(\n value: string,\n): EdgeId<E> {\n assertNonEmptyId(value, \"asEdgeId\");\n return value as EdgeId<E>;\n}\n\n/**\n * Infer the props type from an EdgeType.\n */\nexport type EdgeProps<E extends AnyEdgeType> = z.infer<E[\"schema\"]>;\n\n// ============================================================\n// Configuration Types\n// ============================================================\n\n/**\n * Delete behaviors for nodes.\n */\nexport type DeleteBehavior = \"restrict\" | \"cascade\" | \"disconnect\";\n\n/**\n * Edge cardinality constraints.\n */\nexport type Cardinality =\n | \"many\" // No constraint (default)\n | \"one\" // At most one edge of this kind from any source node\n | \"unique\" // At most one edge of this kind between any (source, target) pair\n | \"oneActive\"; // At most one edge with valid_to IS NULL from any source\n\n/**\n * Endpoint existence modes for edge validation.\n */\nexport type EndpointExistence =\n | \"notDeleted\" // Endpoint deleted_at IS NULL (default)\n | \"currentlyValid\" // Endpoint not deleted AND temporally valid\n | \"ever\"; // Endpoint exists in any state\n\n/**\n * Temporal query modes.\n */\nexport type TemporalMode =\n | \"current\" // Valid now AND not deleted\n | \"asOf\" // Valid at specific date AND not deleted\n | \"includeEnded\" // All validity periods AND not deleted\n | \"includeTombstones\"; // Everything including soft-deleted\n\n/**\n * Uniqueness constraint scope.\n */\nexport type UniquenessScope =\n | \"kind\" // Unique within this exact kind only\n | \"kindWithSubClasses\"; // Unique across this kind and all subclasses\n\n/**\n * Collation for uniqueness constraints.\n */\nexport type Collation = \"binary\" | \"caseInsensitive\";\n\n// ============================================================\n// Uniqueness Constraint\n// ============================================================\n\n/**\n * Uniqueness constraint definition.\n */\nexport type UniqueConstraint<\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n name: string;\n fields: readonly (keyof z.infer<S> & string)[];\n where?: (\n props: UniqueConstraintPredicateBuilder<S>,\n ) => UniqueConstraintPredicate;\n scope: UniquenessScope;\n collation: Collation;\n}>;\n\n/**\n * Predicate builder for uniqueness constraint where clause.\n * Uses -? to make all fields required in the builder, even if optional in the schema.\n */\ntype UniqueConstraintPredicateBuilder<S extends z.ZodObject<z.ZodRawShape>> =\n Readonly<{\n [K in keyof z.infer<S>]-?: UniqueConstraintField;\n }>;\n\n/**\n * Field operations for uniqueness constraint predicates.\n */\ntype UniqueConstraintField = Readonly<{\n isNull: () => UniqueConstraintPredicate;\n isNotNull: () => UniqueConstraintPredicate;\n}>;\n\n/**\n * A uniqueness constraint predicate (internal representation).\n */\ntype UniqueConstraintPredicate = Readonly<{\n __type: \"unique_predicate\";\n field: string;\n op: NullCheckOp;\n}>;\n\n// ============================================================\n// Node Registration\n// ============================================================\n\n/**\n * Node registration in a graph definition.\n */\nexport type NodeRegistration<N extends NodeType = NodeType> = Readonly<{\n type: N;\n unique?: readonly UniqueConstraint<N[\"schema\"]>[];\n onDelete?: DeleteBehavior;\n}>;\n\n// ============================================================\n// Edge Registration\n// ============================================================\n\n/**\n * Edge registration in a graph definition.\n */\nexport type EdgeRegistration<\n E extends AnyEdgeType = AnyEdgeType,\n FromTypes extends NodeType = NodeType,\n ToTypes extends NodeType = NodeType,\n> = Readonly<{\n type: E;\n from: readonly FromTypes[];\n to: readonly ToTypes[];\n cardinality?: Cardinality;\n endpointExistence?: EndpointExistence;\n}>;\n\n// ============================================================\n// Graph Defaults\n// ============================================================\n\n/**\n * Default settings for a graph.\n */\nexport type GraphDefaults = Readonly<{\n onNodeDelete?: DeleteBehavior;\n temporalMode?: TemporalMode;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Checks if a value is a NodeType.\n */\nexport function isNodeType(value: unknown): value is NodeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n NODE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[NODE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType.\n */\nexport function isEdgeType(value: unknown): value is AnyEdgeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n EDGE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[EDGE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType with both from and to constraints defined.\n * Such edges can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport function isEdgeTypeWithEndpoints(\n value: unknown,\n): value is EdgeTypeWithEndpoints {\n return (\n isEdgeType(value) &&\n Array.isArray(value.from) &&\n value.from.length > 0 &&\n Array.isArray(value.to) &&\n value.to.length > 0\n );\n}\n","/**\n * Auto-derive vector index declarations from `embedding()` brands on\n * node schemas.\n *\n * Walks each node's top-level Zod shape, finds fields wrapped in\n * `embedding(dimensions, opts)` (including `.optional()` /\n * `.nullable()` wrappers), and emits one `VectorIndexDeclaration` per\n * (kind, field) pair. The declaration carries the resolved index\n * configuration from the embedding brand — metric, indexType, HNSW /\n * IVFFlat params — so the materializer doesn't need to reach back into\n * the Zod schema.\n *\n * Auto-derivation is intentionally limited to TOP-LEVEL embedding\n * fields. Embeddings nested inside object properties are out of scope\n * for v1 — vector slots are materialized as flat `(kind, fieldPath)`\n * storage units, and top-level fields keep that contract explicit.\n *\n * Explicit `defineVectorIndex(node, fieldPath, opts)` declarations\n * passed via `defineGraph({ indexes })` take precedence — when an\n * explicit declaration matches the same (kind, fieldPath) as an\n * auto-derived one, the explicit version wins. This lets consumers\n * override defaults without losing auto-derivation for other fields.\n */\n\nimport { type z } from \"zod\";\n\nimport {\n getEmbeddingIndex,\n isEmbeddingSchema,\n type ResolvedEmbeddingIndex,\n} from \"../core/embedding\";\nimport { type NodeRegistration } from \"../core/types\";\nimport { type IndexDeclaration, type VectorIndexDeclaration } from \"./types\";\n\n/**\n * Auto-derive vector index declarations from embedding brands on a\n * map of node registrations. Returns one declaration per\n * (kind, top-level field) pair. Empty array when no embeddings found.\n *\n * Cross-graph status-table disambiguation does NOT happen here — the\n * declaration name stays clean (`tg_vec_{kind}_{field}_{metric}`) so\n * `pg_indexes` and result-entry inspection are readable. The\n * materializer composes a graph-scoped key (`${graphId}::${name}`)\n * for status-table identity, applied uniformly to both auto-derived\n * and explicit `VectorIndexDeclaration` entries — see\n * `vectorStatusKey` in `store/materialize-indexes.ts`. This keeps\n * the disambiguation rule in one place that BOTH paths go through,\n * rather than depending on the auto-derive caller to produce a\n * graph-scoped name.\n */\nexport function autoDeriveVectorIndexes(\n nodes: Record<string, NodeRegistration>,\n): readonly VectorIndexDeclaration[] {\n const out: VectorIndexDeclaration[] = [];\n for (const registration of Object.values(nodes)) {\n const node = registration.type;\n const shape = readObjectShape(node.schema);\n if (shape === undefined) continue;\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n const config = readEmbeddingIndex(fieldSchema);\n if (config === undefined) continue;\n const dimensions = readEmbeddingDimensions(fieldSchema);\n if (dimensions === undefined) continue;\n out.push(buildAutoDerived(node.kind, fieldName, dimensions, config));\n }\n }\n return out;\n}\n\n/**\n * Merge auto-derived declarations with explicit ones, preferring\n * explicit on (kind, fieldPath) collisions. Returns a flat list of all\n * indexes; non-vector entries from `explicit` pass through unchanged.\n */\nexport function mergeVectorIndexes(\n explicit: readonly IndexDeclaration[],\n autoDerived: readonly VectorIndexDeclaration[],\n): readonly IndexDeclaration[] {\n if (autoDerived.length === 0) return explicit;\n const explicitVectorKeys = new Set<string>();\n for (const declaration of explicit) {\n if (declaration.entity === \"vector\") {\n explicitVectorKeys.add(`${declaration.kind}|${declaration.fieldPath}`);\n }\n }\n const filteredAuto = autoDerived.filter(\n (entry) => !explicitVectorKeys.has(`${entry.kind}|${entry.fieldPath}`),\n );\n return [...explicit, ...filteredAuto];\n}\n\n/**\n * Generate the deterministic vector index name. The visible prefix\n * `tg_vec_<kind>_<field>_<metric>` keeps it scannable in result-entry\n * inspection and the `typegraph_index_materializations` table.\n *\n * Cross-graph disambiguation is handled separately at the\n * materialization boundary (see `vectorStatusKey`) so the declaration\n * name doesn't need to carry `graphId` — the same auto-derived name\n * is reusable across graphs and the materializer composes a\n * graph-scoped status key for both auto-derived and explicit entries\n * uniformly.\n */\nfunction buildAutoDerived(\n kind: string,\n fieldName: string,\n dimensions: number,\n config: ResolvedEmbeddingIndex,\n): VectorIndexDeclaration {\n const fieldPath = fieldName;\n return Object.freeze({\n entity: \"vector\" as const,\n name: `tg_vec_${sanitize(kind)}_${sanitize(fieldName)}_${config.metric}`,\n kind,\n fieldPath,\n dimensions,\n metric: config.metric,\n indexType: config.indexType,\n indexParams: Object.freeze({\n m: config.m,\n efConstruction: config.efConstruction,\n lists: config.lists,\n }),\n });\n}\n\nfunction sanitize(value: string): string {\n return value.replaceAll(/[^a-zA-Z0-9]/g, \"_\").toLowerCase();\n}\n\nfunction readObjectShape(\n schema: z.ZodType,\n): Record<string, z.ZodType> | undefined {\n if ((schema as { type?: string }).type !== \"object\") return undefined;\n const shape = (schema.def as { shape?: Record<string, z.ZodType> }).shape;\n return shape;\n}\n\nfunction readEmbeddingIndex(\n schema: z.ZodType,\n): ResolvedEmbeddingIndex | undefined {\n for (const candidate of unwrapChain(schema)) {\n const config = getEmbeddingIndex(candidate);\n if (config !== undefined) return config;\n }\n return undefined;\n}\n\nfunction readEmbeddingDimensions(schema: z.ZodType): number | undefined {\n for (const candidate of unwrapChain(schema)) {\n if (isEmbeddingSchema(candidate)) {\n return (candidate as unknown as Record<string, number>)\n ._embeddingDimensions;\n }\n }\n return undefined;\n}\n\n/**\n * Yield the schema and every reachable inner schema by repeatedly\n * applying `.unwrap()` (Zod 4 optional/nullable/default) and\n * `.def.innerType` (some wrappers). Cycle-guarded by depth and\n * reference identity. Generators stop at the first non-unwrappable\n * schema OR after 8 levels — deeper wrapping is pathological and not\n * worth supporting.\n */\nfunction* unwrapChain(schema: z.ZodType): Generator<z.ZodType, void, void> {\n const seen = new Set<z.ZodType>();\n let current: z.ZodType | undefined = schema;\n let depth = 0;\n while (current !== undefined && !seen.has(current) && depth < 8) {\n seen.add(current);\n yield current;\n current = unwrapOnce(current);\n depth++;\n }\n}\n\nfunction unwrapOnce(schema: z.ZodType): z.ZodType | undefined {\n // Zod 4 wrappers expose `.unwrap()` on optional/nullable/default.\n const candidate = schema as unknown as { unwrap?: () => z.ZodType };\n if (typeof candidate.unwrap === \"function\") return candidate.unwrap();\n // Some wrappers expose the inner schema via `.def.innerType`.\n return (schema as unknown as { def?: { innerType?: z.ZodType } }).def\n ?.innerType;\n}\n","import { ConfigurationError } from \"../errors/index\";\nimport { type GraphExtension } from \"../graph-extension/extension-types\";\nimport {\n autoDeriveVectorIndexes,\n mergeVectorIndexes,\n} from \"../indexes/auto-derive\";\nimport { type IndexDeclaration } from \"../indexes/types\";\nimport { type OntologyRelation } from \"../ontology/types\";\nimport {\n type AnyEdgeType,\n type DeleteBehavior,\n type EdgeRegistration,\n type EdgeTypeWithEndpoints,\n type GraphDefaults,\n isEdgeType,\n isEdgeTypeWithEndpoints,\n type KindEntity,\n type NodeRegistration,\n type NodeType,\n type TemporalMode,\n} from \"./types\";\n\n// ============================================================\n// Graph Definition Brand Symbol\n// ============================================================\n\n/** Brand key for GraphDef */\nconst GRAPH_DEF_BRAND = \"__graphDef\" as const;\n\n// ============================================================\n// Edge Entry Types\n// ============================================================\n\n/**\n * An edge entry in the graph definition.\n * Can be:\n * - EdgeType directly (constrained or unconstrained)\n * - EdgeRegistration object (always works, can override/narrow defaults)\n */\ntype EdgeEntry = EdgeRegistration | AnyEdgeType;\n\n/**\n * Normalized edge map type - all entries become EdgeRegistration.\n * For bare EdgeTypes, constrained endpoints are extracted from the type;\n * unconstrained edges fall back to all node types in the graph.\n */\ntype NormalizedEdges<\n TNodes extends Record<string, NodeRegistration>,\n TEdges extends Record<string, EdgeEntry>,\n> = {\n [K in keyof TEdges]: TEdges[K] extends EdgeRegistration ? TEdges[K]\n : TEdges[K] extends AnyEdgeType ?\n EdgeRegistration<\n TEdges[K],\n TEdges[K][\"from\"] extends readonly (infer N extends NodeType)[] ? N\n : TNodes[keyof TNodes][\"type\"],\n TEdges[K][\"to\"] extends readonly (infer N extends NodeType)[] ? N\n : TNodes[keyof TNodes][\"type\"]\n >\n : never;\n};\n\n// ============================================================\n// Edge Normalization Functions\n// ============================================================\n\n/**\n * Validates that an EdgeRegistration's constraints don't widen beyond\n * the edge type's built-in domain/range constraints.\n */\nfunction validateConstraintNarrowing(\n name: string,\n edgeType: EdgeTypeWithEndpoints,\n registration: EdgeRegistration,\n): void {\n const builtInFromNames = new Set(edgeType.from.map((node) => node.kind));\n for (const fromNode of registration.from) {\n if (!builtInFromNames.has(fromNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'from' kind \"${fromNode.kind}\" ` +\n `not in edge's built-in domain: [${[...builtInFromNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidFrom: fromNode.kind,\n allowedFrom: [...builtInFromNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n\n const builtInToNames = new Set(edgeType.to.map((node) => node.kind));\n for (const toNode of registration.to) {\n if (!builtInToNames.has(toNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'to' kind \"${toNode.kind}\" ` +\n `not in edge's built-in range: [${[...builtInToNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidTo: toNode.kind,\n allowedTo: [...builtInToNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n}\n\n/**\n * Normalizes a single edge entry to EdgeRegistration.\n */\nfunction normalizeEdgeEntry(\n name: string,\n entry: EdgeEntry,\n allNodeTypes: readonly NodeType[],\n): EdgeRegistration {\n if (isEdgeType(entry)) {\n if (isEdgeTypeWithEndpoints(entry)) {\n // EdgeType with from/to — convert to EdgeRegistration\n return { type: entry, from: entry.from, to: entry.to };\n }\n // Unconstrained EdgeType — allow any→any\n return { type: entry, from: allNodeTypes, to: allNodeTypes };\n }\n\n // Already EdgeRegistration — validate narrowing if edge has built-in constraints\n if (isEdgeTypeWithEndpoints(entry.type)) {\n validateConstraintNarrowing(name, entry.type, entry);\n }\n\n return entry;\n}\n\n/**\n * Normalizes all edge entries to EdgeRegistration.\n */\nfunction normalizeEdges(\n edges: Record<string, EdgeEntry>,\n allNodeTypes: readonly NodeType[],\n): Record<string, EdgeRegistration> {\n const result: Record<string, EdgeRegistration> = {};\n for (const [name, entry] of Object.entries(edges)) {\n result[name] = normalizeEdgeEntry(name, entry, allNodeTypes);\n }\n return result;\n}\n\n// ============================================================\n// Graph Definition Configuration\n// ============================================================\n\n/**\n * Configuration for defineGraph.\n */\ntype GraphDefConfig<\n TNodes extends Record<string, NodeRegistration>,\n TEdges extends Record<string, EdgeEntry>,\n TOntology extends readonly OntologyRelation[],\n> = Readonly<{\n /** Unique identifier for this graph */\n id: string;\n /** Node registrations */\n nodes: TNodes;\n /** Edge registrations or EdgeTypes with built-in domain/range */\n edges: TEdges;\n /** Ontology relations */\n ontology?: TOntology;\n /** Graph-wide defaults */\n defaults?: GraphDefaults;\n /**\n * Index declarations attached to this graph.\n *\n * Accepts the outputs of `defineNodeIndex` / `defineEdgeIndex` (which\n * already return `IndexDeclaration` values) or pre-built declarations\n * reconstructed from a stored schema or graph extension.\n *\n * Validated at definition time: every index must reference a `kind`\n * that exists in `nodes` / `edges`, and index `name`s must be unique\n * within the graph.\n *\n * Index DDL is **not** generated by `defineGraph`. Indexes flow into\n * `SerializedSchema.indexes` so they can later be materialized via\n * `store.materializeIndexes()` — lifting the storage concern out of\n * the schema-version commit path.\n */\n indexes?: readonly IndexDeclaration[];\n}>;\n\n// ============================================================\n// Graph Definition Type\n// ============================================================\n\n/**\n * A graph definition.\n *\n * This is a compile-time artifact that describes the structure of a graph.\n * Use `createStore()` to create a runtime store from this definition.\n */\nexport type GraphDef<\n TNodes extends Record<string, NodeRegistration> = Record<\n string,\n NodeRegistration\n >,\n TEdges extends Record<string, EdgeRegistration> = Record<\n string,\n EdgeRegistration\n >,\n TOntology extends readonly OntologyRelation[] = readonly OntologyRelation[],\n> = Readonly<{\n [GRAPH_DEF_BRAND]: true;\n id: string;\n nodes: TNodes;\n edges: TEdges;\n ontology: TOntology;\n defaults: Readonly<{\n onNodeDelete: DeleteBehavior;\n temporalMode: TemporalMode;\n }>;\n /**\n * Index declarations attached to this graph. Preserves whatever the\n * caller passed to `defineGraph` (including an explicit empty array)\n * for introspection purposes.\n *\n * The serialized canonical form is order-canonicalized (sorted by\n * `name`) and treats `undefined` and `[]` as the same \"no slice\" form\n * — an empty array does not bump the schema hash, since indexes are\n * an unordered set keyed by name and `[]` carries no semantic meaning\n * that an absent slice doesn't.\n */\n indexes: readonly IndexDeclaration[] | undefined;\n /**\n * Graph extension this graph was merged with, if any. Set by\n * `mergeGraphExtension`; never set by `defineGraph` directly.\n * Exists solely so re-serialization is stable — the rest of the\n * system reads the merged kinds through `nodes` / `edges` /\n * `ontology` and never inspects this field. Absent on graphs that\n * have never been extended; legacy graphs hash byte-identically.\n */\n extension: GraphExtension | undefined;\n /**\n * Soft-deprecated kind names attached to this graph. Set by the\n * loader from the persisted schema and by `store.deprecateKinds(...)`\n * / `store.undeprecateKinds(...)`. A purely informational signal\n * surfaced for introspection — does not gate reads, writes, or\n * queries. Defaults to the empty set on freshly-defined graphs.\n */\n deprecatedKinds: ReadonlySet<string>;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Extract node kind names from a GraphDef.\n */\nexport type NodeKinds<G extends GraphDef> = keyof G[\"nodes\"] & string;\n\n/**\n * Extract edge kind names from a GraphDef.\n */\nexport type EdgeKinds<G extends GraphDef> = keyof G[\"edges\"] & string;\n\n/**\n * Get a NodeType from a GraphDef by kind name.\n */\nexport type GetNodeType<\n G extends GraphDef,\n K extends NodeKinds<G>,\n> = G[\"nodes\"][K][\"type\"];\n\n/**\n * Get an EdgeType from a GraphDef by kind name.\n */\nexport type GetEdgeType<\n G extends GraphDef,\n K extends EdgeKinds<G>,\n> = G[\"edges\"][K][\"type\"];\n\n/**\n * Get all NodeTypes from a GraphDef.\n */\nexport type AllNodeTypes<G extends GraphDef> = {\n [K in NodeKinds<G>]: G[\"nodes\"][K][\"type\"];\n}[NodeKinds<G>];\n\n/**\n * Get all EdgeTypes from a GraphDef.\n */\nexport type AllEdgeTypes<G extends GraphDef> = {\n [K in EdgeKinds<G>]: G[\"edges\"][K][\"type\"];\n}[EdgeKinds<G>];\n\n// ============================================================\n// Define Graph Function\n// ============================================================\n\n/**\n * Creates a graph definition.\n *\n * @example\n * ```typescript\n * const graph = defineGraph({\n * id: \"my_graph\",\n * nodes: {\n * Person: { type: Person },\n * Company: { type: Company },\n * },\n * edges: {\n * // Traditional EdgeRegistration syntax\n * worksAt: {\n * type: worksAt,\n * from: [Person],\n * to: [Company],\n * cardinality: \"many\",\n * },\n * // Or use EdgeType directly if it has from/to defined\n * knows, // EdgeType with built-in domain/range\n * },\n * ontology: [\n * subClassOf(Company, Organization),\n * disjointWith(Person, Organization),\n * ],\n * defaults: {\n * onNodeDelete: \"restrict\",\n * temporalMode: \"current\",\n * },\n * });\n * ```\n */\nexport function defineGraph<\n const TNodes extends Record<string, NodeRegistration<NodeType>>,\n const TEdges extends Record<string, EdgeEntry>,\n const TOntology extends readonly OntologyRelation[],\n>(\n config: GraphDefConfig<TNodes, TEdges, TOntology>,\n): GraphDef<TNodes, NormalizedEdges<TNodes, TEdges>, TOntology> {\n const defaults = {\n onNodeDelete: config.defaults?.onNodeDelete ?? \"restrict\",\n temporalMode: config.defaults?.temporalMode ?? \"current\",\n } as const;\n\n const allNodeTypes = Object.values(config.nodes).map((reg) => reg.type);\n const normalizedEdges = normalizeEdges(config.edges, allNodeTypes);\n // Vector indexes are auto-derived from `embedding()` brands on node\n // schemas (see `autoDeriveVectorIndexes`). Explicit declarations\n // passed via `defineGraph({ indexes })` win on (kind, fieldPath)\n // collisions so consumers can override defaults — see\n // `mergeVectorIndexes`. The merged list flows through\n // `normalizeIndexes` for the standard kind-registered + unique-name\n // checks.\n //\n // Preservation rule: if the consumer never passed `indexes` at all\n // AND no embedding brands exist, leave `graph.indexes` undefined to\n // keep the introspection surface stable for legacy graphs. If the\n // consumer passed an explicit `[]`, surface it as `[]` (not\n // `undefined`) to match the contract pinned by the\n // \"preserves an explicit empty indexes array\" test.\n const autoVectorIndexes = autoDeriveVectorIndexes(config.nodes);\n const explicitProvided = config.indexes !== undefined;\n const mergedIndexes = mergeVectorIndexes(\n config.indexes ?? [],\n autoVectorIndexes,\n );\n const indexes =\n !explicitProvided && mergedIndexes.length === 0 ?\n undefined\n : normalizeIndexes(mergedIndexes, config.nodes, normalizedEdges);\n\n return Object.freeze({\n [GRAPH_DEF_BRAND]: true as const,\n id: config.id,\n nodes: config.nodes,\n edges: normalizedEdges,\n ontology: config.ontology ?? ([] as unknown as TOntology),\n defaults,\n indexes,\n extension: undefined,\n deprecatedKinds: EMPTY_DEPRECATED_KINDS,\n }) as GraphDef<TNodes, NormalizedEdges<TNodes, TEdges>, TOntology>;\n}\n\n// Sharing one frozen empty Set keeps the canonical-form hash stable\n// across graphs that never deprecate any kinds.\nconst EMPTY_DEPRECATED_KINDS: ReadonlySet<string> = Object.freeze(\n new Set<string>(),\n);\n\n// ============================================================\n// Index Normalization\n// ============================================================\n\n/**\n * Validates the `indexes` config slice:\n *\n * - Every index references a kind that exists in the graph's `nodes`\n * (for node indexes) or `edges` (for edge indexes).\n * - Index `name`s are unique within the graph.\n */\nfunction normalizeIndexes(\n inputs: readonly IndexDeclaration[],\n nodes: Record<string, NodeRegistration>,\n edges: Record<string, EdgeRegistration>,\n): readonly IndexDeclaration[] {\n if (inputs.length === 0) {\n return [];\n }\n\n const nodeKinds = collectKinds(nodes);\n const edgeKinds = collectKinds(edges);\n const seenNames = new Set<string>();\n\n for (const declaration of inputs) {\n if (declaration.entity === \"node\" || declaration.entity === \"vector\") {\n // Vector indexes attach to node kinds (the embedding lives on a\n // node field). Validation reuses the node-kind check.\n assertKindRegistered(declaration, nodeKinds, \"node\");\n } else {\n assertKindRegistered(declaration, edgeKinds, \"edge\");\n }\n\n if (seenNames.has(declaration.name)) {\n throw new ConfigurationError(\n `Duplicate index name \"${declaration.name}\" in defineGraph({ indexes }). ` +\n `Index names must be unique within a graph.`,\n { indexName: declaration.name },\n {\n suggestion: `Pass an explicit { name: \"...\" } to disambiguate.`,\n },\n );\n }\n seenNames.add(declaration.name);\n }\n\n return inputs;\n}\n\nfunction collectKinds(\n registrations: Record<string, { type: { kind: string } }>,\n): ReadonlySet<string> {\n const kinds = new Set<string>();\n for (const registration of Object.values(registrations)) {\n kinds.add(registration.type.kind);\n }\n return kinds;\n}\n\nfunction assertKindRegistered(\n declaration: IndexDeclaration,\n registeredKinds: ReadonlySet<string>,\n entity: KindEntity,\n): void {\n if (registeredKinds.has(declaration.kind)) return;\n\n const slot = entity === \"node\" ? \"nodes\" : \"edges\";\n const suggestion =\n entity === \"node\" ?\n `Add { ${declaration.kind}: { type: ${declaration.kind} } } to defineGraph({ nodes }) ` +\n `or remove the index from \"indexes\".`\n : `Register the edge in defineGraph({ edges }) or remove the index from \"indexes\".`;\n\n throw new ConfigurationError(\n `Index \"${declaration.name}\" references ${entity} kind \"${declaration.kind}\" ` +\n `which is not registered in this graph's \"${slot}\".`,\n {\n indexName: declaration.name,\n referencedKind: declaration.kind,\n availableKinds: [...registeredKinds],\n },\n { suggestion },\n );\n}\n\n// ============================================================\n// Graph Definition Utilities\n// ============================================================\n\n/**\n * Checks if a value is a GraphDef.\n */\nexport function isGraphDef(value: unknown): value is GraphDef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n GRAPH_DEF_BRAND in value &&\n (value as Record<string, unknown>)[GRAPH_DEF_BRAND] === true\n );\n}\n\n/**\n * Gets all node kind names from a GraphDef.\n */\nexport function getNodeKinds<G extends GraphDef>(\n graph: G,\n): readonly (keyof G[\"nodes\"] & string)[] {\n return Object.keys(graph.nodes);\n}\n\n/**\n * Gets all edge kind names from a GraphDef.\n */\nexport function getEdgeKinds<G extends GraphDef>(\n graph: G,\n): readonly (keyof G[\"edges\"] & string)[] {\n return Object.keys(graph.edges);\n}\n\n/**\n * Returns true when `name` is registered as either a node or edge kind\n * on the given graph.\n */\nexport function isKnownKind(graph: GraphDef, name: string): boolean {\n return Object.hasOwn(graph.nodes, name) || Object.hasOwn(graph.edges, name);\n}\n","/**\n * Contextual Validation Utilities\n *\n * Provides Zod validation wrappers that include full context about\n * which entity (node/edge) and operation (create/update) failed.\n *\n * @example\n * ```typescript\n * const props = validateNodeProps(schema, input, {\n * kind: \"Person\",\n * operation: \"create\",\n * });\n * ```\n */\n\nimport { type ZodError, type ZodType } from \"zod\";\n\nimport type { KindEntity } from \"../core/types\";\nimport { ValidationError, type ValidationIssue } from \"./index\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Context for validation operations.\n */\nexport type ValidationContext = 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 (for updates) */\n id?: string;\n}>;\n\n// ============================================================\n// Validation Functions\n// ============================================================\n\n/**\n * Converts Zod issues to ValidationIssue format.\n */\nfunction zodIssuesToValidationIssues(error: ZodError): ValidationIssue[] {\n return error.issues.map((issue) => ({\n path: issue.path.join(\".\"),\n message: issue.message,\n code: issue.code,\n }));\n}\n\n/**\n * Builds a descriptive location string for error messages.\n */\nfunction buildLocationString(context: ValidationContext): string {\n if (context.id) {\n return `${context.kind}/${context.id}`;\n }\n return `new ${context.kind}`;\n}\n\n/**\n * Validates props with full context for error messages.\n *\n * @param schema - Zod schema to validate against\n * @param props - Properties to validate\n * @param context - Context about the entity and operation\n * @returns Validated and transformed props\n * @throws ValidationError with full context if validation fails\n *\n * @example\n * ```typescript\n * const validatedProps = validateProps(personSchema, input, {\n * entityType: \"node\",\n * kind: \"Person\",\n * operation: \"create\",\n * });\n * ```\n */\nexport function validateProps<T>(\n schema: ZodType<T>,\n props: unknown,\n context: ValidationContext,\n): T {\n const result = schema.safeParse(props);\n\n if (result.success) {\n return result.data;\n }\n\n const issues = zodIssuesToValidationIssues(result.error);\n const location = buildLocationString(context);\n\n throw new ValidationError(\n `Invalid ${context.entityType} props for ${location}: ${result.error.message}`,\n {\n entityType: context.entityType,\n kind: context.kind,\n operation: context.operation,\n ...(context.id !== undefined && { id: context.id }),\n issues,\n },\n { cause: result.error },\n );\n}\n\n/**\n * Validates node props with full context.\n *\n * Convenience wrapper around validateProps for node operations.\n *\n * @example\n * ```typescript\n * const props = validateNodeProps(schema, input, {\n * kind: \"Person\",\n * operation: \"create\",\n * });\n * ```\n */\nexport function validateNodeProps<T>(\n schema: ZodType<T>,\n props: unknown,\n context: Readonly<{\n kind: string;\n operation: \"create\" | \"update\";\n id?: string;\n }>,\n): T {\n return validateProps(schema, props, {\n entityType: \"node\",\n ...context,\n });\n}\n\n/**\n * Validates edge props with full context.\n *\n * Convenience wrapper around validateProps for edge operations.\n *\n * @example\n * ```typescript\n * const props = validateEdgeProps(schema, input, {\n * kind: \"worksAt\",\n * operation: \"create\",\n * });\n * ```\n */\nexport function validateEdgeProps<T>(\n schema: ZodType<T>,\n props: unknown,\n context: Readonly<{\n kind: string;\n operation: \"create\" | \"update\";\n id?: string;\n }>,\n): T {\n return validateProps(schema, props, {\n entityType: \"edge\",\n ...context,\n });\n}\n\n/**\n * Wraps a Zod error with TypeGraph context.\n *\n * Use this when you've already caught a ZodError and want to\n * convert it to a ValidationError with context.\n *\n * @example\n * ```typescript\n * try {\n * schema.parse(input);\n * } catch (error) {\n * if (error instanceof ZodError) {\n * throw wrapZodError(error, {\n * entityType: \"node\",\n * kind: \"Person\",\n * operation: \"create\",\n * });\n * }\n * throw error;\n * }\n * ```\n */\nexport function wrapZodError(\n error: ZodError,\n context: ValidationContext,\n): ValidationError {\n const issues = zodIssuesToValidationIssues(error);\n const location = buildLocationString(context);\n\n return new ValidationError(\n `Validation failed for ${context.entityType} ${location}: ${error.message}`,\n {\n entityType: context.entityType,\n kind: context.kind,\n operation: context.operation,\n ...(context.id !== undefined && { id: context.id }),\n issues,\n },\n { cause: error },\n );\n}\n\n/**\n * Creates a simple ValidationError without Zod context.\n *\n * Use this for custom validation rules that aren't part of a Zod schema.\n *\n * @example\n * ```typescript\n * if (startDate > endDate) {\n * throw createValidationError(\n * \"Start date must be before end date\",\n * [{ path: \"startDate\", message: \"Must be before endDate\" }],\n * { entityType: \"edge\", kind: \"employment\", operation: \"create\" }\n * );\n * }\n * ```\n */\nexport function createValidationError(\n message: string,\n issues: ValidationIssue[],\n context?: Partial<ValidationContext>,\n): ValidationError {\n return new ValidationError(message, {\n ...(context?.entityType !== undefined && {\n entityType: context.entityType,\n }),\n ...(context?.kind !== undefined && { kind: context.kind }),\n ...(context?.operation !== undefined && { operation: context.operation }),\n ...(context?.id !== undefined && { id: context.id }),\n issues,\n });\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/backend/drizzle/columns/vector.ts","../src/query/dialect/vector/pgvector-strategy.ts"],"names":[],"mappings":";;;;;;AA0CsB,UAAA,CAInB;AAAA,EACD,SAAS,MAAA,EAAQ;AAEf,IAAA,OAAO,MAAA,EAAQ,UAAA,GAAa,CAAA,OAAA,EAAU,MAAA,CAAO,UAAU,CAAA,CAAA,CAAA,GAAM,QAAA;AAAA,EAC/D,CAAA;AAAA,EAEA,SAAS,KAAA,EAAyB;AAEhC,IAAA,OAAO,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AA,CAAK,SAAA;AAChC,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,+BAAA,EAAkC,MAAA,CAAO,WAAW,CAAC,CAAA,CAAE,CAAA;AAAA,IACzE;AAAA;AAEJ","file":"chunk-5KPNWT6X.js","sourcesContent":["/**\n * Custom Drizzle column type for pgvector's VECTOR type.\n *\n * Provides native support for PostgreSQL vector embeddings without\n * requiring runtime casts in queries.\n *\n * @example\n * ```typescript\n * import { pgTable, text, integer } from \"drizzle-orm/pg-core\";\n * import { vector } from \"./columns/vector\";\n *\n * const embeddings = pgTable(\"embeddings\", {\n * id: text(\"id\").primaryKey(),\n * embedding: vector(\"embedding\"),\n * dimensions: integer(\"dimensions\"),\n * });\n * ```\n */\nimport { customType } from \"drizzle-orm/pg-core\";\n\n/**\n * PostgreSQL vector column type for pgvector extension.\n *\n * Stores embeddings as native VECTOR type, enabling efficient\n * similarity search without runtime casts.\n *\n * The column type is unparameterized (`VECTOR` not `VECTOR(N)`)\n * to support multiple embedding dimensions in a single table.\n * Dimension validation is handled at the application level.\n *\n * @example\n * ```typescript\n * // In table definition\n * embedding: vector(\"embedding\").notNull(),\n *\n * // In queries - no cast needed\n * db.execute(sql`\n * SELECT * FROM embeddings\n * WHERE embedding <=> ${formatVector([0.1, 0.2, 0.3])} < 0.5\n * `);\n * ```\n */\nexport const vector = customType<{\n data: number[];\n driverData: string;\n config: { dimensions?: number };\n}>({\n dataType(config) {\n // Use parameterized type if dimensions specified, otherwise unparameterized\n return config?.dimensions ? `vector(${config.dimensions})` : \"vector\";\n },\n\n toDriver(value: number[]): string {\n // Format as pgvector literal: [1.0,2.0,3.0]\n return `[${value.join(\",\")}]`;\n },\n\n fromDriver(value: string): number[] {\n // pgvector returns '[1,2,3]' format\n // Handle both string and already-parsed array (some drivers differ)\n if (Array.isArray(value)) {\n return value as number[];\n }\n // Parse the string representation\n const content = value.slice(1, -1); // Remove [ and ]\n if (content === \"\") {\n return [];\n }\n return content.split(\",\").map((s) => Number.parseFloat(s.trim()));\n },\n});\n\n/**\n * Formats a number array as a pgvector literal string.\n *\n * Use this when building raw SQL queries with embeddings.\n *\n * @example\n * ```typescript\n * const embedding = [0.1, 0.2, 0.3];\n * db.execute(sql`\n * SELECT * FROM embeddings\n * WHERE embedding <=> ${formatVector(embedding)}::vector < 0.5\n * `);\n * ```\n */\nexport function formatVector(embedding: readonly number[]): string {\n return `[${embedding.join(\",\")}]`;\n}\n","/**\n * pgvector strategy.\n *\n * Postgres' pgvector extension is the one engine where the *same* SQL serves\n * brute-force and ANN: `ORDER BY embedding <=> q LIMIT k` scans sequentially\n * with no index and is rewritten to an HNSW/IVFFlat scan the moment a matching\n * index exists — the planner picks it up automatically. So `buildSearch` never\n * branches on `slot.indexType`; it emits one relevance scan and lets Postgres\n * decide. (Contrast libSQL/sqlite-vec, whose ANN needs distinct syntax.)\n *\n * Storage is per-`(nodeKind, fieldPath)`: a `vector(N)` column carrying the\n * field's fixed dimension `N`, with the operator-class-typed ANN index folded\n * into the same table contribution so materialization builds table + index\n * together. The typed column means the index does not need the legacy\n * `::vector(N)` cast-in-index escape hatch the old shared table relied on.\n *\n * Metric support is the full pgvector set — `cosine`, `l2`, `inner_product` —\n * advertised as data on `capabilities`, mirroring `vector_cosine_ops` /\n * `vector_l2_ops` / `vector_ip_ops` and the `<=>` / `<->` / `<#>` operators.\n *\n * Mirrors the `libsqlVectorStrategy` / `sqliteVecStrategy` structure while\n * letting Postgres' planner pick the ANN index when one exists.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport { formatVector } from \"../../../backend/drizzle/columns/vector\";\nimport { quotedTableName } from \"../../../backend/drizzle/operations/shared\";\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 {\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 prefixes for the per-field table and its ANN index. */\nconst TABLE_PREFIX = \"tg_vec\";\nconst INDEX_PREFIX = \"tg_vecidx\";\n\n/**\n * pgvector defines `hnsw.ef_search` as an integer GUC with a valid range\n * of 1..1000; `SET hnsw.ef_search = 1001` errors at the server. The\n * backend validates a per-search `efSearch` against this ceiling before\n * inlining it into `SET LOCAL`, surfacing a clear message instead of a raw\n * pgvector error.\n */\nexport const MAX_HNSW_EF_SEARCH = 1000;\n\n/**\n * Validates a per-search `efSearch` override against pgvector's\n * `hnsw.ef_search` valid range. `undefined` (no override) is accepted.\n */\nexport function assertPgvectorEfSearch(efSearch?: number): void {\n if (efSearch === undefined) return;\n if (!Number.isInteger(efSearch) || efSearch <= 0) {\n throw new Error(`efSearch must be a positive integer, got: ${efSearch}`);\n }\n if (efSearch > MAX_HNSW_EF_SEARCH) {\n throw new RangeError(\n `efSearch must be ≤ ${MAX_HNSW_EF_SEARCH} (pgvector's hnsw.ef_search ` +\n `valid range is 1..${MAX_HNSW_EF_SEARCH}), got: ${efSearch}`,\n );\n }\n}\n\n/**\n * pgvector's `vector` type caps at 16,000 dimensions for a stored column\n * (2,000 for an indexed column, but the column-type ceiling is what governs\n * storage; recall degradation beyond 2,000 is a tuning concern, not a hard\n * limit advertised here).\n */\nconst PGVECTOR_MAX_DIMENSIONS = 16_000;\n\n/** Default HNSW `m` (max connections per layer) — pgvector's own default. */\nconst DEFAULT_HNSW_M = 16;\n/** Default HNSW `ef_construction` (build candidate list) — pgvector's own default. */\nconst DEFAULT_HNSW_EF_CONSTRUCTION = 64;\n/** Default IVFFlat `lists` (inverted lists) — pgvector's own default. */\nconst DEFAULT_IVFFLAT_LISTS = 100;\n\nconst PGVECTOR_CAPABILITIES: VectorCapabilities = {\n supported: true,\n metrics: [\"cosine\", \"l2\", \"inner_product\"],\n indexTypes: [\"hnsw\", \"ivfflat\", \"none\"],\n maxDimensions: PGVECTOR_MAX_DIMENSIONS,\n // The backend probes `pg_extension.extversion` once and turns on\n // `hnsw.iterative_scan` / `ivfflat.iterative_scan` when pgvector >= 0.8, so a\n // filtered scan re-enters the index for more candidates.\n //\n // NOT a full-page guarantee, on either axis. The iterative scan stops at\n // `hnsw.max_scan_tuples` / `ivfflat.max_probes`; and on pgvector < 0.8 there\n // is no iterative scan at all, so the search stays `ef_search`-bounded and\n // behaves like a post-filter. A statically-declared mode cannot express\n // either, which is why the guarantee is its own field.\n filteredApproximateSearch: {\n mode: \"iterative-scan\",\n guaranteesFullPage: false,\n },\n};\n\n/** Whether a slot's declared index type materializes a real pgvector ANN index. */\nfunction usesAnnIndex(slot: VectorSlot): boolean {\n return slot.indexType === \"hnsw\" || slot.indexType === \"ivfflat\";\n}\n\n/**\n * pgvector operator class for a metric's ANN index — `vector_cosine_ops` /\n * `vector_l2_ops` / `vector_ip_ops`, mirroring the `<=>` / `<->` / `<#>`\n * distance operators this strategy emits.\n */\nfunction operatorClass(metric: VectorMetric): string {\n switch (metric) {\n case \"cosine\": {\n return \"vector_cosine_ops\";\n }\n case \"l2\": {\n return \"vector_l2_ops\";\n }\n case \"inner_product\": {\n return \"vector_ip_ops\";\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 a `::vector` literal. The value is bound as a\n * parameter (not interpolated) — Postgres parses the `[a,b,c]` text and the\n * cast types it. Finiteness is validated first so a NaN names its index.\n */\nfunction vectorLiteral(embedding: readonly number[], name: string): SQL {\n assertFiniteEmbedding(embedding, name);\n return sql`${formatVector(embedding)}::vector`;\n}\n\nfunction distanceExpression(\n embeddingColumn: SQL,\n queryEmbedding: readonly number[],\n metric: VectorMetric,\n): SQL {\n const query = vectorLiteral(queryEmbedding, \"queryEmbedding\");\n switch (metric) {\n case \"cosine\": {\n return sql`(${embeddingColumn} <=> ${query})`;\n }\n case \"l2\": {\n return sql`(${embeddingColumn} <-> ${query})`;\n }\n case \"inner_product\": {\n return sql`(${embeddingColumn} <#> ${query})`;\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);\n }\n }\n}\n\nexport const pgvectorStrategy: VectorStrategy = {\n name: \"pgvector\",\n capabilities: PGVECTOR_CAPABILITIES,\n\n tableName(graphId, nodeKind, fieldPath) {\n return vectorPhysicalName(TABLE_PREFIX, graphId, nodeKind, fieldPath);\n },\n\n ownedTables(slot): readonly StrategyTableContribution[] {\n const table = this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath);\n const name = quoteIdentifier(table);\n\n // No standalone graph_id index: the PRIMARY KEY (graph_id, node_id) already\n // covers `WHERE graph_id = ?` via its leading column, so a separate index\n // would be pure write amplification.\n const createDdl = [\n `CREATE TABLE IF NOT EXISTS ${name} (\n \"graph_id\" TEXT NOT NULL,\n \"node_id\" TEXT NOT NULL,\n \"embedding\" vector(${slot.dimensions}) NOT NULL,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ NOT NULL,\n PRIMARY KEY (\"graph_id\", \"node_id\")\n);`,\n ];\n\n // The HNSW/IVFFlat index is intentionally NOT created here. pgvector\n // similarity SQL is planner-driven (`ORDER BY embedding <=> q LIMIT k`\n // uses the index when present, sequential-scans when not), so the index\n // is a pure materialization concern: `buildCreateIndex` builds it through\n // `materializeIndexes()` with the field's declared `m`/`ef_construction`/\n // `lists`. Building it eagerly here would bake in default tuning (the\n // write-ensure slot has no `indexParams`) and `CREATE INDEX IF NOT EXISTS`\n // would then mask the tuned index materialization would emit.\n\n return [\n {\n logicalName: `${VECTOR_CONTRIBUTION_PREFIX}:${slot.nodeKind}.${slot.fieldPath}`,\n owner: \"pgvector\",\n tableName: table,\n createDdl,\n runtimeEnsure: true,\n },\n ];\n },\n\n buildUpsert(slot, params: UpsertEmbeddingParams, timestamp): readonly SQL[] {\n const table = quotedTableName(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n const value = vectorLiteral(params.embedding, \"embedding\");\n return [\n sql`\n INSERT INTO ${table} (\"graph_id\", \"node_id\", \"embedding\", \"created_at\", \"updated_at\")\n VALUES (${params.graphId}, ${params.nodeId}, ${value}, ${timestamp}, ${timestamp})\n ON CONFLICT (\"graph_id\", \"node_id\")\n DO UPDATE SET \"embedding\" = EXCLUDED.\"embedding\", \"updated_at\" = EXCLUDED.\"updated_at\"\n `,\n ];\n },\n\n buildUpsertBatch(\n slot,\n params: UpsertEmbeddingBatchParams,\n timestamp,\n ): readonly SQL[] {\n const table = quotedTableName(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n const valueRows = sql.join(\n params.rows.map(\n (row) =>\n sql`(${params.graphId}, ${row.nodeId}, ${vectorLiteral(row.embedding, \"embedding\")}, ${timestamp}, ${timestamp})`,\n ),\n sql`, `,\n );\n return [\n sql`\n INSERT INTO ${table} (\"graph_id\", \"node_id\", \"embedding\", \"created_at\", \"updated_at\")\n VALUES ${valueRows}\n ON CONFLICT (\"graph_id\", \"node_id\")\n DO UPDATE SET \"embedding\" = EXCLUDED.\"embedding\", \"updated_at\" = EXCLUDED.\"updated_at\"\n `,\n ];\n },\n\n buildDelete(slot, params: DeleteEmbeddingParams): readonly SQL[] {\n const table = quotedTableName(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n return [\n sql`\n DELETE FROM ${table}\n WHERE \"graph_id\" = ${params.graphId} AND \"node_id\" = ${params.nodeId}\n `,\n ];\n },\n\n buildSearch(slot, params: VectorSearchParams, candidates?: SQL): SQL {\n const table = quotedTableName(\n this.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 // Same SQL for brute-force and ANN: with a matching HNSW/IVFFlat index the\n // Postgres planner rewrites this `ORDER BY distance LIMIT k` into an index\n // scan automatically, so the strategy never branches on `slot.indexType`.\n const conditions: SQL[] = [sql`${table}.\"graph_id\" = ${params.graphId}`];\n if (params.minScore !== undefined) {\n conditions.push(\n vectorMinScoreCondition(distance, params.metric, params.minScore),\n );\n }\n // Candidate pushdown keeps the HNSW scan (verified plan: HNSW Index Scan\n // -> Nested Loop probe of the nodes pkey -> Limit). Exact under\n // `hnsw.iterative_scan` (pgvector >= 0.8, applied by the backend);\n // bounded by `ef_search` on older pgvector — still strictly better than\n // ranking tombstones into top-k and dropping them post-hoc.\n //\n // Plain `IN (subquery)`: with fresh statistics the planner hashes it\n // (brute-force scans) or drives per-row probes of the nodes pkey\n // under the ordered HNSW scan — the plan-verified shape the liveness\n // pushdown was built on. Stale statistics degrade any membership\n // form; the answer is `store.refreshStatistics()` after bulk loads,\n // not a cleverer SQL shape.\n if (candidates !== undefined) {\n conditions.push(sql`${table}.\"node_id\" IN (${candidates})`);\n }\n // Pagination is rank-relative: the scan fetches `limit + offset`\n // ordered candidates and OFFSET discards the leading page.\n const pageOffset = params.offset ?? 0;\n const pageClause = vectorPageClause(params.limit, params.offset);\n // IVFFlat's iterative scan only offers `relaxed_order` (no\n // strict_order mode), so under the backend-applied\n // `ivfflat.iterative_scan` the index may emit the candidate set\n // slightly out of distance order. Re-sort the bounded set inside a\n // MATERIALIZED wrapper — the fence stops the planner from collapsing\n // the sort back into the index scan's claimed ordering — and page in\n // the wrapper: an OFFSET inside the relaxed scan could discard the\n // wrong rows. Score is monotone in distance, so ordering by score per\n // the metric's direction restores exact ranking.\n if (slot.indexType === \"ivfflat\") {\n const direction =\n params.metric === \"cosine\" ? sql.raw(\"DESC\") : sql.raw(\"ASC\");\n const relaxedBody = 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 LIMIT ${params.limit + pageOffset}\n `;\n return sql`\n WITH tg_vec_relaxed AS MATERIALIZED (${relaxedBody})\n SELECT node_id, score FROM tg_vec_relaxed\n ORDER BY score ${direction}, node_id ASC\n ${pageClause}\n `;\n }\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 buildCreateIndex(slot, options): SQL | undefined {\n if (!usesAnnIndex(slot)) return undefined;\n return sql.raw(\n pgvectorIndexDdl(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n slot,\n options?.concurrent === true,\n ),\n );\n },\n\n buildDropIndex(slot): SQL | undefined {\n if (!usesAnnIndex(slot)) return undefined;\n const indexName = pgvectorIndexName(slot);\n return sql.raw(`DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`);\n },\n\n buildDropStorage(slot): readonly string[] {\n const table = quoteIdentifier(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n // CASCADE drops the ANN index along with the table.\n return [`DROP TABLE IF EXISTS ${table} CASCADE`];\n },\n};\n\nfunction pgvectorIndexName(slot: VectorSlot): string {\n return vectorPhysicalName(\n INDEX_PREFIX,\n slot.graphId,\n slot.nodeKind,\n slot.fieldPath,\n );\n}\n\nfunction pgvectorIndexDdl(\n table: string,\n slot: VectorSlot,\n concurrent: boolean,\n): string {\n const indexName = quoteIdentifier(pgvectorIndexName(slot));\n const quotedTable = quoteIdentifier(table);\n const opClass = operatorClass(slot.metric);\n // Honor the field's declared tuning; fall back to pgvector defaults.\n const m = slot.indexParams?.m ?? DEFAULT_HNSW_M;\n const efConstruction =\n slot.indexParams?.efConstruction ?? DEFAULT_HNSW_EF_CONSTRUCTION;\n const lists = slot.indexParams?.lists ?? DEFAULT_IVFFLAT_LISTS;\n // CONCURRENTLY builds without taking a write-blocking lock on the live table\n // (materializeIndexes passes concurrent on Postgres). Run outside a tx.\n const create = `CREATE INDEX${concurrent ? \" CONCURRENTLY\" : \"\"} IF NOT EXISTS`;\n\n switch (slot.indexType) {\n case \"hnsw\": {\n return `${create} ${indexName} ON ${quotedTable} USING hnsw (\"embedding\" ${opClass}) WITH (m = ${m}, ef_construction = ${efConstruction});`;\n }\n case \"ivfflat\": {\n return `${create} ${indexName} ON ${quotedTable} USING ivfflat (\"embedding\" ${opClass}) WITH (lists = ${lists});`;\n }\n case \"none\": {\n throw new Error(\n \"pgvectorIndexDdl called for a brute-force-only slot (indexType 'none').\",\n );\n }\n default: {\n const _exhaustive: never = slot.indexType;\n throw new Error(`Unsupported vector index type: ${String(_exhaustive)}`);\n }\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors/index.ts"],"names":[],"mappings":";AAyDA,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,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,UAAU,KAAK,CAAA;AAAA,EAC7B,SAAS,KAAA,EAAO;A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A,CAAe;AAAA,EACzD,YAAY,OAAA,EAA+B;AACzC,IAAA,KAAA;AAAA,MACE,wJAAA;AAAA,MAEA,oBAAA;AAAA,MACA;AAAA,QACE,QAAA,EAAU,MAAA;AAAA,QACV,UAAA,EACE,mMAAA;AAAA,QAGF,OAAO,OAAA,EAAS;AAAA;AAClB,KACF;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AAAA,EACd;AACF;AAoBO,SAAS,iBAAiB,KAAA,EAAyC;AACxE,EAAA,OAAO,KAAA,YAAiB,cAAA;AAC1B;AAmBO,SAAS,kBAAkB,KAAA,EAAyB;AACzD,EAAA,IAAI,CAAC,gBAAA,CAAiB,KAAK,CAAA,EAAG,OAAO,KAAA;AACrC,EAAA,OAAO,KAAA,CAAM,QAAA,KAAa,MAAA,IAAU,KAAA,CAAM,QAAA,KAAa,YAAA;AACzD;AAUO,SAAS,cAAc,KAAA,EAAyB;AACrD,EAAA,OAAO,gBAAA,CAAiB,KAAK,CAAA,IAAK,KAAA,CAAM,QAAA,KAAa,QAAA;AACvD;AAKO,SAAS,kBAAkB,KAAA,EAAyB;AACzD,EAAA,OAAO,gBAAA,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-5PNMDJ7J.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\";\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 */\nexport type MigrationErrorDetails = Readonly<{\n graphId: string;\n fromVersion: number;\n toVersion: number;\n reason?: string;\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(algorithm: string, maxIterations: number) {\n super(\n `${algorithm} did not converge within ${maxIterations} iterations.`,\n \"GRAPH_ALGORITHM_CONVERGENCE_ERROR\",\n {\n details: { algorithm, maxIterations },\n category: \"user\",\n suggestion:\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/indexes/ddl.ts"],"names":["sql","compileNodeIndexKeys","compileEdgeIndexKeys","compileIndexWhere","getDialect","CasingCache"],"mappings":";;;;;;AA0CO,SAAS,gBAAA,CACd,KAAA,EACA,OAAA,EACA,OAAA,GAAmC,EAAC,EAC5B;AACR,EAAA,IAAI,KAAA,CAAM,WAAW,MAAA,EAAQ;AAC3B,IAAA,OAAO,oBAAA,CAAqB,KAAA,EAAO,OAAA,EAAS,OAAO,CAAA;AAAA,EACrD;AACA,EAAA,OAAO,oBAAA,CAAqB,KAAA,EAAO,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AA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,KAAA,CAAM,GAAA;AACf;AAEA,SAAS,WAAA,CAAY,OAAgB,OAAA,EAA6B;AAChE,EAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,KAAA,KAAU,MAAA,EAAW;AACzC,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,IAAI,iBAAiB,IAAA,EAAM;AACzB,IAAA,OAAO,mBAAA,CAAoB,KAAA,CAAM,WAAA,EAAa,CAAA;AAAA,EAChD;AAEA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,oBAAoB,KAAK,CAAA;AAAA,EAClC;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,MAAM,QAAA,EAAS;AAAA,EACxB;AACA,EAAA,IAAI,OAAO,UAAU,SAAA,EAAW;AAC9B,IAAA,OAAOD,4BAAA,CAAW,OAAO,CAAA,CAAE,oBAAA,CAAqB,KAAK,CAAA;AAAA,EACvD;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,MAAM,QAAA,EAAS;AAAA,EACxB;AAEA,EAAA,MAAM,IAAI,SAAA;AAAA,IACR;AAAA,GACF;AACF;AAEA,SAAS,oBAAoB,KAAA,EAAuB;AAClD,EAAA,OAAO,CAAA,CAAA,EAAI,KAAA,CAAM,UAAA,CAAW,GAAA,EAAK,IAAI,CAAC,CAAA,CAAA,CAAA;AACxC","file":"chunk-6EEO3OVU.cjs","sourcesContent":["import { type SQL, sql } from \"drizzle-orm\";\nimport { CasingCache } from \"drizzle-orm/casing\";\n\nimport { getDialect } from \"../query/dialect\";\nimport { type SqlDialect } from \"../query/dialect/types\";\nimport {\n compileEdgeIndexKeys,\n compileIndexWhere,\n compileNodeIndexKeys,\n type IndexCompilationContext,\n} from \"./compiler\";\nimport {\n type EdgeIndexDeclaration,\n type NodeIndexDeclaration,\n type RelationalIndexDeclaration,\n type SystemColumnName,\n} from \"./types\";\n\nexport type GenerateIndexDdlOptions = Readonly<{\n nodesTableName?: string | undefined;\n edgesTableName?: string | undefined;\n ifNotExists?: boolean | undefined;\n /**\n * Emit `CREATE INDEX CONCURRENTLY` (Postgres only). Required for\n * `store.materializeIndexes()` so live tables don't take an\n * `AccessExclusiveLock`. Ignored on SQLite (no equivalent; SQLite is\n * single-writer regardless). When true on Postgres, the resulting\n * statement cannot be executed inside a transaction.\n */\n concurrent?: boolean | undefined;\n}>;\n\n/**\n * Generate `CREATE INDEX` DDL for a single relational index declaration.\n *\n * Vector index declarations (`entity: \"vector\"`) are NOT handled here —\n * they go through `backend.createVectorIndex` instead because the DDL\n * is dialect-specific (`USING hnsw (...) WITH (m=..., ef_construction=...)`\n * on Postgres) and operates on the strategy's per-`(kind, field)` embedding\n * tables, not `typegraph_nodes` / `typegraph_edges`. Callers narrow to the\n * relational subset before calling this function.\n */\nexport function generateIndexDDL(\n index: RelationalIndexDeclaration,\n dialect: SqlDialect,\n options: GenerateIndexDdlOptions = {},\n): string {\n if (index.entity === \"node\") {\n return generateNodeIndexDDL(index, dialect, options);\n }\n return generateEdgeIndexDDL(index, dialect, options);\n}\n\nexport function generateNodeIndexDDL(\n index: NodeIndexDeclaration,\n dialect: SqlDialect,\n options: GenerateIndexDdlOptions = {},\n): string {\n const tableName = options.nodesTableName ?? \"typegraph_nodes\";\n return generateTableIndexDDL(index, dialect, tableName, options);\n}\n\nexport function generateEdgeIndexDDL(\n index: EdgeIndexDeclaration,\n dialect: SqlDialect,\n options: GenerateIndexDdlOptions = {},\n): string {\n const tableName = options.edgesTableName ?? \"typegraph_edges\";\n return generateTableIndexDDL(index, dialect, tableName, options);\n}\n\nfunction generateTableIndexDDL(\n index: RelationalIndexDeclaration,\n dialect: SqlDialect,\n tableName: string,\n options: GenerateIndexDdlOptions,\n): string {\n if (index.method !== undefined) {\n return generateGinFamilyIndexDDL(index, dialect, tableName, options);\n }\n const ifNotExists = options.ifNotExists ?? true;\n const propsColumn = sql.raw('\"props\"');\n const systemColumn = (column: SystemColumnName): SQL =>\n sql.raw(quoteIdentifier(column));\n\n const keys =\n index.entity === \"node\" ?\n compileNodeIndexKeys(index, dialect, propsColumn, systemColumn).keys\n : compileEdgeIndexKeys(index, dialect, propsColumn, systemColumn).keys;\n\n const whereSql =\n index.where ?\n sqlToInlineString(\n compileIndexWhere(\n {\n dialect,\n propsColumn,\n systemColumn,\n } satisfies IndexCompilationContext,\n index.where,\n ),\n dialect,\n )\n : undefined;\n\n const keySql = keys.map((k) => sqlToInlineString(k, dialect)).join(\", \");\n const unique = index.unique ? \"UNIQUE \" : \"\";\n const concurrent =\n options.concurrent === true && dialect === \"postgres\" ?\n \"CONCURRENTLY \"\n : \"\";\n const ifNotExistsSql = ifNotExists ? \"IF NOT EXISTS \" : \"\";\n\n const whereClause = whereSql ? ` WHERE ${whereSql}` : \"\";\n\n return `CREATE ${unique}INDEX ${concurrent}${ifNotExistsSql}${quoteIdentifier(index.name)} ON ${quoteIdentifier(tableName)} (${keySql})${whereClause};`;\n}\n\n/**\n * DDL for the GIN-family methods (`\"gin\"` / `\"trigram\"`) — a PostgreSQL\n * expression GIN over the declaration's single field.\n *\n * The indexed expression is built from the SAME dialect extraction the\n * query compiler emits for the field (`jsonExtract` → `\"props\" #> ARRAY[…]`\n * for containment, `jsonExtractText` → `#>>` for text), because Postgres\n * matches expression indexes structurally: `(props #> ARRAY['tags']) @> $1`\n * and `(props #>> ARRAY['name']) ILIKE $1 ESCAPE '\\'` both hit their GIN\n * (verified against parameterized prepared statements). No scope prefix\n * columns, uniqueness, or partial clause: a GIN indexes one expression, and\n * the query's `graph_id` / `kind` equality filters apply as residual\n * conditions over the candidate rows.\n */\nfunction generateGinFamilyIndexDDL(\n index: RelationalIndexDeclaration,\n dialect: SqlDialect,\n tableName: string,\n options: GenerateIndexDdlOptions,\n): string {\n if (dialect !== \"postgres\") {\n throw new Error(\n `Index \"${index.name}\" declares method \"${index.method}\", which ` +\n \"requires PostgreSQL. materializeIndexes() reports such \" +\n \"declarations as skipped on SQLite instead of calling this.\",\n );\n }\n const adapter = getDialect(dialect);\n const propsColumn = sql.raw('\"props\"');\n const pointer = index.fields[0]!;\n const expression =\n index.method === \"gin\" ?\n adapter.jsonExtract(propsColumn, pointer)\n : adapter.jsonExtractText(propsColumn, pointer);\n const operatorClass =\n index.method === \"gin\" ? \"jsonb_path_ops\" : \"gin_trgm_ops\";\n const concurrent = options.concurrent === true ? \"CONCURRENTLY \" : \"\";\n const ifNotExistsSql = (options.ifNotExists ?? true) ? \"IF NOT EXISTS \" : \"\";\n return `CREATE INDEX ${concurrent}${ifNotExistsSql}${quoteIdentifier(index.name)} ON ${quoteIdentifier(tableName)} USING GIN ((${sqlToInlineString(expression, dialect)}) ${operatorClass});`;\n}\n\nfunction quoteIdentifier(identifier: string): string {\n return `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction sqlToInlineString(object: SQL, dialect: SqlDialect): string {\n const query = object.toQuery({\n casing: new CasingCache(),\n escapeName: (name) => name,\n escapeParam: (_number, value) => inlineParam(value, dialect),\n escapeString: (value) => escapeStringLiteral(value),\n inlineParams: true,\n invokeSource: \"indexes\",\n });\n\n if (query.params.length > 0) {\n throw new Error(\n \"Index DDL generation produced parameters; expected fully inlined SQL\",\n );\n }\n\n return query.sql;\n}\n\nfunction inlineParam(value: unknown, dialect: SqlDialect): string {\n if (value === null || value === undefined) {\n return \"NULL\";\n }\n if (value instanceof Date) {\n return escapeStringLiteral(value.toISOString());\n }\n\n if (typeof value === \"string\") {\n return escapeStringLiteral(value);\n }\n if (typeof value === \"number\") {\n return value.toString();\n }\n if (typeof value === \"boolean\") {\n return getDialect(dialect).booleanLiteralString(value);\n }\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n throw new TypeError(\n \"Index DDL generation received an unsupported SQL parameter value\",\n );\n}\n\nfunction escapeStringLiteral(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n"]}
|
package/dist/chunk-7YSP4V4R.cjs
DELETED
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
var drizzleOrm = require('drizzle-orm');
|
|
4
|
-
|
|
5
|
-
// src/backend/drizzle/operations/shared.ts
|
|
6
|
-
function sqlNull(value) {
|
|
7
|
-
return value ?? drizzleOrm.sql.raw("NULL");
|
|
8
|
-
}
|
|
9
|
-
function resolveValidFrom(validFrom, timestamp) {
|
|
10
|
-
if (validFrom === null) return void 0;
|
|
11
|
-
return validFrom ?? timestamp;
|
|
12
|
-
}
|
|
13
|
-
function quotedColumn(column) {
|
|
14
|
-
return drizzleOrm.sql.raw(`"${column.name.replaceAll('"', '""')}"`);
|
|
15
|
-
}
|
|
16
|
-
function quotedTableName(tableName) {
|
|
17
|
-
return drizzleOrm.sql.raw(`"${tableName.replaceAll('"', '""')}"`);
|
|
18
|
-
}
|
|
19
|
-
function codePointOrderKey(column, dialect) {
|
|
20
|
-
return dialect === "postgres" ? drizzleOrm.sql`${column} COLLATE "C"` : column;
|
|
21
|
-
}
|
|
22
|
-
function liveNodeIdsSubquery(nodes, graphId, nodeKind, nowIso) {
|
|
23
|
-
return drizzleOrm.sql`SELECT ${nodes.id} AS node_id FROM ${nodes} WHERE ${nodes.graphId} = ${graphId} AND ${nodes.kind} = ${nodeKind} AND ${nodes.deletedAt} IS NULL AND (${nodes.validFrom} IS NULL OR ${nodes.validFrom} <= ${nowIso}) AND (${nodes.validTo} IS NULL OR ${nodes.validTo} > ${nowIso})`;
|
|
24
|
-
}
|
|
25
|
-
function nodeColumnList(nodes) {
|
|
26
|
-
return drizzleOrm.sql.raw(`"${nodes.graphId.name}", "${nodes.kind.name}", "${nodes.id.name}", "${nodes.props.name}", "${nodes.version.name}", "${nodes.validFrom.name}", "${nodes.validTo.name}", "${nodes.createdAt.name}", "${nodes.updatedAt.name}"`);
|
|
27
|
-
}
|
|
28
|
-
function edgeColumnList(edges) {
|
|
29
|
-
return drizzleOrm.sql.raw(`"${edges.graphId.name}", "${edges.id.name}", "${edges.kind.name}", "${edges.fromKind.name}", "${edges.fromId.name}", "${edges.toKind.name}", "${edges.toId.name}", "${edges.props.name}", "${edges.validFrom.name}", "${edges.validTo.name}", "${edges.createdAt.name}", "${edges.updatedAt.name}"`);
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// src/constants.ts
|
|
33
|
-
var MAX_PG_IDENTIFIER_LENGTH = 63;
|
|
34
|
-
var TRUNCATED_IDENTIFIER_MAX_LENGTH = 54;
|
|
35
|
-
var IDENTIFIER_COMPONENT_MAX_LENGTH = 20;
|
|
36
|
-
var FNV1A_OFFSET_BASIS = 2166136261;
|
|
37
|
-
var FNV1A_PRIME = 16777619;
|
|
38
|
-
var DEFAULT_PAGINATION_LIMIT = 20;
|
|
39
|
-
var DEFAULT_STREAM_BATCH_SIZE = 1e3;
|
|
40
|
-
var SQLITE_PATH_DELIMITER = "|";
|
|
41
|
-
var PG_PATH_ELEMENT_SEPARATOR = ",";
|
|
42
|
-
var PG_ARRAY_START = "{";
|
|
43
|
-
var PG_ARRAY_END = "}";
|
|
44
|
-
var LIKE_ESCAPE_CHARACTER = "\\";
|
|
45
|
-
var likeEscapeClause = drizzleOrm.sql`ESCAPE '\\'`;
|
|
46
|
-
|
|
47
|
-
exports.DEFAULT_PAGINATION_LIMIT = DEFAULT_PAGINATION_LIMIT;
|
|
48
|
-
exports.DEFAULT_STREAM_BATCH_SIZE = DEFAULT_STREAM_BATCH_SIZE;
|
|
49
|
-
exports.FNV1A_OFFSET_BASIS = FNV1A_OFFSET_BASIS;
|
|
50
|
-
exports.FNV1A_PRIME = FNV1A_PRIME;
|
|
51
|
-
exports.IDENTIFIER_COMPONENT_MAX_LENGTH = IDENTIFIER_COMPONENT_MAX_LENGTH;
|
|
52
|
-
exports.LIKE_ESCAPE_CHARACTER = LIKE_ESCAPE_CHARACTER;
|
|
53
|
-
exports.MAX_PG_IDENTIFIER_LENGTH = MAX_PG_IDENTIFIER_LENGTH;
|
|
54
|
-
exports.PG_ARRAY_END = PG_ARRAY_END;
|
|
55
|
-
exports.PG_ARRAY_START = PG_ARRAY_START;
|
|
56
|
-
exports.PG_PATH_ELEMENT_SEPARATOR = PG_PATH_ELEMENT_SEPARATOR;
|
|
57
|
-
exports.SQLITE_PATH_DELIMITER = SQLITE_PATH_DELIMITER;
|
|
58
|
-
exports.TRUNCATED_IDENTIFIER_MAX_LENGTH = TRUNCATED_IDENTIFIER_MAX_LENGTH;
|
|
59
|
-
exports.codePointOrderKey = codePointOrderKey;
|
|
60
|
-
exports.edgeColumnList = edgeColumnList;
|
|
61
|
-
exports.likeEscapeClause = likeEscapeClause;
|
|
62
|
-
exports.liveNodeIdsSubquery = liveNodeIdsSubquery;
|
|
63
|
-
exports.nodeColumnList = nodeColumnList;
|
|
64
|
-
exports.quotedColumn = quotedColumn;
|
|
65
|
-
exports.quotedTableName = quotedTableName;
|
|
66
|
-
exports.resolveValidFrom = resolveValidFrom;
|
|
67
|
-
exports.sqlNull = sqlNull;
|
|
68
|
-
//# sourceMappingURL=chunk-7YSP4V4R.cjs.map
|
|
69
|
-
//# sourceMappingURL=chunk-7YSP4V4R.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/backend/drizzle/operations/shared.ts","../src/constants.ts","../src/query/dialect/like-escape.ts"],"names":["sql"],"mappings":";;;;;AAYO,SAAS,QAAQ,KAAA,EAAyC;AAC/D,EAAA,OAAO,KAAA,IAASA,cAAA,CAAI,GAAA,CAAI,MAAM,CAAA;AAChC;AAgBO,SAAS,gBAAA,CACd,WACA,SAAA,EACoB;AACpB,EAAA,IAAI,SAAA,KAAc,MAAM,OAAO,MAAA;AAC/B,EAAA,OAAO,SAAA,IAAa,SAAA;AACtB;AAEO,SAAS,aAAa,MAAA,EAA+B;AAC1D,EAAA,OAAOA,cAAA,CAAI,IAAI,CAAA,CAAA,EAAI,MAAA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qlDialect } from \"../../types\";\nimport type { PostgresTables } from \"../schema/postgres\";\nimport type { SqliteTables } from \"../schema/sqlite\";\n\nexport type Tables = SqliteTables | PostgresTables;\n\n/**\n * Converts undefined to SQL NULL for use in template literals.\n * Drizzle doesn't handle undefined in sql`` templates correctly.\n */\nexport function sqlNull(value: string | undefined): SQL | string {\n return value ?? sql.raw(\"NULL\");\n}\n\n/**\n * Resolves a `validFrom` insert value against the row's creation timestamp.\n * Three states, matching {@link InsertNodeParams.validFrom} /\n * {@link InsertEdgeParams.validFrom}:\n * - `undefined` (omitted): defaults to `timestamp` — every insert path\n * (single, batch, returning/non-returning) agrees that \"no validFrom\"\n * means \"valid from creation\", not open-left NULL (see issue #240).\n * - `null`: preserves an explicit open-left window — returned as\n * `undefined` here so the caller's {@link sqlNull} wrap emits SQL NULL,\n * letting interchange import round-trip a row that predates the #240\n * fix without narrowing its validity window on re-import (e.g. via a\n * `branch()` clone).\n * - a string: passed through unchanged.\n */\nexport function resolveValidFrom(\n validFrom: string | null | undefined,\n timestamp: string,\n): string | undefined {\n if (validFrom === null) return undefined;\n return validFrom ?? timestamp;\n}\n\nexport function quotedColumn(column: { name: string }): SQL {\n return sql.raw(`\"${column.name.replaceAll('\"', '\"\"')}\"`);\n}\n\n/**\n * Returns a quoted SQL identifier for a bare table name string.\n * Use when the operation targets a table that isn't represented as a\n * Drizzle table object (e.g. the FTS5 virtual table).\n */\nexport function quotedTableName(tableName: string): SQL {\n return sql.raw(`\"${tableName.replaceAll('\"', '\"\"')}\"`);\n}\n\n/**\n * `column` rendered so that ORDER BY sorts it by code point on both engines.\n *\n * Relevance-ranking SQL breaks score ties on `node_id`. Left bare, Postgres\n * sorts it under the column's collation — a linguistic collation such as\n * `en_US.UTF-8` orders `a, A, b, B` where byte order gives `A, B, a, b`, so\n * the same query returns different pages on two databases whose `datcollate`\n * differs. SQLite's default `BINARY` collation is already code-point order,\n * as is the store's `compareCodePoints`, which ranks the same rows whenever a\n * search falls back to fusing in JavaScript.\n *\n * Forcing the `C` collation on Postgres makes all three agree. The ranking is\n * sorted anyway (no index supplies the order), so this costs nothing.\n */\nexport function codePointOrderKey(column: SQL, dialect: SqlDialect): SQL {\n return dialect === \"postgres\" ? sql`${column} COLLATE \"C\"` : column;\n}\n\n/**\n * Subquery yielding the ids of CURRENT nodes of one kind — the candidate\n * set a facade search statement is allowed to return. Passed into the\n * fulltext and vector search builders so top-k is computed over current\n * rows in SQL, instead of ranking side-table rows first and dropping\n * tombstoned/expired nodes after (which silently shrinks results below\n * `limit` under index drift).\n *\n * Currency matches a `current` read: non-tombstoned AND inside the\n * validity window. The instant is BOUND as a parameter (the backend's\n * clock, same source as its write timestamps) rather than compiled as a\n * per-row SQL now() call — on SQLite a per-row strftime() across two\n * search legs dominated unfiltered facade searches.\n */\nexport function liveNodeIdsSubquery(\n nodes: Tables[\"nodes\"],\n graphId: string,\n nodeKind: string,\n nowIso: string,\n): SQL {\n return sql`SELECT ${nodes.id} AS node_id FROM ${nodes} WHERE ${nodes.graphId} = ${graphId} AND ${nodes.kind} = ${nodeKind} AND ${nodes.deletedAt} IS NULL AND (${nodes.validFrom} IS NULL OR ${nodes.validFrom} <= ${nowIso}) AND (${nodes.validTo} IS NULL OR ${nodes.validTo} > ${nowIso})`;\n}\n\nexport function nodeColumnList(nodes: Tables[\"nodes\"]): SQL {\n return sql.raw(`\"${nodes.graphId.name}\", \"${nodes.kind.name}\", \"${nodes.id.name}\", \"${nodes.props.name}\", \"${nodes.version.name}\", \"${nodes.validFrom.name}\", \"${nodes.validTo.name}\", \"${nodes.createdAt.name}\", \"${nodes.updatedAt.name}\"`);\n}\n\nexport function edgeColumnList(edges: Tables[\"edges\"]): SQL {\n return sql.raw(`\"${edges.graphId.name}\", \"${edges.id.name}\", \"${edges.kind.name}\", \"${edges.fromKind.name}\", \"${edges.fromId.name}\", \"${edges.toKind.name}\", \"${edges.toId.name}\", \"${edges.props.name}\", \"${edges.validFrom.name}\", \"${edges.validTo.name}\", \"${edges.createdAt.name}\", \"${edges.updatedAt.name}\"`);\n}\n","/**\n * Shared constants used across the TypeGraph codebase.\n */\n\n// ============================================================\n// PostgreSQL Limits\n// ============================================================\n\n/**\n * PostgreSQL truncates identifiers longer than 63 bytes.\n * Used for column aliases, index names, and other generated identifiers.\n */\nexport const MAX_PG_IDENTIFIER_LENGTH = 63;\n\n/** Maximum byte length for the truncated portion of a generated identifier. */\nexport const TRUNCATED_IDENTIFIER_MAX_LENGTH = 54;\n\n/** Maximum length for a single component (kind name, field name) in a generated identifier. */\nexport const IDENTIFIER_COMPONENT_MAX_LENGTH = 20;\n\n// ============================================================\n// FNV-1a Hash Constants\n// ============================================================\n\n/** FNV-1a 32-bit offset basis. */\nexport const FNV1A_OFFSET_BASIS = 0x81_1c_9d_c5;\n\n/** FNV-1a 32-bit prime. */\nexport const FNV1A_PRIME = 0x01_00_01_93;\n\n// ============================================================\n// Pagination\n// ============================================================\n\n/** Default page size for paginate() and cursor-based pagination. */\nexport const DEFAULT_PAGINATION_LIMIT = 20;\n\n/** Default batch size for streaming query results. */\nexport const DEFAULT_STREAM_BATCH_SIZE = 1000;\n\n// ============================================================\n// Path Delimiters\n// ============================================================\n\n/** SQLite stores array paths as pipe-delimited strings: |id1|id2|id3| */\nexport const SQLITE_PATH_DELIMITER = \"|\";\n\n/** PostgreSQL text arrays use comma-separated elements: {id1,id2,id3} */\nexport const PG_PATH_ELEMENT_SEPARATOR = \",\";\n\n/** PostgreSQL text array start delimiter. */\nexport const PG_ARRAY_START = \"{\";\n\n/** PostgreSQL text array end delimiter. */\nexport const PG_ARRAY_END = \"}\";\n","/**\n * Shared LIKE-escape clause for the query compiler.\n *\n * The compiler builds `contains` / `startsWith` / `endsWith` patterns by\n * escaping the literal `%`, `_`, and `\\` in user input with a backslash (see\n * the pattern builders in `compiler/predicates.ts`). For that escaping to take\n * effect the emitted `LIKE` / `ILIKE` must declare backslash as its escape\n * character. PostgreSQL's default LIKE escape is already backslash, so this\n * clause is a no-op there; SQLite has *no* default escape character, so without\n * it an escaped `\\%` matches a literal backslash followed by any character —\n * silently diverging from Postgres. Emitting it on every compiled predicate\n * makes the two backends match by construction.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\n/**\n * The backslash escape character used by the JS pattern builder\n * (`compileStringPattern` in `compiler/predicates.ts`) to prefix the literal\n * `%`, `_`, and `\\` in user input. It must match the character declared by\n * {@link likeEscapeClause}: the builder prefixes wildcards with this character,\n * and the clause tells SQL to treat it as the escape. Both are backslash.\n */\nexport const LIKE_ESCAPE_CHARACTER = \"\\\\\";\n\n/**\n * `ESCAPE '\\'` clause appended to every compiled `LIKE` / `ILIKE` predicate,\n * declaring {@link LIKE_ESCAPE_CHARACTER} as the escape character. The single\n * backslash inside the quotes is a literal in both PostgreSQL (with\n * `standard_conforming_strings`, the default) and SQLite.\n */\nexport const likeEscapeClause: SQL = sql`ESCAPE '\\\\'`;\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/compare.ts"],"names":[],"mappings":";;;AAeO,SAAS,cAAA,CAAe,MAAc,KAAA,EAAuB;AAClE,EAAA,IAAI,IAAA,GAAO,OAAO,OAAO,EAAA;AACzB,EAAA,OAAO,IAAA,GAAO,QAAQ,CAAA,GAAI,CAAA;AAC5B;AAiBO,SAAS,iBAAA,CAAkB,MAAc,KAAA,EAAuB;AACrE,EAAA,IAAI,IAAA,KAAS,OAAO,OAAO,CAAA;AAG3B,EAAA,IAAI,SAAA,GAAY,CAAA;AAChB,EAAA,IAAI,UAAA,GAAa,CAAA;AACjB,EAAA,OAAO,SAAA,GAAY,IAAA,CAAK,MAAA,IAAU,UAAA,GAAa,MAAM,MAAA,EAAQ;AAC3D,IAAA,MAAM,SAAA,GAAY,IAAA,CAAK,WAAA,CAAY,SAAS,CAAA;AAC5C,IAAA,MAAM,UAAA,GAAa,KAAA,CAAM,WAAA,CAAY,UAAU,CAAA;AAC/C,IAAA,IAAI,SAAA,KAAc,UAAA,EAAY,OAAO,SAAA,GAAY,aAAa,EAAA,GAAK,CAAA;AACnE,IAAA,SAAA,IAAa,SAAA,GAAY,QAAU,CAAA,GAAI,CAAA;AACvC,IAAA,UAAA,IAAc,UAAA,GAAa,QAAU,CAAA,GAAI,CAAA;AAAA,EAC3C;AACA,EAAA,MAAM,aAAA,GAAgB,aAAa,IAAA,CAAK,MAAA;AACxC,EAAA,MAAM,cAAA,GAAiB,cAAc,KAAA,CAAM,MAAA;AAC3C,EAAA,IAAI,aAAA,IAAiB,gBAAgB,OAAO,CAAA;AAC5C,EAAA,OAAO,gBAAgB,EAAA,GAAK,CAAA;AAC9B","file":"chunk-A42GCBGX.cjs","sourcesContent":["/**\n * Deterministic UTF-16 code-unit string comparison.\n *\n * `localeCompare` (and any `Intl`-backed collation) varies with the host's\n * ICU configuration, so two processes can order the same strings differently\n * — which turns \"sorted\" lock-acquisition sequences into cross-process\n * deadlocks and makes result/report ordering flap between environments.\n * Code-unit order is identical everywhere, matches SQLite's BINARY collation\n * for ASCII identifiers, and sorts NUL below every other character, so\n * NUL-separated composite keys compare as true tuples.\n *\n * Use this (or `Array.prototype.toSorted()` with no comparator, which is the\n * same order) for every internal ordering; locale-aware collation belongs\n * only in user-facing presentation code, which this library does not have.\n */\nexport function compareStrings(left: string, right: string): number {\n if (left < right) return -1;\n return left > right ? 1 : 0;\n}\n\n/**\n * Deterministic code-point string comparison — the order a SQL engine uses.\n *\n * {@link compareStrings} compares UTF-16 code *units*, which disagrees with\n * SQL byte order for astral characters: `\"\\u{10000}\"` is stored as the\n * surrogate pair `𐀀`, so code-unit order sorts it below `\"\"`\n * even though its code point (and its UTF-8 encoding) is far above. SQLite's\n * `BINARY` collation, Postgres's `C` collation, and UTF-8 byte order all agree\n * with code-point order.\n *\n * Use this wherever a JS-side ordering must reproduce an ORDER BY the database\n * could equally have performed — notably the hybrid-search fusion fallback,\n * whose ranks and page boundary must match the single-statement SQL path row\n * for row. Everywhere else {@link compareStrings} is cheaper and sufficient.\n */\nexport function compareCodePoints(left: string, right: string): number {\n if (left === right) return 0;\n // Walks by code point, stepping over the low surrogate of an astral pair.\n // `codePointAt` at a valid index always yields a number.\n let leftIndex = 0;\n let rightIndex = 0;\n while (leftIndex < left.length && rightIndex < right.length) {\n const leftPoint = left.codePointAt(leftIndex)!;\n const rightPoint = right.codePointAt(rightIndex)!;\n if (leftPoint !== rightPoint) return leftPoint < rightPoint ? -1 : 1;\n leftIndex += leftPoint > 0xff_ff ? 2 : 1;\n rightIndex += rightPoint > 0xff_ff ? 2 : 1;\n }\n const leftExhausted = leftIndex >= left.length;\n const rightExhausted = rightIndex >= right.length;\n if (leftExhausted && rightExhausted) return 0;\n return leftExhausted ? -1 : 1;\n}\n"]}
|