@nicia-ai/typegraph 0.28.1 → 0.29.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 (172) hide show
  1. package/dist/backend/postgres/index.cjs +23 -761
  2. package/dist/backend/postgres/index.cjs.map +1 -1
  3. package/dist/backend/postgres/index.d.cts +24 -5
  4. package/dist/backend/postgres/index.d.ts +24 -5
  5. package/dist/backend/postgres/index.js +10 -752
  6. package/dist/backend/postgres/index.js.map +1 -1
  7. package/dist/backend/postgres/pglite.cjs +52 -0
  8. package/dist/backend/postgres/pglite.cjs.map +1 -0
  9. package/dist/backend/postgres/pglite.d.cts +116 -0
  10. package/dist/backend/postgres/pglite.d.ts +116 -0
  11. package/dist/backend/postgres/pglite.js +50 -0
  12. package/dist/backend/postgres/pglite.js.map +1 -0
  13. package/dist/backend/sqlite/index.cjs +22 -26
  14. package/dist/backend/sqlite/index.d.cts +17 -15
  15. package/dist/backend/sqlite/index.d.ts +17 -15
  16. package/dist/backend/sqlite/index.js +9 -9
  17. package/dist/backend/sqlite/libsql.cjs +17 -13
  18. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  19. package/dist/backend/sqlite/libsql.d.cts +3 -3
  20. package/dist/backend/sqlite/libsql.d.ts +3 -3
  21. package/dist/backend/sqlite/libsql.js +16 -12
  22. package/dist/backend/sqlite/libsql.js.map +1 -1
  23. package/dist/backend/sqlite/local.cjs +17 -16
  24. package/dist/backend/sqlite/local.cjs.map +1 -1
  25. package/dist/backend/sqlite/local.d.cts +3 -3
  26. package/dist/backend/sqlite/local.d.ts +3 -3
  27. package/dist/backend/sqlite/local.js +15 -14
  28. package/dist/backend/sqlite/local.js.map +1 -1
  29. package/dist/{chunk-TKM2WDT4.js → chunk-3DTLDGIM.js} +386 -1093
  30. package/dist/chunk-3DTLDGIM.js.map +1 -0
  31. package/dist/{chunk-WVQXAFP3.js → chunk-454I6GDF.js} +46 -5
  32. package/dist/chunk-454I6GDF.js.map +1 -0
  33. package/dist/chunk-4K6IHUW6.cjs +183 -0
  34. package/dist/chunk-4K6IHUW6.cjs.map +1 -0
  35. package/dist/{chunk-ZTREJOGB.js → chunk-7KLVFWXR.js} +113 -68
  36. package/dist/chunk-7KLVFWXR.js.map +1 -0
  37. package/dist/{chunk-PGU2XKMA.js → chunk-A4H6QMV4.js} +110 -102
  38. package/dist/chunk-A4H6QMV4.js.map +1 -0
  39. package/dist/{chunk-E5ROA3MN.js → chunk-BMDF2S7S.js} +3 -3
  40. package/dist/{chunk-E5ROA3MN.js.map → chunk-BMDF2S7S.js.map} +1 -1
  41. package/dist/{chunk-PN37HVAV.cjs → chunk-C2RWFIYP.cjs} +121 -67
  42. package/dist/chunk-C2RWFIYP.cjs.map +1 -0
  43. package/dist/chunk-CUZGBWFT.js +206 -0
  44. package/dist/chunk-CUZGBWFT.js.map +1 -0
  45. package/dist/chunk-F2Q76CQ4.cjs +266 -0
  46. package/dist/chunk-F2Q76CQ4.cjs.map +1 -0
  47. package/dist/{chunk-YEDQLNVE.cjs → chunk-G6P3OVDY.cjs} +14 -2
  48. package/dist/chunk-G6P3OVDY.cjs.map +1 -0
  49. package/dist/chunk-GPUNAJFH.js +181 -0
  50. package/dist/chunk-GPUNAJFH.js.map +1 -0
  51. package/dist/chunk-HKN622O4.js +254 -0
  52. package/dist/chunk-HKN622O4.js.map +1 -0
  53. package/dist/{chunk-PYJOBZR3.cjs → chunk-HM6XMR3E.cjs} +52 -52
  54. package/dist/chunk-HM6XMR3E.cjs.map +1 -0
  55. package/dist/chunk-IE2TPFBT.js +305 -0
  56. package/dist/chunk-IE2TPFBT.js.map +1 -0
  57. package/dist/chunk-KGAJ5HFO.cjs +319 -0
  58. package/dist/chunk-KGAJ5HFO.cjs.map +1 -0
  59. package/dist/{chunk-O57GYGYK.js → chunk-M6OC455F.js} +32 -18
  60. package/dist/chunk-M6OC455F.js.map +1 -0
  61. package/dist/{chunk-U5ROKVRF.js → chunk-MB363HT5.js} +14 -3
  62. package/dist/chunk-MB363HT5.js.map +1 -0
  63. package/dist/{chunk-5MTOKWDA.js → chunk-MRMD7S7E.js} +9 -9
  64. package/dist/{chunk-5MTOKWDA.js.map → chunk-MRMD7S7E.js.map} +1 -1
  65. package/dist/{chunk-OOS2RKRH.js → chunk-N3VVQDMA.js} +3 -3
  66. package/dist/{chunk-OOS2RKRH.js.map → chunk-N3VVQDMA.js.map} +1 -1
  67. package/dist/{chunk-EJCDOA37.js → chunk-OGUH56BB.js} +4 -4
  68. package/dist/{chunk-EJCDOA37.js.map → chunk-OGUH56BB.js.map} +1 -1
  69. package/dist/chunk-Q3ZZLU3O.cjs +12 -0
  70. package/dist/{chunk-4FJVSF3K.cjs.map → chunk-Q3ZZLU3O.cjs.map} +1 -1
  71. package/dist/chunk-Q5ASTPM4.cjs +208 -0
  72. package/dist/chunk-Q5ASTPM4.cjs.map +1 -0
  73. package/dist/{chunk-WFUN6DCM.cjs → chunk-R2LA6MKR.cjs} +11 -11
  74. package/dist/chunk-R2LA6MKR.cjs.map +1 -0
  75. package/dist/{chunk-FFHW2JEK.cjs → chunk-RP7YITHX.cjs} +32 -17
  76. package/dist/chunk-RP7YITHX.cjs.map +1 -0
  77. package/dist/{chunk-NMOE2ZEU.cjs → chunk-RU5BBUU2.cjs} +132 -124
  78. package/dist/chunk-RU5BBUU2.cjs.map +1 -0
  79. package/dist/{chunk-TSGBRPNE.js → chunk-SFNUHFON.js} +45 -45
  80. package/dist/chunk-SFNUHFON.js.map +1 -0
  81. package/dist/chunk-UP4QAJND.cjs +740 -0
  82. package/dist/chunk-UP4QAJND.cjs.map +1 -0
  83. package/dist/{chunk-CTHNVU6K.cjs → chunk-UPBXUOW7.cjs} +8 -8
  84. package/dist/{chunk-CTHNVU6K.cjs.map → chunk-UPBXUOW7.cjs.map} +1 -1
  85. package/dist/{chunk-EK6RJ373.cjs → chunk-VGU26WIU.cjs} +5 -5
  86. package/dist/{chunk-EK6RJ373.cjs.map → chunk-VGU26WIU.cjs.map} +1 -1
  87. package/dist/{chunk-WZH2MKHW.cjs → chunk-XTQHSOIC.cjs} +101 -101
  88. package/dist/{chunk-WZH2MKHW.cjs.map → chunk-XTQHSOIC.cjs.map} +1 -1
  89. package/dist/chunk-Y52UNT66.js +738 -0
  90. package/dist/chunk-Y52UNT66.js.map +1 -0
  91. package/dist/{chunk-OYLF3IC7.js → chunk-Z36W5WUM.js} +4 -4
  92. package/dist/chunk-Z36W5WUM.js.map +1 -0
  93. package/dist/{chunk-X3244EKP.cjs → chunk-ZFWNO3GE.cjs} +48 -4
  94. package/dist/chunk-ZFWNO3GE.cjs.map +1 -0
  95. package/dist/{chunk-NYQFPGYP.cjs → chunk-ZYQEXGYC.cjs} +423 -1139
  96. package/dist/chunk-ZYQEXGYC.cjs.map +1 -0
  97. package/dist/ddl-BwH00BB6.d.ts +38 -0
  98. package/dist/ddl-D3o-RmsV.d.cts +38 -0
  99. package/dist/{extension-types-B78CZfA5.d.cts → extension-types-CwHV-Uk4.d.cts} +4 -4
  100. package/dist/{extension-types-B78CZfA5.d.ts → extension-types-CwHV-Uk4.d.ts} +4 -4
  101. package/dist/graph-extension/index.cjs +18 -18
  102. package/dist/graph-extension/index.d.cts +4 -4
  103. package/dist/graph-extension/index.d.ts +4 -4
  104. package/dist/graph-extension/index.js +3 -3
  105. package/dist/{index-CWdBFWbI.d.ts → index-CapHwi1a.d.ts} +22 -3
  106. package/dist/{index-Bilw0pYm.d.cts → index-jPPexxM5.d.cts} +22 -3
  107. package/dist/index.cjs +1211 -945
  108. package/dist/index.cjs.map +1 -1
  109. package/dist/index.d.cts +142 -12
  110. package/dist/index.d.ts +142 -12
  111. package/dist/index.js +778 -544
  112. package/dist/index.js.map +1 -1
  113. package/dist/indexes/index.cjs +18 -18
  114. package/dist/indexes/index.d.cts +9 -9
  115. package/dist/indexes/index.d.ts +9 -9
  116. package/dist/indexes/index.js +4 -4
  117. package/dist/interchange/index.cjs +8 -14
  118. package/dist/interchange/index.cjs.map +1 -1
  119. package/dist/interchange/index.d.cts +5 -16
  120. package/dist/interchange/index.d.ts +5 -16
  121. package/dist/interchange/index.js +3 -9
  122. package/dist/interchange/index.js.map +1 -1
  123. package/dist/{manager-ehLTTNq0.d.ts → manager-BUugwCYz.d.ts} +2 -2
  124. package/dist/{manager-c1MGaVVR.d.cts → manager-DpIpn1HQ.d.cts} +2 -2
  125. package/dist/{materialize-indexes-DFavFQah.d.ts → materialize-indexes-lkawaDor.d.ts} +1 -1
  126. package/dist/{materialize-indexes-BQfaAZKA.d.cts → materialize-indexes-oanE3RU0.d.cts} +1 -1
  127. package/dist/{ddl-0Ooc2dpL.d.ts → postgres-CQL9UIn2.d.cts} +2 -471
  128. package/dist/{ddl-Dza3kDrI.d.cts → postgres-CcRLaxz0.d.ts} +2 -471
  129. package/dist/profiler/index.cjs +4 -4
  130. package/dist/profiler/index.d.cts +7 -7
  131. package/dist/profiler/index.d.ts +7 -7
  132. package/dist/profiler/index.js +2 -2
  133. package/dist/schema/index.cjs +32 -32
  134. package/dist/schema/index.d.cts +7 -7
  135. package/dist/schema/index.d.ts +7 -7
  136. package/dist/schema/index.js +9 -9
  137. package/dist/{sqlite-BxZUPbyD.d.ts → sqlite-CZDFUfHS.d.ts} +2 -468
  138. package/dist/{sqlite-mvpXjEeB.d.cts → sqlite-Rj3xu4It.d.cts} +2 -468
  139. package/dist/{store-D7YEMg2v.d.cts → store-B43FpOVX.d.cts} +84 -5
  140. package/dist/{store-Ufc1Eoey.d.ts → store-De0Y33wP.d.ts} +84 -5
  141. package/dist/{types-B-sJJ4GQ.d.ts → types-B5GSeE3t.d.ts} +2 -2
  142. package/dist/{types-CmUA9sal.d.cts → types-Bwlp_yvu.d.cts} +2 -2
  143. package/dist/{types-CMQymcwk.d.cts → types-CmAT-Z47.d.ts} +250 -46
  144. package/dist/{types-CQ7xXJMP.d.ts → types-DXCSyxac.d.cts} +250 -46
  145. package/dist/{where-5zf15aFZ.d.cts → where-2dsyYt3d.d.cts} +2 -2
  146. package/dist/{where-CtrLu1Zf.d.ts → where-CP4qGIHd.d.ts} +2 -2
  147. package/package.json +20 -5
  148. package/dist/chunk-3EUKJEQ3.js +0 -77
  149. package/dist/chunk-3EUKJEQ3.js.map +0 -1
  150. package/dist/chunk-4FJVSF3K.cjs +0 -12
  151. package/dist/chunk-FFHW2JEK.cjs.map +0 -1
  152. package/dist/chunk-HTGDWIDE.cjs +0 -89
  153. package/dist/chunk-HTGDWIDE.cjs.map +0 -1
  154. package/dist/chunk-LYRUNG6E.cjs +0 -52
  155. package/dist/chunk-LYRUNG6E.cjs.map +0 -1
  156. package/dist/chunk-NMOE2ZEU.cjs.map +0 -1
  157. package/dist/chunk-NYQFPGYP.cjs.map +0 -1
  158. package/dist/chunk-O57GYGYK.js.map +0 -1
  159. package/dist/chunk-OYLF3IC7.js.map +0 -1
  160. package/dist/chunk-PCHTTG42.js +0 -47
  161. package/dist/chunk-PCHTTG42.js.map +0 -1
  162. package/dist/chunk-PGU2XKMA.js.map +0 -1
  163. package/dist/chunk-PN37HVAV.cjs.map +0 -1
  164. package/dist/chunk-PYJOBZR3.cjs.map +0 -1
  165. package/dist/chunk-TKM2WDT4.js.map +0 -1
  166. package/dist/chunk-TSGBRPNE.js.map +0 -1
  167. package/dist/chunk-U5ROKVRF.js.map +0 -1
  168. package/dist/chunk-WFUN6DCM.cjs.map +0 -1
  169. package/dist/chunk-WVQXAFP3.js.map +0 -1
  170. package/dist/chunk-X3244EKP.cjs.map +0 -1
  171. package/dist/chunk-YEDQLNVE.cjs.map +0 -1
  172. package/dist/chunk-ZTREJOGB.js.map +0 -1
