Author SHA1 Message Date
chrnxandClaude Opus 5 180de79462 docs: describe the mechanism instead of asserting adjectives
npm shows this line in search results, and "a zen, opinionated, type-safe
framework" is three adjectives a reader cannot verify. Zen is a real claim
here — the framework does the wiring so you write business logic — but it
lands only when the mechanism is visible.

So: state what you declare, and the three things the framework does with it.
Those three are exactly the work it takes off your hands, which is the claim,
demonstrated rather than announced.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 14:41:09 -05:00
chrnx 4f504eda11 Merge branch 'develop' into docs/observability-scope-and-analytics
CI / build (pull_request) Successful in 34s
2026-08-07 19:27:37 +00:00
chrnx 94ab334d85 Merge pull request 'chore: clear the dependency advisories blocking CI' (#17) from chore/audit-advisories into develop
CI / build (push) Successful in 33s
Reviewed-on: #17
2026-08-07 19:27:21 +00:00
chrnxandClaude Opus 5 3a8d93320d chore: clear the dependency advisories blocking CI
CI / build (pull_request) Successful in 33s
Both audit trees were failing, for unrelated reasons and with different fixes.

**Root — undici, high.** miniflare 4.20260730.0 (the newest stable) pulls
undici 7.28.0, and the advisory range is 7.0.0–7.28.0. `npm audit fix --force`
wants miniflare 5.20260801.1-alpha: a breaking major, and an alpha, to patch a
devDependency that never ships. undici 7.29.0 is outside the range, so pin it
through `overrides` instead — same approach already used for find-my-way and
hyperid.

**website — js-yaml, high.** Reached through Starlight. 4.3.1 carries the fix
and the bump is not breaking, so a plain `npm audit fix` covers it.

Verified: root and website audits both report 0 vulnerabilities; 357 tests
pass; `test:edge` still passes, which is the one that actually exercises
miniflare against the pinned undici; `docs:build` produces its 23 pages.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 14:22:43 -05:00
chrnxandClaude Opus 5 270480b2d6 docs: fix changelog compare links to point at the public mirror
CI / build (pull_request) Failing after 13s
CHANGELOG.md ships inside the npm package, and its link references pointed at
the internal Gitea host — unreachable for anyone reading the changelog on
npmjs. Point them at the GitHub mirror, and compare Unreleased against `main`,
since `develop` is not mirrored.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 14:13:54 -05:00
chrnxandClaude Opus 5 27f1d103ea docs(website): add privacy-friendly analytics to the docs site
CI / build (pull_request) Failing after 12s
GoatCounter via Starlight's `head` option, same site code as the marketing
site so /docs traffic lands in one dashboard and referrer paths stay
comparable. No cookies, no personal data, no consent banner, nothing to host.

Answers the one question we cannot answer today: do the articles convert into
documentation reads?

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 14:03:39 -05:00
chrnxandClaude Opus 5 0ad53fa284 docs: lead with the problem, document limits, declare the observability gap
The README opened with identity and an install block; the pain that motivates
the graph only appeared after a scroll. Move it up: `req.user` first, then the
idea, then how to install it.

Three fixes while in here:

- The install line now pins `@beta`. `latest` and `beta` both point at the
  newest beta until a stable ships, and the versioning note said the opposite.
- Document `RequestLimits`. Body caps, multipart parts and the request /
  headers / keep-alive timeouts were already applied with defaults tighter
  than Node's, and nothing in the README said so.
- Honest scope now admits there is no observability layer — no logger, no
  metrics, no tracing hooks — and points at the issue tracking it as one
  design. It is the gap a team hits in week one of a real evaluation.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 14:03:37 -05:00
chrnx 5fccd3cc8c Merge pull request 'fix(release): validate npm provenance and mutable staging' (#14) from hotfix/npm-release-provenance into develop
CI / build (push) Successful in 33s
Reviewed-on: #14
2026-08-03 03:44:11 +00:00
chrnx 9398a5a2df fix(ci): keep Verdaccio staging mutable
CI / build (pull_request) Successful in 34s
Replace an existing prerelease before publishing the refreshed candidate. Verdaccio remains mutable for validation while npmjs release versions stay immutable.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 22:42:39 -05:00
chrnx 29aafde84c fix(ci): make Verdaccio staging idempotent
CI / build (pull_request) Successful in 32s
Stage only release branches and preserve immutable versions. Repeated identical candidates now exit successfully, while content changes under an existing version require a prerelease bump.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 22:38:56 -05:00
chrnx dbb996dd4c fix(package): declare npm publication metadata
Link the package to its public source, issue tracker, and documentation so npm Trusted Publishing can validate provenance and consumers receive canonical project links.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 22:38:47 -05:00
chrnx f45ee7d309 Merge pull request 'feat: close router and security gaps for 26.8 beta' (#12) from feat/router-security-beta into develop
CI / build (push) Successful in 39s
Reviewed-on: #12
2026-08-03 02:28:13 +00:00
chrnx 00aef4541b Merge branch 'feat/router-security-beta' into develop
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:22:10 -05:00
chrnx bd3b2556bc docs: remove design whitespace
CI / build (pull_request) Successful in 56s
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:21:13 -05:00
chrnx 87c1226e97 chore(deps): sync deno lockfile
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:19:03 -05:00
chrnx 1db4e01e40 fix(deno): snapshot metadata before websocket upgrade
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:18:40 -05:00
chrnx 74f09d2e0b docs: document router completeness for beta
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:13:59 -05:00
chrnx fcd3df7022 docs(website): align guides with router behavior
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:11:08 -05:00
chrnx 934fbd4c19 ci: gate releases on clean dependency audits
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:03:54 -05:00
chrnx d9276a4769 docs: expand website documentation audit plan
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 21:01:49 -05:00
chrnx 3a56e656bd chore(deps): remediate security advisories
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:56:17 -05:00
chrnx a2acec69bf feat(openapi): document constrained route params
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:47:18 -05:00
chrnx 9a61ba8646 feat(http): complete HEAD and OPTIONS semantics
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:45:44 -05:00
chrnx 63be0ef8f7 feat(router): expose HEAD and OPTIONS decorators
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:40:02 -05:00
chrnx 8e38fffd77 fix(router): reject invalid and ambiguous paths
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:39:09 -05:00
chrnx 790db661e5 feat(router): compile safe constrained patterns
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:36:46 -05:00
chrnx 63a61aeb0b docs: plan router security beta implementation
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:34:03 -05:00
chrnx e343ae501f docs: design router security beta
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-02 20:28:11 -05:00
chrnx e0212d14e5 Merge pull request 'docs: refresh README + docs, host at /docs on expressive-tea.io' (#10) from docs/readme-refresh into develop
CI / build (push) Successful in 29s
CI / build (pull_request) Successful in 23s
2026-07-18 21:08:35 +00:00
chrnx ab6b1b1ef2 Merge pull request 'ci: npmjs Trusted Publishing (OIDC, no token)' (#8) from ci/trusted-publishing into develop
CI / build (push) Successful in 29s
CI / build (pull_request) Successful in 24s
2026-07-18 20:17:41 +00:00
chrnx 1a313c21ad ci: publish prereleases under their channel dist-tag, not latest
CI / build (pull_request) Successful in 24s
A beta/alpha/rc version must not become 'latest' on npmjs (else npm install serves a prerelease). Derive the dist-tag from the version: 26.7.0-beta.0 -> beta, stable -> latest.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-18 14:59:48 -05:00
chrnx 3ff90b418d ci: publish to npmjs via OIDC Trusted Publishing (no token)
CI / build (pull_request) Successful in 23s
Replaces the NPM_AUTH secret on the prod path with npm Trusted Publishing: id-token: write + npm>=11.5.1, npm exchanges the OIDC token for a short-lived publish token and attaches provenance. Requires a trusted publisher configured on npmjs (Expressive-Tea/green-tea, release.yml).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-18 14:53:28 -05:00
chrnx 8e822cad17 Merge pull request 'fix(ci): unpublish before publish to Verdaccio' (#6) from fix/stage-unpublish into develop
CI / build (push) Successful in 24s
CI / build (pull_request) Successful in 24s
2026-07-18 19:08:56 +00:00
chrnx 3fe0016dbd fix(ci): unpublish before publish to Verdaccio (registry rejects overwrite)
CI / build (pull_request) Successful in 24s
The staging registry (npm.svc.zoit.services) does not allow overwriting an existing version, so re-publishing the same prerelease on each main merge failed. Unpublish the version first (tolerant --force, no-op when absent) then publish fresh.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-18 14:08:39 -05:00
chrnx 8bd2a3f61c Merge pull request 'ci: stage/promote/release workflows (two-forge pipeline)' (#4) from feat/ci-publish-workflows into develop
CI / build (push) Successful in 24s
CI / build (pull_request) Successful in 32s
2026-07-18 02:18:28 +00:00
chrnx 96d863d402 ci: use the NPM_AUTH secret for both Verdaccio and npmjs publishes
CI / build (pull_request) Successful in 24s
One secret name across forges: Gitea's NPM_AUTH (org-level) = the Verdaccio token for staging; GitHub's NPM_AUTH = the npmjs token for production. Each forge supplies its own value.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 21:17:17 -05:00
chrnx 33df70730b ci: add stage/promote/release workflows for the two-forge pipeline
CI / build (pull_request) Successful in 23s
stage.yml (Gitea-only): publish package to Verdaccio under 'stg' tag on main merge. promote.yml (Gitea-only): mirror only main + version tags to GitHub. release.yml (GitHub-only): publish stable to npmjs on a v* tag. Forge is detected via github.server_url; secrets: VERDACCIO_TOKEN (Gitea), GH_PROMOTE_TOKEN (Gitea, set), NPM_TOKEN (GitHub, pending).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 20:43:43 -05:00
chrnx 5fc37a2df7 Merge pull request 'ci: relocate workflow to .github/workflows (two-forge compat)' (#3) from chore/ci-two-forge into develop
CI / build (push) Successful in 23s
2026-07-18 01:42:52 +00:00
chrnx 2a84331022 ci: relocate CI workflow to .github/workflows for two-forge compatibility
CI / build (pull_request) Successful in 24s
GitHub Actions only reads .github/workflows; Gitea reads both. Relocating (content unchanged) makes the one gate portable across both forges — the foundation for the Gitea(stg)+GitHub(prod) pipeline.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 20:36:36 -05:00
chrnx 91fe8f8aff Merge pull request 'Deep graphs: O(n²) → O(n), plus a boot warning when they're suspiciously deep' (#2) from fix/pipeline-context-on2 into develop
CI / build (push) Successful in 25s
2026-07-18 00:35:28 +00:00
chrnx 3a4cd5a7ce test(bench): reach bench servers cross-host + add scale and Bun/Deno servers
CI / build (pull_request) Successful in 59s
Fastify and the Nest adapters bound 127.0.0.1, unreachable from a separate load generator; bind 0.0.0.0 so two-machine benchmarks work.

Adds scale-{green-tea,express} (step-vs-middleware depth sweeps that surfaced the O(n^2)) and green-tea-{bun,deno} (the same app served via serveBun/serveDeno, to benchmark across runtimes).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 19:05:52 -05:00
chrnx 642ef109b2 feat(app): warn at boot when a route's dependency chain is unusually deep
A route whose need-closure resolves to more than 20 steps is almost always a modeling smell -- a step doing too much, or work that belongs in a provider. Per-request cost is linear, so this is a design nudge, not a perf guard (and a warning, not an error).

Tunable and silenceable via createApp({ warnGraphDepth }): a number sets the threshold, false quiets it. Default 20.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 16:25:31 -05:00
chrnx 4081106813 perf(pipeline): merge step output in place to drop the O(n^2) context copy
runSteps rebuilt the whole request context every step with { ...context, ...output }, so an N-step route paid 1+2+...+N = O(N^2) property copies plus N throwaway objects. At 100 chained steps that measured ~250us/req vs ~100us after the fix (2.5x throughput); per-step cost drops from superlinear to a flat ~0.5us/step.

Mutate one accumulator in place with Object.assign -- O(N). The returned context is now the same object every step observes. Adds a regression guard that fails if a per-step copy is reintroduced; full suite green (322 tests).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 15:50:59 -05:00
chrnx b72883c2ed docs(runtimes): scope the parity claim to what the suite actually tests
CI / build (pull_request) Successful in 33s
The parity suite compares Node's listener against app.fetch inside Node
('Node is truth') — it does not exercise all four runtimes. Saying 'every
runtime ... enforced by a parity test suite' overstates it; the honest
version is that the others share the same app.fetch/app.upgrade core and
each has its own smoke tests. Also fixed the line crediting Node's
WebSocket support to serveDeno/serveBun — Node does it through listen().

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 10:27:36 -05:00
chrnx 489aa685bb docs: host the docs at green-tea.expressive-tea.io/docs
The site hangs off the expressive-tea.io cPanel as green-tea.expressive-tea.io.
A four-level docs.green-tea.expressive-tea.io subdomain reads badly and would
need its own AutoSSL cert (the *.expressive-tea.io wildcard stops one level
up). A /docs subfolder needs no extra host, DNS, or cert — it's a path — and
is what most projects do.

So the docs site now builds with base: '/docs' (its dist/ contents drop into
the subdomain's docs/ folder in cPanel), the 77 hard-coded content links are
prefixed, and the two hero actions Starlight doesn't rewrite are fixed by
hand. Verified: /docs/ serves, / 404s, no unprefixed internal href remains.
README points at the new docs URL.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 10:13:10 -05:00
chrnx c12be9a2f5 docs(site): document matcha, stop contradicting the transport rule, drop Node-only
The streaming guide argued with itself: the table said a plain return
streams by Accept while the section below it, added with the
explicit-transport change, said that same return is a 500. The prose got
swept, the table didn't.

Getting started said green-tea targets Node — true when written, wrong
since the Deno/Bun/edge adapters landed — and led with a manual install
even though matcha scaffolds a live app in two commands. matcha had no
page at all, so the CLI was invisible to anyone reading the docs.

site: pointed at green-tea.dev, which is the marketing site's domain; the
docs deploy to docs.green-tea.dev.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 09:29:04 -05:00
chrnx 0541464093 docs(readme): tell the truth about runtimes, transport, and where the docs live
The README claimed green-tea was Node-only with Deno/Bun/edge "on the
roadmap, not built" — all four have shipped. It also taught that a plain
return of an AsyncIterable streams by Accept, which the explicit-transport
change turned into a 500 TransportMismatchError: the one thing a README
must never do is document behavior that now throws.

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

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

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-17 09:14:13 -05:00
chrnx 502b2c6b72 Merge branch 'feature/mesh-link-health' into develop
CI / build (push) Successful in 1m2s
Link health for mesh: say what is actually wrong, and notice it without waiting
for a user to find out.

Writing the tests for the status codes turned up three bugs. A teapot with a live
control channel could never shut down — control connections were the one kind of
long-lived socket nobody registered for force-close, so server.close() waited on
a teacup that had no reason to hang up. A downed teapot answered 500 after a full
30s timeout, having queued the frame on a closed socket to wait out a verdict
already known; it now answers 503 at once, and a live-but-slow teapot answers 504.
And the heartbeat's first close code, 1011, silently did nothing: a client may
only send 1000 or 3000-4999, so it threw `invalid code` into a catch that swallows
throws, leaving the link open while looking closed.

Ping/pong are mesh frames, not WebSocket protocol pings, because Deno's and Bun's
platform WebSocket does not expose ws.ping(). They land in v1 while the wire has
no deployed peers to break.

Reconnect, and reconciling app-scope values that outlive their teapot from cache,
stay out — post-beta, on their own spec.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 23:54:21 -05:00
chrnx dba40b0c8b feat(mesh): heartbeat the link, and tell the truth when a teapot is gone
Three bugs, found by writing the tests for the status codes.

A teapot with a live control channel could never shut down. Control connections
were never registered with the stream registry, so server.close() sat waiting on
a connected teacup that had no reason to hang up, and app.close() never resolved.
Every other long-lived socket was already tracked; the control channel was the
one that skipped it.

A downed teapot answered 500 — after 30 seconds. sendRpc queued the frame on a
closed socket and waited out the full timeout for a verdict already known. It now
rejects immediately with 503: a dead upstream is not "this service broke", and the
status is what tells a caller it may retry and an operator where to look. An RPC
that times out on a *live* link is 504 — a slow teapot and a gone one are
different stories.

Heartbeat: each teacup pings its teapots (`mesh.heartbeatMs`, default 15s) and
closes a link after two unanswered rounds. This is what catches a half-open
connection, where the socket looks open with nobody home — otherwise a teacup only
learns on the next request. Ping/pong are mesh frames rather than WebSocket
protocol pings because Deno's and Bun's platform WebSocket does not expose
ws.ping(), so a protocol-level heartbeat could not work everywhere mesh runs.
Added to v1 while the wire still has no deployed peers; later it would be a
version bump that refuses every old peer.

The heartbeat's first close code was 1011, which silently did nothing: a *client*
may only send 1000 or 3000-4999, so it threw `invalid code` — and our neutral
close swallows throws, so the link stayed open while looking closed. 4011 mirrors
1011's meaning inside the application range.

Reconnect (and reconciling app-scope values, which survive their teapot from
cache) stays out — it is a post-beta spec of its own.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 23:32:45 -05:00
chrnx 5e7d952f45 Merge branch 'refactor/solid-cleanup' into develop
A SOLID audit that turned into making mesh work off Node.

The audit found the repo already sound on DIP/ISP, and most candidate findings
did not survive verification. Five real ones did, and fixing the observability
gap exposed the rest: steps were run by three hand-rolled loops, only one of
which emitted request:step:enter/leave, so a logging plugin silently saw nothing
on @Ws routes.

Pulling that thread reached mesh, which was Node-only by construction rather
than by decision: only listen() finalized a mesh graph, and listen() builds a
Node http.Server, so app.fetch — the entry Deno/Bun/edge use — threw forever and
told operators to call something they could not call. Mesh now runs on Node, Deno
and Bun, teapot and teacup, in any combination, proven by cross-process interop
tests rather than reasoned about.

Wire protocol is versioned before it has peers to break; duplicate exported
routes fail the boot rather than silently shadowing, since there is no load
balancing to fall back on; local-over-remote precedence now warns instead of
being an accident of merge order; app.ready() resolves the graph without booting
providers, so one protocol works against mesh and non-mesh apps alike.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 23:14:26 -05:00
chrnx 9886e53747 feat(app): add app.ready() so introspection works on any app
inspect()/graph()/explain() are synchronous, but a mesh graph is not knowable
until its teapots have been asked, so on a mesh app they threw and the caller had
no way to fix it. Code holding an `App` could not tell which kind it had — the
Liskov complaint from the audit, and the last of it: fetch/upgrade stopped
throwing when the boot moved into the gate.

app.ready() resolves the graph and returns. On a mesh app it connects the
teapots; on every other app it is a no-op. So one shape works for both:

    await app.ready();
    app.graph();

which is what actually restores substitutability — a uniform protocol, not a type
that describes the asymmetry.

Deliberately not a full boot: it does not run provider factories. Resolving the
graph and being ready to serve are different things, and a devtool drawing a
diagram should not open your database connections. Serving boots them too and
shares the same memoized step, so ready() then fetch() resolves the graph once.

The guards stay — sync code cannot await network I/O — but the message names the
fix instead of describing the trap.

createApp hit 26 on the complexity gate with ready() added. Both boot stages had
their own copy of the same memoisation, so it collapses into one `once` helper
used by both, which is a smaller createApp than before this change.

Refs .specs/2026-07-15-green-tea-solid-audit (App/Mesh LSP)

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 23:00:14 -05:00
chrnx 34dbb32b2c docs(mesh): warn on shadowed remote routes, and tell the truth about mesh
Local routes are merged ahead of remote ones, so a local twin wins. That
precedence is worth keeping — your own code beating an imported one is how you
override a teapot — but it was an accident of [...local, ...remote] ordering with
nothing said, so a shadowed export looked like a broken teapot from the outside.
Warn, name the teapot, and leave the call to the developer.

The docs had gone stale in the way that started all of this. runtimes.md claimed
four times that mesh is Node-only; the mesh guide said finalization is deferred to
listen(); the changelog said "WebSocket and mesh remain Node-only". All false now.

The mesh guide gains what was enforced but never written down — which is how the
listen() trap got made in the first place, when the previous plan's "document it"
never landed:
- runs on Node/Deno/Bun, teapot and teacup, any combination; not on edge, and why
- no listen() required: the graph boots on first use
- buffered routes only, and why streams cannot cross an RPC hop
- one teapot per route, local-over-remote precedence, and the protocol version

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 9

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 16:20:55 -05:00
chrnx 033af2d1fc fix(mesh): fail the boot when two teapots export the same route
Duplicate scope tokens already threw in setRunner, but duplicate routes did not:
both were pushed into remoteRoutes, and matchRoute keeps the first of two
identical patterns (moreSpecific returns 0, not > 0). The second teapot's route
was silently dead. Same collision, two behaviours — one loud, one mute.

Fail the boot instead, naming the route and both teapots, since which pair
clashed is the thing an operator needs. The message says load balancing is not
implemented *yet*: it is a not-yet, not an impossibility.

Throwing now also keeps the door open. "First teapot wins" is a semantic callers
could come to rely on, so shipping it would make balancing a breaking change
later. An error cannot be relied on — turning it into a strategy stays additive.

Scopes keep failing rather than balancing, and should: an app-scope provider is
memoised, so "balancing" a cached value means nothing.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 16:04:57 -05:00
chrnx a74417494f test(mesh): prove mesh across Node, Deno and Bun
Every mesh test ran on Node and drove listen(); nothing off Node was covered, so
the cross-runtime work was implemented but not demonstrated. vitest excludes
test/{deno,bun,edge}, so `npm test` would not have noticed either way.

Adds, in the real runtimes:
- Deno and Bun, teapot and teacup, served through serveDeno/serveBun. Bun is not a
  duplicate of Deno: its socket events land on a server-level handler, so the
  control channel reaches app.upgrade by a different path.
- The interop matrix, in separate processes: a Deno teacup consuming a Node teapot
  and a Node teacup consuming a Deno teapot. Each asserts the `runtime` field the
  *other* process produces, so a peer answering from the wrong side fails the test.
  Node serves and connects with the `ws` package; Deno uses its global WebSocket —
  same-runtime tests could never have exercised that pairing.
- A hand-rolled v999 peer, refused across the boundary with both versions named.

Verified these tests fail for the right reason: breaking the control-channel
routing in app.upgrade fails the Node-teacup-consumes-Deno-teapot case and only
that case.

test:deno needs --allow-run/--allow-env to spawn the Node peer. The peer lives in
test/interop rather than test/deno because tsconfig excludes test/deno, so tsx
would not apply experimentalDecorators there; vitest ignores it as a non-.test.ts.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 8

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 15:30:43 -05:00
chrnx 0c68cba532 feat(mesh): mount the control channel on app.upgrade, and close links without a server
Two halves of the same "mesh off Node" gap; they touch the same file and landed
together.

Control channel (Task 6): meshControl existed only inside listen(), passed to
createHttpServer, so a teapot could only export its scopes from Node. app.upgrade
— the path serveDeno/serveBun drive — had never heard of it, which would have left
"mesh on three runtimes" meaning consume-only. It is now built in the boot gate
(it captures the finalized ordered nodes, so it cannot exist before finalize) and
the reserved path is routed from app.upgrade. Task 3 already made handle() take a
neutral WsSocket and upgrade holds one, so this is a direct call, not a second
implementation. handle() returns the connection's lifetime like runWsConnection,
so upgrade awaits it instead of returning while the peer is still talking. An app
with nothing exported refuses the reserved path explicitly rather than falling
through to "no matching ws route".

Link lifecycle (Task 7): links were reaped by server.on('close'), reachable only
through listen(), so a mesh app booted through app.fetch had links and no server
and leaked every teapot connection at `if (!server) return`. close() now closes
them first either way; that aborts each socket, which rejects its in-flight RPCs.

Also fixes a race the new tests exposed: upgrade awaited the boot *before* handing
the socket to a consumer, but `channel` is fan-out, so frames arriving during the
boot were dropped with no subscriber attached. For the control channel that is
`hello` itself — against a teapot with slow providers the handshake would hang
until timeout. Inbound is now subscribed synchronously on entry and the buffered
iterator handed down, closing the same gap for regular @Ws routes.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Tasks 6, 7

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 15:13:20 -05:00
chrnx db9a7712af feat(mesh): boot the mesh graph from the app boot gate, not listen()
Only listen() spliced remote scopes and finalized the graph, and listen() builds
a Node http.Server. Deno/Bun/edge serve through app.fetch and can never call it,
so mesh was Node-only by construction: fetch() threw "unavailable before
listen()" forever on those runtimes, telling operators to call something they
had no way to call. buildAppFetch also hardcoded remoteRoutes to [], so even past
the guard it would not have served a remote route.

Move splice+finalize into the memoized boot gate that fetch, upgrade and listen
already share, ahead of the providers — remote nodes must join before the topo
sort. Await it before building the route table rather than after, since for a
mesh app the table is not knowable until the splice has run. listen() keeps
working by awaiting the same gate; the memoization means a fetch followed by a
listen boots once, and concurrent first requests splice once.

The fetch/upgrade guards are gone rather than reworded: they are now unreachable.

inspect()/graph()/explain() keep theirs — they are synchronous and cannot await
network I/O — but their message no longer claims listen() is the only way in.

test/fetch.test.ts asserted the old contract (fetch throws until listen), i.e.
the trap itself; it now pins that a mesh app serves without listen() and that
listen() afterwards does not re-run provider factories.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 5

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 15:04:49 -05:00
chrnx 0ea4db3fef feat(mesh): connect the teacup over a runtime-neutral WebSocket client
connectLink constructed `require('ws')` directly and drove its EventEmitter API,
which is why a teacup could only run on Node. It now goes through the neutral
WsSocket like every other consumer, over whichever client the runtime provides:
the platform global (Deno, Bun, Node >= 22) or the `ws` peer for Node 18-21,
which has no global. `ws` stays optional and is only reached for when the global
is absent.

One bridge covers both because `ws` also implements the browser-compatible event
API and delivers text frames as `event.data` strings — probed against the real
package rather than taken on faith.

Both implementations are exercised in one run: `ws` is always in the matrix, so
the Node 18-21 path cannot rot unseen on CI that only runs a modern Node, which
is how a fallback quietly stops working. connectLink takes an optional Ctor to
make that possible; it doubles as a bring-your-own-WebSocket hook for runtimes
we do not ship an adapter for.

Verified the edge bundle is unaffected: `require('ws')` tree-shakes out of the
workerd build entirely.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 4

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 15:00:04 -05:00
chrnx 71b59e7c25 refactor(mesh): serve the control channel over the neutral WsSocket
The mesh control channel was the last consumer speaking the `ws` EventEmitter
API directly: http/ws.ts handed meshControl.handle a raw socket, while every
@Ws route already went through nodeSocket() to get a neutral WsSocket. Mesh did
not lack an abstraction — it skipped the one the codebase already had.

handle() now takes a WsSocket and consumes `inbound`, so both feeds work: Node
via the existing nodeSocket, and Deno/Bun via app.upgrade, where the socket is
already neutral. That is what unblocks mounting the control channel off Node.

RPCs are still dispatched without awaiting. The old `ws.on('message')` listener
overlapped them, and the peer's id-keyed pending map exists for exactly that —
awaiting inside the receive loop would have silently serialized every mesh call.
A test now pins the overlap.

The unused `http` import in http/types.ts fell out with MeshControl's req
parameter: nothing in that module is Node-shaped any more.

Node behaviour is unchanged — the teapot↔teacup integration tests pass
untouched. teapot.test.ts drives handle() directly, so its fake moved from a raw
EventEmitter to a fake WsSocket.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 3

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:53:09 -05:00
chrnx 87772868ab refactor(mesh): import node:crypto explicitly in the teapot
safeEqual guards the mesh shared secret and reached for Buffer + timingSafeEqual
through a bare 'crypto' specifier, leaving resolution to Deno/Bun node-compat
heuristics. Name the builtin explicitly — the authentication path should not
depend on which compat layer happens to answer.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 2

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:53:07 -05:00
chrnx dd0ea91a1b feat(mesh): version the wire protocol and validate frame shapes
Cross-runtime mesh means peers are separate processes on separate deploy
cadences, so the frame union is a contract between green-tea versions rather
than an internal detail. There was no version field, and decode validated only
that `type` was a known tag before casting `parsed as Frame` — every other
field was trusted, so a skewed or malformed peer failed somewhere downstream
instead of at the boundary.

Add MESH_PROTOCOL_VERSION to the hello/manifest frames. Both ends refuse a
mismatch: the teapot checks the version *before* the secret, since a skewed
peer is not an auth failure and "wrong secret" would send its operator hunting
the wrong bug.

Validate fields per frame type via a Record keyed on the type tag, so a new
frame type must add a row. The lookup uses an own-property check: `type` is
peer-controlled and a bare lookup would resolve SHAPE['constructor'] up the
prototype chain to a truthy non-check.

This is a breaking wire change, done now because it is free exactly once —
mesh is alpha behind experimental:true and has no deployed peers. Adding a
version later would break every peer already in the field.

Refs .specs/2026-07-15-green-tea-mesh-cross-runtime-plan.md Task 1

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:47:35 -05:00
chrnx d56eeafcd8 refactor: close type holes on the transport and error axes
- OpenApiRoute.transport was typed `string`, so the compiler could not check the
  transport branching at all. Type it Transport and key the documented 200 off a
  Record, so a new transport fails the build instead of silently going undocumented.
- pickEncoder fell through to ndjson for unknown transports; make the mapping
  exhaustive so a new transport cannot inherit the wrong wire format by accident.
- HttpError carries optional headers, removing the instanceof Redirect special case
  that coupled the error renderer to one subclass. Custom errors needing headers
  (retry-after, etag) no longer require touching transformers.
- Drop the module-global connSeq in mesh/link: `pending` is already per-connection,
  so a per-link counter suffices and connection ids stop depending on test order.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:37:03 -05:00
chrnx 9421b102d9 refactor(adapters): share ws plumbing across bun/deno/edge
toWsRequest, the neutral-socket wrapper and the upgrade error guard were
copy-pasted across all three runtime adapters, comments included. A change to
the upgrade close code meant remembering to touch three files.

Extract the shared parts to http/ws-adapter (kept separate from ws-core: that
module runs a connection, this one builds one from a host runtime's socket).
Bun keeps its own socket wrapper — its events land on a server-level handler
rather than the socket, so the lifecycle genuinely differs.

Verified against real runtimes: deno test, bun test, workerd via miniflare.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:37:03 -05:00
chrnx 922700674c fix(bus): emit step events for ws and mesh routes
Steps were executed by three separate hand-rolled loops: runPipeline (HTTP),
buildWsRoutes (ws) and resolveScope (mesh). Only the HTTP one emitted
request:step:enter/leave, so a logging plugin silently observed nothing on ws
routes — a gap in a documented public API, not just redundancy.

Route every transport through a single runSteps() so observability is uniform
by construction rather than by remembering to copy the emit calls.

Also fixes the plugins guide, which documented a request:step:exit event that
has never existed (the bus emits request:step:leave).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-15 14:37:03 -05:00
chrnx 44cf547f1b Merge branch 'feature/explicit-transport' into develop
CI / build (push) Has been cancelled
feat(pipeline): transport is declared, not inferred (BREAKING)

A route's declared transport is now the ground truth for what its handler
may return — the old implicit "any handler returning an AsyncIterable
streams" behavior (spec #2) is removed.

- @Get/@Post/@Put/@Patch/@Delete (buffer) MUST return a value; returning an
  AsyncIterable -> 500 TransportMismatchError.
- @Sse/@Ws MUST return an AsyncIterable; returning a value -> 500.
- @Stream (negotiate) still tolerates both (client negotiates via Accept).
- Extensible TRANSPORT_RETURN map (Record<Transport, ReturnContract>);
  runPipeline gains a required `transport` arg, wired at both call sites.
- @Html (buffer) is covered by the general rule; its return contract
  (bare->string, template->object, file->void) is documented.

BREAKING (pre-1.0): a return value no longer changes a route's wire
contract. Declare @Sse/@Stream/@Ws to stream. 0 examples affected.

269 tests, tsc/lint/complexity green. Per-task + final opus review.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 16:22:57 -05:00
chrnx 76267b74ec docs(transport): reword homepage hero — declare @Sse to stream
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 16:07:01 -05:00
chrnx 2b646eaec6 docs(transport): reword stale implicit-streaming passages
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 16:06:02 -05:00
chrnx 535392baba docs(transport): declared-transport contract + @Html return contract
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 16:02:36 -05:00
chrnx 4d1ff33f74 test(transport): end-to-end enforcement via app.fetch
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 15:59:52 -05:00
chrnx f613a6427b feat(pipeline): enforce return contract by declared transport
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 15:55:22 -05:00
chrnx 35861f0fc1 Merge branch 'feature/html-views' into develop
CI / build (push) Has been cancelled
feat(views): HTML serving — @Html decorator, template engine, static

- @Html method decorator: string / file / template modes, buffered GET/POST
  only (boot-validated; SSE/WS/other and @Html+@Transformer throw).
- Zero-dep built-in template engine (render): {{ }} HTML-escaped, {{{ }}} raw,
  nested keys; + createApp({ viewEngine }) bring-your-own hook.
- Zero-config static serving: createApp({ static: true }) -> ./public (or a
  path); content-type by extension, / -> index.html, GET/HEAD, path-traversal
  safe, declared routes win. Node/Deno/Bun (fs); edge throws at boot.
- createApp({ views }) base dir for @Html file paths (default cwd).
- Runtime-agnostic invariant preserved: fs/path lazy-required, barrel still
  loads on workerd; string-mode @Html + render are fs-free.
- Docs: guides/html + runtimes fs-note + reference pages + CHANGELOG.

261 tests, tsc/lint/complexity green. Reviewed per-task + final opus pass.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 15:13:48 -05:00
chrnx 2d6306b318 docs(views): reference pages, guide footgun note, drop unused test import
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 14:58:56 -05:00
chrnx 289ca5f8ff docs(views): @Html, templating, and static serving guide
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 14:50:06 -05:00
chrnx ad3a06f057 feat(views): zero-config static directory serving
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 14:42:20 -05:00
chrnx b8ebb9d04b feat(views): @Html string/file/template modes with boot validation
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 14:36:40 -05:00
chrnx e1a2c3253b feat(views): @Html decorator and metadata
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 14:31:12 -05:00
chrnx da5cc936a3 feat(views): built-in template engine + content-type map
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 14:26:57 -05:00
chrnx e54de8c1db Merge branch 'fix/dev-routes-on-fetch' into develop
CI / build (push) Has been cancelled
Serve /__graph__ + /__openapi__ over app.fetch so the dev tools (graph viewer,
OpenAPI) work on Deno/Bun/edge, not just the Node listen() path.
2026-07-10 00:10:56 -05:00
chrnx df13a62d93 fix(app): serve /__graph__ and /__openapi__ over app.fetch (dev tools on all runtimes)
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-10 00:10:54 -05:00
chrnx 6833293ccf Merge branch 'feature/runtime-edge-ws' into develop
CI / build (push) Has been cancelled
Step 4 runtime-agnostic: Edge / Cloudflare Workers + WebSocket.
- @green-tea/core/edge edgeHandler (HTTP+SSE+WS on workerd), real Miniflare test
- reuses the neutral WsSocket capability + app.upgrade (edge-only supplies a socket)
- lazy-load http/https so createApp is edge/workerd-safe (Node path identical)
- runtime-agnostic saga complete: Node + Deno + Bun + edge
2026-07-09 23:52:30 -05:00
chrnx cb4ecd6801 docs: edgeHandler — WebSocket on Cloudflare Workers / edge
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 23:45:27 -05:00
chrnx 70925035d7 fix(http): lazy-load http/https so createApp is edge/workerd-safe; drop test shim
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 23:40:28 -05:00
chrnx a4c9df9a74 test(edge): edgeHandler HTTP + WebSocket on real workerd via Miniflare
Boots the actual workerd engine locally (miniflare devDep, no CF account
needed) and round-trips HTTP (app.fetch) + WebSocket (WebSocketPair +
app.upgrade) through edgeHandler's real request path, mirroring the Deno/Bun
adapter tests' assertion shape.

workerd's nodejs_compat genuinely does not implement node:http/node:https
(confirmed in isolation against the real runtime; node:crypto, node:stream,
node:net, node:tls, node:events, node:util, node:buffer all load fine under
the same flags). The barrel statically imports them for the Node listen()
path even though edgeHandler never touches it, so the bundler stubs those
two modules at test-bundle time (inert createServer that throws if ever
called) purely to let the worker load — edgeHandler itself is untouched.
See project-docs/.superpowers/sdd/task-2-report.md for the full writeup and
the suggested core follow-up (lazy-defer those imports behind listen()).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 23:34:19 -05:00
chrnx 9344cc7d43 feat(edge): edgeHandler adapter — HTTP+SSE+WS on Cloudflare Workers via /edge subpath
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 23:22:28 -05:00
chrnx 86c206d2c9 Merge branch 'feature/runtime-bun-ws' into develop
CI / build (push) Has been cancelled
Step 3 runtime-agnostic: Bun adapter + WebSocket.
- @green-tea/core/bun serveBun (HTTP+SSE+WS on Bun), real bun test
- reuses the neutral WsSocket capability + app.upgrade (zero core changes)
- open-deferred WsSocket build via ws.data; binary parity + ws error handler
2026-07-09 22:08:58 -05:00
chrnx 82824e5f6d fix(bun): add ws error handler for Node/Deno parity; hoist TextDecoder
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 22:00:23 -05:00
chrnx 3d21117a07 docs: serveBun — WebSocket on Bun
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 21:54:34 -05:00
chrnx 4351b41038 test(bun): serveBun HTTP + WebSocket integration
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 21:51:33 -05:00
chrnx fd6446f514 feat(bun): serveBun adapter — HTTP+SSE+WS on Bun via /bun subpath
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 21:44:46 -05:00
chrnx 8d3a4ca420 Merge branch 'feature/runtime-deno-ws' into develop
CI / build (push) Has been cancelled
Step 2 runtime-agnostic: Deno adapter + WebSocket capability.
- Neutral WS core (ws-core.ts) behind a WsSocket capability
- Node adapter rebuilt over it (behaviour byte-identical)
- app.upgrade(request, socket) neutral primitive
- @green-tea/core/deno serveDeno (HTTP+SSE+WS on Deno), real deno test
- docs + CHANGELOG
2026-07-09 17:39:55 -05:00
chrnx 4a6ef784ec fix(deno): decode binary ws frames to match Node; changelog ctx.req note
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 17:38:23 -05:00
chrnx 47b7bf5f24 docs: serveDeno + app.upgrade — WebSocket on Deno
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 17:27:26 -05:00
chrnx f85b39c2c3 test(deno): serveDeno HTTP + WebSocket integration
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 17:23:24 -05:00
chrnx e9357efb5c fix(deno): guard fire-and-forget app.upgrade against fatal unhandled rejection
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 17:17:20 -05:00
chrnx 12eccd941c feat(deno): serveDeno adapter — HTTP+SSE+WS on Deno via /deno subpath
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 17:11:00 -05:00
chrnx d72452d9b6 feat(app): app.upgrade — neutral WebSocket entry over the graph
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 17:04:38 -05:00
chrnx 7a8be39d57 refactor(ws): Node adapter builds WsSocket over the neutral core
Also fixes buildWsRoutes (app/index.ts) to read the pre-derived
protocol/ip off the neutral WsRequest instead of req.socket, which no
longer exists now that WsOpenCtx.req is WsRequest — without this every
real @Ws route throws on open() and the connection hangs.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 16:56:17 -05:00
chrnx 5e68d2de65 fix(ws): runtime-neutral close reason + registry removal on transport close
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 16:51:42 -05:00
chrnx 179a58f0e4 feat(ws): neutral runWsConnection core behind a WsSocket capability
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 16:44:59 -05:00
chrnx 0aab3ed123 feat(http): runtime-agnostic app.fetch (Web-Standards handler)
CI / build (push) Has been cancelled
Step 1 of runtime-agnostic: expose app.fetch(request): Promise<Response>,
reusing the pipeline core so the app runs on Deno.serve/Bun.serve/edge for
HTTP + SSE. Node app.listen path unchanged (truth grounding, parity-tested).
WebSocket + mesh remain Node-only (later steps).

Merges feature/runtime-agnostic-fetch (9 commits).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 14:47:59 -05:00
chrnx 58853e8ba8 docs: changelog for app.fetch + provider memoization, runtimes body-size note
Record the app.fetch Web-Standards handler and the app-scope provider
memoization behaviour change in the changelog, and note on the runtimes
guide that app.fetch reads oversized bodies fully before rejecting them
(unlike Node's mid-stream abort) so non-Node deployments should also
bound request size at the platform layer.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 14:45:34 -05:00
chrnx 43a4316a29 fix(fetch): gate x-forwarded-for on trustProxy in app.fetch
The Web-Standards fetch adapter read x-forwarded-for unconditionally to
seed ctx.ip, unlike Node's deriveIp which only honours it when
trustProxy is enabled. A client could spoof ctx.ip on any handler
relying on it. Mirror deriveIp's first-hop semantics and only trust
the header when trustProxy is set; otherwise ctx.ip is ''.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 14:45:27 -05:00
chrnx 1fee7de543 docs: app.fetch runtimes guide (Node/Deno/Bun/edge)
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 14:37:12 -05:00
chrnx b75f127b2c fix(http): merge security headers into app.fetch CORS preflight responses
Add a Node-vs-app.fetch parity suite that drives GET/POST/404/CORS-preflight/SSE
through both the real Node server and app.fetch and asserts identical status,
headers, and body. It caught a real divergence: buildFetch's preflight branch
returned only the CORS-specific headers, skipping the security headers
(x-content-type-options, x-frame-options, referrer-policy, x-dns-prefetch-control)
that the Node adapter's writeHead patch applies to every response including the
204 preflight. Fix buildFetch to merge `injected` into the preflight response the
same way, so both paths agree.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 14:33:31 -05:00
chrnx 08cb8554e6 fix(fetch): security headers on early failures, live mesh boot gate
app.fetch's 413/400/501 body-acquisition failures were returned without
the injected security/CORS headers Node's writeHead patch always
applies, breaking byte-identical parity with the listen() path. Extract
computeInjected() (shared by handle() and buildFetch()) and merge it
into every error response, not just handle()'s outcomes.

Also, buildAppFetch captured `booted` by value at createApp() time, so
mesh apps (whose finalize() is deferred into listen()) had app.fetch
permanently throw even after a successful listen(). Read booted live
via a getter, mirroring explain()/graph()/inspect(), and lazily
build/cache the fetch handler on first call after boot.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 14:26:45 -05:00
chrnx 93a4246de5 feat(app): app.fetch — Web-Standards handler over the neutral core
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 14:15:26 -05:00
chrnx fc75cc05e5 feat(http): asReadableStream — AsyncIterable to web ReadableStream
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 14:04:03 -05:00
chrnx 16823408c7 refactor(http): extract runtime-neutral handle() core
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 13:58:35 -05:00
chrnx 118eb5516d refactor(http): extract mergeInjectedHeaders pure helper
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 13:51:55 -05:00
chrnx 9d97443847 feat(brand): Green Tea. identity — logo, wordmark, branded graph & docs
CI / build (push) Has been cancelled
Ship the visual brand across the framework:
- assets/ (logo.svg, logo-mono.svg, logo.png), included in the npm files list
- README header: leaf mark + Green Tea. + tagline; package description aligned
- /__graph__ viewer header now shows the logo + Green Tea. wordmark (Zen Maru)
- website/ (Starlight): matcha accent, Zen Maru headings, logo, favicon, hero

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 13:33:04 -05:00
chrnx aaafe76d8f feat(graph): color-code endpoint method and transport in the viewer
CI / build (push) Has been cancelled
Follow-up to the interactive viewer. Route nodes were arrow 'tag' shapes
that read as disruptive and edges were thick. Calm them down: routes are
now rounded rectangles with thinner edges.

Encode two axes visually on each endpoint — fill colour = HTTP method
(GET/POST/PUT/PATCH/DELETE), border style = transport (solid HTTP, dashed
SSE, double WS) — with a legend that explains node types, edge kinds,
transports and methods.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 11:06:47 -05:00
chrnx 27a984f070 feat(graph): interactive Cytoscape viewer for /__graph__
CI / build (push) Has been cancelled
Mermaid's static diagram overlaps badly as the graph grows. Replace the
/__graph__ HTML with an interactive Cytoscape.js + dagre viewer (both loaded
from a CDN, so no runtime dependency is added — the one-dep pitch holds).

Clicking a route lights up its real transitive slice and dims the rest;
clicking a provider/step shows its blast radius. Edges are colour-coded by
kind (needs vs feeds-endpoint), provider/step/endpoint nodes are visually
distinct, and nodes are draggable. toMermaid()/toDOT() and the text/plain
path are unchanged.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-09 10:44:03 -05:00
chrnx 2db5de6858 feat: per-route body limits, custom error rendering, OpenAPI generation
CI / build (push) Has been cancelled
Three capabilities that share the same request/route metadata:

- **Per-route upload limits** — `@Post('/x', { maxBodyBytes, maxParts })`
  overrides the server-wide `limits` for one route (falls back to the
  global default), mirroring the existing per-route `duplicates`.

- **Custom error rendering** — `createApp({ onError })` takes over how any
  error becomes a response (HTML, RFC 7807, content-negotiated), covering
  the whole surface: handler/step throws, 404, 405, 413, 400. Returns a
  response or undefined to fall back to the default JSON. Also wires the
  previously-unused `HttpError` `body` field so `throw new HttpError(409,
  'conflict', { code })` renders a structured payload. Default behavior is
  unchanged when no hook is set.

- **OpenAPI 3.1** — `app.openapi(info?)` projects the route graph into a
  structural spec (paths, methods, path/query/header params, request-body
  presence, systematic error responses); opt-in `GET /__openapi__` via
  `devOpenapi`. Body/response schemas stay generic (Standard Schema exposes
  no JSON Schema) — the full `@Produce` mode is post-beta.

Docs: new error-handling and OpenAPI guides, plus reference updates.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-08 08:29:17 -05:00
chrnx 7c20d74fe4 chore(release): publish metadata + normalize version to 26.7.0-beta.0
CI / build (push) Has been cancelled
Add the npm metadata needed to publish the scoped package —
`publishConfig.access: "public"` (without it a scoped package publishes
private), `engines`, `keywords`, `author` — and a CHANGELOG entry for the
first beta.

Normalize the version to 26.7.0-beta.0: npm treats versions as semver and
strips the month's leading zero, so 26.07.0 publishes as 26.7.0 regardless.
Align package.json, the VERSION export, the README, and the smoke test.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-07-07 16:04:20 -05:00
chrnx 40d3390ddb Merge pull request 'Feature/beta hardening' (#1) from feature/beta-hardening into develop
CI / build (push) Has been cancelled
Reviewed-on: #1
2026-07-07 20:21:27 +00:00
124 changed files with 10322 additions and 2450 deletions

No files matched your search

@@ -13,9 +13,16 @@ jobs:
with:
node-version: '18'
- run: npm ci
- run: npm audit
- run: npm run lint
- run: npm run format:check
- run: npm run complexity:check
- run: npm run typecheck
- run: npm test
- run: npm run build
- uses: actions/setup-node@v4
with:
node-version: '22.12'
- run: npm ci --prefix website
- run: npm audit --prefix website
- run: npm run docs:build
+30
View File
@@ -0,0 +1,30 @@
name: Promote → GitHub
# Promotion. Runs on GITEA ONLY. Mirrors ONLY `main` + version tags to the public GitHub
# repo — develop and feature branches stay Gitea-private (this is why we don't use Gitea's
# push-mirror, which would expose every branch). A pushed tag lands on GitHub and triggers
# its release workflow (production publish).
on:
push:
branches: [main]
tags: ['v*']
jobs:
push-github:
if: ${{ github.server_url != 'https://github.com' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history + tags for a clean push
- name: Push main + tags to GitHub
env:
GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }}
run: |
git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/green-tea.git"
if [ "${{ github.ref_type }}" = "tag" ]; then
git push github "refs/tags/${{ github.ref_name }}"
else
git push github "HEAD:refs/heads/main"
git push github --tags
fi
+35
View File
@@ -0,0 +1,35 @@
name: Release → npmjs
# Production publish. Runs on GITHUB ONLY, on a version tag (`v*`). Publishes the stable
# package to npmjs via OIDC **Trusted Publishing** — no long-lived token. Requires a trusted
# publisher configured on npmjs for this package (org Expressive-Tea, repo green-tea,
# workflow release.yml). npm also attaches build provenance automatically.
on:
push:
tags: ['v*']
jobs:
publish-prod:
if: ${{ github.server_url == 'https://github.com' }}
runs-on: ubuntu-latest
permissions:
id-token: write # OIDC for Trusted Publishing (also enables provenance)
contents: read
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
registry-url: 'https://registry.npmjs.org'
- run: npm install -g npm@latest # npm >= 11.5.1 is required for OIDC trusted publishing
- run: npm ci
- run: npm audit
# `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) first.
# No NODE_AUTH_TOKEN — npm exchanges the OIDC id-token for a short-lived publish token.
# A prerelease (26.7.0-beta.N) publishes under its channel tag (beta/alpha/rc) so `latest`
# never points at a beta; a stable version publishes under `latest`.
- name: Publish
run: |
TAG=$(node -e "const v=require('./package.json').version;const m=v.match(/-([a-z]+)/);console.log(m?m[1]:'latest')")
echo "dist-tag: $TAG"
npm publish --access public --tag "$TAG"
+35
View File
@@ -0,0 +1,35 @@
name: Stage → Verdaccio
# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub) for release
# branches. Publishes prereleases to the internal Verdaccio under the `stg` dist-tag.
# Staging versions are intentionally mutable: an existing prerelease is removed before
# publishing the updated release candidate under the same version.
on:
push:
branches: ['release/**']
jobs:
publish-stg:
if: ${{ github.server_url != 'https://github.com' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: npm ci
- run: npm audit
- name: Validate release candidate
run: npm run prepublishOnly
- name: Publish prerelease to Verdaccio
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH }}
run: |
npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN"
VER=$(node -p "require('./package.json').version")
case "$VER" in
*-*) ;;
*) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;;
esac
npm unpublish "@green-tea/core@$VER" --registry https://npm.svc.zoit.services --force 2>/dev/null || true
npm publish --ignore-scripts --registry https://npm.svc.zoit.services --tag stg
+3
View File
@@ -14,3 +14,6 @@ coverage/
# Astro (docs site)
.astro/
website/dist/
# Edge (Miniflare) test bundle artifact
test/edge/_worker.mjs
+128 -10
View File
@@ -3,12 +3,113 @@
All notable changes to `@green-tea/core` are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
green-tea uses calendar versioning: `YY.MM.PATCH`.
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
npm treats versions as semver and semver forbids leading zeros.
## [Unreleased]
Beta on the road to a release candidate. No published release yet; the
version below is a placeholder until the API freeze.
## [26.8.0-beta.0] - 2026-08-02
### Added
- **Safe constrained route parameters:** patterns such as `:id(\d+)` match a complete decoded
segment. The parser accepts a deliberately small, bounded regex subset and rejects unsafe or
malformed expressions at boot. Specificity is now static ▸ constrained param ▸ plain param ▸
catch-all; matching remains a linear scan.
- **`@Head` and `@Options` route decorators**, explicit-handler priority, buffered-GET HEAD fallback,
and automatic `204` OPTIONS responses with deterministic `Allow` ordering. GET implies HEAD and
every existing path implies OPTIONS; streaming GET routes do not become implicit HEAD routes.
- **OpenAPI route constraints and methods:** constrained path params emit `schema.pattern`, and
explicitly declared HEAD/OPTIONS handlers appear as operations without inventing automatic ones.
- **HTML / views:** `@Html` decorator (string, file, and template modes), a zero-dep built-in
template engine (`{{ }}` escaped / `{{{ }}}` raw, exported as `render`) with a `viewEngine`
bring-your-own hook, and zero-config `static` directory serving (`createApp({ static: true })`).
File and static serving require a filesystem (Node/Deno/Bun); string-mode `@Html` runs everywhere.
- **`app.fetch(request): Promise<Response>`** — a Web-Standards handler so the
same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API.
- **Deno adapter** (`@green-tea/core/deno`): `serveDeno(app)` runs HTTP + SSE + WebSocket on Deno.
- **Bun adapter** (`@green-tea/core/bun`): `serveBun(app)` runs HTTP + SSE + WebSocket on Bun, reusing the neutral `app.upgrade` / `WsSocket` capability. WebSocket, rooms, and channels behave identically to Node and Deno.
- **Cloudflare Workers / edge adapter** (`@green-tea/core/edge`): `edgeHandler(app)` runs HTTP + SSE + WebSocket on workerd, reusing the neutral `app.upgrade` / `WsSocket` capability. Requires the `nodejs_compat` compatibility flag. Green Tea now runs on Node, Deno, Bun, and the edge — with identical WebSocket, rooms, and channel behaviour on all four.
- **`app.upgrade(request, socket)`**: neutral WebSocket entry point for non-Node runtimes, built on a shared `WsSocket` capability. WebSocket logic is now runtime-agnostic (`src/http/ws-core.ts`).
- **Mesh (alpha) runs on Node, Deno and Bun** — teapot *and* teacup, in any combination
(a Deno teapot can serve a Node teacup). It no longer needs `app.listen()`: the graph boots on
first use, so `serveDeno`/`serveBun` work through `app.fetch`/`app.upgrade`. Edge is **not**
supported — the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which
`nodejs_compat` does not provide.
- **`MESH_PROTOCOL_VERSION`**: the mesh wire is versioned. Peers exchange it in the `hello`/`manifest`
frames and refuse a mismatch, naming both versions, instead of misreading each other's frames.
The teapot checks the version *before* the secret — a skewed peer is not an auth failure.
- **`HttpError` accepts `headers`**, so a custom error can carry its own response headers
(`retry-after`, `etag`, …) without a special case in the error renderer.
- **`app.ready(): Promise<void>`** — resolves the dependency graph and returns. On a mesh app it
connects the teapots and splices their scopes in; on every other app it is a no-op, so
`await app.ready()` before `inspect()`/`graph()`/`explain()` works against either kind without
knowing which you were handed. It does **not** boot providers: resolving the graph and being
ready to serve are different things, and drawing a diagram should not open your database
connections. Serving boots them too and shares the same memoized step.
- **Mesh heartbeat** (`mesh.heartbeatMs`, default 15s): each teacup pings its teapots and closes a
link after two unanswered rounds, so a half-open connection surfaces as an immediate 503 rather
than every request paying `timeoutMs` first. Ping/pong are mesh frames, not WebSocket protocol
pings — the platform `WebSocket` on Deno/Bun does not expose `ws.ping()`.
### Fixed
- The Deno WebSocket adapter snapshots request and connection metadata before accepting an upgrade;
Deno 2.9 invalidates that metadata once upgraded, which previously broke WebSocket and mesh boots.
- Repeated slashes and malformed path encoding now return `400` consistently across Node and Fetch
adapters, retaining configured security/CORS headers. `/path` and `/path/` remain equivalent.
- Ambiguous same-method route shapes now fail at boot with both declarations named. Effective-shape
checks also cover remote mesh conflicts and local routes that shadow a remote export.
- HEAD responses always suppress the body while preserving handler status and headers; Fetch
responses also avoid constructing forbidden bodies for `204`, `205`, and `304` statuses.
- The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now
served over `app.fetch` too, so they work on every runtime (Deno/Bun/edge),
not only the Node `app.listen()` path.
- **A teapot with a live control channel could never shut down.** Mesh control connections were
not registered with the stream registry, so `server.close()` waited on a connected teacup that
had no reason to hang up, and `app.close()` never resolved.
- **A downed teapot now answers 503 immediately** instead of hanging for the full `timeoutMs`
(30s by default) and then answering 500. A closed socket cannot deliver the frame, so the wait
bought nothing. An RPC that times out on a live link is now 504, not 500 — a dead upstream and
a slow one are different operational stories, and neither is "this service broke".
- **`request:step:enter`/`leave` are now emitted for `@Ws` and mesh routes.** Only HTTP routes
emitted them, so a logging plugin silently observed nothing on a WebSocket route — a gap in a
documented plugin API. All transports now run their steps through one path.
- **A mesh route exported by two teapots now fails the boot**, naming both effective patterns and
both teapots, instead of silently serving whichever connected first and leaving the other dead.
There is no load balancing to fall back on, so green-tea will not pick for you.
- **A local route shadowing a remote one now warns.** Local still takes precedence — that is how you
override a teapot — but a silently shadowed export used to look like a broken teapot.
- **`app.close()` closes mesh links even with no server**, so a mesh app booted through `app.fetch`
(every Deno/Bun deployment) no longer leaks its teapot connections.
- **WebSocket frames arriving during boot are no longer dropped.** `app.upgrade` awaited the boot
before handing the socket to a consumer, and the inbound channel is fan-out, so a peer that spoke
first lost those frames — for mesh, that was the handshake itself.
- The plugins guide documented a `request:step:exit` event that has never existed; the bus emits
`request:step:leave`.
### Changed
- Root, runtime-only, and website dependency audits are clean after supported package updates and
narrow pins for vulnerable transitives. CI audits root + website trees and builds the docs; the
GitHub OIDC release workflow audits immediately before its publish gate.
- App-scope providers now boot exactly once (memoized): a second `app.listen()`
call no longer re-runs provider factories or their side effects.
- **`WsOpenCtx.req`** (available in `@Ws`/`@Sse` handlers) is now a neutral
`WsRequest` (`{ url, headers, protocol, ip }`) instead of the Node
`http.IncomingMessage`, so it works the same across Node and Deno. Node-only
fields such as `req.socket` / `req.rawHeaders` are no longer available on
`ctx.req`; use `ctx.protocol` / `ctx.ip` / `ctx.query` / `ctx.headers`
instead — all still provided.
- **Breaking (pre-1.0): transport is now enforced by declaration.** A buffered route
(`@Get`/`@Head`/`@Post`/`@Put`/`@Patch`/`@Delete`/`@Options`) whose handler returns an
`AsyncIterable`, or a streaming route (`@Sse`/`@Ws`) whose handler returns a plain value, now
fails with a 500 `TransportMismatchError` instead of silently switching behavior. `@Stream`
still negotiates both. Declare `@Sse`/`@Stream`/`@Ws` to stream — a return value no longer
changes a route's wire contract.
## [26.7.0-beta.0] - 2026-07-07
First public beta, published under the npm `beta` dist-tag. The API may still
change before the stable release.
### Added
- **Transport security** — native TLS termination (https/wss), CORS with a
@@ -19,10 +120,18 @@ version below is a placeholder until the API freeze.
[Standard Schema](https://standardschema.dev) (zod / valibot / arktype); the
parsed value is passed to the handler, invalid input returns `422` with
per-field issues. Core stays dependency-free.
- **Body parsing** — JSON, `application/x-www-form-urlencoded`, and
`multipart/form-data` file uploads (`@body()` → `{ fields, files }`), with a
configurable repeated-field policy (`bodyDuplicates`, per-route overridable)
and a `maxParts` DoS bound.
- **Body parsing** — JSON and `application/x-www-form-urlencoded` out of the
box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via
the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency
(a multipart request without it returns `501`), with a configurable
repeated-field policy (`bodyDuplicates`, per-route overridable) and a
`maxParts` DoS bound.
- **Routing** — `:name*` catch-all params, specificity-based precedence
(static ▸ `:param` ▸ catch-all, independent of registration order), and
`405 Method Not Allowed` with an `Allow` header when a path exists under a
different method.
- **Argument decorators** — `@needs/@ctx/@param/@query/@body/@headers/@inbound/
@abort`, plus `@header('name')` as a singular alias of `@headers`.
- **Streams** — SSE / ndjson / WebSocket duplex over a multicast
`AsyncIterable` channel, with backpressure and cleanup; `rooms` broadcast hubs.
- **Graph introspection** — `app.explain(route)`, `app.graph()`,
@@ -30,11 +139,20 @@ version below is a placeholder until the API freeze.
- **Operational hardening** — request body/size limits (`413`), request and
keep-alive timeouts, and `app.close()` graceful shutdown (drains in-flight
requests, closes live streams and mesh links).
- **Visible degradation** — optional providers that fail at boot are
summarized on `listen()` and queryable via `app.degraded()`, instead of a
silent warning.
- **Testing ergonomics** — `createApp({ overrides })` swaps any provider/step
by token in one line.
- **Mesh (walking skeleton)** — `teapot`/`teacup` distributed dependency
injection over a secret-gated WebSocket control channel. Experimental.
- **Mesh (alpha, walking skeleton)** — `teapot`/`teacup` distributed dependency
injection over a secret-gated WebSocket control channel. Gated behind
`experimental: true`; `createApp` throws if `mesh` is configured without it.
- **Packaging** — dual **ESM + CommonJS** builds behind an `exports` map, with
matching type declarations; one runtime dependency (`reflect-metadata`),
`ws` and `busboy` optional peers.
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
[Unreleased]: https://git.svc.zoit.services/Green-Tea/core/commits/develop
[Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...main
[26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0
[26.7.0-beta.0]: https://github.com/Expressive-Tea/green-tea/releases/tag/v26.7.0-beta.0
+65 -26
View File
@@ -1,32 +1,57 @@
# 🍵 green-tea
<p align="center">
<img src="./assets/logo.png" width="112" alt="Green Tea" />
</p>
> A calm, type-safe HTTP framework for Node. Your API is an explicit **dependency graph** you can see, slice, and trust — not a mutable bag threaded through positional middleware.
<h1 align="center">Green&nbsp;Tea.</h1>
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata`. Two optional peers you install only if you use them: `ws` (WebSocket / mesh) and `busboy` (multipart uploads).
<p align="center"><b>A zen, opinionated, type-safe framework.</b></p>
```bash
npm install @green-tea/core reflect-metadata
# optional, only if you use them:
npm install ws # WebSocket routes (@Ws) and mesh
npm install busboy # multipart/form-data file uploads
```
<p align="center">
Your API is an explicit <b>dependency graph</b> you can see, slice, and trust —<br />
not a mutable bag threaded through positional middleware. <i>That's the tea.</i> 🍵
</p>
---
## The problem
```js
const user = req.user;
```
It compiles. TypeScript is happy. And it's a prayer — `req.user` exists only if some middleware ran before this handler, which depends on where the router got mounted, which line `app.use()` sits on, and whether a package you installed last sprint quietly inserted itself into the middle of your chain.
So you keep the whole request in your head: what ran, what's on `req` by now, what order things fire in, which plugin deleted your body parser. That bookkeeping is where the bugs live, and no test or type catches them, because nothing is *wrong* — the code is correct and the app is still broken.
## The idea
Most frameworks make you keep the whole request in your head: which middleware ran, whether `req.user` exists by now, what order things fire in, which plugin quietly deleted your body parser. That mental bookkeeping is where bugs live.
green-tea puts the request on the page instead. You declare what each step **needs** and **produces**; the framework computes the order, type-checks the wiring, and can print the whole thing.
green-tea puts the request on the page instead. You declare what each step **needs** and **produces**; the framework computes the order, type-checks the wiring, and can print the whole thing. A route runs only the steps its handler actually depends on. Boot fails loudly when a dependency is missing, so you never serve `undefined`.
- Order is **derived** from your dependencies, never maintained by hand.
- Boot **fails loudly** when nothing provides a key, so you never serve `undefined`.
- A route runs **only** the steps its handler actually depends on.
- `app.explain('/users/:id')` prints the whole chain. Onboarding is reading, not archaeology.
Less to hold in your head. That's the tea.
```bash
npm install @green-tea/core@beta reflect-metadata
```
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata`. Two optional peers you install only if you use them:
```bash
npm install ws # WebSocket routes (@Ws) and mesh
npm install busboy # multipart/form-data file uploads
```
## What's different — and why it matters
- **The pipeline is a graph, not a chain.** You never write "put this before that." You declare `needs`/`provides` and green-tea topologically sorts it. *Why it matters:* no ordering bugs, no positional guesswork, and each route runs only its slice of the graph (an auth step doesn't run on public routes).
- **The type is the contract.** What a handler reads from the context *is* its dependency list. In the typed `flow` core, a handler that reads `ctx.user` **fails to compile** if no step produces `user`. *Why it matters:* whole classes of "it was undefined in prod" disappear at compile time.
- **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram. *Why it matters:* onboarding, debugging, and audits are reading, not archaeology. (NestJS puts this behind a paid Devtools plan.)
- **One primitive for real-time.** Return an `AsyncIterable` and the transport streams it — SSE, ndjson, or a WebSocket duplex — with backpressure and cleanup handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
- **You can see the request before it runs.** `app.explain('/users/:id')` prints the ordered chain with origins; `app.graph()` / `GET /__graph__` render it as a live diagram; `app.openapi()` projects the same metadata into an OpenAPI 3.1 spec. *Why it matters:* onboarding, debugging, audits, and API docs are reading, not archaeology. (NestJS puts the graph behind a paid Devtools plan.)
- **One primitive for real-time.** Declare the transport — SSE, ndjson, or a WebSocket duplex — and return an `AsyncIterable`; backpressure and cleanup are handled. *Why it matters:* no separate gateway, adapter, or library to bolt on.
- **The same app runs on Node, Deno, Bun, and the edge.** One codebase, one import; you swap the entry point (`app.listen` → `serveDeno` / `serveBun` / `edgeHandler`) and nothing else. HTTP, SSE, and WebSocket — including rooms and channels — behave identically on all four. *Why it matters:* the graph model isn't a bet on one runtime's future, and no other opinionated/DI framework runs everywhere.
- **A remote dependency looks like a local one.** `@needs('billing')` resolves the same whether `billing` lives in this process or on another node (mesh, experimental). *Why it matters:* no gRPC layer or message-pattern DSL to learn — there's the graph, and some nodes happen to live elsewhere.
- **Plugins can't sabotage you.** A plugin gets `bus.on(...)` (observe) and `scope.add(...)` (extend its own scope). There is no API to reorder or delete another scope's steps. *Why it matters:* installing a plugin can't break your body parser.
@@ -41,14 +66,15 @@ green-tea has one model: an **`AsyncIterable`**. A handler that returns a sequen
| `@Sse` | server → client | `text/event-stream` | live updates to a browser (`EventSource`) |
| `@Ws` | duplex | WebSocket | chat, collaboration — anything two-way |
| `@Stream` | negotiated | SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` | one handler, the client chooses |
| *(plain return)* | server → client | SSE or ndjson by `Accept` | programmatic streaming over `fetch` |
The primitive never changes — it's always an `AsyncIterable`. What changes is **direction and framing**, and you declare which. That's the difference between each iterable green-tea hands you:
- **`@Sse` / plain return** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line.
- **`@Sse`** — you return **one** iterable: the *outbound* stream. Each `yield` becomes an SSE event, or an ndjson line.
- **`@Ws` (duplex)** — **two** iterables. `@inbound()` gives you the client's *incoming* messages to consume; the one you **return** is the *outbound* stream to the client. `@abort()` hands you an `AbortSignal` for teardown.
- **`@Stream`** — you write the handler once; the client's request decides whether it arrives as SSE, ndjson, or a WebSocket. No branching in your code.
**Your wire contract is what you declared, never what you happened to return.** A buffered route that returns an iterable, or a streaming route that returns a plain value, fails loudly with a `TransportMismatchError` — green-tea will not quietly switch a route's transport because of a return type. Refactoring a handler's internals can't change how it talks to the client.
Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it.
```typescript
@@ -81,6 +107,9 @@ Beta shipped the parts a real API needs, without growing the runtime dependency
- **CORS** with a guarded preflight and the credentials-never-`*` rule enforced for you.
- **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed.
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
- **Ceilings that are already on.** `limits` caps body size (`413`), multipart parts, and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. Configurable, and safe before you configure anything.
- **Graceful shutdown.** `app.close()` drains in-flight requests, closes live streams and mesh links.
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
@@ -107,6 +136,7 @@ Every framework here can serve `/users/:id`. The difference shows up as the app
| **Real-time** | bolt on `ws`/`sse` libs | plugins | separate Gateway + adapter | separate engine | **return an `AsyncIterable`** — SSE, ndjson & WebSocket, one primitive |
| **Cross-service calls** | HTTP client / gRPC by hand | HTTP client / gRPC | Microservices transport + message patterns | — | **`@needs('x')` resolves on another node** |
| **Plugin can break your pipeline?** | yes (deletes your body parser) | encapsulated, but hooks are global | interceptor order matters | yes | **no** — plugins only `bus.on` + `scope.add` |
| **Runs on** | Node | Node | Node | Node | **Node · Deno · Bun · edge** — same code, swap the entry point |
| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws`, `busboy` optional) |
### Read it as a story
@@ -179,17 +209,20 @@ The handler signature declares exactly what it wants — in any order, nothing m
`@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it.
> **Optional providers degrade, they don't crash.** A provider marked `optional: true` that throws on boot does **not** abort startup — it is left unregistered and logged. On `listen()` the app prints a one-line summary of what's running degraded, and the list is queryable via `app.degraded()`. Routes that actually need a degraded provider fail at request time, not at boot. This is deliberate (graceful degradation); wire an alert off `app.degraded()` or the `boot:provider:fail` bus event in production so a degraded start is never silent.
> **Optional providers degrade, they don't crash.** A provider marked `optional: true` that throws on boot does **not** abort startup — it is left unregistered and logged. The first serving call (`fetch`, `upgrade`, or `listen`) prints a one-line summary of what's running degraded, and the list is queryable via `app.degraded()`. Routes that actually need a degraded provider fail at request time, not at boot. This is deliberate (graceful degradation); wire an alert off `app.degraded()` or the `boot:provider:fail` bus event in production so a degraded start is never silent.
## Routing
Patterns match by segment: static, `:param` (one segment), and a trailing `:name*` **catch-all** that captures the rest of the path — slashes included — into `params.name`. When more than one route matches, the **most specific wins** (static ▸ `:param` ▸ catch-all), independent of registration order. A path that exists under a *different* method returns **`405` with an `Allow` header**, not `404`.
Patterns match by segment: static, constrained params such as `:id(\d+)`, plain `:param`, and a trailing `:name*` **catch-all**. The most specific wins (static ▸ constrained ▸ plain param ▸ catch-all), and ambiguous same-method shapes fail at boot instead of depending on registration order.
```typescript
@Get('/users/:id(\\d+)') // /users/42
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
```
**Not yet** (post-beta, on the roadmap): regex / typed param constraints like `:id(\d+)`, and route matching is a linear scan — fine for typical route tables, but a radix-tree matcher for very large ones isn't built.
`@Head` and `@Options` provide explicit handlers. Otherwise a buffered GET can serve HEAD without a body, and OPTIONS on an existing path returns `204` with canonical `Allow`; other method mismatches return `405`. `/path` and `/path/` are equivalent, while repeated slashes and malformed encoding return `400` rather than being normalized ambiguously. Constraints use a deliberately safe regex subset. See the full [routing guide](https://green-tea.expressive-tea.io/docs/guides/routing/).
Matching is still a linear scan — fine for typical route tables. A radix tree for very large tables remains post-beta work.
## Two layers
@@ -210,21 +243,24 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**Bring your own auth (and friends).** green-tea ships transport security — TLS/wss, secure-by-default headers, CORS — but **not** authentication, authorization, rate-limiting, CSRF, or sessions. You compose those as steps and plugins (the `Authenticate` step in the quick look is the pattern). Unlike Express/Fastify, there is no off-the-shelf plugin ecosystem for them yet.
**Node only.** Runs on Node ≥ 18. Deno / Bun / edge runtimes (over web-standard `Request`/`Response`) are on the roadmap, not built — only `src/http/` is runtime-specific today.
**No observability layer, either.** There is no built-in logger, no metrics export, and no tracing hooks; core does not depend on a logging library and does not intend to. Today you compose those as steps and providers like anything else. A first-class contract — an injectable logger, structured output, and hooks an OpenTelemetry exporter can attach to — is [tracked as one design](https://github.com/Expressive-Tea/green-tea/issues/10), because doing it piecemeal produces three mechanisms that don't fit together. If your team's definition of production-ready includes shipping traces on day one, this is the gap to know about.
**Runtimes differ in what they can offer.** Node ≥ 18, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag.
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
## Docs & development
- **[Quickstart](./docs/quickstart.md)** — install + concrete examples (routes/DI, `flow`, validation, uploads, SSE, WebSocket, mesh, plugins).
- **[Architecture](./docs/architecture.md)** — the mental map (layers, request lifecycle, mesh) as diagrams.
- **[green-tea.expressive-tea.io/docs](https://green-tea.expressive-tea.io/docs)** — getting started, concepts (the graph, `flow`), and guides: routing, DI, validation, uploads, streaming, HTML, security, errors, introspection, OpenAPI, plugins, mesh, runtimes, testing.
- **[matcha](https://github.com/Expressive-Tea/matcha)** — the CLI. `matcha new` scaffolds a project (Node, Deno, or Bun), `matcha create` generates and auto-wires controllers/steps/providers/modules, `matcha run` detects your runtime and watches. A standalone Rust binary — no JS runtime needed to install it.
```bash
npm install
npm test # vitest
npm test # vitest (Node); test:deno / test:bun / test:edge for the other runtimes
npm run typecheck # tsc --noEmit (includes the compile-time-guarantee type test)
npm run build # emit dist/
npm run build # emit dist/ (tsup: dual ESM + CJS)
npm run bench # regenerate BENCHMARKS.md
npm run docs:dev # the documentation site (website/)
```
## Roadmap
@@ -234,13 +270,16 @@ npm run bench # regenerate BENCHMARKS.md
- ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel, with backpressure and cleanup.
- ✅ **graph introspection** — `explain` / `graph` / `toMermaid` / `GET /__graph__`.
- ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices.
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), runtime adapters (Deno / Bun / edge over web-standard `Request`/`Response`), official plugins.
- ✅ **runs everywhere** — Node, Deno, Bun, and Cloudflare Workers over web-standard `Request`/`Response`, with identical WebSocket behaviour on all four.
- ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving.
- ✅ **router completeness for beta** — safe constrained params, deterministic precedence, explicit/automatic HEAD and OPTIONS, strict path validation, and ambiguity checks across local and mesh routes.
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), official plugins, and a radix-tree matcher for very large route tables.
## Versioning
green-tea uses **calendar versioning**: `YY.MM.PATCH` (e.g. `26.07.0` = the first release cut in July 2026, patch 0). A version tells you *when* it shipped, not how many breaking changes preceded it — those are always called out in the [CHANGELOG](./CHANGELOG.md).
green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.8.0` = the first release cut in August 2026, patch 0). The month is **not** zero-padded — npm treats versions as semver, which forbids leading zeros. A version tells you *when* it shipped, not how many breaking changes preceded it — those are always called out in the [CHANGELOG](./CHANGELOG.md).
**While in beta**, releases carry a `-beta.N` pre-release suffix on the calendar version (e.g. `26.07.0-beta.0`) and publish under the npm `beta` dist-tag — so a plain `npm install @green-tea/core` won't pick one up until the first stable calendar release. The API can still change between betas.
**While in beta**, releases carry a `-beta.N` pre-release suffix on the calendar version (e.g. `26.8.0-beta.0`) and publish under the npm `beta` dist-tag. Until the first stable release there is nothing else to install, so `latest` tracks the newest beta too — `npm install @green-tea/core` and `@green-tea/core@beta` resolve to the same version. Install with the explicit `@beta` tag anyway: the day a stable ships, `latest` moves to it and your installs stay on the channel you meant. The API can still change between betas.
## License
+16
View File
@@ -0,0 +1,16 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 611 620" fill="none">
<path d="M0 0 C6.4 4.22 7.06 11.7 8.6 18.74 C9.17 21.55 9.71 24.37 10.23 27.2 C10.43 28.25 10.63 29.3 10.84 30.39 C11.48 33.82 12.12 37.25 12.75 40.69 C12.86 41.28 12.86 41.28 13.41 44.27 C19.74 78.61 25.24 113.17 28 148 C28.1 149.25 28.2 150.5 28.31 151.78 C33.71 219.69 29.07 297.74 -17 352 C-37.58 376.04 -63.34 393.66 -92.79 405.14 C-94.83 405.93 -96.85 406.75 -98.87 407.58 C-119.07 415.67 -140.54 420.66 -162 424 C-163.26 424.2 -164.52 424.4 -165.82 424.6 C-213.88 431.88 -265.63 431.11 -313 420 C-313.8 419.81 -314.6 419.63 -315.42 419.43 C-321.96 417.87 -328.02 416.17 -334 413 C-333.4 408.16 -331.32 404.45 -329 400.25 C-328.63 399.57 -328.26 398.88 -327.88 398.18 C-325.16 393.16 -325.16 393.16 -324 392 C-316.45 391.5 -309.28 393.04 -301.88 394.38 C-266.77 400.41 -230.41 401.2 -195 397 C-193.89 396.88 -192.78 396.75 -191.63 396.63 C-143.03 391.12 -90.07 376.55 -53 343 C-52.13 342.26 -51.26 341.53 -50.37 340.77 C-13.69 309.26 -0.6 260.49 3 214 C6.89 162.68 1.22 110.21 -9.66 60.01 C-10 58 -10 58 -10 54 C-10.66 54 -11.32 54 -12 54 C-12.08 54.65 -12.16 55.3 -12.24 55.98 C-13.28 60.13 -15.18 63.61 -17.19 67.38 C-17.63 68.2 -18.06 69.02 -18.51 69.87 C-27.46 86.43 -37.3 102.24 -49 117 C-49.73 117.94 -50.46 118.88 -51.21 119.85 C-55.22 124.97 -59.47 129.83 -63.85 134.63 C-65.75 136.73 -67.6 138.85 -69.44 141 C-76.06 148.56 -83.19 155.34 -91.04 161.6 C-93.13 163.29 -95.16 165 -97.18 166.77 C-122.17 188.79 -151.25 205.29 -180.04 221.76 C-192.95 229.14 -205.58 236.83 -218 245 C-218.85 245.56 -219.7 246.12 -220.58 246.7 C-229.87 252.82 -238.77 259.13 -247.12 266.49 C-249.7 268.74 -252.35 270.84 -255.06 272.94 C-267.05 282.7 -278.61 294.17 -288.03 306.45 C-289.89 308.86 -291.81 311.22 -293.74 313.57 C-298.14 319.07 -302.07 324.81 -305.94 330.69 C-306.64 331.75 -307.34 332.82 -308.07 333.91 C-310.06 336.94 -312.03 339.97 -314 343 C-314.45 343.69 -314.9 344.38 -315.36 345.1 C-333.78 373.72 -347.37 405.97 -360.01 437.47 C-367.19 455.23 -367.19 455.23 -373 459 C-381.02 461.67 -388.52 459.36 -396 456 C-400.94 452.9 -406.06 449.11 -409 444 C-409.81 440.26 -409.56 438.01 -407.71 434.64 C-404.3 429.62 -400.39 425.15 -396.3 420.68 C-391.69 415.32 -387.56 409.58 -383.38 403.88 C-382.15 402.21 -380.9 400.55 -379.64 398.89 C-379 398.02 -378.35 397.15 -377.69 396.25 C-377.13 395.51 -376.58 394.78 -376.01 394.02 C-375 392 -375 392 -375.3 390.07 C-376.44 386.69 -378.78 384.1 -380.94 381.31 C-403.08 351.79 -416.04 315.59 -420 279 C-420.11 278.07 -420.22 277.14 -420.34 276.18 C-425.19 227.03 -413.92 174.12 -382.44 135.12 C-380.97 133.41 -379.49 131.7 -378 130 C-377.28 129.17 -376.56 128.34 -375.82 127.49 C-358.11 107.42 -337.64 91.46 -314 79 C-313.38 78.67 -312.76 78.33 -312.12 77.99 C-300.18 71.58 -287.7 66.68 -275 62 C-274.14 61.68 -273.29 61.36 -272.4 61.03 C-234.24 47.03 -193.39 42.56 -153.28 37.74 C-131.4 35.11 -109.62 32.33 -88 28 C-87.42 27.89 -87.42 27.89 -84.51 27.32 C-61.65 22.81 -40.27 14.77 -19.21 4.91 C-6.48 -0.98 -6.48 -0.98 0 0 Z M-36.19 37.49 C-71.76 55.45 -113.52 58.93 -152.55 63.46 C-196.61 68.6 -196.61 68.6 -216 73 C-217 73.22 -218 73.43 -219.03 73.65 C-264.38 83.45 -306.87 101.06 -341 133 C-341.95 133.88 -342.9 134.77 -343.88 135.68 C-373.91 164.27 -390.12 205.53 -391.38 246.65 C-392.35 288.29 -383.46 327.6 -361 363 C-358.84 360.25 -357.1 357.49 -355.47 354.39 C-354.99 353.5 -354.52 352.61 -354.03 351.69 C-353.78 351.21 -353.78 351.21 -352.5 348.81 C-342.16 329.63 -330.05 311.66 -316 295 C-315.08 293.89 -314.16 292.78 -313.24 291.68 C-308.88 286.45 -304.51 281.32 -299.6 276.6 C-297.85 274.85 -296.28 273.01 -294.69 271.12 C-278.78 252.73 -256.54 237.48 -235.78 225.07 C-233.06 223.44 -230.38 221.74 -227.69 220.06 C-219.23 214.87 -210.61 209.95 -202 205 C-193.33 200.01 -184.66 195.01 -176 190 C-174.99 189.42 -173.99 188.84 -172.95 188.24 C-161.6 181.67 -150.51 174.92 -139.83 167.3 C-137.99 165.99 -136.14 164.7 -134.29 163.41 C-123.48 155.83 -113.46 147.55 -103.79 138.57 C-101.47 136.44 -99.13 134.36 -96.75 132.31 C-89.94 126.39 -83.79 119.91 -78 113 C-77.55 112.46 -77.1 111.93 -76.64 111.38 C-57.15 88.05 -39.86 63.1 -28 35 C-31.34 35 -33.25 36 -36.19 37.49 Z " fill="currentColor" transform="translate(501,80)"/>
<g stroke="currentColor" stroke-width="12" stroke-linecap="round" fill="none">
<path d="M277 312 Q255 263 221 247"/>
<path d="M338 276 Q382 305 393 340"/>
<path d="M366 258 Q348 214 317 200"/>
<path d="M443 186 Q469 204 475 224"/>
</g>
<g fill="currentColor">
<circle cx="221" cy="247" r="13"/>
<circle cx="393" cy="340" r="13"/>
<circle cx="475" cy="224" r="11"/>
</g>
<circle cx="317" cy="200" r="18" fill="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 4.6 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

+16
View File
@@ -0,0 +1,16 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 611 620" fill="none">
<path d="M0 0 C6.4 4.22 7.06 11.7 8.6 18.74 C9.17 21.55 9.71 24.37 10.23 27.2 C10.43 28.25 10.63 29.3 10.84 30.39 C11.48 33.82 12.12 37.25 12.75 40.69 C12.86 41.28 12.86 41.28 13.41 44.27 C19.74 78.61 25.24 113.17 28 148 C28.1 149.25 28.2 150.5 28.31 151.78 C33.71 219.69 29.07 297.74 -17 352 C-37.58 376.04 -63.34 393.66 -92.79 405.14 C-94.83 405.93 -96.85 406.75 -98.87 407.58 C-119.07 415.67 -140.54 420.66 -162 424 C-163.26 424.2 -164.52 424.4 -165.82 424.6 C-213.88 431.88 -265.63 431.11 -313 420 C-313.8 419.81 -314.6 419.63 -315.42 419.43 C-321.96 417.87 -328.02 416.17 -334 413 C-333.4 408.16 -331.32 404.45 -329 400.25 C-328.63 399.57 -328.26 398.88 -327.88 398.18 C-325.16 393.16 -325.16 393.16 -324 392 C-316.45 391.5 -309.28 393.04 -301.88 394.38 C-266.77 400.41 -230.41 401.2 -195 397 C-193.89 396.88 -192.78 396.75 -191.63 396.63 C-143.03 391.12 -90.07 376.55 -53 343 C-52.13 342.26 -51.26 341.53 -50.37 340.77 C-13.69 309.26 -0.6 260.49 3 214 C6.89 162.68 1.22 110.21 -9.66 60.01 C-10 58 -10 58 -10 54 C-10.66 54 -11.32 54 -12 54 C-12.08 54.65 -12.16 55.3 -12.24 55.98 C-13.28 60.13 -15.18 63.61 -17.19 67.38 C-17.63 68.2 -18.06 69.02 -18.51 69.87 C-27.46 86.43 -37.3 102.24 -49 117 C-49.73 117.94 -50.46 118.88 -51.21 119.85 C-55.22 124.97 -59.47 129.83 -63.85 134.63 C-65.75 136.73 -67.6 138.85 -69.44 141 C-76.06 148.56 -83.19 155.34 -91.04 161.6 C-93.13 163.29 -95.16 165 -97.18 166.77 C-122.17 188.79 -151.25 205.29 -180.04 221.76 C-192.95 229.14 -205.58 236.83 -218 245 C-218.85 245.56 -219.7 246.12 -220.58 246.7 C-229.87 252.82 -238.77 259.13 -247.12 266.49 C-249.7 268.74 -252.35 270.84 -255.06 272.94 C-267.05 282.7 -278.61 294.17 -288.03 306.45 C-289.89 308.86 -291.81 311.22 -293.74 313.57 C-298.14 319.07 -302.07 324.81 -305.94 330.69 C-306.64 331.75 -307.34 332.82 -308.07 333.91 C-310.06 336.94 -312.03 339.97 -314 343 C-314.45 343.69 -314.9 344.38 -315.36 345.1 C-333.78 373.72 -347.37 405.97 -360.01 437.47 C-367.19 455.23 -367.19 455.23 -373 459 C-381.02 461.67 -388.52 459.36 -396 456 C-400.94 452.9 -406.06 449.11 -409 444 C-409.81 440.26 -409.56 438.01 -407.71 434.64 C-404.3 429.62 -400.39 425.15 -396.3 420.68 C-391.69 415.32 -387.56 409.58 -383.38 403.88 C-382.15 402.21 -380.9 400.55 -379.64 398.89 C-379 398.02 -378.35 397.15 -377.69 396.25 C-377.13 395.51 -376.58 394.78 -376.01 394.02 C-375 392 -375 392 -375.3 390.07 C-376.44 386.69 -378.78 384.1 -380.94 381.31 C-403.08 351.79 -416.04 315.59 -420 279 C-420.11 278.07 -420.22 277.14 -420.34 276.18 C-425.19 227.03 -413.92 174.12 -382.44 135.12 C-380.97 133.41 -379.49 131.7 -378 130 C-377.28 129.17 -376.56 128.34 -375.82 127.49 C-358.11 107.42 -337.64 91.46 -314 79 C-313.38 78.67 -312.76 78.33 -312.12 77.99 C-300.18 71.58 -287.7 66.68 -275 62 C-274.14 61.68 -273.29 61.36 -272.4 61.03 C-234.24 47.03 -193.39 42.56 -153.28 37.74 C-131.4 35.11 -109.62 32.33 -88 28 C-87.42 27.89 -87.42 27.89 -84.51 27.32 C-61.65 22.81 -40.27 14.77 -19.21 4.91 C-6.48 -0.98 -6.48 -0.98 0 0 Z M-36.19 37.49 C-71.76 55.45 -113.52 58.93 -152.55 63.46 C-196.61 68.6 -196.61 68.6 -216 73 C-217 73.22 -218 73.43 -219.03 73.65 C-264.38 83.45 -306.87 101.06 -341 133 C-341.95 133.88 -342.9 134.77 -343.88 135.68 C-373.91 164.27 -390.12 205.53 -391.38 246.65 C-392.35 288.29 -383.46 327.6 -361 363 C-358.84 360.25 -357.1 357.49 -355.47 354.39 C-354.99 353.5 -354.52 352.61 -354.03 351.69 C-353.78 351.21 -353.78 351.21 -352.5 348.81 C-342.16 329.63 -330.05 311.66 -316 295 C-315.08 293.89 -314.16 292.78 -313.24 291.68 C-308.88 286.45 -304.51 281.32 -299.6 276.6 C-297.85 274.85 -296.28 273.01 -294.69 271.12 C-278.78 252.73 -256.54 237.48 -235.78 225.07 C-233.06 223.44 -230.38 221.74 -227.69 220.06 C-219.23 214.87 -210.61 209.95 -202 205 C-193.33 200.01 -184.66 195.01 -176 190 C-174.99 189.42 -173.99 188.84 -172.95 188.24 C-161.6 181.67 -150.51 174.92 -139.83 167.3 C-137.99 165.99 -136.14 164.7 -134.29 163.41 C-123.48 155.83 -113.46 147.55 -103.79 138.57 C-101.47 136.44 -99.13 134.36 -96.75 132.31 C-89.94 126.39 -83.79 119.91 -78 113 C-77.55 112.46 -77.1 111.93 -76.64 111.38 C-57.15 88.05 -39.86 63.1 -28 35 C-31.34 35 -33.25 36 -36.19 37.49 Z " fill="#5FB88A" transform="translate(501,80)"/>
<g stroke="#5FB88A" stroke-width="12" stroke-linecap="round" fill="none">
<path d="M277 312 Q255 263 221 247"/>
<path d="M338 276 Q382 305 393 340"/>
<path d="M366 258 Q348 214 317 200"/>
<path d="M443 186 Q469 204 475 224"/>
</g>
<g fill="#5FB88A">
<circle cx="221" cy="247" r="13"/>
<circle cx="393" cy="340" r="13"/>
<circle cx="475" cy="224" r="11"/>
</g>
<circle cx="317" cy="200" r="18" fill="#7C6CF0"/>
</svg>

After

Width:  |  Height:  |  Size: 4.6 KiB

+1 -1
View File
@@ -12,7 +12,7 @@ app.post('/validate', {
if (!b.email.includes('@')) { reply.code(422); return { error: 'invalid' }; }
return { email: b.email };
});
app.listen({ port: 0 }, (err, addr) => {
app.listen({ port: 0, host: '0.0.0.0' }, (err, addr) => {
if (err) { console.error(err); process.exit(1); }
console.log(`READY ${Number(new URL(addr).port)}`);
});
+34
View File
@@ -0,0 +1,34 @@
import 'reflect-metadata';
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
import { serveBun } from '../../dist/bun.mjs';
// Same BenchModule as green-tea.ts (Node), served via Bun.serve instead of app.listen.
const emailSchema = {
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
};
function makeStep(n: number) {
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
class S { run() { return { [`s${n}`]: n }; } }
return S;
}
const steps = [1, 2, 3, 4, 5].map(makeStep);
@Route('/')
class Bench {
@Get('/hello') hello() { return { hello: 'world' }; }
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
@Get('/steps/0') steps0() { return { hello: 'world' }; }
@Get('/steps/3') steps3(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
}
@Module({ mountpoint: '/', steps, controllers: [Bench] })
class BenchModule {}
const app = createApp({ modules: [BenchModule], security: false });
const server = serveBun(app, { port: 0, hostname: '0.0.0.0' });
console.log(`READY ${server.port}`);
+33
View File
@@ -0,0 +1,33 @@
import 'reflect-metadata';
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs';
import { serveDeno } from '../../dist/deno.mjs';
// Same BenchModule as green-tea.ts (Node), served via Deno.serve instead of app.listen.
const emailSchema = {
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
};
function makeStep(n: number) {
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
class S { run() { return { [`s${n}`]: n }; } }
return S;
}
const steps = [1, 2, 3, 4, 5].map(makeStep);
@Route('/')
class Bench {
@Get('/hello') hello() { return { hello: 'world' }; }
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
@Get('/steps/0') steps0() { return { hello: 'world' }; }
@Get('/steps/3') steps3(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
}
@Module({ mountpoint: '/', steps, controllers: [Bench] })
class BenchModule {}
const app = createApp({ modules: [BenchModule], security: false });
serveDeno(app, { port: 0, hostname: '0.0.0.0', onListen: (a: { port: number }) => console.log(`READY ${a.port}`) });
+1 -1
View File
@@ -9,7 +9,7 @@ async function main() {
inst.disable('x-powered-by');
inst.set('etag', false);
const app = await NestFactory.create(BenchModule, new ExpressAdapter(inst), { logger: false });
await app.listen(0, '127.0.0.1');
await app.listen(0, '0.0.0.0');
const server = app.getHttpServer();
server.keepAliveTimeout = 5000; // parity (works on Node http.Server after listen)
console.log(`READY ${server.address().port}`);
+1 -1
View File
@@ -6,7 +6,7 @@ import { BenchModule } from './_nest-shared';
async function main() {
const adapter = new FastifyAdapter({ logger: false, keepAliveTimeout: 5000 }); // parity via constructor
const app = await NestFactory.create<NestFastifyApplication>(BenchModule, adapter, { logger: false });
await app.listen(0, '127.0.0.1');
await app.listen(0, '0.0.0.0');
const server = app.getHttpServer();
console.log(`READY ${(server.address() as any).port}`);
}
+26
View File
@@ -0,0 +1,26 @@
import express from 'express';
// Express counterpart: /chain/N runs N trivial middlewares before the handler —
// the closest apples-to-apples to green-tea's N chained steps.
const app = express();
app.disable('x-powered-by');
app.set('etag', false);
const mw = (_req: any, _res: any, next: any) => next();
function route(path: string, n: number): void {
const chain = Array.from({ length: n }, () => mw);
app.get(path, ...chain, (_req, res) => { res.json({ ok: 1 }); });
}
route('/chain/0', 0);
route('/chain/10', 10);
route('/chain/25', 25);
route('/chain/50', 50);
route('/chain/75', 75);
route('/chain/100', 100);
const server = app.listen(0, () => {
server.keepAliveTimeout = 5000;
console.log(`READY ${(server.address() as any).port}`);
});
+33
View File
@@ -0,0 +1,33 @@
import 'reflect-metadata';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
// 100 chained steps: s1..s100, each needs the previous. A route that @needs the Nth
// pulls exactly N steps transitively — so /chain/100 runs the full 100-deep graph slice.
function makeStep(n: number) {
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
class S { run() { return { [`s${n}`]: n }; } }
return S;
}
const steps = Array.from({ length: 100 }, (_, i) => makeStep(i + 1));
@Route('/chain')
class Chain {
@Get('/0') d0() { return { ok: 1 }; }
@Get('/10') d10(@needs('s10') s: number) { return { s }; }
@Get('/25') d25(@needs('s25') s: number) { return { s }; }
@Get('/50') d50(@needs('s50') s: number) { return { s }; }
@Get('/75') d75(@needs('s75') s: number) { return { s }; }
@Get('/100') d100(@needs('s100') s: number) { return { s }; }
}
@Module({ mountpoint: '/', steps, controllers: [Chain] })
class ScaleModule {}
const app = createApp({ modules: [ScaleModule], security: false });
async function main() {
const server = await app.listen(0);
server.keepAliveTimeout = 5000;
console.log(`READY ${(server.address() as any).port}`);
}
main().catch((e) => { console.error(e); process.exit(1); });
+16
View File
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"lib": ["deno.window", "deno.ns"]
},
"unstable": ["sloppy-imports"],
"imports": {
"http": "node:http",
"https": "node:https",
"crypto": "node:crypto",
"events": "node:events",
"stream": "node:stream"
},
"lint": { "exclude": ["dist", "node_modules"] }
}
Generated
+62
View File
@@ -0,0 +1,62 @@
{
"version": "5",
"specifiers": {
"jsr:@std/assert@*": "1.0.19",
"jsr:@std/internal@^1.0.12": "1.0.14"
},
"jsr": {
"@std/assert@1.0.19": {
"integrity": "eaada96ee120cb980bc47e040f82814d786fe8162ecc53c91d8df60b8755991e",
"dependencies": [
"jsr:@std/internal"
]
},
"@std/internal@1.0.14": {
"integrity": "291516b3d4c35024d6ffbc0a9df5bf4c64116e05b50012cf846710152d2ffdf7"
}
},
"workspace": {
"packageJson": {
"dependencies": [
"npm:@eslint/js@^9.39.5",
"npm:@nestjs/common@^11.1.28",
"npm:@nestjs/core@^11.1.28",
"npm:@nestjs/platform-express@^11.1.28",
"npm:@nestjs/platform-fastify@^11.1.28",
"npm:@stylistic/eslint-plugin@^5.10.0",
"npm:@types/autocannon@^7.12.7",
"npm:@types/busboy@^1.5.4",
"npm:@types/express@^5.0.6",
"npm:@types/node@^18.19.0",
"npm:@types/ws@^8.18.1",
"npm:autocannon@8",
"npm:busboy@^1.6.0",
"npm:cognitive-complexity-ts@~0.8.2",
"npm:esbuild@0.27.2",
"npm:eslint@^9.39.5",
"npm:express@^5.2.1",
"npm:fastify@^5.11.0",
"npm:graphql@^16.9.0",
"npm:miniflare@^4.20260730.0",
"npm:prettier@^3.9.6",
"npm:reflect-metadata@0.2.2",
"npm:rxjs@^7.8.2",
"npm:tsup@^8.5.1",
"npm:tsx@^4.23.5",
"npm:typescript-eslint@^8.65.0",
"npm:typescript@^5.5.0",
"npm:vite@^6.4.3",
"npm:vitest@^3.2.7",
"npm:ws@^8.21.1"
],
"overrides": {
"find-my-way": "9.7.0",
"autocannon": {
"hyperid": {
"uuid": "11.1.1"
}
}
}
}
}
}
-115
View File
@@ -1,115 +0,0 @@
# green-tea — Architecture
> The request and boot are an explicit **dependency graph**, not a mutable middleware chain.
> You declare *what* you need; the framework computes the order. The graph can extend in
> **time** (streams) and across **machines** (mesh).
## The four layers
```mermaid
flowchart TB
subgraph L3["#3 MESH — the graph crosses machines"]
direction LR
teacup["teacup (consumer)"] -- "WS RPC" --> teapot["teapot (host)"]
end
subgraph L2["#2 STREAMS — the graph emits over time"]
sse["SSE / ndjson"]:::n
ws["WebSocket duplex"]:::n
end
subgraph L15["#1.5 ARG DECORATORS — the handler declares its deps"]
sig["handler signature = dependency declaration"]:::n
end
subgraph L1["#1 CORE — graph DI + boot + router + pipeline + flow"]
core["Providers · Steps · Routes · Transformers · Container · Bus"]:::n
end
L3 --> L2 --> L15 --> L1
classDef n fill:#f6f8fa,stroke:#aaa;
```
## Building blocks
```mermaid
flowchart LR
Provider["@Provider\n(app scope · singleton)"]:::p
Step["@Step\n(request scope · per call)"]:::s
Route["@Route + @Get/@Post/@Sse/@Ws/@Stream"]:::r
Transformer["@Transformer\nvalue → ResponseShape"]:::t
Container["Container.resolve()\nasync · transport-agnostic"]:::c
Bus["Bus\nlifecycle events"]:::b
Provider --> Container
Step --> Container
Route --> Transformer
Container -. "remote binding (mesh)" .-> Provider
classDef p fill:#e7f5ff,stroke:#4dabf7;
classDef s fill:#fff3bf,stroke:#f59f00;
classDef r fill:#ebfbee,stroke:#40c057;
classDef t fill:#f3f0ff,stroke:#7950f2;
classDef c fill:#fff0f6,stroke:#e64980;
classDef b fill:#f1f3f5,stroke:#868e96;
```
## Request lifecycle
```mermaid
sequenceDiagram
participant C as Client
participant H as http.ts (transport)
participant P as Pipeline
participant G as Graph (providers/steps)
participant T as Transformer
C->>H: HTTP request
H->>H: matchRoute(method, path)
H->>P: runPipeline(seed = req envelope)
P->>G: providers (cached) + steps (topo order)
Note over G: each step merges into ctx;<br/>throw = short-circuit, return = continue
P->>P: handler(args resolved from ctx)
alt returns a value
P->>T: transformer → {status, headers, body}
T-->>C: buffered response
else returns an AsyncIterable
P-->>C: stream (SSE / ndjson / WS), backpressure + cleanup
else @needs a remote token
G-->>C: RPC to teapot, value spliced into ctx
end
```
## The unifying rule
```mermaid
flowchart TD
Q{"what does the handler return /\nwhere does a token live?"}
Q -->|"a value"| A["buffered (transformer → JSON)"]
Q -->|"an AsyncIterable"| B["stream (SSE / WS)"]
Q -->|"a token with no local provider"| D["RPC to a teapot (mesh)"]
```
One question — *"what produces this token and where does it live?"* — answers local DI,
streaming, and distribution. That single seam is why green-tea isn't "Express with decorators":
**the graph is the product.**
## Mesh walking skeleton (spec #3)
```mermaid
flowchart LR
subgraph A["Node A — teapot"]
ea["@Provider({export:true})\n@Step({export:true})\n@Get('/x',{export:true})"]
mc["control channel\n/__mesh__/control\n(secret-gated)"]
end
subgraph B["Node B — teacup"]
bn["@needs('auth') with\nno local provider"]
lk["link: handshake → manifest\n→ synthetic graph nodes\nwith RPC runners"]
end
bn --> lk
lk -- "hello + secret" --> mc
mc -- "manifest {scopes, routes}" --> lk
lk -- "rpc-req {id, kind, name, ctx}" --> mc
mc -- "rpc-res {id, ok, result}" --> lk
```
- **Provider exported → app scope** (resolved once via RPC, cached).
- **Step exported → request scope** (RPC per request, carries the request envelope).
- **Route exported → proxy** (teacup forwards the request, teapot runs the full pipeline).
Deferred to mesh sub-specs: discovery/auto-registration, 2-way load-balancing, failover/health.
@@ -0,0 +1,170 @@
# Router correctness and security beta design
**Date:** 2026-08-02
**Target:** `26.8.0-beta.0`
**Status:** Approved
## Goal
Prepare the August beta by completing the router's missing HTTP behavior, adding safe segment constraints, aligning the public documentation with the code, and removing known dependency vulnerabilities from the core repository and documentation site.
The release keeps the current linear matcher. A radix tree remains a separate performance project that must earn its complexity through benchmarks.
## Scope
This change includes:
- first-class `HEAD` and `OPTIONS` routes;
- automatic `HEAD` fallback to `GET`;
- automatic bare `OPTIONS` responses;
- correct and deterministic `Allow` headers;
- a tolerant trailing-slash policy with rejection of repeated internal slashes;
- route-pattern validation at boot;
- safe parameter constraints such as `:id(\d+)`;
- malformed URI handling as a client error;
- duplicate and ambiguous route detection;
- OpenAPI projection of constrained parameters;
- dependency remediation for the root package and `website/`;
- public documentation and changelog updates;
- the `26.8.0-beta.0` package-version bump.
This change excludes:
- a radix-tree matcher;
- arbitrary, unrestricted regular expressions;
- manual publication, npm tags, or registry mutations;
- mesh discovery, load balancing, and failover.
## Route semantics
### Path normalization
`/users` and `/users/` identify the same route. The matcher removes one trailing slash except for `/`.
The ingress rejects repeated slashes, including `/users//42`, with `400 Bad Request`. It applies this rule before declared-route matching and static-file fallback, so Node and Fetch adapters behave alike.
Malformed percent encoding also returns `400 Bad Request`. A malformed path never escapes the matcher as `URIError` and never becomes `500`.
### Methods
The public `HttpMethod` type and decorator surface gain `HEAD` and `OPTIONS`. `@Head` and `@Options` accept the same route options as the existing buffered method decorators.
For `HEAD`, an explicit `HEAD` route wins. Without one, the router matches the corresponding `GET` route and executes its pipeline, but every adapter suppresses the response body. The response retains the status and headers that `GET` would produce. Streaming routes do not serve as implicit `HEAD` handlers.
For a bare `OPTIONS` request, an explicit `OPTIONS` route wins. Without one, any matching path receives `204 No Content` and an `Allow` header. CORS preflight remains the earlier specialized branch and keeps its configured CORS response.
`Allow` uses a stable method order. It adds `HEAD` when a buffered `GET` route exists and adds `OPTIONS` whenever the path exists. A request with another unsupported method receives `405` plus the same value.
### Pattern validation
The application compiles and validates route patterns during graph construction. Invalid declarations fail before the app serves traffic. Validation rejects:
- a catch-all outside the final segment;
- empty parameter or catch-all names;
- repeated parameter names in one pattern;
- repeated internal slashes in declarations;
- malformed constraints;
- duplicate routes with the same method and effective pattern;
- patterns that differ only by parameter names and therefore match the same requests with equal precedence.
Errors name the method, pattern, controller origin, and conflict when applicable.
### Segment constraints
The matcher accepts a constrained parameter such as `:id(\d+)`. A constraint matches the whole decoded segment. `/users/12` matches `:id(\d+)`; `/users/12x` does not. A failed constraint remains a normal non-match, so another route may win before the router returns `404`.
The implementation compiles constraints once and caches the compiled pattern. It accepts a deliberately small regular-expression subset for common numeric, UUID, slug, and enumerated segments. It rejects lookarounds, backreferences, nested groups, nested quantifiers, and other constructs that create a practical ReDoS risk. This keeps the advertised syntax without executing unrestricted attacker-facing regular expressions.
Specificity remains deterministic:
1. static segment;
2. constrained parameter;
3. unconstrained parameter;
4. catch-all.
Registration order resolves only genuine, non-ambiguous ties that survive boot validation.
## Architecture
`src/http/router.ts` owns pattern parsing, validation, compilation, matching, method fallback, and `Allow` calculation. A compiled representation records normalized segments, parameter names, optional constraints, catch-all state, and specificity.
`src/metadata.ts` exposes the new method type and decorators. Application graph construction compiles route definitions and reports declaration errors with controller context. The runtime-neutral HTTP core decides `HEAD`, `OPTIONS`, `400`, `404`, and `405`; Node and Fetch adapters only serialize its outcome.
`src/openapi.ts` converts constrained paths to OpenAPI templates and places the accepted expression in the path parameter's `schema.pattern`. It lists explicit `HEAD` and `OPTIONS` operations but does not invent operations for automatic fallbacks.
Mesh route manifests carry the expanded method union. Existing wire behavior stays compatible because method values are strings and the change adds values without changing the envelope shape.
## Error behavior
Declaration errors fail at boot. Request syntax errors return the standard error envelope with status `400` and pass through the configured `onError` renderer. Pattern non-matches return `404`; method mismatches return `405`; automatic `OPTIONS` returns `204`.
Error responses keep the existing security and CORS header injection. They do not include decoded attacker input, stack traces, or internal regular-expression details.
## Dependency remediation
The published runtime dependency set is already clean: `npm audit --omit=dev` reports zero vulnerabilities. The full development tree and documentation site require remediation.
The root update will prefer the smallest supported versions that close each advisory:
- Vitest moves to `3.2.6`, which fixes the critical advisory while preserving Node 18 support;
- the Nest benchmark packages move to `11.1.28`, including Multer `2.2.0`;
- Miniflare moves to its current compatible patch with fixed Sharp;
- Fastify and compatible toolchain packages receive current patch/minor updates;
- `find-my-way` receives a narrow `9.7.0` override while Nest pins the vulnerable `9.6.0`, with Nest/Fastify benchmarks as a compatibility gate;
- Autocannon's `hyperid`/`uuid` chain receives an isolated remediation only if the benchmark suite proves it compatible; otherwise the benchmark dependency will be replaced or isolated rather than suppressing the advisory.
The documentation site moves Astro to `7.1.6`, Starlight to `0.41.6`, and resolves the patched PostCSS and SVGO versions. Both lockfiles will be regenerated from their manifests.
The work will not use `npm audit fix --force`, security-audit suppression, or an incompatible downgrade merely to produce a green report.
## Documentation
The change updates:
- the README routing section and roadmap;
- the Routing guide;
- the Decorators reference;
- the OpenAPI guide where constrained parameters affect output;
- the CHANGELOG and package version;
- the Starlight 404 configuration that currently emits a build warning.
Examples will state the trailing-slash policy, double-slash rejection, automatic method behavior, constraint limits, and the deferred radix-tree work.
## Verification
The implementation adds unit and integration coverage for:
- explicit and implicit `HEAD`;
- body suppression and header preservation;
- explicit and automatic `OPTIONS`;
- CORS-preflight precedence;
- deterministic `Allow` values;
- trailing slash equivalence and double-slash rejection;
- invalid percent encoding;
- route-declaration failures;
- constrained matches, non-matches, precedence, and unsafe-expression rejection;
- OpenAPI path and `schema.pattern` output;
- Node and Fetch parity;
- mesh method serialization where relevant.
The release gate runs:
- root and website audits with zero known vulnerabilities;
- the runtime-only root audit separately;
- Node tests, typecheck, lint, format, complexity, and build;
- Deno, Bun, and Edge suites when their runtimes are available;
- documentation build without the current 404 warning;
- framework benchmarks, including the Nest/Fastify paths affected by overrides;
- `npm pack --dry-run` to inspect the published artifact.
## CI and publication flow
Gitea remains the source of the release flow:
1. CI runs on `develop` and `main`.
2. A merge to Gitea `main` publishes the package to internal Verdaccio under `stg`.
3. Gitea's promotion workflow pushes only `main` and version tags to GitHub.
4. A promoted `v*` tag triggers GitHub's `release.yml`.
5. GitHub publishes to npm through Trusted Publishing/OIDC and derives `beta` from `26.8.0-beta.0`.
This implementation prepares the version and validates the workflows. It does not merge to `main`, create a release tag, publish to Verdaccio, or invoke `npm publish` locally.
@@ -0,0 +1,679 @@
# Router Security Beta Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** Ship `26.8.0-beta.0` with complete HEAD/OPTIONS behavior, safe constrained route parameters, strict path handling, accurate documentation, and clean dependency audits.
**Architecture:** Keep the linear route table, but compile and validate each pattern once. Centralize path syntax, matching, method fallback, and `Allow` calculation in the runtime-neutral HTTP layer so Node and Fetch adapters stay behaviorally identical. Remediate tooling dependencies without changing the package's Node 18 runtime contract or its one required runtime dependency.
**Tech Stack:** TypeScript, legacy decorators, Node HTTP, Fetch API, Vitest, OpenAPI 3.1, Astro/Starlight, npm lockfiles, GitHub/Gitea Actions.
---
### Task 1: Compile and validate route patterns
**Skills:** `@superpowers:test-driven-development`, `@security-review`
**Files:**
- Modify: `src/http/router.ts`
- Modify: `src/http/types.ts`
- Test: `test/router.test.ts`
**Step 1: Write failing compiler tests**
Add tests that establish the supported grammar and precedence:
```typescript
describe('compilePattern', () => {
it('compiles constrained params and gives them precedence over plain params', () => {
const routes = [route('GET', '/users/:value'), route('GET', '/users/:id(\\d+)')];
expect(matchRoute(routes, 'GET', '/users/42')?.def.pattern).toBe('/users/:id(\\d+)');
expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value');
});
it.each([
'/files/:rest*/tail',
'/users/:',
'/users/:id/:id',
'/users//:id',
'/users/:id((a+)+)',
'/users/:id((?=a)a)',
'/users/:id(\\1)',
])('rejects invalid or unsafe pattern %s', (pattern) => {
expect(() => compilePattern(pattern)).toThrow(/invalid route pattern|unsafe route constraint/);
});
});
```
Also cover numeric, UUID-like, slug, and bounded-quantifier examples; a constraint must match the complete decoded segment.
**Step 2: Run the focused test and confirm RED**
Run:
```bash
npx vitest run test/router.test.ts
```
Expected: FAIL because `compilePattern` and constrained matching do not exist.
**Step 3: Implement the compiled representation**
In `src/http/router.ts`, add:
```typescript
type CompiledSegment =
| { kind: 'static'; value: string }
| { kind: 'param'; name: string; constraint?: RegExp }
| { kind: 'catchAll'; name: string };
export interface CompiledPattern {
source: string;
normalized: string;
shape: string;
segments: CompiledSegment[];
kinds: number[]; // static=3, constrained=2, param=1; catch-all stored separately
catchAll: boolean;
}
```
Implement `compilePattern(pattern)`, `matchCompiled(compiled, pathSegments)`, and a string-keyed cache used by `matchPattern`. Parse `:name(expr)` only when the closing `)` ends the segment. Anchor accepted constraints as `^(?:${expr})$`.
Implement `assertSafeConstraint` as a small whitelist parser. Permit literals, character classes, `\\d`/`\\w`/`\\s` classes, escaped literals, and simple quantifiers. Reject expression length above 128, groups, alternation, anchors, lookarounds, backreferences, nested quantifiers, and adjacent unbounded quantified atoms without a separating literal. Do not add a runtime dependency.
Build `shape` from segment kinds and constraint source so `:id` and `:name` have the same effective shape.
**Step 4: Run tests and confirm GREEN**
Run:
```bash
npx vitest run test/router.test.ts
npm run typecheck
```
Expected: all router tests pass and TypeScript reports no errors.
**Step 5: Commit**
```bash
git add src/http/router.ts src/http/types.ts test/router.test.ts
git commit -s -m "feat(router): compile safe constrained patterns"
```
### Task 2: Validate request paths and route-table ambiguity
**Skills:** `@superpowers:test-driven-development`, `@security-review`
**Files:**
- Modify: `src/http/router.ts`
- Modify: `src/app/index.ts`
- Modify: `src/app/types.ts`
- Test: `test/router.test.ts`
- Test: `test/app.test.ts`
**Step 1: Write failing path-policy tests**
Add router tests for the approved normalization:
```typescript
expect(normalizeRequestPath('/users')).toBe('/users');
expect(normalizeRequestPath('/users/')).toBe('/users');
expect(normalizeRequestPath('/')).toBe('/');
expect(() => normalizeRequestPath('/users//42')).toThrow(/repeated slash/);
expect(() => normalizeRequestPath('/users/%E0%A4%A')).toThrow(/malformed path encoding/);
```
Add app-construction tests proving that identical routes and routes that differ only by parameter names fail before serving:
```typescript
expect(() => createApp({ modules: [DuplicateRouteModule] })).toThrow(/ambiguous route.*GET/);
```
Cover the same path under different methods as valid.
**Step 2: Run focused tests and confirm RED**
```bash
npx vitest run test/router.test.ts test/app.test.ts
```
Expected: FAIL because normalization and ambiguity checks are absent.
**Step 3: Implement request normalization**
Add `InvalidRequestPathError` and `normalizeRequestPath(path)` to `src/http/router.ts`. Strip exactly one trailing slash except at root, reject `//`, and call `decodeURIComponent` on every raw segment only to validate encoding. Matching still compares static segments according to the existing encoded-path contract and decodes captured values once.
**Step 4: Implement route-table validation**
Store a `compiled` pattern on each internal `RoutePlan`/`RouteDef`, or expose a shared cache accessor if that avoids duplicating state. During `collectControllers`, compile each joined pattern and compare the candidate's method plus `shape` with existing route plans. Throw an error that includes method, pattern, controller/handler, and conflicting declaration.
Apply the same validation after remote mesh routes join. A remote conflict must name both mesh owner URLs rather than silently selecting registration order.
**Step 5: Run focused and mesh tests**
```bash
npx vitest run test/router.test.ts test/app.test.ts test/mesh/fetch-boot.test.ts test/mesh/integration.test.ts
npm run typecheck
```
Expected: all selected tests pass.
**Step 6: Commit**
```bash
git add src/http/router.ts src/app/index.ts src/app/types.ts test/router.test.ts test/app.test.ts
git commit -s -m "fix(router): reject invalid and ambiguous paths"
```
### Task 3: Add HEAD and OPTIONS to the public decorator API
**Skills:** `@superpowers:test-driven-development`
**Files:**
- Modify: `src/metadata.ts`
- Modify: `src/index.ts`
- Modify: `src/signals.ts`
- Test: `test/metadata.test.ts`
- Test: `test/smoke.test.ts`
**Step 1: Write failing decorator tests**
```typescript
class Methods {
@Head('/resource') head() {}
@Options('/resource') options() {}
}
expect(getRoutes(Methods).map(({ method }) => method)).toEqual(['HEAD', 'OPTIONS']);
```
Add a public-barrel smoke test that imports `Head`, `Options`, and `HttpMethod` from `src/index.ts`.
**Step 2: Run tests and confirm RED**
```bash
npx vitest run test/metadata.test.ts test/smoke.test.ts
```
Expected: FAIL because the exports do not exist.
**Step 3: Implement decorators and messages**
Extend `HttpMethod`:
```typescript
export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
```
Create buffered `Head` and `Options` decorators through `routeDecorator`, export them from `src/index.ts`, and update `TransportMismatchError`'s buffered-method message. Keep `@Html` restricted to GET/POST and update its rejection text to include HEAD/OPTIONS.
**Step 4: Run tests and typecheck**
```bash
npx vitest run test/metadata.test.ts test/smoke.test.ts test/transport-enforcement.test.ts test/views-html.test.ts
npm run typecheck
```
Expected: all pass.
**Step 5: Commit**
```bash
git add src/metadata.ts src/index.ts src/signals.ts test/metadata.test.ts test/smoke.test.ts
git commit -s -m "feat(router): expose HEAD and OPTIONS decorators"
```
### Task 4: Implement runtime-neutral HEAD, OPTIONS, and path errors
**Skills:** `@superpowers:test-driven-development`, `@security-review`
**Files:**
- Modify: `src/http/router.ts`
- Modify: `src/http/core.ts`
- Modify: `src/http/web.ts`
- Modify: `src/http/server.ts`
- Test: `test/router.test.ts`
- Test: `test/http.test.ts`
- Test: `test/fetch.test.ts`
- Test: `test/parity.test.ts`
- Test: `test/transport-security.test.ts`
**Step 1: Write failing method-semantics tests**
Cover these cases in both Node and `app.fetch`:
```typescript
// Explicit HEAD wins.
// Otherwise buffered GET runs once, retains status/headers, and emits an empty body.
// Streaming GET does not become implicit HEAD.
// Explicit OPTIONS wins.
// Automatic OPTIONS returns 204 and deterministic Allow.
// GET implies HEAD; every existing path implies OPTIONS.
// CORS preflight still runs before explicit/automatic OPTIONS.
// Double slash and malformed encoding return 400 with security headers.
```
Use a canonical expected header such as `GET, HEAD, POST, OPTIONS`.
**Step 2: Run focused tests and confirm RED**
```bash
npx vitest run test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
```
Expected: new assertions fail under the current 405 behavior.
**Step 3: Implement method resolution**
In `src/http/router.ts`, add a stable method order and helpers:
```typescript
export interface ResolvedRoute extends MatchedRoute {
implicitHead: boolean;
}
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined;
export function allowedMethods(routes: RouteDef[], path: string): HttpMethod[];
```
`resolveRoute` tries explicit method first. For HEAD only, it falls back to a matching buffered GET. `allowedMethods` deduplicates explicit methods, adds HEAD for buffered GET, adds OPTIONS for every existing path, and sorts canonically.
**Step 4: Implement core outcomes**
At the start of `handle`, normalize the path and render `InvalidRequestPathError` as `400`. Preserve the existing CORS-preflight branch. Resolve explicit OPTIONS normally; otherwise return buffered `204` with `allow` and empty body. For an implicit or explicit HEAD route, run the normal pipeline but replace a buffered result body with `''`. Reject a stream outcome for HEAD as a transport mismatch rather than opening a stream.
**Step 5: Align body acquisition in both adapters**
Replace early `matchRoute` calls in `src/http/web.ts` and `src/http/server.ts` with the same normalization and resolution helper used by `handle`. If path validation fails before body acquisition, render `400` through `onError` with injected security/CORS headers. Never read a request body for automatic OPTIONS or an invalid path.
**Step 6: Run focused tests and confirm GREEN**
```bash
npx vitest run test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
npm run typecheck
```
Expected: all selected tests pass with Node/Fetch parity.
**Step 7: Commit**
```bash
git add src/http/router.ts src/http/core.ts src/http/web.ts src/http/server.ts test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
git commit -s -m "feat(http): complete HEAD and OPTIONS semantics"
```
### Task 5: Project constraints into OpenAPI and introspection
**Skills:** `@superpowers:test-driven-development`
**Files:**
- Modify: `src/openapi.ts`
- Modify: `src/app/introspect.ts`
- Test: `test/openapi.test.ts`
- Test: `test/graph-viz.test.ts`
**Step 1: Write failing OpenAPI tests**
Add `@Get('/:id(\\d+)')`, explicit `@Head`, and explicit `@Options` routes to the fixture. Assert:
```typescript
expect(doc.paths['/api/users/{id}']).toBeDefined();
expect((doc.paths['/api/users/{id}'].get as any).parameters).toContainEqual(
expect.objectContaining({ name: 'id', schema: { type: 'string', pattern: '\\d+' } }),
);
expect(doc.paths['/api/users/{id}'].head).toBeDefined();
expect(doc.paths['/api/users/{id}'].options).toBeDefined();
```
Assert that automatic HEAD/OPTIONS operations are not invented.
**Step 2: Run tests and confirm RED**
```bash
npx vitest run test/openapi.test.ts test/graph-viz.test.ts
```
Expected: constrained template parsing or schema assertions fail.
**Step 3: Implement projection**
Reuse the route compiler's parsed segment data instead of parsing the syntax a second way. Convert params and catch-alls to `{name}`. Add `schema.pattern` only for constrained params. Ensure `inspect`, `explain`, Mermaid, and DOT retain the human-readable original pattern.
**Step 4: Run tests and typecheck**
```bash
npx vitest run test/openapi.test.ts test/graph-viz.test.ts test/app.test.ts
npm run typecheck
```
Expected: all pass.
**Step 5: Commit**
```bash
git add src/openapi.ts src/app/introspect.ts test/openapi.test.ts test/graph-viz.test.ts
git commit -s -m "feat(openapi): document constrained route params"
```
### Task 6: Remove root and website dependency advisories
**Skills:** `@security-review`
**Files:**
- Modify: `package.json`
- Modify: `package-lock.json`
- Modify: `website/package.json`
- Modify: `website/package-lock.json`
- Test: `bench/servers/nestjs-express.ts`
- Test: `bench/servers/nestjs-fastify.ts`
**Step 1: Record the failing audit baseline**
```bash
npm audit
npm --prefix website audit
npm audit --omit=dev
```
Expected: root full audit reports 17 advisories, website reports 3, runtime-only root reports 0.
**Step 2: Apply supported direct updates**
Update root dependencies with explicit commands so the manifests and lockfile agree:
```bash
npm install --save-dev vitest@^3.2.6 \
@nestjs/common@^11.1.28 @nestjs/core@^11.1.28 \
@nestjs/platform-express@^11.1.28 @nestjs/platform-fastify@^11.1.28 \
fastify@^5.11.0 miniflare@^4.20260730.0 \
@eslint/js@^9.39.5 eslint@^9.39.5 prettier@^3.9.6 \
tsx@^4.23.5 typescript-eslint@^8.65.0 ws@^8.21.1
npm --prefix website install astro@^7.1.6 @astrojs/starlight@^0.41.6
```
Do not bump TypeScript, ESLint, or GraphQL across their next major versions.
**Step 3: Add narrow overrides only for unresolved vulnerable transitives**
Run `npm audit --json` and inspect the exact remaining paths. Add the smallest overrides justified by that output, initially:
```json
{
"overrides": {
"@nestjs/platform-fastify": {
"find-my-way": "9.7.0"
},
"autocannon": {
"hyperid": {
"uuid": "11.1.1"
}
}
}
}
```
If npm rejects nested override syntax, express the same ownership with `$` references or the supported nested-object form for the installed npm version. Never add a global override when a package-scoped one works.
**Step 4: Prove compatibility before accepting overrides**
```bash
npm run typecheck
npm test
npm run bench
```
Expected: tests pass; Express, Fastify, Nest Express, and Nest Fastify scenarios start and complete; Autocannon produces all scenario rows. If the UUID override breaks Autocannon, revert only that override and replace/isolate Autocannon in a follow-up commit within this task until the full audit is clean.
**Step 5: Verify clean audits**
```bash
npm audit
npm audit --omit=dev
npm --prefix website audit
```
Expected: all three commands exit 0 with zero vulnerabilities.
**Step 6: Commit**
```bash
git add package.json package-lock.json website/package.json website/package-lock.json
git commit -s -m "chore(deps): remediate security advisories"
```
### Task 7: Add security and documentation gates to CI
**Skills:** `@security-review`
**Files:**
- Modify: `.github/workflows/ci.yml`
- Modify: `.github/workflows/release.yml`
**Step 1: Define the expected gates**
The CI job must install root and website lockfiles, audit both, build docs, and preserve the existing Node 18 package gate. The GitHub-only release job must audit the root tree immediately after `npm ci` and before `npm publish`.
**Step 2: Update CI**
Add these steps after the root `npm ci`:
```yaml
- run: npm audit
- run: npm ci --prefix website
- run: npm audit --prefix website
- run: npm run docs:build
```
Keep lint, format, complexity, typecheck, test, and build unchanged.
**Step 3: Update the GitHub release gate**
Add `npm audit` after `npm ci` in `.github/workflows/release.yml`. Do not change the tag trigger, Gitea server guard, Node 22 OIDC setup, dist-tag derivation, or `npm publish` command.
Do not modify `stage.yml` or `promote.yml`; their verified GitFlow responsibilities remain:
- Gitea `main` → Verdaccio `stg`;
- Gitea `main` and `v*` tags → GitHub;
- GitHub `v*` → npm OIDC release.
**Step 4: Validate workflow syntax and diff**
```bash
npx prettier --check .github/workflows/ci.yml .github/workflows/release.yml
git diff --check
```
If Prettier does not parse the workflow format in this repo, inspect with `ruby -e "require 'yaml'; YAML.load_file(ARGV[0])" <file>` and record that command instead.
**Step 5: Commit**
```bash
git add .github/workflows/ci.yml .github/workflows/release.yml
git commit -s -m "ci: gate releases on clean dependency audits"
```
### Task 8: Audit and align the complete website documentation
**Skills:** `@writing-clearly-and-concisely`
**Files:**
- Review: every page under `website/src/content/docs/`
- Modify: `website/src/content/docs/guides/routing.md`
- Modify: `website/src/content/docs/reference/decorators.md`
- Modify: `website/src/content/docs/guides/openapi.md`
- Modify: any other website page whose API, behavior, example, or cross-link has drifted from the code
- Create: `website/src/content/docs/404.md`
**Step 1: Build a code-backed website documentation inventory**
Compare every website page with the current public exports in `src/index.ts`, app options and methods in `src/app/types.ts`, decorator metadata in `src/metadata.ts`, routing behavior in `src/http/router.ts`, and the executable tests. Search the whole documentation tree for stale method lists, obsolete limitations, old error semantics, old beta/version examples, broken internal links, and examples that no longer typecheck conceptually.
Do not change a claim from memory. Each correction must be supported by code or a passing test.
**Step 2: Update routing documentation from the verified behavior**
Document:
- `@Head` and `@Options`;
- explicit-route priority and automatic fallbacks;
- canonical `Allow` behavior;
- `/path` equals `/path/`;
- `//` and malformed encoding return `400`;
- catch-all must be final;
- `:id(\\d+)`, whole-segment matching, precedence, and the safe-subset restriction;
- the matcher remains linear and a radix tree remains deferred.
Remove the current statement that bare OPTIONS returns 405.
**Step 3: Align cross-cutting website references**
At minimum, verify and correct:
- every buffered-method list to include or intentionally exclude `HEAD`/`OPTIONS` according to the actual API;
- `405`, automatic `OPTIONS`, implicit `HEAD`, CORS-preflight, malformed-path, and security-header descriptions;
- OpenAPI behavior: explicit HEAD/OPTIONS appear as operations, constrained params produce `schema.pattern`, and automatic fallbacks remain absent;
- mesh route-conflict wording after effective-pattern normalization;
- examples and links between routing, decorators, errors, HTML, streaming, security, OpenAPI, and `createApp` reference pages;
- navigation/frontmatter descriptions that still advertise the old router surface.
Keep intentional historical or roadmap statements only when they remain true.
**Step 4: Fix the Starlight 404 warning**
Create the missing `404.md` entry with valid Starlight frontmatter and concise navigation back to the docs index. Run `npm run docs:build` and confirm the line `Entry docs → 404 was not found` disappears.
**Step 5: Validate the whole website documentation tree**
```bash
npm run docs:build
npm --prefix website audit
rg -n 'Not built|bare `OPTIONS`|returns `405`|@Get.*@Post.*@Put.*@Patch.*@Delete' website/src/content/docs
rg -n '\]\(/docs/' website/src/content/docs
git diff --check
```
Expected: all 23+ pages build without the missing-404 warning, the website audit remains clean, obsolete router claims are gone, and every changed claim has a code/test source.
**Step 6: Commit**
```bash
git add website/src/content/docs
git commit -s -m "docs(website): align guides with router behavior"
```
### Task 9: Align package documentation and prepare the August beta
**Skills:** `@writing-clearly-and-concisely`
**Files:**
- Modify: `README.md`
- Modify: `CHANGELOG.md`
- Modify: `src/index.ts`
- Modify: `package.json`
- Modify: `package-lock.json`
**Step 1: Align the package-facing documentation**
Update README routing, roadmap, method, security, and beta-status claims from the same verified behavior documented in the website. Keep README concise and link to the complete website guides rather than duplicating their full reference material.
**Step 2: Bump the beta version consistently**
Run:
```bash
npm version 26.8.0-beta.0 --no-git-tag-version
```
Update `src/index.ts`'s `VERSION` constant and add a `26.8.0-beta.0` CHANGELOG entry covering routes, security remediation, docs, and compatibility. Confirm README's CalVer examples remain accurate.
**Step 3: Verify docs and version consistency**
```bash
npm run docs:build
node -e "const p=require('./package.json'); const l=require('./package-lock.json'); if (p.version !== l.version || p.version !== l.packages[''].version) process.exit(1)"
rg -n '26\.7\.0-beta\.0|Not built|bare `OPTIONS`' README.md CHANGELOG.md src website/src/content/docs
git diff --check
```
Expected: package versions agree, website docs still build, and any old beta string is retained only in historical release examples.
**Step 4: Commit**
```bash
git add README.md CHANGELOG.md src/index.ts package.json package-lock.json
git commit -s -m "docs: document router completeness for beta"
```
### Task 10: Run the complete release-candidate verification
**Skills:** `@superpowers:verification-before-completion`, `@security-review`
**Files:**
- Modify only if a verification failure reveals an in-scope defect.
**Step 1: Run static and Node gates**
```bash
npm run lint
npm run format:check
npm run complexity:check
npm run typecheck
npm run typecheck:bench
npm test
npm run build
```
Expected: every command exits 0. Record the existing lint-warning count separately; introduce no new warnings.
**Step 2: Run multi-runtime gates**
```bash
npm run test:deno
npm run test:bun
npm run test:edge
```
Expected: every installed runtime suite exits 0. If a runtime is unavailable, report the exact missing command; do not claim that suite passed.
**Step 3: Run security, docs, and benchmark gates**
```bash
npm audit
npm audit --omit=dev
npm --prefix website audit
npm run docs:build
npm run bench
```
Expected: zero advisories; docs build without warning; all benchmark scenarios complete.
**Step 4: Inspect the publish artifact without publishing**
```bash
npm pack --dry-run
```
Expected: package contains `dist`, assets, README, CHANGELOG, and LICENSE; version is `26.8.0-beta.0`; no docs worktree, tests, secrets, or local environment files appear.
**Step 5: Review branch and workflow boundaries**
```bash
git status --short --branch
git log --oneline --decorate develop..HEAD
git diff --check develop...HEAD
git diff --stat develop...HEAD
```
Expected: clean `feat/router-security-beta`; all commits carry `Signed-off-by`; no tag, registry publication, `main` merge, or workflow secret change occurred.
**Step 6: Commit any verification-only repair**
Only if Step 1–5 exposed an in-scope defect:
```bash
git add <exact repaired files>
git commit -s -m "fix: address beta verification findings"
```
Re-run the failed gate and the complete related suite after any repair.
-522
View File
@@ -1,522 +0,0 @@
# green-tea — Quickstart
A type-safe HTTP framework where the request/boot pipeline is an explicit **dependency
graph**. You declare what you need; the framework computes the order, validates it at boot,
and can extend the graph over time (streams) and across machines (mesh).
See [architecture.md](./architecture.md) for the mental map.
## Install
```bash
npm install @green-tea/core reflect-metadata
# ws is an OPTIONAL peer dependency — only needed for WebSocket / mesh on Node:
npm install ws # optional
```
`tsconfig.json` must enable decorator metadata:
```jsonc
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"target": "es2017",
"module": "commonjs"
}
}
```
Import `reflect-metadata` once at your entrypoint.
## 1. A route with dependency injection
A **provider** is an app-scope singleton. A **step** runs per request and transforms the
context. A handler's **argument decorators are its dependency declaration** — ask for what
you want, in any order. If you `@needs` a token nothing produces, you get a **boot error**,
not an `undefined` at runtime.
```typescript
import 'reflect-metadata';
import { createApp, Provider, Step, Route, Get, Module, Unauthorized, needs, param } from '@green-tea/core';
@Provider({ provides: 'db' })
class Database {
provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; }
}
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx: any) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline
return { user }; // return = continue, merge into ctx
}
}
@Route('/users')
class UserController {
@Get('/:id')
getUser(@needs('user') user: any, @param('id') id: string) {
return { requested: id, you: user }; // auto-serialized as JSON
}
}
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
const app = createApp({ modules: [ApiModule] });
await app.listen(3000);
// GET /api/users/9 (header x-token) → { "requested": "9", "you": { "id": "...", "name": "Diego" } }
await app.close(); // graceful shutdown: drains in-flight requests, closes streams + mesh links
```
> **Per-route execution (important).** Each route runs **only the providers/steps in the transitive
> closure of its handler's `@needs`** — nothing else. A route that doesn't `@needs('user')` does **not**
> run the `Authenticate` step. This means a cross-cutting *enforcement* step (e.g. auth that throws 401)
> only protects routes that actually `@needs` its token. To run something on **every** route regardless
> of needs (logging, audit, a global guard), add it as a **plugin step** via `scope.add({ ..., provides: [] })` —
> steps that produce nothing run unconditionally. Don't rely on a token-providing step to guard routes
> that don't declare it.
### Argument decorators
| Decorator | Reads from | Adds a graph dependency? |
|---|---|---|
| `@needs('user')` | a value produced by a provider/step | **yes** (boot-validated) |
| `@ctx()` | the whole accumulated context | no |
| `@param('id')` | route params | no |
| `@query('q')` | parsed query string | no |
| `@body()` | parsed JSON body | no |
| `@headers('x')` | request headers | no |
| `@inbound()` | the incoming WS message channel | no (WS only) |
| `@abort()` | an `AbortSignal` that fires on disconnect | no (stream/WS) |
Each envelope decorator has three forms: `@query()` (whole object), `@query('q')` (one key),
`@query(['q','date'])` (subset).
## 2. Compile-time guarantee with `flow`
The decorator layer validates the graph at boot. The functional core `flow` validates it in
the **type checker**:
```typescript
import { flow } from '@green-tea/core';
const pipeline = flow()
.step('db', () => ({ find: (id: string) => id }))
.step('user', (ctx) => ctx.db.find('u1')); // referencing a missing 'db' would not compile
```
## 3. Streaming — SSE
Return an `AsyncIterable` and the pipeline streams it (the transformer is bypassed; the
transport frames it, handles backpressure, and cleans up on disconnect).
```typescript
import { Route, Sse } from '@green-tea/core';
@Route('/feed')
class FeedController {
@Sse('/ticks')
ticks() {
return (async function* () {
for (let n = 1; n <= 3; n++) yield { tick: n };
})();
}
}
// GET /feed/ticks (Accept: text/event-stream)
// data: {"tick":1}
// data: {"tick":2}
// data: {"tick":3}
```
`@Stream(path)` negotiates the transport by header (`Accept: text/event-stream` → SSE,
`Upgrade: websocket` → WS, else ndjson chunked).
## 4. Streaming — WebSocket duplex
A WS handler receives the **inbound** channel and returns the **outbound** channel — a step
that consumes one channel and produces another.
```typescript
import { Route, Ws, inbound, channel } from '@green-tea/core';
@Route('/chat')
class ChatController {
@Ws('/echo')
echo(@inbound() incoming: AsyncIterable<string>) {
const out = channel<string>();
(async () => {
for await (const msg of incoming) out.push(`echo: ${msg}`);
out.close();
})();
return out;
}
}
```
`channel<T>()` is a multicast `AsyncIterable` with `push` / `close` / `fail` and an optional
bounded buffer (`channel({ buffer: 100 })`, drop-oldest).
## 5. Mesh — distributed dependency injection
A **teacup** can depend on a token that physically lives on a **teapot**. Exports are
opt-in (`export: true`) and the control channel is gated by a shared secret.
> ⚠️ **mesh is alpha** — its API and wire protocol may change. It's gated behind `experimental: true`;
> `createApp` throws if you pass `mesh` without it. Don't ship it to production yet.
**Node A — teapot (exposes `config`, `auth`, and a route):**
```typescript
@Provider({ provides: 'config', export: true })
class Config { provide() { return { config: { region: 'mx', tier: 'pro' } }; } }
@Step({ provides: 'auth', needs: [], export: true })
class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } }
@Route('/svc')
class Svc { @Get('/ping', { export: true }) ping() { return { pong: true }; } }
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [Svc] })
class TeapotModule {}
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'shh' } });
await teapot.listen(3002);
```
**Node B — teacup (uses `config` + `auth` with no local providers):**
```typescript
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth }; // both resolved by RPC to the teapot
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] },
});
await teacup.listen(3003);
// GET B:3003/api/local/who (x-token: abc)
// → { "config": { "region": "mx", "tier": "pro" }, "auth": { "token": "abc" } }
```
`@needs('config' | 'auth')` validates at boot because the teapot announced them in its
manifest on connect. A provider export is app-scope (resolved once, cached); a step export is
request-scope (RPC per request, carrying the request envelope).
> Skeleton limitations (by design): no discovery, load-balancing, or failover yet; app-scope
> remote values are not reconciled on reconnect; the request envelope omits `req.url`.
## 6. Plugins & observability
```typescript
const logger = (api: any) => {
api.bus.on('request:step:enter', (p: any) => console.log(`→ ${p.name}`));
api.bus.on('stream:open', (p: any) => console.log(`stream open ${p.name}`));
api.bus.on('mesh:rpc:error', (p: any) => console.error('mesh rpc failed', p.error));
};
const app = createApp({ modules: [ApiModule], plugins: [logger] });
```
Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`,
`mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
## 7. Transport security
Four `createApp` options cover TLS, proxying, CORS, and response headers.
### TLS (native https/wss)
```typescript
import { readFileSync } from 'fs';
const app = createApp({
modules: [App],
tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
});
```
When `tls` is set the server serves https, and WebSocket upgrades become wss on the same
port — no other changes.
### `trustProxy`
```typescript
const app = createApp({ modules: [App], trustProxy: true });
```
Behind a reverse proxy, reads `X-Forwarded-Proto` / `X-Forwarded-For` to populate
`ctx.protocol` (`'http' | 'https'`) and `ctx.ip` (read via `@ctx()`). Off by default —
forwarded headers are ignored (and spoofable) until you opt in. It trusts the immediate hop
unconditionally; there's no CIDR allowlist yet.
### CORS
Off unless `origins` is set.
```typescript
const app = createApp({
modules: [App],
cors: { origins: 'https://app.example.com', credentials: true },
});
```
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
request (with `Access-Control-Request-Method`) is auto-answered with 204.
- With `credentials: true`, the server never sends `Access-Control-Allow-Origin: *` — it
echoes the concrete allowed origin (or blocks the request).
- **Security warning:** `origins: '*'` together with `credentials: true` reflects *any*
origin with credentials attached — the classic reflect-any foot-gun. Only combine them if
you truly intend an open credentialed API; prefer an explicit allowlist.
### `security` (headers, ON by default)
Applied to every HTTP response. Disable everything with `security: false`, or override
individual headers with an options object.
| Header | Default |
|---|---|
| `X-Content-Type-Options` | `nosniff` |
| `X-Frame-Options` | `SAMEORIGIN` |
| `Referrer-Policy` | `no-referrer` |
| `X-DNS-Prefetch-Control` | `off` |
| `Strict-Transport-Security` | `max-age=15552000` (180d) — **only when the connection is secure** (native TLS, or `trustProxy` + `X-Forwarded-Proto: https`); no `includeSubDomains`/`preload` |
| `Content-Security-Policy` | not set — pass `security: { csp: "..." }` |
```typescript
const app = createApp({ modules: [App], security: { csp: "default-src 'self'" } });
```
**Scope caveat:** `security` and `cors` headers apply to HTTP responses; they do not apply
to the WebSocket handshake (101/upgrade) response.
### Defaults
| Option | Default |
|---|---|
| `tls` | off (plain http/ws) |
| `trustProxy` | off |
| `cors` | off (same-origin only) |
| `security` | ON (HSTS only when the connection is secure) |
## 8. File uploads / multipart
> Multipart parsing uses the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency — install it with `npm i busboy`. A `multipart/form-data` request to a server without busboy installed returns `501`. (JSON and urlencoded need nothing extra.)
A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }`
instead of a plain object:
```typescript
import { Route, Post, body } from '@green-tea/core';
import type { MultipartBody } from '@green-tea/core';
@Route('/profile')
class ProfileController {
@Post('/avatar')
upload(@body() form: MultipartBody) {
const name = form.fields.name; // string | string[]
const avatar = form.files.avatar; // UploadedFile | UploadedFile[]
return { name, size: Array.isArray(avatar) ? undefined : avatar?.size };
}
}
```
`UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered
in memory, no temp files.
> **Access note (asymmetry).** For multipart, `@body('title')` returns `undefined` — the value
> lives at `body.fields.title`, not `body.title`, unlike JSON/urlencoded where `@body('title')`
> picks the value directly. Use `@body()` and read `.fields`/`.files`, or key into the envelope
> itself with `@body('fields')` / `@body('files')`.
### Repeated fields — `bodyDuplicates`
By default, a repeated field name keeps the **last** value (`'last'`, matching urlencoded).
Set `bodyDuplicates: 'array'` on `createApp` to accumulate repeats into a `string[]` instead —
this applies to **both** urlencoded and multipart text fields:
```typescript
const app = createApp({ modules: [ApiModule], bodyDuplicates: 'array' });
```
Files under a repeated field name always become an array (`UploadedFile[]`), regardless of
`bodyDuplicates`.
### Per-endpoint override
```typescript
@Post('/upload', { duplicates: 'array' })
upload(@body() form: MultipartBody) { /* ... */ }
```
Precedence: route `duplicates` → app `bodyDuplicates` → `'last'`.
### Limits
Uploaded files are held in memory, so they're bounded by the same `maxBodyBytes` limit as any
other request body (over the limit → 413). `maxParts` (default `1000`) caps the number of
multipart parts per request:
```typescript
const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } });
```
A malformed multipart body (bad boundary, missing headers, truncated part) → 400.
## 9. Validation
`@body`, `@query`, `@headers`, and `@param` accept an optional **Standard Schema**
(the [`~standard` interface](https://standardschema.dev) shared by zod, valibot, arktype,
and others). green-tea's core has **zero runtime dependency** on any of them — bring
whichever validator you already use:
```typescript
import { z } from 'zod';
import { Route, Post, body } from '@green-tea/core';
const CreateUser = z.object({ email: z.string().email() });
@Route('/users')
class UserController {
@Post('/')
create(@body(CreateUser) user: { email: string }) {
return { created: user.email };
}
}
```
The value the handler receives is the schema's **parsed/coerced output**, not the raw
input — `ctx.body` (via `@ctx()` or a `@needs`-fed step) stays exactly what the transport
parsed. Query strings are always strings on the wire, so a schema is often the coercion
point:
```typescript
const ListQuery = z.object({ page: z.coerce.number() });
@Get('/list')
list(@query(ListQuery) q: { page: number }) {
return { page: q.page, isNum: typeof q.page === 'number' }; // GET /list?page=2 → true
}
```
> **Access shape (asymmetry).** `@param('id', Schema)` takes the key in slot 1 and the schema
> in slot 2 — `@param` always needs a name to say which route param it binds. `@body(Schema)`,
> `@query(Schema)`, and `@headers(Schema)` take the schema as their only argument, validating
> the whole parsed object (all of `body`/`query`/`headers`).
A failing schema short-circuits the request with **422**:
```json
{ "error": "Validation failed", "source": "body", "issues": [{ "path": "email", "message": "Invalid email" }] }
```
`source` is which envelope failed (`'body' | 'query' | 'params' | 'headers'`); `issues` is
the schema's issues flattened to `{ path, message }` (`path` is dot-joined).
**Caveats:**
- **Fail-fast.** Arguments validate in order; the **first** failing one throws — later args in
the same handler are not checked in that request.
- **Steps see raw input.** Only the resolved handler argument is coerced/validated; a `@Step`
reading the same data via `ctx.body`/`ctx.query`/etc. always sees the untouched value.
- **A throwing schema is a 500, not a 422.** The Standard Schema contract says `validate()`
returns `{ issues }` on failure — it isn't supposed to throw. If it does anyway, that
propagates as an uncaught error (→ 500), since it signals a bug in the schema, not user input.
- **Async schemas are awaited** — `validate()` returning a `Promise` works transparently.
**Not covered yet:** response/output validation, validating a `@Step`'s own inputs, and
mesh remote-route validation are all out of scope for this feature.
## Inspect & test the graph
### Visualize with Mermaid
```typescript
console.log(app.toMermaid()); // flowchart diagram of all nodes and routes
```
Enable a live `GET /__graph__` endpoint (renders HTML with Mermaid, or plain-text with `Accept: text/plain`):
```typescript
const app = createApp({ modules: [ApiModule], devGraph: true });
// GET /__graph__ → HTML viewer
// GET /__graph__ (text/plain) → raw Mermaid source
```
### Explain a route
```typescript
const e = app.explain('/api/users/:id');
// { pattern, method, transport, chain: [{ name, kind, origin, needs, provides }, ...] }
console.log(e.chain.map((n) => `${n.kind}:${n.name}`));
// → ['provider:db', 'step:user', 'handler:getUser']
```
### Override tokens in tests
Swap any provider or step token with a test double at construction time — no monkey-patching:
```typescript
const app = createApp({
modules: [ApiModule],
overrides: {
db: { find: () => ({ id: 'test-user' }) }, // plain object — wrapped as { db: value }
user: () => ({ user: { id: 'stub' } }), // function runner
},
});
```
Overrides replace only the named token's runner; the rest of the graph is untouched.
## Runnable examples
The `example/` directory holds end-to-end apps you can `node`-run and read top to bottom.
### CRUD — methods, query, JSON & urlencoded body
`@Get/@Post/@Put/@Patch/@Delete` over a provider-backed store. Filter via `@query('done')`,
read the payload via `@body()` — the same handler accepts both `application/json` and
`application/x-www-form-urlencoded` (the transport parses each into a plain object). Missing
rows throw `NotFound` (→ 404).
See [`example/crud.ts`](../example/crud.ts).
### Chat — rooms + handshake auth
A `@Step` reads `?token=` and `provides: 'user'`, throwing `Unauthorized` on a missing token —
which closes the socket with code **4401** (`4000 + status`). The `@Ws` handler pumps the
`@inbound()` channel into `rooms.room(name)` and returns that same room as its outbound channel,
so every joined socket multicasts to the others. `rooms` is the built-in shared `Rooms`
primitive (one instance app-wide).
See [`example/chat.ts`](../example/chat.ts).
### GraphQL — query/mutation over POST, subscription over SSE
A schema built programmatically with `graphql` (a dev/example dependency — the core has no
runtime dep on it). `POST /graphql` runs queries and mutations through `graphql()`. The
`mutation` pushes each new message into `rooms.room('messages')`; the `@Sse('/stream')` route
calls `subscribe()` whose source **is** that room, guards the result with `isAsyncIterable`,
and returns it — the framework streams each `ExecutionResult` as an SSE `data:` frame. This is
the tie between GraphQL, green-tea streams, and the `rooms` primitive.
See [`example/graphql.ts`](../example/graphql.ts) — `npm install graphql` first.
## The one rule to remember
```
return a VALUE → buffered response (transformer → JSON)
return an AsyncIterable → stream (SSE / WS)
@needs a remote token → RPC to a teapot (mesh)
```
+1916 -929
View File
File diff suppressed because it is too large. Load diff
+87 -14
View File
@@ -1,8 +1,35 @@
{
"name": "@green-tea/core",
"version": "26.07.0-beta.0",
"description": "Declarative, type-safe HTTP framework. The pipeline is a graph, not a middleware chain.",
"version": "26.8.0-beta.0",
"description": "You declare what each step needs and provides; green-tea computes the execution order, fails at boot if something is missing, and prints the whole pipeline. HTTP, SSE and WebSocket on Node, Deno, Bun and the edge.",
"license": "MIT",
"author": "green-tea contributors",
"repository": {
"type": "git",
"url": "git+https://github.com/Expressive-Tea/green-tea.git"
},
"bugs": {
"url": "https://github.com/Expressive-Tea/green-tea/issues"
},
"homepage": "https://green-tea.expressive-tea.io/docs/",
"keywords": [
"http",
"framework",
"typescript",
"dependency-injection",
"decorators",
"dependency-graph",
"sse",
"websocket",
"streaming",
"node"
],
"engines": {
"node": ">=18"
},
"publishConfig": {
"access": "public"
},
"type": "commonjs",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
@@ -17,10 +44,41 @@
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"./deno": {
"import": {
"types": "./dist/deno.d.mts",
"default": "./dist/deno.mjs"
},
"require": {
"types": "./dist/deno.d.ts",
"default": "./dist/deno.js"
}
},
"./bun": {
"import": {
"types": "./dist/bun.d.mts",
"default": "./dist/bun.mjs"
},
"require": {
"types": "./dist/bun.d.ts",
"default": "./dist/bun.js"
}
},
"./edge": {
"import": {
"types": "./dist/edge.d.mts",
"default": "./dist/edge.mjs"
},
"require": {
"types": "./dist/edge.d.ts",
"default": "./dist/edge.js"
}
}
},
"files": [
"dist",
"assets",
"README.md",
"CHANGELOG.md",
"LICENSE"
@@ -29,6 +87,9 @@
"build": "tsup",
"test": "vitest run",
"test:dev": "vitest",
"test:deno": "deno test --allow-net --allow-read --allow-run --allow-env --no-check test/deno/",
"test:bun": "bun test test/bun/",
"test:edge": "tsx test/edge/run.ts",
"typecheck": "tsc --noEmit -p tsconfig.json",
"typecheck:bench": "tsc --noEmit -p bench/tsconfig.json",
"lint": "eslint src",
@@ -59,12 +120,21 @@
"optional": true
}
},
"overrides": {
"find-my-way": "9.7.0",
"autocannon": {
"hyperid": {
"uuid": "11.1.1"
}
},
"undici": "7.29.0"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@nestjs/common": "^11.1.27",
"@nestjs/core": "^11.1.27",
"@nestjs/platform-express": "^11.1.27",
"@nestjs/platform-fastify": "^11.1.27",
"@eslint/js": "^9.39.5",
"@nestjs/common": "^11.1.28",
"@nestjs/core": "^11.1.28",
"@nestjs/platform-express": "^11.1.28",
"@nestjs/platform-fastify": "^11.1.28",
"@stylistic/eslint-plugin": "^5.10.0",
"@types/autocannon": "^7.12.7",
"@types/busboy": "^1.5.4",
@@ -74,17 +144,20 @@
"autocannon": "^8.0.0",
"busboy": "^1.6.0",
"cognitive-complexity-ts": "^0.8.2",
"eslint": "^9.39.4",
"eslint": "^9.39.5",
"esbuild": "0.27.2",
"express": "^5.2.1",
"fastify": "^5.10.0",
"fastify": "^5.11.0",
"graphql": "^16.9.0",
"prettier": "^3.9.4",
"miniflare": "^4.20260730.0",
"prettier": "^3.9.6",
"rxjs": "^7.8.2",
"tsup": "^8.5.1",
"tsx": "^4.23.0",
"tsx": "^4.23.5",
"typescript": "^5.5.0",
"typescript-eslint": "^8.63.0",
"vitest": "^2.0.0",
"ws": "^8.21.0"
"typescript-eslint": "^8.65.0",
"vite": "^6.4.3",
"vitest": "^3.2.7",
"ws": "^8.21.1"
}
}
+438 -63
View File
@@ -1,24 +1,41 @@
import http from 'http';
import type http from 'http';
import { Bus } from '../bus';
import { Container } from '../container';
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
import { runPipeline, PipelineStep } from '../pipeline';
import { runPipeline, runSteps, PipelineStep } from '../pipeline';
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
import type { HttpOptions } from '../http';
import { buildFetch } from '../http/web';
import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocket } from '../http/ws-core';
import { isAsyncIterable } from '../channel';
import { JsonTransformer } from '../transformers';
import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
import { Ctor, getModuleMeta, getProviderMeta, getStepMeta, getRoutes, getTransformer, joinPath } from '../metadata';
import {
Ctor,
getModuleMeta,
getProviderMeta,
getStepMeta,
getRoutes,
getTransformer,
getHtmlMeta,
joinPath,
type RouteMeta,
type TransformerFn,
} from '../metadata';
import { buildHtmlTransformer, buildStaticResolver, type ViewsContext } from '../views';
import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
import { buildOpenApi, type OpenApiInfo } from '../openapi';
import { connectLink, type Link } from '../mesh/link';
import { Rooms } from '../rooms';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import { buildRemote } from '../mesh/teacup';
import { buildManifest, createMeshControl } from '../mesh/teapot';
import { buildManifest, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot';
import type { MeshControl } from '../http';
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
import { compilePattern } from '../http/router';
export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types';
@@ -37,11 +54,27 @@ interface Registry {
setRunner(name: string, runner: Runner): void;
}
/**
* Memoizes an async step so repeat and concurrent callers share one run. Both boot stages need
* this: `fetch`, `upgrade`, `listen` and `ready` can each be the first to trigger them, and
* re-running would re-splice a mesh or re-run provider factories and their side effects.
*/
function once(run: () => Promise<void>): () => Promise<void> {
let promise: Promise<void> | undefined;
return (): Promise<void> => {
if (!promise) promise = run();
return promise;
};
}
/** Request-time helpers shared by the HTTP, WS and mesh route builders. */
interface PipelineDeps {
providedSeed(plan: RoutePlan): Promise<Record<string, unknown>>;
planSteps(plan: RoutePlan): PipelineStep[];
bus: Bus;
onError?: ErrorRenderer;
}
/**
@@ -55,14 +88,29 @@ export function createApp(opts: {
mesh?: MeshConfig;
limits?: RequestLimits;
devGraph?: boolean;
devOpenapi?: boolean;
overrides?: Record<string, unknown>;
tls?: TlsOptions;
trustProxy?: boolean;
security?: boolean | SecurityOptions;
cors?: CorsOptions;
bodyDuplicates?: 'array' | 'last';
/** Render errors your own way (HTML, custom JSON, …); return a response or undefined to fall back to JSON. */
onError?: ErrorRenderer;
/** Base directory `@Html('file.html')` paths resolve against (default: `process.cwd()`). */
views?: string;
/** Bring-your-own template engine for `@Html(..., { template: true })`; defaults to the built-in `render`. */
viewEngine?: (source: string, data: unknown) => string;
/** Serve a static directory as a GET/HEAD fallback (after declared routes, before 404). `true` → `./public`. */
static?: boolean | string;
/** Opt in to alpha features whose API may still change. Currently gates `mesh`. */
experimental?: boolean;
/**
* Warn at boot when a route's dependency chain resolves to more than this many steps (default 20;
* `false` silences). A design nudge, not a perf limit — deep graphs run fine (cost is linear), but
* 20+ steps on one route usually means a step is doing too much.
*/
warnGraphDepth?: number | false;
}): App {
// mesh is alpha: its API and wire protocol may change. Require an explicit opt-in.
if (opts.mesh && !opts.experimental) {
@@ -78,39 +126,38 @@ export function createApp(opts: {
const degradedProviders: string[] = []; // optional providers that failed to boot (running degraded)
// Collect declarations from modules, then splice in plugin- and built-in-provided nodes.
const registry = collectModules(opts.modules);
const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine };
const registry = collectModules(opts.modules, viewsCtx);
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
mountPlugins(opts.plugins, bus, registry);
provideBuiltins(registry);
// For each route, resolve which providers/steps feed it via topo order.
// MVP: every route depends on every declared step + provider in the app graph.
// For mesh apps, finalize is DEFERRED to listen() so remote scopes can join the graph first.
// For mesh apps, finalize is DEFERRED to the boot gate so remote scopes can join the graph
// first — connecting to teapots is network I/O, so it cannot happen during construction.
let orderedProviders: GraphNode[] = [];
let orderedSteps: GraphNode[] = [];
let booted = false;
let remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = [];
const finalize = (): void => {
({ orderedProviders, orderedSteps } = finalizeGraph(registry));
({ orderedProviders, orderedSteps } = finalizeGraph(registry, opts.warnGraphDepth));
booted = true;
};
if (!opts.mesh) finalize();
const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted);
const graph = (): GraphView => buildGraphView(providerNodes, stepNodes, routePlans, booted);
const explain = (routePath: string): Explain => explainRoute(routePlans, routePath, booted);
const providedSeed = (plan: RoutePlan) => seedProviders(container, plan);
const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan);
const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError };
let meshControl: MeshControl | undefined;
const listen = async (port: number): Promise<http.Server> => {
const deps: PipelineDeps = { providedSeed, planSteps, bus };
// mesh teacup: connect remote teapots, splice their scopes/routes into the graph, then finalize
let remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = [];
// mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize.
// mesh teapot: build the control channel — it captures the *finalized* ordered nodes, so it
// can only be built here, after finalize(), and never at construction time.
const prepareGraph = async (): Promise<void> => {
if (opts.mesh && !booted) {
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry);
remoteRoutes = spliced.remoteRoutes;
@@ -118,25 +165,83 @@ export function createApp(opts: {
finalize();
}
applyOverrides(opts.overrides, registry);
degradedProviders.length = 0;
degradedProviders.push(...(await bootProviders(orderedProviders, { runners, container, providerMeta, bus })));
if (degradedProviders.length) {
console.warn(
`[green-tea] started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`,
);
}
const meshControl = buildMeshControl(opts.mesh, registry, {
meshControl = buildMeshControl(opts.mesh, registry, {
container,
orderedProviders,
orderedSteps,
deps,
deps: pipelineDeps,
});
};
const httpRoutes = buildHttpRoutes(routePlans, remoteRoutes, deps);
if (opts.devGraph) httpRoutes.push(devGraphRoute(graph));
// Memoized separately from the provider boot on purpose: resolving the graph and being ready
// to serve are different things. Introspection needs only the former, and must not run
// provider factories (and open their connections) as a side effect of drawing a diagram.
const ready = once(prepareGraph);
const inspect = (routePath: string): InspectLine[] => inspectRoute(routePlans, routePath, booted);
const graph = (): GraphView => buildGraphView(providerNodes, stepNodes, routePlans, booted);
const explain = (routePath: string): Explain => explainRoute(routePlans, routePath, booted);
const openapi = (info?: OpenApiInfo) =>
buildOpenApi(
routePlans.map((plan) => ({
method: plan.method,
pattern: plan.pattern,
transport: plan.transport,
args: plan.args,
})),
info,
);
// Dev-only introspection routes (opt-in). Shared by BOTH listen() and app.fetch so the
// graph viewer + OpenAPI doc are served on every runtime (Node/Deno/Bun/edge), not Node alone.
const devRoutes = (): RouteDef[] => {
const routes: RouteDef[] = [];
if (opts.devGraph) routes.push(devGraphRoute(graph));
if (opts.devOpenapi) routes.push(openApiRoute(openapi));
return routes;
};
// Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling
// several never double-boots (which would re-run provider factories and their side effects).
const bootApp = makeAppBooter(
registry,
opts.overrides,
() => orderedProviders,
{ runners, container, providerMeta, bus },
degradedProviders,
ready,
);
const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined;
const fetchOpts: HttpOptions = {
limits: opts.limits,
tls: opts.tls,
trustProxy: opts.trustProxy,
security: opts.security ?? true,
cors: opts.cors,
bodyDuplicates: opts.bodyDuplicates,
onError: opts.onError,
static: staticResolver,
};
const fetchFn = buildAppFetch(
routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError },
fetchOpts,
bootApp,
devRoutes,
() => remoteRoutes,
);
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl);
const listen = async (port: number): Promise<http.Server> => {
const deps = pipelineDeps;
// the same gate app.fetch uses: splices remote mesh scopes, finalizes, boots providers,
// and builds the mesh control channel — so Node and Deno/Bun serve an identical graph
await bootApp();
const httpRoutes = [...buildHttpRoutes(routePlans, remoteRoutes, deps), ...devRoutes()];
const wsRoutes = buildWsRoutes(routePlans, deps);
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, {
@@ -147,6 +252,8 @@ export function createApp(opts: {
security: opts.security ?? true,
cors: opts.cors,
bodyDuplicates: opts.bodyDuplicates,
onError: opts.onError,
static: staticResolver,
});
server.on('close', () => closeLinks(meshLinks));
await new Promise<void>((resolve) => server!.listen(port, resolve));
@@ -155,7 +262,13 @@ export function createApp(opts: {
const close = (): Promise<void> =>
new Promise<void>((resolve) => {
// before the server check: a mesh app booted through app.fetch (Deno/Bun, where listen()
// never runs) has links but no server, and would otherwise leak every teapot connection.
// Closing a link rejects its in-flight RPCs via the socket's abort.
closeLinks(meshLinks);
if (!server) return resolve();
server.close(() => resolve()); // waits for in-flight buffered to drain
for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves
server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive
@@ -164,11 +277,15 @@ export function createApp(opts: {
return {
listen,
close,
ready,
fetch: fetchFn,
upgrade: upgradeFn,
inspect,
graph,
toMermaid: () => toMermaid(graph()),
toDOT: () => toDOT(graph()),
explain,
openapi,
degraded: () => [...degradedProviders],
bus,
};
@@ -221,37 +338,92 @@ function collectSteps(steps: Ctor[], origin: string, registry: Registry): void {
}
/** Registers each `@Route` handler on a module's controllers as a {@link RoutePlan}. */
function collectControllers(controllers: Ctor[], mountpoint: string, origin: string, registry: Registry): void {
function collectControllers(
controllers: Ctor[],
mountpoint: string,
origin: string,
registry: Registry,
viewsCtx: ViewsContext,
): void {
for (const ControllerClass of controllers) {
for (const route of getRoutes(ControllerClass)) {
const instance: any = new ControllerClass();
const argSpecs = getArgs(ControllerClass, route.handlerName);
const pattern = joinPath(mountpoint, route.path);
const declaration = `${ControllerClass.name}.${route.handlerName}`;
if (route.export) {
if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`);
registry.exportedRoutes.push({ method: route.method, pattern });
}
registry.routePlans.push({
const transformer = resolveTransformer(ControllerClass, route, pattern, viewsCtx);
const plan: RoutePlan = {
pattern,
method: route.method,
transport: route.transport,
origin,
declaration,
providers: [],
steps: [],
handlerName: route.handlerName,
needs: getHandlerNeeds(argSpecs),
run: async (context: any) => instance[route.handlerName](...(await resolveArgs(argSpecs, context))),
transformer: getTransformer(ControllerClass, route.handlerName) ?? JsonTransformer,
transformer,
duplicates: route.duplicates,
});
maxBodyBytes: route.maxBodyBytes,
maxParts: route.maxParts,
args: argSpecs,
};
assertRouteAvailable(registry.routePlans, plan);
registry.routePlans.push(plan);
}
}
}
/** Rejects local routes that have the same method and effective match shape. */
function assertRouteAvailable(existing: RoutePlan[], candidate: RoutePlan): void {
const compiled = compilePattern(candidate.pattern);
const conflict = existing.find(
(plan) => plan.method === candidate.method && compilePattern(plan.pattern).shape === compiled.shape,
);
if (!conflict) return;
throw new Error(
`ambiguous route ${candidate.method} ${candidate.pattern} at ${candidate.declaration} conflicts with ` +
`${conflict.method} ${conflict.pattern} at ${conflict.declaration}`,
);
}
/**
* Resolves the response transformer for a route: `@Html` metadata builds an HTML transformer (after
* validating placement — buffered GET/POST only, and not combined with `@Transformer`); otherwise the
* user's `@Transformer` wins, falling back to {@link JsonTransformer}.
*/
function resolveTransformer(
ControllerClass: Ctor,
route: RouteMeta,
pattern: string,
viewsCtx: ViewsContext,
): TransformerFn {
const html = getHtmlMeta(ControllerClass, route.handlerName);
const userTransformer = getTransformer(ControllerClass, route.handlerName);
if (!html) return userTransformer ?? JsonTransformer;
if (route.transport !== 'buffer' || (route.method !== 'GET' && route.method !== 'POST')) {
throw new Error(
`@Html on ${route.method} ${pattern} is not allowed — @Html only supports buffered GET/POST routes (not SSE/WS/HEAD/PUT/PATCH/DELETE/OPTIONS)`,
);
}
if (userTransformer) throw new Error(`@Html and @Transformer on ${pattern} conflict — use one`);
return buildHtmlTransformer(html, viewsCtx);
}
/** Reads every module's metadata into a fresh {@link Registry} of graph nodes, runners and exports. */
function collectModules(modules: Ctor[]): Registry {
function collectModules(modules: Ctor[], viewsCtx: ViewsContext): Registry {
const registry = emptyRegistry();
for (const mod of modules) {
@@ -260,7 +432,7 @@ function collectModules(modules: Ctor[]): Registry {
const origin = `module:${mod.name}`;
collectProviders(moduleMeta.providers ?? [], origin, registry);
collectSteps(moduleMeta.steps ?? [], origin, registry);
collectControllers(moduleMeta.controllers ?? [], moduleMeta.mountpoint, origin, registry);
collectControllers(moduleMeta.controllers ?? [], moduleMeta.mountpoint, origin, registry, viewsCtx);
}
return registry;
@@ -290,11 +462,19 @@ function provideBuiltins(registry: Registry): void {
registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms
}
// Boot-time nudge: a route whose need-closure pulls this many steps is almost always a modeling
// smell (a step doing too much, or work that belongs in a provider), not a real dependency depth.
// Cost is linear so it isn't a perf problem — it's a design one. Generous on purpose.
const DEEP_GRAPH_WARN = 20;
/**
* Topo-sorts the graph, slices each route's provider/step closure into its plan, and validates every need.
* @returns The app-scope providers and request-scope steps in execution order.
*/
function finalizeGraph(registry: Registry): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
function finalizeGraph(
registry: Registry,
warnDepth: number | false = DEEP_GRAPH_WARN,
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
const { providerNodes, stepNodes, routePlans } = registry;
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']);
const orderedProviders = ordered.filter((node) => providerNodes.includes(node));
@@ -307,6 +487,17 @@ function finalizeGraph(registry: Registry): { orderedProviders: GraphNode[]; ord
plan.providers = closure.filter((node) => providerNodes.includes(node));
const sliced = new Set<GraphNode>([...closure.filter((node) => stepNodes.includes(node)), ...alwaysSteps]);
plan.steps = ordered.filter((node) => stepNodes.includes(node) && sliced.has(node)); // topo order, deduped
// The route's own dependency depth, excluding always-on observer steps (plugins).
const depth = closure.filter((node) => stepNodes.includes(node)).length;
if (warnDepth !== false && depth > warnDepth) {
console.warn(
`[green-tea] ${plan.method} ${plan.pattern} resolves to ${depth} steps — an unusually deep dependency chain. ` +
`It runs fine (per-request cost is linear), but ${warnDepth}+ steps on one route usually means a step ` +
`is doing too much or the graph wants splitting. If it's intentional, ignore this.`,
);
}
}
assertNeedsSatisfiable(routePlans, providerNodes, stepNodes);
@@ -340,10 +531,17 @@ async function spliceRemoteScopes(
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
const remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = [];
const routeOwners = new Map<string, { url: string; pattern: string }>(); // "METHOD effective-shape" -> owner
try {
for (const teapot of mesh.teapots ?? []) {
const link = await connectLink({ url: teapot.url, secret: teapot.secret, timeoutMs: mesh.timeoutMs, bus });
const link = await connectLink({
url: teapot.url,
secret: teapot.secret,
timeoutMs: mesh.timeoutMs,
heartbeatMs: mesh.heartbeatMs,
bus,
});
meshLinks.push(link);
const { providers, steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`;
@@ -360,6 +558,43 @@ async function spliceRemoteScopes(
}
for (const route of routes) {
const display = `${route.method} ${route.pattern}`;
const key = `${route.method} ${compilePattern(route.pattern).shape}`;
const owner = routeOwners.get(key);
// Fail the boot rather than pick one. Route matching keeps the first of two identical
// patterns, so the loser would be silently dead — and callers could come to depend on
// "first teapot wins", which would make adding balancing later a breaking change.
// Scope tokens already fail this way in setRunner; routes now match.
if (owner) {
throw new Error(
`mesh: ambiguous remote route '${display}' from ${teapot.url} conflicts with ` +
`'${route.method} ${owner.pattern}' from ${owner.url} — ` +
'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' +
'Export it from a single teapot.',
);
}
routeOwners.set(key, { url: teapot.url, pattern: route.pattern });
// Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin
// wins. That precedence is deliberate — your own code beats an imported one, and it is
// how you override a teapot — but silently shadowing an export looks exactly like a
// broken teapot from the outside. Warn and let the developer decide.
if (
registry.routePlans.some(
(plan) =>
plan.method === route.method &&
compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape,
)
) {
console.warn(
`[green-tea] mesh: route '${display}' is exported by teapot ${teapot.url} but also declared locally — ` +
'the local route takes precedence and the remote one will not be reached. ' +
'Remove one if that is not what you meant.',
);
}
remoteRoutes.push({
method: route.method,
pattern: route.pattern,
@@ -429,6 +664,43 @@ async function bootProviders(
return degraded;
}
/**
* Returns a memoized boot function: prepares the graph, applies overrides and boots app-scope
* providers exactly once, however first triggered — `app.fetch`, `app.upgrade` and `listen()` may
* all call it, and the memoization guarantees only the first runs the sequence. This is the single
* place an app becomes ready, which is what lets a mesh app boot on any runtime rather than only
* where `listen()` (a Node http.Server) can be built.
*/
function makeAppBooter(
registry: Registry,
overrides: Record<string, unknown> | undefined,
getOrderedProviders: () => GraphNode[],
deps: {
runners: Map<string, Runner>;
container: Container;
providerMeta: Map<string, { optional: boolean }>;
bus: Bus;
},
degradedProviders: string[],
/** Resolves the graph (splices remote mesh scopes, finalizes). Must precede providers: remote nodes join the topo sort. */
prepareGraph: () => Promise<void>,
): () => Promise<void> {
const runBoot = async (): Promise<void> => {
await prepareGraph();
applyOverrides(overrides, registry);
degradedProviders.length = 0;
degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps)));
if (degradedProviders.length) {
console.warn(
`[green-tea] started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`,
);
}
};
return once(runBoot);
}
/**
* Builds the mesh control gateway that exposes this node's declared exports over the control channel.
* Returns undefined when there is nothing to export; throws if exports are declared without a gating secret.
@@ -447,20 +719,18 @@ function buildMeshControl(
if (!mesh?.secret || !hasExports) return undefined;
const { container, orderedProviders, orderedSteps } = deps;
const { bus, providedSeed, planSteps } = deps.deps;
const { bus, providedSeed, planSteps, onError } = deps.deps;
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
// context is intentionally `any`: providers and steps merge arbitrary keys into it
let context: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers };
const seed: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers };
for (const provider of orderedProviders)
if (container.has(provider.name)) Object.assign(context, await container.resolve(provider.name));
if (container.has(provider.name)) Object.assign(seed, await container.resolve(provider.name));
for (const step of orderedSteps) {
const runner = runners.get(step.name)!;
context = { ...context, ...(await runner(context)) };
}
const steps = orderedSteps.map((step) => ({ name: step.name, origin: step.origin, run: runners.get(step.name)! }));
const context = await runSteps(steps, seed, bus);
return context[name];
};
@@ -480,6 +750,8 @@ function buildMeshControl(
handler: plan.run,
transformer: plan.transformer,
bus,
onError,
transport: plan.transport,
seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
});
@@ -497,7 +769,7 @@ function buildMeshControl(
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] {
const { providedSeed, planSteps, bus } = deps;
const { providedSeed, planSteps, bus, onError } = deps;
const local = routePlans
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
@@ -506,6 +778,8 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
pattern: plan.pattern,
transport: plan.transport,
bodyDuplicates: plan.duplicates,
maxBodyBytes: plan.maxBodyBytes,
maxParts: plan.maxParts,
handler: async (req) => {
const provided = await providedSeed(plan);
return runPipeline({
@@ -513,6 +787,8 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
handler: plan.run,
transformer: plan.transformer,
bus,
onError,
transport: plan.transport,
seed: {
...provided,
req,
@@ -530,6 +806,91 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
return [...local, ...remoteRoutes];
}
/**
* Builds `app.fetch`: a Web-Standards handler over the same route table `listen()` uses, so
* `Deno.serve(app.fetch)` / `Bun.serve({ fetch: app.fetch })` work without ever calling `listen()`.
* The boot is awaited *before* the route table is built: for a mesh app the table is not knowable
* until remote scopes have spliced in, and the boot is what does that. Both are memoized, so this
* costs one flag check per request after the first.
*/
function buildAppFetch(
routePlans: RoutePlan[],
deps: PipelineDeps,
fetchOpts: HttpOptions,
ensureBooted: () => Promise<void>,
devRoutes: () => RouteDef[],
getRemoteRoutes: () => RouteDef[],
): (request: Request) => Promise<Response> {
let handler: ((request: Request) => Promise<Response>) | undefined;
return async (request: Request): Promise<Response> => {
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
if (!handler) {
handler = buildFetch([...buildHttpRoutes(routePlans, getRemoteRoutes(), deps), ...devRoutes()], fetchOpts);
}
return handler(request);
};
}
/**
* Builds `app.upgrade`: the neutral WebSocket entry over the same route table `listen()` uses, so
* Deno/Bun/edge adapters can drive ws connections without ever calling `listen()`. Node keeps its own
* `server.on('upgrade')` path (see `attachWs`) and never calls this.
* Mirrors {@link buildAppFetch}: the boot is awaited before the ws route table is built.
*/
function buildAppUpgrade(
routePlans: RoutePlan[],
deps: PipelineDeps,
streams: Set<() => void>,
ensureBooted: () => Promise<void>,
getMeshControl: () => MeshControl | undefined,
): (request: WsRequest, socket: WsSocket) => Promise<void> {
let wsRoutes: WsRouteDef[] | undefined;
return async (request: WsRequest, socket: WsSocket): Promise<void> => {
// Subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed with no
// subscriber is dropped, so anything the peer sends while providers are still booting would be
// lost. For the mesh control channel that is the `hello` itself — the handshake would hang
// until timeout against a teapot whose providers happened to boot slowly.
const frames = socket.inbound[Symbol.asyncIterator]();
const ready: WsSocket = Object.create(socket, {
inbound: { value: { [Symbol.asyncIterator]: () => frames } },
}) as WsSocket;
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
const path = request.url.split('?')[0];
const meshControl = getMeshControl();
// The reserved mesh path, checked before route matching: this is what lets a teapot export
// its scopes from Deno/Bun, where the Node `server.on('upgrade')` path does not exist.
if (path === MESH_CONTROL_PATH) {
// an explicit refusal, not "no matching ws route": the path is reserved either way, and a
// peer that reached a teapot with nothing exported deserves to be told which it was
if (!meshControl) {
ready.close(1008, 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret');
return;
}
await trackUntil(ready, meshControl.handle(ready), streams);
return;
}
if (!wsRoutes) wsRoutes = buildWsRoutes(routePlans, deps);
const route = matchWsRoute(wsRoutes, path);
if (!route) {
ready.close(1008, 'no matching ws route');
return;
}
await runWsConnection(ready, request, route, deps.bus, streams);
};
}
/** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */
function devGraphRoute(graph: () => GraphView): RouteDef {
return {
@@ -537,18 +898,32 @@ function devGraphRoute(graph: () => GraphView): RouteDef {
pattern: '/__graph__',
transport: 'buffer',
handler: async (req) => {
const mermaid = toMermaid(graph());
const view = graph();
const accept = String(req.headers['accept'] ?? '');
return accept.includes('text/plain')
? { status: 200, headers: { 'content-type': 'text/plain' }, body: mermaid }
: { status: 200, headers: { 'content-type': 'text/html' }, body: graphHtml(mermaid) };
? { status: 200, headers: { 'content-type': 'text/plain' }, body: toMermaid(view) }
: { status: 200, headers: { 'content-type': 'text/html' }, body: graphHtml(view) };
},
};
}
/** The dev-only `/__openapi__` route: serves the structural OpenAPI 3.1 document as JSON. */
function openApiRoute(openapi: () => unknown): RouteDef {
return {
method: 'GET',
pattern: '/__openapi__',
transport: 'buffer',
handler: async () => ({
status: 200,
headers: { 'content-type': 'application/json' },
body: JSON.stringify(openapi()),
}),
};
}
/** Compiles every ws/negotiate route plan into a WebSocket route that seeds context and runs its steps + handler. */
function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[] {
const { providedSeed, planSteps } = deps;
const { providedSeed, planSteps, bus } = deps;
return routePlans
.filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate')
@@ -556,9 +931,11 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[
pattern: plan.pattern,
open: async ({ params, inbound, abort, req }) => {
const provided = await providedSeed(plan);
// ws upgrades come in on the raw Node req; trustProxy derivation for ws is out of scope here
// context is intentionally `any`: each step merges arbitrary keys into it
let context: any = {
// ws upgrades carry the neutral WsRequest (protocol/ip pre-derived by the runtime adapter);
// trustProxy derivation for ws is out of scope here
const context = await runSteps(
planSteps(plan),
{
...provided,
req,
params,
@@ -567,13 +944,11 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[
headers: req.headers,
inbound,
abort,
protocol: (req.socket as any).encrypted ? 'https' : 'http',
ip: req.socket.remoteAddress ?? '',
};
for (const step of planSteps(plan)) {
context = { ...context, ...(await step.run(context)) };
}
protocol: req.protocol,
ip: req.ip,
},
bus,
);
const result = await plan.run(context);
if (!isAsyncIterable(result)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
+12 -3
View File
@@ -4,7 +4,10 @@ import type { InspectLine, Explain, ExplainNode, RoutePlan } from './types';
/** Lists the provider/step/handler chain for a route, in execution order. */
export function inspectRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): InspectLine[] {
if (!booted) throw new Error('inspect() unavailable before listen() for mesh apps');
if (!booted)
throw new Error(
'inspect() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app',
);
const plan = routePlans.find((candidate) => candidate.pattern === routePath);
if (!plan) throw new Error(`no route: ${routePath}`);
return [
@@ -25,7 +28,10 @@ export function buildGraphView(
routePlans: RoutePlan[],
booted: boolean,
): GraphView {
if (!booted) throw new Error('graph() unavailable before listen() for mesh apps');
if (!booted)
throw new Error(
'graph() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app',
);
return {
nodes: [
...providerNodes.map((node) => ({
@@ -54,7 +60,10 @@ export function buildGraphView(
/** Explains a single route: its match criteria and the ordered chain with each node's needs/provides. */
export function explainRoute(routePlans: RoutePlan[], routePath: string, booted: boolean): Explain {
if (!booted) throw new Error('explain() unavailable before listen() for mesh apps');
if (!booted)
throw new Error(
'explain() unavailable until a mesh app has booted: a mesh graph is not knowable until its teapots are asked. Call `await app.ready()` first — it is a no-op on a non-mesh app',
);
const plan = routePlans.find((candidate) => candidate.pattern === routePath);
if (!plan) throw new Error(`no route: ${routePath}`);
const toExplainNode = (node: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({
+32
View File
@@ -3,6 +3,9 @@ import type { Bus } from '../bus';
import type { GraphNode } from '../graph';
import type { GraphView } from '../graph-viz';
import type { HttpMethod, Transport } from '../metadata';
import type { ArgSpec } from '../params';
import type { OpenApiDoc, OpenApiInfo } from '../openapi';
import type { WsRequest, WsSocket } from '../http/ws-core';
import { JsonTransformer } from '../transformers';
/** One entry in an {@link App.inspect} listing: a provider, step or handler and where it came from. */
@@ -33,11 +36,29 @@ export interface Explain {
export interface App {
listen(port: number): Promise<http.Server>;
close(): Promise<void>;
/**
* Resolves the dependency graph, then returns. For a mesh app that means connecting to its
* teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every
* other app it is a no-op, so code holding an `App` can `await app.ready()` before
* `inspect()`/`graph()`/`explain()` without caring which kind it was handed.
*
* Deliberately *not* a full boot: it does not run provider factories. Resolving the graph and
* being ready to serve are different things, and drawing a diagram should not open your
* database connections. Serving (`fetch`/`upgrade`/`listen`) boots the providers as well, and
* shares this same memoized step — calling both never resolves the graph twice.
*/
ready(): Promise<void>;
/** Web-Standards handler: run a Fetch API Request through the graph and return a Response (Node/Deno/Bun/edge). WS not included. */
fetch(request: Request): Promise<Response>;
/** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */
upgrade(request: WsRequest, socket: WsSocket): Promise<void>;
inspect(routePath: string): InspectLine[];
graph(): GraphView;
toMermaid(): string;
toDOT(): string;
explain(routePath: string): Explain;
/** Generate a structural OpenAPI 3.1 document from the registered routes. */
openapi(info?: OpenApiInfo): OpenApiDoc;
/** Names of optional providers that failed to boot and are running degraded (empty until {@link App.listen}). */
degraded(): string[];
bus: Bus;
@@ -49,6 +70,7 @@ export interface RoutePlan {
method: HttpMethod;
transport: Transport;
origin: string;
declaration: string;
providers: GraphNode[];
steps: GraphNode[];
handlerName: string;
@@ -56,11 +78,21 @@ export interface RoutePlan {
run: (ctx: any) => Promise<unknown>;
transformer: typeof JsonTransformer;
duplicates?: 'array' | 'last';
maxBodyBytes?: number;
maxParts?: number;
args: ArgSpec[];
}
/** Mesh networking options: a secret to gate this node's exports and/or remote teapots to connect to. */
export interface MeshConfig {
secret?: string;
teapots?: Array<{ url: string; secret: string }>;
/** How long an RPC may wait for its teapot before failing with 504 (default: 30s). */
timeoutMs?: number;
/**
* Gap between heartbeat pings to each teapot (default: 15s). Two unanswered rounds close the
* link, so a half-open connection surfaces as an immediate 503 instead of every request paying
* `timeoutMs` first. Lower it to notice a dead teapot sooner, at the cost of more chatter.
*/
heartbeatMs?: number;
}
+98
View File
@@ -0,0 +1,98 @@
import { channel } from './channel';
import type { Channel } from './channel';
import type { App } from './app/types';
import type { WsSocket, WsRequest } from './http/ws-core';
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
// Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
interface BunServerWebSocket {
data: unknown;
readyState: number;
send(data: string): number;
close(code?: number, reason?: string): void;
terminate?(): void;
}
interface BunWebSocketHandler {
open?(ws: BunServerWebSocket): void;
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
close?(ws: BunServerWebSocket, code: number, reason: string): void;
error?(ws: BunServerWebSocket, error?: unknown): void;
}
interface BunServer {
port: number;
stop(closeActiveConnections?: boolean): void;
upgrade(request: Request, options?: { data?: unknown; headers?: Record<string, string> }): boolean;
requestIP(request: Request): { address: string; family: string; port: number } | null;
}
interface BunServeOptions {
port?: number;
hostname?: string;
fetch(request: Request, server: BunServer): Response | Promise<Response> | undefined;
websocket?: BunWebSocketHandler;
}
type BunServeShortOptions = { port?: number; hostname?: string };
declare const Bun: { serve(options: BunServeOptions): BunServer };
/** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */
interface BunConnData {
wsReq: WsRequest;
inbound: Channel<unknown>;
ac: AbortController;
}
/**
* Wraps a Bun ServerWebSocket as a neutral WsSocket. Unlike Deno/edge, Bun delivers socket
* events to a server-level handler rather than the socket, so the channel and abort are
* created during the upgrade and stashed on ws.data — there is nothing here to wire up.
*/
function bunSocket(ws: BunServerWebSocket): WsSocket {
const { inbound, ac } = ws.data as BunConnData;
return neutralSocket(ws, inbound, ac);
}
/**
* Serve a Green Tea app on Bun: HTTP + SSE via app.fetch, WebSocket via Bun's server-level
* websocket handler. The ServerWebSocket only exists in open(), so per-connection state
* (inbound channel, abort, WsRequest) is stashed on ws.data during the upgrade.
*/
export function serveBun(app: App, options?: BunServeShortOptions): BunServer {
return Bun.serve({
...options,
fetch(request, server) {
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
const inbound = channel();
const ac = new AbortController();
const wsReq = toWsRequest(request, server.requestIP(request)?.address ?? '');
const data: BunConnData = { wsReq, inbound, ac };
if (server.upgrade(request, { data })) return undefined;
return new Response('WebSocket upgrade failed', { status: 400 });
}
return app.fetch(request);
},
websocket: {
open(ws) {
const { wsReq } = ws.data as BunConnData;
void upgradeSafely(app, wsReq, bunSocket(ws));
},
message(ws, message) {
const { inbound } = ws.data as BunConnData;
inbound.push(decodeMessage(message));
},
close(ws) {
const { inbound, ac } = ws.data as BunConnData;
inbound.close();
ac.abort();
},
error(ws) {
const { inbound, ac } = ws.data as BunConnData;
inbound.fail(new Error('websocket error'));
ac.abort();
},
},
});
}
+49
View File
@@ -0,0 +1,49 @@
import type { App } from './app/types';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
// The project tsconfig's `lib` doesn't include `DOM`, and the installed `@types/node` (18.x)
// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use.
interface WebSocket extends EventfulSocket {
binaryType: string;
}
// Minimal ambient for the Deno globals we use — avoids a @types/deno devDep.
// Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call.
interface DenoServeOptions {
port?: number;
hostname?: string;
signal?: AbortSignal;
onListen?: (addr: { hostname: string; port: number }) => void;
}
interface DenoServeHandlerInfo {
remoteAddr: { hostname: string; port: number; transport: string };
}
interface DenoHttpServer {
finished: Promise<void>;
shutdown(): Promise<void>;
}
type DenoServeHandler = (request: Request, info: DenoServeHandlerInfo) => Response | Promise<Response>;
declare const Deno: {
serve(options: DenoServeOptions, handler: DenoServeHandler): DenoHttpServer;
upgradeWebSocket(request: Request): { socket: WebSocket; response: Response };
};
/**
* Serve a Green Tea app on Deno: HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket.
* WebSocket messages flow through app.upgrade over the shared neutral core.
*/
export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer {
return Deno.serve(options ?? {}, (request, info) => {
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
// Deno invalidates request connection metadata as soon as the upgrade is accepted.
const wsRequest = toWsRequest(request, info.remoteAddr.hostname);
const { socket, response } = Deno.upgradeWebSocket(request);
socket.binaryType = 'arraybuffer'; // deliver binary frames as ArrayBuffer, which decodeMessage expects
// fire-and-forget: the 101 response must be returned synchronously while the graph runs
void upgradeSafely(app, wsRequest, eventSocket(socket));
return response;
}
return app.fetch(request);
});
}
+36
View File
@@ -0,0 +1,36 @@
import type { App } from './app/types';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
// Declares only what we call; mirrors the real workerd signatures.
interface EdgeWebSocket extends EventfulSocket {
accept(): void;
}
interface EdgeCtx {
waitUntil(promise: Promise<unknown>): void;
}
declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } };
/**
* Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair.
* Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat`
* compatibility flag. The WS lifecycle runs on ctx.waitUntil so it survives past the 101 response.
*/
export function edgeHandler(
app: App,
): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise<Response> {
return (request, _env, ctx) => {
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
server.accept();
const wsReq = toWsRequest(request, request.headers.get('cf-connecting-ip') ?? '');
const lifecycle = upgradeSafely(app, wsReq, eventSocket(server));
if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
else void lifecycle;
return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket });
}
return app.fetch(request);
};
}
+167 -10
View File
@@ -68,14 +68,171 @@ export function toDOT(view: GraphView): string {
return out.join('\n');
}
/** Wraps Mermaid source in a self-contained HTML page that renders it in the browser. */
export function graphHtml(mermaid: string): string {
return [
'<!doctype html><html><head><meta charset="utf-8"><title>green-tea graph</title>',
'<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script></head>',
'<body><pre class="mermaid">',
mermaid,
'</pre>',
'<script>mermaid.initialize({ startOnLoad: true });</script></body></html>',
].join('\n');
/**
* Renders the graph as a self-contained, interactive HTML page (Cytoscape.js +
* dagre, both from a CDN — no runtime dependency is added). Clicking a route
* lights up its exact transitive slice and dims everything else; clicking a
* provider/step shows its blast radius (every route that depends on it).
*
* The whole {@link GraphView} is embedded as JSON, so all interaction is
* client-side — the page needs nothing from the server after it loads.
*/
/** The Green Tea. mark (leaf whose venation is a dependency graph), inlined for the dev graph header. */
const BRAND_LOGO =
'<svg viewBox="0 0 611 620" fill="none" aria-hidden="true"> <path d="M0 0 C6.4 4.22 7.06 11.7 8.6 18.74 C9.17 21.55 9.71 24.37 10.23 27.2 C10.43 28.25 10.63 29.3 10.84 30.39 C11.48 33.82 12.12 37.25 12.75 40.69 C12.86 41.28 12.86 41.28 13.41 44.27 C19.74 78.61 25.24 113.17 28 148 C28.1 149.25 28.2 150.5 28.31 151.78 C33.71 219.69 29.07 297.74 -17 352 C-37.58 376.04 -63.34 393.66 -92.79 405.14 C-94.83 405.93 -96.85 406.75 -98.87 407.58 C-119.07 415.67 -140.54 420.66 -162 424 C-163.26 424.2 -164.52 424.4 -165.82 424.6 C-213.88 431.88 -265.63 431.11 -313 420 C-313.8 419.81 -314.6 419.63 -315.42 419.43 C-321.96 417.87 -328.02 416.17 -334 413 C-333.4 408.16 -331.32 404.45 -329 400.25 C-328.63 399.57 -328.26 398.88 -327.88 398.18 C-325.16 393.16 -325.16 393.16 -324 392 C-316.45 391.5 -309.28 393.04 -301.88 394.38 C-266.77 400.41 -230.41 401.2 -195 397 C-193.89 396.88 -192.78 396.75 -191.63 396.63 C-143.03 391.12 -90.07 376.55 -53 343 C-52.13 342.26 -51.26 341.53 -50.37 340.77 C-13.69 309.26 -0.6 260.49 3 214 C6.89 162.68 1.22 110.21 -9.66 60.01 C-10 58 -10 58 -10 54 C-10.66 54 -11.32 54 -12 54 C-12.08 54.65 -12.16 55.3 -12.24 55.98 C-13.28 60.13 -15.18 63.61 -17.19 67.38 C-17.63 68.2 -18.06 69.02 -18.51 69.87 C-27.46 86.43 -37.3 102.24 -49 117 C-49.73 117.94 -50.46 118.88 -51.21 119.85 C-55.22 124.97 -59.47 129.83 -63.85 134.63 C-65.75 136.73 -67.6 138.85 -69.44 141 C-76.06 148.56 -83.19 155.34 -91.04 161.6 C-93.13 163.29 -95.16 165 -97.18 166.77 C-122.17 188.79 -151.25 205.29 -180.04 221.76 C-192.95 229.14 -205.58 236.83 -218 245 C-218.85 245.56 -219.7 246.12 -220.58 246.7 C-229.87 252.82 -238.77 259.13 -247.12 266.49 C-249.7 268.74 -252.35 270.84 -255.06 272.94 C-267.05 282.7 -278.61 294.17 -288.03 306.45 C-289.89 308.86 -291.81 311.22 -293.74 313.57 C-298.14 319.07 -302.07 324.81 -305.94 330.69 C-306.64 331.75 -307.34 332.82 -308.07 333.91 C-310.06 336.94 -312.03 339.97 -314 343 C-314.45 343.69 -314.9 344.38 -315.36 345.1 C-333.78 373.72 -347.37 405.97 -360.01 437.47 C-367.19 455.23 -367.19 455.23 -373 459 C-381.02 461.67 -388.52 459.36 -396 456 C-400.94 452.9 -406.06 449.11 -409 444 C-409.81 440.26 -409.56 438.01 -407.71 434.64 C-404.3 429.62 -400.39 425.15 -396.3 420.68 C-391.69 415.32 -387.56 409.58 -383.38 403.88 C-382.15 402.21 -380.9 400.55 -379.64 398.89 C-379 398.02 -378.35 397.15 -377.69 396.25 C-377.13 395.51 -376.58 394.78 -376.01 394.02 C-375 392 -375 392 -375.3 390.07 C-376.44 386.69 -378.78 384.1 -380.94 381.31 C-403.08 351.79 -416.04 315.59 -420 279 C-420.11 278.07 -420.22 277.14 -420.34 276.18 C-425.19 227.03 -413.92 174.12 -382.44 135.12 C-380.97 133.41 -379.49 131.7 -378 130 C-377.28 129.17 -376.56 128.34 -375.82 127.49 C-358.11 107.42 -337.64 91.46 -314 79 C-313.38 78.67 -312.76 78.33 -312.12 77.99 C-300.18 71.58 -287.7 66.68 -275 62 C-274.14 61.68 -273.29 61.36 -272.4 61.03 C-234.24 47.03 -193.39 42.56 -153.28 37.74 C-131.4 35.11 -109.62 32.33 -88 28 C-87.42 27.89 -87.42 27.89 -84.51 27.32 C-61.65 22.81 -40.27 14.77 -19.21 4.91 C-6.48 -0.98 -6.48 -0.98 0 0 Z M-36.19 37.49 C-71.76 55.45 -113.52 58.93 -152.55 63.46 C-196.61 68.6 -196.61 68.6 -216 73 C-217 73.22 -218 73.43 -219.03 73.65 C-264.38 83.45 -306.87 101.06 -341 133 C-341.95 133.88 -342.9 134.77 -343.88 135.68 C-373.91 164.27 -390.12 205.53 -391.38 246.65 C-392.35 288.29 -383.46 327.6 -361 363 C-358.84 360.25 -357.1 357.49 -355.47 354.39 C-354.99 353.5 -354.52 352.61 -354.03 351.69 C-353.78 351.21 -353.78 351.21 -352.5 348.81 C-342.16 329.63 -330.05 311.66 -316 295 C-315.08 293.89 -314.16 292.78 -313.24 291.68 C-308.88 286.45 -304.51 281.32 -299.6 276.6 C-297.85 274.85 -296.28 273.01 -294.69 271.12 C-278.78 252.73 -256.54 237.48 -235.78 225.07 C-233.06 223.44 -230.38 221.74 -227.69 220.06 C-219.23 214.87 -210.61 209.95 -202 205 C-193.33 200.01 -184.66 195.01 -176 190 C-174.99 189.42 -173.99 188.84 -172.95 188.24 C-161.6 181.67 -150.51 174.92 -139.83 167.3 C-137.99 165.99 -136.14 164.7 -134.29 163.41 C-123.48 155.83 -113.46 147.55 -103.79 138.57 C-101.47 136.44 -99.13 134.36 -96.75 132.31 C-89.94 126.39 -83.79 119.91 -78 113 C-77.55 112.46 -77.1 111.93 -76.64 111.38 C-57.15 88.05 -39.86 63.1 -28 35 C-31.34 35 -33.25 36 -36.19 37.49 Z " fill="#5FB88A" transform="translate(501,80)"/> <g stroke="#5FB88A" stroke-width="12" stroke-linecap="round" fill="none"> <path d="M277 312 Q255 263 221 247"/> <path d="M338 276 Q382 305 393 340"/> <path d="M366 258 Q348 214 317 200"/> <path d="M443 186 Q469 204 475 224"/> </g> <g fill="#5FB88A"> <circle cx="221" cy="247" r="13"/> <circle cx="393" cy="340" r="13"/> <circle cx="475" cy="224" r="11"/> </g> <circle cx="317" cy="200" r="18" fill="#7C6CF0"/> </svg>';
export function graphHtml(view: GraphView): string {
const data = JSON.stringify(view).replace(/</g, '\\u003c');
return `<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>green-tea graph</title>
<script src="https://cdn.jsdelivr.net/npm/cytoscape@3.30.2/dist/cytoscape.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dagre@0.8.5/dist/dagre.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/cytoscape-dagre@2.5.0/cytoscape-dagre.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Zen+Maru+Gothic:wght@700&display=swap" rel="stylesheet">
<style>
:root { --bg:#fff; --ink:#1c2128; --dim:#57606a; --line:#d0d7de; --tea:#7c6cf0; --panel:#f6f8fa;
--matcha:#3fa873; --prov:#1f9e8a; --step:#7c6cf0; --need:#2f81f7; --feed:#bf8700; }
@media (prefers-color-scheme: dark) { :root { --bg:#0d1117; --ink:#e6edf3; --dim:#8b949e; --line:#30363d; --tea:#a78bfa; --panel:#161b22;
--matcha:#5fb88a; --prov:#3fd0b8; --step:#a78bfa; --need:#58a6ff; --feed:#e3b341; } }
* { box-sizing:border-box; } html,body { margin:0; height:100%; background:var(--bg); color:var(--ink);
font:13px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace; }
#cy { position:absolute; inset:0; }
#bar { position:absolute; top:0; left:0; right:0; padding:10px 14px; z-index:2; pointer-events:none;
background:linear-gradient(var(--bg),transparent); }
#bar b { color:var(--tea); } #bar span { color:var(--dim); }
#bar .brand { display:flex; align-items:center; gap:9px; margin-bottom:5px; }
#bar .brand svg { height:27px; width:auto; }
#bar .brand .wm { font-family:'Zen Maru Gothic',sans-serif; font-weight:700; font-size:18px; color:var(--matcha); }
#bar .brand .wm .dot { color:var(--step); }
#legend { margin-top:6px; color:var(--dim); font-size:12px; display:flex; gap:14px; flex-wrap:wrap; }
#legend i { display:inline-block; vertical-align:middle; margin-right:5px; }
#legend .sw { width:11px; height:11px; border-radius:3px; border:1.5px solid; }
#legend .prov { background:var(--panel); border-color:var(--prov); }
#legend .step { background:var(--panel); border-color:var(--step); border-radius:0; }
#legend .route { background:var(--tea); border-color:var(--tea); }
#legend .ln { width:16px; height:0; border-top:3px solid; border-radius:0; }
#legend .need { border-color:var(--need); } #legend .feed { border-color:var(--feed); }
#legend .tp { background:transparent; border-color:var(--dim); }
#legend .tp-http { border-style:solid; } #legend .tp-sse { border-style:dashed; }
#legend .tp-ws { border-style:double; border-width:3px; }
#info { position:absolute; left:14px; bottom:14px; z-index:2; max-width:340px; padding:10px 12px;
background:var(--panel); border:1px solid var(--line); border-radius:8px; white-space:pre-wrap; display:none; }
#info .t { color:var(--tea); font-weight:700; } #info .k { color:var(--dim); }
</style></head><body>
<div id="bar"><div class="brand">${BRAND_LOGO}<span class="wm">Green Tea<span class="dot">.</span></span></div><span>click a <b>route</b> for its slice · click a <b>provider/step</b> for its blast radius · drag to rearrange · click canvas to reset</span>
<div id="legend"><span><i class="sw prov"></i>provider</span><span><i class="sw step"></i>step</span><span><i class="ln need"></i>needs</span><span><i class="ln feed"></i>feeds endpoint</span><span><i class="sw tp tp-http"></i>HTTP</span><span><i class="sw tp tp-sse"></i>SSE</span><span><i class="sw tp tp-ws"></i>WS</span></div></div>
<div id="cy"></div>
<div id="info"></div>
<script>
var DATA = ${data};
try { if (window.cytoscapeDagre) cytoscape.use(window.cytoscapeDagre); } catch (e) {}
var css = getComputedStyle(document.documentElement);
var C = function (n) { return css.getPropertyValue(n).trim(); };
var nodeNames = new Set(DATA.nodes.map(function (n) { return n.name; }));
var nid = function (s) { return 'n_' + s.replace(/[^a-zA-Z0-9]/g, '_'); };
var rid = function (s) { return 'r_' + s.replace(/[^a-zA-Z0-9]/g, '_'); };
// HTTP method -> colour, so the endpoint type is visual, not just text.
var METHOD_COLORS = { GET: '#3fb950', POST: '#a371f7', PUT: '#d29922', PATCH: '#db61a2', DELETE: '#f85149', HEAD: '#8b949e', OPTIONS: '#8b949e' };
var methodColor = function (m) { return METHOD_COLORS[m] || '#8b949e'; };
var els = [];
DATA.nodes.forEach(function (n) {
els.push({ data: { id: nid(n.name), label: n.name, kind: n.kind, origin: n.origin,
needs: (n.needs || []).join(', '), provides: (n.provides || []).join(', ') } });
});
DATA.routes.forEach(function (r) {
var suffix = r.transport && r.transport !== 'buffer' ? ' · ' + r.transport : '';
els.push({ data: { id: rid(r.pattern), label: r.method + ' ' + r.pattern + suffix, kind: 'route',
method: r.method, transport: r.transport, color: methodColor(r.method) } });
});
DATA.nodes.forEach(function (n) {
(n.needs || []).forEach(function (need) {
if (nodeNames.has(need)) els.push({ data: { id: 'e' + nid(need) + nid(n.name), source: nid(need), target: nid(n.name), rel: 'need' } });
});
});
DATA.routes.forEach(function (r) {
(r.chain || []).forEach(function (name) {
if (nodeNames.has(name)) els.push({ data: { id: 'e' + nid(name) + rid(r.pattern), source: nid(name), target: rid(r.pattern), rel: 'feed' } });
});
});
// Precomputed highlight sets (uses green-tea's real per-route slice).
var routeChain = {}; DATA.routes.forEach(function (r) {
routeChain[rid(r.pattern)] = (r.chain || []).filter(function (x) { return nodeNames.has(x); }).map(nid);
});
var nodeRoutes = {}; DATA.nodes.forEach(function (n) {
nodeRoutes[nid(n.name)] = DATA.routes.filter(function (r) { return (r.chain || []).indexOf(n.name) >= 0; })
.map(function (r) { return rid(r.pattern); });
});
// Method colour chips in the legend — only for methods actually present.
var legend = document.getElementById('legend'), seenMethod = {};
DATA.routes.forEach(function (r) {
if (seenMethod[r.method]) return; seenMethod[r.method] = 1;
var s = document.createElement('span');
s.innerHTML = '<i class="sw" style="background:' + methodColor(r.method) + ';border-color:' + methodColor(r.method) + '"></i>' + r.method;
legend.appendChild(s);
});
var cy = cytoscape({
container: document.getElementById('cy'),
elements: els,
style: [
{ selector: 'node', style: { 'label': 'data(label)', 'color': C('--ink'), 'font-family': 'ui-monospace,Menlo,monospace',
'font-size': 12, 'text-valign': 'center', 'text-halign': 'center', 'width': 'label', 'height': 'label',
'padding': '10px', 'background-color': C('--panel'), 'border-width': 1.5, 'border-color': C('--tea'), 'shape': 'round-rectangle' } },
{ selector: 'node[kind = "provider"]', style: { 'shape': 'round-rectangle', 'background-color': C('--panel'), 'border-color': C('--prov') } },
{ selector: 'node[kind = "step"]', style: { 'shape': 'rectangle', 'border-color': C('--step') } },
{ selector: 'node[kind = "route"]', style: { 'shape': 'round-rectangle', 'background-color': 'data(color)', 'color': '#fff', 'border-width': 1.5, 'border-color': '#fff', 'border-style': 'solid', 'font-weight': 'bold' } },
{ selector: 'node[transport = "sse"]', style: { 'border-style': 'dashed', 'border-width': 2.5 } },
{ selector: 'node[transport = "negotiate"]', style: { 'border-style': 'dotted', 'border-width': 2.5 } },
{ selector: 'node[transport = "ws"]', style: { 'border-style': 'double', 'border-width': 4 } },
{ selector: 'edge', style: { 'width': 1, 'target-arrow-shape': 'triangle', 'curve-style': 'bezier', 'arrow-scale': 0.75 } },
{ selector: 'edge[rel = "need"]', style: { 'line-color': C('--need'), 'target-arrow-color': C('--need') } },
{ selector: 'edge[rel = "feed"]', style: { 'line-color': C('--feed'), 'target-arrow-color': C('--feed') } },
{ selector: '.dim', style: { 'opacity': 0.1 } },
{ selector: 'node.hot', style: { 'border-width': 3 } },
{ selector: 'edge.hot', style: { 'width': 1.9, 'opacity': 1 } }
]
});
var layout = { name: 'dagre', rankDir: 'LR', nodeSep: 36, rankSep: 90, edgeSep: 12 };
try { cy.layout(layout).run(); } catch (e) { cy.layout({ name: 'breadthfirst', directed: true }).run(); }
function highlight(idSet) {
cy.batch(function () {
cy.elements().removeClass('hot').addClass('dim');
idSet.forEach(function (id) { cy.getElementById(id).removeClass('dim').addClass('hot'); });
cy.edges().forEach(function (e) {
if (idSet.has(e.source().id()) && idSet.has(e.target().id())) e.removeClass('dim').addClass('hot');
});
});
}
function reset() { cy.batch(function () { cy.elements().removeClass('dim hot'); }); }
var info = document.getElementById('info');
function showInfo(el) {
var k = el.data('kind');
var body = k === 'route'
? '<span class="k">' + el.data('transport') + ' route</span>'
: '<span class="k">kind</span> ' + k + '\\n<span class="k">needs</span> ' + (el.data('needs') || '—')
+ '\\n<span class="k">provides</span> ' + (el.data('provides') || '—')
+ '\\n<span class="k">origin</span> ' + (el.data('origin') || '—');
info.style.display = 'block';
info.innerHTML = '<span class="t">' + el.data('label') + '</span>\\n' + body;
}
cy.on('tap', 'node', function (evt) {
var el = evt.target, id = el.id();
var ids = el.data('kind') === 'route'
? new Set([id].concat(routeChain[id] || []))
: new Set([id].concat(nodeRoutes[id] || []));
highlight(ids);
showInfo(el);
});
cy.on('mouseover', 'node', function (evt) { showInfo(evt.target); });
cy.on('tap', function (evt) { if (evt.target === cy) { reset(); info.style.display = 'none'; } });
</script></body></html>`;
}
+165
View File
@@ -0,0 +1,165 @@
// src/http/core.ts — runtime-neutral request handling core, shared by the Node adapter and (later) app.fetch.
import { HttpError, NotFound } from '../signals';
import { renderError } from '../transformers';
import { isStreamResult, type PipelineResult } from '../pipeline';
import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security';
import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
import { pickEncoder } from './stream';
import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders';
/** A runtime-neutral inbound request: body already parsed by the caller's ingress (Node stream, fetch Request, …). */
export interface NeutralRequest {
method: string;
url: string; // path + query, e.g. "/users/9?x=1"
headers: Record<string, string | string[] | undefined>;
body: unknown; // already-parsed body
secure: boolean;
ip: string;
}
/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */
export type NeutralOutcome =
| { kind: 'buffered'; status: number; headers: Record<string, string>; body: string | Buffer }
| { kind: 'stream'; headers: Record<string, string>; stream: AsyncIterable<unknown>; encoder: StreamEncoder };
/** {@link handle}'s result for a normal (non-preflight) request. */
export interface HandleResult {
injected: Record<string, string>;
outcome: NeutralOutcome;
}
/** {@link handle}'s result for a CORS preflight: the caller must answer with 204 + these headers. */
export interface Preflight {
preflight: Record<string, string>;
}
/**
* Computes the security + CORS headers that get injected into every response for a request — the same
* authoritative set {@link handle} applies to its outcomes. Shared with `buildFetch` (src/http/web.ts)
* so early-failure responses (413/400/501, before a route even matches) carry the same headers Node's
* `patchResponseHeaders` would have installed up-front.
*/
export function computeInjected(
opts: HttpOptions | undefined,
req: { secure: boolean; headers: Record<string, string | string[] | undefined> },
): Record<string, string> {
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) };
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
return injected;
}
function errorOutcome(
error: unknown,
req: NeutralRequest,
injected: Record<string, string>,
opts: HttpOptions | undefined,
headers: Record<string, string> = {},
): HandleResult {
const rendered = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
return {
injected,
outcome: {
kind: 'buffered',
status: rendered.status,
headers: { ...rendered.headers, ...headers },
body: req.method === 'HEAD' ? '' : rendered.body,
},
};
}
async function unmatchedOutcome(
routes: RouteDef[],
opts: HttpOptions | undefined,
req: NeutralRequest,
path: string,
injected: Record<string, string>,
): Promise<HandleResult> {
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
const hit = await opts.static(path);
if (hit) {
return {
injected,
outcome: {
kind: 'buffered',
status: 200,
headers: { 'content-type': hit.contentType },
body: req.method === 'HEAD' ? '' : hit.body,
},
};
}
}
const allow = allowedMethods(routes, path);
if (req.method === 'OPTIONS' && allow.length) {
return {
injected,
outcome: { kind: 'buffered', status: 204, headers: { allow: allow.join(', ') }, body: '' },
};
}
const error = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found');
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
}
/**
* Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405,
* route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the
* caller (a Node adapter, a fetch adapter, …) reads/writes the actual request/response.
*/
export async function handle(
routes: RouteDef[],
opts: HttpOptions | undefined,
req: NeutralRequest,
): Promise<HandleResult | Preflight> {
const injected = computeInjected(opts, req);
let path: string;
try {
path = normalizeRequestPath(req.url.split('?')[0]);
} catch {
return errorOutcome(new HttpError(400, 'Bad Request'), req, injected, opts);
}
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
return { preflight: corsPreflightHeaders(opts.cors, req) };
}
const matched = resolveRoute(routes, req.method, path);
if (!matched) return unmatchedOutcome(routes, opts, req, path, injected);
let result: PipelineResult;
try {
result = await matched.def.handler({
method: req.method,
url: req.url,
headers: req.headers,
params: matched.params,
query: parseQuery(req.url),
body: req.body,
protocol: req.secure ? 'https' : 'http',
ip: req.ip,
});
} catch (error) {
result = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
}
if (isStreamResult(result)) {
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } };
}
return {
injected,
outcome: {
kind: 'buffered',
status: result.status,
headers: result.headers,
body: req.method === 'HEAD' ? '' : result.body,
},
};
}
+32
View File
@@ -0,0 +1,32 @@
import { mergeVary } from '../security';
/**
* Merges a handler's response headers with authoritative `injected` headers
* (security + CORS). Injected keys win case-insensitively; `vary` is merged.
* Extracted from the Node writeHead patch so app.fetch shares the exact logic.
*/
export function mergeInjectedHeaders(
handlerHeaders: Record<string, any> | undefined,
injected: Record<string, string>,
): Record<string, any> {
const merged: Record<string, any> = {};
const injectedLower = new Set(Object.keys(injected).map((key) => key.toLowerCase()));
let handlerVary: string | undefined;
if (handlerHeaders)
for (const key of Object.keys(handlerHeaders)) {
const lowerKey = key.toLowerCase();
if (lowerKey === 'vary') {
handlerVary = handlerHeaders[key];
continue;
}
if (!injectedLower.has(lowerKey)) merged[key] = handlerHeaders[key];
}
Object.assign(merged, injected);
if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']);
else if (handlerVary !== undefined) merged['vary'] = handlerVary;
return merged;
}
+1 -1
View File
@@ -1,4 +1,4 @@
import http from 'http';
import type http from 'http';
import { HttpError } from '../signals';
/** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */
+240 -34
View File
@@ -1,63 +1,236 @@
import type { RouteDef, MatchedRoute } from './types';
/**
* Matches a route pattern against a request path. Supports static segments, `:param` (one segment),
* and a trailing `:name*` catch-all that captures the rest of the path (slashes included) into `params.name`.
* @returns Extracted params (decoded) when the path matches, otherwise undefined.
*/
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
export type CompiledSegment =
| { kind: 'static'; value: string }
| { kind: 'param'; name: string; constraint?: RegExp; constraintSource?: string }
| { kind: 'catchAll'; name: string };
/** Parsed route pattern reused by matching, specificity, ambiguity checks, and OpenAPI projection. */
export interface CompiledPattern {
source: string;
normalized: string;
shape: string;
segments: CompiledSegment[];
kinds: number[];
catchAll: boolean;
}
const compiledCache = new Map<string, CompiledPattern>();
const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
const MAX_CONSTRAINT_LENGTH = 128;
/** Request-path syntax error. Adapters translate this to the standard 400 response envelope. */
export class InvalidRequestPathError extends Error {
constructor(message: string) {
super(message);
this.name = 'InvalidRequestPathError';
}
}
interface ConstraintToken {
length: number;
unbounded: boolean;
separator: boolean;
}
/** Reads one atom plus its optional quantifier from the deliberately small safe-regex subset. */
function readConstraintToken(source: string): ConstraintToken | undefined {
const atom = /^(?:\\[dDsSwW]|\\[.\-_/]|[A-Za-z0-9_.-]|\[(?:\\.|[^\]\\])+\])/u.exec(source)?.[0];
if (!atom) return undefined;
const rest = source.slice(atom.length);
const quantifier = /^(?:[+*?]|\{\d+(?:,\d*)?\})/u.exec(rest)?.[0] ?? '';
if (quantifier.startsWith('{')) assertBoundedQuantifier(quantifier);
return {
length: atom.length + quantifier.length,
unbounded: quantifier === '+' || quantifier === '*' || quantifier.endsWith(',}'),
separator: quantifier === '' && /^(?:\\[.\-_/]|[._-])$/u.test(atom),
};
}
/** Rejects nonsensical or excessively large counted quantifiers before RegExp compilation. */
function assertBoundedQuantifier(quantifier: string): void {
const [minText, maxText] = quantifier.slice(1, -1).split(',');
const min = Number(minText);
const max = maxText === undefined || maxText === '' ? min : Number(maxText);
if (min > max || max > 2048) throw new Error(`unsafe route constraint: invalid quantifier '${quantifier}'`);
}
/** Accepts only a linear, group-free regex subset to keep attacker-controlled segments ReDoS-safe. */
function assertSafeConstraint(source: string): void {
if (!source || source.length > MAX_CONSTRAINT_LENGTH)
throw new Error('unsafe route constraint: expression must contain 1-128 characters');
let offset = 0;
let previousUnbounded = false;
while (offset < source.length) {
const token = readConstraintToken(source.slice(offset));
if (!token) throw new Error(`unsafe route constraint: unsupported expression '${source}'`);
if (previousUnbounded && token.unbounded)
throw new Error(`unsafe route constraint: adjacent unbounded quantifiers in '${source}'`);
previousUnbounded = token.separator ? false : token.unbounded;
offset += token.length;
}
}
function assertParamName(name: string, pattern: string): void {
if (!PARAM_NAME.test(name)) throw new Error(`invalid route pattern '${pattern}': invalid parameter name '${name}'`);
}
function compileParam(segment: string, pattern: string): Extract<CompiledSegment, { kind: 'param' }> {
const constraintStart = segment.indexOf('(');
if (constraintStart < 0) {
const name = segment.slice(1);
assertParamName(name, pattern);
return { kind: 'param', name };
}
if (!segment.endsWith(')')) throw new Error(`invalid route pattern '${pattern}': malformed constraint`);
const name = segment.slice(1, constraintStart);
const constraintSource = segment.slice(constraintStart + 1, -1);
assertParamName(name, pattern);
assertSafeConstraint(constraintSource);
return {
kind: 'param',
name,
constraintSource,
constraint: new RegExp(`^(?:${constraintSource})$`, 'u'),
};
}
function compileSegments(pattern: string, rawSegments: string[]): CompiledSegment[] {
const names = new Set<string>();
const compiled: CompiledSegment[] = [];
for (let index = 0; index < rawSegments.length; index++) {
const raw = rawSegments[index];
let segment: CompiledSegment;
if (raw.startsWith(':') && raw.endsWith('*')) {
const name = raw.slice(1, -1);
assertParamName(name, pattern);
if (index !== rawSegments.length - 1)
throw new Error(`invalid route pattern '${pattern}': catch-all must be the final segment`);
segment = { kind: 'catchAll', name };
} else if (raw.startsWith(':')) {
segment = compileParam(raw, pattern);
} else {
segment = { kind: 'static', value: raw };
}
if (segment.kind !== 'static') {
if (names.has(segment.name))
throw new Error(`invalid route pattern '${pattern}': duplicate parameter '${segment.name}'`);
names.add(segment.name);
}
compiled.push(segment);
}
return compiled;
}
function segmentShape(segment: CompiledSegment): string {
if (segment.kind === 'static') return `s:${segment.value}`;
if (segment.kind === 'catchAll') return 'c';
return segment.constraintSource ? `r:${segment.constraintSource}` : 'p';
}
/** Compiles and validates one route pattern. Results are cached by source string. */
export function compilePattern(pattern: string): CompiledPattern {
const cached = compiledCache.get(pattern);
if (cached) return cached;
if (!pattern.startsWith('/')) throw new Error(`invalid route pattern '${pattern}': pattern must start with '/'`);
if (pattern.includes('//')) throw new Error(`invalid route pattern '${pattern}': repeated slash`);
const normalized = pattern.length > 1 && pattern.endsWith('/') ? pattern.slice(0, -1) : pattern;
const rawSegments = normalized === '/' ? [] : normalized.split('/').slice(1);
const segments = compileSegments(pattern, rawSegments);
const compiled: CompiledPattern = {
source: pattern,
normalized,
shape: segments.map(segmentShape).join('/'),
segments,
kinds: segments
.filter((segment) => segment.kind !== 'catchAll')
.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),
catchAll: segments.at(-1)?.kind === 'catchAll',
};
compiledCache.set(pattern, compiled);
return compiled;
}
/** Applies the public trailing-slash policy and validates every segment's percent encoding. */
export function normalizeRequestPath(path: string): string {
if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash');
if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash');
const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
try {
for (const segment of normalized.split('/').slice(1)) decodeURIComponent(segment);
} catch {
throw new InvalidRequestPathError('invalid request path: malformed path encoding');
}
return normalized;
}
function decodeSegment(value: string): string {
return decodeURIComponent(value);
}
function matchCompiled(compiled: CompiledPattern, path: string): Record<string, string> | undefined {
const pathSegs = path.split('/').filter(Boolean);
const patternSegs = pattern.split('/').filter(Boolean);
const params: Record<string, string> = {};
for (let i = 0; i < patternSegs.length; i++) {
const seg = patternSegs[i];
for (let index = 0; index < compiled.segments.length; index++) {
const segment = compiled.segments[index];
// Trailing catch-all: capture every remaining segment (possibly none) as one decoded value.
if (seg.startsWith(':') && seg.endsWith('*')) {
params[seg.slice(1, -1)] = pathSegs.slice(i).map(decodeURIComponent).join('/');
if (segment.kind === 'catchAll') {
params[segment.name] = pathSegs.slice(index).map(decodeSegment).join('/');
return params;
}
if (i >= pathSegs.length) return undefined; // pattern longer than path
if (index >= pathSegs.length) return undefined;
if (seg.startsWith(':')) params[seg.slice(1)] = decodeURIComponent(pathSegs[i]);
else if (seg !== pathSegs[i]) return undefined;
if (segment.kind === 'static') {
if (segment.value !== pathSegs[index]) return undefined;
continue;
}
// No catch-all consumed the tail, so the lengths must match exactly.
return patternSegs.length === pathSegs.length ? params : undefined;
const value = decodeSegment(pathSegs[index]);
if (segment.constraint && !segment.constraint.test(value)) return undefined;
params[segment.name] = value;
}
/** Splits a pattern into its fixed-prefix segment kinds (2 = static, 1 = param) and whether it ends in a catch-all. */
function segScores(pattern: string): { catchAll: boolean; kinds: number[] } {
const kinds: number[] = [];
for (const seg of pattern.split('/').filter(Boolean)) {
if (seg.startsWith(':') && seg.endsWith('*')) return { catchAll: true, kinds };
kinds.push(seg.startsWith(':') ? 1 : 2);
return compiled.segments.length === pathSegs.length ? params : undefined;
}
return { catchAll: false, kinds };
/** Matches a compiled segment pattern and returns its decoded parameters. */
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
return matchCompiled(compilePattern(pattern), path);
}
/** Orders two matching patterns by specificity: exact beats catch-all, then static beats param, then longer wins. */
/** Orders matching patterns by exactness, then static/constrained/plain segment specificity. */
function moreSpecific(a: string, b: string): number {
const scoreA = segScores(a);
const scoreB = segScores(b);
const scoreA = compilePattern(a);
const scoreB = compilePattern(b);
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
for (let i = 0; i < length; i++) {
const kindA = scoreA.kinds[i] ?? -1;
const kindB = scoreB.kinds[i] ?? -1;
for (let index = 0; index < length; index++) {
const kindA = scoreA.kinds[index] ?? -1;
const kindB = scoreB.kinds[index] ?? -1;
if (kindA !== kindB) return kindA - kindB;
}
return 0;
}
/** Finds the most specific route matching both method and path (static > param > catch-all; ties keep registration order). */
/** Finds the most specific route matching both method and path; ties keep registration order. */
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
let best: MatchedRoute | undefined;
let bestPattern = '';
@@ -76,11 +249,44 @@ export function matchRoute(routes: RouteDef[], method: string, path: string): Ma
return best;
}
/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */
export interface ResolvedRoute extends MatchedRoute {
implicitHead: boolean;
}
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined {
const explicit = matchRoute(routes, method, path);
if (explicit) return { ...explicit, implicitHead: false };
if (method !== 'HEAD') return undefined;
const fallback = matchRoute(
routes.filter((route) => route.transport === 'buffer'),
'GET',
path,
);
return fallback ? { ...fallback, implicitHead: true } : undefined;
}
const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */
export function allowedMethods(routes: RouteDef[], path: string): string[] {
const methods = new Set<string>();
for (const route of routes) if (matchPattern(route.pattern, path)) methods.add(route.method);
return [...methods];
for (const route of routes) {
if (!matchPattern(route.pattern, path)) continue;
methods.add(route.method);
if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD');
}
if (methods.size) methods.add('OPTIONS');
return [...methods].sort((a, b) => {
const indexA = METHOD_ORDER.indexOf(a);
const indexB = METHOD_ORDER.indexOf(b);
return (
(indexA < 0 ? METHOD_ORDER.length : indexA) - (indexB < 0 ? METHOD_ORDER.length : indexB) || a.localeCompare(b)
);
});
}
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
+72 -86
View File
@@ -1,15 +1,16 @@
import http from 'http';
import https from 'https';
import { errorToResponse } from '../transformers';
import { isHttpError } from '../signals';
import { isStreamResult, type PipelineResult, type ResponseShape } from '../pipeline';
import type http from 'http';
import type https from 'https';
import { renderError, type ErrorRequest } from '../transformers';
import { isHttpError, HttpError } from '../signals';
import type { Bus } from '../bus';
import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from '../security';
import { buildSecurityHeaders, resolveCors } from '../security';
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
import { matchRoute, allowedMethods, parseQuery } from './router';
import { normalizeRequestPath, resolveRoute } from './router';
import { readBody, deriveSecure, deriveIp } from './request';
import { pickEncoder, pipeStream } from './stream';
import { pipeStream } from './stream';
import { attachWs } from './ws';
import { mergeInjectedHeaders } from './headers';
import { handle } from './core';
import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types';
interface HandlerConfig {
@@ -23,6 +24,11 @@ interface HandlerConfig {
/** A ready-to-send error response produced while acquiring the request body. */
type BodyFailure = { fail: { status: number; headers: Record<string, string>; body: string } };
/** Builds the {@link ErrorRequest} handed to a user error renderer. */
function errorRequest(req: http.IncomingMessage): ErrorRequest {
return { method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers };
}
/**
* Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades.
* @param routes HTTP route definitions.
@@ -42,10 +48,17 @@ export function createHttpServer(
const trustProxy = opts?.trustProxy ?? false;
const handler = createRequestHandler({ routes, bus, opts, maxBody, trustProxy });
// Node http/https are loaded lazily so importing createApp stays edge/workerd-safe
// (workerd's nodejs_compat provides no node:http/node:https). This path only runs under listen().
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodeHttp = require('http') as typeof import('http');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodeHttps = require('https') as typeof import('https');
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
const server: http.Server = (opts?.tls
? https.createServer(opts.tls as https.ServerOptions, handler)
: http.createServer(handler)) as unknown as http.Server;
? nodeHttps.createServer(opts.tls as https.ServerOptions, handler)
: nodeHttp.createServer(handler)) as unknown as http.Server;
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
@@ -53,13 +66,20 @@ export function createHttpServer(
return server;
}
/** Builds the request listener: security/CORS headers, routing, body parsing, then buffered or streamed response. */
/**
* Builds the request listener: a thin Node adapter around the runtime-neutral {@link handle} core.
* Reads the body (Node-specific), delegates security/CORS/routing/error-rendering to `handle()`,
* then writes the result to `res` (buffered or streamed). The security-header monkeypatch is
* installed here — and stays the single source of truth for merging headers into every response —
* so `handle()`'s own `injected` is intentionally unused by this adapter.
*/
function createRequestHandler(cfg: HandlerConfig) {
const { routes, bus, opts, maxBody, trustProxy } = cfg;
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
const url = req.url ?? '/';
const path = url.split('?')[0];
const method = req.method ?? 'GET';
// Install the security-header patch BEFORE any routing/response so every path
// (200, 404, error, stream) writes headers through the same patched writeHead.
const secure = deriveSecure(req, trustProxy);
@@ -70,29 +90,20 @@ function createRequestHandler(cfg: HandlerConfig) {
// by reference at writeHead time, so keys added here still land on every response.
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
res.writeHead(204, corsPreflightHeaders(opts.cors, req));
res.end();
return;
// Mirror handle()'s own preflight/route-match decision here, so we only read the body
// (below) for a request that actually reaches a route handler — matching prior behaviour.
const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']);
let matched: ReturnType<typeof resolveRoute>;
try {
matched = isPreflight ? undefined : resolveRoute(routes, method, normalizeRequestPath(path));
} catch {
matched = undefined; // handle() owns the standard 400 envelope and injected headers
}
const matched = matchRoute(routes, req.method ?? 'GET', path);
if (!matched) {
// Path matches a route under a different method → 405 with Allow; otherwise 404.
const allow = allowedMethods(routes, path);
if (allow.length) {
res.writeHead(405, { 'content-type': 'application/json', allow: allow.join(', ') });
res.end(JSON.stringify({ error: 'Method Not Allowed' }));
return;
}
res.writeHead(404, { 'content-type': 'application/json' });
res.end(JSON.stringify({ error: 'Not Found' }));
return;
}
let body: unknown;
if (matched) {
const acquired = await acquireBody(req, matched, opts, maxBody);
if ('fail' in acquired) {
@@ -101,32 +112,31 @@ function createRequestHandler(cfg: HandlerConfig) {
return;
}
let result: PipelineResult;
try {
result = await matched.def.handler({
method: req.method ?? 'GET',
url,
headers: req.headers,
params: matched.params,
query: parseQuery(url),
body: acquired.body,
protocol: secure ? 'https' : 'http',
ip: deriveIp(req, trustProxy),
});
} catch (error) {
result = errorToResponse(error);
body = acquired.body;
}
if (isStreamResult(result)) {
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
await pipeStream(res, result.stream, encoder, bus, matched.def.pattern, opts?.streams);
const result = await handle(routes, opts, {
method,
url,
headers: req.headers,
body,
secure,
ip: deriveIp(req, trustProxy),
});
if ('preflight' in result) {
res.writeHead(204, result.preflight);
res.end();
return;
}
const response: ResponseShape = result;
res.writeHead(response.status, response.headers);
res.end(response.body);
if (result.outcome.kind === 'stream') {
await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, matched?.def.pattern, opts?.streams);
return;
}
res.writeHead(result.outcome.status, result.outcome.headers);
res.end(result.outcome.body);
};
}
@@ -138,28 +148,23 @@ async function acquireBody(
maxBody: number,
): Promise<{ body: unknown } | BodyFailure> {
let buf: Buffer | undefined;
const bodyLimit = matched.def.maxBodyBytes ?? maxBody; // per-route override falls back to the server default
try {
buf = await readBody(req, maxBody);
buf = await readBody(req, bodyLimit);
} catch (error) {
const response = errorToResponse(error);
return {
fail: { status: response.status, headers: { ...response.headers, connection: 'close' }, body: response.body },
};
const rendered = renderError(error, errorRequest(req), opts?.onError);
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
}
const contentType = String(req.headers['content-type'] ?? '');
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
const parsed = await parseRequestBody(buf, contentType, duplicates, opts?.limits?.maxParts ?? 1000);
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts);
if ('error' in parsed) {
return {
fail: {
status: parsed.status ?? 400,
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ error: parsed.error }),
},
};
const rendered = renderError(new HttpError(parsed.status ?? 400, parsed.error), errorRequest(req), opts?.onError);
return { fail: rendered };
}
return { body: parsed.body };
@@ -174,27 +179,8 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record<string,
const origWriteHead = res.writeHead.bind(res);
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
// normalize (statusMessage?, headers?) overloads
const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined;
const merged: Record<string, any> = {};
const injectedLower = new Set(Object.keys(injected).map((key) => key.toLowerCase()));
let handlerVary: string | undefined;
if (handlerHeaders)
for (const key of Object.keys(handlerHeaders)) {
const lowerKey = key.toLowerCase();
if (lowerKey === 'vary') {
handlerVary = handlerHeaders[key];
continue;
} // merged separately below
if (!injectedLower.has(lowerKey)) merged[key] = handlerHeaders[key];
}
Object.assign(merged, injected);
if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']);
else if (handlerVary !== undefined) merged['vary'] = handlerVary; // preserve handler Vary when no CORS
const merged = mergeInjectedHeaders(handlerHeaders, injected);
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
};
}
@@ -206,7 +192,7 @@ type ParseResult = { body: unknown } | { error: string; status?: number };
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
*/
async function parseRequestBody(
export async function parseRequestBody(
buf: Buffer | undefined,
contentType: string,
duplicates: 'array' | 'last',
+19 -5
View File
@@ -1,4 +1,4 @@
import http from 'http';
import type http from 'http';
import { once } from 'events';
import { sseEncoder, ndjsonEncoder, StreamEncoder } from '../encoders';
import type { Transport } from '../metadata';
@@ -6,11 +6,25 @@ import type { Bus } from '../bus';
const PING_MS = 15_000;
/** Selects the stream encoder for a transport, falling back to the client's `Accept` header for `stream`. */
/**
* Stream encoder per transport, or `null` for transports that never produce an HTTP stream.
* A new transport must add a row — the compiler fails until it does, so it can't silently
* inherit ndjson framing.
*/
const STREAM_ENCODERS: Record<Transport, ((accept: string) => StreamEncoder) | null> = {
buffer: null, // a buffered handler returning a stream throws TransportMismatchError before reaching here
ws: null, // not an HTTP response; ws routes are served via upgrade, not handle()
sse: () => sseEncoder,
ndjson: () => ndjsonEncoder,
negotiate: (accept) => (accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder),
};
/** Selects the stream encoder for a transport, falling back to the client's `Accept` header for `negotiate`. */
export function pickEncoder(transport: Transport, accept: string): StreamEncoder {
if (transport === 'sse') return sseEncoder;
if (transport === 'ndjson') return ndjsonEncoder;
return accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder;
const pick = STREAM_ENCODERS[transport];
if (!pick) throw new Error(`transport '${transport}' does not produce an HTTP stream`);
return pick(accept);
}
/** Pipes an async-iterable result to the response as an HTTP stream, with keep-alive pings and backpressure handling. */
+15 -4
View File
@@ -1,7 +1,9 @@
import http from 'http';
import type { Transport } from '../metadata';
import type { PipelineResult } from '../pipeline';
import type { ErrorRenderer } from '../transformers';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import type { WsRequest, WsSocket } from './ws-core';
import type { StaticResolver } from '../views';
/** Per-request size and timeout ceilings applied by the server. */
export interface RequestLimits {
@@ -21,6 +23,8 @@ export interface HttpOptions {
security?: boolean | SecurityOptions;
cors?: CorsOptions;
bodyDuplicates?: 'array' | 'last';
onError?: ErrorRenderer;
static?: StaticResolver;
}
/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */
@@ -42,6 +46,8 @@ export interface RouteDef {
transport: Transport;
handler: RouteHandler;
bodyDuplicates?: 'array' | 'last';
maxBodyBytes?: number; // per-route override of the server's maxBodyBytes
maxParts?: number; // per-route override of the server's multipart maxParts
}
/** Result of matching a request path against a route: extracted params plus the matched definition. */
@@ -50,12 +56,12 @@ export interface MatchedRoute {
def: RouteDef;
}
/** Context passed to a WebSocket route's `open`: path params, inbound message stream, abort signal, and raw request. */
/** Context passed to a WebSocket route's `open`: path params, inbound message stream, abort signal, and neutral request. */
export interface WsOpenCtx {
params: Record<string, string>;
inbound: AsyncIterable<unknown>;
abort: AbortSignal;
req: http.IncomingMessage;
req: WsRequest;
}
/** A registered WebSocket route: path pattern and an `open` that returns the outbound message stream. */
@@ -67,5 +73,10 @@ export interface WsRouteDef {
/** Hook for a mesh gateway to take over WebSocket upgrades on a fixed path. */
export interface MeshControl {
path: string;
handle(ws: any, req: http.IncomingMessage): void;
/**
* Serves one control connection over the neutral socket — the same capability every other ws
* consumer takes, so Node (via `nodeSocket`) and Deno/Bun (via `app.upgrade`) both feed it.
* Resolves when the connection ends, like `runWsConnection`.
*/
handle(socket: WsSocket): Promise<void>;
}
+173
View File
@@ -0,0 +1,173 @@
import type { StreamEncoder } from '../encoders';
import { handle, computeInjected, type HandleResult } from './core';
import { mergeInjectedHeaders } from './headers';
import { parseRequestBody } from './server';
import { normalizeRequestPath, resolveRoute } from './router';
import { HttpError } from '../signals';
import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers';
import type { RouteDef, HttpOptions, MatchedRoute } from './types';
/** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */
export function asReadableStream(source: AsyncIterable<unknown>, encoder: StreamEncoder): ReadableStream<Uint8Array> {
const iterator = source[Symbol.asyncIterator]();
const te = new TextEncoder();
return new ReadableStream<Uint8Array>({
async pull(controller) {
try {
const { value, done } = await iterator.next();
if (done) {
controller.close();
return;
}
const encoded = encoder.encode(value);
const bytes = typeof encoded === 'string' ? te.encode(encoded) : encoded;
controller.enqueue(bytes);
} catch (err) {
controller.error(err);
}
},
async cancel() {
await iterator.return?.();
},
});
}
/** Converts a web `Headers` into the plain record shape the neutral core and body parser expect. */
function headersToRecord(headers: Headers): Record<string, string> {
const out: Record<string, string> = {};
headers.forEach((value, key) => {
out[key] = value;
});
return out;
}
/**
* Turns a rendered error (or any {status, headers, body}) into a web `Response`, merging in the
* authoritative `injected` security/CORS headers — mirrors the Node adapter, where
* `patchResponseHeaders` installs these before body acquisition even runs, so early failures
* (413/400/501) carry them too.
*/
function errorResponse(rendered: ErrorResponse, injected: Record<string, string>): Response {
const headers = mergeInjectedHeaders(rendered.headers, injected);
return new Response(rendered.body, { status: rendered.status, headers });
}
/**
* Reads and parses a matched request's body (enforcing `maxBodyBytes` → 413), mirroring the Node
* adapter's `acquireBody`. Returns `{ body }` on success, or a ready-to-send `{ response }` on failure.
*/
async function acquireFetchBody(
request: Request,
matched: MatchedRoute,
headers: Record<string, string>,
path: string,
maxBody: number,
opts: HttpOptions | undefined,
injected: Record<string, string>,
): Promise<{ body: unknown } | { response: Response }> {
const errReq: ErrorRequest = { method: request.method, url: path, headers };
let buf: Buffer | undefined;
if (request.body) {
const arrayBuffer = await request.arrayBuffer();
const bodyLimit = matched.def.maxBodyBytes ?? maxBody;
if (arrayBuffer.byteLength > bodyLimit) {
return {
response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError), injected),
};
}
buf = arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer);
}
const contentType = headers['content-type'] ?? '';
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts);
if ('error' in parsed) {
return {
response: errorResponse(
renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError),
injected,
),
};
}
return { body: parsed.body };
}
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
function outcomeToResponse(result: HandleResult): Response {
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
if (result.outcome.kind === 'stream') {
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers });
}
const body = [204, 205, 304].includes(result.outcome.status) ? null : result.outcome.body;
return new Response(body, { status: result.outcome.status, headers });
}
/**
* Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses:
* reads the body (enforcing `maxBodyBytes` → 413), parses it by content type, runs it through the
* runtime-neutral {@link handle}, and converts the outcome to a `Response` (buffered or streamed).
*/
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
return async (request: Request): Promise<Response> => {
const url = new URL(request.url);
const path = url.pathname + url.search;
const headers = headersToRecord(request.headers);
let matched: ReturnType<typeof resolveRoute>;
try {
matched = resolveRoute(routes, request.method, normalizeRequestPath(url.pathname));
} catch {
matched = undefined; // handle() renders the shared 400 response without reading a body
}
const secure = url.protocol === 'https:';
// Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501,
// before a route handler even runs) carry the same security/CORS headers Node's writeHead patch
// would have installed before body acquisition.
const injected = computeInjected(opts, { secure, headers });
let body: unknown;
if (matched) {
const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts, injected);
if ('response' in acquired) return acquired.response;
body = acquired.body;
}
const result = await handle(routes, opts, {
method: request.method,
url: path,
headers,
body,
secure,
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is
// trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket
// peer address to fall back to on the fetch path, so the untrusted case is simply ''.
ip: opts?.trustProxy
? String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim()
: '',
});
// Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and
// so picks up the same authoritative security headers `injected` carries (Node's writeHead patch
// merges every response — including the 204 preflight — with `injected`; this adapter must too).
if ('preflight' in result) {
return new Response(null, { status: 204, headers: mergeInjectedHeaders(result.preflight, injected) });
}
return outcomeToResponse(result);
};
}
+162
View File
@@ -0,0 +1,162 @@
import { channel } from '../channel';
import type { App } from '../app/types';
import type { WsRequest, WsSocket } from './ws-core';
/**
* Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket
* to the neutral {@link WsSocket} the core talks to. Separate from `ws-core` on purpose:
* that module *runs* a connection, this one *builds* one from a host runtime's socket.
*/
const decoder = new TextDecoder();
const OPEN = 1; // WebSocket.OPEN — same constant in every runtime; avoids a per-runtime ambient
/** Decodes a host `message` payload to the string the core expects (parity with Node's Buffer.toString()). */
export function decodeMessage(data: string | ArrayBuffer | Uint8Array): string {
return typeof data === 'string' ? data : decoder.decode(data);
}
/**
* Builds a neutral {@link WsRequest} from a Web-standard `Request`. Every adapter derives
* url/headers/protocol identically; only the client IP is runtime-specific, so it's passed in.
*/
export function toWsRequest(request: Request, ip: string): WsRequest {
const url = new URL(request.url);
const headers: Record<string, string> = {};
request.headers.forEach((value, key) => {
headers[key] = value;
});
return {
url: url.pathname + url.search,
headers,
protocol: url.protocol === 'https:' ? 'https' : 'http',
ip,
};
}
/** The subset of a host WebSocket that {@link eventSocket} drives (Deno's WebSocket and workerd's both satisfy it). */
export interface EventfulSocket {
readonly readyState: number;
send(data: string): void;
close(code?: number, reason?: string): void;
addEventListener(
type: 'open' | 'message' | 'close' | 'error',
listener: (event: { data?: string | ArrayBuffer; error?: unknown }) => void,
): void;
}
/**
* Wraps an `addEventListener`-style host socket (Deno, workerd) as a neutral {@link WsSocket}:
* creates the inbound channel and abort controller and wires message/close/error into them.
* Bun does not use this — its socket events are delivered to a server-level handler rather
* than the socket, so it builds its own {@link WsSocket} over state stashed on `ws.data`.
*/
export function eventSocket(host: EventfulSocket): WsSocket {
const inbound = channel<unknown>();
const ac = new AbortController();
host.addEventListener('message', (event) => {
inbound.push(decodeMessage(event.data as string | ArrayBuffer));
});
host.addEventListener('close', () => {
inbound.close();
ac.abort();
});
host.addEventListener('error', () => {
inbound.fail(new Error('websocket error'));
ac.abort();
});
return neutralSocket(host, inbound, ac);
}
/**
* Wraps a host socket's send/close/readyState as a neutral {@link WsSocket} over an
* already-wired channel and abort controller. `close`/`terminate` swallow throws so
* callers never have to guard an already-closed socket.
*/
export function neutralSocket(
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
inbound: ReturnType<typeof channel<unknown>>,
ac: AbortController,
): WsSocket {
return {
inbound,
abort: ac.signal,
get isOpen() {
return host.readyState === OPEN;
},
send: (data) => {
host.send(data);
},
close: (code, reason) => {
try {
host.close(code, reason);
} catch {
/* already closed */
}
},
terminate: () => {
try {
(host.terminate ?? host.close).call(host);
} catch {
/* already closed */
}
},
};
}
/** Constructs a host WebSocket *client*. Both the platform global and the `ws` package satisfy it. */
export type SocketCtor = new (url: string) => EventfulSocket;
/**
* The WebSocket client implementation: the platform global where it exists (Deno, Bun, and
* Node >= 22), else the `ws` optional peer — Node 18-21, our declared floor, has no global.
*
* Both expose the same `addEventListener` API and deliver text frames as `event.data` strings,
* so one bridge covers both. That is verified rather than assumed: `ws` implements the
* browser-compatible event API alongside its EventEmitter one.
*/
export function loadWebSocketCtor(): SocketCtor {
const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket;
if (platform) return platform;
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('ws') as SocketCtor;
}
/**
* Opens a client connection and wraps it as a neutral {@link WsSocket}. `opened` resolves once
* the socket is live (the caller's cue to send its first frame) and rejects if it never opens.
*
* `Ctor` is injectable so both implementations can be exercised on one runtime — otherwise CI
* on a single Node version would silently cover only one of the two paths.
*/
export function connectSocket(
url: string,
Ctor: SocketCtor = loadWebSocketCtor(),
): { socket: WsSocket; opened: Promise<void> } {
const host = new Ctor(url);
// registered before eventSocket's own error listener, so a connect failure rejects `opened`
// with the host's real error rather than eventSocket's generic one
const opened = new Promise<void>((resolve, reject) => {
host.addEventListener('open', () => resolve());
host.addEventListener('error', (event) => reject(event?.error ?? new Error(`websocket error: ${url}`)));
});
return { socket: eventSocket(host), opened };
}
/**
* Runs the ws lifecycle, closing with 1011 if it rejects. `app.upgrade` can reject *before*
* `runWsConnection`'s own try/catch (mesh-before-listen, provider boot failure); unguarded,
* that surfaces as an uncaught rejection and is fatal on Bun/Deno. Returns the promise so
* edge can hand it to `ctx.waitUntil`.
*/
export function upgradeSafely(app: App, request: WsRequest, socket: WsSocket): Promise<void> {
return app.upgrade(request, socket).catch(() => {
socket.close(1011, 'internal error'); // neutral close already swallows throws
});
}
+137
View File
@@ -0,0 +1,137 @@
import { isHttpError } from '../signals';
import type { Bus } from '../bus';
import { matchPattern } from './router';
import type { WsRouteDef } from './types';
/** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */
export interface WsRequest {
url: string;
headers: Record<string, string | string[] | undefined>;
protocol: 'http' | 'https';
ip: string;
}
/** Capability an adapter builds from its runtime socket. The neutral core talks only to this. */
export interface WsSocket {
readonly inbound: AsyncIterable<unknown>;
readonly abort: AbortSignal;
readonly isOpen: boolean;
send(data: string): void;
close(code?: number, reason?: string): void;
terminate(): void;
}
/** Finds the first ws route whose pattern matches `path`, capturing its params. */
export function matchWsRoute(
wsRoutes: WsRouteDef[],
path: string,
): { def: WsRouteDef; params: Record<string, string> | undefined } | undefined {
return wsRoutes
.map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) }))
.find((entry) => entry.params);
}
/**
* Runs `connection` with the socket registered for force-close on shutdown, unregistering it
* when the connection ends. Without this a long-lived socket keeps `server.close()` waiting for
* a peer that has no reason to hang up — the mesh control channel is exactly that shape.
*/
export async function trackUntil(
socket: WsSocket,
connection: Promise<void>,
streams?: Set<() => void>,
): Promise<void> {
const { closer } = trackConnection(socket, streams);
try {
await connection;
} finally {
streams?.delete(closer);
}
}
/** Registers the connection with the stream registry so it can be force-closed on shutdown. */
function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer: () => void } {
const closer = () => {
try {
socket.terminate();
} catch {
/* */
}
};
streams?.add(closer);
return { closer };
}
/** Drives the outbound async iterator, sending each yielded value until done or the socket closes. */
async function pumpOutbound(socket: WsSocket, iterator: AsyncIterator<unknown>): Promise<void> {
while (true) {
const { value, done } = await iterator.next();
if (done) break;
if (!socket.isOpen) break;
socket.send(typeof value === 'string' ? value : JSON.stringify(value));
}
try {
socket.close();
} catch {
/* already closed */
}
}
/** Closes with 4000+status for HttpErrors, 1011 otherwise. */
function closeOnError(socket: WsSocket, err: unknown): void {
if (isHttpError(err)) {
const reason = new TextDecoder().decode(new TextEncoder().encode(String(err.message)).subarray(0, 120));
try {
socket.close(4000 + err.status, reason);
} catch {
/* already closed */
}
} else {
try {
socket.close(1011);
} catch {
/* already closed */
}
}
}
/** Runs the full per-connection lifecycle over a neutral socket capability. */
export async function runWsConnection(
socket: WsSocket,
request: WsRequest,
route: { def: WsRouteDef; params: Record<string, string> | undefined },
bus?: Bus,
streams?: Set<() => void>,
): Promise<void> {
const { closer } = trackConnection(socket, streams);
const name = route.def.pattern;
let iterator: AsyncIterator<unknown> | undefined;
const onAbort = () => {
streams?.delete(closer);
void Promise.resolve(iterator?.return?.()).catch(() => {});
};
socket.abort.addEventListener('abort', onAbort, { once: true });
bus?.emit('stream:open', { name });
try {
const outbound = await route.def.open({
params: route.params ?? {},
inbound: socket.inbound,
abort: socket.abort,
req: request,
});
iterator = outbound[Symbol.asyncIterator]();
await pumpOutbound(socket, iterator);
} catch (err) {
bus?.emit('stream:error', { name, error: err });
closeOnError(socket, err);
} finally {
bus?.emit('stream:close', { name });
}
}
+41 -96
View File
@@ -1,8 +1,7 @@
import http from 'http';
import type http from 'http';
import { channel } from '../channel';
import { isHttpError } from '../signals';
import type { Bus } from '../bus';
import { matchPattern } from './router';
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
import type { WsRouteDef, MeshControl } from './types';
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
@@ -31,6 +30,7 @@ function handleMeshUpgrade(
req: http.IncomingMessage,
socket: any,
head: Buffer,
streams?: Set<() => void>,
): boolean {
if (path !== meshControl.path) return false;
@@ -39,112 +39,55 @@ function handleMeshUpgrade(
return true;
}
wss.handleUpgrade(req, socket, head, (ws: any) => meshControl.handle(ws, req));
// nodeSocket, not the raw ws: the control channel is the last consumer that spoke the
// `ws` EventEmitter API directly. It now takes the same neutral socket every route does.
// Tracked like any other long-lived socket: a connected teacup has no reason to hang up, so
// an untracked control channel leaves the teapot's server.close() waiting on it forever.
// serveFrames swallows its own failures, so the floating promise cannot reject.
wss.handleUpgrade(req, socket, head, (ws: any) => {
const neutral = nodeSocket(ws);
void trackUntil(neutral, meshControl.handle(neutral), streams);
});
return true;
}
/** Finds the first ws route whose pattern matches `path`, capturing its params. */
function matchWsRoute(
wsRoutes: WsRouteDef[],
path: string,
): { def: WsRouteDef; params: Record<string, string> | undefined } | undefined {
return wsRoutes
.map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) }))
.find((entry) => entry.params);
/** Builds the neutral WsRequest from a Node upgrade request. Same values the old open() read from req.socket. */
function nodeWsRequest(req: http.IncomingMessage): WsRequest {
return {
url: req.url ?? '/',
headers: req.headers,
protocol: (req.socket as any).encrypted ? 'https' : 'http',
ip: req.socket.remoteAddress ?? '',
};
}
/** Wires inbound message/close/error events into a channel and returns the channel plus its abort controller. */
function wireInbound(ws: any): { inbound: ReturnType<typeof channel<unknown>>; abortController: AbortController } {
/** Wraps a `ws` socket as a neutral WsSocket: inbound channel + abort on close + send/close/terminate. */
function nodeSocket(ws: any): WsSocket {
const inbound = channel<unknown>();
const abortController = new AbortController();
const ac = new AbortController();
ws.on('message', (data: Buffer) => inbound.push(data.toString()));
ws.on('close', () => {
inbound.close();
abortController.abort();
ac.abort();
});
ws.on('error', (err: unknown) => inbound.fail(err));
return { inbound, abortController };
}
/** Registers the connection with the stream registry so it can be force-closed on shutdown. */
function trackConnection(ws: any, streams?: Set<() => void>): void {
const closer = () => {
return {
inbound,
abort: ac.signal,
get isOpen() {
return ws.readyState === 1; // 1 = OPEN
},
send: (data) => ws.send(data),
close: (code, reason) => {
try {
(ws.terminate ?? ws.close).call(ws);
ws.close(code, reason);
} catch {
/* */
/* already closed */
}
},
terminate: () => (ws.terminate ?? ws.close).call(ws),
};
streams?.add(closer);
ws.on('close', () => streams?.delete(closer));
}
/** Drives the outbound async iterator, sending each yielded value over the socket until done or closed. */
async function pumpOutbound(ws: any, iterator: AsyncIterator<unknown>): Promise<void> {
while (true) {
const { value, done } = await iterator.next();
if (done) break;
if (ws.readyState !== 1) break; // 1 = OPEN; stop if socket gone
ws.send(typeof value === 'string' ? value : JSON.stringify(value));
}
try {
ws.close();
} catch {
/* already closed */
}
}
/** Closes the socket with the appropriate code after an outbound error (4000+status for HTTP errors, 1011 otherwise). */
function closeOnError(ws: any, err: unknown): void {
if (isHttpError(err)) {
const reason = Buffer.from(String(err.message)).subarray(0, 120).toString();
try {
ws.close(4000 + err.status, reason);
} catch {
/* already closed */
}
} else {
try {
ws.close(1011);
} catch {
/* already closed */
}
}
}
/** Runs the full per-connection lifecycle: inbound wiring, opening the route stream, and pumping outbound values. */
async function openWsConnection(
ws: any,
route: { def: WsRouteDef; params: Record<string, string> | undefined },
req: http.IncomingMessage,
bus?: Bus,
streams?: Set<() => void>,
): Promise<void> {
trackConnection(ws, streams);
const { inbound, abortController } = wireInbound(ws);
const name = route.def.pattern;
let iterator: AsyncIterator<unknown> | undefined;
ws.on('close', () => {
void Promise.resolve(iterator?.return?.()).catch(() => {});
}); // force-cancel outbound
bus?.emit('stream:open', { name });
try {
const outbound = await route.def.open({ params: route.params!, inbound, abort: abortController.signal, req });
iterator = outbound[Symbol.asyncIterator]();
await pumpOutbound(ws, iterator);
} catch (err) {
bus?.emit('stream:error', { name, error: err });
closeOnError(ws, err);
} finally {
abortController.abort();
bus?.emit('stream:close', { name });
}
}
/** Attaches WebSocket upgrade handling to the server: routes to `wsRoutes` or a mesh control path. */
@@ -161,7 +104,7 @@ export function attachWs(
server.on('upgrade', (req, socket, head) => {
const path = (req.url ?? '/').split('?')[0];
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head)) return;
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return;
const route = matchWsRoute(wsRoutes, path);
@@ -175,6 +118,8 @@ export function attachWs(
return;
}
wss.handleUpgrade(req, socket, head, (ws: any) => openWsConnection(ws, route, req, bus, streams));
wss.handleUpgrade(req, socket, head, (ws: any) => {
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams);
});
});
}
+34 -3
View File
@@ -6,7 +6,7 @@
import 'reflect-metadata';
/** Package version, replaced at publish time. */
export const VERSION = '26.07.0-beta.0';
export const VERSION = '26.8.0-beta.0';
// Application
export { createApp } from './app';
@@ -15,15 +15,46 @@ export type { App, InspectLine, Explain, MeshConfig } from './app';
// Graph visualization
export { toMermaid, toDOT } from './graph-viz';
export type { GraphView } from './graph-viz';
export { buildOpenApi } from './openapi';
export type { OpenApiDoc, OpenApiInfo, OpenApiRoute } from './openapi';
// Views
export { render } from './views';
// Routing & decorators
export { Provider, Step, Route, Get, Module, Transformer, Sse, Ws, Stream, Post, Put, Patch, Delete } from './metadata';
export {
Provider,
Step,
Route,
Get,
Head,
Module,
Transformer,
Sse,
Ws,
Stream,
Post,
Put,
Patch,
Delete,
Options,
Html,
} from './metadata';
export type { Transport, HttpMethod } from './metadata';
export type { Plugin } from './plugin';
// Transformers & error signals
export { JsonTransformer } from './transformers';
export { HttpError, Unauthorized, NotFound, Redirect, NotModified, ValidationError } from './signals';
export type { ErrorRenderer, ErrorRequest, ErrorResponse } from './transformers';
export {
HttpError,
Unauthorized,
NotFound,
Redirect,
NotModified,
ValidationError,
TransportMismatchError,
} from './signals';
// Bus & flow
export { Bus } from './bus';
+169 -56
View File
@@ -1,8 +1,8 @@
import type { Bus } from '../bus';
import { HttpError } from '../signals';
import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol';
let connSeq = 0; // module-level: deterministic unique connection-id prefix (no Date.now/Math.random)
import { connectSocket, type SocketCtor } from '../http/ws-adapter';
import type { WsSocket } from '../http/ws-core';
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol';
/** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */
export interface Link {
@@ -18,17 +18,15 @@ type PendingEntry = {
timer: ReturnType<typeof setTimeout>;
};
function loadWs(): any {
// lazy/optional, like streams; the ws CJS export is the WebSocket class
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('ws');
}
/** Reject and clear every in-flight RPC — used when the link closes. */
/**
* Reject and clear every in-flight RPC — used when the link closes.
* 503, not a bare Error: a dead upstream is not "this service broke", and the status is what
* tells a caller it may retry and an operator where to look. A bare Error renders as a 500.
*/
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): void {
for (const [, entry] of pending) {
clearTimeout(entry.timer);
entry.reject(new Error(reason));
entry.reject(new HttpError(503, reason));
}
pending.clear();
@@ -36,7 +34,7 @@ function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): v
/** Register one RPC in `pending` by id, send its request, and reject it on timeout. */
function sendRpc(
ws: any,
socket: WsSocket,
pending: Map<string, PendingEntry>,
id: string,
kind: 'scope' | 'route',
@@ -44,36 +42,41 @@ function sendRpc(
ctx: RequestEnvelope,
timeoutMs: number,
): Promise<unknown> {
// Answer now rather than in timeoutMs. A closed socket cannot deliver the frame, so waiting
// would make every request to a downed teapot hang for the full timeout (30s by default)
// before failing anyway — the caller pays for a verdict already known.
if (!socket.isOpen) {
return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`));
}
return new Promise((resolveCall, rejectCall) => {
// 504: the link is alive but the teapot did not answer in time — a gateway timeout,
// which is a different operational story from a link that is down.
const timer = setTimeout(() => {
pending.delete(id);
rejectCall(new Error(`mesh rpc timeout: ${name}`));
rejectCall(new HttpError(504, `mesh rpc timeout: ${name}`));
}, timeoutMs);
pending.set(id, { resolve: resolveCall, reject: rejectCall, timer });
ws.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
socket.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
});
}
/** Assemble the client-facing Link once the manifest arrives. */
function buildLink(
ws: any,
pending: Map<string, PendingEntry>,
manifest: Manifest,
connId: string,
timeoutMs: number,
): Link {
function buildLink(socket: WsSocket, pending: Map<string, PendingEntry>, manifest: Manifest, timeoutMs: number): Link {
// ids only need to be unique within this link: `pending` is per-connection, so a
// per-link counter suffices (no module-global sequence, no test-order coupling).
let counter = 0;
return {
manifest,
rpc(kind, name, ctx) {
const id = `${connId}:${counter++}`;
const id = String(counter++);
return sendRpc(ws, pending, id, kind, name, ctx, timeoutMs);
return sendRpc(socket, pending, id, kind, name, ctx, timeoutMs);
},
close() {
ws.close();
socket.close();
},
};
}
@@ -97,50 +100,160 @@ function settleRpcResponse(
}
}
/** Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest arrives. */
export function connectLink(args: { url: string; secret: string; timeoutMs?: number; bus?: Bus }): Promise<Link> {
const timeoutMs = args.timeoutMs ?? 30_000;
const WS = loadWs();
const ws = new WS(args.url);
const pending = new Map<string, PendingEntry>();
const connId = `c${connSeq++}`;
let manifest: Manifest | undefined;
/** Default gap between heartbeat pings. Two missed rounds close the link. */
const HEARTBEAT_MS = 15_000;
return new Promise<Link>((resolve, reject) => {
const connectTimer = setTimeout(() => {
ws.close();
reject(new Error(`mesh connect timeout: ${args.url}`));
}, timeoutMs);
/**
* Close code for a link we hang up on because its teapot went quiet.
*
* Not 1011: a *client* may only send 1000 or 3000-4999 — anything else throws `invalid code`,
* and our neutral close swallows throws, so a reserved code would leave the link open while
* looking like it closed. 4000+ is the application range, so 4011 mirrors 1011's meaning.
*/
const CLOSE_HEARTBEAT_TIMEOUT = 4011;
ws.on('open', () => ws.send(encode({ type: 'hello', secret: args.secret })));
ws.on('error', (error: unknown) => reject(error));
ws.on('close', () => {
clearTimeout(connectTimer);
args.bus?.emit('mesh:disconnect', { name: args.url });
rejectAllPending(pending, 'mesh link closed');
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`));
});
/**
* Pings the teapot on an interval and closes the link if a round goes unanswered.
*
* A TCP connection can die without either side noticing — a dropped route, a killed container,
* a NAT timing out — leaving the socket "open" with nobody home. Without this, a teacup only
* learns on the next request, which pays the full rpc timeout before failing. Closing the socket
* turns that into an immediate 503 from the dead-link guard, and emits `mesh:disconnect`.
*
* The interval is unref'd, so a heartbeat never holds the process open by itself.
*/
function startHeartbeat(socket: WsSocket, everyMs: number): { stop: () => void; markAlive: () => void } {
let answered = true;
ws.on('message', (data: unknown) => {
const timer = setInterval(() => {
if (!answered) {
socket.close(CLOSE_HEARTBEAT_TIMEOUT, 'mesh heartbeat timeout'); // aborts -> disconnect + reject pending
return;
}
answered = false;
socket.send(encode({ type: 'ping' }));
}, everyMs);
timer.unref?.();
return {
stop: () => clearInterval(timer),
markAlive: () => {
answered = true;
},
};
}
/** Handle for the in-flight handshake, so the frame loop can settle `connectLink`'s promise. */
interface Handshake {
url: string;
socket: WsSocket;
pending: Map<string, PendingEntry>;
timeoutMs: number;
bus?: Bus;
resolve: (link: Link) => void;
reject: (error: unknown) => void;
onManifest: () => void;
onPong: () => void;
}
/** Settle the handshake from a `manifest` frame: refuse a version mismatch, else build the Link. */
function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handshake): void {
if (frame.v !== MESH_PROTOCOL_VERSION) {
hs.socket.close();
hs.reject(
new Error(
`mesh protocol version mismatch at ${hs.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`,
),
);
return;
}
hs.onManifest();
hs.bus?.emit('mesh:connect', { name: hs.url });
hs.resolve(buildLink(hs.socket, hs.pending, { scopes: frame.scopes, routes: frame.routes }, hs.timeoutMs));
}
/** Consume the link's inbound frames until it closes, settling the handshake then each RPC. */
async function readFrames(hs: Handshake): Promise<void> {
for await (const data of hs.socket.inbound) {
let frame: Frame;
try {
frame = decode(String(data));
} catch {
return;
continue; // undecodable frames are ignored
}
if (frame.type === 'manifest') {
manifest = { scopes: frame.scopes, routes: frame.routes };
if (frame.type === 'manifest') settleManifest(frame, hs);
else if (frame.type === 'pong') hs.onPong();
else if (frame.type === 'rpc-res') settleRpcResponse(hs.pending, frame, hs.bus);
}
}
/**
* Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest
* arrives. `Ctor` is injectable to exercise both client implementations on a single runtime.
*/
export function connectLink(args: {
url: string;
secret: string;
timeoutMs?: number;
heartbeatMs?: number;
bus?: Bus;
Ctor?: SocketCtor;
}): Promise<Link> {
const timeoutMs = args.timeoutMs ?? 30_000;
const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined);
const pending = new Map<string, PendingEntry>();
let manifest = false;
let heartbeat: { stop: () => void; markAlive: () => void } | undefined;
return new Promise<Link>((resolve, reject) => {
const connectTimer = setTimeout(() => {
socket.close();
reject(new Error(`mesh connect timeout: ${args.url}`));
}, timeoutMs);
const hs: Handshake = {
url: args.url,
socket,
pending,
timeoutMs,
bus: args.bus,
resolve,
reject,
onManifest: () => {
manifest = true;
clearTimeout(connectTimer);
args.bus?.emit('mesh:connect', { name: args.url });
resolve(buildLink(ws, pending, manifest, connId, timeoutMs));
return;
}
// started only once authenticated: an unauthenticated peer should not be pinging
heartbeat = startHeartbeat(socket, args.heartbeatMs ?? HEARTBEAT_MS);
},
onPong: () => heartbeat?.markAlive(),
};
if (frame.type === 'rpc-res') {
settleRpcResponse(pending, frame, args.bus);
}
opened.then(
() => socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret })),
(error) => reject(error),
);
// abort fires on close *and* on error (see eventSocket), covering both paths the raw
// 'close' listener used to: a refused handshake and a dropped link.
socket.abort.addEventListener(
'abort',
() => {
clearTimeout(connectTimer);
heartbeat?.stop();
args.bus?.emit('mesh:disconnect', { name: args.url });
rejectAllPending(pending, `mesh link to ${args.url} is down`);
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`));
},
{ once: true },
);
void readFrames(hs).catch(() => {
/* inbound failed; the abort listener above reports it */
});
});
}
+72 -11
View File
@@ -1,3 +1,11 @@
/**
* Version of the mesh wire protocol. Peers are separate processes on separate deploy
* cadences — possibly on different runtimes — so the frame shapes are a contract between
* green-tea versions, not an internal detail. Bump on any breaking frame change; peers
* refuse each other on mismatch rather than misparsing downstream.
*/
export const MESH_PROTOCOL_VERSION = 1;
/** Serialized request context sent across the mesh for a scope or route RPC. */
export interface RequestEnvelope {
method: string;
@@ -23,28 +31,81 @@ export interface Manifest {
routes: RouteEntry[];
}
/** Discriminated union of every message on the mesh wire. */
/**
* Discriminated union of every message on the mesh wire. The handshake frames carry `v`.
*
* `ping`/`pong` are application frames rather than WebSocket protocol pings on purpose: the `ws`
* package exposes `ws.ping()`, but the platform `WebSocket` that Deno and Bun provide does not,
* so a protocol-level heartbeat could not work on every runtime mesh claims to support.
*/
export type Frame =
| { type: 'hello'; secret: string }
| { type: 'manifest'; scopes: ScopeEntry[]; routes: RouteEntry[] }
| { type: 'hello'; v: number; secret: string }
| { type: 'manifest'; v: number; scopes: ScopeEntry[]; routes: RouteEntry[] }
| { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope }
| { type: 'rpc-res'; id: string; ok: true; result: unknown }
| { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } };
| { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }
| { type: 'ping' }
| { type: 'pong' };
const TYPES = new Set(['hello', 'manifest', 'rpc-req', 'rpc-res']);
const isString = (value: unknown): value is string => typeof value === 'string';
const isNumber = (value: unknown): boolean => typeof value === 'number';
const isObject = (value: unknown): boolean => typeof value === 'object' && value !== null;
/** Rejects a frame whose fields don't match its `type` tag. `bad` always throws. */
type ShapeCheck = (frame: Record<string, unknown>, bad: (why: string) => never) => void;
/**
* Field checks per frame type. `decode` is the mesh's trust boundary: past it, frames are fed
* straight to the scope/route resolvers, so a bad shape must die here rather than surface as a
* confusing failure downstream. A new frame type must add a row — the compiler fails until it does.
*/
const SHAPE: Record<Frame['type'], ShapeCheck> = {
hello: (frame, bad) => {
if (!isNumber(frame.v)) bad('missing protocol version');
if (!isString(frame.secret)) bad('secret must be a string');
},
manifest: (frame, bad) => {
if (!isNumber(frame.v)) bad('missing protocol version');
if (!Array.isArray(frame.scopes) || !Array.isArray(frame.routes)) bad('scopes and routes must be arrays');
},
'rpc-req': (frame, bad) => {
if (!isString(frame.id)) bad('id must be a string');
if (frame.kind !== 'scope' && frame.kind !== 'route') bad("kind must be 'scope' or 'route'");
if (!isString(frame.name)) bad('name must be a string');
if (!isObject(frame.ctx)) bad('ctx must be an object');
},
'rpc-res': (frame, bad) => {
if (!isString(frame.id)) bad('id must be a string');
if (typeof frame.ok !== 'boolean') bad('ok must be a boolean');
if (frame.ok === false && !isObject(frame.error)) bad('error must be an object when ok is false');
},
ping: () => {
/* the tag is the whole frame */
},
pong: () => {
/* the tag is the whole frame */
},
};
/** Serialize a frame to a JSON wire string. */
export function encode(frame: Frame): string {
return JSON.stringify(frame);
}
/** Parse a wire string into a frame, throwing if the `type` tag is unknown. */
/** Parse a wire string into a frame, throwing if the `type` tag is unknown or the shape is malformed. */
export function decode(json: string): Frame {
const parsed = JSON.parse(json) as { type?: unknown };
const parsed = JSON.parse(json) as Record<string, unknown>;
const type = parsed.type;
// own-property check, not a bare lookup: `type` is peer-controlled, and SHAPE['constructor']
// would otherwise resolve up the prototype chain to a truthy non-check.
const known = isString(type) && Object.prototype.hasOwnProperty.call(SHAPE, type);
const check = known ? SHAPE[type as Frame['type']] : undefined;
if (typeof parsed.type !== 'string' || !TYPES.has(parsed.type)) {
throw new Error(`unknown frame type: ${String(parsed.type)}`);
}
if (!check) throw new Error(`unknown frame type: ${String(type)}`);
return parsed as Frame;
check(parsed, (why) => {
throw new Error(`malformed ${String(type)} frame: ${why}`);
});
return parsed as unknown as Frame;
}
+102 -31
View File
@@ -1,8 +1,20 @@
import crypto from 'crypto';
// node: prefix, not a bare specifier: this is the mesh auth path, and on Deno/Bun a bare
// 'crypto' leans on node-compat resolution heuristics. Buffer + timingSafeEqual resolve
// under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec).
import crypto from 'node:crypto';
import type { Bus } from '../bus';
import type { WsSocket } from '../http/ws-core';
import type { ResponseShape } from '../pipeline';
import { isHttpError } from '../signals';
import { encode, decode, type Manifest, type RequestEnvelope, type RouteEntry, type Frame } from './protocol';
import {
encode,
decode,
MESH_PROTOCOL_VERSION,
type Manifest,
type RequestEnvelope,
type RouteEntry,
type Frame,
} from './protocol';
/** WebSocket path where a teapot exposes its mesh control channel. */
export const MESH_CONTROL_PATH = '/__mesh__/control';
@@ -49,20 +61,46 @@ function notExported(name: string): Error {
return error;
}
/** Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch. */
function handleHandshake(ws: any, frame: Frame, deps: MeshControlDeps): boolean {
if (frame.type === 'hello' && safeEqual(frame.secret, deps.secret)) {
ws.send(encode({ type: 'manifest', scopes: deps.manifest.scopes, routes: deps.manifest.routes }));
/**
* Validate an unauthenticated hello frame; reply with the manifest on success or close on mismatch.
* The version is checked *before* the secret: a skewed peer is not an auth failure, and telling it
* "wrong secret" would send its operator hunting the wrong bug.
*/
function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps): boolean {
if (frame.type !== 'hello') {
socket.close(1008);
return false;
}
if (frame.v !== MESH_PROTOCOL_VERSION) {
socket.close(
1008,
`mesh protocol version mismatch: peer speaks v${frame.v}, this teapot speaks v${MESH_PROTOCOL_VERSION}`,
);
return false;
}
if (!safeEqual(frame.secret, deps.secret)) {
socket.close(1008);
return false;
}
socket.send(
encode({
type: 'manifest',
v: MESH_PROTOCOL_VERSION,
scopes: deps.manifest.scopes,
routes: deps.manifest.routes,
}),
);
deps.bus?.emit('mesh:connect', { name: 'teapot' });
return true;
}
ws.close(1008);
return false;
}
/** Resolve an authenticated rpc-req against the exported scopes/routes, enforcing export gating. */
function resolveRpc(
frame: RpcReqFrame,
@@ -85,7 +123,7 @@ function resolveRpc(
/** Serve one authenticated rpc-req: resolve it and frame the ok/error response back to the peer. */
async function handleRpc(
ws: any,
socket: WsSocket,
frame: RpcReqFrame,
deps: MeshControlDeps,
exportedScopes: Set<string>,
@@ -96,44 +134,77 @@ async function handleRpc(
try {
const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes);
ws.send(encode({ type: 'rpc-res', id, ok: true, result }));
socket.send(encode({ type: 'rpc-res', id, ok: true, result }));
} catch (err) {
const status = isHttpError(err) ? err.status : ((err as any)?.status ?? 500);
deps.bus?.emit('mesh:rpc:error', { name, error: err });
ws.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } }));
socket.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } }));
}
}
/** Build a WebSocket handler that authenticates peers and serves scope/route RPCs from the manifest. */
export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (ws: any) => void } {
const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token));
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
return {
path: MESH_CONTROL_PATH,
handle(ws: any) {
/** Drive one control connection to completion: handshake, then serve RPCs until the socket ends. */
async function serveFrames(
socket: WsSocket,
deps: MeshControlDeps,
exportedScopes: Set<string>,
exportedRoutes: Set<string>,
): Promise<void> {
let authed = false;
ws.on('message', async (data: unknown) => {
try {
for await (const data of socket.inbound) {
let frame: Frame;
try {
frame = decode(String(data));
} catch {
return;
continue; // undecodable frames are ignored, as before
}
if (!authed) {
authed = handleHandshake(ws, frame, deps);
return;
authed = handleHandshake(socket, frame, deps);
continue;
}
if (frame.type !== 'rpc-req') return;
// answered only after the handshake: an unauthenticated peer gets no signal at all
if (frame.type === 'ping') {
socket.send(encode({ type: 'pong' }));
continue;
}
await handleRpc(ws, frame, deps, exportedScopes, exportedRoutes);
});
ws.on('close', () => deps.bus?.emit('mesh:disconnect', { name: 'teapot' }));
if (frame.type !== 'rpc-req') continue;
// deliberately not awaited: RPCs overlap, exactly as they did under the `ws.on('message')`
// listener. The id-keyed `pending` map on the peer exists to allow in-flight concurrency —
// awaiting here would silently serialize every mesh call.
void handleRpc(socket, frame, deps, exportedScopes, exportedRoutes);
}
} catch {
/* socket failed; the disconnect emit below is the same signal a clean close gives */
} finally {
deps.bus?.emit('mesh:disconnect', { name: 'teapot' });
}
}
/** Build a control handler that authenticates peers and serves scope/route RPCs from the manifest. */
export function createMeshControl(deps: MeshControlDeps): {
path: string;
handle: (socket: WsSocket) => Promise<void>;
} {
const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token));
const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`));
return {
path: MESH_CONTROL_PATH,
/**
* Resolves when the connection ends, mirroring `runWsConnection` — so `app.upgrade` can await
* the control channel's lifetime the same way it awaits a regular ws route's.
* `channel` is fan-out and subscribes when the async iterator is created, which `for await`
* does synchronously, so the loop is live before any frame can arrive.
*/
handle(socket: WsSocket): Promise<void> {
return serveFrames(socket, deps, exportedScopes, exportedRoutes);
},
};
}
+48 -2
View File
@@ -5,6 +5,11 @@ export type Ctor = new (...args: any[]) => any;
/** Serializes a handler's return value into an HTTP response envelope. */
export type TransformerFn = (value: unknown) => { status?: number; headers?: Record<string, string>; body: string };
/** Metadata attached by `@Html`: optional file path and whether it is a template. */
export interface HtmlMeta {
path?: string;
template?: boolean;
}
/** Metadata attached by `@Provider`: what it provides, what it needs, and its visibility. */
export interface ProviderMeta {
provides: string;
@@ -20,7 +25,7 @@ export interface StepMeta {
export: boolean;
}
/** HTTP verbs supported by the route decorators. */
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
/** Wire transport a route responds with. */
export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws';
/** Metadata attached by a route decorator to a single handler method. */
@@ -31,6 +36,8 @@ export interface RouteMeta {
transport: Transport;
export: boolean;
duplicates?: 'array' | 'last';
maxBodyBytes?: number;
maxParts?: number;
}
/** Options accepted by the `@Module` decorator. */
export interface ModuleOptions {
@@ -47,6 +54,7 @@ const K = {
routes: Symbol('gt:routes'),
module: Symbol('gt:module'),
transformer: Symbol('gt:transformer'),
html: Symbol('gt:html'),
};
/** Marks a class as a provider: a lazily-built dependency addressable by its `provides` key. */
@@ -93,7 +101,10 @@ export function Route(prefix: string): ClassDecorator {
}
function routeDecorator(method: HttpMethod, transport: Transport) {
return (path: string, opts?: { export?: boolean; duplicates?: 'array' | 'last' }): MethodDecorator =>
return (
path: string,
opts?: { export?: boolean; duplicates?: 'array' | 'last'; maxBodyBytes?: number; maxParts?: number },
): MethodDecorator =>
(target, propertyKey) => {
const ctor = target.constructor;
const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [];
@@ -104,6 +115,8 @@ function routeDecorator(method: HttpMethod, transport: Transport) {
transport,
export: opts?.export ?? false,
duplicates: opts?.duplicates,
maxBodyBytes: opts?.maxBodyBytes,
maxParts: opts?.maxParts,
});
Reflect.defineMetadata(K.routes, routes, ctor);
};
@@ -111,6 +124,8 @@ function routeDecorator(method: HttpMethod, transport: Transport) {
/** Declares a buffered `GET` route. */
export const Get = routeDecorator('GET', 'buffer');
/** Declares a buffered `HEAD` route. */
export const Head = routeDecorator('HEAD', 'buffer');
/** Declares a buffered `POST` route. */
export const Post = routeDecorator('POST', 'buffer');
/** Declares a buffered `PUT` route. */
@@ -119,6 +134,8 @@ export const Put = routeDecorator('PUT', 'buffer');
export const Patch = routeDecorator('PATCH', 'buffer');
/** Declares a buffered `DELETE` route. */
export const Delete = routeDecorator('DELETE', 'buffer');
/** Declares a buffered `OPTIONS` route. */
export const Options = routeDecorator('OPTIONS', 'buffer');
/** Declares a `GET` route streamed as Server-Sent Events. */
export const Sse = routeDecorator('GET', 'sse');
/** Declares a `GET` route whose transport is content-negotiated at request time. */
@@ -140,6 +157,35 @@ export function Module(opts: ModuleOptions): ClassDecorator {
};
}
/**
* Marks a buffered GET/POST handler as serving HTML. Bare `@Html` sends the handler's string return as
* `text/html`. `@Html('file.html')` serves that file (return ignored). `@Html('file.html', { template: true })`
* renders the file with the handler's returned data. Placement is validated at boot (buffered GET/POST only).
*/
export function Html(path: string, opts?: { template?: boolean }): MethodDecorator;
export function Html(target: object, propertyKey: string | symbol): void;
export function Html(a: unknown, b?: unknown): MethodDecorator | void {
if (typeof a !== 'string') {
// Bare usage: TS calls (prototype, propertyKey, descriptor?).
Reflect.defineMetadata(K.html, {}, (a as { constructor: Ctor }).constructor, String(b));
return;
}
const path = a;
const opts = b as { template?: boolean } | undefined;
return (target, propertyKey) => {
const meta: HtmlMeta = { path, template: opts?.template };
Reflect.defineMetadata(K.html, meta, (target as { constructor: Ctor }).constructor, String(propertyKey));
};
}
/** Reads the `@Html` metadata registered for a handler method, if any. */
export function getHtmlMeta(cls: Ctor, methodName: string): HtmlMeta | undefined {
return Reflect.getMetadata(K.html, cls, methodName);
}
/** Reads the `@Provider` metadata off a class, if any. */
export function getProviderMeta(cls: Ctor): ProviderMeta | undefined {
return Reflect.getMetadata(K.provider, cls);
+135
View File
@@ -0,0 +1,135 @@
import type { ArgSpec } from './params';
import type { Transport } from './metadata';
import { compilePattern } from './http/router';
/** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */
export interface OpenApiRoute {
method: string;
pattern: string;
transport: Transport;
args: ArgSpec[];
}
/** `info` block overrides for the generated document. */
export interface OpenApiInfo {
title?: string;
version?: string;
description?: string;
}
/** A generated OpenAPI 3.1 document (structural: paths, params, and error responses; body/response schemas are generic). */
export interface OpenApiDoc {
openapi: string;
info: { title: string; version: string; description?: string };
paths: Record<string, Record<string, unknown>>;
}
type Parameter = {
name: string;
in: 'path' | 'query' | 'header';
required: boolean;
schema: { type: 'string'; pattern?: string };
};
/** Converts a route pattern to an OpenAPI path template: `/users/:id` → `/users/{id}`, `:rest*` → `{rest}`. */
function templatePath(pattern: string): string {
const segments = compilePattern(pattern).segments.map((segment) =>
segment.kind === 'static' ? segment.value : `{${segment.name}}`,
);
return `/${segments.join('/')}`;
}
/** Every `:name` (and `:name*`) segment of a pattern becomes a required path parameter. */
function pathParams(pattern: string): Parameter[] {
return compilePattern(pattern).segments.flatMap((segment): Parameter[] => {
if (segment.kind === 'static') return [];
return [
{
name: segment.name,
in: 'path',
required: true,
schema: {
type: 'string',
...(segment.kind === 'param' && segment.constraintSource ? { pattern: segment.constraintSource } : {}),
},
},
];
});
}
/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */
function argParams(args: ArgSpec[]): Parameter[] {
const params: Parameter[] = [];
for (const arg of args) {
if (arg.source !== 'query' && arg.source !== 'headers') continue;
const location = arg.source === 'query' ? 'query' : 'header';
const names = arg.keys ?? (arg.key ? [arg.key] : []);
for (const name of names) params.push({ name, in: location, required: false, schema: { type: 'string' } });
}
return params;
}
/**
* The documented `200` per transport. `ws` is absent by construction — ws routes are not
* HTTP request/response and are filtered out before this runs. A new transport adds a row,
* and the compiler fails until it does.
*/
type HttpTransport = Exclude<Transport, 'ws'>;
const TRANSPORT_OK: Record<HttpTransport, Record<string, unknown>> = {
buffer: { description: 'OK', content: { 'application/json': { schema: {} } } },
sse: { description: 'Event stream', content: { 'text/event-stream': {} } },
ndjson: { description: 'Stream', content: { 'application/x-ndjson': {} } },
negotiate: { description: 'Stream', content: { 'application/x-ndjson': {} } },
};
/** The success/error responses documented for a route, keyed by transport and whether any input is validated. */
function responses(route: OpenApiRoute, transport: HttpTransport): Record<string, unknown> {
const result: Record<string, unknown> = { '200': TRANSPORT_OK[transport] };
if (route.args.some((arg) => arg.schema)) result['422'] = { description: 'Validation failed' };
result['500'] = { description: 'Internal Server Error' };
return result;
}
/** Builds a single OpenAPI operation object for a route. */
function operation(route: OpenApiRoute, transport: HttpTransport): Record<string, unknown> {
const parameters = [...pathParams(route.pattern), ...argParams(route.args)];
const op: Record<string, unknown> = { responses: responses(route, transport) };
if (parameters.length) op.parameters = parameters;
if (route.args.some((arg) => arg.source === 'body')) {
op.requestBody = { content: { 'application/json': { schema: {} } } };
}
return op;
}
/**
* Projects the route graph into a structural OpenAPI 3.1 document: paths, methods, path/query/header
* parameters, which routes take a body, and the systematic error responses. Body and response *schemas*
* are generic — Standard Schema doesn't expose JSON Schema (see the roadmap). WebSocket routes are omitted.
*/
export function buildOpenApi(routes: OpenApiRoute[], info?: OpenApiInfo): OpenApiDoc {
const paths: Record<string, Record<string, unknown>> = {};
for (const route of routes) {
const transport = route.transport;
if (transport === 'ws') continue; // not an HTTP request/response; narrows to HttpTransport below
const path = templatePath(route.pattern);
(paths[path] ??= {})[route.method.toLowerCase()] = operation(route, transport);
}
return {
openapi: '3.1.0',
info: {
title: info?.title ?? 'green-tea API',
version: info?.version ?? '0.0.0',
...(info?.description ? { description: info.description } : {}),
},
paths,
};
}
+55 -11
View File
@@ -1,7 +1,8 @@
import { Bus } from './bus';
import { errorToResponse } from './transformers';
import { renderError, type ErrorRenderer } from './transformers';
import { isAsyncIterable } from './channel';
import type { TransformerFn } from './metadata';
import type { TransformerFn, Transport } from './metadata';
import { TransportMismatchError } from './signals';
/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
export interface PipelineStep {
@@ -22,11 +23,42 @@ export interface StreamResult {
/** The outcome of {@link runPipeline}: either a buffered response or a stream. */
export type PipelineResult = ResponseShape | StreamResult;
/** What a route's declared transport requires its handler to return. */
export type ReturnContract = 'buffer' | 'stream' | 'either';
/** Return contract per transport. A new transport just adds a row. `ws` never reaches runPipeline (filtered earlier). */
export const TRANSPORT_RETURN: Record<Transport, ReturnContract> = {
buffer: 'buffer',
sse: 'stream',
ndjson: 'stream',
ws: 'stream',
negotiate: 'either',
};
/** Type guard narrowing a {@link PipelineResult} to a {@link StreamResult}. */
export function isStreamResult(result: PipelineResult): result is StreamResult {
return 'stream' in result;
}
/**
* Run `steps` in order, merging each step's output into the context and emitting
* `request:step:enter`/`leave` on the bus. The single place steps are executed — every
* transport (HTTP, ws, mesh) goes through here so observability is uniform by construction.
*/
export async function runSteps(steps: PipelineStep[], seed: Record<string, unknown>, bus: Bus): Promise<any> {
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
const context: any = seed;
for (const step of steps) {
bus.emit('request:step:enter', { name: step.name, scope: step.origin });
const output = await step.run(context);
Object.assign(context, output);
bus.emit('request:step:leave', { name: step.name, scope: step.origin });
}
return context;
}
/**
* Run `steps` in order over a context seeded from `seed`, then invoke `handler`.
* An async-iterable handler result becomes a stream; anything else is run through `transformer`.
@@ -38,25 +70,37 @@ export async function runPipeline(args: {
transformer: TransformerFn;
seed: Record<string, unknown>;
bus: Bus;
transport: Transport;
onError?: ErrorRenderer;
}): Promise<PipelineResult> {
const { steps, handler, transformer, seed, bus } = args;
const { steps, handler, transformer, seed, bus, transport, onError } = args;
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
let context: any = { ...seed };
try {
for (const step of steps) {
bus.emit('request:step:enter', { name: step.name, scope: step.origin });
const output = await step.run(context);
context = { ...context, ...output };
bus.emit('request:step:leave', { name: step.name, scope: step.origin });
context = await runSteps(steps, context, bus);
const result = await handler(context);
const streaming = isAsyncIterable(result);
const contract = TRANSPORT_RETURN[transport];
if (contract === 'buffer' && streaming) {
throw new TransportMismatchError(transport, 'stream', context.req as { method?: string; url?: string });
}
const result = await handler(context);
if (isAsyncIterable(result)) return { stream: result }; // stream path: transformer bypassed
if (contract === 'stream' && !streaming) {
throw new TransportMismatchError(transport, 'value', context.req as { method?: string; url?: string });
}
if (streaming) return { stream: result }; // stream path: transformer bypassed
const transformed = transformer(result);
return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body };
} catch (error) {
bus.emit('request:step:error', { name: 'pipeline', error });
return errorToResponse(error);
const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> };
return renderError(
error,
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
onError,
);
}
}
+20 -2
View File
@@ -1,11 +1,16 @@
import type { StandardIssue } from './standard-schema';
/** Error carrying an HTTP status code and optional response body. Base of all signals. */
/**
* Error carrying an HTTP status code and optional response body. Base of all signals.
* A subclass needing response headers (e.g. `location`, `retry-after`) sets `headers`
* rather than requiring a special case in the error renderer.
*/
export class HttpError extends Error {
constructor(
readonly status: number,
message?: string,
readonly body?: unknown,
readonly headers?: Record<string, string>,
) {
super(message ?? `HTTP ${status}`);
this.name = new.target.name;
@@ -36,7 +41,7 @@ export class NotModified extends HttpError {
/** 302 redirect to `location`. */
export class Redirect extends HttpError {
constructor(readonly location: string) {
super(302);
super(302, undefined, undefined, { location });
}
}
@@ -50,6 +55,19 @@ export class ValidationError extends HttpError {
}
}
/** Thrown when a handler's return value contradicts its route's declared transport (a programming error). */
export class TransportMismatchError extends HttpError {
constructor(transport: string, got: 'stream' | 'value', req?: { method?: string; url?: string }) {
const where = req?.method && req?.url ? ` (${req.method} ${req.url})` : '';
const expected = got === 'stream' ? 'return a value' : 'return an AsyncIterable';
const fix =
got === 'stream'
? 'buffered routes (@Get/@Head/@Post/@Put/@Patch/@Delete/@Options) must return a value — to stream, declare @Sse, @Stream, or @Ws'
: 'streaming routes (@Sse/@Ws) must return an AsyncIterable (e.g. an async generator or channel())';
super(500, `Transport '${transport}'${where} must ${expected}, but the handler returned a ${got}. ${fix}.`);
}
}
/** Type guard: true if `error` is an {@link HttpError}. */
export function isHttpError(error: unknown): error is HttpError {
return error instanceof HttpError;
+34 -6
View File
@@ -1,7 +1,27 @@
import { isHttpError, Redirect, ValidationError } from './signals';
import { isHttpError, ValidationError } from './signals';
import type { TransformerFn } from './metadata';
import { flattenPath } from './standard-schema';
/** A ready-to-send HTTP response. */
export interface ErrorResponse {
status: number;
headers: Record<string, string>;
body: string;
}
/** The request a {@link ErrorRenderer} is given, to inspect (e.g. `headers.accept`) while rendering. */
export interface ErrorRequest {
method: string;
url: string;
headers: Record<string, string | string[] | undefined>;
}
/**
* User hook to render errors however you like (HTML, custom JSON, RFC 7807, …).
* Return a response to take over, or `undefined`/`void` to fall back to the default JSON.
*/
export type ErrorRenderer = (error: unknown, req: ErrorRequest) => ErrorResponse | undefined | void;
/** Default transformer: serialize a handler's return value as a JSON `200` response. */
export const JsonTransformer: TransformerFn = (value) => ({
status: 200,
@@ -9,8 +29,11 @@ export const JsonTransformer: TransformerFn = (value) => ({
body: JSON.stringify(value),
});
/** Map a thrown value to a JSON error response (422 for validation, HttpError status, else 500). */
export function errorToResponse(error: unknown): { status: number; headers: Record<string, string>; body: string } {
/**
* Map a thrown value to a JSON error response (422 for validation, `HttpError` status, else 500).
* An `HttpError` carrying a `body` renders that payload instead of the default `{ error: message }`.
*/
export function errorToResponse(error: unknown): ErrorResponse {
if (error instanceof ValidationError) {
return {
status: 422,
@@ -24,9 +47,9 @@ export function errorToResponse(error: unknown): { status: number; headers: Reco
}
if (isHttpError(error)) {
const headers: Record<string, string> = { 'content-type': 'application/json' };
if (error instanceof Redirect) headers.location = error.location;
return { status: error.status, headers, body: JSON.stringify({ error: error.message }) };
const headers = { 'content-type': 'application/json', ...error.headers };
const payload = error.body !== undefined ? error.body : { error: error.message };
return { status: error.status, headers, body: JSON.stringify(payload) };
}
return {
@@ -35,3 +58,8 @@ export function errorToResponse(error: unknown): { status: number; headers: Reco
body: JSON.stringify({ error: 'Internal Server Error' }),
};
}
/** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */
export function renderError(error: unknown, req: ErrorRequest, onError?: ErrorRenderer): ErrorResponse {
return onError?.(error, req) ?? errorToResponse(error);
}
+147
View File
@@ -0,0 +1,147 @@
// src/views.ts — HTML views: built-in templating, content-type map, and boot-time builders.
// fs/path are lazy-required inside functions so the barrel stays edge-loadable (workerd has no filesystem).
import type { TransformerFn } from './metadata';
import type { HtmlMeta } from './metadata';
/** Escape the five HTML-significant characters so interpolated data can't inject markup. */
export function escapeHtml(s: string): string {
const map: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
return s.replace(/[&<>"']/g, (c) => map[c]);
}
function stringify(v: unknown): string {
return v === null || v === undefined ? '' : String(v);
}
/**
* Minimal built-in template engine: `{{ key }}` interpolates HTML-escaped, `{{{ key }}}` raw,
* `{{ a.b }}` walks nested keys, a missing key renders empty. No loops/conditionals/partials.
*/
export function render(source: string, data: unknown): string {
const lookup = (key: string): unknown =>
key.split('.').reduce<any>((obj, k) => (obj === null || obj === undefined ? undefined : obj[k]), data);
return source
.replace(/\{\{\{\s*([\w.]+)\s*\}\}\}/g, (_, key) => stringify(lookup(key)))
.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, key) => escapeHtml(stringify(lookup(key))));
}
const CONTENT_TYPES: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.ico': 'image/x-icon',
'.woff2': 'font/woff2',
'.txt': 'text/plain; charset=utf-8',
};
/** Content-type for a file extension (case-insensitive, leading dot); unknown → `application/octet-stream`. */
export function contentTypeFor(ext: string): string {
return CONTENT_TYPES[ext.toLowerCase()] ?? 'application/octet-stream';
}
const HTML_HEADERS = { 'content-type': 'text/html; charset=utf-8' } as const;
/** Boot-time context for building `@Html` transformers: the views base dir and an optional BYO engine. */
export interface ViewsContext {
views?: string;
viewEngine?: (source: string, data: unknown) => string;
}
/** Reads a view file at boot (lazy fs). Relative paths resolve against `views` (default cwd); absolute as-is.
* node:fs/node:path are loaded lazily so importing the barrel stays edge/workerd-safe
* (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes. */
function readViewFile(views: string | undefined, path: string): string {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodePath = require('node:path') as typeof import('node:path');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const fs = require('node:fs') as typeof import('node:fs');
const base = views ?? process.cwd();
const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path);
try {
return fs.readFileSync(full, 'utf8');
} catch (err) {
throw new Error(
`@Html('${path}') could not read '${full}' — on a runtime without a filesystem (edge), return a string from @Html instead. (${(err as Error).message})`,
);
}
}
/** A static-file hit: the raw bytes and the content-type to send. */
export interface StaticHit {
body: Buffer;
contentType: string;
}
/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */
export type StaticResolver = (urlPath: string) => Promise<StaticHit | undefined>;
/**
* Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at
* boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss.
*/
export function buildStaticResolver(root: string | true): StaticResolver {
let fs: typeof import('node:fs');
let nodePath: typeof import('node:path');
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
fs = require('node:fs');
// eslint-disable-next-line @typescript-eslint/no-require-imports
nodePath = require('node:path');
} catch {
throw new Error(
'`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.',
);
}
const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root);
return async (urlPath) => {
let rel: string;
try {
rel = decodeURIComponent(urlPath.split('?')[0]);
} catch {
return undefined;
}
if (rel === '' || rel.endsWith('/')) rel += 'index.html';
const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel));
if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard
try {
const stat = await fs.promises.stat(full);
const target = stat.isDirectory() ? nodePath.join(full, 'index.html') : full;
const body = await fs.promises.readFile(target);
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
} catch {
return undefined;
}
};
}
/** Turns `@Html` metadata into a response transformer at boot. String mode is fs-free; path/template modes read+cache the file. */
export function buildHtmlTransformer(meta: HtmlMeta, ctx: ViewsContext): TransformerFn {
if (!meta.path) {
return (value) => ({ status: 200, headers: { ...HTML_HEADERS }, body: String(value) });
}
const source = readViewFile(ctx.views, meta.path);
if (meta.template) {
const engine = ctx.viewEngine ?? render;
return (value) => ({ status: 200, headers: { ...HTML_HEADERS }, body: engine(source, value) });
}
return () => ({ status: 200, headers: { ...HTML_HEADERS }, body: source });
}
+96
View File
@@ -0,0 +1,96 @@
import { describe, it, expect } from 'vitest';
import { createApp, Route, Ws, Module, ctx, Step, needs } from '../src/index';
import { channel } from '../src/channel';
import type { WsSocket, WsRequest } from '../src/http/ws-core';
@Route('/rt')
class Rt {
@Ws('/echo')
echo(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `echo:${msg}`;
})();
}
}
@Module({ mountpoint: '/', controllers: [Rt] })
class M {}
const app = createApp({ modules: [M] });
@Step({ provides: 'tag' })
class Tagger {
run() {
return { tag: 't' };
}
}
@Route('/tagged')
class TaggedCtl {
@Ws('/echo')
echo(@needs('tag') tag: string, @ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `${tag}:${msg}`;
})();
}
}
@Module({ mountpoint: '/', steps: [Tagger], controllers: [TaggedCtl] })
class Tagged {}
function fakeSocket() {
const inbound = channel<unknown>();
const ac = new AbortController();
const sent: string[] = [];
const socket: WsSocket = {
inbound,
abort: ac.signal,
isOpen: true,
send: (d) => sent.push(d),
close: () => ac.abort(),
terminate: () => ac.abort(),
};
return { socket, inbound, sent };
}
describe('app.upgrade', () => {
it('routes a matching ws path through the graph', async () => {
const { socket, inbound, sent } = fakeSocket();
const req: WsRequest = { url: '/rt/echo', headers: {}, protocol: 'http', ip: '' };
const run = app.upgrade(req, socket);
// let the handler's async generator start subscribing to `inbound` (channel is fan-out:
// push before subscription is lost) before pushing — a macrotask flushes every pending
// microtask in the upgrade/boot chain first, so this is deterministic, not a sleep-and-hope.
await new Promise((resolve) => setTimeout(resolve, 0));
inbound.push('hi');
inbound.close();
await run;
expect(sent).toEqual(['echo:hi']);
});
it('emits request:step:enter/leave for ws steps, like HTTP routes do', async () => {
const seen: string[] = [];
const logger = (api: any) => {
api.bus.on('request:step:enter', (p: any) => seen.push(`enter:${p.name}`));
api.bus.on('request:step:leave', (p: any) => seen.push(`leave:${p.name}`));
};
const wsApp = createApp({ modules: [Tagged], plugins: [logger] });
const { socket, inbound, sent } = fakeSocket();
const req: WsRequest = { url: '/tagged/echo', headers: {}, protocol: 'http', ip: '' };
const run = wsApp.upgrade(req, socket);
await new Promise((resolve) => setTimeout(resolve, 0));
inbound.push('hi');
inbound.close();
await run;
expect(sent).toEqual(['t:hi']);
expect(seen).toEqual(['enter:tag', 'leave:tag']);
});
it('closes 1008 on an unknown ws path', async () => {
const { socket } = fakeSocket();
let closedCode: number | undefined;
socket.close = (c) => {
closedCode = c;
};
const req: WsRequest = { url: '/rt/nope', headers: {}, protocol: 'http', ip: '' };
await app.upgrade(req, socket);
expect(closedCode).toBe(1008);
});
});
+337 -58
View File
@@ -1,13 +1,17 @@
import 'reflect-metadata';
import { describe, expect, it, test, vi } from 'vitest';
import { Provider, Step, Route, Get, Module, Transformer } from '../src/metadata';
import { Provider, Step, Route, Get, Post, Module, Transformer } from '../src/metadata';
import { JsonTransformer } from '../src/transformers';
import { Unauthorized } from '../src/signals';
import { createApp } from '../src/app';
import { needs, param, query } from '../src/params';
import { needs, param, query, body } from '../src/params';
@Provider({ provides: 'db' })
class Db { provide() { return { db: { find: (t: string) => (t === 'good' ? { id: 'u1' } : null) } }; } }
class Db {
provide() {
return { db: { find: (t: string) => (t === 'good' ? { id: 'u1' } : null) } };
}
}
@Step({ provides: 'user', needs: ['db', 'req'] })
class Auth {
@@ -22,7 +26,9 @@ class Auth {
class UserCtl {
@Get('/:id')
@Transformer(JsonTransformer)
getUser(@needs('user') user: any, @param('id') id: string) { return { id, user }; }
getUser(@needs('user') user: any, @param('id') id: string) {
return { id, user };
}
}
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [UserCtl] })
@@ -34,6 +40,20 @@ test('inspect lists the ordered chain with origins', () => {
expect(lines.map((l) => `${l.kind}:${l.name}`)).toEqual(['provider:db', 'step:user', 'handler:getUser']);
});
test('ready() is a no-op on a non-mesh app, so one protocol works for both', async () => {
// The point: code holding an `App` should not have to know whether it is a mesh app.
// `await app.ready(); app.graph()` is uniform — here it changes nothing and boots nothing.
const app = createApp({ modules: [ApiModule] });
const booted: string[] = [];
app.bus.on('boot:provider:start', (p) => booted.push(p.name));
const before = app.graph().nodes.length;
await app.ready();
expect(app.graph().nodes.length).toBe(before);
expect(booted).toEqual([]);
});
test('a logger plugin observes step:enter without mutating the chain', async () => {
const seen: string[] = [];
const logger = (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name));
@@ -54,7 +74,11 @@ test('a logger plugin observes step:enter without mutating the chain', async ()
test('required provider failure aborts boot', () => {
@Provider({ provides: 'broken' })
class Broken { provide() { throw new Error('cannot connect'); } }
class Broken {
provide() {
throw new Error('cannot connect');
}
}
@Module({ mountpoint: '/x', providers: [Broken], steps: [], controllers: [] })
class BrokenModule {}
@@ -65,9 +89,17 @@ test('required provider failure aborts boot', () => {
test('optional provider failure warns but does not abort boot', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
@Provider({ provides: 'cache', optional: true })
class FlakyCache { provide() { throw new Error('cache down'); } }
class FlakyCache {
provide() {
throw new Error('cache down');
}
}
@Route('/ping')
class PingCtl { @Get('/') ping() { return { ok: true }; } }
class PingCtl {
@Get('/') ping() {
return { ok: true };
}
}
@Module({ mountpoint: '/sys', providers: [FlakyCache], steps: [], controllers: [PingCtl] })
class SysModule {}
@@ -86,7 +118,9 @@ test('handler receives @query value through a live request', async () => {
@Route('/search')
class SearchCtl {
@Get('/')
run(@query('q') q: string) { return { q }; }
run(@query('q') q: string) {
return { q };
}
}
@Module({ mountpoint: '/s', providers: [], steps: [], controllers: [SearchCtl] })
class SearchModule {}
@@ -103,19 +137,31 @@ test('boot fails when a handler needs something nothing provides', () => {
@Route('/things')
class ThingCtl {
@Get('/')
list(@needs('missing') _m: any) { return []; }
list(@needs('missing') _m: any) {
return [];
}
}
@Module({ mountpoint: '/t', providers: [], steps: [], controllers: [ThingCtl] })
class ThingModule {}
expect(() => createApp({ modules: [ThingModule] }))
.toThrow(/handler 'list' needs 'missing'/);
expect(() => createApp({ modules: [ThingModule] })).toThrow(/handler 'list' needs 'missing'/);
});
it('boot error for a misspelled @needs suggests the closest token', () => {
@Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } }
@Route('/u') class Ctl { @Get('/x') x(@needs('usr') u: any) { return { u }; } }
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {}
@Step({ provides: 'user', needs: [] })
class Auth {
run() {
return { user: 1 };
}
}
@Route('/u')
class Ctl {
@Get('/x') x(@needs('usr') u: any) {
return { u };
}
}
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(/did you mean 'user'\?/);
});
@@ -128,10 +174,14 @@ describe('app streaming wiring', () => {
@Route('/')
class Ctl {
@Sse('/ticks') ticks() {
return (async function* () { yield { t: 1 }; yield { t: 2 }; })();
return (async function* () {
yield { t: 1 };
yield { t: 2 };
})();
}
}
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const server = await app.listen(0);
const addr = server.address() as import('net').AddressInfo;
@@ -147,11 +197,15 @@ describe('app streaming wiring', () => {
class Ctl {
@Ws('/echo') echo(@inbound() inc: AsyncIterable<string>) {
const out = channel<string>();
(async () => { for await (const m of inc) out.push(`re:${m}`); out.close(); })();
(async () => {
for await (const m of inc) out.push(`re:${m}`);
out.close();
})();
return out;
}
}
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const server = await app.listen(0);
const addr = server.address() as import('net').AddressInfo;
@@ -161,7 +215,8 @@ describe('app streaming wiring', () => {
const got = new Promise<string>((r) => client.on('message', (d: Buffer) => r(d.toString())));
client.send('yo');
expect(await got).toBe('re:yo');
client.close(); server.close();
client.close();
server.close();
});
});
@@ -169,13 +224,23 @@ describe('per-route subgraph slicing', () => {
it('a route that does not @needs a step does not run it', async () => {
const ran: string[] = [];
@Step({ provides: 'tracked', needs: [] })
class Tracked { run() { ran.push('tracked'); return { tracked: true }; } }
class Tracked {
run() {
ran.push('tracked');
return { tracked: true };
}
}
@Route('/')
class Ctl {
@Get('/needs') needs(@needs('tracked') t: any) { return { t }; }
@Get('/free') free() { return { ok: true }; }
@Get('/needs') needs(@needs('tracked') t: any) {
return { t };
}
@Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] }) class M {}
@Get('/free') free() {
return { ok: true };
}
}
@Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const server = await app.listen(0);
const port = (server.address() as any).port;
@@ -191,10 +256,25 @@ describe('per-route subgraph slicing', () => {
it('a side-effect step (provides: []) added by a plugin runs unconditionally', async () => {
// NB: @Step always provides exactly one token (always sliceable). provides:[] only arises via a plugin's scope.add.
const ran: string[] = [];
const observer = (api: any) => api.scope.add({ kind: 'step', name: 'obs', needs: [], provides: [], run: () => { ran.push('obs'); return {}; } });
const observer = (api: any) =>
api.scope.add({
kind: 'step',
name: 'obs',
needs: [],
provides: [],
run: () => {
ran.push('obs');
return {};
},
});
@Route('/')
class Ctl { @Get('/free') free() { return { ok: true }; } }
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
class Ctl {
@Get('/free') free() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [observer] });
const server = await app.listen(0);
const port = (server.address() as any).port;
@@ -205,12 +285,31 @@ describe('per-route subgraph slicing', () => {
it('an always-run observer step receives its declared needs even when the route does not need them', async () => {
let seen: any;
const observer = (api: any) => api.scope.add({ kind: 'step', name: 'audit', needs: ['user'], provides: [], run: (ctx: any) => { seen = ctx.user; return {}; } });
const observer = (api: any) =>
api.scope.add({
kind: 'step',
name: 'audit',
needs: ['user'],
provides: [],
run: (ctx: any) => {
seen = ctx.user;
return {};
},
});
@Step({ provides: 'user', needs: [] })
class Auth { run() { return { user: { id: 'u1' } }; } }
class Auth {
run() {
return { user: { id: 'u1' } };
}
}
@Route('/')
class Ctl { @Get('/free') free() { return { ok: true }; } } // does NOT @needs('user')
@Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] }) class M {}
class Ctl {
@Get('/free') free() {
return { ok: true };
}
} // does NOT @needs('user')
@Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [observer] });
const server = await app.listen(0);
const port = (server.address() as any).port;
@@ -225,10 +324,26 @@ import { toMermaid as renderMermaid } from '../src/graph-viz';
describe('app.graph / explain', () => {
it('graph() returns nodes (with origin/needs/provides) and routes with their sliced chain', async () => {
@Provider({ provides: 'db' }) class Db { provide() { return { db: 1 }; } }
@Step({ provides: 'user', needs: ['db'] }) class Auth { run() { return { user: 1 }; } }
@Route('/u') class Ctl { @Get('/:id') get(@needs('user') u: any) { return { u }; } }
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] }) class M {}
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: 1 };
}
}
@Step({ provides: 'user', needs: ['db'] })
class Auth {
run() {
return { user: 1 };
}
}
@Route('/u')
class Ctl {
@Get('/:id') get(@needs('user') u: any) {
return { u };
}
}
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const g = app.graph();
expect(g.nodes.find((n) => n.name === 'db')).toMatchObject({ kind: 'provider', origin: 'module:M' });
@@ -239,9 +354,20 @@ describe('app.graph / explain', () => {
});
it('explain() returns the rich chain with origin and a handler entry', async () => {
@Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } }
@Route('/u') class Ctl { @Get('/me') me(@needs('user') u: any) { return { u }; } }
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {}
@Step({ provides: 'user', needs: [] })
class Auth {
run() {
return { user: 1 };
}
}
@Route('/u')
class Ctl {
@Get('/me') me(@needs('user') u: any) {
return { u };
}
}
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const e = app.explain('/api/u/me');
expect(e).toMatchObject({ pattern: '/api/u/me', method: 'GET', transport: 'buffer' });
@@ -253,34 +379,79 @@ describe('app.graph / explain', () => {
describe('devGraph endpoint', () => {
const portOf = (s: any) => (s.address() as any).port;
it('serves /__graph__ as HTML when devGraph:true', async () => {
@Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } }
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
@Route('/u')
class Ctl {
@Get('/me') me() {
return { ok: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], devGraph: true });
const s = await app.listen(0);
const html = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`).then((r) => r.text());
expect(html).toContain('class="mermaid"');
expect(html).toContain('flowchart');
expect(html).toContain('cytoscape');
expect(html).toContain('/api/u/me');
const mmd = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`, { headers: { accept: 'text/plain' } });
expect(mmd.headers.get('content-type')).toContain('text/plain');
expect(await mmd.text()).toContain('flowchart');
s.close();
});
it('does NOT mount /__graph__ without devGraph', async () => {
@Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } }
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
@Route('/u')
class Ctl {
@Get('/me') me() {
return { ok: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const s = await app.listen(0);
const res = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`);
expect(res.status).toBe(404);
s.close();
});
it('serves /__graph__ and /__openapi__ over app.fetch too (runtime-agnostic dev tools)', async () => {
@Route('/u')
class Ctl {
@Get('/me') me() {
return { ok: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], devGraph: true, devOpenapi: true });
const graph = await app.fetch(new Request('http://x/__graph__'));
expect(graph.status).toBe(200);
expect(await graph.text()).toContain('cytoscape');
const openapi = await app.fetch(new Request('http://x/__openapi__'));
expect(openapi.status).toBe(200);
expect(((await openapi.json()) as { openapi: string }).openapi).toBe('3.1.0');
// still absent when the flags are off, on the fetch path too
const off = createApp({ modules: [M] });
expect((await off.fetch(new Request('http://x/__graph__'))).status).toBe(404);
});
});
describe('graceful shutdown', () => {
it('app.close() stops accepting and resolves, even with an SSE stream open', async () => {
@Route('/')
class Ctl { @Sse('/ticks') ticks() { return (async function* () { yield { t: 1 }; await new Promise((r) => setTimeout(r, 1000)); yield { t: 2 }; })(); } }
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
class Ctl {
@Sse('/ticks') ticks() {
return (async function* () {
yield { t: 1 };
await new Promise((r) => setTimeout(r, 1000));
yield { t: 2 };
})();
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const server = await app.listen(0);
const port = (server.address() as any).port;
@@ -298,26 +469,54 @@ describe('graceful shutdown', () => {
describe('overrides', () => {
const portOf = (s: any) => (s.address() as any).port;
it('overrides a provider token with a plain value (wrapped as a merge object)', async () => {
@Provider({ provides: 'db' }) class Db { provide() { return { db: { real: true } }; } }
@Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } }
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {}
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: { real: true } };
}
}
@Route('/u')
class Ctl {
@Get('/x') x(@needs('db') db: any) {
return { db };
}
}
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], overrides: { db: { fake: true } } });
const s = await app.listen(0);
expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: { fake: true } });
s.close();
});
it('overrides with a function runner', async () => {
@Provider({ provides: 'db' }) class Db { provide() { return { db: 'real' }; } }
@Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } }
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {}
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: 'real' };
}
}
@Route('/u')
class Ctl {
@Get('/x') x(@needs('db') db: any) {
return { db };
}
}
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], overrides: { db: () => ({ db: 'fn' }) } });
const s = await app.listen(0);
expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: 'fn' });
s.close();
});
it('rejects an override for an unknown token', async () => {
@Route('/u') class Ctl { @Get('/x') x() { return { ok: 1 }; } }
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
@Route('/u')
class Ctl {
@Get('/x') x() {
return { ok: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], overrides: { nope: 1 } });
await expect(app.listen(0)).rejects.toThrow(/unknown token 'nope'/);
});
@@ -325,8 +524,14 @@ describe('overrides', () => {
describe('rooms auto-provide', () => {
it('injects a built-in rooms instance resolvable via @needs("rooms")', async () => {
@Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: Rooms) { return { ok: rooms instanceof Rooms }; } }
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
@Route('/r')
class Ctl {
@Get('/x') x(@needs('rooms') rooms: Rooms) {
return { ok: rooms instanceof Rooms };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const s = await app.listen(0);
const port = (s.address() as any).port;
@@ -334,9 +539,83 @@ describe('rooms auto-provide', () => {
s.close();
});
it('a user-declared rooms provider wins (no duplicate-name throw)', () => {
@Provider({ provides: 'rooms' }) class MyRooms { provide() { return { rooms: { custom: true } }; } }
@Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: any) { return rooms; } }
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] }) class M {}
@Provider({ provides: 'rooms' })
class MyRooms {
provide() {
return { rooms: { custom: true } };
}
}
@Route('/r')
class Ctl {
@Get('/x') x(@needs('rooms') rooms: any) {
return rooms;
}
}
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).not.toThrow();
});
});
test('per-route maxBodyBytes overrides the server default', async () => {
@Route('/up')
class C {
@Post('/small', { maxBodyBytes: 10 }) small(@body() _b: unknown) {
return { ok: true };
}
@Post('/big') big(@body() _b: unknown) {
return { ok: true };
}
}
@Module({ mountpoint: '/', providers: [], steps: [], controllers: [C] })
class M {}
const app = createApp({ modules: [M], limits: { maxBodyBytes: 1000 } });
const server = await app.listen(0);
const port = (server.address() as any).port;
const payload = JSON.stringify({ x: 'aaaaaaaaaaaaaaaaaaaa' }); // ~30 bytes, over the route's 10-byte cap
const opts = { method: 'POST', headers: { 'content-type': 'application/json' }, body: payload };
const tight = await fetch(`http://127.0.0.1:${port}/up/small`, opts);
expect(tight.status).toBe(413); // per-route cap of 10 bytes
const loose = await fetch(`http://127.0.0.1:${port}/up/big`, opts);
expect(loose.status).toBe(200); // falls back to the server's 1000-byte limit
server.close();
});
describe('route table validation', () => {
it('rejects routes with the same method and effective pattern', () => {
@Route('/users')
class DuplicateCtl {
@Get('/:id') byId() {
return {};
}
@Get('/:name') byName() {
return {};
}
}
@Module({ mountpoint: '/api', controllers: [DuplicateCtl] })
class DuplicateModule {}
expect(() => createApp({ modules: [DuplicateModule] })).toThrow(
/ambiguous route GET.*\/api\/users\/:name.*DuplicateCtl\.byName.*DuplicateCtl\.byId/,
);
});
it('allows the same effective pattern under different methods', () => {
@Route('/users')
class MethodsCtl {
@Get('/:id') get() {
return {};
}
@Post('/:name') post() {
return {};
}
}
@Module({ mountpoint: '/api', controllers: [MethodsCtl] })
class MethodsModule {}
expect(() => createApp({ modules: [MethodsModule] })).not.toThrow();
});
});
+84
View File
@@ -0,0 +1,84 @@
// Real Bun integration test for mesh: a teapot exporting its scopes and a teacup consuming
// them, both under the actual Bun runtime, driven entirely through serveBun.
//
// Bun's ws lifecycle differs from Deno's — its socket events land on a server-level handler
// rather than the socket — so the control channel reaching app.upgrade here is a distinct
// path from the Deno test, not a duplicate of it.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { region: 'mx', runtime: 'bun' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run(ctx: any) {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
test('mesh on Bun: teacup resolves a Bun teapot through the graph', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = serveBun(teapot, { port: 0 });
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }] },
});
const cServer = serveBun(teacup, { port: 0 });
try {
const res = await fetch(`http://127.0.0.1:${cServer.port}/api/local/who`, { headers: { 'x-token': 'abc' } });
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
config: { region: 'mx', runtime: 'bun' },
auth: { token: 'abc' },
});
} finally {
await teacup.close();
cServer.stop(true);
tServer.stop(true);
}
});
test('mesh on Bun: a teapot refuses a bad secret over its control channel', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = serveBun(teapot, { port: 0 });
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: 'WRONG' }], timeoutMs: 1000 },
});
try {
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/);
} finally {
await teacup.close();
tServer.stop(true);
}
});
+49
View File
@@ -0,0 +1,49 @@
// Real Bun integration test for serveBun: boots an app under the actual Bun runtime
// and round-trips both HTTP (app.fetch) and WebSocket (Bun's server-level websocket
// handler -> app.upgrade).
//
// Run with: npm run test:bun (or: bun test test/bun/)
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp, Route, Get, Ws, ctx, Module } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
@Route('/rt')
class Rt {
@Get('/hello')
hello() {
return { ok: true };
}
@Ws('/echo')
echo(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `echo:${msg}`;
})();
}
}
@Module({ mountpoint: '/', controllers: [Rt] })
class M {}
test('serveBun: HTTP + WebSocket round-trip', async () => {
const app = createApp({ modules: [M] });
const server = serveBun(app, { port: 0 });
const port = server.port;
try {
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
expect(httpRes.status).toBe(200);
expect((await httpRes.json()).ok).toBe(true);
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/echo`);
const got = await new Promise<string>((resolve, reject) => {
ws.onopen = () => ws.send('hi');
ws.onmessage = (e) => {
resolve(String(e.data));
ws.close();
};
ws.onerror = () => reject(new Error('ws error'));
});
expect(got).toBe('echo:hi');
} finally {
server.stop(true);
}
});
+50
View File
@@ -0,0 +1,50 @@
import { afterEach, expect, it, vi } from 'vitest';
import type { App } from '../src/app/types';
import { serveDeno } from '../src/deno';
afterEach(() => {
vi.unstubAllGlobals();
});
it('snapshots connection metadata before Deno invalidates the upgraded request', async () => {
let upgraded = false;
let handler: ((request: Request, info: unknown) => Response | Promise<Response>) | undefined;
const socket = {
readyState: 1,
binaryType: '',
send: vi.fn(),
close: vi.fn(),
addEventListener: vi.fn(),
};
vi.stubGlobal('Deno', {
serve: (_options: unknown, next: typeof handler) => {
handler = next;
return { finished: Promise.resolve(), shutdown: vi.fn() };
},
upgradeWebSocket: () => {
upgraded = true;
return { socket, response: new Response() };
},
});
const upgrade = vi.fn().mockResolvedValue(undefined);
serveDeno({ upgrade } as unknown as App);
const info = {
get remoteAddr() {
if (upgraded) throw new TypeError('Request closed');
return { hostname: '127.0.0.1', port: 1234, transport: 'tcp' };
},
};
const request = new Request('http://localhost/socket?token=x', {
headers: { upgrade: 'websocket', 'x-test': 'yes' },
});
expect(() => handler!(request, info)).not.toThrow();
await vi.waitFor(() =>
expect(upgrade).toHaveBeenCalledWith(
expect.objectContaining({ url: '/socket?token=x', ip: '127.0.0.1' }),
expect.any(Object),
),
);
});
+170
View File
@@ -0,0 +1,170 @@
// Cross-runtime mesh: a Node peer and a Deno peer, in separate processes, talking over the
// wire protocol. This is the test the whole cross-runtime effort exists for.
//
// Deno<->Deno and Node<->Node passing prove each runtime works with itself; neither proves a
// Node teapot can serve a Deno teacup, which is the shape mesh actually deploys in once it
// spans runtimes. The two sides use genuinely different code here — Node serves through the
// `ws` package (WebSocketServer + nodeSocket) and connects with it too; Deno uses its global
// WebSocket both ways — so only a real cross-process run exercises the pairing.
//
// Run with: npm run test:deno (needs --allow-run to spawn the Node peer)
import 'npm:reflect-metadata';
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
const SECRET = 's3cr3t';
const NODE_PEER = 'test/interop/_node-peer.ts';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { region: 'mx', runtime: 'deno' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run(ctx: any) {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
/** Spawns the Node peer under tsx, streaming its stdout lines. */
function spawnNodePeer(args: string[]) {
const child = new Deno.Command('npx', {
args: ['tsx', NODE_PEER, ...args],
env: { ...Deno.env.toObject(), MESH_SECRET: SECRET },
stdout: 'piped',
stderr: 'piped',
}).spawn();
return child;
}
/** Reads stdout until a JSON line parses, or the peer dies / we run out of patience. */
async function firstJsonLine(child: Deno.ChildProcess, timeoutMs = 30_000): Promise<any> {
const reader = child.stdout.getReader();
const decoder = new TextDecoder();
let buffer = '';
const deadline = Date.now() + timeoutMs;
try {
while (Date.now() < deadline) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
for (const line of buffer.split('\n')) {
const trimmed = line.trim();
if (!trimmed.startsWith('{')) continue;
try {
return JSON.parse(trimmed);
} catch {
/* partial line; keep reading */
}
}
}
} finally {
reader.releaseLock();
}
throw new Error(`node peer produced no JSON line within ${timeoutMs}ms`);
}
async function kill(child: Deno.ChildProcess): Promise<void> {
try {
child.kill('SIGKILL');
} catch {
/* already gone */
}
await child.status;
try {
await child.stdout.cancel();
await child.stderr.cancel();
} catch {
/* already released */
}
}
Deno.test('interop: a Deno teacup consumes a Node teapot', async () => {
const node = spawnNodePeer(['teapot']);
const { port } = await firstJsonLine(node);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(port), secret: SECRET }], timeoutMs: 5000 },
});
try {
const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
assertEquals(res.status, 200);
// the config came from the Node process: proof the scope crossed the runtime boundary
assertEquals(await res.json(), {
config: { region: 'mx', runtime: 'node' },
auth: { token: 'abc' },
});
} finally {
await teacup.close();
await kill(node);
}
});
Deno.test('interop: a Node teacup consumes a Deno teapot', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
let port = 0;
const { serveDeno } = await import('../../src/deno.ts');
const server = serveDeno(teapot, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
const node = spawnNodePeer(['teacup', controlUrl(port)]);
try {
const result = await firstJsonLine(node);
assertEquals(result.ok, true);
// the Node peer resolved a scope served by Deno's app.upgrade control channel
assertEquals(result.body.config, { region: 'mx', runtime: 'deno' });
assertEquals(result.body.auth, { token: 'abc' });
} finally {
await kill(node);
await server.shutdown();
}
});
Deno.test('interop: a version-skewed peer is refused across runtimes', async () => {
const node = spawnNodePeer(['teapot']);
const { port } = await firstJsonLine(node);
try {
// hand-rolled peer speaking a future protocol: the teapot must refuse before the secret
const ws = new WebSocket(controlUrl(port));
const closed = await new Promise<{ code: number; reason: string }>((resolve, reject) => {
ws.onopen = () => ws.send(JSON.stringify({ type: 'hello', v: 999, secret: SECRET }));
ws.onclose = (e) => resolve({ code: e.code, reason: e.reason });
ws.onerror = () => reject(new Error('ws error'));
});
assertEquals(closed.code, 1008);
assertStringIncludes(closed.reason, '999');
} finally {
await kill(node);
}
});
+108
View File
@@ -0,0 +1,108 @@
// Real Deno integration test for mesh: a teapot exporting its scopes and a teacup consuming
// them, both under the actual Deno runtime, driven entirely through serveDeno.
//
// This is the test that makes "mesh runs off Node" a fact rather than an intention. It covers,
// in one round-trip, everything that used to be Node-only:
// - the teacup's WebSocket client is Deno's global (no `ws` package here at all)
// - the teapot's control channel is served via app.upgrade (Deno has no server.on('upgrade'))
// - the graph boots on the first request; `listen()` is never called and cannot be
// - node:crypto's timingSafeEqual + Buffer resolve under Deno's node-compat
//
// Run with: npm run test:deno
// `--no-check`: see the note in ws.test.ts — Deno type-checks the whole reachable graph,
// including Node-only modules this test never executes. tsc covers those.
import 'npm:reflect-metadata';
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { region: 'mx', runtime: 'deno' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run(ctx: any) {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
/** Starts an app on Deno and resolves once its port is known. */
async function serve(app: ReturnType<typeof createApp>) {
let port = 0;
const server = serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
return { server, port };
}
const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
Deno.test('mesh on Deno: teacup resolves a Deno teapot through the graph', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const t = await serve(teapot);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(t.port), secret: SECRET }] },
});
const c = await serve(teacup);
try {
const res = await fetch(`http://127.0.0.1:${c.port}/api/local/who`, { headers: { 'x-token': 'abc' } });
assertEquals(res.status, 200);
assertEquals(await res.json(), {
config: { region: 'mx', runtime: 'deno' },
auth: { token: 'abc' },
});
} finally {
await teacup.close();
await c.server.shutdown();
await t.server.shutdown();
}
});
Deno.test('mesh on Deno: a teapot refuses a bad secret over its control channel', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const t = await serve(teapot);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(t.port), secret: 'WRONG' }], timeoutMs: 1000 },
});
try {
let message = '';
try {
await teacup.fetch(new Request('http://x/api/local/who'));
} catch (err) {
message = String((err as Error).message);
}
assertStringIncludes(message, 'mesh');
} finally {
await teacup.close();
await t.server.shutdown();
}
});
+71
View File
@@ -0,0 +1,71 @@
// Real Deno integration test for serveDeno: boots an app under the actual Deno runtime
// and round-trips both HTTP (app.fetch) and WebSocket (Deno.upgradeWebSocket -> app.upgrade).
//
// Run with: npm run test:deno (or: deno test --allow-net --allow-read --no-check test/deno/)
//
// `--no-check`: the barrel (`src/index.ts`) re-exports types from Node-only modules
// (e.g. `src/http/*`) that reference ambient Node globals like `Buffer`. Those modules
// aren't executed under Deno (this test only exercises `serveDeno`'s fetch/WebSocket
// path), but Deno's checker still type-checks the whole reachable graph and has no
// ambient `Buffer` type without a full `@types/node` setup. Node-side static typing for
// those modules is already covered by `npm run typecheck` (tsc); this test's job is to
// prove Deno *runtime* behavior of the adapter, not re-typecheck Node-only internals.
import 'npm:reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp, Route, Ws, Get, Module, ctx } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
@Route('/rt')
class Rt {
@Get('/hello')
hello() {
return { ok: true };
}
@Ws('/echo')
echo(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `echo:${msg}`;
})();
}
}
@Module({ mountpoint: '/', controllers: [Rt] })
class M {}
Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () => {
const app = createApp({ modules: [M] });
let port = 0;
const server = serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
// Let onListen fire before we try to connect.
await new Promise((resolve) => setTimeout(resolve, 50));
try {
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
assertEquals(httpRes.status, 200);
assertEquals((await httpRes.json()).ok, true);
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/echo`);
try {
const got = await new Promise<string>((resolve, reject) => {
ws.onopen = () => ws.send('hi');
ws.onmessage = (e) => resolve(String(e.data));
ws.onerror = () => reject(new Error('ws error'));
});
assertEquals(got, 'echo:hi');
} finally {
ws.close();
// Give the close frame a moment to complete the handshake so no socket is leaked.
await new Promise((resolve) => setTimeout(resolve, 20));
}
} finally {
await server.shutdown();
}
});
+96
View File
@@ -0,0 +1,96 @@
// Real Miniflare (workerd) integration test for edgeHandler: bundles test/edge/worker.ts
// for the Cloudflare Workers runtime and boots it in the actual workerd engine (via the
// `miniflare` npm package — no CF account/deploy needed), then round-trips HTTP + WS
// through the real graph.
//
// Run with: npm run test:edge
//
// NODEJS_COMPAT: workerd's `nodejs_compat` genuinely does NOT implement `node:http`/
// `node:https` (confirmed in isolation: `node:crypto`, `node:stream`, `node:net`, `node:tls`,
// `node:events`, `node:util`, `node:buffer` all load fine under the same flags/compat date;
// only `http`/`https` fail with "Uncaught Error: No such module 'node:http'" at worker LOAD
// time) — a real platform gap, not a bundler misconfiguration. The barrel used to statically
// VALUE-import `http`/`https` for the Node `listen()` path even though `edgeHandler` never
// touches them, which broke worker load with no shim. The fix (see src/http/server.ts,
// src/app/index.ts, and the other src/http/*.ts files) converts every `http`/`https` import
// to `import type` (zero runtime code) and lazy-`require()`s them only inside
// `createHttpServer`, which the edge path never calls. That means the real barrel now loads
// on workerd with no test-time stub — this run exercises it as-is.
import { strict as assert } from 'node:assert';
import { build } from 'esbuild';
import { Miniflare } from 'miniflare';
const BUNDLE = 'test/edge/_worker.mjs';
async function main() {
// Bundle the worker for workerd: ESM, Node builtins left external + aliased to node:*
// so workerd's nodejs_compat provides them (not esbuild). `http`/`https` are no longer
// imported as VALUES by the barrel at module-eval time (see comment above) — they're now
// `import type` (erased) plus a lazy `require()` reached only from `createHttpServer`,
// which `edgeHandler` never calls. esbuild still needs a resolution for that bare
// `require('http')`/`require('https')` text even though it's dead code on this path, so
// they're marked external here (left unresolved, exactly like the `node:*` builtins) rather
// than stubbed — no fake implementation is provided, and the real barrel is what's tested.
await build({
entryPoints: ['test/edge/worker.ts'],
bundle: true,
format: 'esm',
outfile: BUNDLE,
platform: 'browser', // workerd is not node; keep esbuild from injecting node shims
target: 'esnext',
// Leave Node builtins for workerd's nodejs_compat to resolve; http/https are external
// too (unresolved, never called by edgeHandler) since workerd has no node:http/https.
external: ['node:*', 'http', 'https'],
alias: {
crypto: 'node:crypto',
stream: 'node:stream',
zlib: 'node:zlib',
buffer: 'node:buffer',
events: 'node:events',
net: 'node:net',
tls: 'node:tls',
util: 'node:util',
},
});
const mf = new Miniflare({
modules: true,
scriptPath: BUNDLE,
compatibilityDate: '2024-11-01',
compatibilityFlags: ['nodejs_compat'],
});
try {
// HTTP
const httpRes = await mf.dispatchFetch('http://localhost/rt/hello');
assert.equal(httpRes.status, 200);
assert.deepEqual(await httpRes.json(), { ok: true });
// WebSocket
const wsRes = await mf.dispatchFetch('http://localhost/rt/echo', {
headers: { Upgrade: 'websocket' },
});
assert.equal(wsRes.status, 101);
const ws = wsRes.webSocket;
assert.ok(ws, 'expected a client webSocket on the 101 response');
ws.accept();
const got = await new Promise<string>((resolve, reject) => {
ws.addEventListener('message', (e: { data: unknown }) => {
resolve(String(e.data));
ws.close();
});
ws.addEventListener('error', () => reject(new Error('ws error')));
ws.send('hi');
});
assert.equal(got, 'echo:hi');
console.log('edge (workerd via miniflare): HTTP 200 + WS echo:hi — PASS');
} finally {
await mf.dispose();
}
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
+27
View File
@@ -0,0 +1,27 @@
// Worker entry for the real workerd (Miniflare) integration test.
// Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven
// identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts).
import { createApp, Route, Get, Ws, ctx, Module } from '../../src/index';
import { edgeHandler } from '../../src/edge';
@Route('/rt')
class Rt {
@Get('/hello')
hello() {
return { ok: true };
}
@Ws('/echo')
echo(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `echo:${msg}`;
})();
}
}
@Module({ mountpoint: '/', controllers: [Rt] })
class M {}
const app = createApp({ modules: [M] });
export default { fetch: edgeHandler(app) };
+82
View File
@@ -0,0 +1,82 @@
import 'reflect-metadata';
import { describe, it, expect } from 'vitest';
import { createApp } from '../src/app';
import { Route, Get, Module } from '../src/metadata';
import { HttpError, Unauthorized, isHttpError } from '../src/signals';
import type { ErrorRenderer } from '../src/transformers';
// Renders every error as HTML, reading the status off HttpError when present.
const htmlErrors: ErrorRenderer = (error) => ({
status: isHttpError(error) ? error.status : 500,
headers: { 'content-type': 'text/html' },
body: `<h1>${isHttpError(error) ? error.status : 500}</h1>`,
});
@Route('/x')
class Ctl {
@Get('/boom') boom() {
throw new Unauthorized('nope');
}
@Get('/ok') ok() {
return { ok: true };
}
@Get('/teapot') teapot() {
throw new HttpError(418, 'short and stout', { code: 'TEA', reason: 'short and stout' });
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
async function serve(onError?: ErrorRenderer) {
const app = createApp({ modules: [M], onError });
const server = await app.listen(0);
const port = (server.address() as any).port;
return { server, base: `http://127.0.0.1:${port}` };
}
describe('onError renderer', () => {
it('renders a handler-thrown error through the hook (HTML, right status)', async () => {
const { server, base } = await serve(htmlErrors);
const res = await fetch(`${base}/x/boom`);
expect(res.status).toBe(401);
expect(res.headers.get('content-type')).toBe('text/html');
expect(await res.text()).toBe('<h1>401</h1>');
server.close();
});
it('renders infra errors too — a no-route 404 goes through the hook', async () => {
const { server, base } = await serve(htmlErrors);
const res = await fetch(`${base}/nope`);
expect(res.status).toBe(404);
expect(res.headers.get('content-type')).toBe('text/html');
expect(await res.text()).toBe('<h1>404</h1>');
server.close();
});
it('falls back to the default JSON when the hook returns undefined', async () => {
const { server, base } = await serve(() => undefined);
const res = await fetch(`${base}/x/boom`);
expect(res.status).toBe(401);
expect(res.headers.get('content-type')).toBe('application/json');
expect(await res.json()).toEqual({ error: 'nope' });
server.close();
});
it('with no hook, behavior is unchanged (default JSON 404)', async () => {
const { server, base } = await serve();
const res = await fetch(`${base}/nope`);
expect(res.status).toBe(404);
expect(await res.json()).toEqual({ error: 'Not Found' });
server.close();
});
});
describe('HttpError body', () => {
it('an HttpError carrying a body renders that payload instead of { error: message }', async () => {
const { server, base } = await serve();
const res = await fetch(`${base}/x/teapot`);
expect(res.status).toBe(418);
expect(await res.json()).toEqual({ code: 'TEA', reason: 'short and stout' });
server.close();
});
});
+147
View File
@@ -0,0 +1,147 @@
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index';
@Provider({ provides: 'store' })
class Store {
provide() {
return { store: { hi: 'ok' } };
}
}
@Route('/api')
class Ctl {
@Get('/hello') hello(@needs('store') s: any) {
return { store: s.hi };
}
@Post('/echo') echo(@body() b: any) {
return { got: b };
}
@Post('/tiny', { maxBodyBytes: 10 }) tiny(@body() b: any) {
return { got: b };
}
}
@Module({ mountpoint: '/', providers: [Store], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
@Route('/mesh')
class MeshCtl {
@Get('/ping') ping() {
return { pong: true };
}
}
@Module({ mountpoint: '/api', controllers: [MeshCtl] })
class MeshModule {}
describe('app.fetch', () => {
it('handles GET and returns JSON 200', async () => {
const res = await app.fetch(new Request('http://x/api/hello'));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ store: 'ok' });
});
it('parses a POST body', async () => {
const res = await app.fetch(
new Request('http://x/api/echo', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ a: 1 }),
}),
);
expect(await res.json()).toEqual({ got: { a: 1 } });
});
it('404s an unknown route', async () => {
const res = await app.fetch(new Request('http://x/nope'));
expect(res.status).toBe(404);
});
it('sets secure-by-default headers', async () => {
const res = await app.fetch(new Request('http://x/api/hello'));
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
});
it('a 413 (oversized body) still carries the injected security headers', async () => {
const res = await app.fetch(
new Request('http://x/api/tiny', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ x: 'well over ten bytes' }),
}),
);
expect(res.status).toBe(413);
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
expect(res.headers.get('x-frame-options')).toBe('SAMEORIGIN');
});
it('a 400 (invalid JSON) still carries the injected security headers', async () => {
const res = await app.fetch(
new Request('http://x/api/echo', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: '{not json',
}),
);
expect(res.status).toBe(400);
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
});
});
@Route('/ip')
class IpCtl {
@Get('/whoami') whoami(@ctx() c: any) {
return { ip: c.ip };
}
}
@Module({ mountpoint: '/', controllers: [IpCtl] })
class IpModule {}
describe('app.fetch trustProxy gates x-forwarded-for', () => {
it('honors x-forwarded-for (first hop) when trustProxy is true', async () => {
const trustingApp = createApp({ modules: [IpModule], trustProxy: true });
const res = await trustingApp.fetch(
new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9, 1.1.1.1' } }),
);
expect(await res.json()).toEqual({ ip: '9.9.9.9' });
});
it('ignores x-forwarded-for when trustProxy is off (default)', async () => {
const untrustingApp = createApp({ modules: [IpModule] });
const res = await untrustingApp.fetch(
new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9, 1.1.1.1' } }),
);
expect(await res.json()).toEqual({ ip: '' });
});
});
describe('app.fetch on a mesh app', () => {
// Previously this asserted fetch() *threw* until listen() ran, which made mesh Node-only:
// Deno/Bun/edge serve through app.fetch and can never call listen() (it builds an http.Server).
// The boot gate now finalizes the mesh graph on first use, whoever triggers it.
it('serves without ever calling listen()', async () => {
const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } });
const res = await meshApp.fetch(new Request('http://x/api/mesh/ping'));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ pong: true });
await meshApp.close();
});
it('does not re-boot when listen() follows a fetch', async () => {
const meshApp = createApp({ modules: [MeshModule], experimental: true, mesh: { secret: 's3cr3t' } });
let booted = 0;
meshApp.bus.on('boot:provider:start', () => {
booted += 1;
});
await meshApp.fetch(new Request('http://x/api/mesh/ping'));
const bootsAfterFetch = booted;
const server = await meshApp.listen(0);
try {
const res = await meshApp.fetch(new Request('http://x/api/mesh/ping'));
expect(res.status).toBe(200);
// listen() shares fetch's memoized gate: provider factories must not run twice
expect(booted).toBe(bootsAfterFetch);
} finally {
server.close();
}
});
});
+50
View File
@@ -0,0 +1,50 @@
import 'reflect-metadata';
import { describe, expect, it, vi } from 'vitest';
import { createApp, Step, Route, Get, Module, needs } from '../src/index';
// Builds a module with an n-deep chain: s1..sn (each needs the previous) + a route that @needs the last.
function deepModule(n: number) {
const steps = Array.from({ length: n }, (_, i) => {
const k = i + 1;
@Step({ provides: `s${k}`, needs: k > 1 ? [`s${k - 1}`] : [] })
class S { run() { return { [`s${k}`]: k }; } }
return S;
});
@Route('/')
class C { @Get('/deep') deep(@needs(`s${n}`) s: number) { return { s }; } }
@Module({ mountpoint: '/', steps, controllers: [C] })
class M {}
return M;
}
describe('deep-graph warning', () => {
it('warns at boot when a route resolves to more than 20 steps', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
createApp({ modules: [deepModule(25)] });
expect(warn).toHaveBeenCalledWith(expect.stringContaining('25 steps'));
warn.mockRestore();
});
it('stays quiet under the threshold', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
createApp({ modules: [deepModule(10)] });
expect(warn).not.toHaveBeenCalled();
warn.mockRestore();
});
it('warnGraphDepth: false silences it', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
createApp({ modules: [deepModule(25)], warnGraphDepth: false });
expect(warn).not.toHaveBeenCalled();
warn.mockRestore();
});
it('warnGraphDepth tunes the threshold', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
createApp({ modules: [deepModule(10)], warnGraphDepth: 5 });
expect(warn).toHaveBeenCalledWith(expect.stringContaining('10 steps'));
warn.mockRestore();
});
});
+15 -5
View File
@@ -32,10 +32,20 @@ describe('toDOT', () => {
});
describe('graphHtml', () => {
it('wraps mermaid source in an HTML page that loads mermaid', () => {
const html = graphHtml('flowchart LR\n a-->b');
expect(html).toContain('<pre class="mermaid">');
expect(html).toContain('flowchart LR');
expect(html).toContain('mermaid');
it('emits an interactive Cytoscape page with the graph embedded as JSON', () => {
const html = graphHtml(view);
expect(html).toContain('cytoscape'); // loads the viz lib from CDN
expect(html).toContain('cytoscape-dagre'); // and the DAG layout
expect(html).toContain('"user"'); // node data is embedded client-side
expect(html).toContain('/users/:id'); // route data too
});
it('escapes embedded JSON so a node name cannot break out of the script tag', () => {
const evil = graphHtml({
nodes: [{ name: 'a</script><b', kind: 'provider', origin: 'x', needs: [], provides: ['a'] }],
routes: [],
});
expect(evil).not.toContain('a</script><b'); // raw injection must not survive
expect(evil).toContain('a\\u003c/script'); // '<' is escaped to <
});
});
+25
View File
@@ -0,0 +1,25 @@
import { describe, it, expect } from 'vitest';
import { mergeInjectedHeaders } from '../src/http/headers';
describe('mergeInjectedHeaders', () => {
it('makes injected keys authoritative regardless of handler casing', () => {
const out = mergeInjectedHeaders(
{ 'Content-Type': 'text/html', 'X-Content-Type-Options': 'sniffme' },
{ 'x-content-type-options': 'nosniff' },
);
expect(out['x-content-type-options']).toBe('nosniff');
expect(Object.keys(out).filter((k) => k.toLowerCase() === 'x-content-type-options')).toHaveLength(1);
expect(out['Content-Type']).toBe('text/html'); // untouched handler header kept
});
it('merges Vary from handler and injected', () => {
const out = mergeInjectedHeaders({ Vary: 'Accept' }, { vary: 'Origin' });
expect(out['vary'].toLowerCase()).toContain('accept');
expect(out['vary'].toLowerCase()).toContain('origin');
});
it('preserves handler Vary when no injected Vary', () => {
const out = mergeInjectedHeaders({ Vary: 'Accept' }, {});
expect(out['vary']).toBe('Accept');
});
});
+71
View File
@@ -0,0 +1,71 @@
// Not a test — a Node-hosted mesh peer, spawned by mesh-interop.test.ts. Deno's test runner
// only discovers *.test.ts, so this file is ignored by `deno test`.
//
// It exists so the interop claim is tested rather than reasoned about: Deno<->Deno passing
// says nothing about a Node teapot serving a Deno teacup, which is the actual deployment
// shape once mesh spans runtimes. Node's side uses the `ws` package (WebSocketServer +
// nodeSocket); Deno's uses its global WebSocket. Only a real cross-process run exercises both.
//
// Modes:
// teapot -> exports scopes, prints {"port":N}, serves until killed
// teacup <controlUrl> -> consumes the remote scopes, prints {"ok":true,"body":{...}}
import 'reflect-metadata';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
const SECRET = process.env.MESH_SECRET ?? 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { region: 'mx', runtime: 'node' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run(ctx: any) {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const [mode, controlUrl] = process.argv.slice(2);
async function main(): Promise<void> {
if (mode === 'teapot') {
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = await app.listen(0);
console.log(JSON.stringify({ port: (server.address() as { port: number }).port }));
return; // stays alive on the open server until the parent kills it
}
if (mode === 'teacup') {
const app = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl, secret: SECRET }], timeoutMs: 5000 },
});
const res = await app.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
const body = await res.json();
console.log(JSON.stringify({ ok: res.status === 200, body }));
await app.close();
process.exit(0);
}
throw new Error(`unknown mode: ${mode}`);
}
main().catch((err: unknown) => {
console.log(JSON.stringify({ ok: false, error: String((err as Error).message) }));
process.exit(1);
});
+1 -1
View File
@@ -5,7 +5,7 @@ import { createHttpServer, type MeshControl } from '../../src/http';
describe('mesh control upgrade', () => {
it('routes the reserved path to meshControl.handle and leaves wsRoutes intact', async () => {
let handled = false;
const meshControl: MeshControl = { path: '/__mesh__/control', handle: (ws) => { handled = true; ws.send('hi'); } };
const meshControl: MeshControl = { path: '/__mesh__/control', handle: async (ws) => { handled = true; ws.send('hi'); } };
const server = createHttpServer([], [], undefined, meshControl);
await new Promise<void>((r) => server.listen(0, r));
const port = (server.address() as any).port;
+121
View File
@@ -0,0 +1,121 @@
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { region: 'mx' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run() {
return { auth: { token: 'ok' } };
}
}
@Route('/svc')
class SvcCtl {
@Get('/ping', { export: true })
ping() {
return { pong: true };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [SvcCtl] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('auth') auth: any) {
return { auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const controlUrl = (server: any) => `ws://127.0.0.1:${(server.address() as any).port}/__mesh__/control`;
/**
* What a teacup answers once its teapot is gone. The status is the whole point: a dead upstream
* is not "I broke" (500) — it is "my dependency is unavailable" (503), which is what tells an
* operator where to look and what a caller may retry.
*/
describe('mesh link failure', () => {
it('answers 503 on a remote step once the teapot is gone', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer), secret: SECRET }] },
});
const ok = await teacup.fetch(new Request('http://x/api/local/who'));
expect(ok.status).toBe(200);
await teapot.close();
await new Promise((r) => setTimeout(r, 50));
const down = await teacup.fetch(new Request('http://x/api/local/who'));
expect(down.status).toBe(503);
await teacup.close();
});
it('answers 503 on a proxied remote route once the teapot is gone', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer), secret: SECRET }] },
});
const ok = await teacup.fetch(new Request('http://x/api/svc/ping'));
expect(ok.status).toBe(200);
await teapot.close();
await new Promise((r) => setTimeout(r, 50));
const down = await teacup.fetch(new Request('http://x/api/svc/ping'));
expect(down.status).toBe(503);
await teacup.close();
});
it('keeps serving an app-scope remote from cache after the link drops', async () => {
// Not a bug, but worth pinning: an app-scope export is resolved once and memoised, so it
// survives its teapot — with a value that can go stale. Reconciling on reconnect is a
// known gap (see the mesh guide), and this test is what would catch it changing by accident.
@Route('/cached')
class CachedCtl {
@Get('/cfg')
cfg(@needs('config') config: any) {
return { config };
}
}
@Module({ mountpoint: '/api', controllers: [CachedCtl] })
class CachedModule {}
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const teacup = createApp({
modules: [CachedModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer), secret: SECRET }] },
});
expect((await teacup.fetch(new Request('http://x/api/cached/cfg'))).status).toBe(200);
await teapot.close();
await new Promise((r) => setTimeout(r, 50));
const after = await teacup.fetch(new Request('http://x/api/cached/cfg'));
expect(after.status).toBe(200); // cached, so still answering
expect(await after.json()).toEqual({ config: { region: 'mx' } });
await teacup.close();
});
});
+308
View File
@@ -0,0 +1,308 @@
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
import { channel } from '../../src/channel';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
import type { WsSocket, WsRequest } from '../../src/http/ws-core';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { region: 'mx' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run(ctx: any) {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
@Route('/plain')
class PlainCtl {
@Get('/ok')
ok() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [PlainCtl] })
class PlainModule {}
const teapotUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
/** A neutral socket, exactly what serveDeno/serveBun hand to app.upgrade. */
const fakePeer = () => {
const inbound = channel<unknown>();
const ac = new AbortController();
const sent: any[] = [];
const closed: { code?: number; reason?: string }[] = [];
const socket: WsSocket = {
inbound,
abort: ac.signal,
isOpen: true,
send: (data: string) => {
sent.push(decode(data));
},
close: (code, reason) => {
closed.push({ code, reason });
inbound.close();
ac.abort();
},
terminate: () => ac.abort(),
};
return { socket, sent, closed, inbound };
};
const controlReq = (): WsRequest => ({ url: '/__mesh__/control', headers: {}, protocol: 'http', ip: '' });
/**
* A mesh teacup driven purely through `app.fetch` — the entry point Deno/Bun/edge use.
* `listen()` is never called on the teacup, because on those runtimes it cannot be:
* it builds a Node http.Server.
*/
describe('mesh over app.fetch (no listen)', () => {
it('boots the mesh graph on the first request and resolves remote scopes', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ config: { region: 'mx' }, auth: { token: 'abc' } });
await teacup.close();
tServer.close();
});
it('boots exactly once across concurrent first requests', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
let connects = 0;
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
teacup.bus.on('mesh:connect', () => {
connects += 1;
});
const hit = () => teacup.fetch(new Request('http://x/api/local/who'));
const all = await Promise.all([hit(), hit(), hit()]);
expect(all.map((r) => r.status)).toEqual([200, 200, 200]);
expect(connects).toBe(1); // the boot gate is memoized: three racing requests splice once
await teacup.close();
tServer.close();
});
it('serves the remote scope in inspect() once a request has booted the graph', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
await teacup.fetch(new Request('http://x/api/local/who'));
const chain = teacup.inspect('/api/local/who').map((line) => `${line.kind}:${line.name}`);
// the remote provider and step spliced into the local route's chain
expect(chain).toContain('provider:config');
expect(chain).toContain('step:auth');
expect(teacup.graph().nodes.some((n) => n.name === 'config')).toBe(true);
await teacup.close();
tServer.close();
});
it('closes the teapot links, even with no server to hang the close off', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
const disconnects: string[] = [];
teacup.bus.on('mesh:disconnect', (p) => disconnects.push(p.name));
await teacup.fetch(new Request('http://x/api/local/who'));
expect(disconnects).toEqual([]);
// listen() never ran, so there is no server whose 'close' could reap the links
await teacup.close();
await new Promise((r) => setTimeout(r, 50));
expect(disconnects).toEqual([url]);
tServer.close();
});
it('resolves the graph via ready() without serving a request', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
// a mesh graph is not knowable without asking the teapots, so it throws until resolved
expect(() => teacup.graph()).toThrow(/until a mesh app has booted/);
await teacup.ready();
expect(teacup.graph().nodes.some((n) => n.name === 'config')).toBe(true);
expect(teacup.inspect('/api/local/who').map((l) => `${l.kind}:${l.name}`)).toContain('provider:config');
expect(teacup.explain('/api/local/who')).toBeTruthy();
await teacup.close();
tServer.close();
});
it('ready() resolves the graph but does NOT boot providers', async () => {
// the point of ready() over a full boot: a devtool asking for the graph must not run
// provider factories and open their connections as a side effect
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
const booted: string[] = [];
teacup.bus.on('boot:provider:start', (p) => booted.push(p.name));
await teacup.ready();
expect(teacup.graph().nodes.length).toBeGreaterThan(0); // graph is resolved
expect(booted).toEqual([]); // and nothing was booted to get it
await teacup.fetch(new Request('http://x/api/local/who'));
expect(booted.length).toBeGreaterThan(0); // serving does boot them
await teacup.close();
tServer.close();
});
it('ready() is memoized and shared with the boot: a later fetch does not re-splice', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
let connects = 0;
teacup.bus.on('mesh:connect', () => {
connects += 1;
});
await Promise.all([teacup.ready(), teacup.ready()]);
await teacup.fetch(new Request('http://x/api/local/who'));
await teacup.ready();
expect(connects).toBe(1);
await teacup.close();
tServer.close();
});
it('surfaces a failed mesh boot as a request error, not a silent success', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = teapotUrl((tServer.address() as any).port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: 'WRONG' }], timeoutMs: 800 },
});
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow();
await teacup.close();
tServer.close();
});
});
/**
* A teapot *exporting* over app.upgrade — the path serveDeno/serveBun drive. Without this the
* control channel only existed on Node's server.on('upgrade'), so a teapot could not run off Node
* and "mesh on 3 runtimes" would have meant consuming only.
*/
describe('mesh control over app.upgrade (no listen)', () => {
it('serves the handshake to a peer that never touched a Node server', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const peer = fakePeer();
void teapot.upgrade(controlReq(), peer.socket);
peer.inbound.push(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: SECRET }));
await new Promise((r) => setTimeout(r, 20));
expect(peer.sent[0]).toMatchObject({
type: 'manifest',
v: MESH_PROTOCOL_VERSION,
scopes: expect.arrayContaining([{ token: 'config', scope: 'app' }]),
});
await teapot.close();
});
it('rejects a bad secret over app.upgrade too', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const peer = fakePeer();
void teapot.upgrade(controlReq(), peer.socket);
peer.inbound.push(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: 'WRONG' }));
await new Promise((r) => setTimeout(r, 20));
expect(peer.sent).toEqual([]);
expect(peer.closed[0].code).toBe(1008);
await teapot.close();
});
it('refuses the reserved path explicitly on an app that exports nothing', async () => {
// a plain, self-contained app: the path is reserved regardless, so say so rather than
// let it fall through to the generic "no matching ws route"
const plain = createApp({ modules: [PlainModule] });
const peer = fakePeer();
await plain.upgrade(controlReq(), peer.socket);
expect(peer.closed[0].code).toBe(1008);
expect(peer.closed[0].reason).toMatch(/mesh control channel not enabled/i);
});
});
+86
View File
@@ -0,0 +1,86 @@
import { describe, it, expect } from 'vitest';
import { WebSocketServer } from 'ws';
import { connectLink } from '../../src/mesh/link';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
const V = MESH_PROTOCOL_VERSION;
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
/**
* A teapot that handshakes and answers RPCs, and optionally ignores pings — the shape of a
* half-open link: TCP still looks alive, the peer is not. Without a heartbeat a teacup only
* finds out when a request pays the full rpc timeout.
*/
function startTeapot(opts: { answerPings: boolean }) {
const wss = new WebSocketServer({ port: 0 });
const seen: string[] = [];
wss.on('connection', (ws) => {
ws.on('message', (data) => {
const frame = decode(data.toString());
seen.push(frame.type);
if (frame.type === 'hello') {
ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'auth', scope: 'request' }], routes: [] }));
}
if (frame.type === 'ping' && opts.answerPings) ws.send(encode({ type: 'pong' }));
if (frame.type === 'rpc-req') ws.send(encode({ type: 'rpc-res', id: frame.id, ok: true, result: { got: 1 } }));
});
});
const port = (wss.address() as any).port;
return { url: `ws://127.0.0.1:${port}/__mesh__/control`, seen, close: () => wss.close() };
}
describe('mesh heartbeat', () => {
it('pings the teapot and keeps the link alive while it pongs', async () => {
const t = startTeapot({ answerPings: true });
const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30 });
await new Promise((r) => setTimeout(r, 120));
expect(t.seen.filter((f) => f === 'ping').length).toBeGreaterThan(1);
expect(await link.rpc('scope', 'auth', env)).toEqual({ got: 1 }); // still usable
link.close();
t.close();
});
it('closes the link when the teapot stops answering pings', async () => {
// the half-open case: the socket never errors, the peer just stops talking
const t = startTeapot({ answerPings: false });
const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30, timeoutMs: 10_000 });
await new Promise((r) => setTimeout(r, 200));
// 503 immediately from the dead-link guard, not a 10s wait on the rpc timeout
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
t.close();
});
it('emits mesh:disconnect when the heartbeat gives up', async () => {
const t = startTeapot({ answerPings: false });
const seen: string[] = [];
const bus = { emit: (e: string, p: any) => seen.push(`${e}:${p.name}`), on: () => () => {} } as any;
const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30, bus });
await new Promise((r) => setTimeout(r, 200));
expect(seen.some((s) => s.startsWith('mesh:disconnect'))).toBe(true);
link.close();
t.close();
});
it('does not ping before the handshake completes', async () => {
const t = startTeapot({ answerPings: true });
const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30 });
// hello must be first on the wire: an unauthenticated peer has no business pinging
expect(t.seen[0]).toBe('hello');
link.close();
t.close();
});
});
+173 -1
View File
@@ -1,4 +1,4 @@
import { describe, it, expect } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
const SECRET = 's3cr3t';
@@ -23,6 +23,59 @@ class LocalCtl {
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
// Two teapots exporting the SAME route and no scopes — a scope clash would throw first
// (setRunner enforces unique tokens), which would hide the route clash under test.
@Route('/dup')
class DupCtl {
@Get('/ping', { export: true })
ping() {
return { pong: true };
}
}
@Module({ mountpoint: '/api', controllers: [DupCtl] })
class DupTeapotModule {}
@Route('/shape')
class ParamIdCtl {
@Get('/:id', { export: true })
get() {
return { from: 'id' };
}
}
@Module({ mountpoint: '/api', controllers: [ParamIdCtl] })
class ParamIdTeapotModule {}
@Route('/shape')
class ParamNameCtl {
@Get('/:name', { export: true })
get() {
return { from: 'name' };
}
}
@Module({ mountpoint: '/api', controllers: [ParamNameCtl] })
class ParamNameTeapotModule {}
@Route('/c')
class PlainCtl {
@Get('/ok')
ok() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [PlainCtl] })
class PlainTeacupModule {}
// A teacup declaring a route locally at the same path a teapot exports it.
@Route('/dup')
class ShadowCtl {
@Get('/ping')
ping() {
return { from: 'local' };
}
}
@Module({ mountpoint: '/api', controllers: [ShadowCtl] })
class ShadowTeacupModule {}
describe('mesh skeleton integration', () => {
it('teacup resolves remote app-scope + request-scope into a local handler', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
@@ -52,6 +105,125 @@ describe('mesh skeleton integration', () => {
s.close();
});
it('refuses to boot when two teapots export the same route, naming both', async () => {
// No load balancing exists yet, so picking one silently would be a wrong answer that
// callers could come to depend on — and it would make adding LB later a breaking change.
const a = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } });
const b = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } });
const aServer = await a.listen(0);
const bServer = await b.listen(0);
const url = (s: any) => `ws://127.0.0.1:${(s.address() as any).port}/__mesh__/control`;
const teacup = createApp({
modules: [PlainTeacupModule],
experimental: true,
mesh: {
teapots: [
{ url: url(aServer), secret: SECRET },
{ url: url(bServer), secret: SECRET },
],
},
});
await expect(teacup.fetch(new Request('http://x/c/ok'))).rejects.toThrow(/GET \/api\/dup\/ping/);
await expect(teacup.fetch(new Request('http://x/c/ok'))).rejects.toThrow(/load balancing/i);
aServer.close();
bServer.close();
});
it('refuses ambiguous remote routes that differ only by parameter name', async () => {
const a = createApp({ modules: [ParamIdTeapotModule], experimental: true, mesh: { secret: SECRET } });
const b = createApp({ modules: [ParamNameTeapotModule], experimental: true, mesh: { secret: SECRET } });
const aServer = await a.listen(0);
const bServer = await b.listen(0);
const url = (s: any) => `ws://127.0.0.1:${(s.address() as any).port}/__mesh__/control`;
const teacup = createApp({
modules: [PlainTeacupModule],
experimental: true,
mesh: { teapots: [{ url: url(aServer), secret: SECRET }, { url: url(bServer), secret: SECRET }] },
});
try {
await expect(teacup.ready()).rejects.toThrow(/ambiguous remote route.*GET \/api\/shape\/:name/i);
} finally {
await teacup.close();
aServer.close();
bServer.close();
}
});
it('accepts the same route from a single teapot (regression: no false positive)', async () => {
const a = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } });
const aServer = await a.listen(0);
const url = `ws://127.0.0.1:${(aServer.address() as any).port}/__mesh__/control`;
const teacup = createApp({
modules: [PlainTeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
const res = await teacup.fetch(new Request('http://x/api/dup/ping'));
expect(await res.json()).toEqual({ pong: true });
await teacup.close();
aServer.close();
});
it('gives a local route precedence over a remote one, and says so', async () => {
// Local-wins is the design: your own code beats an imported one, and it is how you
// override a teapot. But it used to be an accident of [...local, ...remote] ordering
// with nothing said, so a shadowed export looked like a broken teapot.
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const teapot = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`;
const teacup = createApp({
modules: [ShadowTeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
try {
const res = await teacup.fetch(new Request('http://x/api/dup/ping'));
expect(await res.json()).toEqual({ from: 'local' }); // local wins, not the teapot's {pong:true}
const warned = warn.mock.calls.map((c) => String(c[0])).join('\n');
expect(warned).toMatch(/GET \/api\/dup\/ping/);
expect(warned).toMatch(/local/i);
expect(warned).toContain(url); // which teapot got shadowed
} finally {
warn.mockRestore();
await teacup.close();
tServer.close();
}
});
it('does not warn when a remote route has no local twin', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const teapot = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`;
const teacup = createApp({
modules: [PlainTeacupModule],
experimental: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
try {
await teacup.fetch(new Request('http://x/c/ok'));
const shadowWarnings = warn.mock.calls.filter((c) => String(c[0]).includes('precedence'));
expect(shadowWarnings).toEqual([]);
} finally {
warn.mockRestore();
await teacup.close();
tServer.close();
}
});
it('rejects a bad secret (teacup boot fails)', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0); const tPort = (tServer.address() as any).port;
+64 -4
View File
@@ -1,7 +1,10 @@
import { describe, it, expect } from 'vitest';
import { WebSocketServer } from 'ws';
import WS, { WebSocketServer } from 'ws';
import { connectLink } from '../../src/mesh/link';
import { encode, decode } from '../../src/mesh/protocol';
import { loadWebSocketCtor, type SocketCtor } from '../../src/http/ws-adapter';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
const V = MESH_PROTOCOL_VERSION;
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
@@ -13,7 +16,7 @@ function startTeapot(secret = 'good') {
ws.on('message', (d) => {
const f = decode(d.toString());
if (!authed) {
if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); }
if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); }
else ws.close(1008);
return;
}
@@ -33,7 +36,7 @@ function startSilentTeapot(secret = 'good') {
wss.on('connection', (ws) => {
ws.on('message', (d) => {
const f = decode(d.toString());
if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', scopes: [], routes: [] }));
if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
// ignore rpc-req entirely
});
});
@@ -41,7 +44,64 @@ function startSilentTeapot(secret = 'good') {
return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() };
}
// teapot running a future protocol: handshakes, but answers with a skewed manifest
function startSkewedTeapot() {
const wss = new WebSocketServer({ port: 0 });
wss.on('connection', (ws) => {
ws.on('message', () => ws.send(encode({ type: 'manifest', v: V + 1, scopes: [], routes: [] } as any)));
});
const port = (wss.address() as any).port;
return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() };
}
/**
* Both client implementations, exercised on whatever Node runs the suite. `ws` is always in the
* list: it is the Node 18-21 path, and on a modern CI the platform global would otherwise be the
* only one ever covered — the fallback would rot unnoticed until someone ran the declared floor.
*/
const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket;
const CTORS: [string, SocketCtor][] = [['the ws package (Node < 22 path)', WS as unknown as SocketCtor]];
if (platform) CTORS.push(['the platform global WebSocket', platform]);
describe('WebSocket client implementations', () => {
it.each(CTORS)('handshakes and serves RPC over %s', async (_label, Ctor) => {
const t = startTeapot();
const link = await connectLink({ url: t.url, secret: 'good', Ctor });
expect(link.manifest.scopes).toEqual([{ token: 'auth', scope: 'request' }]);
expect(await link.rpc('scope', 'auth', env)).toEqual({ got: 'auth' });
link.close();
t.close();
});
it('prefers the platform global when it exists, else falls back to the ws package', () => {
expect(loadWebSocketCtor()).toBe(platform ?? (WS as unknown as SocketCtor));
});
});
describe('connectLink', () => {
it('sends its protocol version in the hello', async () => {
const seen: any[] = [];
const wss = new WebSocketServer({ port: 0 });
wss.on('connection', (ws) =>
ws.on('message', (d) => {
seen.push(decode(d.toString()));
ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
}),
);
const url = `ws://127.0.0.1:${(wss.address() as any).port}/__mesh__/control`;
const link = await connectLink({ url, secret: 'good' });
expect(seen[0]).toMatchObject({ type: 'hello', v: V });
link.close();
wss.close();
});
it('refuses a teapot on a different protocol version', async () => {
const t = startSkewedTeapot();
await expect(connectLink({ url: t.url, secret: 'good', timeoutMs: 500 })).rejects.toThrow(/version/i);
t.close();
});
it('handshakes and exposes the manifest', async () => {
const t = startTeapot();
const link = await connectLink({ url: t.url, secret: 'good' });
+65 -6
View File
@@ -1,16 +1,22 @@
import { describe, it, expect } from 'vitest';
import { encode, decode, type Frame, type RequestEnvelope } from '../../src/mesh/protocol';
import { encode, decode, MESH_PROTOCOL_VERSION, type Frame, type RequestEnvelope } from '../../src/mesh/protocol';
const env: RequestEnvelope = { method: 'GET', params: { id: '1' }, query: {}, body: undefined, headers: {} };
const V = MESH_PROTOCOL_VERSION;
describe('protocol codec', () => {
it('round-trips each frame type', () => {
const frames: Frame[] = [
{ type: 'hello', secret: 's3cr3t' },
{ type: 'manifest', scopes: [{ token: 'auth', scope: 'request' }], routes: [{ method: 'GET', pattern: '/u/:id' }] },
{ type: 'rpc-req', id: 'c1:1', kind: 'scope', name: 'auth', ctx: env },
{ type: 'rpc-res', id: 'c1:1', ok: true, result: { id: 'u1' } },
{ type: 'rpc-res', id: 'c1:2', ok: false, error: { message: 'no', status: 401 } },
{ type: 'hello', v: V, secret: 's3cr3t' },
{
type: 'manifest',
v: V,
scopes: [{ token: 'auth', scope: 'request' }],
routes: [{ method: 'GET', pattern: '/u/:id' }],
},
{ type: 'rpc-req', id: '1', kind: 'scope', name: 'auth', ctx: env },
{ type: 'rpc-res', id: '1', ok: true, result: { id: 'u1' } },
{ type: 'rpc-res', id: '2', ok: false, error: { message: 'no', status: 401 } },
];
for (const f of frames) expect(decode(encode(f))).toEqual(f);
});
@@ -22,4 +28,57 @@ describe('protocol codec', () => {
it('throws on unknown frame type', () => {
expect(() => decode(JSON.stringify({ type: 'bogus' }))).toThrow(/unknown frame/i);
});
it.each(['constructor', 'toString', '__proto__', 'hasOwnProperty'])(
'treats inherited Object property %s as an unknown type, not a validator',
(type) => {
// `type` is peer-controlled; a bare SHAPE[type] lookup would walk the prototype chain
expect(() => decode(JSON.stringify({ type }))).toThrow(/unknown frame/i);
},
);
it('throws on a non-string type tag', () => {
expect(() => decode(JSON.stringify({ type: 42 }))).toThrow(/unknown frame/i);
expect(() => decode(JSON.stringify({}))).toThrow(/unknown frame/i);
});
});
describe('protocol versioning', () => {
it('carries the protocol version on the handshake frames', () => {
const hello = decode(encode({ type: 'hello', v: V, secret: 's' }));
const manifest = decode(encode({ type: 'manifest', v: V, scopes: [], routes: [] }));
expect(hello).toMatchObject({ v: V });
expect(manifest).toMatchObject({ v: V });
});
it('rejects a handshake frame with no version — an unversioned peer is not decodable', () => {
expect(() => decode(JSON.stringify({ type: 'hello', secret: 's' }))).toThrow(/malformed hello/i);
expect(() => decode(JSON.stringify({ type: 'manifest', scopes: [], routes: [] }))).toThrow(/malformed manifest/i);
});
});
describe('protocol field validation', () => {
// decode is the trust boundary: past it, teapot.ts feeds frames straight into
// resolveScope/resolveRoute. A bad shape must die here, not downstream.
it.each([
['hello without secret', { type: 'hello', v: V }],
['hello with non-string secret', { type: 'hello', v: V, secret: 42 }],
['manifest with non-array scopes', { type: 'manifest', v: V, scopes: 'nope', routes: [] }],
['rpc-req without id', { type: 'rpc-req', kind: 'scope', name: 'auth', ctx: env }],
['rpc-req without ctx', { type: 'rpc-req', id: '1', kind: 'scope', name: 'auth' }],
['rpc-req with unknown kind', { type: 'rpc-req', id: '1', kind: 'bogus', name: 'auth', ctx: env }],
['rpc-req without name', { type: 'rpc-req', id: '1', kind: 'scope', ctx: env }],
['rpc-res without id', { type: 'rpc-res', ok: true, result: 1 }],
['rpc-res with non-boolean ok', { type: 'rpc-res', id: '1', ok: 'yes' }],
['rpc-res error without an error payload', { type: 'rpc-res', id: '1', ok: false }],
])('rejects %s', (_label, frame) => {
expect(() => decode(JSON.stringify(frame))).toThrow(/malformed/i);
});
it('accepts a valid rpc-req unchanged', () => {
const frame: Frame = { type: 'rpc-req', id: '1', kind: 'route', name: '/u/:id', ctx: env };
expect(decode(encode(frame))).toEqual(frame);
});
});
+125 -40
View File
@@ -1,15 +1,45 @@
import { describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { buildManifest, createMeshControl } from '../../src/mesh/teapot';
import { encode, decode } from '../../src/mesh/protocol';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
import { channel } from '../../src/channel';
import type { WsSocket } from '../../src/http/ws-core';
import { Unauthorized } from '../../src/signals';
const fakeWs = () => {
const ws: any = new EventEmitter();
ws.sent = [];
ws.send = (s: string) => ws.sent.push(decode(s));
ws.close = vi.fn();
return ws;
const V = MESH_PROTOCOL_VERSION;
/** Lets the control loop drain: it consumes `inbound` asynchronously and does not await RPCs. */
const settle = () => new Promise((resolve) => setTimeout(resolve, 5));
/**
* A fake neutral WsSocket — the same capability `nodeSocket` builds on Node and `app.upgrade`
* hands over on Deno/Bun. `close` also ends `inbound`, mirroring a real socket's close.
*/
const fakeSocket = () => {
const inbound = channel<unknown>();
const ac = new AbortController();
const sent: any[] = [];
const close = vi.fn((_code?: number, _reason?: string) => {
inbound.close();
ac.abort();
});
const socket: WsSocket = {
inbound,
abort: ac.signal,
isOpen: true,
send: (data: string) => {
sent.push(decode(data));
},
close,
terminate: () => ac.abort(),
};
/** Deliver a frame the way a peer would, then let the loop process it. */
const deliver = async (frame: unknown) => {
inbound.push(encode(frame as never));
await settle();
};
return { socket, sent, close, deliver, inbound };
};
describe('buildManifest', () => {
@@ -22,9 +52,15 @@ describe('buildManifest', () => {
});
describe('createMeshControl', () => {
const manifest = buildManifest({ providers: ['config'], steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] });
const make = (over: Partial<Parameters<typeof createMeshControl>[0]> = {}) => createMeshControl({
secret: 'good', manifest,
const manifest = buildManifest({
providers: ['config'],
steps: ['auth'],
routes: [{ method: 'GET', pattern: '/u/:id' }],
});
const make = (over: Partial<Parameters<typeof createMeshControl>[0]> = {}) =>
createMeshControl({
secret: 'good',
manifest,
resolveScope: async (name) => ({ resolved: name }),
resolveRoute: async () => ({ status: 200, headers: {}, body: 'route-body' }),
...over,
@@ -34,51 +70,100 @@ describe('createMeshControl', () => {
expect(make().path).toBe('/__mesh__/control');
});
it('rejects a bad secret and closes', () => {
const ws = fakeWs(); make().handle(ws);
ws.emit('message', encode({ type: 'hello', secret: 'wrong' }));
expect(ws.close).toHaveBeenCalledWith(1008);
expect(ws.sent).toEqual([]);
it('rejects a bad secret and closes', async () => {
const t = fakeSocket();
make().handle(t.socket);
await t.deliver({ type: 'hello', v: V, secret: 'wrong' });
expect(t.close).toHaveBeenCalledWith(1008);
expect(t.sent).toEqual([]);
});
it('answers a good hello with the manifest', () => {
const ws = fakeWs(); make().handle(ws);
ws.emit('message', encode({ type: 'hello', secret: 'good' }));
expect(ws.sent[0]).toMatchObject({ type: 'manifest', scopes: manifest.scopes });
it('answers a good hello with the manifest, stamped with the protocol version', async () => {
const t = fakeSocket();
make().handle(t.socket);
await t.deliver({ type: 'hello', v: V, secret: 'good' });
expect(t.sent[0]).toMatchObject({ type: 'manifest', v: V, scopes: manifest.scopes });
});
it('rejects a version-skewed peer before checking its secret, naming both versions', async () => {
const t = fakeSocket();
make().handle(t.socket);
// correct secret, wrong protocol: must still be refused — and not as an auth failure
await t.deliver({ type: 'hello', v: V + 1, secret: 'good' });
expect(t.sent).toEqual([]);
const [code, reason] = t.close.mock.calls[0];
expect(code).toBe(1008);
expect(reason).toContain(String(V));
expect(reason).toContain(String(V + 1));
});
it('refuses a version-skewed peer even when its secret is also wrong', async () => {
const t = fakeSocket();
make().handle(t.socket);
await t.deliver({ type: 'hello', v: V + 1, secret: 'wrong' });
expect(t.sent).toEqual([]);
expect(t.close).toHaveBeenCalled();
});
it('does NOT process rpc before handshake', async () => {
const ws = fakeWs(); make().handle(ws);
ws.emit('message', encode({ type: 'rpc-req', id: '1', kind: 'scope', name: 'config', ctx: {} as any }));
await new Promise((r) => setTimeout(r, 5));
expect(ws.sent).toEqual([]);
const t = fakeSocket();
make().handle(t.socket);
await t.deliver({ type: 'rpc-req', id: '1', kind: 'scope', name: 'config', ctx: {} });
expect(t.sent).toEqual([]);
});
it('resolves an exported scope after handshake', async () => {
const ws = fakeWs(); make().handle(ws);
ws.emit('message', encode({ type: 'hello', secret: 'good' }));
ws.emit('message', encode({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} as any }));
await new Promise((r) => setTimeout(r, 5));
expect(ws.sent.find((f: any) => f.type === 'rpc-res')).toEqual({ type: 'rpc-res', id: '7', ok: true, result: { resolved: 'config' } });
const t = fakeSocket();
make().handle(t.socket);
await t.deliver({ type: 'hello', v: V, secret: 'good' });
await t.deliver({ type: 'rpc-req', id: '7', kind: 'scope', name: 'config', ctx: {} });
expect(t.sent.find((f: any) => f.type === 'rpc-res')).toEqual({
type: 'rpc-res',
id: '7',
ok: true,
result: { resolved: 'config' },
});
});
it('rejects an unexported scope', async () => {
const ws = fakeWs(); make().handle(ws);
ws.emit('message', encode({ type: 'hello', secret: 'good' }));
ws.emit('message', encode({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} as any }));
await new Promise((r) => setTimeout(r, 5));
const res: any = ws.sent.find((f: any) => f.type === 'rpc-res');
const t = fakeSocket();
make().handle(t.socket);
await t.deliver({ type: 'hello', v: V, secret: 'good' });
await t.deliver({ type: 'rpc-req', id: '8', kind: 'scope', name: 'secretsvc', ctx: {} });
const res: any = t.sent.find((f: any) => f.type === 'rpc-res');
expect(res.ok).toBe(false);
expect(res.error.status).toBe(403);
});
it('propagates a thrown HttpError status in the error frame', async () => {
const ws = fakeWs();
make({ resolveScope: async () => { throw new Unauthorized('nope'); } }).handle(ws);
ws.emit('message', encode({ type: 'hello', secret: 'good' }));
ws.emit('message', encode({ type: 'rpc-req', id: '9', kind: 'scope', name: 'config', ctx: {} as any }));
await new Promise((r) => setTimeout(r, 5));
const res: any = ws.sent.find((f: any) => f.type === 'rpc-res');
const t = fakeSocket();
make({
resolveScope: async () => {
throw new Unauthorized('nope');
},
}).handle(t.socket);
await t.deliver({ type: 'hello', v: V, secret: 'good' });
await t.deliver({ type: 'rpc-req', id: '9', kind: 'scope', name: 'config', ctx: {} });
const res: any = t.sent.find((f: any) => f.type === 'rpc-res');
expect(res).toMatchObject({ id: '9', ok: false, error: { message: 'nope', status: 401 } });
});
it('serves overlapping RPCs concurrently rather than head-of-line blocking', async () => {
// the loop must not await handleRpc: a slow call would otherwise stall every later one.
// fast is delivered second but resolves first, which can only happen if they overlap.
const t = fakeSocket();
make({
resolveScope: async (name) => {
if (name === 'config') await new Promise((r) => setTimeout(r, 30));
return { resolved: name };
},
}).handle(t.socket);
await t.deliver({ type: 'hello', v: V, secret: 'good' });
t.inbound.push(encode({ type: 'rpc-req', id: 'slow', kind: 'scope', name: 'config', ctx: {} as never }));
t.inbound.push(encode({ type: 'rpc-req', id: 'fast', kind: 'scope', name: 'auth', ctx: {} as never }));
await new Promise((r) => setTimeout(r, 60));
const ids = t.sent.filter((f: any) => f.type === 'rpc-res').map((f: any) => f.id);
expect(ids).toEqual(['fast', 'slow']);
});
});
+34 -1
View File
@@ -3,7 +3,7 @@ import { expect, test, describe, it } from 'vitest';
import {
Provider, Step, Route, Get, Module,
getProviderMeta, getStepMeta, getRoutes, getModuleMeta,
Sse, Ws, Stream, Post,
Sse, Ws, Stream, Post, Head, Options,
} from '../src/metadata';
@Provider({ provides: 'db', needs: ['config'] })
@@ -54,6 +54,18 @@ describe('stream route decorators', () => {
});
});
describe('HEAD and OPTIONS decorators', () => {
it('records both as buffered methods', () => {
class Methods {
@Head('/resource') head() {}
@Options('/resource') options() {}
}
const byName = Object.fromEntries(getRoutes(Methods).map((route) => [route.handlerName, route]));
expect(byName.head).toMatchObject({ method: 'HEAD', transport: 'buffer', path: '/resource' });
expect(byName.options).toMatchObject({ method: 'OPTIONS', transport: 'buffer', path: '/resource' });
});
});
describe('mesh export flags', () => {
it('providers/steps carry export (default false)', () => {
@Provider({ provides: 'config', export: true }) class C { provide() { return {}; } }
@@ -74,3 +86,24 @@ describe('mesh export flags', () => {
expect(byName.priv.export).toBe(false);
});
});
import { Html, getHtmlMeta } from '../src/metadata';
describe('@Html', () => {
it('records empty meta for bare @Html', () => {
class A { @Html m() { return ''; } }
expect(getHtmlMeta(A, 'm')).toEqual({});
});
it('records path and template for called @Html', () => {
class B {
@Html('views/x.html') a() {}
@Html('views/y.html', { template: true }) c() { return {}; }
}
expect(getHtmlMeta(B, 'a')).toEqual({ path: 'views/x.html', template: undefined });
expect(getHtmlMeta(B, 'c')).toEqual({ path: 'views/y.html', template: true });
});
it('returns undefined when @Html is absent', () => {
class C { m() {} }
expect(getHtmlMeta(C, 'm')).toBeUndefined();
});
});
+106
View File
@@ -0,0 +1,106 @@
import 'reflect-metadata';
import { describe, it, expect } from 'vitest';
import { createApp } from '../src/app';
import { Route, Get, Head, Options, Post, Ws, Module } from '../src/metadata';
import { param, query, headers, body } from '../src/params';
const numSchema = {
'~standard': {
version: 1 as const,
vendor: 'test',
validate: (v: unknown) => ({ value: Number(v) }),
},
};
@Route('/users')
class Users {
@Get('/:id(\\d+)') get(@param('id') _id: string, @query('expand') _e: string, @headers('x-trace') _t: string) {
return {};
}
@Head('/:id(\\d+)') head() {
return {};
}
@Options('/:id(\\d+)') options() {
return {};
}
@Post('/') create(@body() _b: unknown) {
return {};
}
@Get('/:id/files/:path*') files(@param('path') _p: string) {
return {};
}
@Get('/search') search(@query('n', numSchema) _n: number) {
return {};
}
@Ws('/live') live() {
return (async function* () {})();
}
}
@Module({ mountpoint: '/api', controllers: [Users] })
class M {}
describe('app.openapi()', () => {
const doc = createApp({ modules: [M] }).openapi({ title: 'Demo', version: '1.2.3' });
it('emits a 3.1 doc with info overrides', () => {
expect(doc.openapi).toBe('3.1.0');
expect(doc.info).toEqual({ title: 'Demo', version: '1.2.3' });
});
it('templates path params: /users/:id → /users/{id}', () => {
expect(doc.paths['/api/users/{id}']).toBeDefined();
expect(doc.paths['/api/users/{id}/files/{path}']).toBeDefined();
});
it('derives path, query, and header parameters from the handler signature', () => {
const op = doc.paths['/api/users/{id}'].get as any;
const byName = Object.fromEntries(op.parameters.map((p: any) => [p.name, p.in]));
expect(byName).toEqual({ id: 'path', expand: 'query', 'x-trace': 'header' });
});
it('projects a constrained param into schema.pattern', () => {
const op = doc.paths['/api/users/{id}'].get as any;
expect(op.parameters).toContainEqual({
name: 'id',
in: 'path',
required: true,
schema: { type: 'string', pattern: '\\d+' },
});
});
it('includes explicit HEAD and OPTIONS without inventing automatic operations', () => {
expect(doc.paths['/api/users/{id}'].head).toBeDefined();
expect(doc.paths['/api/users/{id}'].options).toBeDefined();
expect(doc.paths['/api/users/search'].head).toBeUndefined();
expect(doc.paths['/api/users/search'].options).toBeUndefined();
});
it('marks routes that take a body with requestBody', () => {
const op = doc.paths['/api/users'].post as any;
expect(op.requestBody.content['application/json']).toBeDefined();
});
it('adds a 422 response when an argument is validated by a schema', () => {
const op = doc.paths['/api/users/search'].get as any;
expect(op.responses['422']).toBeDefined();
expect((doc.paths['/api/users/{id}'].get as any).responses['422']).toBeUndefined();
});
it('omits WebSocket routes', () => {
expect(doc.paths['/api/users/live']).toBeUndefined();
});
});
describe('GET /__openapi__', () => {
it('serves the document as JSON when devOpenapi is enabled', async () => {
const app = createApp({ modules: [M], devOpenapi: true });
const server = await app.listen(0);
const port = (server.address() as any).port;
const res = await fetch(`http://127.0.0.1:${port}/__openapi__`);
expect(res.headers.get('content-type')).toBe('application/json');
const json = (await res.json()) as any;
expect(json.openapi).toBe('3.1.0');
expect(json.paths['/api/users/{id}']).toBeDefined();
server.close();
});
});
+33
View File
@@ -0,0 +1,33 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
interface PackageMetadata {
readonly repository?: {
readonly type?: string;
readonly url?: string;
};
readonly bugs?: {
readonly url?: string;
};
readonly homepage?: string;
}
const packageJson = JSON.parse(readFileSync(resolve(process.cwd(), 'package.json'), 'utf8')) as PackageMetadata;
describe('package publication metadata', () => {
it('links npm provenance to the public GitHub repository', () => {
expect(packageJson.repository).toEqual({
type: 'git',
url: 'git+https://github.com/Expressive-Tea/green-tea.git',
});
});
it('links npm consumers to support and documentation', () => {
expect(packageJson.bugs).toEqual({
url: 'https://github.com/Expressive-Tea/green-tea/issues',
});
expect(packageJson.homepage).toBe('https://green-tea.expressive-tea.io/docs/');
});
});
+133
View File
@@ -0,0 +1,133 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import type { Server } from 'http';
import { createApp, Provider, Route, Get, Head, Options, Post, Module, needs, body, Sse } from '../src/index';
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: { v: 42 } };
}
}
@Route('/api')
class Ctl {
@Get('/x') x(@needs('db') d: any) {
return { v: d.v };
}
@Post('/y') y(@body() b: any) {
return { echo: b };
}
@Sse('/s') s() {
return (async function* () {
yield { n: 1 };
yield { n: 2 };
})();
}
@Get('/implicit-head') implicitHead() {
return { from: 'get' };
}
@Get('/explicit-head') explicitHeadGet() {
return { from: 'get' };
}
@Head('/explicit-head') explicitHead() {
return { from: 'head' };
}
@Get('/explicit-options') explicitOptionsGet() {
return { from: 'get' };
}
@Options('/explicit-options') explicitOptions() {
return { from: 'options' };
}
}
@Module({ mountpoint: '/', providers: [Db], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], cors: { origins: ['https://a.test'], credentials: false } });
// `app.listen` returns a Promise, so it's acquired in `beforeAll` rather than via a top-level
// `await` — this repo's tsconfig (module: commonjs, target: es2017) doesn't support top-level await.
let server: Server;
let base: string;
beforeAll(async () => {
server = await app.listen(0);
const port = (server.address() as any).port;
base = `http://127.0.0.1:${port}`;
});
afterAll(() => server.close());
const norm = (h: Headers) => {
const o: Record<string, string> = {};
h.forEach((v, k) => {
if (k !== 'date' && k !== 'connection' && k !== 'keep-alive' && k !== 'content-length' && k !== 'transfer-encoding')
o[k] = v;
});
return o;
};
async function both(path: string, init?: RequestInit) {
const node = await fetch(base + path, init);
const web = await app.fetch(new Request(base + path, init));
return { node, web };
}
describe('Node vs app.fetch parity (Node is truth)', () => {
it('GET /api/x', async () => {
const { node, web } = await both('/api/x');
expect(web.status).toBe(node.status);
expect(norm(web.headers)).toEqual(norm(node.headers));
expect(await web.json()).toEqual(await node.json());
});
it('POST /api/y', async () => {
const init = { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ a: 1 }) };
const { node, web } = await both('/api/y', init);
expect(web.status).toBe(node.status);
expect(await web.json()).toEqual(await node.json());
});
it('404', async () => {
const { node, web } = await both('/missing');
expect(web.status).toBe(node.status);
expect(norm(web.headers)).toEqual(norm(node.headers));
});
it('CORS preflight', async () => {
const init = { method: 'OPTIONS', headers: { origin: 'https://a.test', 'access-control-request-method': 'GET' } };
const { node, web } = await both('/api/x', init);
expect(web.status).toBe(node.status);
expect(norm(web.headers)).toEqual(norm(node.headers));
});
it('implicit and explicit HEAD return no body in both adapters', async () => {
for (const path of ['/api/implicit-head', '/api/explicit-head']) {
const { node, web } = await both(path, { method: 'HEAD' });
expect(node.status).toBe(200);
expect(web.status).toBe(node.status);
expect(await node.text()).toBe('');
expect(await web.text()).toBe('');
}
});
it('automatic OPTIONS is 204 with the same canonical Allow header', async () => {
const { node, web } = await both('/api/x', { method: 'OPTIONS' });
expect(node.status).toBe(204);
expect(web.status).toBe(204);
expect(node.headers.get('allow')).toBe('GET, HEAD, OPTIONS');
expect(web.headers.get('allow')).toBe(node.headers.get('allow'));
});
it('explicit OPTIONS route runs normally', async () => {
const { node, web } = await both('/api/explicit-options', { method: 'OPTIONS' });
expect(node.status).toBe(200);
expect(web.status).toBe(200);
expect(await node.json()).toEqual({ from: 'options' });
expect(await web.json()).toEqual({ from: 'options' });
});
it('rejects repeated slashes and malformed encoding with secure 400 responses', async () => {
for (const path of ['/api//x', '/api/%E0%A4%A']) {
const { node, web } = await both(path);
expect(node.status).toBe(400);
expect(web.status).toBe(400);
expect(node.headers.get('x-content-type-options')).toBe('nosniff');
expect(web.headers.get('x-content-type-options')).toBe('nosniff');
}
});
it('SSE first two events', async () => {
const nodeText = await (await fetch(base + '/api/s')).text();
const webText = await (await app.fetch(new Request(base + '/api/s'))).text();
expect(webText).toBe(nodeText);
});
});
+73 -6
View File
@@ -1,5 +1,5 @@
import { describe, expect, it, test, vi } from 'vitest';
import { runPipeline, isStreamResult } from '../src/pipeline';
import { runPipeline, runSteps, isStreamResult } from '../src/pipeline';
import { Bus } from '../src/bus';
import { JsonTransformer } from '../src/transformers';
import { Unauthorized } from '../src/signals';
@@ -9,7 +9,7 @@ const base = { transformer: JsonTransformer, seed: { req: { token: 'abc' } } };
test('runs steps, accumulates ctx, transforms handler return', async () => {
const bus = new Bus();
const res = await runPipeline({
...base, bus,
...base, bus, transport: 'buffer',
steps: [{ name: 'auth', origin: 'mod', run: (ctx) => ({ user: ctx.req.token }) }],
handler: (ctx) => ({ user: ctx.user }),
});
@@ -23,7 +23,7 @@ test('runs steps, accumulates ctx, transforms handler return', async () => {
test('a thrown HttpError short-circuits to an error response', async () => {
const bus = new Bus();
const res = await runPipeline({
...base, bus,
...base, bus, transport: 'buffer',
steps: [{ name: 'auth', origin: 'mod', run: () => { throw new Unauthorized('no'); } }],
handler: () => ({ never: true }),
});
@@ -37,7 +37,7 @@ test('emits enter/leave/error lifecycle events', async () => {
bus.on('request:step:enter', enter);
bus.on('request:step:error', error);
await runPipeline({
...base, bus,
...base, bus, transport: 'buffer',
steps: [{ name: 'boom', origin: 'mod', run: () => { throw new Unauthorized(); } }],
handler: () => ({}),
});
@@ -51,7 +51,7 @@ describe('runPipeline streaming', () => {
it('returns a StreamResult when the handler returns an AsyncIterable (transformer bypassed)', async () => {
async function* gen() { yield 1; yield 2; }
const res = await runPipeline({ steps: [], handler: () => gen(), transformer: noTransform, seed: {}, bus });
const res = await runPipeline({ steps: [], handler: () => gen(), transformer: noTransform, seed: {}, bus, transport: 'sse' });
expect(isStreamResult(res)).toBe(true);
if (isStreamResult(res)) {
const out: unknown[] = [];
@@ -61,8 +61,75 @@ describe('runPipeline streaming', () => {
});
it('still buffers a normal return through the transformer', async () => {
const res = await runPipeline({ steps: [], handler: () => 'hi', transformer: () => ({ body: 'HI' }), seed: {}, bus });
const res = await runPipeline({ steps: [], handler: () => 'hi', transformer: () => ({ body: 'HI' }), seed: {}, bus, transport: 'buffer' });
expect(isStreamResult(res)).toBe(false);
if (!isStreamResult(res)) expect(res.body).toBe('HI');
});
});
describe('runPipeline transport enforcement', () => {
const bus = new Bus();
const noTransform = (v: unknown) => ({ body: String(v) });
async function* gen() { yield 1; }
it('renders a 500 mismatch when a buffered route returns an AsyncIterable', async () => {
const res = await runPipeline({ steps: [], handler: () => gen(), transformer: noTransform, seed: {}, bus, transport: 'buffer' });
expect(isStreamResult(res)).toBe(false);
if (!isStreamResult(res)) {
expect(res.status).toBe(500);
expect(res.body).toContain('must return a value');
}
});
it('renders a 500 mismatch when a streaming route returns a non-iterable', async () => {
const res = await runPipeline({ steps: [], handler: () => ({ x: 1 }), transformer: noTransform, seed: {}, bus, transport: 'sse' });
expect(isStreamResult(res)).toBe(false);
if (!isStreamResult(res)) {
expect(res.status).toBe(500);
expect(res.body).toContain('must return an AsyncIterable');
}
});
it('negotiate tolerates a value (buffered)', async () => {
const res = await runPipeline({ steps: [], handler: () => 'hi', transformer: noTransform, seed: {}, bus, transport: 'negotiate' });
expect(isStreamResult(res)).toBe(false);
});
it('negotiate tolerates an AsyncIterable (stream)', async () => {
const res = await runPipeline({ steps: [], handler: () => gen(), transformer: noTransform, seed: {}, bus, transport: 'negotiate' });
expect(isStreamResult(res)).toBe(true);
});
});
describe('runSteps accumulation', () => {
// A chain where step k reads s{k-1} and provides s{k} = s{k-1} + 1: proves each
// step observes the previous ones' output (the graph's whole point).
const chain = (n: number) =>
Array.from({ length: n }, (_, i) => {
const k = i + 1;
return { name: `s${k}`, origin: 'mod', run: (ctx: any) => ({ [`s${k}`]: (ctx[`s${k - 1}`] ?? 0) + 1 }) };
});
it('each step sees prior outputs; the final context holds them all', async () => {
const ctx = await runSteps(chain(50), {}, new Bus());
expect(ctx.s1).toBe(1);
expect(ctx.s50).toBe(50); // 50 only lands if every step saw the previous
expect(Object.keys(ctx)).toHaveLength(50);
});
// Regression guard for the O(n^2) context merge (was `context = { ...context, ...output }`,
// which handed every step a freshly copied object — quadratic in the step count). The fix
// accumulates into ONE object in place, so every step must observe the same instance.
it('accumulates into a single object in place — never a per-step copy', async () => {
const seen: unknown[] = [];
const steps = Array.from({ length: 6 }, (_, i) => ({
name: `s${i}`,
origin: 'mod',
run: (ctx: any) => { seen.push(ctx); return { [`k${i}`]: i }; },
}));
const out = await runSteps(steps, { req: {} }, new Bus());
for (const ctx of seen) expect(ctx).toBe(seen[0]); // a spread would hand each step a new object
expect(out).toBe(seen[0]); // and the returned context is that same accumulator
expect((out as any).k5).toBe(5);
});
});
+77 -4
View File
@@ -1,5 +1,12 @@
import { describe, it, expect } from 'vitest';
import { matchPattern, matchRoute, allowedMethods } from '../src/http/router';
import {
compilePattern,
matchPattern,
matchRoute,
resolveRoute,
allowedMethods,
normalizeRequestPath,
} from '../src/http/router';
import type { RouteDef } from '../src/http/types';
const route = (method: string, pattern: string): RouteDef => ({
@@ -10,6 +17,11 @@ const route = (method: string, pattern: string): RouteDef => ({
});
describe('matchPattern', () => {
it('matches the root pattern only at root', () => {
expect(matchPattern('/', '/')).toEqual({});
expect(matchPattern('/', '/users')).toBeUndefined();
});
it('matches static and :param segments, decoding params', () => {
expect(matchPattern('/users/:id', '/users/a%20b')).toEqual({ id: 'a b' });
expect(matchPattern('/users/:id', '/users')).toBeUndefined();
@@ -24,6 +36,46 @@ describe('matchPattern', () => {
it(':name* matches zero remaining segments as an empty string', () => {
expect(matchPattern('/files/:path*', '/files')).toEqual({ path: '' });
});
it('matches safe constraints against the complete decoded segment', () => {
expect(matchPattern('/users/:id(\\d+)', '/users/42')).toEqual({ id: '42' });
expect(matchPattern('/users/:id(\\d+)', '/users/42x')).toBeUndefined();
expect(matchPattern('/posts/:slug([a-z0-9_-]+)', '/posts/green-tea_26')).toEqual({ slug: 'green-tea_26' });
expect(matchPattern('/build/:version(\\d{2}\\.\\d{1,2})', '/build/26.8')).toEqual({ version: '26.8' });
});
});
describe('compilePattern', () => {
it('records a stable shape independent of parameter names', () => {
expect(compilePattern('/users/:id').shape).toBe(compilePattern('/users/:name').shape);
expect(compilePattern('/users/:id(\\d+)').shape).not.toBe(compilePattern('/users/:id').shape);
});
it.each([
'/files/:rest*/tail',
'/users/:',
'/users/:id/:id',
'/users//:id',
'/users/:id((a+)+)',
'/users/:id((?=a)a)',
'/users/:id(\\1)',
'/users/:id(a|b)',
])('rejects invalid or unsafe pattern %s', (pattern) => {
expect(() => compilePattern(pattern)).toThrow(/invalid route pattern|unsafe route constraint/);
});
});
describe('normalizeRequestPath', () => {
it('treats one trailing slash as equivalent and preserves root', () => {
expect(normalizeRequestPath('/users')).toBe('/users');
expect(normalizeRequestPath('/users/')).toBe('/users');
expect(normalizeRequestPath('/')).toBe('/');
});
it('rejects repeated slashes and malformed percent encoding', () => {
expect(() => normalizeRequestPath('/users//42')).toThrow(/repeated slash/);
expect(() => normalizeRequestPath('/users/%E0%A4%A')).toThrow(/malformed path encoding/);
});
});
describe('matchRoute precedence', () => {
@@ -34,6 +86,12 @@ describe('matchRoute precedence', () => {
expect(matchRoute(routes, 'GET', '/a/x/y')?.def.pattern).toBe('/a/:rest*');
});
it('constrained params beat unconstrained params regardless of registration order', () => {
const routes = [route('GET', '/users/:value'), route('GET', '/users/:id(\\d+)')];
expect(matchRoute(routes, 'GET', '/users/42')?.def.pattern).toBe('/users/:id(\\d+)');
expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value');
});
it('returns undefined when no pattern matches the path', () => {
expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined();
});
@@ -44,9 +102,24 @@ describe('matchRoute precedence', () => {
});
describe('allowedMethods (405 support)', () => {
it('lists distinct methods whose pattern matches the path', () => {
const routes = [route('GET', '/a'), route('POST', '/a'), route('GET', '/b')];
expect(allowedMethods(routes, '/a').sort()).toEqual(['GET', 'POST']);
it('lists methods in canonical order with implicit HEAD and OPTIONS', () => {
const routes = [route('POST', '/a'), route('GET', '/a'), route('GET', '/b')];
expect(allowedMethods(routes, '/a')).toEqual(['GET', 'HEAD', 'POST', 'OPTIONS']);
expect(allowedMethods(routes, '/nope')).toEqual([]);
});
});
describe('resolveRoute', () => {
it('prefers explicit HEAD and otherwise falls back to buffered GET', () => {
const explicit = [route('GET', '/a'), route('HEAD', '/a')];
expect(resolveRoute(explicit, 'HEAD', '/a')).toMatchObject({ implicitHead: false, def: { method: 'HEAD' } });
const fallback = resolveRoute([route('GET', '/a')], 'HEAD', '/a');
expect(fallback).toMatchObject({ implicitHead: true, def: { method: 'GET' } });
});
it('does not use a streaming GET as implicit HEAD', () => {
const streaming = { ...route('GET', '/a'), transport: 'sse' as const };
expect(resolveRoute([streaming], 'HEAD', '/a')).toBeUndefined();
});
});
+9 -2
View File
@@ -1,6 +1,13 @@
import { expect, test } from 'vitest';
import { VERSION } from '../src/index';
import { Head, Options, VERSION, type HttpMethod } from '../src/index';
test('package loads and exposes a CalVer VERSION', () => {
expect(VERSION).toMatch(/^\d{2}\.\d{2}\.\d+(-beta\.\d+)?$/);
expect(VERSION).toMatch(/^\d{2}\.\d{1,2}\.\d+(-beta\.\d+)?$/);
});
test('public barrel exports HEAD and OPTIONS route decorators', () => {
const methods: HttpMethod[] = ['HEAD', 'OPTIONS'];
expect(Head).toBeTypeOf('function');
expect(Options).toBeTypeOf('function');
expect(methods).toEqual(['HEAD', 'OPTIONS']);
});
+17
View File
@@ -0,0 +1,17 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
const workflow = readFileSync(resolve(process.cwd(), '.github/workflows/stage.yml'), 'utf8');
describe('Verdaccio staging workflow', () => {
it('replaces mutable prereleases only from release branches', () => {
expect(workflow).toContain("branches: ['release/**']");
expect(workflow).toContain('npm audit');
expect(workflow).toContain('npm run prepublishOnly');
expect(workflow).toContain('npm unpublish');
expect(workflow).toContain('npm publish --ignore-scripts');
expect(workflow).not.toContain('scripts/staging-integrity.ts');
});
});
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest';
import { createApp, Route, Get, Sse, Module } from '../src/index';
@Route('/api')
class Ctl {
@Get('/ok') ok() { return { ok: true }; } // buffered value — fine
@Get('/leak') leak() { return (async function* () { yield 1; })(); } // buffered + iterable — 500
@Sse('/stream') stream() { return (async function* () { yield { n: 1 }; })(); } // stream — fine
@Sse('/empty') empty() { return { not: 'a stream' }; } // stream + value — 500
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
describe('transport enforcement (integration)', () => {
it('a normal buffered GET still returns its value', async () => {
const res = await app.fetch(new Request('http://x/api/ok'));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ ok: true });
});
it('a buffered GET that returns an AsyncIterable is a 500 mismatch', async () => {
const res = await app.fetch(new Request('http://x/api/leak'));
expect(res.status).toBe(500);
expect(await res.text()).toContain('must return a value');
});
it('a normal SSE stream still streams', async () => {
const res = await app.fetch(new Request('http://x/api/stream'));
expect(res.status).toBe(200);
expect(res.headers.get('content-type')).toContain('text/event-stream');
});
it('an SSE route that returns a plain value is a 500 mismatch', async () => {
const res = await app.fetch(new Request('http://x/api/empty'));
expect(res.status).toBe(500);
expect(await res.text()).toContain('must return an AsyncIterable');
});
});
+5 -5
View File
@@ -187,7 +187,7 @@ describe('CORS', () => {
expect(r.headers.get('access-control-allow-credentials')).toBe('true');
});
it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) → 405 Allow for an existing path', async () => {
it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) → automatic 204 Allow', async () => {
@Route('/') class C { @Get('/x') x() { return { ok: 1 }; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } });
@@ -195,11 +195,11 @@ describe('CORS', () => {
const port = (server.address() as any).port;
const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://evil.com' } });
expect(r.headers.get('access-control-allow-origin')).toBeNull();
// A bare OPTIONS (no Access-Control-Request-Method) isn't a CORS preflight; the path exists
// under GET, so the router answers 405 with an Allow header rather than 404.
// A bare OPTIONS (no Access-Control-Request-Method) isn't a CORS preflight; the router
// answers it automatically and advertises the explicit + implicit methods.
const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' });
expect(bare.status).toBe(405);
expect(bare.headers.get('allow')).toContain('GET');
expect(bare.status).toBe(204);
expect(bare.headers.get('allow')).toBe('GET, HEAD, OPTIONS');
});
it("merges a handler's Title-Case Vary with CORS's Origin", async () => {
+59
View File
@@ -0,0 +1,59 @@
import { describe, expect, it } from 'vitest';
import { writeFileSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createApp, Route, Get, Sse, Transformer, Html, Module } from '../src/index';
const dir = join(tmpdir(), 'gt-views-test');
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, 'dash.html'), '<h1>Dash</h1>');
writeFileSync(join(dir, 'user.html'), '<h1>Hi {{ name }}</h1>');
@Route('/')
class Views {
@Get('/str') @Html str() { return '<p>inline</p>'; }
@Get('/dash') @Html('dash.html') dash() {}
@Get('/user') @Html('user.html', { template: true }) user() { return { name: '<b>D</b>' }; }
}
@Module({ mountpoint: '/', controllers: [Views] })
class M {}
const app = createApp({ modules: [M], views: dir });
describe('@Html modes', () => {
it('string mode sends the handler return as text/html', async () => {
const res = await app.fetch(new Request('http://x/str'));
expect(res.headers.get('content-type')).toBe('text/html; charset=utf-8');
expect(await res.text()).toBe('<p>inline</p>');
});
it('path mode serves the file and ignores the return', async () => {
expect(await (await app.fetch(new Request('http://x/dash'))).text()).toBe('<h1>Dash</h1>');
});
it('template mode renders the file with returned data, escaping by default', async () => {
expect(await (await app.fetch(new Request('http://x/user'))).text()).toBe('<h1>Hi &lt;b&gt;D&lt;/b&gt;</h1>');
});
});
describe('@Html boot validation', () => {
it('rejects @Html on a streaming (SSE) route', () => {
@Route('/') class Bad { @Sse('/s') @Html s() { return (async function* () {})(); } }
@Module({ mountpoint: '/', controllers: [Bad] }) class BM {}
expect(() => createApp({ modules: [BM] })).toThrow(/@Html/);
});
it('rejects @Html combined with @Transformer', () => {
const t = (v: unknown) => ({ status: 200, headers: {}, body: String(v) });
@Route('/') class Bad2 { @Get('/g') @Html @Transformer(t) g() { return ''; } }
@Module({ mountpoint: '/', controllers: [Bad2] }) class BM2 {}
expect(() => createApp({ modules: [BM2] })).toThrow(/@Html and @Transformer/);
});
});
describe('viewEngine override', () => {
it('uses a bring-your-own engine for template mode', async () => {
const app2 = createApp({
modules: [M],
views: dir,
viewEngine: (source, data: any) => source.replace('{{ name }}', `RAW:${data.name}`),
});
expect(await (await app2.fetch(new Request('http://x/user'))).text()).toBe('<h1>Hi RAW:<b>D</b></h1>');
});
});
+55
View File
@@ -0,0 +1,55 @@
import { describe, expect, it } from 'vitest';
import { writeFileSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createApp, Route, Get, Module } from '../src/index';
import { buildStaticResolver } from '../src/views';
const root = join(tmpdir(), 'gt-static-test');
mkdirSync(root, { recursive: true });
writeFileSync(join(root, 'index.html'), '<h1>Home</h1>');
writeFileSync(join(root, 'app.css'), 'body{}');
writeFileSync(join(tmpdir(), 'gt-secret.txt'), 'TOP SECRET');
@Route('/api')
class Api {
@Get('/ping')
ping() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Api] })
class M {}
const app = createApp({ modules: [M], static: root });
describe('static serving', () => {
it('serves a file by path with its content-type', async () => {
const res = await app.fetch(new Request('http://x/app.css'));
expect(res.status).toBe(200);
expect(res.headers.get('content-type')).toBe('text/css; charset=utf-8');
expect(await res.text()).toBe('body{}');
});
it('serves index.html for /', async () => {
expect(await (await app.fetch(new Request('http://x/'))).text()).toBe('<h1>Home</h1>');
});
it('declared routes win over static', async () => {
expect(await (await app.fetch(new Request('http://x/api/ping'))).json()).toEqual({ ok: true });
});
it('returns 404 for a missing file', async () => {
expect((await app.fetch(new Request('http://x/nope.html'))).status).toBe(404);
});
it('rejects path traversal', async () => {
const res = await app.fetch(new Request('http://x/../gt-secret.txt'));
expect(res.status).toBe(404);
});
it('answers HEAD with headers and no body', async () => {
const res = await app.fetch(new Request('http://x/app.css', { method: 'HEAD' }));
expect(res.status).toBe(200);
expect(await res.text()).toBe('');
});
it('resolver refuses to escape its root', async () => {
const resolve = buildStaticResolver(root);
expect(await resolve('/../gt-secret.txt')).toBeUndefined();
expect(await resolve('/%2e%2e/gt-secret.txt')).toBeUndefined();
});
});
+28
View File
@@ -0,0 +1,28 @@
import { describe, expect, it } from 'vitest';
import { render, escapeHtml, contentTypeFor } from '../src/views';
describe('escapeHtml', () => {
it('escapes the five HTML-significant characters', () => {
expect(escapeHtml(`<a href="x">&'`)).toBe('&lt;a href=&quot;x&quot;&gt;&amp;&#39;');
});
});
describe('render', () => {
it('interpolates and HTML-escapes {{ x }} by default', () => {
expect(render('<h1>{{ name }}</h1>', { name: '<b>hi</b>' })).toBe('<h1>&lt;b&gt;hi&lt;/b&gt;</h1>');
});
it('leaves {{{ x }}} raw (unescaped)', () => {
expect(render('{{{ html }}}', { html: '<b>hi</b>' })).toBe('<b>hi</b>');
});
it('resolves nested keys and renders missing keys as empty', () => {
expect(render('{{ user.name }}|{{ nope }}', { user: { name: 'Diego' } })).toBe('Diego|');
});
});
describe('contentTypeFor', () => {
it('maps known extensions and defaults unknown to octet-stream', () => {
expect(contentTypeFor('.css')).toBe('text/css; charset=utf-8');
expect(contentTypeFor('.PNG')).toBe('image/png');
expect(contentTypeFor('.xyz')).toBe('application/octet-stream');
});
});
+25
View File
@@ -0,0 +1,25 @@
import { describe, it, expect } from 'vitest';
import { asReadableStream } from '../src/http/web';
import { sseEncoder } from '../src/encoders';
async function* nums() { yield { n: 1 }; yield { n: 2 }; }
describe('asReadableStream', () => {
it('encodes each yielded value with the encoder', async () => {
const rs = asReadableStream(nums(), sseEncoder);
const text = await new Response(rs).text();
expect(text).toContain('data: {"n":1}');
expect(text).toContain('data: {"n":2}');
});
it('cancels the source iterator when the stream is cancelled', async () => {
let returned = false;
async function* forever() { try { while (true) yield { t: 1 }; } finally { returned = true; } }
const rs = asReadableStream(forever(), sseEncoder);
const reader = rs.getReader();
await reader.read();
await reader.cancel();
await new Promise((r) => setTimeout(r, 10));
expect(returned).toBe(true);
});
});
+112
View File
@@ -0,0 +1,112 @@
import { describe, it, expect } from 'vitest';
import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from '../src/http/ws-core';
import { channel } from '../src/channel';
import { HttpError } from '../src/signals';
import type { WsRouteDef } from '../src/http/types';
/** A controllable fake WsSocket that records sends and closes. */
function fakeSocket() {
const inbound = channel<unknown>();
const ac = new AbortController();
const sent: string[] = [];
const closes: Array<{ code?: number; reason?: string }> = [];
let open = true;
const socket: WsSocket = {
inbound,
abort: ac.signal,
get isOpen() {
return open;
},
send: (d) => sent.push(d),
close: (code, reason) => {
open = false;
closes.push({ code, reason });
ac.abort();
},
terminate: () => {
open = false;
ac.abort();
},
};
return { socket, inbound, sent, closes, ac };
}
const req: WsRequest = { url: '/ws', headers: {}, protocol: 'http', ip: '127.0.0.1' };
describe('runWsConnection (neutral core)', () => {
it('sends each yielded outbound value, string or JSON', async () => {
const def: WsRouteDef = {
pattern: '/ws',
open: async () =>
(async function* () {
yield 'hi';
yield { n: 1 };
})(),
};
const { socket, sent } = fakeSocket();
await runWsConnection(socket, req, { def, params: {} });
expect(sent).toEqual(['hi', JSON.stringify({ n: 1 })]);
});
it('closes with 4000+status when the route throws an HttpError', async () => {
const def: WsRouteDef = {
pattern: '/ws',
open: async () => {
throw new HttpError(401, 'nope');
},
};
const { socket, closes } = fakeSocket();
await runWsConnection(socket, req, { def, params: {} });
expect(closes[0].code).toBe(4401);
expect(closes[0].reason).toBe('nope');
});
it('closes with 1011 on a generic throw', async () => {
const def: WsRouteDef = {
pattern: '/ws',
open: async () => {
throw new Error('boom');
},
};
const { socket, closes } = fakeSocket();
await runWsConnection(socket, req, { def, params: {} });
expect(closes[0].code).toBe(1011);
});
it('registers a closer in the shutdown registry and removes it when done', async () => {
const streams = new Set<() => void>();
const def: WsRouteDef = {
pattern: '/ws',
open: async () =>
(async function* () {
yield 'x';
})(),
};
const { socket } = fakeSocket();
await runWsConnection(socket, req, { def, params: {} }, undefined, streams);
expect(streams.size).toBe(0); // added then removed
});
it('passes inbound + params + request to route.open', async () => {
let seen: any;
const def: WsRouteDef = {
pattern: '/ws/:id',
open: async (ctx) => {
seen = ctx;
return (async function* () {})();
},
};
const { socket } = fakeSocket();
await runWsConnection(socket, req, { def, params: { id: '7' } });
expect(seen.params).toEqual({ id: '7' });
expect(seen.req).toBe(req);
expect(typeof seen.inbound[Symbol.asyncIterator]).toBe('function');
expect(seen.abort).toBeInstanceOf(AbortSignal);
});
it('matchWsRoute finds a pattern and captures params', () => {
const routes: WsRouteDef[] = [{ pattern: '/ws/:id', open: async () => (async function* () {})() }];
expect(matchWsRoute(routes, '/ws/42')?.params).toEqual({ id: '42' });
expect(matchWsRoute(routes, '/nope')).toBeUndefined();
});
});
+2 -1
View File
@@ -14,5 +14,6 @@
"emitDecoratorMetadata": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src", "test", "example"]
"include": ["src", "test", "example"],
"exclude": ["test/deno", "test/bun", "test/edge"]
}
+1 -1
View File
@@ -4,7 +4,7 @@ import { defineConfig } from 'tsup';
// tsup injects a createRequire shim into the ESM output so the lazy require('ws') / require('busboy')
// (optional peer deps) keep working there. reflect-metadata and the peer deps stay external.
export default defineConfig({
entry: ['src/index.ts'],
entry: ['src/index.ts', 'src/deno.ts', 'src/bun.ts', 'src/edge.ts'],
format: ['cjs', 'esm'],
dts: true,
clean: true,
+9 -2
View File
@@ -1,5 +1,12 @@
import { defineConfig } from 'vitest/config';
import { defineConfig, configDefaults } from 'vitest/config';
export default defineConfig({
test: { globals: false, environment: 'node', include: ['test/**/*.test.ts'] },
test: {
globals: false,
environment: 'node',
include: ['test/**/*.test.ts'],
// test/deno/** holds Deno.test files run separately via `npm run test:deno`;
// they use `npm:`/`jsr:` specifiers vitest can't resolve.
exclude: [...configDefaults.exclude, 'test/deno/**', 'test/bun/**', 'test/edge/**'],
},
});
+26 -3
View File
@@ -3,11 +3,29 @@ import starlight from '@astrojs/starlight';
// Docs site for @green-tea/core. Content lives in src/content/docs/**.
export default defineConfig({
site: 'https://green-tea.dev',
site: 'https://green-tea.expressive-tea.io',
base: '/docs',
integrations: [
starlight({
title: 'green-tea',
description: 'A calm, type-safe HTTP framework for Node — your API is an explicit dependency graph.',
// GoatCounter — same site code as the marketing site, so /docs traffic lands in
// the same dashboard and referrer paths stay comparable.
head: [
{
tag: 'script',
attrs: {
'data-goatcounter': 'https://greentea.goatcounter.com/count',
async: true,
src: '//gc.zgo.at/count.js',
},
},
],
// Let the content-backed 404.md own /404; otherwise Astro also injects a conflicting route.
disable404Route: true,
title: 'Green Tea.',
description: 'A zen, opinionated, type-safe framework — your API is a graph, not a chain.',
logo: { src: './src/assets/logo.svg', alt: 'Green Tea' },
favicon: '/favicon.svg',
customCss: ['./src/styles/brand.css'],
tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 3 },
sidebar: [
{
@@ -27,15 +45,20 @@ export default defineConfig({
{
label: 'Guides',
items: [
{ label: 'The matcha CLI', slug: 'guides/cli' },
{ label: 'Routing', slug: 'guides/routing' },
{ label: 'Dependency injection', slug: 'guides/dependency-injection' },
{ label: 'Argument decorators', slug: 'guides/arguments' },
{ label: 'Validation', slug: 'guides/validation' },
{ label: 'Error handling', slug: 'guides/errors' },
{ label: 'Streaming & real-time', slug: 'guides/streaming' },
{ label: 'File uploads', slug: 'guides/uploads' },
{ label: 'HTML & views', slug: 'guides/html' },
{ label: 'Transport security', slug: 'guides/security' },
{ label: 'Plugins & observability', slug: 'guides/plugins' },
{ label: 'Graph introspection', slug: 'guides/introspection' },
{ label: 'OpenAPI', slug: 'guides/openapi' },
{ label: 'Runtimes', slug: 'guides/runtimes' },
{ label: 'Testing', slug: 'guides/testing' },
{ label: 'Mesh (alpha)', slug: 'guides/mesh', badge: { text: 'alpha', variant: 'caution' } },
],
+161 -174
View File
@@ -6,35 +6,35 @@
"": {
"name": "green-tea-docs",
"dependencies": {
"@astrojs/starlight": "^0.41.3",
"astro": "^7.0.6",
"@astrojs/starlight": "^0.41.6",
"astro": "^7.1.6",
"sharp": "^0.35.3"
}
},
"node_modules/@astrojs/compiler-binding": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding/-/compiler-binding-0.3.0.tgz",
"integrity": "sha512-zlsOT5COD9hRwplJCgQhS21unxON5AKirf0vgt1ijXwuseYIaZdm2ZOpF8fsz+DY9EyXx+I/ukxtg7uoBep68A==",
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding/-/compiler-binding-0.3.2.tgz",
"integrity": "sha512-8w/9CWmYrAJJ8N0SY3O43ws2BgxoW6u3QsD8u2mE140lMYAlwh+tlNoUeSBq22wVheFuiBbR212l6ixZ2IIgCQ==",
"license": "MIT",
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"optionalDependencies": {
"@astrojs/compiler-binding-darwin-arm64": "0.3.0",
"@astrojs/compiler-binding-darwin-x64": "0.3.0",
"@astrojs/compiler-binding-linux-arm64-gnu": "0.3.0",
"@astrojs/compiler-binding-linux-arm64-musl": "0.3.0",
"@astrojs/compiler-binding-linux-x64-gnu": "0.3.0",
"@astrojs/compiler-binding-linux-x64-musl": "0.3.0",
"@astrojs/compiler-binding-wasm32-wasi": "0.3.0",
"@astrojs/compiler-binding-win32-arm64-msvc": "0.3.0",
"@astrojs/compiler-binding-win32-x64-msvc": "0.3.0"
"@astrojs/compiler-binding-darwin-arm64": "0.3.2",
"@astrojs/compiler-binding-darwin-x64": "0.3.2",
"@astrojs/compiler-binding-linux-arm64-gnu": "0.3.2",
"@astrojs/compiler-binding-linux-arm64-musl": "0.3.2",
"@astrojs/compiler-binding-linux-x64-gnu": "0.3.2",
"@astrojs/compiler-binding-linux-x64-musl": "0.3.2",
"@astrojs/compiler-binding-wasm32-wasi": "0.3.2",
"@astrojs/compiler-binding-win32-arm64-msvc": "0.3.2",
"@astrojs/compiler-binding-win32-x64-msvc": "0.3.2"
}
},
"node_modules/@astrojs/compiler-binding-darwin-arm64": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-arm64/-/compiler-binding-darwin-arm64-0.3.0.tgz",
"integrity": "sha512-3n0uu+uJpnCq8b4JFi3uGDsIisAvHctxSmH+cIO9Gbei1H1Y1QXaYboXyiWJugUmprr3OEYP7+LdodzpVFzLMQ==",
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-arm64/-/compiler-binding-darwin-arm64-0.3.2.tgz",
"integrity": "sha512-MM8tn8CSimcfytaOla4b6acN8mKWiL/rlAA1fpT3/Wl7dNGSE4y8FjTN/zJVNnb63CsLWG5zZwCt01TXtDKh9g==",
"cpu": [
"arm64"
],
@@ -48,9 +48,9 @@
}
},
"node_modules/@astrojs/compiler-binding-darwin-x64": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-x64/-/compiler-binding-darwin-x64-0.3.0.tgz",
"integrity": "sha512-scxNGKjOBydMo1QR4LtK0FMgh7ubQomJDv953nz2msQFkPKke/0FpPv/cQM0T/kuZdReZQFU8Oz3iOrP/6WHEg==",
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-x64/-/compiler-binding-darwin-x64-0.3.2.tgz",
"integrity": "sha512-2lXOlzf8xb7jLomRsf/aswh61/NnGusynB2OwFkK6k4pmOtpfXMYnG0PLfXrEvxXYj69NdCnmUYXtHDd+JOOag==",
"cpu": [
"x64"
],
@@ -64,9 +64,9 @@
}
},
"node_modules/@astrojs/compiler-binding-linux-arm64-gnu": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-gnu/-/compiler-binding-linux-arm64-gnu-0.3.0.tgz",
"integrity": "sha512-NZrWLolVUANmrnl0zrFK/Sx5Sock1gEUT49ALfMTTCA5Ya2ec/BoJXMIg4KgE+wZcrdXJ8e+WyEhM7YLk/FJkA==",
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-gnu/-/compiler-binding-linux-arm64-gnu-0.3.2.tgz",
"integrity": "sha512-BmU3kWj7qnLrd4vzm49zFEPJ5oFnn1tCT4Vt9hZbqdU5Cmb8GZl7fn6VFsnNfe7B18a2gIFtVzbLINtYl5kBjQ==",
"cpu": [
"arm64"
],
@@ -80,9 +80,9 @@
}
},
"node_modules/@astrojs/compiler-binding-linux-arm64-musl": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-musl/-/compiler-binding-linux-arm64-musl-0.3.0.tgz",
"integrity": "sha512-PjwRmKgMFDsFhg82g0poXlIY8Qn3fMA3hXjaR0coJWJzTJsRH9ATU0j2ocigjtU1h3vL/yR7yLUxGj/lTCq73g==",
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-musl/-/compiler-binding-linux-arm64-musl-0.3.2.tgz",
"integrity": "sha512-f0heT9ZZEseSu5bHCeb80eL2DH07ArE6U9xi1WT/PEusNjzPmEr3GJsjG1tRLo5VYUUYX7h3ScaqGmGrMOVGmw==",
"cpu": [
"arm64"
],
@@ -96,9 +96,9 @@
}
},
"node_modules/@astrojs/compiler-binding-linux-x64-gnu": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-gnu/-/compiler-binding-linux-x64-gnu-0.3.0.tgz",
"integrity": "sha512-Dr69VJYlnSfyL8gzELW6S4mE41P7TDPn1IKjwMnjdZ7+dxgJI50oMLFSk1LVe26bHmWB3ktuh8fDVK1THI9e9A==",
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-gnu/-/compiler-binding-linux-x64-gnu-0.3.2.tgz",
"integrity": "sha512-M8fOUt0itRpqiGyoEA/ij184s8O+hqbCz3+YozRusOOM3osgGljpDThhbKAJjqh82wOo6FioQ4w8PBvU1XMD5Q==",
"cpu": [
"x64"
],
@@ -112,9 +112,9 @@
}
},
"node_modules/@astrojs/compiler-binding-linux-x64-musl": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-musl/-/compiler-binding-linux-x64-musl-0.3.0.tgz",
"integrity": "sha512-AEt+bRw8PfImCcyRH1lpXVB8CdmQ1K/wPo5u99iec4/U/XdNvQZ715YVuNzIJpbJXelgQeZ5H2+Ea7XwRyWY5g==",
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-musl/-/compiler-binding-linux-x64-musl-0.3.2.tgz",
"integrity": "sha512-/Kebk8sO6HnLeSd691JkaAPfN7CqR9/KEXmWvyNPkaKNGmj8rTZ/lf2uXtnPu92Lan84UrKdIKVPy1fSo2encQ==",
"cpu": [
"x64"
],
@@ -128,25 +128,25 @@
}
},
"node_modules/@astrojs/compiler-binding-wasm32-wasi": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-wasm32-wasi/-/compiler-binding-wasm32-wasi-0.3.0.tgz",
"integrity": "sha512-U80tA1j8V6LjhiTZzVCtG4E8hrNVVNXDGV5fCgJ94q8FU9CPH+XwdDDhLzBybfWhKfyItXmQiZNRPTiPCYTpVg==",
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-wasm32-wasi/-/compiler-binding-wasm32-wasi-0.3.2.tgz",
"integrity": "sha512-pUA6xbcOSB7DhfzIArB8BCAkFfAIqriiR7zl5zOStd6oU2G0kIKj+GUdGnyXyhfiv881Hffyk5tC0mR18sDjDw==",
"cpu": [
"wasm32"
],
"license": "MIT",
"optional": true,
"dependencies": {
"@napi-rs/wasm-runtime": "^1.1.6"
"@napi-rs/wasm-runtime": "^1.2.0"
},
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/@astrojs/compiler-binding-win32-arm64-msvc": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-arm64-msvc/-/compiler-binding-win32-arm64-msvc-0.3.0.tgz",
"integrity": "sha512-CpY1RII2r1XMpOUVD1VR/F2wtuRsiOCkFULS10Khyj8/DFZMtxVuUCAWGw+CW2Ka0h6eP3Xc1CA+glFlvXMPxA==",
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-arm64-msvc/-/compiler-binding-win32-arm64-msvc-0.3.2.tgz",
"integrity": "sha512-ESruf+6Qkl1trHUFxI6GSf6t52j8yN2kCNSzMWdzt7V/T09tFHrYzrVaJQohb2C9bJUH76pNvX6Zb51+xCQc9Q==",
"cpu": [
"arm64"
],
@@ -160,9 +160,9 @@
}
},
"node_modules/@astrojs/compiler-binding-win32-x64-msvc": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-x64-msvc/-/compiler-binding-win32-x64-msvc-0.3.0.tgz",
"integrity": "sha512-qmFbs769oeeGrRebAnCW7aBk8m71vf85W/dX/jddfx5Z06/w0wf7TZCfJPOX1Fld2t+4N+iXzfGEJG+zJQ+bzg==",
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-x64-msvc/-/compiler-binding-win32-x64-msvc-0.3.2.tgz",
"integrity": "sha512-wzzVrEbOwbsLWOdEbocskjMRx2aZPxJ7ZbmL+jnpBamFwmigm+2M/wzuM6JWncocgYwLic1csSpalBh96kQKXA==",
"cpu": [
"x64"
],
@@ -176,12 +176,12 @@
}
},
"node_modules/@astrojs/compiler-rs": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-rs/-/compiler-rs-0.3.0.tgz",
"integrity": "sha512-J2qEVHtIDjEM9TxwmwuebOGmZNwhKu/dR7P7qBpnJKGmBBX0vdweQ/4cEXhj8fBbWVUB5V12xWChri3CgKNULQ==",
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-rs/-/compiler-rs-0.3.2.tgz",
"integrity": "sha512-xlx/T7JovIKduu4ucbTQUxQ5+Q8wxkHxhLjnZk3VlJbhbQ9RLvvuDk1p2YYFYFQ5y14dVm3FGGO4isQXa4F+Tg==",
"license": "MIT",
"dependencies": {
"@astrojs/compiler-binding": "0.3.0"
"@astrojs/compiler-binding": "0.3.2"
},
"engines": {
"node": ">=22.12.0"
@@ -203,41 +203,33 @@
"unified": "^11.0.5"
}
},
"node_modules/@astrojs/markdown-remark": {
"version": "7.2.1",
"resolved": "https://registry.npmjs.org/@astrojs/markdown-remark/-/markdown-remark-7.2.1.tgz",
"integrity": "sha512-jPVNIqTvk+yKviikszv/Y1U4jGUSKpp/Nw48QZV4qjWgp70j4Lkq3lhSDRbWwCfgKvEyO9GHuVbV1dM2WYXy1w==",
"node_modules/@astrojs/markdown-satteri": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/@astrojs/markdown-satteri/-/markdown-satteri-0.3.5.tgz",
"integrity": "sha512-CvWVEFAbay7YO+i9SaqDJubipA5ckiVB89QWoMJ5XC0m5CtFg8JwZ7Kau6X9sYY7FZURH0w2l03ISH2jOS/RDQ==",
"license": "MIT",
"dependencies": {
"@astrojs/internal-helpers": "0.10.1",
"@astrojs/internal-helpers": "0.10.2",
"@astrojs/prism": "4.0.2",
"github-slugger": "^2.0.0",
"hast-util-from-html": "^2.0.3",
"hast-util-to-text": "^4.0.2",
"mdast-util-definitions": "^6.0.0",
"rehype-raw": "^7.0.0",
"rehype-stringify": "^10.0.1",
"remark-gfm": "^4.0.1",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"remark-smartypants": "^3.0.2",
"unified": "^11.0.5",
"unist-util-remove-position": "^5.0.0",
"unist-util-visit": "^5.1.0",
"unist-util-visit-parents": "^6.0.2",
"vfile": "^6.0.3"
"satteri": "^0.9.1"
}
},
"node_modules/@astrojs/markdown-satteri": {
"version": "0.3.3",
"resolved": "https://registry.npmjs.org/@astrojs/markdown-satteri/-/markdown-satteri-0.3.3.tgz",
"integrity": "sha512-Lje33Ittd8UQGgbIIWQvhPkj5X5c4b1sZnZWX3JQV/AWpfbuQGxVi2ONt6+ScydcwfR4egilslEWyczMclrJ1g==",
"node_modules/@astrojs/markdown-satteri/node_modules/@astrojs/internal-helpers": {
"version": "0.10.2",
"resolved": "https://registry.npmjs.org/@astrojs/internal-helpers/-/internal-helpers-0.10.2.tgz",
"integrity": "sha512-yt7fMgPYqSM4Tmr+taTW6Per+hjJ8Pk6lA1PAcDyqzOt8HzJ6Kje5WzCxA2Sd+9wsUW7uhkLeoTMK0cXPwH9rQ==",
"license": "MIT",
"dependencies": {
"@astrojs/internal-helpers": "0.10.1",
"@astrojs/prism": "4.0.2",
"github-slugger": "^2.0.0",
"satteri": "^0.9.1"
"@types/hast": "^3.0.4",
"@types/mdast": "^4.0.4",
"js-yaml": "^4.3.0",
"picomatch": "^4.0.4",
"retext-smartypants": "^6.2.0",
"shiki": "^4.0.2",
"smol-toml": "^1.6.0",
"unified": "^11.0.5"
}
},
"node_modules/@astrojs/mdx": {
@@ -274,6 +266,31 @@
}
}
},
"node_modules/@astrojs/mdx/node_modules/@astrojs/markdown-remark": {
"version": "7.2.1",
"resolved": "https://registry.npmjs.org/@astrojs/markdown-remark/-/markdown-remark-7.2.1.tgz",
"integrity": "sha512-jPVNIqTvk+yKviikszv/Y1U4jGUSKpp/Nw48QZV4qjWgp70j4Lkq3lhSDRbWwCfgKvEyO9GHuVbV1dM2WYXy1w==",
"license": "MIT",
"dependencies": {
"@astrojs/internal-helpers": "0.10.1",
"@astrojs/prism": "4.0.2",
"github-slugger": "^2.0.0",
"hast-util-from-html": "^2.0.3",
"hast-util-to-text": "^4.0.2",
"mdast-util-definitions": "^6.0.0",
"rehype-raw": "^7.0.0",
"rehype-stringify": "^10.0.1",
"remark-gfm": "^4.0.1",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"remark-smartypants": "^3.0.2",
"unified": "^11.0.5",
"unist-util-remove-position": "^5.0.0",
"unist-util-visit": "^5.1.0",
"unist-util-visit-parents": "^6.0.2",
"vfile": "^6.0.3"
}
},
"node_modules/@astrojs/prism": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@astrojs/prism/-/prism-4.0.2.tgz",
@@ -298,9 +315,9 @@
}
},
"node_modules/@astrojs/starlight": {
"version": "0.41.3",
"resolved": "https://registry.npmjs.org/@astrojs/starlight/-/starlight-0.41.3.tgz",
"integrity": "sha512-8xsG6UpK581TJmtOc7/pnxHKEbP16rV06VLWaVa7FOyE/VEwnaHOsLtL+miifCEfuiuv0Wn+j8u3JSluRQesMQ==",
"version": "0.41.6",
"resolved": "https://registry.npmjs.org/@astrojs/starlight/-/starlight-0.41.6.tgz",
"integrity": "sha512-Dt0/wY2JbFGUpxMgclw1j2Iqks2GG0LHYKgP7TfBXsFrs4LIbKvQ596lzyhXLz6nFcnPdIB9ZRFyDJeuVcx3Ug==",
"license": "MIT",
"dependencies": {
"@astrojs/markdown-satteri": "^0.3.2",
@@ -344,16 +361,15 @@
}
},
"node_modules/@astrojs/telemetry": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/@astrojs/telemetry/-/telemetry-3.3.2.tgz",
"integrity": "sha512-j8DNruA8ors99Al39RYZPJK4DC1bKkoNm93mAMuBhY9TCNC4R8n1q7ovFnJ5qhGh5Lsh7pa1gpQVpYpsJPeTHQ==",
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/@astrojs/telemetry/-/telemetry-3.3.3.tgz",
"integrity": "sha512-C1TLn5sPJr0x4vk56piHWKbnqlEB8BKyte5Y45V02U+D7BGO5eMqZDH5aPjnkXQWJggvmsTXxH03QMZ9NgWLzQ==",
"license": "MIT",
"dependencies": {
"ci-info": "^4.4.0",
"dset": "^3.1.4",
"is-docker": "^4.0.0",
"is-wsl": "^3.1.1",
"which-pm-runs": "^1.1.0"
"package-manager-detector": "^1.6.0"
},
"engines": {
"node": "18.20.8 || ^20.3.0 || >=22.0.0"
@@ -1625,21 +1641,24 @@
}
},
"node_modules/@napi-rs/wasm-runtime": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz",
"integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==",
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.2.tgz",
"integrity": "sha512-JfB4kuJQjaoHuCTseIINHtHWeJnvgEcxjwA5t/Y00ZgaOO1Crz3fjT/p8kT28zA/Caz7oiUMn3d6H2yOVCVwuw==",
"license": "MIT",
"optional": true,
"dependencies": {
"@tybys/wasm-util": "^0.10.3"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"peerDependencies": {
"@emnapi/core": "^1.7.1",
"@emnapi/runtime": "^1.7.1"
"@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3",
"@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3"
}
},
"node_modules/@oslojs/encoding": {
@@ -2359,15 +2378,15 @@
}
},
"node_modules/astro": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/astro/-/astro-7.0.6.tgz",
"integrity": "sha512-Myw0sFia+zs/Y0yqfZEsUYXfDPh3ELcLf1f0Q/qQzVXBh/af1qO62WNT+P89DCcfGVV51nMoQhEfkBYqJmoUOQ==",
"version": "7.1.6",
"resolved": "https://registry.npmjs.org/astro/-/astro-7.1.6.tgz",
"integrity": "sha512-83x9rYbHazMaZkYrAFRVZXSQx2moFkz0F7cjTDUF3GWfS0a3p2vZXG1ZdhV86rStHApQCodBJW+XTD37xISIrQ==",
"license": "MIT",
"dependencies": {
"@astrojs/compiler-rs": "^0.3.0",
"@astrojs/internal-helpers": "0.10.1",
"@astrojs/markdown-satteri": "0.3.3",
"@astrojs/telemetry": "3.3.2",
"@astrojs/compiler-rs": "^0.3.2",
"@astrojs/internal-helpers": "0.10.2",
"@astrojs/markdown-satteri": "0.3.5",
"@astrojs/telemetry": "3.3.3",
"@capsizecss/unpack": "^4.0.0",
"@clack/prompts": "^1.1.0",
"@oslojs/encoding": "^1.1.0",
@@ -2378,7 +2397,7 @@
"ci-info": "^4.4.0",
"clsx": "^2.1.1",
"common-ancestor-path": "^2.0.0",
"cookie": "^1.1.1",
"cookie": "^2.0.1",
"devalue": "^5.8.1",
"diff": "^8.0.3",
"dset": "^3.1.4",
@@ -2390,12 +2409,12 @@
"github-slugger": "^2.0.0",
"html-escaper": "3.0.3",
"http-cache-semantics": "^4.2.0",
"js-yaml": "^4.1.1",
"js-yaml": "^4.3.0",
"jsonc-parser": "^3.3.1",
"magic-string": "^0.30.21",
"magic-string": "^1.0.0",
"magicast": "^0.5.2",
"mrmime": "^2.0.1",
"neotraverse": "^0.6.18",
"neotraverse": "^1.0.1",
"obug": "^2.1.1",
"p-limit": "^7.3.0",
"p-queue": "^9.1.0",
@@ -2434,7 +2453,7 @@
"sharp": "^0.34.0 || ^0.35.0"
},
"peerDependencies": {
"@astrojs/markdown-remark": "7.2.1"
"@astrojs/markdown-remark": "7.2.2"
},
"peerDependenciesMeta": {
"@astrojs/markdown-remark": {
@@ -2455,6 +2474,31 @@
"astro": "^4.0.0-beta || ^5.0.0-beta || ^3.3.0 || ^6.0.0-beta || ^7.0.0"
}
},
"node_modules/astro/node_modules/@astrojs/internal-helpers": {
"version": "0.10.2",
"resolved": "https://registry.npmjs.org/@astrojs/internal-helpers/-/internal-helpers-0.10.2.tgz",
"integrity": "sha512-yt7fMgPYqSM4Tmr+taTW6Per+hjJ8Pk6lA1PAcDyqzOt8HzJ6Kje5WzCxA2Sd+9wsUW7uhkLeoTMK0cXPwH9rQ==",
"license": "MIT",
"dependencies": {
"@types/hast": "^3.0.4",
"@types/mdast": "^4.0.4",
"js-yaml": "^4.3.0",
"picomatch": "^4.0.4",
"retext-smartypants": "^6.2.0",
"shiki": "^4.0.2",
"smol-toml": "^1.6.0",
"unified": "^11.0.5"
}
},
"node_modules/astro/node_modules/magic-string": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.1.0.tgz",
"integrity": "sha512-kS3VHe0nEPST2saQV4Rbkchcd3UBRkVTQHo1D3h/ZTwFDhai/mfKkmtPAtD129EOI7K3HlHIsFOt0WrI2/oU9g==",
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/axobject-query": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
@@ -2633,12 +2677,12 @@
}
},
"node_modules/cookie": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.1.tgz",
"integrity": "sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w==",
"license": "MIT",
"engines": {
"node": ">=18"
"node": ">=22"
},
"funding": {
"type": "opencollective",
@@ -3779,39 +3823,6 @@
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/is-inside-container": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz",
"integrity": "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==",
"license": "MIT",
"dependencies": {
"is-docker": "^3.0.0"
},
"bin": {
"is-inside-container": "cli.js"
},
"engines": {
"node": ">=14.16"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/is-inside-container/node_modules/is-docker": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz",
"integrity": "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==",
"license": "MIT",
"bin": {
"is-docker": "cli.js"
},
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/is-plain-obj": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
@@ -3824,25 +3835,10 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/is-wsl": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.1.tgz",
"integrity": "sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==",
"license": "MIT",
"dependencies": {
"is-inside-container": "^1.0.0"
},
"engines": {
"node": ">=16"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/js-yaml": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
"integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==",
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz",
"integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==",
"funding": [
{
"type": "github",
@@ -5267,9 +5263,9 @@
"license": "MIT"
},
"node_modules/nanoid": {
"version": "3.3.15",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",
"integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==",
"version": "3.3.16",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
"funding": [
{
"type": "github",
@@ -5285,9 +5281,9 @@
}
},
"node_modules/neotraverse": {
"version": "0.6.18",
"resolved": "https://registry.npmjs.org/neotraverse/-/neotraverse-0.6.18.tgz",
"integrity": "sha512-Z4SmBUweYa09+o6pG+eASabEpP6QkQ70yHj351pQoEXIs8uHbaU2DWVmzBANKgflPa47A50PtB2+NgRpQvr7vA==",
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/neotraverse/-/neotraverse-1.0.1.tgz",
"integrity": "sha512-WmmLty1YWwJl9yZi77v2dVIV6X2kuYV8YYBI/G3LWGKdGHmHUvL1z7FW0iDvEvGAwNEoc5x1tOOOyDnf5jJw/w==",
"license": "MIT",
"engines": {
"node": ">= 10"
@@ -5533,9 +5529,9 @@
}
},
"node_modules/postcss": {
"version": "8.5.16",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz",
"integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==",
"version": "8.5.25",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz",
"integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==",
"funding": [
{
"type": "opencollective",
@@ -5552,7 +5548,7 @@
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.12",
"nanoid": "^3.3.16",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
@@ -6264,9 +6260,9 @@
}
},
"node_modules/svgo": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/svgo/-/svgo-4.0.1.tgz",
"integrity": "sha512-XDpWUOPC6FEibaLzjfe0ucaV0YrOjYotGJO1WpF0Zd+n6ZGEQUsSugaoLq9QkEZtAfQIxT42UChcssDVPP3+/w==",
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/svgo/-/svgo-4.0.2.tgz",
"integrity": "sha512-ekx94z1rRc5LDi6oSUaeRnYhd0UOJxdtQCL2rF8xpWxD3TPAsISWOrxezqGovqS38GRZOdpDfvQe3ts6F7nsng==",
"license": "MIT",
"dependencies": {
"commander": "^11.1.0",
@@ -6807,15 +6803,6 @@
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/which-pm-runs": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/which-pm-runs/-/which-pm-runs-1.1.0.tgz",
"integrity": "sha512-n1brCuqClxfFfq/Rb0ICg9giSZqCS+pLtccdag6C2HyufBrh3fBOiy9nb6ggRMvWOVH5GrdJskj5iGTZNxd7SA==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/xxhash-wasm": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz",
+2 -2
View File
@@ -8,8 +8,8 @@
"preview": "astro preview"
},
"dependencies": {
"@astrojs/starlight": "^0.41.3",
"astro": "^7.0.6",
"@astrojs/starlight": "^0.41.6",
"astro": "^7.1.6",
"sharp": "^0.35.3"
}
}
+16
View File
@@ -0,0 +1,16 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 611 620" fill="none">
<path d="M0 0 C6.4 4.22 7.06 11.7 8.6 18.74 C9.17 21.55 9.71 24.37 10.23 27.2 C10.43 28.25 10.63 29.3 10.84 30.39 C11.48 33.82 12.12 37.25 12.75 40.69 C12.86 41.28 12.86 41.28 13.41 44.27 C19.74 78.61 25.24 113.17 28 148 C28.1 149.25 28.2 150.5 28.31 151.78 C33.71 219.69 29.07 297.74 -17 352 C-37.58 376.04 -63.34 393.66 -92.79 405.14 C-94.83 405.93 -96.85 406.75 -98.87 407.58 C-119.07 415.67 -140.54 420.66 -162 424 C-163.26 424.2 -164.52 424.4 -165.82 424.6 C-213.88 431.88 -265.63 431.11 -313 420 C-313.8 419.81 -314.6 419.63 -315.42 419.43 C-321.96 417.87 -328.02 416.17 -334 413 C-333.4 408.16 -331.32 404.45 -329 400.25 C-328.63 399.57 -328.26 398.88 -327.88 398.18 C-325.16 393.16 -325.16 393.16 -324 392 C-316.45 391.5 -309.28 393.04 -301.88 394.38 C-266.77 400.41 -230.41 401.2 -195 397 C-193.89 396.88 -192.78 396.75 -191.63 396.63 C-143.03 391.12 -90.07 376.55 -53 343 C-52.13 342.26 -51.26 341.53 -50.37 340.77 C-13.69 309.26 -0.6 260.49 3 214 C6.89 162.68 1.22 110.21 -9.66 60.01 C-10 58 -10 58 -10 54 C-10.66 54 -11.32 54 -12 54 C-12.08 54.65 -12.16 55.3 -12.24 55.98 C-13.28 60.13 -15.18 63.61 -17.19 67.38 C-17.63 68.2 -18.06 69.02 -18.51 69.87 C-27.46 86.43 -37.3 102.24 -49 117 C-49.73 117.94 -50.46 118.88 -51.21 119.85 C-55.22 124.97 -59.47 129.83 -63.85 134.63 C-65.75 136.73 -67.6 138.85 -69.44 141 C-76.06 148.56 -83.19 155.34 -91.04 161.6 C-93.13 163.29 -95.16 165 -97.18 166.77 C-122.17 188.79 -151.25 205.29 -180.04 221.76 C-192.95 229.14 -205.58 236.83 -218 245 C-218.85 245.56 -219.7 246.12 -220.58 246.7 C-229.87 252.82 -238.77 259.13 -247.12 266.49 C-249.7 268.74 -252.35 270.84 -255.06 272.94 C-267.05 282.7 -278.61 294.17 -288.03 306.45 C-289.89 308.86 -291.81 311.22 -293.74 313.57 C-298.14 319.07 -302.07 324.81 -305.94 330.69 C-306.64 331.75 -307.34 332.82 -308.07 333.91 C-310.06 336.94 -312.03 339.97 -314 343 C-314.45 343.69 -314.9 344.38 -315.36 345.1 C-333.78 373.72 -347.37 405.97 -360.01 437.47 C-367.19 455.23 -367.19 455.23 -373 459 C-381.02 461.67 -388.52 459.36 -396 456 C-400.94 452.9 -406.06 449.11 -409 444 C-409.81 440.26 -409.56 438.01 -407.71 434.64 C-404.3 429.62 -400.39 425.15 -396.3 420.68 C-391.69 415.32 -387.56 409.58 -383.38 403.88 C-382.15 402.21 -380.9 400.55 -379.64 398.89 C-379 398.02 -378.35 397.15 -377.69 396.25 C-377.13 395.51 -376.58 394.78 -376.01 394.02 C-375 392 -375 392 -375.3 390.07 C-376.44 386.69 -378.78 384.1 -380.94 381.31 C-403.08 351.79 -416.04 315.59 -420 279 C-420.11 278.07 -420.22 277.14 -420.34 276.18 C-425.19 227.03 -413.92 174.12 -382.44 135.12 C-380.97 133.41 -379.49 131.7 -378 130 C-377.28 129.17 -376.56 128.34 -375.82 127.49 C-358.11 107.42 -337.64 91.46 -314 79 C-313.38 78.67 -312.76 78.33 -312.12 77.99 C-300.18 71.58 -287.7 66.68 -275 62 C-274.14 61.68 -273.29 61.36 -272.4 61.03 C-234.24 47.03 -193.39 42.56 -153.28 37.74 C-131.4 35.11 -109.62 32.33 -88 28 C-87.42 27.89 -87.42 27.89 -84.51 27.32 C-61.65 22.81 -40.27 14.77 -19.21 4.91 C-6.48 -0.98 -6.48 -0.98 0 0 Z M-36.19 37.49 C-71.76 55.45 -113.52 58.93 -152.55 63.46 C-196.61 68.6 -196.61 68.6 -216 73 C-217 73.22 -218 73.43 -219.03 73.65 C-264.38 83.45 -306.87 101.06 -341 133 C-341.95 133.88 -342.9 134.77 -343.88 135.68 C-373.91 164.27 -390.12 205.53 -391.38 246.65 C-392.35 288.29 -383.46 327.6 -361 363 C-358.84 360.25 -357.1 357.49 -355.47 354.39 C-354.99 353.5 -354.52 352.61 -354.03 351.69 C-353.78 351.21 -353.78 351.21 -352.5 348.81 C-342.16 329.63 -330.05 311.66 -316 295 C-315.08 293.89 -314.16 292.78 -313.24 291.68 C-308.88 286.45 -304.51 281.32 -299.6 276.6 C-297.85 274.85 -296.28 273.01 -294.69 271.12 C-278.78 252.73 -256.54 237.48 -235.78 225.07 C-233.06 223.44 -230.38 221.74 -227.69 220.06 C-219.23 214.87 -210.61 209.95 -202 205 C-193.33 200.01 -184.66 195.01 -176 190 C-174.99 189.42 -173.99 188.84 -172.95 188.24 C-161.6 181.67 -150.51 174.92 -139.83 167.3 C-137.99 165.99 -136.14 164.7 -134.29 163.41 C-123.48 155.83 -113.46 147.55 -103.79 138.57 C-101.47 136.44 -99.13 134.36 -96.75 132.31 C-89.94 126.39 -83.79 119.91 -78 113 C-77.55 112.46 -77.1 111.93 -76.64 111.38 C-57.15 88.05 -39.86 63.1 -28 35 C-31.34 35 -33.25 36 -36.19 37.49 Z " fill="#5FB88A" transform="translate(501,80)"/>
<g stroke="#5FB88A" stroke-width="12" stroke-linecap="round" fill="none">
<path d="M277 312 Q255 263 221 247"/>
<path d="M338 276 Q382 305 393 340"/>
<path d="M366 258 Q348 214 317 200"/>
<path d="M443 186 Q469 204 475 224"/>
</g>
<g fill="#5FB88A">
<circle cx="221" cy="247" r="13"/>
<circle cx="393" cy="340" r="13"/>
<circle cx="475" cy="224" r="11"/>
</g>
<circle cx="317" cy="200" r="18" fill="#7C6CF0"/>
</svg>

After

Width:  |  Height:  |  Size: 4.6 KiB

+16
View File
@@ -0,0 +1,16 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 611 620" fill="none">
<path d="M0 0 C6.4 4.22 7.06 11.7 8.6 18.74 C9.17 21.55 9.71 24.37 10.23 27.2 C10.43 28.25 10.63 29.3 10.84 30.39 C11.48 33.82 12.12 37.25 12.75 40.69 C12.86 41.28 12.86 41.28 13.41 44.27 C19.74 78.61 25.24 113.17 28 148 C28.1 149.25 28.2 150.5 28.31 151.78 C33.71 219.69 29.07 297.74 -17 352 C-37.58 376.04 -63.34 393.66 -92.79 405.14 C-94.83 405.93 -96.85 406.75 -98.87 407.58 C-119.07 415.67 -140.54 420.66 -162 424 C-163.26 424.2 -164.52 424.4 -165.82 424.6 C-213.88 431.88 -265.63 431.11 -313 420 C-313.8 419.81 -314.6 419.63 -315.42 419.43 C-321.96 417.87 -328.02 416.17 -334 413 C-333.4 408.16 -331.32 404.45 -329 400.25 C-328.63 399.57 -328.26 398.88 -327.88 398.18 C-325.16 393.16 -325.16 393.16 -324 392 C-316.45 391.5 -309.28 393.04 -301.88 394.38 C-266.77 400.41 -230.41 401.2 -195 397 C-193.89 396.88 -192.78 396.75 -191.63 396.63 C-143.03 391.12 -90.07 376.55 -53 343 C-52.13 342.26 -51.26 341.53 -50.37 340.77 C-13.69 309.26 -0.6 260.49 3 214 C6.89 162.68 1.22 110.21 -9.66 60.01 C-10 58 -10 58 -10 54 C-10.66 54 -11.32 54 -12 54 C-12.08 54.65 -12.16 55.3 -12.24 55.98 C-13.28 60.13 -15.18 63.61 -17.19 67.38 C-17.63 68.2 -18.06 69.02 -18.51 69.87 C-27.46 86.43 -37.3 102.24 -49 117 C-49.73 117.94 -50.46 118.88 -51.21 119.85 C-55.22 124.97 -59.47 129.83 -63.85 134.63 C-65.75 136.73 -67.6 138.85 -69.44 141 C-76.06 148.56 -83.19 155.34 -91.04 161.6 C-93.13 163.29 -95.16 165 -97.18 166.77 C-122.17 188.79 -151.25 205.29 -180.04 221.76 C-192.95 229.14 -205.58 236.83 -218 245 C-218.85 245.56 -219.7 246.12 -220.58 246.7 C-229.87 252.82 -238.77 259.13 -247.12 266.49 C-249.7 268.74 -252.35 270.84 -255.06 272.94 C-267.05 282.7 -278.61 294.17 -288.03 306.45 C-289.89 308.86 -291.81 311.22 -293.74 313.57 C-298.14 319.07 -302.07 324.81 -305.94 330.69 C-306.64 331.75 -307.34 332.82 -308.07 333.91 C-310.06 336.94 -312.03 339.97 -314 343 C-314.45 343.69 -314.9 344.38 -315.36 345.1 C-333.78 373.72 -347.37 405.97 -360.01 437.47 C-367.19 455.23 -367.19 455.23 -373 459 C-381.02 461.67 -388.52 459.36 -396 456 C-400.94 452.9 -406.06 449.11 -409 444 C-409.81 440.26 -409.56 438.01 -407.71 434.64 C-404.3 429.62 -400.39 425.15 -396.3 420.68 C-391.69 415.32 -387.56 409.58 -383.38 403.88 C-382.15 402.21 -380.9 400.55 -379.64 398.89 C-379 398.02 -378.35 397.15 -377.69 396.25 C-377.13 395.51 -376.58 394.78 -376.01 394.02 C-375 392 -375 392 -375.3 390.07 C-376.44 386.69 -378.78 384.1 -380.94 381.31 C-403.08 351.79 -416.04 315.59 -420 279 C-420.11 278.07 -420.22 277.14 -420.34 276.18 C-425.19 227.03 -413.92 174.12 -382.44 135.12 C-380.97 133.41 -379.49 131.7 -378 130 C-377.28 129.17 -376.56 128.34 -375.82 127.49 C-358.11 107.42 -337.64 91.46 -314 79 C-313.38 78.67 -312.76 78.33 -312.12 77.99 C-300.18 71.58 -287.7 66.68 -275 62 C-274.14 61.68 -273.29 61.36 -272.4 61.03 C-234.24 47.03 -193.39 42.56 -153.28 37.74 C-131.4 35.11 -109.62 32.33 -88 28 C-87.42 27.89 -87.42 27.89 -84.51 27.32 C-61.65 22.81 -40.27 14.77 -19.21 4.91 C-6.48 -0.98 -6.48 -0.98 0 0 Z M-36.19 37.49 C-71.76 55.45 -113.52 58.93 -152.55 63.46 C-196.61 68.6 -196.61 68.6 -216 73 C-217 73.22 -218 73.43 -219.03 73.65 C-264.38 83.45 -306.87 101.06 -341 133 C-341.95 133.88 -342.9 134.77 -343.88 135.68 C-373.91 164.27 -390.12 205.53 -391.38 246.65 C-392.35 288.29 -383.46 327.6 -361 363 C-358.84 360.25 -357.1 357.49 -355.47 354.39 C-354.99 353.5 -354.52 352.61 -354.03 351.69 C-353.78 351.21 -353.78 351.21 -352.5 348.81 C-342.16 329.63 -330.05 311.66 -316 295 C-315.08 293.89 -314.16 292.78 -313.24 291.68 C-308.88 286.45 -304.51 281.32 -299.6 276.6 C-297.85 274.85 -296.28 273.01 -294.69 271.12 C-278.78 252.73 -256.54 237.48 -235.78 225.07 C-233.06 223.44 -230.38 221.74 -227.69 220.06 C-219.23 214.87 -210.61 209.95 -202 205 C-193.33 200.01 -184.66 195.01 -176 190 C-174.99 189.42 -173.99 188.84 -172.95 188.24 C-161.6 181.67 -150.51 174.92 -139.83 167.3 C-137.99 165.99 -136.14 164.7 -134.29 163.41 C-123.48 155.83 -113.46 147.55 -103.79 138.57 C-101.47 136.44 -99.13 134.36 -96.75 132.31 C-89.94 126.39 -83.79 119.91 -78 113 C-77.55 112.46 -77.1 111.93 -76.64 111.38 C-57.15 88.05 -39.86 63.1 -28 35 C-31.34 35 -33.25 36 -36.19 37.49 Z " fill="#5FB88A" transform="translate(501,80)"/>
<g stroke="#5FB88A" stroke-width="12" stroke-linecap="round" fill="none">
<path d="M277 312 Q255 263 221 247"/>
<path d="M338 276 Q382 305 393 340"/>
<path d="M366 258 Q348 214 317 200"/>
<path d="M443 186 Q469 204 475 224"/>
</g>
<g fill="#5FB88A">
<circle cx="221" cy="247" r="13"/>
<circle cx="393" cy="340" r="13"/>
<circle cx="475" cy="224" r="11"/>
</g>
<circle cx="317" cy="200" r="18" fill="#7C6CF0"/>
</svg>

After

Width:  |  Height:  |  Size: 4.6 KiB

Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more