Compare commits
10
Commits
cc0044ba6a
...
e38d972566
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e38d972566 | ||
|
|
c39eb667ac | ||
|
|
0c29c76a8a | ||
|
|
8335ff2875 | ||
|
|
3842271c4d | ||
|
|
9050a7e5d9 | ||
|
|
6171e5e6bd | ||
|
|
2bbc43505e | ||
|
|
07b6b57611 | ||
|
|
9d8088d0a9 |
No files matched your search
@@ -228,6 +228,81 @@ 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.
|
||||
|
||||
## Runnable examples
|
||||
|
||||
The `example/` directory holds end-to-end apps you can `node`-run and read top to bottom.
|
||||
|
||||
### CRUD — methods, query, JSON & urlencoded body
|
||||
|
||||
`@Get/@Post/@Put/@Patch/@Delete` over a provider-backed store. Filter via `@query('done')`,
|
||||
read the payload via `@body()` — the same handler accepts both `application/json` and
|
||||
`application/x-www-form-urlencoded` (the transport parses each into a plain object). Missing
|
||||
rows throw `NotFound` (→ 404).
|
||||
|
||||
See [`example/crud.ts`](../example/crud.ts).
|
||||
|
||||
### Chat — rooms + handshake auth
|
||||
|
||||
A `@Step` reads `?token=` and `provides: 'user'`, throwing `Unauthorized` on a missing token —
|
||||
which closes the socket with code **4401** (`4000 + status`). The `@Ws` handler pumps the
|
||||
`@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel,
|
||||
so every joined socket multicasts to the others. `rooms` is the built-in shared `Rooms`
|
||||
primitive (one instance app-wide).
|
||||
|
||||
See [`example/chat.ts`](../example/chat.ts).
|
||||
|
||||
### GraphQL — query/mutation over POST, subscription over SSE
|
||||
|
||||
A schema built programmatically with `graphql` (a dev/example dependency — the core has no
|
||||
runtime dep on it). `POST /graphql` runs queries and mutations through `graphql()`. The
|
||||
`mutation` pushes each new message into `rooms.room('messages')`; the `@Sse('/stream')` route
|
||||
calls `subscribe()` whose source **is** that room, guards the result with `isAsyncIterable`,
|
||||
and returns it — the framework streams each `ExecutionResult` as an SSE `data:` frame. This is
|
||||
the tie between GraphQL, green-tea streams, and the `rooms` primitive.
|
||||
|
||||
See [`example/graphql.ts`](../example/graphql.ts) — `npm install graphql` first.
|
||||
|
||||
## The one rule to remember
|
||||
|
||||
```
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { createApp, Step, Route, Ws, Module, Unauthorized, param, needs, inbound, Rooms } from '../src/index';
|
||||
|
||||
@Step({ provides: 'user', needs: [] })
|
||||
class Authenticate {
|
||||
run(ctx: any) {
|
||||
const token = ctx.query?.token; // steps read ctx directly (no @query on steps)
|
||||
if (!token) throw new Unauthorized('token required');
|
||||
return { user: { id: String(token) } };
|
||||
}
|
||||
}
|
||||
|
||||
@Route('/chat')
|
||||
class ChatController {
|
||||
@Ws('/:room')
|
||||
join(@param('room') room: string, @needs('user') user: any, @needs('rooms') rooms: Rooms, @inbound() incoming: AsyncIterable<string>) {
|
||||
const hub = rooms.room<string>(room);
|
||||
(async () => { for await (const msg of incoming) hub.push(`${user.id}: ${msg}`); })().catch(() => {}); // fire-and-forget pump
|
||||
return hub; // broadcast as the outbound channel
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', steps: [Authenticate], controllers: [ChatController] })
|
||||
class ChatModule {}
|
||||
|
||||
export const app = createApp({ modules: [ChatModule] });
|
||||
|
||||
if (require.main === module) {
|
||||
app.listen(4100).then(() => console.log('chat on ws://localhost:4100/chat/:room?token=...'));
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
createApp, Provider, Route,
|
||||
Get, Post, Put, Patch, Delete,
|
||||
Module, needs, param, query, body, NotFound,
|
||||
} from '../src/index';
|
||||
|
||||
interface Todo { id: string; title: string; done: boolean }
|
||||
|
||||
interface Store {
|
||||
todos: Map<string, Todo>;
|
||||
next(): string;
|
||||
}
|
||||
|
||||
@Provider({ provides: 'store' })
|
||||
class TodoStore {
|
||||
private counter = 0;
|
||||
private readonly todos: Map<string, Todo> = new Map();
|
||||
|
||||
provide(): { store: Store } {
|
||||
const store: Store = {
|
||||
todos: this.todos,
|
||||
next: () => String(++this.counter),
|
||||
};
|
||||
return { store };
|
||||
}
|
||||
}
|
||||
|
||||
@Route('/todos')
|
||||
class TodoController {
|
||||
@Get('/')
|
||||
list(@needs('store') store: Store, @query('done') done: string | undefined): Todo[] {
|
||||
const all = [...store.todos.values()];
|
||||
if (done !== undefined) {
|
||||
const flag = done === 'true';
|
||||
return all.filter((t) => t.done === flag);
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
@Get('/:id')
|
||||
get(@needs('store') store: Store, @param('id') id: string): Todo {
|
||||
const todo = store.todos.get(id);
|
||||
if (!todo) throw new NotFound(`todo ${id} not found`);
|
||||
return todo;
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
create(@needs('store') store: Store, @body() data: Record<string, unknown>): Todo {
|
||||
const id = store.next();
|
||||
const todo: Todo = { id, title: String(data.title ?? ''), done: false };
|
||||
store.todos.set(id, todo);
|
||||
return todo;
|
||||
}
|
||||
|
||||
@Put('/:id')
|
||||
replace(@needs('store') store: Store, @param('id') id: string, @body() data: Record<string, unknown>): Todo {
|
||||
if (!store.todos.has(id)) throw new NotFound(`todo ${id} not found`);
|
||||
const todo: Todo = { id, title: String(data.title ?? ''), done: Boolean(data.done ?? false) };
|
||||
store.todos.set(id, todo);
|
||||
return todo;
|
||||
}
|
||||
|
||||
@Patch('/:id')
|
||||
merge(@needs('store') store: Store, @param('id') id: string, @body() data: Record<string, unknown>): Todo {
|
||||
const todo = store.todos.get(id);
|
||||
if (!todo) throw new NotFound(`todo ${id} not found`);
|
||||
const updated: Todo = {
|
||||
id,
|
||||
title: 'title' in data ? String(data.title) : todo.title,
|
||||
done: 'done' in data ? Boolean(data.done) : todo.done,
|
||||
};
|
||||
store.todos.set(id, updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
remove(@needs('store') store: Store, @param('id') id: string): { deleted: string } {
|
||||
if (!store.todos.has(id)) throw new NotFound(`todo ${id} not found`);
|
||||
store.todos.delete(id);
|
||||
return { deleted: id };
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/api', providers: [TodoStore], controllers: [TodoController] })
|
||||
class TodoModule {}
|
||||
|
||||
export const app = createApp({ modules: [TodoModule] });
|
||||
|
||||
if (require.main === module) {
|
||||
app.listen(3300).then(() => console.log('green-tea crud on http://localhost:3300'));
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLList, GraphQLNonNull, graphql, subscribe, parse } from 'graphql';
|
||||
import { createApp, Route, Post, Sse, Module, body, needs, isAsyncIterable, Rooms } from '../src/index';
|
||||
|
||||
interface Message { text: string }
|
||||
const store: Message[] = [];
|
||||
const MessageType = new GraphQLObjectType({ name: 'Message', fields: { text: { type: GraphQLString } } });
|
||||
|
||||
function buildSchema(rooms: Rooms): GraphQLSchema {
|
||||
return new GraphQLSchema({
|
||||
query: new GraphQLObjectType({ name: 'Query', fields: {
|
||||
messages: { type: new GraphQLList(MessageType), resolve: () => store },
|
||||
} }),
|
||||
mutation: new GraphQLObjectType({ name: 'Mutation', fields: {
|
||||
postMessage: { type: MessageType, args: { text: { type: new GraphQLNonNull(GraphQLString) } },
|
||||
resolve: (_root, { text }: { text: string }) => { const m = { text }; store.push(m); rooms.room('messages').push(m); return m; } },
|
||||
} }),
|
||||
subscription: new GraphQLObjectType({ name: 'Subscription', fields: {
|
||||
messageAdded: { type: MessageType,
|
||||
subscribe: () => rooms.room<Message>('messages'), // Channel is the AsyncIterable source
|
||||
resolve: (payload: Message) => payload },
|
||||
} }),
|
||||
});
|
||||
}
|
||||
|
||||
@Route('/graphql')
|
||||
class GraphQLController {
|
||||
@Post('')
|
||||
async run(@body() input: any, @needs('rooms') rooms: Rooms) {
|
||||
return graphql({ schema: buildSchema(rooms), source: input?.query ?? '', variableValues: input?.variables });
|
||||
}
|
||||
|
||||
@Sse('/stream')
|
||||
async stream(@needs('rooms') rooms: Rooms) {
|
||||
const result = await subscribe({ schema: buildSchema(rooms), document: parse('subscription { messageAdded { text } }') });
|
||||
if (!isAsyncIterable(result)) throw new Error('subscription failed'); // subscribe() returns a single ExecutionResult on error
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [GraphQLController] })
|
||||
class GraphQLModule {}
|
||||
|
||||
export const app = createApp({ modules: [GraphQLModule] });
|
||||
|
||||
if (require.main === module) {
|
||||
app.listen(4200).then(() => console.log('graphql on http://localhost:4200/graphql'));
|
||||
}
|
||||
@@ -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'));
|
||||
}
|
||||
|
||||
Generated
+19
@@ -14,9 +14,18 @@
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.19.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"graphql": "^16.9.0",
|
||||
"typescript": "^5.5.0",
|
||||
"vitest": "^2.0.0",
|
||||
"ws": "^8.21.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"ws": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
@@ -1063,6 +1072,16 @@
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/graphql": {
|
||||
"version": "16.14.2",
|
||||
"resolved": "https://registry.npmjs.org/graphql/-/graphql-16.14.2.tgz",
|
||||
"integrity": "sha512-Chq1s4CY7jmh8gO2qvLIJyfCDIN+EHLFW/9iShnp1z8FjBQMoodWP1kDC36VAMXXIvAjj4ARa7ntfAV2BrjsbA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/loupe": {
|
||||
"version": "3.2.1",
|
||||
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.19.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"graphql": "^16.9.0",
|
||||
"typescript": "^5.5.0",
|
||||
"vitest": "^2.0.0",
|
||||
"ws": "^8.21.0"
|
||||
|
||||
+12
-2
@@ -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';
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from './metadata';
|
||||
import { getArgs, getHandlerNeeds, resolveArgs } from './params';
|
||||
import { connectLink, type Link } from './mesh/link';
|
||||
import { Rooms } from './rooms';
|
||||
import { buildRemote } from './mesh/teacup';
|
||||
import { buildManifest, createMeshControl } from './mesh/teapot';
|
||||
import type { MeshControl } from './http';
|
||||
@@ -126,6 +127,14 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
||||
setRunner(n.name, n.run);
|
||||
}
|
||||
|
||||
// built-in: auto-provide a shared Rooms instance (unless the user declares one)
|
||||
if (!runners.has('rooms')) {
|
||||
const roomsInstance = new Rooms();
|
||||
providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' });
|
||||
providerMeta.set('rooms', { optional: false });
|
||||
setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms
|
||||
}
|
||||
|
||||
// For each route, resolve which providers/steps feed it via topo order.
|
||||
// MVP: every route depends on every declared step + provider in the app graph.
|
||||
// For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first.
|
||||
@@ -153,7 +162,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}'?` : ''}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>): 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[];
|
||||
|
||||
+10
-2
@@ -2,7 +2,7 @@ import http from 'http';
|
||||
import { once } from 'events';
|
||||
import { channel } from './channel';
|
||||
import { errorToResponse } from './transformers';
|
||||
import { HttpError } from './signals';
|
||||
import { HttpError, isHttpError } from './signals';
|
||||
import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
|
||||
import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
|
||||
import type { Transport } from './metadata';
|
||||
@@ -91,6 +91,7 @@ async function pipeStream(
|
||||
bus?: Bus, name = '', streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
res.writeHead(200, encoder.headers);
|
||||
res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers
|
||||
bus?.emit('stream:open', { name });
|
||||
const it = stream[Symbol.asyncIterator]();
|
||||
let ping: ReturnType<typeof setInterval> | undefined;
|
||||
@@ -167,7 +168,12 @@ function attachWs(
|
||||
try { ws.close(); } catch { /* already closed */ }
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, error: err });
|
||||
try { ws.close(1011); } catch { /* already closed */ }
|
||||
if (isHttpError(err)) {
|
||||
const reason = Buffer.from(String(err.message)).subarray(0, 120).toString();
|
||||
try { ws.close(4000 + err.status, reason); } catch { /* already closed */ }
|
||||
} else {
|
||||
try { ws.close(1011); } catch { /* already closed */ }
|
||||
}
|
||||
} finally {
|
||||
ac.abort();
|
||||
bus?.emit('stream:close', { name });
|
||||
@@ -207,6 +213,8 @@ export function createHttpServer(
|
||||
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
|
||||
return;
|
||||
}
|
||||
} else if (raw !== undefined && ct.includes('application/x-www-form-urlencoded')) {
|
||||
body = Object.fromEntries(new URLSearchParams(raw));
|
||||
}
|
||||
let result: PipelineResult;
|
||||
try {
|
||||
|
||||
@@ -16,6 +16,7 @@ export { needs, ctx, param, query, body, headers } from './params';
|
||||
export type { Query, Headers, Context, ArgSpec } from './params';
|
||||
export { channel, isAsyncIterable } from './channel';
|
||||
export type { Channel } from './channel';
|
||||
export { Rooms } from './rooms';
|
||||
export { Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata';
|
||||
export type { Transport, HttpMethod } from './metadata';
|
||||
export { inbound, abort } from './params';
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { channel, type Channel } from './channel';
|
||||
|
||||
export class Rooms {
|
||||
private readonly hubs = new Map<string, Channel<unknown>>();
|
||||
room<T = unknown>(name: string): Channel<T> {
|
||||
let hub = this.hubs.get(name);
|
||||
if (!hub) { hub = channel<unknown>(); this.hubs.set(name, hub); }
|
||||
return hub as unknown as Channel<T>;
|
||||
}
|
||||
names(): string[] { return [...this.hubs.keys()]; }
|
||||
}
|
||||
@@ -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';
|
||||
@@ -209,6 +216,7 @@ describe('per-route subgraph slicing', () => {
|
||||
});
|
||||
});
|
||||
|
||||
import { Rooms } from '../src/rooms';
|
||||
import { toMermaid as renderMermaid } from '../src/graph-viz';
|
||||
|
||||
describe('app.graph / explain', () => {
|
||||
@@ -310,3 +318,21 @@ describe('overrides', () => {
|
||||
await expect(app.listen(0)).rejects.toThrow(/unknown token 'nope'/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rooms auto-provide', () => {
|
||||
it('injects a built-in rooms instance resolvable via @needs("rooms")', async () => {
|
||||
@Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: Rooms) { return { ok: rooms instanceof Rooms }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const s = await app.listen(0);
|
||||
const port = (s.address() as any).port;
|
||||
expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true });
|
||||
s.close();
|
||||
});
|
||||
it('a user-declared rooms provider wins (no duplicate-name throw)', () => {
|
||||
@Provider({ provides: 'rooms' }) class MyRooms { provide() { return { rooms: { custom: true } }; } }
|
||||
@Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: any) { return rooms; } }
|
||||
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] }) class M {}
|
||||
expect(() => createApp({ modules: [M] })).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, it, expect, afterAll } from 'vitest';
|
||||
import { app } from '../../example/chat';
|
||||
|
||||
let server: any; let port: number;
|
||||
afterAll(() => server?.close());
|
||||
|
||||
describe('chat example', () => {
|
||||
it('two authed clients in a room see each other; missing token is rejected 4401', async () => {
|
||||
server = await app.listen(0); port = (server.address() as any).port;
|
||||
const WebSocket = (await import('ws')).default;
|
||||
|
||||
const a = new WebSocket(`ws://127.0.0.1:${port}/chat/general?token=alice`);
|
||||
const b = new WebSocket(`ws://127.0.0.1:${port}/chat/general?token=bob`);
|
||||
await Promise.all([new Promise((r) => a.on('open', r)), new Promise((r) => b.on('open', r))]);
|
||||
const bGot = new Promise<string>((r) => b.on('message', (d: Buffer) => r(d.toString())));
|
||||
await new Promise((r) => setTimeout(r, 50)); // let server-side open()/subscribe complete (channel has no replay)
|
||||
a.send('hi');
|
||||
expect(await bGot).toContain('hi');
|
||||
a.close(); b.close();
|
||||
|
||||
const noTok = new WebSocket(`ws://127.0.0.1:${port}/chat/general`);
|
||||
const code = await new Promise<number>((r) => noTok.on('close', (c: number) => r(c)));
|
||||
expect(code).toBe(4401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, it, expect, afterAll } from 'vitest';
|
||||
import { app } from '../../example/crud';
|
||||
|
||||
let base: string; let server: any;
|
||||
const url = (p: string) => `${base}${p}`;
|
||||
afterAll(() => server?.close());
|
||||
|
||||
describe('crud example', () => {
|
||||
it('supports create / read / update / delete', async () => {
|
||||
server = await app.listen(0); base = `http://127.0.0.1:${(server.address() as any).port}`;
|
||||
const created = await fetch(url('/api/todos'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title: 'a' }) }).then((r) => r.json() as Promise<{ id: string; title: string; done: boolean }>);
|
||||
expect(created).toMatchObject({ title: 'a' });
|
||||
const id = created.id;
|
||||
expect(await fetch(url(`/api/todos/${id}`)).then((r) => r.json())).toMatchObject({ title: 'a' });
|
||||
await fetch(url(`/api/todos/${id}`), { method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ done: true }) });
|
||||
expect(await fetch(url(`/api/todos/${id}`)).then((r) => r.json())).toMatchObject({ done: true });
|
||||
const list = await fetch(url('/api/todos')).then((r) => r.json());
|
||||
expect(Array.isArray(list)).toBe(true);
|
||||
const del = await fetch(url(`/api/todos/${id}`), { method: 'DELETE' });
|
||||
expect(del.status).toBe(200);
|
||||
expect((await fetch(url(`/api/todos/${id}`))).status).toBe(404);
|
||||
});
|
||||
|
||||
it('accepts urlencoded form bodies', async () => {
|
||||
const res = await fetch(url('/api/todos'), { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'title=form' });
|
||||
expect(await res.json()).toMatchObject({ title: 'form' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, it, expect, afterAll } from 'vitest';
|
||||
import { app } from '../../example/graphql';
|
||||
|
||||
let server: any; let base: string;
|
||||
afterAll(() => server?.close());
|
||||
const gql = (query: string, variables?: any) =>
|
||||
fetch(`${base}/graphql`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query, variables }) }).then((r) => r.json() as Promise<any>);
|
||||
|
||||
describe('graphql example', () => {
|
||||
it('runs a query and a mutation, and streams a subscription over SSE', async () => {
|
||||
server = await app.listen(0); base = `http://127.0.0.1:${(server.address() as any).port}`;
|
||||
|
||||
expect(await gql('{ messages { text } }')).toMatchObject({ data: { messages: expect.any(Array) } });
|
||||
|
||||
const res = await fetch(`${base}/graphql/stream`, { headers: { accept: 'text/event-stream' } });
|
||||
const reader = res.body!.getReader();
|
||||
await new Promise((r) => setTimeout(r, 50)); // let the subscription subscribe to the room before publishing
|
||||
await gql('mutation($t:String!){ postMessage(text:$t){ text } }', { t: 'hello-sub' });
|
||||
const dec = new TextDecoder(); let buf = '';
|
||||
while (!buf.includes('hello-sub')) buf += dec.decode((await reader.read()).value);
|
||||
expect(buf).toContain('hello-sub');
|
||||
await reader.cancel();
|
||||
});
|
||||
});
|
||||
+11
-1
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -137,4 +137,18 @@ describe('request hardening', () => {
|
||||
expect(text).toContain('data: {"n":3}');
|
||||
server.close();
|
||||
});
|
||||
|
||||
it('parses application/x-www-form-urlencoded into an object body', async () => {
|
||||
const getUrl = (s: import('http').Server) => `http://127.0.0.1:${(s.address() as any).port}`;
|
||||
const server = createHttpServer([{
|
||||
method: 'POST', pattern: '/form', transport: 'buffer',
|
||||
handler: async (req) => ({ status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify(req.body) }),
|
||||
}]);
|
||||
await new Promise<void>((r) => server.listen(0, r));
|
||||
const res = await fetch(`${getUrl(server)}/form`, {
|
||||
method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'a=1&b=two',
|
||||
});
|
||||
expect(await res.json()).toEqual({ a: '1', b: 'two' });
|
||||
server.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { Rooms } from '../src/rooms';
|
||||
|
||||
describe('Rooms', () => {
|
||||
it('returns the same shared channel for a given name', () => {
|
||||
const r = new Rooms();
|
||||
expect(r.room('general')).toBe(r.room('general'));
|
||||
expect(r.room('a')).not.toBe(r.room('b'));
|
||||
});
|
||||
it('broadcasts a push to all current subscribers of a room', async () => {
|
||||
const r = new Rooms();
|
||||
const hub = r.room<number>('x');
|
||||
const a = hub[Symbol.asyncIterator]();
|
||||
const b = hub[Symbol.asyncIterator]();
|
||||
await Promise.resolve();
|
||||
hub.push(7);
|
||||
expect((await a.next()).value).toBe(7);
|
||||
expect((await b.next()).value).toBe(7);
|
||||
});
|
||||
it('isolates distinct rooms', async () => {
|
||||
const r = new Rooms();
|
||||
const it = r.room<number>('a')[Symbol.asyncIterator]();
|
||||
await Promise.resolve();
|
||||
r.room<number>('b').push(1);
|
||||
r.room<number>('a').push(2);
|
||||
expect((await it.next()).value).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';
|
||||
import WebSocket from 'ws';
|
||||
import { channel } from '../src/channel';
|
||||
import { createHttpServer, type WsRouteDef } from '../src/http';
|
||||
import { Unauthorized } from '../src/signals';
|
||||
|
||||
const url = (server: import('http').Server, path: string) => {
|
||||
const a = server.address();
|
||||
@@ -34,4 +35,19 @@ describe('ws upgrade', () => {
|
||||
expect(aborted).toBe(true);
|
||||
server.close();
|
||||
});
|
||||
|
||||
it('closes with a 4000+status code when the WS open() throws an HttpError', async () => {
|
||||
const wsRoutes = [{ pattern: '/secure', open: async () => { throw new Unauthorized('no token'); } }];
|
||||
const server = createHttpServer([], wsRoutes as any);
|
||||
await new Promise<void>((r) => server.listen(0, r));
|
||||
const port = (server.address() as any).port;
|
||||
const WebSocket = (await import('ws')).default;
|
||||
const client = new WebSocket(`ws://127.0.0.1:${port}/secure`);
|
||||
const { code, reason } = await new Promise<{ code: number; reason: string }>((res) => {
|
||||
client.on('close', (code: number, reason: Buffer) => res({ code, reason: reason.toString() }));
|
||||
});
|
||||
expect(code).toBe(4401);
|
||||
expect(reason).toContain('no token');
|
||||
server.close();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user