From 201572512eb08f64736468583f9e392c1f0f8b1a Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 26 Jun 2026 00:40:25 -0500 Subject: [PATCH] feat: dependency graph topological sort with cycle/missing-dep validation --- src/graph.ts | 39 +++++++++++++++++++++++++++++++++++++++ test/graph.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 src/graph.ts create mode 100644 test/graph.test.ts diff --git a/src/graph.ts b/src/graph.ts new file mode 100644 index 0000000..76f3112 --- /dev/null +++ b/src/graph.ts @@ -0,0 +1,39 @@ +export interface GraphNode { + name: string; + needs: string[]; + provides: string[]; + origin: string; +} + +export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { + const producedBy = new Map(); + for (const n of nodes) for (const key of n.provides) producedBy.set(key, n); + + // validate dependencies exist + for (const n of nodes) { + for (const key of n.needs) { + if (!seedKeys.includes(key) && !producedBy.has(key)) { + throw new Error(`missing dependency: ${key} needed by ${n.name}`); + } + } + } + + const ordered: GraphNode[] = []; + const state = new Map(); + + const visit = (n: GraphNode, trail: string[]): void => { + const s = state.get(n); + if (s === 'done') return; + if (s === 'visiting') throw new Error(`cycle detected: ${[...trail, n.name].join(' -> ')}`); + state.set(n, 'visiting'); + for (const key of n.needs) { + const dep = producedBy.get(key); + if (dep && dep !== n) visit(dep, [...trail, n.name]); + } + state.set(n, 'done'); + ordered.push(n); + }; + + for (const n of nodes) visit(n, []); + return ordered; +} diff --git a/test/graph.test.ts b/test/graph.test.ts new file mode 100644 index 0000000..f59b92e --- /dev/null +++ b/test/graph.test.ts @@ -0,0 +1,25 @@ +import { expect, test } from 'vitest'; +import { topoSort, GraphNode } from '../src/graph'; + +const node = (name: string, needs: string[], provides: string[]): GraphNode => + ({ name, needs, provides, origin: 'test' }); + +test('orders nodes so dependencies come first (regardless of input order)', () => { + const nodes = [ + node('handler', ['user'], []), + node('auth', ['db'], ['user']), + node('db', ['config'], ['db']), + ]; + const ordered = topoSort(nodes, ['config']).map((n) => n.name); + expect(ordered).toEqual(['db', 'auth', 'handler']); +}); + +test('throws on missing dependency', () => { + const nodes = [node('handler', ['user'], [])]; + expect(() => topoSort(nodes, [])).toThrow(/missing dependency: user needed by handler/); +}); + +test('throws on cycle', () => { + const nodes = [node('a', ['b'], ['a']), node('b', ['a'], ['b'])]; + expect(() => topoSort(nodes, [])).toThrow(/cycle detected/); +});