diff --git a/docs/quickstart.md b/docs/quickstart.md index 6db7651..d7fcdbe 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -228,6 +228,47 @@ const app = createApp({ modules: [ApiModule], plugins: [logger] }); Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`, `mesh:connect|disconnect|rpc:error`, `plugin:mounted`. +## Inspect & test the graph + +### Visualize with Mermaid + +```typescript +console.log(app.toMermaid()); // flowchart diagram of all nodes and routes +``` + +Enable a live `GET /__graph__` endpoint (renders HTML with Mermaid, or plain-text with `Accept: text/plain`): + +```typescript +const app = createApp({ modules: [ApiModule], devGraph: true }); +// GET /__graph__ → HTML viewer +// GET /__graph__ (text/plain) → raw Mermaid source +``` + +### Explain a route + +```typescript +const e = app.explain('/api/users/:id'); +// { pattern, method, transport, chain: [{ name, kind, origin, needs, provides }, ...] } +console.log(e.chain.map((n) => `${n.kind}:${n.name}`)); +// → ['provider:db', 'step:user', 'handler:getUser'] +``` + +### Override tokens in tests + +Swap any provider or step token with a test double at construction time — no monkey-patching: + +```typescript +const app = createApp({ + modules: [ApiModule], + overrides: { + db: { find: () => ({ id: 'test-user' }) }, // plain object — wrapped as { db: value } + user: () => ({ user: { id: 'stub' } }), // function runner + }, +}); +``` + +Overrides replace only the named token's runner; the rest of the graph is untouched. + ## The one rule to remember ``` diff --git a/example/server.ts b/example/server.ts index 7ab6c97..c9c1367 100644 --- a/example/server.ts +++ b/example/server.ts @@ -67,6 +67,8 @@ export const streamApp = createApp({ modules: [StreamModule] }); if (require.main === module) { console.log('chain for /api/users/:id ->', app.inspect('/api/users/:id')); + console.log('graph:\n' + app.toMermaid()); + console.log('explain /api/users/:id:', app.explain('/api/users/:id')); app.listen(3000).then(() => console.log('green-tea on http://localhost:3000')); streamApp.listen(3001).then(() => console.log('green-tea streams on http://localhost:3001')); } diff --git a/src/app.ts b/src/app.ts index aacd63b..7d1af04 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,7 +1,7 @@ import http from 'http'; import { Bus } from './bus'; import { Container } from './container'; -import { topoSort, subgraphFor, GraphNode } from './graph'; +import { topoSort, subgraphFor, GraphNode, nearest } from './graph'; import { toMermaid, toDOT, graphHtml, type GraphView } from './graph-viz'; import { runPipeline, PipelineStep } from './pipeline'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http'; @@ -153,7 +153,8 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me for (const plan of routePlans) { for (const need of plan.needs) { if (!allowed.has(need)) { - throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it`); + const hint = nearest(need, allowed); + throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`); } } } diff --git a/src/graph.ts b/src/graph.ts index 7a215a9..1e992d1 100644 --- a/src/graph.ts +++ b/src/graph.ts @@ -1,3 +1,21 @@ +function levenshtein(a: string, b: string): number { + const m = a.length, n = b.length; + const d: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); + for (let i = 0; i <= m; i++) d[i][0] = i; + for (let j = 0; j <= n; j++) d[0][j] = j; + for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) { + d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); + } + return d[m][n]; +} + +export function nearest(token: string, candidates: Iterable): string | undefined { + let best: string | undefined; + let bestD = 3; // only suggest edit distance <= 2 + for (const c of candidates) { const dist = levenshtein(token, c); if (dist < bestD) { bestD = dist; best = c; } } + return best; +} + export interface GraphNode { name: string; needs: string[]; diff --git a/test/app.test.ts b/test/app.test.ts index c1a5ddb..d555167 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -108,6 +108,13 @@ test('boot fails when a handler needs something nothing provides', () => { .toThrow(/handler 'list' needs 'missing'/); }); +it('boot error for a misspelled @needs suggests the closest token', () => { + @Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } } + @Route('/u') class Ctl { @Get('/x') x(@needs('usr') u: any) { return { u }; } } + @Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {} + expect(() => createApp({ modules: [M] })).toThrow(/did you mean 'user'\?/); +}); + import { Sse, Ws } from '../src/metadata'; import { inbound } from '../src/params'; import { channel } from '../src/channel'; diff --git a/test/graph.test.ts b/test/graph.test.ts index a64bb44..dc5e825 100644 --- a/test/graph.test.ts +++ b/test/graph.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, test } from 'vitest'; -import { topoSort, GraphNode, subgraphFor } from '../src/graph'; +import { topoSort, GraphNode, subgraphFor, nearest } from '../src/graph'; const node = (name: string, needs: string[], provides: string[]): GraphNode => ({ name, needs, provides, origin: 'test' }); @@ -41,3 +41,13 @@ describe('subgraphFor', () => { expect(subgraphFor(['user'], ordered).map((n) => n.name)).not.toContain('audit'); }); }); + +describe('nearest', () => { + it('suggests a close candidate (edit distance <= 2)', () => { + expect(nearest('usr', ['user', 'config', 'db'])).toBe('user'); + expect(nearest('confgi', ['user', 'config'])).toBe('config'); + }); + it('returns undefined when nothing is close', () => { + expect(nearest('zzzzzz', ['user', 'db'])).toBeUndefined(); + }); +}); diff --git a/test/types/flow-types.test.ts b/test/types/flow-types.test.ts index 66c5c1f..a6e76cf 100644 --- a/test/types/flow-types.test.ts +++ b/test/types/flow-types.test.ts @@ -12,5 +12,11 @@ test('type guarantee holds (this file must typecheck)', () => { // @ts-expect-error — `user` is not in the accumulated context .handle((ctx) => ctx.user); + // GUARANTEE: a step can only read tokens produced by PRIOR steps. + flow<{ req: { token: string } }>() + .step('user', (ctx) => ({ user: ctx.req.token })) // produces `user` + // @ts-expect-error — `db` was never produced by a prior step (only `user` was) + .step('next', (ctx) => ({ next: ctx.db })); + expect(true).toBe(true); });