@nicia-ai/typegraph 0.24.1 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/backend/postgres/index.cjs +178 -55
- package/dist/backend/postgres/index.cjs.map +1 -1
- package/dist/backend/postgres/index.d.cts +6 -7
- package/dist/backend/postgres/index.d.ts +6 -7
- package/dist/backend/postgres/index.js +151 -28
- package/dist/backend/postgres/index.js.map +1 -1
- package/dist/backend/sqlite/index.cjs +19 -17
- package/dist/backend/sqlite/index.d.cts +6 -7
- package/dist/backend/sqlite/index.d.ts +6 -7
- package/dist/backend/sqlite/index.js +9 -7
- package/dist/backend/sqlite/libsql.cjs +12 -10
- package/dist/backend/sqlite/libsql.cjs.map +1 -1
- package/dist/backend/sqlite/libsql.d.cts +4 -5
- package/dist/backend/sqlite/libsql.d.ts +4 -5
- package/dist/backend/sqlite/libsql.js +9 -7
- package/dist/backend/sqlite/libsql.js.map +1 -1
- package/dist/backend/sqlite/local.cjs +14 -12
- package/dist/backend/sqlite/local.cjs.map +1 -1
- package/dist/backend/sqlite/local.d.cts +4 -5
- package/dist/backend/sqlite/local.d.ts +4 -5
- package/dist/backend/sqlite/local.js +9 -7
- package/dist/backend/sqlite/local.js.map +1 -1
- package/dist/chunk-4BOWVUGQ.js +2029 -0
- package/dist/chunk-4BOWVUGQ.js.map +1 -0
- package/dist/{chunk-SUHW2UYL.cjs → chunk-7CDXX3QZ.cjs} +2 -2
- package/dist/chunk-7CDXX3QZ.cjs.map +1 -0
- package/dist/chunk-7V335GHG.cjs +112 -0
- package/dist/chunk-7V335GHG.cjs.map +1 -0
- package/dist/chunk-7W3KAMVQ.cjs +2678 -0
- package/dist/chunk-7W3KAMVQ.cjs.map +1 -0
- package/dist/chunk-CTHNVU6K.cjs +551 -0
- package/dist/chunk-CTHNVU6K.cjs.map +1 -0
- package/dist/chunk-D2GO3RBL.cjs +12 -0
- package/dist/chunk-D2GO3RBL.cjs.map +1 -0
- package/dist/{chunk-WFMTAEEN.js → chunk-DOTEN2FG.js} +81 -7
- package/dist/chunk-DOTEN2FG.js.map +1 -0
- package/dist/chunk-E5JZSEGJ.cjs +301 -0
- package/dist/chunk-E5JZSEGJ.cjs.map +1 -0
- package/dist/chunk-EG6TJ3I5.js +286 -0
- package/dist/chunk-EG6TJ3I5.js.map +1 -0
- package/dist/chunk-EJCDOA37.js +537 -0
- package/dist/chunk-EJCDOA37.js.map +1 -0
- package/dist/{chunk-UVZHTBZ5.cjs → chunk-EK6RJ373.cjs} +7 -150
- package/dist/chunk-EK6RJ373.cjs.map +1 -0
- package/dist/{chunk-GUTQTMOV.js → chunk-FPCOUJSL.js} +2 -2
- package/dist/chunk-FPCOUJSL.js.map +1 -0
- package/dist/{chunk-3JK66E3I.cjs → chunk-JTI5WT4P.cjs} +630 -59
- package/dist/chunk-JTI5WT4P.cjs.map +1 -0
- package/dist/chunk-LVCSL6A3.js +2626 -0
- package/dist/chunk-LVCSL6A3.js.map +1 -0
- package/dist/chunk-NHQWXSTS.js +10 -0
- package/dist/chunk-NHQWXSTS.js.map +1 -0
- package/dist/chunk-NZ5PMBTG.js +105 -0
- package/dist/chunk-NZ5PMBTG.js.map +1 -0
- package/dist/{chunk-5HVDOPZU.cjs → chunk-O2P3KAUT.cjs} +416 -93
- package/dist/chunk-O2P3KAUT.cjs.map +1 -0
- package/dist/{chunk-QOLTW7OZ.js → chunk-OJ6IQVZG.js} +151 -13
- package/dist/chunk-OJ6IQVZG.js.map +1 -0
- package/dist/{chunk-EYELZHKY.js → chunk-OOS2RKRH.js} +5 -140
- package/dist/chunk-OOS2RKRH.js.map +1 -0
- package/dist/chunk-RCAJZG67.cjs +2069 -0
- package/dist/chunk-RCAJZG67.cjs.map +1 -0
- package/dist/{chunk-O5PST6TB.cjs → chunk-W5MTHMTE.cjs} +83 -6
- package/dist/chunk-W5MTHMTE.cjs.map +1 -0
- package/dist/{chunk-EY4LBX3F.js → chunk-WI5VRP3X.js} +337 -26
- package/dist/chunk-WI5VRP3X.js.map +1 -0
- package/dist/chunk-WVQXAFP3.js +79 -0
- package/dist/chunk-WVQXAFP3.js.map +1 -0
- package/dist/chunk-X3244EKP.cjs +84 -0
- package/dist/chunk-X3244EKP.cjs.map +1 -0
- package/dist/{chunk-753F33CV.js → chunk-YZZBDCLV.js} +617 -44
- package/dist/chunk-YZZBDCLV.js.map +1 -0
- package/dist/{chunk-OVJ2BE5Q.cjs → chunk-ZEMNF3QK.cjs} +171 -33
- package/dist/chunk-ZEMNF3QK.cjs.map +1 -0
- package/dist/{ddl-B_H8JM-E.d.cts → ddl-B2jjLjpR.d.cts} +762 -99
- package/dist/{ddl-1tFIvt9V.d.ts → ddl-DpaeAKPp.d.ts} +762 -99
- package/dist/extension-types-D07e_NTw.d.cts +543 -0
- package/dist/extension-types-D07e_NTw.d.ts +543 -0
- package/dist/graph-extension/index.cjs +71 -0
- package/dist/graph-extension/index.cjs.map +1 -0
- package/dist/graph-extension/index.d.cts +278 -0
- package/dist/graph-extension/index.d.ts +278 -0
- package/dist/graph-extension/index.js +6 -0
- package/dist/graph-extension/index.js.map +1 -0
- package/dist/{index-DXkEXpNz.d.ts → index-CT6nvtxL.d.cts} +114 -5
- package/dist/{index-DXkEXpNz.d.cts → index-DQheiVQV.d.ts} +114 -5
- package/dist/index.cjs +2672 -901
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +29 -10
- package/dist/index.d.ts +29 -10
- package/dist/index.js +2248 -598
- package/dist/index.js.map +1 -1
- package/dist/indexes/index.cjs +25 -23
- package/dist/indexes/index.d.cts +40 -22
- package/dist/indexes/index.d.ts +40 -22
- package/dist/indexes/index.js +5 -3
- package/dist/interchange/index.cjs +8 -7
- package/dist/interchange/index.cjs.map +1 -1
- package/dist/interchange/index.d.cts +5 -4
- package/dist/interchange/index.d.ts +5 -4
- package/dist/interchange/index.js +3 -2
- package/dist/interchange/index.js.map +1 -1
- package/dist/{manager-nIhmttD-.d.ts → manager-BKaPQbns.d.ts} +189 -6
- package/dist/{manager-Vkz28eAC.d.cts → manager-BpjBW1JK.d.cts} +189 -6
- package/dist/materialize-indexes-BB9N5uQl.d.cts +68 -0
- package/dist/materialize-indexes-BYpU2RKh.d.ts +68 -0
- package/dist/profiler/index.cjs +10 -8
- package/dist/profiler/index.cjs.map +1 -1
- package/dist/profiler/index.d.cts +8 -7
- package/dist/profiler/index.d.ts +8 -7
- package/dist/profiler/index.js +3 -1
- package/dist/profiler/index.js.map +1 -1
- package/dist/schema/index.cjs +43 -22
- package/dist/schema/index.cjs.map +1 -1
- package/dist/schema/index.d.cts +17 -8
- package/dist/schema/index.d.ts +17 -8
- package/dist/schema/index.js +9 -4
- package/dist/schema/index.js.map +1 -1
- package/dist/{sqlite-D0aceIe0.d.cts → sqlite-CU3j6rc7.d.ts} +837 -120
- package/dist/{sqlite-SUxbZqfy.d.ts → sqlite-Myo8e3Lr.d.cts} +837 -120
- package/dist/{store-U3i2tUch.d.ts → store-BAGuOHDh.d.cts} +659 -23
- package/dist/{store-CpvwTMxV.d.cts → store-De98Lod4.d.ts} +659 -23
- package/dist/types--0EslBx5.d.cts +2123 -0
- package/dist/{types-qYFZ9SqD.d.ts → types-BLmJq4wI.d.ts} +3 -2
- package/dist/types-BNWYZ-0-.d.ts +2123 -0
- package/dist/{types-yH4_p0XB.d.cts → types-CYga3lZp.d.cts} +3 -2
- package/dist/where-CluR73rs.d.ts +11 -0
- package/dist/where-m1uWsdua.d.cts +11 -0
- package/package.json +33 -73
- package/dist/ast-C8S37w1A.d.ts +0 -497
- package/dist/ast-dgLhLOg0.d.cts +0 -497
- package/dist/chunk-3JK66E3I.cjs.map +0 -1
- package/dist/chunk-3PPEHLGK.js +0 -1116
- package/dist/chunk-3PPEHLGK.js.map +0 -1
- package/dist/chunk-5HVDOPZU.cjs.map +0 -1
- package/dist/chunk-753F33CV.js.map +0 -1
- package/dist/chunk-EY4LBX3F.js.map +0 -1
- package/dist/chunk-EYELZHKY.js.map +0 -1
- package/dist/chunk-GFGVREHH.js +0 -1381
- package/dist/chunk-GFGVREHH.js.map +0 -1
- package/dist/chunk-GUTQTMOV.js.map +0 -1
- package/dist/chunk-LBORRUNJ.js +0 -135
- package/dist/chunk-LBORRUNJ.js.map +0 -1
- package/dist/chunk-O5PST6TB.cjs.map +0 -1
- package/dist/chunk-OLROXS2S.cjs +0 -147
- package/dist/chunk-OLROXS2S.cjs.map +0 -1
- package/dist/chunk-OVJ2BE5Q.cjs.map +0 -1
- package/dist/chunk-PAUN562Y.cjs +0 -1417
- package/dist/chunk-PAUN562Y.cjs.map +0 -1
- package/dist/chunk-PEE4EWXZ.cjs +0 -1131
- package/dist/chunk-PEE4EWXZ.cjs.map +0 -1
- package/dist/chunk-QOLTW7OZ.js.map +0 -1
- package/dist/chunk-SUHW2UYL.cjs.map +0 -1
- package/dist/chunk-UVZHTBZ5.cjs.map +0 -1
- package/dist/chunk-WFMTAEEN.js.map +0 -1
- package/dist/types-C-zfYDJB.d.ts +0 -159
- package/dist/types-CQx4iW5Y.d.cts +0 -159
- package/dist/types-Qk2l3IkQ.d.cts +0 -1254
- package/dist/types-Qk2l3IkQ.d.ts +0 -1254
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/graph-extension/errors.ts","../src/graph-extension/extension-types.ts","../src/utils/object.ts","../src/core/json-value.ts","../src/ontology/closures.ts","../src/ontology/constants.ts","../src/store/reserved-keys.ts","../src/utils/result.ts","../src/graph-extension/validation.ts"],"names":["index"],"mappings":";;;;AA0DO,IAAM,2BAAA,GAA8B;AAAA,EACzC,2BAAA;AAAA,EACA,6BAAA;AAAA,EACA,cAAA;AAAA,EACA,wBAAA;AAAA,EACA,yBAAA;AAAA,EACA,qBAAA;AAAA,EACA,uBAAA;AAAA,EACA,uBAAA;AAAA,EACA,iBAAA;AAAA,EACA,8BAAA;AAAA,EACA,6BAAA;AAAA,EACA,wBAAA;AAAA,EACA,mBAAA;AAAA,EACA,qBAAA;AAAA,EACA,kBAAA;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3D;AAAA,MACJ,SACE,KAAA,CAAM,OAAA,KAAY,SAChB,MAAA,GACA,MAAA,CAAO,OAAO,KAAA,CAAM,OAAA,CAAQ,GAAA,CAAI,CAAC,UAAU,UAAA,CAAW,EAAE,GAAG,KAAA,EAAO,CAAC,CAAC;AAAA,KACzE;AAAA,GACH;AACF","file":"chunk-4BOWVUGQ.js","sourcesContent":["/**\n * Errors raised across the graph-extension surface.\n *\n * Two flavours:\n *\n * - **Validation issues** (`GraphExtensionValidationError` +\n * `GraphExtensionIssue` / `GraphExtensionIssueCode`) — produced by\n * `validateGraphExtension`. The issue list batches every failure\n * with a JSON-pointer `path` so a UI can highlight every offending\n * field at once.\n * - **Operation errors** (every other class in this file, all extending\n * `GraphExtensionError`) — thrown one at a time from `evolve`,\n * `removeKinds`, `materializeIndexes`, search, etc. Each carries a\n * stable string `code` for logging / serialization PLUS a typed\n * shape so consumers can `instanceof` for control flow.\n */\nimport type { KindEntity } from \"../core/types\";\nimport { type ErrorCategory, TypeGraphError } from \"../errors\";\n\n// ============================================================\n// Validation issues (multi-issue batch)\n// ============================================================\n\n/**\n * One specific issue raised during graph-extension validation.\n */\nexport type GraphExtensionIssue = Readonly<{\n /**\n * JSON-pointer path to the offending value, rooted at the document\n * (e.g. `/nodes/Paper/properties/title/pattern`). The empty string\n * `\"\"` means \"the document itself\".\n */\n path: string;\n /** Human-readable explanation of the failure. */\n message: string;\n /**\n * Stable machine-readable code so callers (and tests) can branch on\n * specific failure modes without parsing messages. New codes are\n * additive.\n */\n code: GraphExtensionIssueCode;\n}>;\n\n/**\n * Stable machine codes for every validation failure produced by the\n * document validator. New codes are additive — existing codes never\n * change meaning.\n *\n * Note: codes here describe per-field validation problems. Operation-\n * level errors (kind not found, version mismatch on persisted doc,\n * compile-time-kind removal, etc.) surface as typed Error subclasses\n * exported below — not as issue codes.\n */\n/**\n * Every issue code emitted by `validateGraphExtension`. Const-array form\n * so tests, codegen, and runtime introspection can iterate the full set\n * without restating it.\n */\nexport const GRAPH_EXTENSION_ISSUE_CODES = [\n \"UNSUPPORTED_PROPERTY_TYPE\",\n \"INVALID_PROPERTY_REFINEMENT\",\n \"NESTED_ARRAY\",\n \"NESTED_OBJECT_TOO_DEEP\",\n \"INVALID_MODIFIER_TARGET\",\n \"INVALID_ENUM_VALUES\",\n \"INVALID_NUMBER_BOUNDS\",\n \"INVALID_LENGTH_BOUNDS\",\n \"INVALID_PATTERN\",\n \"INVALID_EMBEDDING_DIMENSIONS\",\n \"INVALID_SEARCHABLE_LANGUAGE\",\n \"RESERVED_PROPERTY_NAME\",\n \"INVALID_KIND_NAME\",\n \"DUPLICATE_KIND_NAME\",\n \"EMPTY_PROPERTIES\",\n \"EMPTY_FROM_OR_TO\",\n \"DUPLICATE_UNIQUE_CONSTRAINT\",\n \"EMPTY_UNIQUE_FIELDS\",\n \"DUPLICATE_UNIQUE_FIELD\",\n \"UNKNOWN_UNIQUE_FIELD\",\n \"INVALID_UNIQUE_WHERE_OP\",\n \"UNKNOWN_UNIQUE_WHERE_FIELD\",\n \"INVALID_ANNOTATION\",\n \"UNKNOWN_META_EDGE\",\n \"ONTOLOGY_CYCLE\",\n \"ONTOLOGY_SELF_LOOP\",\n \"ONTOLOGY_DISJOINT_CONFLICT\",\n \"DUPLICATE_ONTOLOGY_RELATION\",\n \"INVALID_DOCUMENT_SHAPE\",\n \"UNKNOWN_DOCUMENT_KEY\",\n \"UNSUPPORTED_STRING_FORMAT\",\n \"INVALID_INDEX_DECLARATION\",\n \"DUPLICATE_INDEX_NAME\",\n \"EMPTY_INDEX_FIELDS\",\n \"UNKNOWN_PROPERTY_KEY\",\n] as const;\n\nexport type GraphExtensionIssueCode =\n (typeof GRAPH_EXTENSION_ISSUE_CODES)[number];\n\n// ============================================================\n// Operation errors (typed, single-error throws)\n// ============================================================\n\n/**\n * Base class for every graph-extension error. Consumers can catch\n * the family with one `instanceof GraphExtensionError` check and\n * branch on the concrete subclass beneath. Carries the same\n * `code` / `category` / `details` slots as `TypeGraphError` so existing\n * `isTypeGraphError` / `isUserRecoverable` helpers continue to apply.\n */\nexport abstract class GraphExtensionError extends TypeGraphError {\n // The concrete `code` is set as a literal-typed property on each\n // subclass so consumers can branch on it with full type narrowing.\n declare readonly code: string;\n\n protected constructor(spec: {\n message: string;\n code: string;\n details: Readonly<Record<string, unknown>>;\n suggestion: string;\n category?: ErrorCategory;\n cause?: unknown;\n }) {\n super(spec.message, spec.code, {\n details: spec.details,\n category: spec.category ?? \"user\",\n suggestion: spec.suggestion,\n ...(spec.cause === undefined ? {} : { cause: spec.cause }),\n });\n // `new.target.name` resolves to the concrete subclass at construction\n // time, eliminating per-subclass `this.name = \"ClassName\"` repetition.\n this.name = new.target.name;\n }\n}\n\n/**\n * Thrown when `validateGraphExtension` (or `defineGraphExtension`)\n * rejects an input document for one or more shape/content reasons.\n *\n * The `issues` array carries every failure with a JSON-pointer\n * `path`, so callers presenting the document to a human reviewer can\n * highlight every offending field at once.\n */\nexport class GraphExtensionValidationError extends GraphExtensionError {\n readonly code = \"GRAPH_EXTENSION_INVALID\" as const;\n readonly issues: readonly GraphExtensionIssue[];\n declare readonly details: Readonly<{\n issues: readonly GraphExtensionIssue[];\n }>;\n\n constructor(issues: readonly GraphExtensionIssue[], cause?: unknown) {\n const frozenIssues = Object.freeze([...issues]);\n super({\n message: `Graph extension document is invalid (${issues.length} issue${\n issues.length === 1 ? \"\" : \"s\"\n }): ${summarizeIssues(issues)}`,\n code: \"GRAPH_EXTENSION_INVALID\",\n details: { issues: frozenIssues },\n suggestion: `Inspect error.issues for per-field paths and codes; each issue's \"path\" is a JSON pointer into the source document.`,\n cause,\n });\n this.issues = frozenIssues;\n }\n}\n\n/**\n * Generic \"first N items + overflow tail\" summary for inclusion in an\n * Error message. Shared by `summarizeIssues` and `summarizeChanges`\n * because the overflow shape is identical; only the per-item\n * formatting differs.\n */\nfunction summarizeWithOverflow<T>(\n items: readonly T[],\n formatItem: (item: T) => string,\n emptyMessage: string,\n): string {\n if (items.length === 0) return emptyMessage;\n const head = items\n .slice(0, 3)\n .map((item) => formatItem(item))\n .join(\"; \");\n const overflow = items.length > 3 ? ` (+${items.length - 3} more)` : \"\";\n return `${head}${overflow}`;\n}\n\nfunction summarizeIssues(issues: readonly GraphExtensionIssue[]): string {\n return summarizeWithOverflow(\n issues,\n (issue) => `${issue.path || \"(root)\"} — ${issue.message}`,\n \"no specific issues recorded\",\n );\n}\n\n/**\n * Thrown when an extension declares a kind whose name collides with an\n * existing compile-time kind. The graph-extension contract is\n * additive: graph-extension-declared kinds cannot shadow compile-time kinds.\n */\nexport class KindCollisionError extends GraphExtensionError {\n readonly code = \"KIND_COLLISION\" as const;\n readonly kindName: string;\n readonly entity: KindEntity;\n\n constructor(kindName: string, entity: KindEntity, graphId: string) {\n super({\n message: `Graph extension declares ${entity} kind \"${kindName}\" which already exists as a compile-time kind on graph \"${graphId}\". Graph-extension-declared kinds cannot collide with compile-time kinds.`,\n code: \"KIND_COLLISION\",\n details: { kindName, entity, graphId },\n suggestion:\n \"Pick a different graph-extension-declared kind name, or remove the compile-time declaration.\",\n });\n this.kindName = kindName;\n this.entity = entity;\n }\n}\n\n/**\n * One classified delta in a `IncompatibleChangeError`.\n *\n * `field` is `undefined` for kind-level changes (e.g. tightening edge\n * endpoints, adding a unique constraint to a populated kind). `detail`\n * is human-readable and intended for surfaces showing the change to a\n * reviewer (e.g. `\"minLength: 5 → 10\"`).\n */\n/**\n * Every incompatible-change classification produced by `evolve`'s\n * delta classifier. Const-array form so tests and reviewer UIs can\n * enumerate the set without restating it.\n */\nexport const INCOMPATIBLE_CHANGE_TYPES = [\n \"REMOVE_PROPERTY\",\n \"ADD_REQUIRED_PROPERTY\",\n \"TIGHTEN_OPTIONALITY\",\n \"TIGHTEN_CONSTRAINT\",\n \"ADD_PATTERN\",\n \"CHANGE_PATTERN\",\n \"ADD_FORMAT\",\n \"CHANGE_FORMAT\",\n \"TIGHTEN_INT\",\n \"TIGHTEN_ENUM\",\n \"TYPE_CHANGE\",\n \"ADD_UNIQUE_ON_POPULATED\",\n \"TIGHTEN_EDGE_ENDPOINTS\",\n] as const;\n\nexport type IncompatibleChangeType = (typeof INCOMPATIBLE_CHANGE_TYPES)[number];\n\nexport type IncompatibleChange = Readonly<{\n kind: string;\n field?: string;\n type: IncompatibleChangeType;\n detail?: string;\n}>;\n\n/**\n * Thrown when `evolve` rejects one or more deltas against an existing\n * extension kind. Carries a structured `changes` list so a reviewer\n * UI can show the incompatible deltas across every affected kind in\n * one shot.\n */\nexport class IncompatibleChangeError extends GraphExtensionError {\n readonly code = \"INCOMPATIBLE_CHANGE\" as const;\n readonly changes: readonly IncompatibleChange[];\n\n constructor(changes: readonly IncompatibleChange[], graphId: string) {\n const frozenChanges = Object.freeze([...changes]);\n super({\n message: `Graph extension contains ${changes.length} incompatible change${\n changes.length === 1 ? \"\" : \"s\"\n } against existing graph-extension kinds on graph \"${graphId}\": ${summarizeChanges(changes)}`,\n code: \"INCOMPATIBLE_CHANGE\",\n details: { graphId, changes: frozenChanges },\n suggestion:\n \"Inspect error.changes for the per-field rejections. Compatible options: change the modification to an additive one (e.g. `optional: true`), or apply the change against an empty kind.\",\n });\n this.changes = frozenChanges;\n }\n}\n\nfunction summarizeChanges(changes: readonly IncompatibleChange[]): string {\n return summarizeWithOverflow(\n changes,\n (change) => {\n const field = change.field === undefined ? \"\" : `.${change.field}`;\n const detail = change.detail === undefined ? \"\" : ` (${change.detail})`;\n return `${change.kind}${field}: ${change.type}${detail}`;\n },\n \"(no specific changes recorded)\",\n );\n}\n\n/**\n * Thrown when an extension's edge or ontology endpoint references a\n * kind that exists in neither the extension nor the host graph.\n * Distinct from `KindNotFoundError` because the cause is a\n * stale persisted extension (a compile-time kind was removed from\n * source after the extension was committed) rather than a\n * call-site typo.\n */\nexport class GraphExtensionUnresolvedEndpointError extends GraphExtensionError {\n readonly code = \"GRAPH_EXTENSION_UNRESOLVED_ENDPOINT\" as const;\n readonly edgeKind: string;\n readonly side: \"from\" | \"to\";\n readonly endpoint: string;\n\n constructor(\n edgeKind: string,\n side: \"from\" | \"to\",\n endpoint: string,\n graphId: string,\n ) {\n super({\n message: `Graph-extension edge \"${edgeKind}\" ${side}-endpoint \"${endpoint}\" does not resolve to any kind on graph \"${graphId}\". The compile-time kind may have been removed since the extension was committed.`,\n code: \"GRAPH_EXTENSION_UNRESOLVED_ENDPOINT\",\n details: { edgeKind, side, endpoint, graphId },\n suggestion:\n \"Restore the compile-time kind, or remove the graph-extension-declared kind via store.removeKinds before redeploying without it.\",\n });\n this.edgeKind = edgeKind;\n this.side = side;\n this.endpoint = endpoint;\n }\n}\n\n/**\n * Thrown by `removeKinds` when the removal list contains a compile-\n * time kind. Compile-time kinds are removed by recompiling and\n * redeploying — persisting \"removed-compile-time-kind\" state in\n * `schema_doc` is incoherent because the kind would resurrect on the\n * next deploy.\n */\nexport class RemoveCompileTimeKindError extends GraphExtensionError {\n readonly code = \"REMOVE_COMPILE_TIME_KIND\" as const;\n readonly kindName: string;\n readonly entity: KindEntity;\n\n constructor(kindName: string, entity: KindEntity, graphId: string) {\n super({\n message: `Cannot remove compile-time ${entity} kind \"${kindName}\" via store.removeKinds. Compile-time kinds are removed by recompiling and redeploying without them on graph \"${graphId}\".`,\n code: \"REMOVE_COMPILE_TIME_KIND\",\n details: { kindName, entity, graphId },\n suggestion:\n \"Drop the kind from your defineGraph call and redeploy. Only graph-extension kinds (added via store.evolve) are removable through removeKinds.\",\n });\n this.kindName = kindName;\n this.entity = entity;\n }\n}\n\n/**\n * Thrown by `removeKinds` when a compile-time edge or ontology\n * relation references the graph-extension kind being removed. Removing the\n * kind would orphan compile-time references — incoherent at the next\n * deploy.\n */\nexport class KindHasReferentsError extends GraphExtensionError {\n readonly code = \"KIND_HAS_REFERENTS\" as const;\n readonly kindName: string;\n readonly referents: readonly KindReferent[];\n\n constructor(\n kindName: string,\n referents: readonly KindReferent[],\n graphId: string,\n ) {\n const summary = referents\n .map((referent) => `${referent.type}:${referent.name}`)\n .join(\", \");\n const frozenReferents = Object.freeze([...referents]);\n super({\n message: `Cannot remove graph-extension kind \"${kindName}\" on graph \"${graphId}\" — it is referenced by compile-time declarations: ${summary}.`,\n code: \"KIND_HAS_REFERENTS\",\n details: { kindName, graphId, referents: frozenReferents },\n suggestion:\n \"Remove the compile-time references first (drop the edge or ontology relation from defineGraph), or pick a different kind to remove.\",\n });\n this.kindName = kindName;\n this.referents = frozenReferents;\n }\n}\n\nexport type KindReferent = Readonly<{\n type: \"compile-time-edge\" | \"compile-time-ontology\";\n name: string;\n}>;\n\n/**\n * Thrown when a persisted graph extension was authored against a\n * higher major version of the graph-extension format than the\n * current library supports. The library refuses to load it rather\n * than risk silently misreading newer fields.\n */\nexport class GraphExtensionVersionUnsupportedError extends GraphExtensionError {\n readonly code = \"GRAPH_EXTENSION_VERSION_UNSUPPORTED\" as const;\n readonly persistedVersion: number;\n readonly currentVersion: number;\n\n constructor(persistedVersion: number, currentVersion: number) {\n super({\n message: `Persisted extension was authored against graph-extension format v${persistedVersion}, but this library only supports up to v${currentVersion}. Upgrade @nicia-ai/typegraph.`,\n code: \"GRAPH_EXTENSION_VERSION_UNSUPPORTED\",\n details: { persistedVersion, currentVersion },\n category: \"system\",\n suggestion: `Upgrade @nicia-ai/typegraph to a version that supports graph-extension format v${persistedVersion}, or downgrade the writer.`,\n });\n this.persistedVersion = persistedVersion;\n this.currentVersion = currentVersion;\n }\n}\n","/**\n * Pure-value document format for graph extensions.\n *\n * A `GraphExtension` is a plain JSON-serializable description of\n * additional node kinds, edge kinds, and ontology relations that should\n * be merged into a graph at runtime. The document is the canonical\n * artifact: every restart re-compiles it back to the same Zod-bearing\n * `NodeType` / `EdgeType` / `OntologyRelation` shapes.\n *\n * The supported property-type subset is intentionally narrower than full\n * JSON Schema — only what compiles cleanly to Zod and what real\n * agent-induced schemas use in practice. Anything outside this set fails\n * loudly at `defineGraphExtension(...)`.\n */\nimport { type KindAnnotations, type NullCheckOp } from \"../core/types\";\nimport { type MetaEdgeName } from \"../ontology/constants\";\n\n// ============================================================\n// Property Types\n// ============================================================\n\n/**\n * Per-property modifier: tag the field as fulltext-searchable.\n *\n * Compiles to a `searchable({ language })`-wrapped Zod string when applied\n * to a `string` property. Rejected on any other property type at validation\n * time.\n */\nexport type ExtensionSearchableModifier = Readonly<{\n language?: string;\n}>;\n\n/**\n * Per-property modifier: declare a vector embedding with the given\n * dimensionality. Compiles to `embedding(dimensions)` and is only valid on\n * `array` properties whose item type is `number`. Rejected elsewhere.\n */\nexport type ExtensionEmbeddingModifier = Readonly<{\n dimensions: number;\n}>;\n\n/**\n * Modifiers shared by every graph-extension property type.\n *\n * `optional: true` flips the field from required-with-graph-extension-validation\n * to `.optional()` and removes it from the parent object's `required`\n * list. `searchable` and `embedding` only apply to specific underlying\n * types — see the per-modifier docs.\n */\ntype ExtensionPropertyModifiers = Readonly<{\n optional?: boolean;\n searchable?: ExtensionSearchableModifier;\n embedding?: ExtensionEmbeddingModifier;\n description?: string;\n}>;\n\n/**\n * String property. Compiles to `z.string()` plus the requested refinements.\n * `format` accepts the two formats motivated by induced schemas in\n * practice — covers ISO datetimes, URIs, email addresses, UUIDs, and\n * date-only strings. Each format routes to the corresponding Zod\n * factory (`z.iso.datetime()`, `z.url()`, `z.email()`, `z.uuid()`,\n * `z.iso.date()`); other JSON-Schema formats are deliberately not\n * supported in v1.\n */\nexport type ExtensionStringProperty = Readonly<{\n type: \"string\";\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n format?: \"datetime\" | \"uri\" | \"email\" | \"uuid\" | \"date\";\n}> &\n ExtensionPropertyModifiers;\n\n/**\n * Number property. `int: true` requires whole numbers; `min` / `max` are\n * inclusive bounds. Compiles to `z.number().int()?.min(...)?.max(...)`.\n */\nexport type ExtensionNumberProperty = Readonly<{\n type: \"number\";\n min?: number;\n max?: number;\n int?: boolean;\n}> &\n ExtensionPropertyModifiers;\n\n/**\n * Boolean property. Compiles to `z.boolean()`.\n */\nexport type ExtensionBooleanProperty = Readonly<{\n type: \"boolean\";\n}> &\n ExtensionPropertyModifiers;\n\n/**\n * Closed-set string enum. Compiles to `z.enum([...values])`. Must contain\n * at least one value; duplicate values are rejected at validation time.\n */\nexport type ExtensionEnumProperty = Readonly<{\n type: \"enum\";\n values: readonly string[];\n}> &\n ExtensionPropertyModifiers;\n\n/**\n * Array property. `items` is any of the scalar property types or an\n * object property — nested arrays are forbidden in v1. Compiles to\n * `z.array(<items>)`. The `embedding` modifier turns this into a\n * vector embedding instead of a generic array.\n */\nexport type ExtensionArrayProperty = Readonly<{\n type: \"array\";\n items: ExtensionArrayItemType;\n}> &\n ExtensionPropertyModifiers;\n\n/**\n * Element types allowed inside an array — every leaf property type plus\n * single-level object. Nesting an array inside an array is rejected at\n * validation time so the v1 surface stays a flat tree.\n */\nexport type ExtensionArrayItemType =\n | ExtensionStringProperty\n | ExtensionNumberProperty\n | ExtensionBooleanProperty\n | ExtensionEnumProperty\n | ExtensionObjectProperty;\n\n/**\n * Object property. `properties` is a single nesting level; deeper objects\n * are rejected at validation time so the v1 surface is auditable at a\n * glance.\n */\nexport type ExtensionObjectProperty = Readonly<{\n type: \"object\";\n properties: Readonly<Record<string, ExtensionObjectFieldProperty>>;\n}> &\n ExtensionPropertyModifiers;\n\n/**\n * Property types allowed inside an `object`'s `properties` — leaf scalars\n * and arrays only. Nested objects are blocked here to enforce the\n * single-nesting-level rule.\n */\nexport type ExtensionObjectFieldProperty =\n | ExtensionStringProperty\n | ExtensionNumberProperty\n | ExtensionBooleanProperty\n | ExtensionEnumProperty\n | ExtensionArrayProperty;\n\n/**\n * Top-level property descriptor for a node or edge field.\n *\n * The discriminated union covers every type in the v1 subset; arbitrary\n * `unknown` inputs are validated against this set at\n * `defineGraphExtension(...)` time.\n */\nexport type ExtensionPropertyType =\n | ExtensionStringProperty\n | ExtensionNumberProperty\n | ExtensionBooleanProperty\n | ExtensionEnumProperty\n | ExtensionArrayProperty\n | ExtensionObjectProperty;\n\n// ============================================================\n// Unique Constraints\n// ============================================================\n\n/**\n * Document-side `where` clause for a unique constraint.\n *\n * Mirrors `serializeWherePredicate`'s capability — the only operations\n * round-trippable through the persisted form are `isNull` and `isNotNull`.\n * Anything richer (equality, `in`, etc.) is rejected at validation time.\n */\nexport type ExtensionUniqueWhere = Readonly<{\n field: string;\n op: NullCheckOp;\n}>;\n\n/**\n * Unique constraint declaration. `fields` must reference declared\n * properties on the kind. Defaults match the existing `UniqueConstraint`:\n * `scope: \"kind\"`, `collation: \"binary\"`.\n */\nexport type ExtensionUniqueConstraint = Readonly<{\n name: string;\n fields: readonly string[];\n scope?: \"kind\" | \"kindWithSubClasses\";\n collation?: \"binary\" | \"caseInsensitive\";\n where?: ExtensionUniqueWhere;\n}>;\n\n// ============================================================\n// Node and Edge Documents\n// ============================================================\n\n/**\n * Graph-extension declaration of a node kind.\n *\n * Property names follow the same reserved-key rules as compile-time\n * `defineNode` (`id`, `kind`, `meta`, and the `$`-prefix accessor\n * namespace are forbidden). Annotation values must be JSON.\n */\nexport type ExtensionNodeDef = Readonly<{\n description?: string;\n annotations?: KindAnnotations;\n properties: Readonly<Record<string, ExtensionPropertyType>>;\n unique?: readonly ExtensionUniqueConstraint[];\n}>;\n\n/**\n * Graph-extension declaration of an edge kind.\n *\n * `from` / `to` reference node kind names — either kinds declared in this\n * same document or compile-time kinds the document is being merged into.\n * Endpoints that resolve to nothing within the document are flagged as\n * soft references at validation time but not rejected; the final\n * cross-graph check happens when the document is merged into a host\n * `GraphDef`.\n */\nexport type ExtensionEdgeDef = Readonly<{\n description?: string;\n annotations?: KindAnnotations;\n from: readonly string[];\n to: readonly string[];\n properties?: Readonly<Record<string, ExtensionPropertyType>>;\n}>;\n\n// ============================================================\n// Indexes (relational)\n// ============================================================\n\n/**\n * Document-level analogue of compile-time `defineNodeIndex` /\n * `defineEdgeIndex`. Mirrors `serializeWherePredicate`'s persistence-\n * round-trippable subset: only `isNull` / `isNotNull` predicates are\n * supported in v1, matching `ExtensionUniqueWhere`.\n */\nexport type ExtensionIndexWhere = Readonly<{\n field: string;\n op: NullCheckOp;\n}>;\n\n/**\n * Graph-extension-declared node index. `kind` references either a kind\n * declared in this same document or a compile-time host kind resolved\n * at merge time. `fields` and `coveringFields` are top-level property\n * names — JSON-pointer paths are not supported in v1, matching the\n * `ExtensionUniqueConstraint` v1 surface.\n */\nexport type ExtensionNodeIndex = Readonly<{\n entity: \"node\";\n kind: string;\n name?: string;\n fields: readonly string[];\n coveringFields?: readonly string[];\n unique?: boolean;\n scope?: \"graphAndKind\" | \"graph\" | \"none\";\n where?: ExtensionIndexWhere;\n}>;\n\n/**\n * Graph-extension-declared edge index. `direction` mirrors\n * `EdgeIndexDirection`; `kind` references a graph-extension or compile-time\n * edge kind.\n */\nexport type ExtensionEdgeIndex = Readonly<{\n entity: \"edge\";\n kind: string;\n name?: string;\n direction?: \"out\" | \"in\" | \"none\";\n fields: readonly string[];\n coveringFields?: readonly string[];\n unique?: boolean;\n scope?: \"graphAndKind\" | \"graph\" | \"none\";\n where?: ExtensionIndexWhere;\n}>;\n\nexport type ExtensionIndex = ExtensionNodeIndex | ExtensionEdgeIndex;\n\n// ============================================================\n// Ontology\n// ============================================================\n\n/**\n * Graph-extension ontology relation. `metaEdge` is one of the built-in\n * meta-edge names (subClassOf, broader, disjointWith, etc.).\n *\n * `from` / `to` are either node-kind names declared in this document or\n * external IRI strings. The pure-value document does not distinguish the\n * two — the compiler treats endpoints that match a declared kind as\n * `NodeType` references and falls back to passing the raw string for\n * IRIs (matching the existing `OntologyRelation` shape, where\n * `from`/`to` are `NodeType | EdgeType | string`).\n */\nexport type ExtensionOntologyRelation = Readonly<{\n metaEdge: MetaEdgeName;\n from: string;\n to: string;\n}>;\n\n// ============================================================\n// Document\n// ============================================================\n\n/**\n * Stable default major used when a stored document omits `version`.\n *\n * Pinned to `1` permanently. Pre-versioning documents (those persisted\n * before the field existed) and documents that explicitly omit\n * `version` are interpreted as `1` regardless of which major the\n * library currently supports. Splitting this from\n * `CURRENT_GRAPH_EXTENSION_VERSION` is load-bearing for future major\n * bumps: when v2 ships, `CURRENT` becomes `2` but `LEGACY` stays at\n * `1`, so a v1-era stored document still parses as v1 (and the\n * version-mismatch path can route it through a migration) rather than\n * being silently misinterpreted as v2.\n */\nexport const LEGACY_GRAPH_EXTENSION_VERSION = 1 as const;\n\n/**\n * Current major version of the `GraphExtension` format.\n *\n * Documents with a higher major version than this constant are\n * rejected with `GRAPH_EXTENSION_VERSION_UNSUPPORTED` — there is no\n * automatic downgrade path. Minor / additive changes ride forward-\n * compat via `.loose()` on every nested object schema.\n */\nexport const CURRENT_GRAPH_EXTENSION_VERSION = 1 as const;\n\n/**\n * Type of the `GraphExtension.version` field. Stays `number`\n * rather than `typeof CURRENT_GRAPH_EXTENSION_VERSION` because the\n * field can carry any major across the library version range a\n * stored document might have been written by — the\n * document-vs-supported check happens in the validator, not at the\n * type level. Pinning to the current literal would prevent a v1\n * v1 library from typing a v2 document at all, which is the wrong\n * relationship: we WANT a v1 library to receive v2 documents and\n * report `GRAPH_EXTENSION_VERSION_UNSUPPORTED` cleanly.\n */\nexport type GraphExtensionVersion = number;\n\n/**\n * The canonical pure-value graph-extension document.\n *\n * Frozen at construction. Round-trips losslessly through `JSON.stringify`\n * / `JSON.parse`; the `GraphExtension → CompiledExtension` direction\n * is provided by `compileGraphExtension(...)`. There is no\n * `Zod → GraphExtension` direction because graph-extension kinds always\n * originate as documents.\n *\n * `version` is the major-version tag for the document format. The\n * compiler accepts documents whose version is equal to the current\n * supported major (today: 1) or absent (the canonical persisted form\n * omits `version` when it equals the legacy default — see\n * `serializer.ts` — so the round-trip default is \"absent means legacy\n * major\"). Higher majors surface as\n * `GRAPH_EXTENSION_VERSION_UNSUPPORTED` so a newer-version extension\n * committed by a future writer can't be silently misread by an older\n * runtime. See `graph-extensions.md` for the format-versioning policy.\n */\nexport type GraphExtension = Readonly<{\n version?: GraphExtensionVersion;\n nodes?: Readonly<Record<string, ExtensionNodeDef>>;\n edges?: Readonly<Record<string, ExtensionEdgeDef>>;\n ontology?: readonly ExtensionOntologyRelation[];\n /**\n * Graph-extension-declared relational indexes. Each entry references a\n * node or edge kind by name — either declared in this document or\n * a compile-time host kind that the document is being merged into.\n * Vector indexes auto-derive from `embedding()` modifiers on\n * graph-extension kinds; this slot is for explicit relational indexes\n * (analogue of compile-time `defineGraph({ indexes: [...] })`).\n */\n indexes?: readonly ExtensionIndex[];\n}>;\n\n/**\n * Top-level v1 slots a `GraphExtension` document may carry. Single\n * source of truth for both the strict-authoring validator (typo rejection\n * via `defineGraphExtension`) and the persistence Zod schema (which\n * leaves the field set loose for forward compatibility but uses this\n * list to drive the Zod object shape).\n */\nexport const GRAPH_EXTENSION_TOP_LEVEL_KEYS = [\n \"version\",\n \"nodes\",\n \"edges\",\n \"ontology\",\n \"indexes\",\n] as const;\n\nexport type GraphExtensionTopLevelKey =\n (typeof GRAPH_EXTENSION_TOP_LEVEL_KEYS)[number];\n","/**\n * Plain-object predicate. Excludes class instances (Date, Map, Set,\n * RegExp, Buffer, …) and arrays. Used wherever the caller needs to\n * distinguish a literal `{}` from anything else — e.g. JSON-value\n * validation and runtime-document structural checks.\n */\nexport function isPlainObject(\n value: unknown,\n): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * Builds an object dropping any keys whose value is `undefined`.\n *\n * Lets callers construct discriminated-union members and `defineNode` /\n * `defineEdge` option objects without tripping over\n * `exactOptionalPropertyTypes: true` — which forbids setting `optional:\n * undefined` on a type that declares `optional?: boolean`. The cast keeps\n * call sites readable; this helper is the single typed seam.\n */\nexport function compactUndefined<T extends object>(value: {\n [K in keyof T]: T[K] | undefined;\n}): T {\n const result: Record<string, unknown> = {};\n for (const [key, fieldValue] of Object.entries(value)) {\n if (fieldValue !== undefined) result[key] = fieldValue;\n }\n return result as T;\n}\n\n/**\n * Recursively `Object.freeze` every plain object / array reachable from\n * `value`. Already-frozen branches are skipped. Returns the input for\n * convenient chaining; the freeze is in-place.\n *\n * Class instances and other non-plain values are left alone — only their\n * containers freeze.\n */\nexport function freezeDeep<T>(value: T): T {\n if (value === null || typeof value !== \"object\") return value;\n if (Object.isFrozen(value)) return value;\n for (const nested of Object.values(value as Record<string, unknown>)) {\n freezeDeep(nested);\n }\n return Object.freeze(value);\n}\n","/**\n * Runtime validation for JSON-serializable values.\n *\n * Used at definition-time boundaries (e.g., `defineNode`/`defineEdge` annotations)\n * to reject values that would silently break `JSON.stringify` round-trips or\n * throw at hash time. Catches accidental violations from untyped JS callers\n * and `as any` escape hatches that bypass the `JsonValue` type.\n */\nimport { ConfigurationError } from \"../errors\";\nimport { isPlainObject } from \"../utils/object\";\n\n/**\n * Asserts that `value` is JSON-serializable.\n *\n * Throws `ConfigurationError` with a dotted path identifying the offending\n * field. Rejects `bigint`, `function`, `symbol`, `undefined`, and class\n * instances such as `Date`, `Map`, `Set`, regex literals, and Buffers — all\n * of which either throw or silently coerce under `JSON.stringify`.\n *\n * @param value - The value to validate\n * @param rootLabel - Label for the root of the value (e.g., `\"annotations\"`)\n * used as the prefix of the error path\n * @param ownerKind - Human-readable owner identifier for the error message\n * (e.g., `'Node \"Person\"'`)\n */\nexport function assertJsonValue(\n value: unknown,\n rootLabel: string,\n ownerKind: string,\n): void {\n walk(value, rootLabel, ownerKind);\n}\n\nfunction walk(value: unknown, path: string, ownerKind: string): void {\n if (value === null) return;\n const valueType = typeof value;\n if (valueType === \"number\") {\n // NaN/Infinity/-Infinity are not JSON values; JSON.stringify silently\n // coerces them to `null`, which would change the canonical hash input\n // without the consumer noticing.\n if (!Number.isFinite(value)) {\n throwInvalid(path, describeNonFinite(value as number), ownerKind);\n }\n return;\n }\n if (valueType === \"string\" || valueType === \"boolean\") return;\n if (\n valueType === \"bigint\" ||\n valueType === \"function\" ||\n valueType === \"symbol\" ||\n valueType === \"undefined\"\n ) {\n throwInvalid(path, valueType, ownerKind);\n }\n if (Array.isArray(value)) {\n for (const [index, element] of value.entries()) {\n walk(element, `${path}[${index}]`, ownerKind);\n }\n return;\n }\n if (!isPlainObject(value)) {\n throwInvalid(path, describeNonPlain(value), ownerKind);\n }\n for (const [key, nested] of Object.entries(value)) {\n walk(nested, `${path}.${key}`, ownerKind);\n }\n}\n\nfunction describeNonFinite(value: number): string {\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Number.POSITIVE_INFINITY) return \"Infinity\";\n if (value === Number.NEGATIVE_INFINITY) return \"-Infinity\";\n return \"non-finite number\";\n}\n\nfunction describeNonPlain(value: unknown): string {\n const constructorName = (value as { constructor?: { name?: unknown } } | null)\n ?.constructor?.name;\n if (typeof constructorName === \"string\" && constructorName.length > 0) {\n return `${constructorName} instance`;\n }\n return \"non-plain object\";\n}\n\nfunction throwInvalid(path: string, kind: string, ownerKind: string): never {\n throw new ConfigurationError(\n `${ownerKind} ${path} contains a non-JSON value (${kind}). Annotations must be JSON-serializable.`,\n { path, valueKind: kind },\n {\n suggestion:\n \"Use only strings, numbers, booleans, null, arrays, and plain objects in annotations.\",\n },\n );\n}\n","/**\n * Transitive closure computation for ontology relationships.\n *\n * Uses Warshall's algorithm for efficient closure computation.\n */\n\n/**\n * Computes the transitive closure of a set of directed relations.\n *\n * Given relations like [A→B, B→C], computes all transitive paths [A→B, A→C, B→C].\n *\n * @param relations - Array of [from, to] pairs representing direct relationships\n * @returns Map from each 'from' to the set of all reachable 'to' values\n */\nexport function computeTransitiveClosure(\n relations: readonly (readonly [string, string])[],\n): ReadonlyMap<string, ReadonlySet<string>> {\n // Build mutable map for computation\n const closure = new Map<string, Set<string>>();\n\n // Collect all nodes\n const allNodes = new Set<string>();\n for (const [from, to] of relations) {\n allNodes.add(from);\n allNodes.add(to);\n }\n\n // Initialize empty sets for all nodes\n for (const node of allNodes) {\n closure.set(node, new Set());\n }\n\n // Add direct relationships\n for (const [from, to] of relations) {\n closure.get(from)?.add(to);\n }\n\n // Warshall's algorithm for transitive closure\n // For each intermediate node k, check if i→k and k→j implies i→j\n for (const k of allNodes) {\n for (const index of allNodes) {\n const indexReaches = closure.get(index);\n if (!indexReaches?.has(k)) continue;\n\n const kReaches = closure.get(k);\n if (!kReaches) continue;\n\n for (const index of kReaches) {\n indexReaches.add(index);\n }\n }\n }\n\n return closure;\n}\n\n/**\n * Computes the inverse of a transitive closure map.\n *\n * Given A→{B, C}, returns B→{A}, C→{A}.\n */\nexport function invertClosure(\n closure: ReadonlyMap<string, ReadonlySet<string>>,\n): ReadonlyMap<string, ReadonlySet<string>> {\n const result = new Map<string, Set<string>>();\n\n for (const [from, tos] of closure) {\n for (const to of tos) {\n const existing = result.get(to) ?? new Set();\n existing.add(from);\n result.set(to, existing);\n }\n }\n\n return result;\n}\n\n/**\n * Checks if there's a path from source to target in the closure.\n */\nexport function isReachable(\n closure: ReadonlyMap<string, ReadonlySet<string>>,\n source: string,\n target: string,\n): boolean {\n return closure.get(source)?.has(target) ?? false;\n}\n","/**\n * Named constants for ontology meta-edge names.\n *\n * Use these constants instead of string literals for type safety\n * and IDE support.\n */\n\n// ============================================================\n// Meta-Edge Names\n// ============================================================\n\n/** Type inheritance (Podcast subClassOf Media) */\nexport const META_EDGE_SUB_CLASS_OF = \"subClassOf\" as const;\n\n/** Broader concept (ML broader AI) */\nexport const META_EDGE_BROADER = \"broader\" as const;\n\n/** Narrower concept (AI narrower ML) */\nexport const META_EDGE_NARROWER = \"narrower\" as const;\n\n/** Non-hierarchical association */\nexport const META_EDGE_RELATED_TO = \"relatedTo\" as const;\n\n/** Same class, different representation */\nexport const META_EDGE_EQUIVALENT_TO = \"equivalentTo\" as const;\n\n/** Same individual (for deduplication) */\nexport const META_EDGE_SAME_AS = \"sameAs\" as const;\n\n/** Explicitly different individuals */\nexport const META_EDGE_DIFFERENT_FROM = \"differentFrom\" as const;\n\n/** Mutually exclusive types */\nexport const META_EDGE_DISJOINT_WITH = \"disjointWith\" as const;\n\n/** X is part of Y */\nexport const META_EDGE_PART_OF = \"partOf\" as const;\n\n/** Y has part X */\nexport const META_EDGE_HAS_PART = \"hasPart\" as const;\n\n/** Edge A is inverse of edge B */\nexport const META_EDGE_INVERSE_OF = \"inverseOf\" as const;\n\n/** Edge A implies edge B exists */\nexport const META_EDGE_IMPLIES = \"implies\" as const;\n\n// ============================================================\n// All Meta-Edge Names (for validation)\n// ============================================================\n\nexport const ALL_META_EDGE_NAMES = [\n META_EDGE_SUB_CLASS_OF,\n META_EDGE_BROADER,\n META_EDGE_NARROWER,\n META_EDGE_RELATED_TO,\n META_EDGE_EQUIVALENT_TO,\n META_EDGE_SAME_AS,\n META_EDGE_DIFFERENT_FROM,\n META_EDGE_DISJOINT_WITH,\n META_EDGE_PART_OF,\n META_EDGE_HAS_PART,\n META_EDGE_INVERSE_OF,\n META_EDGE_IMPLIES,\n] as const;\n\nexport type MetaEdgeName = (typeof ALL_META_EDGE_NAMES)[number];\n","/**\n * Reserved Keys for Store Entities\n *\n * Structural keys that cannot be overwritten by user-defined properties.\n * Shared across row-mappers, subgraph projection, and schema validation.\n */\nimport type { KindEntity } from \"../core/types\";\nimport { ConfigurationError } from \"../errors\";\n\nexport const RESERVED_NODE_KEYS: ReadonlySet<string> = new Set([\n \"id\",\n \"kind\",\n \"meta\",\n]);\n\nexport const RESERVED_EDGE_KEYS: ReadonlySet<string> = new Set([\n \"id\",\n \"kind\",\n \"meta\",\n \"fromKind\",\n \"fromId\",\n \"toKind\",\n \"toId\",\n]);\n\nconst PROTOTYPE_POLLUTION_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Properties starting with `$` are reserved for TypeGraph-owned accessors\n * on the query-builder node/edge proxies (today: `$fulltext`). Reserving\n * the whole prefix — not just the currently-used names — keeps future\n * accessors (e.g. `$vector`, `$json`) from colliding with user fields.\n */\nconst RESERVED_PROPERTY_PREFIX = \"$\";\n\n/**\n * True if a user-defined field name is reserved by TypeGraph's accessor\n * namespace. `defineNode` / `defineEdge` call this against schema keys so\n * the collision fails fast at graph-definition time rather than silently\n * at query time.\n */\nfunction isReservedPropertyName(name: string): boolean {\n return name.startsWith(RESERVED_PROPERTY_PREFIX);\n}\n\n/**\n * Validates that a node or edge schema does not use any reserved property\n * name. Covers both the structural keys (`id`, `kind`, etc.) and the\n * `$`-prefix accessor namespace. Throws a single `ConfigurationError`\n * per conflict class so the user sees all collisions in one pass.\n */\nexport function assertSchemaKeysAreFree(\n entityKind: \"Node\" | \"Edge\",\n name: string,\n keys: readonly string[],\n reservedStructuralKeys: ReadonlySet<string>,\n): void {\n const structuralConflicts = keys.filter((key) =>\n reservedStructuralKeys.has(key),\n );\n if (structuralConflicts.length > 0) {\n const label = entityKind.toLowerCase();\n throw new ConfigurationError(\n `${entityKind} \"${name}\" schema contains reserved property names: ${structuralConflicts.join(\", \")}`,\n {\n [`${label}Type`]: name,\n conflicts: structuralConflicts,\n reservedKeys: [...reservedStructuralKeys],\n },\n {\n suggestion: `Rename the conflicting properties. Reserved names (${[...reservedStructuralKeys].join(\", \")}) are added automatically to all ${label}s.`,\n },\n );\n }\n\n const prefixConflicts = keys.filter((key) => isReservedPropertyName(key));\n if (prefixConflicts.length > 0) {\n const label = entityKind.toLowerCase();\n throw new ConfigurationError(\n `${entityKind} \"${name}\" schema uses the reserved \"${RESERVED_PROPERTY_PREFIX}\" prefix on: ${prefixConflicts.join(\", \")}`,\n {\n [`${label}Type`]: name,\n conflicts: prefixConflicts,\n reservedPrefix: RESERVED_PROPERTY_PREFIX,\n },\n {\n suggestion: `Property names starting with \"${RESERVED_PROPERTY_PREFIX}\" are reserved for TypeGraph accessors (e.g. $fulltext). Rename each field.`,\n },\n );\n }\n}\n\n/**\n * Validates that a projection field name is safe to assign onto a result object.\n * Rejects reserved structural keys and prototype-pollution vectors.\n *\n * @throws ConfigurationError if the field is reserved or dangerous\n */\nexport function validateProjectionField(\n field: string,\n entityType: KindEntity,\n kind: string,\n): void {\n const reserved =\n entityType === \"node\" ? RESERVED_NODE_KEYS : RESERVED_EDGE_KEYS;\n\n if (reserved.has(field)) {\n throw new ConfigurationError(\n `Projection field \"${field}\" on ${entityType} kind \"${kind}\" conflicts with a reserved structural key`,\n { field, kind, entityType, reservedKeys: [...reserved] },\n {\n suggestion: `Remove \"${field}\" from the projection. Structural fields (${[...reserved].join(\", \")}) are included automatically when relevant.`,\n },\n );\n }\n\n if (PROTOTYPE_POLLUTION_KEYS.has(field)) {\n throw new ConfigurationError(\n `Projection field \"${field}\" on ${entityType} kind \"${kind}\" is not allowed`,\n { field, kind, entityType },\n {\n suggestion: `\"${field}\" cannot be used as a projection field name.`,\n },\n );\n }\n}\n\n/**\n * Filters out reserved keys from a props object to prevent runtime collisions.\n */\nexport function filterReservedKeys(\n props: Record<string, unknown>,\n reservedKeys: ReadonlySet<string>,\n): Record<string, unknown> {\n const filtered: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(props)) {\n if (!reservedKeys.has(key)) {\n filtered[key] = value;\n }\n }\n return filtered;\n}\n","/**\n * Result type for error handling without exceptions.\n * Use at service boundaries and for operations that can fail.\n */\nexport type Result<T, E = Error> =\n | Readonly<{ success: true; data: T }>\n | Readonly<{ success: false; error: E }>;\n\n/**\n * Creates a successful result.\n */\nexport function ok<T = undefined>(data?: T): Result<T, never> {\n return { success: true, data: data as T };\n}\n\n/**\n * Creates a failed result.\n */\nexport function err<E>(error: E): Result<never, E> {\n return { success: false, error };\n}\n\n/**\n * Unwraps a result, throwing if it's an error.\n */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n if (result.success) {\n return result.data;\n }\n throw result.error;\n}\n\n/**\n * Unwraps a result or returns a default value.\n */\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n if (result.success) {\n return result.data;\n }\n return defaultValue;\n}\n\n/**\n * Type guard to check if result is successful.\n */\nexport function isOk<T, E>(\n result: Result<T, E>,\n): result is { success: true; data: T } {\n return result.success;\n}\n\n/**\n * Type guard to check if result is an error.\n */\nexport function isErr<T, E>(\n result: Result<T, E>,\n): result is { success: false; error: E } {\n return !result.success;\n}\n\n/**\n * Transforms the success value of a result.\n */\nexport function map<T, U, E>(\n result: Result<T, E>,\n fn: (data: T) => U,\n): Result<U, E> {\n if (result.success) return ok(fn(result.data));\n return result;\n}\n\n/**\n * Transforms the error value of a result.\n */\nexport function mapErr<T, E, F>(\n result: Result<T, E>,\n fn: (error: E) => F,\n): Result<T, F> {\n if (result.success) return result;\n return err(fn(result.error));\n}\n\n/**\n * Chains an operation that returns a Result on the success value.\n */\nexport function flatMap<T, U, E>(\n result: Result<T, E>,\n fn: (data: T) => Result<U, E>,\n): Result<U, E> {\n if (result.success) return fn(result.data);\n return result;\n}\n\n/**\n * Recovers from an error by producing an alternative Result.\n */\nexport function orElse<T, E, F>(\n result: Result<T, E>,\n fn: (error: E) => Result<T, F>,\n): Result<T, F> {\n if (result.success) return result;\n return fn(result.error);\n}\n","/**\n * Pure structural validation for `GraphExtension`.\n *\n * Walks the document and accumulates every issue (no fail-fast) so a\n * caller showing the document to a human reviewer can surface all\n * problems in one round. Cross-document references — edge endpoints,\n * ontology endpoints — resolve only against this document; resolution\n * against an existing compile-time graph happens later, when the\n * document is merged into a host `GraphDef`.\n */\nimport { assertJsonValue } from \"../core/json-value\";\nimport {\n type KindAnnotations,\n type KindEntity,\n type NullCheckOp,\n} from \"../core/types\";\nimport { ConfigurationError } from \"../errors\";\nimport { computeTransitiveClosure } from \"../ontology/closures\";\nimport { ALL_META_EDGE_NAMES, type MetaEdgeName } from \"../ontology/constants\";\nimport { encodeJsonPointerSegment } from \"../query/json-pointer\";\nimport { RESERVED_EDGE_KEYS, RESERVED_NODE_KEYS } from \"../store/reserved-keys\";\nimport { compactUndefined, freezeDeep, isPlainObject } from \"../utils/object\";\nimport { err, ok, type Result } from \"../utils/result\";\nimport {\n type GraphExtensionIssue,\n type GraphExtensionIssueCode,\n GraphExtensionValidationError,\n GraphExtensionVersionUnsupportedError,\n} from \"./errors\";\nimport {\n CURRENT_GRAPH_EXTENSION_VERSION,\n type ExtensionArrayProperty,\n type ExtensionBooleanProperty,\n type ExtensionEdgeDef,\n type ExtensionEnumProperty,\n type ExtensionIndex,\n type ExtensionNodeDef,\n type ExtensionNumberProperty,\n type ExtensionObjectFieldProperty,\n type ExtensionObjectProperty,\n type ExtensionOntologyRelation,\n type ExtensionPropertyType,\n type ExtensionStringProperty,\n type ExtensionUniqueConstraint,\n GRAPH_EXTENSION_TOP_LEVEL_KEYS,\n type GraphExtension,\n type GraphExtensionVersion,\n LEGACY_GRAPH_EXTENSION_VERSION,\n} from \"./extension-types\";\n\nconst META_EDGE_NAME_SET: ReadonlySet<string> = new Set(ALL_META_EDGE_NAMES);\n\nconst SUPPORTED_PROPERTY_TYPES = new Set([\n \"string\",\n \"number\",\n \"boolean\",\n \"enum\",\n \"array\",\n \"object\",\n]);\n\n// Unknown per-property-type refinement keys are intentionally accepted\n// for forward compatibility: a future v1.x.y writer may emit additive\n// refinements an older v1 reader doesn't recognize. Recognized\n// refinements are read inline by the per-type validators\n// (e.g. `minLength` in `validateStringProperty`).\n\nconst SUPPORTED_STRING_FORMATS = new Set([\n \"datetime\",\n \"uri\",\n \"email\",\n \"uuid\",\n \"date\",\n]);\n\n/**\n * Recognized keys shared by every property-type descriptor. The strict\n * authoring path rejects unknown sibling keys against the union of this\n * set and the per-type allowlist below; the loose persistence-load path\n * passes them through untouched (a future v1.x.y writer may emit\n * additive keys an older v1 reader doesn't recognize).\n */\nconst COMMON_PROPERTY_KEYS: ReadonlySet<string> = new Set([\n \"type\",\n \"optional\",\n \"description\",\n \"searchable\",\n \"embedding\",\n]);\n\nconst PROPERTY_TYPE_KEYS: Readonly<Record<string, ReadonlySet<string>>> = {\n string: new Set([\"minLength\", \"maxLength\", \"pattern\", \"format\"]),\n number: new Set([\"min\", \"max\", \"int\"]),\n boolean: new Set(),\n enum: new Set([\"values\"]),\n array: new Set([\"items\"]),\n object: new Set([\"properties\"]),\n};\n\n/**\n * In strict mode, surface an `UNKNOWN_PROPERTY_KEY` issue for every\n * key on `raw` that's not in either allowlist. This is the LLM /\n * agent-trust-boundary check: a typo like `minLenght: 5` on a string\n * field, or a refinement key from a future v1.x that this library\n * doesn't recognize, would otherwise compile to a weaker schema with\n * no signal to the reviewer.\n */\nfunction rejectUnknownPropertyKeys(\n raw: Record<string, unknown>,\n type: string,\n path: string,\n issues: GraphExtensionIssue[],\n): void {\n const typeKeys = PROPERTY_TYPE_KEYS[type] ?? new Set<string>();\n const recognized = [...COMMON_PROPERTY_KEYS, ...typeKeys];\n for (const key of Object.keys(raw)) {\n if (COMMON_PROPERTY_KEYS.has(key) || typeKeys.has(key)) continue;\n issues.push({\n path: `${path}/${encodeJsonPointerSegment(key)}`,\n message: `Unknown property key \"${key}\" for type \"${type}\". Recognized keys: ${recognized.join(\", \")}.`,\n code: \"UNKNOWN_PROPERTY_KEY\",\n });\n }\n}\n\n/**\n * Sibling of `rejectUnknownPropertyKeys` for the non-property strict-mode\n * checks (top-level slots, node/edge/ontology body keys, unique constraint\n * body, where-clause body, …). Each call site previously open-coded the\n * same `for-key-of-Object.keys` walk — this helper consolidates them.\n */\nfunction rejectUnknownObjectKeys(\n raw: Readonly<Record<string, unknown>>,\n allowed: ReadonlySet<string>,\n label: string,\n path: string,\n code: GraphExtensionIssueCode,\n issues: GraphExtensionIssue[],\n): void {\n for (const key of Object.keys(raw)) {\n if (allowed.has(key)) continue;\n issues.push({\n path: `${path}/${encodeJsonPointerSegment(key)}`,\n message: `Unknown ${label} key \"${key}\". Allowed: ${[...allowed].join(\", \")}.`,\n code,\n });\n }\n}\n\n/**\n * Top-level slots accepted in v1 documents. Strict-authoring callers\n * reject unknown sibling keys to surface typos like `node` instead of\n * `nodes`; the loose persistence-load path leaves unknowns untouched\n * for forward compatibility.\n */\nconst KNOWN_DOCUMENT_KEYS: ReadonlySet<string> = new Set(\n GRAPH_EXTENSION_TOP_LEVEL_KEYS,\n);\n\n/**\n * Recognized body-level key sets — one per document-shape that the\n * strict-authoring path validates. Drives both the per-shape allowlist\n * check (`rejectUnknownObjectKeys`) and the human-readable \"Allowed:\"\n * tail in the error messages.\n */\nconst NODE_BODY_KEYS: ReadonlySet<string> = new Set([\n \"description\",\n \"annotations\",\n \"properties\",\n \"unique\",\n]);\nconst EDGE_BODY_KEYS: ReadonlySet<string> = new Set([\n \"description\",\n \"annotations\",\n \"from\",\n \"to\",\n \"properties\",\n]);\nconst ONTOLOGY_ENTRY_KEYS: ReadonlySet<string> = new Set([\n \"metaEdge\",\n \"from\",\n \"to\",\n]);\nconst UNIQUE_CONSTRAINT_KEYS: ReadonlySet<string> = new Set([\n \"name\",\n \"fields\",\n \"scope\",\n \"collation\",\n \"where\",\n]);\nconst WHERE_CLAUSE_KEYS: ReadonlySet<string> = new Set([\"field\", \"op\"]);\nconst NODE_INDEX_KEYS: ReadonlySet<string> = new Set([\n \"entity\",\n \"kind\",\n \"name\",\n \"fields\",\n \"coveringFields\",\n \"unique\",\n \"scope\",\n \"where\",\n]);\nconst EDGE_INDEX_KEYS: ReadonlySet<string> = new Set([\n \"entity\",\n \"kind\",\n \"name\",\n \"fields\",\n \"coveringFields\",\n \"unique\",\n \"scope\",\n \"direction\",\n \"where\",\n]);\n\ntype ValidateGraphExtensionOptions = Readonly<{\n /**\n * Reject unknown top-level keys and unsupported string formats.\n * Used by `defineGraphExtension`, where the document is being\n * authored fresh against the current library version — typos in\n * `nodes` / `format: \"date-time\"` etc. should fail loudly. The\n * persistence-load path leaves this off so a document committed by\n * a future v1.x writer with additive fields still parses on an\n * older v1 reader.\n */\n strict?: boolean;\n}>;\n\n/**\n * Validates a graph extension.\n *\n * Returns the (frozen, deeply normalized) extension on success, or a\n * `GraphExtensionValidationError` carrying every issue on authoring\n * failure. Unsupported future major versions throw\n * `GraphExtensionVersionUnsupportedError` immediately because the\n * current library cannot safely decode the rest of the document.\n * Callers that prefer exceptions for validation failures wrap the\n * returned `Result` with `unwrap()`.\n */\nexport function validateGraphExtension(\n input: unknown,\n options: ValidateGraphExtensionOptions = {},\n): Result<GraphExtension, GraphExtensionValidationError> {\n const issues: GraphExtensionIssue[] = [];\n const strict = options.strict === true;\n\n if (!isPlainObject(input)) {\n issues.push({\n path: \"\",\n message: \"Document must be a plain object.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return err(new GraphExtensionValidationError(issues));\n }\n\n const documentRecord = input;\n\n // Forward-compat: in non-strict (persistence-load) mode, unknown\n // top-level keys are intentionally NOT rejected. The persistence-\n // side zod schema is `.loose()` on every nested object, and the\n // documented format-versioning policy promises that additive minor\n // changes (a new top-level slice in a future v1.x.y) ride forward\n // without bumping the major. In strict (authoring) mode, unknown\n // keys surface as `UNKNOWN_DOCUMENT_KEY` so a typo like `node`\n // instead of `nodes` fails loudly instead of silently producing an\n // empty extension.\n if (strict) {\n for (const key of Object.keys(documentRecord)) {\n if (!KNOWN_DOCUMENT_KEYS.has(key)) {\n issues.push({\n path: `/${encodeJsonPointerSegment(key)}`,\n message: `Unknown top-level key \"${key}\". Did you mean one of: ${[...KNOWN_DOCUMENT_KEYS].join(\", \")}?`,\n code: \"UNKNOWN_DOCUMENT_KEY\",\n });\n }\n }\n }\n\n const version = validateVersion(documentRecord.version, issues);\n\n const nodes = validateNodesSection(documentRecord.nodes, issues, strict);\n const edges = validateEdgesSection(documentRecord.edges, issues, strict);\n\n // Edge endpoints can reference (a) kinds declared in this same document,\n // (b) compile-time host kinds resolved at merge time, or (c) external\n // IRIs. The cross-graph resolution check happens at merge time, not\n // here.\n\n const ontology = validateOntologySection(\n documentRecord.ontology,\n issues,\n strict,\n );\n if (ontology !== undefined) {\n validateOntology(ontology, nodes, issues);\n }\n\n const indexes = validateIndexesSection(\n documentRecord.indexes,\n issues,\n strict,\n );\n\n if (issues.length > 0) {\n return err(new GraphExtensionValidationError(issues));\n }\n\n return ok(freezeDocument({ version, nodes, edges, ontology, indexes }));\n}\n\n/**\n * Validates the `version` field against the current supported major.\n *\n * Absent → resolved to `LEGACY_GRAPH_EXTENSION_VERSION` (a stable\n * `1`). The serializer omits `version` from the canonical persisted\n * form when it equals the legacy default, so the on-disk shape is\n * always version-less for v1 documents — the validator's absent →\n * legacy mapping closes that round-trip. Splitting `LEGACY` from\n * `CURRENT` is forward-looking design for future major bumps: when\n * v2 ships, `CURRENT` becomes `2` but `LEGACY` stays `1`, so a v1-era\n * stored document still parses as v1.\n *\n * Equal to current → accepted. Higher major → rejected with\n * `GRAPH_EXTENSION_VERSION_UNSUPPORTED`. Non-integer / non-positive\n * → rejected with `INVALID_DOCUMENT_SHAPE`.\n */\nfunction validateVersion(\n raw: unknown,\n issues: GraphExtensionIssue[],\n): GraphExtensionVersion {\n if (raw === undefined) return LEGACY_GRAPH_EXTENSION_VERSION;\n if (typeof raw !== \"number\" || !Number.isInteger(raw) || raw < 1) {\n issues.push({\n path: \"/version\",\n message: `Document version must be a positive integer; received ${JSON.stringify(raw)}.`,\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return LEGACY_GRAPH_EXTENSION_VERSION;\n }\n if (raw > CURRENT_GRAPH_EXTENSION_VERSION) {\n // Version mismatch is unrecoverable — the rest of the document\n // may use fields the current library can't decode. Throw the\n // typed class directly rather than batching into the issue list,\n // which is reserved for per-field validation problems a UI can\n // surface alongside others.\n throw new GraphExtensionVersionUnsupportedError(\n raw,\n CURRENT_GRAPH_EXTENSION_VERSION,\n );\n }\n return raw;\n}\n\n// ============================================================\n// Section: nodes\n// ============================================================\n\nfunction validateNodesSection(\n rawNodes: unknown,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): Record<string, ExtensionNodeDef> | undefined {\n if (rawNodes === undefined) return undefined;\n\n if (!isPlainObject(rawNodes)) {\n issues.push({\n path: \"/nodes\",\n message: \"`nodes` must be a plain object keyed by node-kind name.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n\n const result: Record<string, ExtensionNodeDef> = {};\n const recorded = new Set<string>();\n\n for (const [kindName, rawNode] of Object.entries(rawNodes)) {\n const path = `/nodes/${encodeJsonPointerSegment(kindName)}`;\n\n if (!isValidKindName(kindName)) {\n issues.push({\n path,\n message: `Node kind name \"${kindName}\" must match /^[A-Za-z_][A-Za-z0-9_]*$/.`,\n code: \"INVALID_KIND_NAME\",\n });\n continue;\n }\n\n if (recorded.has(kindName)) {\n issues.push({\n path,\n message: `Duplicate node kind name \"${kindName}\".`,\n code: \"DUPLICATE_KIND_NAME\",\n });\n continue;\n }\n\n const node = validateNodeDocument(kindName, rawNode, path, issues, strict);\n if (node === undefined) continue;\n result[kindName] = node;\n recorded.add(kindName);\n }\n\n return result;\n}\n\nfunction validateNodeDocument(\n kindName: string,\n raw: unknown,\n path: string,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): ExtensionNodeDef | undefined {\n if (!isPlainObject(raw)) {\n issues.push({\n path,\n message: `Node \"${kindName}\" must be a plain object.`,\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n\n if (strict) {\n rejectUnknownObjectKeys(\n raw,\n NODE_BODY_KEYS,\n \"node-level\",\n path,\n \"INVALID_DOCUMENT_SHAPE\",\n issues,\n );\n }\n\n const description = validateOptionalString(\n raw.description,\n `${path}/description`,\n \"`description`\",\n \"INVALID_DOCUMENT_SHAPE\",\n issues,\n );\n\n const annotations = validateAnnotations(\n raw.annotations,\n `${path}/annotations`,\n `Node \"${kindName}\"`,\n issues,\n );\n\n const propertiesRaw = raw.properties;\n const properties = validatePropertiesMap(\n propertiesRaw,\n `${path}/properties`,\n \"node\",\n kindName,\n issues,\n strict,\n );\n if (properties === undefined) return undefined;\n\n const uniqueRaw = raw.unique;\n const unique = validateUniqueConstraints(\n uniqueRaw,\n `${path}/unique`,\n properties,\n issues,\n strict,\n );\n\n return compactUndefined<ExtensionNodeDef>({\n description,\n annotations,\n properties,\n unique,\n });\n}\n\n// ============================================================\n// Section: edges\n// ============================================================\n\nfunction validateEdgesSection(\n rawEdges: unknown,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): Record<string, ExtensionEdgeDef> | undefined {\n if (rawEdges === undefined) return undefined;\n\n if (!isPlainObject(rawEdges)) {\n issues.push({\n path: \"/edges\",\n message: \"`edges` must be a plain object keyed by edge-kind name.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n\n const result: Record<string, ExtensionEdgeDef> = {};\n const recorded = new Set<string>();\n\n for (const [kindName, rawEdge] of Object.entries(rawEdges)) {\n const path = `/edges/${encodeJsonPointerSegment(kindName)}`;\n\n if (!isValidKindName(kindName)) {\n issues.push({\n path,\n message: `Edge kind name \"${kindName}\" must match /^[A-Za-z_][A-Za-z0-9_]*$/.`,\n code: \"INVALID_KIND_NAME\",\n });\n continue;\n }\n\n if (recorded.has(kindName)) {\n issues.push({\n path,\n message: `Duplicate edge kind name \"${kindName}\".`,\n code: \"DUPLICATE_KIND_NAME\",\n });\n continue;\n }\n\n const edge = validateEdgeDocument(kindName, rawEdge, path, issues, strict);\n if (edge === undefined) continue;\n result[kindName] = edge;\n recorded.add(kindName);\n }\n\n return result;\n}\n\nfunction validateEdgeDocument(\n kindName: string,\n raw: unknown,\n path: string,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): ExtensionEdgeDef | undefined {\n if (!isPlainObject(raw)) {\n issues.push({\n path,\n message: `Edge \"${kindName}\" must be a plain object.`,\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n\n if (strict) {\n rejectUnknownObjectKeys(\n raw,\n EDGE_BODY_KEYS,\n \"edge-level\",\n path,\n \"INVALID_DOCUMENT_SHAPE\",\n issues,\n );\n }\n\n const description = validateOptionalString(\n raw.description,\n `${path}/description`,\n \"`description`\",\n \"INVALID_DOCUMENT_SHAPE\",\n issues,\n );\n\n const annotations = validateAnnotations(\n raw.annotations,\n `${path}/annotations`,\n `Edge \"${kindName}\"`,\n issues,\n );\n\n const from = validateEndpointList(raw.from, `${path}/from`, issues);\n const to = validateEndpointList(raw.to, `${path}/to`, issues);\n if (from === undefined || to === undefined) return undefined;\n\n const propertiesRaw = raw.properties;\n const properties =\n propertiesRaw === undefined ?\n {}\n : validatePropertiesMap(\n propertiesRaw,\n `${path}/properties`,\n \"edge\",\n kindName,\n issues,\n strict,\n );\n if (properties === undefined) return undefined;\n\n return compactUndefined<ExtensionEdgeDef>({\n description,\n annotations,\n from,\n to,\n properties,\n });\n}\n\nfunction validateEndpointList(\n raw: unknown,\n path: string,\n issues: GraphExtensionIssue[],\n): readonly string[] | undefined {\n if (!Array.isArray(raw)) {\n issues.push({\n path,\n message: \"Edge endpoint list must be an array of node-kind names.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n if (raw.length === 0) {\n issues.push({\n path,\n message: \"Edge endpoint list must contain at least one node-kind name.\",\n code: \"EMPTY_FROM_OR_TO\",\n });\n return undefined;\n }\n const names: string[] = [];\n for (const [index, value] of raw.entries()) {\n if (typeof value !== \"string\" || value.length === 0) {\n issues.push({\n path: `${path}/${index}`,\n message: \"Edge endpoint must be a non-empty string node-kind name.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n names.push(value);\n }\n return names;\n}\n\n// ============================================================\n// Section: ontology\n// ============================================================\n\nfunction validateOntologySection(\n raw: unknown,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): ExtensionOntologyRelation[] | undefined {\n if (raw === undefined) return undefined;\n if (!Array.isArray(raw)) {\n issues.push({\n path: \"/ontology\",\n message: \"`ontology` must be an array of relation objects.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n\n const result: ExtensionOntologyRelation[] = [];\n for (const [index, entry] of raw.entries()) {\n const path = `/ontology/${index}`;\n if (!isPlainObject(entry)) {\n issues.push({\n path,\n message: \"Ontology entry must be a plain object.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n continue;\n }\n if (strict) {\n rejectUnknownObjectKeys(\n entry,\n ONTOLOGY_ENTRY_KEYS,\n \"ontology-entry\",\n path,\n \"INVALID_DOCUMENT_SHAPE\",\n issues,\n );\n }\n\n const metaEdge = entry.metaEdge;\n const from = entry.from;\n const to = entry.to;\n\n if (typeof metaEdge !== \"string\" || !META_EDGE_NAME_SET.has(metaEdge)) {\n issues.push({\n path: `${path}/metaEdge`,\n message: `Unknown meta-edge ${describeUnknownValue(metaEdge)}. Allowed: ${[...ALL_META_EDGE_NAMES].join(\", \")}.`,\n code: \"UNKNOWN_META_EDGE\",\n });\n continue;\n }\n if (typeof from !== \"string\" || from.length === 0) {\n issues.push({\n path: `${path}/from`,\n message: \"Ontology relation `from` must be a non-empty string.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n continue;\n }\n if (typeof to !== \"string\" || to.length === 0) {\n issues.push({\n path: `${path}/to`,\n message: \"Ontology relation `to` must be a non-empty string.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n continue;\n }\n\n result.push({ metaEdge: metaEdge as MetaEdgeName, from, to });\n }\n return result;\n}\n\nfunction validateOntology(\n ontology: readonly ExtensionOntologyRelation[],\n _nodes: Record<string, ExtensionNodeDef> | undefined,\n issues: GraphExtensionIssue[],\n): void {\n const seenKey = new Set<string>();\n\n for (const [index, relation] of ontology.entries()) {\n const path = `/ontology/${index}`;\n\n if (\n relation.from === relation.to &&\n isStrictlyHierarchicalMetaEdge(relation.metaEdge)\n ) {\n issues.push({\n path,\n message: `Hierarchical meta-edge \"${relation.metaEdge}\" cannot be a self-loop (\"${relation.from}\" → \"${relation.to}\").`,\n code: \"ONTOLOGY_SELF_LOOP\",\n });\n }\n\n const key = `${relation.metaEdge}::${relation.from}->${relation.to}`;\n if (seenKey.has(key)) {\n issues.push({\n path,\n message: `Duplicate ontology relation \"${relation.metaEdge}\" (${relation.from} → ${relation.to}).`,\n code: \"DUPLICATE_ONTOLOGY_RELATION\",\n });\n continue;\n }\n seenKey.add(key);\n }\n\n // Cycle detection on transitive hierarchical relations declared *within*\n // this document. Cross-document cycles will be caught at evolve() time\n // when the graph extension is merged with the existing graph.\n detectHierarchicalCycles(ontology, issues);\n\n // disjointWith ↔ subClassOf contradictions: declaring two kinds as\n // both subclass-related (subClassOf, broader, narrower) AND\n // disjointWith is incoherent — a subclass instance is also an\n // instance of its parent, so they can't be in disjoint sets.\n // Detect within the document; cross-document detection happens at\n // merge time when the registry's closures are rebuilt.\n detectDisjointHierarchyContradictions(ontology, issues);\n}\n\nconst STRICTLY_HIERARCHICAL: ReadonlySet<MetaEdgeName> = new Set([\n \"subClassOf\",\n \"broader\",\n \"narrower\",\n \"partOf\",\n \"hasPart\",\n]);\n\nfunction isStrictlyHierarchicalMetaEdge(name: MetaEdgeName): boolean {\n return STRICTLY_HIERARCHICAL.has(name);\n}\n\n/**\n * Maps each hierarchical meta-edge to the canonical group it normalizes\n * into, mirroring the registry's relation-table flattening\n * (`computeClosuresFromOntology`). `narrower A→B` is the inverse of\n * `broader A→B`; `hasPart A→B` is the inverse of `partOf A→B`. Cycle\n * detection must run on the same normalized set the registry will, or\n * mixed-direction cycles like `broader A→B` + `narrower A→B` slip\n * through validation and surface only at runtime.\n */\nconst HIERARCHICAL_NORMALIZATION: ReadonlyMap<\n MetaEdgeName,\n Readonly<{ canonical: MetaEdgeName; flip: boolean }>\n> = new Map([\n [\"subClassOf\", { canonical: \"subClassOf\", flip: false }],\n [\"broader\", { canonical: \"broader\", flip: false }],\n [\"narrower\", { canonical: \"broader\", flip: true }],\n [\"partOf\", { canonical: \"partOf\", flip: false }],\n [\"hasPart\", { canonical: \"partOf\", flip: true }],\n]);\n\ntype NormalizedHierarchicalEdge = Readonly<{\n from: string;\n to: string;\n originalIndex: number;\n}>;\n\n/**\n * Group ontology relations by their canonical hierarchical meta-edge,\n * flipping `narrower` / `hasPart` entries into their canonical direction.\n * Mirrors `computeClosuresFromOntology`'s flattening so cycle and\n * disjoint-contradiction detection see the same edge set the registry\n * will. `skipSelfLoops` is set by the cycle detector (self-loops are\n * already reported by `detectOntologySelfLoops`) and unset by the\n * disjoint-contradiction detector (which still wants `(A, A)` in the\n * closure for a `disjointWith(A, A)` check).\n */\nfunction buildHierarchicalGroups(\n ontology: readonly ExtensionOntologyRelation[],\n options: Readonly<{ skipSelfLoops: boolean }>,\n): Map<MetaEdgeName, NormalizedHierarchicalEdge[]> {\n const groups = new Map<MetaEdgeName, NormalizedHierarchicalEdge[]>();\n for (const [index, relation] of ontology.entries()) {\n const normalization = HIERARCHICAL_NORMALIZATION.get(relation.metaEdge);\n if (normalization === undefined) continue;\n if (options.skipSelfLoops && relation.from === relation.to) continue;\n\n const from = normalization.flip ? relation.to : relation.from;\n const to = normalization.flip ? relation.from : relation.to;\n\n const list = groups.get(normalization.canonical) ?? [];\n list.push({ from, to, originalIndex: index });\n groups.set(normalization.canonical, list);\n }\n return groups;\n}\n\nfunction detectHierarchicalCycles(\n ontology: readonly ExtensionOntologyRelation[],\n issues: GraphExtensionIssue[],\n): void {\n const groups = buildHierarchicalGroups(ontology, { skipSelfLoops: true });\n\n for (const [name, edges] of groups) {\n const closure = computeTransitiveClosure(\n edges.map((edge) => [edge.from, edge.to] as const),\n );\n const reportedNodes = new Set<string>();\n for (const [from, reachable] of closure) {\n if (!reachable.has(from) || reportedNodes.has(from)) continue;\n reportedNodes.add(from);\n const offendingEdge = edges.find((edge) => edge.from === from);\n const path =\n offendingEdge === undefined ? \"/ontology\" : (\n `/ontology/${offendingEdge.originalIndex}`\n );\n issues.push({\n path,\n message: `Cycle detected in \"${name}\" relations involving \"${from}\".`,\n code: \"ONTOLOGY_CYCLE\",\n });\n }\n }\n}\n\n/**\n * Detects `disjointWith` ↔ subClassOf-family contradictions: declaring\n * `(A, B) disjointWith` AND `(A, B) subClassOf` (or any subclass-\n * relating meta-edge) in the same document is incoherent — a subclass\n * instance is also an instance of its parent, so they can't be in\n * disjoint sets.\n *\n * Detection runs against the closure of the hierarchical relations\n * because `(A, B) subClassOf` plus `(B, C) subClassOf` makes A and C\n * disjoint-incompatible too. `narrower` / `hasPart` are flipped to\n * their canonical direction during normalization, mirroring how\n * `detectHierarchicalCycles` builds its groups.\n *\n * Cross-document contradictions (extension declares `disjointWith(A,B)`\n * while a previously-evolved extension declared `subClassOf(A,B)`) are\n * caught at merge time when the registry's closures are rebuilt.\n */\nfunction detectDisjointHierarchyContradictions(\n ontology: readonly ExtensionOntologyRelation[],\n issues: GraphExtensionIssue[],\n): void {\n const disjointPairs = new Set<string>();\n const disjointPath = new Map<string, string>();\n for (const [index, relation] of ontology.entries()) {\n if (relation.metaEdge !== \"disjointWith\") continue;\n // disjointWith is symmetric; record both orderings so the closure\n // check below catches the contradiction regardless of which side\n // the subclass relation orders by.\n disjointPairs.add(`${relation.from}|${relation.to}`);\n disjointPairs.add(`${relation.to}|${relation.from}`);\n disjointPath.set(`${relation.from}|${relation.to}`, `/ontology/${index}`);\n disjointPath.set(`${relation.to}|${relation.from}`, `/ontology/${index}`);\n }\n if (disjointPairs.size === 0) return;\n\n // Walk the closure of every hierarchical group; any (from, reachable)\n // pair that also appears in `disjointPairs` is a contradiction.\n const groups = buildHierarchicalGroups(ontology, { skipSelfLoops: false });\n const reported = new Set<string>();\n for (const [name, edges] of groups) {\n const closure = computeTransitiveClosure(\n edges.map((edge) => [edge.from, edge.to] as const),\n );\n for (const [from, reachable] of closure) {\n for (const to of reachable) {\n const pairKey = `${from}|${to}`;\n if (!disjointPairs.has(pairKey)) continue;\n if (reported.has(pairKey)) continue;\n reported.add(pairKey);\n issues.push({\n path: disjointPath.get(pairKey) ?? \"/ontology\",\n message: `Contradiction: \"${from}\" and \"${to}\" are declared disjointWith but also related by \"${name}\" (directly or transitively).`,\n code: \"ONTOLOGY_DISJOINT_CONFLICT\",\n });\n }\n }\n }\n}\n\n// ============================================================\n// Section: indexes\n// ============================================================\n\nconst INDEX_SCOPE_VALUES = [\"graphAndKind\", \"graph\", \"none\"] as const;\nconst EDGE_INDEX_DIRECTION_VALUES = [\"out\", \"in\", \"none\"] as const;\n\nconst RUNTIME_INDEX_WHERE_OPS: ReadonlySet<string> = new Set([\n \"isNull\",\n \"isNotNull\",\n]);\n\nfunction validateIndexesSection(\n rawIndexes: unknown,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): readonly ExtensionIndex[] | undefined {\n if (rawIndexes === undefined) return undefined;\n if (!Array.isArray(rawIndexes)) {\n issues.push({\n path: \"/indexes\",\n message: \"`indexes` must be an array of index declarations.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n\n const result: ExtensionIndex[] = [];\n const seenNames = new Set<string>();\n\n for (const [arrayIndex, entry] of rawIndexes.entries()) {\n const path = `/indexes/${arrayIndex}`;\n const validated = validateIndexEntry(entry, path, issues, strict);\n if (validated === undefined) continue;\n\n if (validated.name !== undefined) {\n if (seenNames.has(validated.name)) {\n issues.push({\n path: `${path}/name`,\n message: `Duplicate index name \"${validated.name}\".`,\n code: \"DUPLICATE_INDEX_NAME\",\n });\n continue;\n }\n seenNames.add(validated.name);\n }\n result.push(validated);\n }\n\n return result;\n}\n\nfunction validateIndexEntry(\n raw: unknown,\n path: string,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): ExtensionIndex | undefined {\n if (!isPlainObject(raw)) {\n issues.push({\n path,\n message: \"Index entry must be a plain object.\",\n code: \"INVALID_INDEX_DECLARATION\",\n });\n return undefined;\n }\n\n const entity = raw.entity;\n if (entity !== \"node\" && entity !== \"edge\") {\n issues.push({\n path: `${path}/entity`,\n message: `Index \\`entity\\` must be \"node\" or \"edge\"; received ${describeUnknownValue(entity)}.`,\n code: \"INVALID_INDEX_DECLARATION\",\n });\n return undefined;\n }\n\n // Strict-authoring typo check: `coveringField` (singular), `wheres`,\n // etc. would otherwise compile to a weaker index with no signal.\n // Allowlist switches on `entity` so edge-only `direction` is valid\n // on edges but flagged on nodes.\n if (strict) {\n rejectUnknownObjectKeys(\n raw,\n entity === \"node\" ? NODE_INDEX_KEYS : EDGE_INDEX_KEYS,\n `${entity}-index`,\n path,\n \"INVALID_INDEX_DECLARATION\",\n issues,\n );\n }\n\n if (typeof raw.kind !== \"string\" || !isValidKindName(raw.kind)) {\n issues.push({\n path: `${path}/kind`,\n message:\n \"Index `kind` must be a non-empty kind name matching /^[A-Za-z_][A-Za-z0-9_]*$/.\",\n code: \"INVALID_INDEX_DECLARATION\",\n });\n return undefined;\n }\n\n const fields = validateStringList(raw.fields, `${path}/fields`, issues, {\n allowEmpty: false,\n label: \"fields\",\n emptyCode: \"EMPTY_INDEX_FIELDS\",\n });\n if (fields === undefined) return undefined;\n\n const coveringFields = validateStringList(\n raw.coveringFields,\n `${path}/coveringFields`,\n issues,\n { allowEmpty: true, label: \"coveringFields\" },\n );\n\n if (raw.unique !== undefined && typeof raw.unique !== \"boolean\") {\n issues.push({\n path: `${path}/unique`,\n message: \"Index `unique` must be a boolean.\",\n code: \"INVALID_INDEX_DECLARATION\",\n });\n return undefined;\n }\n\n let name: string | undefined;\n if (raw.name !== undefined) {\n if (typeof raw.name !== \"string\" || raw.name.length === 0) {\n issues.push({\n path: `${path}/name`,\n message: \"Index `name` must be a non-empty string.\",\n code: \"INVALID_INDEX_DECLARATION\",\n });\n return undefined;\n }\n name = raw.name;\n }\n\n const scopeResult = validateOptionalLiteral(\n raw.scope,\n INDEX_SCOPE_VALUES,\n `${path}/scope`,\n \"Index `scope`\",\n \"INVALID_INDEX_DECLARATION\",\n issues,\n );\n if (!scopeResult.ok) return undefined;\n const scope = scopeResult.value;\n\n const where = validateGraphExtensionIndexWhere(\n raw.where,\n `${path}/where`,\n issues,\n strict,\n );\n\n if (entity === \"node\") {\n return compactUndefined<ExtensionIndex>({\n entity: \"node\",\n kind: raw.kind,\n name,\n fields,\n coveringFields,\n unique: raw.unique,\n scope,\n where,\n });\n }\n\n const directionResult = validateOptionalLiteral(\n raw.direction,\n EDGE_INDEX_DIRECTION_VALUES,\n `${path}/direction`,\n \"Edge index `direction`\",\n \"INVALID_INDEX_DECLARATION\",\n issues,\n );\n if (!directionResult.ok) return undefined;\n const direction = directionResult.value;\n\n return compactUndefined<ExtensionIndex>({\n entity: \"edge\",\n kind: raw.kind,\n name,\n direction,\n fields,\n coveringFields,\n unique: raw.unique,\n scope,\n where,\n });\n}\n\nfunction validateStringList(\n raw: unknown,\n path: string,\n issues: GraphExtensionIssue[],\n options: Readonly<{\n allowEmpty: boolean;\n label: string;\n emptyCode?: GraphExtensionIssueCode;\n }>,\n): readonly string[] | undefined {\n if (raw === undefined) {\n if (options.allowEmpty) return undefined;\n issues.push({\n path,\n message: `\\`${options.label}\\` is required and must contain at least one entry.`,\n code: options.emptyCode ?? \"INVALID_INDEX_DECLARATION\",\n });\n return undefined;\n }\n if (!Array.isArray(raw)) {\n issues.push({\n path,\n message: `\\`${options.label}\\` must be an array of strings.`,\n code: \"INVALID_INDEX_DECLARATION\",\n });\n return undefined;\n }\n const seen = new Set<string>();\n const result: string[] = [];\n for (const [index, value] of raw.entries()) {\n if (typeof value !== \"string\" || value.length === 0) {\n issues.push({\n path: `${path}/${index}`,\n message: `\\`${options.label}[${index}]\\` must be a non-empty string.`,\n code: \"INVALID_INDEX_DECLARATION\",\n });\n return undefined;\n }\n if (seen.has(value)) {\n issues.push({\n path: `${path}/${index}`,\n message: `Duplicate ${options.label} entry \"${value}\".`,\n code: \"INVALID_INDEX_DECLARATION\",\n });\n return undefined;\n }\n seen.add(value);\n result.push(value);\n }\n if (!options.allowEmpty && result.length === 0) {\n issues.push({\n path,\n message: `\\`${options.label}\\` must contain at least one entry.`,\n code: options.emptyCode ?? \"INVALID_INDEX_DECLARATION\",\n });\n return undefined;\n }\n return result;\n}\n\nfunction validateGraphExtensionIndexWhere(\n raw: unknown,\n path: string,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): ExtensionIndex[\"where\"] {\n if (raw === undefined) return undefined;\n if (!isPlainObject(raw)) {\n issues.push({\n path,\n message: \"Index `where` must be a plain object.\",\n code: \"INVALID_INDEX_DECLARATION\",\n });\n return undefined;\n }\n if (strict) {\n rejectUnknownObjectKeys(\n raw,\n WHERE_CLAUSE_KEYS,\n \"where-clause\",\n path,\n \"INVALID_INDEX_DECLARATION\",\n issues,\n );\n }\n if (typeof raw.field !== \"string\" || raw.field.length === 0) {\n issues.push({\n path: `${path}/field`,\n message: \"`where.field` must be a non-empty string.\",\n code: \"INVALID_INDEX_DECLARATION\",\n });\n return undefined;\n }\n if (typeof raw.op !== \"string\" || !RUNTIME_INDEX_WHERE_OPS.has(raw.op)) {\n issues.push({\n path: `${path}/op`,\n message: '`where.op` must be \"isNull\" or \"isNotNull\" in v1.',\n code: \"INVALID_INDEX_DECLARATION\",\n });\n return undefined;\n }\n return Object.freeze({\n field: raw.field,\n op: raw.op as NullCheckOp,\n });\n}\n\n// ============================================================\n// Properties and refinements\n// ============================================================\n\nfunction validatePropertiesMap(\n raw: unknown,\n path: string,\n ownerType: KindEntity,\n ownerName: string,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): Record<string, ExtensionPropertyType> | undefined {\n if (!isPlainObject(raw)) {\n issues.push({\n path,\n message: `\\`properties\\` must be a plain object.`,\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n\n const reserved =\n ownerType === \"node\" ? RESERVED_NODE_KEYS : RESERVED_EDGE_KEYS;\n const result: Record<string, ExtensionPropertyType> = {};\n for (const [propertyName, propertyValue] of Object.entries(raw)) {\n const propertyPath = `${path}/${encodeJsonPointerSegment(propertyName)}`;\n if (reserved.has(propertyName)) {\n issues.push({\n path: propertyPath,\n message: `Property name \"${propertyName}\" is reserved for ${ownerType} \"${ownerName}\".`,\n code: \"RESERVED_PROPERTY_NAME\",\n });\n continue;\n }\n if (propertyName.startsWith(\"$\")) {\n issues.push({\n path: propertyPath,\n message: `Property name \"${propertyName}\" uses the reserved \"$\" prefix.`,\n code: \"RESERVED_PROPERTY_NAME\",\n });\n continue;\n }\n const validated = validateProperty(\n propertyValue,\n propertyPath,\n 0,\n issues,\n strict,\n );\n if (validated === undefined) continue;\n result[propertyName] = validated;\n }\n\n return result;\n}\n\nfunction validateProperty(\n raw: unknown,\n path: string,\n depth: number,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): ExtensionPropertyType | undefined {\n if (!isPlainObject(raw)) {\n issues.push({\n path,\n message:\n \"Property descriptor must be a plain object with a `type` field.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n const property = raw;\n const type = property.type;\n if (typeof type !== \"string\" || !SUPPORTED_PROPERTY_TYPES.has(type)) {\n issues.push({\n path: `${path}/type`,\n message: `Unsupported property type ${describeUnknownValue(type)}. Supported: ${[...SUPPORTED_PROPERTY_TYPES].join(\", \")}.`,\n code: \"UNSUPPORTED_PROPERTY_TYPE\",\n });\n return undefined;\n }\n\n // Strict authoring mode: reject unknown sibling keys against the\n // per-type allowlist BEFORE dispatch. A typo like `minLenght` on a\n // string property would otherwise compile to a `z.string()` with no\n // length constraint and ship through to ingest. Persistence-load\n // mode skips this so a future v1.x.y writer's additive keys ride\n // forward.\n if (strict) rejectUnknownPropertyKeys(property, type, path, issues);\n\n switch (type) {\n case \"string\": {\n return validateStringProperty(property, path, issues, strict);\n }\n case \"number\": {\n return validateNumberProperty(property, path, issues);\n }\n case \"boolean\": {\n return validateBooleanProperty(property, path, issues);\n }\n case \"enum\": {\n return validateEnumProperty(property, path, issues);\n }\n case \"array\": {\n return validateArrayProperty(property, path, depth, issues, strict);\n }\n case \"object\": {\n return validateObjectProperty(property, path, depth, issues, strict);\n }\n }\n return undefined;\n}\n\nfunction validateStringProperty(\n raw: Record<string, unknown>,\n path: string,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): ExtensionStringProperty | undefined {\n const minLength = validateNonNegativeInteger(\n raw.minLength,\n `${path}/minLength`,\n \"string.minLength\",\n \"INVALID_LENGTH_BOUNDS\",\n issues,\n );\n const maxLength = validateNonNegativeInteger(\n raw.maxLength,\n `${path}/maxLength`,\n \"string.maxLength\",\n \"INVALID_LENGTH_BOUNDS\",\n issues,\n );\n if (\n minLength !== undefined &&\n maxLength !== undefined &&\n minLength > maxLength\n ) {\n issues.push({\n path,\n message: `string.minLength (${minLength}) cannot exceed string.maxLength (${maxLength}).`,\n code: \"INVALID_LENGTH_BOUNDS\",\n });\n }\n\n let pattern: string | undefined;\n if (raw.pattern !== undefined) {\n if (typeof raw.pattern === \"string\") {\n try {\n new RegExp(raw.pattern);\n pattern = raw.pattern;\n } catch (error) {\n issues.push({\n path: `${path}/pattern`,\n message: `Pattern is not a valid regular expression: ${\n error instanceof Error ? error.message : String(error)\n }`,\n code: \"INVALID_PATTERN\",\n });\n }\n } else {\n issues.push({\n path: `${path}/pattern`,\n message: \"`pattern` must be a string regular expression.\",\n code: \"INVALID_PATTERN\",\n });\n }\n }\n\n let format: ExtensionStringProperty[\"format\"];\n if (raw.format !== undefined) {\n if (typeof raw.format !== \"string\") {\n issues.push({\n path: `${path}/format`,\n message: `String format must be a string; received ${describeUnknownValue(raw.format)}.`,\n code: \"INVALID_PROPERTY_REFINEMENT\",\n });\n } else if (SUPPORTED_STRING_FORMATS.has(raw.format)) {\n format = raw.format as ExtensionStringProperty[\"format\"];\n } else if (strict) {\n // Authoring-mode reject. A typo like `\"date-time\"` (no\n // hyphen) silently compiled to a plain `z.string()` in earlier\n // versions, so `safeParse(\"not-a-date\")` succeeded — surfacing\n // the typo here is the contract.\n issues.push({\n path: `${path}/format`,\n message: `Unsupported string format \"${raw.format}\". Supported: ${[...SUPPORTED_STRING_FORMATS].join(\", \")}.`,\n code: \"UNSUPPORTED_STRING_FORMAT\",\n });\n }\n // Non-strict (persistence-load) path: unknown format silently\n // drops to a plain `z.string()`. A future v1.x.y writer may\n // introduce a new format identifier; an older v1 reader still\n // parses the document, just without the new format's behaviour.\n }\n\n const modifiers = validatePropertyModifiers(raw, path, \"string\", issues);\n if (modifiers === undefined) return undefined;\n\n if (format !== undefined && modifiers.searchable !== undefined) {\n issues.push({\n path,\n message:\n \"`searchable` cannot be combined with `format` on a string property — the format-specific schema cannot carry the searchable brand. Drop one, or split into two fields.\",\n code: \"INVALID_PROPERTY_REFINEMENT\",\n });\n return undefined;\n }\n\n if (\n format !== undefined &&\n (minLength !== undefined ||\n maxLength !== undefined ||\n pattern !== undefined)\n ) {\n issues.push({\n path,\n message:\n \"`format` cannot be combined with `minLength`, `maxLength`, or `pattern` on a string property — the format-routed schema (`z.iso.datetime` / `z.url`) is not a `z.ZodString` and cannot carry length or pattern refinements. Drop the refinement, or drop the format and validate the shape with `pattern`.\",\n code: \"INVALID_PROPERTY_REFINEMENT\",\n });\n return undefined;\n }\n\n return finalizeProperty<ExtensionStringProperty>(\n \"string\",\n { minLength, maxLength, pattern, format },\n modifiers,\n );\n}\n\nfunction validateNumberProperty(\n raw: Record<string, unknown>,\n path: string,\n issues: GraphExtensionIssue[],\n): ExtensionNumberProperty | undefined {\n // Forward-compat: unknown refinement keys are silently accepted.\n const min = validateOptionalFiniteNumber(\n raw.min,\n `${path}/min`,\n \"`min`\",\n \"INVALID_NUMBER_BOUNDS\",\n issues,\n );\n const max = validateOptionalFiniteNumber(\n raw.max,\n `${path}/max`,\n \"`max`\",\n \"INVALID_NUMBER_BOUNDS\",\n issues,\n );\n if (min !== undefined && max !== undefined && min > max) {\n issues.push({\n path,\n message: `number.min (${min}) cannot exceed number.max (${max}).`,\n code: \"INVALID_NUMBER_BOUNDS\",\n });\n }\n\n const int = validateOptionalBoolean(\n raw.int,\n `${path}/int`,\n \"`int`\",\n \"INVALID_PROPERTY_REFINEMENT\",\n issues,\n );\n\n // Integer + non-integer bounds: reject early so the compiled Zod schema\n // doesn't silently swallow values like `min: 1.5, int: true`.\n if (int === true) {\n if (min !== undefined && !Number.isInteger(min)) {\n issues.push({\n path: `${path}/min`,\n message: \"`min` must be an integer when `int: true`.\",\n code: \"INVALID_NUMBER_BOUNDS\",\n });\n }\n if (max !== undefined && !Number.isInteger(max)) {\n issues.push({\n path: `${path}/max`,\n message: \"`max` must be an integer when `int: true`.\",\n code: \"INVALID_NUMBER_BOUNDS\",\n });\n }\n }\n\n const modifiers = validatePropertyModifiers(raw, path, \"number\", issues);\n if (modifiers === undefined) return undefined;\n\n return finalizeProperty<ExtensionNumberProperty>(\n \"number\",\n { min, max, int },\n modifiers,\n );\n}\n\nfunction validateBooleanProperty(\n raw: Record<string, unknown>,\n path: string,\n issues: GraphExtensionIssue[],\n): ExtensionBooleanProperty | undefined {\n const modifiers = validatePropertyModifiers(raw, path, \"boolean\", issues);\n if (modifiers === undefined) return undefined;\n return finalizeProperty<ExtensionBooleanProperty>(\"boolean\", {}, modifiers);\n}\n\nfunction validateEnumProperty(\n raw: Record<string, unknown>,\n path: string,\n issues: GraphExtensionIssue[],\n): ExtensionEnumProperty | undefined {\n // Forward-compat: unknown refinement keys are silently accepted.\n const valuesRaw = raw.values;\n if (!Array.isArray(valuesRaw) || valuesRaw.length === 0) {\n issues.push({\n path: `${path}/values`,\n message: \"`enum.values` must be a non-empty array of strings.\",\n code: \"INVALID_ENUM_VALUES\",\n });\n return undefined;\n }\n\n const values: string[] = [];\n const seen = new Set<string>();\n for (const [index, value] of valuesRaw.entries()) {\n if (typeof value !== \"string\") {\n issues.push({\n path: `${path}/values/${index}`,\n message: \"`enum.values` entries must be strings.\",\n code: \"INVALID_ENUM_VALUES\",\n });\n return undefined;\n }\n if (seen.has(value)) {\n issues.push({\n path: `${path}/values/${index}`,\n message: `Duplicate enum value \"${value}\".`,\n code: \"INVALID_ENUM_VALUES\",\n });\n return undefined;\n }\n seen.add(value);\n values.push(value);\n }\n\n const modifiers = validatePropertyModifiers(raw, path, \"enum\", issues);\n if (modifiers === undefined) return undefined;\n\n return finalizeProperty<ExtensionEnumProperty>(\"enum\", { values }, modifiers);\n}\n\nfunction validateArrayProperty(\n raw: Record<string, unknown>,\n path: string,\n depth: number,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): ExtensionArrayProperty | undefined {\n // Forward-compat: unknown refinement keys are silently accepted.\n const itemsRaw = raw.items;\n if (itemsRaw === undefined) {\n issues.push({\n path: `${path}/items`,\n message: \"`array.items` is required.\",\n code: \"INVALID_PROPERTY_REFINEMENT\",\n });\n return undefined;\n }\n if (!isPlainObject(itemsRaw)) {\n issues.push({\n path: `${path}/items`,\n message: \"`array.items` must be a plain property descriptor.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n const itemType = itemsRaw.type;\n if (itemType === \"array\") {\n issues.push({\n path: `${path}/items`,\n message: \"Nested arrays are not supported in v1.\",\n code: \"NESTED_ARRAY\",\n });\n return undefined;\n }\n const items = validateProperty(\n itemsRaw,\n `${path}/items`,\n depth + 1,\n issues,\n strict,\n );\n if (items === undefined) return undefined;\n if (items.type === \"array\") {\n // Type-narrow only: `validateProperty` returns the wider\n // `ExtensionPropertyType`, but `ExtensionArrayItemType` excludes\n // nested arrays. The earlier `itemType === \"array\"` check above\n // already rejected this at the raw-shape level, so this branch\n // is unreachable at runtime.\n return undefined;\n }\n\n const modifiers = validatePropertyModifiers(raw, path, \"array\", issues);\n if (modifiers === undefined) return undefined;\n\n return finalizeProperty<ExtensionArrayProperty>(\n \"array\",\n { items },\n modifiers,\n );\n}\n\nfunction validateObjectProperty(\n raw: Record<string, unknown>,\n path: string,\n depth: number,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): ExtensionObjectProperty | undefined {\n // Forward-compat: unknown refinement keys are silently accepted.\n if (depth >= 1) {\n issues.push({\n path,\n message: \"Nested objects are limited to a single level in v1.\",\n code: \"NESTED_OBJECT_TOO_DEEP\",\n });\n return undefined;\n }\n\n const propertiesRaw = raw.properties;\n if (!isPlainObject(propertiesRaw)) {\n issues.push({\n path: `${path}/properties`,\n message: \"`object.properties` must be a plain object.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n\n const propertiesEntries = Object.entries(propertiesRaw);\n if (propertiesEntries.length === 0) {\n issues.push({\n path: `${path}/properties`,\n message: \"`object.properties` must declare at least one field.\",\n code: \"EMPTY_PROPERTIES\",\n });\n return undefined;\n }\n\n const fields: Record<string, ExtensionObjectFieldProperty> = {};\n for (const [name, value] of propertiesEntries) {\n const fieldPath = `${path}/properties/${encodeJsonPointerSegment(name)}`;\n if (!isPlainObject(value)) {\n issues.push({\n path: fieldPath,\n message: \"Object field descriptor must be a plain object.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n continue;\n }\n const fieldType = value.type;\n if (fieldType === \"object\") {\n issues.push({\n path: fieldPath,\n message: \"Nested objects are limited to a single level in v1.\",\n code: \"NESTED_OBJECT_TOO_DEEP\",\n });\n continue;\n }\n const field = validateProperty(value, fieldPath, depth + 1, issues, strict);\n if (field === undefined) continue;\n fields[name] = field as ExtensionObjectFieldProperty;\n }\n\n const modifiers = validatePropertyModifiers(raw, path, \"object\", issues);\n if (modifiers === undefined) return undefined;\n\n return finalizeProperty<ExtensionObjectProperty>(\n \"object\",\n { properties: fields },\n modifiers,\n );\n}\n\n// ============================================================\n// Modifiers\n// ============================================================\n\ntype NormalizedModifiers = Readonly<{\n optional?: boolean;\n searchable?: { language?: string };\n embedding?: { dimensions: number };\n description?: string;\n}>;\n\n/**\n * Assemble a final property descriptor from a type-specific field map\n * plus the already-validated modifiers. Centralizes the modifier-spread\n * boilerplate so adding a new modifier slot (or tweaking how undefineds\n * are pruned) touches one site instead of six.\n *\n * Callers run `validatePropertyModifiers` first because some types\n * (`string`) need cross-modifier validation (e.g. `format` ↔ `searchable`)\n * after the modifiers are known but before the final shape is built.\n */\nfunction finalizeProperty<T extends ExtensionPropertyType>(\n type: T[\"type\"],\n specific: Record<string, unknown>,\n modifiers: NormalizedModifiers,\n): T {\n return compactUndefined<Record<string, unknown>>({\n type,\n ...specific,\n optional: modifiers.optional,\n searchable: modifiers.searchable,\n embedding: modifiers.embedding,\n description: modifiers.description,\n }) as T;\n}\n\nfunction validatePropertyModifiers(\n raw: Record<string, unknown>,\n path: string,\n propertyType: ExtensionPropertyType[\"type\"],\n issues: GraphExtensionIssue[],\n): NormalizedModifiers | undefined {\n // Mirrors `issues.length` rather than carrying its own boolean: any\n // helper that pushes also signals failure here.\n const issuesAtEntry = issues.length;\n\n const optional = validateOptionalBoolean(\n raw.optional,\n `${path}/optional`,\n \"`optional`\",\n \"INVALID_PROPERTY_REFINEMENT\",\n issues,\n );\n\n let searchable: { language?: string } | undefined;\n if (raw.searchable !== undefined) {\n if (propertyType !== \"string\") {\n issues.push({\n path: `${path}/searchable`,\n message: `\\`searchable\\` is only valid on string properties (got \"${propertyType}\").`,\n code: \"INVALID_MODIFIER_TARGET\",\n });\n } else if (isPlainObject(raw.searchable)) {\n const searchableRaw = raw.searchable;\n const language = searchableRaw.language;\n if (language === undefined) {\n searchable = {};\n } else {\n if (typeof language !== \"string\" || language.length === 0) {\n issues.push({\n path: `${path}/searchable/language`,\n message: \"`searchable.language` must be a non-empty string.\",\n code: \"INVALID_SEARCHABLE_LANGUAGE\",\n });\n } else {\n searchable = { language };\n }\n }\n } else {\n issues.push({\n path: `${path}/searchable`,\n message: \"`searchable` must be a plain object (use `{}` for defaults).\",\n code: \"INVALID_PROPERTY_REFINEMENT\",\n });\n }\n }\n\n let embedding: { dimensions: number } | undefined;\n if (raw.embedding !== undefined) {\n if (propertyType === \"array\") {\n const itemsRaw = raw.items;\n const itemType = isPlainObject(itemsRaw) ? itemsRaw.type : undefined;\n if (itemType !== \"number\") {\n issues.push({\n path: `${path}/embedding`,\n message: '`embedding` requires `array.items.type === \"number\"`.',\n code: \"INVALID_MODIFIER_TARGET\",\n });\n } else if (isPlainObject(raw.embedding)) {\n const dim = raw.embedding.dimensions;\n if (typeof dim !== \"number\" || !Number.isInteger(dim) || dim <= 0) {\n issues.push({\n path: `${path}/embedding/dimensions`,\n message: \"`embedding.dimensions` must be a positive integer.\",\n code: \"INVALID_EMBEDDING_DIMENSIONS\",\n });\n } else {\n // `embedding(dimensions)` replaces the array's item validator with a\n // length+finite-number check; any extra refinements on the items\n // (min, max, int) would silently disappear at compile time.\n const itemsObject = isPlainObject(itemsRaw) ? itemsRaw : {};\n const extraneous = Object.keys(itemsObject).filter(\n (key) => key !== \"type\",\n );\n if (extraneous.length > 0) {\n issues.push({\n path: `${path}/items`,\n message: `\\`embedding\\` arrays must declare items as \\`{ type: \"number\" }\\` only — additional refinements (${extraneous.join(\", \")}) are silently dropped by the embedding schema. Drop the refinements, or drop \\`embedding\\` and use a plain array.`,\n code: \"INVALID_PROPERTY_REFINEMENT\",\n });\n } else {\n embedding = { dimensions: dim };\n }\n }\n } else {\n issues.push({\n path: `${path}/embedding`,\n message:\n \"`embedding` must be a plain object with a `dimensions` field.\",\n code: \"INVALID_PROPERTY_REFINEMENT\",\n });\n }\n } else {\n issues.push({\n path: `${path}/embedding`,\n message: `\\`embedding\\` is only valid on array-of-number properties (got \"${propertyType}\").`,\n code: \"INVALID_MODIFIER_TARGET\",\n });\n }\n }\n\n let description: string | undefined;\n if (raw.description !== undefined) {\n if (typeof raw.description === \"string\") {\n description = raw.description;\n } else {\n issues.push({\n path: `${path}/description`,\n message: \"`description` must be a string.\",\n code: \"INVALID_PROPERTY_REFINEMENT\",\n });\n }\n }\n\n if (issues.length > issuesAtEntry) return undefined;\n return compactUndefined<NormalizedModifiers>({\n optional,\n searchable,\n embedding,\n description,\n });\n}\n\n// ============================================================\n// Unique constraints\n// ============================================================\n\nfunction validateUniqueConstraints(\n raw: unknown,\n path: string,\n properties: Record<string, ExtensionPropertyType>,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): readonly ExtensionUniqueConstraint[] | undefined {\n if (raw === undefined) return undefined;\n if (!Array.isArray(raw)) {\n issues.push({\n path,\n message: \"`unique` must be an array of constraint declarations.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n\n const result: ExtensionUniqueConstraint[] = [];\n const names = new Set<string>();\n for (const [index, entry] of raw.entries()) {\n const constraintPath = `${path}/${index}`;\n if (!isPlainObject(entry)) {\n issues.push({\n path: constraintPath,\n message: \"Unique constraint must be a plain object.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n continue;\n }\n\n if (strict) {\n rejectUnknownObjectKeys(\n entry,\n UNIQUE_CONSTRAINT_KEYS,\n \"unique-constraint\",\n constraintPath,\n \"INVALID_DOCUMENT_SHAPE\",\n issues,\n );\n }\n\n const constraint = entry;\n const name = constraint.name;\n if (typeof name !== \"string\" || name.length === 0) {\n issues.push({\n path: `${constraintPath}/name`,\n message: \"Unique constraint `name` must be a non-empty string.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n continue;\n }\n if (names.has(name)) {\n issues.push({\n path: `${constraintPath}/name`,\n message: `Duplicate unique constraint name \"${name}\".`,\n code: \"DUPLICATE_UNIQUE_CONSTRAINT\",\n });\n continue;\n }\n names.add(name);\n\n const fieldsRaw = constraint.fields;\n if (!Array.isArray(fieldsRaw) || fieldsRaw.length === 0) {\n issues.push({\n path: `${constraintPath}/fields`,\n message:\n \"Unique constraint `fields` must be a non-empty array of property names.\",\n code: \"EMPTY_UNIQUE_FIELDS\",\n });\n continue;\n }\n\n const fields: string[] = [];\n const seenFields = new Set<string>();\n let fieldsValid = true;\n for (const [fieldIndex, field] of fieldsRaw.entries()) {\n if (typeof field !== \"string\" || field.length === 0) {\n issues.push({\n path: `${constraintPath}/fields/${fieldIndex}`,\n message: \"Unique constraint field must be a non-empty string.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n fieldsValid = false;\n break;\n }\n if (seenFields.has(field)) {\n issues.push({\n path: `${constraintPath}/fields/${fieldIndex}`,\n message: `Duplicate field \"${field}\" in unique constraint.`,\n code: \"DUPLICATE_UNIQUE_FIELD\",\n });\n fieldsValid = false;\n break;\n }\n if (!(field in properties)) {\n issues.push({\n path: `${constraintPath}/fields/${fieldIndex}`,\n message: `Unique constraint field \"${field}\" is not declared on this kind.`,\n code: \"UNKNOWN_UNIQUE_FIELD\",\n });\n fieldsValid = false;\n break;\n }\n seenFields.add(field);\n fields.push(field);\n }\n if (!fieldsValid) continue;\n\n const scopeResult = validateOptionalLiteral(\n constraint.scope,\n [\"kind\", \"kindWithSubClasses\"] as const,\n `${constraintPath}/scope`,\n \"Unique constraint `scope`\",\n \"INVALID_DOCUMENT_SHAPE\",\n issues,\n );\n if (!scopeResult.ok) continue;\n const scope = scopeResult.value;\n\n const collationResult = validateOptionalLiteral(\n constraint.collation,\n [\"binary\", \"caseInsensitive\"] as const,\n `${constraintPath}/collation`,\n \"Unique constraint `collation`\",\n \"INVALID_DOCUMENT_SHAPE\",\n issues,\n );\n if (!collationResult.ok) continue;\n const collation = collationResult.value;\n\n const where: { field: string; op: NullCheckOp } | undefined =\n constraint.where === undefined ?\n undefined\n : validateUniqueWhere(\n constraint.where,\n `${constraintPath}/where`,\n properties,\n issues,\n strict,\n );\n if (constraint.where !== undefined && where === undefined) continue;\n\n result.push(\n compactUndefined<ExtensionUniqueConstraint>({\n name,\n fields,\n scope,\n collation,\n where,\n }),\n );\n }\n\n return result;\n}\n\nfunction validateUniqueWhere(\n raw: unknown,\n path: string,\n properties: Record<string, ExtensionPropertyType>,\n issues: GraphExtensionIssue[],\n strict: boolean,\n): { field: string; op: NullCheckOp } | undefined {\n if (!isPlainObject(raw)) {\n issues.push({\n path,\n message: \"Unique constraint `where` must be `{ field, op }`.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n if (strict) {\n rejectUnknownObjectKeys(\n raw,\n WHERE_CLAUSE_KEYS,\n \"where-clause\",\n path,\n \"INVALID_DOCUMENT_SHAPE\",\n issues,\n );\n }\n const field = raw.field;\n const op = raw.op;\n if (typeof field !== \"string\" || field.length === 0) {\n issues.push({\n path: `${path}/field`,\n message: \"Unique `where.field` must be a non-empty string.\",\n code: \"INVALID_DOCUMENT_SHAPE\",\n });\n return undefined;\n }\n if (!(field in properties)) {\n issues.push({\n path: `${path}/field`,\n message: `Unique \\`where.field\\` \"${field}\" is not declared on this kind.`,\n code: \"UNKNOWN_UNIQUE_WHERE_FIELD\",\n });\n return undefined;\n }\n if (op !== \"isNull\" && op !== \"isNotNull\") {\n issues.push({\n path: `${path}/op`,\n message: `Unique \\`where.op\\` must be \"isNull\" or \"isNotNull\" (got ${describeUnknownValue(op)}).`,\n code: \"INVALID_UNIQUE_WHERE_OP\",\n });\n return undefined;\n }\n return { field, op };\n}\n\n// ============================================================\n// Annotations\n// ============================================================\n\nfunction validateAnnotations(\n raw: unknown,\n path: string,\n ownerLabel: string,\n issues: GraphExtensionIssue[],\n): KindAnnotations | undefined {\n if (raw === undefined) return undefined;\n if (!isPlainObject(raw)) {\n issues.push({\n path,\n message: `Annotations must be a plain JSON object.`,\n code: \"INVALID_ANNOTATION\",\n });\n return undefined;\n }\n\n try {\n assertJsonValue(raw, \"annotations\", ownerLabel);\n } catch (error) {\n if (error instanceof ConfigurationError) {\n const detailPath = (error.details as Record<string, unknown>).path;\n const annotationPath =\n typeof detailPath === \"string\" ?\n `${path}/${detailPath\n .replace(/^annotations\\.?/, \"\")\n .replaceAll(\".\", \"/\")}`\n : path;\n issues.push({\n path: annotationPath,\n message: error.message,\n code: \"INVALID_ANNOTATION\",\n });\n return undefined;\n }\n throw error;\n }\n\n return raw as KindAnnotations;\n}\n\n// ============================================================\n// Helpers\n// ============================================================\n\n// Two-mode unknown-key handling — see `rejectUnknownPropertyKeys`\n// above. Strict authoring (`defineGraphExtension`,\n// `validateGraphExtension(_, { strict: true })`) rejects unknown\n// sibling keys at every property level so a `minLenght`-style typo\n// from an LLM proposal surfaces with a JSON-pointer path instead of\n// silently compiling to a weaker schema. Persistence load\n// (`validateGraphExtension(_, { strict: false })`, used by the\n// `createStoreWithSchema` reader) ignores unknown keys so a future\n// v1.x.y writer with additive refinements still parses on an older\n// v1 reader — the older compiler builds the Zod schema from the\n// refinements it recognizes, and the new modifier's behavior simply\n// isn't applied. `ExtensionPropertyType` is exported so consumers\n// writing runtime-shape generators can add their own strict-key check\n// if needed for additional validation slots beyond what this\n// validator covers.\n\nfunction validateNonNegativeInteger(\n value: unknown,\n path: string,\n label: string,\n code: GraphExtensionIssueCode,\n issues: GraphExtensionIssue[],\n): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n issues.push({\n path,\n message: `${label} must be a non-negative integer.`,\n code,\n });\n return undefined;\n }\n return value;\n}\n\nfunction validateOptionalString(\n value: unknown,\n path: string,\n label: string,\n code: GraphExtensionIssueCode,\n issues: GraphExtensionIssue[],\n): string | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"string\") {\n issues.push({ path, message: `${label} must be a string.`, code });\n return undefined;\n }\n return value;\n}\n\nfunction validateOptionalBoolean(\n value: unknown,\n path: string,\n label: string,\n code: GraphExtensionIssueCode,\n issues: GraphExtensionIssue[],\n): boolean | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"boolean\") {\n issues.push({ path, message: `${label} must be a boolean.`, code });\n return undefined;\n }\n return value;\n}\n\nfunction validateOptionalFiniteNumber(\n value: unknown,\n path: string,\n label: string,\n code: GraphExtensionIssueCode,\n issues: GraphExtensionIssue[],\n): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n issues.push({ path, message: `${label} must be a finite number.`, code });\n return undefined;\n }\n return value;\n}\n\n/**\n * Discriminated result for optional-literal validation: callers branch\n * on `ok` so \"absent\" (`{ ok: true, value: undefined }`) is distinct from\n * \"invalid\" (`{ ok: false }`). Replaces the prior issue-counter trick\n * (`const before = issues.length; … if (issues.length > before) …`)\n * which conflated those two outcomes when the underlying helper\n * returned `T | undefined`.\n */\ntype OptionalLiteralResult<T> =\n | Readonly<{ ok: true; value: T | undefined }>\n | Readonly<{ ok: false }>;\n\nfunction validateOptionalLiteral<T extends string>(\n value: unknown,\n allowed: readonly T[],\n path: string,\n label: string,\n code: GraphExtensionIssueCode,\n issues: GraphExtensionIssue[],\n): OptionalLiteralResult<T> {\n if (value === undefined) return { ok: true, value: undefined };\n if (typeof value !== \"string\" || !allowed.includes(value as T)) {\n const list = allowed.map((entry) => `\"${entry}\"`).join(\", \");\n issues.push({ path, message: `${label} must be one of: ${list}.`, code });\n return { ok: false };\n }\n return { ok: true, value: value as T };\n}\n\nfunction isValidKindName(name: string): boolean {\n return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name);\n}\n\n/**\n * Renders an unknown value for inclusion in an error message without\n * tripping `[object Object]` from a generic `String()` call. Strings\n * are quoted; numbers, booleans, and null pass through; other values\n * use `JSON.stringify` and fall back to `typeof` if that fails.\n */\nfunction describeUnknownValue(value: unknown): string {\n if (typeof value === \"string\") return `\"${value}\"`;\n if (\n value === null ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return JSON.stringify(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return `(${typeof value})`;\n }\n}\n\n// ============================================================\n// Freezing\n// ============================================================\n\nfunction freezeDocument(input: {\n version: GraphExtensionVersion;\n nodes: Record<string, ExtensionNodeDef> | undefined;\n edges: Record<string, ExtensionEdgeDef> | undefined;\n ontology: readonly ExtensionOntologyRelation[] | undefined;\n indexes: readonly ExtensionIndex[] | undefined;\n}): GraphExtension {\n return Object.freeze(\n compactUndefined<{\n version: GraphExtensionVersion;\n nodes?: Record<string, ExtensionNodeDef>;\n edges?: Record<string, ExtensionEdgeDef>;\n ontology?: readonly ExtensionOntologyRelation[];\n indexes?: readonly ExtensionIndex[];\n }>({\n version: input.version,\n nodes: input.nodes === undefined ? undefined : freezeDeep(input.nodes),\n edges: input.edges === undefined ? undefined : freezeDeep(input.edges),\n ontology:\n input.ontology === undefined ?\n undefined\n : Object.freeze(\n input.ontology.map((entry) => Object.freeze({ ...entry })),\n ),\n indexes:\n input.indexes === undefined ?\n undefined\n : Object.freeze(input.indexes.map((entry) => freezeDeep({ ...entry }))),\n }),\n );\n}\n"]}
|
|
@@ -48,5 +48,5 @@ exports.POSTGRES_CAPABILITIES = POSTGRES_CAPABILITIES;
|
|
|
48
48
|
exports.SQLITE_CAPABILITIES = SQLITE_CAPABILITIES;
|
|
49
49
|
exports.runOptionallyInTransaction = runOptionallyInTransaction;
|
|
50
50
|
exports.wrapWithManagedClose = wrapWithManagedClose;
|
|
51
|
-
//# sourceMappingURL=chunk-
|
|
52
|
-
//# sourceMappingURL=chunk-
|
|
51
|
+
//# sourceMappingURL=chunk-7CDXX3QZ.cjs.map
|
|
52
|
+
//# sourceMappingURL=chunk-7CDXX3QZ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/backend/types.ts"],"names":[],"mappings":";;;AA48BO,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,KAAA,EAAO,KAAA;AAAA;AAAA,EACP,cAAA,EAAgB,IAAA;AAAA;AAAA,EAChB,UAAA,EAAY,KAAA;AAAA;AAAA,EACZ,GAAA,EAAK,IAAA;AAAA;AAAA,EACL,SAAA,EAAW,IAAA;AAAA;AAAA,EACX,YAAA,EAAc;AAAA;AAChB;AAKO,IAAM,qBAAA,GAA6C;AAAA,EACxD,KAAA,EAAO,IAAA;AAAA;AAAA,EACP,cAAA,EAAgB,IAAA;AAAA,EAChB,UAAA,EAAY,IAAA;AAAA,EACZ,GAAA,EAAK,IAAA;AAAA,EACL,SAAA,EAAW,IAAA;AAAA,EACX,YAAA,EAAc;AAAA;AAChB","file":"chunk-7CDXX3QZ.cjs","sourcesContent":["/**\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 SerializedSchema } from \"../schema/types\";\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 JSONB type (vs TEXT for JSON) */\n jsonb: boolean;\n /** Whether the backend supports partial indexes */\n partialIndexes: boolean;\n /** Whether the backend supports GIN indexes for JSON */\n ginIndexes: boolean;\n /** Whether the backend supports CTE (WITH) queries */\n cte: boolean;\n /** Whether the backend supports RETURNING clause */\n returning: boolean;\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 * A row from the typegraph_node_embeddings table.\n */\nexport type EmbeddingRow = Readonly<{\n graph_id: string;\n node_kind: string;\n node_id: string;\n field_path: string;\n embedding: readonly number[];\n dimensions: number;\n created_at: string;\n updated_at: string;\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 */\nexport type UpsertEmbeddingParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n embedding: readonly number[];\n dimensions: number;\n}>;\n\n/**\n * Parameters for deleting an embedding.\n */\nexport type DeleteEmbeddingParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\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 limit: number;\n minScore?: 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// 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// 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 | \"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 // === 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 getEmbedding?: (\n graphId: string,\n nodeKind: string,\n nodeId: string,\n fieldPath: string,\n ) => Promise<EmbeddingRow | undefined>;\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 // === 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 /**\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 transaction: <T>(\n fn: (tx: TransactionBackend) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<T>;\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 jsonb: false, // SQLite uses TEXT with json functions\n partialIndexes: true, // SQLite supports WHERE in CREATE INDEX\n ginIndexes: false, // SQLite doesn't have GIN\n cte: true, // SQLite supports WITH\n returning: true, // SQLite 3.35+ supports RETURNING\n transactions: true, // SQLite supports transactions\n};\n\n/**\n * Default capabilities for PostgreSQL.\n */\nexport const POSTGRES_CAPABILITIES: BackendCapabilities = {\n jsonb: true, // PostgreSQL has native JSONB\n partialIndexes: true,\n ginIndexes: true,\n cte: true,\n returning: true,\n transactions: true, // PostgreSQL supports transactions\n};\n"]}
|