@@ -0,0 +1,254 @@
1
+ import { buildSqliteNodeIndexBuilders, buildSqliteEdgeIndexBuilders } from './chunk-7KLVFWXR.js';
2
+ import { sql } from 'drizzle-orm';
3
+ import { sqliteTable, text, integer, primaryKey, index, uniqueIndex } from 'drizzle-orm/sqlite-core';
4
+
5
+ var LEGACY_EMBEDDINGS_TABLE_NAME = "typegraph_node_embeddings";
6
+ var DEFAULT_TABLE_NAMES = {
7
+ nodes: "typegraph_nodes",
8
+ edges: "typegraph_edges",
9
+ uniques: "typegraph_node_uniques",
10
+ schemaVersions: "typegraph_schema_versions",
11
+ fulltext: "typegraph_node_fulltext",
12
+ indexMaterializations: "typegraph_index_materializations",
13
+ contributionMaterializations: "typegraph_contribution_materializations",
14
+ kindRemovals: "typegraph_kind_removals",
15
+ reconciliationMarkers: "typegraph_reconciliation_markers"
16
+ };
17
+ function createSqliteTables(names = {}, options = {}) {
18
+ const n = { ...DEFAULT_TABLE_NAMES, ...names };
19
+ const indexes = options.indexes ?? [];
20
+ const nodes2 = sqliteTable(
21
+ n.nodes,
22
+ {
23
+ graphId: text("graph_id").notNull(),
24
+ kind: text("kind").notNull(),
25
+ id: text("id").notNull(),
26
+ props: text("props").notNull(),
27
+ version: integer("version").notNull().default(1),
28
+ validFrom: text("valid_from"),
29
+ validTo: text("valid_to"),
30
+ createdAt: text("created_at").notNull(),
31
+ updatedAt: text("updated_at").notNull(),
32
+ deletedAt: text("deleted_at")
33
+ },
34
+ (t) => [
35
+ primaryKey({ columns: [t.graphId, t.kind, t.id] }),
36
+ index(`${n.nodes}_kind_idx`).on(t.graphId, t.kind),
37
+ index(`${n.nodes}_kind_created_idx`).on(
38
+ t.graphId,
39
+ t.kind,
40
+ t.deletedAt,
41
+ t.createdAt
42
+ ),
43
+ index(`${n.nodes}_deleted_idx`).on(t.graphId, t.deletedAt),
44
+ index(`${n.nodes}_valid_idx`).on(t.graphId, t.validFrom, t.validTo),
45
+ ...buildSqliteNodeIndexBuilders(t, indexes)
46
+ ]
47
+ );
48
+ const edges2 = sqliteTable(
49
+ n.edges,
50
+ {
51
+ graphId: text("graph_id").notNull(),
52
+ id: text("id").notNull(),
53
+ kind: text("kind").notNull(),
54
+ fromKind: text("from_kind").notNull(),
55
+ fromId: text("from_id").notNull(),
56
+ toKind: text("to_kind").notNull(),
57
+ toId: text("to_id").notNull(),
58
+ props: text("props").notNull(),
59
+ validFrom: text("valid_from"),
60
+ validTo: text("valid_to"),
61
+ createdAt: text("created_at").notNull(),
62
+ updatedAt: text("updated_at").notNull(),
63
+ deletedAt: text("deleted_at")
64
+ },
65
+ (t) => [
66
+ primaryKey({ columns: [t.graphId, t.id] }),
67
+ index(`${n.edges}_kind_idx`).on(t.graphId, t.kind),
68
+ // Directional traversal index (outgoing): supports endpoint lookups
69
+ // and extra filtering by edge kind / target kind.
70
+ index(`${n.edges}_from_idx`).on(
71
+ t.graphId,
72
+ t.fromKind,
73
+ t.fromId,
74
+ t.kind,
75
+ t.toKind,
76
+ t.deletedAt,
77
+ t.validTo
78
+ ),
79
+ // Directional traversal index (incoming): mirrors from_idx for reverse traversals.
80
+ index(`${n.edges}_to_idx`).on(
81
+ t.graphId,
82
+ t.toKind,
83
+ t.toId,
84
+ t.kind,
85
+ t.fromKind,
86
+ t.deletedAt,
87
+ t.validTo
88
+ ),
89
+ index(`${n.edges}_kind_created_idx`).on(
90
+ t.graphId,
91
+ t.kind,
92
+ t.deletedAt,
93
+ t.createdAt
94
+ ),
95
+ index(`${n.edges}_deleted_idx`).on(t.graphId, t.deletedAt),
96
+ index(`${n.edges}_valid_idx`).on(t.graphId, t.validFrom, t.validTo),
97
+ index(`${n.edges}_cardinality_idx`).on(
98
+ t.graphId,
99
+ t.kind,
100
+ t.fromKind,
101
+ t.fromId,
102
+ t.validTo
103
+ ),
104
+ ...buildSqliteEdgeIndexBuilders(t, indexes)
105
+ ]
106
+ );
107
+ const uniques2 = sqliteTable(
108
+ n.uniques,
109
+ {
110
+ graphId: text("graph_id").notNull(),
111
+ nodeKind: text("node_kind").notNull(),
112
+ constraintName: text("constraint_name").notNull(),
113
+ key: text("key").notNull(),
114
+ nodeId: text("node_id").notNull(),
115
+ concreteKind: text("concrete_kind").notNull(),
116
+ deletedAt: text("deleted_at")
117
+ },
118
+ (t) => [
119
+ primaryKey({
120
+ columns: [t.graphId, t.nodeKind, t.constraintName, t.key]
121
+ }),
122
+ index(`${n.uniques}_node_idx`).on(t.graphId, t.concreteKind, t.nodeId)
123
+ ]
124
+ );
125
+ const schemaVersions2 = sqliteTable(
126
+ n.schemaVersions,
127
+ {
128
+ graphId: text("graph_id").notNull(),
129
+ version: integer("version").notNull(),
130
+ schemaHash: text("schema_hash").notNull(),
131
+ schemaDoc: text("schema_doc").notNull(),
132
+ createdAt: text("created_at").notNull(),
133
+ isActive: integer("is_active", { mode: "boolean" }).notNull().default(false)
134
+ },
135
+ (t) => [
136
+ primaryKey({ columns: [t.graphId, t.version] }),
137
+ index(`${n.schemaVersions}_active_idx`).on(t.graphId, t.isActive),
138
+ // Partial unique index enforcing the "at most one active version
139
+ // per graph" invariant at the storage layer. Defense in depth
140
+ // against buggy backend implementations or out-of-band writes.
141
+ // Forces the deactivate-then-activate ordering used by
142
+ // `commitSchemaVersion` and `setActiveVersion`.
143
+ uniqueIndex(`${n.schemaVersions}_one_active_per_graph_idx`).on(t.graphId).where(sql`${t.isActive} = 1`)
144
+ ]
145
+ );
146
+ const indexMaterializations = sqliteTable(
147
+ n.indexMaterializations,
148
+ {
149
+ indexName: text("index_name").notNull(),
150
+ graphId: text("graph_id").notNull(),
151
+ entity: text("entity").notNull(),
152
+ kind: text("kind").notNull(),
153
+ signature: text("signature").notNull(),
154
+ schemaVersion: integer("schema_version").notNull(),
155
+ materializedAt: text("materialized_at"),
156
+ lastAttemptedAt: text("last_attempted_at").notNull(),
157
+ lastError: text("last_error")
158
+ },
159
+ (t) => [primaryKey({ columns: [t.indexName] })]
160
+ );
161
+ const kindRemovals = sqliteTable(
162
+ n.kindRemovals,
163
+ {
164
+ graphId: text("graph_id").notNull(),
165
+ kindName: text("kind_name").notNull(),
166
+ entity: text("entity").notNull(),
167
+ schemaVersion: integer("schema_version").notNull(),
168
+ removedAt: text("removed_at"),
169
+ lastAttemptedAt: text("last_attempted_at").notNull(),
170
+ lastError: text("last_error")
171
+ },
172
+ (t) => [
173
+ primaryKey({
174
+ columns: [t.graphId, t.kindName, t.entity, t.schemaVersion]
175
+ })
176
+ ]
177
+ );
178
+ const reconciliationMarkers = sqliteTable(
179
+ n.reconciliationMarkers,
180
+ {
181
+ graphId: text("graph_id").notNull(),
182
+ reconciledToVersion: integer("reconciled_to_version").notNull()
183
+ },
184
+ (t) => [primaryKey({ columns: [t.graphId] })]
185
+ );
186
+ const contributionMaterializations = sqliteTable(
187
+ n.contributionMaterializations,
188
+ {
189
+ graphId: text("graph_id").notNull(),
190
+ logicalName: text("logical_name").notNull(),
191
+ owner: text("owner").notNull(),
192
+ tableName: text("table_name").notNull(),
193
+ signature: text("signature").notNull(),
194
+ materializedAt: text("materialized_at"),
195
+ lastAttemptedAt: text("last_attempted_at").notNull(),
196
+ lastError: text("last_error")
197
+ },
198
+ (t) => [
199
+ primaryKey({
200
+ columns: [t.graphId, t.logicalName, t.owner, t.tableName]
201
+ })
202
+ ]
203
+ );
204
+ return {
205
+ nodes: nodes2,
206
+ edges: edges2,
207
+ uniques: uniques2,
208
+ schemaVersions: schemaVersions2,
209
+ indexMaterializations,
210
+ contributionMaterializations,
211
+ kindRemovals,
212
+ reconciliationMarkers,
213
+ /**
214
+ * The fulltext storage is a FTS5 virtual table which Drizzle cannot
215
+ * represent. DDL is emitted as raw SQL and operations query it via
216
+ * `sql.raw()`.
217
+ */
218
+ fulltextTableName: n.fulltext
219
+ };
220
+ }
221
+ var tables = createSqliteTables();
222
+ var { nodes, edges, uniques, schemaVersions } = tables;
223
+
224
+ // src/backend/types.ts
225
+ function wrapWithManagedClose(backend, teardown) {
226
+ let isClosed = false;
227
+ return {
228
+ ...backend,
229
+ async close() {
230
+ if (isClosed) return;
231
+ isClosed = true;
232
+ await backend.close();
233
+ await teardown();
234
+ }
235
+ };
236
+ }
237
+ async function runOptionallyInTransaction(backend, fn, fallback) {
238
+ if (!backend.capabilities.transactions) {
239
+ return fn(fallback ?? backend);
240
+ }
241
+ return backend.transaction((tx) => fn(tx));
242
+ }
243
+ var SQLITE_CAPABILITIES = {
244
+ transactions: true
245
+ // SQLite supports transactions
246
+ };
247
+ var POSTGRES_CAPABILITIES = {
248
+ transactions: true
249
+ // PostgreSQL supports transactions
250
+ };
251
+
252
+ export { LEGACY_EMBEDDINGS_TABLE_NAME, POSTGRES_CAPABILITIES, SQLITE_CAPABILITIES, createSqliteTables, edges, nodes, runOptionallyInTransaction, schemaVersions, tables, uniques, wrapWithManagedClose };
253
+ //# sourceMappingURL=chunk-HKN622O4.js.map
254
+ //# sourceMappingURL=chunk-HKN622O4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/backend/drizzle/schema/sqlite.ts","../src/backend/types.ts"],"names":["nodes","edges","uniques","schemaVersions"],"mappings":";;;;AAyDO,IAAM,4BAAA,GAA+B;AAY5C,IAAM,mBAAA,GAAwC;AAAA,EAC5C,KAAA,EAAO,iBAAA;AAAA,EACP,KAAA,EAAO,iBAAA;AAAA,EACP,OAAA,EAAS,wBAAA;AAAA,EACT,cAAA,EAAgB,2BAAA;AAAA,EAChB,QAAA,EAAU,yBAAA;AAAA,EACV,qBAAA,EAAuB,kCAAA;AAAA,EACvB,4BAAA,EAA8B,yCAAA;AAAA,EAC9B,YAAA,EAAc,yBAAA;AAAA,EACd,qBAAA,EAAuB;AACzB,CAAA;AAMO,SAAS,mBACd,KAAA,GAAmC,EAAC,EACpC,OAAA,GAAqC,EAAC,EACtC;AACA,EAAA,MAAM,CAAA,GAAsB,EAAE,GAAG,mBAAA,EAAqB,GAAG,KAAA,EAAM;AAC/D,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,OAAA,IAAW,EAAC;AAEpC,EAAA,MAAMA,MAAAA,GAAQ,WAAA;AAAA,IACZ,CAAA,CAAE,KAAA;AAAA,IACF;AAAA,MACE,OAAA,EAAS,IAAA,CAAK,UAAU,CAAA,CAAE,OAAA,EAAQ;AAAA,MAClC,IAAA,EAAM,IAAA,CAAK,MAAM,CAAA,CAAE,OAAA,EAAQ;AAAA,MAC3B,EAAA,EAAI,IAAA,CAAK,IAAI,CA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A,IACA,4BAAA;AAAA,IACA,YAAA;AAAA,IACA,qBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMA,mBAAmB,CAAA,CAAE;AAAA,GACvB;AACF;AAKO,IAAM,SAAS,kBAAA;AAKf,IAAM,EAAE,KAAA,EAAO,KAAA,EAAO,OAAA,EAAS,gBAAe,GAAI;;;ACg1BlD,SAAS,oBAAA,CACd,SACA,QAAA,EACc;AACd,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,GAAG,OAAA;AAAA,IACH,MAAM,KAAA,GAAuB;AAC3B,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,MAAM,QAAQ,KAAA,EAAM;AACpB,MAAA,MAAM,QAAA,EAAS;AAAA,IACjB;AAAA,GACF;AACF;AAeA,eAAsB,0BAAA,CACpB,OAAA,EACA,EAAA,EACA,QAAA,EACY;AACZ,EAAA,IAAI,CAAC,OAAA,CAAQ,YAAA,CAAa,YAAA,EAAc;AACtC,IAAA,OAAO,EAAA,CAAG,YAAY,OAAO,CAAA;AAAA,EAC/B;AACA,EAAA,OAAO,QAAQ,WAAA,CAAY,CAAC,EAAA,KAAO,EAAA,CAAG,EAAE,CAAC,CAAA;AAC3C;AA4OO,IAAM,mBAAA,GAA2C;AAAA,EACtD,YAAA,EAAc;AAAA;AAChB;AAKO,IAAM,qBAAA,GAA6C;AAAA,EACxD,YAAA,EAAc;AAAA;AAChB","file":"chunk-HKN622O4.js","sourcesContent":["/**\n * Drizzle SQLite schema for TypeGraph.\n *\n * Provides table definitions that can be customized via the factory function.\n * Users import these tables into their Drizzle schema and use drizzle-kit\n * for migrations.\n *\n * @example\n * ```typescript\n * // Default table names\n * import { tables } from \"@nicia-ai/typegraph/sqlite\";\n *\n * // Custom table names\n * import { createSqliteTables } from \"@nicia-ai/typegraph/sqlite\";\n * const tables = createSqliteTables({\n * nodes: \"myapp_nodes\",\n * edges: \"myapp_edges\",\n * });\n * ```\n */\nimport { sql } from \"drizzle-orm\";\nimport {\n index,\n integer,\n primaryKey,\n sqliteTable,\n text,\n uniqueIndex,\n} from \"drizzle-orm/sqlite-core\";\n\nimport {\n buildSqliteEdgeIndexBuilders,\n buildSqliteNodeIndexBuilders,\n type IndexDeclaration,\n} from \"../../../indexes\";\n\n/**\n * Table name configuration.\n */\nexport type SqliteTableNames = Readonly<{\n nodes: string;\n edges: string;\n uniques: string;\n schemaVersions: string;\n fulltext: string;\n indexMaterializations: string;\n contributionMaterializations: string;\n kindRemovals: string;\n reconciliationMarkers: string;\n}>;\n\n/**\n * Physical name of the legacy single shared embeddings table, dropped in\n * the cross-backend vector cutover (the clean cut of #157). Strategies now\n * own per-`(nodeKind, fieldPath)` typed storage. Retained only so the\n * one-time migration utility can address and drain the old table.\n */\nexport const LEGACY_EMBEDDINGS_TABLE_NAME = \"typegraph_node_embeddings\";\n\nexport type CreateSqliteTablesOptions = Readonly<{\n /**\n * Additional TypeGraph indexes to include in the Drizzle schema.\n *\n * These become first-class Drizzle indexes, so drizzle-kit migrations will\n * pick them up automatically.\n */\n indexes?: readonly IndexDeclaration[] | undefined;\n}>;\n\nconst DEFAULT_TABLE_NAMES: SqliteTableNames = {\n nodes: \"typegraph_nodes\",\n edges: \"typegraph_edges\",\n uniques: \"typegraph_node_uniques\",\n schemaVersions: \"typegraph_schema_versions\",\n fulltext: \"typegraph_node_fulltext\",\n indexMaterializations: \"typegraph_index_materializations\",\n contributionMaterializations: \"typegraph_contribution_materializations\",\n kindRemovals: \"typegraph_kind_removals\",\n reconciliationMarkers: \"typegraph_reconciliation_markers\",\n};\n\n/**\n * Creates SQLite table definitions with customizable table names.\n * Index names are derived from table names.\n */\nexport function createSqliteTables(\n names: Partial<SqliteTableNames> = {},\n options: CreateSqliteTablesOptions = {},\n) {\n const n: SqliteTableNames = { ...DEFAULT_TABLE_NAMES, ...names };\n const indexes = options.indexes ?? [];\n\n const nodes = sqliteTable(\n n.nodes,\n {\n graphId: text(\"graph_id\").notNull(),\n kind: text(\"kind\").notNull(),\n id: text(\"id\").notNull(),\n props: text(\"props\").notNull(),\n version: integer(\"version\").notNull().default(1),\n validFrom: text(\"valid_from\"),\n validTo: text(\"valid_to\"),\n createdAt: text(\"created_at\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n deletedAt: text(\"deleted_at\"),\n },\n (t) => [\n primaryKey({ columns: [t.graphId, t.kind, t.id] }),\n index(`${n.nodes}_kind_idx`).on(t.graphId, t.kind),\n index(`${n.nodes}_kind_created_idx`).on(\n t.graphId,\n t.kind,\n t.deletedAt,\n t.createdAt,\n ),\n index(`${n.nodes}_deleted_idx`).on(t.graphId, t.deletedAt),\n index(`${n.nodes}_valid_idx`).on(t.graphId, t.validFrom, t.validTo),\n ...buildSqliteNodeIndexBuilders(t, indexes),\n ],\n );\n\n const edges = sqliteTable(\n n.edges,\n {\n graphId: text(\"graph_id\").notNull(),\n id: text(\"id\").notNull(),\n kind: text(\"kind\").notNull(),\n fromKind: text(\"from_kind\").notNull(),\n fromId: text(\"from_id\").notNull(),\n toKind: text(\"to_kind\").notNull(),\n toId: text(\"to_id\").notNull(),\n props: text(\"props\").notNull(),\n validFrom: text(\"valid_from\"),\n validTo: text(\"valid_to\"),\n createdAt: text(\"created_at\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n deletedAt: text(\"deleted_at\"),\n },\n (t) => [\n primaryKey({ columns: [t.graphId, t.id] }),\n index(`${n.edges}_kind_idx`).on(t.graphId, t.kind),\n // Directional traversal index (outgoing): supports endpoint lookups\n // and extra filtering by edge kind / target kind.\n index(`${n.edges}_from_idx`).on(\n t.graphId,\n t.fromKind,\n t.fromId,\n t.kind,\n t.toKind,\n t.deletedAt,\n t.validTo,\n ),\n // Directional traversal index (incoming): mirrors from_idx for reverse traversals.\n index(`${n.edges}_to_idx`).on(\n t.graphId,\n t.toKind,\n t.toId,\n t.kind,\n t.fromKind,\n t.deletedAt,\n t.validTo,\n ),\n index(`${n.edges}_kind_created_idx`).on(\n t.graphId,\n t.kind,\n t.deletedAt,\n t.createdAt,\n ),\n index(`${n.edges}_deleted_idx`).on(t.graphId, t.deletedAt),\n index(`${n.edges}_valid_idx`).on(t.graphId, t.validFrom, t.validTo),\n index(`${n.edges}_cardinality_idx`).on(\n t.graphId,\n t.kind,\n t.fromKind,\n t.fromId,\n t.validTo,\n ),\n ...buildSqliteEdgeIndexBuilders(t, indexes),\n ],\n );\n\n const uniques = sqliteTable(\n n.uniques,\n {\n graphId: text(\"graph_id\").notNull(),\n nodeKind: text(\"node_kind\").notNull(),\n constraintName: text(\"constraint_name\").notNull(),\n key: text(\"key\").notNull(),\n nodeId: text(\"node_id\").notNull(),\n concreteKind: text(\"concrete_kind\").notNull(),\n deletedAt: text(\"deleted_at\"),\n },\n (t) => [\n primaryKey({\n columns: [t.graphId, t.nodeKind, t.constraintName, t.key],\n }),\n index(`${n.uniques}_node_idx`).on(t.graphId, t.concreteKind, t.nodeId),\n ],\n );\n\n const schemaVersions = sqliteTable(\n n.schemaVersions,\n {\n graphId: text(\"graph_id\").notNull(),\n version: integer(\"version\").notNull(),\n schemaHash: text(\"schema_hash\").notNull(),\n schemaDoc: text(\"schema_doc\").notNull(),\n createdAt: text(\"created_at\").notNull(),\n isActive: integer(\"is_active\", { mode: \"boolean\" })\n .notNull()\n .default(false),\n },\n (t) => [\n primaryKey({ columns: [t.graphId, t.version] }),\n index(`${n.schemaVersions}_active_idx`).on(t.graphId, t.isActive),\n // Partial unique index enforcing the \"at most one active version\n // per graph\" invariant at the storage layer. Defense in depth\n // against buggy backend implementations or out-of-band writes.\n // Forces the deactivate-then-activate ordering used by\n // `commitSchemaVersion` and `setActiveVersion`.\n uniqueIndex(`${n.schemaVersions}_one_active_per_graph_idx`)\n .on(t.graphId)\n .where(sql`${t.isActive} = 1`),\n ],\n );\n\n /**\n * Per-deployment record of which declared indexes have been\n * materialized against this database. Owned and written by\n * `store.materializeIndexes()`. Keyed on `index_name` because SQL\n * index names are physical, database-global identifiers — `graphId`\n * is provenance, not identity.\n */\n const indexMaterializations = sqliteTable(\n n.indexMaterializations,\n {\n indexName: text(\"index_name\").notNull(),\n graphId: text(\"graph_id\").notNull(),\n entity: text(\"entity\").notNull(),\n kind: text(\"kind\").notNull(),\n signature: text(\"signature\").notNull(),\n schemaVersion: integer(\"schema_version\").notNull(),\n materializedAt: text(\"materialized_at\"),\n lastAttemptedAt: text(\"last_attempted_at\").notNull(),\n lastError: text(\"last_error\"),\n },\n (t) => [primaryKey({ columns: [t.indexName] })],\n );\n\n /**\n * Per-deployment record of extension kinds removed via\n * `store.removeKinds()` whose data has not yet been cleaned up by\n * `store.materializeRemovals()`. Keyed on `(graph_id, kind_name,\n * entity, schema_version)` — each remove operation is its own row.\n * `entity` separates a node and an edge that share a kind name; the\n * `schema_version` discriminator keeps a re-add-then-re-remove cycle\n * (Foo removed at v=N, re-added, then removed again at v=N+2) from\n * collapsing onto the prior row, where the COALESCE-on-failure rule\n * would preserve the earlier `removed_at` and silently skip the new\n * pending cleanup. `removed_at` is null until the data-cleanup pass\n * succeeds; the pending set is \"rows where removed_at IS NULL\".\n */\n const kindRemovals = sqliteTable(\n n.kindRemovals,\n {\n graphId: text(\"graph_id\").notNull(),\n kindName: text(\"kind_name\").notNull(),\n entity: text(\"entity\").notNull(),\n schemaVersion: integer(\"schema_version\").notNull(),\n removedAt: text(\"removed_at\"),\n lastAttemptedAt: text(\"last_attempted_at\").notNull(),\n lastError: text(\"last_error\"),\n },\n (t) => [\n primaryKey({\n columns: [t.graphId, t.kindName, t.entity, t.schemaVersion],\n }),\n ],\n );\n\n /**\n * Per-deployment high-water mark for the `materializeRemovals`\n * reconciliation walk. One row per `graph_id` carrying the schema\n * version up to which the historical \"did every removal land in\n * `kindRemovals`?\" walk has been verified. Lets subsequent calls\n * skip already-checked transitions instead of re-walking from\n * version 1 every time.\n */\n const reconciliationMarkers = sqliteTable(\n n.reconciliationMarkers,\n {\n graphId: text(\"graph_id\").notNull(),\n reconciledToVersion: integer(\"reconciled_to_version\").notNull(),\n },\n (t) => [primaryKey({ columns: [t.graphId] })],\n );\n\n /**\n * Per-deployment durable marker that a strategy-owned table\n * contribution (#129 — the FTS5 virtual table today) has been\n * materialized against this database (#135). Replaces the in-memory\n * per-backend `fulltextEnsured` latch with a queryable database fact.\n * Keyed on `(graph_id, logical_name, owner, table_name)`; `signature`\n * stays out of the key so same-identity drift is a loud error, not a\n * silent re-materialize. Same COALESCE-on-failure preservation rule\n * as `indexMaterializations`.\n */\n const contributionMaterializations = sqliteTable(\n n.contributionMaterializations,\n {\n graphId: text(\"graph_id\").notNull(),\n logicalName: text(\"logical_name\").notNull(),\n owner: text(\"owner\").notNull(),\n tableName: text(\"table_name\").notNull(),\n signature: text(\"signature\").notNull(),\n materializedAt: text(\"materialized_at\"),\n lastAttemptedAt: text(\"last_attempted_at\").notNull(),\n lastError: text(\"last_error\"),\n },\n (t) => [\n primaryKey({\n columns: [t.graphId, t.logicalName, t.owner, t.tableName],\n }),\n ],\n );\n\n return {\n nodes,\n edges,\n uniques,\n schemaVersions,\n indexMaterializations,\n contributionMaterializations,\n kindRemovals,\n reconciliationMarkers,\n /**\n * The fulltext storage is a FTS5 virtual table which Drizzle cannot\n * represent. DDL is emitted as raw SQL and operations query it via\n * `sql.raw()`.\n */\n fulltextTableName: n.fulltext,\n } as const;\n}\n\n/**\n * Default tables with standard TypeGraph table names.\n */\nexport const tables = createSqliteTables();\n\n/**\n * Convenience exports for default tables.\n */\nexport const { nodes, edges, uniques, schemaVersions } = tables;\n\n/**\n * Type representing the tables object returned by createSqliteTables.\n */\nexport type SqliteTables = ReturnType<typeof createSqliteTables>;\n","/**\n * Backend interface types for TypeGraph storage.\n *\n * The backend abstracts database operations, allowing different\n * SQL implementations (SQLite, PostgreSQL) behind a common interface.\n */\nimport { type SQL } from \"drizzle-orm\";\n\nimport {\n type IndexEntity,\n type KindEntity,\n type TemporalMode,\n} from \"../core/types\";\nimport { type SqlTableNames } from \"../query/compiler/schema\";\nimport { type FulltextStrategy } from \"../query/dialect/fulltext-strategy\";\nimport { type VectorStrategy } from \"../query/dialect/vector-strategy\";\nimport { type SerializedSchema } from \"../schema/types\";\nimport {\n type AnyPgDatabase,\n type AnySqliteDatabase,\n} from \"./drizzle/execution\";\n\n// ============================================================\n// Vector Search Types\n// ============================================================\n\n/**\n * Supported vector similarity metrics.\n */\nexport type VectorMetric = \"cosine\" | \"l2\" | \"inner_product\";\n\n/**\n * Supported vector index types.\n */\nexport type VectorIndexType = \"hnsw\" | \"ivfflat\" | \"none\";\n\n/**\n * Vector search capabilities.\n */\nexport type VectorCapabilities = Readonly<{\n /** Whether the backend supports vector operations */\n supported: boolean;\n /** Supported similarity metrics */\n metrics: readonly VectorMetric[];\n /** Supported index types */\n indexTypes: readonly VectorIndexType[];\n /** Maximum dimensions supported */\n maxDimensions: number;\n}>;\n\n// ============================================================\n// Fulltext Search Types\n// ============================================================\n\n/**\n * Query modes for fulltext search.\n *\n * - \"websearch\": Google-style syntax (quoted phrases, +required, -excluded).\n * Postgres: `websearch_to_tsquery`. SQLite: translated to FTS5 MATCH.\n * - \"phrase\": treats the whole query as a phrase.\n * Postgres: `phraseto_tsquery`. SQLite: FTS5 `\"...\"` phrase.\n * - \"plain\": splits on whitespace and ANDs terms.\n * Postgres: `plainto_tsquery`. SQLite: default FTS5 AND.\n * - \"raw\": dialect-native syntax passed through unchanged.\n */\nexport type FulltextQueryMode = \"websearch\" | \"phrase\" | \"plain\" | \"raw\";\n\n/**\n * Fulltext search capabilities declared by a backend.\n */\nexport type FulltextCapabilities = Readonly<{\n /** Whether the backend supports fulltext operations */\n supported: boolean;\n /**\n * Language / tokenizer names understood by this backend.\n * Postgres: installed regconfigs (english, simple, ...).\n * SQLite FTS5: tokenizer names (unicode61, porter, trigram).\n */\n languages: readonly string[];\n /** Whether phrase queries are supported. */\n phraseQueries: boolean;\n /** Whether prefix (`foo*`) queries are supported. */\n prefixQueries: boolean;\n /** Whether highlighting / snippets are supported. */\n highlighting: boolean;\n}>;\n\n// ============================================================\n// SQL Dialect & Capabilities\n// ============================================================\n\nimport { type SqlDialect } from \"../query/dialect/types\";\n\nexport type { SqlDialect } from \"../query/dialect/types\";\n\n/**\n * Backend capabilities that vary by dialect.\n */\nexport type BackendCapabilities = Readonly<{\n /** Whether the backend supports atomic transactions (D1 does not) */\n transactions: boolean;\n /** Vector search capabilities (undefined if not configured) */\n vector?: VectorCapabilities | undefined;\n /** Fulltext search capabilities (undefined if not configured) */\n fulltext?: FulltextCapabilities | undefined;\n}>;\n\n// ============================================================\n// Row Types (Database Records)\n// ============================================================\n\n/**\n * A row from the typegraph_nodes table.\n */\nexport type NodeRow = Readonly<{\n graph_id: string;\n kind: string;\n id: string;\n props: string; // JSON string\n version: number;\n valid_from: string | undefined;\n valid_to: string | undefined;\n created_at: string;\n updated_at: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_edges table.\n */\nexport type EdgeRow = Readonly<{\n graph_id: string;\n id: string;\n kind: string;\n from_kind: string;\n from_id: string;\n to_kind: string;\n to_id: string;\n props: string; // JSON string\n valid_from: string | undefined;\n valid_to: string | undefined;\n created_at: string;\n updated_at: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_node_uniques table.\n */\nexport type UniqueRow = Readonly<{\n graph_id: string;\n node_kind: string;\n constraint_name: string;\n key: string;\n node_id: string;\n concrete_kind: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_schema_versions table.\n */\nexport type SchemaVersionRow = Readonly<{\n graph_id: string;\n version: number;\n schema_hash: string;\n schema_doc: string; // JSON string\n created_at: string;\n is_active: boolean;\n}>;\n\n// ============================================================\n// Insert Parameters\n// ============================================================\n\n/**\n * Parameters for inserting a node.\n */\nexport type InsertNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validFrom?: string;\n validTo?: string;\n}>;\n\n/**\n * Parameters for updating a node.\n */\nexport type UpdateNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validTo?: string;\n incrementVersion?: boolean;\n /** If true, clears deleted_at (un-deletes the node). Used by upsert. */\n clearDeleted?: boolean;\n}>;\n\n/**\n * Parameters for deleting a node (soft delete).\n */\nexport type DeleteNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n}>;\n\n/**\n * Parameters for inserting an edge.\n */\nexport type InsertEdgeParams = Readonly<{\n graphId: string;\n id: string;\n kind: string;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n props: Readonly<Record<string, unknown>>;\n validFrom?: string;\n validTo?: string;\n}>;\n\n/**\n * Parameters for updating an edge.\n */\nexport type UpdateEdgeParams = Readonly<{\n graphId: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validTo?: string;\n clearDeleted?: boolean;\n}>;\n\n/**\n * Parameters for deleting an edge (soft delete).\n */\nexport type DeleteEdgeParams = Readonly<{\n graphId: string;\n id: string;\n}>;\n\n/**\n * Parameters for hard deleting a node (permanent removal).\n */\nexport type HardDeleteNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n}>;\n\n/**\n * Parameters for hard deleting an edge (permanent removal).\n */\nexport type HardDeleteEdgeParams = Readonly<{\n graphId: string;\n id: string;\n}>;\n\n// ============================================================\n// Embedding Parameters\n// ============================================================\n\n/**\n * Parameters for inserting or updating an embedding.\n *\n * `dimensions`, `metric`, and `indexType` together resolve the slot's\n * typed per-`(nodeKind, fieldPath)` storage (the strategy needs the fixed\n * dimension for the column type, and the metric/index type to address the\n * right ANN structure). The store populates them from the schema's\n * `embedding()` declaration via `getEmbeddingDimensions()` /\n * `getEmbeddingIndex()`; the backend constructs a `VectorSlot` from them\n * and stays graph-agnostic.\n */\nexport type UpsertEmbeddingParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n embedding: readonly number[];\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n}>;\n\n/**\n * Parameters for deleting an embedding.\n *\n * `dimensions` / `metric` / `indexType` mirror {@link UpsertEmbeddingParams}\n * so the backend can resolve the slot's typed per-`(nodeKind, fieldPath)`\n * storage and idempotently ensure it exists before the DELETE. That\n * matters because a delete can run before any embedding was ever written\n * (e.g. a node hard-deleted having never carried one), and on Postgres a\n * DELETE against a missing relation inside a transaction aborts the whole\n * transaction. The store populates them from the schema's `embedding()`\n * declaration, exactly as for upserts.\n */\nexport type DeleteEmbeddingParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n}>;\n\n/**\n * Parameters for vector similarity search.\n */\nexport type VectorSearchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n queryEmbedding: readonly number[];\n metric: VectorMetric;\n /**\n * Fixed vector dimension `N` for the searched `(nodeKind, fieldPath)`\n * slot. The store populates it from the schema's `embedding()`\n * declaration via `getEmbeddingDimensions()`; the backend uses it to\n * construct the `VectorSlot` whose typed storage the strategy scans.\n */\n dimensions: number;\n /**\n * Index type materialized for this slot. `\"none\"` means brute-force\n * only; otherwise the strategy may route through its ANN structure.\n * The store populates it from `getEmbeddingIndex()`.\n */\n indexType: VectorIndexType;\n limit: number;\n minScore?: number;\n /**\n * HNSW search frontier for this query (pgvector `hnsw.ef_search`).\n * Sizes the dynamic candidate list the index scan maintains: higher\n * trades latency for recall. The floor for the over-fetch to fill its\n * candidate set is `efSearch >= limit`; ~2–4× is the high-recall\n * target. Applied transaction-locally (`SET LOCAL`) on the Postgres\n * HNSW path only. No-op on backends without an HNSW frontier knob\n * (sqlite-vec) and ignored — with a one-time warning — on Postgres\n * backends without transactions (e.g. `drizzle-orm/neon-http`).\n */\n efSearch?: number;\n}>;\n\n/**\n * Result from a vector similarity search.\n */\nexport type VectorSearchResult = Readonly<{\n nodeId: string;\n /**\n * Cosine metric returns similarity score (higher is better).\n * L2 and inner_product return raw distance (lower is better).\n */\n score: number;\n}>;\n\n/**\n * Parameters for creating a vector index.\n */\nexport type CreateVectorIndexParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n /** Index-specific parameters */\n indexParams?: Readonly<{\n /** HNSW: max connections per layer */\n m?: number;\n /** HNSW: construction search depth */\n efConstruction?: number;\n /** IVFFlat: number of lists */\n lists?: number;\n }>;\n /**\n * Build the index without taking an `AccessExclusiveLock` on live\n * tables (Postgres `CREATE INDEX CONCURRENTLY`). Mirrors the\n * `concurrent` flag the relational DDL path uses inside\n * `materializeIndexes()`. Cannot be set inside a transaction —\n * callers (`materializeIndexes()`) run at top level. Backends that\n * don't have a CONCURRENTLY equivalent (SQLite) ignore this flag.\n */\n concurrent?: boolean;\n}>;\n\n/**\n * Parameters for dropping a vector index.\n */\nexport type DropVectorIndexParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n}>;\n\n// ============================================================\n// Fulltext Parameters\n// ============================================================\n\n/**\n * Parameters for inserting or updating a fulltext entry.\n *\n * One row per node. Callers concatenate the searchable fields into\n * `content` so a single MATCH query can find terms spread across fields.\n *\n * Note: `createFulltextIndex` / `dropFulltextIndex` were removed as\n * dead code in #PR_E. The fulltext table's canonical index (Postgres\n * GIN on `tsv`, SQLite FTS5 virtual table) is created with the table\n * itself by `bootstrapTables` per the active `FulltextStrategy`;\n * per-kind fulltext indexes are an \"advanced strategy\" surface that\n * doesn't fit the relational-style declaration model and is reserved\n * for future work.\n */\nexport type UpsertFulltextParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n content: string;\n language: string;\n}>;\n\n/**\n * Parameters for deleting a single fulltext entry.\n */\nexport type DeleteFulltextParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * A single row in a fulltext batch upsert.\n */\nexport type FulltextBatchRow = Readonly<{\n nodeId: string;\n content: string;\n language: string;\n}>;\n\n/**\n * Parameters for a batched fulltext upsert.\n *\n * Homogeneous: one graph, one node kind, many nodes. Duplicate `nodeId`\n * values within a single batch are deduplicated last-write-wins by the\n * builders before SQL generation — Postgres `ON CONFLICT` errors on\n * repeated conflict keys in one statement, and SQLite `DELETE + INSERT`\n * would create duplicate virtual-table rows otherwise.\n */\nexport type UpsertFulltextBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n rows: readonly FulltextBatchRow[];\n}>;\n\n/**\n * Parameters for a batched fulltext delete.\n */\nexport type DeleteFulltextBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeIds: readonly string[];\n}>;\n\n/**\n * Parameters for fulltext search.\n */\nexport type FulltextSearchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n /** The user-supplied query string. */\n query: string;\n /** How to parse `query`. Default: \"websearch\". */\n mode?: FulltextQueryMode;\n /**\n * Language override. Default: per-row language (as stored at insert time).\n * Postgres: passed as the regconfig to `to_tsquery` / `websearch_to_tsquery`.\n * SQLite: informational only (FTS5 tokenizer is fixed at table-create time).\n */\n language?: string;\n /** Max rows to return. */\n limit: number;\n /** Minimum rank to include (backend-dependent units). */\n minScore?: number;\n /** Whether to return a highlighted snippet per match. */\n includeSnippets?: boolean;\n}>;\n\n/**\n * Result from a fulltext search.\n *\n * Score semantics differ by backend; prefer `rank` (1-based) when fusing\n * with another source via RRF.\n */\nexport type FulltextSearchResult = Readonly<{\n nodeId: string;\n /**\n * Backend-native relevance score.\n * Postgres: `ts_rank_cd` (higher is better).\n * SQLite FTS5: negated `bm25()` (higher is better; FTS5 returns lower-is-better).\n */\n score: number;\n /** 1-based rank within the result set, suitable for RRF. */\n rank: number;\n /** Highlighted snippet of the content (if `includeSnippets` was set). */\n snippet?: string;\n}>;\n\n/**\n * Parameters for creating a fulltext index.\n *\n * The canonical index (Postgres GIN on `tsv`, SQLite FTS5 virtual table)\n * is created when the fulltext table itself is created. This is reserved\n * for advanced per-kind specializations.\n */\n\n// ============================================================\n// Index Materialization Status\n// ============================================================\n\n/**\n * Per-deployment record for a single declared index.\n *\n * Identified by `indexName` because SQL index names are physical,\n * database-global identifiers — `graphId` is provenance, not identity.\n * `materializedAt` is null until the first successful CREATE INDEX\n * completes; `lastAttemptedAt` is always set, even on failure.\n */\nexport type IndexMaterializationRow = Readonly<{\n indexName: string;\n graphId: string;\n entity: IndexEntity;\n kind: string;\n signature: string;\n schemaVersion: number;\n materializedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Parameters for upserting a materialization attempt.\n *\n * On success: pass `materializedAt` (ISO timestamp) and undefined `error`.\n * On failure: pass undefined `materializedAt` (preserve any existing\n * timestamp from a prior success) and the error message.\n */\nexport type RecordIndexMaterializationParams = Readonly<{\n indexName: string;\n graphId: string;\n entity: IndexEntity;\n kind: string;\n signature: string;\n schemaVersion: number;\n attemptedAt: string;\n /** ISO timestamp on success; undefined on failure (preserves existing). */\n materializedAt: string | undefined;\n /** Error message on failure; undefined on success (clears existing). */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Contribution Materializations (#135 — durable strategy-owned\n// storage marker, sibling of index materializations)\n// ============================================================\n\n/**\n * Durable identity of a strategy-owned table contribution (#129),\n * scoped to a graph. This is the primary key of\n * `typegraph_contribution_materializations`.\n *\n * `logicalName` is the stable slot (\"fulltext\"); `owner` is the\n * producing strategy (\"tsvector\" / \"fts5\"); `tableName` is the resolved\n * physical name (custom per-deployment names must be distinguishable).\n * `graphId` is part of identity here — unlike the index status table\n * where the physical index name is database-global, two graphs can each\n * own a logically-identical fulltext contribution.\n */\nexport type ContributionMaterializationIdentity = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n}>;\n\n/**\n * Per-deployment record that a strategy-owned contribution has been\n * durably materialized against this database.\n *\n * `signature` is intentionally NOT part of the identity: a row with the\n * same identity but a different signature means \"materialized artifact\n * is stale/drifted\" — a loud error on the hot path, never a silent\n * re-materialize. `materializedAt` is undefined until the first\n * successful materialization; `lastAttemptedAt` is always set.\n */\nexport type ContributionMaterializationRow = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n signature: string;\n materializedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Parameters for upserting a contribution-materialization attempt.\n * Same success/failure contract as\n * {@link RecordIndexMaterializationParams}: on failure pass undefined\n * `materializedAt` so a prior successful timestamp is preserved via\n * COALESCE, and the error message.\n */\nexport type RecordContributionMaterializationParams = Readonly<{\n graphId: string;\n logicalName: string;\n owner: string;\n tableName: string;\n signature: string;\n attemptedAt: string;\n /** ISO timestamp on success; undefined on failure (preserves existing). */\n materializedAt: string | undefined;\n /** Error message on failure; undefined on success (clears existing). */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Kind Removals (data-cleanup status)\n// ============================================================\n\n/**\n * One row of the per-deployment `typegraph_kind_removals` table:\n * a graph-extension kind that has been removed from the schema and whose\n * data may or may not have been cleaned up yet.\n */\nexport type KindRemovalRow = Readonly<{\n graphId: string;\n kindName: string;\n entity: KindEntity;\n schemaVersion: number;\n /** ISO timestamp when the data-cleanup pass succeeded; undefined while pending. */\n removedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Upsert payload for a kind-removal status row. On removal-commit:\n * pass `removedAt: undefined` (the pending state). On successful\n * data-cleanup: pass `removedAt` set and `error: undefined`. On\n * cleanup failure: pass `removedAt: undefined` (preserves any prior\n * timestamp from a partial success on a different replica) and the\n * error message.\n */\nexport type RecordKindRemovalParams = Readonly<{\n graphId: string;\n kindName: string;\n entity: KindEntity;\n schemaVersion: number;\n attemptedAt: string;\n /** ISO timestamp on success; undefined while pending or on failure. */\n removedAt: string | undefined;\n /** Error message on failure; undefined on success or while pending. */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Query Types\n// ============================================================\n\n/**\n * Transaction options.\n */\nexport type TransactionOptions = Readonly<{\n /** Transaction isolation level (if supported) */\n isolationLevel?:\n | \"read_uncommitted\"\n | \"read_committed\"\n | \"repeatable_read\"\n | \"serializable\";\n}>;\n\n/**\n * A caller-owned, already-open Drizzle transaction handle that a\n * TypeGraph store can adopt so both layers commit/rollback together.\n *\n * The literal client the caller's transaction runs on — a `PgDatabase`\n * transaction (node-postgres / `neon-serverless` Pool) or a\n * `BaseSQLiteDatabase` connection. Async drivers obtain it from\n * `db.transaction(async (tx) => …)`; synchronous `better-sqlite3` (whose\n * driver rejects an `async` transaction callback) passes the connection\n * itself under an explicit `BEGIN`/`COMMIT`/`ROLLBACK`. Passing it to\n * {@link GraphBackend.adoptTransaction} threads that *literal* client\n * through TypeGraph's SQL, so graph writes and the caller's own\n * relational writes share one Postgres/SQLite transaction (#134).\n */\nexport type AdoptedTransaction = AnyPgDatabase | AnySqliteDatabase;\n\n// ============================================================\n// Backend Interface\n// ============================================================\n\n/**\n * Transaction backend — a backend scoped to a transaction.\n *\n * `commitSchemaVersion` and `setActiveVersion` are intentionally omitted:\n * the atomicity / CAS guarantees of those primitives depend on\n * dialect-specific write-locking (BEGIN IMMEDIATE on SQLite,\n * `pg_advisory_xact_lock` on Postgres) acquired by the top-level\n * backend wrappers, not the transaction itself. Calling them from a\n * user-supplied `backend.transaction(...)` callback would bypass that\n * locking and silently weaken the orphan-row crash window the primitive\n * exists to eliminate. Schema commits go through the top-level backend\n * methods only.\n */\nexport type TransactionBackend = Omit<\n GraphBackend,\n | \"transaction\"\n | \"adoptTransaction\"\n | \"close\"\n | \"refreshStatistics\"\n | \"commitSchemaVersion\"\n | \"setActiveVersion\"\n>;\n\n/**\n * The GraphBackend interface abstracts database operations.\n *\n * Implementations should provide:\n * - SQLite backend via better-sqlite3 or libsql\n * - PostgreSQL backend via pg or postgres\n */\nexport type GraphBackend = Readonly<{\n /** The SQL dialect */\n dialect: SqlDialect;\n /** Backend capabilities */\n capabilities: BackendCapabilities;\n /** Table names used by this backend (for query schema auto-derivation) */\n tableNames?: SqlTableNames | undefined;\n /**\n * Optional fulltext strategy override. When present, both the compiler\n * (for `$fulltext.matches()` in query builder) and backend-direct\n * search paths use this instead of the dialect's default strategy —\n * allowing a Postgres backend to ship pg_trgm, ParadeDB, pgroonga etc.\n * When absent, the dialect's default strategy is used.\n */\n fulltextStrategy?: FulltextStrategy | undefined;\n /**\n * Optional vector strategy this backend is wired with. The query\n * compiler reads it (via `compileQuery` options) to emit per-`(kind,\n * field)` relevance scans for `field.similarTo(...)` predicates, and\n * the index-materialization / removal paths read its deterministic\n * `tableName(...)` to address the right physical per-field storage.\n * `undefined` when the backend has no vector support (e.g. a generic\n * SQLite backend without sqlite-vec).\n */\n vectorStrategy?: VectorStrategy | undefined;\n\n // === Node Operations ===\n insertNode: (params: InsertNodeParams) => Promise<NodeRow>;\n insertNodeNoReturn?: (params: InsertNodeParams) => Promise<void>;\n insertNodesBatch?: (params: readonly InsertNodeParams[]) => Promise<void>;\n insertNodesBatchReturning?: (\n params: readonly InsertNodeParams[],\n ) => Promise<readonly NodeRow[]>;\n updateNode: (params: UpdateNodeParams) => Promise<NodeRow>;\n deleteNode: (params: DeleteNodeParams) => Promise<void>;\n hardDeleteNode: (params: HardDeleteNodeParams) => Promise<void>;\n getNode: (\n graphId: string,\n kind: string,\n id: string,\n ) => Promise<NodeRow | undefined>;\n getNodes?: (\n graphId: string,\n kind: string,\n ids: readonly string[],\n ) => Promise<readonly NodeRow[]>;\n\n // === Edge Operations ===\n insertEdge: (params: InsertEdgeParams) => Promise<EdgeRow>;\n insertEdgeNoReturn?: (params: InsertEdgeParams) => Promise<void>;\n insertEdgesBatch?: (params: readonly InsertEdgeParams[]) => Promise<void>;\n insertEdgesBatchReturning?: (\n params: readonly InsertEdgeParams[],\n ) => Promise<readonly EdgeRow[]>;\n updateEdge: (params: UpdateEdgeParams) => Promise<EdgeRow>;\n deleteEdge: (params: DeleteEdgeParams) => Promise<void>;\n hardDeleteEdge: (params: HardDeleteEdgeParams) => Promise<void>;\n getEdge: (graphId: string, id: string) => Promise<EdgeRow | undefined>;\n getEdges?: (\n graphId: string,\n ids: readonly string[],\n ) => Promise<readonly EdgeRow[]>;\n\n // === Edge Cardinality Operations ===\n countEdgesFrom: (params: CountEdgesFromParams) => Promise<number>;\n edgeExistsBetween: (params: EdgeExistsBetweenParams) => Promise<boolean>;\n\n // === Edge Query Operations ===\n findEdgesConnectedTo: (\n params: FindEdgesConnectedToParams,\n ) => Promise<readonly EdgeRow[]>;\n\n // === Collection Query Operations ===\n findNodesByKind: (\n params: FindNodesByKindParams,\n ) => Promise<readonly NodeRow[]>;\n countNodesByKind: (params: CountNodesByKindParams) => Promise<number>;\n findEdgesByKind: (\n params: FindEdgesByKindParams,\n ) => Promise<readonly EdgeRow[]>;\n countEdgesByKind: (params: CountEdgesByKindParams) => Promise<number>;\n\n // === Unique Constraint Operations ===\n insertUnique: (params: InsertUniqueParams) => Promise<void>;\n deleteUnique: (params: DeleteUniqueParams) => Promise<void>;\n checkUnique: (params: CheckUniqueParams) => Promise<UniqueRow | undefined>;\n checkUniqueBatch?: (\n params: CheckUniqueBatchParams,\n ) => Promise<readonly UniqueRow[]>;\n\n // === Schema Operations ===\n getActiveSchema: (graphId: string) => Promise<SchemaVersionRow | undefined>;\n getSchemaVersion: (\n graphId: string,\n version: number,\n ) => Promise<SchemaVersionRow | undefined>;\n /**\n * Atomically inserts a new schema version and activates it as a single\n * transactional unit, with optimistic compare-and-swap on the currently\n * active version.\n *\n * - If `expected.kind === \"active\"` and the actual active version\n * differs, throws `StaleVersionError` (caller should refetch and\n * retry).\n * - If a row already exists at `params.version` with the same\n * `schemaHash`, returns it idempotently — reactivating it if it was\n * left inactive by an earlier crashed commit.\n * - If a row already exists at `params.version` with a different\n * `schemaHash`, throws `SchemaContentConflictError`.\n *\n * Requires `capabilities.transactions === true`. On non-transactional\n * backends (e.g. Cloudflare D1, drizzle-orm/neon-http) this method\n * throws `ConfigurationError` rather than running with degraded\n * atomicity that would silently re-introduce the orphan-row crash\n * window the primitive exists to eliminate.\n */\n commitSchemaVersion: (\n params: CommitSchemaVersionParams,\n ) => Promise<SchemaVersionRow>;\n /**\n * Atomically flips the active schema pointer to an existing version,\n * with optimistic compare-and-swap on the currently active version.\n * Used by `rollbackSchema` and any other \"promote/demote existing\n * version\" workflow. Throws `StaleVersionError` on CAS mismatch and\n * `MigrationError` if the target version row does not exist.\n *\n * Same transactional requirements as `commitSchemaVersion`.\n */\n setActiveVersion: (params: SetActiveVersionParams) => Promise<void>;\n\n // === Embedding Operations (optional - depends on vector capabilities) ===\n upsertEmbedding?: (params: UpsertEmbeddingParams) => Promise<void>;\n deleteEmbedding?: (params: DeleteEmbeddingParams) => Promise<void>;\n vectorSearch?: (\n params: VectorSearchParams,\n ) => Promise<readonly VectorSearchResult[]>;\n createVectorIndex?: (params: CreateVectorIndexParams) => Promise<void>;\n dropVectorIndex?: (params: DropVectorIndexParams) => Promise<void>;\n\n // === Fulltext Operations (optional - depends on fulltext capabilities) ===\n upsertFulltext?: (params: UpsertFulltextParams) => Promise<void>;\n deleteFulltext?: (params: DeleteFulltextParams) => Promise<void>;\n /**\n * Batched variant of `upsertFulltext`. Optional — callers fall back to\n * per-row `upsertFulltext` when unset.\n */\n upsertFulltextBatch?: (params: UpsertFulltextBatchParams) => Promise<void>;\n /**\n * Batched variant of `deleteFulltext`. Optional — callers fall back to\n * per-row `deleteFulltext` when unset.\n */\n deleteFulltextBatch?: (params: DeleteFulltextBatchParams) => Promise<void>;\n fulltextSearch?: (\n params: FulltextSearchParams,\n ) => Promise<readonly FulltextSearchResult[]>;\n\n // === Index Materialization (used by store.materializeIndexes) ===\n /**\n * Idempotently ensure ONLY the `typegraph_index_materializations`\n * table exists — separate from `bootstrapTables` so that\n * `materializeIndexes` doesn't pull in the full base-table DDL set\n * just to access the status table.\n *\n * Why focused: `bootstrapTables` issues 20+ `CREATE TABLE / CREATE\n * INDEX IF NOT EXISTS` statements covering every base table. Two\n * concurrent calls (e.g. two replicas of the same `schema_doc` both\n * starting up and calling `materializeIndexes`) race on\n * Postgres SHARE locks and DEADLOCK. Restricting the ensure-step to\n * the single status table eliminates the cross-table race entirely\n * — concurrent `CREATE TABLE IF NOT EXISTS` for one specific table\n * is well-behaved on Postgres.\n */\n ensureIndexMaterializationsTable?: () => Promise<void>;\n\n /**\n * Look up a recorded materialization for a declared index by its\n * physical SQL index name. Returns `undefined` if no row exists.\n */\n getIndexMaterialization?: (\n indexName: string,\n ) => Promise<IndexMaterializationRow | undefined>;\n /**\n * Bulk variant of `getIndexMaterialization`: load every recorded\n * materialization whose `indexName` (status key) is in `statusKeys`,\n * in a single round-trip. Returned rows are unordered — callers index\n * by `indexName`. Optional; consumers fall back to per-key\n * `getIndexMaterialization` when unset.\n */\n getIndexMaterializations?: (\n statusKeys: readonly string[],\n ) => Promise<readonly IndexMaterializationRow[]>;\n /**\n * Upsert a materialization attempt — success or failure. Failure rows\n * preserve any prior `materializedAt` so the historical successful\n * timestamp survives across error windows.\n */\n recordIndexMaterialization?: (\n params: RecordIndexMaterializationParams,\n ) => Promise<void>;\n\n // === Contribution Materialization (#135 — durable strategy-owned\n // storage marker, sibling of the index status table) ===\n\n /**\n * Idempotently ensure ONLY the\n * `typegraph_contribution_materializations` table exists. Same\n * focused-bootstrap rationale as `ensureIndexMaterializationsTable`:\n * a single `CREATE TABLE IF NOT EXISTS` is concurrency-safe under\n * replica startup, where the full `bootstrapTables` set risks a\n * Postgres SHARE-lock deadlock.\n */\n ensureContributionMaterializationsTable?: () => Promise<void>;\n\n /**\n * Look up the durable materialization marker for one strategy-owned\n * contribution identity. Returns `undefined` when no row exists\n * (\"never initialized\").\n */\n getContributionMaterialization?: (\n identity: ContributionMaterializationIdentity,\n ) => Promise<ContributionMaterializationRow | undefined>;\n\n /**\n * Upsert a contribution-materialization attempt — success or failure.\n * Failure rows preserve any prior `materializedAt` via COALESCE so a\n * later failed re-attempt doesn't erase the historical success.\n */\n recordContributionMaterialization?: (\n params: RecordContributionMaterializationParams,\n ) => Promise<void>;\n\n /**\n * Resolve (once per backend instance, cached) and assert the durable\n * materialization markers for every `runtimeEnsure` contribution this\n * backend's strategy declares, for `graphId`. Throws\n * `StoreNotInitializedError` when a marker is missing, stale\n * (signature drift), or recorded a failed last attempt.\n *\n * This is the single read-side gate the fulltext hot-path wrappers\n * and `store.transaction()` consult. It performs ZERO DDL and ZERO\n * marker writes — initialization is the exclusive job of the async\n * boot path (`createStoreWithSchema` → `ensureRuntimeContributions`).\n */\n assertRuntimeContributionsInitialized?: (graphId: string) => Promise<void>;\n\n // === Kind Removal Status ===\n\n /**\n * Bootstraps the per-deployment `typegraph_kind_removals` table so\n * `store.removeKinds()` and `store.materializeRemovals()` can persist\n * removal status. Mirrors the focused-bootstrap rationale documented\n * on `ensureIndexMaterializationsTable` — the full `bootstrapTables`\n * touches every base table and risks Postgres SHARE-lock deadlock\n * under concurrent replica startup.\n */\n ensureKindRemovalsTable?: () => Promise<void>;\n\n /**\n * List graph-extension kind removals whose data-cleanup pass has not yet\n * succeeded for this `graphId`. Returns rows with\n * `removedAt: undefined`. Order is unspecified; callers materialize\n * one-at-a-time and don't depend on it.\n */\n getPendingKindRemovals?: (\n graphId: string,\n ) => Promise<readonly KindRemovalRow[]>;\n\n /**\n * List ALL kind-removal rows for a `graphId` — pending and completed.\n * Used by `materializeRemovals()` reconciliation to detect rows that\n * are missing entirely (the `removeKinds()` crash window) versus\n * already completed. Without this distinction the reconciler would\n * have to upsert every expected historical removal on every call,\n * churning `last_attempted_at` on rows that long since succeeded.\n * Order is unspecified.\n */\n getAllKindRemovals?: (graphId: string) => Promise<readonly KindRemovalRow[]>;\n\n /**\n * Upsert a kind-removal status row. `removedAt: undefined` records\n * the pending state at schema-commit time; `removedAt: <iso>`\n * marks the data cleanup successful. The COALESCE rule on `removedAt`\n * mirrors `recordIndexMaterialization` so a later failure doesn't\n * clobber the historical successful timestamp from another replica.\n */\n recordKindRemoval?: (params: RecordKindRemovalParams) => Promise<void>;\n\n // === Reconciliation Watermark ===\n\n /**\n * Bootstraps the per-deployment `typegraph_reconciliation_markers`\n * table so `materializeRemovals()` can persist reconciliation\n * progress. Same focused-bootstrap rationale as the other status\n * tables — full `bootstrapTables` risks Postgres SHARE-lock\n * deadlock under concurrent replica startup.\n */\n ensureReconciliationMarkersTable?: () => Promise<void>;\n\n // === Table Contributions (#129) ===\n\n /**\n * Materializes every contribution flagged `runtimeEnsure` — the\n * strategy-owned runtime tables (fulltext today) that drizzle-kit-\n * managed setups don't create. Called once after a successful schema\n * load. Deliberately scoped: base/drizzle-visible tables are\n * `runtimeEnsure: false`, so this does not regress startup into\n * broad DDL/probing across every table.\n *\n * The canonical durable-marker writer (#135): for each runtime\n * contribution it short-circuits when the marker already records a\n * matching signature, otherwise runs the idempotent `createDdl` and\n * records the marker (success or failure) keyed by `graphId`.\n */\n ensureRuntimeContributions?: (graphId: string) => Promise<void>;\n\n /**\n * Bootstraps the fulltext storage table the active `FulltextStrategy`\n * owns. Same focused-bootstrap rationale as the other `ensure*Table`\n * methods: idempotent and concurrency-safe under replica startup.\n *\n * Superseded by `ensureRuntimeContributions()` (#129); retained as\n * a thin back-compat wrapper for backends/callers predating #129. Not\n * machine-`@deprecated` because the manager still calls it as the\n * pre-#129 fallback. #135 removed the remaining hot-path callers and\n * routed this through the durable-marker writer.\n */\n ensureFulltextTable?: (graphId: string) => Promise<void>;\n\n /**\n * Read the high-water mark schema version for which\n * `materializeRemovals` reconciliation has already verified history\n * for `graphId`. Returns `undefined` when no marker has been\n * recorded yet. Used to skip already-checked transitions in the\n * recovery walk.\n */\n getReconciliationMarker?: (graphId: string) => Promise<number | undefined>;\n\n /**\n * Persist the reconciliation high-water mark for `graphId`. Called\n * after `materializeRemovals` completes a clean walk; subsequent\n * calls walk only versions newer than this marker. Idempotent\n * upsert by `graphId`.\n */\n setReconciliationMarker?: (graphId: string, version: number) => Promise<void>;\n\n // === Graph Lifecycle ===\n /**\n * Hard-deletes all data for a graph (nodes, edges, uniques, embeddings, schema versions).\n * Intended for import-replacement workflows. No hooks, no per-row logic.\n */\n clearGraph: (graphId: string) => Promise<void>;\n\n /**\n * Creates the base TypeGraph tables if they don't already exist.\n *\n * Called automatically by `createStoreWithSchema()` when a fresh database\n * is detected. Users who manage DDL themselves via `createStore()` never\n * hit this path.\n */\n bootstrapTables?: () => Promise<void>;\n\n /**\n * Refreshes the backend's query-planner statistics.\n *\n * Call this once after a large initial import or bulk backfill. Without\n * up-to-date statistics, the planner can pick suboptimal execution plans\n * — on PostgreSQL this is the difference between a 0.5ms and a 5ms\n * forward traversal; on SQLite it's the difference between 0.9ms and\n * 23ms fulltext search. Autovacuum / background statistics collection\n * will catch up eventually, but calling this explicitly after a bulk\n * load gives you correct latencies immediately.\n *\n * Implementations:\n * - SQLite runs `ANALYZE`, which populates `sqlite_stat1`\n * - PostgreSQL runs `ANALYZE` on the TypeGraph-managed tables\n *\n * Safe to call at any time; costs a few tens of milliseconds on the\n * sizes this library is designed for.\n */\n refreshStatistics: () => Promise<void>;\n\n // === Query Execution ===\n execute: <T>(query: SQL) => Promise<readonly T[]>;\n\n /** Execute pre-compiled SQL text with bound parameters. Available on sync SQLite and pg backends. */\n executeRaw?: <T>(\n sqlText: string,\n params: readonly unknown[],\n ) => Promise<readonly T[]>;\n\n /** Compile a Drizzle SQL object to { sql, params } without executing. */\n compileSql?: (\n query: SQL,\n ) => Readonly<{ sql: string; params: readonly unknown[] }>;\n\n /**\n * Execute a DDL statement that returns no rows (CREATE INDEX,\n * CREATE TABLE, ALTER TABLE, etc.). Separate from `executeRaw`\n * because some drivers (better-sqlite3) require `.run()` for DDL\n * and `.all()` for queries — the ambiguity can't be resolved by\n * inspecting the SQL string portably.\n *\n * Postgres path can use this for `CREATE INDEX CONCURRENTLY`, which\n * cannot run inside a transaction. Implementations must execute the\n * statement outside `transaction(...)`.\n */\n executeDdl?: (ddl: string) => Promise<void>;\n\n // === Transaction ===\n /**\n * `fn` receives the tx-scoped backend and the raw Drizzle handle\n * **bound to that same transaction** (`AdoptedTransaction`). The\n * store surfaces the second argument as `TransactionContext.sql` so\n * callers can write their own relational tables inside the\n * graph-owned transaction. Implementations MUST pass the *exact*\n * handle the tx-scoped backend writes through (the Postgres/libsql\n * tx handle; for better-sqlite3 / do-sqlite the bound connection),\n * never a fresh one.\n */\n transaction: <T>(\n fn: (tx: TransactionBackend, sql: AdoptedTransaction) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<T>;\n\n /**\n * Adopt a caller-owned, already-open transaction (#134).\n *\n * Returns a transaction-scoped backend bound to the *exact*\n * `externalTx` client, reusing this backend's already-resolved\n * schema/strategy config — no `createStoreWithSchema` / `evolve` /\n * `migrateSchema`, and **no DDL inside the caller's business\n * transaction**. The caller owns `BEGIN`/`COMMIT`/`ROLLBACK`; this\n * method neither opens nor closes a transaction. Async drivers\n * (node-postgres, `neon-serverless` Pool, libsql) wrap with\n * `db.transaction(async …)`; synchronous `better-sqlite3` must instead\n * issue explicit `BEGIN`/`COMMIT`/`ROLLBACK` (its driver rejects an\n * `async` transaction callback).\n *\n * Optional and presence-detected like the other capability-scoped\n * members: only the Drizzle Postgres/SQLite backends provide it.\n * Implementations MUST throw (not silently degrade) when\n * `capabilities.transactions` is `false` — a non-atomic fallback is\n * safe for graph-only writes but dangerous for cross-store flows,\n * where the caller's relational write *would* still commit.\n *\n * Fulltext stays safe by construction: the returned backend's\n * fulltext methods assert the durable materialization marker (a\n * cached SELECT, never DDL) at point of use and throw\n * `StoreNotInitializedError` on a missing/stale/failed marker rather\n * than migrating mid-transaction. Prefer booting the parent store via\n * `createStoreWithSchema` so that assertion is a warm-cache no-op.\n */\n adoptTransaction?: (externalTx: AdoptedTransaction) => TransactionBackend;\n\n // === Lifecycle ===\n close: () => Promise<void>;\n}>;\n\n// ============================================================\n// Managed Backend Helper\n// ============================================================\n\n/**\n * Wraps a GraphBackend with idempotent close that also runs a teardown\n * callback (e.g. closing the underlying database connection).\n */\nexport function wrapWithManagedClose(\n backend: GraphBackend,\n teardown: () => void | Promise<void>,\n): GraphBackend {\n let isClosed = false;\n return {\n ...backend,\n async close(): Promise<void> {\n if (isClosed) return;\n isClosed = true;\n await backend.close();\n await teardown();\n },\n };\n}\n\n/**\n * Runs `fn` inside a transaction when the backend supports one, falling\n * through to a direct invocation otherwise. Lets call sites benefit from\n * atomicity on backends that have transactions while staying functional\n * on backends that don't (Cloudflare D1, `drizzle-orm/neon-http` over\n * HTTP). The single-statement race window is already implicit on any\n * backend that reports `transactions: false`; callers that cannot\n * tolerate it must branch on the capability themselves.\n *\n * Pass `fallback` only when the toplevel backend method would recurse\n * — pass the operation-level backend so the no-tx path doesn't loop\n * back through the same toplevel method.\n */\nexport async function runOptionallyInTransaction<T>(\n backend: GraphBackend,\n fn: (target: GraphBackend | TransactionBackend) => Promise<T>,\n fallback?: GraphBackend | TransactionBackend,\n): Promise<T> {\n if (!backend.capabilities.transactions) {\n return fn(fallback ?? backend);\n }\n return backend.transaction((tx) => fn(tx));\n}\n\n// ============================================================\n// Additional Parameter Types\n// ============================================================\n\n/**\n * Parameters for inserting a unique constraint entry.\n */\nexport type InsertUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n nodeId: string;\n concreteKind: string;\n}>;\n\n/**\n * Parameters for deleting a unique constraint entry.\n */\nexport type DeleteUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n}>;\n\n/**\n * Parameters for checking a unique constraint.\n */\nexport type CheckUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n /** If true, also returns soft-deleted entries. Used by get-or-create operations. */\n includeDeleted?: boolean;\n}>;\n\n/**\n * Parameters for batch-checking unique constraints.\n */\nexport type CheckUniqueBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n keys: readonly string[];\n /** If true, also returns soft-deleted entries. Used by get-or-create operations. */\n includeDeleted?: boolean;\n}>;\n\n/**\n * Parameters for inserting a schema version.\n *\n * Used internally by backend implementations. Public callers go through\n * `commitSchemaVersion`, which handles the insert + activate atomically\n * with CAS guarantees.\n */\nexport type InsertSchemaParams = Readonly<{\n graphId: string;\n version: number;\n schemaHash: string;\n schemaDoc: SerializedSchema;\n isActive: boolean;\n}>;\n\n/**\n * The caller's claim about the currently-active schema version, used as\n * the optimistic compare-and-swap guard for `commitSchemaVersion`.\n *\n * - `{ kind: \"initial\" }` — caller is committing the first-ever version\n * for this graph and asserts no active version exists yet.\n * - `{ kind: \"active\", version: N }` — caller observed version N as\n * active and is committing version N+1 against that baseline. The\n * commit fails with `StaleVersionError` if some other writer has\n * advanced or rolled back the pointer in the meantime.\n *\n * Tagged-union form (rather than a magic `version: 0` sentinel) because\n * the two cases have materially different semantics: the initial path\n * skips the \"deactivate prior\" UPDATE, and the no-active-row state is\n * a *valid* expected state, not an out-of-band signal.\n */\nexport type CommitSchemaVersionExpected =\n | Readonly<{ kind: \"initial\" }>\n | Readonly<{ kind: \"active\"; version: number }>;\n\n/**\n * Parameters for `commitSchemaVersion`.\n */\nexport type CommitSchemaVersionParams = Readonly<{\n graphId: string;\n /** CAS guard — see `CommitSchemaVersionExpected`. */\n expected: CommitSchemaVersionExpected;\n /** The new version to insert and activate. */\n version: number;\n schemaHash: string;\n schemaDoc: SerializedSchema;\n}>;\n\n/**\n * Parameters for `setActiveVersion`.\n *\n * Flips the active pointer from `expected` to `version` for an existing\n * row. CAS prevents overwriting a concurrent rollback or commit.\n */\nexport type SetActiveVersionParams = Readonly<{\n graphId: string;\n /** CAS guard. Same semantics as `commitSchemaVersion.expected`. */\n expected: CommitSchemaVersionExpected;\n /** The version to mark active. Must already exist. */\n version: number;\n}>;\n\n/**\n * Parameters for counting edges from a source node.\n */\nexport type CountEdgesFromParams = Readonly<{\n graphId: string;\n edgeKind: string;\n fromKind: string;\n fromId: string;\n /** If true, only count edges where valid_to IS NULL */\n activeOnly?: boolean;\n}>;\n\n/**\n * Parameters for checking if an edge exists between two nodes.\n */\nexport type EdgeExistsBetweenParams = Readonly<{\n graphId: string;\n edgeKind: string;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n}>;\n\n/**\n * Parameters for finding edges connected to a node.\n */\nexport type FindEdgesConnectedToParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * Parameters for finding nodes by kind.\n */\nexport type FindNodesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n /** Max rows to return. */\n limit?: number;\n /** Offset. Present for backward compat; rebuild uses `after` instead. */\n offset?: number;\n /** If true, exclude deleted nodes. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n /**\n * Stable ordering for keyset pagination. Default: \"created_at\" (existing\n * behavior). Rebuild should use \"id\" for iteration that is stable under\n * concurrent writes and shared timestamps.\n */\n orderBy?: \"id\" | \"created_at\";\n /**\n * Keyset cursor. Returns rows strictly greater (by `orderBy`) than this\n * value. When `orderBy: \"id\"`, compared lexicographically. Mutually\n * exclusive with `offset` — callers pick one.\n */\n after?: string;\n}>;\n\n/**\n * Parameters for counting nodes by kind.\n */\nexport type CountNodesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n /** If true, exclude deleted nodes. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n/**\n * Parameters for finding edges by kind.\n */\nexport type FindEdgesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n fromKind?: string;\n fromId?: string;\n toKind?: string;\n toId?: string;\n limit?: number;\n offset?: number;\n /** If true, exclude deleted edges. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n/**\n * Parameters for counting edges by kind.\n */\nexport type CountEdgesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n fromKind?: string;\n fromId?: string;\n toKind?: string;\n toId?: string;\n /** If true, exclude deleted edges. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n// ============================================================\n// Default Capabilities\n// ============================================================\n\n/**\n * Default capabilities for SQLite.\n */\nexport const SQLITE_CAPABILITIES: BackendCapabilities = {\n transactions: true, // SQLite supports transactions\n};\n\n/**\n * Default capabilities for PostgreSQL.\n */\nexport const POSTGRES_CAPABILITIES: BackendCapabilities = {\n transactions: true, // PostgreSQL supports transactions\n};\n"]}
@@ -1,8 +1,50 @@
1
1
  'use strict';
