@nicia-ai/typegraph 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +47 -0
  3. package/dist/ast-BVyihVbP.d.cts +564 -0
  4. package/dist/ast-BVyihVbP.d.ts +564 -0
  5. package/dist/backend/drizzle/index.cjs +41 -0
  6. package/dist/backend/drizzle/index.cjs.map +1 -0
  7. package/dist/backend/drizzle/index.d.cts +12 -0
  8. package/dist/backend/drizzle/index.d.ts +12 -0
  9. package/dist/backend/drizzle/index.js +12 -0
  10. package/dist/backend/drizzle/index.js.map +1 -0
  11. package/dist/backend/drizzle/postgres.cjs +27 -0
  12. package/dist/backend/drizzle/postgres.cjs.map +1 -0
  13. package/dist/backend/drizzle/postgres.d.cts +37 -0
  14. package/dist/backend/drizzle/postgres.d.ts +37 -0
  15. package/dist/backend/drizzle/postgres.js +10 -0
  16. package/dist/backend/drizzle/postgres.js.map +1 -0
  17. package/dist/backend/drizzle/schema/postgres.cjs +40 -0
  18. package/dist/backend/drizzle/schema/postgres.cjs.map +1 -0
  19. package/dist/backend/drizzle/schema/postgres.d.cts +2419 -0
  20. package/dist/backend/drizzle/schema/postgres.d.ts +2419 -0
  21. package/dist/backend/drizzle/schema/postgres.js +7 -0
  22. package/dist/backend/drizzle/schema/postgres.js.map +1 -0
  23. package/dist/backend/drizzle/schema/sqlite.cjs +40 -0
  24. package/dist/backend/drizzle/schema/sqlite.cjs.map +1 -0
  25. package/dist/backend/drizzle/schema/sqlite.d.cts +2647 -0
  26. package/dist/backend/drizzle/schema/sqlite.d.ts +2647 -0
  27. package/dist/backend/drizzle/schema/sqlite.js +7 -0
  28. package/dist/backend/drizzle/schema/sqlite.js.map +1 -0
  29. package/dist/backend/drizzle/sqlite.cjs +27 -0
  30. package/dist/backend/drizzle/sqlite.cjs.map +1 -0
  31. package/dist/backend/drizzle/sqlite.d.cts +36 -0
  32. package/dist/backend/drizzle/sqlite.d.ts +36 -0
  33. package/dist/backend/drizzle/sqlite.js +10 -0
  34. package/dist/backend/drizzle/sqlite.js.map +1 -0
  35. package/dist/backend/postgres/index.cjs +53 -0
  36. package/dist/backend/postgres/index.cjs.map +1 -0
  37. package/dist/backend/postgres/index.d.cts +12 -0
  38. package/dist/backend/postgres/index.d.ts +12 -0
  39. package/dist/backend/postgres/index.js +12 -0
  40. package/dist/backend/postgres/index.js.map +1 -0
  41. package/dist/backend/sqlite/index.cjs +117 -0
  42. package/dist/backend/sqlite/index.cjs.map +1 -0
  43. package/dist/backend/sqlite/index.d.cts +71 -0
  44. package/dist/backend/sqlite/index.d.ts +71 -0
  45. package/dist/backend/sqlite/index.js +78 -0
  46. package/dist/backend/sqlite/index.js.map +1 -0
  47. package/dist/chunk-2QHQ2C4P.js +146 -0
  48. package/dist/chunk-2QHQ2C4P.js.map +1 -0
  49. package/dist/chunk-3A5TKOEJ.js +306 -0
  50. package/dist/chunk-3A5TKOEJ.js.map +1 -0
  51. package/dist/chunk-4PIEL2VO.js +162 -0
  52. package/dist/chunk-4PIEL2VO.js.map +1 -0
  53. package/dist/chunk-536PH5FT.js +342 -0
  54. package/dist/chunk-536PH5FT.js.map +1 -0
  55. package/dist/chunk-DBFCKELK.cjs +156 -0
  56. package/dist/chunk-DBFCKELK.cjs.map +1 -0
  57. package/dist/chunk-DDM2FZRJ.cjs +1143 -0
  58. package/dist/chunk-DDM2FZRJ.cjs.map +1 -0
  59. package/dist/chunk-DGUM43GV.js +10 -0
  60. package/dist/chunk-DGUM43GV.js.map +1 -0
  61. package/dist/chunk-F32HCHYA.cjs +680 -0
  62. package/dist/chunk-F32HCHYA.cjs.map +1 -0
  63. package/dist/chunk-IIAT36MI.js +353 -0
  64. package/dist/chunk-IIAT36MI.js.map +1 -0
  65. package/dist/chunk-JDAET5LO.js +236 -0
  66. package/dist/chunk-JDAET5LO.js.map +1 -0
  67. package/dist/chunk-JEQ2X3Z6.cjs +12 -0
  68. package/dist/chunk-JEQ2X3Z6.cjs.map +1 -0
  69. package/dist/chunk-JKTO7TW3.js +299 -0
  70. package/dist/chunk-JKTO7TW3.js.map +1 -0
  71. package/dist/chunk-K7SQ3SWP.js +497 -0
  72. package/dist/chunk-K7SQ3SWP.js.map +1 -0
  73. package/dist/chunk-L642L24T.js +142 -0
  74. package/dist/chunk-L642L24T.js.map +1 -0
  75. package/dist/chunk-MFVCSNIY.cjs +308 -0
  76. package/dist/chunk-MFVCSNIY.cjs.map +1 -0
  77. package/dist/chunk-MNO33ASC.cjs +240 -0
  78. package/dist/chunk-MNO33ASC.cjs.map +1 -0
  79. package/dist/chunk-N4AOJ3VF.cjs +154 -0
  80. package/dist/chunk-N4AOJ3VF.cjs.map +1 -0
  81. package/dist/chunk-P5CNM325.cjs +508 -0
  82. package/dist/chunk-P5CNM325.cjs.map +1 -0
  83. package/dist/chunk-RYT4H46I.js +646 -0
  84. package/dist/chunk-RYT4H46I.js.map +1 -0
  85. package/dist/chunk-SV5H3XM5.cjs +321 -0
  86. package/dist/chunk-SV5H3XM5.cjs.map +1 -0
  87. package/dist/chunk-TXHKFLWX.cjs +344 -0
  88. package/dist/chunk-TXHKFLWX.cjs.map +1 -0
  89. package/dist/chunk-UJAGXJDG.cjs +170 -0
  90. package/dist/chunk-UJAGXJDG.cjs.map +1 -0
  91. package/dist/chunk-VXRVGFCI.js +1128 -0
  92. package/dist/chunk-VXRVGFCI.js.map +1 -0
  93. package/dist/chunk-YM5AL65Y.cjs +357 -0
  94. package/dist/chunk-YM5AL65Y.cjs.map +1 -0
  95. package/dist/index.cjs +8334 -0
  96. package/dist/index.cjs.map +1 -0
  97. package/dist/index.d.cts +1365 -0
  98. package/dist/index.d.ts +1365 -0
  99. package/dist/index.js +8105 -0
  100. package/dist/index.js.map +1 -0
  101. package/dist/indexes/index.cjs +67 -0
  102. package/dist/indexes/index.cjs.map +1 -0
  103. package/dist/indexes/index.d.cts +62 -0
  104. package/dist/indexes/index.d.ts +62 -0
  105. package/dist/indexes/index.js +6 -0
  106. package/dist/indexes/index.js.map +1 -0
  107. package/dist/interchange/index.cjs +612 -0
  108. package/dist/interchange/index.cjs.map +1 -0
  109. package/dist/interchange/index.d.cts +288 -0
  110. package/dist/interchange/index.d.ts +288 -0
  111. package/dist/interchange/index.js +598 -0
  112. package/dist/interchange/index.js.map +1 -0
  113. package/dist/profiler/index.cjs +793 -0
  114. package/dist/profiler/index.cjs.map +1 -0
  115. package/dist/profiler/index.d.cts +283 -0
  116. package/dist/profiler/index.d.ts +283 -0
  117. package/dist/profiler/index.js +785 -0
  118. package/dist/profiler/index.js.map +1 -0
  119. package/dist/store-60Lcfi0w.d.ts +2263 -0
  120. package/dist/store-Bifii8MZ.d.cts +2263 -0
  121. package/dist/test-helpers-BjyRYJZX.d.ts +22 -0
  122. package/dist/test-helpers-NoQXhleQ.d.cts +22 -0
  123. package/dist/types-BRzHlhKC.d.cts +14 -0
  124. package/dist/types-BRzHlhKC.d.ts +14 -0
  125. package/dist/types-BrSfFSpW.d.cts +158 -0
  126. package/dist/types-CX4cLd7M.d.ts +152 -0
  127. package/dist/types-CjZ7g_7v.d.ts +442 -0
  128. package/dist/types-DDOSfrih.d.cts +442 -0
  129. package/dist/types-D_3mEv2y.d.ts +158 -0
  130. package/dist/types-a5rAxC92.d.cts +152 -0
  131. package/package.json +201 -0
