@nicia-ai/typegraph 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { G as GraphDef } from '../manager-Bj1UEnhE.cjs';
3
- import { Y as Store } from '../store-BnUu4qo5.cjs';
3
+ import { a7 as Store } from '../store-DRRvALu8.cjs';
4
4
  import '../types-DMzKq0d5.cjs';
5
5
  import '../types-B3mmOMJV.cjs';
6
6
  import 'drizzle-orm';
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { G as GraphDef } from '../manager-Chhrq1vl.js';
3
- import { Y as Store } from '../store-CCOwNft_.js';
3
+ import { a7 as Store } from '../store-BMrRi_mY.js';
4
4
  import '../types-DMzKq0d5.js';
5
5
  import '../types-ThB4cFLp.js';
6
6
  import 'drizzle-orm';
@@ -1,6 +1,6 @@
1
1
  import { G as GraphDef } from '../manager-Bj1UEnhE.cjs';
2
2
  import { Q as QueryAst } from '../ast-Bh2NDeaK.cjs';
3
- import { Y as Store } from '../store-BnUu4qo5.cjs';
3
+ import { a7 as Store } from '../store-DRRvALu8.cjs';
4
4
  import { P as ProfilerOptions, a as ProfileReport } from '../types-CVtGFpB9.cjs';
5
5
  export { D as DeclaredIndex, I as IndexRecommendation, b as ProfileSummary, c as PropertyAccessStats, d as PropertyPath, R as RecommendationPriority, U as UsageContext } from '../types-CVtGFpB9.cjs';
6
6
  import '../types-DMzKq0d5.cjs';
@@ -1,6 +1,6 @@
1
1
  import { G as GraphDef } from '../manager-Chhrq1vl.js';
2
2
  import { Q as QueryAst } from '../ast-COMyNeMn.js';
3
- import { Y as Store } from '../store-CCOwNft_.js';
3
+ import { a7 as Store } from '../store-BMrRi_mY.js';
4
4
  import { P as ProfilerOptions, a as ProfileReport } from '../types-COPePE8_.js';
5
5
  export { D as DeclaredIndex, I as IndexRecommendation, b as ProfileSummary, c as PropertyAccessStats, d as PropertyPath, R as RecommendationPriority, U as UsageContext } from '../types-COPePE8_.js';
6
6
  import '../types-DMzKq0d5.js';