2
2
 
3
- var chunkYEDQLNVE_cjs = require('./chunk-YEDQLNVE.cjs');
3
+ var chunkG6P3OVDY_cjs = require('./chunk-G6P3OVDY.cjs');
4
4
  var chunk7V335GHG_cjs = require('./chunk-7V335GHG.cjs');
5
5
 
6
+ // src/ontology/closures.ts
7
+ function computeTransitiveClosure(relations) {
8
+ const closure = /* @__PURE__ */ new Map();
9
+ const allNodes = /* @__PURE__ */ new Set();
10
+ for (const [from, to] of relations) {
11
+ allNodes.add(from);
12
+ allNodes.add(to);
13
+ }
14
+ for (const node of allNodes) {
15
+ closure.set(node, /* @__PURE__ */ new Set());
16
+ }
17
+ for (const [from, to] of relations) {
18
+ closure.get(from)?.add(to);
19
+ }
20
+ for (const k of allNodes) {
21
+ for (const index of allNodes) {
22
+ const indexReaches = closure.get(index);
23
+ if (!indexReaches?.has(k)) continue;
24
+ const kReaches = closure.get(k);
25
+ if (!kReaches) continue;
26
+ for (const index2 of kReaches) {
27
+ indexReaches.add(index2);
28
+ }
29
+ }
30
+ }
31
+ return closure;
32
+ }
33
+ function invertClosure(closure) {
34
+ const result = /* @__PURE__ */ new Map();
35
+ for (const [from, tos] of closure) {
36
+ for (const to of tos) {
37
+ const existing = result.get(to) ?? /* @__PURE__ */ new Set();
38
+ existing.add(from);
39
+ result.set(to, existing);
40
+ }
41
+ }
42
+ return result;
43
+ }
44
+ function isReachable(closure, source, target) {
45
+ return closure.get(source)?.has(target) ?? false;
46
+ }
47
+
6
48
  // src/graph-extension/errors.ts