@@ -0,0 +1,236 @@
1
+ import { tables as tables$1 } from './chunk-4PIEL2VO.js';
2
+ import { tables } from './chunk-2QHQ2C4P.js';
3
+ import { getTableConfig as getTableConfig$1 } from 'drizzle-orm/pg-core';
4
+ import { getTableConfig } from 'drizzle-orm/sqlite-core';
5
+
6
+ function getSqliteColumnType(column) {
7
+ switch (column.columnType) {
8
+ case "SQLiteText": {
9
+ return "TEXT";
10
+ }
11
+ case "SQLiteInteger": {
12
+ return "INTEGER";
13
+ }
14
+ case "SQLiteReal": {
15
+ return "REAL";
16
+ }
17
+ case "SQLiteBlob": {
18
+ return "BLOB";
19
+ }
20
+ default: {
21
+ return "TEXT";
22
+ }
23
+ }
24
+ }
25
+ function formatDefaultValue(value) {
26
+ if (value === null) return "NULL";
27
+ if (typeof value === "string") return `'${value}'`;
28
+ if (typeof value === "number") return String(value);
29
+ if (typeof value === "boolean") return value ? "1" : "0";
30
+ return JSON.stringify(value);
31
+ }
32
+ function generateSqliteCreateTableSQL(table) {
33
+ const config = getTableConfig(table);
34
+ const columnDefs = [];
35
+ for (const column of config.columns) {
36
+ const parts = [
37
+ `"${column.name}"`,
38
+ getSqliteColumnType(column)
39
+ ];
40
+ if (column.notNull) {
41
+ parts.push("NOT NULL");
42
+ }
43
+ if (column.hasDefault && column.default !== void 0) {
44
+ parts.push(`DEFAULT ${formatDefaultValue(column.default)}`);
45
+ }
46
+ columnDefs.push(parts.join(" "));
47
+ }
48
+ const pk = config.primaryKeys[0];
49
+ if (pk) {
50
+ const pkColumns = pk.columns.map((c) => `"${c.name}"`).join(", ");
51
+ columnDefs.push(`PRIMARY KEY (${pkColumns})`);
52
+ }
53
+ return `CREATE TABLE IF NOT EXISTS "${config.name}" (
54
+ ${columnDefs.join(",\n ")}
55
+ );`;
56
+ }
57
+ function renderIndexColumn(col) {
58
+ if (col && typeof col === "object" && "name" in col) {
59
+ return `"${col.name}"`;
60
+ }
61
+ const sql = tryInlineSql(col);
62
+ if (sql !== void 0) {
63
+ return sql;
64
+ }
65
+ return "unknown";
66
+ }
67
+ function tryInlineSql(value) {
68
+ if (value && typeof value === "object" && "getSQL" in value) {
69
+ const maybe = value;
70
+ if (typeof maybe.getSQL === "function") {
71
+ return inlineSql(maybe.getSQL());
72
+ }
73
+ }
74
+ return inlineSql(value);
75
+ }
76
+ function flattenSqlChunk(chunk) {
77
+ if (typeof chunk === "string") {
78
+ return chunk;
79
+ }
80
+ if (typeof chunk === "object" && chunk !== null) {
81
+ if ("value" in chunk && Array.isArray(chunk.value)) {
82
+ return chunk.value.map((part) => flattenSqlChunk(part)).join("");
83
+ }
84
+ if ("queryChunks" in chunk && Array.isArray(chunk.queryChunks)) {
85
+ return chunk.queryChunks.map((part) => flattenSqlChunk(part)).join("");
86
+ }
87
+ if ("getSQL" in chunk) {
88
+ const maybe = chunk;
89
+ if (typeof maybe.getSQL === "function") {
90
+ return flattenSqlChunk(maybe.getSQL());
91
+ }
92
+ }
93
+ }
94
+ throw new Error(`Unable to inline SQL chunk: ${String(chunk)}`);
95
+ }
96
+ function inlineSql(value) {
97
+ try {
98
+ return flattenSqlChunk(value);
99
+ } catch {
100
+ return void 0;
101
+ }
102
+ }
103
+ function inlineSqlOrThrow(value, context) {
104
+ const inlined = inlineSql(value);
105
+ if (inlined === void 0) {
106
+ throw new Error(`Unable to inline SQL for ${context}`);
107
+ }
108
+ return inlined;
109
+ }
110
+ function generateSqliteCreateIndexSQL(table) {
111
+ const config = getTableConfig(table);
112
+ const statements = [];
113
+ for (const index of config.indexes) {
114
+ const indexConfig = index.config;
115
+ const columns = indexConfig.columns.map((c) => renderIndexColumn(c)).join(", ");
116
+ const unique = indexConfig.unique ? "UNIQUE " : "";
117
+ const where = indexConfig.where ? ` WHERE ${inlineSqlOrThrow(indexConfig.where, `SQLite index "${indexConfig.name}" WHERE clause`)}` : "";
118
+ statements.push(
119
+ `CREATE ${unique}INDEX IF NOT EXISTS "${indexConfig.name}" ON "${config.name}" (${columns})${where};`
120
+ );
121
+ }
122
+ return statements;
123
+ }
124
+ function generateSqliteDDL(tables3 = tables) {
125
+ const statements = [];
126
+ for (const table of Object.values(tables3)) {
127
+ statements.push(generateSqliteCreateTableSQL(table));
128
+ }
129
+ for (const table of Object.values(tables3)) {
130
+ statements.push(...generateSqliteCreateIndexSQL(table));
131
+ }
132
+ return statements;
133
+ }
134
+ function getSqliteMigrationSQL(tables3 = tables) {
135
+ return generateSqliteDDL(tables3).join("\n\n");
136
+ }
137
+ function getPgColumnType(column) {
138
+ switch (column.columnType) {
139
+ case "PgText": {
140
+ return "TEXT";
141
+ }
142
+ case "PgInteger": {
143
+ return "INTEGER";
144
+ }
145
+ case "PgBoolean": {
146
+ return "BOOLEAN";
147
+ }
148
+ case "PgJsonb": {
149
+ return "JSONB";
150
+ }
151
+ case "PgTimestamp": {
152
+ return column.config?.withTimezone ? "TIMESTAMPTZ" : "TIMESTAMP";
153
+ }
154
+ case "PgReal": {
155
+ return "REAL";
156
+ }
157
+ case "PgDoublePrecision": {
158
+ return "DOUBLE PRECISION";
159
+ }
160
+ case "PgCustomColumn": {
161
+ const dataType = column.getSQLType?.();
162
+ return dataType ?? "TEXT";
163
+ }
164
+ default: {
165
+ return "TEXT";
166
+ }
167
+ }
168
+ }
169
+ function formatPgDefaultValue(value) {
170
+ if (value === null) return "NULL";
171
+ if (typeof value === "string") return `'${value}'`;
172
+ if (typeof value === "number") return String(value);
173
+ if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
174
+ return JSON.stringify(value);
175
+ }
176
+ function generatePgCreateTableSQL(table) {
177
+ const config = getTableConfig$1(table);
178
+ const columnDefs = [];
179
+ for (const column of config.columns) {
180
+ const parts = [
181
+ `"${column.name}"`,
182
+ getPgColumnType(column)
183
+ ];
184
+ if (column.notNull) {
185
+ parts.push("NOT NULL");
186
+ }
187
+ if (column.hasDefault && column.default !== void 0) {
188
+ parts.push(`DEFAULT ${formatPgDefaultValue(column.default)}`);
189
+ }
190
+ columnDefs.push(parts.join(" "));
191
+ }
192
+ const pk = config.primaryKeys[0];
193
+ if (pk) {
194
+ const pkColumns = pk.columns.map((c) => `"${c.name}"`).join(", ");
195
+ columnDefs.push(`PRIMARY KEY (${pkColumns})`);
196
+ }
197
+ return `CREATE TABLE IF NOT EXISTS "${config.name}" (
198
+ ${columnDefs.join(",\n ")}
199
+ );`;
200
+ }
201
+ function generatePgCreateIndexSQL(table) {
202
+ const config = getTableConfig$1(table);
203
+ const statements = [];
204
+ for (const index of config.indexes) {
205
+ const indexConfig = index.config;
206
+ const columns = indexConfig.columns.map((c) => renderIndexColumn(c)).join(", ");
207
+ const unique = indexConfig.unique ? "UNIQUE " : "";
208
+ const method = indexConfig.method && indexConfig.method !== "btree" ? ` USING ${indexConfig.method}` : "";
209
+ const where = indexConfig.where ? ` WHERE ${inlineSqlOrThrow(indexConfig.where, `PostgreSQL index "${indexConfig.name}" WHERE clause`)}` : "";
210
+ statements.push(
211
+ `CREATE ${unique}INDEX IF NOT EXISTS "${indexConfig.name}" ON "${config.name}"${method} (${columns})${where};`
212
+ );
213
+ }
214
+ return statements;
215
+ }
216
+ function generatePostgresDDL(tables3 = tables$1) {
217
+ const statements = [];
218
+ for (const table of Object.values(tables3)) {
219
+ statements.push(generatePgCreateTableSQL(table));
220
+ }
221
+ for (const table of Object.values(tables3)) {
222
+ statements.push(...generatePgCreateIndexSQL(table));
223
+ }
224
+ return statements;
225
+ }
226
+ function getPostgresMigrationSQL(tables3 = tables$1) {
227
+ const extensionSql = "-- Enable pgvector extension for vector similarity search\nCREATE EXTENSION IF NOT EXISTS vector;";
228
+ const ddlSql = generatePostgresDDL(tables3).join("\n\n");
229
+ return `${extensionSql}
230
+
231
+ ${ddlSql}`;
232
+ }
233
+
234
+ export { generateSqliteDDL, getPostgresMigrationSQL, getSqliteMigrationSQL };
235
+ //# sourceMappingURL=chunk-JDAET5LO.js.map
236
+ //# sourceMappingURL=chunk-JDAET5LO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/backend/drizzle/test-helpers.ts"],"names":["getSqliteTableConfig","tables","getPgTableConfig"],"mappings":";;;;;AA2BA,SAAS,oBAAoB,MAAA,EAA8B;AACzD,EAAA,QAAQ,OAAO,UAAA;AAAY,IACzB,KAAK,YAAA,EAAc;AACjB,MAAA,OAAO,MAAA;AAAA,IACT;AAAA,IACA,KAAK,eAAA,EAAiB;AACpB,MAAA,OAAO,SAAA;AAAA,IACT;AAAA,IACA,KAAK,YAAA,EAAc;AACjB,MAAA,OAAO,MAAA;AAAA,IACT;AAAA,IACA,KAAK,YAAA,EAAc;AACjB,MAAA,OAAO,MAAA;AAAA,IACT;AAAA,IACA,SAAS;AAC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AA,EAAG;AACzC,IAAA,UAAA,CAAW,IAAA,CAAK,wBAAA,CAAyB,KAAK,CAAC,CAAA;AAAA,EACjD;AAEA,EAAA,KAAA,MAAW,KAAA,IAAS,MAAA,CAAO,MAAA,CAAOA,OAAM,CAAA,EAAG;AACzC,IAAA,UAAA,CAAW,IAAA,CAAK,GAAG,wBAAA,CAAyB,KAAK,CAAC,CAAA;AAAA,EACpD;AAEA,EAAA,OAAO,UAAA;AACT;AASO,SAAS,uBAAA,CAAwBA,UAAyBA,QAAAA,EAAwB;AAEvF,EAAA,MAAM,YAAA,GAAe,mGAAA;AACrB,EAAA,MAAM,MAAA,GAAS,mBAAA,CAAoBA,OAAM,CAAA,CAAE,KAAK,MAAM,CAAA;AACtD,EAAA,OAAO,GAAG,YAAY;;AAAA,EAAO,MAAM,CAAA,CAAA;AACrC","file":"chunk-JDAET5LO.js","sourcesContent":["/**\n * DDL generation utilities for TypeGraph backends.\n *\n * Provides utilities for generating DDL statements from Drizzle\n * table definitions. This ensures migrations match production schema.\n */\nimport {\n getTableConfig as getPgTableConfig,\n type PgColumn,\n type PgTableWithColumns,\n} from \"drizzle-orm/pg-core\";\nimport {\n getTableConfig as getSqliteTableConfig,\n type SQLiteColumn,\n type SQLiteTableWithColumns,\n} from \"drizzle-orm/sqlite-core\";\n\nimport { type PostgresTables, tables as postgresTables } from \"./schema/postgres\";\nimport { type SqliteTables, tables as sqliteTables } from \"./schema/sqlite\";\n\n// ============================================================\n// SQLite DDL Generation\n// ============================================================\n\n/**\n * Maps Drizzle column types to SQLite types.\n */\nfunction getSqliteColumnType(column: SQLiteColumn): string {\n switch (column.columnType) {\n case \"SQLiteText\": {\n return \"TEXT\";\n }\n case \"SQLiteInteger\": {\n return \"INTEGER\";\n }\n case \"SQLiteReal\": {\n return \"REAL\";\n }\n case \"SQLiteBlob\": {\n return \"BLOB\";\n }\n default: {\n return \"TEXT\";\n }\n }\n}\n\n/**\n * Formats a default value for SQLite.\n */\nfunction formatDefaultValue(value: unknown): string {\n if (value === null) return \"NULL\";\n if (typeof value === \"string\") return `'${value}'`;\n if (typeof value === \"number\") return String(value);\n if (typeof value === \"boolean\") return value ? \"1\" : \"0\";\n // For other types, use JSON.stringify to avoid [object Object]\n return JSON.stringify(value);\n}\n\n/**\n * Generates CREATE TABLE SQL from a Drizzle SQLite table definition.\n */\nfunction generateSqliteCreateTableSQL(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n table: SQLiteTableWithColumns<any>,\n): string {\n const config = getSqliteTableConfig(table);\n const columnDefs: string[] = [];\n\n // Generate column definitions\n for (const column of config.columns) {\n const parts: string[] = [\n `\"${column.name}\"`,\n getSqliteColumnType(column as SQLiteColumn),\n ];\n\n if (column.notNull) {\n parts.push(\"NOT NULL\");\n }\n\n if (column.hasDefault && column.default !== undefined) {\n parts.push(`DEFAULT ${formatDefaultValue(column.default)}`);\n }\n\n columnDefs.push(parts.join(\" \"));\n }\n\n // Add primary key constraint\n const pk = config.primaryKeys[0];\n if (pk) {\n const pkColumns = pk.columns.map((c) => `\"${c.name}\"`).join(\", \");\n columnDefs.push(`PRIMARY KEY (${pkColumns})`);\n }\n\n return `CREATE TABLE IF NOT EXISTS \"${config.name}\" (\\n ${columnDefs.join(\",\\n \")}\\n);`;\n}\n\n/**\n * Gets the column name from an index column, handling both Column and SQL types.\n */\nfunction renderIndexColumn(col: unknown): string {\n if (col && typeof col === \"object\" && \"name\" in col) {\n return `\"${(col as { name: string }).name}\"`;\n }\n\n const sql = tryInlineSql(col);\n if (sql !== undefined) {\n return sql;\n }\n\n return \"unknown\";\n}\n\nfunction tryInlineSql(value: unknown): string | undefined {\n if (value && typeof value === \"object\" && \"getSQL\" in value) {\n const maybe = value as { getSQL?: () => unknown };\n if (typeof maybe.getSQL === \"function\") {\n return inlineSql(maybe.getSQL());\n }\n }\n\n return inlineSql(value);\n}\n\nfunction flattenSqlChunk(chunk: unknown): string {\n if (typeof chunk === \"string\") {\n return chunk;\n }\n\n if (typeof chunk === \"object\" && chunk !== null) {\n if (\"value\" in chunk && Array.isArray((chunk as { value: unknown }).value)) {\n return (chunk as { value: readonly unknown[] }).value\n .map((part) => flattenSqlChunk(part))\n .join(\"\");\n }\n\n if (\n \"queryChunks\" in chunk &&\n Array.isArray((chunk as { queryChunks: unknown }).queryChunks)\n ) {\n return (chunk as { queryChunks: readonly unknown[] }).queryChunks\n .map((part) => flattenSqlChunk(part))\n .join(\"\");\n }\n\n if (\"getSQL\" in chunk) {\n const maybe = chunk as { getSQL?: () => unknown };\n if (typeof maybe.getSQL === \"function\") {\n return flattenSqlChunk(maybe.getSQL());\n }\n }\n }\n\n throw new Error(`Unable to inline SQL chunk: ${String(chunk)}`);\n}\n\nfunction inlineSql(value: unknown): string | undefined {\n try {\n return flattenSqlChunk(value);\n } catch {\n return undefined;\n }\n}\n\nfunction inlineSqlOrThrow(value: unknown, context: string): string {\n const inlined = inlineSql(value);\n if (inlined === undefined) {\n throw new Error(`Unable to inline SQL for ${context}`);\n }\n return inlined;\n}\n\n/**\n * Generates CREATE INDEX SQL statements from a Drizzle SQLite table definition.\n */\nfunction generateSqliteCreateIndexSQL(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n table: SQLiteTableWithColumns<any>,\n): string[] {\n const config = getSqliteTableConfig(table);\n const statements: string[] = [];\n\n for (const index of config.indexes) {\n const indexConfig = index.config;\n const columns = indexConfig.columns\n .map((c) => renderIndexColumn(c))\n .join(\", \");\n const unique = indexConfig.unique ? \"UNIQUE \" : \"\";\n const where =\n indexConfig.where ?\n ` WHERE ${inlineSqlOrThrow(indexConfig.where, `SQLite index \"${indexConfig.name}\" WHERE clause`)}`\n : \"\";\n\n statements.push(\n `CREATE ${unique}INDEX IF NOT EXISTS \"${indexConfig.name}\" ON \"${config.name}\" (${columns})${where};`,\n );\n }\n\n return statements;\n}\n\n/**\n * Generates all DDL statements for the given SQLite tables.\n */\nexport function generateSqliteDDL(tables: SqliteTables = sqliteTables): string[] {\n const statements: string[] = [];\n\n // Generate in dependency order (tables first, then indexes)\n for (const table of Object.values(tables)) {\n statements.push(generateSqliteCreateTableSQL(table));\n }\n\n for (const table of Object.values(tables)) {\n statements.push(...generateSqliteCreateIndexSQL(table));\n }\n\n return statements;\n}\n\n/**\n * Generates a single SQL string for SQLite migrations.\n * Convenience function that joins all DDL statements.\n */\nexport function getSqliteMigrationSQL(tables: SqliteTables = sqliteTables): string {\n return generateSqliteDDL(tables).join(\"\\n\\n\");\n}\n\n// ============================================================\n// PostgreSQL DDL Generation\n// ============================================================\n\n/**\n * Maps Drizzle column types to PostgreSQL types.\n */\nfunction getPgColumnType(column: PgColumn): string {\n switch (column.columnType) {\n case \"PgText\": {\n return \"TEXT\";\n }\n case \"PgInteger\": {\n return \"INTEGER\";\n }\n case \"PgBoolean\": {\n return \"BOOLEAN\";\n }\n case \"PgJsonb\": {\n return \"JSONB\";\n }\n case \"PgTimestamp\": {\n // Check if it has timezone\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n return (column as any).config?.withTimezone ? \"TIMESTAMPTZ\" : \"TIMESTAMP\";\n }\n case \"PgReal\": {\n return \"REAL\";\n }\n case \"PgDoublePrecision\": {\n return \"DOUBLE PRECISION\";\n }\n case \"PgCustomColumn\": {\n // Custom column type - get the SQL type from dataType()\n // This handles our vector column type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n const dataType = (column as any).getSQLType?.() as string | undefined;\n return dataType ?? \"TEXT\";\n }\n default: {\n return \"TEXT\";\n }\n }\n}\n\n/**\n * Formats a default value for PostgreSQL.\n */\nfunction formatPgDefaultValue(value: unknown): string {\n if (value === null) return \"NULL\";\n if (typeof value === \"string\") return `'${value}'`;\n if (typeof value === \"number\") return String(value);\n if (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n // For other types, use JSON.stringify to avoid [object Object]\n return JSON.stringify(value);\n}\n\n/**\n * Generates CREATE TABLE SQL from a Drizzle PostgreSQL table definition.\n */\nfunction generatePgCreateTableSQL(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n table: PgTableWithColumns<any>,\n): string {\n const config = getPgTableConfig(table);\n const columnDefs: string[] = [];\n\n // Generate column definitions\n for (const column of config.columns) {\n const parts: string[] = [\n `\"${column.name}\"`,\n getPgColumnType(column),\n ];\n\n if (column.notNull) {\n parts.push(\"NOT NULL\");\n }\n\n if (column.hasDefault && column.default !== undefined) {\n parts.push(`DEFAULT ${formatPgDefaultValue(column.default)}`);\n }\n\n columnDefs.push(parts.join(\" \"));\n }\n\n // Add primary key constraint\n const pk = config.primaryKeys[0];\n if (pk) {\n const pkColumns = pk.columns.map((c) => `\"${c.name}\"`).join(\", \");\n columnDefs.push(`PRIMARY KEY (${pkColumns})`);\n }\n\n return `CREATE TABLE IF NOT EXISTS \"${config.name}\" (\\n ${columnDefs.join(\",\\n \")}\\n);`;\n}\n\n/**\n * Generates CREATE INDEX SQL statements from a Drizzle PostgreSQL table definition.\n */\nfunction generatePgCreateIndexSQL(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n table: PgTableWithColumns<any>,\n): string[] {\n const config = getPgTableConfig(table);\n const statements: string[] = [];\n\n for (const index of config.indexes) {\n const indexConfig = index.config;\n const columns = indexConfig.columns\n .map((c) => renderIndexColumn(c))\n .join(\", \");\n const unique = indexConfig.unique ? \"UNIQUE \" : \"\";\n const method =\n indexConfig.method && indexConfig.method !== \"btree\" ?\n ` USING ${indexConfig.method}`\n : \"\";\n const where =\n indexConfig.where ?\n ` WHERE ${inlineSqlOrThrow(indexConfig.where, `PostgreSQL index \"${indexConfig.name}\" WHERE clause`)}`\n : \"\";\n\n statements.push(\n `CREATE ${unique}INDEX IF NOT EXISTS \"${indexConfig.name}\" ON \"${config.name}\"${method} (${columns})${where};`,\n );\n }\n\n return statements;\n}\n\n/**\n * Generates all DDL statements for the given PostgreSQL tables.\n */\nexport function generatePostgresDDL(tables: PostgresTables = postgresTables): string[] {\n const statements: string[] = [];\n\n // Generate in dependency order (tables first, then indexes)\n for (const table of Object.values(tables)) {\n statements.push(generatePgCreateTableSQL(table));\n }\n\n for (const table of Object.values(tables)) {\n statements.push(...generatePgCreateIndexSQL(table));\n }\n\n return statements;\n}\n\n/**\n * Generates a single SQL string for PostgreSQL migrations.\n * Convenience function that joins all DDL statements.\n *\n * Includes CREATE EXTENSION for pgvector since the embeddings table\n * uses the native VECTOR type.\n */\nexport function getPostgresMigrationSQL(tables: PostgresTables = postgresTables): string {\n // pgvector extension is required for the embeddings table\n const extensionSql = \"-- Enable pgvector extension for vector similarity search\\nCREATE EXTENSION IF NOT EXISTS vector;\";\n const ddlSql = generatePostgresDDL(tables).join(\"\\n\\n\");\n return `${extensionSql}\\n\\n${ddlSql}`;\n}\n"]}
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
9
+
10
+ exports.__require = __require;
11
+ //# sourceMappingURL=chunk-JEQ2X3Z6.cjs.map
12
+ //# sourceMappingURL=chunk-JEQ2X3Z6.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"chunk-JEQ2X3Z6.cjs"}
@@ -0,0 +1,299 @@
1
+ // src/errors/index.ts
2
+ function formatCause(cause) {
3
+ if (cause instanceof Error) {
4
+ return cause.stack ?? cause.message;
5
+ }
6
+ if (typeof cause === "string") {
7
+ return cause;
8
+ }
9
+ if (typeof cause === "number" || typeof cause === "boolean" || typeof cause === "bigint") {
10
+ return String(cause);
11
+ }
12
+ if (typeof cause === "symbol") {
13
+ return cause.description ?? "Symbol";
14
+ }
15
+ if (cause === void 0) {
16
+ return "Unknown cause";
17
+ }
18
+ try {
19
+ return JSON.stringify(cause);
20
+ } catch (error) {
21
+ return `Unserializable cause: ${error instanceof Error ? error.message : "Unknown error"}`;
22
+ }
23
+ }
24
+ var TypeGraphError = class extends Error {
25
+ /** Machine-readable error code (e.g., "VALIDATION_ERROR") */
26
+ code;
27
+ /** Error category for handling strategies */
28
+ category;
29
+ /** Structured context about the error */
30
+ details;
31
+ /** Recovery guidance for users */
32
+ suggestion;
33
+ constructor(message, code, options) {
34
+ super(message, options.cause ? { cause: options.cause } : void 0);
35
+ this.name = "TypeGraphError";
36
+ this.code = code;
37
+ this.category = options.category;
38
+ this.details = Object.freeze(options.details ?? {});
39
+ if (options.suggestion !== void 0) {
40
+ this.suggestion = options.suggestion;
41
+ }
42
+ }
43
+ /**
44
+ * Returns a user-friendly error message with suggestion if available.
45
+ */
46
+ toUserMessage() {
47
+ if (this.suggestion) {
48
+ return `${this.message}
49
+
50
+ Suggestion: ${this.suggestion}`;
51
+ }
52
+ return this.message;
53
+ }
54
+ /**
55
+ * Returns a detailed string representation for logging.
56
+ */
57
+ toLogString() {
58
+ const lines = [
59
+ `[${this.code}] ${this.message}`,
60
+ ` Category: ${this.category}`
61
+ ];
62
+ if (this.suggestion) {
63
+ lines.push(` Suggestion: ${this.suggestion}`);
64
+ }
65
+ const detailKeys = Object.keys(this.details);
66
+ if (detailKeys.length > 0) {
67
+ lines.push(` Details: ${JSON.stringify(this.details)}`);
68
+ }
69
+ if (this.cause) {
70
+ lines.push(` Cause: ${formatCause(this.cause)}`);
71
+ }
72
+ return lines.join("\n");
73
+ }
74
+ };
75
+ var ValidationError = class extends TypeGraphError {
76
+ constructor(message, details, options) {
77
+ const fieldList = details.issues.length > 0 ? details.issues.map((index) => index.path || "(root)").join(", ") : "unknown";
78
+ super(message, "VALIDATION_ERROR", {
79
+ details,
80
+ category: "user",
81
+ suggestion: options?.suggestion ?? `Check the following fields: ${fieldList}. See error.details.issues for specific validation failures.`,
82
+ cause: options?.cause
83
+ });
84
+ this.name = "ValidationError";
85
+ }
86
+ };
87
+ var NodeNotFoundError = class extends TypeGraphError {
88
+ constructor(kind, id, options) {
89
+ super(`Node not found: ${kind}/${id}`, "NODE_NOT_FOUND", {
90
+ details: { kind, id },
91
+ category: "user",
92
+ suggestion: `Verify the node ID "${id}" exists and has not been deleted.`,
93
+ cause: options?.cause
94
+ });
95
+ this.name = "NodeNotFoundError";
96
+ }
97
+ };
98
+ var EdgeNotFoundError = class extends TypeGraphError {
99
+ constructor(kind, id, options) {
100
+ super(`Edge not found: ${kind}/${id}`, "EDGE_NOT_FOUND", {
101
+ details: { kind, id },
102
+ category: "user",
103
+ suggestion: `Verify the edge ID "${id}" exists and has not been deleted.`,
104
+ cause: options?.cause
105
+ });
106
+ this.name = "EdgeNotFoundError";
107
+ }
108
+ };
109
+ var KindNotFoundError = class extends TypeGraphError {
110
+ constructor(kind, type, options) {
111
+ super(
112
+ `${type === "node" ? "Node" : "Edge"} kind not found: ${kind}`,
113
+ "KIND_NOT_FOUND",
114
+ {
115
+ details: { kind, type },
116
+ category: "user",
117
+ suggestion: `Verify "${kind}" is defined in your graph schema and spelled correctly.`,
118
+ cause: options?.cause
119
+ }
120
+ );
121
+ this.name = "KindNotFoundError";
122
+ }
123
+ };
124
+ var EndpointNotFoundError = class extends TypeGraphError {
125
+ constructor(details, options) {
126
+ super(
127
+ `Endpoint node not found for edge "${details.edgeKind}": ${details.nodeKind}/${details.nodeId} (${details.endpoint})`,
128
+ "ENDPOINT_NOT_FOUND",
129
+ {
130
+ details,
131
+ category: "constraint",
132
+ suggestion: `Ensure the ${details.endpoint} node exists before creating the edge.`,
133
+ cause: options?.cause
134
+ }
135
+ );
136
+ this.name = "EndpointNotFoundError";
137
+ }
138
+ };
139
+ var EndpointError = class extends TypeGraphError {
140
+ constructor(details, options) {
141
+ const expected = details.expectedKinds.join(" | ");
142
+ super(
143
+ `Invalid ${details.endpoint} endpoint for edge "${details.edgeKind}": got "${details.actualKind}", expected ${expected}`,
144
+ "ENDPOINT_ERROR",
145
+ {
146
+ details,
147
+ category: "constraint",
148
+ suggestion: `Use a node of type ${expected} as the ${details.endpoint} endpoint.`,
149
+ cause: options?.cause
150
+ }
151
+ );
152
+ this.name = "EndpointError";
153
+ }
154
+ };
155
+ var UniquenessError = class extends TypeGraphError {
156
+ constructor(details, options) {
157
+ const fieldList = details.fields.join(", ");
158
+ super(
159
+ `Uniqueness violation on "${details.kind}": constraint "${details.constraintName}" (fields: ${fieldList}) conflicts with existing node ${details.existingId}`,
160
+ "UNIQUENESS_VIOLATION",
161
+ {
162
+ details,
163
+ category: "constraint",
164
+ suggestion: `Change the values for fields [${fieldList}] to be unique, or update the existing node ${details.existingId} instead.`,
165
+ cause: options?.cause
166
+ }
167
+ );
168
+ this.name = "UniquenessError";
169
+ }
170
+ };
171
+ var CardinalityError = class extends TypeGraphError {
172
+ constructor(details, options) {
173
+ super(
174
+ `Cardinality violation: "${details.edgeKind}" from ${details.fromKind}/${details.fromId} allows "${details.cardinality}" but ${details.existingCount} edge(s) already exist`,
175
+ "CARDINALITY_ERROR",
176
+ {
177
+ details,
178
+ category: "constraint",
179
+ suggestion: details.cardinality === "one" || details.cardinality === "unique" ? `Delete the existing edge before creating a new one, or use cardinality "many".` : `Check if the cardinality constraint "${details.cardinality}" is correct for your use case.`,
180
+ cause: options?.cause
181
+ }
182
+ );
183
+ this.name = "CardinalityError";
184
+ }
185
+ };
186
+ var DisjointError = class extends TypeGraphError {
187
+ constructor(details, options) {
188
+ super(
189
+ `Disjoint constraint violation: cannot create ${details.attemptedKind} with ID "${details.nodeId}" - conflicts with existing ${details.conflictingKind}`,
190
+ "DISJOINT_ERROR",
191
+ {
192
+ details,
193
+ category: "constraint",
194
+ suggestion: `Use a different ID for the new ${details.attemptedKind} node, or delete the existing ${details.conflictingKind}/${details.nodeId} first.`,
195
+ cause: options?.cause
196
+ }
197
+ );
198
+ this.name = "DisjointError";
199
+ }
200
+ };
201
+ var RestrictedDeleteError = class extends TypeGraphError {
202
+ constructor(details, options) {
203
+ const edgeList = details.edgeKinds.join(", ");
204
+ super(
205
+ `Cannot delete ${details.nodeKind}/${details.nodeId}: ${details.edgeCount} connected edge(s) exist (${edgeList})`,
206
+ "RESTRICTED_DELETE",
207
+ {
208
+ details,
209
+ category: "constraint",
210
+ suggestion: `Delete the connected edges first, or change onDelete behavior to "cascade" (auto-delete edges) or "disconnect" (soft-delete edges).`,
211
+ cause: options?.cause
212
+ }
213
+ );
214
+ this.name = "RestrictedDeleteError";
215
+ }
216
+ };
217
+ var VersionConflictError = class extends TypeGraphError {
218
+ constructor(details, options) {
219
+ super(
220
+ `Version conflict on ${details.kind}/${details.id}: expected version ${details.expectedVersion}, found ${details.actualVersion}`,
221
+ "VERSION_CONFLICT",
222
+ {
223
+ details,
224
+ category: "system",
225
+ suggestion: `Fetch the latest version of the entity and retry the operation. This error indicates concurrent modification.`,
226
+ cause: options?.cause
227
+ }
228
+ );
229
+ this.name = "VersionConflictError";
230
+ }
231
+ };
232
+ var SchemaMismatchError = class extends TypeGraphError {
233
+ constructor(details, options) {
234
+ super(
235
+ `Schema mismatch for graph "${details.graphId}": code schema differs from database schema`,
236
+ "SCHEMA_MISMATCH",
237
+ {
238
+ details,
239
+ category: "system",
240
+ suggestion: `Run schema migration to update the database, or use createStoreWithSchema() for automatic migration.`,
241
+ cause: options?.cause
242
+ }
243
+ );
244
+ this.name = "SchemaMismatchError";
245
+ }
246
+ };
247
+ var MigrationError = class extends TypeGraphError {
248
+ constructor(message, details, options) {
249
+ super(message, "MIGRATION_ERROR", {
250
+ details,
251
+ category: "system",
252
+ suggestion: `Review the schema changes and ensure they are backwards compatible, or implement a data migration.`,
253
+ cause: options?.cause
254
+ });
255
+ this.name = "MigrationError";
256
+ }
257
+ };
258
+ var ConfigurationError = class extends TypeGraphError {
259
+ constructor(message, details = {}, options) {
260
+ super(message, "CONFIGURATION_ERROR", {
261
+ details,
262
+ category: "user",
263
+ suggestion: options?.suggestion ?? `Review your graph definition for errors.`,
264
+ cause: options?.cause
265
+ });
266
+ this.name = "ConfigurationError";
267
+ }
268
+ };
269
+ var UnsupportedPredicateError = class extends TypeGraphError {
270
+ constructor(message, details = {}, options) {
271
+ super(message, "UNSUPPORTED_PREDICATE", {
272
+ details,
273
+ category: "system",
274
+ suggestion: options?.suggestion ?? `This predicate may not be supported by your database backend. Check the documentation for supported predicates.`,
275
+ cause: options?.cause
276
+ });
277
+ this.name = "UnsupportedPredicateError";
278
+ }
279
+ };
280
+ function isTypeGraphError(error) {
281
+ return error instanceof TypeGraphError;
282
+ }
283
+ function isUserRecoverable(error) {
284
+ if (!isTypeGraphError(error)) return false;
285
+ return error.category === "user" || error.category === "constraint";
286
+ }
287
+ function isSystemError(error) {
288
+ return isTypeGraphError(error) && error.category === "system";
289
+ }
290
+ function isConstraintError(error) {
291
+ return isTypeGraphError(error) && error.category === "constraint";
292
+ }
293
+ function getErrorSuggestion(error) {
294
+ return isTypeGraphError(error) ? error.suggestion : void 0;
295
+ }
296
+
297
+ export { CardinalityError, ConfigurationError, DisjointError, EdgeNotFoundError, EndpointError, EndpointNotFoundError, KindNotFoundError, MigrationError, NodeNotFoundError, RestrictedDeleteError, SchemaMismatchError, TypeGraphError, UniquenessError, UnsupportedPredicateError, ValidationError, VersionConflictError, getErrorSuggestion, isConstraintError, isSystemError, isTypeGraphError, isUserRecoverable };
298
+ //# sourceMappingURL=chunk-JKTO7TW3.js.map
299
+ //# sourceMappingURL=chunk-JKTO7TW3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors/index.ts"],"names":[],"mappings":";AAmDA,SAAS,YAAY,KAAA,EAAwB;AAC3C,EAAA,IAAI,iBAAiB,KAAA,EAAO;AAC1B,IAAA,OAAO,KAAA,CAAM,SAAS,KAAA,CAAM,OAAA;AAAA,EAC9B;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,IACE,OAAO,U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,CAAA,EAAG,OAAO,KAAA;AACrC,EAAA,OAAO,KAAA,CAAM,QAAA,KAAa,MAAA,IAAU,KAAA,CAAM,QAAA,KAAa,YAAA;AACzD;AAUO,SAAS,cAAc,KAAA,EAAyB;AACrD,EAAA,OAAO,gBAAA,CAAiB,KAAK,CAAA,IAAK,KAAA,CAAM,QAAA,KAAa,QAAA;AACvD;AAKO,SAAS,kBAAkB,KAAA,EAAyB;AACzD,EAAA,OAAO,gBAAA,CAAiB,KAAK,CAAA,IAAK,KAAA,CAAM,QAAA,KAAa,YAAA;AACvD;AAKO,SAAS,mBAAmB,KAAA,EAAoC;AACrE,EAAA,OAAO,gBAAA,CAAiB,KAAK,CAAA,GAAI,KAAA,CAAM,UAAA,GAAa,MAAA;AACtD","file":"chunk-JKTO7TW3.js","sourcesContent":["/**\n * TypeGraph Error Hierarchy\n *\n * All errors extend TypeGraphError with:\n * - `code`: Machine-readable error code for programmatic handling\n * - `category`: Classification for error handling strategies\n * - `suggestion`: Optional recovery guidance for users\n * - `details`: Structured context about the error\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({ name: \"\" });\n * } catch (error) {\n * if (isTypeGraphError(error)) {\n * console.error(error.toUserMessage());\n * if (isUserRecoverable(error)) {\n * // Show to user for correction\n * }\n * }\n * }\n * ```\n */\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Error category for programmatic handling.\n *\n * - `user`: Caused by invalid input or incorrect usage. Recoverable by fixing input.\n * - `constraint`: Business rule or schema constraint violation. Recoverable by changing data.\n * - `system`: Internal error or infrastructure issue. May require investigation or retry.\n */\nexport type ErrorCategory = \"user\" | \"constraint\" | \"system\";\n\n/**\n * Options for TypeGraphError constructor.\n */\nexport type TypeGraphErrorOptions = Readonly<{\n /** Structured context about the error */\n details?: Record<string, unknown>;\n /** Error category for handling strategies */\n category: ErrorCategory;\n /** Recovery guidance for users */\n suggestion?: string;\n /** Underlying cause of the error */\n cause?: unknown;\n}>;\n\nfunction formatCause(cause: unknown): string {\n if (cause instanceof Error) {\n return cause.stack ?? cause.message;\n }\n if (typeof cause === \"string\") {\n return cause;\n }\n if (\n typeof cause === \"number\" ||\n typeof cause === \"boolean\" ||\n typeof cause === \"bigint\"\n ) {\n return String(cause);\n }\n if (typeof cause === \"symbol\") {\n return cause.description ?? \"Symbol\";\n }\n if (cause === undefined) {\n return \"Unknown cause\";\n }\n\n try {\n return JSON.stringify(cause);\n } catch (error) {\n return `Unserializable cause: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`;\n }\n}\n\n// ============================================================\n// Base Error\n// ============================================================\n\n/**\n * Base error class for all TypeGraph errors.\n *\n * Provides structured error information for both programmatic handling\n * and user-friendly messages.\n */\nexport class TypeGraphError extends Error {\n /** Machine-readable error code (e.g., \"VALIDATION_ERROR\") */\n readonly code: string;\n\n /** Error category for handling strategies */\n readonly category: ErrorCategory;\n\n /** Structured context about the error */\n readonly details: Readonly<Record<string, unknown>>;\n\n /** Recovery guidance for users */\n readonly suggestion?: string;\n\n constructor(message: string, code: string, options: TypeGraphErrorOptions) {\n super(message, options.cause ? { cause: options.cause } : undefined);\n this.name = \"TypeGraphError\";\n this.code = code;\n this.category = options.category;\n this.details = Object.freeze(options.details ?? {});\n if (options.suggestion !== undefined) {\n this.suggestion = options.suggestion;\n }\n }\n\n /**\n * Returns a user-friendly error message with suggestion if available.\n */\n toUserMessage(): string {\n if (this.suggestion) {\n return `${this.message}\\n\\nSuggestion: ${this.suggestion}`;\n }\n return this.message;\n }\n\n /**\n * Returns a detailed string representation for logging.\n */\n toLogString(): string {\n const lines = [\n `[${this.code}] ${this.message}`,\n ` Category: ${this.category}`,\n ];\n\n if (this.suggestion) {\n lines.push(` Suggestion: ${this.suggestion}`);\n }\n\n const detailKeys = Object.keys(this.details);\n if (detailKeys.length > 0) {\n lines.push(` Details: ${JSON.stringify(this.details)}`);\n }\n\n if (this.cause) {\n lines.push(` Cause: ${formatCause(this.cause)}`);\n }\n\n return lines.join(\"\\n\");\n }\n}\n\n// ============================================================\n// Validation Errors (category: \"user\")\n// ============================================================\n\n/**\n * Validation issue from Zod or custom validation.\n */\nexport type ValidationIssue = Readonly<{\n /** Path to the invalid field (e.g., \"address.city\") */\n path: string;\n /** Human-readable error message */\n message: string;\n /** Zod error code if from Zod validation */\n code?: string;\n}>;\n\n/**\n * Details for ValidationError.\n */\nexport type ValidationErrorDetails = Readonly<{\n /** Type of entity being validated */\n entityType?: \"node\" | \"edge\";\n /** Kind/type name of the entity */\n kind?: string;\n /** Operation being performed */\n operation?: \"create\" | \"update\";\n /** Entity ID if updating */\n id?: string;\n /** Individual validation issues */\n issues: readonly ValidationIssue[];\n}>;\n\n/**\n * Thrown when schema validation fails during node or edge operations.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({ email: \"invalid\" });\n * } catch (error) {\n * if (error instanceof ValidationError) {\n * console.log(error.details.issues);\n * // [{ path: \"email\", message: \"Invalid email\" }]\n * }\n * }\n * ```\n */\nexport class ValidationError extends TypeGraphError {\n declare readonly details: ValidationErrorDetails;\n\n constructor(\n message: string,\n details: ValidationErrorDetails,\n options?: { cause?: unknown; suggestion?: string },\n ) {\n const fieldList =\n details.issues.length > 0 ?\n details.issues.map((index) => index.path || \"(root)\").join(\", \")\n : \"unknown\";\n\n super(message, \"VALIDATION_ERROR\", {\n details,\n category: \"user\",\n suggestion:\n options?.suggestion ??\n `Check the following fields: ${fieldList}. See error.details.issues for specific validation failures.`,\n cause: options?.cause,\n });\n this.name = \"ValidationError\";\n }\n}\n\n// ============================================================\n// Not Found Errors (category: \"user\")\n// ============================================================\n\n/**\n * Thrown when a node is not found.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.get(\"nonexistent-id\");\n * } catch (error) {\n * if (error instanceof NodeNotFoundError) {\n * console.log(error.details.kind, error.details.id);\n * }\n * }\n * ```\n */\nexport class NodeNotFoundError extends TypeGraphError {\n constructor(kind: string, id: string, options?: { cause?: unknown }) {\n super(`Node not found: ${kind}/${id}`, \"NODE_NOT_FOUND\", {\n details: { kind, id },\n category: \"user\",\n suggestion: `Verify the node ID \"${id}\" exists and has not been deleted.`,\n cause: options?.cause,\n });\n this.name = \"NodeNotFoundError\";\n }\n}\n\n/**\n * Thrown when an edge is not found.\n */\nexport class EdgeNotFoundError extends TypeGraphError {\n constructor(kind: string, id: string, options?: { cause?: unknown }) {\n super(`Edge not found: ${kind}/${id}`, \"EDGE_NOT_FOUND\", {\n details: { kind, id },\n category: \"user\",\n suggestion: `Verify the edge ID \"${id}\" exists and has not been deleted.`,\n cause: options?.cause,\n });\n this.name = \"EdgeNotFoundError\";\n }\n}\n\n/**\n * Thrown when a kind is not found in the graph registry.\n */\nexport class KindNotFoundError extends TypeGraphError {\n constructor(\n kind: string,\n type: \"node\" | \"edge\",\n options?: { cause?: unknown },\n ) {\n super(\n `${type === \"node\" ? \"Node\" : \"Edge\"} kind not found: ${kind}`,\n \"KIND_NOT_FOUND\",\n {\n details: { kind, type },\n category: \"user\",\n suggestion: `Verify \"${kind}\" is defined in your graph schema and spelled correctly.`,\n cause: options?.cause,\n },\n );\n this.name = \"KindNotFoundError\";\n }\n}\n\n// ============================================================\n// Constraint Errors (category: \"constraint\")\n// ============================================================\n\n/**\n * Thrown when edge endpoint node does not exist or is deleted.\n */\nexport class EndpointNotFoundError extends TypeGraphError {\n constructor(\n details: Readonly<{\n edgeKind: string;\n endpoint: \"from\" | \"to\";\n nodeKind: string;\n nodeId: string;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Endpoint node not found for edge \"${details.edgeKind}\": ${details.nodeKind}/${details.nodeId} (${details.endpoint})`,\n \"ENDPOINT_NOT_FOUND\",\n {\n details,\n category: \"constraint\",\n suggestion: `Ensure the ${details.endpoint} node exists before creating the edge.`,\n cause: options?.cause,\n },\n );\n this.name = \"EndpointNotFoundError\";\n }\n}\n\n/**\n * Thrown when edge endpoint has wrong node type.\n */\nexport class EndpointError extends TypeGraphError {\n constructor(\n details: Readonly<{\n edgeKind: string;\n endpoint: \"from\" | \"to\";\n actualKind: string;\n expectedKinds: readonly string[];\n }>,\n options?: { cause?: unknown },\n ) {\n const expected = details.expectedKinds.join(\" | \");\n super(\n `Invalid ${details.endpoint} endpoint for edge \"${details.edgeKind}\": got \"${details.actualKind}\", expected ${expected}`,\n \"ENDPOINT_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion: `Use a node of type ${expected} as the ${details.endpoint} endpoint.`,\n cause: options?.cause,\n },\n );\n this.name = \"EndpointError\";\n }\n}\n\n/**\n * Thrown when uniqueness constraint is violated.\n */\nexport class UniquenessError extends TypeGraphError {\n constructor(\n details: Readonly<{\n constraintName: string;\n kind: string;\n existingId: string;\n newId: string;\n fields: readonly string[];\n }>,\n options?: { cause?: unknown },\n ) {\n const fieldList = details.fields.join(\", \");\n super(\n `Uniqueness violation on \"${details.kind}\": constraint \"${details.constraintName}\" (fields: ${fieldList}) conflicts with existing node ${details.existingId}`,\n \"UNIQUENESS_VIOLATION\",\n {\n details,\n category: \"constraint\",\n suggestion: `Change the values for fields [${fieldList}] to be unique, or update the existing node ${details.existingId} instead.`,\n cause: options?.cause,\n },\n );\n this.name = \"UniquenessError\";\n }\n}\n\n/**\n * Thrown when cardinality constraint is violated.\n */\nexport class CardinalityError extends TypeGraphError {\n constructor(\n details: Readonly<{\n edgeKind: string;\n fromKind: string;\n fromId: string;\n cardinality: string;\n existingCount: number;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Cardinality violation: \"${details.edgeKind}\" from ${details.fromKind}/${details.fromId} allows \"${details.cardinality}\" but ${details.existingCount} edge(s) already exist`,\n \"CARDINALITY_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion:\n details.cardinality === \"one\" || details.cardinality === \"unique\" ?\n `Delete the existing edge before creating a new one, or use cardinality \"many\".`\n : `Check if the cardinality constraint \"${details.cardinality}\" is correct for your use case.`,\n cause: options?.cause,\n },\n );\n this.name = \"CardinalityError\";\n }\n}\n\n/**\n * Thrown when disjointness constraint is violated.\n *\n * Disjoint types cannot share the same ID - a node cannot be both\n * a Person and an Organization if they are declared disjoint.\n */\nexport class DisjointError extends TypeGraphError {\n constructor(\n details: Readonly<{\n nodeId: string;\n attemptedKind: string;\n conflictingKind: string;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Disjoint constraint violation: cannot create ${details.attemptedKind} with ID \"${details.nodeId}\" - conflicts with existing ${details.conflictingKind}`,\n \"DISJOINT_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion: `Use a different ID for the new ${details.attemptedKind} node, or delete the existing ${details.conflictingKind}/${details.nodeId} first.`,\n cause: options?.cause,\n },\n );\n this.name = \"DisjointError\";\n }\n}\n\n/**\n * Thrown when deletion is blocked due to existing edges (restrict behavior).\n */\nexport class RestrictedDeleteError extends TypeGraphError {\n constructor(\n details: Readonly<{\n nodeKind: string;\n nodeId: string;\n edgeCount: number;\n edgeKinds: readonly string[];\n }>,\n options?: { cause?: unknown },\n ) {\n const edgeList = details.edgeKinds.join(\", \");\n super(\n `Cannot delete ${details.nodeKind}/${details.nodeId}: ${details.edgeCount} connected edge(s) exist (${edgeList})`,\n \"RESTRICTED_DELETE\",\n {\n details,\n category: \"constraint\",\n suggestion: `Delete the connected edges first, or change onDelete behavior to \"cascade\" (auto-delete edges) or \"disconnect\" (soft-delete edges).`,\n cause: options?.cause,\n },\n );\n this.name = \"RestrictedDeleteError\";\n }\n}\n\n// ============================================================\n// Concurrency Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when optimistic locking detects a concurrent modification.\n *\n * This occurs when two operations try to update the same entity simultaneously.\n * The operation with the stale version fails.\n */\nexport class VersionConflictError extends TypeGraphError {\n constructor(\n details: Readonly<{\n kind: string;\n id: string;\n expectedVersion: number;\n actualVersion: number;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Version conflict on ${details.kind}/${details.id}: expected version ${details.expectedVersion}, found ${details.actualVersion}`,\n \"VERSION_CONFLICT\",\n {\n details,\n category: \"system\",\n suggestion: `Fetch the latest version of the entity and retry the operation. This error indicates concurrent modification.`,\n cause: options?.cause,\n },\n );\n this.name = \"VersionConflictError\";\n }\n}\n\n// ============================================================\n// Schema Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when the schema in code doesn't match the schema in the database.\n */\nexport class SchemaMismatchError extends TypeGraphError {\n constructor(\n details: Readonly<{\n graphId: string;\n expectedHash: string;\n actualHash: string;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema mismatch for graph \"${details.graphId}\": code schema differs from database schema`,\n \"SCHEMA_MISMATCH\",\n {\n details,\n category: \"system\",\n suggestion: `Run schema migration to update the database, or use createStoreWithSchema() for automatic migration.`,\n cause: options?.cause,\n },\n );\n this.name = \"SchemaMismatchError\";\n }\n}\n\n/**\n * Thrown when schema migration fails.\n */\nexport class MigrationError extends TypeGraphError {\n constructor(\n message: string,\n details: Readonly<{\n graphId: string;\n fromVersion: number;\n toVersion: number;\n reason?: string;\n }>,\n options?: { cause?: unknown },\n ) {\n super(message, \"MIGRATION_ERROR\", {\n details,\n category: \"system\",\n suggestion: `Review the schema changes and ensure they are backwards compatible, or implement a data migration.`,\n cause: options?.cause,\n });\n this.name = \"MigrationError\";\n }\n}\n\n// ============================================================\n// Configuration Errors (category: \"user\")\n// ============================================================\n\n/**\n * Thrown when graph configuration is invalid.\n *\n * This includes invalid schema definitions, ontology conflicts,\n * and other configuration issues detected at graph creation time.\n */\nexport class ConfigurationError extends TypeGraphError {\n constructor(\n message: string,\n details: Record<string, unknown> = {},\n options?: { cause?: unknown; suggestion?: string },\n ) {\n super(message, \"CONFIGURATION_ERROR\", {\n details,\n category: \"user\",\n suggestion:\n options?.suggestion ?? `Review your graph definition for errors.`,\n cause: options?.cause,\n });\n this.name = \"ConfigurationError\";\n }\n}\n\n// ============================================================\n// Query Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a query predicate cannot be compiled for the target database.\n */\nexport class UnsupportedPredicateError extends TypeGraphError {\n constructor(\n message: string,\n details: Readonly<Record<string, unknown>> = {},\n options?: { cause?: unknown; suggestion?: string },\n ) {\n super(message, \"UNSUPPORTED_PREDICATE\", {\n details,\n category: \"system\",\n suggestion:\n options?.suggestion ??\n `This predicate may not be supported by your database backend. Check the documentation for supported predicates.`,\n cause: options?.cause,\n });\n this.name = \"UnsupportedPredicateError\";\n }\n}\n\n// ============================================================\n// Utility Functions\n// ============================================================\n\n/**\n * Type guard for TypeGraphError.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({});\n * } catch (error) {\n * if (isTypeGraphError(error)) {\n * console.log(error.code, error.category);\n * }\n * }\n * ```\n */\nexport function isTypeGraphError(error: unknown): error is TypeGraphError {\n return error instanceof TypeGraphError;\n}\n\n/**\n * Check if error is recoverable by user action (user or constraint error).\n *\n * User-recoverable errors can typically be resolved by:\n * - Fixing invalid input data\n * - Using different IDs or values\n * - Deleting conflicting data first\n *\n * @example\n * ```typescript\n * if (isUserRecoverable(error)) {\n * showErrorToUser(error.toUserMessage());\n * } else {\n * logAndAlertOps(error);\n * }\n * ```\n */\nexport function isUserRecoverable(error: unknown): boolean {\n if (!isTypeGraphError(error)) return false;\n return error.category === \"user\" || error.category === \"constraint\";\n}\n\n/**\n * Check if error indicates a system/infrastructure issue.\n *\n * System errors typically require:\n * - Retry logic (for transient failures)\n * - Investigation (for persistent failures)\n * - Ops team notification\n */\nexport function isSystemError(error: unknown): boolean {\n return isTypeGraphError(error) && error.category === \"system\";\n}\n\n/**\n * Check if error is a constraint violation.\n */\nexport function isConstraintError(error: unknown): boolean {\n return isTypeGraphError(error) && error.category === \"constraint\";\n}\n\n/**\n * Extract suggestion from error if available.\n */\nexport function getErrorSuggestion(error: unknown): string | undefined {\n return isTypeGraphError(error) ? error.suggestion : undefined;\n}\n"]}