@@ -2,7 +2,7 @@ import { S as SqlSchema, G as GraphBackend, T as TransactionBackend, E as EdgeRo
2
2
  import { K as KindRegistry, G as GraphDef, E as EdgeKinds, N as NodeKinds, a as AllNodeTypes, S as SchemaManagerOptions, d as SchemaValidationResult } from './manager-Chhrq1vl.js';
3
3
  import { S as SqlDialect, N as NodeType, A as AnyEdgeType, T as TemporalMode, E as EdgeType, d as EdgeRegistration, b as EdgeId, g as NodeId, i as NodeRegistration } from './types-DMzKq0d5.js';
4
4
  import { z } from 'zod';
5
- import { V as ValueType, i as PredicateExpression, k as VectorMetricType, Q as QueryAst, J as JsonPointer, F as FieldRef, P as ParameterRef, c as JsonPointerInput, T as TraversalExpansion, l as Traversal, N as NodePredicate, m as ProjectedField, O as OrderSpec, G as GroupBySpec, o as RecursiveCyclePolicy, q as TraversalDirection, A as AggregateExpr, r as SelectiveField, s as ComposableQuery, t as SetOperationType, u as SetOperation, S as SortDirection } from './ast-COMyNeMn.js';
5
+ import { V as ValueType, i as PredicateExpression, k as VectorMetricType, Q as QueryAst, J as JsonPointer, F as FieldRef, P as ParameterRef, c as JsonPointerInput, T as TraversalExpansion, l as Traversal, N as NodePredicate, m as ProjectedField, O as OrderSpec, G as GroupBySpec, o as RecursiveCyclePolicy, q as TraversalDirection$1, A as AggregateExpr, r as SelectiveField, s as ComposableQuery, t as SetOperationType, u as SetOperation, S as SortDirection } from './ast-COMyNeMn.js';
6
6
  import { SQL } from 'drizzle-orm';
7
7
 
8
8
  /**
@@ -273,7 +273,7 @@ type BatchResults<Queries extends readonly BatchableQuery<unknown>[]> = {
273
273
  * // ValidEdgeTargets<G, "worksAt", "out"> = "Company" | "Organization"
274
274
  * // ValidEdgeTargets<G, "worksAt", "in"> = "Person"
275
275
  */
276
- type ValidEdgeTargets<G extends GraphDef, EK extends keyof G["edges"] & string, Dir extends TraversalDirection> = G["edges"][EK] extends EdgeRegistration ? Dir extends "out" ? G["edges"][EK]["to"][number]["kind"] : G["edges"][EK]["from"][number]["kind"] : never;
276
+ type ValidEdgeTargets<G extends GraphDef, EK extends keyof G["edges"] & string, Dir extends TraversalDirection$1> = G["edges"][EK] extends EdgeRegistration ? Dir extends "out" ? G["edges"][EK]["to"][number]["kind"] : G["edges"][EK]["from"][number]["kind"] : never;
277
277
  /**
278
278
  * A node alias with its associated type.
279
279
  */
@@ -1485,6 +1485,13 @@ type SubgraphOptions<G extends GraphDef, EK extends EdgeKinds<G>, NK extends Nod
1485
1485
  direction?: "out" | "both";
1486
1486
  /** Cycle policy — reuse RecursiveCyclePolicy (default: "prevent"). */
1487
1487
  cyclePolicy?: RecursiveCyclePolicy;
1488
+ /**
1489
+ * Temporal mode applied to both nodes and edges along the traversal and in
1490
+ * the hydrated result. Defaults to `graph.defaults.temporalMode`.
1491
+ */
1492
+ temporalMode?: TemporalMode;
1493
+ /** ISO-8601 timestamp used when `temporalMode === "asOf"`. */
1494
+ asOf?: string;
1488
1495
  /**
1489
1496
  * Optional field-level projection per node/edge kind.
1490
1497
  *
@@ -1866,7 +1873,7 @@ interface VariableLengthState {
1866
1873
  * Type parameters track the edge kind and direction to constrain
1867
1874
  * which node kinds are valid targets in the `to()` method.
1868
1875
  */
1869
- declare class TraversalBuilder<G extends GraphDef, Aliases extends AliasMap, EdgeAliases extends EdgeAliasMap = {}, EK extends keyof G["edges"] & string = keyof G["edges"] & string, EA extends string = string, Dir extends TraversalDirection = "out", Optional extends boolean = false, DC extends boolean | string = false, PC extends boolean | string = false, RecAliases extends RecursiveAliasMap = {}> {
1876
+ declare class TraversalBuilder<G extends GraphDef, Aliases extends AliasMap, EdgeAliases extends EdgeAliasMap = {}, EK extends keyof G["edges"] & string = keyof G["edges"] & string, EA extends string = string, Dir extends TraversalDirection$1 = "out", Optional extends boolean = false, DC extends boolean | string = false, PC extends boolean | string = false, RecAliases extends RecursiveAliasMap = {}> {
1870
1877
  #private;
1871
1878
  constructor(config: QueryBuilderConfig, state: QueryBuilderState, edgeKinds: readonly string[], edgeAlias: EA, direction: Dir, fromAlias: string, inverseEdgeKinds?: readonly string[], optional?: Optional, variableLength?: VariableLengthState, pendingEdgePredicates?: readonly NodePredicate[]);
1872
1879
  /**
@@ -2073,6 +2080,198 @@ declare class QueryBuilder<G extends GraphDef, Aliases extends AliasMap = {}, Ed
2073
2080
  pipe<OutAliases extends AliasMap, OutEdgeAliases extends EdgeAliasMap = EdgeAliases, OutRecAliases extends RecursiveAliasMap = RecursiveAliases>(fragment: (builder: QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases>) => QueryBuilder<G, OutAliases, OutEdgeAliases, OutRecAliases>): QueryBuilder<G, OutAliases, OutEdgeAliases, OutRecAliases>;
2074
2081
  }
2075
2082
 
2083
+ /**
2084
+ * Shared types for Tier 1 graph algorithms.
2085
+ *
2086
+ * Algorithms operate over one or more edge kinds and may traverse edges
2087
+ * in the forward direction ("out"), reverse ("in"), or undirected ("both").
2088
+ */
2089
+
2090
+ /**
2091
+ * Direction of edge traversal.
2092
+ *
2093
+ * - `"out"` — follow edges from source to target (default)
2094
+ * - `"in"` — follow edges from target back to source
2095
+ * - `"both"` — undirected traversal over either endpoint
2096
+ */
2097
+ type TraversalDirection = "out" | "in" | "both";
2098
+ /**
2099
+ * Cycle-handling strategy during recursive traversal.
2100
+ *
2101
+ * - `"prevent"` — skip any node already on the current path (default).
2102
+ * Guarantees termination even in cyclic graphs.
2103
+ * - `"allow"` — permit revisiting nodes. Only safe with a bounded `maxHops`.
2104
+ *
2105
+ * Aliased to `RecursiveCyclePolicy` so algorithms and query-builder traversals
2106
+ * share a single canonical union.
2107
+ */
2108
+ type AlgorithmCyclePolicy = RecursiveCyclePolicy;
2109
+ /**
2110
+ * Temporal filter options shared by every algorithm.
2111
+ *
2112
+ * Algorithms honor the same temporal model as the rest of the store: both
2113
+ * nodes and edges are filtered according to the resolved mode. `asOf` is
2114
+ * only consulted when the resolved mode is `"asOf"`. If neither option is
2115
+ * supplied, the algorithm falls back to `graph.defaults.temporalMode`.
2116
+ */
2117
+ type TemporalAlgorithmOptions = Readonly<{
2118
+ /** Temporal mode. Defaults to the graph's configured default. */
2119
+ temporalMode?: TemporalMode;
2120
+ /**
2121
+ * ISO-8601 timestamp used when `temporalMode` is `"asOf"`. Required in that
2122
+ * mode; ignored in all others.
2123
+ */
2124
+ asOf?: string;
2125
+ }>;
2126
+ /**
2127
+ * Base options for traversal-style algorithms.
2128
+ */
2129
+ type BaseTraversalOptions<G extends GraphDef> = TemporalAlgorithmOptions & Readonly<{
2130
+ /** Edge kinds to follow. At least one kind is required. */
2131
+ edges: readonly EdgeKinds<G>[];
2132
+ /**
2133
+ * Maximum number of hops to traverse. Defaults to 10.
2134
+ * Must be between 1 and 1000.
2135
+ */
2136
+ maxHops?: number;
2137
+ /** Direction of traversal (default: `"out"`). */
2138
+ direction?: TraversalDirection;
2139
+ /** Cycle policy (default: `"prevent"`). */
2140
+ cyclePolicy?: AlgorithmCyclePolicy;
2141
+ }>;
2142
+ /**
2143
+ * A node reached during traversal, annotated with the shortest depth at which
2144
+ * it was first discovered.
2145
+ */
2146
+ type ReachableNode = Readonly<{
2147
+ id: string;
2148
+ kind: string;
2149
+ /** Number of edges traversed from the source. 0 for the source itself. */
2150
+ depth: number;
2151
+ }>;
2152
+ /**
2153
+ * A node along a shortest path. Endpoints are included.
2154
+ */
2155
+ type PathNode = Readonly<{
2156
+ id: string;
2157
+ kind: string;
2158
+ }>;
2159
+ /**
2160
+ * Result of `shortestPath`: the ordered node sequence and its length in hops.
2161
+ */
2162
+ type ShortestPathResult = Readonly<{
2163
+ /** Ordered nodes from source to target (inclusive). */
2164
+ nodes: readonly PathNode[];
2165
+ /** Number of edges traversed. Equals `nodes.length - 1`. */
2166
+ depth: number;
2167
+ }>;
2168
+ /**
2169
+ * Options for `shortestPath` and `canReach`. Reuses the base traversal
2170
+ * options; cycle policy defaults to `"prevent"` since both algorithms only
2171
+ * care about the first time a target is reached.
2172
+ */
2173
+ type ShortestPathOptions<G extends GraphDef> = BaseTraversalOptions<G>;
2174
+ /**
2175
+ * Options for `reachable`.
2176
+ *
2177
+ * Returns every node reachable from the source within `maxHops`, each
2178
+ * annotated with its minimum discovered depth. `depth: 0` refers to the
2179
+ * source itself and is included unless `excludeSource` is `true`.
2180
+ */
2181
+ type ReachableOptions<G extends GraphDef> = BaseTraversalOptions<G> & Readonly<{
2182
+ /** Exclude the source node from the result set (default: `false`). */
2183
+ excludeSource?: boolean;
2184
+ }>;
2185
+ /**
2186
+ * Options for `neighbors`.
2187
+ *
2188
+ * Like `reachable`, but the parameter is named `depth` for readability —
2189
+ * "2-hop neighbors" reads more naturally than "reachable with maxHops=2".
2190
+ * The source is always excluded.
2191
+ */
2192
+ type NeighborsOptions<G extends GraphDef> = TemporalAlgorithmOptions & Readonly<{
2193
+ /** Edge kinds to follow. At least one kind is required. */
2194
+ edges: readonly EdgeKinds<G>[];
2195
+ /** Maximum neighborhood depth (default: 1). Must be between 1 and 1000. */
2196
+ depth?: number;
2197
+ /** Direction of traversal (default: `"out"`). */
2198
+ direction?: TraversalDirection;
2199
+ /** Cycle policy (default: `"prevent"`). */
2200
+ cyclePolicy?: AlgorithmCyclePolicy;
2201
+ }>;
2202
+ /**
2203
+ * Options for `degree`.
2204
+ *
2205
+ * Counts active edges incident to a node. With `direction: "both"`, an edge
2206
+ * that happens to be a self-loop (from === to) is counted once, not twice.
2207
+ */
2208
+ type DegreeOptions<G extends GraphDef> = TemporalAlgorithmOptions & Readonly<{
2209
+ /**
2210
+ * Edge kinds to count. If omitted, counts across all edge kinds in the
2211
+ * graph.
2212
+ */
2213
+ edges?: readonly EdgeKinds<G>[];
2214
+ /** Direction (default: `"both"`). */
2215
+ direction?: TraversalDirection;
2216
+ }>;
2217
+
2218
+ /**
2219
+ * Raw node id or any object with an `id: string` field. Covers `Node`,
2220
+ * `NodeRef`, and the lightweight `ReachableNode` / `PathNode` shapes
2221
+ * returned by the algorithms themselves.
2222
+ *
2223
+ * Deliberately kind-agnostic: graph algorithms don't constrain the source
2224
+ * node's kind — you can start a traversal from any node reachable via the
2225
+ * given edge kinds. `NodeRef<N>` exists for the edge-endpoint case where
2226
+ * kind *is* load-bearing; using it here would paint a constraint onto a
2227
+ * contract that doesn't need one and would reject common patterns like
2228
+ * passing `ReachableNode` / cache entries / `{ id }` records straight
2229
+ * through.
2230
+ */
2231
+ type NodeIdentifier = string | Readonly<{
2232
+ id: string;
2233
+ }>;
2234
+ type GraphAlgorithms<G extends GraphDef> = Readonly<{
2235
+ /**
2236
+ * Finds the shortest directed path from `from` to `to` using the given
2237
+ * edge kinds. Returns `undefined` when no path exists within `maxHops`.
2238
+ *
2239
+ * @example
2240
+ * ```typescript
2241
+ * const path = await store.algorithms.shortestPath(alice, bob, {
2242
+ * edges: ["knows"],
2243
+ * maxHops: 6,
2244
+ * });
2245
+ * if (path) {
2246
+ * console.log(`${path.depth} hops via`, path.nodes.map((n) => n.id));
2247
+ * }
2248
+ * ```
2249
+ */
2250
+ shortestPath: (from: NodeIdentifier, to: NodeIdentifier, options: ShortestPathOptions<G>) => Promise<ShortestPathResult | undefined>;
2251
+ /**
2252
+ * Returns every node reachable from `from` within `maxHops` edges of the
2253
+ * allowed kinds. Each node carries its minimum discovered depth.
2254
+ */
2255
+ reachable: (from: NodeIdentifier, options: ReachableOptions<G>) => Promise<readonly ReachableNode[]>;
2256
+ /**
2257
+ * Fast boolean check: is `to` reachable from `from` within `maxHops`
2258
+ * edges? Short-circuits the underlying recursive CTE with `LIMIT 1`.
2259
+ */
2260
+ canReach: (from: NodeIdentifier, to: NodeIdentifier, options: BaseTraversalOptions<G>) => Promise<boolean>;
2261
+ /**
2262
+ * Returns the k-hop neighborhood of a node. The source is always
2263
+ * excluded. `depth` defaults to 1, matching the common "immediate
2264
+ * neighbors" interpretation.
2265
+ */
2266
+ neighbors: (node: NodeIdentifier, options: NeighborsOptions<G>) => Promise<readonly ReachableNode[]>;
2267
+ /**
2268
+ * Counts active edges incident to `node`.
2269
+ *
2270
+ * With `direction: "both"` (default), self-loops contribute once.
2271
+ */
2272
+ degree: (node: NodeIdentifier, options?: DegreeOptions<G>) => Promise<number>;
2273
+ }>;
2274
+
2076
2275
  /**
2077
2276
  * Main Store implementation for TypeGraph.
2078
2277
  *
@@ -2161,6 +2360,27 @@ declare class Store<G extends GraphDef> {
2161
2360
  * ```
2162
2361
  */
2163
2362
  get edges(): GraphEdgeCollections<G>;
2363
+ /**
2364
+ * Tier 1 graph algorithms: shortest path, reachability, neighborhoods, and
2365
+ * degree centrality.
2366
+ *
2367
+ * Each call compiles to a single recursive-CTE query against the backend.
2368
+ * The facade is built lazily on first access and cached for the lifetime
2369
+ * of the store.
2370
+ *
2371
+ * @example
2372
+ * ```typescript
2373
+ * const path = await store.algorithms.shortestPath(alice, bob, {
2374
+ * edges: ["knows"],
2375
+ * });
2376
+ *
2377
+ * const friends = await store.algorithms.neighbors(alice, {
2378
+ * edges: ["knows"],
2379
+ * depth: 2,
2380
+ * });
2381
+ * ```
2382
+ */
2383
+ get algorithms(): GraphAlgorithms<G>;
2164
2384
  /**
2165
2385
  * Returns the node collection for the given kind, or undefined if the kind
2166
2386
  * is not registered in this graph.
@@ -2354,4 +2574,4 @@ declare function createStore<G extends GraphDef>(graph: G, backend: GraphBackend
2354
2574
  */
2355
2575
  declare function createStoreWithSchema<G extends GraphDef>(graph: G, backend: GraphBackend, options?: StoreOptions & SchemaManagerOptions): Promise<[Store<G>, SchemaValidationResult]>;
2356
2576
 
2357
- export { type StoreProjection as $, type AliasMap as A, type BatchResults as B, type CreateQueryBuilderOptions as C, type DynamicEdgeCollection as D, type EdgeAliasMap as E, type FieldAccessor as F, type GetOrCreateAction as G, type HookContext as H, type IfExistsMode as I, type PaginatedResult as J, type Predicate as K, PreparedQuery as L, type PropsAccessor as M, type Node as N, type OperationHookContext as O, type PaginateOptions as P, QueryBuilder as Q, type QueryHookContext as R, type QueryOptions as S, TraversalBuilder as T, type RecursiveTraversalOptions as U, type SelectContext as V, type SelectableEdge as W, type SelectableNode as X, Store as Y, type StoreHooks as Z, type StoreOptions as _, type AggregateResult as a, type StreamOptions as a0, type SubgraphEdgeResult as a1, type SubgraphNodeResult as a2, type SubgraphOptions as a3, type SubgraphResult as a4, type SubsetEdge as a5, type SubsetNode as a6, type TransactionContext as a7, type TypedEdgeCollection as a8, UnionableQuery as a9, type UpdateEdgeInput as aa, type UpdateNodeInput as ab, createStore as ac, createStoreWithSchema as ad, defineSubgraphProject as ae, embedding as af, exists as ag, fieldRef as ah, getEmbeddingDimensions as ai, inSubquery as aj, isEmbeddingSchema as ak, isParameterRef as al, notExists as am, notInSubquery as an, param as ao, type AnyEdge as b, type AnyNode as c, type BatchableQuery as d, type ConstraintNames as e, type CreateEdgeInput as f, type CreateNodeInput as g, type DynamicNodeCollection as h, type Edge as i, type EdgeAccessor as j, type EdgeCollection as k, type EdgeFindByEndpointsOptions as l, type EdgeGetOrCreateByEndpointsOptions as m, type EdgeGetOrCreateByEndpointsResult as n, type EmbeddingSchema as o, type EmbeddingValue as p, ExecutableAggregateQuery as q, ExecutableQuery as r, type GraphEdgeCollections as s, type GraphNodeCollections as t, type NodeAccessor as u, type NodeAlias as v, type NodeCollection as w, type NodeGetOrCreateByConstraintOptions as x, type NodeGetOrCreateByConstraintResult as y, type NodeRef as z };
2577
+ export { type ReachableNode as $, type AliasMap as A, type BaseTraversalOptions as B, type CreateQueryBuilderOptions as C, type DegreeOptions as D, type EdgeAliasMap as E, type FieldAccessor as F, type GetOrCreateAction as G, type HookContext as H, type IfExistsMode as I, type NodeAlias as J, type NodeCollection as K, type NodeGetOrCreateByConstraintOptions as L, type NodeGetOrCreateByConstraintResult as M, type NeighborsOptions as N, type NodeIdentifier as O, type NodeRef as P, QueryBuilder as Q, type OperationHookContext as R, type PaginateOptions as S, TraversalBuilder as T, type PaginatedResult as U, type PathNode as V, type Predicate as W, PreparedQuery as X, type PropsAccessor as Y, type QueryHookContext as Z, type QueryOptions as _, type AggregateResult as a, type ReachableOptions as a0, type RecursiveTraversalOptions as a1, type SelectContext as a2, type SelectableEdge as a3, type SelectableNode as a4, type ShortestPathOptions as a5, type ShortestPathResult as a6, Store as a7, type StoreHooks as a8, type StoreOptions as a9, notInSubquery as aA, param as aB, type StoreProjection as aa, type StreamOptions as ab, type SubgraphEdgeResult as ac, type SubgraphNodeResult as ad, type SubgraphOptions as ae, type SubgraphResult as af, type SubsetEdge as ag, type SubsetNode as ah, type TemporalAlgorithmOptions as ai, type TransactionContext as aj, type TraversalDirection as ak, type TypedEdgeCollection as al, UnionableQuery as am, type UpdateEdgeInput as an, type UpdateNodeInput as ao, createStore as ap, createStoreWithSchema as aq, defineSubgraphProject as ar, embedding as as, exists as at, fieldRef as au, getEmbeddingDimensions as av, inSubquery as aw, isEmbeddingSchema as ax, isParameterRef as ay, notExists as az, type AlgorithmCyclePolicy as b, type AnyEdge as c, type AnyNode as d, type BatchResults as e, type BatchableQuery as f, type ConstraintNames as g, type CreateEdgeInput as h, type CreateNodeInput as i, type DynamicEdgeCollection as j, type DynamicNodeCollection as k, type Edge as l, type EdgeAccessor as m, type EdgeCollection as n, type EdgeFindByEndpointsOptions as o, type EdgeGetOrCreateByEndpointsOptions as p, type EdgeGetOrCreateByEndpointsResult as q, type EmbeddingSchema as r, type EmbeddingValue as s, ExecutableAggregateQuery as t, ExecutableQuery as u, type GraphAlgorithms as v, type GraphEdgeCollections as w, type GraphNodeCollections as x, type Node as y, type NodeAccessor as z };
@@ -2,7 +2,7 @@ import { S as SqlSchema, G as GraphBackend, T as TransactionBackend, E as EdgeRo
2
2
  import { K as KindRegistry, G as GraphDef, E as EdgeKinds, N as NodeKinds, a as AllNodeTypes, S as SchemaManagerOptions, d as SchemaValidationResult } from './manager-Bj1UEnhE.cjs';
3
3
  import { S as SqlDialect, N as NodeType, A as AnyEdgeType, T as TemporalMode, E as EdgeType, d as EdgeRegistration, b as EdgeId, g as NodeId, i as NodeRegistration } from './types-DMzKq0d5.cjs';
4
4
  import { z } from 'zod';
5
- import { V as ValueType, i as PredicateExpression, k as VectorMetricType, Q as QueryAst, J as JsonPointer, F as FieldRef, P as ParameterRef, c as JsonPointerInput, T as TraversalExpansion, l as Traversal, N as NodePredicate, m as ProjectedField, O as OrderSpec, G as GroupBySpec, o as RecursiveCyclePolicy, q as TraversalDirection, A as AggregateExpr, r as SelectiveField, s as ComposableQuery, t as SetOperationType, u as SetOperation, S as SortDirection } from './ast-Bh2NDeaK.cjs';
5
+ import { V as ValueType, i as PredicateExpression, k as VectorMetricType, Q as QueryAst, J as JsonPointer, F as FieldRef, P as ParameterRef, c as JsonPointerInput, T as TraversalExpansion, l as Traversal, N as NodePredicate, m as ProjectedField, O as OrderSpec, G as GroupBySpec, o as RecursiveCyclePolicy, q as TraversalDirection$1, A as AggregateExpr, r as SelectiveField, s as ComposableQuery, t as SetOperationType, u as SetOperation, S as SortDirection } from './ast-Bh2NDeaK.cjs';
6
6
  import { SQL } from 'drizzle-orm';
7
7
 
8
8
  /**
@@ -273,7 +273,7 @@ type BatchResults<Queries extends readonly BatchableQuery<unknown>[]> = {
273
273
  * // ValidEdgeTargets<G, "worksAt", "out"> = "Company" | "Organization"
274
274
  * // ValidEdgeTargets<G, "worksAt", "in"> = "Person"
275
275
  */
276
- type ValidEdgeTargets<G extends GraphDef, EK extends keyof G["edges"] & string, Dir extends TraversalDirection> = G["edges"][EK] extends EdgeRegistration ? Dir extends "out" ? G["edges"][EK]["to"][number]["kind"] : G["edges"][EK]["from"][number]["kind"] : never;
276
+ type ValidEdgeTargets<G extends GraphDef, EK extends keyof G["edges"] & string, Dir extends TraversalDirection$1> = G["edges"][EK] extends EdgeRegistration ? Dir extends "out" ? G["edges"][EK]["to"][number]["kind"] : G["edges"][EK]["from"][number]["kind"] : never;
277
277
  /**
278
278
  * A node alias with its associated type.
279
279
  */
@@ -1485,6 +1485,13 @@ type SubgraphOptions<G extends GraphDef, EK extends EdgeKinds<G>, NK extends Nod
1485
1485
  direction?: "out" | "both";
1486
1486
  /** Cycle policy — reuse RecursiveCyclePolicy (default: "prevent"). */
1487
1487
  cyclePolicy?: RecursiveCyclePolicy;
1488
+ /**
1489
+ * Temporal mode applied to both nodes and edges along the traversal and in
1490
+ * the hydrated result. Defaults to `graph.defaults.temporalMode`.
1491
+ */
1492
+ temporalMode?: TemporalMode;
1493
+ /** ISO-8601 timestamp used when `temporalMode === "asOf"`. */
1494
+ asOf?: string;
1488
1495
  /**
1489
1496
  * Optional field-level projection per node/edge kind.
1490
1497
  *
@@ -1866,7 +1873,7 @@ interface VariableLengthState {
1866
1873
  * Type parameters track the edge kind and direction to constrain
1867
1874
  * which node kinds are valid targets in the `to()` method.
1868
1875
  */
1869
- declare class TraversalBuilder<G extends GraphDef, Aliases extends AliasMap, EdgeAliases extends EdgeAliasMap = {}, EK extends keyof G["edges"] & string = keyof G["edges"] & string, EA extends string = string, Dir extends TraversalDirection = "out", Optional extends boolean = false, DC extends boolean | string = false, PC extends boolean | string = false, RecAliases extends RecursiveAliasMap = {}> {
1876
+ declare class TraversalBuilder<G extends GraphDef, Aliases extends AliasMap, EdgeAliases extends EdgeAliasMap = {}, EK extends keyof G["edges"] & string = keyof G["edges"] & string, EA extends string = string, Dir extends TraversalDirection$1 = "out", Optional extends boolean = false, DC extends boolean | string = false, PC extends boolean | string = false, RecAliases extends RecursiveAliasMap = {}> {
1870
1877
  #private;
1871
1878
  constructor(config: QueryBuilderConfig, state: QueryBuilderState, edgeKinds: readonly string[], edgeAlias: EA, direction: Dir, fromAlias: string, inverseEdgeKinds?: readonly string[], optional?: Optional, variableLength?: VariableLengthState, pendingEdgePredicates?: readonly NodePredicate[]);
1872
1879
  /**
@@ -2073,6 +2080,198 @@ declare class QueryBuilder<G extends GraphDef, Aliases extends AliasMap = {}, Ed
2073
2080
  pipe<OutAliases extends AliasMap, OutEdgeAliases extends EdgeAliasMap = EdgeAliases, OutRecAliases extends RecursiveAliasMap = RecursiveAliases>(fragment: (builder: QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases>) => QueryBuilder<G, OutAliases, OutEdgeAliases, OutRecAliases>): QueryBuilder<G, OutAliases, OutEdgeAliases, OutRecAliases>;
2074
2081
  }
2075
2082
 
2083
+ /**
2084
+ * Shared types for Tier 1 graph algorithms.
2085
+ *
2086
+ * Algorithms operate over one or more edge kinds and may traverse edges
2087
+ * in the forward direction ("out"), reverse ("in"), or undirected ("both").
2088
+ */
2089
+
2090
+ /**
2091
+ * Direction of edge traversal.
2092
+ *
2093
+ * - `"out"` — follow edges from source to target (default)
2094
+ * - `"in"` — follow edges from target back to source
2095
+ * - `"both"` — undirected traversal over either endpoint
2096
+ */
2097
+ type TraversalDirection = "out" | "in" | "both";
2098
+ /**
2099
+ * Cycle-handling strategy during recursive traversal.
2100
+ *
2101
+ * - `"prevent"` — skip any node already on the current path (default).
2102
+ * Guarantees termination even in cyclic graphs.
2103
+ * - `"allow"` — permit revisiting nodes. Only safe with a bounded `maxHops`.
2104
+ *
2105
+ * Aliased to `RecursiveCyclePolicy` so algorithms and query-builder traversals
2106
+ * share a single canonical union.
2107
+ */
2108
+ type AlgorithmCyclePolicy = RecursiveCyclePolicy;
2109
+ /**
2110
+ * Temporal filter options shared by every algorithm.
2111
+ *
2112
+ * Algorithms honor the same temporal model as the rest of the store: both
2113
+ * nodes and edges are filtered according to the resolved mode. `asOf` is
2114
+ * only consulted when the resolved mode is `"asOf"`. If neither option is
2115
+ * supplied, the algorithm falls back to `graph.defaults.temporalMode`.
2116
+ */
2117
+ type TemporalAlgorithmOptions = Readonly<{
2118
+ /** Temporal mode. Defaults to the graph's configured default. */
2119
+ temporalMode?: TemporalMode;
2120
+ /**
2121
+ * ISO-8601 timestamp used when `temporalMode` is `"asOf"`. Required in that
2122
+ * mode; ignored in all others.
2123
+ */
2124
+ asOf?: string;
2125
+ }>;
2126
+ /**
2127
+ * Base options for traversal-style algorithms.
2128
+ */
2129
+ type BaseTraversalOptions<G extends GraphDef> = TemporalAlgorithmOptions & Readonly<{
2130
+ /** Edge kinds to follow. At least one kind is required. */
2131
+ edges: readonly EdgeKinds<G>[];
2132
+ /**
2133
+ * Maximum number of hops to traverse. Defaults to 10.
2134
+ * Must be between 1 and 1000.
2135
+ */
2136
+ maxHops?: number;
2137
+ /** Direction of traversal (default: `"out"`). */
2138
+ direction?: TraversalDirection;
2139
+ /** Cycle policy (default: `"prevent"`). */
2140
+ cyclePolicy?: AlgorithmCyclePolicy;
2141
+ }>;
2142
+ /**
2143
+ * A node reached during traversal, annotated with the shortest depth at which
2144
+ * it was first discovered.
2145
+ */
2146
+ type ReachableNode = Readonly<{
2147
+ id: string;
2148
+ kind: string;
2149
+ /** Number of edges traversed from the source. 0 for the source itself. */
2150
+ depth: number;
2151
+ }>;
2152
+ /**
2153
+ * A node along a shortest path. Endpoints are included.
2154
+ */
2155
+ type PathNode = Readonly<{
2156
+ id: string;
2157
+ kind: string;
2158
+ }>;
2159
+ /**
2160
+ * Result of `shortestPath`: the ordered node sequence and its length in hops.
2161
+ */
2162
+ type ShortestPathResult = Readonly<{
2163
+ /** Ordered nodes from source to target (inclusive). */
2164
+ nodes: readonly PathNode[];
2165
+ /** Number of edges traversed. Equals `nodes.length - 1`. */
2166
+ depth: number;
2167
+ }>;
2168
+ /**
2169
+ * Options for `shortestPath` and `canReach`. Reuses the base traversal
2170
+ * options; cycle policy defaults to `"prevent"` since both algorithms only
2171
+ * care about the first time a target is reached.
2172
+ */
2173
+ type ShortestPathOptions<G extends GraphDef> = BaseTraversalOptions<G>;
2174
+ /**
2175
+ * Options for `reachable`.
2176
+ *
2177
+ * Returns every node reachable from the source within `maxHops`, each
2178
+ * annotated with its minimum discovered depth. `depth: 0` refers to the
2179
+ * source itself and is included unless `excludeSource` is `true`.
2180
+ */
2181
+ type ReachableOptions<G extends GraphDef> = BaseTraversalOptions<G> & Readonly<{
2182
+ /** Exclude the source node from the result set (default: `false`). */
2183
+ excludeSource?: boolean;
2184
+ }>;
2185
+ /**
2186
+ * Options for `neighbors`.
2187
+ *
2188
+ * Like `reachable`, but the parameter is named `depth` for readability —
2189
+ * "2-hop neighbors" reads more naturally than "reachable with maxHops=2".
2190
+ * The source is always excluded.
2191
+ */
2192
+ type NeighborsOptions<G extends GraphDef> = TemporalAlgorithmOptions & Readonly<{
2193
+ /** Edge kinds to follow. At least one kind is required. */
2194
+ edges: readonly EdgeKinds<G>[];
2195
+ /** Maximum neighborhood depth (default: 1). Must be between 1 and 1000. */
2196
+ depth?: number;
2197
+ /** Direction of traversal (default: `"out"`). */
2198
+ direction?: TraversalDirection;
2199
+ /** Cycle policy (default: `"prevent"`). */
2200
+ cyclePolicy?: AlgorithmCyclePolicy;
2201
+ }>;
2202
+ /**
2203
+ * Options for `degree`.
2204
+ *
2205
+ * Counts active edges incident to a node. With `direction: "both"`, an edge
2206
+ * that happens to be a self-loop (from === to) is counted once, not twice.
2207
+ */
2208
+ type DegreeOptions<G extends GraphDef> = TemporalAlgorithmOptions & Readonly<{
2209
+ /**
2210
+ * Edge kinds to count. If omitted, counts across all edge kinds in the
2211
+ * graph.
2212
+ */
2213
+ edges?: readonly EdgeKinds<G>[];
2214
+ /** Direction (default: `"both"`). */
2215
+ direction?: TraversalDirection;
2216
+ }>;
2217
+
2218
+ /**
2219
+ * Raw node id or any object with an `id: string` field. Covers `Node`,
2220
+ * `NodeRef`, and the lightweight `ReachableNode` / `PathNode` shapes
2221
+ * returned by the algorithms themselves.
2222
+ *
2223
+ * Deliberately kind-agnostic: graph algorithms don't constrain the source
2224
+ * node's kind — you can start a traversal from any node reachable via the
2225
+ * given edge kinds. `NodeRef<N>` exists for the edge-endpoint case where
2226
+ * kind *is* load-bearing; using it here would paint a constraint onto a
2227
+ * contract that doesn't need one and would reject common patterns like
2228
+ * passing `ReachableNode` / cache entries / `{ id }` records straight
2229
+ * through.
2230
+ */
2231
+ type NodeIdentifier = string | Readonly<{
2232
+ id: string;
2233
+ }>;
2234
+ type GraphAlgorithms<G extends GraphDef> = Readonly<{
2235
+ /**
2236
+ * Finds the shortest directed path from `from` to `to` using the given
2237
+ * edge kinds. Returns `undefined` when no path exists within `maxHops`.
2238
+ *
2239
+ * @example
2240
+ * ```typescript
2241
+ * const path = await store.algorithms.shortestPath(alice, bob, {
2242
+ * edges: ["knows"],
2243
+ * maxHops: 6,
2244
+ * });
2245
+ * if (path) {
2246
+ * console.log(`${path.depth} hops via`, path.nodes.map((n) => n.id));
2247
+ * }
2248
+ * ```
2249
+ */
2250
+ shortestPath: (from: NodeIdentifier, to: NodeIdentifier, options: ShortestPathOptions<G>) => Promise<ShortestPathResult | undefined>;
2251
+ /**
2252
+ * Returns every node reachable from `from` within `maxHops` edges of the
2253
+ * allowed kinds. Each node carries its minimum discovered depth.
2254
+ */
2255
+ reachable: (from: NodeIdentifier, options: ReachableOptions<G>) => Promise<readonly ReachableNode[]>;
2256
+ /**
2257
+ * Fast boolean check: is `to` reachable from `from` within `maxHops`
2258
+ * edges? Short-circuits the underlying recursive CTE with `LIMIT 1`.
2259
+ */
2260
+ canReach: (from: NodeIdentifier, to: NodeIdentifier, options: BaseTraversalOptions<G>) => Promise<boolean>;
2261
+ /**
2262
+ * Returns the k-hop neighborhood of a node. The source is always
2263
+ * excluded. `depth` defaults to 1, matching the common "immediate
2264
+ * neighbors" interpretation.
2265
+ */
2266
+ neighbors: (node: NodeIdentifier, options: NeighborsOptions<G>) => Promise<readonly ReachableNode[]>;
2267
+ /**
2268
+ * Counts active edges incident to `node`.
2269
+ *
2270
+ * With `direction: "both"` (default), self-loops contribute once.
2271
+ */
2272
+ degree: (node: NodeIdentifier, options?: DegreeOptions<G>) => Promise<number>;
2273
+ }>;
2274
+
2076
2275
  /**
2077
2276
  * Main Store implementation for TypeGraph.
2078
2277
  *
@@ -2161,6 +2360,27 @@ declare class Store<G extends GraphDef> {
2161
2360
  * ```
2162
2361
  */
2163
2362
  get edges(): GraphEdgeCollections<G>;
2363
+ /**
2364
+ * Tier 1 graph algorithms: shortest path, reachability, neighborhoods, and
2365
+ * degree centrality.
2366
+ *
2367
+ * Each call compiles to a single recursive-CTE query against the backend.
2368
+ * The facade is built lazily on first access and cached for the lifetime
2369
+ * of the store.
2370
+ *
2371
+ * @example
2372
+ * ```typescript
2373
+ * const path = await store.algorithms.shortestPath(alice, bob, {
2374
+ * edges: ["knows"],
2375
+ * });
2376
+ *
2377
+ * const friends = await store.algorithms.neighbors(alice, {
2378
+ * edges: ["knows"],
2379
+ * depth: 2,
2380
+ * });
2381
+ * ```
2382
+ */
2383
+ get algorithms(): GraphAlgorithms<G>;
2164
2384
  /**
2165
2385
  * Returns the node collection for the given kind, or undefined if the kind
2166
2386
  * is not registered in this graph.
@@ -2354,4 +2574,4 @@ declare function createStore<G extends GraphDef>(graph: G, backend: GraphBackend
2354
2574
  */
2355
2575
  declare function createStoreWithSchema<G extends GraphDef>(graph: G, backend: GraphBackend, options?: StoreOptions & SchemaManagerOptions): Promise<[Store<G>, SchemaValidationResult]>;
2356
2576
 
2357
- export { type StoreProjection as $, type AliasMap as A, type BatchResults as B, type CreateQueryBuilderOptions as C, type DynamicEdgeCollection as D, type EdgeAliasMap as E, type FieldAccessor as F, type GetOrCreateAction as G, type HookContext as H, type IfExistsMode as I, type PaginatedResult as J, type Predicate as K, PreparedQuery as L, type PropsAccessor as M, type Node as N, type OperationHookContext as O, type PaginateOptions as P, QueryBuilder as Q, type QueryHookContext as R, type QueryOptions as S, TraversalBuilder as T, type RecursiveTraversalOptions as U, type SelectContext as V, type SelectableEdge as W, type SelectableNode as X, Store as Y, type StoreHooks as Z, type StoreOptions as _, type AggregateResult as a, type StreamOptions as a0, type SubgraphEdgeResult as a1, type SubgraphNodeResult as a2, type SubgraphOptions as a3, type SubgraphResult as a4, type SubsetEdge as a5, type SubsetNode as a6, type TransactionContext as a7, type TypedEdgeCollection as a8, UnionableQuery as a9, type UpdateEdgeInput as aa, type UpdateNodeInput as ab, createStore as ac, createStoreWithSchema as ad, defineSubgraphProject as ae, embedding as af, exists as ag, fieldRef as ah, getEmbeddingDimensions as ai, inSubquery as aj, isEmbeddingSchema as ak, isParameterRef as al, notExists as am, notInSubquery as an, param as ao, type AnyEdge as b, type AnyNode as c, type BatchableQuery as d, type ConstraintNames as e, type CreateEdgeInput as f, type CreateNodeInput as g, type DynamicNodeCollection as h, type Edge as i, type EdgeAccessor as j, type EdgeCollection as k, type EdgeFindByEndpointsOptions as l, type EdgeGetOrCreateByEndpointsOptions as m, type EdgeGetOrCreateByEndpointsResult as n, type EmbeddingSchema as o, type EmbeddingValue as p, ExecutableAggregateQuery as q, ExecutableQuery as r, type GraphEdgeCollections as s, type GraphNodeCollections as t, type NodeAccessor as u, type NodeAlias as v, type NodeCollection as w, type NodeGetOrCreateByConstraintOptions as x, type NodeGetOrCreateByConstraintResult as y, type NodeRef as z };
2577
+ export { type ReachableNode as $, type AliasMap as A, type BaseTraversalOptions as B, type CreateQueryBuilderOptions as C, type DegreeOptions as D, type EdgeAliasMap as E, type FieldAccessor as F, type GetOrCreateAction as G, type HookContext as H, type IfExistsMode as I, type NodeAlias as J, type NodeCollection as K, type NodeGetOrCreateByConstraintOptions as L, type NodeGetOrCreateByConstraintResult as M, type NeighborsOptions as N, type NodeIdentifier as O, type NodeRef as P, QueryBuilder as Q, type OperationHookContext as R, type PaginateOptions as S, TraversalBuilder as T, type PaginatedResult as U, type PathNode as V, type Predicate as W, PreparedQuery as X, type PropsAccessor as Y, type QueryHookContext as Z, type QueryOptions as _, type AggregateResult as a, type ReachableOptions as a0, type RecursiveTraversalOptions as a1, type SelectContext as a2, type SelectableEdge as a3, type SelectableNode as a4, type ShortestPathOptions as a5, type ShortestPathResult as a6, Store as a7, type StoreHooks as a8, type StoreOptions as a9, notInSubquery as aA, param as aB, type StoreProjection as aa, type StreamOptions as ab, type SubgraphEdgeResult as ac, type SubgraphNodeResult as ad, type SubgraphOptions as ae, type SubgraphResult as af, type SubsetEdge as ag, type SubsetNode as ah, type TemporalAlgorithmOptions as ai, type TransactionContext as aj, type TraversalDirection as ak, type TypedEdgeCollection as al, UnionableQuery as am, type UpdateEdgeInput as an, type UpdateNodeInput as ao, createStore as ap, createStoreWithSchema as aq, defineSubgraphProject as ar, embedding as as, exists as at, fieldRef as au, getEmbeddingDimensions as av, inSubquery as aw, isEmbeddingSchema as ax, isParameterRef as ay, notExists as az, type AlgorithmCyclePolicy as b, type AnyEdge as c, type AnyNode as d, type BatchResults as e, type BatchableQuery as f, type ConstraintNames as g, type CreateEdgeInput as h, type CreateNodeInput as i, type DynamicEdgeCollection as j, type DynamicNodeCollection as k, type Edge as l, type EdgeAccessor as m, type EdgeCollection as n, type EdgeFindByEndpointsOptions as o, type EdgeGetOrCreateByEndpointsOptions as p, type EdgeGetOrCreateByEndpointsResult as q, type EmbeddingSchema as r, type EmbeddingValue as s, ExecutableAggregateQuery as t, ExecutableQuery as u, type GraphAlgorithms as v, type GraphEdgeCollections as w, type GraphNodeCollections as x, type Node as y, type NodeAccessor as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nicia-ai/typegraph",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "TypeScript-first embedded knowledge graph library with ontological reasoning",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -155,17 +155,17 @@
155
155
  "@types/better-sqlite3": "^7.6.13",
156
156
  "@types/node": "^24.12.0",
157
157
  "@types/pg": "^8.20.0",
158
- "@vitest/coverage-v8": "^4.1.2",
158
+ "@vitest/coverage-v8": "^4.1.3",
159
159
  "better-sqlite3": "^12.8.0",
160
160
  "drizzle-orm": "^0.45.2",
161
- "eslint": "^10.1.0",
161
+ "eslint": "^10.2.0",
162
162
  "fast-check": "^4.6.0",
163
163
  "pg": "^8.20.0",
164
- "sqlite-vec": "^0.1.8",
164
+ "sqlite-vec": "^0.1.9",
165
165
  "tsd": "^0.33.0",
166
166
  "tsup": "^8.5.1",
167
167
  "typescript": "^5.9.3",
168
- "vitest": "^4.1.2",
168
+ "vitest": "^4.1.3",
169
169
  "zod": "^4.3.6",
170
170
  "@typegraph/eslint-config": "0.1.0"
171
171
  },