7
49
  var GRAPH_EXTENSION_ISSUE_CODES = [
8
50
  "UNSUPPORTED_PROPERTY_TYPE",
@@ -41,7 +83,7 @@ var GRAPH_EXTENSION_ISSUE_CODES = [
41
83
  "EMPTY_INDEX_FIELDS",
42
84
  "UNKNOWN_PROPERTY_KEY"
43
85
  ];
44
- var GraphExtensionError = class extends chunkYEDQLNVE_cjs.TypeGraphError {
86
+ var GraphExtensionError = class extends chunkG6P3OVDY_cjs.TypeGraphError {
45
87
  constructor(spec) {
46
88
  super(spec.message, spec.code, {
47
89
  details: spec.details,
@@ -278,7 +320,7 @@ function describeNonPlain(value) {
278
320
  return "non-plain object";
279
321
  }
280
322
  function throwInvalid(path, kind, ownerKind) {
281
- throw new chunkYEDQLNVE_cjs.ConfigurationError(
323
+ throw new chunkG6P3OVDY_cjs.ConfigurationError(
282
324
  `${ownerKind} ${path} contains a non-JSON value (${kind}). Annotations must be JSON-serializable.`,
283
325
  { path, valueKind: kind },
284
326
  {
@@ -287,48 +329,6 @@ function throwInvalid(path, kind, ownerKind) {
287
329
  );
288
330
  }
289
331
 
290
- // src/ontology/closures.ts
291
- function computeTransitiveClosure(relations) {
292
- const closure = /* @__PURE__ */ new Map();
293
- const allNodes = /* @__PURE__ */ new Set();
294
- for (const [from, to] of relations) {
295
- allNodes.add(from);
296
- allNodes.add(to);
297
- }
298
- for (const node of allNodes) {
299
- closure.set(node, /* @__PURE__ */ new Set());
300
- }
301
- for (const [from, to] of relations) {
302
- closure.get(from)?.add(to);
303
- }
304
- for (const k of allNodes) {
305
- for (const index of allNodes) {
306
- const indexReaches = closure.get(index);
307
- if (!indexReaches?.has(k)) continue;
308
- const kReaches = closure.get(k);
309
- if (!kReaches) continue;
310
- for (const index2 of kReaches) {
311
- indexReaches.add(index2);
312
- }
313
- }
314
- }
315
- return closure;
316
- }
317
- function invertClosure(closure) {
318
- const result = /* @__PURE__ */ new Map();
319
- for (const [from, tos] of closure) {
320
- for (const to of tos) {
321
- const existing = result.get(to) ?? /* @__PURE__ */ new Set();
322
- existing.add(from);
323
- result.set(to, existing);
324
- }
325
- }
326
- return result;
327
- }
328
- function isReachable(closure, source, target) {
329
- return closure.get(source)?.has(target) ?? false;
330
- }
331
-
332
332
  // src/ontology/constants.ts
333
333
  var META_EDGE_SUB_CLASS_OF = "subClassOf";
334
334
  var META_EDGE_BROADER = "broader";
@@ -387,7 +387,7 @@ function assertSchemaKeysAreFree(entityKind, name, keys, reservedStructuralKeys)
387
387
  );
388
388
  if (structuralConflicts.length > 0) {
389
389
  const label = entityKind.toLowerCase();
390
- throw new chunkYEDQLNVE_cjs.ConfigurationError(
390
+ throw new chunkG6P3OVDY_cjs.ConfigurationError(
391
391
  `${entityKind} "${name}" schema contains reserved property names: ${structuralConflicts.join(", ")}`,
392
392
  {
393
393
  [`${label}Type`]: name,
@@ -402,7 +402,7 @@ function assertSchemaKeysAreFree(entityKind, name, keys, reservedStructuralKeys)
402
402
  const prefixConflicts = keys.filter((key) => isReservedPropertyName(key));
403
403
  if (prefixConflicts.length > 0) {
404
404
  const label = entityKind.toLowerCase();
405
- throw new chunkYEDQLNVE_cjs.ConfigurationError(
405
+ throw new chunkG6P3OVDY_cjs.ConfigurationError(
406
406
  `${entityKind} "${name}" schema uses the reserved "${RESERVED_PROPERTY_PREFIX}" prefix on: ${prefixConflicts.join(", ")}`,
407
407
  {
408
408
  [`${label}Type`]: name,
@@ -418,7 +418,7 @@ function assertSchemaKeysAreFree(entityKind, name, keys, reservedStructuralKeys)
418
418
  function validateProjectionField(field, entityType, kind) {
419
419
  const reserved = entityType === "node" ? RESERVED_NODE_KEYS : RESERVED_EDGE_KEYS;
420
420
  if (reserved.has(field)) {
421
- throw new chunkYEDQLNVE_cjs.ConfigurationError(
421
+ throw new chunkG6P3OVDY_cjs.ConfigurationError(
422
422
  `Projection field "${field}" on ${entityType} kind "${kind}" conflicts with a reserved structural key`,
423
423
  { field, kind, entityType, reservedKeys: [...reserved] },
424
424
  {
@@ -427,7 +427,7 @@ function validateProjectionField(field, entityType, kind) {
427
427
  );
428
428
  }
429
429
  if (PROTOTYPE_POLLUTION_KEYS.has(field)) {
430
- throw new chunkYEDQLNVE_cjs.ConfigurationError(
430
+ throw new chunkG6P3OVDY_cjs.ConfigurationError(
431
431
  `Projection field "${field}" on ${entityType} kind "${kind}" is not allowed`,
432
432
  { field, kind, entityType },
433
433
  {
@@ -1939,7 +1939,7 @@ function validateAnnotations(raw, path, ownerLabel, issues) {
1939
1939
  try {
1940
1940
  assertJsonValue(raw, "annotations", ownerLabel);
1941
1941
  } catch (error) {
1942
- if (error instanceof chunkYEDQLNVE_cjs.ConfigurationError) {
1942
+ if (error instanceof chunkG6P3OVDY_cjs.ConfigurationError) {
1943
1943
  const detailPath = error.details.path;
1944
1944
  const annotationPath = typeof detailPath === "string" ? `${path}/${detailPath.replace(/^annotations\.?/, "").replaceAll(".", "/")}` : path;
1945
1945
  issues.push({
@@ -2065,5 +2065,5 @@ exports.isReachable = isReachable;
2065
2065
  exports.unwrap = unwrap;
2066
2066
  exports.validateGraphExtension = validateGraphExtension;
2067
2067
  exports.validateProjectionField = validateProjectionField;
2068
- //# sourceMappingURL=chunk-PYJOBZR3.cjs.map
2069
- //# sourceMappingURL=chunk-PYJOBZR3.cjs.map
2068
+ //# sourceMappingURL=chunk-HM6XMR3E.cjs.map
2069
+ //# sourceMappingURL=chunk-HM6XMR3E.cjs.map