UNPKG

@fluxgraph/knowledge

Version:

A flexible, database-agnostic knowledge graph implementation for TypeScript

351 lines (347 loc) 9.44 kB
import { D as DatabaseAdapter } from './base-DQbXAhv3.js'; /** * Core types for the knowledge graph system */ /** * Type for node types - users define their own enums */ type NodeType = string; /** * Common edge types that users can extend */ declare enum CommonEdgeType { RELATED_TO = "RELATED_TO", SIMILAR_TO = "SIMILAR_TO", OPPOSITE_OF = "OPPOSITE_OF", PART_OF = "PART_OF", HAS_PART = "HAS_PART", KNOWS = "KNOWS", FRIEND_OF = "FRIEND_OF", COLLEAGUE_OF = "COLLEAGUE_OF", REPORTS_TO = "REPORTS_TO", MANAGES = "MANAGES", HAS_FAMILY_MEMBER = "HAS_FAMILY_MEMBER", PARENT_OF = "PARENT_OF", CHILD_OF = "CHILD_OF", SPOUSE_OF = "SPOUSE_OF", SIBLING_OF = "SIBLING_OF", LIVES_AT = "LIVES_AT", WORKS_AT = "WORKS_AT", LOCATED_IN = "LOCATED_IN", VISITED = "VISITED", PLANS_TO_VISIT = "PLANS_TO_VISIT", OWNS = "OWNS", OWNED_BY = "OWNED_BY", CREATED_BY = "CREATED_BY", CREATED = "CREATED", PAID_TO = "PAID_TO", RECEIVED_FROM = "RECEIVED_FROM", SAVED_FOR = "SAVED_FOR", SPENT_ON = "SPENT_ON", EARNS_FROM = "EARNS_FROM", INVESTS_IN = "INVESTS_IN", EMPLOYED_BY = "EMPLOYED_BY", EMPLOYS = "EMPLOYS", HAS_SKILL = "HAS_SKILL", REQUIRES_SKILL = "REQUIRES_SKILL", STUDIED_AT = "STUDIED_AT", GRADUATED_FROM = "GRADUATED_FROM", HAPPENED_BEFORE = "HAPPENED_BEFORE", HAPPENED_AFTER = "HAPPENED_AFTER", HAPPENED_DURING = "HAPPENED_DURING", CAUSED = "CAUSED", CAUSED_BY = "CAUSED_BY", LIKES = "LIKES", DISLIKES = "DISLIKES", INTERESTED_IN = "INTERESTED_IN", PREFERS = "PREFERS", PARTICIPATED_IN = "PARTICIPATED_IN", ATTENDED = "ATTENDED", ORGANIZED = "ORGANIZED", MENTIONED = "MENTIONED", REFERENCED = "REFERENCED", CONTAINS = "CONTAINS", CONTAINED_IN = "CONTAINED_IN", DERIVED_FROM = "DERIVED_FROM", BASED_ON = "BASED_ON" } /** * Type for edge types - users can extend CommonEdgeType or define their own */ type EdgeType = CommonEdgeType | string; /** * Core knowledge node interface */ interface KnowledgeNode<T = Record<string, unknown>> { id: string; type: NodeType | string; label: string; properties: T; confidence: number; createdAt: Date; updatedAt: Date; sourceSessionIds?: string[]; } /** * Core knowledge edge interface */ interface KnowledgeEdge<T = Record<string, unknown>> { id: string; type: EdgeType | string; fromNodeId: string; toNodeId: string; properties: T; confidence: number; createdAt: Date; sourceSessionIds?: string[]; } /** * Query result containing nodes and edges */ interface QueryResult<N = KnowledgeNode, E = KnowledgeEdge> { nodes: N[]; edges: E[]; relevanceScore?: number; metadata?: Record<string, unknown>; } /** * Options for graph queries */ interface QueryOptions { limit?: number; offset?: number; minConfidence?: number; includeEdges?: boolean; depth?: number; direction?: 'in' | 'out' | 'both'; nodeTypes?: (NodeType | string)[]; edgeTypes?: (EdgeType | string)[]; orderBy?: 'confidence' | 'createdAt' | 'updatedAt' | 'relevance'; orderDirection?: 'asc' | 'desc'; } /** * Options for node creation/update */ interface NodeOptions<TNodeType extends string = string, TProperties = Record<string, unknown>> { type: TNodeType; label: string; properties?: TProperties; confidence?: number; sourceSessionId?: string; mergeStrategy?: 'replace' | 'merge' | 'skip'; } /** * Options for edge creation/update */ interface EdgeOptions<TEdgeType extends string = string, TProperties = Record<string, unknown>> { type: TEdgeType; fromNodeId: string; toNodeId: string; properties?: TProperties; confidence?: number; sourceSessionId?: string; bidirectional?: boolean; } /** * Graph traversal options */ interface TraversalOptions { startNodeId: string; direction?: 'in' | 'out' | 'both'; maxDepth?: number; edgeTypes?: (EdgeType | string)[]; nodeFilter?: (node: KnowledgeNode) => boolean; edgeFilter?: (edge: KnowledgeEdge) => boolean; visitOnce?: boolean; } /** * Path finding result */ interface Path<N = KnowledgeNode, E = KnowledgeEdge> { nodes: N[]; edges: E[]; length: number; weight?: number; } /** * Graph statistics */ interface GraphStats { nodeCount: number; edgeCount: number; nodesByType: Record<string, number>; edgesByType: Record<string, number>; averageDegree: number; density: number; lastUpdated: Date; } /** * Extracted knowledge data for processing */ interface ExtractedNodeData<T = Record<string, unknown>> { type: NodeType | string; label: string; properties: T; confidence: number; sourceSessionIds?: string[]; } interface ExtractedEdgeData<T = Record<string, unknown>> { type: EdgeType | string; fromNodeLabel: string; toNodeLabel: string; properties: T; confidence: number; sourceSessionIds?: string[]; } interface ExtractedKnowledge<N = ExtractedNodeData, E = ExtractedEdgeData> { nodes: N[]; edges: E[]; confidence: number; metadata?: Record<string, unknown>; } /** * Search options */ interface SearchOptions { query: string; fields?: ('label' | 'properties' | string)[]; nodeTypes?: (NodeType | string)[]; fuzzy?: boolean; limit?: number; minScore?: number; } /** * Batch operation results */ interface BatchResult { successful: number; failed: number; errors?: Array<{ item: unknown; error: Error; }>; } /** * Migration interface for version upgrades */ interface Migration { version: string; up: (db: unknown) => Promise<void>; down: (db: unknown) => Promise<void>; description?: string; } /** * Main KnowledgeGraph class that provides high-level graph operations */ declare class KnowledgeGraph<TNodeType extends string = string> { private adapter; private initialized; constructor(adapter: DatabaseAdapter); /** * Initialize the knowledge graph */ initialize(): Promise<void>; /** * Ensure the graph is initialized */ private ensureInitialized; /** * Add a new node to the graph */ addNode(options: NodeOptions<TNodeType>): Promise<KnowledgeNode>; /** * Update an existing node */ updateNode(nodeId: string, updates: Partial<NodeOptions<TNodeType>>, mergeProperties?: boolean): Promise<KnowledgeNode | null>; /** * Delete a node and all its edges */ deleteNode(nodeId: string): Promise<boolean>; /** * Get a node by ID */ getNode(nodeId: string): Promise<KnowledgeNode | null>; /** * Find nodes by label (exact or partial match) */ findNodesByLabel(label: string, exact?: boolean): Promise<KnowledgeNode[]>; /** * Add an edge between two nodes */ addEdge(options: EdgeOptions): Promise<KnowledgeEdge>; /** * Delete an edge */ deleteEdge(edgeId: string): Promise<boolean>; /** * Get edges between two nodes */ getEdgesBetween(fromNodeId: string, toNodeId: string, edgeType?: EdgeType | string): Promise<KnowledgeEdge[]>; /** * Query nodes by type */ queryByType(nodeType: NodeType | string, options?: QueryOptions): Promise<QueryResult>; /** * Query related nodes starting from a given node */ queryRelated(nodeId: string, options?: QueryOptions): Promise<QueryResult>; /** * Search nodes using text query */ search(options: SearchOptions): Promise<QueryResult>; /** * Traverse the graph from a starting node */ traverse(options: TraversalOptions): Promise<QueryResult>; /** * Find shortest path between two nodes */ findShortestPath(fromNodeId: string, toNodeId: string, options?: { edgeTypes?: (EdgeType | string)[]; }): Promise<Path | null>; /** * Get graph statistics */ getStats(): Promise<GraphStats>; /** * Batch insert nodes */ batchAddNodes(nodes: NodeOptions<TNodeType>[]): Promise<BatchResult>; /** * Batch insert edges */ batchAddEdges(edges: EdgeOptions[]): Promise<BatchResult>; /** * Vacuum the database to reclaim space */ vacuum(): Promise<void>; /** * Close the database connection */ close(): Promise<void>; /** * Execute raw SQL query (for advanced use cases) */ private execute; /** * Normalize a node from database format */ private normalizeNode; /** * Normalize an edge from database format */ private normalizeEdge; /** * Index a node for search */ private indexNodeForSearch; /** * Traverse graph helper */ private traverseGraph; /** * Calculate relevance score */ private calculateRelevance; } export { type BatchResult as B, CommonEdgeType as C, type ExtractedNodeData as E, type GraphStats as G, KnowledgeGraph as K, type Migration as M, type NodeType as N, type Path as P, type QueryResult as Q, type SearchOptions as S, type TraversalOptions as T, type ExtractedEdgeData as a, type ExtractedKnowledge as b, type EdgeType as c, type KnowledgeNode as d, type KnowledgeEdge as e, type QueryOptions as f, type NodeOptions as g, type EdgeOptions as h };