feat: per-route body limits, custom error rendering, OpenAPI generation
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:
chrnx committed 2026-07-08 08:29:17 -05:00
1 parent 7c20d74fe4
commit 2db5de6858
19 files changed
+811 -100

No files matched your search

+43 -4
View File
@@ -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;
+7
View File
@@ -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
View File
@@ -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 };
+4
View File
@@ -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. */
+3
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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);
}