@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.
- package/dist/backend/postgres/index.cjs +28 -28
- package/dist/backend/postgres/index.js +3 -3
- package/dist/backend/sqlite/index.cjs +13 -13
- package/dist/backend/sqlite/index.js +3 -3
- package/dist/backend/sqlite/local.cjs +10 -10
- package/dist/backend/sqlite/local.cjs.map +1 -1
- package/dist/backend/sqlite/local.js +6 -6
- package/dist/backend/sqlite/local.js.map +1 -1
- package/dist/{chunk-CRMN2NOM.cjs → chunk-2UTJRP4F.cjs} +14 -14
- package/dist/{chunk-CRMN2NOM.cjs.map → chunk-2UTJRP4F.cjs.map} +1 -1
- package/dist/{chunk-NI2GV74U.cjs → chunk-5GZMPJOP.cjs} +6 -6
- package/dist/{chunk-NI2GV74U.cjs.map → chunk-5GZMPJOP.cjs.map} +1 -1
- package/dist/{chunk-56RQFK7U.cjs → chunk-5H74QKKF.cjs} +50 -26
- package/dist/chunk-5H74QKKF.cjs.map +1 -0
- package/dist/{chunk-HWWF3FOP.js → chunk-7ZVPFJLQ.js} +3 -3
- package/dist/{chunk-HWWF3FOP.js.map → chunk-7ZVPFJLQ.js.map} +1 -1
- package/dist/{chunk-IRFD3MEU.js → chunk-G5CYWKRF.js} +3 -3
- package/dist/{chunk-IRFD3MEU.js.map → chunk-G5CYWKRF.js.map} +1 -1
- package/dist/{chunk-XZBAGJJH.js → chunk-IRS2C6GN.js} +36 -12
- package/dist/chunk-IRS2C6GN.js.map +1 -0
- package/dist/{chunk-44SXEVF4.cjs → chunk-O5PST6TB.cjs} +17 -2
- package/dist/chunk-O5PST6TB.cjs.map +1 -0
- package/dist/{chunk-L4ON6RJF.js → chunk-W6M7XWKX.js} +4 -4
- package/dist/{chunk-L4ON6RJF.js.map → chunk-W6M7XWKX.js.map} +1 -1
- package/dist/{chunk-SJ2QMDXY.js → chunk-WFMTAEEN.js} +17 -3
- package/dist/chunk-WFMTAEEN.js.map +1 -0
- package/dist/{chunk-3HQLOKS5.cjs → chunk-X33WV2UF.cjs} +14 -14
- package/dist/{chunk-3HQLOKS5.cjs.map → chunk-X33WV2UF.cjs.map} +1 -1
- package/dist/{index-QTnQwakS.d.cts → index-DXkEXpNz.d.cts} +13 -1
- package/dist/{index-QTnQwakS.d.ts → index-DXkEXpNz.d.ts} +13 -1
- package/dist/index.cjs +220 -216
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +6 -6
- package/dist/interchange/index.cjs +7 -7
- package/dist/interchange/index.js +2 -2
- package/dist/schema/index.cjs +22 -22
- package/dist/schema/index.d.cts +1 -1
- package/dist/schema/index.d.ts +1 -1
- package/dist/schema/index.js +4 -4
- package/package.json +1 -1
- package/dist/chunk-44SXEVF4.cjs.map +0 -1
- package/dist/chunk-56RQFK7U.cjs.map +0 -1
- package/dist/chunk-SJ2QMDXY.js.map +0 -1
- package/dist/chunk-XZBAGJJH.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkO5PST6TB_cjs = require('./chunk-O5PST6TB.cjs');
|
|
4
4
|
|
|
5
5
|
// src/core/types.ts
|
|
6
6
|
var NODE_TYPE_BRAND = "__nodeType";
|
|
@@ -21,7 +21,7 @@ function validateConstraintNarrowing(name, edgeType, registration) {
|
|
|
21
21
|
const builtInFromNames = new Set(edgeType.from.map((n) => n.kind));
|
|
22
22
|
for (const fromNode of registration.from) {
|
|
23
23
|
if (!builtInFromNames.has(fromNode.kind)) {
|
|
24
|
-
throw new
|
|
24
|
+
throw new chunkO5PST6TB_cjs.ConfigurationError(
|
|
25
25
|
`Edge "${name}" registration has 'from' kind "${fromNode.kind}" not in edge's built-in domain: [${[...builtInFromNames].join(", ")}]`,
|
|
26
26
|
{
|
|
27
27
|
edgeName: name,
|
|
@@ -37,7 +37,7 @@ function validateConstraintNarrowing(name, edgeType, registration) {
|
|
|
37
37
|
const builtInToNames = new Set(edgeType.to.map((n) => n.kind));
|
|
38
38
|
for (const toNode of registration.to) {
|
|
39
39
|
if (!builtInToNames.has(toNode.kind)) {
|
|
40
|
-
throw new
|
|
40
|
+
throw new chunkO5PST6TB_cjs.ConfigurationError(
|
|
41
41
|
`Edge "${name}" registration has 'to' kind "${toNode.kind}" not in edge's built-in range: [${[...builtInToNames].join(", ")}]`,
|
|
42
42
|
{
|
|
43
43
|
edgeName: name,
|
|
@@ -107,7 +107,7 @@ function isValidIsoDate(value) {
|
|
|
107
107
|
}
|
|
108
108
|
function validateIsoDate(value, fieldName) {
|
|
109
109
|
if (!isValidIsoDate(value)) {
|
|
110
|
-
throw new
|
|
110
|
+
throw new chunkO5PST6TB_cjs.ValidationError(
|
|
111
111
|
`Invalid ISO 8601 datetime for "${fieldName}": "${value}". Expected format: YYYY-MM-DDTHH:mm:ss.sssZ`,
|
|
112
112
|
{
|
|
113
113
|
issues: [
|
|
@@ -143,5 +143,5 @@ exports.isGraphDef = isGraphDef;
|
|
|
143
143
|
exports.isNodeType = isNodeType;
|
|
144
144
|
exports.nowIso = nowIso;
|
|
145
145
|
exports.validateOptionalIsoDate = validateOptionalIsoDate;
|
|
146
|
-
//# sourceMappingURL=chunk-
|
|
147
|
-
//# sourceMappingURL=chunk-
|
|
146
|
+
//# sourceMappingURL=chunk-5GZMPJOP.cjs.map
|
|
147
|
+
//# sourceMappingURL=chunk-5GZMPJOP.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/types.ts","../src/core/define-graph.ts","../src/utils/date.ts"],"names":["ConfigurationError","ValidationError"],"mappings":";;;;;AAOO,IAAM,eAAA,GAAkB;AAGxB,IAAM,eAAA,GAAkB;AA0PxB,SAAS,WAAW,KAAA,EAAmC;AAC5D,EAAA,OACE,OAAO,UAAU,QAAA,IACjB,KAAA,KAAU,QACV,eAAA,IAAmB,KAAA,IAClB,KAAA,CAAkC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,aACd,KAAA,EACwC;AACxC,EAAA,OAAO,MAAA,CAAO,IAAA,CAAK,KAAA,CAAM,KAAK,CAAA;AAChC;;;AChUA,IAAM,gBAAA,GAAmB,sDAAA;AAQlB,SAAS,eAAe,KAAA,EAAwB;AACrD,EAAA,IAAI,CAAC,gBAAA,CAAiB,IAAA,CAAK,KAAK,CAAA,EAAG;AACjC,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,IAAA,GAAO,IAAI,IAAA,CAAK,KAAK,CAAA;AAC3B,EAAA,OAAO,CAAC,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,SAAS,CAAA;AACrC;AAWO,SAAS,eAAA,CAAgB,OAAe,SAAA,EAA2B;AACxE,EAAA,IAAI,CAAC,cAAA,CAAe,KAAK,CAAA,EAAG;AAC1B,IAAA,MAAM,IAAIC,iCAAA;AAAA,MACR,CAAA,+BAAA,EAAkC,SAAS,CAAA,IAAA,EAAO,KAAK,CAAA,4CAAA,CAAA;AAAA,MAEvD;AAAA,QACE,MAAA,EAAQ;AAAA,UACN;AAAA,YACE,IAAA,EAAM,SAAA;AAAA,YACN,OAAA,EAAS,+EAA+E,KAAK,CAAA,CAAA;AAAA;AAC/F;AACF,OACF;AAAA,MACA;AAAA,QACE,UAAA,EAAY,CAAA,iEAAA;AAAA;AACd,KACF;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;AAMO,SAAS,uBAAA,CACd,OACA,SAAA,EACoB;AACpB,EAAA,IAAI,KAAA,KAAU,QAAW,OAAO,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-NI2GV74U.cjs","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":["../src/core/types.ts","../src/core/define-graph.ts","../src/utils/date.ts"],"names":["ConfigurationError","ValidationError"],"mappings":";;;;;AAOO,IAAM,eAAA,GAAkB;AAGxB,IAAM,eAAA,GAAkB;AA0PxB,SAAS,WAAW,KAAA,EAAmC;AAC5D,EAAA,OACE,OAAO,UAAU,QAAA,IACjB,KAAA,KAAU,QACV,eAAA,IAAmB,KAAA,IAClB,KAAA,CAAkC,eAAe,CAAA,KAAM,IA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C,EAAA,OAAO,MAAA,CAAO,IAAA,CAAK,KAAA,CAAM,KAAK,CAAA;AAChC;;;AChUA,IAAM,gBAAA,GAAmB,sDAAA;AAQlB,SAAS,eAAe,KAAA,EAAwB;AACrD,EAAA,IAAI,CAAC,gBAAA,CAAiB,IAAA,CAAK,KAAK,CAAA,EAAG;AACjC,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,IAAA,GAAO,IAAI,IAAA,CAAK,KAAK,CAAA;AAC3B,EAAA,OAAO,CAAC,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,SAAS,CAAA;AACrC;AAWO,SAAS,eAAA,CAAgB,OAAe,SAAA,EAA2B;AACxE,EAAA,IAAI,CAAC,cAAA,CAAe,KAAK,CAAA,EAAG;AAC1B,IAAA,MAAM,IAAIC,iCAAA;AAAA,MACR,CAAA,+BAAA,EAAkC,SAAS,CAAA,IAAA,EAAO,KAAK,CAAA,4CAAA,CAAA;AAAA,MAEvD;AAAA,QACE,MAAA,EAAQ;AAAA,UACN;AAAA,YACE,IAAA,EAAM,SAAA;AAAA,YACN,OAAA,EAAS,+EAA+E,KAAK,CAAA,CAAA;AAAA;AAC/F;AACF,OACF;AAAA,MACA;AAAA,QACE,UAAA,EAAY,CAAA,iEAAA;AAAA;AACd,KACF;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;AAMO,SAAS,uBAAA,CACd,OACA,SAAA,EACoB;AACpB,EAAA,IAAI,KAAA,KAAU,QAAW,OAAO,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-5GZMPJOP.cjs","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,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
3
|
+
var chunk2UTJRP4F_cjs = require('./chunk-2UTJRP4F.cjs');
|
|
4
|
+
var chunkO5PST6TB_cjs = require('./chunk-O5PST6TB.cjs');
|
|
5
5
|
var drizzleOrm = require('drizzle-orm');
|
|
6
6
|
|
|
7
7
|
var DEFAULT_PREPARED_STATEMENT_CACHE_MAX = 256;
|
|
@@ -107,7 +107,7 @@ function createSqliteExecutionAdapter(db, statementCacheMaxOrOptions = {}) {
|
|
|
107
107
|
supportsCompiledExecution: sqliteClient !== void 0,
|
|
108
108
|
transactionMode
|
|
109
109
|
};
|
|
110
|
-
const compile = (query) =>
|
|
110
|
+
const compile = (query) => chunk2UTJRP4F_cjs.compileQueryWithDialect(db, query, "SQLite");
|
|
111
111
|
if (sqliteClient !== void 0) {
|
|
112
112
|
let executeCompiled2 = function(compiledQuery) {
|
|
113
113
|
const preparedStatement = getOrCreatePreparedStatement(
|
|
@@ -178,15 +178,37 @@ var SQLITE_CHECK_UNIQUE_BATCH_CHUNK_SIZE = Math.max(
|
|
|
178
178
|
1,
|
|
179
179
|
SQLITE_MAX_BIND_PARAMETERS - CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT
|
|
180
180
|
);
|
|
181
|
-
var toNodeRow =
|
|
182
|
-
var toEdgeRow =
|
|
183
|
-
var toUniqueRow =
|
|
184
|
-
var toSchemaVersionRow =
|
|
181
|
+
var toNodeRow = chunk2UTJRP4F_cjs.createNodeRowMapper(chunk2UTJRP4F_cjs.SQLITE_ROW_MAPPER_CONFIG);
|
|
182
|
+
var toEdgeRow = chunk2UTJRP4F_cjs.createEdgeRowMapper(chunk2UTJRP4F_cjs.SQLITE_ROW_MAPPER_CONFIG);
|
|
183
|
+
var toUniqueRow = chunk2UTJRP4F_cjs.createUniqueRowMapper(chunk2UTJRP4F_cjs.SQLITE_ROW_MAPPER_CONFIG);
|
|
184
|
+
var toSchemaVersionRow = chunk2UTJRP4F_cjs.createSchemaVersionRowMapper(chunk2UTJRP4F_cjs.SQLITE_ROW_MAPPER_CONFIG);
|
|
185
|
+
var PENDING_FOREVER = new Promise(noop);
|
|
186
|
+
function pendingForever() {
|
|
187
|
+
return PENDING_FOREVER;
|
|
188
|
+
}
|
|
189
|
+
function noop() {
|
|
190
|
+
}
|
|
185
191
|
function createSerializedExecutionQueue() {
|
|
186
192
|
let tail = Promise.resolve();
|
|
193
|
+
let disposed = false;
|
|
194
|
+
function isDisposed() {
|
|
195
|
+
return disposed;
|
|
196
|
+
}
|
|
187
197
|
return {
|
|
188
|
-
|
|
189
|
-
|
|
198
|
+
dispose() {
|
|
199
|
+
disposed = true;
|
|
200
|
+
},
|
|
201
|
+
runExclusive(task) {
|
|
202
|
+
if (isDisposed()) return Promise.reject(new chunkO5PST6TB_cjs.BackendDisposedError());
|
|
203
|
+
const runTask = async () => {
|
|
204
|
+
if (isDisposed()) return pendingForever();
|
|
205
|
+
try {
|
|
206
|
+
return await task();
|
|
207
|
+
} catch (error) {
|
|
208
|
+
if (isDisposed()) return pendingForever();
|
|
209
|
+
throw error;
|
|
210
|
+
}
|
|
211
|
+
};
|
|
190
212
|
const result = tail.then(runTask, runTask);
|
|
191
213
|
tail = result.then(
|
|
192
214
|
() => 0,
|
|
@@ -196,7 +218,7 @@ function createSerializedExecutionQueue() {
|
|
|
196
218
|
}
|
|
197
219
|
};
|
|
198
220
|
}
|
|
199
|
-
|
|
221
|
+
function runWithSerializedQueue(queue, task) {
|
|
200
222
|
if (queue === void 0) return task();
|
|
201
223
|
return queue.runExclusive(task);
|
|
202
224
|
}
|
|
@@ -209,25 +231,25 @@ function createSqliteOperationBackend(options) {
|
|
|
209
231
|
serializedQueue,
|
|
210
232
|
tableNames
|
|
211
233
|
} = options;
|
|
212
|
-
|
|
234
|
+
function execGet(query) {
|
|
213
235
|
return runWithSerializedQueue(serializedQueue, async () => {
|
|
214
236
|
const result = db.get(query);
|
|
215
237
|
return result instanceof Promise ? await result : result;
|
|
216
238
|
});
|
|
217
239
|
}
|
|
218
|
-
|
|
240
|
+
function execAll(query) {
|
|
219
241
|
return runWithSerializedQueue(serializedQueue, async () => {
|
|
220
242
|
const result = db.all(query);
|
|
221
243
|
return result instanceof Promise ? await result : result;
|
|
222
244
|
});
|
|
223
245
|
}
|
|
224
|
-
|
|
225
|
-
|
|
246
|
+
function execRun(query) {
|
|
247
|
+
return runWithSerializedQueue(serializedQueue, async () => {
|
|
226
248
|
const result = db.run(query);
|
|
227
249
|
if (result instanceof Promise) await result;
|
|
228
250
|
});
|
|
229
251
|
}
|
|
230
|
-
const commonBackend =
|
|
252
|
+
const commonBackend = chunk2UTJRP4F_cjs.createCommonOperationBackend({
|
|
231
253
|
batchConfig: {
|
|
232
254
|
checkUniqueBatchChunkSize: SQLITE_CHECK_UNIQUE_BATCH_CHUNK_SIZE,
|
|
233
255
|
edgeInsertBatchSize: SQLITE_EDGE_INSERT_BATCH_SIZE,
|
|
@@ -240,7 +262,7 @@ function createSqliteOperationBackend(options) {
|
|
|
240
262
|
execGet,
|
|
241
263
|
execRun
|
|
242
264
|
},
|
|
243
|
-
nowIso:
|
|
265
|
+
nowIso: chunk2UTJRP4F_cjs.nowIso,
|
|
244
266
|
operationStrategy,
|
|
245
267
|
rowMappers: {
|
|
246
268
|
toEdgeRow,
|
|
@@ -276,14 +298,14 @@ function createSqliteOperationBackend(options) {
|
|
|
276
298
|
...params.indexParams?.efConstruction === void 0 ? {} : { hnswEfConstruction: params.indexParams.efConstruction },
|
|
277
299
|
...params.indexParams?.lists === void 0 ? {} : { ivfflatLists: params.indexParams.lists }
|
|
278
300
|
};
|
|
279
|
-
const result =
|
|
301
|
+
const result = chunk2UTJRP4F_cjs.createSqliteVectorIndex(indexOptions);
|
|
280
302
|
if (!result.success) {
|
|
281
303
|
throw new Error(result.message ?? "Failed to create SQLite vector index");
|
|
282
304
|
}
|
|
283
305
|
return Promise.resolve();
|
|
284
306
|
},
|
|
285
307
|
dropVectorIndex(params) {
|
|
286
|
-
const result =
|
|
308
|
+
const result = chunk2UTJRP4F_cjs.dropSqliteVectorIndex(
|
|
287
309
|
params.graphId,
|
|
288
310
|
params.nodeKind,
|
|
289
311
|
params.fieldPath
|
|
@@ -307,17 +329,17 @@ function createSqliteOperationBackend(options) {
|
|
|
307
329
|
return operationBackend;
|
|
308
330
|
}
|
|
309
331
|
function createSqliteBackend(db, options = {}) {
|
|
310
|
-
const tables2 = options.tables ??
|
|
332
|
+
const tables2 = options.tables ?? chunk2UTJRP4F_cjs.tables2;
|
|
311
333
|
const profileHints = options.executionProfile ?? {};
|
|
312
334
|
const executionAdapter = createSqliteExecutionAdapter(db, { profileHints });
|
|
313
335
|
const { isSync, transactionMode } = executionAdapter.profile;
|
|
314
|
-
const capabilities = transactionMode === "none" ? { ...
|
|
336
|
+
const capabilities = transactionMode === "none" ? { ...chunk2UTJRP4F_cjs.SQLITE_CAPABILITIES, transactions: false } : chunk2UTJRP4F_cjs.SQLITE_CAPABILITIES;
|
|
315
337
|
const tableNames = {
|
|
316
338
|
nodes: drizzleOrm.getTableName(tables2.nodes),
|
|
317
339
|
edges: drizzleOrm.getTableName(tables2.edges),
|
|
318
340
|
embeddings: drizzleOrm.getTableName(tables2.embeddings)
|
|
319
341
|
};
|
|
320
|
-
const operationStrategy =
|
|
342
|
+
const operationStrategy = chunk2UTJRP4F_cjs.createSqliteOperationStrategy(tables2);
|
|
321
343
|
const serializedQueue = isSync ? createSerializedExecutionQueue() : void 0;
|
|
322
344
|
const operations = createSqliteOperationBackend({
|
|
323
345
|
capabilities,
|
|
@@ -330,7 +352,7 @@ function createSqliteBackend(db, options = {}) {
|
|
|
330
352
|
const backend = {
|
|
331
353
|
...operations,
|
|
332
354
|
bootstrapTables() {
|
|
333
|
-
const statements =
|
|
355
|
+
const statements = chunk2UTJRP4F_cjs.generateSqliteDDL(tables2);
|
|
334
356
|
for (const statement of statements) {
|
|
335
357
|
db.run(drizzleOrm.sql.raw(statement));
|
|
336
358
|
}
|
|
@@ -343,7 +365,7 @@ function createSqliteBackend(db, options = {}) {
|
|
|
343
365
|
},
|
|
344
366
|
async transaction(fn, _options) {
|
|
345
367
|
if (transactionMode === "none") {
|
|
346
|
-
throw new
|
|
368
|
+
throw new chunkO5PST6TB_cjs.ConfigurationError(
|
|
347
369
|
"This SQLite backend does not support atomic transactions. Operations within a transaction are not rolled back on failure. Use backend.capabilities.transactions to check for transaction support, or use individual operations with manual error handling.",
|
|
348
370
|
{
|
|
349
371
|
backend: "sqlite",
|
|
@@ -387,7 +409,9 @@ function createSqliteBackend(db, options = {}) {
|
|
|
387
409
|
})
|
|
388
410
|
);
|
|
389
411
|
},
|
|
390
|
-
|
|
412
|
+
close() {
|
|
413
|
+
serializedQueue?.dispose();
|
|
414
|
+
return Promise.resolve();
|
|
391
415
|
}
|
|
392
416
|
};
|
|
393
417
|
return backend;
|
|
@@ -406,5 +430,5 @@ function createTransactionBackend(options) {
|
|
|
406
430
|
}
|
|
407
431
|
|
|
408
432
|
exports.createSqliteBackend = createSqliteBackend;
|
|
409
|
-
//# sourceMappingURL=chunk-
|
|
410
|
-
//# sourceMappingURL=chunk-
|
|
433
|
+
//# sourceMappingURL=chunk-5H74QKKF.cjs.map
|
|
434
|
+
//# sourceMappingURL=chunk-5H74QKKF.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/backend/drizzle/execution/sqlite-execution.ts","../src/backend/drizzle/sqlite.ts"],"names":["sql","compileQueryWithDialect","executeCompiled","createNodeRowMapper","SQLITE_ROW_MAPPER_CONFIG","createEdgeRowMapper","createUniqueRowMapper","createSchemaVersionRowMapper","BackendDisposedError","createCommonOperationBackend","nowIso","createSqliteVectorIndex","dropSqliteVectorIndex","tables","SQLITE_CAPABILITIES","getTableName","createSqliteOperationStrategy","generateSqliteDDL","ConfigurationError"],"mappings":";;;;;;AAUA,IAAM,oCAAA,GAAuC,GAAA;AAgE7C,SAAS,eAAe,EAAA,EAA2C;AACjE,EAAA,MAAM,mBAAA,GAAsB,EAAA;AAC5B,EAAA,MAAM,kBAAA,GAAqB,mBAAA,CAAoB,OAAA,EAAS,WAAA,EAAa,IAAA;AACrE,EAAA,IAAI,uBAAuB,MAAA,EAAW;AACpC,IAAA,OAAO,kBAAA;AAAA,EACT;AAEA,EAAA,OAAO,mBAAA,CAAoB,CAAA,EAAG,OAAA,EAAS,WAAA,EAAa,IAAA;AACtD;AAEA,SAAS,0BAA0B,EAAA,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["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"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DatabaseOperationError, UniquenessError } from './chunk-
|
|
1
|
+
import { DatabaseOperationError, UniquenessError } from './chunk-WFMTAEEN.js';
|
|
2
2
|
import { buildPostgresNodeIndexBuilders, buildPostgresEdgeIndexBuilders, buildSqliteNodeIndexBuilders, buildSqliteEdgeIndexBuilders } from './chunk-6GWJH6AR.js';
|
|
3
3
|
import { MAX_PG_IDENTIFIER_LENGTH } from './chunk-GNIYZKBI.js';
|
|
4
4
|
import { customType, pgTable, timestamp, integer, jsonb, text, primaryKey, index, boolean, getTableConfig as getTableConfig$1 } from 'drizzle-orm/pg-core';
|
|
@@ -2122,5 +2122,5 @@ function compileQueryWithDialect(db, query, backendName) {
|
|
|
2122
2122
|
}
|
|
2123
2123
|
|
|
2124
2124
|
export { POSTGRES_CAPABILITIES, POSTGRES_ROW_MAPPER_CONFIG, SQLITE_CAPABILITIES, SQLITE_ROW_MAPPER_CONFIG, compileQueryWithDialect, createCommonOperationBackend, createEdgeRowMapper, createNodeRowMapper, createPostgresOperationStrategy, createPostgresTables, createPostgresVectorIndex, createSchemaVersionRowMapper, createSqliteOperationStrategy, createSqliteTables, createSqliteVectorIndex, createUniqueRowMapper, dropPostgresVectorIndex, dropSqliteVectorIndex, edges, edges2, embeddings, embeddings2, formatPostgresTimestamp, generatePostgresDDL, generatePostgresMigrationSQL, generateSqliteDDL, generateSqliteMigrationSQL, generateVectorIndexName, nodes, nodes2, nowIso, schemaVersions, schemaVersions2, tables, tables2, uniques, uniques2 };
|
|
2125
|
-
//# sourceMappingURL=chunk-
|
|
2126
|
-
//# sourceMappingURL=chunk-
|
|
2125
|
+
//# sourceMappingURL=chunk-7ZVPFJLQ.js.map
|
|
2126
|
+
//# sourceMappingURL=chunk-7ZVPFJLQ.js.map
|