feat: per-route body limits, custom error rendering, OpenAPI generation
CI / build (push) Has been cancelled
CI / build (push) Has been cancelled
Three capabilities that share the same request/route metadata:
- **Per-route upload limits** — `@Post('/x', { maxBodyBytes, maxParts })`
overrides the server-wide `limits` for one route (falls back to the
global default), mirroring the existing per-route `duplicates`.
- **Custom error rendering** — `createApp({ onError })` takes over how any
error becomes a response (HTML, RFC 7807, content-negotiated), covering
the whole surface: handler/step throws, 404, 405, 413, 400. Returns a
response or undefined to fall back to the default JSON. Also wires the
previously-unused `HttpError` `body` field so `throw new HttpError(409,
'conflict', { code })` renders a structured payload. Default behavior is
unchanged when no hook is set.
- **OpenAPI 3.1** — `app.openapi(info?)` projects the route graph into a
structural spec (paths, methods, path/query/header params, request-body
presence, systematic error responses); opt-in `GET /__openapi__` via
`devOpenapi`. Body/response schemas stay generic (Standard Schema exposes
no JSON Schema) — the full `@Produce` mode is post-beta.
Docs: new error-handling and OpenAPI guides, plus reference updates.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
19 files changed
+811
-100
No files matched your search
@@ -25,7 +25,7 @@ Less to hold in your head. That's the tea.
|
||||
|
||||
- **The pipeline is a graph, not a chain.** You never write "put this before that." You declare `needs`/`provides` and green-tea topologically sorts it. *Why it matters:* no ordering bugs, no positional guesswork, and each route runs only its slice of the graph (an auth step doesn't run on public routes).
|
||||
- **The type is the contract.** What a handler reads from the context *is* its dependency list. In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. *Why it matters:* whole classes of "it was undefined in prod" disappear at compile time.
|
||||
- **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram. *Why it matters:* onboarding, debugging, and audits are reading, not archaeology. (NestJS puts this behind a paid Devtools plan.)
|
||||
- **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram; `app.openapi()` projects the same metadata into an OpenAPI 3.1 spec. *Why it matters:* onboarding, debugging, audits, and API docs are reading, not archaeology. (NestJS puts the graph behind a paid Devtools plan.)
|
||||
- **One primitive for real-time.** Return an `AsyncIterable` and the transport streams it — SSE, ndjson, or a WebSocket duplex — with backpressure and cleanup handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
|
||||
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
|
||||
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
|
||||
@@ -81,6 +81,7 @@ Beta shipped the parts a real API needs, without growing the runtime dependency
|
||||
- **CORS** with a guarded preflight and the credentials-never-`*` rule enforced for you.
|
||||
- **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed.
|
||||
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
|
||||
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
|
||||
- **Graceful shutdown.** `app.close()` drains in-flight requests, closes live streams and mesh links.
|
||||
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
|
||||
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
|
||||
|
||||
+43
-4
@@ -6,10 +6,11 @@ import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
|
||||
import { runPipeline, PipelineStep } from '../pipeline';
|
||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
|
||||
import { isAsyncIterable } from '../channel';
|
||||
import { JsonTransformer } from '../transformers';
|
||||
import { JsonTransformer, type ErrorRenderer } from '../transformers';
|
||||
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
|
||||
import { Ctor, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath } from '../metadata';
|
||||
import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
|
||||
import { buildOpenApi, type OpenApiInfo } from '../openapi';
|
||||
import { connectLink, type Link } from '../mesh/link';
|
||||
import { Rooms } from '../rooms';
|
||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||
@@ -42,6 +43,7 @@ interface PipelineDeps {
|
||||
providedSeed(plan: RoutePlan): Promise<Record<string, unknown>>;
|
||||
planSteps(plan: RoutePlan): PipelineStep[];
|
||||
bus: Bus;
|
||||
onError?: ErrorRenderer;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -55,12 +57,15 @@ export function createApp(opts: {
|
||||
mesh?: MeshConfig;
|
||||
limits?: RequestLimits;
|
||||
devGraph?: boolean;
|
||||
devOpenapi?: boolean;
|
||||
overrides?: Record<string, unknown>;
|
||||
tls?: TlsOptions;
|
||||
trustProxy?: boolean;
|
||||
security?: boolean | SecurityOptions;
|
||||
cors?: CorsOptions;
|
||||
bodyDuplicates?: 'array' | 'last';
|
||||
/** Render errors your own way (HTML, custom JSON, …); return a response or undefined to fall back to JSON. */
|
||||
onError?: ErrorRenderer;
|
||||
/** Opt in to alpha features whose API may still change. Currently gates `mesh`. */
|
||||
experimental?: boolean;
|
||||
}): App {
|
||||
@@ -100,12 +105,22 @@ export function createApp(opts: {
|
||||
const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted);
|
||||
const graph = (): GraphView => buildGraphView(providerNodes, stepNodes, routePlans, booted);
|
||||
const explain = (routePath: string): Explain => explainRoute(routePlans, routePath, booted);
|
||||
const openapi = (info?: OpenApiInfo) =>
|
||||
buildOpenApi(
|
||||
routePlans.map((plan) => ({
|
||||
method: plan.method,
|
||||
pattern: plan.pattern,
|
||||
transport: plan.transport,
|
||||
args: plan.args,
|
||||
})),
|
||||
info,
|
||||
);
|
||||
|
||||
const providedSeed = (plan: RoutePlan) => seedProviders(container, plan);
|
||||
const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan);
|
||||
|
||||
const listen = async (port: number): Promise<http.Server> => {
|
||||
const deps: PipelineDeps = { providedSeed, planSteps, bus };
|
||||
const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError };
|
||||
|
||||
// mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize
|
||||
let remoteRoutes: RouteDef[] = [];
|
||||
@@ -137,6 +152,7 @@ export function createApp(opts: {
|
||||
|
||||
const httpRoutes = buildHttpRoutes(routePlans, remoteRoutes, deps);
|
||||
if (opts.devGraph) httpRoutes.push(devGraphRoute(graph));
|
||||
if (opts.devOpenapi) httpRoutes.push(openApiRoute(openapi));
|
||||
const wsRoutes = buildWsRoutes(routePlans, deps);
|
||||
|
||||
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, {
|
||||
@@ -147,6 +163,7 @@ export function createApp(opts: {
|
||||
security: opts.security ?? true,
|
||||
cors: opts.cors,
|
||||
bodyDuplicates: opts.bodyDuplicates,
|
||||
onError: opts.onError,
|
||||
});
|
||||
server.on('close', () => closeLinks(meshLinks));
|
||||
await new Promise<void>((resolve) => server!.listen(port, resolve));
|
||||
@@ -169,6 +186,7 @@ export function createApp(opts: {
|
||||
toMermaid: () => toMermaid(graph()),
|
||||
toDOT: () => toDOT(graph()),
|
||||
explain,
|
||||
openapi,
|
||||
degraded: () => [...degradedProviders],
|
||||
bus,
|
||||
};
|
||||
@@ -245,6 +263,9 @@ function collectControllers(controllers: Ctor[], mountpoint: string, origin: str
|
||||
run: async (context: any) => instance[route.handlerName](...(await resolveArgs(argSpecs, context))),
|
||||
transformer: getTransformer(ControllerClass, route.handlerName) ?? JsonTransformer,
|
||||
duplicates: route.duplicates,
|
||||
maxBodyBytes: route.maxBodyBytes,
|
||||
maxParts: route.maxParts,
|
||||
args: argSpecs,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -447,7 +468,7 @@ function buildMeshControl(
|
||||
|
||||
if (!mesh?.secret || !hasExports) return undefined;
|
||||
const { container, orderedProviders, orderedSteps } = deps;
|
||||
const { bus, providedSeed, planSteps } = deps.deps;
|
||||
const { bus, providedSeed, planSteps, onError } = deps.deps;
|
||||
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
|
||||
|
||||
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
|
||||
@@ -480,6 +501,7 @@ function buildMeshControl(
|
||||
handler: plan.run,
|
||||
transformer: plan.transformer,
|
||||
bus,
|
||||
onError,
|
||||
seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
|
||||
});
|
||||
|
||||
@@ -497,7 +519,7 @@ function buildMeshControl(
|
||||
|
||||
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
|
||||
function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] {
|
||||
const { providedSeed, planSteps, bus } = deps;
|
||||
const { providedSeed, planSteps, bus, onError } = deps;
|
||||
|
||||
const local = routePlans
|
||||
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
|
||||
@@ -506,6 +528,8 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
|
||||
pattern: plan.pattern,
|
||||
transport: plan.transport,
|
||||
bodyDuplicates: plan.duplicates,
|
||||
maxBodyBytes: plan.maxBodyBytes,
|
||||
maxParts: plan.maxParts,
|
||||
handler: async (req) => {
|
||||
const provided = await providedSeed(plan);
|
||||
return runPipeline({
|
||||
@@ -513,6 +537,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
|
||||
handler: plan.run,
|
||||
transformer: plan.transformer,
|
||||
bus,
|
||||
onError,
|
||||
seed: {
|
||||
...provided,
|
||||
req,
|
||||
@@ -546,6 +571,20 @@ function devGraphRoute(graph: () => GraphView): RouteDef {
|
||||
};
|
||||
}
|
||||
|
||||
/** The dev-only `/__openapi__` route: serves the structural OpenAPI 3.1 document as JSON. */
|
||||
function openApiRoute(openapi: () => unknown): RouteDef {
|
||||
return {
|
||||
method: 'GET',
|
||||
pattern: '/__openapi__',
|
||||
transport: 'buffer',
|
||||
handler: async () => ({
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(openapi()),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Compiles every ws/negotiate route plan into a WebSocket route that seeds context and runs its steps + handler. */
|
||||
function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[] {
|
||||
const { providedSeed, planSteps } = deps;
|
||||
|
||||
@@ -3,6 +3,8 @@ import type { Bus } from '../bus';
|
||||
import type { GraphNode } from '../graph';
|
||||
import type { GraphView } from '../graph-viz';
|
||||
import type { HttpMethod, Transport } from '../metadata';
|
||||
import type { ArgSpec } from '../params';
|
||||
import type { OpenApiDoc, OpenApiInfo } from '../openapi';
|
||||
import { JsonTransformer } from '../transformers';
|
||||
|
||||
/** One entry in an {@link App.inspect} listing: a provider, step or handler and where it came from. */
|
||||
@@ -38,6 +40,8 @@ export interface App {
|
||||
toMermaid(): string;
|
||||
toDOT(): string;
|
||||
explain(routePath: string): Explain;
|
||||
/** Generate a structural OpenAPI 3.1 document from the registered routes. */
|
||||
openapi(info?: OpenApiInfo): OpenApiDoc;
|
||||
/** Names of optional providers that failed to boot and are running degraded (empty until {@link App.listen}). */
|
||||
degraded(): string[];
|
||||
bus: Bus;
|
||||
@@ -56,6 +60,9 @@ export interface RoutePlan {
|
||||
run: (ctx: any) => Promise<unknown>;
|
||||
transformer: typeof JsonTransformer;
|
||||
duplicates?: 'array' | 'last';
|
||||
maxBodyBytes?: number;
|
||||
maxParts?: number;
|
||||
args: ArgSpec[];
|
||||
}
|
||||
|
||||
/** Mesh networking options: a secret to gate this node's exports and/or remote teapots to connect to. */
|
||||
|
||||
+31
-20
@@ -1,7 +1,7 @@
|
||||
import http from 'http';
|
||||
import https from 'https';
|
||||
import { errorToResponse } from '../transformers';
|
||||
import { isHttpError } from '../signals';
|
||||
import { renderError, type ErrorRequest, type ErrorRenderer } from '../transformers';
|
||||
import { isHttpError, HttpError, NotFound } from '../signals';
|
||||
import { isStreamResult, type PipelineResult, type ResponseShape } from '../pipeline';
|
||||
import type { Bus } from '../bus';
|
||||
import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from '../security';
|
||||
@@ -23,6 +23,24 @@ interface HandlerConfig {
|
||||
/** A ready-to-send error response produced while acquiring the request body. */
|
||||
type BodyFailure = { fail: { status: number; headers: Record<string, string>; body: string } };
|
||||
|
||||
/** Builds the {@link ErrorRequest} handed to a user error renderer. */
|
||||
function errorRequest(req: http.IncomingMessage): ErrorRequest {
|
||||
return { method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers };
|
||||
}
|
||||
|
||||
/** Renders an error (through the optional user hook) and writes it, merging any extra headers (e.g. `Allow`). */
|
||||
function sendError(
|
||||
res: http.ServerResponse,
|
||||
error: unknown,
|
||||
req: http.IncomingMessage,
|
||||
onError?: ErrorRenderer,
|
||||
extraHeaders?: Record<string, string>,
|
||||
): void {
|
||||
const rendered = renderError(error, errorRequest(req), onError);
|
||||
res.writeHead(rendered.status, extraHeaders ? { ...rendered.headers, ...extraHeaders } : rendered.headers);
|
||||
res.end(rendered.body);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades.
|
||||
* @param routes HTTP route definitions.
|
||||
@@ -83,13 +101,11 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
const allow = allowedMethods(routes, path);
|
||||
|
||||
if (allow.length) {
|
||||
res.writeHead(405, { 'content-type': 'application/json', allow: allow.join(', ') });
|
||||
res.end(JSON.stringify({ error: 'Method Not Allowed' }));
|
||||
sendError(res, new HttpError(405, 'Method Not Allowed'), req, opts?.onError, { allow: allow.join(', ') });
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(404, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ error: 'Not Found' }));
|
||||
sendError(res, new NotFound('Not Found'), req, opts?.onError);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -115,7 +131,7 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
ip: deriveIp(req, trustProxy),
|
||||
});
|
||||
} catch (error) {
|
||||
result = errorToResponse(error);
|
||||
result = renderError(error, errorRequest(req), opts?.onError);
|
||||
}
|
||||
|
||||
if (isStreamResult(result)) {
|
||||
@@ -138,28 +154,23 @@ async function acquireBody(
|
||||
maxBody: number,
|
||||
): Promise<{ body: unknown } | BodyFailure> {
|
||||
let buf: Buffer | undefined;
|
||||
const bodyLimit = matched.def.maxBodyBytes ?? maxBody; // per-route override falls back to the server default
|
||||
|
||||
try {
|
||||
buf = await readBody(req, maxBody);
|
||||
buf = await readBody(req, bodyLimit);
|
||||
} catch (error) {
|
||||
const response = errorToResponse(error);
|
||||
return {
|
||||
fail: { status: response.status, headers: { ...response.headers, connection: 'close' }, body: response.body },
|
||||
};
|
||||
const rendered = renderError(error, errorRequest(req), opts?.onError);
|
||||
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
|
||||
}
|
||||
|
||||
const contentType = String(req.headers['content-type'] ?? '');
|
||||
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
|
||||
const parsed = await parseRequestBody(buf, contentType, duplicates, opts?.limits?.maxParts ?? 1000);
|
||||
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
|
||||
const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts);
|
||||
|
||||
if ('error' in parsed) {
|
||||
return {
|
||||
fail: {
|
||||
status: parsed.status ?? 400,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ error: parsed.error }),
|
||||
},
|
||||
};
|
||||
const rendered = renderError(new HttpError(parsed.status ?? 400, parsed.error), errorRequest(req), opts?.onError);
|
||||
return { fail: rendered };
|
||||
}
|
||||
|
||||
return { body: parsed.body };
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import http from 'http';
|
||||
import type { Transport } from '../metadata';
|
||||
import type { PipelineResult } from '../pipeline';
|
||||
import type { ErrorRenderer } from '../transformers';
|
||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||
|
||||
/** Per-request size and timeout ceilings applied by the server. */
|
||||
@@ -21,6 +22,7 @@ export interface HttpOptions {
|
||||
security?: boolean | SecurityOptions;
|
||||
cors?: CorsOptions;
|
||||
bodyDuplicates?: 'array' | 'last';
|
||||
onError?: ErrorRenderer;
|
||||
}
|
||||
|
||||
/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */
|
||||
@@ -42,6 +44,8 @@ export interface RouteDef {
|
||||
transport: Transport;
|
||||
handler: RouteHandler;
|
||||
bodyDuplicates?: 'array' | 'last';
|
||||
maxBodyBytes?: number; // per-route override of the server's maxBodyBytes
|
||||
maxParts?: number; // per-route override of the server's multipart maxParts
|
||||
}
|
||||
|
||||
/** Result of matching a request path against a route: extracted params plus the matched definition. */
|
||||
|
||||
@@ -15,6 +15,8 @@ export type { App, InspectLine, Explain, MeshConfig } from './app';
|
||||
// Graph visualization
|
||||
export { toMermaid, toDOT } from './graph-viz';
|
||||
export type { GraphView } from './graph-viz';
|
||||
export { buildOpenApi } from './openapi';
|
||||
export type { OpenApiDoc, OpenApiInfo, OpenApiRoute } from './openapi';
|
||||
|
||||
// Routing & decorators
|
||||
export { Provider, Step, Route, Get, Module, Transformer, Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata';
|
||||
@@ -23,6 +25,7 @@ export type { Plugin } from './plugin';
|
||||
|
||||
// Transformers & error signals
|
||||
export { JsonTransformer } from './transformers';
|
||||
export type { ErrorRenderer, ErrorRequest, ErrorResponse } from './transformers';
|
||||
export { HttpError, Unauthorized, NotFound, Redirect, NotModified, ValidationError } from './signals';
|
||||
|
||||
// Bus & flow
|
||||
|
||||
+8
-1
@@ -31,6 +31,8 @@ export interface RouteMeta {
|
||||
transport: Transport;
|
||||
export: boolean;
|
||||
duplicates?: 'array' | 'last';
|
||||
maxBodyBytes?: number;
|
||||
maxParts?: number;
|
||||
}
|
||||
/** Options accepted by the `@Module` decorator. */
|
||||
export interface ModuleOptions {
|
||||
@@ -93,7 +95,10 @@ export function Route(prefix: string): ClassDecorator {
|
||||
}
|
||||
|
||||
function routeDecorator(method: HttpMethod, transport: Transport) {
|
||||
return (path: string, opts?: { export?: boolean; duplicates?: 'array' | 'last' }): MethodDecorator =>
|
||||
return (
|
||||
path: string,
|
||||
opts?: { export?: boolean; duplicates?: 'array' | 'last'; maxBodyBytes?: number; maxParts?: number },
|
||||
): MethodDecorator =>
|
||||
(target, propertyKey) => {
|
||||
const ctor = target.constructor;
|
||||
const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [];
|
||||
@@ -104,6 +109,8 @@ function routeDecorator(method: HttpMethod, transport: Transport) {
|
||||
transport,
|
||||
export: opts?.export ?? false,
|
||||
duplicates: opts?.duplicates,
|
||||
maxBodyBytes: opts?.maxBodyBytes,
|
||||
maxParts: opts?.maxParts,
|
||||
});
|
||||
Reflect.defineMetadata(K.routes, routes, ctor);
|
||||
};
|
||||
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
import type { ArgSpec } from './params';
|
||||
|
||||
/** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */
|
||||
export interface OpenApiRoute {
|
||||
method: string;
|
||||
pattern: string;
|
||||
transport: string;
|
||||
args: ArgSpec[];
|
||||
}
|
||||
|
||||
/** `info` block overrides for the generated document. */
|
||||
export interface OpenApiInfo {
|
||||
title?: string;
|
||||
version?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/** A generated OpenAPI 3.1 document (structural: paths, params, and error responses; body/response schemas are generic). */
|
||||
export interface OpenApiDoc {
|
||||
openapi: string;
|
||||
info: { title: string; version: string; description?: string };
|
||||
paths: Record<string, Record<string, unknown>>;
|
||||
}
|
||||
|
||||
type Parameter = { name: string; in: 'path' | 'query' | 'header'; required: boolean; schema: { type: 'string' } };
|
||||
|
||||
/** Converts a route pattern to an OpenAPI path template: `/users/:id` → `/users/{id}`, `:rest*` → `{rest}`. */
|
||||
function templatePath(pattern: string): string {
|
||||
const segments = pattern
|
||||
.split('/')
|
||||
.filter(Boolean)
|
||||
.map((seg) => (seg.startsWith(':') ? `{${seg.slice(1).replace(/\*$/, '')}}` : seg));
|
||||
return `/${segments.join('/')}`;
|
||||
}
|
||||
|
||||
/** Every `:name` (and `:name*`) segment of a pattern becomes a required path parameter. */
|
||||
function pathParams(pattern: string): Parameter[] {
|
||||
return pattern
|
||||
.split('/')
|
||||
.filter((seg) => seg.startsWith(':'))
|
||||
.map((seg) => ({ name: seg.slice(1).replace(/\*$/, ''), in: 'path', required: true, schema: { type: 'string' } }));
|
||||
}
|
||||
|
||||
/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */
|
||||
function argParams(args: ArgSpec[]): Parameter[] {
|
||||
const params: Parameter[] = [];
|
||||
|
||||
for (const arg of args) {
|
||||
if (arg.source !== 'query' && arg.source !== 'headers') continue;
|
||||
const location = arg.source === 'query' ? 'query' : 'header';
|
||||
const names = arg.keys ?? (arg.key ? [arg.key] : []);
|
||||
for (const name of names) params.push({ name, in: location, required: false, schema: { type: 'string' } });
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
/** The success/error responses documented for a route, keyed by transport and whether any input is validated. */
|
||||
function responses(route: OpenApiRoute): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = {};
|
||||
|
||||
if (route.transport === 'sse') {
|
||||
result['200'] = { description: 'Event stream', content: { 'text/event-stream': {} } };
|
||||
} else if (route.transport === 'ndjson' || route.transport === 'negotiate') {
|
||||
result['200'] = { description: 'Stream', content: { 'application/x-ndjson': {} } };
|
||||
} else {
|
||||
result['200'] = { description: 'OK', content: { 'application/json': { schema: {} } } };
|
||||
}
|
||||
|
||||
if (route.args.some((arg) => arg.schema)) result['422'] = { description: 'Validation failed' };
|
||||
result['500'] = { description: 'Internal Server Error' };
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Builds a single OpenAPI operation object for a route. */
|
||||
function operation(route: OpenApiRoute): Record<string, unknown> {
|
||||
const parameters = [...pathParams(route.pattern), ...argParams(route.args)];
|
||||
const op: Record<string, unknown> = { responses: responses(route) };
|
||||
|
||||
if (parameters.length) op.parameters = parameters;
|
||||
|
||||
if (route.args.some((arg) => arg.source === 'body')) {
|
||||
op.requestBody = { content: { 'application/json': { schema: {} } } };
|
||||
}
|
||||
|
||||
return op;
|
||||
}
|
||||
|
||||
/**
|
||||
* Projects the route graph into a structural OpenAPI 3.1 document: paths, methods, path/query/header
|
||||
* parameters, which routes take a body, and the systematic error responses. Body and response *schemas*
|
||||
* are generic — Standard Schema doesn't expose JSON Schema (see the roadmap). WebSocket routes are omitted.
|
||||
*/
|
||||
export function buildOpenApi(routes: OpenApiRoute[], info?: OpenApiInfo): OpenApiDoc {
|
||||
const paths: Record<string, Record<string, unknown>> = {};
|
||||
|
||||
for (const route of routes) {
|
||||
if (route.transport === 'ws') continue; // not an HTTP request/response
|
||||
const path = templatePath(route.pattern);
|
||||
(paths[path] ??= {})[route.method.toLowerCase()] = operation(route);
|
||||
}
|
||||
|
||||
return {
|
||||
openapi: '3.1.0',
|
||||
info: {
|
||||
title: info?.title ?? 'green-tea API',
|
||||
version: info?.version ?? '0.0.0',
|
||||
...(info?.description ? { description: info.description } : {}),
|
||||
},
|
||||
paths,
|
||||
};
|
||||
}
|
||||
+9
-3
@@ -1,5 +1,5 @@
|
||||
import { Bus } from './bus';
|
||||
import { errorToResponse } from './transformers';
|
||||
import { renderError, type ErrorRenderer } from './transformers';
|
||||
import { isAsyncIterable } from './channel';
|
||||
import type { TransformerFn } from './metadata';
|
||||
|
||||
@@ -38,8 +38,9 @@ export async function runPipeline(args: {
|
||||
transformer: TransformerFn;
|
||||
seed: Record<string, unknown>;
|
||||
bus: Bus;
|
||||
onError?: ErrorRenderer;
|
||||
}): Promise<PipelineResult> {
|
||||
const { steps, handler, transformer, seed, bus } = args;
|
||||
const { steps, handler, transformer, seed, bus, onError } = args;
|
||||
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
|
||||
let context: any = { ...seed };
|
||||
|
||||
@@ -57,6 +58,11 @@ export async function runPipeline(args: {
|
||||
return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body };
|
||||
} catch (error) {
|
||||
bus.emit('request:step:error', { name: 'pipeline', error });
|
||||
return errorToResponse(error);
|
||||
const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> };
|
||||
return renderError(
|
||||
error,
|
||||
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
|
||||
onError,
|
||||
);
|
||||
}
|
||||
}
|
||||
+32
-3
@@ -2,6 +2,26 @@ import { isHttpError, Redirect, ValidationError } from './signals';
|
||||
import type { TransformerFn } from './metadata';
|
||||
import { flattenPath } from './standard-schema';
|
||||
|
||||
/** A ready-to-send HTTP response. */
|
||||
export interface ErrorResponse {
|
||||
status: number;
|
||||
headers: Record<string, string>;
|
||||
body: string;
|
||||
}
|
||||
|
||||
/** The request a {@link ErrorRenderer} is given, to inspect (e.g. `headers.accept`) while rendering. */
|
||||
export interface ErrorRequest {
|
||||
method: string;
|
||||
url: string;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
}
|
||||
|
||||
/**
|
||||
* User hook to render errors however you like (HTML, custom JSON, RFC 7807, …).
|
||||
* Return a response to take over, or `undefined`/`void` to fall back to the default JSON.
|
||||
*/
|
||||
export type ErrorRenderer = (error: unknown, req: ErrorRequest) => ErrorResponse | undefined | void;
|
||||
|
||||
/** Default transformer: serialize a handler's return value as a JSON `200` response. */
|
||||
export const JsonTransformer: TransformerFn = (value) => ({
|
||||
status: 200,
|
||||
@@ -9,8 +29,11 @@ export const JsonTransformer: TransformerFn = (value) => ({
|
||||
body: JSON.stringify(value),
|
||||
});
|
||||
|
||||
/** Map a thrown value to a JSON error response (422 for validation, HttpError status, else 500). */
|
||||
export function errorToResponse(error: unknown): { status: number; headers: Record<string, string>; body: string } {
|
||||
/**
|
||||
* Map a thrown value to a JSON error response (422 for validation, `HttpError` status, else 500).
|
||||
* An `HttpError` carrying a `body` renders that payload instead of the default `{ error: message }`.
|
||||
*/
|
||||
export function errorToResponse(error: unknown): ErrorResponse {
|
||||
if (error instanceof ValidationError) {
|
||||
return {
|
||||
status: 422,
|
||||
@@ -26,7 +49,8 @@ export function errorToResponse(error: unknown): { status: number; headers: Reco
|
||||
if (isHttpError(error)) {
|
||||
const headers: Record<string, string> = { 'content-type': 'application/json' };
|
||||
if (error instanceof Redirect) headers.location = error.location;
|
||||
return { status: error.status, headers, body: JSON.stringify({ error: error.message }) };
|
||||
const payload = error.body !== undefined ? error.body : { error: error.message };
|
||||
return { status: error.status, headers, body: JSON.stringify(payload) };
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -35,3 +59,8 @@ export function errorToResponse(error: unknown): { status: number; headers: Reco
|
||||
body: JSON.stringify({ error: 'Internal Server Error' }),
|
||||
};
|
||||
}
|
||||
|
||||
/** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */
|
||||
export function renderError(error: unknown, req: ErrorRequest, onError?: ErrorRenderer): ErrorResponse {
|
||||
return onError?.(error, req) ?? errorToResponse(error);
|
||||
}
|
||||
+269
-64
@@ -1,13 +1,17 @@
|
||||
import 'reflect-metadata';
|
||||
import { describe, expect, it, test, vi } from 'vitest';
|
||||
import { Provider, Step, Route, Get, Module, Transformer } from '../src/metadata';
|
||||
import { Provider, Step, Route, Get, Post, Module, Transformer } from '../src/metadata';
|
||||
import { JsonTransformer } from '../src/transformers';
|
||||
import { Unauthorized } from '../src/signals';
|
||||
import { createApp } from '../src/app';
|
||||
import { needs, param, query } from '../src/params';
|
||||
import { needs, param, query, body } from '../src/params';
|
||||
|
||||
@Provider({ provides: 'db' })
|
||||
class Db { provide() { return { db: { find: (t: string) => (t === 'good' ? { id: 'u1' } : null) } }; } }
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: { find: (t: string) => (t === 'good' ? { id: 'u1' } : null) } };
|
||||
}
|
||||
}
|
||||
|
||||
@Step({ provides: 'user', needs: ['db', 'req'] })
|
||||
class Auth {
|
||||
@@ -22,7 +26,9 @@ class Auth {
|
||||
class UserCtl {
|
||||
@Get('/:id')
|
||||
@Transformer(JsonTransformer)
|
||||
getUser(@needs('user') user: any, @param('id') id: string) { return { id, user }; }
|
||||
getUser(@needs('user') user: any, @param('id') id: string) {
|
||||
return { id, user };
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [UserCtl] })
|
||||
@@ -54,7 +60,11 @@ test('a logger plugin observes step:enter without mutating the chain', async ()
|
||||
|
||||
test('required provider failure aborts boot', () => {
|
||||
@Provider({ provides: 'broken' })
|
||||
class Broken { provide() { throw new Error('cannot connect'); } }
|
||||
class Broken {
|
||||
provide() {
|
||||
throw new Error('cannot connect');
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/x', providers: [Broken], steps: [], controllers: [] })
|
||||
class BrokenModule {}
|
||||
|
||||
@@ -65,15 +75,23 @@ test('required provider failure aborts boot', () => {
|
||||
test('optional provider failure warns but does not abort boot', async () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
@Provider({ provides: 'cache', optional: true })
|
||||
class FlakyCache { provide() { throw new Error('cache down'); } }
|
||||
class FlakyCache {
|
||||
provide() {
|
||||
throw new Error('cache down');
|
||||
}
|
||||
}
|
||||
@Route('/ping')
|
||||
class PingCtl { @Get('/') ping() { return { ok: true }; } }
|
||||
class PingCtl {
|
||||
@Get('/') ping() {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/sys', providers: [FlakyCache], steps: [], controllers: [PingCtl] })
|
||||
class SysModule {}
|
||||
|
||||
const app = createApp({ modules: [SysModule] });
|
||||
expect(app.degraded()).toEqual([]); // nothing degraded until boot runs
|
||||
const server = await app.listen(0); // must NOT throw
|
||||
const server = await app.listen(0); // must NOT throw
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining("optional provider 'cache' failed"));
|
||||
// boot ends with a summary of everything running degraded, and it is queryable on the app
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining('started with 1 degraded optional provider(s): cache'));
|
||||
@@ -86,7 +104,9 @@ test('handler receives @query value through a live request', async () => {
|
||||
@Route('/search')
|
||||
class SearchCtl {
|
||||
@Get('/')
|
||||
run(@query('q') q: string) { return { q }; }
|
||||
run(@query('q') q: string) {
|
||||
return { q };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/s', providers: [], steps: [], controllers: [SearchCtl] })
|
||||
class SearchModule {}
|
||||
@@ -103,19 +123,31 @@ test('boot fails when a handler needs something nothing provides', () => {
|
||||
@Route('/things')
|
||||
class ThingCtl {
|
||||
@Get('/')
|
||||
list(@needs('missing') _m: any) { return []; }
|
||||
list(@needs('missing') _m: any) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/t', providers: [], steps: [], controllers: [ThingCtl] })
|
||||
class ThingModule {}
|
||||
|
||||
expect(() => createApp({ modules: [ThingModule] }))
|
||||
.toThrow(/handler 'list' needs 'missing'/);
|
||||
expect(() => createApp({ modules: [ThingModule] })).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 {}
|
||||
@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'\?/);
|
||||
});
|
||||
|
||||
@@ -128,10 +160,14 @@ describe('app streaming wiring', () => {
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Sse('/ticks') ticks() {
|
||||
return (async function* () { yield { t: 1 }; yield { t: 2 }; })();
|
||||
return (async function* () {
|
||||
yield { t: 1 };
|
||||
yield { t: 2 };
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await app.listen(0);
|
||||
const addr = server.address() as import('net').AddressInfo;
|
||||
@@ -147,11 +183,15 @@ describe('app streaming wiring', () => {
|
||||
class Ctl {
|
||||
@Ws('/echo') echo(@inbound() inc: AsyncIterable<string>) {
|
||||
const out = channel<string>();
|
||||
(async () => { for await (const m of inc) out.push(`re:${m}`); out.close(); })();
|
||||
(async () => {
|
||||
for await (const m of inc) out.push(`re:${m}`);
|
||||
out.close();
|
||||
})();
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await app.listen(0);
|
||||
const addr = server.address() as import('net').AddressInfo;
|
||||
@@ -161,7 +201,8 @@ describe('app streaming wiring', () => {
|
||||
const got = new Promise<string>((r) => client.on('message', (d: Buffer) => r(d.toString())));
|
||||
client.send('yo');
|
||||
expect(await got).toBe('re:yo');
|
||||
client.close(); server.close();
|
||||
client.close();
|
||||
server.close();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -169,53 +210,97 @@ describe('per-route subgraph slicing', () => {
|
||||
it('a route that does not @needs a step does not run it', async () => {
|
||||
const ran: string[] = [];
|
||||
@Step({ provides: 'tracked', needs: [] })
|
||||
class Tracked { run() { ran.push('tracked'); return { tracked: true }; } }
|
||||
class Tracked {
|
||||
run() {
|
||||
ran.push('tracked');
|
||||
return { tracked: true };
|
||||
}
|
||||
}
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Get('/needs') needs(@needs('tracked') t: any) { return { t }; }
|
||||
@Get('/free') free() { return { ok: true }; }
|
||||
@Get('/needs') needs(@needs('tracked') t: any) {
|
||||
return { t };
|
||||
}
|
||||
@Get('/free') free() {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] }) class M {}
|
||||
@Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
|
||||
await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json());
|
||||
expect(ran).toEqual([]); // step did NOT run for /free
|
||||
expect(ran).toEqual([]); // step did NOT run for /free
|
||||
await fetch(`http://127.0.0.1:${port}/needs`).then((r) => r.json());
|
||||
expect(ran).toEqual(['tracked']); // step ran for /needs
|
||||
expect(app.inspect('/free').map((l) => l.kind)).toEqual(['handler']); // no step in the chain
|
||||
expect(ran).toEqual(['tracked']); // step ran for /needs
|
||||
expect(app.inspect('/free').map((l) => l.kind)).toEqual(['handler']); // no step in the chain
|
||||
server.close();
|
||||
});
|
||||
|
||||
it('a side-effect step (provides: []) added by a plugin runs unconditionally', async () => {
|
||||
// NB: @Step always provides exactly one token (always sliceable). provides:[] only arises via a plugin's scope.add.
|
||||
const ran: string[] = [];
|
||||
const observer = (api: any) => api.scope.add({ kind: 'step', name: 'obs', needs: [], provides: [], run: () => { ran.push('obs'); return {}; } });
|
||||
const observer = (api: any) =>
|
||||
api.scope.add({
|
||||
kind: 'step',
|
||||
name: 'obs',
|
||||
needs: [],
|
||||
provides: [],
|
||||
run: () => {
|
||||
ran.push('obs');
|
||||
return {};
|
||||
},
|
||||
});
|
||||
@Route('/')
|
||||
class Ctl { @Get('/free') free() { return { ok: true }; } }
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
|
||||
class Ctl {
|
||||
@Get('/free') free() {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], plugins: [observer] });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json());
|
||||
expect(ran).toEqual(['obs']); // ran despite the route @needs-ing nothing
|
||||
expect(ran).toEqual(['obs']); // ran despite the route @needs-ing nothing
|
||||
server.close();
|
||||
});
|
||||
|
||||
it('an always-run observer step receives its declared needs even when the route does not need them', async () => {
|
||||
let seen: any;
|
||||
const observer = (api: any) => api.scope.add({ kind: 'step', name: 'audit', needs: ['user'], provides: [], run: (ctx: any) => { seen = ctx.user; return {}; } });
|
||||
const observer = (api: any) =>
|
||||
api.scope.add({
|
||||
kind: 'step',
|
||||
name: 'audit',
|
||||
needs: ['user'],
|
||||
provides: [],
|
||||
run: (ctx: any) => {
|
||||
seen = ctx.user;
|
||||
return {};
|
||||
},
|
||||
});
|
||||
@Step({ provides: 'user', needs: [] })
|
||||
class Auth { run() { return { user: { id: 'u1' } }; } }
|
||||
class Auth {
|
||||
run() {
|
||||
return { user: { id: 'u1' } };
|
||||
}
|
||||
}
|
||||
@Route('/')
|
||||
class Ctl { @Get('/free') free() { return { ok: true }; } } // does NOT @needs('user')
|
||||
@Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] }) class M {}
|
||||
class Ctl {
|
||||
@Get('/free') free() {
|
||||
return { ok: true };
|
||||
}
|
||||
} // does NOT @needs('user')
|
||||
@Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], plugins: [observer] });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json());
|
||||
expect(seen).toEqual({ id: 'u1' }); // observer got user, not undefined
|
||||
expect(seen).toEqual({ id: 'u1' }); // observer got user, not undefined
|
||||
server.close();
|
||||
});
|
||||
});
|
||||
@@ -225,10 +310,26 @@ import { toMermaid as renderMermaid } from '../src/graph-viz';
|
||||
|
||||
describe('app.graph / explain', () => {
|
||||
it('graph() returns nodes (with origin/needs/provides) and routes with their sliced chain', async () => {
|
||||
@Provider({ provides: 'db' }) class Db { provide() { return { db: 1 }; } }
|
||||
@Step({ provides: 'user', needs: ['db'] }) class Auth { run() { return { user: 1 }; } }
|
||||
@Route('/u') class Ctl { @Get('/:id') get(@needs('user') u: any) { return { u }; } }
|
||||
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] }) class M {}
|
||||
@Provider({ provides: 'db' })
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: 1 };
|
||||
}
|
||||
}
|
||||
@Step({ provides: 'user', needs: ['db'] })
|
||||
class Auth {
|
||||
run() {
|
||||
return { user: 1 };
|
||||
}
|
||||
}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/:id') get(@needs('user') u: any) {
|
||||
return { u };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const g = app.graph();
|
||||
expect(g.nodes.find((n) => n.name === 'db')).toMatchObject({ kind: 'provider', origin: 'module:M' });
|
||||
@@ -239,9 +340,20 @@ describe('app.graph / explain', () => {
|
||||
});
|
||||
|
||||
it('explain() returns the rich chain with origin and a handler entry', async () => {
|
||||
@Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } }
|
||||
@Route('/u') class Ctl { @Get('/me') me(@needs('user') u: any) { return { u }; } }
|
||||
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {}
|
||||
@Step({ provides: 'user', needs: [] })
|
||||
class Auth {
|
||||
run() {
|
||||
return { user: 1 };
|
||||
}
|
||||
}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/me') me(@needs('user') u: any) {
|
||||
return { u };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const e = app.explain('/api/u/me');
|
||||
expect(e).toMatchObject({ pattern: '/api/u/me', method: 'GET', transport: 'buffer' });
|
||||
@@ -253,8 +365,14 @@ describe('app.graph / explain', () => {
|
||||
describe('devGraph endpoint', () => {
|
||||
const portOf = (s: any) => (s.address() as any).port;
|
||||
it('serves /__graph__ as HTML when devGraph:true', async () => {
|
||||
@Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/me') me() {
|
||||
return { ok: 1 };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], devGraph: true });
|
||||
const s = await app.listen(0);
|
||||
const html = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`).then((r) => r.text());
|
||||
@@ -266,8 +384,14 @@ describe('devGraph endpoint', () => {
|
||||
s.close();
|
||||
});
|
||||
it('does NOT mount /__graph__ without devGraph', async () => {
|
||||
@Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/me') me() {
|
||||
return { ok: 1 };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const s = await app.listen(0);
|
||||
const res = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`);
|
||||
@@ -279,17 +403,26 @@ describe('devGraph endpoint', () => {
|
||||
describe('graceful shutdown', () => {
|
||||
it('app.close() stops accepting and resolves, even with an SSE stream open', async () => {
|
||||
@Route('/')
|
||||
class Ctl { @Sse('/ticks') ticks() { return (async function* () { yield { t: 1 }; await new Promise((r) => setTimeout(r, 1000)); yield { t: 2 }; })(); } }
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
|
||||
class Ctl {
|
||||
@Sse('/ticks') ticks() {
|
||||
return (async function* () {
|
||||
yield { t: 1 };
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
yield { t: 2 };
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
|
||||
const res = await fetch(`http://127.0.0.1:${port}/ticks`, { headers: { accept: 'text/event-stream' } });
|
||||
const reader = res.body!.getReader();
|
||||
await reader.read(); // first event; stream still open
|
||||
await reader.read(); // first event; stream still open
|
||||
|
||||
await app.close(); // must NOT hang despite the open stream
|
||||
await app.close(); // must NOT hang despite the open stream
|
||||
await expect(fetch(`http://127.0.0.1:${port}/ticks`).then((r) => r.text())).rejects.toThrow();
|
||||
reader.cancel().catch(() => {});
|
||||
});
|
||||
@@ -298,26 +431,54 @@ describe('graceful shutdown', () => {
|
||||
describe('overrides', () => {
|
||||
const portOf = (s: any) => (s.address() as any).port;
|
||||
it('overrides a provider token with a plain value (wrapped as a merge object)', async () => {
|
||||
@Provider({ provides: 'db' }) class Db { provide() { return { db: { real: true } }; } }
|
||||
@Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } }
|
||||
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {}
|
||||
@Provider({ provides: 'db' })
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: { real: true } };
|
||||
}
|
||||
}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/x') x(@needs('db') db: any) {
|
||||
return { db };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], overrides: { db: { fake: true } } });
|
||||
const s = await app.listen(0);
|
||||
expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: { fake: true } });
|
||||
s.close();
|
||||
});
|
||||
it('overrides with a function runner', async () => {
|
||||
@Provider({ provides: 'db' }) class Db { provide() { return { db: 'real' }; } }
|
||||
@Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } }
|
||||
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {}
|
||||
@Provider({ provides: 'db' })
|
||||
class Db {
|
||||
provide() {
|
||||
return { db: 'real' };
|
||||
}
|
||||
}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/x') x(@needs('db') db: any) {
|
||||
return { db };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], overrides: { db: () => ({ db: 'fn' }) } });
|
||||
const s = await app.listen(0);
|
||||
expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: 'fn' });
|
||||
s.close();
|
||||
});
|
||||
it('rejects an override for an unknown token', async () => {
|
||||
@Route('/u') class Ctl { @Get('/x') x() { return { ok: 1 }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
@Route('/u')
|
||||
class Ctl {
|
||||
@Get('/x') x() {
|
||||
return { ok: 1 };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M], overrides: { nope: 1 } });
|
||||
await expect(app.listen(0)).rejects.toThrow(/unknown token 'nope'/);
|
||||
});
|
||||
@@ -325,8 +486,14 @@ describe('overrides', () => {
|
||||
|
||||
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 {}
|
||||
@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;
|
||||
@@ -334,9 +501,47 @@ describe('rooms auto-provide', () => {
|
||||
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 {}
|
||||
@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();
|
||||
});
|
||||
});
|
||||
|
||||
test('per-route maxBodyBytes overrides the server default', async () => {
|
||||
@Route('/up')
|
||||
class C {
|
||||
@Post('/small', { maxBodyBytes: 10 }) small(@body() _b: unknown) {
|
||||
return { ok: true };
|
||||
}
|
||||
@Post('/big') big(@body() _b: unknown) {
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', providers: [], steps: [], controllers: [C] })
|
||||
class M {}
|
||||
|
||||
const app = createApp({ modules: [M], limits: { maxBodyBytes: 1000 } });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
const payload = JSON.stringify({ x: 'aaaaaaaaaaaaaaaaaaaa' }); // ~30 bytes, over the route's 10-byte cap
|
||||
const opts = { method: 'POST', headers: { 'content-type': 'application/json' }, body: payload };
|
||||
|
||||
const tight = await fetch(`http://127.0.0.1:${port}/up/small`, opts);
|
||||
expect(tight.status).toBe(413); // per-route cap of 10 bytes
|
||||
const loose = await fetch(`http://127.0.0.1:${port}/up/big`, opts);
|
||||
expect(loose.status).toBe(200); // falls back to the server's 1000-byte limit
|
||||
|
||||
server.close();
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import 'reflect-metadata';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp } from '../src/app';
|
||||
import { Route, Get, Module } from '../src/metadata';
|
||||
import { HttpError, Unauthorized, isHttpError } from '../src/signals';
|
||||
import type { ErrorRenderer } from '../src/transformers';
|
||||
|
||||
// Renders every error as HTML, reading the status off HttpError when present.
|
||||
const htmlErrors: ErrorRenderer = (error) => ({
|
||||
status: isHttpError(error) ? error.status : 500,
|
||||
headers: { 'content-type': 'text/html' },
|
||||
body: `<h1>${isHttpError(error) ? error.status : 500}</h1>`,
|
||||
});
|
||||
|
||||
@Route('/x')
|
||||
class Ctl {
|
||||
@Get('/boom') boom() {
|
||||
throw new Unauthorized('nope');
|
||||
}
|
||||
@Get('/ok') ok() {
|
||||
return { ok: true };
|
||||
}
|
||||
@Get('/teapot') teapot() {
|
||||
throw new HttpError(418, 'short and stout', { code: 'TEA', reason: 'short and stout' });
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
async function serve(onError?: ErrorRenderer) {
|
||||
const app = createApp({ modules: [M], onError });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
return { server, base: `http://127.0.0.1:${port}` };
|
||||
}
|
||||
|
||||
describe('onError renderer', () => {
|
||||
it('renders a handler-thrown error through the hook (HTML, right status)', async () => {
|
||||
const { server, base } = await serve(htmlErrors);
|
||||
const res = await fetch(`${base}/x/boom`);
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.headers.get('content-type')).toBe('text/html');
|
||||
expect(await res.text()).toBe('<h1>401</h1>');
|
||||
server.close();
|
||||
});
|
||||
|
||||
it('renders infra errors too — a no-route 404 goes through the hook', async () => {
|
||||
const { server, base } = await serve(htmlErrors);
|
||||
const res = await fetch(`${base}/nope`);
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.headers.get('content-type')).toBe('text/html');
|
||||
expect(await res.text()).toBe('<h1>404</h1>');
|
||||
server.close();
|
||||
});
|
||||
|
||||
it('falls back to the default JSON when the hook returns undefined', async () => {
|
||||
const { server, base } = await serve(() => undefined);
|
||||
const res = await fetch(`${base}/x/boom`);
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.headers.get('content-type')).toBe('application/json');
|
||||
expect(await res.json()).toEqual({ error: 'nope' });
|
||||
server.close();
|
||||
});
|
||||
|
||||
it('with no hook, behavior is unchanged (default JSON 404)', async () => {
|
||||
const { server, base } = await serve();
|
||||
const res = await fetch(`${base}/nope`);
|
||||
expect(res.status).toBe(404);
|
||||
expect(await res.json()).toEqual({ error: 'Not Found' });
|
||||
server.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('HttpError body', () => {
|
||||
it('an HttpError carrying a body renders that payload instead of { error: message }', async () => {
|
||||
const { server, base } = await serve();
|
||||
const res = await fetch(`${base}/x/teapot`);
|
||||
expect(res.status).toBe(418);
|
||||
expect(await res.json()).toEqual({ code: 'TEA', reason: 'short and stout' });
|
||||
server.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import 'reflect-metadata';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp } from '../src/app';
|
||||
import { Route, Get, Post, Ws, Module } from '../src/metadata';
|
||||
import { param, query, headers, body } from '../src/params';
|
||||
|
||||
const numSchema = {
|
||||
'~standard': {
|
||||
version: 1 as const,
|
||||
vendor: 'test',
|
||||
validate: (v: unknown) => ({ value: Number(v) }),
|
||||
},
|
||||
};
|
||||
|
||||
@Route('/users')
|
||||
class Users {
|
||||
@Get('/:id') get(@param('id') _id: string, @query('expand') _e: string, @headers('x-trace') _t: string) {
|
||||
return {};
|
||||
}
|
||||
@Post('/') create(@body() _b: unknown) {
|
||||
return {};
|
||||
}
|
||||
@Get('/:id/files/:path*') files(@param('path') _p: string) {
|
||||
return {};
|
||||
}
|
||||
@Get('/search') search(@query('n', numSchema) _n: number) {
|
||||
return {};
|
||||
}
|
||||
@Ws('/live') live() {
|
||||
return (async function* () {})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', controllers: [Users] })
|
||||
class M {}
|
||||
|
||||
describe('app.openapi()', () => {
|
||||
const doc = createApp({ modules: [M] }).openapi({ title: 'Demo', version: '1.2.3' });
|
||||
|
||||
it('emits a 3.1 doc with info overrides', () => {
|
||||
expect(doc.openapi).toBe('3.1.0');
|
||||
expect(doc.info).toEqual({ title: 'Demo', version: '1.2.3' });
|
||||
});
|
||||
|
||||
it('templates path params: /users/:id → /users/{id}', () => {
|
||||
expect(doc.paths['/api/users/{id}']).toBeDefined();
|
||||
expect(doc.paths['/api/users/{id}/files/{path}']).toBeDefined();
|
||||
});
|
||||
|
||||
it('derives path, query, and header parameters from the handler signature', () => {
|
||||
const op = doc.paths['/api/users/{id}'].get as any;
|
||||
const byName = Object.fromEntries(op.parameters.map((p: any) => [p.name, p.in]));
|
||||
expect(byName).toEqual({ id: 'path', expand: 'query', 'x-trace': 'header' });
|
||||
});
|
||||
|
||||
it('marks routes that take a body with requestBody', () => {
|
||||
const op = doc.paths['/api/users'].post as any;
|
||||
expect(op.requestBody.content['application/json']).toBeDefined();
|
||||
});
|
||||
|
||||
it('adds a 422 response when an argument is validated by a schema', () => {
|
||||
const op = doc.paths['/api/users/search'].get as any;
|
||||
expect(op.responses['422']).toBeDefined();
|
||||
expect((doc.paths['/api/users/{id}'].get as any).responses['422']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('omits WebSocket routes', () => {
|
||||
expect(doc.paths['/api/users/live']).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /__openapi__', () => {
|
||||
it('serves the document as JSON when devOpenapi is enabled', async () => {
|
||||
const app = createApp({ modules: [M], devOpenapi: true });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
const res = await fetch(`http://127.0.0.1:${port}/__openapi__`);
|
||||
expect(res.headers.get('content-type')).toBe('application/json');
|
||||
const json = (await res.json()) as any;
|
||||
expect(json.openapi).toBe('3.1.0');
|
||||
expect(json.paths['/api/users/{id}']).toBeDefined();
|
||||
server.close();
|
||||
});
|
||||
});
|
||||
@@ -31,11 +31,13 @@ export default defineConfig({
|
||||
{ label: 'Dependency injection', slug: 'guides/dependency-injection' },
|
||||
{ label: 'Argument decorators', slug: 'guides/arguments' },
|
||||
{ label: 'Validation', slug: 'guides/validation' },
|
||||
{ label: 'Error handling', slug: 'guides/errors' },
|
||||
{ label: 'Streaming & real-time', slug: 'guides/streaming' },
|
||||
{ label: 'File uploads', slug: 'guides/uploads' },
|
||||
{ label: 'Transport security', slug: 'guides/security' },
|
||||
{ label: 'Plugins & observability', slug: 'guides/plugins' },
|
||||
{ label: 'Graph introspection', slug: 'guides/introspection' },
|
||||
{ label: 'OpenAPI', slug: 'guides/openapi' },
|
||||
{ label: 'Testing', slug: 'guides/testing' },
|
||||
{ label: 'Mesh (alpha)', slug: 'guides/mesh', badge: { text: 'alpha', variant: 'caution' } },
|
||||
],
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
title: Error handling
|
||||
description: "Throw typed errors anywhere; render them however you like with onError."
|
||||
---
|
||||
|
||||
Errors are **thrown, not returned**. Throw a typed error anywhere in the pipeline — a provider, a step, or a handler — and green-tea converts it to a response at one place.
|
||||
|
||||
## The typed errors
|
||||
|
||||
All live in `@green-tea/core`:
|
||||
|
||||
| Throw | Status |
|
||||
|---|---|
|
||||
| `Unauthorized(msg?)` | `401` |
|
||||
| `NotFound(msg?)` | `404` |
|
||||
| `NotModified()` | `304` |
|
||||
| `Redirect(location)` | `302` + `Location` |
|
||||
| `ValidationError` | `422` (raised for you by schema validation) |
|
||||
| `HttpError(status, msg?, body?)` | any status |
|
||||
| anything else | `500` (message hidden — internals never leak) |
|
||||
|
||||
```typescript
|
||||
@Step({ provides: 'user', needs: ['db', 'req'] })
|
||||
class Authenticate {
|
||||
run(ctx) {
|
||||
const user = ctx.db.find(ctx.req.headers['x-token']);
|
||||
if (!user) throw new Unauthorized('invalid token'); // → 401, cuts the request
|
||||
return { user };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
By default an error becomes JSON: `{ "error": "<message>" }` (validation adds `source` + per-field `issues`).
|
||||
|
||||
## Structured error bodies
|
||||
|
||||
An `HttpError` can carry a **body** — return a structured payload instead of the default `{ error }`:
|
||||
|
||||
```typescript
|
||||
throw new HttpError(409, 'conflict', { code: 'DUP_EMAIL', field: 'email' });
|
||||
// → 409 { "code": "DUP_EMAIL", "field": "email" }
|
||||
```
|
||||
|
||||
## Render errors your way — `onError`
|
||||
|
||||
Not everything should be JSON. Pass `onError` to `createApp` to render errors however you like — HTML, [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807), content-negotiated, anything. It receives the error and the request, and returns a response — or `undefined` to fall back to the default JSON.
|
||||
|
||||
```typescript
|
||||
import { isHttpError } from '@green-tea/core';
|
||||
|
||||
const app = createApp({
|
||||
modules: [ApiModule],
|
||||
onError(error, req) {
|
||||
const status = isHttpError(error) ? error.status : 500;
|
||||
// negotiate: HTML for browsers, JSON for API clients
|
||||
if (String(req.headers.accept).includes('text/html')) {
|
||||
return { status, headers: { 'content-type': 'text/html' }, body: `<h1>${status}</h1>` };
|
||||
}
|
||||
return undefined; // fall back to the default JSON
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
`onError` intercepts **every** HTTP error response — handler/step throws, a `404` for an unmatched route, `405`, a `413` (body too large), and a `400` (malformed body) — so your error surface is consistent across the whole app. Streaming and WebSocket errors are out of scope (they surface as an error frame or a WebSocket close code, not a response body).
|
||||
|
||||
:::note
|
||||
Errors are also observable without changing the response: subscribe to `request:step:error` (and `stream:error`) on [`app.bus`](/guides/plugins/) to log or trace them.
|
||||
:::
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
title: OpenAPI
|
||||
description: "Generate a structural OpenAPI 3.1 document from the route graph."
|
||||
---
|
||||
|
||||
Because the request pipeline is [data you can read](/concepts/the-graph/), green-tea can project it — the same way it renders [Mermaid/DOT](/guides/introspection/), it emits **OpenAPI**.
|
||||
|
||||
## `app.openapi()`
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [ApiModule] });
|
||||
const spec = app.openapi({ title: 'My API', version: '1.0.0' });
|
||||
// → OpenAPI 3.1 document
|
||||
```
|
||||
|
||||
It reads the routes and handler signatures and produces, for each route:
|
||||
|
||||
- the **path**, templated — `/users/:id` → `/users/{id}`, catch-all `:path*` → `{path}`;
|
||||
- the **method**;
|
||||
- **parameters** — path params from the pattern, plus query/header params from the handler's `@query` / `@headers` / `@header` decorators;
|
||||
- a **request body** entry for routes that read `@body()`;
|
||||
- the systematic **responses** — `200`, a `422` when any argument is schema-validated, and `500`.
|
||||
|
||||
WebSocket routes are omitted (they aren't request/response).
|
||||
|
||||
## Serve it — `devOpenapi`
|
||||
|
||||
Opt in to a `GET /__openapi__` endpoint that returns the document as JSON — point Swagger UI, Redoc, or a codegen client at it:
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [ApiModule], devOpenapi: true });
|
||||
// GET /__openapi__ → application/json
|
||||
```
|
||||
|
||||
## What's structural (and what isn't yet)
|
||||
|
||||
This is a **structural** spec: paths, methods, parameters, which routes take a body, and the standard error responses. What it does **not** include yet:
|
||||
|
||||
- **Request/response body schemas.** [Standard Schema](/guides/validation/) (zod/valibot/arktype) validates input but does not expose a JSON Schema representation, so body shapes are documented generically. Parameter types default to `string`.
|
||||
|
||||
Full schemas — declared and enforced on the way out via a `@Produce(schema)` decorator that also validates responses — are on the roadmap for the stable release. For beta, the structural document already drives Swagger UI, client codegen, and API diffing.
|
||||
@@ -57,7 +57,14 @@ Uploaded files are held in memory, so they're bounded by the same `maxBodyBytes`
|
||||
const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } });
|
||||
```
|
||||
|
||||
A malformed multipart body (bad boundary, missing headers, truncated part) → **400**.
|
||||
Both limits can be overridden **per route** — an upload endpoint can allow a larger body than the rest of the API:
|
||||
|
||||
```typescript
|
||||
@Post('/avatar', { maxBodyBytes: 5_000_000, maxParts: 20 })
|
||||
uploadAvatar(@body() form: MultipartBody) { /* ... */ }
|
||||
```
|
||||
|
||||
A route's `maxBodyBytes` / `maxParts` fall back to the server-wide `limits` when unset. A malformed multipart body (bad boundary, missing headers, truncated part) → **400**.
|
||||
|
||||
:::note
|
||||
To validate parsed fields against a schema, pass a Standard Schema to `@body()` — see [validation](/guides/validation/).
|
||||
|
||||
@@ -15,12 +15,14 @@ const app = createApp(options);
|
||||
| `plugins` | `Plugin[]` | `[]` | plugins, each limited to `bus.on` + `scope.add` ([plugins](/guides/plugins/)) |
|
||||
| `limits` | `RequestLimits` | see below | body-size and timeout ceilings |
|
||||
| `devGraph` | `boolean` | `false` | mount `GET /__graph__` ([introspection](/guides/introspection/)) |
|
||||
| `devOpenapi` | `boolean` | `false` | mount `GET /__openapi__` serving the [OpenAPI](/guides/openapi/) document |
|
||||
| `overrides` | `Record<string, unknown>` | — | swap any node by token ([testing](/guides/testing/)) |
|
||||
| `tls` | `TlsOptions` | — | serve over https/wss |
|
||||
| `trustProxy` | `boolean` | `false` | honor `X-Forwarded-*` for `ctx.protocol` / `ctx.ip` |
|
||||
| `security` | `boolean \| SecurityOptions` | `true` | secure-by-default headers ([security](/guides/security/)) |
|
||||
| `cors` | `CorsOptions` | — | CORS handling |
|
||||
| `bodyDuplicates` | `'array' \| 'last'` | `'last'` | policy for repeated form fields |
|
||||
| `onError` | `ErrorRenderer` | — | render errors your way ([error handling](/guides/errors/)); returns a response or `undefined` to fall back to JSON |
|
||||
| `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/guides/mesh/)) |
|
||||
| `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) |
|
||||
|
||||
@@ -62,6 +64,7 @@ const app = createApp(options);
|
||||
| `explain(route)` | `Explain` | the chain annotated with each node's needs/provides |
|
||||
| `graph()` | `GraphView` | the full node + route graph |
|
||||
| `toMermaid()` / `toDOT()` | `string` | render the graph |
|
||||
| `openapi(info?)` | `OpenApiDoc` | structural OpenAPI 3.1 document ([details](/guides/openapi/)) |
|
||||
| `degraded()` | `string[]` | optional providers running degraded (empty until `listen()`) |
|
||||
| `bus` | `Bus` | lifecycle + request event bus |
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ Method decorator. Turns a handler's return value into `{ status?, headers?, body
|
||||
|
||||
## Routes
|
||||
|
||||
Method decorators on a controller. All accept `(path, opts?)` where `opts = { export?: boolean, duplicates?: 'array' | 'last' }`.
|
||||
Method decorators on a controller. All accept `(path, opts?)` where `opts = { export?: boolean, duplicates?: 'array' | 'last', maxBodyBytes?: number, maxParts?: number }`. `maxBodyBytes` / `maxParts` override the server-wide [`limits`](/reference/createapp/) for this route only.
|
||||
|
||||
| Decorator | Method | Transport |
|
||||
|---|---|---|
|
||||
@@ -58,8 +58,9 @@ Method decorators on a controller. All accept `(path, opts?)` where `opts = { ex
|
||||
| `@Stream` | GET | negotiated (SSE / ndjson / WS) |
|
||||
|
||||
```typescript
|
||||
@Get('/ping', { export: true }) // exportable over mesh
|
||||
@Post('/upload', { duplicates: 'array' }) // repeated form fields → arrays
|
||||
@Get('/ping', { export: true }) // exportable over mesh
|
||||
@Post('/upload', { duplicates: 'array' }) // repeated form fields → arrays
|
||||
@Post('/avatar', { maxBodyBytes: 5_000_000, maxParts: 20 }) // per-route upload limits
|
||||
```
|
||||
|
||||
See [Routing](/guides/routing/) for pattern matching and [Streaming](/guides/streaming/) for the transports.
|
||||
|
||||
Reference in new issue
Block a user