diff --git a/CHANGELOG.md b/CHANGELOG.md index 71eafdd..61d84f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,14 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. ## [Unreleased] -_Nothing yet._ +### Added +- **`app.fetch(request): Promise`** — a Web-Standards handler so the + same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API + (WebSocket and mesh remain Node-only). + +### Changed +- App-scope providers now boot exactly once (memoized): a second `app.listen()` + call no longer re-runs provider factories or their side effects. ## [26.7.0-beta.0] - 2026-07-07 diff --git a/src/app/index.ts b/src/app/index.ts index 6d1d966..d156c21 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -5,6 +5,8 @@ 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 type { HttpOptions } from '../http'; +import { buildFetch } from '../http/web'; import { isAsyncIterable } from '../channel'; import { JsonTransformer, type ErrorRenderer } from '../transformers'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; @@ -119,6 +121,33 @@ export function createApp(opts: { const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); + // Boots app-scope providers exactly once, however first triggered (app.fetch or listen()); calling + // both never double-boots (which would re-run provider factories and their side effects). + const bootAppProviders = makeProviderBooter( + registry, + opts.overrides, + () => orderedProviders, + { runners, container, providerMeta, bus }, + degradedProviders, + ); + + const fetchOpts: HttpOptions = { + limits: opts.limits, + tls: opts.tls, + trustProxy: opts.trustProxy, + security: opts.security ?? true, + cors: opts.cors, + bodyDuplicates: opts.bodyDuplicates, + onError: opts.onError, + }; + const fetchFn = buildAppFetch( + () => booted, + routePlans, + { providedSeed, planSteps, bus, onError: opts.onError }, + fetchOpts, + bootAppProviders, + ); + const listen = async (port: number): Promise => { const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; @@ -133,15 +162,7 @@ export function createApp(opts: { 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.`, - ); - } + await bootAppProviders(); const meshControl = buildMeshControl(opts.mesh, registry, { container, @@ -181,6 +202,7 @@ export function createApp(opts: { return { listen, close, + fetch: fetchFn, inspect, graph, toMermaid: () => toMermaid(graph()), @@ -450,6 +472,43 @@ async function bootProviders( return degraded; } +/** + * Returns a memoized boot function: applies overrides and boots app-scope providers exactly once, + * however first triggered — {@link buildAppFetch}'s handler or `listen()` may both call it, and the + * memoization guarantees only the first call actually runs (and warns about) the boot sequence. + */ +function makeProviderBooter( + registry: Registry, + overrides: Record | undefined, + getOrderedProviders: () => GraphNode[], + deps: { + runners: Map; + container: Container; + providerMeta: Map; + bus: Bus; + }, + degradedProviders: string[], +): () => Promise { + let bootPromise: Promise | undefined; + + const runBoot = async (): Promise => { + applyOverrides(overrides, registry); + degradedProviders.length = 0; + degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps))); + + 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.`, + ); + } + }; + + return (): Promise => { + if (!bootPromise) bootPromise = runBoot(); + return bootPromise; + }; +} + /** * 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. @@ -555,6 +614,35 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps return [...local, ...remoteRoutes]; } +/** + * Builds `app.fetch`: a Web-Standards handler over the same route table `listen()` uses, so + * `Deno.serve(app.fetch)` / `Bun.serve({ fetch: app.fetch })` work without ever calling `listen()`. + * Non-mesh apps finalize eagerly, so `getBooted()` is already `true` and the route table is built + * on the very first call. Mesh apps defer finalize to `listen()` (remote scopes must splice into the + * graph first): `getBooted` reads the outer `booted` flag *live* on every call — exactly like + * `explain()`/`graph()`/`inspect()` do — so the returned function throws until `listen()` finalizes, + * then starts working from the next call on, without ever needing to be rebuilt. + */ +function buildAppFetch( + getBooted: () => boolean, + routePlans: RoutePlan[], + deps: PipelineDeps, + fetchOpts: HttpOptions, + ensureBooted: () => Promise, +): (request: Request) => Promise { + let handler: ((request: Request) => Promise) | undefined; + + return async (request: Request): Promise => { + if (!handler) { + if (!getBooted()) throw new Error('fetch() unavailable before listen() for mesh apps'); + handler = buildFetch(buildHttpRoutes(routePlans, [], deps), fetchOpts); + } + + await ensureBooted(); // idempotent: no-op if listen() already booted the providers + return handler(request); + }; +} + /** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */ function devGraphRoute(graph: () => GraphView): RouteDef { return { diff --git a/src/app/types.ts b/src/app/types.ts index 12cbb4b..086146b 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -35,6 +35,8 @@ export interface Explain { export interface App { listen(port: number): Promise; close(): Promise; + /** Web-Standards handler: run a Fetch API Request through the graph and return a Response (Node/Deno/Bun/edge). WS not included. */ + fetch(request: Request): Promise; inspect(routePath: string): InspectLine[]; graph(): GraphView; toMermaid(): string; diff --git a/src/http/core.ts b/src/http/core.ts new file mode 100644 index 0000000..a6771bb --- /dev/null +++ b/src/http/core.ts @@ -0,0 +1,103 @@ +// src/http/core.ts — runtime-neutral request handling core, shared by the Node adapter and (later) app.fetch. +import { HttpError, NotFound } from '../signals'; +import { renderError } from '../transformers'; +import { isStreamResult, type PipelineResult } from '../pipeline'; +import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security'; +import { matchRoute, allowedMethods, parseQuery } from './router'; +import { pickEncoder } from './stream'; +import type { RouteDef, HttpOptions } from './types'; +import type { StreamEncoder } from '../encoders'; + +/** A runtime-neutral inbound request: body already parsed by the caller's ingress (Node stream, fetch Request, …). */ +export interface NeutralRequest { + method: string; + url: string; // path + query, e.g. "/users/9?x=1" + headers: Record; + body: unknown; // already-parsed body + secure: boolean; + ip: string; +} + +/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */ +export type NeutralOutcome = + | { kind: 'buffered'; status: number; headers: Record; body: string | Buffer } + | { kind: 'stream'; headers: Record; stream: AsyncIterable; encoder: StreamEncoder }; + +/** {@link handle}'s result for a normal (non-preflight) request. */ +export interface HandleResult { + injected: Record; + outcome: NeutralOutcome; +} + +/** {@link handle}'s result for a CORS preflight: the caller must answer with 204 + these headers. */ +export interface Preflight { + preflight: Record; +} + +/** + * Computes the security + CORS headers that get injected into every response for a request — the same + * authoritative set {@link handle} applies to its outcomes. Shared with `buildFetch` (src/http/web.ts) + * so early-failure responses (413/400/501, before a route even matches) carry the same headers Node's + * `patchResponseHeaders` would have installed up-front. + */ +export function computeInjected( + opts: HttpOptions | undefined, + req: { secure: boolean; headers: Record }, +): Record { + const injected: Record = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) }; + if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); + return injected; +} + +/** + * Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405, + * route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the + * caller (a Node adapter, a fetch adapter, …) reads/writes the actual request/response. + */ +export async function handle( + routes: RouteDef[], + opts: HttpOptions | undefined, + req: NeutralRequest, +): Promise { + const path = req.url.split('?')[0]; + const injected = computeInjected(opts, req); + + if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { + return { preflight: corsPreflightHeaders(opts.cors, req) }; + } + + const matched = matchRoute(routes, req.method, path); + + if (!matched) { + // Path matches a route under a different method → 405 with Allow; otherwise 404. + const allow = allowedMethods(routes, path); + const err = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found'); + const rendered = renderError(err, { method: req.method, url: req.url, headers: req.headers }, opts?.onError); + const headers = allow.length ? { ...rendered.headers, allow: allow.join(', ') } : rendered.headers; + return { injected, outcome: { kind: 'buffered', status: rendered.status, headers, body: rendered.body } }; + } + + let result: PipelineResult; + + try { + result = await matched.def.handler({ + method: req.method, + url: req.url, + headers: req.headers, + params: matched.params, + query: parseQuery(req.url), + body: req.body, + protocol: req.secure ? 'https' : 'http', + ip: req.ip, + }); + } catch (error) { + result = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError); + } + + if (isStreamResult(result)) { + const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? '')); + return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } }; + } + + return { injected, outcome: { kind: 'buffered', status: result.status, headers: result.headers, body: result.body } }; +} diff --git a/src/http/headers.ts b/src/http/headers.ts new file mode 100644 index 0000000..d9fb64e --- /dev/null +++ b/src/http/headers.ts @@ -0,0 +1,32 @@ +import { mergeVary } from '../security'; + +/** + * Merges a handler's response headers with authoritative `injected` headers + * (security + CORS). Injected keys win case-insensitively; `vary` is merged. + * Extracted from the Node writeHead patch so app.fetch shares the exact logic. + */ +export function mergeInjectedHeaders( + handlerHeaders: Record | undefined, + injected: Record, +): Record { + 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; + } + + 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; + return merged; +} diff --git a/src/http/server.ts b/src/http/server.ts index 719d8ff..27ec76a 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -1,15 +1,16 @@ import http from 'http'; import https from 'https'; -import { renderError, type ErrorRequest, type ErrorRenderer } from '../transformers'; -import { isHttpError, HttpError, NotFound } from '../signals'; -import { isStreamResult, type PipelineResult, type ResponseShape } from '../pipeline'; +import { renderError, type ErrorRequest } from '../transformers'; +import { isHttpError, HttpError } from '../signals'; import type { Bus } from '../bus'; -import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from '../security'; +import { buildSecurityHeaders, resolveCors } from '../security'; import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart'; -import { matchRoute, allowedMethods, parseQuery } from './router'; +import { matchRoute } from './router'; import { readBody, deriveSecure, deriveIp } from './request'; -import { pickEncoder, pipeStream } from './stream'; +import { pipeStream } from './stream'; import { attachWs } from './ws'; +import { mergeInjectedHeaders } from './headers'; +import { handle } from './core'; import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types'; interface HandlerConfig { @@ -28,19 +29,6 @@ function errorRequest(req: http.IncomingMessage): ErrorRequest { return { method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers }; } -/** Renders an error (through the optional user hook) and writes it, merging any extra headers (e.g. `Allow`). */ -function sendError( - res: http.ServerResponse, - error: unknown, - req: http.IncomingMessage, - onError?: ErrorRenderer, - extraHeaders?: Record, -): void { - const rendered = renderError(error, errorRequest(req), onError); - res.writeHead(rendered.status, extraHeaders ? { ...rendered.headers, ...extraHeaders } : rendered.headers); - res.end(rendered.body); -} - /** * Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades. * @param routes HTTP route definitions. @@ -71,13 +59,20 @@ export function createHttpServer( return server; } -/** Builds the request listener: security/CORS headers, routing, body parsing, then buffered or streamed response. */ +/** + * Builds the request listener: a thin Node adapter around the runtime-neutral {@link handle} core. + * Reads the body (Node-specific), delegates security/CORS/routing/error-rendering to `handle()`, + * then writes the result to `res` (buffered or streamed). The security-header monkeypatch is + * installed here — and stays the single source of truth for merging headers into every response — + * so `handle()`'s own `injected` is intentionally unused by this adapter. + */ 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]; + const method = req.method ?? 'GET'; // 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); @@ -88,61 +83,47 @@ function createRequestHandler(cfg: HandlerConfig) { // 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)); + // Mirror handle()'s own preflight/route-match decision here, so we only read the body + // (below) for a request that actually reaches a route handler — matching prior behaviour. + const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']); + const matched = isPreflight ? undefined : matchRoute(routes, method, path); + + let body: unknown; + + if (matched) { + 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; + } + + body = acquired.body; + } + + const result = await handle(routes, opts, { + method, + url, + headers: req.headers, + body, + secure, + ip: deriveIp(req, trustProxy), + }); + + if ('preflight' in result) { + res.writeHead(204, result.preflight); 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) { - sendError(res, new HttpError(405, 'Method Not Allowed'), req, opts?.onError, { allow: allow.join(', ') }); - return; - } - - sendError(res, new NotFound('Not Found'), req, opts?.onError); + if (result.outcome.kind === 'stream') { + await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, matched?.def.pattern, opts?.streams); 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 = renderError(error, errorRequest(req), opts?.onError); - } - - 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); + res.writeHead(result.outcome.status, result.outcome.headers); + res.end(result.outcome.body); }; } @@ -185,27 +166,8 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record { - // 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 + const merged = mergeInjectedHeaders(handlerHeaders, injected); return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged); }; } @@ -217,7 +179,7 @@ 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( +export async function parseRequestBody( buf: Buffer | undefined, contentType: string, duplicates: 'array' | 'last', diff --git a/src/http/web.ts b/src/http/web.ts new file mode 100644 index 0000000..c0f5e97 --- /dev/null +++ b/src/http/web.ts @@ -0,0 +1,165 @@ +import type { StreamEncoder } from '../encoders'; +import { handle, computeInjected, type HandleResult } from './core'; +import { mergeInjectedHeaders } from './headers'; +import { parseRequestBody } from './server'; +import { matchRoute } from './router'; +import { HttpError } from '../signals'; +import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers'; +import type { RouteDef, HttpOptions, MatchedRoute } from './types'; + +/** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */ +export function asReadableStream(source: AsyncIterable, encoder: StreamEncoder): ReadableStream { + const iterator = source[Symbol.asyncIterator](); + const te = new TextEncoder(); + return new ReadableStream({ + async pull(controller) { + try { + const { value, done } = await iterator.next(); + + if (done) { + controller.close(); + return; + } + + const encoded = encoder.encode(value); + const bytes = typeof encoded === 'string' ? te.encode(encoded) : encoded; + controller.enqueue(bytes); + } catch (err) { + controller.error(err); + } + }, + async cancel() { + await iterator.return?.(); + }, + }); +} + +/** Converts a web `Headers` into the plain record shape the neutral core and body parser expect. */ +function headersToRecord(headers: Headers): Record { + const out: Record = {}; + headers.forEach((value, key) => { + out[key] = value; + }); + return out; +} + +/** + * Turns a rendered error (or any {status, headers, body}) into a web `Response`, merging in the + * authoritative `injected` security/CORS headers — mirrors the Node adapter, where + * `patchResponseHeaders` installs these before body acquisition even runs, so early failures + * (413/400/501) carry them too. + */ +function errorResponse(rendered: ErrorResponse, injected: Record): Response { + const headers = mergeInjectedHeaders(rendered.headers, injected); + return new Response(rendered.body, { status: rendered.status, headers }); +} + +/** + * Reads and parses a matched request's body (enforcing `maxBodyBytes` → 413), mirroring the Node + * adapter's `acquireBody`. Returns `{ body }` on success, or a ready-to-send `{ response }` on failure. + */ +async function acquireFetchBody( + request: Request, + matched: MatchedRoute, + headers: Record, + path: string, + maxBody: number, + opts: HttpOptions | undefined, + injected: Record, +): Promise<{ body: unknown } | { response: Response }> { + const errReq: ErrorRequest = { method: request.method, url: path, headers }; + let buf: Buffer | undefined; + + if (request.body) { + const arrayBuffer = await request.arrayBuffer(); + const bodyLimit = matched.def.maxBodyBytes ?? maxBody; + + if (arrayBuffer.byteLength > bodyLimit) { + return { + response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError), injected), + }; + } + + buf = arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer); + } + + const contentType = headers['content-type'] ?? ''; + const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last'; + const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000; + const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts); + + if ('error' in parsed) { + return { + response: errorResponse( + renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError), + injected, + ), + }; + } + + return { body: parsed.body }; +} + +/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */ +function outcomeToResponse(result: HandleResult): Response { + const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record; + + if (result.outcome.kind === 'stream') { + return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers }); + } + + return new Response(result.outcome.body, { status: result.outcome.status, headers }); +} + +/** + * Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses: + * reads the body (enforcing `maxBodyBytes` → 413), parses it by content type, runs it through the + * runtime-neutral {@link handle}, and converts the outcome to a `Response` (buffered or streamed). + */ +export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { + const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000; + + return async (request: Request): Promise => { + const url = new URL(request.url); + const path = url.pathname + url.search; + const headers = headersToRecord(request.headers); + const matched = matchRoute(routes, request.method, url.pathname); + const secure = url.protocol === 'https:'; + // Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501, + // before a route handler even runs) carry the same security/CORS headers Node's writeHead patch + // would have installed before body acquisition. + const injected = computeInjected(opts, { secure, headers }); + let body: unknown; + + if (matched) { + const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts, injected); + if ('response' in acquired) return acquired.response; + body = acquired.body; + } + + const result = await handle(routes, opts, { + method: request.method, + url: path, + headers, + body, + secure, + // Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is + // trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket + // peer address to fall back to on the fetch path, so the untrusted case is simply ''. + ip: opts?.trustProxy + ? String(headers['x-forwarded-for'] ?? '') + .split(',')[0] + .trim() + : '', + }); + + // Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and + // so picks up the same authoritative security headers `injected` carries (Node's writeHead patch + // merges every response — including the 204 preflight — with `injected`; this adapter must too). + if ('preflight' in result) { + return new Response(null, { status: 204, headers: mergeInjectedHeaders(result.preflight, injected) }); + } + + return outcomeToResponse(result); + }; +} diff --git a/test/fetch.test.ts b/test/fetch.test.ts new file mode 100644 index 0000000..1d0373b --- /dev/null +++ b/test/fetch.test.ts @@ -0,0 +1,128 @@ +import { describe, it, expect } from 'vitest'; +import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index'; + +@Provider({ provides: 'store' }) +class Store { + provide() { + return { store: { hi: 'ok' } }; + } +} +@Route('/api') +class Ctl { + @Get('/hello') hello(@needs('store') s: any) { + return { store: s.hi }; + } + @Post('/echo') echo(@body() b: any) { + return { got: b }; + } + @Post('/tiny', { maxBodyBytes: 10 }) tiny(@body() b: any) { + return { got: b }; + } +} +@Module({ mountpoint: '/', providers: [Store], controllers: [Ctl] }) +class M {} +const app = createApp({ modules: [M] }); + +@Route('/mesh') +class MeshCtl { + @Get('/ping') ping() { + return { pong: true }; + } +} +@Module({ mountpoint: '/api', controllers: [MeshCtl] }) +class MeshModule {} + +describe('app.fetch', () => { + it('handles GET and returns JSON 200', async () => { + const res = await app.fetch(new Request('http://x/api/hello')); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ store: 'ok' }); + }); + it('parses a POST body', async () => { + const res = await app.fetch( + new Request('http://x/api/echo', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ a: 1 }), + }), + ); + expect(await res.json()).toEqual({ got: { a: 1 } }); + }); + it('404s an unknown route', async () => { + const res = await app.fetch(new Request('http://x/nope')); + expect(res.status).toBe(404); + }); + it('sets secure-by-default headers', async () => { + const res = await app.fetch(new Request('http://x/api/hello')); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + }); + + it('a 413 (oversized body) still carries the injected security headers', async () => { + const res = await app.fetch( + new Request('http://x/api/tiny', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ x: 'well over ten bytes' }), + }), + ); + expect(res.status).toBe(413); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + expect(res.headers.get('x-frame-options')).toBe('SAMEORIGIN'); + }); + + it('a 400 (invalid JSON) still carries the injected security headers', async () => { + const res = await app.fetch( + new Request('http://x/api/echo', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: '{not json', + }), + ); + expect(res.status).toBe(400); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + }); +}); + +@Route('/ip') +class IpCtl { + @Get('/whoami') whoami(@ctx() c: any) { + return { ip: c.ip }; + } +} +@Module({ mountpoint: '/', controllers: [IpCtl] }) +class IpModule {} + +describe('app.fetch trustProxy gates x-forwarded-for', () => { + it('honors x-forwarded-for (first hop) when trustProxy is true', async () => { + const trustingApp = createApp({ modules: [IpModule], trustProxy: true }); + const res = await trustingApp.fetch( + new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9, 1.1.1.1' } }), + ); + expect(await res.json()).toEqual({ ip: '9.9.9.9' }); + }); + + it('ignores x-forwarded-for when trustProxy is off (default)', async () => { + const untrustingApp = createApp({ modules: [IpModule] }); + const res = await untrustingApp.fetch( + new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9, 1.1.1.1' } }), + ); + expect(await res.json()).toEqual({ ip: '' }); + }); +}); + +describe('app.fetch mesh gating (live `booted` read)', () => { + it('throws before listen() and starts working after listen() finalizes', async () => { + const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } }); + + await expect(meshApp.fetch(new Request('http://x/api/mesh/ping'))).rejects.toThrow(/unavailable before listen/); + + const server = await meshApp.listen(0); + try { + const res = await meshApp.fetch(new Request('http://x/api/mesh/ping')); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ pong: true }); + } finally { + server.close(); + } + }); +}); diff --git a/test/http-headers.test.ts b/test/http-headers.test.ts new file mode 100644 index 0000000..ac12196 --- /dev/null +++ b/test/http-headers.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from 'vitest'; +import { mergeInjectedHeaders } from '../src/http/headers'; + +describe('mergeInjectedHeaders', () => { + it('makes injected keys authoritative regardless of handler casing', () => { + const out = mergeInjectedHeaders( + { 'Content-Type': 'text/html', 'X-Content-Type-Options': 'sniffme' }, + { 'x-content-type-options': 'nosniff' }, + ); + expect(out['x-content-type-options']).toBe('nosniff'); + expect(Object.keys(out).filter((k) => k.toLowerCase() === 'x-content-type-options')).toHaveLength(1); + expect(out['Content-Type']).toBe('text/html'); // untouched handler header kept + }); + + it('merges Vary from handler and injected', () => { + const out = mergeInjectedHeaders({ Vary: 'Accept' }, { vary: 'Origin' }); + expect(out['vary'].toLowerCase()).toContain('accept'); + expect(out['vary'].toLowerCase()).toContain('origin'); + }); + + it('preserves handler Vary when no injected Vary', () => { + const out = mergeInjectedHeaders({ Vary: 'Accept' }, {}); + expect(out['vary']).toBe('Accept'); + }); +}); diff --git a/test/parity.test.ts b/test/parity.test.ts new file mode 100644 index 0000000..c880a20 --- /dev/null +++ b/test/parity.test.ts @@ -0,0 +1,86 @@ +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import type { Server } from 'http'; +import { createApp, Provider, Route, Get, Post, Module, needs, body, Sse } from '../src/index'; + +@Provider({ provides: 'db' }) +class Db { + provide() { + return { db: { v: 42 } }; + } +} +@Route('/api') +class Ctl { + @Get('/x') x(@needs('db') d: any) { + return { v: d.v }; + } + @Post('/y') y(@body() b: any) { + return { echo: b }; + } + @Sse('/s') s() { + return (async function* () { + yield { n: 1 }; + yield { n: 2 }; + })(); + } +} +@Module({ mountpoint: '/', providers: [Db], controllers: [Ctl] }) +class M {} +const app = createApp({ modules: [M], cors: { origins: ['https://a.test'], credentials: false } }); + +// `app.listen` returns a Promise, so it's acquired in `beforeAll` rather than via a top-level +// `await` — this repo's tsconfig (module: commonjs, target: es2017) doesn't support top-level await. +let server: Server; +let base: string; + +beforeAll(async () => { + server = await app.listen(0); + const port = (server.address() as any).port; + base = `http://127.0.0.1:${port}`; +}); +afterAll(() => server.close()); + +const norm = (h: Headers) => { + const o: Record = {}; + h.forEach((v, k) => { + if (k !== 'date' && k !== 'connection' && k !== 'keep-alive' && k !== 'content-length' && k !== 'transfer-encoding') + o[k] = v; + }); + return o; +}; + +async function both(path: string, init?: RequestInit) { + const node = await fetch(base + path, init); + const web = await app.fetch(new Request(base + path, init)); + return { node, web }; +} + +describe('Node vs app.fetch parity (Node is truth)', () => { + it('GET /api/x', async () => { + const { node, web } = await both('/api/x'); + expect(web.status).toBe(node.status); + expect(norm(web.headers)).toEqual(norm(node.headers)); + expect(await web.json()).toEqual(await node.json()); + }); + it('POST /api/y', async () => { + const init = { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ a: 1 }) }; + const { node, web } = await both('/api/y', init); + expect(web.status).toBe(node.status); + expect(await web.json()).toEqual(await node.json()); + }); + it('404', async () => { + const { node, web } = await both('/missing'); + expect(web.status).toBe(node.status); + expect(norm(web.headers)).toEqual(norm(node.headers)); + }); + it('CORS preflight', async () => { + const init = { method: 'OPTIONS', headers: { origin: 'https://a.test', 'access-control-request-method': 'GET' } }; + const { node, web } = await both('/api/x', init); + expect(web.status).toBe(node.status); + expect(norm(web.headers)).toEqual(norm(node.headers)); + }); + it('SSE first two events', async () => { + const nodeText = await (await fetch(base + '/api/s')).text(); + const webText = await (await app.fetch(new Request(base + '/api/s'))).text(); + expect(webText).toBe(nodeText); + }); +}); diff --git a/test/web-stream.test.ts b/test/web-stream.test.ts new file mode 100644 index 0000000..ad21768 --- /dev/null +++ b/test/web-stream.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from 'vitest'; +import { asReadableStream } from '../src/http/web'; +import { sseEncoder } from '../src/encoders'; + +async function* nums() { yield { n: 1 }; yield { n: 2 }; } + +describe('asReadableStream', () => { + it('encodes each yielded value with the encoder', async () => { + const rs = asReadableStream(nums(), sseEncoder); + const text = await new Response(rs).text(); + expect(text).toContain('data: {"n":1}'); + expect(text).toContain('data: {"n":2}'); + }); + + it('cancels the source iterator when the stream is cancelled', async () => { + let returned = false; + async function* forever() { try { while (true) yield { t: 1 }; } finally { returned = true; } } + const rs = asReadableStream(forever(), sseEncoder); + const reader = rs.getReader(); + await reader.read(); + await reader.cancel(); + await new Promise((r) => setTimeout(r, 10)); + expect(returned).toBe(true); + }); +}); diff --git a/website/astro.config.mjs b/website/astro.config.mjs index ea69358..db488a6 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -41,6 +41,7 @@ export default defineConfig({ { label: 'Plugins & observability', slug: 'guides/plugins' }, { label: 'Graph introspection', slug: 'guides/introspection' }, { label: 'OpenAPI', slug: 'guides/openapi' }, + { label: 'Runtimes', slug: 'guides/runtimes' }, { label: 'Testing', slug: 'guides/testing' }, { label: 'Mesh (alpha)', slug: 'guides/mesh', badge: { text: 'alpha', variant: 'caution' } }, ], diff --git a/website/src/content/docs/guides/runtimes.md b/website/src/content/docs/guides/runtimes.md new file mode 100644 index 0000000..0136f73 --- /dev/null +++ b/website/src/content/docs/guides/runtimes.md @@ -0,0 +1,34 @@ +--- +title: Runtimes (Node, Deno, Bun, edge) +description: "Run Green Tea anywhere with app.fetch — the Web-Standards handler." +--- + +Green Tea exposes a Web-Standards handler, `app.fetch(request): Promise`, so the +same app runs on any runtime that speaks the Fetch API — for **HTTP and SSE** today. + +```ts +const app = createApp({ modules: [ApiModule] }); + +// Node (native listener, TLS, timeouts) +app.listen(3000); + +// Deno +Deno.serve(app.fetch); + +// Bun +Bun.serve({ fetch: app.fetch }); + +// Cloudflare / edge +export default { fetch: app.fetch }; +``` + +**Node is the reference implementation** — every runtime returns the same status, headers, +and body for the same request (enforced by a parity test suite). + +**Not yet on non-Node runtimes:** WebSocket (`@Ws`) and mesh — Node-only for now; cross-runtime +WebSocket is on the roadmap. `app.listen()` and TLS are Node-only; on Deno/Bun/edge you get +`app.fetch`. + +**Body-size enforcement differs slightly:** on `app.fetch`, an oversized body is read in full +before the `413` is returned, whereas Node aborts mid-stream once the limit is hit — so on +non-Node runtimes, also bound request size at the platform/runtime layer.