@nicia-ai/typegraph 0.16.1 → 0.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/backend/postgres/index.cjs +28 -28
  2. package/dist/backend/postgres/index.js +3 -3
  3. package/dist/backend/sqlite/index.cjs +13 -13
  4. package/dist/backend/sqlite/index.js +3 -3
  5. package/dist/backend/sqlite/local.cjs +10 -10
  6. package/dist/backend/sqlite/local.cjs.map +1 -1
  7. package/dist/backend/sqlite/local.js +6 -6
  8. package/dist/backend/sqlite/local.js.map +1 -1
  9. package/dist/{chunk-CRMN2NOM.cjs → chunk-2UTJRP4F.cjs} +14 -14
  10. package/dist/{chunk-CRMN2NOM.cjs.map → chunk-2UTJRP4F.cjs.map} +1 -1
  11. package/dist/{chunk-NI2GV74U.cjs → chunk-5GZMPJOP.cjs} +6 -6
  12. package/dist/{chunk-NI2GV74U.cjs.map → chunk-5GZMPJOP.cjs.map} +1 -1
  13. package/dist/{chunk-56RQFK7U.cjs → chunk-5H74QKKF.cjs} +50 -26
  14. package/dist/chunk-5H74QKKF.cjs.map +1 -0
  15. package/dist/{chunk-HWWF3FOP.js → chunk-7ZVPFJLQ.js} +3 -3
  16. package/dist/{chunk-HWWF3FOP.js.map → chunk-7ZVPFJLQ.js.map} +1 -1
  17. package/dist/{chunk-IRFD3MEU.js → chunk-G5CYWKRF.js} +3 -3
  18. package/dist/{chunk-IRFD3MEU.js.map → chunk-G5CYWKRF.js.map} +1 -1
  19. package/dist/{chunk-XZBAGJJH.js → chunk-IRS2C6GN.js} +36 -12
  20. package/dist/chunk-IRS2C6GN.js.map +1 -0
  21. package/dist/{chunk-44SXEVF4.cjs → chunk-O5PST6TB.cjs} +17 -2
  22. package/dist/chunk-O5PST6TB.cjs.map +1 -0
  23. package/dist/{chunk-L4ON6RJF.js → chunk-W6M7XWKX.js} +4 -4
  24. package/dist/{chunk-L4ON6RJF.js.map → chunk-W6M7XWKX.js.map} +1 -1
  25. package/dist/{chunk-SJ2QMDXY.js → chunk-WFMTAEEN.js} +17 -3
  26. package/dist/chunk-WFMTAEEN.js.map +1 -0
  27. package/dist/{chunk-3HQLOKS5.cjs → chunk-X33WV2UF.cjs} +14 -14
  28. package/dist/{chunk-3HQLOKS5.cjs.map → chunk-X33WV2UF.cjs.map} +1 -1
  29. package/dist/{index-QTnQwakS.d.cts → index-DXkEXpNz.d.cts} +13 -1
  30. package/dist/{index-QTnQwakS.d.ts → index-DXkEXpNz.d.ts} +13 -1
  31. package/dist/index.cjs +220 -216
  32. package/dist/index.d.cts +1 -1
  33. package/dist/index.d.ts +1 -1
  34. package/dist/index.js +6 -6
  35. package/dist/interchange/index.cjs +7 -7
  36. package/dist/interchange/index.js +2 -2
  37. package/dist/schema/index.cjs +22 -22
  38. package/dist/schema/index.d.cts +1 -1
  39. package/dist/schema/index.d.ts +1 -1
  40. package/dist/schema/index.js +4 -4
  41. package/package.json +1 -1
  42. package/dist/chunk-44SXEVF4.cjs.map +0 -1
  43. package/dist/chunk-56RQFK7U.cjs.map +0 -1
  44. package/dist/chunk-SJ2QMDXY.js.map +0 -1
  45. package/dist/chunk-XZBAGJJH.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { ValidationError, ConfigurationError } from './chunk-SJ2QMDXY.js';
1
+ import { ValidationError, ConfigurationError } from './chunk-WFMTAEEN.js';
2
2
 
3
3
  // src/core/types.ts
4
4
  var NODE_TYPE_BRAND = "__nodeType";
@@ -131,5 +131,5 @@ function nowIso() {
131
131
  }
132
132
 
133
133
  export { EDGE_TYPE_BRAND, NODE_TYPE_BRAND, defineGraph, getEdgeKinds, getNodeKinds, isEdgeType, isEdgeTypeWithEndpoints, isGraphDef, isNodeType, nowIso, validateOptionalIsoDate };
