Express-simple. Fastify-fast. Typed end to end. No magic.
Architecture RFC Β· Roadmap Β· Trade-offs Β· Error codes Β· Changelog Β· Contributing
Important
Alpha. Published to npm on the alpha tag for feedback, not for
production: the API will change before 1.0. See Status.
npm install @erenthedeveloper0/zen@alphaimport { zen } from '@erenthedeveloper0/zen'
const app = zen()
app.get('/', () => 'Hello world')
await app.listen(3000)Two concepts: app.METHOD(path, handler), and the handler returns the response.
That is one fewer than Express, because there is no response object to learn.
A schema is the whole contract β validation, the handler's types, the response filter and the OpenAPI document all come from it:
import { zen, NotFound } from '@erenthedeveloper0/zen'
import { z } from 'zod'
const User = z.object({ id: z.number().int(), email: z.email(), name: z.string() })
const app = zen()
app.get('/users/:id<int>', { response: { 200: User } }, async (ctx) => {
const row = await db.users.find(ctx.params.id) // ctx.params.id is a number
if (row === undefined) throw new NotFound(`User ${ctx.params.id} not found`)
return row // passwordHash is never sent
})
await app.listen(3000)Contents β The idea Β· What's different Β· Status Β· In depth Β· Try it Β· Layout Β· Examples Β· Contributing
A web framework is a compiler with an HTTP server attached.
Registration is the source language. The per-request path is the target language.
Routes, middleware chains, validators, serializers β and the Context class's own
memory layout β are compiled once at boot from a frozen application graph.
You can read what it emits:
$ node scripts/show-generated.ts
function finish(ctx, reply) {
const s1 = d.steps[3](ctx, reply) // after: auditLog
if (s1 !== null && typeof s1 === 'object' && typeof s1.then === 'function') return Promise.resolve(s1).then((v) => k1(ctx, v))
return k1(ctx, s1) // β not a promise: carry on, now
}
function k1(ctx, reply) {
return reply
}
function seg1(ctx) {
let r
const out = d.handler(ctx)
if (out !== null && typeof out === 'object' && typeof out.then === 'function') return Promise.resolve(out).then((v) => k2(ctx, v))
return k2(ctx, out)
}
function k2(ctx, out) {
let r
let reply = d.finalize(out, false)
return finish(ctx, reply)
}
async function seg0(ctx) {
let r
r = d.steps[0](ctx); if (r !== null && typeof r === 'object' && typeof r.then === 'function') r = await r
if (r !== undefined) return finish(ctx, d.finalize(r, true))
r = d.steps[1](ctx); if (r !== null && typeof r === 'object' && typeof r.then === 'function') r = await r
if (r !== undefined) return finish(ctx, d.finalize(r, true))
return d.steps[2](ctx, async function () { return seg1(ctx) }) // β around: the only closure
}
No array iteration. No dynamic dispatch. Stages the route doesn't use are not
emitted at all β not skipped by a runtime if, absent from the source.
Every function in that app is a plain one β no async, no marker. Each call is a
speculation point: when what it returned is not a promise, the rest runs at once, so
a request on which nothing returns one allocates no promise in the pipeline
(Β§8.4). seg0 keeps the async form because
it holds the around, whose next() is a promise by contract. A route of plain functions
with no around and no body to read has no async and no await in it at all.
| Express problem | Zen |
|---|---|
req.user = x |
Slots β declared, typed, integer-indexed. ctx.get(CurrentUser) compiles to this.$s[3]. One hidden class per app, no global type augmentation |
next() confusion |
Two named forms. app.use (no next, zero closures) for the ~90% that never wrap; app.around for the 10% that must. The cost is legible at the call site |
res.send() side effects |
Handlers return a Reply value. Double-send and hung requests are structurally impossible; around can inspect the real reply with no monkey-patching |
| Silent route shadowing | Boot-time conflict analysis. Duplicates and genuine ambiguities are refused, with every diagnostic reported at once |
| Validation bolt-ons | Standard Schema β Zod, Valibot, ArkType work with zero adapters, and core depends on none of them |
| Wrong-method 404s | Free, correct 405 with an Allow header |
Leaking passwordHash |
Response schemas compile to a serializer that cannot emit undeclared fields β there is no Object.keys in the generated source to leak through |
| Docs that drift from the code | OpenAPI is a projection of the app graph, generated from the same schemas the serializer executes. A test asserts the documented fields equal the fields the wire actually carries |
| Timing middleware that stops the clock too early | Twelve lifecycle phases. onResponse runs after the last byte is flushed, so its number includes serialization and egress. Phases you don't use emit no code β asserted in CI as byte-identical output |
app.use(logger) and hoping |
Hooks scope to the app, a collection subtree, or one route β lexically. explainRoute(record) prints the resolved chain, generated from the same arrays the compiler consumed, so it cannot drift |
| A hung handler holding its socket forever | Deadlines per app, collection or route. The arm answers on time; the compiled pipeline stops the abandoned work at the next stage boundary instead of leaving it running behind an answered request |
| A timeout you cannot pass downstream | ctx.timeLeft is the remaining budget, so a fan-out gives each call a truthful slice instead of promising all four of them the original thirty seconds |
One /health doing two jobs |
Liveness and readiness are separate, and a check is readiness unless it says otherwise β because the other mistake, dependencies in the liveness probe, restarts the whole fleet during a database blip and then stops the pools reconnecting |
| 502s on every rolling deploy | Readiness flips to draining at the top of shutdown, before the socket stops accepting. Asserted over a real connection, mid-shutdown, because that ordering is the entire feature |
| A health check that hammers the thing it is checking | Results are cached and concurrent probes share one in-flight call: 500 simultaneous polls, one probe. CI fails if that stops being true |
Number(process.env.PORT ?? 3000) |
A validated environment, checked before any plugin's setup runs, with the expected constraint read off the schema and the .env file and line named in the error |
| "Which config file set this?" | Resolution keeps a { value, layer, source } record per value, so explainConfig prints the provenance. {...a, ...b} has no memory of a; a fold over records does |
console.log(config) in a log aggregator |
Marked secrets redact themselves on serialisation β toJSON and inspect hooks at every level β while the code that opens the connection still gets the real value by name |
/v2/ prefixes, and res.format({...}) |
Representations are declared, not branched on. One route can serve v1+json, v2+json and text/csv; Accept picks one before the handler runs, both JSON versions go through the same compiled serializer, and a route that declares one representation emits no negotiation code at all |
Accept: text/csv;q=0 served as CSV anyway |
The most specific matching range decides, per RFC 9110 Β§12.5.1 β so q=0 under a permissive wildcard means "anything except this". Scoring by the highest q is the obvious implementation and it serves the one format the client refused. CI gate, not a test |
res.send('<p>' + req.query.name + '</p>') |
HTML escaped by construction. ctx.html() takes SafeHtml, which the html tag builds by escaping every hole for where it sits: a javascript: URL in an href is replaced rather than escaped, and a template that puts a value inside <script> or an onclick β where no escaping helps β is refused on its first render |
res.redirect(req.query.next) |
Redirects stay on the origin unless one line lists where else they may go. //evil.example, /\evil.example and the other spellings that slip past a regular expression are read the way the browser reads the Location header, and refused |
`/files/${name}` in a link |
Links are asked of the route. app.url('files.show', { name }) encodes each value as one segment, tests it with the parameter's own type, and asks the router whether the path reaches that route β so a value cannot become a different path, and /users/:id given me beside a GET /users/me is refused rather than linked |
Full reasoning, including the arguments that lost, is in ARCHITECTURE.md.
Alpha β 0.2.0-alpha. The architecture RFC is complete; the implementation is a
working vertical slice, published on npm's alpha tag for feedback. Do not put this in
production: the API will change, and several subsystems the RFC describes are not built
(below). What is built has been through three audit passes β two before the first
publish, one before this release's β each reproducing a defect before fixing it, and
CHANGELOG.md lists every one.
| Package | |
|---|---|
@erenthedeveloper0/zen |
install this β everything below, wired together |
@erenthedeveloper0/zen-core |
registries, compilers, runtime, and the testing kit (/testing) β zero dependencies |
@erenthedeveloper0/zen-router |
compiled radix router |
@erenthedeveloper0/zen-adapter-node |
Node http adapter |
@erenthedeveloper0/zen-middleware |
CORS, security headers, request ids, rate limiting |
@erenthedeveloper0/zen-openapi |
OpenAPI 3.1, $ref dedup, breaking-change detection |
Requires Node β₯ 22.6, and TypeScript β₯ 5.0 if you use TypeScript. The packages run on Node today; the adapter boundary is designed for Bun, Deno and the edge (Β§14), and those adapters are not built yet.
- Every diagnostic points at a line: each registration β route, middleware, hook, plugin, collection, service, health check, decoration, configuration β records the
file:line:colthat made it, every boot diagnostic prints the lines of what it is about (both, for a conflict), andexplainRoute()prints one per step - Development errors with the code in them: a development 5xx names the route's registration line, the line of application code that raised it with the lines around it, the route's resolved chain, the fix and the docs β rendered to the terminal with clickable locations, and to a browser as an escaped HTML page; production is unchanged
- The graph as a document:
app.graphDocument()is the application as canonical JSON with a SHA-256 fingerprint that ignores registration order and file layout, and a contract fingerprint per route that ignores documentation;fingerprintHeaders: truesends both on every response explainRequest()β EXPLAIN ANALYZE for one request: every step that ran, its outcome and time, the headers it staged and the slots it set, the fields the response schema kept off the wire; served from a copy of the route table, so the application is never changed- Compiled context class β
ctx.ipsandctx.protocolincluded, as getters, so its shape never changes β per-route compiled pipelines, generated params builders; the generated source is kept after boot only withinspect: trueordev: true; development seals the context and freezes request data - The sync fast path, for plain functions: every call that is not
asyncis a speculation point, so a route of plain functions compiles with noasyncand noawait, andexplainRoute()says which path a route got ctx.logbound to the request β a child carrying the request id and route template, made on its first read and remade whenctx.idchanges, so a request that never logs pays nothing- Backtracking radix router: static/typed/wildcard/optional params,
app.paramType()(itstestchecked for backtracking regexes in development), correct 405 with a completeAllow,HEADβGET; matching is case-sensitive and a trailing slash is normalised - Boot-time conflict analysis with aggregated, rendered diagnostics β duplicate paths and names, ambiguous routes, and parameter types that can match the same value; registration order never decides which route answers
app.get/post/β¦/all(path, [spec,] handler)andapp.listen(port)β the Express spellings β alongside the spec and options forms- Phase / around / after middleware at app, collection and route scope (
use: [checkOwnership]on a route), collections β including a collection'swhen, decided once at boot against the validated environment, so a subtree that is off is absent from the router, the graph and the document β and slots - Configured middleware:
defineMiddleware({ name, options, setup })validates its options at boot and runssetuponce;use(fn, { when: { env } })omits a step at boot, and{ when: { request } }guards it per request - A route spec that carries its rule and its dependencies:
checkfor the business rule, answered as a 422 like a schema's;injectfor services, resolved once at boot for singletons;intakefor the route's own body limits, or the body as raw bytes or a stream - The hook system: all twelve phases, three lexical scopes, compiled into the pipeline, with mirror ordering so before/after pairs nest β and
explainRoute()to print the resolved chain - Request deadlines: per app / collection / route,
ctx.signalwired to the timeout as well as to disconnect,ctx.timeLeftto propagate the remaining budget downstream, and abandoned work stopped at the stage boundary rather than left running behind an answered request - Health and readiness: two endpoints answering two different questions, per-check budgets and cancellation, stampede-safe caching, and a
drainingstate that goes red before the server stops accepting - Plugins: manifests, semver dependency resolution, topological ordering, cycle/conflict/capability detection β checked against what the adapter says it can do β context decorations with type accumulation, and options validated at boot before any plugin runs, so
rateLimit({ limt: 100 })fails with did you mean "limit"? - DI: typed tokens β optional ones resolve to
undefinedβ three lifetimes, request-scoped services stored in the slot array and disposed at the end of the request, boot-time cycle and captive-dependency analysis; a service or slot value implementingSymbol.disposeorSymbol.asyncDisposeis released through it, with no second declaration - Standard Schema validation with normalised issues β a missing value is
requiredwhatever the library calls it, andregisterIssueMapper()reads the rest from the library's own issue codes, not its (translatable) messages β and aparamsschema checked against its path at boot; RFC 9457 error envelopes, every error class with a code of its own, an abort classified by whose it was β the request's own, an upstream that timed out (503), or the application's (500) β and a formatter that keeps failing answered by a circuit breaker rather than afatalper request - Response validation: a response of the wrong value is refused with
ZEN_RESPONSE_INVALIDin development, logged under the hardened profile in production, and costs nothing β no emitted code β when off. It judges the value as the serializer will send it, so a row with extra fields and aDatepass a strict schema the bytes on the wire satisfy - Coercion profiles:
?page=2is anumberbecause the schema saysnumberβ schema-guided, so?sku=00713stays a string, and a source with nothing to convert emits no code - Configuration: layered resolution that keeps the provenance of every value, a schema-validated environment checked before any plugin's
setupruns, typedapp.config/ctx.config, and secrets that redact themselves when serialised - Request policy is configuration: the deadline, body limits, proxy trust, redirect allowlist and ingress limits are read from the configuration with a source each, and
zen({ profile: 'hardened' })is a named source of production values - Logs that redact: the built-in logger masks the
logging.redactpaths (**.authorization,**.cookie,**.passwordby default) wherever they sit in a line, andrequestLog()writes one line per request, 404s included - First-party middleware:
cors,securityHeaders,requestId,rateLimitβ each a global hook rather than middleware, so a preflight to a path with no route is answered and a 404 flood counts against the limit; each staging its headers, so they are on the 404 and the 429 as well as the 200; and each with an options schema, so a misspelt option fails at boot - Content negotiation: one route, several representations, chosen from
Acceptbefore the handler runs β versioned JSON for free through the same compiled serializer, an encoder seam for everything else,Vary: Accepton every response including the 406, and no emitted code at all on a route that declares one representation - Compiled response serializers: undeclared fields cannot be emitted, because the generated function has no key enumeration to emit them through β and a declared one its own schema marks
writeOnlyis refused at boot, in every representation and every encoder - Injection defences: an
htmltemplate tag that escapes each interpolation for the position it sits in and refuses the positions where no escaping helps, actx.html()that takes only itsSafeHtml, and actx.redirect()that will not leave the origin unlessredirect.allowExternalsays where - URL generation:
app.url(name, params, query)returns a path its route answers, with the values given β encoded, typed and checked against the router β or refuses; reachable from a collection and from a plugin, and always on the application's origin - OpenAPI 3.1:
AppGraph β documentas a pure function,$refdeduplication, components named withapp.schema(name, schema), a dependency-free reference viewer, the security schemes plugins declare withapp.meta, and nowriteOnlyfield documented as returned - Breaking-change detection that reads every constraint: bounds, patterns,
additionalProperties, defaults and any other keyword, each classified by direction β held to the contract fingerprint by an oracle of a thousand seeded schema edits - Body intake emitted only when a route declares a body; prototype-pollution stripping
- Node adapter with lazy
RawRequest(no WHATWGRequestconstruction), client disconnects wired toctx.signal, shutdown that drains and then closes keep-alive connections rather than waiting on them, and ingress limits that refuse before any of Zen runs: 8 KB of headers (431, from Node) and an 8 KB URL (414ZEN_URI_TOO_LONG) by default, plus a per-socket request cap - Server-sent events β
ctx.sse(), with heartbeats, backpressure, a bound on what a slow client can hold, and a finalshutdownevent on drain - File responses β
ctx.file(path, { root })with root confinement,ETag/Last-Modified, 304 revalidation and single-range 206 - Process lifecycle β
SIGTERM/SIGINTrun the graceful shutdown; an uncaught exception is logged and shuts down with exit code 1;listen({ signal })aborts into the same sequence inject()in-process testing β including the peer address a request comes from, and a deadline that answers even when nothing else keeps the process alive; streaming responses; graceful shutdown, which releases singletons only after the server has stopped accepting- A testing kit:
createTestApp(makeApp, { override: [[Db, () => fakeDb]] })compiles the real application with the fakes β each checked against its token's type βtestContext()calls a handler with no application at all, andassertNoLeaks()fails on a timer or socket left running - Interpreted twins for the pipeline, context, router and serializer, verified by differential suites
Every bullet above carries an id that scripts/claims.ts maps to a probe against the
built packages, run in CI: a sentence cannot be promoted to this list without a check that
breaks if it stops being true, and a gap the docs admit fails the build the day it closes,
until the docs say so.
CLI (zen dev, routes, build, doctor) Β· typed client, and a test response typed from its route Β· non-Node adapters and the conformance suite Β· WebSockets Β· app.isolate() Β· resource and module routing Β· a middleware's provides and requires Β· a generated matcher (matching walks the trie; params builders are generated) Β· a returned WHATWG Response passing through Β· compression and static file serving (both need a platform, so they belong to an adapter-coupled package rather than to the middleware one β Β§32.6) Β· negotiation of language and encoding, as opposed to media type (Β§28.8). The roadmap in Β§25 sequences them.
Each subsystem below was built against a claim in the RFC, and each claim is either measured by a benchmark or asserted by a CI gate β usually both. Where a measurement came out worse than the claim, the claim was corrected.
Β§1.4 makes a falsifiable prediction: Zen's per-request work should be within noise of a
hand-written http.createServer handler doing the same job, "and if that is not true in
benchmarks, the thesis has failed and we should say so." So: it is not true yet. On Annex C's
first six workloads (benchmarks/competitors), Zen serves 0.89β0.96Γ of the hand-written
baseline wherever no I/O hides the difference β up from about 0.8Γ before this release β where
Fastify serves about 1.0Γ:
Workload β fraction of node:http |
Zen, alpha.5 | Zen | Fastify | Hono | Express |
|---|---|---|---|---|---|
| 1. Static JSON, no schema | 0.82Γ | 0.96Γ | 0.84Γ | 0.93Γ | 0.65Γ |
| 2. JSON with a response schema | 0.82Γ | 0.91Γ | 1.04Γ | 0.96Γ | 0.66Γ |
| 3. A route with 5 path params | 0.79Γ | 0.95Γ | 0.98Γ | 0.93Γ | 0.62Γ |
| 4. POST + body validation (Zod), ~1 KB | 0.79Γ | 0.89Γ | 0.96Γ | 0.95Γ | 0.70Γ |
| 5. 10 middleware | 0.80Γ | 0.94Γ | 1.00Γ | 0.81Γ | 0.63Γ |
| 6. Realistic: JWT, rate limit, Zod, 5 ms DB, ~2 KB out | 0.98Γ | 1.01Γ | 1.00Γ | 1.06Γ | 0.93Γ |
The table is 0.2.0-alpha's, from its release gate. Through 0.1.0-alpha.5 Zen sat at ~0.8Γ on
every workload without I/O β the same on static JSON as through ten middleware, so a cost every
request paid rather than any one feature (the POST workload was 0.49Γ until 0.1.0-alpha.5
stopped running a reviver over every JSON body). A profile found it on the way out: every JSON
body was encoded to bytes and written as a second buffer beside the head, where a string goes
out with the head in one write. Three changes to the response path took it out (CHANGELOG) β
paired against the same tree without them, 10β14% more requests a second without I/O.
benchmarks/results/competitors.md has every cell, the
run after each fix, and what the method is not β one laptop, 10-second runs, the load
generator on the same machine. This run was also on battery, and some cells spread Β±10β16%:
Fastify's 0.84Γ on workload 1 is its outlier (1.00β1.02Γ in the two runs before it), and Zen's
own workload-2 cell is one of the wide ones.
The biggest risk in the design (Β§28.2) is that plugin type accumulation makes tsc crawl in real codebases. Measured, not assumed β best of 3, with the run-to-run spread shown because a single cold run of a one-second workload is not evidence:
| Routes | Plugins | tsc --noEmit |
Per route | Spread |
|---|---|---|---|---|
| 100 | 4 | 0.73 s | 7.3 ms | 24% |
| 250 | 8 | 0.93 s | 3.7 ms | 10% |
| 500 | 12 | 1.07 s | 2.1 ms | 7% |
~0.64 s of each figure is fixed tsc startup; the marginal cost is β0.9 ms per route and does not degrade as the plugin chain deepens. node benchmarks/typecheck/run.ts reproduces it.
The first version of this harness ran once per cell and reported roughly double these numbers for the same code. Β§28.2 keeps that measurement on the record and explains why it was the more interesting result.
The gate also found a real bug: five of eight HTTP verbs had untyped overloads, so ctx silently became any on them. Hand-written tests missed it because they all use get and post.
A route that declares response: { 200: User } compiles to a serializer that cannot emit passwordHash β not "does not", cannot: there is no Object.keys in the generated source. node scripts/show-serializer.ts prints it.
Speed is the secondary benefit, and the RFC's original "2β5Γ faster than JSON.stringify" was too optimistic. Measured (node benchmarks/serializer/run.ts):
| Response | Same fields as declared | Plus undeclared fields |
|---|---|---|
| flat object, 5 fields | 2.1Γ | 1.7Γ |
| list of 50 objects | 1.2Γ | 2.6Γ |
| nested object + arrays | 1.3Γ | 4.0Γ |
| string-heavy (escapes) | 1.7Γ | 2.2Γ |
On identical work it is 1.2β2.1Γ (Node 26; re-run on 2026-10-15, 1.2β2.2Γ there and 1.1β2.5Γ on Node 24 β the range moves with V8's own JSON.stringify). The bigger numbers come from skipping fields, which is real but is partly doing less work rather than doing the same work faster. V8's JSON.stringify is a tuned C++ path; Β§13.3.2 has the full account, including the two measurements that changed the implementation.
AppGraph β OpenAPIDocument is a pure function (Β§29). The interesting part is not that it generates a document β every framework has a plugin for that β it is that the document is generated from the same schemas the serializer executes, with Zen's additionalProperties rule applied (Β§13.3.1), so it says exactly what the wire will carry:
handler returned : {"id":1,β¦,"passwordHash":"$2b$12$β¦","totpSecret":"JBSWY3DPEHPK3PXP",β¦}
wire : {"id":1,"email":"ada@example.com","name":"Ada Lovelace","role":"admin","createdAt":"β¦"}
document says : properties: id, email, name, role, createdAt additionalProperties: false
The test suite asserts that by running values through the real compiled serializer and comparing key sets β so a document that promises a field the serializer drops fails the build.
Measured (node benchmarks/openapi/run.ts, best of 5):
| Routes | Components | Generation | Per route | Document |
|---|---|---|---|---|
| 100 | 42 | 1.6 ms | 16 Β΅s | 74 kB |
| 250 | 102 | 3.8 ms | 15 Β΅s | 183 kB |
| 500 | 202 | 8.0 ms | 16 Β΅s | 365 kB |
Once, at boot. The per-request difference between an app with the plugin and the same app without it is inside the run-to-run noise β the endpoint serves a string built during ready().
$ref deduplication removes 77% of the document. Naming your schemas is worth a further 8%, which is less than expected and is published as such; the reason to name them is stable client type names, not bytes.
Breaking-change detection ships with it: diffDocuments(before, after) classifies each change as breaking, compatible or documentation-only, using the rule that requests are contravariant and responses are covariant. npm run openapi:check is a working gate.
Each registration records the file:line:col that made it, so a boot failure names
both lines it is about, relative to the working directory:
Boot failed: 1 problem
1. ZEN_ROUTE_AMBIGUOUS Ambiguous routes: GET /:org/settings and GET /admin/:page can both match the same request, and no priority rule separates them.
at GET /:org/settings src/routes.ts:6:12 β GET /admin/:page src/routes.ts:7:12
fix: Make one segment static, or narrow one parameter with a type (e.g. ":id<int>") so the matcher can tell them apart.
docs: https://github.com/erenthedeveloper0/zen/blob/main/docs/errors.md#zen_route_ambiguous
Every suite in the repository boots its applications through a check that fails the test
when a boot diagnostic has no line, so a new diagnostic cannot ship without one. The same
origins reach a development 5xx β the route's registration line and the application line
that raised the error, with the code around it β and explainRequest() shows what one
request did at each step of the chain explainRoute() prints:
POST /api/orders β orders.create 2.499 ms budget 2000 ms Β· 1997.5 left
onRequest [global] rateLimit 0.014 ms continue
phase [root/api] authenticate 0.007 ms continue
intake read the body 0.146 ms ok Β· application/json Β· 14 B
validate body 0.742 ms ok
handler createOrder 0.041 ms ran Β· async
serialize 201 0.024 ms ok Β· 8 B Β· dropped undeclared: costCents
wire 201 2 headers Β· 8 B
The explained request runs on a copy of the route table compiled with observers, so the application serving other requests at the same time is never changed.
app.graphDocument() serialises the whole application β routes with their schemas as
JSON Schema, hooks, plugins, services, health checks, the redacted configuration β
to canonical JSON, with two kinds of SHA-256 fingerprint
(Β§2.4). The application's ignores
registration order, file layout and configuration; each route's contract covers only
what crosses the wire, normalised, so a reworded description or a converter's other
spelling of the same schema changes nothing and a tightened maxLength changes it.
diffDocuments() reads the same constraints, and a seeded suite of a thousand schema
edits holds the two to each other: the fingerprint moves exactly when the diff reports a
non-documentation change. Each example's tests boot it ten times and check the document
round-trips with one fingerprint.
Twelve lifecycle phases (Β§9), at three lexical scopes:
app.hook('onResponse', metrics) // every route
app.collection('/admin', { hooks: { onRequest: audit } }) // this subtree
app.get('/x', { hooks: { onSend: cacheHeader } }, handler) // exactly hereEvery other framework with hooks keeps a table and walks it per request, and pays a small cost for every phase forever. Zen compiles them into the pipeline, so a phase nobody registered emits no source text. That is not a claim you should take on a benchmark, so CI does not: it compiles a route in an app with no hooks and the same route in an app with eight phases registered on a different collection, and fails the build unless the two generated pipelines are byte identical.
Measured (node benchmarks/hooks/run.ts, paired sampling, Node 26):
| A phase you don't use | 0 bytes, byte-identical pipeline β asserted, not timed |
1 onRequest hook |
+2 ns over none |
16 onRequest hooks |
+9β13 ns over none, i.e. β1 ns each |
| One hook on each of 6 phases vs 6 on one | inside noise β the cost is per hook |
| Hooks vs phase middleware | Identical generated source after renaming the array |
| Compiled pipeline vs the interpreted twin | β1.6Γ |
The hook rows are a range because that is what the harness resolves: a call site at this scale is a few nanoseconds and consecutive runs move by a few nanoseconds. Quoting one figure to two decimals would be reporting the noise. The first row is not a range, because it is not a measurement.
What the phases buy, in examples/observability β a complete metrics + request-log + Server-Timing stack, one plugin, ten phases, nothing patched:
Server-Timing: parse;dur=0.223, validate;dur=1.790, handler;dur=0.940, epilogue;dur=0.237, total;dur=3.355
logged: POST /checkout 201 3.967ms parse=0.22 validate=1.79 handler=0.94
The logged total is larger, and that gap is egress. A response-time middleware cannot see it, because onResponse is the only thing that runs after the last byte is flushed. Meanwhile four requests to /products/1..4 produce exactly one metric series β the label comes from the route template, because that is what the onRoute hook is handed; there is no raw URL available to accidentally label on.
You configure a timeout, which is a duration. A request carries a deadline, which is an instant. A service told "you have 30 seconds" that forwards 30 seconds to each of four sequential calls has quietly promised two minutes; one that forwards the time remaining has not.
const app = zen({ timeout: { default: '30s', header: 'x-request-timeout' } })
app.collection('/reports', { timeout: '10s' }, β¦) // a slower subtree
app.get('/status', { timeout: '250ms' }, handler) // one fast route
app.get('/feed', { timeout: false }, handler) // a stream, refusing it
app.get('/quotes', async (ctx) => {
// The budget is a value. This is the whole point.
const slice = ctx.timeLeft - EGRESS_RESERVE
return Promise.allSettled(providers.map((p) => p.quote({ budgetMs: slice, signal: ctx.signal })))
})Two mechanisms, because one is not enough. The arm answers on time, so a hung handler cannot hold its connection until the process restarts. It cannot make the work stop β you cannot interrupt a running await. So the compiled pipeline also checks at each Β§4.1 stage boundary, and a request that is already over stops there instead of validating a body and querying a database for an answer nobody will read.
That second half is what a compiled framework gets nearly free: the boundaries are known statically, so the checks are two or three branches on routes that asked for a deadline and no emitted text at all on routes that did not β the same gate as the hooks, run the same way.
| A route with no deadline | 0 bytes β byte-identical to three other configurations, asserted in CI |
| Each stage boundary | β1 ns, and measurably above the noise |
| Arming one | β1 Β΅s β a timer, an AbortController, a listener, a promise |
| A synchronous route | Cannot time out. It never yields, so its timer cannot run β and it cannot hang either |
The microsecond is the honest headline and it is why the default is off: against a route that does nothing it is a large fraction of a small number, against a route that talks to a database it is under half a percent, and Zen does not levy costs nobody asked for. It is also the one line every public service should write. A coarse timer wheel would remove most of it and is not built.
onTimeout is handed the stage it blew in, because the pipeline marked it on the way past β so a 504 says "the handler stage blew a 2 s budget after 2.04 s" rather than "timeout". examples/deadlines uses that to answer 200 with a partial result instead of 504 with none:
GET /quotes 200 { quotes: [fast, steady], missed: ['slow'], partial: true }
GET /quotes/best-effort 200 x-degraded: deadline β served from onTimeout
GET /feed/live 200 timeout: false, streams to the end
/healthz asks should the orchestrator restart me? /readyz asks should the load balancer send me traffic? Conflating them is why deployments 502 β and the mistake is worse in the other direction, because a liveness probe that checks the database tells every pod to restart at once during a blip, which then guarantees the pools never reconnect.
So a check is readiness unless it says otherwise. Reaching liveness takes a word a reviewer can see.
app.use(healthPlugin, { path: '/healthz', readiness: '/readyz', checks: ['db', 'payments'] })
app.health('db', async (signal) => { await pool.query('select 1', { signal }) })
app.health('cache', probe, { critical: false }) // reported, not fatal
app.health('lag', probe, { kind: 'liveness' }) // deliberate, and visiblechecks: [...] is an assertion, not a filter: if nothing registered payments, the app refuses to boot. Delete the plugin that owned that probe and you would otherwise keep answering 200 for a dependency nobody is watching β the same failure Β§9.7 refuses for hooks.
| Each check | Its own budget and its own AbortSignal, so a wedged dependency is cancelled, cannot hold the endpoint, and cannot hide a healthy one's answer |
| 500 simultaneous polls | 1 probe. Cached by TTL, concurrent probes share one call β CI fails if that regresses |
| Shutdown | /readyz goes 503 first, and the process keeps answering for the whole drain window |
| An app route | 0 bytes. Registering the plugin leaves the generated pipeline byte-identical |
Building it found that the shutdown sequence had been running Β§4.5's steps inverted β pools disposed during the window in which traffic is still arriving. Invisible for as long as it was, because the drain delay defaults to zero and nothing could ask the question. examples/health lets you watch the fixed version:
curl -sX POST localhost:3000/control/db/down
GET /readyz 503 { status: fail, checks: { db: { status: fail } } }
GET /healthz 200 β out of the load balancer, not out of the fleet
curl -sX POST localhost:3000/control/payments/hang
GET /readyz 503 { checks: { payments: "probe exceeded its 600ms budget", db: pass } }
A query string is text. ?page=2 has no way to say the number two, so every
framework deals with it somehow, and all the answers are bad: Express hands you
'2', and the Zod-on-anything pattern makes you write z.coerce.number() on
every numeric field of every query schema forever β where forgetting it produces
no error at all, because '2' > 1 is true.
Zen's position is that the schema already contains the answer (Β§11.4):
app.get('/catalog', {
query: z.object({
page: z.number().int().min(1).default(1), // ?page=2 β 2
inStock: z.boolean().optional(), // ?inStock=on β true
tags: z.array(z.string()).default([]), // ?tags=sale β ['sale']
sku: z.string().optional(), // ?sku=00713 β '00713'
}),
}, ctx => svc.search(ctx.query)) // every field already the right typeEach source's schema is converted to JSON Schema once at boot β the same probe the response serializer and the OpenAPI generator use β and a plan is compiled into that route's validator. Three rules fall out, and each one is a promise that could only be broken silently:
| A position that accepts a string | is never converted. ?sku=00713 stays '00713', and so does z.union([z.string(), z.number()]). Ambiguity is left alone too: if a schema takes a number or a boolean, the wire cannot say which '1' meant |
| Coercion cannot fail | A value it will not convert passes through unchanged, and the schema rejects it with the schema's own message and path. There is one authority on what a valid request is, and it is not the coercer |
| Nothing to convert | no code. Not an empty function β no function. Asserted against the generated bytes in CI |
The sharpest case is precision: ?id=9007199254740993 is an ordinary Postgres
bigint, and Number() turns it into β¦992. An integer-typed value that does
not survive the round trip is left as a string so the schema reports it, because
a visible 400 beats a silent off-by-one on a primary key.
npm run explain -w @erenthedeveloper0/zen-example-coercion prints the derived plan rather
than the profile β an outcome, not a policy, because the question is never "is
numeric coercion on" but "why did ?sku=00713 survive and ?page=2 not":
GET /catalog β catalog.search
coerce query: page β integer, limit β integer, inStock β boolean, tags β array of string (repeat)
validate query
handler searchCatalog
That plan lives on the RouteRecord, so it is also what the OpenAPI generator
reads: a route with arrays: 'comma' is documented as style: form, explode: false, and a generated client sends what the server actually parses. Nobody
wrote the mapping twice.
It is not faster. Converting a string to a number costs what it costs, and the
head-to-head against a hand-written z.coerce is inside the benchmark's noise
(+65 ns per field converted, either way). What it buys is that the behaviour
follows from the declared type instead of from whether somebody remembered β
examples/coercion builds the same service both ways and asserts they answer
identically.
Almost every Node service starts with this line, and it is wrong in two ways that only show up in production:
export const config = { port: Number(process.env.PORT ?? 3000) }PORT=abc produces NaN, which listen accepts. And when DATABASE_URL is
missing, nothing fails until the first request that touches the database.
// zen.config.ts
export default defineConfig({
env: z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().min(1).max(65535).default(3000),
DATABASE_URL: z.string().min(1).meta({ format: 'password' }), // β the secret marker
PAGE_SIZE: z.coerce.number().int().min(1).max(100).default(25),
}),
server: { port: env => env.PORT },
database: { url: env => env.DATABASE_URL, poolSize: 10 },
pagination: { pageSize: env => env.PAGE_SIZE, maxPageSize: 100 },
})const app = zen({ config, env: envSources() })
await app.listen() // the address comes from config.serverValidation runs before anything else boots, and that is literal: a bad
environment means no plugin's setup has run, so nothing has opened a
connection pool (Β§16.2).
Problems are aggregated, because a developer setting up a service has three of
them at once:
Boot failed: 2 problems
1. ZEN_ENV_INVALID DATABASE_URL β ******** was rejected: Too small: expected
string to have >=1 characters (expected: string, min length 1)
at .env.production:4
fix: Correct DATABASE_URL where it is set (.env.production:4).
also: Read by jwt, which will not work without it.
2. ZEN_ENV_INVALID PAGE_SIZE β "1000" was rejected: Too big: expected number
to be <=100 (expected: integer, between 1 and 100)
at process.env
Four things there are mechanisms rather than prose. expected: is read off
the schema, through the same JSON Schema probe the response serializer and the
OpenAPI generator use β nobody wrote "between 1 and 100", so nobody can forget
to update it. at .env.production:4 is why the .env parser returns line
numbers. used by jwt comes from the plugin's manifest, which is why it is
readable before any plugin runs. And ******** is there because
DATABASE_URL is marked and PAGE_SIZE is not: PORT="abc" is only actionable
if you can see the "abc", and a secret is only safe if you cannot.
Then npm run config:explain answers the question no other framework can, because
{...a, ...b} has no memory of a:
server.port 3000 β zen.config
server.host 127.0.0.1 β default
database.url ******** β zen.config (redacted)
mailer.from orders@example.com β mailer
mailer.timeout 3s β zen.config
pagination.pageSize 25 β .env:19
default default 0 of 2 kept
plugin mailer 2 of 3 kept
config zen.config 13 of 13 kept
dotenv .env 6 of 6 kept
Resolution does not produce values, it produces records β { value, layer, source } per leaf β and app.config is the projection that drops the
provenance. So mailer.from β mailer next to mailer.timeout β zen.config is a
fact rather than a guess: a plugin's defaults merge field by field, which is
the difference between a default and a template. And default 0 of 2 kept says
the framework's own server.port is a real layer that lost, not an ?? 3000
hiding inside listen.
Config is deeply frozen after boot, and it redacts itself when serialised β
toJSON and nodejs.util.inspect.custom at every level, so console.log(app.config),
JSON.stringify(app.config.database) and a structured logger all produce
********, while the code that opens the connection gets the real value by
asking for it by name. ctx.config costs nothing: it is a getter over the
app-wide object every context already carries, so a route that never reads
configuration compiles to a byte-identical pipeline and a byte-identical
context class β gated in CI, because the tempting change is to make it a field.
Against the plain module it replaces, reading ctx.config.x.y measures inside
the benchmark's noise. That is the correct result: what this buys is at boot and
in the diagnostics, not in the hot path.
@erenthedeveloper0/zen-middleware ships cors, securityHeaders, requestId and rateLimit.
The interesting thing about them is not that a framework has CORS β every
framework does β but that building them started by measuring whether the usual
shape works. It does not:
| registration | ran on a matched GET, an unmatched path, and a preflight |
|---|---|
app.use(fn) β phase middleware |
1 of 3 |
a global onRequest hook |
3 of 3 |
Phase middleware lives inside a route's compiled pipeline, so a request that
matched no route has no middleware. A browser sends OPTIONS /api/notes before
any cross-origin write, almost nobody registers an OPTIONS route, and a
.use()-registered CORS middleware therefore never runs on the one request the
whole mechanism exists for. The browser reports the failure on the next
request β in a file that is correct β and the usual resolution is origin: '*'.
So every member of the pack is a plugin that registers a global hook:
app.use(securityHeaders())
app.use(cors()) // the allowlist comes from config.cors.origin
app.use(rateLimit())
app.use(requestId({ trustHeader: false }))The second half is what those hooks do. They never write a reply's headers;
they stage them through ctx.res, which egress applies on every path β success,
error, timeout and unmatched alike. An after middleware cannot: Β§4.6
keeps the error path out of user middleware entirely. The difference is a whole
column:
case status access-control-allow-origin x-content-type-options ratelimit
a served request 200 https://notes.example nosniff limit=120, remaining=119
a 404 404 https://notes.example nosniff limit=120, remaining=118
a 422 (bad body) 422 https://notes.example nosniff limit=120, remaining=117
a 401 401 https://notes.example nosniff limit=120, remaining=116
a preflight 204 https://notes.example nosniff β
a preflight, no route 204 https://notes.example nosniff β
a 404, no Origin 404 β nosniff limit=120, remaining=115
Only the first row is one a stamping middleware would have filled in. The rest are why "our API works in Postman but not in the browser" is usually a 500 the browser will not let anyone see.
Three details that fell out of the framework rather than out of the middleware:
Access-Control-Allow-Methods is read off the graph. A read-only API does
not advertise DELETE, and HEAD is advertised even though no RouteRecord
declares it, because Β§4.2 serves it free
for every GET. Add a PUT route tomorrow and the preflight starts advertising
it, with no second file to remember.
The pack orders itself. Register the four backwards and they still run request-id β security-headers β cors β rate-limit, because the ordering is declared in the manifests. It is load-bearing twice: security headers must be staged before anything can short-circuit, and CORS headers before the limiter can refuse β a 429 without them arrives at a browser as a CORS error.
A CORS/CORP contradiction is a boot error naming both settings.
Cross-Origin-Resource-Policy: same-origin and an allowlist that permits
cross-origin reads say opposite things; the CORP header wins and the symptom
appears nowhere in the CORS configuration. Both are plugins on one graph, so
each can read the other's decision.
Measured: +2.02 Β΅s for all four on a cross-origin request, and an app that
imports the pack without registering it compiles a byte-identical pipeline. The
CI gate that matters more is the other one β a disallowed origin is never
reflected, across six shapes of allowlist crossed with eight hostile origins,
because reflecting whatever arrives is the fastest possible CORS and therefore
the shortcut a later optimisation reaches for first.
One number came out backwards and is worth keeping: answering a preflight was
6.2Γ cheaper than not answering one (4.2 Β΅s against 26.1 Β΅s). Dropping it
meant a 404, and a 404 cost ~10Γ a served request β almost all of it one Error
object and its stack. That was a finding about the framework rather than about
the pack, and it has since been fixed: see the refusal path.
app.get('/sales', {
response: {
200: {
'application/vnd.acme.sales.v2+json': SalesV2,
'application/vnd.acme.sales.v1+json': SalesV1,
'text/csv': SalesCsv,
},
404: ProblemShape, // plain form β *not* negotiated
},
}, ctx => sales.list(ctx.query))No /v2/ prefix, no second route, no if (accept.includes('csv')), and no
Vary header written by hand. The Accept header is matched at
stage 5 β before validation, before the
handler, before anything touches a database β and the chosen representation
decides which compiled writer runs and what Content-Type goes out.
Two things about that declaration are worth more than the feature.
The form is the opt-in. 200: SalesV2 is not negotiated and emits no
negotiation code: no Accept read, no Vary, no branch. 200: { 'application/json': SalesV2 }
is, even with one media type in it. There is no negotiate: true option,
because an option is a second place to say something the declaration already
says β and two places can disagree. A route that declares one representation
compiles to the same bytes it compiled before this feature existed, which is a
CI gate, not an aspiration.
Versioning by media type is free. Two of those three are JSON, so both are
written by the same compiled serializer Zen already had β with the same
guarantee that an undeclared field cannot be emitted. A +json vendor type
needs no encoder at all, and a client pinned to v1 keeps getting v1 from that
URL forever. It is the most common real reason to negotiate and it is the
cheapest.
text/csv is not something a zero-dependency package can ship, so it is a seam,
shaped exactly like the schema-converter seam:
registerMediaEncoder('text/csv', (schema) => {
const columns = Object.keys(schema?.items?.properties ?? {}) // once, at boot
return (rows) => /* per request: appends strings */
})A factory, not a function β it receives the response schema and returns a
writer, so everything schema-shaped happens at boot and the per-request half
appends strings. Two things fall out. The columns come from the schema, so the
CSV inherits the leak-proofing rather than re-implementing it: examples/negotiation
puts an internalMargin on every row and it reaches neither format, with
nothing in the handler removing it. And a declared media type with no
encoder is a boot error naming the fix, because the alternative is booting fine
and sending a JSON body under Content-Type: text/csv, which is discovered by
whoever opens the file rather than by whoever deployed it.
Then the part that is just HTTP done properly:
Accept status Content-Type why
(none) 200 v2 the server preference β declaration order
*/* 200 v2 ditto: the client expressed none
text/csv 200 csv an exact match
v1 200 v1 a client pinned to v1, forever
text/* 200 csv a subtype wildcard
v1;q=0.8, v2;q=0.9 200 v2 quality decides
v2;q=0.5, v1;q=0.5 200 v2 a tie β the server decides
text/csv;q=0, */* 200 v2 anything EXCEPT csv
*/*;q=0, text/csv 200 csv nothing, EXCEPT csv
*/*;q=0 406 problem+json nothing at all
application/pdf 406 problem+json we cannot produce it
garbage 200 v2 unreadable β treated as absent, not as a refusal
Rows 8 and 9 are the ones implementations get backwards. RFC 9110 Β§12.5.1 says
the most specific matching range decides an offer's quality β so
text/csv;q=0 overrides the wildcard that would otherwise allow it. Scoring by
"the highest q among matching ranges" is the obvious implementation and the
faster one, and it serves the client the single format it named and refused.
Nobody writes q=0 by accident. It is a CI gate, five shapes of offer list
crossed with eight hostile headers, for the same reason the
never-reflect-an-origin gate exists.
Three more details, each of which is somebody's afternoon somewhere:
Vary: Accept is staged before the decision, not after it β so it is on the
406, and on a request that sent no Accept at all. A response without it is one
a shared cache may hand to a client that asked for something else. And in an app
that also uses CORS, Vary: Origin and Vary: Accept come from two subsystems
that know nothing about each other and must accumulate; there is a smoke check
over a real socket for the pair, because both in-process readers had that exact
defect once.
A status declared in the plain form keeps its own Content-Type. Ask for
CSV, get a 404, and the body is application/problem+json β not a one-row CSV
file. A CSV parser handed a JSON object reports a parse error at line 1, so the
bug report says "the export is corrupt" rather than "the id does not exist".
Two statuses that offer different media types is a boot error. Accept is
matched once, before the handler runs, so the offer list cannot depend on a
status that does not exist yet β and the order is part of it, because
declaration order is the server's preference and it decides ties.
Measured: ~1 ns for no Accept header, ~4 ns for an exact declared
type, ~10 ns for a cached browser header β against ~850 ns to parse one, so
roughly 50Γ and 100Γ. Per request, four of five Accept shapes are
inside the measurement noise.
And one number that came out backwards, again: a 406 cost 13Γ the 200 it
would otherwise have been (35.7 Β΅s against 2.8 Β΅s). Not a negotiation cost β
the matcher answered in the nanoseconds above. It was the Error object and its
stack: the same finding the middleware pack surfaced from behind a preflight,
reached from the other direction. Two features arriving at one number is what
made it a property of the framework's refusal path, and it is now fixed.
A 404, a 405 and a 406 are the cheapest hostile traffic there is, and all three
used to arrive with a free amplification factor: an Error whose stack was
captured β twice β and which could only ever point at the dispatcher. A refusal
the framework makes is now built without a stack, and every ZenError captures
its stack once. An error a handler throws keeps its stack, because that one
points somewhere worth reading.
Measured (node benchmarks/refusals/run.ts, paired arms, one machine):
| before | after | |
|---|---|---|
| 404, no route | 10.0 Β΅s β 5.6Γ a served 200 | 4.2 Β΅s β 2.3Γ |
| 405, wrong method | 10.6 Β΅s β 5.7Γ | 4.7 Β΅s β 2.6Γ |
406, Accept: application/pdf |
17.5 Β΅s β 9.5Γ | 6.4 Β΅s β 3.6Γ |
Re-measured in 0.2.0-alpha: 3.8, 4.2 and 5.1 Β΅s β no dearer than above, and now 4.6β6.1Γ a served
200, because a served request itself fell to ~0.84 Β΅s in process.
| 404 thrown by a handler (keeps its stack) | 15.4 Β΅s | 10.8 Β΅s |
The CI gate is structural, not timed: it fails if a framework refusal captures a stack frame, or if an application's error stops keeping its own.
The two oldest bugs in server-rendered HTML are a string that reaches a page unescaped and a redirect that goes wherever the query string says. Neither is something an application should have to remember (Β§19.5):
import { html, isLocalUrl, NotFound } from '@erenthedeveloper0/zen'
import { z } from 'zod'
app.get('/notes/:id<int>', (ctx) => {
const note = notes.find(ctx.params.id)
if (note === undefined) throw new NotFound()
return html`<h1>${note.title}</h1>
<p>${note.body}</p>
<a href="${ctx.query['from']}">Back</a>`
})
app.get('/login', { query: z.object({ next: z.string().default('/') }) },
(ctx) => ctx.redirect(isLocalUrl(ctx.query.next) ? ctx.query.next : '/'))html is a tagged template, and the template is what gets analysed β once,
the first time it renders, the way the HTML tokenizer will read it β so every
hole is escaped for where it sits:
| a hole in | gets |
|---|---|
| element content | escaped; a nested html`β¦` is written as markup, which is how fragments compose |
| a quoted attribute | escaped, including a nested fragment β markup means nothing there |
href, src, action, β¦ |
escaped, and replaced with about:invalid#zen-unsafe-url if its scheme could run script β javascript:, JaVa\tScRiPt:, data: |
<script src>, <form action>, <base href>, β¦ |
the same, and the value may not choose the origin: a link elsewhere is normal, a script from elsewhere is the attack |
<script>, onclick="β¦", an unquoted value, a tag or attribute name |
refused β ZEN_HTML_UNSAFE on the first render, because no escaping function makes a value safe there |
<title>, <textarea>, <noscript>, <svg>, β¦ |
escaped; a nested fragment is refused if it could end the text element, or carry a script only HTML can read into SVG |
The refused row is the one a helper that only escapes cannot have.
onclick="go('${x}')" is entity-decoded before the script runs, so an escaped
quote is a quote again by the time it matters; <div ${attrs}> needs no special
character at all to become onmouseover=alert(1). Those templates are bugs in
the template, so they fail in the first test that renders them.
The last row is there because HTML and SVG read some elements differently:
HTML ends a <noscript> at the first </noscript in it β even one inside what
looks like an attribute value β and inside an <svg> a <style> or <script>
holds markup rather than text. A fragment can be nested anywhere, so the tag
keeps both readings and refuses any template, or nested fragment, on which they
disagree about where an element ends. The test suite has a spec-conformant HTML
parser judge random pages built that way; against the tag's first version it
finds a value in an attribute name within two hundred pages.
ctx.html() takes the SafeHtml that html returns and nothing else β a plain
string is a compile error, and a ZEN_HTML_UNSAFE for a caller without types.
Markup the application already trusts, a template engine's output say, is marked
with unsafeHtml(markup), which is spelled for a code review. A handler may also
just return html`β¦`, the way it returns a string.
ctx.redirect() sends a path, a query or a fragment. Anything that leaves the
origin β including //evil.example, /\evil.example and a tab between two
slashes, each of which has slipped past a regular expression somewhere β is
refused unless its origin is listed:
const app = zen({ redirect: { allowExternal: ['https://accounts.google.com'] } })The reference is read the way the browser reads the Location header, by a
scanner that is fuzzed against the WHATWG URL parser; an absolute URL to the
application's own host is treated as external, because only the Host header
could say otherwise and the client writes that.
Measured (node benchmarks/injection/run.ts, paired arms, one machine):
| a hostile value in 7 positions Γ 12 payloads | never escapes its hole β judged by the WHATWG parser (gate) |
| a hostile redirect under 3 policies | never reaches an origin it was not allowed (gate) |
escapeHtml against a regex replace |
1.5β2.7Γ faster |
html`β¦` with six holes and an href |
1.6Γ the same card built by hand β which writes javascript: into the href |
ctx.redirect('/path') |
+34 ns |
a JSON handler, for () => html`β¦` |
inside noise |
Two of those rows came out of the benchmark rather than into it. The first
escapeHtml was a character scan alone and lost the clean-text case by 30Γ,
because the regex engine finds "nothing to escape" in a kilobyte in ~70 ns; it
now searches first. And checking every object a handler returns for SafeHtml
cost 13.5% of finalize on every JSON response in every application β so a
fragment is now an async iterable of its own markup, and the check moved into
the branch finalize already takes for streams.
app.get('/notes/:id<int>', { name: 'notes.show' }, showNote)
app.url('notes.show', { id: 7 }) // '/notes/7'
app.url('notes.show', { id: 7 }, { from: 'feed' }) // '/notes/7?from=feed'
notes.post('/', { body: NewNote }, (ctx) => {
const note = service.create(ctx.body)
return ctx.json(note, { status: 201, headers: { location: notes.url('notes.show', { id: note.id }) } })
})A route's name and segments are already on the frozen graph, so reverse routing
is a read of it (Β§5.7). What url()
adds over a template literal is a guarantee: the URL it returns is one the
named route answers, with the values it was given β or it throws.
| written by hand | what url() does |
|---|---|
/files/${name} with a/b?c#d is another path, a query and a fragment |
each value is percent-encoded as exactly one segment |
/files/${'..'} is a link to / β a browser resolves it, %2E%2E too |
., .. and '' are refused: no URL can carry them to the route |
/notes/${'7a'} is a 404 for whoever clicks it |
the parameter's own type tests the value, in the handler that built the link |
/users/${'me'} is answered by GET /users/me |
the compiled router is asked, and the refusal names the route that would have won |
?tags=${tags} |
the query is written the way the route parses it β repeated, comma-joined or bracketed, from its coercion plan |
The result is always a path on this origin, so ctx.redirect() sends it
without consulting redirect.allowExternal. A feature module links through the
collection it is handed (notes.url(β¦)), a plugin through its registrar.
It is checked when it is called rather than by tsc. The design typed it by
route name, and a collection's callback cannot pass a type back out β so a name
nothing registered (ZEN_ROUTE_UNKNOWN, with the one you probably meant) or a
value that cannot build the link (ZEN_PARAM_MISMATCH) fails the first test
that renders it.
Measured (node benchmarks/url/run.ts, paired arms, one machine):
| hostile values over a table of shadowing traps | every link reaches its route with its values; the rest are refused (gate) |
| naming and linking routes | byte-identical generated code (gate) |
| a static route | ~60 ns |
one <int> parameter |
~0.5 Β΅s β about half of it the router match that is the guarantee |
| the table at boot, 500 named routes | 0.13 ms, once |
Building it read route names as keys for the first time, and the reader found
two things the RFC described that did not exist: a collection's name was
supposed to prefix its routes' names, and a params schema was supposed to be
checked against its path at boot. Neither was built; the first is now decided
against β every application already namespaces by hand β and the second was
built in 0.1.0-alpha.4.
git clone https://github.com/erenthedeveloper0/zen.git && cd zen
npm ci
npm run typecheck # builds every package (tsc -b)
npm test # 1,508 tests
node scripts/smoke.ts # 80 checks over a real socket
node scripts/negative-controls.ts # break 190 things on purpose; every suite must notice
node scripts/claims.ts # every "Working today" bullet, probed against the build
node scripts/check-strata.ts # no import in core points up a stratum
node scripts/check-regex.ts # no regex in framework source can backtrack without bound
node scripts/check-pack.ts # what each npm tarball contains β installed and run outside the repo
node benchmarks/typecheck/run.ts # the M2 gate
node benchmarks/serializer/run.ts # serializer throughput
node benchmarks/openapi/run.ts # document generation + per-request cost
node benchmarks/hooks/run.ts # hook cost, and the zero-code assertion
node benchmarks/deadlines/run.ts # what a deadline costs, and the same assertion
node benchmarks/health/run.ts # stampede safety, probe isolation, zero route cost
node benchmarks/coercion/run.ts # what a conversion costs, and what a declared string does not
node benchmarks/config/run.ts # what config costs a request (nothing), and the redaction gate
node benchmarks/middleware/run.ts # what the pack costs, and the never-reflect gate
node benchmarks/negotiation/run.ts # what Accept costs, and the never-serve-a-refusal gate
node benchmarks/refusals/run.ts # what a 404/405/406 costs, and the no-stack gate
node benchmarks/request-path/run.ts # what the audit's fixes cost, and where their code is not emitted
node benchmarks/injection/run.ts # what escaping and redirect checks cost, and the never-escape gates
node benchmarks/url/run.ts # what a link costs, and the never-reach-another-route gate
node scripts/show-generated.ts # read what the pipeline compiler emitted
node scripts/show-serializer.ts # read what the serializer compiler emitted
npm run explain # print the resolved chain for every route
npm run explain:deadlines # every route's budget, and where it came from
npm run health:explain # which dependencies are probed, and by whom
npm run explain -w @erenthedeveloper0/zen-example-coercion # what each route converts, and what it leaves alone
npm run config:explain # where every configured value came from
npm run middleware:explain # which responses carry which headers, and why
npm run negotiation:explain # what each Accept header gets, and what the plain route paid
node examples/hello-world/src/main.tsWorking on the repository needs Node β₯ 22.18: the sources run straight through Node's type stripping, which is unflagged from 22.18, with no bundler. The published packages need Node β₯ 22.6. CONTRIBUTING.md has the rest.
| Suite | What it proves |
|---|---|
app.test.ts |
Routing (including absolute-form targets, + in paths, HEAD on wildcards and all()), middleware at every scope, next() as a Promise on the sync fast path, slots and their disposal, errors, boot diagnostics, body handling (+json included), every error class with a code of its own (a 503 thrown on purpose is not ZEN_INTERNAL; a bad Host is not an invalid body), and an abort classified by whose it was |
plugins.test.ts |
Registration, dependency resolution, cycles, versions, capabilities β read from the adapter, and a string requirement asked for exactly β semver; options validated before any setup runs (the typo named with the key it meant, an async schema awaited, the schema's output handed to setup, a factory's bound options checked, values never quoted); both doors to onBoot firing in order; and app.meta reaching the graph |
di.test.ts |
Lifetimes, request scoping, cycle + captive-dependency detection, disposal order β and request-scoped services released at the end of every request, the failed ones included; a service implementing Symbol.dispose or Symbol.asyncDispose released through it, and an explicit dispose winning |
serializer.test.ts |
Field filtering, escapes, number/date policy, unions, $ref, strict mode, boot diagnostics |
hooks.test.ts |
All nine pipeline phases in lifecycle order, three-scope resolution and the mirror, short-circuits, the error path, phase availability, and that a hookless route generates no hook code |
timeouts.test.ts |
Budget resolution across the scope chain, timeout: false, the arm answering on time, 408-vs-504, onTimeout and its stage, the pipeline stopping at the boundary, one-way header propagation, that an unbounded route generates no deadline code β and, in a child process with nothing else alive, that an inject() only its deadline can answer is answered before the process exits |
health.test.ts |
That liveness runs no dependency probes and readiness runs no liveness ones, the starting β live β draining β stopped transitions, per-check budgets and cancellation, single-flight under 200 concurrent probes, critical: false, withheld error text, a missing required check refused at boot, and that close() reports draining before the server stops accepting |
differential.test.ts |
Compiled pipeline β‘ interpreted pipeline over every step pair + 300 random chains; compiled hooks β‘ the twin over 200 random hook plans; and deadlines β‘ the twin over 200 chains where the client leaves at a random position β agreeing on which boundary abandoned it, not just that one did. All three assert their own coverage, so an agreement that ran nothing cannot pass β and the speculative sync path β‘ the twin over 400 random chains of plain functions that return a value on one call and a promise on the next, including that a route of plain functions emits no async and no await, and that 33 speculation points fall back to the async form |
serializer-differential.test.ts |
Compiled β‘ walking serializer over 2 500 generated schema/value pairs, plus "no undeclared key reached the wire" |
context.test.ts |
Compiled context β‘ PlainContext; monomorphism (%HaveSameMap); headers, query, cookies, egress; ctx.ips and ctx.protocol under every trustProxy setting, as getters; ZEN_REPLY_SENT from a builder kept past egress and from ctx.res re-read after it; inject() from a given peer; slot values released through their own disposal protocol; and ctx.log bound to the request id and route on both twins, made on the first read, remade when ctx.id changes, and never made for a request that does not log |
router.test.ts |
Path syntax, param types, conflict classes β every overlapping pair of builtin param types refused and every disjoint pair left alone β typed params tried in the same order whatever the registration order, compiled β‘ interpreted router; and that a match leaves nothing for the next β no captures, no Allow β even when a parameter type matches a path from inside one |
types.test.ts |
Type-level inference incl. negative @ts-expect-error cases; the M2 budget |
openapi.test.ts |
Path/param/schema mapping, $ref dedup, documented fields β‘ fields the compiled serializer emits, and the diff classifier β which compares what a schema says rather than how its converter spelled it: zod 4.4's anyOf and 4.6's type list are one schema, a field removed inside a nullable union is breaking, and a recursive component is compared to where it repeats instead of overflowing the stack; security schemes a plugin declares with app.meta, and a writeOnly field withheld from every response schema |
examples/openapi |
The same drift check over real requests, plus the API compatibility gate |
examples/observability |
Bounded metric cardinality, per-stage attribution, that onResponse measures more than onSend can, and that a transform hook cannot smuggle a field past the response contract |
examples/deadlines |
That a sliced budget drops a slow provider instead of the request, that the provider was cancelled rather than merely stopped waiting for, that onTimeout can serve a partial 200, and that an inbound header shortens the budget but never lengthens it |
examples/health |
That a dead dependency takes the pod out of the load balancer and not out of the fleet, that a non-critical one only warns, that a hanging one cannot hold the endpoint or hide a healthy sibling, that 100 simultaneous polls cost one round trip, and that readiness goes red while the service is still answering |
config.test.ts + config-properties.test.ts |
Layer precedence and per-value provenance, environment validation running before any plugin's setup, aggregated per-key diagnostics with the constraint read off the schema, secrets absent from every projection, the deep freeze, and that ctx.config changes no generated byte. The property suite fuzzes 2 000 random layer stacks for six invariants β it is not a differential suite, because configuration compiles nothing, and it caught a collision rule the hand-written test passed against |
examples/config |
The same claims against real Zod: .meta({ format: 'password' }) marking a secret, expected: integer, between 1 and 100 read back off z.toJSONSchema, .env line numbers in the error, a plugin's namespace merging field by field, and β checked by tsc, not by an assertion β that ctx.config.pagination.pageSize is a number |
examples/coercion |
That the same service written with Β§11.4 and written with z.coerce answers identically β so adopting it is a refactor and not a behaviour change β plus that a zero-padded SKU survives, that a single ?tags=a is still an array, that a bigint-shaped id is refused rather than silently rounded β and that real Zod's issues get the same issues[].code in English and in Turkish |
cors Β· security Β· request-id Β· rate-limit.test.ts |
That a preflight to a path with no route is answered, that a disallowed origin is refused without the response saying so, that Vary: Origin is present even on a request that had none, that the headers reach the 404 / 422 / 401 / 429 / 500, that an inbound request id is validated before it is trusted, and that a rate limiter sees the requests a router does not |
pack.test.ts |
The claim the design rests on, as a count rather than a description: a .use() middleware ran 1 of 3 requests and a global hook ran 3 of 3. Plus that the pack reorders itself when registered backwards, that a 429 still carries CORS headers, and that an app which does not register it compiles a byte-identical pipeline; and the four options schemas β each factory naming its own misspelt key, a wrong type refused by option name, and no value ever quoted |
rate-limit-differential.test.ts |
The evicting store β‘ a never-evicting reference over 2 000 random request streams, with coverage assertions on boundaries crossed and keys reused across one β and the single clock-step case where they legitimately differ, pinned in its own test with its direction (it can only undercount) |
examples/middleware |
The composition rather than the plugins: an allowlist arriving from CORS_ORIGINS through a Zod-validated environment, a preflight advertising only the methods the graph actually serves, a 404 flood consuming the budget, a note stored with a <script> in it rendered as text, a ?next= that cannot leave the origin, and β checked by tsc β that ctx.config.cors.origin is a string[] and that ctx.html('<p>') does not compile |
negotiation.test.ts |
The matcher against RFC 9110 Β§12.5.1 β specificity beating quality, ties going to the server, q=0 never served β plus Vary: Accept on the 406 and on a request that sent none, a plain-form 404 keeping application/problem+json, a 406 refusing before body intake, and that a route with one representation emits no negotiation code; and a writeOnly field refused at boot in every representation and every encoder β through arrays, records, unions and recursion β while a format: 'password' warning keeps the route negotiating |
negotiation-properties.test.ts |
Six invariants over 2 000 random offer sets Γ Accept headers, the load-bearing one being that a refused representation is never chosen; and a real differential β the cached negotiator against the uncached matcher over 2 000 random streams, because the bugs a cache introduces are order-dependent |
examples/negotiation |
Three representations of one resource against real Zod: a client pinned to v1 staying pinned, CSV columns taken from the same schema the JSON fields come from, a field the database has and neither format contains, a spreadsheet-formula cell neutralised, and β checked by tsc β that ctx.negotiated is string | null |
adapter.test.ts (adapter-node) |
Over real sockets, because inject() could not see any of it: a request body does not abort ctx.signal, a POST under a deadline is answered rather than abandoned, a client leaving mid-stream neither crashes the process nor logs a failure, a missing file is a 404 rather than a dropped connection, a path cannot escape its root (symlinks included), 304/206/416 and HEAD for files, SSE framing, heartbeats and disconnects, that shutdown neither waits on idle keep-alive connections nor severs event streams, and the ingress limits over a bare socket β a 414 at one byte past maxUrlLength with nothing dispatched, Node's 431 past 8 KB of headers, maxRequestsPerSocket's Connection: close and 503 |
sse.test.ts |
The event-stream framing, including a line break in event or id refused rather than forging a field; graceful close(); the maxBuffered bound; heartbeats that start only when something reads; and ctx.sse() on both context twins |
json-intake.test.ts |
That parsing a body without a reviver is exactly as strict as parsing it with one: 2 000 hand-written texts β forbidden keys spelled with \u escapes, the words inside values, near misses, truncated JSON β each parsed to what the reviver produces or refused by both, with coverage asserted on every branch; the depth limit refusing exactly what the per-value walk refused over 3 000 nestings; and a clean body never handed a reviver |
issue-codes.test.ts |
A vendor's issue mapper deciding issues[].code from the issue's own fields whatever the message's language β on async validators and combined sources too, looked up when a request fails so a late registration still applies β and a missing value required before any mapper is asked, an inherited key not counted as present |
validation.test.ts |
A bad query and a bad body are reported in one response, each issue tagged with its source; 422 only when the body alone failed; async validators collected too; and a one-source route compiles exactly as before |
registration.test.ts |
Registrations that could never take effect are boot errors: a typo'd hook phase (with the phase you meant), an application phase on a route, a decoration that would shadow ctx.json, two routes sharing a name, a params schema its path cannot satisfy β one test per case of Β§5.2's table β and a collection when that answers with something other than a boolean; a subtree when turned off absent from router, graph and hooks; route-scoped use in the right place in the chain; app.paramType(); one boot per application however many callers race for it, and a failed boot that stays failed; and a shutdown that completes when an onClose hook throws |
origins.test.ts |
Every registration surface records the line that made it β every verb, collections and their options, middleware and hooks at each scope, services, checks, decorations, plugins and defineConfig β and a catalogue provoking every boot diagnostic core can raise, each required to print the lines of what it is about; scripts/placed-boot.ts, loaded before every suite, fails any test whose boot error has a diagnostic with no line |
error-engine.test.ts + dev-errors.test.ts |
The formatter circuit breaker opening once and closing on the first success; a development 5xx naming its route's registration line, the application line that raised it and the code around it, the chain and the docs; the HTML page escaping every value and keeping the error's own headers; production carrying none of it; and the terminal rendering, with OSC 8 links, written only to a terminal |
graph-document.test.ts + contract-oracle.test.ts |
The graph round-tripping to canonical JSON with one fingerprint across ten shuffled boots, unmoved by where code sits, by re-ordered lists or by slots another module declared, and moved by a swapped pair of hooks; and the oracle β a thousand seeded schema edits on which the contract fingerprint and diffDocuments must agree about what changed |
explain-request.test.ts |
Every step that ran, in order, with what it did β a refusal showing where the request stopped, a short-circuit, an unmatched request β and the instrumented pipeline never installed: concurrent and later requests run the production one, and nothing is compiled into the application |
route-spec.test.ts + middleware-definitions.test.ts |
check answering as a 422 with its source, inject resolving singletons once at boot and request-scoped services per request, per-route body limits and the raw and streamed body modes; defineMiddleware options validated at boot with setup run once, and when: { env } omitting a step from the pipeline while when: { request } guards it |
policy.test.ts + response-validation.test.ts |
Request policy read from configuration with a source per value, zen() options as its sugar and the hardened profile as a named source; a wrong response value refused under 'error', logged under 'log', sampled, and β when off β no emitted code at all |
testing.test.ts |
The testing kit as an application uses it: a fake winning over a provider a plugin registers at boot, configuration at the override layer, a booted factory refused, a timer left running named by assertNoLeaks, and a handler called on testContext(); the type fixture holds a fake of the wrong shape to a compile error |
examples/* |
Each of the ten examples boots ten times to one graph fingerprint, and refuses a seeded wrong-type value in a response |
leaks.test.ts |
Β§20.7's first two properties, which no other suite checked: a real port served β SSE, a deadline kept and one blown, a file, a health probe β and closed with nothing left holding the process open, and 500 interleaved requests that each read back only the slot values, hook state and scoped instance they wrote |
generated-source.test.ts |
Everything the compilers emit for one fixture application β context class, params builders, pipelines with every hook phase, coercer, serializers β against a committed snapshot, so a compiler change is a reviewable diff of code; and that an app keeps none of it after boot unless built with inspect or dev, and says so instead of answering with an empty list |
regex-safety.test.ts |
The analyser behind Β§19.3's lint, against the shapes that backtrack ((a+)+, (a|aa)+, (-?[a-z]+)*) and the idioms that must not be refused ([a-z0-9]+(?:-[a-z0-9]+)*); and app.paramType() warning about a test that can backtrack, in development only |
lifecycle.test.ts (meta-package) |
A real child process: SIGTERM drains and exits 0, an uncaught exception or unhandled rejection drains and exits 1, and nothing is installed on the process until listen() |
error-docs.test.ts |
Every error code any package can produce has its entry in docs/errors.md β the page every problem document links to |
scripts/claims.ts |
That the docs are true: each "Working today" bullet above and each "Status: built" block in the architecture names a probe, run against the built packages; and each gap the docs admit names one that asserts it is still a gap, so the day it closes the build fails until the docs say so |
logger.test.ts |
The default logger never throws β a cycle or a bigint in an error's metadata still produces the log line and the error response β and metadata cannot overwrite a line's code or status |
id.test.ts |
The request id every request carries: ULID-shaped, its first ten characters the millisecond it was made in, and counting up by exactly one within a millisecond across every carry β the property a generator that re-encodes only what changed could break |
html.test.ts |
Every position a hole can take β escaped in content and in both quotes, a javascript: URL replaced in every spelling a browser accepts, a <script src> held to the origin, and each position escaping cannot fix refused on the first render β plus a SafeHtml no JSON body or borrowed prototype can forge, and the templates HTML and SVG would read differently refused. Then property suites judged by the WHATWG URL parser, a grammar for escaped text, and parse5 β a spec-conformant HTML parser that parses 2,000 random pages, fragments nested in fragments, and reports where every value landed. None shares code with the tag |
redirect.test.ts |
Paths, queries and fragments sent; every spelling that has slipped past a regex refused (//, /\, a tab, a leading space, https:host, userinfo); the allowlist's look-alikes refused; a malformed allowlist entry a boot error with the spelling that would match β and a real differential: the reference scanner against the WHATWG URL parser over 2,000 random targets, with its coverage asserted |
url.test.ts |
A value encoded as one segment whatever it holds; a number, a bigint and a Date written the way their routes read them back; ., .., empty values, objects and lone surrogates refused; each way one route outranks another β a static segment, a typed parameter, anything over a wildcard β refused with the winner named; the query written in the route's own list style; reachable from a collection and a plugin. Then a property suite: 2,000 links from hostile values over a table of shadowing traps, put through the WHATWG URL parser the way a browser treats an href and sent to the app, which must answer on the named route with the values given β coverage asserted per kind of refusal |
scripts/negative-controls.ts |
That the suites above are load-bearing. A hundred and ninety known defects patched in one at a time; each must make its named suite β or, for the strata, regex and claims checks, its script β fail. It caught a fuzzer asserting on a branch its generator never produced, a test aimed at a code path that could not reach the behaviour it claimed to cover, a guard proven unreachable β and a test that probed for a free port with the very call it was testing, so the defect and the probe agreed |
packages/
core/ registries Β· compilers Β· runtime Β· context Β· errors (0 deps)
router/ compiled + interpreted radix routers, conflict analysis
adapter-node/ the optimised Node path
openapi/ AppGraph β OAS 3.1, $ref dedup, diffing, viewer
middleware/ cors Β· securityHeaders Β· requestId Β· requestLog Β· rateLimit + the Store seam
zen/ meta-package: wires core + router + adapter + middleware
examples/
hello-world/ routing, slots, the three middleware forms, a response schema, streaming
rest-api/ response contracts, plugins, DI, validation β the full tour
openapi/ Zod, OAS 3.1, the API diff gate β and the RFC's recommended layout
observability/ the hook system running: metrics, request log, Server-Timing
deadlines/ budgets, propagation, cancellation, partial results on timeout
health/ liveness vs readiness, per-probe budgets, a watchable drain
coercion/ ?page=2 is a number, ?sku=00713 is not β and the same app both ways
config/ layered config, env validation, provenance, redaction
middleware/ a browser-facing API: preflights, 429s browsers can read, pages that escape and link
negotiation/ one resource in three representations, and the encoder seam
benchmarks/ serializer, OpenAPI, hook, deadline, health, coercion, config,
middleware, negotiation, refusal, request-path, injection, URL and boot cost;
the M2 gate; Zen against node:http, Fastify, Hono and Express
scripts/ smoke test, negative controls, codegen inspectors, and release
tooling: version.ts, check-release.ts, check-pack.ts
docs/errors.md every error code β where each problem document's `type` points
ARCHITECTURE.md RFC 0001 β the full design
RELEASING.md how the packages get to npm, and why that way
CONTRIBUTING.md conventions, setup, sign-off Β· SECURITY.md Β· CODE_OF_CONDUCT.md
@erenthedeveloper0/zen-core has zero runtime dependencies, and imports nothing from node:.
npm run example # hello-world β five minutes to understand
npm run example:rest # rest-api β plugins, DI, validation, response contracts
npm run example:inspect # what rest-api compiled to
npm run example:openapi # openapi β then open /docs
npm run openapi:check # the API compatibility gate
npm run example:observability # observability β then curl -i /products/1 and /metrics
npm run example:deadlines # deadlines β then curl -i /quotes and /quotes/best-effort
npm run example:health # health β then break a dependency and watch /readyz
npm run example:config # config β then try PAGE_SIZE=1000 and DATABASE_URL=
npm run example:middleware # middleware β then send a preflight to a path that does not exist
npm run example:negotiation # negotiation β then ask /api/sales for text/csv, then for a PDF
npm run explain # the resolved hook + middleware chain, per route
npm run explain:deadlines # every route's budget, and the scope that set it
npm run health:explain # every dependency, its budget, and who registered it
npm run config:explain # where every configured value came from
npm run middleware:explain # which responses carry which headers, and why
npm run negotiation:explain # what each Accept header gets, and what a plain route paidexamples/rest-api is the one to read. It is a user
directory whose UserRow carries passwordHash, totpSecret,
stripeCustomerId and internalNotes, and whose handlers return those rows
unmodified:
users.get('/:id<int>', { response: { 200: PublicUser } }, (ctx) => {
const row = ctx.resolve(UserRepoToken).find(ctx.params.id)
if (row === undefined) throw new NotFound(`User ${ctx.params.id} not found`)
return row // β all ten fields
})handler returned: {"id":1,β¦,"passwordHash":"$2b$12$β¦","totpSecret":"JBSWY3DPEHPK3PXP",β¦}
wire: {"id":1,"email":"ada@example.com","name":"Ada Lovelace","role":"admin","createdAt":"β¦"}
It also carries a 150-line schema library written inside the example, which the framework has never heard of β that is the cleanest demonstration that "works with Zod, Valibot and ArkType" is a consequence of Standard Schema rather than a list of integrations Zen maintains. One declaration drives both the request validator and the response serializer.
examples/openapi is the same idea taken one step
further, with real Zod and a generated document:
handler returned : {"id":1,β¦,"passwordHash":"$2b$12$β¦","totpSecret":"JBSWY3DPEHPK3PXP",β¦}
wire : {"id":1,"email":"ada@example.com","name":"Ada Lovelace","role":"admin","createdAt":"β¦"}
document says : properties: id, email, name, role, createdAt additionalProperties: false
All three agree, and the suite proves it by making a real request for every
documented response and comparing the keys. The Zod integration is four lines in
application code; neither @erenthedeveloper0/zen-core nor @erenthedeveloper0/zen-openapi imports it.
It is also the first example laid out the way
Β§23.4 recommends β
feature-first, with src/features/{users,orders}/ owning their own routes,
schemas, service and tests. So yes: Zen has an opinion about your folder
structure, it is written down, and now it runs.
examples/observability is the hook system doing
something worth doing. One plugin touches ten phases and produces a Prometheus
endpoint, a structured request log, and a Server-Timing header β and no
feature file knows it exists. There is no withMetrics(handler) wrapper, no
logger.info at the top of each handler, and no timing middleware to remember
to register, which is the actual test of whether a cross-cutting concern was
kept cross-cutting.
npm run explain prints what each route resolved to, with provenance:
GET /admin/orders β admin.orders
onRequest [global] metrics.start
onRequest [root/admin] requireAdminKey
onRoute [global] metrics.route
preHandler [global] metrics.preHandler
handler listOrders
onSerialize [global] stampGeneration
onSend [global] metrics.serverTiming
onResponse [root/admin] auditLog
onResponse [global] metrics.finish
Note the mirror: the collection's onResponse runs before the global one, so
onRequest/onResponse pairs nest like a stack rather than queueing.
examples/deadlines is a gateway that fans out to three
providers under a shared budget. No handler in it mentions a timeout β they read
ctx.timeLeft and pass it on, so the same code is correct whether the operator
configures two seconds or twenty, and the budgets are three lines in app.ts.
npm run explain:deadlines answers "what is our request timeout" completely,
which in most codebases takes four files and a guess:
GET /quotes 2000 ms from app
GET /quotes/best-effort 2000 ms from app
GET /reports/quarterly 10000 ms from root/reports
GET /reports/status 250 ms from route
GET /feed/live none β
5/5 application routes are bounded.
Unbounded on purpose: /feed/live
The provenance column is the useful half: the surprising budgets are always the inherited ones.
examples/coercion is a catalogue whose query string
carries numbers, booleans, lists and a zero-padded SKU β every case that makes
the problem interesting, in one endpoint. src/app.ts builds the service
twice: once as written above, and once with coercion: false plus
z.coerce and the hand-written z.preprocess you need for the
single-value-array problem, which z.coerce has no answer for at all. The tests
assert the two answer identically on the same requests β which is a stronger
claim than "the feature works": it says adopting it cannot change behaviour,
because the behaviour is the one people were already hand-writing.
examples/config is the one that makes the layering
visible. process.env appears exactly once in it β in the fifteen lines
that read .env files, where it is I/O rather than configuration β and every
other file reads ctx.config. Try PAGE_SIZE=1000 npm run example:config for
a bound enforced at boot rather than on the first slow report, and
DATABASE_URL= npm run example:config for a missing secret reported without
being printed.
It also shows the framework's own boundary honestly: core parses .env text and
states the precedence, and opens no files, because fs and process do not
exist on workerd. And it names the gap it does not close β secrecy propagates by
identity, so url: env => env.DATABASE_URL inherits the marking and
`${env.DATABASE_URL}?replica=1` does not. There is a test asserting the
leak, so the gap cannot move without someone deciding to move it.
Contributions are welcome β CONTRIBUTING.md has setup, the checks to run and the sign-off, and SECURITY.md how to report a vulnerability privately. Read ARCHITECTURE.md first β particularly Β§1.1, the nine invariants. They are numbered so reviewers can cite them, and a PR that violates one needs an argument, not a workaround.
Four rules worth knowing up front:
- Every compiled subsystem needs an interpreted twin, and the differential
suite must pass. Those suites have already caught five real bugs: an
undeclared
let rin generated pipelines, silently dropped middleware, anaroundscoping divergence, a phantom plugin cycle, and a degenerateanyOf: [null, null]the serializer refused instead of collapsing. A fuzzer must also assert its own coverage β two implementations that agree because neither ran anything report a pass and prove nothing. - Build the reader, not just the writer. Every subsystem that consumes
the application graph has found gaps that writing more routes never would.
The OpenAPI generator turned up four in one sitting: param types unreachable
outside the router package, no way for a plugin to register a route, no
nested collections, and a converter seam that could not express
input-versus-output. Building the observability example turned up two more,
both invisible from the spec side:
preHandlerwas running before body intake, and globalonRequesthooks were skipped entirely for unmatched requests β which made rate limiting bypassable by requesting a path that does not exist. Building the deadlines example turned up a third:onTimeouthad been givenonError's nearest-handler rule, so a route serving partial results silenced the plugin counting timeouts β the counter would have read zero on exactly the routes that handled their deadlines best. And the health endpoints turned up the sharpest one: graceful shutdown had been running Β§4.5's steps inverted, disposing the connection pools during the window in which the load balancer is still sending traffic. It survived writing, implementing and reviewing because nothing could ask it a question β "readiness flips before the socket stops accepting" is not a checkable sentence until a readiness endpoint exists. The count is now five: the configuration example's provenance table found that the environment section was enumerating every variable in the process, which buried the relevant rows and put the name of every variable on the AppGraph β where a name is topology even when the value is withheld. - A test that passes against the bug is not a test. Before trusting a new assertion, break the thing it covers and watch it fail. The deadline fuzzer was checked that way, and so was a narrow crash the deadline arm could cause: the first version of that test passed with and without the fix, because a plain throwing handler compiles to an async function and the failure needed a genuinely synchronous one. Seven controls were run against the configuration fold and one of them found the same thing again: deleting half of the scalar-versus-branch rule left the resolved object correct and only the snapshot wrong, so the hand-written test for that exact rule passed and only the property fuzzer failed.
- Performance claims need numbers. Losses get published with the same
prominence as wins β see the
seal()result in Β§28.2, which has read anywhere from +0.6% to β10.4% between runs and is decided by the numbers, not by whoever wrote the API; Β§13.3.2, where the serializer came in under its published claim and the claim was corrected rather than the benchmark; and Β§29.8, where naming your schemas turned out to be worth 8% rather than the large saving expected, and the first version of that benchmark was thrown out for measuring an artefact of its own fixture. The hook benchmark cost two drafts for the same reason: the first measured throughinject(), putting ~2 Β΅s of scaffolding around an effect of tens of nanoseconds, and reported a per-hook cost that fell as hooks were added. Where a structural assertion is available, prefer it β "the generated source is byte identical" beats "the difference was inside the noise", because the second is also true when the cost is real and small.
MIT Β© Eren SΓΌmer. Everyone who has contributed is listed in CONTRIBUTORS.md.