diff --git a/example/server.ts b/example/server.ts index c9c1367..ed43747 100644 --- a/example/server.ts +++ b/example/server.ts @@ -101,7 +101,7 @@ class PingController { @Module({ mountpoint: '/mesh', providers: [ConfigProvider], steps: [AuthStep], controllers: [PingController] }) class TeapotModule {} -export const teapotApp = createApp({ modules: [TeapotModule], mesh: { secret: 'demo-secret' } }); +export const teapotApp = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'demo-secret' } }); @Route('/remote') class TeacupController { diff --git a/src/app.ts b/src/app.ts deleted file mode 100644 index 74ead24..0000000 --- a/src/app.ts +++ /dev/null @@ -1,387 +0,0 @@ -import http from 'http'; -import { Bus } from './bus'; -import { Container } from './container'; -import { topoSort, subgraphFor, GraphNode, nearest } from './graph'; -import { toMermaid, toDOT, graphHtml, type GraphView } from './graph-viz'; -import { runPipeline, PipelineStep } from './pipeline'; -import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http'; -import { isAsyncIterable } from './channel'; -import { JsonTransformer } from './transformers'; -import { mountPlugin, Plugin, ScopeApi, ScopeNode } from './plugin'; -import { - Ctor, HttpMethod, Transport, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath, -} from './metadata'; -import { getArgs, getHandlerNeeds, resolveArgs } from './params'; -import { connectLink, type Link } from './mesh/link'; -import { Rooms } from './rooms'; -import type { TlsOptions, SecurityOptions, CorsOptions } from './security'; -import { buildRemote } from './mesh/teacup'; -import { buildManifest, createMeshControl } from './mesh/teapot'; -import type { MeshControl } from './http'; -import type { RequestEnvelope, RouteEntry } from './mesh/protocol'; - -export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string } -export interface ExplainNode { name: string; kind: 'provider' | 'step' | 'handler'; origin: string; needs: string[]; provides: string[] } -export interface Explain { pattern: string; method: HttpMethod; transport: Transport; chain: ExplainNode[] } -export interface App { - listen(port: number): Promise; - close(): Promise; - inspect(routePath: string): InspectLine[]; - graph(): GraphView; - toMermaid(): string; - toDOT(): string; - explain(routePath: string): Explain; - bus: Bus; -} - -interface RoutePlan { - pattern: string; - method: HttpMethod; - transport: Transport; - origin: string; - providers: GraphNode[]; - steps: GraphNode[]; - handlerName: string; - needs: string[]; - run: (ctx: any) => Promise; - transformer: typeof JsonTransformer; - duplicates?: 'array' | 'last'; -} - -export interface MeshConfig { - secret?: string; - teapots?: Array<{ url: string; secret: string }>; - timeoutMs?: number; -} - -export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last' }): App { - const bus = new Bus(); - const container = new Container(); - let server: http.Server | undefined; - const streams = new Set<() => void>(); - const extraSteps: ScopeNode[] = []; - const scope: ScopeApi = { add: (n) => extraSteps.push(n) }; - - // collect declarations from modules - const providerNodes: GraphNode[] = []; - const stepNodes: GraphNode[] = []; - const runners = new Map any>(); // node name -> runtime fn - const setRunner = (name: string, fn: (ctx: any) => any) => { - if (runners.has(name)) throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`); - runners.set(name, fn); - }; - const providerMeta = new Map(); - const routePlans: RoutePlan[] = []; - const exportedProviders: string[] = []; - const exportedSteps: string[] = []; - const exportedRoutes: RouteEntry[] = []; - - for (const mod of opts.modules) { - const m = getModuleMeta(mod); - if (!m) throw new Error(`${mod.name} is not a @Module`); - const origin = `module:${mod.name}`; - - for (const P of m.providers ?? []) { - const meta = getProviderMeta(P)!; - providerNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin }); - providerMeta.set(meta.provides, { optional: meta.optional }); - if (meta.export) exportedProviders.push(meta.provides); - const inst: any = new P(); - setRunner(meta.provides, (ctx) => inst.provide(ctx)); - } - for (const S of m.steps ?? []) { - const meta = getStepMeta(S)!; - stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin }); - if (meta.export) exportedSteps.push(meta.provides); - const inst: any = new S(); - setRunner(meta.provides, (ctx) => inst.run(ctx)); - } - for (const C of m.controllers ?? []) { - for (const route of getRoutes(C)) { - const inst: any = new C(); - const argSpecs = getArgs(C, route.handlerName); - const pattern = joinPath(m.mountpoint, route.path); - if (route.export) { - if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`); - exportedRoutes.push({ method: route.method, pattern }); - } - routePlans.push({ - pattern, - method: route.method, - transport: route.transport, - origin, - providers: [], - steps: [], - handlerName: route.handlerName, - needs: getHandlerNeeds(argSpecs), - run: async (c: any) => inst[route.handlerName](...(await resolveArgs(argSpecs, c))), - transformer: getTransformer(C, route.handlerName) ?? JsonTransformer, - duplicates: route.duplicates, - }); - } - } - } - - // plugin-added steps join the graph as their own scope - for (const plugin of opts.plugins ?? []) mountPlugin(plugin, bus, scope); - for (const n of extraSteps) { - const node = { name: n.name, needs: n.needs, provides: n.provides, origin: 'plugin' }; - if (n.kind === 'provider') providerNodes.push(node); else stepNodes.push(node); - setRunner(n.name, n.run); - } - - // built-in: auto-provide a shared Rooms instance (unless the user declares one) - if (!runners.has('rooms')) { - const roomsInstance = new Rooms(); - providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' }); - providerMeta.set('rooms', { optional: false }); - setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms - } - - // For each route, resolve which providers/steps feed it via topo order. - // MVP: every route depends on every declared step + provider in the app graph. - // For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first. - let orderedProviders: GraphNode[] = []; - let orderedSteps: GraphNode[] = []; - let booted = false; - const finalizeGraph = (): void => { - const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']); - orderedProviders = ordered.filter((n) => providerNodes.includes(n)); - orderedSteps = ordered.filter((n) => stepNodes.includes(n)); - const alwaysSteps = stepNodes.filter((n) => n.provides.length === 0); // side-effect/observer steps (plugins) - const alwaysNeeds = alwaysSteps.flatMap((n) => n.needs); // pull observers' deps into every route - for (const plan of routePlans) { - const closure = subgraphFor([...plan.needs, ...alwaysNeeds], ordered); - plan.providers = closure.filter((n) => providerNodes.includes(n)); - const sliced = new Set([...closure.filter((n) => stepNodes.includes(n)), ...alwaysSteps]); - plan.steps = ordered.filter((n) => stepNodes.includes(n) && sliced.has(n)); // topo order, deduped - } - - const producedKeys = new Set([ - ...providerNodes.flatMap((n) => n.provides), - ...stepNodes.flatMap((n) => n.provides), - ]); - const allowed = new Set([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']); - for (const plan of routePlans) { - for (const need of plan.needs) { - if (!allowed.has(need)) { - const hint = nearest(need, allowed); - throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`); - } - } - } - booted = true; - }; - if (!opts.mesh) finalizeGraph(); - - const inspect = (routePath: string): InspectLine[] => { - if (!booted) throw new Error('inspect() unavailable before listen() for mesh apps'); - const plan = routePlans.find((p) => p.pattern === routePath); - if (!plan) throw new Error(`no route: ${routePath}`); - return [ - ...plan.providers.map((p) => ({ name: p.name, kind: 'provider' as const, origin: p.origin })), - ...plan.steps.map((s) => ({ name: s.name, kind: 'step' as const, origin: s.origin })), - { name: plan.handlerName, kind: 'handler' as const, origin: plan.origin }, - ]; - }; - - const graph = (): GraphView => { - if (!booted) throw new Error('graph() unavailable before listen() for mesh apps'); - return { - nodes: [ - ...providerNodes.map((n) => ({ name: n.name, kind: 'provider' as const, origin: n.origin, needs: n.needs, provides: n.provides })), - ...stepNodes.map((n) => ({ name: n.name, kind: 'step' as const, origin: n.origin, needs: n.needs, provides: n.provides })), - ], - routes: routePlans.map((p) => ({ - pattern: p.pattern, method: p.method, transport: p.transport, - chain: [...p.providers.map((n) => n.name), ...p.steps.map((n) => n.name), p.handlerName], - })), - }; - }; - - const explain = (routePath: string): Explain => { - if (!booted) throw new Error('explain() unavailable before listen() for mesh apps'); - const plan = routePlans.find((p) => p.pattern === routePath); - if (!plan) throw new Error(`no route: ${routePath}`); - const nv = (n: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({ name: n.name, kind, origin: n.origin, needs: n.needs, provides: n.provides }); - return { - pattern: plan.pattern, method: plan.method, transport: plan.transport, - chain: [ - ...plan.providers.map((n) => nv(n, 'provider')), - ...plan.steps.map((n) => nv(n, 'step')), - { name: plan.handlerName, kind: 'handler', origin: plan.origin, needs: plan.needs, provides: [] }, - ], - }; - }; - - const providedSeed = async (plan: RoutePlan): Promise> => { - const provided: Record = {}; - for (const p of plan.providers) { - if (container.has(p.name)) Object.assign(provided, (await container.resolve(p.name)) as Record); - } - return provided; - }; - const planSteps = (plan: RoutePlan): PipelineStep[] => plan.steps.map((s) => { - const fn = runners.get(s.name); - if (!fn) throw new Error(`no runner registered for step '${s.name}'`); - return { name: s.name, origin: s.origin, run: fn }; - }); - - const listen = async (port: number): Promise => { - // mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize - const remoteRoutes: RouteDef[] = []; - const meshLinks: Link[] = []; - let meshControl: MeshControl | undefined; - if (opts.mesh && !booted) { - try { - for (const t of opts.mesh.teapots ?? []) { - const link = await connectLink({ url: t.url, secret: t.secret, timeoutMs: opts.mesh.timeoutMs, bus }); - meshLinks.push(link); - const { providers, steps, routes } = buildRemote(link, t.url); - for (const p of providers) { - providerNodes.push({ name: p.name, needs: [], provides: [p.name], origin: `mesh:${t.url}` }); - providerMeta.set(p.name, { optional: false }); - setRunner(p.name, p.run); - } - for (const s of steps) { - stepNodes.push({ name: s.name, needs: [], provides: [s.name], origin: `mesh:${t.url}` }); - setRunner(s.name, s.run); - } - for (const r of routes) { - remoteRoutes.push({ - method: r.method, pattern: r.pattern, transport: 'buffer', - handler: async (req) => r.handler(req as RequestEnvelope), - }); - } - } - finalizeGraph(); - } catch (err) { - for (const l of meshLinks) { try { l.close(); } catch { /* */ } } - throw err; - } - } - - // apply overrides: swap any provider/step runner by token in one line - if (opts.overrides) { - const produced = new Set([...providerNodes, ...stepNodes].flatMap((n) => n.provides)); - for (const [token, val] of Object.entries(opts.overrides)) { - if (!produced.has(token)) throw new Error(`override for unknown token '${token}'`); - const fn = typeof val === 'function' ? (val as (ctx: any) => any) : () => ({ [token]: val }); - runners.set(token, fn); // direct set (setRunner throws on dup); replaces the real runner - } - } - - // run app-scoped providers in order (fail-fast for required) - for (const node of orderedProviders) { - bus.emit('boot:provider:start', { name: node.name, scope: node.origin }); - try { - const value = await runners.get(node.name)!(await snapshot(container, node.needs)); - container.register(node.name, 'app', () => value); - await container.resolve(node.name); // warm the cache - bus.emit('boot:provider:ok', { name: node.name }); - } catch (error) { - bus.emit('boot:provider:fail', { name: node.name, error }); - if (!providerMeta.get(node.name)?.optional) { - throw new Error(`provider '${node.name}' failed: ${(error as Error).message}`); - } - // optional: warn, leave it unregistered; routes needing it fail at request time - // ponytail: full partial-degradation is out of scope (spec §10); warn is enough here - console.warn(`[green-tea] optional provider '${node.name}' failed: ${(error as Error).message}`); - } - } - - // mesh teapot: expose declared exports over the control channel (lazy resolvers read live state) - const hasExports = exportedProviders.length || exportedSteps.length || exportedRoutes.length; - if (hasExports && !opts.mesh?.secret) { - throw new Error('mesh: exports declared (export: true) but no mesh.secret configured to gate the control channel'); - } - if (opts.mesh?.secret && hasExports) { - const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes }); - const resolveScope = async (name: string, env: RequestEnvelope): Promise => { - let ctx: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers }; - for (const p of orderedProviders) if (container.has(p.name)) Object.assign(ctx, await container.resolve(p.name)); - for (const s of orderedSteps) { const fn = runners.get(s.name)!; ctx = { ...ctx, ...(await fn(ctx)) }; } - return ctx[name]; - }; - const resolveRoute = async (name: string, env: RequestEnvelope) => { - const plan = routePlans.find((p) => p.pattern === name && p.method === env.method); - if (!plan) { const e: any = new Error(`no route ${name}`); e.status = 404; throw e; } - const provided = await providedSeed(plan); - const result = await runPipeline({ - steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus, - seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers }, - }); - if ('stream' in result) { const e: any = new Error('cannot proxy a streaming route'); e.status = 500; throw e; } - return result; - }; - meshControl = createMeshControl({ secret: opts.mesh.secret, manifest, resolveScope, resolveRoute, bus }); - } - - const httpRoutes: RouteDef[] = [ - ...routePlans - .filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate - .map((plan): RouteDef => ({ - method: plan.method, pattern: plan.pattern, transport: plan.transport, bodyDuplicates: plan.duplicates, - handler: async (req) => { - const provided = await providedSeed(plan); - return runPipeline({ - steps: planSteps(plan), handler: plan.run, transformer: plan.transformer, bus, - seed: { ...provided, req, params: req.params, query: req.query, body: req.body, headers: req.headers, - protocol: req.protocol, ip: req.ip }, - }); - }, - })), - ...remoteRoutes, - ]; - - if (opts.devGraph) { - httpRoutes.push({ - method: 'GET', pattern: '/__graph__', transport: 'buffer', - handler: async (req) => { - const mermaid = toMermaid(graph()); - const accept = String(req.headers['accept'] ?? ''); - return accept.includes('text/plain') - ? { status: 200, headers: { 'content-type': 'text/plain' }, body: mermaid } - : { status: 200, headers: { 'content-type': 'text/html' }, body: graphHtml(mermaid) }; - }, - }); - } - - const wsRoutes: WsRouteDef[] = routePlans - .filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate') - .map((plan) => ({ - pattern: plan.pattern, - open: async ({ params, inbound, abort, req }) => { - const provided = await providedSeed(plan); - // ws upgrades come in on the raw Node req; trustProxy derivation for ws is out of scope here - let ctx: any = { ...provided, req, params, query: parseQuery(req.url ?? ''), body: undefined, - headers: req.headers, inbound, abort, - protocol: (req.socket as any).encrypted ? 'https' : 'http', ip: req.socket.remoteAddress ?? '' }; - for (const s of planSteps(plan)) { ctx = { ...ctx, ...(await s.run(ctx)) }; } - const out = await plan.run(ctx); - if (!isAsyncIterable(out)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`); - return out as AsyncIterable; - }, - })); - - server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true, cors: opts.cors, bodyDuplicates: opts.bodyDuplicates }); - server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } }); - await new Promise((resolve) => server!.listen(port, resolve)); - return server; - }; - - const close = (): Promise => new Promise((resolve) => { - if (!server) return resolve(); - server.close(() => resolve()); // waits for in-flight buffered to drain - for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves - server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive - }); - - return { listen, close, inspect, graph, toMermaid: () => toMermaid(graph()), toDOT: () => toDOT(graph()), explain, bus }; -} - -async function snapshot(c: Container, needs: string[]): Promise> { - const out: Record = {}; - for (const key of needs) if (c.has(key)) Object.assign(out, (await c.resolve(key)) as Record); - return out; -} diff --git a/src/app/index.ts b/src/app/index.ts new file mode 100644 index 0000000..4073e14 --- /dev/null +++ b/src/app/index.ts @@ -0,0 +1,625 @@ +import http from 'http'; +import { Bus } from '../bus'; +import { Container } from '../container'; +import { topoSort, subgraphFor, GraphNode, nearest } from '../graph'; +import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz'; +import { runPipeline, PipelineStep } from '../pipeline'; +import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; +import { isAsyncIterable } from '../channel'; +import { JsonTransformer } 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 { connectLink, type Link } from '../mesh/link'; +import { Rooms } from '../rooms'; +import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; +import { buildRemote } from '../mesh/teacup'; +import { buildManifest, createMeshControl } from '../mesh/teapot'; +import type { MeshControl } from '../http'; +import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; +import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types'; +import { inspectRoute, buildGraphView, explainRoute } from './introspect'; + +export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types'; + +type Runner = (ctx: any) => any; + +/** Mutable graph state assembled from modules/plugins and later spliced with remote mesh scopes. */ +interface Registry { + providerNodes: GraphNode[]; + stepNodes: GraphNode[]; + runners: Map; + providerMeta: Map; + routePlans: RoutePlan[]; + exportedProviders: string[]; + exportedSteps: string[]; + exportedRoutes: RouteEntry[]; + setRunner(name: string, runner: Runner): void; +} + +/** Request-time helpers shared by the HTTP, WS and mesh route builders. */ +interface PipelineDeps { + providedSeed(plan: RoutePlan): Promise>; + planSteps(plan: RoutePlan): PipelineStep[]; + bus: Bus; +} + +/** + * Build an {@link App} from the given modules and options. + * Wires providers, steps, controllers and plugins into a dependency graph; for non-mesh apps + * the graph is finalized eagerly, otherwise finalization is deferred to {@link App.listen}. + */ +export function createApp(opts: { + modules: Ctor[]; + plugins?: Plugin[]; + mesh?: MeshConfig; + limits?: RequestLimits; + devGraph?: boolean; + overrides?: Record; + tls?: TlsOptions; + trustProxy?: boolean; + security?: boolean | SecurityOptions; + cors?: CorsOptions; + bodyDuplicates?: 'array' | 'last'; + /** Opt in to alpha features whose API may still change. Currently gates `mesh`. */ + experimental?: boolean; +}): App { + // mesh is alpha: its API and wire protocol may change. Require an explicit opt-in. + if (opts.mesh && !opts.experimental) { + throw new Error( + 'mesh is an alpha feature — pass `experimental: true` to createApp to enable it (its API may change between releases)', + ); + } + + const bus = new Bus(); + const container = new Container(); + let server: http.Server | undefined; + const streams = new Set<() => void>(); + const degradedProviders: string[] = []; // optional providers that failed to boot (running degraded) + + // Collect declarations from modules, then splice in plugin- and built-in-provided nodes. + const registry = collectModules(opts.modules); + const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry; + mountPlugins(opts.plugins, bus, registry); + provideBuiltins(registry); + + // For each route, resolve which providers/steps feed it via topo order. + // MVP: every route depends on every declared step + provider in the app graph. + // For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first. + let orderedProviders: GraphNode[] = []; + let orderedSteps: GraphNode[] = []; + let booted = false; + + const finalize = (): void => { + ({ orderedProviders, orderedSteps } = finalizeGraph(registry)); + booted = true; + }; + + if (!opts.mesh) finalize(); + + 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 providedSeed = (plan: RoutePlan) => seedProviders(container, plan); + const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); + + const listen = async (port: number): Promise => { + const deps: PipelineDeps = { providedSeed, planSteps, bus }; + + // mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize + let remoteRoutes: RouteDef[] = []; + const meshLinks: Link[] = []; + + if (opts.mesh && !booted) { + const spliced = await spliceRemoteScopes(opts.mesh, bus, registry); + remoteRoutes = spliced.remoteRoutes; + meshLinks.push(...spliced.meshLinks); + finalize(); + } + + applyOverrides(opts.overrides, registry); + degradedProviders.length = 0; + degradedProviders.push(...(await bootProviders(orderedProviders, { runners, container, providerMeta, bus }))); + + if (degradedProviders.length) { + console.warn( + `[green-tea] started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`, + ); + } + + const meshControl = buildMeshControl(opts.mesh, registry, { + container, + orderedProviders, + orderedSteps, + deps, + }); + + const httpRoutes = buildHttpRoutes(routePlans, remoteRoutes, deps); + if (opts.devGraph) httpRoutes.push(devGraphRoute(graph)); + const wsRoutes = buildWsRoutes(routePlans, deps); + + server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { + limits: opts.limits, + streams, + tls: opts.tls, + trustProxy: opts.trustProxy, + security: opts.security ?? true, + cors: opts.cors, + bodyDuplicates: opts.bodyDuplicates, + }); + server.on('close', () => closeLinks(meshLinks)); + await new Promise((resolve) => server!.listen(port, resolve)); + return server; + }; + + const close = (): Promise => + new Promise((resolve) => { + if (!server) return resolve(); + server.close(() => resolve()); // waits for in-flight buffered to drain + for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves + server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive + }); + + return { + listen, + close, + inspect, + graph, + toMermaid: () => toMermaid(graph()), + toDOT: () => toDOT(graph()), + explain, + degraded: () => [...degradedProviders], + bus, + }; +} + +/** Creates an empty {@link Registry} whose `setRunner` enforces globally-unique provider/step names. */ +function emptyRegistry(): Registry { + const runners = new Map(); // node name -> runtime fn + + const setRunner = (name: string, runner: Runner) => { + if (runners.has(name)) + throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`); + runners.set(name, runner); + }; + + return { + providerNodes: [], + stepNodes: [], + runners, + providerMeta: new Map(), + routePlans: [], + exportedProviders: [], + exportedSteps: [], + exportedRoutes: [], + setRunner, + }; +} + +/** Registers a module's `@Provider` classes as app-scope provider nodes. */ +function collectProviders(providers: Ctor[], origin: string, registry: Registry): void { + for (const ProviderClass of providers) { + const meta = getProviderMeta(ProviderClass)!; + registry.providerNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin }); + registry.providerMeta.set(meta.provides, { optional: meta.optional }); + if (meta.export) registry.exportedProviders.push(meta.provides); + const instance: any = new ProviderClass(); + registry.setRunner(meta.provides, (ctx) => instance.provide(ctx)); + } +} + +/** Registers a module's `@Step` classes as request-scope step nodes. */ +function collectSteps(steps: Ctor[], origin: string, registry: Registry): void { + for (const StepClass of steps) { + const meta = getStepMeta(StepClass)!; + registry.stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin }); + if (meta.export) registry.exportedSteps.push(meta.provides); + const instance: any = new StepClass(); + registry.setRunner(meta.provides, (ctx) => instance.run(ctx)); + } +} + +/** Registers each `@Route` handler on a module's controllers as a {@link RoutePlan}. */ +function collectControllers(controllers: Ctor[], mountpoint: string, origin: string, registry: Registry): void { + for (const ControllerClass of controllers) { + for (const route of getRoutes(ControllerClass)) { + const instance: any = new ControllerClass(); + const argSpecs = getArgs(ControllerClass, route.handlerName); + const pattern = joinPath(mountpoint, route.path); + + if (route.export) { + if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`); + registry.exportedRoutes.push({ method: route.method, pattern }); + } + + registry.routePlans.push({ + pattern, + method: route.method, + transport: route.transport, + origin, + providers: [], + steps: [], + handlerName: route.handlerName, + needs: getHandlerNeeds(argSpecs), + run: async (context: any) => instance[route.handlerName](...(await resolveArgs(argSpecs, context))), + transformer: getTransformer(ControllerClass, route.handlerName) ?? JsonTransformer, + duplicates: route.duplicates, + }); + } + } +} + +/** Reads every module's metadata into a fresh {@link Registry} of graph nodes, runners and exports. */ +function collectModules(modules: Ctor[]): Registry { + const registry = emptyRegistry(); + + for (const mod of modules) { + const moduleMeta = getModuleMeta(mod); + if (!moduleMeta) throw new Error(`${mod.name} is not a @Module`); + const origin = `module:${mod.name}`; + collectProviders(moduleMeta.providers ?? [], origin, registry); + collectSteps(moduleMeta.steps ?? [], origin, registry); + collectControllers(moduleMeta.controllers ?? [], moduleMeta.mountpoint, origin, registry); + } + + return registry; +} + +/** Mounts plugins and splices any steps/providers they add into the registry as their own scope. */ +function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registry): void { + const extraSteps: ScopeNode[] = []; + const scope: ScopeApi = { add: (node) => extraSteps.push(node) }; + + for (const plugin of plugins ?? []) mountPlugin(plugin, bus, scope); + + for (const scopeNode of extraSteps) { + const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' }; + if (scopeNode.kind === 'provider') registry.providerNodes.push(node); + else registry.stepNodes.push(node); + registry.setRunner(scopeNode.name, scopeNode.run); + } +} + +/** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */ +function provideBuiltins(registry: Registry): void { + if (registry.runners.has('rooms')) return; + const roomsInstance = new Rooms(); + registry.providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' }); + registry.providerMeta.set('rooms', { optional: false }); + registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms +} + +/** + * Topo-sorts the graph, slices each route's provider/step closure into its plan, and validates every need. + * @returns The app-scope providers and request-scope steps in execution order. + */ +function finalizeGraph(registry: Registry): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } { + const { providerNodes, stepNodes, routePlans } = registry; + const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']); + const orderedProviders = ordered.filter((node) => providerNodes.includes(node)); + const orderedSteps = ordered.filter((node) => stepNodes.includes(node)); + const alwaysSteps = stepNodes.filter((node) => node.provides.length === 0); // side-effect/observer steps (plugins) + const alwaysNeeds = alwaysSteps.flatMap((node) => node.needs); // pull observers' deps into every route + + for (const plan of routePlans) { + const closure = subgraphFor([...plan.needs, ...alwaysNeeds], ordered); + plan.providers = closure.filter((node) => providerNodes.includes(node)); + const sliced = new Set([...closure.filter((node) => stepNodes.includes(node)), ...alwaysSteps]); + plan.steps = ordered.filter((node) => stepNodes.includes(node) && sliced.has(node)); // topo order, deduped + } + + assertNeedsSatisfiable(routePlans, providerNodes, stepNodes); + return { orderedProviders, orderedSteps }; +} + +/** Throws if any route needs a key that nothing (local or mesh) provides, suggesting the nearest match. */ +function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNode[], stepNodes: GraphNode[]): void { + const producedKeys = new Set([ + ...providerNodes.flatMap((node) => node.provides), + ...stepNodes.flatMap((node) => node.provides), + ]); + const allowed = new Set([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']); + + for (const plan of routePlans) { + for (const need of plan.needs) { + if (allowed.has(need)) continue; + const hint = nearest(need, allowed); + throw new Error( + `handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`, + ); + } + } +} + +/** Connects the configured teapots, splices their remote providers/steps into the registry, and returns their routes. */ +async function spliceRemoteScopes( + mesh: MeshConfig, + bus: Bus, + registry: Registry, +): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> { + const remoteRoutes: RouteDef[] = []; + const meshLinks: Link[] = []; + + try { + for (const teapot of mesh.teapots ?? []) { + const link = await connectLink({ url: teapot.url, secret: teapot.secret, timeoutMs: mesh.timeoutMs, bus }); + meshLinks.push(link); + const { providers, steps, routes } = buildRemote(link); + const origin = `mesh:${teapot.url}`; + + for (const provider of providers) { + registry.providerNodes.push({ name: provider.name, needs: [], provides: [provider.name], origin }); + registry.providerMeta.set(provider.name, { optional: false }); + registry.setRunner(provider.name, provider.run); + } + + for (const step of steps) { + registry.stepNodes.push({ name: step.name, needs: [], provides: [step.name], origin }); + registry.setRunner(step.name, step.run); + } + + for (const route of routes) { + remoteRoutes.push({ + method: route.method, + pattern: route.pattern, + transport: 'buffer', + handler: async (req) => route.handler(req as RequestEnvelope), + }); + } + } + } catch (err) { + closeLinks(meshLinks); + throw err; + } + + return { remoteRoutes, meshLinks }; +} + +/** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */ +function applyOverrides(overrides: Record | undefined, registry: Registry): void { + if (!overrides) return; + const produced = new Set([...registry.providerNodes, ...registry.stepNodes].flatMap((node) => node.provides)); + + for (const [token, val] of Object.entries(overrides)) { + if (!produced.has(token)) throw new Error(`override for unknown token '${token}'`); + const runner: Runner = typeof val === 'function' ? (val as Runner) : () => ({ [token]: val }); + registry.runners.set(token, runner); // direct set (setRunner throws on dup); replaces the real runner + } +} + +/** + * Runs app-scoped providers in topo order, caching each result; required failures abort, optional ones warn. + * @returns The names of optional providers that failed and are running degraded (unregistered). + */ +async function bootProviders( + orderedProviders: GraphNode[], + deps: { + runners: Map; + container: Container; + providerMeta: Map; + bus: Bus; + }, +): Promise { + const { runners, container, providerMeta, bus } = deps; + const degraded: string[] = []; + + for (const node of orderedProviders) { + bus.emit('boot:provider:start', { name: node.name, scope: node.origin }); + + try { + const value = await runners.get(node.name)!(await snapshot(container, node.needs)); + container.register(node.name, 'app', () => value); + await container.resolve(node.name); // warm the cache + bus.emit('boot:provider:ok', { name: node.name }); + } catch (error) { + bus.emit('boot:provider:fail', { name: node.name, error }); + + if (!providerMeta.get(node.name)?.optional) { + throw new Error(`provider '${node.name}' failed: ${(error as Error).message}`); + } + + // optional: warn, leave it unregistered; routes needing it fail at request time + // ponytail: full partial-degradation is out of scope (spec §10); warn is enough here + degraded.push(node.name); + console.warn(`[green-tea] optional provider '${node.name}' failed: ${(error as Error).message}`); + } + } + + return degraded; +} + +/** + * Builds the mesh control gateway that exposes this node's declared exports over the control channel. + * Returns undefined when there is nothing to export; throws if exports are declared without a gating secret. + */ +function buildMeshControl( + mesh: MeshConfig | undefined, + registry: Registry, + deps: { container: Container; orderedProviders: GraphNode[]; orderedSteps: GraphNode[]; deps: PipelineDeps }, +): MeshControl | undefined { + const { exportedProviders, exportedSteps, exportedRoutes, routePlans, runners } = registry; + const hasExports = exportedProviders.length || exportedSteps.length || exportedRoutes.length; + + if (hasExports && !mesh?.secret) { + throw new Error('mesh: exports declared (export: true) but no mesh.secret configured to gate the control channel'); + } + + if (!mesh?.secret || !hasExports) return undefined; + const { container, orderedProviders, orderedSteps } = deps; + const { bus, providedSeed, planSteps } = deps.deps; + const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes }); + + const resolveScope = async (name: string, env: RequestEnvelope): Promise => { + // context is intentionally `any`: providers and steps merge arbitrary keys into it + let context: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers }; + + for (const provider of orderedProviders) + if (container.has(provider.name)) Object.assign(context, await container.resolve(provider.name)); + + for (const step of orderedSteps) { + const runner = runners.get(step.name)!; + context = { ...context, ...(await runner(context)) }; + } + + return context[name]; + }; + + const resolveRoute = async (name: string, env: RequestEnvelope) => { + const plan = routePlans.find((candidate) => candidate.pattern === name && candidate.method === env.method); + + if (!plan) { + const error: any = new Error(`no route ${name}`); + error.status = 404; + throw error; + } + + const provided = await providedSeed(plan); + const result = await runPipeline({ + steps: planSteps(plan), + handler: plan.run, + transformer: plan.transformer, + bus, + seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers }, + }); + + if ('stream' in result) { + const error: any = new Error('cannot proxy a streaming route'); + error.status = 500; + throw error; + } + + return result; + }; + + return createMeshControl({ secret: mesh.secret, manifest, resolveScope, resolveRoute, bus }); +} + +/** 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 local = routePlans + .filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate + .map((plan): RouteDef => ({ + method: plan.method, + pattern: plan.pattern, + transport: plan.transport, + bodyDuplicates: plan.duplicates, + handler: async (req) => { + const provided = await providedSeed(plan); + return runPipeline({ + steps: planSteps(plan), + handler: plan.run, + transformer: plan.transformer, + bus, + seed: { + ...provided, + req, + params: req.params, + query: req.query, + body: req.body, + headers: req.headers, + protocol: req.protocol, + ip: req.ip, + }, + }); + }, + })); + + return [...local, ...remoteRoutes]; +} + +/** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */ +function devGraphRoute(graph: () => GraphView): RouteDef { + return { + method: 'GET', + pattern: '/__graph__', + transport: 'buffer', + handler: async (req) => { + const mermaid = toMermaid(graph()); + const accept = String(req.headers['accept'] ?? ''); + return accept.includes('text/plain') + ? { status: 200, headers: { 'content-type': 'text/plain' }, body: mermaid } + : { status: 200, headers: { 'content-type': 'text/html' }, body: graphHtml(mermaid) }; + }, + }; +} + +/** 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; + + return routePlans + .filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate') + .map((plan) => ({ + pattern: plan.pattern, + open: async ({ params, inbound, abort, req }) => { + const provided = await providedSeed(plan); + // ws upgrades come in on the raw Node req; trustProxy derivation for ws is out of scope here + // context is intentionally `any`: each step merges arbitrary keys into it + let context: any = { + ...provided, + req, + params, + query: parseQuery(req.url ?? ''), + body: undefined, + headers: req.headers, + inbound, + abort, + protocol: (req.socket as any).encrypted ? 'https' : 'http', + ip: req.socket.remoteAddress ?? '', + }; + + for (const step of planSteps(plan)) { + context = { ...context, ...(await step.run(context)) }; + } + + const result = await plan.run(context); + if (!isAsyncIterable(result)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`); + return result as AsyncIterable; + }, + })); +} + +/** Best-effort close of every mesh link, ignoring individual failures. */ +function closeLinks(links: Link[]): void { + for (const link of links) { + try { + link.close(); + } catch { + /* */ + } + } +} + +/** Merges every app-scope provider bound to a route into a request seed (skips unresolved providers). */ +async function seedProviders(container: Container, plan: RoutePlan): Promise> { + const provided: Record = {}; + + for (const provider of plan.providers) { + if (container.has(provider.name)) + Object.assign(provided, (await container.resolve(provider.name)) as Record); + } + + return provided; +} + +/** Resolves a route's step nodes into runnable pipeline steps, failing if any runner is missing. */ +function compilePlanSteps(runners: Map, plan: RoutePlan): PipelineStep[] { + return plan.steps.map((step) => { + const runner = runners.get(step.name); + if (!runner) throw new Error(`no runner registered for step '${step.name}'`); + return { name: step.name, origin: step.origin, run: runner }; + }); +} + +/** Resolves the given need-keys from the container into a merged snapshot (skips unregistered keys). */ +async function snapshot(container: Container, needs: string[]): Promise> { + const resolved: Record = {}; + + for (const key of needs) + if (container.has(key)) Object.assign(resolved, (await container.resolve(key)) as Record); + + return resolved; +} diff --git a/src/app/introspect.ts b/src/app/introspect.ts new file mode 100644 index 0000000..7607c3d --- /dev/null +++ b/src/app/introspect.ts @@ -0,0 +1,77 @@ +import type { GraphNode } from '../graph'; +import type { GraphView } from '../graph-viz'; +import type { InspectLine, Explain, ExplainNode, RoutePlan } from './types'; + +/** Lists the provider/step/handler chain for a route, in execution order. */ +export function inspectRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): InspectLine[] { + if (!booted) throw new Error('inspect() unavailable before listen() for mesh apps'); + const plan = routePlans.find((candidate) => candidate.pattern === routePath); + if (!plan) throw new Error(`no route: ${routePath}`); + return [ + ...plan.providers.map((provider) => ({ + name: provider.name, + kind: 'provider' as const, + origin: provider.origin, + })), + ...plan.steps.map((step) => ({ name: step.name, kind: 'step' as const, origin: step.origin })), + { name: plan.handlerName, kind: 'handler' as const, origin: plan.origin }, + ]; +} + +/** Builds the full dependency-graph view: every provider/step node plus each route's chain. */ +export function buildGraphView( + providerNodes: GraphNode[], + stepNodes: GraphNode[], + routePlans: RoutePlan[], + booted: boolean, +): GraphView { + if (!booted) throw new Error('graph() unavailable before listen() for mesh apps'); + return { + nodes: [ + ...providerNodes.map((node) => ({ + name: node.name, + kind: 'provider' as const, + origin: node.origin, + needs: node.needs, + provides: node.provides, + })), + ...stepNodes.map((node) => ({ + name: node.name, + kind: 'step' as const, + origin: node.origin, + needs: node.needs, + provides: node.provides, + })), + ], + routes: routePlans.map((plan) => ({ + pattern: plan.pattern, + method: plan.method, + transport: plan.transport, + chain: [...plan.providers.map((node) => node.name), ...plan.steps.map((node) => node.name), plan.handlerName], + })), + }; +} + +/** Explains a single route: its match criteria and the ordered chain with each node's needs/provides. */ +export function explainRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): Explain { + if (!booted) throw new Error('explain() unavailable before listen() for mesh apps'); + const plan = routePlans.find((candidate) => candidate.pattern === routePath); + if (!plan) throw new Error(`no route: ${routePath}`); + const toExplainNode = (node: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({ + name: node.name, + kind, + origin: node.origin, + needs: node.needs, + provides: node.provides, + }); + return { + pattern: plan.pattern, + method: plan.method, + transport: plan.transport, + chain: [ + ...plan.providers.map((node) => toExplainNode(node, 'provider')), + ...plan.steps.map((node) => toExplainNode(node, 'step')), + { name: plan.handlerName, kind: 'handler', origin: plan.origin, needs: plan.needs, provides: [] }, + ], + }; +} diff --git a/src/app/types.ts b/src/app/types.ts new file mode 100644 index 0000000..8876f44 --- /dev/null +++ b/src/app/types.ts @@ -0,0 +1,66 @@ +import type http from 'http'; +import type { Bus } from '../bus'; +import type { GraphNode } from '../graph'; +import type { GraphView } from '../graph-viz'; +import type { HttpMethod, Transport } from '../metadata'; +import { JsonTransformer } from '../transformers'; + +/** One entry in an {@link App.inspect} listing: a provider, step or handler and where it came from. */ +export interface InspectLine { + name: string; + kind: 'provider' | 'step' | 'handler'; + origin: string; +} + +/** A node in an {@link Explain} chain, annotated with the keys it needs and provides. */ +export interface ExplainNode { + name: string; + kind: 'provider' | 'step' | 'handler'; + origin: string; + needs: string[]; + provides: string[]; +} + +/** A full route explanation: its match criteria and the ordered provider/step/handler chain. */ +export interface Explain { + pattern: string; + method: HttpMethod; + transport: Transport; + chain: ExplainNode[]; +} + +/** A running application instance with lifecycle, introspection and graph-export methods. */ +export interface App { + listen(port: number): Promise; + close(): Promise; + inspect(routePath: string): InspectLine[]; + graph(): GraphView; + toMermaid(): string; + toDOT(): string; + explain(routePath: string): Explain; + /** Names of optional providers that failed to boot and are running degraded (empty until {@link App.listen}). */ + degraded(): string[]; + bus: Bus; +} + +/** Internal per-route plan: match criteria, its resolved provider/step closure, and the compiled handler. */ +export interface RoutePlan { + pattern: string; + method: HttpMethod; + transport: Transport; + origin: string; + providers: GraphNode[]; + steps: GraphNode[]; + handlerName: string; + needs: string[]; + run: (ctx: any) => Promise; + transformer: typeof JsonTransformer; + duplicates?: 'array' | 'last'; +} + +/** Mesh networking options: a secret to gate this node's exports and/or remote teapots to connect to. */ +export interface MeshConfig { + secret?: string; + teapots?: Array<{ url: string; secret: string }>; + timeoutMs?: number; +} diff --git a/src/bus.ts b/src/bus.ts index 9143d9e..149b890 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -1,10 +1,20 @@ +/** Names of every lifecycle event the framework emits over the {@link Bus}. */ export type LifecycleEvent = - | 'boot:provider:start' | 'boot:provider:ok' | 'boot:provider:fail' - | 'request:step:enter' | 'request:step:leave' | 'request:step:error' - | 'stream:open' | 'stream:close' | 'stream:error' - | 'mesh:connect' | 'mesh:disconnect' | 'mesh:rpc:error' + | 'boot:provider:start' + | 'boot:provider:ok' + | 'boot:provider:fail' + | 'request:step:enter' + | 'request:step:leave' + | 'request:step:error' + | 'stream:open' + | 'stream:close' + | 'stream:error' + | 'mesh:connect' + | 'mesh:disconnect' + | 'mesh:rpc:error' | 'plugin:mounted'; +/** Data carried by a lifecycle event: the subject's name plus optional scope, error and timing. */ export interface EventPayload { name: string; scope?: string; @@ -12,19 +22,26 @@ export interface EventPayload { durationMs?: number; } +/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */ export class Bus { private readonly listeners = new Map void>>(); - on(event: LifecycleEvent, fn: (p: EventPayload) => void): () => void { - const set = this.listeners.get(event) ?? new Set(); - set.add(fn); - this.listeners.set(event, set); - return () => set.delete(fn); + /** Subscribe `listener` to `event`; returns an unsubscribe function. */ + on(event: LifecycleEvent, listener: (p: EventPayload) => void): () => void { + const listenerSet = this.listeners.get(event) ?? new Set(); + listenerSet.add(listener); + this.listeners.set(event, listenerSet); + return () => listenerSet.delete(listener); } - emit(event: LifecycleEvent, p: EventPayload): void { - for (const fn of this.listeners.get(event) ?? []) { - try { fn(p); } catch { /* observers must never break the pipeline */ } + /** Dispatch `payload` to every listener of `event`; a throwing listener is isolated and does not affect the others. */ + emit(event: LifecycleEvent, payload: EventPayload): void { + for (const listener of this.listeners.get(event) ?? []) { + try { + listener(payload); + } catch { + /* observers must never break the pipeline */ + } } } } diff --git a/src/channel.ts b/src/channel.ts index def9077..7f71793 100644 --- a/src/channel.ts +++ b/src/channel.ts @@ -1,3 +1,7 @@ +/** + * A push-driven async stream: producers call `push`/`close`/`fail`, consumers use `for await`. + * Each `for await` gets its own independent subscription (fan-out). + */ export interface Channel extends AsyncIterable { push(value: T): void; close(): void; @@ -5,15 +9,16 @@ export interface Channel extends AsyncIterable { readonly closed: boolean; } +/** Type guard: true when `x` implements the async-iterable protocol. */ export function isAsyncIterable(x: unknown): x is AsyncIterable { return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function'; } interface Sub { iterator: AsyncIterator; - push(v: T, cap: number): void; + push(value: T, cap: number): void; end(): void; - fail(e: unknown): void; + fail(err: unknown): void; } function newSub(onReturn: () => void): Sub { @@ -23,29 +28,48 @@ function newSub(onReturn: () => void): Sub { let failure: { err: unknown } | null = null; return { - push(v, cap) { + push(value, cap) { if (ended) return; - if (pending) { const p = pending; pending = null; p.resolve({ value: v, done: false }); return; } - queue.push(v); + + if (pending) { + const waiter = pending; + pending = null; + waiter.resolve({ value, done: false }); + return; + } + + queue.push(value); if (queue.length > cap) queue.shift(); // drop-oldest when buffer is full }, end() { if (ended) return; ended = true; - if (pending) { const p = pending; pending = null; p.resolve({ value: undefined as never, done: true }); } + + if (pending) { + const waiter = pending; + pending = null; + waiter.resolve({ value: undefined as never, done: true }); + } }, - fail(e) { + fail(err) { if (ended) return; ended = true; - failure = { err: e }; - if (pending) { const p = pending; pending = null; p.reject(e); } + failure = { err }; + + if (pending) { + const waiter = pending; + pending = null; + waiter.reject(err); + } }, iterator: { next(): Promise> { if (queue.length) return Promise.resolve({ value: queue.shift() as T, done: false }); if (failure) return Promise.reject(failure.err); if (ended) return Promise.resolve({ value: undefined as never, done: true }); - return new Promise>((resolve, reject) => { pending = { resolve, reject }; }); + return new Promise>((resolve, reject) => { + pending = { resolve, reject }; + }); }, return(): Promise> { ended = true; @@ -56,6 +80,10 @@ function newSub(onReturn: () => void): Sub { }; } +/** + * Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber. + * @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded). + */ export function channel(opts: { buffer?: number } = {}): Channel { const cap = opts.buffer ?? Infinity; const subs = new Set>(); @@ -63,27 +91,31 @@ export function channel(opts: { buffer?: number } = {}): Channel { let closedFlag = false; return { - get closed() { return closedFlag; }, + get closed() { + return closedFlag; + }, push(value) { if (done) return; - for (const s of subs) s.push(value, cap); + for (const sub of subs) sub.push(value, cap); }, close() { if (done) return; - done = true; closedFlag = true; - for (const s of subs) s.end(); + done = true; + closedFlag = true; + for (const sub of subs) sub.end(); subs.clear(); }, fail(err) { if (done) return; - done = true; closedFlag = true; - for (const s of subs) s.fail(err); + done = true; + closedFlag = true; + for (const sub of subs) sub.fail(err); subs.clear(); }, [Symbol.asyncIterator](): AsyncIterator { - const s = newSub(() => subs.delete(s)); - subs.add(s); - return s.iterator; + const sub = newSub(() => subs.delete(sub)); + subs.add(sub); + return sub.iterator; }, }; } diff --git a/src/container.ts b/src/container.ts index d376eeb..af53dd0 100644 --- a/src/container.ts +++ b/src/container.ts @@ -1,27 +1,43 @@ +/** Lifetime of a binding: `app` values are memoized for the process, `request` values are recomputed per resolve. */ export type Scope = 'app' | 'request'; +/** Produces a bound value from the current context; may be async. */ export type Factory = (ctx: Record) => unknown | Promise; -interface Binding { scope: Scope; factory: Factory; cached?: unknown; resolved?: boolean } +interface Binding { + scope: Scope; + factory: Factory; + cached?: unknown; + resolved?: boolean; +} +/** Minimal token-keyed dependency container with app-scoped memoization and async, mesh-ready resolution. */ export class Container { private readonly bindings = new Map(); + /** Bind `token` to `factory` under `scope`, replacing any existing binding. */ register(token: string, scope: Scope, factory: Factory): void { this.bindings.set(token, { scope, factory }); } + /** Whether `token` currently has a binding. */ has(token: string): boolean { return this.bindings.has(token); } + /** Resolve `token`'s value; app-scoped results are cached, request-scoped ones re-run the factory. Throws on unknown tokens. */ // ponytail: app-scope memoizes; request-scope always re-runs. resolve is async // so a future remote transport (mesh) slots in without changing callers. async resolve(token: string, ctx: Record = {}): Promise { - const b = this.bindings.get(token); - if (!b) throw new Error(`unknown token: ${token}`); - if (b.scope === 'app' && b.resolved) return b.cached; - const value = await b.factory(ctx); - if (b.scope === 'app') { b.cached = value; b.resolved = true; } + const binding = this.bindings.get(token); + if (!binding) throw new Error(`unknown token: ${token}`); + if (binding.scope === 'app' && binding.resolved) return binding.cached; + const value = await binding.factory(ctx); + + if (binding.scope === 'app') { + binding.cached = value; + binding.resolved = true; + } + return value; } } diff --git a/src/encoders.ts b/src/encoders.ts index e5642e3..9819a88 100644 --- a/src/encoders.ts +++ b/src/encoders.ts @@ -1,3 +1,7 @@ +/** + * Serializes stream items into wire frames for a streaming transport (SSE, NDJSON). + * `headers` is written once before the first frame; `ping` (if present) is sent periodically to keep the connection alive. + */ export interface StreamEncoder { headers: Record; encode(item: unknown): string | Buffer; @@ -5,17 +9,19 @@ export interface StreamEncoder { ping?(): string; } -const msgOf = (e: unknown): string => (e instanceof Error ? e.message : String(e)); +const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error)); +/** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */ export const sseEncoder: StreamEncoder = { headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' }, encode: (item) => `data: ${JSON.stringify(item)}\n\n`, - encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: msgOf(err) })}\n\n`, + encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`, ping: () => ': ping\n\n', }; +/** Newline-delimited JSON encoder: one JSON object per line. */ export const ndjsonEncoder: StreamEncoder = { headers: { 'content-type': 'application/x-ndjson' }, encode: (item) => `${JSON.stringify(item)}\n`, - encodeError: (err) => `${JSON.stringify({ error: msgOf(err) })}\n`, + encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`, }; diff --git a/src/flow.ts b/src/flow.ts index 263af84..1728083 100644 --- a/src/flow.ts +++ b/src/flow.ts @@ -1,18 +1,23 @@ +/** A single flow step: receives the accumulated context and returns the fields it contributes. */ export type StepFn = (ctx: In) => Out | Promise; +/** A built flow ready to execute: its ordered steps, terminal handler, and a `run` entry point. */ export interface CompiledFlow { steps: { name: string; fn: StepFn }[]; handler: (ctx: Acc) => unknown; run(seed: Seed): Promise; } +/** Immutable builder that chains typed steps, each widening the accumulated context type. */ export class Flow { constructor(private readonly steps: { name: string; fn: StepFn }[] = []) {} + /** Appends a step and returns a new Flow whose context now includes the step's output. */ step(name: string, fn: StepFn): Flow { return new Flow([...this.steps, { name, fn }]); } + /** Seals the flow with a terminal handler, producing a runnable CompiledFlow. */ handle(handler: (ctx: Acc) => unknown): CompiledFlow { const steps = this.steps; return { @@ -20,16 +25,19 @@ export class Flow { handler, async run(seed: Seed): Promise { let ctx: any = { ...seed }; - for (const s of steps) { - const out = await s.fn(ctx); - ctx = { ...ctx, ...out }; + + for (const step of steps) { + const output = await step.fn(ctx); + ctx = { ...ctx, ...output }; } + return handler(ctx); }, }; } } +/** Starts a new flow whose seed and initial context are the same type. */ export function flow(): Flow { return new Flow(); } diff --git a/src/graph-viz.ts b/src/graph-viz.ts index f981962..686c2eb 100644 --- a/src/graph-viz.ts +++ b/src/graph-viz.ts @@ -1,45 +1,81 @@ -export interface GraphNodeView { name: string; kind: 'provider' | 'step'; origin: string; needs: string[]; provides: string[] } -export interface GraphRouteView { pattern: string; method: string; transport: string; chain: string[] } -export interface GraphView { nodes: GraphNodeView[]; routes: GraphRouteView[] } +/** Renderable view of a graph node (provider or step). */ +export interface GraphNodeView { + name: string; + kind: 'provider' | 'step'; + origin: string; + needs: string[]; + provides: string[]; +} +/** Renderable view of a route and the chain of nodes feeding its handler. */ +export interface GraphRouteView { + pattern: string; + method: string; + transport: string; + chain: string[]; +} +/** Full graph payload consumed by the diagram renderers. */ +export interface GraphView { + nodes: GraphNodeView[]; + routes: GraphRouteView[]; +} -const nid = (s: string) => 'n_' + s.replace(/[^a-zA-Z0-9]/g, '_'); -const rid = (s: string) => 'r_' + s.replace(/[^a-zA-Z0-9]/g, '_'); +/** Sanitizes a node name into a Mermaid/DOT-safe node id. */ +const nid = (name: string) => 'n_' + name.replace(/[^a-zA-Z0-9]/g, '_'); +/** Sanitizes a route pattern into a Mermaid/DOT-safe node id. */ +const rid = (pattern: string) => 'r_' + pattern.replace(/[^a-zA-Z0-9]/g, '_'); +/** Renders the graph view as Mermaid `flowchart` source. */ export function toMermaid(view: GraphView): string { - const known = new Set(view.nodes.map((n) => n.name)); + const known = new Set(view.nodes.map((node) => node.name)); const out: string[] = ['flowchart LR']; - for (const n of view.nodes) { - out.push(n.kind === 'provider' ? ` ${nid(n.name)}(["${n.name}"])` : ` ${nid(n.name)}["${n.name}"]`); + + for (const node of view.nodes) { + out.push( + node.kind === 'provider' ? ` ${nid(node.name)}(["${node.name}"])` : ` ${nid(node.name)}["${node.name}"]`, + ); } - for (const n of view.nodes) for (const need of n.needs) if (known.has(need)) out.push(` ${nid(need)} --> ${nid(n.name)}`); - for (const r of view.routes) { - out.push(` ${rid(r.pattern)}{{"${r.method} ${r.pattern}"}}`); - for (const c of r.chain) if (known.has(c)) out.push(` ${nid(c)} --> ${rid(r.pattern)}`); + + for (const node of view.nodes) + for (const need of node.needs) if (known.has(need)) out.push(` ${nid(need)} --> ${nid(node.name)}`); + + for (const route of view.routes) { + out.push(` ${rid(route.pattern)}{{"${route.method} ${route.pattern}"}}`); + for (const link of route.chain) if (known.has(link)) out.push(` ${nid(link)} --> ${rid(route.pattern)}`); } + return out.join('\n'); } +/** Renders the graph view as Graphviz DOT source. */ export function toDOT(view: GraphView): string { - const known = new Set(view.nodes.map((n) => n.name)); + const known = new Set(view.nodes.map((node) => node.name)); const out: string[] = ['digraph green_tea {', ' rankdir=LR;']; - for (const n of view.nodes) { - out.push(` "${n.name}" [shape=${n.kind === 'provider' ? 'ellipse' : 'box'}];`); + + for (const node of view.nodes) { + out.push(` "${node.name}" [shape=${node.kind === 'provider' ? 'ellipse' : 'box'}];`); } - for (const n of view.nodes) for (const need of n.needs) if (known.has(need)) out.push(` "${need}" -> "${n.name}";`); - for (const r of view.routes) { - const label = `${r.method} ${r.pattern}`; + + for (const node of view.nodes) + for (const need of node.needs) if (known.has(need)) out.push(` "${need}" -> "${node.name}";`); + + for (const route of view.routes) { + const label = `${route.method} ${route.pattern}`; out.push(` "${label}" [shape=hexagon];`); - for (const c of r.chain) if (known.has(c)) out.push(` "${c}" -> "${label}";`); + for (const link of route.chain) if (known.has(link)) out.push(` "${link}" -> "${label}";`); } + out.push('}'); return out.join('\n'); } +/** Wraps Mermaid source in a self-contained HTML page that renders it in the browser. */ export function graphHtml(mermaid: string): string { return [ 'green-tea graph', '', - '
', mermaid, '
', + '
',
+    mermaid,
+    '
', '', ].join('\n'); } diff --git a/src/graph.ts b/src/graph.ts index 1e992d1..b576dfd 100644 --- a/src/graph.ts +++ b/src/graph.ts @@ -1,21 +1,40 @@ function levenshtein(a: string, b: string): number { - const m = a.length, n = b.length; - const d: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); - for (let i = 0; i <= m; i++) d[i][0] = i; - for (let j = 0; j <= n; j++) d[0][j] = j; - for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) { - d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); - } - return d[m][n]; + const aLen = a.length, + bLen = b.length; + const matrix: number[][] = Array.from({ length: aLen + 1 }, () => Array(bLen + 1).fill(0)); + for (let i = 0; i <= aLen; i++) matrix[i][0] = i; + for (let j = 0; j <= bLen; j++) matrix[0][j] = j; + + for (let i = 1; i <= aLen; i++) + for (let j = 1; j <= bLen; j++) { + matrix[i][j] = Math.min( + matrix[i - 1][j] + 1, + matrix[i][j - 1] + 1, + matrix[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1), + ); + } + + return matrix[aLen][bLen]; } +/** Returns the candidate within edit distance 2 of `token`, for "did you mean?" hints. */ export function nearest(token: string, candidates: Iterable): string | undefined { let best: string | undefined; - let bestD = 3; // only suggest edit distance <= 2 - for (const c of candidates) { const dist = levenshtein(token, c); if (dist < bestD) { bestD = dist; best = c; } } + let bestDistance = 3; // only suggest edit distance <= 2 + + for (const candidate of candidates) { + const distance = levenshtein(token, candidate); + + if (distance < bestDistance) { + bestDistance = distance; + best = candidate; + } + } + return best; } +/** A node in the dependency graph: what it provides, what it needs, and where it came from. */ export interface GraphNode { name: string; needs: string[]; @@ -23,15 +42,16 @@ export interface GraphNode { origin: string; } +/** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { const producedBy = new Map(); - for (const n of nodes) for (const key of n.provides) producedBy.set(key, n); + for (const node of nodes) for (const key of node.provides) producedBy.set(key, node); // validate dependencies exist - for (const n of nodes) { - for (const key of n.needs) { + for (const node of nodes) { + for (const key of node.needs) { if (!seedKeys.includes(key) && !producedBy.has(key)) { - throw new Error(`missing dependency: ${key} needed by ${n.name}`); + throw new Error(`missing dependency: ${key} needed by ${node.name}`); } } } @@ -39,28 +59,32 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { const ordered: GraphNode[] = []; const state = new Map(); - const visit = (n: GraphNode, trail: string[]): void => { - const s = state.get(n); - if (s === 'done') return; - if (s === 'visiting') throw new Error(`cycle detected: ${[...trail, n.name].join(' -> ')}`); - state.set(n, 'visiting'); - for (const key of n.needs) { - const dep = producedBy.get(key); - if (dep && dep !== n) visit(dep, [...trail, n.name]); + const visit = (node: GraphNode, trail: string[]): void => { + const visitState = state.get(node); + if (visitState === 'done') return; + if (visitState === 'visiting') throw new Error(`cycle detected: ${[...trail, node.name].join(' -> ')}`); + state.set(node, 'visiting'); + + for (const key of node.needs) { + const dependency = producedBy.get(key); + if (dependency && dependency !== node) visit(dependency, [...trail, node.name]); } - state.set(n, 'done'); - ordered.push(n); + + state.set(node, 'done'); + ordered.push(node); }; - for (const n of nodes) visit(n, []); + for (const node of nodes) visit(node, []); return ordered; } +/** Filters `ordered` down to the transitive closure of producers reachable from `needs`. */ export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] { const producedBy = new Map(); - for (const n of ordered) for (const k of n.provides) producedBy.set(k, n); + for (const node of ordered) for (const key of node.provides) producedBy.set(key, node); const inClosure = new Set(); const work = [...needs]; + while (work.length) { const token = work.pop() as string; const node = producedBy.get(token); @@ -68,5 +92,6 @@ export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] inClosure.add(node); work.push(...node.needs); } - return ordered.filter((n) => inClosure.has(n)); + + return ordered.filter((node) => inClosure.has(node)); } diff --git a/src/http.ts b/src/http.ts deleted file mode 100644 index 4b28355..0000000 --- a/src/http.ts +++ /dev/null @@ -1,316 +0,0 @@ -import http from 'http'; -import https from 'https'; -import { once } from 'events'; -import { channel } from './channel'; -import { errorToResponse } from './transformers'; -import { HttpError, isHttpError } from './signals'; -import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders'; -import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline'; -import type { Transport } from './metadata'; -import type { Bus } from './bus'; -import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from './security'; -import type { TlsOptions, SecurityOptions, CorsOptions } from './security'; -import { parseMultipart, extractBoundary, collapseDuplicates } from './multipart'; - -export interface RequestLimits { - maxBodyBytes?: number; // default 1_000_000 - requestTimeoutMs?: number; // default 30_000 - headersTimeoutMs?: number; // default 10_000 - keepAliveTimeoutMs?: number; // default 5_000 - maxParts?: number; // default 1000 -} -export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last' } - -export type RouteHandler = (req: { - method: string; url: string; - headers: Record; - params: Record; - query: Record; - body: unknown; - protocol: 'http' | 'https'; - ip: string; -}) => Promise; - -export interface RouteDef { method: string; pattern: string; transport: Transport; handler: RouteHandler; bodyDuplicates?: 'array' | 'last' } -export interface MatchedRoute { params: Record; def: RouteDef } - -export interface WsOpenCtx { - params: Record; - inbound: AsyncIterable; - abort: AbortSignal; - req: http.IncomingMessage; -} -export interface WsRouteDef { pattern: string; open: (ctx: WsOpenCtx) => Promise> } - -export interface MeshControl { path: string; handle(ws: any, req: http.IncomingMessage): void } - -const PING_MS = 15_000; - -export function matchPattern(pattern: string, path: string): Record | undefined { - const segs = path.split('/').filter(Boolean); - const pat = pattern.split('/').filter(Boolean); - if (pat.length !== segs.length) return undefined; - const params: Record = {}; - for (let i = 0; i < pat.length; i++) { - if (pat[i].startsWith(':')) params[pat[i].slice(1)] = decodeURIComponent(segs[i]); - else if (pat[i] !== segs[i]) return undefined; - } - return params; -} - -export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined { - for (const r of routes) { - if (r.method !== method) continue; - const params = matchPattern(r.pattern, path); - if (params) return { params, def: r }; - } - return undefined; -} - -export function parseQuery(url: string): Record { - const qs = url.split('?')[1] ?? ''; - const out: Record = {}; - for (const [k, v] of new URLSearchParams(qs)) out[k] = v; - return out; -} - -async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise { - const chunks: Buffer[] = []; - let total = 0; - for await (const chunk of req) { - total += (chunk as Buffer).length; - if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large'); - chunks.push(chunk as Buffer); - } - return chunks.length === 0 ? undefined : Buffer.concat(chunks); -} - -function firstToken(v: string | string[] | undefined): string | undefined { - const s = Array.isArray(v) ? v[0] : v; - return s?.split(',')[0].trim(); -} -function deriveSecure(req: http.IncomingMessage, trustProxy: boolean): boolean { - if (trustProxy) { const p = firstToken(req.headers['x-forwarded-proto']); if (p) return p === 'https'; } - return (req.socket as any).encrypted === true; -} -function deriveIp(req: http.IncomingMessage, trustProxy: boolean): string { - if (trustProxy) { const f = firstToken(req.headers['x-forwarded-for']); if (f) return f; } - return req.socket.remoteAddress ?? ''; -} - -function pickEncoder(transport: Transport, accept: string): StreamEncoder { - if (transport === 'sse') return sseEncoder; - if (transport === 'ndjson') return ndjsonEncoder; - return accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder; -} - -async function pipeStream( - res: http.ServerResponse, stream: AsyncIterable, encoder: StreamEncoder, - bus?: Bus, name = '', streams?: Set<() => void>, -): Promise { - res.writeHead(200, encoder.headers); - res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers - bus?.emit('stream:open', { name }); - const it = stream[Symbol.asyncIterator](); - let ping: ReturnType | undefined; - if (encoder.ping) { ping = setInterval(() => res.write(encoder.ping!()), PING_MS); ping.unref?.(); } - const stop = () => { if (ping) clearInterval(ping); void Promise.resolve(it.return?.()).catch(() => {}); }; - res.on('close', stop); - const closer = () => { try { res.destroy(); } catch { /* */ } }; - streams?.add(closer); - const onClose = once(res, 'close'); - try { - while (true) { - const { value, done } = await it.next(); - if (done) break; - if (!res.write(encoder.encode(value))) { - await Promise.race([once(res, 'drain'), onClose]); - if (res.destroyed) break; // let finally clean up - } - } - } catch (err) { - bus?.emit('stream:error', { name, error: err }); - const frame = encoder.encodeError(err); - if (frame && !res.writableEnded) res.write(frame); - } finally { - if (ping) clearInterval(ping); - streams?.delete(closer); - if (!res.writableEnded && !res.destroyed) res.end(); - bus?.emit('stream:close', { name }); - } -} - -function loadWss(): any | null { - try { return require('ws').WebSocketServer; } catch { return null; } -} - -function attachWs( - server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshControl?: MeshControl, streams?: Set<() => void>, -): void { - if (wsRoutes.length === 0 && !meshControl) return; - const WSS = loadWss(); - const wss = WSS ? new WSS({ noServer: true }) : null; - server.on('upgrade', (req, socket, head) => { - const path = (req.url ?? '/').split('?')[0]; - if (meshControl && path === meshControl.path) { - if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; } - wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(ws, req)); - return; - } - const route = wsRoutes.map((r) => ({ r, params: matchPattern(r.pattern, path) })).find((x) => x.params); - if (!route) { socket.destroy(); return; } - if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; } - wss.handleUpgrade(req, socket, head, async (ws: any) => { - const closer = () => { try { (ws.terminate ?? ws.close).call(ws); } catch { /* */ } }; - streams?.add(closer); - ws.on('close', () => streams?.delete(closer)); - const inbound = channel(); - const ac = new AbortController(); - ws.on('message', (d: Buffer) => inbound.push(d.toString())); - ws.on('close', () => { inbound.close(); ac.abort(); }); - ws.on('error', (e: unknown) => inbound.fail(e)); - - const name = route.r.pattern; - let it: AsyncIterator | undefined; - ws.on('close', () => { void Promise.resolve(it?.return?.()).catch(() => {}); }); // force-cancel outbound - bus?.emit('stream:open', { name }); - try { - const out = await route.r.open({ params: route.params!, inbound, abort: ac.signal, req }); - it = out[Symbol.asyncIterator](); - while (true) { - const { value, done } = await it.next(); - if (done) break; - if (ws.readyState !== 1) break; // 1 = OPEN; stop if socket gone - ws.send(typeof value === 'string' ? value : JSON.stringify(value)); - } - try { ws.close(); } catch { /* already closed */ } - } catch (err) { - bus?.emit('stream:error', { name, error: err }); - if (isHttpError(err)) { - const reason = Buffer.from(String(err.message)).subarray(0, 120).toString(); - try { ws.close(4000 + err.status, reason); } catch { /* already closed */ } - } else { - try { ws.close(1011); } catch { /* already closed */ } - } - } finally { - ac.abort(); - bus?.emit('stream:close', { name }); - } - }); - }); -} - -export function createHttpServer( - routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, opts?: HttpOptions, -): http.Server { - const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000; - const trustProxy = opts?.trustProxy ?? false; - const handler = async (req: http.IncomingMessage, res: http.ServerResponse): Promise => { - const url = req.url ?? '/'; - const path = url.split('?')[0]; - // Install the security-header patch BEFORE any routing/response so every path - // (200, 404, error, stream) writes headers through the same patched writeHead. - const secure = deriveSecure(req, trustProxy); - const injected: Record = { ...buildSecurityHeaders(opts?.security ?? true, secure) }; - const orig = res.writeHead.bind(res); - (res as any).writeHead = (status: number, arg2?: any, arg3?: any) => { - // normalize (statusMessage?, headers?) overloads - const hdrs = (typeof arg2 === 'string' ? arg3 : arg2) as Record | undefined; - // injected (security/CORS) is authoritative. Node's writeHead does NOT dedupe case-variant - // keys — both lines would ship and a browser honors the first — so drop any handler header - // whose name case-insensitively collides with an injected one before merging. - const merged: Record = {}; - const injectedLower = new Set(Object.keys(injected).map((k) => k.toLowerCase())); - let handlerVary: string | undefined; - if (hdrs) for (const k of Object.keys(hdrs)) { - const lk = k.toLowerCase(); - if (lk === 'vary') { handlerVary = hdrs[k]; continue; } // merged separately below - if (!injectedLower.has(lk)) merged[k] = hdrs[k]; - } - Object.assign(merged, injected); - if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']); - else if (handlerVary !== undefined) merged['vary'] = handlerVary; // preserve handler Vary when no CORS - return typeof arg2 === 'string' ? orig(status, arg2, merged) : orig(status, merged); - }; - // CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily - // by reference at writeHead time, so keys added here still land on every response. - if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); - if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { - const pf = corsPreflightHeaders(opts.cors, req); - res.writeHead(204, pf); - res.end(); - return; - } - const matched = matchRoute(routes, req.method ?? 'GET', path); - if (!matched) { - res.writeHead(404, { 'content-type': 'application/json' }); - res.end(JSON.stringify({ error: 'Not Found' })); - return; - } - let buf: Buffer | undefined; - try { - buf = await readBody(req, maxBody); - } catch (error) { - const r = errorToResponse(error); - res.writeHead(r.status, { ...r.headers, connection: 'close' }); - res.end(r.body); - return; - } - let body: unknown; - const ct = String(req.headers['content-type'] ?? ''); - const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last'; - if (buf !== undefined && ct.includes('application/json')) { - try { body = JSON.parse(buf.toString('utf8')); } - catch { - res.writeHead(400, { 'content-type': 'application/json' }); - res.end(JSON.stringify({ error: 'Invalid JSON body' })); - return; - } - } else if (buf !== undefined && ct.includes('application/x-www-form-urlencoded')) { - body = collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates); - } else if (buf !== undefined && ct.includes('multipart/form-data')) { - const boundary = extractBoundary(ct); - if (!boundary) { - res.writeHead(400, { 'content-type': 'application/json' }); - res.end(JSON.stringify({ error: 'Invalid multipart body' })); - return; - } - try { body = parseMultipart(buf, boundary, { maxParts: opts?.limits?.maxParts ?? 1000, duplicates }); } - catch { - res.writeHead(400, { 'content-type': 'application/json' }); - res.end(JSON.stringify({ error: 'Invalid multipart body' })); - return; - } - } else { - const s = buf?.toString('utf8'); - body = s === '' ? undefined : s; - } - let result: PipelineResult; - try { - result = await matched.def.handler({ - method: req.method ?? 'GET', url, headers: req.headers, - params: matched.params, query: parseQuery(url), body, - protocol: secure ? 'https' : 'http', ip: deriveIp(req, trustProxy), - }); - } catch (error) { - result = errorToResponse(error); - } - if (isStreamResult(result)) { - const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? '')); - await pipeStream(res, result.stream, encoder, bus, matched.def.pattern, opts?.streams); - return; - } - const r: ResponseShape = result; - res.writeHead(r.status, r.headers); - res.end(r.body); - }; - // runtime-compatible; only @types differ (https.Server lacks the http-only timeout props) - const server: http.Server = (opts?.tls - ? https.createServer(opts.tls as https.ServerOptions, handler) - : http.createServer(handler)) as unknown as http.Server; - server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; - server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; - server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; - attachWs(server, wsRoutes, bus, meshControl, opts?.streams); - return server; -} diff --git a/src/http/index.ts b/src/http/index.ts new file mode 100644 index 0000000..afea4d6 --- /dev/null +++ b/src/http/index.ts @@ -0,0 +1,14 @@ +// Public surface of the HTTP module. Internal helpers (request parsing, streaming, +// ws upgrade) live in sibling files and are composed by ./server. +export type { + RequestLimits, + HttpOptions, + RouteHandler, + RouteDef, + MatchedRoute, + WsOpenCtx, + WsRouteDef, + MeshControl, +} from './types'; +export { matchPattern, matchRoute, parseQuery } from './router'; +export { createHttpServer } from './server'; diff --git a/src/http/request.ts b/src/http/request.ts new file mode 100644 index 0000000..2eef0cd --- /dev/null +++ b/src/http/request.ts @@ -0,0 +1,42 @@ +import http from 'http'; +import { HttpError } from '../signals'; + +/** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */ +export async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise { + const chunks: Buffer[] = []; + let total = 0; + + for await (const chunk of req) { + total += (chunk as Buffer).length; + if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large'); + chunks.push(chunk as Buffer); + } + + return chunks.length === 0 ? undefined : Buffer.concat(chunks); +} + +/** Returns the first comma-separated token of a header value (handles array-valued headers). */ +function firstToken(value: string | string[] | undefined): string | undefined { + const first = Array.isArray(value) ? value[0] : value; + return first?.split(',')[0].trim(); +} + +/** Determines whether the request arrived over HTTPS, honoring `x-forwarded-proto` when proxy is trusted. */ +export function deriveSecure(req: http.IncomingMessage, trustProxy: boolean): boolean { + if (trustProxy) { + const proto = firstToken(req.headers['x-forwarded-proto']); + if (proto) return proto === 'https'; + } + + return (req.socket as any).encrypted === true; +} + +/** Resolves the client IP, honoring `x-forwarded-for` when proxy is trusted. */ +export function deriveIp(req: http.IncomingMessage, trustProxy: boolean): string { + if (trustProxy) { + const forwarded = firstToken(req.headers['x-forwarded-for']); + if (forwarded) return forwarded; + } + + return req.socket.remoteAddress ?? ''; +} diff --git a/src/http/router.ts b/src/http/router.ts new file mode 100644 index 0000000..6b7aedf --- /dev/null +++ b/src/http/router.ts @@ -0,0 +1,92 @@ +import type { RouteDef, MatchedRoute } from './types'; + +/** + * Matches a route pattern against a request path. Supports static segments, `:param` (one segment), + * and a trailing `:name*` catch-all that captures the rest of the path (slashes included) into `params.name`. + * @returns Extracted params (decoded) when the path matches, otherwise undefined. + */ +export function matchPattern(pattern: string, path: string): Record | undefined { + const pathSegs = path.split('/').filter(Boolean); + const patternSegs = pattern.split('/').filter(Boolean); + const params: Record = {}; + + for (let i = 0; i < patternSegs.length; i++) { + const seg = patternSegs[i]; + + // Trailing catch-all: capture every remaining segment (possibly none) as one decoded value. + if (seg.startsWith(':') && seg.endsWith('*')) { + params[seg.slice(1, -1)] = pathSegs.slice(i).map(decodeURIComponent).join('/'); + return params; + } + + if (i >= pathSegs.length) return undefined; // pattern longer than path + + if (seg.startsWith(':')) params[seg.slice(1)] = decodeURIComponent(pathSegs[i]); + else if (seg !== pathSegs[i]) return undefined; + } + + // No catch-all consumed the tail, so the lengths must match exactly. + return patternSegs.length === pathSegs.length ? params : undefined; +} + +/** Splits a pattern into its fixed-prefix segment kinds (2 = static, 1 = param) and whether it ends in a catch-all. */ +function segScores(pattern: string): { catchAll: boolean; kinds: number[] } { + const kinds: number[] = []; + + for (const seg of pattern.split('/').filter(Boolean)) { + if (seg.startsWith(':') && seg.endsWith('*')) return { catchAll: true, kinds }; + kinds.push(seg.startsWith(':') ? 1 : 2); + } + + return { catchAll: false, kinds }; +} + +/** Orders two matching patterns by specificity: exact beats catch-all, then static beats param, then longer wins. */ +function moreSpecific(a: string, b: string): number { + const scoreA = segScores(a); + const scoreB = segScores(b); + if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1; + const length = Math.max(scoreA.kinds.length, scoreB.kinds.length); + + for (let i = 0; i < length; i++) { + const kindA = scoreA.kinds[i] ?? -1; + const kindB = scoreB.kinds[i] ?? -1; + if (kindA !== kindB) return kindA - kindB; + } + + return 0; +} + +/** Finds the most specific route matching both method and path (static > param > catch-all; ties keep registration order). */ +export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined { + let best: MatchedRoute | undefined; + let bestPattern = ''; + + for (const route of routes) { + if (route.method !== method) continue; + const params = matchPattern(route.pattern, path); + if (!params) continue; + + if (!best || moreSpecific(route.pattern, bestPattern) > 0) { + best = { params, def: route }; + bestPattern = route.pattern; + } + } + + return best; +} + +/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */ +export function allowedMethods(routes: RouteDef[], path: string): string[] { + const methods = new Set(); + for (const route of routes) if (matchPattern(route.pattern, path)) methods.add(route.method); + return [...methods]; +} + +/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */ +export function parseQuery(url: string): Record { + const queryString = url.split('?')[1] ?? ''; + const out: Record = {}; + for (const [key, value] of new URLSearchParams(queryString)) out[key] = value; + return out; +} diff --git a/src/http/server.ts b/src/http/server.ts new file mode 100644 index 0000000..eb3a327 --- /dev/null +++ b/src/http/server.ts @@ -0,0 +1,242 @@ +import http from 'http'; +import https from 'https'; +import { errorToResponse } from '../transformers'; +import { isHttpError } from '../signals'; +import { isStreamResult, type PipelineResult, type ResponseShape } from '../pipeline'; +import type { Bus } from '../bus'; +import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from '../security'; +import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart'; +import { matchRoute, allowedMethods, parseQuery } from './router'; +import { readBody, deriveSecure, deriveIp } from './request'; +import { pickEncoder, pipeStream } from './stream'; +import { attachWs } from './ws'; +import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types'; + +interface HandlerConfig { + routes: RouteDef[]; + bus?: Bus; + opts?: HttpOptions; + maxBody: number; + trustProxy: boolean; +} + +/** A ready-to-send error response produced while acquiring the request body. */ +type BodyFailure = { fail: { status: number; headers: Record; body: string } }; + +/** + * Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades. + * @param routes HTTP route definitions. + * @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency). + * @param bus Optional event bus for stream lifecycle events. + * @param meshControl Optional mesh gateway hook for a reserved upgrade path. + * @param opts Limits, TLS, security, CORS, and body-parsing options. + */ +export function createHttpServer( + routes: RouteDef[], + wsRoutes: WsRouteDef[] = [], + bus?: Bus, + meshControl?: MeshControl, + opts?: HttpOptions, +): http.Server { + const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000; + const trustProxy = opts?.trustProxy ?? false; + const handler = createRequestHandler({ routes, bus, opts, maxBody, trustProxy }); + + // runtime-compatible; only @types differ (https.Server lacks the http-only timeout props) + const server: http.Server = (opts?.tls + ? https.createServer(opts.tls as https.ServerOptions, handler) + : http.createServer(handler)) as unknown as http.Server; + server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; + server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; + server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; + attachWs(server, wsRoutes, bus, meshControl, opts?.streams); + return server; +} + +/** Builds the request listener: security/CORS headers, routing, body parsing, then buffered or streamed response. */ +function createRequestHandler(cfg: HandlerConfig) { + const { routes, bus, opts, maxBody, trustProxy } = cfg; + + return async (req: http.IncomingMessage, res: http.ServerResponse): Promise => { + const url = req.url ?? '/'; + const path = url.split('?')[0]; + // Install the security-header patch BEFORE any routing/response so every path + // (200, 404, error, stream) writes headers through the same patched writeHead. + const secure = deriveSecure(req, trustProxy); + const injected: Record = { ...buildSecurityHeaders(opts?.security ?? true, secure) }; + patchResponseHeaders(res, injected); + + // CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily + // by reference at writeHead time, so keys added here still land on every response. + if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); + + if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { + res.writeHead(204, corsPreflightHeaders(opts.cors, req)); + res.end(); + return; + } + + const matched = matchRoute(routes, req.method ?? 'GET', path); + + if (!matched) { + // Path matches a route under a different method → 405 with Allow; otherwise 404. + 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' })); + return; + } + + res.writeHead(404, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: 'Not Found' })); + return; + } + + const acquired = await acquireBody(req, matched, opts, maxBody); + + if ('fail' in acquired) { + res.writeHead(acquired.fail.status, acquired.fail.headers); + res.end(acquired.fail.body); + return; + } + + let result: PipelineResult; + + try { + result = await matched.def.handler({ + method: req.method ?? 'GET', + url, + headers: req.headers, + params: matched.params, + query: parseQuery(url), + body: acquired.body, + protocol: secure ? 'https' : 'http', + ip: deriveIp(req, trustProxy), + }); + } catch (error) { + result = errorToResponse(error); + } + + if (isStreamResult(result)) { + const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? '')); + await pipeStream(res, result.stream, encoder, bus, matched.def.pattern, opts?.streams); + return; + } + + const response: ResponseShape = result; + res.writeHead(response.status, response.headers); + res.end(response.body); + }; +} + +/** Reads and parses the request body, returning `{ body }` or a ready-to-send `{ fail }` error response. */ +async function acquireBody( + req: http.IncomingMessage, + matched: MatchedRoute, + opts: HttpOptions | undefined, + maxBody: number, +): Promise<{ body: unknown } | BodyFailure> { + let buf: Buffer | undefined; + + try { + buf = await readBody(req, maxBody); + } catch (error) { + const response = errorToResponse(error); + return { + fail: { status: response.status, headers: { ...response.headers, connection: 'close' }, body: response.body }, + }; + } + + 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); + + if ('error' in parsed) { + return { + fail: { + status: parsed.status ?? 400, + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ error: parsed.error }), + }, + }; + } + + return { body: parsed.body }; +} + +/** + * Monkey-patches `res.writeHead` so injected (security/CORS) headers are authoritative on every response. + * Handler headers that case-insensitively collide with an injected key are dropped; `Vary` is merged. + * Reads `injected` by reference, so CORS keys added after installation still land. + */ +function patchResponseHeaders(res: http.ServerResponse, injected: Record): void { + const origWriteHead = res.writeHead.bind(res); + + (res as any).writeHead = (status: number, arg2?: any, arg3?: any) => { + // normalize (statusMessage?, headers?) overloads + const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record | undefined; + const merged: Record = {}; + const injectedLower = new Set(Object.keys(injected).map((key) => key.toLowerCase())); + let handlerVary: string | undefined; + + if (handlerHeaders) + for (const key of Object.keys(handlerHeaders)) { + const lowerKey = key.toLowerCase(); + + if (lowerKey === 'vary') { + handlerVary = handlerHeaders[key]; + continue; + } // merged separately below + + if (!injectedLower.has(lowerKey)) merged[key] = handlerHeaders[key]; + } + + Object.assign(merged, injected); + if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']); + else if (handlerVary !== undefined) merged['vary'] = handlerVary; // preserve handler Vary when no CORS + return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged); + }; +} + +/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */ +type ParseResult = { body: unknown } | { error: string; status?: number }; + +/** + * Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text). + * @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support. + */ +async function parseRequestBody( + buf: Buffer | undefined, + contentType: string, + duplicates: 'array' | 'last', + maxParts: number, +): Promise { + if (buf !== undefined && contentType.includes('application/json')) { + try { + return { body: JSON.parse(buf.toString('utf8')) }; + } catch { + return { error: 'Invalid JSON body' }; + } + } + + if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) { + return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) }; + } + + if (buf !== undefined && contentType.includes('multipart/form-data')) { + const boundary = extractBoundary(contentType); + if (!boundary) return { error: 'Invalid multipart body' }; + + try { + return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) }; + } catch (error) { + // HttpError = the busboy peer dep is missing (501); anything else = malformed input (400). + if (isHttpError(error)) return { error: error.message, status: error.status }; + return { error: 'Invalid multipart body' }; + } + } + + const text = buf?.toString('utf8'); + return { body: text === '' ? undefined : text }; +} diff --git a/src/http/stream.ts b/src/http/stream.ts new file mode 100644 index 0000000..1239459 --- /dev/null +++ b/src/http/stream.ts @@ -0,0 +1,74 @@ +import http from 'http'; +import { once } from 'events'; +import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders'; +import type { Transport } from '../metadata'; +import type { Bus } from '../bus'; + +const PING_MS = 15_000; + +/** Selects the stream encoder for a transport, falling back to the client's `Accept` header for `stream`. */ +export function pickEncoder(transport: Transport, accept: string): StreamEncoder { + if (transport === 'sse') return sseEncoder; + if (transport === 'ndjson') return ndjsonEncoder; + return accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder; +} + +/** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */ +export async function pipeStream( + res: http.ServerResponse, + stream: AsyncIterable, + encoder: StreamEncoder, + bus?: Bus, + name = '', + streams?: Set<() => void>, +): Promise { + res.writeHead(200, encoder.headers); + res.flushHeaders(); // establish the stream immediately so idle-until-event sources (e.g. subscriptions) don't deadlock clients awaiting headers + bus?.emit('stream:open', { name }); + const iterator = stream[Symbol.asyncIterator](); + let ping: ReturnType | undefined; + + if (encoder.ping) { + ping = setInterval(() => res.write(encoder.ping!()), PING_MS); + ping.unref?.(); + } + + const stop = () => { + if (ping) clearInterval(ping); + void Promise.resolve(iterator.return?.()).catch(() => {}); + }; + + res.on('close', stop); + + const closer = () => { + try { + res.destroy(); + } catch { + /* */ + } + }; + + streams?.add(closer); + const onClose = once(res, 'close'); + + try { + while (true) { + const { value, done } = await iterator.next(); + if (done) break; + + if (!res.write(encoder.encode(value))) { + await Promise.race([once(res, 'drain'), onClose]); + if (res.destroyed) break; // let finally clean up + } + } + } catch (err) { + bus?.emit('stream:error', { name, error: err }); + const frame = encoder.encodeError(err); + if (frame && !res.writableEnded) res.write(frame); + } finally { + if (ping) clearInterval(ping); + streams?.delete(closer); + if (!res.writableEnded && !res.destroyed) res.end(); + bus?.emit('stream:close', { name }); + } +} diff --git a/src/http/types.ts b/src/http/types.ts new file mode 100644 index 0000000..2afa1a0 --- /dev/null +++ b/src/http/types.ts @@ -0,0 +1,71 @@ +import http from 'http'; +import type { Transport } from '../metadata'; +import type { PipelineResult } from '../pipeline'; +import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; + +/** Per-request size and timeout ceilings applied by the server. */ +export interface RequestLimits { + maxBodyBytes?: number; // default 1_000_000 + requestTimeoutMs?: number; // default 30_000 + headersTimeoutMs?: number; // default 10_000 + keepAliveTimeoutMs?: number; // default 5_000 + maxParts?: number; // default 1000 +} + +/** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */ +export interface HttpOptions { + limits?: RequestLimits; + streams?: Set<() => void>; + tls?: TlsOptions; + trustProxy?: boolean; + security?: boolean | SecurityOptions; + cors?: CorsOptions; + bodyDuplicates?: 'array' | 'last'; +} + +/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */ +export type RouteHandler = (req: { + method: string; + url: string; + headers: Record; + params: Record; + query: Record; + body: unknown; + protocol: 'http' | 'https'; + ip: string; +}) => Promise; + +/** A registered HTTP route: method, path pattern, streaming transport, and handler. */ +export interface RouteDef { + method: string; + pattern: string; + transport: Transport; + handler: RouteHandler; + bodyDuplicates?: 'array' | 'last'; +} + +/** Result of matching a request path against a route: extracted params plus the matched definition. */ +export interface MatchedRoute { + params: Record; + def: RouteDef; +} + +/** Context passed to a WebSocket route's `open`: path params, inbound message stream, abort signal, and raw request. */ +export interface WsOpenCtx { + params: Record; + inbound: AsyncIterable; + abort: AbortSignal; + req: http.IncomingMessage; +} + +/** A registered WebSocket route: path pattern and an `open` that returns the outbound message stream. */ +export interface WsRouteDef { + pattern: string; + open: (ctx: WsOpenCtx) => Promise>; +} + +/** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */ +export interface MeshControl { + path: string; + handle(ws: any, req: http.IncomingMessage): void; +} diff --git a/src/http/ws.ts b/src/http/ws.ts new file mode 100644 index 0000000..a2736fe --- /dev/null +++ b/src/http/ws.ts @@ -0,0 +1,180 @@ +import http from 'http'; +import { channel } from '../channel'; +import { isHttpError } from '../signals'; +import type { Bus } from '../bus'; +import { matchPattern } from './router'; +import type { WsRouteDef, MeshControl } from './types'; + +/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */ +function loadWss(): any | null { + try { + // `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket + // support don't fail. When absent this throws and we fall back to null (501 on upgrade). + // eslint-disable-next-line @typescript-eslint/no-require-imports + return require('ws').WebSocketServer; + } catch { + return null; + } +} + +/** Writes a 501 Not Implemented status to the raw socket and destroys it. */ +function reject501(socket: any): void { + socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); + socket.destroy(); +} + +/** Handles the mesh-control upgrade path; returns true when the request was for the mesh control endpoint. */ +function handleMeshUpgrade( + wss: any, + meshControl: MeshControl, + path: string, + req: http.IncomingMessage, + socket: any, + head: Buffer, +): boolean { + if (path !== meshControl.path) return false; + + if (!wss) { + reject501(socket); + return true; + } + + wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(ws, req)); + return true; +} + +/** Finds the first ws route whose pattern matches `path`, capturing its params. */ +function matchWsRoute( + wsRoutes: WsRouteDef[], + path: string, +): { def: WsRouteDef; params: Record | undefined } | undefined { + return wsRoutes + .map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) })) + .find((entry) => entry.params); +} + +/** Wires inbound message/close/error events into a channel and returns the channel plus its abort controller. */ +function wireInbound(ws: any): { inbound: ReturnType>; abortController: AbortController } { + const inbound = channel(); + const abortController = new AbortController(); + ws.on('message', (data: Buffer) => inbound.push(data.toString())); + ws.on('close', () => { + inbound.close(); + abortController.abort(); + }); + ws.on('error', (err: unknown) => inbound.fail(err)); + + return { inbound, abortController }; +} + +/** Registers the connection with the stream registry so it can be force-closed on shutdown. */ +function trackConnection(ws: any, streams?: Set<() => void>): void { + const closer = () => { + try { + (ws.terminate ?? ws.close).call(ws); + } catch { + /* */ + } + }; + + streams?.add(closer); + ws.on('close', () => streams?.delete(closer)); +} + +/** Drives the outbound async iterator, sending each yielded value over the socket until done or closed. */ +async function pumpOutbound(ws: any, iterator: AsyncIterator): Promise { + while (true) { + const { value, done } = await iterator.next(); + if (done) break; + if (ws.readyState !== 1) break; // 1 = OPEN; stop if socket gone + ws.send(typeof value === 'string' ? value : JSON.stringify(value)); + } + + try { + ws.close(); + } catch { + /* already closed */ + } +} + +/** Closes the socket with the appropriate code after an outbound error (4000+status for HTTP errors, 1011 otherwise). */ +function closeOnError(ws: any, err: unknown): void { + if (isHttpError(err)) { + const reason = Buffer.from(String(err.message)).subarray(0, 120).toString(); + + try { + ws.close(4000 + err.status, reason); + } catch { + /* already closed */ + } + } else { + try { + ws.close(1011); + } catch { + /* already closed */ + } + } +} + +/** Runs the full per-connection lifecycle: inbound wiring, opening the route stream, and pumping outbound values. */ +async function openWsConnection( + ws: any, + route: { def: WsRouteDef; params: Record | undefined }, + req: http.IncomingMessage, + bus?: Bus, + streams?: Set<() => void>, +): Promise { + trackConnection(ws, streams); + const { inbound, abortController } = wireInbound(ws); + + const name = route.def.pattern; + let iterator: AsyncIterator | undefined; + ws.on('close', () => { + void Promise.resolve(iterator?.return?.()).catch(() => {}); + }); // force-cancel outbound + bus?.emit('stream:open', { name }); + + try { + const outbound = await route.def.open({ params: route.params!, inbound, abort: abortController.signal, req }); + iterator = outbound[Symbol.asyncIterator](); + await pumpOutbound(ws, iterator); + } catch (err) { + bus?.emit('stream:error', { name, error: err }); + closeOnError(ws, err); + } finally { + abortController.abort(); + bus?.emit('stream:close', { name }); + } +} + +/** Attaches WebSocket upgrade handling to the server: routes to `wsRoutes` or a mesh control path. */ +export function attachWs( + server: http.Server, + wsRoutes: WsRouteDef[], + bus?: Bus, + meshControl?: MeshControl, + streams?: Set<() => void>, +): void { + if (wsRoutes.length === 0 && !meshControl) return; + const WebSocketServer = loadWss(); + const wss = WebSocketServer ? new WebSocketServer({ noServer: true }) : null; + server.on('upgrade', (req, socket, head) => { + const path = (req.url ?? '/').split('?')[0]; + + if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head)) return; + + const route = matchWsRoute(wsRoutes, path); + + if (!route) { + socket.destroy(); + return; + } + + if (!wss) { + reject501(socket); + return; + } + + wss.handleUpgrade(req, socket, head, (ws: any) => openWsConnection(ws, route, req, bus, streams)); + }); +} diff --git a/src/index.ts b/src/index.ts index b7e7be5..162f748 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,32 +1,53 @@ +/** + * @green-tea/core — a decorator-driven, type-safe HTTP framework. + * Public API barrel: application bootstrap, routing/DI decorators, streaming, + * request validation, security helpers, and the cross-server mesh. + */ import 'reflect-metadata'; -export const VERSION = '0.0.0'; +/** Package version, replaced at publish time. */ +export const VERSION = '26.07.0-beta.0'; + +// Application export { createApp } from './app'; -export type { App, InspectLine, Explain } from './app'; +export type { App, InspectLine, Explain, MeshConfig } from './app'; + +// Graph visualization export { toMermaid, toDOT } from './graph-viz'; export type { GraphView } from './graph-viz'; -export { Provider, Step, Route, Get, Module, Transformer } from './metadata'; + +// Routing & decorators +export { Provider, Step, Route, Get, Module, Transformer, Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata'; +export type { Transport, HttpMethod } from './metadata'; export type { Plugin } from './plugin'; + +// Transformers & error signals export { JsonTransformer } from './transformers'; export { HttpError, Unauthorized, NotFound, Redirect, NotModified, ValidationError } from './signals'; + +// Bus & flow export { Bus } from './bus'; export { flow, Flow } from './flow'; export type { StepFn, CompiledFlow } from './flow'; -export { needs, ctx, param, query, body, headers } from './params'; + +// Parameter decorators +export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params'; export type { Query, Headers, Context, ArgSpec } from './params'; + +// Streaming export { channel, isAsyncIterable } from './channel'; export type { Channel } from './channel'; export { Rooms } from './rooms'; -export { Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata'; -export type { Transport, HttpMethod } from './metadata'; -export { inbound, abort } from './params'; export { sseEncoder, ndjsonEncoder } from './encoders'; export type { StreamEncoder } from './encoders'; -export type { MeshConfig } from './app'; + +// HTTP, security & validation export type { RequestLimits } from './http'; export type { TlsOptions, CorsOptions, SecurityOptions } from './security'; export type { UploadedFile, MultipartBody } from './multipart'; export type { StandardSchemaV1 } from './standard-schema'; + +// Mesh export { connectLink } from './mesh/link'; export { buildRemote, envelopeFrom } from './mesh/teacup'; export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot'; diff --git a/src/mesh/link.ts b/src/mesh/link.ts index 10105d6..397364a 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -4,30 +4,105 @@ import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from let connSeq = 0; // module-level: deterministic unique connection-id prefix (no Date.now/Math.random) +/** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */ export interface Link { manifest: Manifest; rpc(kind: 'scope' | 'route', name: string, ctx: RequestEnvelope): Promise; close(): void; } +/** An in-flight RPC awaiting its `rpc-res`, keyed by id in the pending map. */ +type PendingEntry = { + resolve: (v: unknown) => void; + reject: (e: unknown) => void; + timer: ReturnType; +}; + function loadWs(): any { - return require('ws'); // lazy/optional, like streams; the ws CJS export is the WebSocket class + // lazy/optional, like streams; the ws CJS export is the WebSocket class + // eslint-disable-next-line @typescript-eslint/no-require-imports + return require('ws'); } -export function connectLink(args: { - url: string; - secret: string; - timeoutMs?: number; - bus?: Bus; -}): Promise { +/** Reject and clear every in-flight RPC — used when the link closes. */ +function rejectAllPending(pending: Map, reason: string): void { + for (const [, entry] of pending) { + clearTimeout(entry.timer); + entry.reject(new Error(reason)); + } + + pending.clear(); +} + +/** Register one RPC in `pending` by id, send its request, and reject it on timeout. */ +function sendRpc( + ws: any, + pending: Map, + id: string, + kind: 'scope' | 'route', + name: string, + ctx: RequestEnvelope, + timeoutMs: number, +): Promise { + return new Promise((resolveCall, rejectCall) => { + const timer = setTimeout(() => { + pending.delete(id); + rejectCall(new Error(`mesh rpc timeout: ${name}`)); + }, timeoutMs); + + pending.set(id, { resolve: resolveCall, reject: rejectCall, timer }); + ws.send(encode({ type: 'rpc-req', id, kind, name, ctx })); + }); +} + +/** Assemble the client-facing Link once the manifest arrives. */ +function buildLink( + ws: any, + pending: Map, + manifest: Manifest, + connId: string, + timeoutMs: number, +): Link { + let counter = 0; + + return { + manifest, + rpc(kind, name, ctx) { + const id = `${connId}:${counter++}`; + + return sendRpc(ws, pending, id, kind, name, ctx, timeoutMs); + }, + close() { + ws.close(); + }, + }; +} + +/** Settle a pending RPC from its `rpc-res` frame — resolve on ok, reject (and emit) on error. */ +function settleRpcResponse( + pending: Map, + frame: Extract, + bus?: Bus, +): void { + const entry = pending.get(frame.id); + if (!entry) return; + pending.delete(frame.id); + clearTimeout(entry.timer); + + if (frame.ok) { + entry.resolve(frame.result); + } else { + bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error }); + entry.reject(new HttpError(frame.error.status ?? 500, frame.error.message)); + } +} + +/** Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest arrives. */ +export function connectLink(args: { url: string; secret: string; timeoutMs?: number; bus?: Bus }): Promise { const timeoutMs = args.timeoutMs ?? 30_000; const WS = loadWs(); const ws = new WS(args.url); - const pending = new Map< - string, - { resolve: (v: unknown) => void; reject: (e: unknown) => void; timer: ReturnType } - >(); - let counter = 0; + const pending = new Map(); const connId = `c${connSeq++}`; let manifest: Manifest | undefined; @@ -38,20 +113,17 @@ export function connectLink(args: { }, timeoutMs); ws.on('open', () => ws.send(encode({ type: 'hello', secret: args.secret }))); - ws.on('error', (e: unknown) => reject(e)); + ws.on('error', (error: unknown) => reject(error)); ws.on('close', () => { clearTimeout(connectTimer); args.bus?.emit('mesh:disconnect', { name: args.url }); - for (const [, p] of pending) { - clearTimeout(p.timer); - p.reject(new Error('mesh link closed')); - } - pending.clear(); + rejectAllPending(pending, 'mesh link closed'); if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`)); }); ws.on('message', (data: unknown) => { let frame: Frame; + try { frame = decode(String(data)); } catch { @@ -62,37 +134,12 @@ export function connectLink(args: { manifest = { scopes: frame.scopes, routes: frame.routes }; clearTimeout(connectTimer); args.bus?.emit('mesh:connect', { name: args.url }); - resolve({ - manifest, - rpc(kind, name, ctx) { - const id = `${connId}:${counter++}`; - return new Promise((res, rej) => { - const timer = setTimeout(() => { - pending.delete(id); - rej(new Error(`mesh rpc timeout: ${name}`)); - }, timeoutMs); - pending.set(id, { resolve: res, reject: rej, timer }); - ws.send(encode({ type: 'rpc-req', id, kind, name, ctx })); - }); - }, - close() { - ws.close(); - }, - }); + resolve(buildLink(ws, pending, manifest, connId, timeoutMs)); return; } if (frame.type === 'rpc-res') { - const p = pending.get(frame.id); - if (!p) return; - pending.delete(frame.id); - clearTimeout(p.timer); - if (frame.ok) { - p.resolve(frame.result); - } else { - args.bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error }); - p.reject(new HttpError(frame.error.status ?? 500, frame.error.message)); - } + settleRpcResponse(pending, frame, args.bus); } }); }); diff --git a/src/mesh/protocol.ts b/src/mesh/protocol.ts index b37d242..e2731b2 100644 --- a/src/mesh/protocol.ts +++ b/src/mesh/protocol.ts @@ -1,3 +1,4 @@ +/** Serialized request context sent across the mesh for a scope or route RPC. */ export interface RequestEnvelope { method: string; params: Record; @@ -6,10 +7,23 @@ export interface RequestEnvelope { headers: Record; } -export interface ScopeEntry { token: string; scope: 'app' | 'request' } -export interface RouteEntry { method: string; pattern: string } -export interface Manifest { scopes: ScopeEntry[]; routes: RouteEntry[] } +/** Manifest entry for an exported scope token and its lifetime. */ +export interface ScopeEntry { + token: string; + scope: 'app' | 'request'; +} +/** Manifest entry for an exported route. */ +export interface RouteEntry { + method: string; + pattern: string; +} +/** A mesh server's advertised scopes and routes. */ +export interface Manifest { + scopes: ScopeEntry[]; + routes: RouteEntry[]; +} +/** Discriminated union of every message on the mesh wire. */ export type Frame = | { type: 'hello'; secret: string } | { type: 'manifest'; scopes: ScopeEntry[]; routes: RouteEntry[] } @@ -19,14 +33,18 @@ export type Frame = const TYPES = new Set(['hello', 'manifest', 'rpc-req', 'rpc-res']); -export function encode(f: Frame): string { - return JSON.stringify(f); +/** Serialize a frame to a JSON wire string. */ +export function encode(frame: Frame): string { + return JSON.stringify(frame); } -export function decode(s: string): Frame { - const f = JSON.parse(s) as { type?: unknown }; - if (typeof f.type !== 'string' || !TYPES.has(f.type)) { - throw new Error(`unknown frame type: ${String(f.type)}`); +/** Parse a wire string into a frame, throwing if the `type` tag is unknown. */ +export function decode(json: string): Frame { + const parsed = JSON.parse(json) as { type?: unknown }; + + if (typeof parsed.type !== 'string' || !TYPES.has(parsed.type)) { + throw new Error(`unknown frame type: ${String(parsed.type)}`); } - return f as Frame; + + return parsed as Frame; } diff --git a/src/mesh/teacup.ts b/src/mesh/teacup.ts index 39fe36c..0e0870e 100644 --- a/src/mesh/teacup.ts +++ b/src/mesh/teacup.ts @@ -2,9 +2,19 @@ import type { Link } from './link'; import type { RequestEnvelope } from './protocol'; import type { ResponseShape } from '../pipeline'; -export interface RemoteScopeNode { name: string; run: (ctx: any) => Promise> } -export interface RemoteRoute { method: string; pattern: string; handler: (req: RequestEnvelope) => Promise } +/** Local proxy for a remote scope: runs the RPC and returns its token→value binding. */ +export interface RemoteScopeNode { + name: string; + run: (ctx: any) => Promise>; +} +/** Local proxy for a remote route: forwards the request envelope over the link. */ +export interface RemoteRoute { + method: string; + pattern: string; + handler: (req: RequestEnvelope) => Promise; +} +/** Extract a {@link RequestEnvelope} from a local request context for transmission over the mesh. */ export function envelopeFrom(ctx: any): RequestEnvelope { return { method: ctx?.req?.method ?? ctx?.method ?? 'GET', @@ -15,21 +25,27 @@ export function envelopeFrom(ctx: any): RequestEnvelope { }; } -export function buildRemote(link: Link, origin: string): { - providers: RemoteScopeNode[]; steps: RemoteScopeNode[]; routes: RemoteRoute[]; +/** Turn a link's manifest into local proxy nodes: app-scope providers, request-scope steps, and routes. */ +export function buildRemote(link: Link): { + providers: RemoteScopeNode[]; + steps: RemoteScopeNode[]; + routes: RemoteRoute[]; } { const providers: RemoteScopeNode[] = []; const steps: RemoteScopeNode[] = []; - for (const s of link.manifest.scopes) { + + for (const scope of link.manifest.scopes) { const node: RemoteScopeNode = { - name: s.token, - run: async (ctx: any) => ({ [s.token]: await link.rpc('scope', s.token, envelopeFrom(ctx)) }), + name: scope.token, + run: async (ctx: any) => ({ [scope.token]: await link.rpc('scope', scope.token, envelopeFrom(ctx)) }), }; - (s.scope === 'app' ? providers : steps).push(node); + (scope.scope === 'app' ? providers : steps).push(node); } - const routes: RemoteRoute[] = link.manifest.routes.map((r) => ({ - method: r.method, pattern: r.pattern, - handler: async (req: RequestEnvelope) => (await link.rpc('route', r.pattern, req)) as ResponseShape, + + const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({ + method: route.method, + pattern: route.pattern, + handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape, })); return { providers, steps, routes }; } diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index e0e5496..b7922fa 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -4,12 +4,14 @@ import type { ResponseShape } from '../pipeline'; import { isHttpError } from '../signals'; import { encode, decode, type Manifest, type RequestEnvelope, type RouteEntry, type Frame } from './protocol'; +/** WebSocket path where a teapot exposes its mesh control channel. */ export const MESH_CONTROL_PATH = '/__mesh__/control'; +/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */ export function buildManifest(args: { - providers: string[]; // exported provider tokens (app-scope) - steps: string[]; // exported step tokens (request-scope) - routes: RouteEntry[]; // exported buffered routes + providers: string[]; // exported provider tokens (app-scope) + steps: string[]; // exported step tokens (request-scope) + routes: RouteEntry[]; // exported buffered routes }): Manifest { return { scopes: [ @@ -20,13 +22,14 @@ export function buildManifest(args: { }; } -function safeEqual(a: string, b: string): boolean { - const ba = Buffer.from(a); - const bb = Buffer.from(b); - if (ba.length !== bb.length) return false; - return crypto.timingSafeEqual(ba, bb); +function safeEqual(left: string, right: string): boolean { + const leftBuf = Buffer.from(left); + const rightBuf = Buffer.from(right); + if (leftBuf.length !== rightBuf.length) return false; + return crypto.timingSafeEqual(leftBuf, rightBuf); } +/** Dependencies for the mesh control handler: shared secret, manifest, and scope/route resolvers. */ export interface MeshControlDeps { secret: string; manifest: Manifest; @@ -35,9 +38,77 @@ export interface MeshControlDeps { bus?: Bus; } +/** The rpc-req member of the {@link Frame} union. */ +type RpcReqFrame = Extract; + +/** Build a 403 "not exported" error for an unknown scope/route token. */ +function notExported(name: string): Error { + const error: any = new Error(`not exported: ${name}`); + error.status = 403; + + return error; +} + +/** Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch. */ +function handleHandshake(ws: any, frame: Frame, deps: MeshControlDeps): boolean { + if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) { + ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes })); + deps.bus?.emit('mesh:connect', { name: 'teapot' }); + + return true; + } + + ws.close(1008); + + return false; +} + +/** Resolve an authenticated rpc-req against the exported scopes/routes, enforcing export gating. */ +function resolveRpc( + frame: RpcReqFrame, + deps: MeshControlDeps, + exportedScopes: Set, + exportedRoutes: Set, +): Promise { + const { kind, name, ctx } = frame; + + if (kind === 'scope') { + if (!exportedScopes.has(name)) throw notExported(name); + + return deps.resolveScope(name, ctx); + } + + if (![...exportedRoutes].some((key) => key.endsWith(` ${name}`))) throw notExported(name); + + return deps.resolveRoute(name, ctx); +} + +/** Serve one authenticated rpc-req: resolve it and frame the ok/error response back to the peer. */ +async function handleRpc( + ws: any, + frame: RpcReqFrame, + deps: MeshControlDeps, + exportedScopes: Set, + exportedRoutes: Set, +): Promise { + const { id, name } = frame; + + try { + const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes); + + ws.send(encode({ type: 'rpc-res', id, ok: true, result })); + } catch (err) { + const status = isHttpError(err) ? err.status : ((err as any)?.status ?? 500); + + deps.bus?.emit('mesh:rpc:error', { name, error: err }); + ws.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } })); + } +} + +/** Build a WebSocket handler that authenticates peers and serves scope/route RPCs from the manifest. */ export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (ws: any) => void } { - const exportedScopes = new Set(deps.manifest.scopes.map((s) => s.token)); - const exportedRoutes = new Set(deps.manifest.routes.map((r) => `${r.method} ${r.pattern}`)); + const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token)); + const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`)); return { path: MESH_CONTROL_PATH, @@ -45,36 +116,22 @@ export function createMeshControl(deps: MeshControlDeps): { path: string; handle let authed = false; ws.on('message', async (data: unknown) => { let frame: Frame; - try { frame = decode(String(data)); } catch { return; } + + try { + frame = decode(String(data)); + } catch { + return; + } if (!authed) { - if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) { - authed = true; - ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes })); - deps.bus?.emit('mesh:connect', { name: 'teapot' }); - } else { - ws.close(1008); - } + authed = handleHandshake(ws, frame, deps); + return; } if (frame.type !== 'rpc-req') return; - const { id, kind, name, ctx } = frame; - try { - let result: unknown; - if (kind === 'scope') { - if (!exportedScopes.has(name)) { const e: any = new Error(`not exported: ${name}`); e.status = 403; throw e; } - result = await deps.resolveScope(name, ctx); - } else { - if (![...exportedRoutes].some((k) => k.endsWith(` ${name}`))) { const e: any = new Error(`not exported: ${name}`); e.status = 403; throw e; } - result = await deps.resolveRoute(name, ctx); - } - ws.send(encode({ type: 'rpc-res', id, ok: true, result })); - } catch (err) { - const status = isHttpError(err) ? err.status : (err as any)?.status ?? 500; - deps.bus?.emit('mesh:rpc:error', { name, error: err }); - ws.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } })); - } + + await handleRpc(ws, frame, deps, exportedScopes, exportedRoutes); }); ws.on('close', () => deps.bus?.emit('mesh:disconnect', { name: 'teapot' })); }, diff --git a/src/metadata.ts b/src/metadata.ts index be4efce..9d47050 100644 --- a/src/metadata.ts +++ b/src/metadata.ts @@ -1,15 +1,43 @@ import 'reflect-metadata'; +/** Any class constructor. Kept `any` because decorators must accept every target shape. */ export type Ctor = new (...args: any[]) => any; +/** Serializes a handler's return value into an HTTP response envelope. */ export type TransformerFn = (value: unknown) => { status?: number; headers?: Record; body: string }; -export interface ProviderMeta { provides: string; needs: string[]; optional: boolean; export: boolean } -export interface StepMeta { provides: string; needs: string[]; optional: boolean; export: boolean } +/** Metadata attached by `@Provider`: what it provides, what it needs, and its visibility. */ +export interface ProviderMeta { + provides: string; + needs: string[]; + optional: boolean; + export: boolean; +} +/** Metadata attached by `@Step`: what it provides, what it needs, and its visibility. */ +export interface StepMeta { + provides: string; + needs: string[]; + optional: boolean; + export: boolean; +} +/** HTTP verbs supported by the route decorators. */ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; +/** Wire transport a route responds with. */ export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws'; -export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport; export: boolean; duplicates?: 'array' | 'last' } +/** Metadata attached by a route decorator to a single handler method. */ +export interface RouteMeta { + method: HttpMethod; + path: string; + handlerName: string; + transport: Transport; + export: boolean; + duplicates?: 'array' | 'last'; +} +/** Options accepted by the `@Module` decorator. */ export interface ModuleOptions { - mountpoint: string; providers?: Ctor[]; steps?: Ctor[]; controllers?: Ctor[]; + mountpoint: string; + providers?: Ctor[]; + steps?: Ctor[]; + controllers?: Ctor[]; } const K = { @@ -21,22 +49,47 @@ const K = { transformer: Symbol('gt:transformer'), }; -export function Provider(opts: { provides: string; needs?: string[]; optional?: boolean; export?: boolean }): ClassDecorator { +/** Marks a class as a provider: a lazily-built dependency addressable by its `provides` key. */ +export function Provider(opts: { + provides: string; + needs?: string[]; + optional?: boolean; + export?: boolean; +}): ClassDecorator { return (target) => { - const meta: ProviderMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false, export: opts.export ?? false }; + const meta: ProviderMeta = { + provides: opts.provides, + needs: opts.needs ?? [], + optional: opts.optional ?? false, + export: opts.export ?? false, + }; Reflect.defineMetadata(K.provider, meta, target); }; } -export function Step(opts: { provides: string; needs?: string[]; optional?: boolean; export?: boolean }): ClassDecorator { +/** Marks a class as a step: a per-request unit that runs in dependency order and contributes to the context. */ +export function Step(opts: { + provides: string; + needs?: string[]; + optional?: boolean; + export?: boolean; +}): ClassDecorator { return (target) => { - const meta: StepMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false, export: opts.export ?? false }; + const meta: StepMeta = { + provides: opts.provides, + needs: opts.needs ?? [], + optional: opts.optional ?? false, + export: opts.export ?? false, + }; Reflect.defineMetadata(K.step, meta, target); }; } +/** Sets the shared path prefix for every route declared on the decorated controller. */ export function Route(prefix: string): ClassDecorator { - return (target) => { Reflect.defineMetadata(K.routePrefix, prefix, target); }; + return (target) => { + Reflect.defineMetadata(K.routePrefix, prefix, target); + }; } function routeDecorator(method: HttpMethod, transport: Transport) { @@ -44,48 +97,77 @@ function routeDecorator(method: HttpMethod, transport: Transport) { (target, propertyKey) => { const ctor = target.constructor; const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? []; - routes.push({ method, path, handlerName: String(propertyKey), transport, export: opts?.export ?? false, duplicates: opts?.duplicates }); + routes.push({ + method, + path, + handlerName: String(propertyKey), + transport, + export: opts?.export ?? false, + duplicates: opts?.duplicates, + }); Reflect.defineMetadata(K.routes, routes, ctor); }; } +/** Declares a buffered `GET` route. */ export const Get = routeDecorator('GET', 'buffer'); +/** Declares a buffered `POST` route. */ export const Post = routeDecorator('POST', 'buffer'); +/** Declares a buffered `PUT` route. */ export const Put = routeDecorator('PUT', 'buffer'); +/** Declares a buffered `PATCH` route. */ export const Patch = routeDecorator('PATCH', 'buffer'); +/** Declares a buffered `DELETE` route. */ export const Delete = routeDecorator('DELETE', 'buffer'); +/** Declares a `GET` route streamed as Server-Sent Events. */ export const Sse = routeDecorator('GET', 'sse'); +/** Declares a `GET` route whose transport is content-negotiated at request time. */ export const Stream = routeDecorator('GET', 'negotiate'); +/** Declares a `GET` route upgraded to a WebSocket. */ export const Ws = routeDecorator('GET', 'ws'); +/** Attaches a response transformer to a handler method. */ export function Transformer(fn: TransformerFn): MethodDecorator { return (target, propertyKey) => { Reflect.defineMetadata(K.transformer, fn, target.constructor, String(propertyKey)); }; } +/** Marks a class as a module and records its providers, steps, controllers, and mountpoint. */ export function Module(opts: ModuleOptions): ClassDecorator { - return (target) => { Reflect.defineMetadata(K.module, opts, target); }; + return (target) => { + Reflect.defineMetadata(K.module, opts, target); + }; } +/** Reads the `@Provider` metadata off a class, if any. */ export function getProviderMeta(cls: Ctor): ProviderMeta | undefined { return Reflect.getMetadata(K.provider, cls); } + +/** Reads the `@Step` metadata off a class, if any. */ export function getStepMeta(cls: Ctor): StepMeta | undefined { return Reflect.getMetadata(K.step, cls); } + +/** Reads the `@Module` metadata off a class, if any. */ export function getModuleMeta(cls: Ctor): ModuleOptions | undefined { return Reflect.getMetadata(K.module, cls); } + +/** Reads the response transformer registered for a handler method, if any. */ export function getTransformer(cls: Ctor, methodName: string): TransformerFn | undefined { return Reflect.getMetadata(K.transformer, cls, methodName); } + +/** Returns every route on a controller with its path resolved against the class prefix. */ export function getRoutes(cls: Ctor): RouteMeta[] { const prefix: string = Reflect.getMetadata(K.routePrefix, cls) ?? ''; const routes: RouteMeta[] = Reflect.getMetadata(K.routes, cls) ?? []; - return routes.map((r) => ({ ...r, path: joinPath(prefix, r.path) })); + return routes.map((route) => ({ ...route, path: joinPath(prefix, route.path) })); } -export function joinPath(a: string, b: string): string { - return `${a.replace(/\/$/, '')}/${b.replace(/^\//, '')}`.replace(/\/+/g, '/'); +/** Joins two path segments with exactly one slash, collapsing any duplicates. */ +export function joinPath(base: string, segment: string): string { + return `${base.replace(/\/$/, '')}/${segment.replace(/^\//, '')}`.replace(/\/+/g, '/'); } diff --git a/src/multipart.ts b/src/multipart.ts index 02fad20..3e03cab 100644 --- a/src/multipart.ts +++ b/src/multipart.ts @@ -1,122 +1,130 @@ -// src/multipart.ts — pure, binary-safe multipart/form-data parser. No server deps. -export interface UploadedFile { filename: string; contentType: string; data: Buffer; size: number } +// src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency. +import { Readable } from 'stream'; +import { HttpError } from './signals'; + +/** A single uploaded file part decoded from a multipart body. */ +export interface UploadedFile { + filename: string; + contentType: string; + data: Buffer; + size: number; +} + +/** Decoded multipart body: text fields and file uploads, keyed by part name. */ export interface MultipartBody { fields: Record; files: Record; } -export interface MultipartOpts { maxParts: number; duplicates: 'array' | 'last' } -const CRLF = Buffer.from('\r\n'); +/** Parser limits and duplicate-key policy for {@link parseMultipart}. */ +export interface MultipartOpts { + maxParts: number; + duplicates: 'array' | 'last'; +} -// boundary token from a Content-Type value; supports quoted form. +/** + * Extracts the boundary token from a Content-Type value (supports the quoted form). + * @returns The boundary, or undefined when absent. + */ export function extractBoundary(contentType: string): string | undefined { - const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType); - const b = (m?.[1] ?? m?.[2])?.trim(); - return b || undefined; + const match = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType); + const boundary = (match?.[1] ?? match?.[2])?.trim(); + return boundary || undefined; } -// order-independent, quoted-or-unquoted param lookup within a header value. -// The `(?:^|[;\s])` prefix anchors the key to a param boundary so `name=` does NOT -// match the tail of `filename=`, and `filename=` does not match `filename*=`. -function param(header: string, key: string): string | undefined { - const q = new RegExp(`(?:^|[;\\s])${key}="([^"]*)"`, 'i').exec(header); - if (q) return q[1]; - const u = new RegExp(`(?:^|[;\\s])${key}=([^";]+)`, 'i').exec(header); - return u ? u[1].trim() : undefined; -} - -function addField(fields: MultipartBody['fields'], name: string, value: string, dup: 'array' | 'last'): void { - if (dup === 'array') { - const ex = fields[name]; - if (Array.isArray(ex)) ex.push(value); +function addField(fields: MultipartBody['fields'], name: string, value: string, duplicates: 'array' | 'last'): void { + if (duplicates === 'array') { + const existing = fields[name]; + if (Array.isArray(existing)) existing.push(value); else fields[name] = [value]; } else { fields[name] = value; // last-wins } } -// Reusable accumulator for any iterable of [key, value] pairs (e.g. URLSearchParams) -// so urlencoded bodies collapse duplicates with the exact same policy as multipart fields. +/** + * Collapses an iterable of [key, value] pairs (e.g. URLSearchParams) into an object, + * applying the same duplicate-key policy as multipart fields so urlencoded bodies behave identically. + */ export function collapseDuplicates( - pairs: Iterable<[string, string]>, dup: 'array' | 'last', + pairs: Iterable<[string, string]>, + duplicates: 'array' | 'last', ): Record { const out: Record = {}; - for (const [k, v] of pairs) addField(out, k, v, dup); + for (const [key, value] of pairs) addField(out, key, value, duplicates); return out; } function addFile(files: MultipartBody['files'], name: string, file: UploadedFile): void { - const ex = files[name]; - if (ex === undefined) files[name] = file; - else if (Array.isArray(ex)) ex.push(file); - else files[name] = [ex, file]; + const existing = files[name]; + if (existing === undefined) files[name] = file; + else if (Array.isArray(existing)) existing.push(file); + else files[name] = [existing, file]; } -// Find the next REAL delimiter at/after `from`: a `\r\n--boundary` occurrence that is -// followed by `\r\n` (a part) or `--` (the terminator). This skips false hits where the -// exact `\r\n--boundary` byte sequence appears INSIDE a file body — the data-integrity case. -function findDelim(buf: Buffer, delim: Buffer, from: number): number { - let i = buf.indexOf(delim, from); - while (i !== -1) { - const a = i + delim.length; - if ((buf[a] === 0x0d && buf[a + 1] === 0x0a) || (buf[a] === 0x2d && buf[a + 1] === 0x2d)) return i; - i = buf.indexOf(delim, i + delim.length); // false hit inside a body — keep searching +/** Lazily loads the optional `busboy` peer dependency, or null when it is not installed. */ +function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEmitter) | null { + try { + // `busboy` is an OPTIONAL peer dependency: only multipart uploads need it, so it is + // lazy-required and its absence surfaces as a clear 501 rather than a load-time crash. + // eslint-disable-next-line @typescript-eslint/no-require-imports + return require('busboy'); + } catch { + return null; } - return -1; } -export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpts): MultipartBody { - const fields: MultipartBody['fields'] = {}; - const files: MultipartBody['files'] = {}; - const delim = Buffer.concat([CRLF, Buffer.from(`--${boundary}`)]); // \r\n--boundary - // Normalize: prepend CRLF so the FIRST boundary (which a browser sends with no - // leading CRLF) is also preceded by the delimiter and isn't dropped as preamble. - const buf = Buffer.concat([CRLF, raw]); +/** + * Parses a raw multipart/form-data buffer into decoded fields and files, using `busboy`. + * @param raw The full (already size-capped) request body. + * @param boundary The boundary token (see {@link extractBoundary}). + * @throws HttpError 501 when the optional `busboy` peer dependency is not installed. + * @throws Error 'Invalid multipart body' on malformed input or when `maxParts` is exceeded. + */ +export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpts): Promise { + const busboy = loadBusboy(); - let pos = findDelim(buf, delim, 0); - if (pos === -1) throw new Error('Invalid multipart body'); - let count = 0; - while (true) { - let start = pos + delim.length; - // terminator "--" immediately after the boundary → done - if (buf[start] === 0x2d && buf[start + 1] === 0x2d) break; - // skip the CRLF that ends the boundary line - if (buf[start] === 0x0d && buf[start + 1] === 0x0a) start += 2; - const next = findDelim(buf, delim, start); - if (next === -1) throw new Error('Invalid multipart body'); - if (++count > opts.maxParts) throw new Error('Invalid multipart body'); - const part = buf.subarray(start, next); - const sep = part.indexOf('\r\n\r\n'); - if (sep === -1) throw new Error('Invalid multipart body'); - const headerText = part.subarray(0, sep).toString('utf8'); - const partBody = part.subarray(sep + 4); + if (!busboy) { + throw new HttpError(501, 'multipart/form-data requires the optional "busboy" peer dependency — run `npm i busboy`'); + } - let disposition = ''; - let contentType = ''; - for (const line of headerText.split('\r\n')) { - const c = line.indexOf(':'); - if (c === -1) continue; - const k = line.slice(0, c).trim().toLowerCase(); - const v = line.slice(c + 1).trim(); - if (k === 'content-disposition') disposition = v; - else if (k === 'content-type') contentType = v; - } + return new Promise((resolve, reject) => { + const body: MultipartBody = { fields: {}, files: {} }; + const fail = () => reject(new Error('Invalid multipart body')); + let bb: NodeJS.WritableStream & NodeJS.EventEmitter; - const name = param(disposition, 'name'); - if (name === undefined) throw new Error('Invalid multipart body'); - const filename = param(disposition, 'filename'); - if (filename !== undefined) { - if (filename === '' && partBody.length === 0) { pos = next; continue; } // unselected file input - addFile(files, name, { - filename, - contentType: contentType || 'application/octet-stream', - data: Buffer.from(partBody), // copy out of the shared buffer - size: partBody.length, + try { + bb = busboy({ + headers: { 'content-type': `multipart/form-data; boundary=${boundary}` }, + limits: { parts: opts.maxParts }, }); - } else { - addField(fields, name, partBody.toString('utf8'), opts.duplicates); + } catch { + return fail(); } - pos = next; - } - return { fields, files }; + + bb.on('field', (name: string, value: string) => addField(body.fields, name, value, opts.duplicates)); + + bb.on('file', (name: string, stream: Readable, info: { filename?: string; mimeType?: string }) => { + const chunks: Buffer[] = []; + stream.on('data', (chunk: Buffer) => chunks.push(chunk)); + stream.on('close', () => { + const data = Buffer.concat(chunks); + const filename = info.filename ?? ''; + if (filename === '' && data.length === 0) return; // unselected file input + + addFile(body.files, name, { + filename, + contentType: info.mimeType || 'application/octet-stream', + data, + size: data.length, + }); + }); + }); + + bb.on('partsLimit', fail); // more parts than maxParts → treat as malformed (matches prior behavior) + bb.on('error', fail); + bb.on('close', () => resolve(body)); + + Readable.from(raw).pipe(bb); + }); } diff --git a/src/params.ts b/src/params.ts index a431de3..495bca9 100644 --- a/src/params.ts +++ b/src/params.ts @@ -3,12 +3,22 @@ import type { Ctor } from './metadata'; import { isStandardSchema, type StandardSchemaV1 } from './standard-schema'; import { ValidationError } from './signals'; +/** Parsed URL query string as flat key/value pairs. */ export type Query = Record; +/** Incoming request headers; a header may repeat, hence the array variant. */ export type Headers = Record; +/** Per-request bag that accumulates values produced by steps and providers. */ export type Context = Record; type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort'; -export interface ArgSpec { index: number; source: ArgSource; key?: string; keys?: string[]; schema?: StandardSchemaV1 } +/** Describes how a single handler parameter is sourced and (optionally) validated. */ +export interface ArgSpec { + index: number; + source: ArgSource; + key?: string; + keys?: string[]; + schema?: StandardSchemaV1; +} const ARGS = Symbol('gt:args'); @@ -30,73 +40,94 @@ function envelope(source: ArgSource) { else if (typeof arg === 'string') spec.key = arg; else if (isStandardSchema(arg)) spec.schema = arg; else if (arg !== undefined) throw new Error(`@${source}: expected a Standard Schema or a string/array key`); + if (schema !== undefined) { if (!isStandardSchema(schema)) throw new Error(`@${source}: second argument must be a Standard Schema`); spec.schema = schema; } + record(target, methodKey, spec); }; } +/** Inject a route path parameter; pass a key to pick one, or a schema/array to shape it. */ export const param = envelope('params'); +/** Inject a query-string value; pass a key to pick one, or a schema/array to shape it. */ export const query = envelope('query'); +/** Inject the request body; pass a schema to validate it. */ export const body = envelope('body'); +/** Inject request headers; pass a key to pick one, an array to pick several, or no arg for the whole bag. */ export const headers = envelope('headers'); +/** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */ +export const header = envelope('headers'); +/** Inject a value produced upstream by a step or provider, addressed by key. */ export function needs(key: string): ParameterDecorator { return (target, methodKey, index) => record(target, methodKey, { index, source: 'needs', key }); } +/** Inject the whole request context bag. */ export function ctx(): ParameterDecorator { return (target, methodKey, index) => record(target, methodKey, { index, source: 'ctx' }); } +/** Inject the inbound stream (for streaming/upload handlers). */ export function inbound(): ParameterDecorator { return (target, methodKey, index) => record(target, methodKey, { index, source: 'inbound' }); } +/** Inject the request's abort signal. */ export function abort(): ParameterDecorator { return (target, methodKey, index) => record(target, methodKey, { index, source: 'abort' }); } +/** Read the recorded parameter specs for a handler method, ordered by parameter index. */ export function getArgs(cls: Ctor, methodName: string): ArgSpec[] { const map: Record = Reflect.getMetadata(ARGS, cls) ?? {}; return [...(map[methodName] ?? [])].sort((a, b) => a.index - b.index); } +/** Extract the `@needs` keys a handler depends on, for dependency resolution. */ export function getHandlerNeeds(specs: ArgSpec[]): string[] { - return specs.filter((s) => s.source === 'needs' && s.key).map((s) => s.key as string); + return specs.filter((spec) => spec.source === 'needs' && spec.key).map((spec) => spec.key as string); } +/** Build the positional argument array for a handler by sourcing and validating each spec. */ export async function resolveArgs(specs: ArgSpec[], context: Context): Promise { if (specs.length === 0) return []; - const max = Math.max(...specs.map((s) => s.index)); - const args: unknown[] = new Array(max + 1).fill(undefined); - for (const s of specs) { - let value = resolveOne(s, context); - if (s.schema) { - const result = await s.schema['~standard'].validate(value); - if (result.issues) throw new ValidationError([...result.issues], s.source); + const maxIndex = Math.max(...specs.map((spec) => spec.index)); + const args: unknown[] = new Array(maxIndex + 1).fill(undefined); + + for (const spec of specs) { + let value = resolveOne(spec, context); + + if (spec.schema) { + const result = await spec.schema['~standard'].validate(value); + if (result.issues) throw new ValidationError([...result.issues], spec.source); value = result.value; } - args[s.index] = value; + + args[spec.index] = value; } + return args; } -function resolveOne(s: ArgSpec, context: Context): unknown { - if (s.source === 'ctx') return context; - if (s.source === 'needs') return context[s.key as string]; - if (s.source === 'inbound') return context.inbound; - if (s.source === 'abort') return context.abort; - const bag = context[s.source]; +function resolveOne(spec: ArgSpec, context: Context): unknown { + if (spec.source === 'ctx') return context; + if (spec.source === 'needs') return context[spec.key as string]; + if (spec.source === 'inbound') return context.inbound; + if (spec.source === 'abort') return context.abort; + const bag = context[spec.source]; if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is - const record = bag as Record; - if (s.keys) { - const out: Record = {}; - for (const k of s.keys) out[k] = record[k]; - return out; + const values = bag as Record; + + if (spec.keys) { + const picked: Record = {}; + for (const key of spec.keys) picked[key] = values[key]; + return picked; } - if (s.key !== undefined) return record[s.key]; - return record; + + if (spec.key !== undefined) return values[spec.key]; + return values; } diff --git a/src/pipeline.ts b/src/pipeline.ts index e719b1a..d2ec969 100644 --- a/src/pipeline.ts +++ b/src/pipeline.ts @@ -3,15 +3,35 @@ import { errorToResponse } from './transformers'; import { isAsyncIterable } from './channel'; import type { TransformerFn } from './metadata'; -export interface PipelineStep { name: string; origin: string; run: (ctx: any) => any } -export interface ResponseShape { status: number; headers: Record; body: string } -export interface StreamResult { stream: AsyncIterable } +/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */ +export interface PipelineStep { + name: string; + origin: string; + run: (ctx: any) => any; +} +/** A fully materialized HTTP response produced by a transformer. */ +export interface ResponseShape { + status: number; + headers: Record; + body: string; +} +/** A streaming response; the async iterable is written to the socket and bypasses the transformer. */ +export interface StreamResult { + stream: AsyncIterable; +} +/** The outcome of {@link runPipeline}: either a buffered response or a stream. */ export type PipelineResult = ResponseShape | StreamResult; -export function isStreamResult(r: PipelineResult): r is StreamResult { - return 'stream' in r; +/** Type guard narrowing a {@link PipelineResult} to a {@link StreamResult}. */ +export function isStreamResult(result: PipelineResult): result is StreamResult { + return 'stream' in result; } +/** + * Run `steps` in order over a context seeded from `seed`, then invoke `handler`. + * An async-iterable handler result becomes a stream; anything else is run through `transformer`. + * Errors are caught, emitted on `bus`, and converted to an error response. + */ export async function runPipeline(args: { steps: PipelineStep[]; handler: (ctx: any) => unknown; @@ -20,18 +40,21 @@ export async function runPipeline(args: { bus: Bus; }): Promise { const { steps, handler, transformer, seed, bus } = args; - let ctx: any = { ...seed }; + // context is intentionally `any`: each step merges arbitrary keys into the accumulator + let context: any = { ...seed }; + try { - for (const s of steps) { - bus.emit('request:step:enter', { name: s.name, scope: s.origin }); - const out = await s.run(ctx); - ctx = { ...ctx, ...out }; - bus.emit('request:step:leave', { name: s.name, scope: s.origin }); + for (const step of steps) { + bus.emit('request:step:enter', { name: step.name, scope: step.origin }); + const output = await step.run(context); + context = { ...context, ...output }; + bus.emit('request:step:leave', { name: step.name, scope: step.origin }); } - const result = await handler(ctx); - if (isAsyncIterable(result)) return { stream: result }; // stream path: transformer bypassed - const r = transformer(result); - return { status: r.status ?? 200, headers: r.headers ?? {}, body: r.body }; + + const result = await handler(context); + if (isAsyncIterable(result)) return { stream: result }; // stream path: transformer bypassed + const transformed = transformer(result); + return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body }; } catch (error) { bus.emit('request:step:error', { name: 'pipeline', error }); return errorToResponse(error); diff --git a/src/plugin.ts b/src/plugin.ts index d0c25d8..2a0eb6f 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -1,5 +1,6 @@ import { Bus } from './bus'; +/** A step or provider a plugin contributes to the graph. */ export interface ScopeNode { kind: 'step' | 'provider'; name: string; @@ -8,10 +9,19 @@ export interface ScopeNode { run: (ctx: any) => any; } -export interface ScopeApi { add(node: ScopeNode): void } -export interface PluginApi { bus: { on: Bus['on'] }; scope: ScopeApi } +/** The narrow surface a plugin uses to register nodes into the host graph. */ +export interface ScopeApi { + add(node: ScopeNode): void; +} +/** The capabilities handed to a plugin: event subscription and node registration only. */ +export interface PluginApi { + bus: { on: Bus['on'] }; + scope: ScopeApi; +} +/** A plugin: a function that wires itself up through the provided PluginApi. */ export type Plugin = (api: PluginApi) => void; +/** Runs a plugin against a restricted API, then emits `plugin:mounted`. */ export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi): void { // Hand the plugin ONLY on() and add(). No emit, no other scope. Isolation is structural. const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope }; diff --git a/src/rooms.ts b/src/rooms.ts index 7eee41b..aa5b5a3 100644 --- a/src/rooms.ts +++ b/src/rooms.ts @@ -1,11 +1,21 @@ import { channel, type Channel } from './channel'; +/** Registry of named broadcast channels, lazily created and shared by name. */ export class Rooms { private readonly hubs = new Map>(); + /** Returns the channel for `name`, creating it on first access. */ room(name: string): Channel { let hub = this.hubs.get(name); - if (!hub) { hub = channel(); this.hubs.set(name, hub); } + + if (!hub) { + hub = channel(); + this.hubs.set(name, hub); + } + return hub as unknown as Channel; } - names(): string[] { return [...this.hubs.keys()]; } + /** Lists the names of all rooms created so far. */ + names(): string[] { + return [...this.hubs.keys()]; + } } diff --git a/src/security.ts b/src/security.ts index 18c58b8..c48023d 100644 --- a/src/security.ts +++ b/src/security.ts @@ -1,6 +1,14 @@ // src/security.ts — pure header computation, no server deps -export interface TlsOptions { key: Buffer | string; cert: Buffer | string; ca?: Buffer | string; passphrase?: string } +/** TLS material for an HTTPS server. */ +export interface TlsOptions { + key: Buffer | string; + cert: Buffer | string; + ca?: Buffer | string; + passphrase?: string; +} + +/** CORS policy. `origins` may be a literal, list, `'*'`, or a predicate. */ export interface CorsOptions { origins: string | string[] | '*' | ((origin: string) => boolean); methods?: string[]; @@ -10,6 +18,7 @@ export interface CorsOptions { maxAge?: number; } +/** Security header policy. Each field toggles or configures one response header. */ export interface SecurityOptions { hsts?: boolean | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean }; frameOptions?: 'SAMEORIGIN' | 'DENY' | false; @@ -23,32 +32,47 @@ type Headers = Record; const HSTS_DEFAULT_MAXAGE = 15552000; // 180 days // scheme "://" host [":" port], or literal "null". Rejects control chars/whitespace. +// Control-char ranges (\x00-\x1f\x7f) are intentional: reject control chars in Origin headers. +// eslint-disable-next-line no-control-regex const ORIGIN_RE = /^(?:null|[a-z][a-z0-9+.-]*:\/\/[^\s/?#\x00-\x1f\x7f]+)$/i; -export function isValidOrigin(o: string): boolean { return ORIGIN_RE.test(o); } +/** True if `origin` is a well-formed Origin header value (scheme://host or literal `null`). */ +export function isValidOrigin(origin: string): boolean { + return ORIGIN_RE.test(origin); +} + +/** Append `add` to a `Vary` header value, case-insensitively deduplicated. */ export function mergeVary(existing: string | undefined, add: string): string { - const parts = (existing ? existing.split(',').map((s) => s.trim()).filter(Boolean) : []); - if (!parts.some((p) => p.toLowerCase() === add.toLowerCase())) parts.push(add); + const parts = existing + ? existing + .split(',') + .map((segment) => segment.trim()) + .filter(Boolean) + : []; + if (!parts.some((part) => part.toLowerCase() === add.toLowerCase())) parts.push(add); return parts.join(', '); } +/** Build security response headers (HSTS, frame options, CSP, etc.). `secure` gates HSTS. */ export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: boolean): Headers { if (opts === false) return {}; - const o: SecurityOptions = opts === true ? {} : opts; - const h: Headers = {}; - if (o.noSniff !== false) h['x-content-type-options'] = 'nosniff'; - if (o.frameOptions !== false) h['x-frame-options'] = o.frameOptions ?? 'SAMEORIGIN'; - if (o.referrerPolicy !== false) h['referrer-policy'] = o.referrerPolicy ?? 'no-referrer'; - if (o.dnsPrefetchControl !== false) h['x-dns-prefetch-control'] = 'off'; - if (o.csp) h['content-security-policy'] = o.csp; - if (secure && o.hsts !== false) { - const hs = o.hsts && o.hsts !== true ? o.hsts : {}; - let v = `max-age=${hs.maxAge ?? HSTS_DEFAULT_MAXAGE}`; - if (hs.includeSubDomains) v += '; includeSubDomains'; - if (hs.preload) v += '; preload'; - h['strict-transport-security'] = v; + const options: SecurityOptions = opts === true ? {} : opts; + const headers: Headers = {}; + if (options.noSniff !== false) headers['x-content-type-options'] = 'nosniff'; + if (options.frameOptions !== false) headers['x-frame-options'] = options.frameOptions ?? 'SAMEORIGIN'; + if (options.referrerPolicy !== false) headers['referrer-policy'] = options.referrerPolicy ?? 'no-referrer'; + if (options.dnsPrefetchControl !== false) headers['x-dns-prefetch-control'] = 'off'; + if (options.csp) headers['content-security-policy'] = options.csp; + + if (secure && options.hsts !== false) { + const hsts = options.hsts && options.hsts !== true ? options.hsts : {}; + let value = `max-age=${hsts.maxAge ?? HSTS_DEFAULT_MAXAGE}`; + if (hsts.includeSubDomains) value += '; includeSubDomains'; + if (hsts.preload) value += '; preload'; + headers['strict-transport-security'] = value; } - return h; + + return headers; } function originAllowed(spec: CorsOptions['origins'], origin: string): boolean { @@ -58,36 +82,46 @@ function originAllowed(spec: CorsOptions['origins'], origin: string): boolean { return spec === origin; } -// req: minimal shape { headers: { origin? } } -export function resolveCors(opts: CorsOptions, req: { headers: Record }): Headers { - const h: Headers = {}; - const raw = req.headers['origin']; - const origin = Array.isArray(raw) ? raw[0] : raw; - if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return h; +/** Compute CORS response headers for a request. Returns `{}` when the origin is not allowed. */ +export function resolveCors( + opts: CorsOptions, + req: { headers: Record }, +): Headers { + const headers: Headers = {}; + const rawOrigin = req.headers['origin']; + const origin = Array.isArray(rawOrigin) ? rawOrigin[0] : rawOrigin; + if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return headers; // credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic. if (opts.credentials) { - h['access-control-allow-origin'] = origin; - h['access-control-allow-credentials'] = 'true'; - h['vary'] = mergeVary(h['vary'], 'Origin'); + headers['access-control-allow-origin'] = origin; + headers['access-control-allow-credentials'] = 'true'; + headers['vary'] = mergeVary(headers['vary'], 'Origin'); } else if (opts.origins === '*') { - h['access-control-allow-origin'] = '*'; + headers['access-control-allow-origin'] = '*'; } else { - h['access-control-allow-origin'] = origin; - h['vary'] = mergeVary(h['vary'], 'Origin'); + headers['access-control-allow-origin'] = origin; + headers['vary'] = mergeVary(headers['vary'], 'Origin'); } - if (opts.exposedHeaders?.length) h['access-control-expose-headers'] = opts.exposedHeaders.join(', '); - return h; + + if (opts.exposedHeaders?.length) headers['access-control-expose-headers'] = opts.exposedHeaders.join(', '); + return headers; } -// Preflight-specific headers (methods/allowed-headers/max-age). Call only for OPTIONS+ACRM. -export function corsPreflightHeaders(opts: CorsOptions, req: { headers: Record }): Headers { - const h = resolveCors(opts, req); - if (!h['access-control-allow-origin']) return h; // origin not allowed → bare 204 - h['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(', '); - const reqHdrs = req.headers['access-control-request-headers']; - h['access-control-allow-headers'] = opts.allowedHeaders?.join(', ') - ?? (Array.isArray(reqHdrs) ? reqHdrs.join(', ') : reqHdrs ?? '*'); - if (opts.maxAge != null) h['access-control-max-age'] = String(opts.maxAge); - return h; +/** Preflight-specific headers (methods/allowed-headers/max-age). Call only for OPTIONS+ACRM. */ +export function corsPreflightHeaders( + opts: CorsOptions, + req: { headers: Record }, +): Headers { + const headers = resolveCors(opts, req); + if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204 + headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join( + ', ', + ); + const requestedHeaders = req.headers['access-control-request-headers']; + headers['access-control-allow-headers'] = + opts.allowedHeaders?.join(', ') ?? + (Array.isArray(requestedHeaders) ? requestedHeaders.join(', ') : (requestedHeaders ?? '*')); + if (opts.maxAge != null) headers['access-control-max-age'] = String(opts.maxAge); + return headers; } diff --git a/src/signals.ts b/src/signals.ts index 3b47c24..e7556bb 100644 --- a/src/signals.ts +++ b/src/signals.ts @@ -1,34 +1,56 @@ import type { StandardIssue } from './standard-schema'; +/** Error carrying an HTTP status code and optional response body. Base of all signals. */ export class HttpError extends Error { - constructor(readonly status: number, message?: string, readonly body?: unknown) { + constructor( + readonly status: number, + message?: string, + readonly body?: unknown, + ) { super(message ?? `HTTP ${status}`); this.name = new.target.name; } } +/** 401 Unauthorized. */ export class Unauthorized extends HttpError { - constructor(message?: string) { super(401, message); } + constructor(message?: string) { + super(401, message); + } } +/** 404 Not Found. */ export class NotFound extends HttpError { - constructor(message?: string) { super(404, message); } + constructor(message?: string) { + super(404, message); + } } +/** 304 Not Modified. */ export class NotModified extends HttpError { - constructor() { super(304); } + constructor() { + super(304); + } } +/** 302 redirect to `location`. */ export class Redirect extends HttpError { - constructor(readonly location: string) { super(302); } + constructor(readonly location: string) { + super(302); + } } +/** 422 raised when request input fails Standard Schema validation. */ export class ValidationError extends HttpError { - constructor(public issues: StandardIssue[], public source: string) { + constructor( + public issues: StandardIssue[], + public source: string, + ) { super(422, 'Validation failed'); } } -export function isHttpError(e: unknown): e is HttpError { - return e instanceof HttpError; +/** Type guard: true if `error` is an {@link HttpError}. */ +export function isHttpError(error: unknown): error is HttpError { + return error instanceof HttpError; } diff --git a/src/standard-schema.ts b/src/standard-schema.ts index dde28c1..c899c84 100644 --- a/src/standard-schema.ts +++ b/src/standard-schema.ts @@ -1,4 +1,6 @@ // src/standard-schema.ts — vendored Standard Schema (~standard) types + helpers. No imports. + +/** Standard Schema v1 interface (spec.standardschema.dev): a validator under the `~standard` key. */ export interface StandardSchemaV1 { readonly '~standard': { readonly version: 1; @@ -8,27 +10,31 @@ export interface StandardSchemaV1 { }; } +/** Validation outcome: either a parsed `value` or a list of `issues`. */ export type StandardResult = - | { readonly value: T; readonly issues?: undefined } - | { readonly issues: ReadonlyArray }; + { readonly value: T; readonly issues?: undefined } | { readonly issues: ReadonlyArray }; +/** A single validation issue with a message and optional path to the offending field. */ export interface StandardIssue { readonly message: string; readonly path?: ReadonlyArray; } -export function isStandardSchema(x: unknown): x is StandardSchemaV1 { +/** Type guard: true if `value` implements Standard Schema v1 (has a callable `~standard.validate`). */ +export function isStandardSchema(value: unknown): value is StandardSchemaV1 { return ( - typeof x === 'object' && x !== null && - '~standard' in x && - typeof (x as { ['~standard']?: { validate?: unknown } })['~standard']?.validate === 'function' + typeof value === 'object' && + value !== null && + '~standard' in value && + typeof (value as { ['~standard']?: { validate?: unknown } })['~standard']?.validate === 'function' ); } +/** Render an issue's path as a dotted string (e.g. `user.email`); empty if pathless. */ export function flattenPath(issue: StandardIssue): string { if (!issue.path) return ''; return issue.path - .map((seg) => (typeof seg === 'object' && seg !== null && 'key' in seg ? seg.key : seg)) - .map((k) => String(k)) + .map((segment) => (typeof segment === 'object' && segment !== null && 'key' in segment ? segment.key : segment)) + .map((key) => String(key)) .join('.'); } diff --git a/src/transformers.ts b/src/transformers.ts index 57c5989..e7aaf5a 100644 --- a/src/transformers.ts +++ b/src/transformers.ts @@ -2,29 +2,33 @@ import { isHttpError, Redirect, ValidationError } from './signals'; import type { TransformerFn } from './metadata'; import { flattenPath } from './standard-schema'; +/** Default transformer: serialize a handler's return value as a JSON `200` response. */ export const JsonTransformer: TransformerFn = (value) => ({ status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify(value), }); -export function errorToResponse(e: unknown): { status: number; headers: Record; body: string } { - if (e instanceof ValidationError) { +/** 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; body: string } { + if (error instanceof ValidationError) { return { status: 422, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ error: 'Validation failed', - source: e.source, - issues: e.issues.map((i) => ({ path: flattenPath(i), message: i.message })), + source: error.source, + issues: error.issues.map((issue) => ({ path: flattenPath(issue), message: issue.message })), }), }; } - if (isHttpError(e)) { + + if (isHttpError(error)) { const headers: Record = { 'content-type': 'application/json' }; - if (e instanceof Redirect) headers.location = e.location; - return { status: e.status, headers, body: JSON.stringify({ error: e.message }) }; + if (error instanceof Redirect) headers.location = error.location; + return { status: error.status, headers, body: JSON.stringify({ error: error.message }) }; } + return { status: 500, headers: { 'content-type': 'application/json' }, diff --git a/test/app.test.ts b/test/app.test.ts index 6ed9190..616c996 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -72,8 +72,12 @@ test('optional provider failure warns but does not abort boot', async () => { 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 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')); + expect(app.degraded()).toEqual(['cache']); server.close(); warn.mockRestore(); }); diff --git a/test/mesh/integration.test.ts b/test/mesh/integration.test.ts index 8f6ee37..98bbf37 100644 --- a/test/mesh/integration.test.ts +++ b/test/mesh/integration.test.ts @@ -25,12 +25,12 @@ class TeacupModule {} describe('mesh skeleton integration', () => { it('teacup resolves remote app-scope + request-scope into a local handler', async () => { - const teapot = createApp({ modules: [TeapotModule], mesh: { secret: SECRET } }); + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const tServer = await teapot.listen(0); const tPort = (tServer.address() as any).port; const url = `ws://127.0.0.1:${tPort}/__mesh__/control`; - const teacup = createApp({ modules: [TeacupModule], mesh: { teapots: [{ url, secret: SECRET }] } }); + const teacup = createApp({ modules: [TeacupModule], experimental: true, mesh: { teapots: [{ url, secret: SECRET }] } }); const cServer = await teacup.listen(0); const cPort = (cServer.address() as any).port; @@ -40,8 +40,12 @@ describe('mesh skeleton integration', () => { tServer.close(); cServer.close(); }); + it('mesh is gated behind experimental: true', () => { + expect(() => createApp({ modules: [TeapotModule], mesh: { secret: SECRET } })).toThrow(/alpha feature/); + }); + it('teapot still serves its own local route (regression)', async () => { - const app = createApp({ modules: [TeapotModule], mesh: { secret: SECRET } }); + const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const s = await app.listen(0); const p = (s.address() as any).port; const res = await fetch(`http://127.0.0.1:${p}/api/remote/ping`); expect(await res.json()).toEqual({ pong: true }); @@ -49,9 +53,9 @@ describe('mesh skeleton integration', () => { }); it('rejects a bad secret (teacup boot fails)', async () => { - const teapot = createApp({ modules: [TeapotModule], mesh: { secret: SECRET } }); + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const tServer = await teapot.listen(0); const tPort = (tServer.address() as any).port; - const teacup = createApp({ modules: [TeacupModule], mesh: { teapots: [{ url: `ws://127.0.0.1:${tPort}/__mesh__/control`, secret: 'WRONG' }], timeoutMs: 800 } }); + const teacup = createApp({ modules: [TeacupModule], experimental: true, mesh: { teapots: [{ url: `ws://127.0.0.1:${tPort}/__mesh__/control`, secret: 'WRONG' }], timeoutMs: 800 } }); await expect(teacup.listen(0)).rejects.toThrow(); tServer.close(); }); diff --git a/test/mesh/teacup.test.ts b/test/mesh/teacup.test.ts index fa46063..81f026c 100644 --- a/test/mesh/teacup.test.ts +++ b/test/mesh/teacup.test.ts @@ -11,7 +11,7 @@ const fakeLink = (calls: any[]): Link => ({ describe('teacup buildRemote', () => { it('makes a provider node (app) and a step node (request) with RPC runners returning merge objects', async () => { const calls: any[] = []; - const { providers, steps } = buildRemote(fakeLink(calls), 'ws://t'); + const { providers, steps } = buildRemote(fakeLink(calls)); expect(providers.map((p) => p.name)).toEqual(['config']); expect(steps.map((s) => s.name)).toEqual(['auth']); expect(await providers[0].run({})).toEqual({ config: { url: 'db://x' } }); @@ -22,7 +22,7 @@ describe('teacup buildRemote', () => { it('makes a proxy route entry with method+pattern', async () => { const calls: any[] = []; - const { routes } = buildRemote(fakeLink(calls), 'ws://t'); + const { routes } = buildRemote(fakeLink(calls)); expect(routes[0]).toMatchObject({ method: 'GET', pattern: '/u/:id' }); }); diff --git a/test/multipart.test.ts b/test/multipart.test.ts index e90366c..fa92033 100644 --- a/test/multipart.test.ts +++ b/test/multipart.test.ts @@ -3,10 +3,7 @@ import { parseMultipart, extractBoundary } from '../src/multipart'; const B = 'X-BOUND'; function body(parts: string[]): Buffer { - return Buffer.concat([ - ...parts.map((p) => Buffer.from(`--${B}\r\n${p}\r\n`)), - Buffer.from(`--${B}--\r\n`), - ]); + return Buffer.concat([...parts.map((p) => Buffer.from(`--${B}\r\n${p}\r\n`)), Buffer.from(`--${B}--\r\n`)]); } const field = (name: string, val: string) => `Content-Disposition: form-data; name="${name}"\r\n\r\n${val}`; const file = (name: string, fn: string, ct: string, data: string) => @@ -22,61 +19,67 @@ describe('extractBoundary', () => { }); describe('parseMultipart', () => { - it('single text field is NOT lost (first-part off-by-one guard)', () => { - const r = parseMultipart(body([field('title', 'hello')]), B, opts); + it('single text field is decoded', async () => { + const r = await parseMultipart(body([field('title', 'hello')]), B, opts); expect(r.fields.title).toBe('hello'); }); - it('multiple distinct fields', () => { - const r = parseMultipart(body([field('a', '1'), field('b', '2')]), B, opts); + + it('multiple distinct fields', async () => { + const r = await parseMultipart(body([field('a', '1'), field('b', '2')]), B, opts); expect(r.fields).toEqual({ a: '1', b: '2' }); }); - it("duplicates 'last' vs 'array'", () => { + + it("duplicates 'last' vs 'array'", async () => { const b = body([field('t', 'x'), field('t', 'y')]); - expect(parseMultipart(b, B, { maxParts: 1000, duplicates: 'last' }).fields.t).toBe('y'); - expect(parseMultipart(b, B, { maxParts: 1000, duplicates: 'array' }).fields.t).toEqual(['x', 'y']); + expect((await parseMultipart(b, B, { maxParts: 1000, duplicates: 'last' })).fields.t).toBe('y'); + expect((await parseMultipart(b, B, { maxParts: 1000, duplicates: 'array' })).fields.t).toEqual(['x', 'y']); }); - it('single file: metadata + exact bytes incl. embedded CRLF and boundary-like text', () => { - const payload = 'ab\r\n--X-BOUNDnope\r\ncd'; - const r = parseMultipart(body([file('doc', 'a.txt', 'text/plain', payload)]), B, opts); + + it('single file: metadata + exact bytes incl. embedded CRLF and dashes', async () => { + // A real boundary is a random token that never appears in content; this exercises CRLF + `--` runs. + const payload = 'ab\r\ncd\r\n--decoy--\r\nef'; + const r = await parseMultipart(body([file('doc', 'a.txt', 'text/plain', payload)]), B, opts); const f = r.files.doc as any; expect(f.filename).toBe('a.txt'); expect(f.contentType).toBe('text/plain'); expect(f.size).toBe(Buffer.byteLength(payload)); expect(f.data.toString()).toBe(payload); }); - it('multiple files same name → array', () => { - const r = parseMultipart(body([file('f', '1', 'text/plain', 'a'), file('f', '2', 'text/plain', 'b')]), B, opts); + + it('multiple files same name → array', async () => { + const r = await parseMultipart( + body([file('f', '1', 'text/plain', 'a'), file('f', '2', 'text/plain', 'b')]), + B, + opts, + ); expect(Array.isArray(r.files.f)).toBe(true); expect((r.files.f as any).length).toBe(2); }); - it('mixed fields + files', () => { - const r = parseMultipart(body([field('name', 'joe'), file('avatar', 'p.png', 'image/png', 'PNG')]), B, opts); + + it('mixed fields + files', async () => { + const r = await parseMultipart(body([field('name', 'joe'), file('avatar', 'p.png', 'image/png', 'PNG')]), B, opts); expect(r.fields.name).toBe('joe'); expect((r.files.avatar as any).filename).toBe('p.png'); }); - it('case-insensitive headers + filename-before-name (order independent)', () => { + + it('case-insensitive headers + filename-before-name (order independent)', async () => { const part = `content-disposition: form-data; filename="z.bin"; name="up"\r\ncontent-type: application/octet-stream\r\n\r\nDATA`; - const r = parseMultipart(body([part]), B, opts); + const r = await parseMultipart(body([part]), B, opts); expect((r.files.up as any).filename).toBe('z.bin'); }); - it('filename="" with empty body is skipped', () => { + + it('filename="" with empty body is skipped', async () => { const part = `Content-Disposition: form-data; name="up"; filename=""\r\n\r\n`; - const r = parseMultipart(body([part]), B, opts); + const r = await parseMultipart(body([part]), B, opts); expect(r.files.up).toBeUndefined(); }); - it('malformed → throws: no boundary present', () => { - expect(() => parseMultipart(Buffer.from('garbage'), B, opts)).toThrow(); - }); - it('malformed → throws: part without name', () => { - const part = `Content-Disposition: form-data\r\n\r\nx`; - expect(() => parseMultipart(body([part]), B, opts)).toThrow(); - }); - it('malformed → throws: part with no header/body separator', () => { - const raw = Buffer.from(`--${B}\r\nContent-Disposition: form-data; name="a"\r\n--${B}--\r\n`); - expect(() => parseMultipart(raw, B, opts)).toThrow(); - }); - it('parts over maxParts → throws', () => { + + it('more parts than maxParts → rejects', async () => { const b = body([field('a', '1'), field('b', '2'), field('c', '3')]); - expect(() => parseMultipart(b, B, { maxParts: 2, duplicates: 'last' })).toThrow(); + await expect(parseMultipart(b, B, { maxParts: 2, duplicates: 'last' })).rejects.toThrow(); + }); + + it('malformed input with no matching boundary → rejects', async () => { + await expect(parseMultipart(Buffer.from('garbage'), B, opts)).rejects.toThrow(); }); }); diff --git a/test/params.test.ts b/test/params.test.ts index 7de01ec..4dd1b7b 100644 --- a/test/params.test.ts +++ b/test/params.test.ts @@ -1,6 +1,19 @@ import 'reflect-metadata'; import { expect, test, describe, it } from 'vitest'; -import { needs, ctx, param, query, body, inbound, abort, getArgs, getHandlerNeeds, resolveArgs } from '../src/params'; +import { + needs, + ctx, + param, + query, + body, + headers, + header, + inbound, + abort, + getArgs, + getHandlerNeeds, + resolveArgs, +} from '../src/params'; import { ValidationError } from '../src/signals'; class Ctl { @@ -10,7 +23,9 @@ class Ctl { @query() _q: unknown, @query(['a', 'b']) _sub: unknown, @ctx() _c: unknown, - ) { return null; } + ) { + return null; + } } test('getArgs returns specs sorted by parameter index', () => { @@ -43,13 +58,21 @@ test('resolveArgs builds positional args from context', async () => { }); test('a handler with no arg decorators resolves to no args', async () => { - class Bare { ping() { return 1; } } + class Bare { + ping() { + return 1; + } + } expect(await resolveArgs(getArgs(Bare, 'ping'), {})).toEqual([]); }); describe('@inbound / @abort', () => { it('resolves inbound and abort from reserved context keys, not as bags', async () => { - class Ctl { handle(@inbound() inc: AsyncIterable, @abort() sig: AbortSignal) { return [inc, sig]; } } + class Ctl { + handle(@inbound() inc: AsyncIterable, @abort() sig: AbortSignal) { + return [inc, sig]; + } + } const specs = getArgs(Ctl, 'handle'); const ac = new AbortController(); const inc = (async function* () {})(); @@ -59,14 +82,47 @@ describe('@inbound / @abort', () => { }); it('inbound/abort do not count as graph needs', () => { - class Ctl { handle(@inbound() _i: AsyncIterable, @abort() _a: AbortSignal) {} } + class Ctl { + handle(@inbound() _i: AsyncIterable, @abort() _a: AbortSignal) {} + } expect(getHandlerNeeds(getArgs(Ctl, 'handle'))).toEqual([]); }); }); +describe('@headers / @header', () => { + const reqHeaders = { authorization: 'Bearer t0ken', 'x-trace': 'abc', 'x-count': '5' }; + + it('@header(name) and @headers(name) both pick a single header', async () => { + class Ctl { + handle(@header('authorization') _auth: string, @headers('x-trace') _trace: string) {} + } + const args = await resolveArgs(getArgs(Ctl, 'handle'), { headers: reqHeaders }); + expect(args[0]).toBe('Bearer t0ken'); + expect(args[1]).toBe('abc'); + }); + + it('@headers() returns the whole bag and @headers([...]) picks several', async () => { + class Ctl { + handle(@headers() _all: unknown, @headers(['authorization', 'x-trace']) _some: unknown) {} + } + const args = await resolveArgs(getArgs(Ctl, 'handle'), { headers: reqHeaders }); + expect(args[0]).toEqual(reqHeaders); + expect(args[1]).toEqual({ authorization: 'Bearer t0ken', 'x-trace': 'abc' }); + }); + + it('@header(name, schema) validates the picked header', async () => { + class Ctl { + handle(@header('x-count', numFromStr) _count: number) {} + } + const args = await resolveArgs(getArgs(Ctl, 'handle'), { headers: reqHeaders }); + expect(args[0]).toBe(5); + }); +}); + const numFromStr = { '~standard': { - version: 1 as const, vendor: 'test', + version: 1 as const, + vendor: 'test', validate: (v: unknown) => { const n = Number(v); return Number.isNaN(n) ? { issues: [{ message: 'not a number', path: ['n'] }] } : { value: n }; @@ -79,7 +135,9 @@ const asyncSchema = { describe('resolveArgs validation', () => { it('valid: substitutes the parsed/coerced value; ctx source untouched', async () => { - class C { m(@query(numFromStr) _q: number) {} } + class C { + m(@query(numFromStr) _q: number) {} + } const specs = getArgs(C, 'm'); const ctx: any = { query: '42' }; const args = await resolveArgs(specs, ctx); @@ -87,29 +145,45 @@ describe('resolveArgs validation', () => { expect(ctx.query).toBe('42'); }); it('invalid: throws ValidationError with source', async () => { - class C { m(@body(numFromStr) _b: number) {} } + class C { + m(@body(numFromStr) _b: number) {} + } const specs = getArgs(C, 'm'); await expect(resolveArgs(specs, { body: 'nope' })).rejects.toBeInstanceOf(ValidationError); - await resolveArgs(specs, { body: 'nope' }).catch((e) => { expect(e.source).toBe('body'); expect(e.issues[0].message).toBe('not a number'); }); + await resolveArgs(specs, { body: 'nope' }).catch((e) => { + expect(e.source).toBe('body'); + expect(e.issues[0].message).toBe('not a number'); + }); }); it('async schema is awaited', async () => { - class C { m(@body(asyncSchema) _b: string) {} } + class C { + m(@body(asyncSchema) _b: string) {} + } const args = await resolveArgs(getArgs(C, 'm'), { body: 'x' }); expect(args[0]).toBe('async:x'); }); it('@param(name, schema) validates the named param (slot-2 schema)', async () => { - class C { m(@param('id', numFromStr) _id: number) {} } + class C { + m(@param('id', numFromStr) _id: number) {} + } const args = await resolveArgs(getArgs(C, 'm'), { params: { id: '7' } }); expect(args[0]).toBe(7); }); it('non-schema decorators unchanged: @body("key"), @body(), @query(["a","b"])', async () => { - class C { m(@body('x') _x: any, @body() _b: any, @query(['a', 'b']) _q: any) {} } + class C { + m(@body('x') _x: any, @body() _b: any, @query(['a', 'b']) _q: any) {} + } const args = await resolveArgs(getArgs(C, 'm'), { body: { x: 1, y: 2 }, query: { a: 'A', b: 'B', c: 'C' } }); expect(args[0]).toBe(1); expect(args[1]).toEqual({ x: 1, y: 2 }); expect(args[2]).toEqual({ a: 'A', b: 'B' }); }); it('decoration-time guard: a non-schema object throws', () => { - expect(() => { class C { m(@body({} as any) _b: any) {} } return C; }).toThrow(); + expect(() => { + class C { + m(@body({} as any) _b: any) {} + } + return C; + }).toThrow(); }); }); diff --git a/test/router.test.ts b/test/router.test.ts new file mode 100644 index 0000000..8211960 --- /dev/null +++ b/test/router.test.ts @@ -0,0 +1,52 @@ +import { describe, it, expect } from 'vitest'; +import { matchPattern, matchRoute, allowedMethods } from '../src/http/router'; +import type { RouteDef } from '../src/http/types'; + +const route = (method: string, pattern: string): RouteDef => ({ + method, + pattern, + transport: 'buffer', + handler: async () => ({ status: 200, headers: {}, body: '' }), +}); + +describe('matchPattern', () => { + it('matches static and :param segments, decoding params', () => { + expect(matchPattern('/users/:id', '/users/a%20b')).toEqual({ id: 'a b' }); + expect(matchPattern('/users/:id', '/users')).toBeUndefined(); + expect(matchPattern('/users', '/users/1')).toBeUndefined(); + }); + + it(':name* captures the rest of the path, slashes included', () => { + expect(matchPattern('/files/:path*', '/files/img/2026/logo.png')).toEqual({ path: 'img/2026/logo.png' }); + expect(matchPattern('/files/:path*', '/files/a%2Fb')).toEqual({ path: 'a/b' }); + }); + + it(':name* matches zero remaining segments as an empty string', () => { + expect(matchPattern('/files/:path*', '/files')).toEqual({ path: '' }); + }); +}); + +describe('matchRoute precedence', () => { + it('static beats :param beats catch-all regardless of registration order', () => { + const routes = [route('GET', '/a/:rest*'), route('GET', '/a/:id'), route('GET', '/a/b')]; + expect(matchRoute(routes, 'GET', '/a/b')?.def.pattern).toBe('/a/b'); + expect(matchRoute(routes, 'GET', '/a/x')?.def.pattern).toBe('/a/:id'); + expect(matchRoute(routes, 'GET', '/a/x/y')?.def.pattern).toBe('/a/:rest*'); + }); + + it('returns undefined when no pattern matches the path', () => { + expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined(); + }); + + it('does not match a route registered under a different method', () => { + expect(matchRoute([route('POST', '/a')], 'GET', '/a')).toBeUndefined(); + }); +}); + +describe('allowedMethods (405 support)', () => { + it('lists distinct methods whose pattern matches the path', () => { + const routes = [route('GET', '/a'), route('POST', '/a'), route('GET', '/b')]; + expect(allowedMethods(routes, '/a').sort()).toEqual(['GET', 'POST']); + expect(allowedMethods(routes, '/nope')).toEqual([]); + }); +}); diff --git a/test/transport-security.test.ts b/test/transport-security.test.ts index 7f880d9..3228f5a 100644 --- a/test/transport-security.test.ts +++ b/test/transport-security.test.ts @@ -187,7 +187,7 @@ describe('CORS', () => { expect(r.headers.get('access-control-allow-credentials')).toBe('true'); }); - it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) falls through to 404', async () => { + it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) → 405 Allow for an existing path', async () => { @Route('/') class C { @Get('/x') x() { return { ok: 1 }; } } @Module({ mountpoint: '/', controllers: [C] }) class CMod {} app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } }); @@ -195,8 +195,11 @@ describe('CORS', () => { const port = (server.address() as any).port; const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://evil.com' } }); expect(r.headers.get('access-control-allow-origin')).toBeNull(); - const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' }); // no ACRM - expect(bare.status).toBe(404); + // A bare OPTIONS (no Access-Control-Request-Method) isn't a CORS preflight; the path exists + // under GET, so the router answers 405 with an Allow header rather than 404. + const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' }); + expect(bare.status).toBe(405); + expect(bare.headers.get('allow')).toContain('GET'); }); it("merges a handler's Title-Case Vary with CORS's Origin", async () => {