134
- //# sourceMappingURL=chunk-IRFD3MEU.js.map
135
- //# sourceMappingURL=chunk-IRFD3MEU.js.map
134
+ //# sourceMappingURL=chunk-G5CYWKRF.js.map
135
+ //# sourceMappingURL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AO,MAAA;AAChC,EAAA,OAAO,eAAA,CAAgB,OAAO,SAAS,CAAA;AACzC;AAuBO,SAAS,MAAA,GAAiB;AAC/B,EAAA,OAAA,iBAAO,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAChC","file":"chunk-IRFD3MEU.js","sourcesContent":["import { type z } from \"zod\";\n\n// ============================================================\n// Brand Keys for Nominal Typing\n// ============================================================\n\n/** Brand key for NodeType */\nexport const NODE_TYPE_BRAND = \"__nodeType\" as const;\n\n/** Brand key for EdgeType */\nexport const EDGE_TYPE_BRAND = \"__edgeType\" as const;\n\n/** Brand symbol for NodeId */\ndeclare const __nodeId: unique symbol;\n\n/** Brand symbol for EdgeId */\ndeclare const __edgeId: unique symbol;\n\n// ============================================================\n// Node Type\n// ============================================================\n\n/**\n * A node type definition.\n *\n * Created via `defineNode()`. Represents a type of node in the graph\n * with an associated Zod schema for properties.\n */\nexport type NodeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n [NODE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n}>;\n\n/**\n * Branded node ID type.\n *\n * Prevents mixing IDs from different node types at compile time.\n */\nexport type NodeId<N extends NodeType> = string &\n Readonly<{\n [__nodeId]: N;\n }>;\n\n/**\n * Infer the props type from a NodeType.\n */\nexport type NodeProps<N extends NodeType> = z.infer<N[\"schema\"]>;\n\n// ============================================================\n// Edge Type\n// ============================================================\n\n/**\n * An edge type definition.\n *\n * Created via `defineEdge()`. Represents a type of edge in the graph\n * with an optional Zod schema for properties.\n *\n * Optionally includes `from` and `to` arrays that define the allowed\n * source and target node types (domain and range constraints).\n */\nexport type EdgeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n From extends readonly NodeType[] | undefined = undefined,\n To extends readonly NodeType[] | undefined = undefined,\n> = Readonly<{\n [EDGE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n from: From;\n to: To;\n}>;\n\n/**\n * Base edge type for use in constraints - accepts any from/to configuration.\n */\nexport type AnyEdgeType = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[] | undefined,\n readonly NodeType[] | undefined\n>;\n\n/**\n * An edge type that has both from and to constraints defined.\n * Can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport type EdgeTypeWithEndpoints = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[],\n readonly NodeType[]\n>;\n\n/**\n * Branded edge ID type.\n *\n * Prevents mixing IDs from different edge types at compile time.\n */\nexport type EdgeId<E extends AnyEdgeType = AnyEdgeType> = string &\n Readonly<{\n [__edgeId]: E;\n }>;\n\n/**\n * Infer the props type from an EdgeType.\n */\nexport type EdgeProps<E extends AnyEdgeType> = z.infer<E[\"schema\"]>;\n\n// ============================================================\n// Configuration Types\n// ============================================================\n\n/**\n * Delete behaviors for nodes.\n */\nexport type DeleteBehavior = \"restrict\" | \"cascade\" | \"disconnect\";\n\n/**\n * Edge cardinality constraints.\n */\nexport type Cardinality =\n | \"many\" // No constraint (default)\n | \"one\" // At most one edge of this kind from any source node\n | \"unique\" // At most one edge of this kind between any (source, target) pair\n | \"oneActive\"; // At most one edge with valid_to IS NULL from any source\n\n/**\n * Endpoint existence modes for edge validation.\n */\nexport type EndpointExistence =\n | \"notDeleted\" // Endpoint deleted_at IS NULL (default)\n | \"currentlyValid\" // Endpoint not deleted AND temporally valid\n | \"ever\"; // Endpoint exists in any state\n\n/**\n * Temporal query modes.\n */\nexport type TemporalMode =\n | \"current\" // Valid now AND not deleted\n | \"asOf\" // Valid at specific date AND not deleted\n | \"includeEnded\" // All validity periods AND not deleted\n | \"includeTombstones\"; // Everything including soft-deleted\n\n/**\n * Uniqueness constraint scope.\n */\nexport type UniquenessScope =\n | \"kind\" // Unique within this exact kind only\n | \"kindWithSubClasses\"; // Unique across this kind and all subclasses\n\n/**\n * Collation for uniqueness constraints.\n */\nexport type Collation = \"binary\" | \"caseInsensitive\";\n\n// ============================================================\n// Uniqueness Constraint\n// ============================================================\n\n/**\n * Uniqueness constraint definition.\n */\nexport type UniqueConstraint<\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n name: string;\n fields: readonly (keyof z.infer<S> & string)[];\n where?: (\n props: UniqueConstraintPredicateBuilder<S>,\n ) => UniqueConstraintPredicate;\n scope: UniquenessScope;\n collation: Collation;\n}>;\n\n/**\n * Predicate builder for uniqueness constraint where clause.\n * Uses -? to make all fields required in the builder, even if optional in the schema.\n */\nexport type UniqueConstraintPredicateBuilder<\n S extends z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n [K in keyof z.infer<S>]-?: UniqueConstraintField;\n}>;\n\n/**\n * Field operations for uniqueness constraint predicates.\n */\ntype UniqueConstraintField = Readonly<{\n isNull: () => UniqueConstraintPredicate;\n isNotNull: () => UniqueConstraintPredicate;\n}>;\n\n/**\n * A uniqueness constraint predicate (internal representation).\n */\nexport type UniqueConstraintPredicate = Readonly<{\n __type: \"unique_predicate\";\n field: string;\n op: \"isNull\" | \"isNotNull\";\n}>;\n\n// ============================================================\n// Node Registration\n// ============================================================\n\n/**\n * Node registration in a graph definition.\n */\nexport type NodeRegistration<N extends NodeType = NodeType> = Readonly<{\n type: N;\n unique?: readonly UniqueConstraint<N[\"schema\"]>[];\n onDelete?: DeleteBehavior;\n}>;\n\n// ============================================================\n// Edge Registration\n// ============================================================\n\n/**\n * Edge registration in a graph definition.\n */\nexport type EdgeRegistration<\n E extends AnyEdgeType = AnyEdgeType,\n FromTypes extends NodeType = NodeType,\n ToTypes extends NodeType = NodeType,\n> = Readonly<{\n type: E;\n from: readonly FromTypes[];\n to: readonly ToTypes[];\n cardinality?: Cardinality;\n endpointExistence?: EndpointExistence;\n}>;\n\n// ============================================================\n// Graph Defaults\n// ============================================================\n\n/**\n * Default settings for a graph.\n */\nexport type GraphDefaults = Readonly<{\n onNodeDelete?: DeleteBehavior;\n temporalMode?: TemporalMode;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Checks if a value is a NodeType.\n */\nexport function isNodeType(value: unknown): value is NodeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n NODE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[NODE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType.\n */\nexport function isEdgeType(value: unknown): value is AnyEdgeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n EDGE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[EDGE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType with both from and to constraints defined.\n * Such edges can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport function isEdgeTypeWithEndpoints(\n value: unknown,\n): value is EdgeTypeWithEndpoints {\n return (\n isEdgeType(value) &&\n Array.isArray(value.from) &&\n value.from.length > 0 &&\n Array.isArray(value.to) &&\n value.to.length > 0\n );\n}\n","import { ConfigurationError } from \"../errors/index\";\nimport { type OntologyRelation } from \"../ontology/types\";\nimport {\n type AnyEdgeType,\n type DeleteBehavior,\n type EdgeRegistration,\n type EdgeTypeWithEndpoints,\n type GraphDefaults,\n isEdgeType,\n isEdgeTypeWithEndpoints,\n type NodeRegistration,\n type NodeType,\n type TemporalMode,\n} from \"./types\";\n\n// ============================================================\n// Graph Definition Brand Symbol\n// ============================================================\n\n/** Brand key for GraphDef */\nconst GRAPH_DEF_BRAND = \"__graphDef\" as const;\n\n// ============================================================\n// Edge Entry Types\n// ============================================================\n\n/**\n * An edge entry in the graph definition.\n * Can be:\n * - EdgeType directly (constrained or unconstrained)\n * - EdgeRegistration object (always works, can override/narrow defaults)\n */\ntype EdgeEntry = EdgeRegistration | AnyEdgeType;\n\n/**\n * Normalized edge map type - all entries become EdgeRegistration.\n * For bare EdgeTypes, constrained endpoints are extracted from the type;\n * unconstrained edges fall back to all node types in the graph.\n */\ntype NormalizedEdges<\n TNodes extends Record<string, NodeRegistration>,\n TEdges extends Record<string, EdgeEntry>,\n> = {\n [K in keyof TEdges]: TEdges[K] extends EdgeRegistration ? TEdges[K]\n : TEdges[K] extends AnyEdgeType ?\n EdgeRegistration<\n TEdges[K],\n TEdges[K][\"from\"] extends readonly (infer N extends NodeType)[] ? N\n : TNodes[keyof TNodes][\"type\"],\n TEdges[K][\"to\"] extends readonly (infer N extends NodeType)[] ? N\n : TNodes[keyof TNodes][\"type\"]\n >\n : never;\n};\n\n// ============================================================\n// Edge Normalization Functions\n// ============================================================\n\n/**\n * Validates that an EdgeRegistration's constraints don't widen beyond\n * the edge type's built-in domain/range constraints.\n */\nfunction validateConstraintNarrowing(\n name: string,\n edgeType: EdgeTypeWithEndpoints,\n registration: EdgeRegistration,\n): void {\n const builtInFromNames = new Set(edgeType.from.map((n) => n.kind));\n for (const fromNode of registration.from) {\n if (!builtInFromNames.has(fromNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'from' kind \"${fromNode.kind}\" ` +\n `not in edge's built-in domain: [${[...builtInFromNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidFrom: fromNode.kind,\n allowedFrom: [...builtInFromNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n\n const builtInToNames = new Set(edgeType.to.map((n) => n.kind));\n for (const toNode of registration.to) {\n if (!builtInToNames.has(toNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'to' kind \"${toNode.kind}\" ` +\n `not in edge's built-in range: [${[...builtInToNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidTo: toNode.kind,\n allowedTo: [...builtInToNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n}\n\n/**\n * Normalizes a single edge entry to EdgeRegistration.\n */\nfunction normalizeEdgeEntry(\n name: string,\n entry: EdgeEntry,\n allNodeTypes: readonly NodeType[],\n): EdgeRegistration {\n if (isEdgeType(entry)) {\n if (isEdgeTypeWithEndpoints(entry)) {\n // EdgeType with from/to — convert to EdgeRegistration\n return { type: entry, from: entry.from, to: entry.to };\n }\n // Unconstrained EdgeType — allow any→any\n return { type: entry, from: allNodeTypes, to: allNodeTypes };\n }\n\n // Already EdgeRegistration — validate narrowing if edge has built-in constraints\n if (isEdgeTypeWithEndpoints(entry.type)) {\n validateConstraintNarrowing(name, entry.type, entry);\n }\n\n return entry;\n}\n\n/**\n * Normalizes all edge entries to EdgeRegistration.\n */\nfunction normalizeEdges(\n edges: Record<string, EdgeEntry>,\n allNodeTypes: readonly NodeType[],\n): Record<string, EdgeRegistration> {\n const result: Record<string, EdgeRegistration> = {};\n for (const [name, entry] of Object.entries(edges)) {\n result[name] = normalizeEdgeEntry(name, entry, allNodeTypes);\n }\n return result;\n}\n\n// ============================================================\n// Graph Definition Configuration\n// ============================================================\n\n/**\n * Configuration for defineGraph.\n */\ntype GraphDefConfig<\n TNodes extends Record<string, NodeRegistration>,\n TEdges extends Record<string, EdgeEntry>,\n TOntology extends readonly OntologyRelation[],\n> = Readonly<{\n /** Unique identifier for this graph */\n id: string;\n /** Node registrations */\n nodes: TNodes;\n /** Edge registrations or EdgeTypes with built-in domain/range */\n edges: TEdges;\n /** Ontology relations */\n ontology?: TOntology;\n /** Graph-wide defaults */\n defaults?: GraphDefaults;\n}>;\n\n// ============================================================\n// Graph Definition Type\n// ============================================================\n\n/**\n * A graph definition.\n *\n * This is a compile-time artifact that describes the structure of a graph.\n * Use `createStore()` to create a runtime store from this definition.\n */\nexport type GraphDef<\n TNodes extends Record<string, NodeRegistration> = Record<\n string,\n NodeRegistration\n >,\n TEdges extends Record<string, EdgeRegistration> = Record<\n string,\n EdgeRegistration\n >,\n TOntology extends readonly OntologyRelation[] = readonly OntologyRelation[],\n> = Readonly<{\n [GRAPH_DEF_BRAND]: true;\n id: string;\n nodes: TNodes;\n edges: TEdges;\n ontology: TOntology;\n defaults: Readonly<{\n onNodeDelete: DeleteBehavior;\n temporalMode: TemporalMode;\n }>;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Extract node kind names from a GraphDef.\n */\nexport type NodeKinds<G extends GraphDef> = keyof G[\"nodes\"] & string;\n\n/**\n * Extract edge kind names from a GraphDef.\n */\nexport type EdgeKinds<G extends GraphDef> = keyof G[\"edges\"] & string;\n\n/**\n * Get a NodeType from a GraphDef by kind name.\n */\nexport type GetNodeType<\n G extends GraphDef,\n K extends NodeKinds<G>,\n> = G[\"nodes\"][K][\"type\"];\n\n/**\n * Get an EdgeType from a GraphDef by kind name.\n */\nexport type GetEdgeType<\n G extends GraphDef,\n K extends EdgeKinds<G>,\n> = G[\"edges\"][K][\"type\"];\n\n/**\n * Get all NodeTypes from a GraphDef.\n */\nexport type AllNodeTypes<G extends GraphDef> = {\n [K in NodeKinds<G>]: G[\"nodes\"][K][\"type\"];\n}[NodeKinds<G>];\n\n/**\n * Get all EdgeTypes from a GraphDef.\n */\nexport type AllEdgeTypes<G extends GraphDef> = {\n [K in EdgeKinds<G>]: G[\"edges\"][K][\"type\"];\n}[EdgeKinds<G>];\n\n// ============================================================\n// Define Graph Function\n// ============================================================\n\n/**\n * Creates a graph definition.\n *\n * @example\n * ```typescript\n * const graph = defineGraph({\n * id: \"my_graph\",\n * nodes: {\n * Person: { type: Person },\n * Company: { type: Company },\n * },\n * edges: {\n * // Traditional EdgeRegistration syntax\n * worksAt: {\n * type: worksAt,\n * from: [Person],\n * to: [Company],\n * cardinality: \"many\",\n * },\n * // Or use EdgeType directly if it has from/to defined\n * knows, // EdgeType with built-in domain/range\n * },\n * ontology: [\n * subClassOf(Company, Organization),\n * disjointWith(Person, Organization),\n * ],\n * defaults: {\n * onNodeDelete: \"restrict\",\n * temporalMode: \"current\",\n * },\n * });\n * ```\n */\nexport function defineGraph<\n const TNodes extends Record<string, NodeRegistration<NodeType>>,\n const TEdges extends Record<string, EdgeEntry>,\n const TOntology extends readonly OntologyRelation[],\n>(\n config: GraphDefConfig<TNodes, TEdges, TOntology>,\n): GraphDef<TNodes, NormalizedEdges<TNodes, TEdges>, TOntology> {\n const defaults = {\n onNodeDelete: config.defaults?.onNodeDelete ?? \"restrict\",\n temporalMode: config.defaults?.temporalMode ?? \"current\",\n } as const;\n\n const allNodeTypes = Object.values(config.nodes).map((reg) => reg.type);\n const normalizedEdges = normalizeEdges(config.edges, allNodeTypes);\n\n return Object.freeze({\n [GRAPH_DEF_BRAND]: true as const,\n id: config.id,\n nodes: config.nodes,\n edges: normalizedEdges,\n ontology: config.ontology ?? ([] as unknown as TOntology),\n defaults,\n }) as GraphDef<TNodes, NormalizedEdges<TNodes, TEdges>, TOntology>;\n}\n\n// ============================================================\n// Graph Definition Utilities\n// ============================================================\n\n/**\n * Checks if a value is a GraphDef.\n */\nexport function isGraphDef(value: unknown): value is GraphDef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n GRAPH_DEF_BRAND in value &&\n (value as Record<string, unknown>)[GRAPH_DEF_BRAND] === true\n );\n}\n\n/**\n * Gets all node kind names from a GraphDef.\n */\nexport function getNodeKinds<G extends GraphDef>(\n graph: G,\n): readonly (keyof G[\"nodes\"] & string)[] {\n return Object.keys(graph.nodes) as (keyof G[\"nodes\"] & string)[];\n}\n\n/**\n * Gets all edge kind names from a GraphDef.\n */\nexport function getEdgeKinds<G extends GraphDef>(\n graph: G,\n): readonly (keyof G[\"edges\"] & string)[] {\n return Object.keys(graph.edges) as (keyof G[\"edges\"] & string)[];\n}\n","/**\n * Date encoding utilities for consistent storage.\n *\n * Contract: All dates are stored as ISO 8601 strings in UTC.\n * - Always includes milliseconds\n * - Always UTC (Z suffix)\n * - Sorts correctly as strings\n */\n\nimport { ValidationError } from \"../errors\";\n\n/**\n * ISO 8601 datetime pattern.\n * Matches formats like:\n * - 2024-01-15T10:30:00.000Z\n * - 2024-01-15T10:30:00Z\n * - 2024-01-15T10:30:00.123Z\n */\nconst ISO_DATE_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?Z$/;\n\n/**\n * Checks if a string is a valid ISO 8601 datetime.\n *\n * @param value - String to validate\n * @returns True if valid ISO 8601 datetime\n */\nexport function isValidIsoDate(value: string): boolean {\n if (!ISO_DATE_PATTERN.test(value)) {\n return false;\n }\n // Also check that Date parsing produces a valid date\n const date = new Date(value);\n return !Number.isNaN(date.getTime());\n}\n\n/**\n * Validates that a string is a valid ISO 8601 datetime.\n * Throws ValidationError if invalid.\n *\n * @param value - String to validate\n * @param fieldName - Name of field for error message\n * @returns The validated string\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function validateIsoDate(value: string, fieldName: string): string {\n if (!isValidIsoDate(value)) {\n throw new ValidationError(\n `Invalid ISO 8601 datetime for \"${fieldName}\": \"${value}\". ` +\n `Expected format: YYYY-MM-DDTHH:mm:ss.sssZ`,\n {\n issues: [\n {\n path: fieldName,\n message: `Invalid ISO 8601 datetime format. Expected: YYYY-MM-DDTHH:mm:ss.sssZ, got: \"${value}\"`,\n },\n ],\n },\n {\n suggestion: `Use a valid ISO 8601 UTC datetime like \"2024-01-15T10:30:00.000Z\"`,\n },\n );\n }\n return value;\n}\n\n/**\n * Validates an optional ISO date string.\n * Returns undefined if value is undefined, otherwise validates.\n */\nexport function validateOptionalIsoDate(\n value: string | undefined,\n fieldName: string,\n): string | undefined {\n if (value === undefined) return undefined;\n return validateIsoDate(value, fieldName);\n}\n\n/**\n * Encodes a Date to an ISO 8601 string for storage.\n */\nexport function encodeDate(date: Date): string {\n return date.toISOString();\n}\n\n/**\n * Decodes an ISO 8601 string to a Date.\n * Validates the string format first.\n *\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function decodeDate(isoString: string): Date {\n validateIsoDate(isoString, \"date\");\n return new Date(isoString);\n}\n\n/**\n * Returns the current timestamp as an ISO string.\n */\nexport function nowIso(): string {\n return new Date().toISOString();\n}\n"]}
1
+ {"version":3,"sources":["../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AAA;AACzC;AAuBO,SAAS,MAAA,GAAiB;AAC/B,EAAA,OAAA,iBAAO,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAChC","file":"chunk-G5CYWKRF.js","sourcesContent":["import { type z } from \"zod\";\n\n// ============================================================\n// Brand Keys for Nominal Typing\n// ============================================================\n\n/** Brand key for NodeType */\nexport const NODE_TYPE_BRAND = \"__nodeType\" as const;\n\n/** Brand key for EdgeType */\nexport const EDGE_TYPE_BRAND = \"__edgeType\" as const;\n\n/** Brand symbol for NodeId */\ndeclare const __nodeId: unique symbol;\n\n/** Brand symbol for EdgeId */\ndeclare const __edgeId: unique symbol;\n\n// ============================================================\n// Node Type\n// ============================================================\n\n/**\n * A node type definition.\n *\n * Created via `defineNode()`. Represents a type of node in the graph\n * with an associated Zod schema for properties.\n */\nexport type NodeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n [NODE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n}>;\n\n/**\n * Branded node ID type.\n *\n * Prevents mixing IDs from different node types at compile time.\n */\nexport type NodeId<N extends NodeType> = string &\n Readonly<{\n [__nodeId]: N;\n }>;\n\n/**\n * Infer the props type from a NodeType.\n */\nexport type NodeProps<N extends NodeType> = z.infer<N[\"schema\"]>;\n\n// ============================================================\n// Edge Type\n// ============================================================\n\n/**\n * An edge type definition.\n *\n * Created via `defineEdge()`. Represents a type of edge in the graph\n * with an optional Zod schema for properties.\n *\n * Optionally includes `from` and `to` arrays that define the allowed\n * source and target node types (domain and range constraints).\n */\nexport type EdgeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n From extends readonly NodeType[] | undefined = undefined,\n To extends readonly NodeType[] | undefined = undefined,\n> = Readonly<{\n [EDGE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n from: From;\n to: To;\n}>;\n\n/**\n * Base edge type for use in constraints - accepts any from/to configuration.\n */\nexport type AnyEdgeType = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[] | undefined,\n readonly NodeType[] | undefined\n>;\n\n/**\n * An edge type that has both from and to constraints defined.\n * Can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport type EdgeTypeWithEndpoints = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[],\n readonly NodeType[]\n>;\n\n/**\n * Branded edge ID type.\n *\n * Prevents mixing IDs from different edge types at compile time.\n */\nexport type EdgeId<E extends AnyEdgeType = AnyEdgeType> = string &\n Readonly<{\n [__edgeId]: E;\n }>;\n\n/**\n * Infer the props type from an EdgeType.\n */\nexport type EdgeProps<E extends AnyEdgeType> = z.infer<E[\"schema\"]>;\n\n// ============================================================\n// Configuration Types\n// ============================================================\n\n/**\n * Delete behaviors for nodes.\n */\nexport type DeleteBehavior = \"restrict\" | \"cascade\" | \"disconnect\";\n\n/**\n * Edge cardinality constraints.\n */\nexport type Cardinality =\n | \"many\" // No constraint (default)\n | \"one\" // At most one edge of this kind from any source node\n | \"unique\" // At most one edge of this kind between any (source, target) pair\n | \"oneActive\"; // At most one edge with valid_to IS NULL from any source\n\n/**\n * Endpoint existence modes for edge validation.\n */\nexport type EndpointExistence =\n | \"notDeleted\" // Endpoint deleted_at IS NULL (default)\n | \"currentlyValid\" // Endpoint not deleted AND temporally valid\n | \"ever\"; // Endpoint exists in any state\n\n/**\n * Temporal query modes.\n */\nexport type TemporalMode =\n | \"current\" // Valid now AND not deleted\n | \"asOf\" // Valid at specific date AND not deleted\n | \"includeEnded\" // All validity periods AND not deleted\n | \"includeTombstones\"; // Everything including soft-deleted\n\n/**\n * Uniqueness constraint scope.\n */\nexport type UniquenessScope =\n | \"kind\" // Unique within this exact kind only\n | \"kindWithSubClasses\"; // Unique across this kind and all subclasses\n\n/**\n * Collation for uniqueness constraints.\n */\nexport type Collation = \"binary\" | \"caseInsensitive\";\n\n// ============================================================\n// Uniqueness Constraint\n// ============================================================\n\n/**\n * Uniqueness constraint definition.\n */\nexport type UniqueConstraint<\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n name: string;\n fields: readonly (keyof z.infer<S> & string)[];\n where?: (\n props: UniqueConstraintPredicateBuilder<S>,\n ) => UniqueConstraintPredicate;\n scope: UniquenessScope;\n collation: Collation;\n}>;\n\n/**\n * Predicate builder for uniqueness constraint where clause.\n * Uses -? to make all fields required in the builder, even if optional in the schema.\n */\nexport type UniqueConstraintPredicateBuilder<\n S extends z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n [K in keyof z.infer<S>]-?: UniqueConstraintField;\n}>;\n\n/**\n * Field operations for uniqueness constraint predicates.\n */\ntype UniqueConstraintField = Readonly<{\n isNull: () => UniqueConstraintPredicate;\n isNotNull: () => UniqueConstraintPredicate;\n}>;\n\n/**\n * A uniqueness constraint predicate (internal representation).\n */\nexport type UniqueConstraintPredicate = Readonly<{\n __type: \"unique_predicate\";\n field: string;\n op: \"isNull\" | \"isNotNull\";\n}>;\n\n// ============================================================\n// Node Registration\n// ============================================================\n\n/**\n * Node registration in a graph definition.\n */\nexport type NodeRegistration<N extends NodeType = NodeType> = Readonly<{\n type: N;\n unique?: readonly UniqueConstraint<N[\"schema\"]>[];\n onDelete?: DeleteBehavior;\n}>;\n\n// ============================================================\n// Edge Registration\n// ============================================================\n\n/**\n * Edge registration in a graph definition.\n */\nexport type EdgeRegistration<\n E extends AnyEdgeType = AnyEdgeType,\n FromTypes extends NodeType = NodeType,\n ToTypes extends NodeType = NodeType,\n> = Readonly<{\n type: E;\n from: readonly FromTypes[];\n to: readonly ToTypes[];\n cardinality?: Cardinality;\n endpointExistence?: EndpointExistence;\n}>;\n\n// ============================================================\n// Graph Defaults\n// ============================================================\n\n/**\n * Default settings for a graph.\n */\nexport type GraphDefaults = Readonly<{\n onNodeDelete?: DeleteBehavior;\n temporalMode?: TemporalMode;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Checks if a value is a NodeType.\n */\nexport function isNodeType(value: unknown): value is NodeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n NODE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[NODE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType.\n */\nexport function isEdgeType(value: unknown): value is AnyEdgeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n EDGE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[EDGE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType with both from and to constraints defined.\n * Such edges can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport function isEdgeTypeWithEndpoints(\n value: unknown,\n): value is EdgeTypeWithEndpoints {\n return (\n isEdgeType(value) &&\n Array.isArray(value.from) &&\n value.from.length > 0 &&\n Array.isArray(value.to) &&\n value.to.length > 0\n );\n}\n","import { ConfigurationError } from \"../errors/index\";\nimport { type OntologyRelation } from \"../ontology/types\";\nimport {\n type AnyEdgeType,\n type DeleteBehavior,\n type EdgeRegistration,\n type EdgeTypeWithEndpoints,\n type GraphDefaults,\n isEdgeType,\n isEdgeTypeWithEndpoints,\n type NodeRegistration,\n type NodeType,\n type TemporalMode,\n} from \"./types\";\n\n// ============================================================\n// Graph Definition Brand Symbol\n// ============================================================\n\n/** Brand key for GraphDef */\nconst GRAPH_DEF_BRAND = \"__graphDef\" as const;\n\n// ============================================================\n// Edge Entry Types\n// ============================================================\n\n/**\n * An edge entry in the graph definition.\n * Can be:\n * - EdgeType directly (constrained or unconstrained)\n * - EdgeRegistration object (always works, can override/narrow defaults)\n */\ntype EdgeEntry = EdgeRegistration | AnyEdgeType;\n\n/**\n * Normalized edge map type - all entries become EdgeRegistration.\n * For bare EdgeTypes, constrained endpoints are extracted from the type;\n * unconstrained edges fall back to all node types in the graph.\n */\ntype NormalizedEdges<\n TNodes extends Record<string, NodeRegistration>,\n TEdges extends Record<string, EdgeEntry>,\n> = {\n [K in keyof TEdges]: TEdges[K] extends EdgeRegistration ? TEdges[K]\n : TEdges[K] extends AnyEdgeType ?\n EdgeRegistration<\n TEdges[K],\n TEdges[K][\"from\"] extends readonly (infer N extends NodeType)[] ? N\n : TNodes[keyof TNodes][\"type\"],\n TEdges[K][\"to\"] extends readonly (infer N extends NodeType)[] ? N\n : TNodes[keyof TNodes][\"type\"]\n >\n : never;\n};\n\n// ============================================================\n// Edge Normalization Functions\n// ============================================================\n\n/**\n * Validates that an EdgeRegistration's constraints don't widen beyond\n * the edge type's built-in domain/range constraints.\n */\nfunction validateConstraintNarrowing(\n name: string,\n edgeType: EdgeTypeWithEndpoints,\n registration: EdgeRegistration,\n): void {\n const builtInFromNames = new Set(edgeType.from.map((n) => n.kind));\n for (const fromNode of registration.from) {\n if (!builtInFromNames.has(fromNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'from' kind \"${fromNode.kind}\" ` +\n `not in edge's built-in domain: [${[...builtInFromNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidFrom: fromNode.kind,\n allowedFrom: [...builtInFromNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n\n const builtInToNames = new Set(edgeType.to.map((n) => n.kind));\n for (const toNode of registration.to) {\n if (!builtInToNames.has(toNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'to' kind \"${toNode.kind}\" ` +\n `not in edge's built-in range: [${[...builtInToNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidTo: toNode.kind,\n allowedTo: [...builtInToNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n}\n\n/**\n * Normalizes a single edge entry to EdgeRegistration.\n */\nfunction normalizeEdgeEntry(\n name: string,\n entry: EdgeEntry,\n allNodeTypes: readonly NodeType[],\n): EdgeRegistration {\n if (isEdgeType(entry)) {\n if (isEdgeTypeWithEndpoints(entry)) {\n // EdgeType with from/to — convert to EdgeRegistration\n return { type: entry, from: entry.from, to: entry.to };\n }\n // Unconstrained EdgeType — allow any→any\n return { type: entry, from: allNodeTypes, to: allNodeTypes };\n }\n\n // Already EdgeRegistration — validate narrowing if edge has built-in constraints\n if (isEdgeTypeWithEndpoints(entry.type)) {\n validateConstraintNarrowing(name, entry.type, entry);\n }\n\n return entry;\n}\n\n/**\n * Normalizes all edge entries to EdgeRegistration.\n */\nfunction normalizeEdges(\n edges: Record<string, EdgeEntry>,\n allNodeTypes: readonly NodeType[],\n): Record<string, EdgeRegistration> {\n const result: Record<string, EdgeRegistration> = {};\n for (const [name, entry] of Object.entries(edges)) {\n result[name] = normalizeEdgeEntry(name, entry, allNodeTypes);\n }\n return result;\n}\n\n// ============================================================\n// Graph Definition Configuration\n// ============================================================\n\n/**\n * Configuration for defineGraph.\n */\ntype GraphDefConfig<\n TNodes extends Record<string, NodeRegistration>,\n TEdges extends Record<string, EdgeEntry>,\n TOntology extends readonly OntologyRelation[],\n> = Readonly<{\n /** Unique identifier for this graph */\n id: string;\n /** Node registrations */\n nodes: TNodes;\n /** Edge registrations or EdgeTypes with built-in domain/range */\n edges: TEdges;\n /** Ontology relations */\n ontology?: TOntology;\n /** Graph-wide defaults */\n defaults?: GraphDefaults;\n}>;\n\n// ============================================================\n// Graph Definition Type\n// ============================================================\n\n/**\n * A graph definition.\n *\n * This is a compile-time artifact that describes the structure of a graph.\n * Use `createStore()` to create a runtime store from this definition.\n */\nexport type GraphDef<\n TNodes extends Record<string, NodeRegistration> = Record<\n string,\n NodeRegistration\n >,\n TEdges extends Record<string, EdgeRegistration> = Record<\n string,\n EdgeRegistration\n >,\n TOntology extends readonly OntologyRelation[] = readonly OntologyRelation[],\n> = Readonly<{\n [GRAPH_DEF_BRAND]: true;\n id: string;\n nodes: TNodes;\n edges: TEdges;\n ontology: TOntology;\n defaults: Readonly<{\n onNodeDelete: DeleteBehavior;\n temporalMode: TemporalMode;\n }>;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Extract node kind names from a GraphDef.\n */\nexport type NodeKinds<G extends GraphDef> = keyof G[\"nodes\"] & string;\n\n/**\n * Extract edge kind names from a GraphDef.\n */\nexport type EdgeKinds<G extends GraphDef> = keyof G[\"edges\"] & string;\n\n/**\n * Get a NodeType from a GraphDef by kind name.\n */\nexport type GetNodeType<\n G extends GraphDef,\n K extends NodeKinds<G>,\n> = G[\"nodes\"][K][\"type\"];\n\n/**\n * Get an EdgeType from a GraphDef by kind name.\n */\nexport type GetEdgeType<\n G extends GraphDef,\n K extends EdgeKinds<G>,\n> = G[\"edges\"][K][\"type\"];\n\n/**\n * Get all NodeTypes from a GraphDef.\n */\nexport type AllNodeTypes<G extends GraphDef> = {\n [K in NodeKinds<G>]: G[\"nodes\"][K][\"type\"];\n}[NodeKinds<G>];\n\n/**\n * Get all EdgeTypes from a GraphDef.\n */\nexport type AllEdgeTypes<G extends GraphDef> = {\n [K in EdgeKinds<G>]: G[\"edges\"][K][\"type\"];\n}[EdgeKinds<G>];\n\n// ============================================================\n// Define Graph Function\n// ============================================================\n\n/**\n * Creates a graph definition.\n *\n * @example\n * ```typescript\n * const graph = defineGraph({\n * id: \"my_graph\",\n * nodes: {\n * Person: { type: Person },\n * Company: { type: Company },\n * },\n * edges: {\n * // Traditional EdgeRegistration syntax\n * worksAt: {\n * type: worksAt,\n * from: [Person],\n * to: [Company],\n * cardinality: \"many\",\n * },\n * // Or use EdgeType directly if it has from/to defined\n * knows, // EdgeType with built-in domain/range\n * },\n * ontology: [\n * subClassOf(Company, Organization),\n * disjointWith(Person, Organization),\n * ],\n * defaults: {\n * onNodeDelete: \"restrict\",\n * temporalMode: \"current\",\n * },\n * });\n * ```\n */\nexport function defineGraph<\n const TNodes extends Record<string, NodeRegistration<NodeType>>,\n const TEdges extends Record<string, EdgeEntry>,\n const TOntology extends readonly OntologyRelation[],\n>(\n config: GraphDefConfig<TNodes, TEdges, TOntology>,\n): GraphDef<TNodes, NormalizedEdges<TNodes, TEdges>, TOntology> {\n const defaults = {\n onNodeDelete: config.defaults?.onNodeDelete ?? \"restrict\",\n temporalMode: config.defaults?.temporalMode ?? \"current\",\n } as const;\n\n const allNodeTypes = Object.values(config.nodes).map((reg) => reg.type);\n const normalizedEdges = normalizeEdges(config.edges, allNodeTypes);\n\n return Object.freeze({\n [GRAPH_DEF_BRAND]: true as const,\n id: config.id,\n nodes: config.nodes,\n edges: normalizedEdges,\n ontology: config.ontology ?? ([] as unknown as TOntology),\n defaults,\n }) as GraphDef<TNodes, NormalizedEdges<TNodes, TEdges>, TOntology>;\n}\n\n// ============================================================\n// Graph Definition Utilities\n// ============================================================\n\n/**\n * Checks if a value is a GraphDef.\n */\nexport function isGraphDef(value: unknown): value is GraphDef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n GRAPH_DEF_BRAND in value &&\n (value as Record<string, unknown>)[GRAPH_DEF_BRAND] === true\n );\n}\n\n/**\n * Gets all node kind names from a GraphDef.\n */\nexport function getNodeKinds<G extends GraphDef>(\n graph: G,\n): readonly (keyof G[\"nodes\"] & string)[] {\n return Object.keys(graph.nodes) as (keyof G[\"nodes\"] & string)[];\n}\n\n/**\n * Gets all edge kind names from a GraphDef.\n */\nexport function getEdgeKinds<G extends GraphDef>(\n graph: G,\n): readonly (keyof G[\"edges\"] & string)[] {\n return Object.keys(graph.edges) as (keyof G[\"edges\"] & string)[];\n}\n","/**\n * Date encoding utilities for consistent storage.\n *\n * Contract: All dates are stored as ISO 8601 strings in UTC.\n * - Always includes milliseconds\n * - Always UTC (Z suffix)\n * - Sorts correctly as strings\n */\n\nimport { ValidationError } from \"../errors\";\n\n/**\n * ISO 8601 datetime pattern.\n * Matches formats like:\n * - 2024-01-15T10:30:00.000Z\n * - 2024-01-15T10:30:00Z\n * - 2024-01-15T10:30:00.123Z\n */\nconst ISO_DATE_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?Z$/;\n\n/**\n * Checks if a string is a valid ISO 8601 datetime.\n *\n * @param value - String to validate\n * @returns True if valid ISO 8601 datetime\n */\nexport function isValidIsoDate(value: string): boolean {\n if (!ISO_DATE_PATTERN.test(value)) {\n return false;\n }\n // Also check that Date parsing produces a valid date\n const date = new Date(value);\n return !Number.isNaN(date.getTime());\n}\n\n/**\n * Validates that a string is a valid ISO 8601 datetime.\n * Throws ValidationError if invalid.\n *\n * @param value - String to validate\n * @param fieldName - Name of field for error message\n * @returns The validated string\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function validateIsoDate(value: string, fieldName: string): string {\n if (!isValidIsoDate(value)) {\n throw new ValidationError(\n `Invalid ISO 8601 datetime for \"${fieldName}\": \"${value}\". ` +\n `Expected format: YYYY-MM-DDTHH:mm:ss.sssZ`,\n {\n issues: [\n {\n path: fieldName,\n message: `Invalid ISO 8601 datetime format. Expected: YYYY-MM-DDTHH:mm:ss.sssZ, got: \"${value}\"`,\n },\n ],\n },\n {\n suggestion: `Use a valid ISO 8601 UTC datetime like \"2024-01-15T10:30:00.000Z\"`,\n },\n );\n }\n return value;\n}\n\n/**\n * Validates an optional ISO date string.\n * Returns undefined if value is undefined, otherwise validates.\n */\nexport function validateOptionalIsoDate(\n value: string | undefined,\n fieldName: string,\n): string | undefined {\n if (value === undefined) return undefined;\n return validateIsoDate(value, fieldName);\n}\n\n/**\n * Encodes a Date to an ISO 8601 string for storage.\n */\nexport function encodeDate(date: Date): string {\n return date.toISOString();\n}\n\n/**\n * Decodes an ISO 8601 string to a Date.\n * Validates the string format first.\n *\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function decodeDate(isoString: string): Date {\n validateIsoDate(isoString, \"date\");\n return new Date(isoString);\n}\n\n/**\n * Returns the current timestamp as an ISO string.\n */\nexport function nowIso(): string {\n return new Date().toISOString();\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { createNodeRowMapper, SQLITE_ROW_MAPPER_CONFIG, createEdgeRowMapper, createUniqueRowMapper, createSchemaVersionRowMapper, tables2, SQLITE_CAPABILITIES, createSqliteOperationStrategy, generateSqliteDDL, createCommonOperationBackend, nowIso, compileQueryWithDialect, dropSqliteVectorIndex, createSqliteVectorIndex } from './chunk-HWWF3FOP.js';
2
- import { ConfigurationError } from './chunk-SJ2QMDXY.js';
1
+ import { createNodeRowMapper, SQLITE_ROW_MAPPER_CONFIG, createEdgeRowMapper, createUniqueRowMapper, createSchemaVersionRowMapper, tables2, SQLITE_CAPABILITIES, createSqliteOperationStrategy, generateSqliteDDL, createCommonOperationBackend, nowIso, compileQueryWithDialect, dropSqliteVectorIndex, createSqliteVectorIndex } from './chunk-7ZVPFJLQ.js';
2
+ import { ConfigurationError, BackendDisposedError } from './chunk-WFMTAEEN.js';
3
3
  import { getTableName, sql } from 'drizzle-orm';
4
4
 
5
5
  var DEFAULT_PREPARED_STATEMENT_CACHE_MAX = 256;
@@ -180,11 +180,33 @@ var toNodeRow = createNodeRowMapper(SQLITE_ROW_MAPPER_CONFIG);
180
180
  var toEdgeRow = createEdgeRowMapper(SQLITE_ROW_MAPPER_CONFIG);
181
181
  var toUniqueRow = createUniqueRowMapper(SQLITE_ROW_MAPPER_CONFIG);
182
182
  var toSchemaVersionRow = createSchemaVersionRowMapper(SQLITE_ROW_MAPPER_CONFIG);
183
+ var PENDING_FOREVER = new Promise(noop);
184
+ function pendingForever() {
185
+ return PENDING_FOREVER;
186
+ }
187
+ function noop() {
188
+ }
183
189
  function createSerializedExecutionQueue() {
184
190
  let tail = Promise.resolve();
191
+ let disposed = false;
192
+ function isDisposed() {
193
+ return disposed;
194
+ }
185
195
  return {
186
- async runExclusive(task) {
187
- const runTask = async () => task();
196
+ dispose() {
197
+ disposed = true;
198
+ },
199
+ runExclusive(task) {
200
+ if (isDisposed()) return Promise.reject(new BackendDisposedError());
201
+ const runTask = async () => {
202
+ if (isDisposed()) return pendingForever();
203
+ try {
204
+ return await task();
205
+ } catch (error) {
206
+ if (isDisposed()) return pendingForever();
207
+ throw error;
208
+ }
209
+ };
188
210
  const result = tail.then(runTask, runTask);
189
211
  tail = result.then(
190
212
  () => 0,
@@ -194,7 +216,7 @@ function createSerializedExecutionQueue() {
194
216
  }
195
217
  };
196
218
  }
197
- async function runWithSerializedQueue(queue, task) {
219
+ function runWithSerializedQueue(queue, task) {
198
220
  if (queue === void 0) return task();
199
221
  return queue.runExclusive(task);
200
222
  }
@@ -207,20 +229,20 @@ function createSqliteOperationBackend(options) {
207
229
  serializedQueue,
208
230
  tableNames
209
231
  } = options;
210
- async function execGet(query) {
232
+ function execGet(query) {
211
233
  return runWithSerializedQueue(serializedQueue, async () => {
212
234
  const result = db.get(query);
213
235
  return result instanceof Promise ? await result : result;
214
236
  });
215
237
  }
216
- async function execAll(query) {
238
+ function execAll(query) {
217
239
  return runWithSerializedQueue(serializedQueue, async () => {
218
240
  const result = db.all(query);
219
241
  return result instanceof Promise ? await result : result;
220
242
  });
221
243
  }
222
- async function execRun(query) {
223
- await runWithSerializedQueue(serializedQueue, async () => {
244
+ function execRun(query) {
245
+ return runWithSerializedQueue(serializedQueue, async () => {
224
246
  const result = db.run(query);
225
247
  if (result instanceof Promise) await result;
226
248
  });
@@ -385,7 +407,9 @@ function createSqliteBackend(db, options = {}) {
385
407
  })
386
408
  );
387
409
  },
388
- async close() {
410
+ close() {
411
+ serializedQueue?.dispose();
412
+ return Promise.resolve();
389
413
  }
390
414
  };
391
415
  return backend;
@@ -404,5 +428,5 @@ function createTransactionBackend(options) {
404
428
  }
405
429
 
406
430
  export { createSqliteBackend };
407
- //# sourceMappingURL=chunk-XZBAGJJH.js.map
408
- //# sourceMappingURL=chunk-XZBAGJJH.js.map
431
+ //# sourceMappingURL=chunk-IRS2C6GN.js.map
432
+ //# sourceMappingURL=chunk-IRS2C6GN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/backend/drizzle/execution/sqlite-execution.ts","../src/backend/drizzle/sqlite.ts"],"names":["executeCompiled","tables","sql"],"mapp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,QAAQ,EAAA,EAAI;AAAA,IACvC,cAAc,OAAA,CAAQ;AAAA,GACvB,CAAA;AAEH,EAAA,OAAO,4BAAA,CAA6B;AAAA,IAClC,cAAc,OAAA,CAAQ,YAAA;AAAA,IACtB,IAAI,OAAA,CAAQ,EAAA;AAAA,IACZ,gBAAA,EAAkB,kBAAA;AAAA,IAClB,mBAAmB,OAAA,CAAQ,iBAAA;AAAA,IAC3B,YAAY,OAAA,CAAQ;AAAA,GACrB,CAAA;AACH","file":"chunk-IRS2C6GN.js","sourcesContent":["import { type SQL, sql } from \"drizzle-orm\";\nimport { type BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\nimport {\n type CompiledSqlQuery,\n compileQueryWithDialect,\n type PreparedSqlStatement,\n type SqlExecutionAdapter,\n} from \"./types\";\n\nconst DEFAULT_PREPARED_STATEMENT_CACHE_MAX = 256;\n\ntype PreparedAllStatement = Readonly<{\n all: (...params: readonly unknown[]) => readonly unknown[];\n}>;\n\ntype SqliteClientWithPrepare = Readonly<{\n prepare: (sqlText: string) => PreparedAllStatement;\n}>;\n\ntype SqliteClientCarrier = Readonly<{\n $client?: SqliteClientWithPrepare;\n}>;\n\ntype SessionLike = Readonly<{\n constructor?: Readonly<{\n name?: string;\n }>;\n}>;\n\ntype DatabaseWithSession = Readonly<{\n _?: Readonly<{\n session?: SessionLike;\n }>;\n session?: SessionLike;\n}>;\n\n/**\n * Controls how the backend manages SQLite transactions.\n *\n * - `\"sql\"`: TypeGraph issues BEGIN / COMMIT / ROLLBACK SQL directly.\n * Default for sync drivers (better-sqlite3, bun:sqlite).\n * - `\"drizzle\"`: Delegates to Drizzle's `db.transaction()` method.\n * Default for async drivers (libsql, sql.js).\n * - `\"none\"`: Transactions disabled.\n * Default for Cloudflare D1 and Durable Objects.\n */\nexport type SqliteTransactionMode = \"sql\" | \"drizzle\" | \"none\";\n\nexport type SqliteExecutionProfileHints = Readonly<{\n isSync?: boolean;\n transactionMode?: SqliteTransactionMode;\n}>;\n\ntype SqliteExecutionAdapterOptions = Readonly<{\n profileHints?: SqliteExecutionProfileHints;\n statementCacheMax?: number;\n}>;\n\nexport type AnySqliteDatabase = BaseSQLiteDatabase<\"sync\" | \"async\", unknown>;\n\nexport type SqliteExecutionProfile = Readonly<{\n isSync: boolean;\n supportsCompiledExecution: boolean;\n transactionMode: SqliteTransactionMode;\n}>;\n\nexport type SqliteExecutionAdapter = Readonly<\n SqlExecutionAdapter & {\n clearStatementCache: () => void;\n profile: SqliteExecutionProfile;\n }\n>;\n\nfunction getSessionName(db: AnySqliteDatabase): string | undefined {\n const databaseWithSession = db as DatabaseWithSession;\n const primarySessionName = databaseWithSession.session?.constructor?.name;\n if (primarySessionName !== undefined) {\n return primarySessionName;\n }\n\n return databaseWithSession._?.session?.constructor?.name;\n}\n\nfunction isD1DatabaseBySessionName(db: AnySqliteDatabase): boolean {\n return getSessionName(db) === \"SQLiteD1Session\";\n}\n\nfunction isDurableObjectBySessionName(db: AnySqliteDatabase): boolean {\n const sessionName = getSessionName(db);\n return sessionName === \"SQLiteDurableObjectSession\";\n}\n\nfunction isSyncDatabaseBySessionName(db: AnySqliteDatabase): boolean {\n const sessionName = getSessionName(db);\n return (\n sessionName === \"BetterSQLiteSession\" || sessionName === \"BunSQLiteSession\"\n );\n}\n\nfunction detectSyncProfile(\n db: AnySqliteDatabase,\n profileHints: SqliteExecutionProfileHints,\n): boolean {\n if (profileHints.isSync !== undefined) {\n return profileHints.isSync;\n }\n\n const sessionName = getSessionName(db);\n if (sessionName === \"BetterSQLiteSession\" || sessionName === \"BunSQLiteSession\") {\n return true;\n }\n if (sessionName === \"SQLiteD1Session\") {\n return false;\n }\n\n try {\n const probeResult = db.get(sql`SELECT 1 AS __typegraph_sync_probe__`);\n return !(probeResult instanceof Promise);\n } catch {\n return isSyncDatabaseBySessionName(db);\n }\n}\n\nfunction detectTransactionMode(\n db: AnySqliteDatabase,\n profileHints: SqliteExecutionProfileHints,\n isSync: boolean,\n): SqliteTransactionMode {\n if (profileHints.transactionMode !== undefined) {\n return profileHints.transactionMode;\n }\n // D1 and Durable Object SQLite do not support raw BEGIN/COMMIT SQL\n // through Drizzle's db.run(). Default to \"none\" because async\n // transaction callbacks are not reliably supported across sync\n // Drizzle drivers. Users can opt in to \"drizzle\" mode explicitly if\n // their runtime's db.transaction() handles async callbacks.\n if (isD1DatabaseBySessionName(db) || isDurableObjectBySessionName(db)) {\n return \"none\";\n }\n if (isSync) return \"sql\";\n return \"drizzle\";\n}\n\nfunction resolveSqliteClient(\n db: AnySqliteDatabase,\n): SqliteClientWithPrepare | undefined {\n const databaseWithClient = db as SqliteClientCarrier;\n const sqliteClient = databaseWithClient.$client;\n if (sqliteClient?.prepare === undefined) {\n return undefined;\n }\n return sqliteClient;\n}\n\nfunction getOrCreatePreparedStatement(\n cache: Map<string, PreparedAllStatement>,\n sqliteClient: SqliteClientWithPrepare,\n sqlText: string,\n cacheMax: number,\n): PreparedAllStatement {\n const cachedStatement = cache.get(sqlText);\n if (cachedStatement !== undefined) {\n // Promote to most-recently-used position for LRU eviction\n cache.delete(sqlText);\n cache.set(sqlText, cachedStatement);\n return cachedStatement;\n }\n\n const preparedStatement = sqliteClient.prepare(sqlText);\n cache.set(sqlText, preparedStatement);\n\n if (cache.size > cacheMax) {\n const oldestSqlText = cache.keys().next().value;\n if (typeof oldestSqlText === \"string\") {\n cache.delete(oldestSqlText);\n }\n }\n\n return preparedStatement;\n}\n\nasync function executeDrizzleQuery<TRow>(\n db: AnySqliteDatabase,\n query: SQL,\n): Promise<readonly TRow[]> {\n const rows = db.all(query);\n return (rows instanceof Promise ? await rows : rows) as readonly TRow[];\n}\n\nfunction createPreparedStatementExecutor(\n sqliteClient: SqliteClientWithPrepare,\n cache: Map<string, PreparedAllStatement>,\n sqlText: string,\n cacheMax: number,\n): PreparedSqlStatement {\n return {\n execute<TRow>(params: readonly unknown[]): Promise<readonly TRow[]> {\n const preparedStatement = getOrCreatePreparedStatement(\n cache,\n sqliteClient,\n sqlText,\n cacheMax,\n );\n const rows = preparedStatement.all(...params);\n return Promise.resolve(rows as readonly TRow[]);\n },\n };\n}\n\nexport function createSqliteExecutionAdapter(\n db: AnySqliteDatabase,\n statementCacheMaxOrOptions: number | SqliteExecutionAdapterOptions = {},\n): SqliteExecutionAdapter {\n const options: SqliteExecutionAdapterOptions =\n typeof statementCacheMaxOrOptions === \"number\"\n ? { statementCacheMax: statementCacheMaxOrOptions }\n : statementCacheMaxOrOptions;\n const statementCacheMax =\n options.statementCacheMax ?? DEFAULT_PREPARED_STATEMENT_CACHE_MAX;\n const profileHints = options.profileHints ?? {};\n\n const isSync = detectSyncProfile(db, profileHints);\n const sqliteClient = isSync ? resolveSqliteClient(db) : undefined;\n const transactionMode = detectTransactionMode(db, profileHints, isSync);\n\n const profile: SqliteExecutionProfile = {\n isSync,\n supportsCompiledExecution: sqliteClient !== undefined,\n transactionMode,\n };\n\n const compile = (query: SQL): CompiledSqlQuery =>\n compileQueryWithDialect(db, query, \"SQLite\");\n\n if (sqliteClient !== undefined) {\n const client = sqliteClient;\n const statementCache = new Map<string, PreparedAllStatement>();\n\n function executeCompiled<TRow>(\n compiledQuery: CompiledSqlQuery,\n ): Promise<readonly TRow[]> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n client,\n compiledQuery.sql,\n statementCacheMax,\n );\n const rows = preparedStatement.all(...compiledQuery.params);\n return Promise.resolve(rows as readonly TRow[]);\n }\n\n return {\n clearStatementCache() {\n statementCache.clear();\n },\n compile,\n execute<TRow>(query: SQL): Promise<readonly TRow[]> {\n const compiledQuery = compile(query);\n return executeCompiled<TRow>(compiledQuery);\n },\n executeCompiled,\n prepare(sqlText: string): PreparedSqlStatement {\n return createPreparedStatementExecutor(\n client,\n statementCache,\n sqlText,\n statementCacheMax,\n );\n },\n profile,\n };\n }\n\n return {\n clearStatementCache() {\n // No-op: no statement cache in async/D1 mode\n },\n compile,\n execute<TRow>(query: SQL): Promise<readonly TRow[]> {\n return executeDrizzleQuery<TRow>(db, query);\n },\n profile,\n };\n}\n","/**\n * SQLite backend adapter for TypeGraph.\n *\n * Works with any Drizzle SQLite database instance:\n * - better-sqlite3\n * - libsql / Turso\n * - Cloudflare D1\n * - bun:sqlite\n * - sql.js\n *\n * @example\n * ```typescript\n * import { drizzle } from \"drizzle-orm/better-sqlite3\";\n * import Database from \"better-sqlite3\";\n * import { createSqliteBackend, tables } from \"@nicia-ai/typegraph/sqlite\";\n *\n * const sqlite = new Database(\"app.db\");\n * const db = drizzle(sqlite);\n * const backend = createSqliteBackend(db, { tables });\n * ```\n */\nimport { getTableName, type SQL, sql } from \"drizzle-orm\";\n\nimport { BackendDisposedError, ConfigurationError } from \"../../errors\";\nimport type { SqlTableNames } from \"../../query/compiler/schema\";\nimport {\n type CreateVectorIndexParams,\n type DropVectorIndexParams,\n type GraphBackend,\n SQLITE_CAPABILITIES,\n type TransactionBackend,\n type TransactionOptions,\n} from \"../types\";\nimport {\n type AnySqliteDatabase,\n createSqliteExecutionAdapter,\n type SqliteExecutionAdapter,\n type SqliteExecutionProfileHints,\n} from \"./execution/sqlite-execution\";\nexport type { SqliteTransactionMode } from \"./execution/sqlite-execution\";\nimport { generateSqliteDDL } from \"./ddl\";\nimport { createCommonOperationBackend } from \"./operation-backend-core\";\nimport { createSqliteOperationStrategy } from \"./operations/strategy\";\nimport {\n createEdgeRowMapper,\n createNodeRowMapper,\n createSchemaVersionRowMapper,\n createUniqueRowMapper,\n nowIso,\n SQLITE_ROW_MAPPER_CONFIG,\n} from \"./row-mappers\";\nimport { type SqliteTables, tables as defaultTables } from \"./schema/sqlite\";\nimport {\n createSqliteVectorIndex,\n dropSqliteVectorIndex,\n type VectorIndexOptions,\n} from \"./vector-index\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Options for creating a SQLite backend.\n */\nexport type SqliteBackendOptions = Readonly<{\n /**\n * Custom table definitions. Use createSqliteTables() to customize table names.\n * Defaults to standard TypeGraph table names.\n */\n tables?: SqliteTables;\n /**\n * Optional execution profile hints used to avoid runtime driver reflection.\n * Set `transactionMode: \"none\"` for drivers that do not support transactions\n * (e.g. Cloudflare D1, Durable Objects).\n */\n executionProfile?: SqliteExecutionProfileHints;\n}>;\n\nconst SQLITE_MAX_BIND_PARAMETERS = 999;\nconst NODE_INSERT_PARAM_COUNT = 9;\nconst EDGE_INSERT_PARAM_COUNT = 12;\nconst SQLITE_NODE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(SQLITE_MAX_BIND_PARAMETERS / NODE_INSERT_PARAM_COUNT),\n);\nconst SQLITE_EDGE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(SQLITE_MAX_BIND_PARAMETERS / EDGE_INSERT_PARAM_COUNT),\n);\nconst SQLITE_GET_NODES_ID_CHUNK_SIZE = Math.max(\n 1,\n SQLITE_MAX_BIND_PARAMETERS - 2,\n);\nconst SQLITE_GET_EDGES_ID_CHUNK_SIZE = Math.max(\n 1,\n SQLITE_MAX_BIND_PARAMETERS - 1,\n);\nconst CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT = 3;\nconst SQLITE_CHECK_UNIQUE_BATCH_CHUNK_SIZE = Math.max(\n 1,\n SQLITE_MAX_BIND_PARAMETERS - CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT,\n);\n\ntype SerializedExecutionQueue = Readonly<{\n dispose: () => void;\n runExclusive: <T>(task: () => Promise<T>) => Promise<T>;\n}>;\n\n// ============================================================\n// Utilities\n// ============================================================\n\nconst toNodeRow = createNodeRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toEdgeRow = createEdgeRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toUniqueRow = createUniqueRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toSchemaVersionRow = createSchemaVersionRowMapper(SQLITE_ROW_MAPPER_CONFIG);\n\n/** A shared promise that never settles — used to absorb post-dispose work. */\nconst PENDING_FOREVER: Promise<never> = new Promise<never>(noop);\n\nfunction pendingForever<T>(): Promise<T> {\n return PENDING_FOREVER as Promise<T>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noop(): void {}\n\nfunction createSerializedExecutionQueue(): SerializedExecutionQueue {\n let tail: Promise<unknown> = Promise.resolve();\n let disposed = false;\n\n function isDisposed(): boolean {\n return disposed;\n }\n\n return {\n dispose() {\n disposed = true;\n },\n\n runExclusive<T>(task: () => Promise<T>): Promise<T> {\n if (isDisposed()) return Promise.reject(new BackendDisposedError());\n\n // When disposed, runTask returns a never-settling promise so that no\n // rejection propagates through the 7+ async wrappers between this\n // queue and the store-level caller. A rejection here would become an\n // unhandled rejection if the caller abandoned the promise during\n // teardown — and JavaScript offers no way to `.catch()` a rejection\n // at the bottom of a chain without every async wrapper above it also\n // creating an independently-unhandled rejected promise.\n //\n // The tradeoff: an active caller whose operation was queued before\n // dispose() will see a permanently-pending promise rather than a\n // BackendDisposedError. Post-dispose submissions (the check above)\n // still reject immediately since the caller actively holds that\n // promise.\n const runTask = async (): Promise<T> => {\n if (isDisposed()) return pendingForever<T>();\n try {\n return await task();\n } catch (error) {\n if (isDisposed()) return pendingForever<T>();\n throw error;\n }\n };\n const result = tail.then(runTask, runTask);\n tail = result.then(\n () => 0,\n () => 0,\n );\n return result;\n },\n };\n}\n\nfunction runWithSerializedQueue<T>(\n queue: SerializedExecutionQueue | undefined,\n task: () => Promise<T>,\n): Promise<T> {\n if (queue === undefined) return task();\n return queue.runExclusive(task);\n}\n\n// ============================================================\n// Backend Factory\n// ============================================================\n\n/**\n * Creates a TypeGraph backend for SQLite databases.\n *\n * Works with any Drizzle SQLite instance regardless of the underlying driver.\n *\n * @param db - A Drizzle SQLite database instance\n * @param options - Backend configuration\n * @returns A GraphBackend implementation\n */\ntype CreateSqliteOperationBackendOptions = Readonly<{\n capabilities: GraphBackend[\"capabilities\"];\n db: AnySqliteDatabase;\n executionAdapter: SqliteExecutionAdapter;\n operationStrategy: ReturnType<typeof createSqliteOperationStrategy>;\n serializedQueue?: SerializedExecutionQueue;\n tableNames: SqlTableNames;\n}>;\n\ntype CreateSqliteTransactionBackendOptions = Readonly<{\n capabilities: GraphBackend[\"capabilities\"];\n db: AnySqliteDatabase;\n executionAdapter?: SqliteExecutionAdapter;\n operationStrategy: ReturnType<typeof createSqliteOperationStrategy>;\n profileHints: SqliteExecutionProfileHints;\n tableNames: SqlTableNames;\n}>;\n\nfunction createSqliteOperationBackend(\n options: CreateSqliteOperationBackendOptions,\n): TransactionBackend {\n const {\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n serializedQueue,\n tableNames,\n } = options;\n\n function execGet<T>(query: SQL): Promise<T | undefined> {\n return runWithSerializedQueue(serializedQueue, async () => {\n const result = db.get(query);\n return (result instanceof Promise ? await result : result) as T | undefined;\n });\n }\n\n function execAll<T>(query: SQL): Promise<T[]> {\n return runWithSerializedQueue(serializedQueue, async () => {\n const result = db.all(query);\n return (result instanceof Promise ? await result : result) as T[];\n });\n }\n\n function execRun(query: SQL): Promise<void> {\n return runWithSerializedQueue(serializedQueue, async () => {\n const result = db.run(query);\n if (result instanceof Promise) await result;\n });\n }\n\n const commonBackend = createCommonOperationBackend({\n batchConfig: {\n checkUniqueBatchChunkSize: SQLITE_CHECK_UNIQUE_BATCH_CHUNK_SIZE,\n edgeInsertBatchSize: SQLITE_EDGE_INSERT_BATCH_SIZE,\n getEdgesChunkSize: SQLITE_GET_EDGES_ID_CHUNK_SIZE,\n getNodesChunkSize: SQLITE_GET_NODES_ID_CHUNK_SIZE,\n nodeInsertBatchSize: SQLITE_NODE_INSERT_BATCH_SIZE,\n },\n execution: {\n execAll,\n execGet,\n execRun,\n },\n nowIso,\n operationStrategy,\n rowMappers: {\n toEdgeRow,\n toNodeRow,\n toSchemaVersionRow,\n toUniqueRow,\n },\n });\n\n const executeCompiled = executionAdapter.executeCompiled;\n const executeRawMethod: Pick<TransactionBackend, \"executeRaw\"> =\n executeCompiled === undefined ?\n {}\n : {\n executeRaw<T>(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executeCompiled<T>({ params, sql: sqlText }),\n );\n },\n };\n\n const operationBackend: TransactionBackend = {\n ...commonBackend,\n ...executeRawMethod,\n capabilities,\n dialect: \"sqlite\",\n tableNames,\n\n createVectorIndex(params: CreateVectorIndexParams): Promise<void> {\n const indexOptions: VectorIndexOptions = {\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n fieldPath: params.fieldPath,\n dimensions: params.dimensions,\n indexType: params.indexType,\n metric: params.metric,\n ...(params.indexParams?.m === undefined\n ? {}\n : { hnswM: params.indexParams.m }),\n ...(params.indexParams?.efConstruction === undefined\n ? {}\n : { hnswEfConstruction: params.indexParams.efConstruction }),\n ...(params.indexParams?.lists === undefined\n ? {}\n : { ivfflatLists: params.indexParams.lists }),\n };\n\n const result = createSqliteVectorIndex(indexOptions);\n\n if (!result.success) {\n throw new Error(result.message ?? \"Failed to create SQLite vector index\");\n }\n return Promise.resolve();\n },\n\n dropVectorIndex(params: DropVectorIndexParams): Promise<void> {\n const result = dropSqliteVectorIndex(\n params.graphId,\n params.nodeKind,\n params.fieldPath,\n );\n if (!result.success) {\n throw new Error(result.message ?? \"Failed to drop SQLite vector index\");\n }\n return Promise.resolve();\n },\n\n // === Query Execution ===\n\n async execute<T>(query: SQL): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executionAdapter.execute<T>(query),\n );\n },\n\n compileSql(query: SQL): Readonly<{ sql: string; params: readonly unknown[] }> {\n return executionAdapter.compile(query);\n },\n };\n\n return operationBackend;\n}\n\nexport function createSqliteBackend(\n db: AnySqliteDatabase,\n options: SqliteBackendOptions = {},\n): GraphBackend {\n const tables = options.tables ?? defaultTables;\n const profileHints = options.executionProfile ?? {};\n const executionAdapter = createSqliteExecutionAdapter(db, { profileHints });\n const { isSync, transactionMode } = executionAdapter.profile;\n const capabilities =\n transactionMode === \"none\"\n ? { ...SQLITE_CAPABILITIES, transactions: false }\n : SQLITE_CAPABILITIES;\n\n const tableNames: SqlTableNames = {\n nodes: getTableName(tables.nodes),\n edges: getTableName(tables.edges),\n embeddings: getTableName(tables.embeddings),\n };\n const operationStrategy = createSqliteOperationStrategy(tables);\n const serializedQueue = isSync ? createSerializedExecutionQueue() : undefined;\n const operations = createSqliteOperationBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n tableNames,\n ...(serializedQueue === undefined ? {} : { serializedQueue }),\n });\n\n const backend: GraphBackend = {\n ...operations,\n\n bootstrapTables(): Promise<void> {\n const statements = generateSqliteDDL(tables);\n for (const statement of statements) {\n db.run(sql.raw(statement));\n }\n return Promise.resolve();\n },\n\n async setActiveSchema(graphId: string, version: number): Promise<void> {\n await backend.transaction(async (txBackend) => {\n await txBackend.setActiveSchema(graphId, version);\n });\n },\n\n async transaction<T>(\n fn: (tx: TransactionBackend) => Promise<T>,\n _options?: TransactionOptions,\n ): Promise<T> {\n if (transactionMode === \"none\") {\n throw new ConfigurationError(\n \"This SQLite backend does not support atomic transactions. \" +\n \"Operations within a transaction are not rolled back on failure. \" +\n \"Use backend.capabilities.transactions to check for transaction support, \" +\n \"or use individual operations with manual error handling.\",\n {\n backend: \"sqlite\",\n capability: \"transactions\",\n supportsTransactions: false,\n },\n );\n }\n\n if (transactionMode === \"sql\") {\n return runWithSerializedQueue(serializedQueue, async () => {\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n profileHints: { isSync: true },\n tableNames,\n });\n db.run(sql`BEGIN`);\n\n try {\n const result = await fn(txBackend);\n db.run(sql`COMMIT`);\n return result;\n } catch (error) {\n db.run(sql`ROLLBACK`);\n throw error;\n }\n });\n }\n\n // transactionMode === \"drizzle\"\n return runWithSerializedQueue(serializedQueue, async () =>\n db.transaction(async (tx) => {\n const txBackend = createTransactionBackend({\n capabilities,\n db: tx as AnySqliteDatabase,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n });\n return fn(txBackend);\n }) as Promise<T>,\n );\n },\n\n close(): Promise<void> {\n serializedQueue?.dispose();\n return Promise.resolve();\n },\n };\n\n return backend;\n}\n\nfunction createTransactionBackend(\n options: CreateSqliteTransactionBackendOptions,\n): TransactionBackend {\n const txExecutionAdapter =\n options.executionAdapter ??\n createSqliteExecutionAdapter(options.db, {\n profileHints: options.profileHints,\n });\n\n return createSqliteOperationBackend({\n capabilities: options.capabilities,\n db: options.db,\n executionAdapter: txExecutionAdapter,\n operationStrategy: options.operationStrategy,\n tableNames: options.tableNames,\n });\n}\n\n// Re-export schema utilities\nexport type { SqliteTableNames,SqliteTables } from \"./schema/sqlite\";\nexport { createSqliteTables, tables } from \"./schema/sqlite\";\n"]}
@@ -316,6 +316,20 @@ var CompilerInvariantError = class extends TypeGraphError {
316
316
  this.name = "CompilerInvariantError";
317
317
  }
318
318
  };
319
+ var BackendDisposedError = class extends TypeGraphError {
320
+ constructor(options) {
321
+ super(
322
+ "Backend has been disposed \u2014 the underlying database connection is no longer available",
323
+ "BACKEND_DISPOSED",
324
+ {
325
+ category: "system",
326
+ suggestion: "Ensure all store operations complete before calling backend.close(). In test environments, await store teardown before resetting the database.",
327
+ cause: options?.cause
328
+ }
329
+ );
330
+ this.name = "BackendDisposedError";
331
+ }
332
+ };
319
333
  function isTypeGraphError(error) {
320
334
  return error instanceof TypeGraphError;
321
335
  }
@@ -333,6 +347,7 @@ function getErrorSuggestion(error) {
333
347
  return isTypeGraphError(error) ? error.suggestion : void 0;
334
348
  }
335
349
 
350
+ exports.BackendDisposedError = BackendDisposedError;
336
351
  exports.CardinalityError = CardinalityError;
337
352
  exports.CompilerInvariantError = CompilerInvariantError;
338
353
  exports.ConfigurationError = ConfigurationError;
@@ -357,5 +372,5 @@ exports.isConstraintError = isConstraintError;
357
372
  exports.isSystemError = isSystemError;
358
373
  exports.isTypeGraphError = isTypeGraphError;
359
374
  exports.isUserRecoverable = isUserRecoverable;
360
- //# sourceMappingURL=chunk-44SXEVF4.cjs.map
361
- //# sourceMappingURL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TypeGraphError with:\n * - `code`: Machine-readable error code for programmatic handling\n * - `category`: Classification for error handling strategies\n * - `suggestion`: Optional recovery guidance for users\n * - `details`: Structured context about the error\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({ name: \"\" });\n * } catch (error) {\n * if (isTypeGraphError(error)) {\n * console.error(error.toUserMessage());\n * if (isUserRecoverable(error)) {\n * // Show to user for correction\n * }\n * }\n * }\n * ```\n */\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Error category for programmatic handling.\n *\n * - `user`: Caused by invalid input or incorrect usage. Recoverable by fixing input.\n * - `constraint`: Business rule or schema constraint violation. Recoverable by changing data.\n * - `system`: Internal error or infrastructure issue. May require investigation or retry.\n */\nexport type ErrorCategory = \"user\" | \"constraint\" | \"system\";\n\n/**\n * Options for TypeGraphError constructor.\n */\nexport type TypeGraphErrorOptions = Readonly<{\n /** Structured context about the error */\n details?: Record<string, unknown>;\n /** Error category for handling strategies */\n category: ErrorCategory;\n /** Recovery guidance for users */\n suggestion?: string;\n /** Underlying cause of the error */\n cause?: unknown;\n}>;\n\nfunction formatCause(cause: unknown): string {\n if (cause instanceof Error) {\n return cause.stack ?? cause.message;\n }\n if (typeof cause === \"string\") {\n return cause;\n }\n if (\n typeof cause === \"number\" ||\n typeof cause === \"boolean\" ||\n typeof cause === \"bigint\"\n ) {\n return String(cause);\n }\n if (typeof cause === \"symbol\") {\n return cause.description ?? \"Symbol\";\n }\n if (cause === undefined) {\n return \"Unknown cause\";\n }\n\n try {\n return JSON.stringify(cause);\n } catch (error) {\n return `Unserializable cause: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`;\n }\n}\n\n// ============================================================\n// Base Error\n// ============================================================\n\n/**\n * Base error class for all TypeGraph errors.\n *\n * Provides structured error information for both programmatic handling\n * and user-friendly messages.\n */\nexport class TypeGraphError extends Error {\n /** Machine-readable error code (e.g., \"VALIDATION_ERROR\") */\n readonly code: string;\n\n /** Error category for handling strategies */\n readonly category: ErrorCategory;\n\n /** Structured context about the error */\n readonly details: Readonly<Record<string, unknown>>;\n\n /** Recovery guidance for users */\n readonly suggestion?: string;\n\n constructor(message: string, code: string, options: TypeGraphErrorOptions) {\n super(message, options.cause ? { cause: options.cause } : undefined);\n this.name = \"TypeGraphError\";\n this.code = code;\n this.category = options.category;\n this.details = Object.freeze(options.details ?? {});\n if (options.suggestion !== undefined) {\n this.suggestion = options.suggestion;\n }\n }\n\n /**\n * Returns a user-friendly error message with suggestion if available.\n */\n toUserMessage(): string {\n if (this.suggestion) {\n return `${this.message}\\n\\nSuggestion: ${this.suggestion}`;\n }\n return this.message;\n }\n\n /**\n * Returns a detailed string representation for logging.\n */\n toLogString(): string {\n const lines = [\n `[${this.code}] ${this.message}`,\n ` Category: ${this.category}`,\n ];\n\n if (this.suggestion) {\n lines.push(` Suggestion: ${this.suggestion}`);\n }\n\n const detailKeys = Object.keys(this.details);\n if (detailKeys.length > 0) {\n lines.push(` Details: ${JSON.stringify(this.details)}`);\n }\n\n if (this.cause) {\n lines.push(` Cause: ${formatCause(this.cause)}`);\n }\n\n return lines.join(\"\\n\");\n }\n}\n\n// ============================================================\n// Validation Errors (category: \"user\")\n// ============================================================\n\n/**\n * Validation issue from Zod or custom validation.\n */\nexport type ValidationIssue = Readonly<{\n /** Path to the invalid field (e.g., \"address.city\") */\n path: string;\n /** Human-readable error message */\n message: string;\n /** Zod error code if from Zod validation */\n code?: string;\n}>;\n\n/**\n * Details for ValidationError.\n */\nexport type ValidationErrorDetails = Readonly<{\n /** Type of entity being validated */\n entityType?: \"node\" | \"edge\";\n /** Kind/type name of the entity */\n kind?: string;\n /** Operation being performed */\n operation?: \"create\" | \"update\";\n /** Entity ID if updating */\n id?: string;\n /** Individual validation issues */\n issues: readonly ValidationIssue[];\n}>;\n\n/**\n * Thrown when schema validation fails during node or edge operations.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({ email: \"invalid\" });\n * } catch (error) {\n * if (error instanceof ValidationError) {\n * console.log(error.details.issues);\n * // [{ path: \"email\", message: \"Invalid email\" }]\n * }\n * }\n * ```\n */\nexport class ValidationError extends TypeGraphError {\n declare readonly details: ValidationErrorDetails;\n\n constructor(\n message: string,\n details: ValidationErrorDetails,\n options?: { cause?: unknown; suggestion?: string },\n ) {\n const fieldList =\n details.issues.length > 0 ?\n details.issues.map((index) => index.path || \"(root)\").join(\", \")\n : \"unknown\";\n\n super(message, \"VALIDATION_ERROR\", {\n details,\n category: \"user\",\n suggestion:\n options?.suggestion ??\n `Check the following fields: ${fieldList}. See error.details.issues for specific validation failures.`,\n cause: options?.cause,\n });\n this.name = \"ValidationError\";\n }\n}\n\n// ============================================================\n// Not Found Errors (category: \"user\")\n// ============================================================\n\n/**\n * Thrown when a node is not found.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.get(\"nonexistent-id\");\n * } catch (error) {\n * if (error instanceof NodeNotFoundError) {\n * console.log(error.details.kind, error.details.id);\n * }\n * }\n * ```\n */\nexport class NodeNotFoundError extends TypeGraphError {\n constructor(kind: string, id: string, options?: { cause?: unknown }) {\n super(`Node not found: ${kind}/${id}`, \"NODE_NOT_FOUND\", {\n details: { kind, id },\n category: \"user\",\n suggestion: `Verify the node ID \"${id}\" exists and has not been deleted.`,\n cause: options?.cause,\n });\n this.name = \"NodeNotFoundError\";\n }\n}\n\n/**\n * Thrown when an edge is not found.\n */\nexport class EdgeNotFoundError extends TypeGraphError {\n constructor(kind: string, id: string, options?: { cause?: unknown }) {\n super(`Edge not found: ${kind}/${id}`, \"EDGE_NOT_FOUND\", {\n details: { kind, id },\n category: \"user\",\n suggestion: `Verify the edge ID \"${id}\" exists and has not been deleted.`,\n cause: options?.cause,\n });\n this.name = \"EdgeNotFoundError\";\n }\n}\n\n/**\n * Thrown when a kind is not found in the graph registry.\n */\nexport class KindNotFoundError extends TypeGraphError {\n constructor(\n kind: string,\n type: \"node\" | \"edge\",\n options?: { cause?: unknown },\n ) {\n super(\n `${type === \"node\" ? \"Node\" : \"Edge\"} kind not found: ${kind}`,\n \"KIND_NOT_FOUND\",\n {\n details: { kind, type },\n category: \"user\",\n suggestion: `Verify \"${kind}\" is defined in your graph schema and spelled correctly.`,\n cause: options?.cause,\n },\n );\n this.name = \"KindNotFoundError\";\n }\n}\n\n/**\n * Thrown when a uniqueness constraint name is not found on a node kind.\n */\nexport class NodeConstraintNotFoundError extends TypeGraphError {\n constructor(\n constraintName: string,\n kind: string,\n options?: { cause?: unknown },\n ) {\n super(\n `Constraint not found: \"${constraintName}\" on node kind \"${kind}\"`,\n \"CONSTRAINT_NOT_FOUND\",\n {\n details: { constraintName, kind },\n category: \"user\",\n suggestion: `Verify the constraint name \"${constraintName}\" is defined in the unique constraints for \"${kind}\".`,\n cause: options?.cause,\n },\n );\n this.name = \"NodeConstraintNotFoundError\";\n }\n}\n\n// ============================================================\n// Constraint Errors (category: \"constraint\")\n// ============================================================\n\n/**\n * Thrown when edge endpoint node does not exist or is deleted.\n */\nexport class EndpointNotFoundError extends TypeGraphError {\n constructor(\n details: Readonly<{\n edgeKind: string;\n endpoint: \"from\" | \"to\";\n nodeKind: string;\n nodeId: string;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Endpoint node not found for edge \"${details.edgeKind}\": ${details.nodeKind}/${details.nodeId} (${details.endpoint})`,\n \"ENDPOINT_NOT_FOUND\",\n {\n details,\n category: \"constraint\",\n suggestion: `Ensure the ${details.endpoint} node exists before creating the edge.`,\n cause: options?.cause,\n },\n );\n this.name = \"EndpointNotFoundError\";\n }\n}\n\n/**\n * Thrown when edge endpoint has wrong node type.\n */\nexport class EndpointError extends TypeGraphError {\n constructor(\n details: Readonly<{\n edgeKind: string;\n endpoint: \"from\" | \"to\";\n actualKind: string;\n expectedKinds: readonly string[];\n }>,\n options?: { cause?: unknown },\n ) {\n const expected = details.expectedKinds.join(\" | \");\n super(\n `Invalid ${details.endpoint} endpoint for edge \"${details.edgeKind}\": got \"${details.actualKind}\", expected ${expected}`,\n \"ENDPOINT_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion: `Use a node of type ${expected} as the ${details.endpoint} endpoint.`,\n cause: options?.cause,\n },\n );\n this.name = \"EndpointError\";\n }\n}\n\n/**\n * Thrown when uniqueness constraint is violated.\n */\nexport class UniquenessError extends TypeGraphError {\n constructor(\n details: Readonly<{\n constraintName: string;\n kind: string;\n existingId: string;\n newId: string;\n fields: readonly string[];\n }>,\n options?: { cause?: unknown },\n ) {\n const fieldList = details.fields.join(\", \");\n super(\n `Uniqueness violation on \"${details.kind}\": constraint \"${details.constraintName}\" (fields: ${fieldList}) conflicts with existing node ${details.existingId}`,\n \"UNIQUENESS_VIOLATION\",\n {\n details,\n category: \"constraint\",\n suggestion: `Change the values for fields [${fieldList}] to be unique, or update the existing node ${details.existingId} instead.`,\n cause: options?.cause,\n },\n );\n this.name = \"UniquenessError\";\n }\n}\n\n/**\n * Thrown when cardinality constraint is violated.\n */\nexport class CardinalityError extends TypeGraphError {\n constructor(\n details: Readonly<{\n edgeKind: string;\n fromKind: string;\n fromId: string;\n cardinality: string;\n existingCount: number;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Cardinality violation: \"${details.edgeKind}\" from ${details.fromKind}/${details.fromId} allows \"${details.cardinality}\" but ${details.existingCount} edge(s) already exist`,\n \"CARDINALITY_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion:\n details.cardinality === \"one\" || details.cardinality === \"unique\" ?\n `Delete the existing edge before creating a new one, or use cardinality \"many\".`\n : `Check if the cardinality constraint \"${details.cardinality}\" is correct for your use case.`,\n cause: options?.cause,\n },\n );\n this.name = \"CardinalityError\";\n }\n}\n\n/**\n * Thrown when disjointness constraint is violated.\n *\n * Disjoint types cannot share the same ID - a node cannot be both\n * a Person and an Organization if they are declared disjoint.\n */\nexport class DisjointError extends TypeGraphError {\n constructor(\n details: Readonly<{\n nodeId: string;\n attemptedKind: string;\n conflictingKind: string;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Disjoint constraint violation: cannot create ${details.attemptedKind} with ID \"${details.nodeId}\" - conflicts with existing ${details.conflictingKind}`,\n \"DISJOINT_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion: `Use a different ID for the new ${details.attemptedKind} node, or delete the existing ${details.conflictingKind}/${details.nodeId} first.`,\n cause: options?.cause,\n },\n );\n this.name = \"DisjointError\";\n }\n}\n\n/**\n * Thrown when deletion is blocked due to existing edges (restrict behavior).\n */\nexport class RestrictedDeleteError extends TypeGraphError {\n constructor(\n details: Readonly<{\n nodeKind: string;\n nodeId: string;\n edgeCount: number;\n edgeKinds: readonly string[];\n }>,\n options?: { cause?: unknown },\n ) {\n const edgeList = details.edgeKinds.join(\", \");\n super(\n `Cannot delete ${details.nodeKind}/${details.nodeId}: ${details.edgeCount} connected edge(s) exist (${edgeList})`,\n \"RESTRICTED_DELETE\",\n {\n details,\n category: \"constraint\",\n suggestion: `Delete the connected edges first, or change onDelete behavior to \"cascade\" (auto-delete edges) or \"disconnect\" (soft-delete edges).`,\n cause: options?.cause,\n },\n );\n this.name = \"RestrictedDeleteError\";\n }\n}\n\n// ============================================================\n// Concurrency Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when optimistic locking detects a concurrent modification.\n *\n * This occurs when two operations try to update the same entity simultaneously.\n * The operation with the stale version fails.\n */\nexport class VersionConflictError extends TypeGraphError {\n constructor(\n details: Readonly<{\n kind: string;\n id: string;\n expectedVersion: number;\n actualVersion: number;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Version conflict on ${details.kind}/${details.id}: expected version ${details.expectedVersion}, found ${details.actualVersion}`,\n \"VERSION_CONFLICT\",\n {\n details,\n category: \"system\",\n suggestion: `Fetch the latest version of the entity and retry the operation. This error indicates concurrent modification.`,\n cause: options?.cause,\n },\n );\n this.name = \"VersionConflictError\";\n }\n}\n\n// ============================================================\n// Schema Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when the schema in code doesn't match the schema in the database.\n */\nexport class SchemaMismatchError extends TypeGraphError {\n constructor(\n details: Readonly<{\n graphId: string;\n expectedHash: string;\n actualHash: string;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema mismatch for graph \"${details.graphId}\": code schema differs from database schema`,\n \"SCHEMA_MISMATCH\",\n {\n details,\n category: \"system\",\n suggestion: `Run schema migration to update the database, or use createStoreWithSchema() for automatic migration.`,\n cause: options?.cause,\n },\n );\n this.name = \"SchemaMismatchError\";\n }\n}\n\n/**\n * Thrown when schema migration fails.\n */\nexport class MigrationError extends TypeGraphError {\n constructor(\n message: string,\n details: Readonly<{\n graphId: string;\n fromVersion: number;\n toVersion: number;\n reason?: string;\n }>,\n options?: { cause?: unknown },\n ) {\n super(message, \"MIGRATION_ERROR\", {\n details,\n category: \"system\",\n suggestion: `Review the schema changes and ensure they are backwards compatible, or implement a data migration.`,\n cause: options?.cause,\n });\n this.name = \"MigrationError\";\n }\n}\n\n// ============================================================\n// Configuration Errors (category: \"user\")\n// ============================================================\n\n/**\n * Thrown when graph configuration is invalid.\n *\n * This includes invalid schema definitions, ontology conflicts,\n * and other configuration issues detected at graph creation time.\n */\nexport class ConfigurationError extends TypeGraphError {\n constructor(\n message: string,\n details: Record<string, unknown> = {},\n options?: { cause?: unknown; suggestion?: string },\n ) {\n super(message, \"CONFIGURATION_ERROR\", {\n details,\n category: \"user\",\n suggestion:\n options?.suggestion ?? `Review your graph definition for errors.`,\n cause: options?.cause,\n });\n this.name = \"ConfigurationError\";\n }\n}\n\n// ============================================================\n// Database Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a database operation fails unexpectedly.\n *\n * This indicates a system-level failure in the database backend,\n * not a user-recoverable error.\n */\nexport class DatabaseOperationError extends TypeGraphError {\n constructor(\n message: string,\n details: Readonly<{ operation: string; entity: string }>,\n options?: { cause?: unknown },\n ) {\n super(message, \"DATABASE_OPERATION_ERROR\", {\n details,\n category: \"system\",\n suggestion: `This is a system-level database error. Check the database connection and retry the operation. If the problem persists, investigate the underlying cause.`,\n cause: options?.cause,\n });\n this.name = \"DatabaseOperationError\";\n }\n}\n\n// ============================================================\n// Query Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a query predicate cannot be compiled for the target database.\n */\nexport class UnsupportedPredicateError extends TypeGraphError {\n constructor(\n message: string,\n details: Readonly<Record<string, unknown>> = {},\n options?: { cause?: unknown; suggestion?: string },\n ) {\n super(message, \"UNSUPPORTED_PREDICATE\", {\n details,\n category: \"system\",\n suggestion:\n options?.suggestion ??\n `This predicate may not be supported by your database backend. Check the documentation for supported predicates.`,\n cause: options?.cause,\n });\n this.name = \"UnsupportedPredicateError\";\n }\n}\n\n// ============================================================\n// Compiler Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a compiler invariant is violated.\n *\n * This indicates a bug in the query compiler — the compiler reached\n * a state that should be unreachable. These errors are not user-recoverable.\n */\nexport class CompilerInvariantError extends TypeGraphError {\n constructor(\n message: string,\n details?: Readonly<Record<string, unknown>>,\n options?: { cause?: unknown },\n ) {\n super(message, \"COMPILER_INVARIANT_ERROR\", {\n details: details ?? {},\n category: \"system\",\n suggestion: `This is an internal compiler error. Please report it as a bug with the query that triggered it.`,\n cause: options?.cause,\n });\n this.name = \"CompilerInvariantError\";\n }\n}\n\n// ============================================================\n// Lifecycle Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when an operation is attempted on a backend that has been disposed.\n *\n * This typically occurs during runtime teardown — for example, when a\n * Cloudflare Workers test runner resets Durable Object storage while\n * the TypeGraph backend still has queued operations.\n */\nexport class BackendDisposedError extends TypeGraphError {\n constructor(options?: { cause?: unknown }) {\n super(\n \"Backend has been disposed — the underlying database connection is no longer available\",\n \"BACKEND_DISPOSED\",\n {\n category: \"system\",\n suggestion:\n \"Ensure all store operations complete before calling backend.close(). \" +\n \"In test environments, await store teardown before resetting the database.\",\n cause: options?.cause,\n },\n );\n this.name = \"BackendDisposedError\";\n }\n}\n\n// ============================================================\n// Utility Functions\n// ============================================================\n\n/**\n * Type guard for TypeGraphError.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({});\n * } catch (error) {\n * if (isTypeGraphError(error)) {\n * console.log(error.code, error.category);\n * }\n * }\n * ```\n */\nexport function isTypeGraphError(error: unknown): error is TypeGraphError {\n return error instanceof TypeGraphError;\n}\n\n/**\n * Check if error is recoverable by user action (user or constraint error).\n *\n * User-recoverable errors can typically be resolved by:\n * - Fixing invalid input data\n * - Using different IDs or values\n * - Deleting conflicting data first\n *\n * @example\n * ```typescript\n * if (isUserRecoverable(error)) {\n * showErrorToUser(error.toUserMessage());\n * } else {\n * logAndAlertOps(error);\n * }\n * ```\n */\nexport function isUserRecoverable(error: unknown): boolean {\n if (!isTypeGraphError(error)) return false;\n return error.category === \"user\" || error.category === \"constraint\";\n}\n\n/**\n * Check if error indicates a system/infrastructure issue.\n *\n * System errors typically require:\n * - Retry logic (for transient failures)\n * - Investigation (for persistent failures)\n * - Ops team notification\n */\nexport function isSystemError(error: unknown): boolean {\n return isTypeGraphError(error) && error.category === \"system\";\n}\n\n/**\n * Check if error is a constraint violation.\n */\nexport function isConstraintError(error: unknown): boolean {\n return isTypeGraphError(error) && error.category === \"constraint\";\n}\n\n/**\n * Extract suggestion from error if available.\n */\nexport function getErrorSuggestion(error: unknown): string | undefined {\n return isTypeGraphError(error) ? error.suggestion : undefined;\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { nowIso, getNodeKinds, getEdgeKinds } from './chunk-IRFD3MEU.js';
2
- import { ValidationError, MigrationError, DatabaseOperationError } from './chunk-SJ2QMDXY.js';
1
+ import { nowIso, getNodeKinds, getEdgeKinds } from './chunk-G5CYWKRF.js';
2
+ import { ValidationError, MigrationError, DatabaseOperationError } from './chunk-WFMTAEEN.js';
3
3
  import { z } from 'zod';
4
4
 
5
5
  // src/ontology/types.ts
@@ -1374,5 +1374,5 @@ async function getSchemaChanges(backend, graph) {
1374
1374
  }
1375
1375
 
1376
1376
  export { KindRegistry, META_EDGE_BRAND, META_EDGE_BROADER, META_EDGE_DIFFERENT_FROM, META_EDGE_DISJOINT_WITH, META_EDGE_EQUIVALENT_TO, META_EDGE_HAS_PART, META_EDGE_IMPLIES, META_EDGE_INVERSE_OF, META_EDGE_NARROWER, META_EDGE_PART_OF, META_EDGE_RELATED_TO, META_EDGE_SAME_AS, META_EDGE_SUB_CLASS_OF, computeClosuresFromOntology, computeSchemaDiff, computeSchemaHash, createEmptyClosures, createValidationError, deserializeWherePredicate, ensureSchema, getActiveSchema, getMigrationActions, getSchemaChanges, initializeSchema, isBackwardsCompatible, isMetaEdge, isSchemaInitialized, migrateSchema, rollbackSchema, serializeSchema, validateEdgeProps, validateNodeProps, validateProps, wrapZodError };
1377
- //# sourceMappingURL=chunk-L4ON6RJF.js.map
1378
- //# sourceMappingURL=chunk-L4ON6RJF.js.map
1377
+ //# sourceMappingURL=chunk-W6M7XWKX.js.map
1378
+ //# sourceMappingURL=chunk-W6M7XWKX.js.map