docs(readme): tell the truth about runtimes, transport, and where the docs live

The README claimed green-tea was Node-only with Deno/Bun/edge "on the
roadmap, not built" — all four have shipped. It also taught that a plain
return of an AsyncIterable streams by Accept, which the explicit-transport
change turned into a 500 TransportMismatchError: the one thing a README
must never do is document behavior that now throws.

docs/ had been frozen since the Starlight site replaced it; nothing but
the README referenced those two files, so they were a second copy to keep
in sync and had already drifted. Point at the site instead.

Also adds what shipped unmentioned (@Html/views/static, the four runtimes,
matcha) and fixes the CHANGELOG's YY.MM.PATCH, which contradicted the
README's correct explanation of why the month is not zero-padded.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-17 09:14:13 -05:00
1 parent 502b2c6b72
commit 0541464093
4 files changed
+18 -647

No files matched your search

+2 -1
View File
@@ -3,7 +3,8 @@
All notable changes to `@green-tea/core` are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
green-tea uses calendar versioning: `YY.MM.PATCH`.
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
npm treats versions as semver and semver forbids leading zeros.
## [Unreleased]
+16 -9
View File
@@ -35,7 +35,8 @@ Less to hold in your head. That's the tea.
- **The pipeline is a graph, not a chain.** You never write "put this before that." You declare `needs`/`provides` and green-tea topologically sorts it. *Why it matters:* no ordering bugs, no positional guesswork, and each route runs only its slice of the graph (an auth step doesn't run on public routes).
- **The type is the contract.** What a handler reads from the context *is* its dependency list. In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. *Why it matters:* whole classes of "it was undefined in prod" disappear at compile time.
- **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram; `app.openapi()` projects the same metadata into an OpenAPI 3.1 spec. *Why it matters:* onboarding, debugging, audits, and API docs are reading, not archaeology. (NestJS puts the graph behind a paid Devtools plan.)
- **One primitive for real-time.** Return an `AsyncIterable` and the transport streams it — SSE, ndjson, or a WebSocket duplex — with backpressure and cleanup handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
- **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
- **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`app.listen` → `serveDeno` / `serveBun` / `edgeHandler`) and nothing else. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
@@ -50,14 +51,15 @@ green-tea has one model: an **`AsyncIterable`**. A handler that returns a sequen
| `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) |
| `@Ws` | duplex | WebSocket | chat, collaboration — anything two-way |
| `@Stream` | negotiated | SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` | one handler, the client chooses |
| *(plain return)* | server → client | SSE or ndjson by `Accept` | programmatic streaming over `fetch` |
The primitive never changes — it's always an `AsyncIterable`. What changes is **direction and framing**, and you declare which. That's the difference between each iterable green-tea hands you:
- **`@Sse` / plain return** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line.
- **`@Sse`** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line.
- **`@Ws` (duplex)** — **two** iterables. `@inbound()` gives you the client's *incoming* messages to consume; the one you **return** is the *outbound* stream to the client. `@abort()` hands you an `AbortSignal` for teardown.
- **`@Stream`** — you write the handler once; the client's request decides whether it arrives as SSE, ndjson, or a WebSocket. No branching in your code.
**Your wire contract is what you declared, never what you happened to return.** A buffered route that returns an iterable, or a streaming route that returns a plain value, fails loudly with a `TransportMismatchError` — green-tea will not quietly switch a route's transport because of a return type. Refactoring a handler's internals can't change how it talks to the client.
Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it.
```typescript
@@ -91,6 +93,7 @@ Beta shipped the parts a real API needs, without growing the runtime dependency
- **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed.
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
- **Graceful shutdown.** `app.close()` drains in-flight requests, closes live streams and mesh links.
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
@@ -117,6 +120,7 @@ Every framework here can serve `/users/:id`. The difference shows up as the app
| **Real-time** | bolt on `ws`/`sse` libs | plugins | separate Gateway + adapter | separate engine | **return an `AsyncIterable`** — SSE, ndjson & WebSocket, one primitive |
| **Cross-service calls** | HTTP client / gRPC by hand | HTTP client / gRPC | Microservices transport + message patterns | — | **`@needs('x')` resolves on another node** |
| **Plugin can break your pipeline?** | yes (deletes your body parser) | encapsulated, but hooks are global | interceptor order matters | yes | **no** — plugins only `bus.on` + `scope.add` |
| **Runs on** | Node | Node | Node | Node | **Node · Deno · Bun · edge** — same code, swap the entry point |
| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws`, `busboy` optional) |
### Read it as a story
@@ -220,21 +224,22 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**Bring your own auth (and friends).** green-tea ships transport security — TLS/wss, secure-by-default headers, CORS — but **not** authentication, authorization, rate-limiting, CSRF, or sessions. You compose those as steps and plugins (the `Authenticate` step in the quick look is the pattern). Unlike Express/Fastify, there is no off-the-shelf plugin ecosystem for them yet.
**Node only.** Runs on Node ≥ 18. Deno / Bun / edge runtimes (over web-standard `Request`/`Response`) are on the roadmap, not built — only `src/http/` is runtime-specific today.
**Runtimes differ in what they can offer.** Node ≥ 18, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag.
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
## Docs & development
- **[Quickstart](./docs/quickstart.md)** — install + concrete examples (routes/DI, `flow`, validation, uploads, SSE, WebSocket, mesh, plugins).
- **[Architecture](./docs/architecture.md)** — the mental map (layers, request lifecycle, mesh) as diagrams.
- **[docs.green-tea.dev](https://docs.green-tea.dev)** — getting started, concepts (the graph, `flow`), and guides: routing, DI, validation, uploads, streaming, HTML, security, errors, introspection, OpenAPI, plugins, mesh, runtimes, testing.
- **[matcha](https://github.com/Expressive-Tea/matcha)** — the CLI. `matcha new` scaffolds a project (Node, Deno, or Bun), `matcha create` generates and auto-wires controllers/steps/providers/modules, `matcha run` detects your runtime and watches. A standalone Rust binary — no JS runtime needed to install it.
```bash
npm install
npm test # vitest
npm test # vitest (Node); test:deno / test:bun / test:edge for the other runtimes
npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test)
npm run build # emit dist/
npm run build # emit dist/ (tsup: dual ESM + CJS)
npm run bench # regenerate BENCHMARKS.md
npm run docs:dev # the documentation site (website/)
```
## Roadmap
@@ -244,7 +249,9 @@ npm run bench # regenerate BENCHMARKS.md
- ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel, with backpressure and cleanup.
- ✅ **graph introspection** — `explain` / `graph` / `toMermaid` / `GET /__graph__`.
- ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices.
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), runtime adapters (Deno / Bun / edge over web-standard `Request`/`Response`), official plugins.
- ✅ **runs everywhere** — Node, Deno, Bun, and Cloudflare Workers over web-standard `Request`/`Response`, with identical WebSocket behaviour on all four.
- ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving.
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), official plugins, router regex constraints and a radix-tree matcher.
## Versioning
-115
View File
@@ -1,115 +0,0 @@
# green-tea — Architecture
> The request and boot are an explicit **dependency graph**, not a mutable middleware chain.
> You declare *what* you need; the framework computes the order. The graph can extend in
> **time** (streams) and across **machines** (mesh).
## The four layers
```mermaid
flowchart TB
subgraph L3["#3 MESH — the graph crosses machines"]
direction LR
teacup["teacup (consumer)"] -- "WS RPC" --> teapot["teapot (host)"]
end
subgraph L2["#2 STREAMS — the graph emits over time"]
sse["SSE / ndjson"]:::n
ws["WebSocket duplex"]:::n
end
subgraph L15["#1.5 ARG DECORATORS — the handler declares its deps"]
sig["handler signature = dependency declaration"]:::n
end
subgraph L1["#1 CORE — graph DI + boot + router + pipeline + flow"]
core["Providers · Steps · Routes · Transformers · Container · Bus"]:::n
end
L3 --> L2 --> L15 --> L1
classDef n fill:#f6f8fa,stroke:#aaa;
```
## Building blocks
```mermaid
flowchart LR
Provider["@Provider\n(app scope · singleton)"]:::p
Step["@Step\n(request scope · per call)"]:::s
Route["@Route + @Get/@Post/@Sse/@Ws/@Stream"]:::r
Transformer["@Transformer\nvalue → ResponseShape"]:::t
Container["Container.resolve()\nasync · transport-agnostic"]:::c
Bus["Bus\nlifecycle events"]:::b
Provider --> Container
Step --> Container
Route --> Transformer
Container -. "remote binding (mesh)" .-> Provider
classDef p fill:#e7f5ff,stroke:#4dabf7;
classDef s fill:#fff3bf,stroke:#f59f00;
classDef r fill:#ebfbee,stroke:#40c057;
classDef t fill:#f3f0ff,stroke:#7950f2;
classDef c fill:#fff0f6,stroke:#e64980;
classDef b fill:#f1f3f5,stroke:#868e96;
```
## Request lifecycle
```mermaid
sequenceDiagram
participant C as Client
participant H as http.ts (transport)
participant P as Pipeline
participant G as Graph (providers/steps)
participant T as Transformer
C->>H: HTTP request
H->>H: matchRoute(method, path)
H->>P: runPipeline(seed = req envelope)
P->>G: providers (cached) + steps (topo order)
Note over G: each step merges into ctx;<br/>throw = short-circuit, return = continue
P->>P: handler(args resolved from ctx)
alt returns a value
P->>T: transformer → {status, headers, body}
T-->>C: buffered response
else returns an AsyncIterable
P-->>C: stream (SSE / ndjson / WS), backpressure + cleanup
else @needs a remote token
G-->>C: RPC to teapot, value spliced into ctx
end
```
## The unifying rule
```mermaid
flowchart TD
Q{"what does the handler return /\nwhere does a token live?"}
Q -->|"a value"| A["buffered (transformer → JSON)"]
Q -->|"an AsyncIterable"| B["stream (SSE / WS)"]
Q -->|"a token with no local provider"| D["RPC to a teapot (mesh)"]
```
One question — *"what produces this token and where does it live?"* — answers local DI,
streaming, and distribution. That single seam is why green-tea isn't "Express with decorators":
**the graph is the product.**
## Mesh walking skeleton (spec #3)
```mermaid
flowchart LR
subgraph A["Node A — teapot"]
ea["@Provider({export:true})\n@Step({export:true})\n@Get('/x',{export:true})"]
mc["control channel\n/__mesh__/control\n(secret-gated)"]
end
subgraph B["Node B — teacup"]
bn["@needs('auth') with\nno local provider"]
lk["link: handshake → manifest\n→ synthetic graph nodes\nwith RPC runners"]
end
bn --> lk
lk -- "hello + secret" --> mc
mc -- "manifest {scopes, routes}" --> lk
lk -- "rpc-req {id, kind, name, ctx}" --> mc
mc -- "rpc-res {id, ok, result}" --> lk
```
- **Provider exported → app scope** (resolved once via RPC, cached).
- **Step exported → request scope** (RPC per request, carries the request envelope).
- **Route exported → proxy** (teacup forwards the request, teapot runs the full pipeline).
Deferred to mesh sub-specs: discovery/auto-registration, 2-way load-balancing, failover/health.
-522
View File
@@ -1,522 +0,0 @@
# green-tea — Quickstart
A type-safe HTTP framework where the request/boot pipeline is an explicit **dependency
graph**. You declare what you need; the framework computes the order, validates it at boot,
and can extend the graph over time (streams) and across machines (mesh).
See [architecture.md](./architecture.md) for the mental map.
## Install
```bash
npm install @green-tea/core reflect-metadata
# ws is an OPTIONAL peer dependency — only needed for WebSocket / mesh on Node:
npm install ws # optional
```
`tsconfig.json` must enable decorator metadata:
```jsonc
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"target": "es2017",
"module": "commonjs"
}
}
```
Import `reflect-metadata` once at your entrypoint.
## 1. A route with dependency injection
A **provider** is an app-scope singleton. A **step** runs per request and transforms the
context. A handler's **argument decorators are its dependency declaration** — ask for what
you want, in any order. If you `@needs` a token nothing produces, you get a **boot error**,
not an `undefined` at runtime.
```typescript
import 'reflect-metadata';
import { createApp, Provider, Step, Route, Get, Module, Unauthorized, needs, param } from '@green-tea/core';
@Provider({ provides: 'db' })
class Database {
provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; }
}
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx: any) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline
return { user }; // return = continue, merge into ctx
}
}
@Route('/users')
class UserController {
@Get('/:id')
getUser(@needs('user') user: any, @param('id') id: string) {
return { requested: id, you: user }; // auto-serialized as JSON
}
}
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
const app = createApp({ modules: [ApiModule] });
await app.listen(3000);
// GET /api/users/9 (header x-token) → { "requested": "9", "you": { "id": "...", "name": "Diego" } }
await app.close(); // graceful shutdown: drains in-flight requests, closes streams + mesh links
```
> **Per-route execution (important).** Each route runs **only the providers/steps in the transitive
> closure of its handler's `@needs`** — nothing else. A route that doesn't `@needs('user')` does **not**
> run the `Authenticate` step. This means a cross-cutting *enforcement* step (e.g. auth that throws 401)
> only protects routes that actually `@needs` its token. To run something on **every** route regardless
> of needs (logging, audit, a global guard), add it as a **plugin step** via `scope.add({ ..., provides: [] })` —
> steps that produce nothing run unconditionally. Don't rely on a token-providing step to guard routes
> that don't declare it.
### Argument decorators
| Decorator | Reads from | Adds a graph dependency? |
|---|---|---|
| `@needs('user')` | a value produced by a provider/step | **yes** (boot-validated) |
| `@ctx()` | the whole accumulated context | no |
| `@param('id')` | route params | no |
| `@query('q')` | parsed query string | no |
| `@body()` | parsed JSON body | no |
| `@headers('x')` | request headers | no |
| `@inbound()` | the incoming WS message channel | no (WS only) |
| `@abort()` | an `AbortSignal` that fires on disconnect | no (stream/WS) |
Each envelope decorator has three forms: `@query()` (whole object), `@query('q')` (one key),
`@query(['q','date'])` (subset).
## 2. Compile-time guarantee with `flow`
The decorator layer validates the graph at boot. The functional core `flow` validates it in
the **type checker**:
```typescript
import { flow } from '@green-tea/core';
const pipeline = flow()
.step('db', () => ({ find: (id: string) => id }))
.step('user', (ctx) => ctx.db.find('u1')); // referencing a missing 'db' would not compile
```
## 3. Streaming — SSE
Return an `AsyncIterable` and the pipeline streams it (the transformer is bypassed; the
transport frames it, handles backpressure, and cleans up on disconnect).
```typescript
import { Route, Sse } from '@green-tea/core';
@Route('/feed')
class FeedController {
@Sse('/ticks')
ticks() {
return (async function* () {
for (let n = 1; n <= 3; n++) yield { tick: n };
})();
}
}
// GET /feed/ticks (Accept: text/event-stream)
// data: {"tick":1}
// data: {"tick":2}
// data: {"tick":3}
```
`@Stream(path)` negotiates the transport by header (`Accept: text/event-stream` → SSE,
`Upgrade: websocket` → WS, else ndjson chunked).
## 4. Streaming — WebSocket duplex
A WS handler receives the **inbound** channel and returns the **outbound** channel — a step
that consumes one channel and produces another.
```typescript
import { Route, Ws, inbound, channel } from '@green-tea/core';
@Route('/chat')
class ChatController {
@Ws('/echo')
echo(@inbound() incoming: AsyncIterable<string>) {
const out = channel<string>();
(async () => {
for await (const msg of incoming) out.push(`echo: ${msg}`);
out.close();
})();
return out;
}
}
```
`channel<T>()` is a multicast `AsyncIterable` with `push` / `close` / `fail` and an optional
bounded buffer (`channel({ buffer: 100 })`, drop-oldest).
## 5. Mesh — distributed dependency injection
A **teacup** can depend on a token that physically lives on a **teapot**. Exports are
opt-in (`export: true`) and the control channel is gated by a shared secret.
> ⚠️ **mesh is alpha** — its API and wire protocol may change. It's gated behind `experimental: true`;
> `createApp` throws if you pass `mesh` without it. Don't ship it to production yet.
**Node A — teapot (exposes `config`, `auth`, and a route):**
```typescript
@Provider({ provides: 'config', export: true })
class Config { provide() { return { config: { region: 'mx', tier: 'pro' } }; } }
@Step({ provides: 'auth', needs: [], export: true })
class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } }
@Route('/svc')
class Svc { @Get('/ping', { export: true }) ping() { return { pong: true }; } }
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [Svc] })
class TeapotModule {}
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'shh' } });
await teapot.listen(3002);
```
**Node B — teacup (uses `config` + `auth` with no local providers):**
```typescript
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth }; // both resolved by RPC to the teapot
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] },
});
await teacup.listen(3003);
// GET B:3003/api/local/who (x-token: abc)
// → { "config": { "region": "mx", "tier": "pro" }, "auth": { "token": "abc" } }
```
`@needs('config' | 'auth')` validates at boot because the teapot announced them in its
manifest on connect. A provider export is app-scope (resolved once, cached); a step export is
request-scope (RPC per request, carrying the request envelope).
> Skeleton limitations (by design): no discovery, load-balancing, or failover yet; app-scope
> remote values are not reconciled on reconnect; the request envelope omits `req.url`.
## 6. Plugins & observability
```typescript
const logger = (api: any) => {
api.bus.on('request:step:enter', (p: any) => console.log(`→ ${p.name}`));
api.bus.on('stream:open', (p: any) => console.log(`stream open ${p.name}`));
api.bus.on('mesh:rpc:error', (p: any) => console.error('mesh rpc failed', p.error));
};
const app = createApp({ modules: [ApiModule], plugins: [logger] });
```
Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`,
`mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
## 7. Transport security
Four `createApp` options cover TLS, proxying, CORS, and response headers.
### TLS (native https/wss)
```typescript
import { readFileSync } from 'fs';
const app = createApp({
modules: [App],
tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
});
```
When `tls` is set the server serves https, and WebSocket upgrades become wss on the same
port — no other changes.
### `trustProxy`
```typescript
const app = createApp({ modules: [App], trustProxy: true });
```
Behind a reverse proxy, reads `X-Forwarded-Proto` / `X-Forwarded-For` to populate
`ctx.protocol` (`'http' | 'https'`) and `ctx.ip` (read via `@ctx()`). Off by default —
forwarded headers are ignored (and spoofable) until you opt in. It trusts the immediate hop
unconditionally; there's no CIDR allowlist yet.
### CORS
Off unless `origins` is set.
```typescript
const app = createApp({
modules: [App],
cors: { origins: 'https://app.example.com', credentials: true },
});
```
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
request (with `Access-Control-Request-Method`) is auto-answered with 204.
- With `credentials: true`, the server never sends `Access-Control-Allow-Origin: *` — it
echoes the concrete allowed origin (or blocks the request).
- **Security warning:** `origins: '*'` together with `credentials: true` reflects *any*
origin with credentials attached — the classic reflect-any foot-gun. Only combine them if
you truly intend an open credentialed API; prefer an explicit allowlist.
### `security` (headers, ON by default)
Applied to every HTTP response. Disable everything with `security: false`, or override
individual headers with an options object.
| Header | Default |
|---|---|
| `X-Content-Type-Options` | `nosniff` |
| `X-Frame-Options` | `SAMEORIGIN` |
| `Referrer-Policy` | `no-referrer` |
| `X-DNS-Prefetch-Control` | `off` |
| `Strict-Transport-Security` | `max-age=15552000` (180d) — **only when the connection is secure** (native TLS, or `trustProxy` + `X-Forwarded-Proto: https`); no `includeSubDomains`/`preload` |
| `Content-Security-Policy` | not set — pass `security: { csp: "..." }` |
```typescript
const app = createApp({ modules: [App], security: { csp: "default-src 'self'" } });
```
**Scope caveat:** `security` and `cors` headers apply to HTTP responses; they do not apply
to the WebSocket handshake (101/upgrade) response.
### Defaults
| Option | Default |
|---|---|
| `tls` | off (plain http/ws) |
| `trustProxy` | off |
| `cors` | off (same-origin only) |
| `security` | ON (HSTS only when the connection is secure) |
## 8. File uploads / multipart
> Multipart parsing uses the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency — install it with `npm i busboy`. A `multipart/form-data` request to a server without busboy installed returns `501`. (JSON and urlencoded need nothing extra.)
A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }`
instead of a plain object:
```typescript
import { Route, Post, body } from '@green-tea/core';
import type { MultipartBody } from '@green-tea/core';
@Route('/profile')
class ProfileController {
@Post('/avatar')
upload(@body() form: MultipartBody) {
const name = form.fields.name; // string | string[]
const avatar = form.files.avatar; // UploadedFile | UploadedFile[]
return { name, size: Array.isArray(avatar) ? undefined : avatar?.size };
}
}
```
`UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered
in memory, no temp files.
> **Access note (asymmetry).** For multipart, `@body('title')` returns `undefined` — the value
> lives at `body.fields.title`, not `body.title`, unlike JSON/urlencoded where `@body('title')`
> picks the value directly. Use `@body()` and read `.fields`/`.files`, or key into the envelope
> itself with `@body('fields')` / `@body('files')`.
### Repeated fields — `bodyDuplicates`
By default, a repeated field name keeps the **last** value (`'last'`, matching urlencoded).
Set `bodyDuplicates: 'array'` on `createApp` to accumulate repeats into a `string[]` instead —
this applies to **both** urlencoded and multipart text fields:
```typescript
const app = createApp({ modules: [ApiModule], bodyDuplicates: 'array' });
```
Files under a repeated field name always become an array (`UploadedFile[]`), regardless of
`bodyDuplicates`.
### Per-endpoint override
```typescript
@Post('/upload', { duplicates: 'array' })
upload(@body() form: MultipartBody) { /* ... */ }
```
Precedence: route `duplicates` → app `bodyDuplicates` → `'last'`.
### Limits
Uploaded files are held in memory, so they're bounded by the same `maxBodyBytes` limit as any
other request body (over the limit → 413). `maxParts` (default `1000`) caps the number of
multipart parts per request:
```typescript
const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } });
```
A malformed multipart body (bad boundary, missing headers, truncated part) → 400.
## 9. Validation
`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema**
(the [`~standard` interface](https://standardschema.dev) shared by zod, valibot, arktype,
and others). green-tea's core has **zero runtime dependency** on any of them — bring
whichever validator you already use:
```typescript
import { z } from 'zod';
import { Route, Post, body } from '@green-tea/core';
const CreateUser = z.object({ email: z.string().email() });
@Route('/users')
class UserController {
@Post('/')
create(@body(CreateUser) user: { email: string }) {
return { created: user.email };
}
}
```
The value the handler receives is the schema's **parsed/coerced output**, not the raw
input — `ctx.body` (via `@ctx()` or a `@needs`-fed step) stays exactly what the transport
parsed. Query strings are always strings on the wire, so a schema is often the coercion
point:
```typescript
const ListQuery = z.object({ page: z.coerce.number() });
@Get('/list')
list(@query(ListQuery) q: { page: number }) {
return { page: q.page, isNum: typeof q.page === 'number' }; // GET /list?page=2 → true
}
```
> **Access shape (asymmetry).** `@param('id', Schema)` takes the key in slot 1 and the schema
> in slot 2 — `@param` always needs a name to say which route param it binds. `@body(Schema)`,
> `@query(Schema)`, and `@headers(Schema)` take the schema as their only argument, validating
> the whole parsed object (all of `body`/`query`/`headers`).
A failing schema short-circuits the request with **422**:
```json
{ "error": "Validation failed", "source": "body", "issues": [{ "path": "email", "message": "Invalid email" }] }
```
`source` is which envelope failed (`'body' | 'query' | 'params' | 'headers'`); `issues` is
the schema's issues flattened to `{ path, message }` (`path` is dot-joined).
**Caveats:**
- **Fail-fast.** Arguments validate in order; the **first** failing one throws — later args in
the same handler are not checked in that request.
- **Steps see raw input.** Only the resolved handler argument is coerced/validated; a `@Step`
reading the same data via `ctx.body`/`ctx.query`/etc. always sees the untouched value.
- **A throwing schema is a 500, not a 422.** The Standard Schema contract says `validate()`
returns `{ issues }` on failure — it isn't supposed to throw. If it does anyway, that
propagates as an uncaught error (→ 500), since it signals a bug in the schema, not user input.
- **Async schemas are awaited** — `validate()` returning a `Promise` works transparently.
**Not covered yet:** response/output validation, validating a `@Step`'s own inputs, and
mesh remote-route validation are all out of scope for this feature.
## Inspect & test the graph
### Visualize with Mermaid
```typescript
console.log(app.toMermaid()); // flowchart diagram of all nodes and routes
```
Enable a live `GET /__graph__` endpoint (renders HTML with Mermaid, or plain-text with `Accept: text/plain`):
```typescript
const app = createApp({ modules: [ApiModule], devGraph: true });
// GET /__graph__ → HTML viewer
// GET /__graph__ (text/plain) → raw Mermaid source
```
### Explain a route
```typescript
const e = app.explain('/api/users/:id');
// { pattern, method, transport, chain: [{ name, kind, origin, needs, provides }, ...] }
console.log(e.chain.map((n) => `${n.kind}:${n.name}`));
// → ['provider:db', 'step:user', 'handler:getUser']
```
### Override tokens in tests
Swap any provider or step token with a test double at construction time — no monkey-patching:
```typescript
const app = createApp({
modules: [ApiModule],
overrides: {
db: { find: () => ({ id: 'test-user' }) }, // plain object — wrapped as { db: value }
user: () => ({ user: { id: 'stub' } }), // function runner
},
});
```
Overrides replace only the named token's runner; the rest of the graph is untouched.
## Runnable examples
The `example/` directory holds end-to-end apps you can `node`-run and read top to bottom.
### CRUD — methods, query, JSON & urlencoded body
`@Get/@Post/@Put/@Patch/@Delete` over a provider-backed store. Filter via `@query('done')`,
read the payload via `@body()` — the same handler accepts both `application/json` and
`application/x-www-form-urlencoded` (the transport parses each into a plain object). Missing
rows throw `NotFound` (→ 404).
See [`example/crud.ts`](../example/crud.ts).
### Chat — rooms + handshake auth
A `@Step` reads `?token=` and `provides: 'user'`, throwing `Unauthorized` on a missing token —
which closes the socket with code **4401** (`4000 + status`). The `@Ws` handler pumps the
`@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel,
so every joined socket multicasts to the others. `rooms` is the built-in shared `Rooms`
primitive (one instance app-wide).
See [`example/chat.ts`](../example/chat.ts).
### GraphQL — query/mutation over POST, subscription over SSE
A schema built programmatically with `graphql` (a dev/example dependency — the core has no
runtime dep on it). `POST /graphql` runs queries and mutations through `graphql()`. The
`mutation` pushes each new message into `rooms.room('messages')`; the `@Sse('/stream')` route
calls `subscribe()` whose source **is** that room, guards the result with `isAsyncIterable`,
and returns it — the framework streams each `ExecutionResult` as an SSE `data:` frame. This is
the tie between GraphQL, green-tea streams, and the `rooms` primitive.
See [`example/graphql.ts`](../example/graphql.ts) — `npm install graphql` first.
## The one rule to remember
```
return a VALUE → buffered response (transformer → JSON)
return an AsyncIterable → stream (SSE / WS)
@needs a remote token → RPC to a teapot (mesh)
```