@nicia-ai/typegraph 0.35.0 → 0.37.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/dist/backend/postgres/index.cjs +24 -24
- package/dist/backend/postgres/index.d.cts +6 -6
- package/dist/backend/postgres/index.d.ts +6 -6
- package/dist/backend/postgres/index.js +11 -11
- package/dist/backend/postgres/pglite.cjs +16 -16
- package/dist/backend/postgres/pglite.d.cts +3 -3
- package/dist/backend/postgres/pglite.d.ts +3 -3
- package/dist/backend/postgres/pglite.js +11 -11
- package/dist/backend/sqlite/index.cjs +22 -21
- package/dist/backend/sqlite/index.d.cts +11 -9
- package/dist/backend/sqlite/index.d.ts +11 -9
- package/dist/backend/sqlite/index.js +10 -9
- package/dist/backend/sqlite/libsql.cjs +15 -14
- package/dist/backend/sqlite/libsql.cjs.map +1 -1
- package/dist/backend/sqlite/libsql.d.cts +3 -3
- package/dist/backend/sqlite/libsql.d.ts +3 -3
- package/dist/backend/sqlite/libsql.js +11 -10
- package/dist/backend/sqlite/libsql.js.map +1 -1
- package/dist/backend/sqlite/local.cjs +30 -23
- package/dist/backend/sqlite/local.cjs.map +1 -1
- package/dist/backend/sqlite/local.d.cts +3 -3
- package/dist/backend/sqlite/local.d.ts +3 -3
- package/dist/backend/sqlite/local.js +18 -11
- package/dist/backend/sqlite/local.js.map +1 -1
- package/dist/{chunk-TCOCYN2P.cjs → chunk-27SSDCEP.cjs} +14 -14
- package/dist/{chunk-TCOCYN2P.cjs.map → chunk-27SSDCEP.cjs.map} +1 -1
- package/dist/{chunk-5AQIKK56.cjs → chunk-2N6EOBTH.cjs} +16 -16
- package/dist/{chunk-5AQIKK56.cjs.map → chunk-2N6EOBTH.cjs.map} +1 -1
- package/dist/{chunk-FN35DLCN.cjs → chunk-3C2RYI6L.cjs} +13 -107
- package/dist/chunk-3C2RYI6L.cjs.map +1 -0
- package/dist/{chunk-4JEZZJ6S.cjs → chunk-3DS7Z4T4.cjs} +39 -39
- package/dist/{chunk-4JEZZJ6S.cjs.map → chunk-3DS7Z4T4.cjs.map} +1 -1
- package/dist/{chunk-BLZDPRXT.cjs → chunk-3GH67G4Z.cjs} +5 -5
- package/dist/{chunk-BLZDPRXT.cjs.map → chunk-3GH67G4Z.cjs.map} +1 -1
- package/dist/{chunk-K3PPLHY7.js → chunk-3RWZPJKV.js} +24 -9
- package/dist/chunk-3RWZPJKV.js.map +1 -0
- package/dist/{chunk-QWEUYILR.js → chunk-3SLPDKHQ.js} +4 -4
- package/dist/chunk-3SLPDKHQ.js.map +1 -0
- package/dist/{chunk-5A6FNS6N.cjs → chunk-3XXGYU62.cjs} +11 -11
- package/dist/{chunk-5A6FNS6N.cjs.map → chunk-3XXGYU62.cjs.map} +1 -1
- package/dist/{chunk-JBTOYDMN.js → chunk-44TA22QT.js} +58 -11
- package/dist/chunk-44TA22QT.js.map +1 -0
- package/dist/{chunk-UES55P7G.js → chunk-552KNYQJ.js} +2652 -409
- package/dist/chunk-552KNYQJ.js.map +1 -0
- package/dist/{chunk-VPYHY3LJ.cjs → chunk-5KEQ74YU.cjs} +14 -14
- package/dist/chunk-5KEQ74YU.cjs.map +1 -0
- package/dist/{chunk-Q5TEXCTB.js → chunk-5KPNWT6X.js} +3 -3
- package/dist/{chunk-Q5TEXCTB.js.map → chunk-5KPNWT6X.js.map} +1 -1
- package/dist/{chunk-MP2JQKSG.js → chunk-5PNMDJ7J.js} +108 -5
- package/dist/chunk-5PNMDJ7J.js.map +1 -0
- package/dist/{chunk-AW4A3P5A.cjs → chunk-5VQM6VWP.cjs} +2 -2
- package/dist/{chunk-AW4A3P5A.cjs.map → chunk-5VQM6VWP.cjs.map} +1 -1
- package/dist/{chunk-A3W7QG7K.js → chunk-5WWVZMVX.js} +2 -2
- package/dist/{chunk-A3W7QG7K.js.map → chunk-5WWVZMVX.js.map} +1 -1
- package/dist/{chunk-FACJJWGF.cjs → chunk-6EEO3OVU.cjs} +7 -7
- package/dist/{chunk-FACJJWGF.cjs.map → chunk-6EEO3OVU.cjs.map} +1 -1
- package/dist/{chunk-LGEALRC6.cjs → chunk-BVRDGYXQ.cjs} +113 -4
- package/dist/chunk-BVRDGYXQ.cjs.map +1 -0
- package/dist/{chunk-GSQ6NPH6.cjs → chunk-DEFQM7JU.cjs} +7 -7
- package/dist/{chunk-GSQ6NPH6.cjs.map → chunk-DEFQM7JU.cjs.map} +1 -1
- package/dist/{chunk-EM3CWPND.cjs → chunk-DIQ3AV5W.cjs} +574 -268
- package/dist/chunk-DIQ3AV5W.cjs.map +1 -0
- package/dist/{chunk-FPIZFYHE.js → chunk-EXU3RASM.js} +74 -15
- package/dist/chunk-EXU3RASM.js.map +1 -0
- package/dist/{chunk-H7YNSMA7.cjs → chunk-HAHNRASW.cjs} +20 -2
- package/dist/chunk-HAHNRASW.cjs.map +1 -0
- package/dist/{chunk-FL472AMI.cjs → chunk-IP3CGGPA.cjs} +8 -8
- package/dist/{chunk-FL472AMI.cjs.map → chunk-IP3CGGPA.cjs.map} +1 -1
- package/dist/{chunk-4TOD4LBZ.cjs → chunk-IPSVVTWT.cjs} +94 -35
- package/dist/chunk-IPSVVTWT.cjs.map +1 -0
- package/dist/{chunk-RGP33ZJ5.js → chunk-IXGYRP2P.js} +184 -92
- package/dist/chunk-IXGYRP2P.js.map +1 -0
- package/dist/{chunk-3TWF3SH4.js → chunk-J4IUSYFF.js} +251 -121
- package/dist/chunk-J4IUSYFF.js.map +1 -0
- package/dist/{chunk-O7UN7OXA.cjs → chunk-JBNOGRKW.cjs} +318 -188
- package/dist/chunk-JBNOGRKW.cjs.map +1 -0
- package/dist/{chunk-WDBCBWC4.js → chunk-K3Q3LJY3.js} +520 -221
- package/dist/chunk-K3Q3LJY3.js.map +1 -0
- package/dist/{chunk-OR5ZA5WP.js → chunk-K5UBVGJN.js} +4 -4
- package/dist/{chunk-OR5ZA5WP.js.map → chunk-K5UBVGJN.js.map} +1 -1
- package/dist/{chunk-UZV3AZKF.js → chunk-KQJ54OG5.js} +3 -3
- package/dist/{chunk-UZV3AZKF.js.map → chunk-KQJ54OG5.js.map} +1 -1
- package/dist/{chunk-QOTI55H7.js → chunk-L7HQ2OSI.js} +4 -4
- package/dist/{chunk-QOTI55H7.js.map → chunk-L7HQ2OSI.js.map} +1 -1
- package/dist/{chunk-55MZDDZV.js → chunk-M6VES7V6.js} +4 -4
- package/dist/{chunk-55MZDDZV.js.map → chunk-M6VES7V6.js.map} +1 -1
- package/dist/{chunk-J7WFGBJR.cjs → chunk-NBP2WTJW.cjs} +3249 -1006
- package/dist/chunk-NBP2WTJW.cjs.map +1 -0
- package/dist/{chunk-CK5BVQOW.cjs → chunk-NUIG3BCV.cjs} +100 -85
- package/dist/chunk-NUIG3BCV.cjs.map +1 -0
- package/dist/{chunk-EMF62TZG.cjs → chunk-NXQFATMF.cjs} +269 -177
- package/dist/chunk-NXQFATMF.cjs.map +1 -0
- package/dist/{chunk-KBGQIPRQ.js → chunk-PC2UBAUB.js} +20 -3
- package/dist/chunk-PC2UBAUB.js.map +1 -0
- package/dist/chunk-QARBLBXT.cjs +219 -0
- package/dist/chunk-QARBLBXT.cjs.map +1 -0
- package/dist/{chunk-6FR2MMS6.js → chunk-QERAIDRJ.js} +45 -4
- package/dist/chunk-QERAIDRJ.js.map +1 -0
- package/dist/chunk-QSXTWU4U.cjs +12 -0
- package/dist/{chunk-GUR2FNB5.cjs.map → chunk-QSXTWU4U.cjs.map} +1 -1
- package/dist/{chunk-QNKSQTKQ.js → chunk-RCVLFTCT.js} +49 -19
- package/dist/chunk-RCVLFTCT.js.map +1 -0
- package/dist/{chunk-VSPCZAXF.js → chunk-RRSNR3TP.js} +3 -3
- package/dist/{chunk-VSPCZAXF.js.map → chunk-RRSNR3TP.js.map} +1 -1
- package/dist/{chunk-WJT7OU7E.cjs → chunk-TGOMW4MB.cjs} +129 -98
- package/dist/chunk-TGOMW4MB.cjs.map +1 -0
- package/dist/{chunk-KMI7LYAF.js → chunk-TKT2XHED.js} +8 -8
- package/dist/{chunk-KMI7LYAF.js.map → chunk-TKT2XHED.js.map} +1 -1
- package/dist/{chunk-RGPG7EOJ.js → chunk-TPF25IG6.js} +3 -3
- package/dist/{chunk-RGPG7EOJ.js.map → chunk-TPF25IG6.js.map} +1 -1
- package/dist/{chunk-5SEGFTZX.js → chunk-UGZUAYAR.js} +3 -3
- package/dist/{chunk-5SEGFTZX.js.map → chunk-UGZUAYAR.js.map} +1 -1
- package/dist/{chunk-VHMPG6UL.js → chunk-UXLSNRYL.js} +11 -105
- package/dist/chunk-UXLSNRYL.js.map +1 -0
- package/dist/{chunk-FRV5Q5IO.js → chunk-UYQMBBWJ.js} +3 -3
- package/dist/{chunk-FRV5Q5IO.js.map → chunk-UYQMBBWJ.js.map} +1 -1
- package/dist/{chunk-UUT7UN2N.cjs → chunk-VGDDG3XJ.cjs} +7 -7
- package/dist/{chunk-UUT7UN2N.cjs.map → chunk-VGDDG3XJ.cjs.map} +1 -1
- package/dist/{chunk-CZQ3FO2Q.js → chunk-VKGKDOKR.js} +56 -21
- package/dist/chunk-VKGKDOKR.js.map +1 -0
- package/dist/{chunk-CTTSDJLY.cjs → chunk-VL2V6PEN.cjs} +11 -11
- package/dist/{chunk-CTTSDJLY.cjs.map → chunk-VL2V6PEN.cjs.map} +1 -1
- package/dist/{chunk-XOX22WHL.cjs → chunk-WOJMKB3N.cjs} +125 -90
- package/dist/chunk-WOJMKB3N.cjs.map +1 -0
- package/dist/{chunk-UMDVATGY.cjs → chunk-WWFHO375.cjs} +6 -6
- package/dist/{chunk-UMDVATGY.cjs.map → chunk-WWFHO375.cjs.map} +1 -1
- package/dist/{chunk-I7ZUZKFD.js → chunk-XGPUQ56G.js} +3 -3
- package/dist/{chunk-I7ZUZKFD.js.map → chunk-XGPUQ56G.js.map} +1 -1
- package/dist/{chunk-D7ZEOS56.cjs → chunk-XGU7DZDA.cjs} +74 -14
- package/dist/chunk-XGU7DZDA.cjs.map +1 -0
- package/dist/{chunk-S55OV6PW.cjs → chunk-XPCZADMT.cjs} +54 -11
- package/dist/chunk-XPCZADMT.cjs.map +1 -0
- package/dist/{chunk-T2WUSPDA.js → chunk-XWV4JT34.js} +3 -3
- package/dist/{chunk-T2WUSPDA.js.map → chunk-XWV4JT34.js.map} +1 -1
- package/dist/chunk-YTSN73ND.js +212 -0
- package/dist/chunk-YTSN73ND.js.map +1 -0
- package/dist/{ddl-CZz7a0E8.d.cts → ddl-BD-ZfKeX.d.cts} +3 -3
- package/dist/{ddl-C2rZ-Aen.d.ts → ddl-CS0KUVwB.d.ts} +3 -3
- package/dist/{extension-types-ixRpJVUp.d.cts → extension-types-BM2ACfYO.d.cts} +6 -1
- package/dist/{extension-types-ixRpJVUp.d.ts → extension-types-BM2ACfYO.d.ts} +6 -1
- package/dist/{fulltext-strategy-CDkSSYhq.d.cts → fulltext-strategy-C27vXaeB.d.cts} +127 -8
- package/dist/{fulltext-strategy-B57yvC5Q.d.ts → fulltext-strategy-DebsMrqg.d.ts} +127 -8
- package/dist/graph-extension/index.cjs +19 -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 +4 -4
- package/dist/graph-merge/index.cjs +88 -88
- package/dist/graph-merge/index.cjs.map +1 -1
- package/dist/graph-merge/index.d.cts +6 -6
- package/dist/graph-merge/index.d.ts +6 -6
- package/dist/graph-merge/index.js +19 -19
- package/dist/graph-merge/index.js.map +1 -1
- package/dist/{index-Bks_3HHK.d.cts → index-BPM59vsg.d.cts} +119 -7
- package/dist/{index-6CSUAq-x.d.ts → index-BeacbPoe.d.ts} +119 -7
- package/dist/index.cjs +230 -185
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -11
- package/dist/index.d.ts +11 -11
- package/dist/index.js +53 -40
- package/dist/index.js.map +1 -1
- package/dist/indexes/index.cjs +30 -21
- package/dist/indexes/index.d.cts +5 -5
- package/dist/indexes/index.d.ts +5 -5
- package/dist/indexes/index.js +8 -7
- package/dist/interchange/index.cjs +208 -30
- package/dist/interchange/index.cjs.map +1 -1
- package/dist/interchange/index.d.cts +25 -8
- package/dist/interchange/index.d.ts +25 -8
- package/dist/interchange/index.js +191 -11
- package/dist/interchange/index.js.map +1 -1
- package/dist/{manager-DwQi8eV0.d.cts → manager-D00_NXvT.d.ts} +11 -2
- package/dist/{manager-ejUCB52T.d.ts → manager-nU1vTJLy.d.cts} +11 -2
- package/dist/{materialize-indexes-B4e9360H.d.cts → materialize-indexes-CuR3gAZb.d.cts} +8 -2
- package/dist/{materialize-indexes-te9TPMMJ.d.ts → materialize-indexes-zK2J_flP.d.ts} +8 -2
- package/dist/{postgres-DQ5R6rzV.d.ts → postgres-IaBA4RgE.d.ts} +1 -1
- package/dist/{postgres-CfEqsRMp.d.cts → postgres-YrYmPlaU.d.cts} +1 -1
- package/dist/profiler/index.cjs +3 -3
- package/dist/profiler/index.d.cts +7 -7
- package/dist/profiler/index.d.ts +7 -7
- package/dist/profiler/index.js +2 -2
- package/dist/provenance/index.cjs +32 -33
- package/dist/provenance/index.cjs.map +1 -1
- package/dist/provenance/index.d.cts +5 -5
- package/dist/provenance/index.d.ts +5 -5
- package/dist/provenance/index.js +5 -6
- package/dist/provenance/index.js.map +1 -1
- package/dist/schema/index.cjs +35 -35
- package/dist/schema/index.d.cts +7 -7
- package/dist/schema/index.d.ts +7 -7
- package/dist/schema/index.js +11 -11
- package/dist/{sqlite-DvQndLky.d.ts → sqlite-BUOHPx7p.d.ts} +1 -1
- package/dist/{sqlite-D7zBinNR.d.cts → sqlite-Pp8O19WE.d.cts} +1 -1
- package/dist/{store-view-CKbHFRnn.d.ts → store-view-ANL6mTph.d.ts} +457 -57
- package/dist/{store-view-BSpqvAxK.d.cts → store-view-X96Rd00T.d.cts} +457 -57
- package/dist/{types-Bv9DcS_E.d.cts → types-r-Zyq2Hz.d.cts} +2 -2
- package/dist/{types-CoxuV7EJ.d.ts → types-wsvuBgPK.d.ts} +2 -2
- package/dist/where-CJOpJj3a.d.ts +36 -0
- package/dist/where-K3uBP33l.d.cts +36 -0
- package/package.json +1 -1
- package/dist/chunk-3TWF3SH4.js.map +0 -1
- package/dist/chunk-4TOD4LBZ.cjs.map +0 -1
- package/dist/chunk-6FR2MMS6.js.map +0 -1
- package/dist/chunk-CK5BVQOW.cjs.map +0 -1
- package/dist/chunk-CZQ3FO2Q.js.map +0 -1
- package/dist/chunk-D7ZEOS56.cjs.map +0 -1
- package/dist/chunk-EM3CWPND.cjs.map +0 -1
- package/dist/chunk-EMF62TZG.cjs.map +0 -1
- package/dist/chunk-EOLERH7Y.cjs +0 -40
- package/dist/chunk-EOLERH7Y.cjs.map +0 -1
- package/dist/chunk-FN35DLCN.cjs.map +0 -1
- package/dist/chunk-FPIZFYHE.js.map +0 -1
- package/dist/chunk-GUR2FNB5.cjs +0 -12
- package/dist/chunk-H7YNSMA7.cjs.map +0 -1
- package/dist/chunk-J7WFGBJR.cjs.map +0 -1
- package/dist/chunk-JBTOYDMN.js.map +0 -1
- package/dist/chunk-K3PPLHY7.js.map +0 -1
- package/dist/chunk-KBGQIPRQ.js.map +0 -1
- package/dist/chunk-LGEALRC6.cjs.map +0 -1
- package/dist/chunk-MP2JQKSG.js.map +0 -1
- package/dist/chunk-O7UN7OXA.cjs.map +0 -1
- package/dist/chunk-QNKSQTKQ.js.map +0 -1
- package/dist/chunk-QWEUYILR.js.map +0 -1
- package/dist/chunk-RGP33ZJ5.js.map +0 -1
- package/dist/chunk-S55OV6PW.cjs.map +0 -1
- package/dist/chunk-UES55P7G.js.map +0 -1
- package/dist/chunk-UT3S4SEN.js +0 -31
- package/dist/chunk-UT3S4SEN.js.map +0 -1
- package/dist/chunk-VHMPG6UL.js.map +0 -1
- package/dist/chunk-VPYHY3LJ.cjs.map +0 -1
- package/dist/chunk-WDBCBWC4.js.map +0 -1
- package/dist/chunk-WJT7OU7E.cjs.map +0 -1
- package/dist/chunk-XOX22WHL.cjs.map +0 -1
- package/dist/where-7RKFOsXt.d.ts +0 -11
- package/dist/where-DdMIXOtH.d.cts +0 -11
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
3
|
+
var chunkHAHNRASW_cjs = require('./chunk-HAHNRASW.cjs');
|
|
4
|
+
var chunkBVRDGYXQ_cjs = require('./chunk-BVRDGYXQ.cjs');
|
|
5
5
|
|
|
6
6
|
// src/core/types.ts
|
|
7
7
|
var NODE_TYPE_BRAND = "__nodeType";
|
|
@@ -10,7 +10,7 @@ function assertNonEmptyId(value, path) {
|
|
|
10
10
|
if (value.length > 0) {
|
|
11
11
|
return;
|
|
12
12
|
}
|
|
13
|
-
throw new
|
|
13
|
+
throw new chunkBVRDGYXQ_cjs.ValidationError(
|
|
14
14
|
`${path} must be a non-empty string.`,
|
|
15
15
|
{
|
|
16
16
|
issues: [
|
|
@@ -100,14 +100,14 @@ function readObjectShape(schema) {
|
|
|
100
100
|
}
|
|
101
101
|
function readEmbeddingIndex(schema) {
|
|
102
102
|
for (const candidate of unwrapChain(schema)) {
|
|
103
|
-
const config =
|
|
103
|
+
const config = chunkHAHNRASW_cjs.getEmbeddingIndex(candidate);
|
|
104
104
|
if (config !== void 0) return config;
|
|
105
105
|
}
|
|
106
106
|
return void 0;
|
|
107
107
|
}
|
|
108
108
|
function readEmbeddingDimensions(schema) {
|
|
109
109
|
for (const candidate of unwrapChain(schema)) {
|
|
110
|
-
if (
|
|
110
|
+
if (chunkHAHNRASW_cjs.isEmbeddingSchema(candidate)) {
|
|
111
111
|
return candidate._embeddingDimensions;
|
|
112
112
|
}
|
|
113
113
|
}
|
|
@@ -136,7 +136,7 @@ function validateConstraintNarrowing(name, edgeType, registration) {
|
|
|
136
136
|
const builtInFromNames = new Set(edgeType.from.map((node) => node.kind));
|
|
137
137
|
for (const fromNode of registration.from) {
|
|
138
138
|
if (!builtInFromNames.has(fromNode.kind)) {
|
|
139
|
-
throw new
|
|
139
|
+
throw new chunkBVRDGYXQ_cjs.ConfigurationError(
|
|
140
140
|
`Edge "${name}" registration has 'from' kind "${fromNode.kind}" not in edge's built-in domain: [${[...builtInFromNames].join(", ")}]`,
|
|
141
141
|
{
|
|
142
142
|
edgeName: name,
|
|
@@ -152,7 +152,7 @@ function validateConstraintNarrowing(name, edgeType, registration) {
|
|
|
152
152
|
const builtInToNames = new Set(edgeType.to.map((node) => node.kind));
|
|
153
153
|
for (const toNode of registration.to) {
|
|
154
154
|
if (!builtInToNames.has(toNode.kind)) {
|
|
155
|
-
throw new
|
|
155
|
+
throw new chunkBVRDGYXQ_cjs.ConfigurationError(
|
|
156
156
|
`Edge "${name}" registration has 'to' kind "${toNode.kind}" not in edge's built-in range: [${[...builtInToNames].join(", ")}]`,
|
|
157
157
|
{
|
|
158
158
|
edgeName: name,
|
|
@@ -228,7 +228,7 @@ function normalizeIndexes(inputs, nodes, edges) {
|
|
|
228
228
|
assertKindRegistered(declaration, edgeKinds, "edge");
|
|
229
229
|
}
|
|
230
230
|
if (seenNames.has(declaration.name)) {
|
|
231
|
-
throw new
|
|
231
|
+
throw new chunkBVRDGYXQ_cjs.ConfigurationError(
|
|
232
232
|
`Duplicate index name "${declaration.name}" in defineGraph({ indexes }). Index names must be unique within a graph.`,
|
|
233
233
|
{ indexName: declaration.name },
|
|
234
234
|
{
|
|
@@ -251,7 +251,7 @@ function assertKindRegistered(declaration, registeredKinds, entity) {
|
|
|
251
251
|
if (registeredKinds.has(declaration.kind)) return;
|
|
252
252
|
const slot = entity === "node" ? "nodes" : "edges";
|
|
253
253
|
const suggestion = entity === "node" ? `Add { ${declaration.kind}: { type: ${declaration.kind} } } to defineGraph({ nodes }) or remove the index from "indexes".` : `Register the edge in defineGraph({ edges }) or remove the index from "indexes".`;
|
|
254
|
-
throw new
|
|
254
|
+
throw new chunkBVRDGYXQ_cjs.ConfigurationError(
|
|
255
255
|
`Index "${declaration.name}" references ${entity} kind "${declaration.kind}" which is not registered in this graph's "${slot}".`,
|
|
256
256
|
{
|
|
257
257
|
indexName: declaration.name,
|
|
@@ -295,7 +295,7 @@ function validateProps(schema, props, context) {
|
|
|
295
295
|
}
|
|
296
296
|
const issues = zodIssuesToValidationIssues(result.error);
|
|
297
297
|
const location = buildLocationString(context);
|
|
298
|
-
throw new
|
|
298
|
+
throw new chunkBVRDGYXQ_cjs.ValidationError(
|
|
299
299
|
`Invalid ${context.entityType} props for ${location}: ${result.error.message}`,
|
|
300
300
|
{
|
|
301
301
|
entityType: context.entityType,
|
|
@@ -322,7 +322,7 @@ function validateEdgeProps(schema, props, context) {
|
|
|
322
322
|
function wrapZodError(error, context) {
|
|
323
323
|
const issues = zodIssuesToValidationIssues(error);
|
|
324
324
|
const location = buildLocationString(context);
|
|
325
|
-
return new
|
|
325
|
+
return new chunkBVRDGYXQ_cjs.ValidationError(
|
|
326
326
|
`Validation failed for ${context.entityType} ${location}: ${error.message}`,
|
|
327
327
|
{
|
|
328
328
|
entityType: context.entityType,
|
|
@@ -335,7 +335,7 @@ function wrapZodError(error, context) {
|
|
|
335
335
|
);
|
|
336
336
|
}
|
|
337
337
|
function createValidationError(message, issues, context) {
|
|
338
|
-
return new
|
|
338
|
+
return new chunkBVRDGYXQ_cjs.ValidationError(message, {
|
|
339
339
|
...context?.entityType !== void 0 && {
|
|
340
340
|
entityType: context.entityType
|
|
341
341
|
},
|
|
@@ -365,5 +365,5 @@ exports.validateEdgeProps = validateEdgeProps;
|
|
|
365
365
|
exports.validateNodeProps = validateNodeProps;
|
|
366
366
|
exports.validateProps = validateProps;
|
|
367
367
|
exports.wrapZodError = wrapZodError;
|
|
368
|
-
//# sourceMappingURL=chunk-
|
|
369
|
-
//# sourceMappingURL=chunk-
|
|
368
|
+
//# sourceMappingURL=chunk-5KEQ74YU.cjs.map
|
|
369
|
+
//# sourceMappingURL=chunk-5KEQ74YU.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/types.ts","../src/indexes/auto-derive.ts","../src/core/define-graph.ts","../src/errors/validation.ts"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B,EAAA,MAAM,MAAA,GAAS,4BAA4B,KAAK,CAAA;AAChD,EAAA,MAAM,QAAA,GAAW,oBAAoB,OAAO,CAAA;AAE5C,EAAA,OAAO,IAAIA,iCAAA;AAAA,IACT,yBAAyB,OAAA,CAAQ,UAAU,IAAI,QAAQ,CAAA,EAAA,EAAK,MAAM,OAAO,CAAA,CAAA;AAAA,IACzE;AAAA,MACE,YAAY,OAAA,CAAQ,UAAA;AAAA,MACpB,MAAM,OAAA,CAAQ,IAAA;AAAA,MACd,WAAW,OAAA,CAAQ,SAAA;AAAA,MACnB,GAAI,OAAA,CAAQ,EAAA,KAAO,UAAa,EAAE,EAAA,EAAI,QAAQ,EAAA,EAAG;AAAA,MACjD;AAAA,KACF;AAAA,IACA,EAAE,OAAO,KAAA;AAAM,GACjB;AACF;AAkBO,SAAS,qBAAA,CACd,OAAA,EACA,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,5 +1,5 @@
|
|
|
1
1
|
import { vectorPageClause } from './chunk-DFVLCOP6.js';
|
|
2
|
-
import { quoteIdentifier, vectorScoreExpression, vectorMinScoreCondition, VECTOR_CONTRIBUTION_PREFIX, vectorPhysicalName, assertFiniteEmbedding } from './chunk-
|
|
2
|
+
import { quoteIdentifier, vectorScoreExpression, vectorMinScoreCondition, VECTOR_CONTRIBUTION_PREFIX, vectorPhysicalName, assertFiniteEmbedding } from './chunk-EXU3RASM.js';
|
|
3
3
|
import { quotedTableName } from './chunk-OHMP6N2J.js';
|
|
4
4
|
import { sql } from 'drizzle-orm';
|
|
5
5
|
import { customType } from 'drizzle-orm/pg-core';
|
|
@@ -286,5 +286,5 @@ function pgvectorIndexDdl(table, slot, concurrent) {
|
|
|
286
286
|
}
|
|
287
287
|
|
|
288
288
|
export { assertPgvectorEfSearch, pgvectorStrategy };
|
|
289
|
-
//# sourceMappingURL=chunk-
|
|
290
|
-
//# sourceMappingURL=chunk-
|
|
289
|
+
//# sourceMappingURL=chunk-5KPNWT6X.js.map
|
|
290
|
+
//# sourceMappingURL=chunk-5KPNWT6X.js.map
|
|
@@ -1 +1 @@
|
|
|
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,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qB,IAAA,CAAK,SAAA;AAChC,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,+BAAA,EAAkC,MAAA,CAAO,WAAW,CAAC,CAAA,CAAE,CAAA;AAAA,IACzE;AAAA;AAEJ","file":"chunk-Q5TEXCTB.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
|
+
{"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,CAAA,CAAA,EAAI,KAAA,CAAM,IAAA,CAAK,GAAG,CAAC,CAAA,CAAA,CAAA;AAAA,EAC5B,CAAA;AAAA,EAEA,WAAW,KAAA,EAAyB;AAGlC,IAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG;AACxB,MAAA,OAAO,KAAA;AAAA,IACT;AAEA,IAAA,MAAM,OAAA,GAAU,KAAA,CAAM,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AACjC,IAAA,IAAI,YAAY,EAAA,EAAI;AAClB,MAAA,OAAO,EAAC;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AAA,GAAI,IAAA,CAAK,WAAA,EAAa,CAAA,IAAK,cAAA;AACjC,EAAA,MAAM,cAAA,GACJ,IAAA,CAAK,WAAA,EAAa,cAAA,IAAkB,4BAAA;AACtC,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,WAAA,EAAa,KAAA,IAAS,qBAAA;AAGzC,EAAA,MAAM,MAAA,GAAS,CAAA,YAAA,EAAe,UAAA,GAAa,eAAA,GAAkB,EAAE,CAAA,cAAA,CAAA;AAE/D,EAAA,QAAQ,KAAK,SAAA;AAAW,IACtB,KAAK,MAAA,EAAQ;AACX,MAAA,OAAO,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,SAAS,CAAA,IAAA,EAAO,WAAW,CAAA,yBAAA,EAA4B,OAAO,CAAA,YAAA,EAAe,CAAC,CAAA,oBAAA,EAAuB,cAAc,CAAA,EAAA,CAAA;AAAA,IACzI;AAAA,IACA,KAAK,SAAA,EAAW;AACd,MAAA,OAAO,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,SAAS,OAAO,WAAW,CAAA,4BAAA,EAA+B,OAAO,CAAA,gBAAA,EAAmB,KAAK,CAAA,EAAA,CAAA;AAAA,IAC/G;AAAA,IACA,KAAK,MAAA,EAAQ;AACX,MAAA,MAAM,IAAI,KAAA;AAAA,QACR;AAAA,OACF;AAAA,IACF;AAAA,IACA,SAAS;AACP,MAAA,MAAM,cAAqB,IAAA,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"]}
|
|
@@ -370,6 +370,91 @@ var ConfigurationError = class extends TypeGraphError {
|
|
|
370
370
|
this.name = "ConfigurationError";
|
|
371
371
|
}
|
|
372
372
|
};
|
|
373
|
+
var GraphAlgorithmConvergenceError = class extends TypeGraphError {
|
|
374
|
+
constructor(algorithm, maxIterations) {
|
|
375
|
+
super(
|
|
376
|
+
`${algorithm} did not converge within ${maxIterations} iterations.`,
|
|
377
|
+
"GRAPH_ALGORITHM_CONVERGENCE_ERROR",
|
|
378
|
+
{
|
|
379
|
+
details: { algorithm, maxIterations },
|
|
380
|
+
category: "user",
|
|
381
|
+
suggestion: "Increase maxIterations or reduce the selected graph before retrying."
|
|
382
|
+
}
|
|
383
|
+
);
|
|
384
|
+
this.name = "GraphAlgorithmConvergenceError";
|
|
385
|
+
}
|
|
386
|
+
};
|
|
387
|
+
var EDGE_WEIGHT_REASONS = {
|
|
388
|
+
missing: {
|
|
389
|
+
message: "has no value for weight property",
|
|
390
|
+
suggestion: "Set the property on every selected edge, or provide defaultWeight for edges without it."
|
|
391
|
+
},
|
|
392
|
+
negative: {
|
|
393
|
+
message: "has a negative value for weight property",
|
|
394
|
+
suggestion: "Weighted traversal requires non-negative weights; repair the edge data before retrying."
|
|
395
|
+
},
|
|
396
|
+
non_numeric: {
|
|
397
|
+
message: "has a non-numeric value for weight property",
|
|
398
|
+
suggestion: "Store the weight property as a JSON number on every selected edge before retrying."
|
|
399
|
+
},
|
|
400
|
+
out_of_range: {
|
|
401
|
+
message: "has a value outside the supported range for weight property",
|
|
402
|
+
suggestion: "Keep weight magnitudes within the range weightedShortestPath documents (large enough to be a normal IEEE 754 double, small enough that path sums cannot overflow)."
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
var InvalidEdgeWeightError = class extends TypeGraphError {
|
|
406
|
+
constructor(details) {
|
|
407
|
+
super(
|
|
408
|
+
`Edge '${details.edgeId}' (kind '${details.edgeKind}') ${EDGE_WEIGHT_REASONS[details.reason].message} '${details.property}'${details.value === void 0 ? "" : ` (value: ${details.value})`}.`,
|
|
409
|
+
"INVALID_EDGE_WEIGHT",
|
|
410
|
+
{
|
|
411
|
+
details: { ...details },
|
|
412
|
+
category: "user",
|
|
413
|
+
suggestion: EDGE_WEIGHT_REASONS[details.reason].suggestion
|
|
414
|
+
}
|
|
415
|
+
);
|
|
416
|
+
this.name = "InvalidEdgeWeightError";
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
var UnsupportedBackendCapabilityError = class extends TypeGraphError {
|
|
420
|
+
constructor(operation, capability, details = {}, suggestion) {
|
|
421
|
+
super(
|
|
422
|
+
`${operation} requires backend capability '${capability}'.`,
|
|
423
|
+
"UNSUPPORTED_BACKEND_CAPABILITY",
|
|
424
|
+
{
|
|
425
|
+
details: { operation, capability, ...details },
|
|
426
|
+
category: "user",
|
|
427
|
+
suggestion: suggestion ?? "Use a backend that advertises this capability before invoking the operation."
|
|
428
|
+
}
|
|
429
|
+
);
|
|
430
|
+
this.name = "UnsupportedBackendCapabilityError";
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
var TrustedImportError = class extends TypeGraphError {
|
|
434
|
+
constructor(message, reason, details = {}, options) {
|
|
435
|
+
super(message, "TRUSTED_IMPORT_ERROR", {
|
|
436
|
+
details: { ...details, reason },
|
|
437
|
+
category: "user",
|
|
438
|
+
suggestion: options?.suggestion ?? "Use the validating bulk or interchange import APIs unless every trusted-import precondition is satisfied.",
|
|
439
|
+
cause: options?.cause
|
|
440
|
+
});
|
|
441
|
+
this.name = "TrustedImportError";
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
var RECORDED_CAPTURE_GUARD_CODES = [
|
|
445
|
+
"RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION",
|
|
446
|
+
"RECORDED_CAPTURE_RAW_SQL_DISABLED",
|
|
447
|
+
"REVISION_TRACKING_RAW_SQL_DISABLED"
|
|
448
|
+
];
|
|
449
|
+
function isRecordedCaptureGuardCode(value) {
|
|
450
|
+
return RECORDED_CAPTURE_GUARD_CODES.includes(value);
|
|
451
|
+
}
|
|
452
|
+
function isRecordedCaptureGuardError(error, code) {
|
|
453
|
+
if (!(error instanceof ConfigurationError)) return false;
|
|
454
|
+
const actual = error.details.code;
|
|
455
|
+
if (!isRecordedCaptureGuardCode(actual)) return false;
|
|
456
|
+
return code === void 0 || actual === code;
|
|
457
|
+
}
|
|
373
458
|
var STORE_NOT_INITIALIZED_REASON_PHRASE = {
|
|
374
459
|
missing: "is not initialized",
|
|
375
460
|
stale: "is stale (recorded materialization signature no longer matches)",
|
|
@@ -383,18 +468,36 @@ var StoreNotInitializedError = class extends TypeGraphError {
|
|
|
383
468
|
// accidentally-colliding extra key.
|
|
384
469
|
constructor(graphId, reason, options) {
|
|
385
470
|
super(
|
|
386
|
-
|
|
471
|
+
`${storageLabelFromLogicalName(options?.details?.logicalName)} for graph "${graphId}" ${STORE_NOT_INITIALIZED_REASON_PHRASE[reason]}. ` + storeNotInitializedAction(reason, options?.details?.logicalName),
|
|
387
472
|
"STORE_NOT_INITIALIZED",
|
|
388
473
|
{
|
|
389
474
|
details: { ...options?.details, graphId, reason },
|
|
390
475
|
category: "user",
|
|
391
|
-
suggestion: "Call createStoreWithSchema(graph, backend) once at application startup. createStore() attaches to an already-initialized database and does not materialize storage itself.",
|
|
476
|
+
suggestion: isStaleVectorSlot(reason, options?.details?.logicalName) ? "The field's declared shape (e.g. its dimension) changed after its storage was provisioned. Run store.reembedVectorField(kind, fieldPath) to recreate the storage at the new shape and re-embed." : "Call createStoreWithSchema(graph, backend) once at application startup. createStore() attaches to an already-initialized database and does not materialize storage itself.",
|
|
392
477
|
cause: options?.cause
|
|
393
478
|
}
|
|
394
479
|
);
|
|
395
480
|
this.name = "StoreNotInitializedError";
|
|
396
481
|
}
|
|
397
482
|
};
|
|
483
|
+
var VECTOR_LOGICAL_NAME_PREFIX = "vector:";
|
|
484
|
+
function isStaleVectorSlot(reason, logicalName) {
|
|
485
|
+
return reason === "stale" && typeof logicalName === "string" && logicalName.startsWith(VECTOR_LOGICAL_NAME_PREFIX);
|
|
486
|
+
}
|
|
487
|
+
function storeNotInitializedAction(reason, logicalName) {
|
|
488
|
+
if (isStaleVectorSlot(reason, logicalName)) {
|
|
489
|
+
return `The declared shape changed after provisioning \u2014 run store.reembedVectorField(kind, fieldPath) to recreate the storage at the new shape.`;
|
|
490
|
+
}
|
|
491
|
+
return `Run createStoreWithSchema(graph, backend) during application boot, outside request handlers and adopted transactions, before using createStore().`;
|
|
492
|
+
}
|
|
493
|
+
function storageLabelFromLogicalName(logicalName) {
|
|
494
|
+
if (typeof logicalName !== "string") return "runtime storage";
|
|
495
|
+
if (logicalName.startsWith(VECTOR_LOGICAL_NAME_PREFIX)) {
|
|
496
|
+
return `vector storage "${logicalName.slice(VECTOR_LOGICAL_NAME_PREFIX.length)}"`;
|
|
497
|
+
}
|
|
498
|
+
if (logicalName === "fulltext") return "fulltext storage";
|
|
499
|
+
return `"${logicalName}" storage`;
|
|
500
|
+
}
|
|
398
501
|
var DatabaseOperationError = class extends TypeGraphError {
|
|
399
502
|
constructor(message, details, options) {
|
|
400
503
|
super(message, "DATABASE_OPERATION_ERROR", {
|
|
@@ -484,6 +587,6 @@ function getErrorSuggestion(error) {
|
|
|
484
587
|
return isTypeGraphError(error) ? error.suggestion : void 0;
|
|
485
588
|
}
|
|
486
589
|
|
|
487
|
-
export { BackendDisposedError, CardinalityError, CompilerInvariantError, ConfigurationError, DatabaseOperationError, DisjointError, EagerMaterializationError, EdgeNotFoundError, EmbeddingDimensionChangedError, EndpointError, EndpointNotFoundError, KindNotFoundError, MigrationError, NodeConstraintNotFoundError, NodeIndexNotFoundError, NodeNotFoundError, RestrictedDeleteError, SchemaContentConflictError, SchemaMismatchError, StaleVersionError, StoreNotInitializedError, TransactionClosedError, TypeGraphError, UniquenessError, UnsupportedPredicateError, ValidationError, VersionConflictError, getErrorSuggestion, isConstraintError, isSystemError, isTypeGraphError, isUserRecoverable };
|
|
488
|
-
//# sourceMappingURL=chunk-
|
|
489
|
-
//# sourceMappingURL=chunk-
|
|
590
|
+
export { BackendDisposedError, CardinalityError, CompilerInvariantError, ConfigurationError, DatabaseOperationError, DisjointError, EagerMaterializationError, EdgeNotFoundError, EmbeddingDimensionChangedError, EndpointError, EndpointNotFoundError, GraphAlgorithmConvergenceError, InvalidEdgeWeightError, KindNotFoundError, MigrationError, NodeConstraintNotFoundError, NodeIndexNotFoundError, NodeNotFoundError, RECORDED_CAPTURE_GUARD_CODES, RestrictedDeleteError, SchemaContentConflictError, SchemaMismatchError, StaleVersionError, StoreNotInitializedError, TransactionClosedError, TrustedImportError, TypeGraphError, UniquenessError, UnsupportedBackendCapabilityError, UnsupportedPredicateError, ValidationError, VersionConflictError, getErrorSuggestion, isConstraintError, isRecordedCaptureGuardError, isSystemError, isTypeGraphError, isUserRecoverable };
|
|
591
|
+
//# sourceMappingURL=chunk-5PNMDJ7J.js.map
|
|
592
|
+
//# sourceMappingURL=chunk-5PNMDJ7J.js.map
|