Merge branch 'feat/router-security-beta' into develop
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
42 files changed
+3177
-1436
No files matched your search
@@ -13,9 +13,16 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
node-version: '18'
|
node-version: '18'
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
|
- run: npm audit
|
||||||
- run: npm run lint
|
- run: npm run lint
|
||||||
- run: npm run format:check
|
- run: npm run format:check
|
||||||
- run: npm run complexity:check
|
- run: npm run complexity:check
|
||||||
- run: npm run typecheck
|
- run: npm run typecheck
|
||||||
- run: npm test
|
- run: npm test
|
||||||
- run: npm run build
|
- 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
|
||||||
@@ -23,6 +23,7 @@ jobs:
|
|||||||
registry-url: 'https://registry.npmjs.org'
|
registry-url: 'https://registry.npmjs.org'
|
||||||
- run: npm install -g npm@latest # npm >= 11.5.1 is required for OIDC trusted publishing
|
- run: npm install -g npm@latest # npm >= 11.5.1 is required for OIDC trusted publishing
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
|
- run: npm audit
|
||||||
# `npm publish` runs prepublishOnly (lint + complexity + typecheck + test + build) first.
|
# `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.
|
# 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`
|
# A prerelease (26.7.0-beta.N) publishes under its channel tag (beta/alpha/rc) so `latest`
|
||||||
|
|||||||
+33
-9
@@ -8,7 +8,18 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [26.8.0-beta.0] - 2026-08-02
|
||||||
|
|
||||||
### Added
|
### 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
|
- **HTML / views:** `@Html` decorator (string, file, and template modes), a zero-dep built-in
|
||||||
template engine (`{{ }}` escaped / `{{{ }}}` raw, exported as `render`) with a `viewEngine`
|
template engine (`{{ }}` escaped / `{{{ }}}` raw, exported as `render`) with a `viewEngine`
|
||||||
bring-your-own hook, and zero-config `static` directory serving (`createApp({ static: true })`).
|
bring-your-own hook, and zero-config `static` directory serving (`createApp({ static: true })`).
|
||||||
@@ -42,6 +53,14 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
pings — the platform `WebSocket` on Deno/Bun does not expose `ws.ping()`.
|
pings — the platform `WebSocket` on Deno/Bun does not expose `ws.ping()`.
|
||||||
|
|
||||||
### Fixed
|
### 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
|
- 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),
|
served over `app.fetch` too, so they work on every runtime (Deno/Bun/edge),
|
||||||
not only the Node `app.listen()` path.
|
not only the Node `app.listen()` path.
|
||||||
@@ -55,9 +74,9 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
- **`request:step:enter`/`leave` are now emitted for `@Ws` and mesh routes.** Only HTTP routes
|
- **`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
|
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.
|
documented plugin API. All transports now run their steps through one path.
|
||||||
- **A mesh route exported by two teapots now fails the boot**, naming the route and both teapots,
|
- **A mesh route exported by two teapots now fails the boot**, naming both effective patterns and
|
||||||
instead of silently serving whichever connected first and leaving the other dead. There is no
|
both teapots, instead of silently serving whichever connected first and leaving the other dead.
|
||||||
load balancing to fall back on, so green-tea will not pick for you.
|
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
|
- **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.
|
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`
|
- **`app.close()` closes mesh links even with no server**, so a mesh app booted through `app.fetch`
|
||||||
@@ -69,6 +88,9 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
`request:step:leave`.
|
`request:step:leave`.
|
||||||
|
|
||||||
### Changed
|
### 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()`
|
- App-scope providers now boot exactly once (memoized): a second `app.listen()`
|
||||||
call no longer re-runs provider factories or their side effects.
|
call no longer re-runs provider factories or their side effects.
|
||||||
- **`WsOpenCtx.req`** (available in `@Ws`/`@Sse` handlers) is now a neutral
|
- **`WsOpenCtx.req`** (available in `@Ws`/`@Sse` handlers) is now a neutral
|
||||||
@@ -78,10 +100,11 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
`ctx.req`; use `ctx.protocol` / `ctx.ip` / `ctx.query` / `ctx.headers`
|
`ctx.req`; use `ctx.protocol` / `ctx.ip` / `ctx.query` / `ctx.headers`
|
||||||
instead — all still provided.
|
instead — all still provided.
|
||||||
- **Breaking (pre-1.0): transport is now enforced by declaration.** A buffered route
|
- **Breaking (pre-1.0): transport is now enforced by declaration.** A buffered route
|
||||||
(`@Get`/`@Post`/`@Put`/`@Patch`/`@Delete`) whose handler returns an `AsyncIterable`, or a streaming
|
(`@Get`/`@Head`/`@Post`/`@Put`/`@Patch`/`@Delete`/`@Options`) whose handler returns an
|
||||||
route (`@Sse`/`@Ws`) whose handler returns a plain value, now fails with a 500 `TransportMismatchError`
|
`AsyncIterable`, or a streaming route (`@Sse`/`@Ws`) whose handler returns a plain value, now
|
||||||
instead of silently switching behavior. `@Stream` still negotiates both. Declare `@Sse`/`@Stream`/`@Ws`
|
fails with a 500 `TransportMismatchError` instead of silently switching behavior. `@Stream`
|
||||||
to stream — a return value no longer changes a route's wire contract.
|
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
|
## [26.7.0-beta.0] - 2026-07-07
|
||||||
|
|
||||||
@@ -130,5 +153,6 @@ change before the stable release.
|
|||||||
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
|
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
|
||||||
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
|
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
|
||||||
|
|
||||||
[Unreleased]: https://git.svc.zoit.services/Green-Tea/core/compare/26.7.0-beta.0...develop
|
[Unreleased]: https://git.svc.zoit.services/Green-Tea/core/compare/v26.8.0-beta.0...develop
|
||||||
[26.7.0-beta.0]: https://git.svc.zoit.services/Green-Tea/core/releases/tag/26.7.0-beta.0
|
[26.8.0-beta.0]: https://git.svc.zoit.services/Green-Tea/core/compare/v26.7.0-beta.0...v26.8.0-beta.0
|
||||||
|
[26.7.0-beta.0]: https://git.svc.zoit.services/Green-Tea/core/releases/tag/v26.7.0-beta.0
|
||||||
@@ -193,17 +193,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.
|
`@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
|
## 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
|
```typescript
|
||||||
|
@Get('/users/:id(\\d+)') // /users/42
|
||||||
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
|
@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
|
## Two layers
|
||||||
|
|
||||||
@@ -251,13 +254,14 @@ npm run docs:dev # the documentation site (website/)
|
|||||||
- ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices.
|
- ✅ **mesh (walking skeleton)** — `teapot`/`teacup` distributed DI over a secret-gated WS control channel. A BEAM/OTP-style cluster, *not* microservices.
|
||||||
- ✅ **runs everywhere** — Node, Deno, Bun, and Cloudflare Workers over web-standard `Request`/`Response`, with identical WebSocket behaviour on all four.
|
- ✅ **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.
|
- ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving.
|
||||||
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), official plugins, router regex constraints and a radix-tree matcher.
|
- ✅ **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
|
## Versioning
|
||||||
|
|
||||||
green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.7.0` = the first release cut in July 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).
|
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.7.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 — 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.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
@@ -18,11 +18,11 @@
|
|||||||
"workspace": {
|
"workspace": {
|
||||||
"packageJson": {
|
"packageJson": {
|
||||||
"dependencies": [
|
"dependencies": [
|
||||||
"npm:@eslint/js@^9.39.4",
|
"npm:@eslint/js@^9.39.5",
|
||||||
"npm:@nestjs/common@^11.1.27",
|
"npm:@nestjs/common@^11.1.28",
|
||||||
"npm:@nestjs/core@^11.1.27",
|
"npm:@nestjs/core@^11.1.28",
|
||||||
"npm:@nestjs/platform-express@^11.1.27",
|
"npm:@nestjs/platform-express@^11.1.28",
|
||||||
"npm:@nestjs/platform-fastify@^11.1.27",
|
"npm:@nestjs/platform-fastify@^11.1.28",
|
||||||
"npm:@stylistic/eslint-plugin@^5.10.0",
|
"npm:@stylistic/eslint-plugin@^5.10.0",
|
||||||
"npm:@types/autocannon@^7.12.7",
|
"npm:@types/autocannon@^7.12.7",
|
||||||
"npm:@types/busboy@^1.5.4",
|
"npm:@types/busboy@^1.5.4",
|
||||||
@@ -32,20 +32,31 @@
|
|||||||
"npm:autocannon@8",
|
"npm:autocannon@8",
|
||||||
"npm:busboy@^1.6.0",
|
"npm:busboy@^1.6.0",
|
||||||
"npm:cognitive-complexity-ts@~0.8.2",
|
"npm:cognitive-complexity-ts@~0.8.2",
|
||||||
"npm:eslint@^9.39.4",
|
"npm:esbuild@0.27.2",
|
||||||
|
"npm:eslint@^9.39.5",
|
||||||
"npm:express@^5.2.1",
|
"npm:express@^5.2.1",
|
||||||
"npm:fastify@^5.10.0",
|
"npm:fastify@^5.11.0",
|
||||||
"npm:graphql@^16.9.0",
|
"npm:graphql@^16.9.0",
|
||||||
"npm:prettier@^3.9.4",
|
"npm:miniflare@^4.20260730.0",
|
||||||
|
"npm:prettier@^3.9.6",
|
||||||
"npm:reflect-metadata@0.2.2",
|
"npm:reflect-metadata@0.2.2",
|
||||||
"npm:rxjs@^7.8.2",
|
"npm:rxjs@^7.8.2",
|
||||||
"npm:tsup@^8.5.1",
|
"npm:tsup@^8.5.1",
|
||||||
"npm:tsx@^4.23.0",
|
"npm:tsx@^4.23.5",
|
||||||
"npm:typescript-eslint@^8.63.0",
|
"npm:typescript-eslint@^8.65.0",
|
||||||
"npm:typescript@^5.5.0",
|
"npm:typescript@^5.5.0",
|
||||||
"npm:vitest@2",
|
"npm:vite@^6.4.3",
|
||||||
"npm:ws@^8.21.0"
|
"npm:vitest@^3.2.7",
|
||||||
]
|
"npm:ws@^8.21.1"
|
||||||
|
],
|
||||||
|
"overrides": {
|
||||||
|
"find-my-way": "9.7.0",
|
||||||
|
"autocannon": {
|
||||||
|
"hyperid": {
|
||||||
|
"uuid": "11.1.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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.
|
||||||
Generated
+1285
-1092
File diff suppressed because it is too large.
Load diff
+24
-14
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@green-tea/core",
|
"name": "@green-tea/core",
|
||||||
"version": "26.7.0-beta.0",
|
"version": "26.8.0-beta.0",
|
||||||
"description": "A zen, opinionated, type-safe framework — your API is a graph, not a middleware chain.",
|
"description": "A zen, opinionated, type-safe framework — your API is a graph, not a middleware chain.",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"author": "green-tea contributors",
|
"author": "green-tea contributors",
|
||||||
@@ -112,12 +112,20 @@
|
|||||||
"optional": true
|
"optional": true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"overrides": {
|
||||||
|
"find-my-way": "9.7.0",
|
||||||
|
"autocannon": {
|
||||||
|
"hyperid": {
|
||||||
|
"uuid": "11.1.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.39.4",
|
"@eslint/js": "^9.39.5",
|
||||||
"@nestjs/common": "^11.1.27",
|
"@nestjs/common": "^11.1.28",
|
||||||
"@nestjs/core": "^11.1.27",
|
"@nestjs/core": "^11.1.28",
|
||||||
"@nestjs/platform-express": "^11.1.27",
|
"@nestjs/platform-express": "^11.1.28",
|
||||||
"@nestjs/platform-fastify": "^11.1.27",
|
"@nestjs/platform-fastify": "^11.1.28",
|
||||||
"@stylistic/eslint-plugin": "^5.10.0",
|
"@stylistic/eslint-plugin": "^5.10.0",
|
||||||
"@types/autocannon": "^7.12.7",
|
"@types/autocannon": "^7.12.7",
|
||||||
"@types/busboy": "^1.5.4",
|
"@types/busboy": "^1.5.4",
|
||||||
@@ -127,18 +135,20 @@
|
|||||||
"autocannon": "^8.0.0",
|
"autocannon": "^8.0.0",
|
||||||
"busboy": "^1.6.0",
|
"busboy": "^1.6.0",
|
||||||
"cognitive-complexity-ts": "^0.8.2",
|
"cognitive-complexity-ts": "^0.8.2",
|
||||||
"eslint": "^9.39.4",
|
"eslint": "^9.39.5",
|
||||||
|
"esbuild": "0.27.2",
|
||||||
"express": "^5.2.1",
|
"express": "^5.2.1",
|
||||||
"fastify": "^5.10.0",
|
"fastify": "^5.11.0",
|
||||||
"graphql": "^16.9.0",
|
"graphql": "^16.9.0",
|
||||||
"miniflare": "^4.20260708.1",
|
"miniflare": "^4.20260730.0",
|
||||||
"prettier": "^3.9.4",
|
"prettier": "^3.9.6",
|
||||||
"rxjs": "^7.8.2",
|
"rxjs": "^7.8.2",
|
||||||
"tsup": "^8.5.1",
|
"tsup": "^8.5.1",
|
||||||
"tsx": "^4.23.0",
|
"tsx": "^4.23.5",
|
||||||
"typescript": "^5.5.0",
|
"typescript": "^5.5.0",
|
||||||
"typescript-eslint": "^8.63.0",
|
"typescript-eslint": "^8.65.0",
|
||||||
"vitest": "^2.0.0",
|
"vite": "^6.4.3",
|
||||||
"ws": "^8.21.0"
|
"vitest": "^3.2.7",
|
||||||
|
"ws": "^8.21.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+36
-9
@@ -35,6 +35,7 @@ import type { MeshControl } from '../http';
|
|||||||
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
|
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
|
||||||
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
|
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
|
||||||
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
|
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
|
||||||
|
import { compilePattern } from '../http/router';
|
||||||
|
|
||||||
export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types';
|
export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types';
|
||||||
|
|
||||||
@@ -349,6 +350,7 @@ function collectControllers(
|
|||||||
const instance: any = new ControllerClass();
|
const instance: any = new ControllerClass();
|
||||||
const argSpecs = getArgs(ControllerClass, route.handlerName);
|
const argSpecs = getArgs(ControllerClass, route.handlerName);
|
||||||
const pattern = joinPath(mountpoint, route.path);
|
const pattern = joinPath(mountpoint, route.path);
|
||||||
|
const declaration = `${ControllerClass.name}.${route.handlerName}`;
|
||||||
|
|
||||||
if (route.export) {
|
if (route.export) {
|
||||||
if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`);
|
if (route.transport !== 'buffer') throw new Error(`cannot export streaming route ${pattern}`);
|
||||||
@@ -357,11 +359,12 @@ function collectControllers(
|
|||||||
|
|
||||||
const transformer = resolveTransformer(ControllerClass, route, pattern, viewsCtx);
|
const transformer = resolveTransformer(ControllerClass, route, pattern, viewsCtx);
|
||||||
|
|
||||||
registry.routePlans.push({
|
const plan: RoutePlan = {
|
||||||
pattern,
|
pattern,
|
||||||
method: route.method,
|
method: route.method,
|
||||||
transport: route.transport,
|
transport: route.transport,
|
||||||
origin,
|
origin,
|
||||||
|
declaration,
|
||||||
providers: [],
|
providers: [],
|
||||||
steps: [],
|
steps: [],
|
||||||
handlerName: route.handlerName,
|
handlerName: route.handlerName,
|
||||||
@@ -372,11 +375,27 @@ function collectControllers(
|
|||||||
maxBodyBytes: route.maxBodyBytes,
|
maxBodyBytes: route.maxBodyBytes,
|
||||||
maxParts: route.maxParts,
|
maxParts: route.maxParts,
|
||||||
args: argSpecs,
|
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
|
* 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
|
* validating placement — buffered GET/POST only, and not combined with `@Transformer`); otherwise the
|
||||||
@@ -394,7 +413,7 @@ function resolveTransformer(
|
|||||||
|
|
||||||
if (route.transport !== 'buffer' || (route.method !== 'GET' && route.method !== 'POST')) {
|
if (route.transport !== 'buffer' || (route.method !== 'GET' && route.method !== 'POST')) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`@Html on ${route.method} ${pattern} is not allowed — @Html only supports buffered GET/POST routes (not SSE/WS/PUT/PATCH/DELETE)`,
|
`@Html on ${route.method} ${pattern} is not allowed — @Html only supports buffered GET/POST routes (not SSE/WS/HEAD/PUT/PATCH/DELETE/OPTIONS)`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -512,7 +531,7 @@ async function spliceRemoteScopes(
|
|||||||
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
|
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
|
||||||
const remoteRoutes: RouteDef[] = [];
|
const remoteRoutes: RouteDef[] = [];
|
||||||
const meshLinks: Link[] = [];
|
const meshLinks: Link[] = [];
|
||||||
const routeOwners = new Map<string, string>(); // "METHOD /pattern" -> the teapot that exported it
|
const routeOwners = new Map<string, { url: string; pattern: string }>(); // "METHOD effective-shape" -> owner
|
||||||
|
|
||||||
try {
|
try {
|
||||||
for (const teapot of mesh.teapots ?? []) {
|
for (const teapot of mesh.teapots ?? []) {
|
||||||
@@ -539,7 +558,8 @@ async function spliceRemoteScopes(
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (const route of routes) {
|
for (const route of routes) {
|
||||||
const key = `${route.method} ${route.pattern}`;
|
const display = `${route.method} ${route.pattern}`;
|
||||||
|
const key = `${route.method} ${compilePattern(route.pattern).shape}`;
|
||||||
const owner = routeOwners.get(key);
|
const owner = routeOwners.get(key);
|
||||||
|
|
||||||
// Fail the boot rather than pick one. Route matching keeps the first of two identical
|
// Fail the boot rather than pick one. Route matching keeps the first of two identical
|
||||||
@@ -548,21 +568,28 @@ async function spliceRemoteScopes(
|
|||||||
// Scope tokens already fail this way in setRunner; routes now match.
|
// Scope tokens already fail this way in setRunner; routes now match.
|
||||||
if (owner) {
|
if (owner) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`mesh: route '${key}' is exported by more than one teapot (${owner} and ${teapot.url}) — ` +
|
`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. ' +
|
'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' +
|
||||||
'Export it from a single teapot.',
|
'Export it from a single teapot.',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
routeOwners.set(key, teapot.url);
|
routeOwners.set(key, { url: teapot.url, pattern: route.pattern });
|
||||||
|
|
||||||
// Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin
|
// 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
|
// 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
|
// 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.
|
// broken teapot from the outside. Warn and let the developer decide.
|
||||||
if (registry.routePlans.some((plan) => plan.method === route.method && plan.pattern === route.pattern)) {
|
if (
|
||||||
|
registry.routePlans.some(
|
||||||
|
(plan) =>
|
||||||
|
plan.method === route.method &&
|
||||||
|
compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape,
|
||||||
|
)
|
||||||
|
) {
|
||||||
console.warn(
|
console.warn(
|
||||||
`[green-tea] mesh: route '${key}' is exported by teapot ${teapot.url} but also declared locally — ` +
|
`[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. ' +
|
'the local route takes precedence and the remote one will not be reached. ' +
|
||||||
'Remove one if that is not what you meant.',
|
'Remove one if that is not what you meant.',
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ export interface RoutePlan {
|
|||||||
method: HttpMethod;
|
method: HttpMethod;
|
||||||
transport: Transport;
|
transport: Transport;
|
||||||
origin: string;
|
origin: string;
|
||||||
|
declaration: string;
|
||||||
providers: GraphNode[];
|
providers: GraphNode[];
|
||||||
steps: GraphNode[];
|
steps: GraphNode[];
|
||||||
handlerName: string;
|
handlerName: string;
|
||||||
|
|||||||
+3
-1
@@ -35,10 +35,12 @@ declare const Deno: {
|
|||||||
export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer {
|
export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer {
|
||||||
return Deno.serve(options ?? {}, (request, info) => {
|
return Deno.serve(options ?? {}, (request, info) => {
|
||||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
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);
|
const { socket, response } = Deno.upgradeWebSocket(request);
|
||||||
socket.binaryType = 'arraybuffer'; // deliver binary frames as ArrayBuffer, which decodeMessage expects
|
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
|
// fire-and-forget: the 101 response must be returned synchronously while the graph runs
|
||||||
void upgradeSafely(app, toWsRequest(request, info.remoteAddr.hostname), eventSocket(socket));
|
void upgradeSafely(app, wsRequest, eventSocket(socket));
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+74
-24
@@ -3,7 +3,7 @@ import { HttpError, NotFound } from '../signals';
|
|||||||
import { renderError } from '../transformers';
|
import { renderError } from '../transformers';
|
||||||
import { isStreamResult, type PipelineResult } from '../pipeline';
|
import { isStreamResult, type PipelineResult } from '../pipeline';
|
||||||
import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security';
|
import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security';
|
||||||
import { matchRoute, allowedMethods, parseQuery } from './router';
|
import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
|
||||||
import { pickEncoder } from './stream';
|
import { pickEncoder } from './stream';
|
||||||
import type { RouteDef, HttpOptions } from './types';
|
import type { RouteDef, HttpOptions } from './types';
|
||||||
import type { StreamEncoder } from '../encoders';
|
import type { StreamEncoder } from '../encoders';
|
||||||
@@ -49,6 +49,61 @@ export function computeInjected(
|
|||||||
return injected;
|
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,
|
* 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
|
* route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the
|
||||||
@@ -59,35 +114,22 @@ export async function handle(
|
|||||||
opts: HttpOptions | undefined,
|
opts: HttpOptions | undefined,
|
||||||
req: NeutralRequest,
|
req: NeutralRequest,
|
||||||
): Promise<HandleResult | Preflight> {
|
): Promise<HandleResult | Preflight> {
|
||||||
const path = req.url.split('?')[0];
|
|
||||||
const injected = computeInjected(opts, req);
|
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']) {
|
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
||||||
return { preflight: corsPreflightHeaders(opts.cors, req) };
|
return { preflight: corsPreflightHeaders(opts.cors, req) };
|
||||||
}
|
}
|
||||||
|
|
||||||
const matched = matchRoute(routes, req.method, path);
|
const matched = resolveRoute(routes, req.method, path);
|
||||||
|
|
||||||
if (!matched) {
|
if (!matched) return unmatchedOutcome(routes, opts, req, path, injected);
|
||||||
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
|
|
||||||
const hit = await opts.static(path);
|
|
||||||
|
|
||||||
if (hit) {
|
|
||||||
const body = req.method === 'HEAD' ? '' : hit.body;
|
|
||||||
return {
|
|
||||||
injected,
|
|
||||||
outcome: { kind: 'buffered', status: 200, headers: { 'content-type': hit.contentType }, body },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Path matches a route under a different method → 405 with Allow; otherwise 404.
|
|
||||||
const allow = allowedMethods(routes, path);
|
|
||||||
const err = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found');
|
|
||||||
const rendered = renderError(err, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
|
|
||||||
const headers = allow.length ? { ...rendered.headers, allow: allow.join(', ') } : rendered.headers;
|
|
||||||
return { injected, outcome: { kind: 'buffered', status: rendered.status, headers, body: rendered.body } };
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: PipelineResult;
|
let result: PipelineResult;
|
||||||
|
|
||||||
@@ -111,5 +153,13 @@ export async function handle(
|
|||||||
return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } };
|
return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } };
|
||||||
}
|
}
|
||||||
|
|
||||||
return { injected, outcome: { kind: 'buffered', status: result.status, headers: result.headers, body: result.body } };
|
return {
|
||||||
|
injected,
|
||||||
|
outcome: {
|
||||||
|
kind: 'buffered',
|
||||||
|
status: result.status,
|
||||||
|
headers: result.headers,
|
||||||
|
body: req.method === 'HEAD' ? '' : result.body,
|
||||||
|
},
|
||||||
|
};
|
||||||
}
|
}
|
||||||
+240
-34
@@ -1,63 +1,236 @@
|
|||||||
import type { RouteDef, MatchedRoute } from './types';
|
import type { RouteDef, MatchedRoute } from './types';
|
||||||
|
|
||||||
/**
|
export type CompiledSegment =
|
||||||
* Matches a route pattern against a request path. Supports static segments, `:param` (one segment),
|
| { kind: 'static'; value: string }
|
||||||
* and a trailing `:name*` catch-all that captures the rest of the path (slashes included) into `params.name`.
|
| { kind: 'param'; name: string; constraint?: RegExp; constraintSource?: string }
|
||||||
* @returns Extracted params (decoded) when the path matches, otherwise undefined.
|
| { kind: 'catchAll'; name: string };
|
||||||
*/
|
|
||||||
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
|
/** 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 pathSegs = path.split('/').filter(Boolean);
|
||||||
const patternSegs = pattern.split('/').filter(Boolean);
|
|
||||||
const params: Record<string, string> = {};
|
const params: Record<string, string> = {};
|
||||||
|
|
||||||
for (let i = 0; i < patternSegs.length; i++) {
|
for (let index = 0; index < compiled.segments.length; index++) {
|
||||||
const seg = patternSegs[i];
|
const segment = compiled.segments[index];
|
||||||
|
|
||||||
// Trailing catch-all: capture every remaining segment (possibly none) as one decoded value.
|
if (segment.kind === 'catchAll') {
|
||||||
if (seg.startsWith(':') && seg.endsWith('*')) {
|
params[segment.name] = pathSegs.slice(index).map(decodeSegment).join('/');
|
||||||
params[seg.slice(1, -1)] = pathSegs.slice(i).map(decodeURIComponent).join('/');
|
|
||||||
return params;
|
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]);
|
if (segment.kind === 'static') {
|
||||||
else if (seg !== pathSegs[i]) return undefined;
|
if (segment.value !== pathSegs[index]) return undefined;
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// No catch-all consumed the tail, so the lengths must match exactly.
|
const value = decodeSegment(pathSegs[index]);
|
||||||
return patternSegs.length === pathSegs.length ? params : undefined;
|
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. */
|
return compiled.segments.length === pathSegs.length ? params : undefined;
|
||||||
function segScores(pattern: string): { catchAll: boolean; kinds: number[] } {
|
|
||||||
const kinds: number[] = [];
|
|
||||||
|
|
||||||
for (const seg of pattern.split('/').filter(Boolean)) {
|
|
||||||
if (seg.startsWith(':') && seg.endsWith('*')) return { catchAll: true, kinds };
|
|
||||||
kinds.push(seg.startsWith(':') ? 1 : 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return { catchAll: false, kinds };
|
/** 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 {
|
function moreSpecific(a: string, b: string): number {
|
||||||
const scoreA = segScores(a);
|
const scoreA = compilePattern(a);
|
||||||
const scoreB = segScores(b);
|
const scoreB = compilePattern(b);
|
||||||
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
|
if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1;
|
||||||
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
|
const length = Math.max(scoreA.kinds.length, scoreB.kinds.length);
|
||||||
|
|
||||||
for (let i = 0; i < length; i++) {
|
for (let index = 0; index < length; index++) {
|
||||||
const kindA = scoreA.kinds[i] ?? -1;
|
const kindA = scoreA.kinds[index] ?? -1;
|
||||||
const kindB = scoreB.kinds[i] ?? -1;
|
const kindB = scoreB.kinds[index] ?? -1;
|
||||||
if (kindA !== kindB) return kindA - kindB;
|
if (kindA !== kindB) return kindA - kindB;
|
||||||
}
|
}
|
||||||
|
|
||||||
return 0;
|
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 {
|
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
||||||
let best: MatchedRoute | undefined;
|
let best: MatchedRoute | undefined;
|
||||||
let bestPattern = '';
|
let bestPattern = '';
|
||||||
@@ -76,11 +249,44 @@ export function matchRoute(routes: RouteDef[], method: string, path: string): Ma
|
|||||||
return best;
|
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. */
|
/** 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[] {
|
export function allowedMethods(routes: RouteDef[], path: string): string[] {
|
||||||
const methods = new Set<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). */
|
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
|
||||||
|
|||||||
+8
-2
@@ -5,7 +5,7 @@ import { isHttpError, HttpError } from '../signals';
|
|||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
import { buildSecurityHeaders, resolveCors } from '../security';
|
import { buildSecurityHeaders, resolveCors } from '../security';
|
||||||
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
|
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
|
||||||
import { matchRoute } from './router';
|
import { normalizeRequestPath, resolveRoute } from './router';
|
||||||
import { readBody, deriveSecure, deriveIp } from './request';
|
import { readBody, deriveSecure, deriveIp } from './request';
|
||||||
import { pipeStream } from './stream';
|
import { pipeStream } from './stream';
|
||||||
import { attachWs } from './ws';
|
import { attachWs } from './ws';
|
||||||
@@ -93,7 +93,13 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
// Mirror handle()'s own preflight/route-match decision here, so we only read the body
|
// 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.
|
// (below) for a request that actually reaches a route handler — matching prior behaviour.
|
||||||
const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']);
|
const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']);
|
||||||
const matched = isPreflight ? undefined : matchRoute(routes, method, path);
|
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
|
||||||
|
}
|
||||||
|
|
||||||
let body: unknown;
|
let body: unknown;
|
||||||
|
|
||||||
|
|||||||
+11
-3
@@ -2,7 +2,7 @@ import type { StreamEncoder } from '../encoders';
|
|||||||
import { handle, computeInjected, type HandleResult } from './core';
|
import { handle, computeInjected, type HandleResult } from './core';
|
||||||
import { mergeInjectedHeaders } from './headers';
|
import { mergeInjectedHeaders } from './headers';
|
||||||
import { parseRequestBody } from './server';
|
import { parseRequestBody } from './server';
|
||||||
import { matchRoute } from './router';
|
import { normalizeRequestPath, resolveRoute } from './router';
|
||||||
import { HttpError } from '../signals';
|
import { HttpError } from '../signals';
|
||||||
import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers';
|
import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers';
|
||||||
import type { RouteDef, HttpOptions, MatchedRoute } from './types';
|
import type { RouteDef, HttpOptions, MatchedRoute } from './types';
|
||||||
@@ -108,7 +108,8 @@ function outcomeToResponse(result: HandleResult): Response {
|
|||||||
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers });
|
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers });
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Response(result.outcome.body, { status: result.outcome.status, headers });
|
const body = [204, 205, 304].includes(result.outcome.status) ? null : result.outcome.body;
|
||||||
|
return new Response(body, { status: result.outcome.status, headers });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -123,7 +124,14 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
|||||||
const url = new URL(request.url);
|
const url = new URL(request.url);
|
||||||
const path = url.pathname + url.search;
|
const path = url.pathname + url.search;
|
||||||
const headers = headersToRecord(request.headers);
|
const headers = headersToRecord(request.headers);
|
||||||
const matched = matchRoute(routes, request.method, url.pathname);
|
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:';
|
const secure = url.protocol === 'https:';
|
||||||
// Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501,
|
// 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
|
// before a route handler even runs) carry the same security/CORS headers Node's writeHead patch
|
||||||
|
|||||||
+3
-1
@@ -6,7 +6,7 @@
|
|||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
|
|
||||||
/** Package version, replaced at publish time. */
|
/** Package version, replaced at publish time. */
|
||||||
export const VERSION = '26.7.0-beta.0';
|
export const VERSION = '26.8.0-beta.0';
|
||||||
|
|
||||||
// Application
|
// Application
|
||||||
export { createApp } from './app';
|
export { createApp } from './app';
|
||||||
@@ -27,6 +27,7 @@ export {
|
|||||||
Step,
|
Step,
|
||||||
Route,
|
Route,
|
||||||
Get,
|
Get,
|
||||||
|
Head,
|
||||||
Module,
|
Module,
|
||||||
Transformer,
|
Transformer,
|
||||||
Sse,
|
Sse,
|
||||||
@@ -36,6 +37,7 @@ export {
|
|||||||
Put,
|
Put,
|
||||||
Patch,
|
Patch,
|
||||||
Delete,
|
Delete,
|
||||||
|
Options,
|
||||||
Html,
|
Html,
|
||||||
} from './metadata';
|
} from './metadata';
|
||||||
export type { Transport, HttpMethod } from './metadata';
|
export type { Transport, HttpMethod } from './metadata';
|
||||||
|
|||||||
+5
-1
@@ -25,7 +25,7 @@ export interface StepMeta {
|
|||||||
export: boolean;
|
export: boolean;
|
||||||
}
|
}
|
||||||
/** HTTP verbs supported by the route decorators. */
|
/** 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. */
|
/** Wire transport a route responds with. */
|
||||||
export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws';
|
export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws';
|
||||||
/** Metadata attached by a route decorator to a single handler method. */
|
/** Metadata attached by a route decorator to a single handler method. */
|
||||||
@@ -124,6 +124,8 @@ function routeDecorator(method: HttpMethod, transport: Transport) {
|
|||||||
|
|
||||||
/** Declares a buffered `GET` route. */
|
/** Declares a buffered `GET` route. */
|
||||||
export const Get = routeDecorator('GET', 'buffer');
|
export const Get = routeDecorator('GET', 'buffer');
|
||||||
|
/** Declares a buffered `HEAD` route. */
|
||||||
|
export const Head = routeDecorator('HEAD', 'buffer');
|
||||||
/** Declares a buffered `POST` route. */
|
/** Declares a buffered `POST` route. */
|
||||||
export const Post = routeDecorator('POST', 'buffer');
|
export const Post = routeDecorator('POST', 'buffer');
|
||||||
/** Declares a buffered `PUT` route. */
|
/** Declares a buffered `PUT` route. */
|
||||||
@@ -132,6 +134,8 @@ export const Put = routeDecorator('PUT', 'buffer');
|
|||||||
export const Patch = routeDecorator('PATCH', 'buffer');
|
export const Patch = routeDecorator('PATCH', 'buffer');
|
||||||
/** Declares a buffered `DELETE` route. */
|
/** Declares a buffered `DELETE` route. */
|
||||||
export const Delete = routeDecorator('DELETE', 'buffer');
|
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. */
|
/** Declares a `GET` route streamed as Server-Sent Events. */
|
||||||
export const Sse = routeDecorator('GET', 'sse');
|
export const Sse = routeDecorator('GET', 'sse');
|
||||||
/** Declares a `GET` route whose transport is content-negotiated at request time. */
|
/** Declares a `GET` route whose transport is content-negotiated at request time. */
|
||||||
|
|||||||
+24
-9
@@ -1,5 +1,6 @@
|
|||||||
import type { ArgSpec } from './params';
|
import type { ArgSpec } from './params';
|
||||||
import type { Transport } from './metadata';
|
import type { Transport } from './metadata';
|
||||||
|
import { compilePattern } from './http/router';
|
||||||
|
|
||||||
/** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */
|
/** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */
|
||||||
export interface OpenApiRoute {
|
export interface OpenApiRoute {
|
||||||
@@ -23,23 +24,37 @@ export interface OpenApiDoc {
|
|||||||
paths: Record<string, Record<string, unknown>>;
|
paths: Record<string, Record<string, unknown>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
type Parameter = { name: string; in: 'path' | 'query' | 'header'; required: boolean; schema: { type: 'string' } };
|
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}`. */
|
/** Converts a route pattern to an OpenAPI path template: `/users/:id` → `/users/{id}`, `:rest*` → `{rest}`. */
|
||||||
function templatePath(pattern: string): string {
|
function templatePath(pattern: string): string {
|
||||||
const segments = pattern
|
const segments = compilePattern(pattern).segments.map((segment) =>
|
||||||
.split('/')
|
segment.kind === 'static' ? segment.value : `{${segment.name}}`,
|
||||||
.filter(Boolean)
|
);
|
||||||
.map((seg) => (seg.startsWith(':') ? `{${seg.slice(1).replace(/\*$/, '')}}` : seg));
|
|
||||||
return `/${segments.join('/')}`;
|
return `/${segments.join('/')}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Every `:name` (and `:name*`) segment of a pattern becomes a required path parameter. */
|
/** Every `:name` (and `:name*`) segment of a pattern becomes a required path parameter. */
|
||||||
function pathParams(pattern: string): Parameter[] {
|
function pathParams(pattern: string): Parameter[] {
|
||||||
return pattern
|
return compilePattern(pattern).segments.flatMap((segment): Parameter[] => {
|
||||||
.split('/')
|
if (segment.kind === 'static') return [];
|
||||||
.filter((seg) => seg.startsWith(':'))
|
return [
|
||||||
.map((seg) => ({ name: seg.slice(1).replace(/\*$/, ''), in: 'path', required: true, schema: { type: 'string' } }));
|
{
|
||||||
|
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. */
|
/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */
|
||||||
|
|||||||
+1
-1
@@ -62,7 +62,7 @@ export class TransportMismatchError extends HttpError {
|
|||||||
const expected = got === 'stream' ? 'return a value' : 'return an AsyncIterable';
|
const expected = got === 'stream' ? 'return a value' : 'return an AsyncIterable';
|
||||||
const fix =
|
const fix =
|
||||||
got === 'stream'
|
got === 'stream'
|
||||||
? 'buffered routes (@Get/@Post/@Put/@Patch/@Delete) must return a value — to stream, declare @Sse, @Stream, or @Ws'
|
? '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())';
|
: '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}.`);
|
super(500, `Transport '${transport}'${where} must ${expected}, but the handler returned a ${got}. ${fix}.`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -583,3 +583,39 @@ test('per-route maxBodyBytes overrides the server default', async () => {
|
|||||||
|
|
||||||
server.close();
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -35,6 +35,26 @@ class DupCtl {
|
|||||||
@Module({ mountpoint: '/api', controllers: [DupCtl] })
|
@Module({ mountpoint: '/api', controllers: [DupCtl] })
|
||||||
class DupTeapotModule {}
|
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')
|
@Route('/c')
|
||||||
class PlainCtl {
|
class PlainCtl {
|
||||||
@Get('/ok')
|
@Get('/ok')
|
||||||
@@ -112,6 +132,27 @@ describe('mesh skeleton integration', () => {
|
|||||||
bServer.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 () => {
|
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 a = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||||
const aServer = await a.listen(0);
|
const aServer = await a.listen(0);
|
||||||
|
|||||||
+13
-1
@@ -3,7 +3,7 @@ import { expect, test, describe, it } from 'vitest';
|
|||||||
import {
|
import {
|
||||||
Provider, Step, Route, Get, Module,
|
Provider, Step, Route, Get, Module,
|
||||||
getProviderMeta, getStepMeta, getRoutes, getModuleMeta,
|
getProviderMeta, getStepMeta, getRoutes, getModuleMeta,
|
||||||
Sse, Ws, Stream, Post,
|
Sse, Ws, Stream, Post, Head, Options,
|
||||||
} from '../src/metadata';
|
} from '../src/metadata';
|
||||||
|
|
||||||
@Provider({ provides: 'db', needs: ['config'] })
|
@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', () => {
|
describe('mesh export flags', () => {
|
||||||
it('providers/steps carry export (default false)', () => {
|
it('providers/steps carry export (default false)', () => {
|
||||||
@Provider({ provides: 'config', export: true }) class C { provide() { return {}; } }
|
@Provider({ provides: 'config', export: true }) class C { provide() { return {}; } }
|
||||||
|
|||||||
+25
-2
@@ -1,7 +1,7 @@
|
|||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
import { describe, it, expect } from 'vitest';
|
import { describe, it, expect } from 'vitest';
|
||||||
import { createApp } from '../src/app';
|
import { createApp } from '../src/app';
|
||||||
import { Route, Get, Post, Ws, Module } from '../src/metadata';
|
import { Route, Get, Head, Options, Post, Ws, Module } from '../src/metadata';
|
||||||
import { param, query, headers, body } from '../src/params';
|
import { param, query, headers, body } from '../src/params';
|
||||||
|
|
||||||
const numSchema = {
|
const numSchema = {
|
||||||
@@ -14,7 +14,13 @@ const numSchema = {
|
|||||||
|
|
||||||
@Route('/users')
|
@Route('/users')
|
||||||
class Users {
|
class Users {
|
||||||
@Get('/:id') get(@param('id') _id: string, @query('expand') _e: string, @headers('x-trace') _t: string) {
|
@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 {};
|
return {};
|
||||||
}
|
}
|
||||||
@Post('/') create(@body() _b: unknown) {
|
@Post('/') create(@body() _b: unknown) {
|
||||||
@@ -52,6 +58,23 @@ describe('app.openapi()', () => {
|
|||||||
expect(byName).toEqual({ id: 'path', expand: 'query', 'x-trace': 'header' });
|
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', () => {
|
it('marks routes that take a body with requestBody', () => {
|
||||||
const op = doc.paths['/api/users'].post as any;
|
const op = doc.paths['/api/users'].post as any;
|
||||||
expect(op.requestBody.content['application/json']).toBeDefined();
|
expect(op.requestBody.content['application/json']).toBeDefined();
|
||||||
|
|||||||
+48
-1
@@ -1,6 +1,6 @@
|
|||||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||||
import type { Server } from 'http';
|
import type { Server } from 'http';
|
||||||
import { createApp, Provider, Route, Get, Post, Module, needs, body, Sse } from '../src/index';
|
import { createApp, Provider, Route, Get, Head, Options, Post, Module, needs, body, Sse } from '../src/index';
|
||||||
|
|
||||||
@Provider({ provides: 'db' })
|
@Provider({ provides: 'db' })
|
||||||
class Db {
|
class Db {
|
||||||
@@ -22,6 +22,21 @@ class Ctl {
|
|||||||
yield { n: 2 };
|
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] })
|
@Module({ mountpoint: '/', providers: [Db], controllers: [Ctl] })
|
||||||
class M {}
|
class M {}
|
||||||
@@ -78,6 +93,38 @@ describe('Node vs app.fetch parity (Node is truth)', () => {
|
|||||||
expect(web.status).toBe(node.status);
|
expect(web.status).toBe(node.status);
|
||||||
expect(norm(web.headers)).toEqual(norm(node.headers));
|
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 () => {
|
it('SSE first two events', async () => {
|
||||||
const nodeText = await (await fetch(base + '/api/s')).text();
|
const nodeText = await (await fetch(base + '/api/s')).text();
|
||||||
const webText = await (await app.fetch(new Request(base + '/api/s'))).text();
|
const webText = await (await app.fetch(new Request(base + '/api/s'))).text();
|
||||||
|
|||||||
+77
-4
@@ -1,5 +1,12 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
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';
|
import type { RouteDef } from '../src/http/types';
|
||||||
|
|
||||||
const route = (method: string, pattern: string): RouteDef => ({
|
const route = (method: string, pattern: string): RouteDef => ({
|
||||||
@@ -10,6 +17,11 @@ const route = (method: string, pattern: string): RouteDef => ({
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('matchPattern', () => {
|
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', () => {
|
it('matches static and :param segments, decoding params', () => {
|
||||||
expect(matchPattern('/users/:id', '/users/a%20b')).toEqual({ id: 'a b' });
|
expect(matchPattern('/users/:id', '/users/a%20b')).toEqual({ id: 'a b' });
|
||||||
expect(matchPattern('/users/:id', '/users')).toBeUndefined();
|
expect(matchPattern('/users/:id', '/users')).toBeUndefined();
|
||||||
@@ -24,6 +36,46 @@ describe('matchPattern', () => {
|
|||||||
it(':name* matches zero remaining segments as an empty string', () => {
|
it(':name* matches zero remaining segments as an empty string', () => {
|
||||||
expect(matchPattern('/files/:path*', '/files')).toEqual({ path: '' });
|
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', () => {
|
describe('matchRoute precedence', () => {
|
||||||
@@ -34,6 +86,12 @@ describe('matchRoute precedence', () => {
|
|||||||
expect(matchRoute(routes, 'GET', '/a/x/y')?.def.pattern).toBe('/a/:rest*');
|
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', () => {
|
it('returns undefined when no pattern matches the path', () => {
|
||||||
expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined();
|
expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined();
|
||||||
});
|
});
|
||||||
@@ -44,9 +102,24 @@ describe('matchRoute precedence', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('allowedMethods (405 support)', () => {
|
describe('allowedMethods (405 support)', () => {
|
||||||
it('lists distinct methods whose pattern matches the path', () => {
|
it('lists methods in canonical order with implicit HEAD and OPTIONS', () => {
|
||||||
const routes = [route('GET', '/a'), route('POST', '/a'), route('GET', '/b')];
|
const routes = [route('POST', '/a'), route('GET', '/a'), route('GET', '/b')];
|
||||||
expect(allowedMethods(routes, '/a').sort()).toEqual(['GET', 'POST']);
|
expect(allowedMethods(routes, '/a')).toEqual(['GET', 'HEAD', 'POST', 'OPTIONS']);
|
||||||
expect(allowedMethods(routes, '/nope')).toEqual([]);
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
+8
-1
@@ -1,6 +1,13 @@
|
|||||||
import { expect, test } from 'vitest';
|
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', () => {
|
test('package loads and exposes a CalVer VERSION', () => {
|
||||||
expect(VERSION).toMatch(/^\d{2}\.\d{1,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']);
|
||||||
|
});
|
||||||
@@ -187,7 +187,7 @@ describe('CORS', () => {
|
|||||||
expect(r.headers.get('access-control-allow-credentials')).toBe('true');
|
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 }; } }
|
@Route('/') class C { @Get('/x') x() { return { ok: 1 }; } }
|
||||||
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } });
|
app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } });
|
||||||
@@ -195,11 +195,11 @@ describe('CORS', () => {
|
|||||||
const port = (server.address() as any).port;
|
const port = (server.address() as any).port;
|
||||||
const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://evil.com' } });
|
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();
|
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
|
// A bare OPTIONS (no Access-Control-Request-Method) isn't a CORS preflight; the router
|
||||||
// under GET, so the router answers 405 with an Allow header rather than 404.
|
// answers it automatically and advertises the explicit + implicit methods.
|
||||||
const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' });
|
const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' });
|
||||||
expect(bare.status).toBe(405);
|
expect(bare.status).toBe(204);
|
||||||
expect(bare.headers.get('allow')).toContain('GET');
|
expect(bare.headers.get('allow')).toBe('GET, HEAD, OPTIONS');
|
||||||
});
|
});
|
||||||
|
|
||||||
it("merges a handler's Title-Case Vary with CORS's Origin", async () => {
|
it("merges a handler's Title-Case Vary with CORS's Origin", async () => {
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ export default defineConfig({
|
|||||||
base: '/docs',
|
base: '/docs',
|
||||||
integrations: [
|
integrations: [
|
||||||
starlight({
|
starlight({
|
||||||
|
// Let the content-backed 404.md own /404; otherwise Astro also injects a conflicting route.
|
||||||
|
disable404Route: true,
|
||||||
title: 'Green Tea.',
|
title: 'Green Tea.',
|
||||||
description: 'A zen, opinionated, type-safe framework — your API is a graph, not a chain.',
|
description: 'A zen, opinionated, type-safe framework — your API is a graph, not a chain.',
|
||||||
logo: { src: './src/assets/logo.svg', alt: 'Green Tea' },
|
logo: { src: './src/assets/logo.svg', alt: 'Green Tea' },
|
||||||
|
|||||||
Generated
+170
-171
@@ -6,35 +6,35 @@
|
|||||||
"": {
|
"": {
|
||||||
"name": "green-tea-docs",
|
"name": "green-tea-docs",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/starlight": "^0.41.3",
|
"@astrojs/starlight": "^0.41.6",
|
||||||
"astro": "^7.0.6",
|
"astro": "^7.1.6",
|
||||||
"sharp": "^0.35.3"
|
"sharp": "^0.35.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding": {
|
"node_modules/@astrojs/compiler-binding": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding/-/compiler-binding-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding/-/compiler-binding-0.3.2.tgz",
|
||||||
"integrity": "sha512-zlsOT5COD9hRwplJCgQhS21unxON5AKirf0vgt1ijXwuseYIaZdm2ZOpF8fsz+DY9EyXx+I/ukxtg7uoBep68A==",
|
"integrity": "sha512-8w/9CWmYrAJJ8N0SY3O43ws2BgxoW6u3QsD8u2mE140lMYAlwh+tlNoUeSBq22wVheFuiBbR212l6ixZ2IIgCQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^20.19.0 || >=22.12.0"
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@astrojs/compiler-binding-darwin-arm64": "0.3.0",
|
"@astrojs/compiler-binding-darwin-arm64": "0.3.2",
|
||||||
"@astrojs/compiler-binding-darwin-x64": "0.3.0",
|
"@astrojs/compiler-binding-darwin-x64": "0.3.2",
|
||||||
"@astrojs/compiler-binding-linux-arm64-gnu": "0.3.0",
|
"@astrojs/compiler-binding-linux-arm64-gnu": "0.3.2",
|
||||||
"@astrojs/compiler-binding-linux-arm64-musl": "0.3.0",
|
"@astrojs/compiler-binding-linux-arm64-musl": "0.3.2",
|
||||||
"@astrojs/compiler-binding-linux-x64-gnu": "0.3.0",
|
"@astrojs/compiler-binding-linux-x64-gnu": "0.3.2",
|
||||||
"@astrojs/compiler-binding-linux-x64-musl": "0.3.0",
|
"@astrojs/compiler-binding-linux-x64-musl": "0.3.2",
|
||||||
"@astrojs/compiler-binding-wasm32-wasi": "0.3.0",
|
"@astrojs/compiler-binding-wasm32-wasi": "0.3.2",
|
||||||
"@astrojs/compiler-binding-win32-arm64-msvc": "0.3.0",
|
"@astrojs/compiler-binding-win32-arm64-msvc": "0.3.2",
|
||||||
"@astrojs/compiler-binding-win32-x64-msvc": "0.3.0"
|
"@astrojs/compiler-binding-win32-x64-msvc": "0.3.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-darwin-arm64": {
|
"node_modules/@astrojs/compiler-binding-darwin-arm64": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-arm64/-/compiler-binding-darwin-arm64-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-arm64/-/compiler-binding-darwin-arm64-0.3.2.tgz",
|
||||||
"integrity": "sha512-3n0uu+uJpnCq8b4JFi3uGDsIisAvHctxSmH+cIO9Gbei1H1Y1QXaYboXyiWJugUmprr3OEYP7+LdodzpVFzLMQ==",
|
"integrity": "sha512-MM8tn8CSimcfytaOla4b6acN8mKWiL/rlAA1fpT3/Wl7dNGSE4y8FjTN/zJVNnb63CsLWG5zZwCt01TXtDKh9g==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -48,9 +48,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-darwin-x64": {
|
"node_modules/@astrojs/compiler-binding-darwin-x64": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-x64/-/compiler-binding-darwin-x64-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-darwin-x64/-/compiler-binding-darwin-x64-0.3.2.tgz",
|
||||||
"integrity": "sha512-scxNGKjOBydMo1QR4LtK0FMgh7ubQomJDv953nz2msQFkPKke/0FpPv/cQM0T/kuZdReZQFU8Oz3iOrP/6WHEg==",
|
"integrity": "sha512-2lXOlzf8xb7jLomRsf/aswh61/NnGusynB2OwFkK6k4pmOtpfXMYnG0PLfXrEvxXYj69NdCnmUYXtHDd+JOOag==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -64,12 +64,15 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-linux-arm64-gnu": {
|
"node_modules/@astrojs/compiler-binding-linux-arm64-gnu": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-gnu/-/compiler-binding-linux-arm64-gnu-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-gnu/-/compiler-binding-linux-arm64-gnu-0.3.2.tgz",
|
||||||
"integrity": "sha512-NZrWLolVUANmrnl0zrFK/Sx5Sock1gEUT49ALfMTTCA5Ya2ec/BoJXMIg4KgE+wZcrdXJ8e+WyEhM7YLk/FJkA==",
|
"integrity": "sha512-BmU3kWj7qnLrd4vzm49zFEPJ5oFnn1tCT4Vt9hZbqdU5Cmb8GZl7fn6VFsnNfe7B18a2gIFtVzbLINtYl5kBjQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
|
"libc": [
|
||||||
|
"glibc"
|
||||||
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -80,12 +83,15 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-linux-arm64-musl": {
|
"node_modules/@astrojs/compiler-binding-linux-arm64-musl": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-musl/-/compiler-binding-linux-arm64-musl-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-arm64-musl/-/compiler-binding-linux-arm64-musl-0.3.2.tgz",
|
||||||
"integrity": "sha512-PjwRmKgMFDsFhg82g0poXlIY8Qn3fMA3hXjaR0coJWJzTJsRH9ATU0j2ocigjtU1h3vL/yR7yLUxGj/lTCq73g==",
|
"integrity": "sha512-f0heT9ZZEseSu5bHCeb80eL2DH07ArE6U9xi1WT/PEusNjzPmEr3GJsjG1tRLo5VYUUYX7h3ScaqGmGrMOVGmw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
|
"libc": [
|
||||||
|
"musl"
|
||||||
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -96,12 +102,15 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-linux-x64-gnu": {
|
"node_modules/@astrojs/compiler-binding-linux-x64-gnu": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-gnu/-/compiler-binding-linux-x64-gnu-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-gnu/-/compiler-binding-linux-x64-gnu-0.3.2.tgz",
|
||||||
"integrity": "sha512-Dr69VJYlnSfyL8gzELW6S4mE41P7TDPn1IKjwMnjdZ7+dxgJI50oMLFSk1LVe26bHmWB3ktuh8fDVK1THI9e9A==",
|
"integrity": "sha512-M8fOUt0itRpqiGyoEA/ij184s8O+hqbCz3+YozRusOOM3osgGljpDThhbKAJjqh82wOo6FioQ4w8PBvU1XMD5Q==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
|
"libc": [
|
||||||
|
"glibc"
|
||||||
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -112,12 +121,15 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-linux-x64-musl": {
|
"node_modules/@astrojs/compiler-binding-linux-x64-musl": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-musl/-/compiler-binding-linux-x64-musl-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-linux-x64-musl/-/compiler-binding-linux-x64-musl-0.3.2.tgz",
|
||||||
"integrity": "sha512-AEt+bRw8PfImCcyRH1lpXVB8CdmQ1K/wPo5u99iec4/U/XdNvQZ715YVuNzIJpbJXelgQeZ5H2+Ea7XwRyWY5g==",
|
"integrity": "sha512-/Kebk8sO6HnLeSd691JkaAPfN7CqR9/KEXmWvyNPkaKNGmj8rTZ/lf2uXtnPu92Lan84UrKdIKVPy1fSo2encQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
|
"libc": [
|
||||||
|
"musl"
|
||||||
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -128,25 +140,25 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-wasm32-wasi": {
|
"node_modules/@astrojs/compiler-binding-wasm32-wasi": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-wasm32-wasi/-/compiler-binding-wasm32-wasi-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-wasm32-wasi/-/compiler-binding-wasm32-wasi-0.3.2.tgz",
|
||||||
"integrity": "sha512-U80tA1j8V6LjhiTZzVCtG4E8hrNVVNXDGV5fCgJ94q8FU9CPH+XwdDDhLzBybfWhKfyItXmQiZNRPTiPCYTpVg==",
|
"integrity": "sha512-pUA6xbcOSB7DhfzIArB8BCAkFfAIqriiR7zl5zOStd6oU2G0kIKj+GUdGnyXyhfiv881Hffyk5tC0mR18sDjDw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"wasm32"
|
"wasm32"
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@napi-rs/wasm-runtime": "^1.1.6"
|
"@napi-rs/wasm-runtime": "^1.2.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=14.0.0"
|
"node": ">=14.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-win32-arm64-msvc": {
|
"node_modules/@astrojs/compiler-binding-win32-arm64-msvc": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-arm64-msvc/-/compiler-binding-win32-arm64-msvc-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-arm64-msvc/-/compiler-binding-win32-arm64-msvc-0.3.2.tgz",
|
||||||
"integrity": "sha512-CpY1RII2r1XMpOUVD1VR/F2wtuRsiOCkFULS10Khyj8/DFZMtxVuUCAWGw+CW2Ka0h6eP3Xc1CA+glFlvXMPxA==",
|
"integrity": "sha512-ESruf+6Qkl1trHUFxI6GSf6t52j8yN2kCNSzMWdzt7V/T09tFHrYzrVaJQohb2C9bJUH76pNvX6Zb51+xCQc9Q==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -160,9 +172,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-binding-win32-x64-msvc": {
|
"node_modules/@astrojs/compiler-binding-win32-x64-msvc": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-x64-msvc/-/compiler-binding-win32-x64-msvc-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding-win32-x64-msvc/-/compiler-binding-win32-x64-msvc-0.3.2.tgz",
|
||||||
"integrity": "sha512-qmFbs769oeeGrRebAnCW7aBk8m71vf85W/dX/jddfx5Z06/w0wf7TZCfJPOX1Fld2t+4N+iXzfGEJG+zJQ+bzg==",
|
"integrity": "sha512-wzzVrEbOwbsLWOdEbocskjMRx2aZPxJ7ZbmL+jnpBamFwmigm+2M/wzuM6JWncocgYwLic1csSpalBh96kQKXA==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -176,12 +188,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/compiler-rs": {
|
"node_modules/@astrojs/compiler-rs": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler-rs/-/compiler-rs-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/compiler-rs/-/compiler-rs-0.3.2.tgz",
|
||||||
"integrity": "sha512-J2qEVHtIDjEM9TxwmwuebOGmZNwhKu/dR7P7qBpnJKGmBBX0vdweQ/4cEXhj8fBbWVUB5V12xWChri3CgKNULQ==",
|
"integrity": "sha512-xlx/T7JovIKduu4ucbTQUxQ5+Q8wxkHxhLjnZk3VlJbhbQ9RLvvuDk1p2YYFYFQ5y14dVm3FGGO4isQXa4F+Tg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/compiler-binding": "0.3.0"
|
"@astrojs/compiler-binding": "0.3.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=22.12.0"
|
"node": ">=22.12.0"
|
||||||
@@ -203,41 +215,33 @@
|
|||||||
"unified": "^11.0.5"
|
"unified": "^11.0.5"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/markdown-remark": {
|
"node_modules/@astrojs/markdown-satteri": {
|
||||||
"version": "7.2.1",
|
"version": "0.3.5",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/markdown-remark/-/markdown-remark-7.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/markdown-satteri/-/markdown-satteri-0.3.5.tgz",
|
||||||
"integrity": "sha512-jPVNIqTvk+yKviikszv/Y1U4jGUSKpp/Nw48QZV4qjWgp70j4Lkq3lhSDRbWwCfgKvEyO9GHuVbV1dM2WYXy1w==",
|
"integrity": "sha512-CvWVEFAbay7YO+i9SaqDJubipA5ckiVB89QWoMJ5XC0m5CtFg8JwZ7Kau6X9sYY7FZURH0w2l03ISH2jOS/RDQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/internal-helpers": "0.10.1",
|
"@astrojs/internal-helpers": "0.10.2",
|
||||||
"@astrojs/prism": "4.0.2",
|
"@astrojs/prism": "4.0.2",
|
||||||
"github-slugger": "^2.0.0",
|
"github-slugger": "^2.0.0",
|
||||||
"hast-util-from-html": "^2.0.3",
|
"hast-util-from-html": "^2.0.3",
|
||||||
"hast-util-to-text": "^4.0.2",
|
"satteri": "^0.9.1"
|
||||||
"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/markdown-satteri": {
|
"node_modules/@astrojs/markdown-satteri/node_modules/@astrojs/internal-helpers": {
|
||||||
"version": "0.3.3",
|
"version": "0.10.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/markdown-satteri/-/markdown-satteri-0.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/internal-helpers/-/internal-helpers-0.10.2.tgz",
|
||||||
"integrity": "sha512-Lje33Ittd8UQGgbIIWQvhPkj5X5c4b1sZnZWX3JQV/AWpfbuQGxVi2ONt6+ScydcwfR4egilslEWyczMclrJ1g==",
|
"integrity": "sha512-yt7fMgPYqSM4Tmr+taTW6Per+hjJ8Pk6lA1PAcDyqzOt8HzJ6Kje5WzCxA2Sd+9wsUW7uhkLeoTMK0cXPwH9rQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/internal-helpers": "0.10.1",
|
"@types/hast": "^3.0.4",
|
||||||
"@astrojs/prism": "4.0.2",
|
"@types/mdast": "^4.0.4",
|
||||||
"github-slugger": "^2.0.0",
|
"js-yaml": "^4.3.0",
|
||||||
"satteri": "^0.9.1"
|
"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": {
|
"node_modules/@astrojs/mdx": {
|
||||||
@@ -274,6 +278,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": {
|
"node_modules/@astrojs/prism": {
|
||||||
"version": "4.0.2",
|
"version": "4.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/prism/-/prism-4.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/prism/-/prism-4.0.2.tgz",
|
||||||
@@ -298,9 +327,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/starlight": {
|
"node_modules/@astrojs/starlight": {
|
||||||
"version": "0.41.3",
|
"version": "0.41.6",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/starlight/-/starlight-0.41.3.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/starlight/-/starlight-0.41.6.tgz",
|
||||||
"integrity": "sha512-8xsG6UpK581TJmtOc7/pnxHKEbP16rV06VLWaVa7FOyE/VEwnaHOsLtL+miifCEfuiuv0Wn+j8u3JSluRQesMQ==",
|
"integrity": "sha512-Dt0/wY2JbFGUpxMgclw1j2Iqks2GG0LHYKgP7TfBXsFrs4LIbKvQ596lzyhXLz6nFcnPdIB9ZRFyDJeuVcx3Ug==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/markdown-satteri": "^0.3.2",
|
"@astrojs/markdown-satteri": "^0.3.2",
|
||||||
@@ -344,16 +373,15 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@astrojs/telemetry": {
|
"node_modules/@astrojs/telemetry": {
|
||||||
"version": "3.3.2",
|
"version": "3.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/@astrojs/telemetry/-/telemetry-3.3.2.tgz",
|
"resolved": "https://registry.npmjs.org/@astrojs/telemetry/-/telemetry-3.3.3.tgz",
|
||||||
"integrity": "sha512-j8DNruA8ors99Al39RYZPJK4DC1bKkoNm93mAMuBhY9TCNC4R8n1q7ovFnJ5qhGh5Lsh7pa1gpQVpYpsJPeTHQ==",
|
"integrity": "sha512-C1TLn5sPJr0x4vk56piHWKbnqlEB8BKyte5Y45V02U+D7BGO5eMqZDH5aPjnkXQWJggvmsTXxH03QMZ9NgWLzQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"ci-info": "^4.4.0",
|
"ci-info": "^4.4.0",
|
||||||
"dset": "^3.1.4",
|
"dset": "^3.1.4",
|
||||||
"is-docker": "^4.0.0",
|
"is-docker": "^4.0.0",
|
||||||
"is-wsl": "^3.1.1",
|
"package-manager-detector": "^1.6.0"
|
||||||
"which-pm-runs": "^1.1.0"
|
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "18.20.8 || ^20.3.0 || >=22.0.0"
|
"node": "18.20.8 || ^20.3.0 || >=22.0.0"
|
||||||
@@ -1625,21 +1653,24 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@napi-rs/wasm-runtime": {
|
"node_modules/@napi-rs/wasm-runtime": {
|
||||||
"version": "1.1.6",
|
"version": "1.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz",
|
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.2.tgz",
|
||||||
"integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==",
|
"integrity": "sha512-JfB4kuJQjaoHuCTseIINHtHWeJnvgEcxjwA5t/Y00ZgaOO1Crz3fjT/p8kT28zA/Caz7oiUMn3d6H2yOVCVwuw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tybys/wasm-util": "^0.10.3"
|
"@tybys/wasm-util": "^0.10.3"
|
||||||
},
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
|
||||||
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"type": "github",
|
"type": "github",
|
||||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@emnapi/core": "^1.7.1",
|
"@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3",
|
||||||
"@emnapi/runtime": "^1.7.1"
|
"@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@oslojs/encoding": {
|
"node_modules/@oslojs/encoding": {
|
||||||
@@ -2359,15 +2390,15 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/astro": {
|
"node_modules/astro": {
|
||||||
"version": "7.0.6",
|
"version": "7.1.6",
|
||||||
"resolved": "https://registry.npmjs.org/astro/-/astro-7.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/astro/-/astro-7.1.6.tgz",
|
||||||
"integrity": "sha512-Myw0sFia+zs/Y0yqfZEsUYXfDPh3ELcLf1f0Q/qQzVXBh/af1qO62WNT+P89DCcfGVV51nMoQhEfkBYqJmoUOQ==",
|
"integrity": "sha512-83x9rYbHazMaZkYrAFRVZXSQx2moFkz0F7cjTDUF3GWfS0a3p2vZXG1ZdhV86rStHApQCodBJW+XTD37xISIrQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/compiler-rs": "^0.3.0",
|
"@astrojs/compiler-rs": "^0.3.2",
|
||||||
"@astrojs/internal-helpers": "0.10.1",
|
"@astrojs/internal-helpers": "0.10.2",
|
||||||
"@astrojs/markdown-satteri": "0.3.3",
|
"@astrojs/markdown-satteri": "0.3.5",
|
||||||
"@astrojs/telemetry": "3.3.2",
|
"@astrojs/telemetry": "3.3.3",
|
||||||
"@capsizecss/unpack": "^4.0.0",
|
"@capsizecss/unpack": "^4.0.0",
|
||||||
"@clack/prompts": "^1.1.0",
|
"@clack/prompts": "^1.1.0",
|
||||||
"@oslojs/encoding": "^1.1.0",
|
"@oslojs/encoding": "^1.1.0",
|
||||||
@@ -2378,7 +2409,7 @@
|
|||||||
"ci-info": "^4.4.0",
|
"ci-info": "^4.4.0",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"common-ancestor-path": "^2.0.0",
|
"common-ancestor-path": "^2.0.0",
|
||||||
"cookie": "^1.1.1",
|
"cookie": "^2.0.1",
|
||||||
"devalue": "^5.8.1",
|
"devalue": "^5.8.1",
|
||||||
"diff": "^8.0.3",
|
"diff": "^8.0.3",
|
||||||
"dset": "^3.1.4",
|
"dset": "^3.1.4",
|
||||||
@@ -2390,12 +2421,12 @@
|
|||||||
"github-slugger": "^2.0.0",
|
"github-slugger": "^2.0.0",
|
||||||
"html-escaper": "3.0.3",
|
"html-escaper": "3.0.3",
|
||||||
"http-cache-semantics": "^4.2.0",
|
"http-cache-semantics": "^4.2.0",
|
||||||
"js-yaml": "^4.1.1",
|
"js-yaml": "^4.3.0",
|
||||||
"jsonc-parser": "^3.3.1",
|
"jsonc-parser": "^3.3.1",
|
||||||
"magic-string": "^0.30.21",
|
"magic-string": "^1.0.0",
|
||||||
"magicast": "^0.5.2",
|
"magicast": "^0.5.2",
|
||||||
"mrmime": "^2.0.1",
|
"mrmime": "^2.0.1",
|
||||||
"neotraverse": "^0.6.18",
|
"neotraverse": "^1.0.1",
|
||||||
"obug": "^2.1.1",
|
"obug": "^2.1.1",
|
||||||
"p-limit": "^7.3.0",
|
"p-limit": "^7.3.0",
|
||||||
"p-queue": "^9.1.0",
|
"p-queue": "^9.1.0",
|
||||||
@@ -2434,7 +2465,7 @@
|
|||||||
"sharp": "^0.34.0 || ^0.35.0"
|
"sharp": "^0.34.0 || ^0.35.0"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@astrojs/markdown-remark": "7.2.1"
|
"@astrojs/markdown-remark": "7.2.2"
|
||||||
},
|
},
|
||||||
"peerDependenciesMeta": {
|
"peerDependenciesMeta": {
|
||||||
"@astrojs/markdown-remark": {
|
"@astrojs/markdown-remark": {
|
||||||
@@ -2455,6 +2486,31 @@
|
|||||||
"astro": "^4.0.0-beta || ^5.0.0-beta || ^3.3.0 || ^6.0.0-beta || ^7.0.0"
|
"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": {
|
"node_modules/axobject-query": {
|
||||||
"version": "4.1.0",
|
"version": "4.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
|
||||||
@@ -2633,12 +2689,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/cookie": {
|
"node_modules/cookie": {
|
||||||
"version": "1.1.1",
|
"version": "2.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.1.tgz",
|
||||||
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
|
"integrity": "sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18"
|
"node": ">=22"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"type": "opencollective",
|
"type": "opencollective",
|
||||||
@@ -3779,39 +3835,6 @@
|
|||||||
"url": "https://github.com/sponsors/wooorm"
|
"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": {
|
"node_modules/is-plain-obj": {
|
||||||
"version": "4.1.0",
|
"version": "4.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
|
||||||
@@ -3824,21 +3847,6 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"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": {
|
"node_modules/js-yaml": {
|
||||||
"version": "4.3.0",
|
"version": "4.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
|
||||||
@@ -5267,9 +5275,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/nanoid": {
|
"node_modules/nanoid": {
|
||||||
"version": "3.3.15",
|
"version": "3.3.16",
|
||||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",
|
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
|
||||||
"integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==",
|
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "github",
|
"type": "github",
|
||||||
@@ -5285,9 +5293,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/neotraverse": {
|
"node_modules/neotraverse": {
|
||||||
"version": "0.6.18",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/neotraverse/-/neotraverse-0.6.18.tgz",
|
"resolved": "https://registry.npmjs.org/neotraverse/-/neotraverse-1.0.1.tgz",
|
||||||
"integrity": "sha512-Z4SmBUweYa09+o6pG+eASabEpP6QkQ70yHj351pQoEXIs8uHbaU2DWVmzBANKgflPa47A50PtB2+NgRpQvr7vA==",
|
"integrity": "sha512-WmmLty1YWwJl9yZi77v2dVIV6X2kuYV8YYBI/G3LWGKdGHmHUvL1z7FW0iDvEvGAwNEoc5x1tOOOyDnf5jJw/w==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 10"
|
"node": ">= 10"
|
||||||
@@ -5533,9 +5541,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/postcss": {
|
"node_modules/postcss": {
|
||||||
"version": "8.5.16",
|
"version": "8.5.25",
|
||||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz",
|
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz",
|
||||||
"integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==",
|
"integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==",
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "opencollective",
|
"type": "opencollective",
|
||||||
@@ -5552,7 +5560,7 @@
|
|||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"nanoid": "^3.3.12",
|
"nanoid": "^3.3.16",
|
||||||
"picocolors": "^1.1.1",
|
"picocolors": "^1.1.1",
|
||||||
"source-map-js": "^1.2.1"
|
"source-map-js": "^1.2.1"
|
||||||
},
|
},
|
||||||
@@ -6264,9 +6272,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/svgo": {
|
"node_modules/svgo": {
|
||||||
"version": "4.0.1",
|
"version": "4.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/svgo/-/svgo-4.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/svgo/-/svgo-4.0.2.tgz",
|
||||||
"integrity": "sha512-XDpWUOPC6FEibaLzjfe0ucaV0YrOjYotGJO1WpF0Zd+n6ZGEQUsSugaoLq9QkEZtAfQIxT42UChcssDVPP3+/w==",
|
"integrity": "sha512-ekx94z1rRc5LDi6oSUaeRnYhd0UOJxdtQCL2rF8xpWxD3TPAsISWOrxezqGovqS38GRZOdpDfvQe3ts6F7nsng==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"commander": "^11.1.0",
|
"commander": "^11.1.0",
|
||||||
@@ -6807,15 +6815,6 @@
|
|||||||
"url": "https://github.com/sponsors/wooorm"
|
"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": {
|
"node_modules/xxhash-wasm": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz",
|
||||||
|
|||||||
@@ -8,8 +8,8 @@
|
|||||||
"preview": "astro preview"
|
"preview": "astro preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/starlight": "^0.41.3",
|
"@astrojs/starlight": "^0.41.6",
|
||||||
"astro": "^7.0.6",
|
"astro": "^7.1.6",
|
||||||
"sharp": "^0.35.3"
|
"sharp": "^0.35.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
---
|
||||||
|
title: Page not found
|
||||||
|
description: "The requested Green Tea documentation page does not exist."
|
||||||
|
template: splash
|
||||||
|
hero:
|
||||||
|
tagline: The documentation page you requested could not be found.
|
||||||
|
actions:
|
||||||
|
- text: Back to documentation
|
||||||
|
link: /docs/
|
||||||
|
icon: right-arrow
|
||||||
|
---
|
||||||
@@ -46,12 +46,12 @@ throw new HttpError(409, 'conflict', { code: 'DUP_EMAIL', field: 'email' });
|
|||||||
Not everything should be JSON. Pass `onError` to `createApp` to render errors however you like — HTML, [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807), content-negotiated, anything. It receives the error and the request, and returns a response — or `undefined` to fall back to the default JSON.
|
Not everything should be JSON. Pass `onError` to `createApp` to render errors however you like — HTML, [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807), content-negotiated, anything. It receives the error and the request, and returns a response — or `undefined` to fall back to the default JSON.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { isHttpError } from '@green-tea/core';
|
import { HttpError } from '@green-tea/core';
|
||||||
|
|
||||||
const app = createApp({
|
const app = createApp({
|
||||||
modules: [ApiModule],
|
modules: [ApiModule],
|
||||||
onError(error, req) {
|
onError(error, req) {
|
||||||
const status = isHttpError(error) ? error.status : 500;
|
const status = error instanceof HttpError ? error.status : 500;
|
||||||
// negotiate: HTML for browsers, JSON for API clients
|
// negotiate: HTML for browsers, JSON for API clients
|
||||||
if (String(req.headers.accept).includes('text/html')) {
|
if (String(req.headers.accept).includes('text/html')) {
|
||||||
return { status, headers: { 'content-type': 'text/html' }, body: `<h1>${status}</h1>` };
|
return { status, headers: { 'content-type': 'text/html' }, body: `<h1>${status}</h1>` };
|
||||||
@@ -61,7 +61,7 @@ const app = createApp({
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
`onError` intercepts **every** HTTP error response — handler/step throws, a `404` for an unmatched route, `405`, a `413` (body too large), and a `400` (malformed body) — so your error surface is consistent across the whole app. Streaming and WebSocket errors are out of scope (they surface as an error frame or a WebSocket close code, not a response body).
|
`onError` intercepts **every** HTTP error response — handler/step throws, a `404` for an unmatched route, `405`, a `413` (body too large), and a `400` (malformed body, repeated slash, or malformed path encoding) — so your error surface is consistent across the whole app. HEAD error responses keep the same status and headers but suppress the body. Streaming and WebSocket errors are out of scope (they surface as an error frame or a WebSocket close code, not a response body).
|
||||||
|
|
||||||
:::note
|
:::note
|
||||||
Errors are also observable without changing the response: subscribe to `request:step:error` (and `stream:error`) on [`app.bus`](/docs/guides/plugins/) to log or trace them.
|
Errors are also observable without changing the response: subscribe to `request:step:error` (and `stream:error`) on [`app.bus`](/docs/guides/plugins/) to log or trace them.
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ Same filesystem requirement as file mode: Node/Deno/Bun only.
|
|||||||
`string`; `@Html('file.html', { template: true })` returns the data object rendered into the
|
`string`; `@Html('file.html', { template: true })` returns the data object rendered into the
|
||||||
template; `@Html('file.html')` (no template) ignores the return entirely — annotate it `: void`
|
template; `@Html('file.html')` (no template) ignores the return entirely — annotate it `: void`
|
||||||
by convention, e.g. `page(@needs('x')): void {}`. Returning an `AsyncIterable` from any `@Html`
|
by convention, e.g. `page(@needs('x')): void {}`. Returning an `AsyncIterable` from any `@Html`
|
||||||
handler is the same buffered-route mismatch as any other `@Get`/`@Post`/`@Put`/`@Patch`/`@Delete`
|
handler is the same buffered-route mismatch as any other `@Get`/`@Head`/`@Post`/`@Put`/`@Patch`/`@Delete`/`@Options`
|
||||||
handler: a 500 `TransportMismatchError`, not a silent raw stream.
|
handler: a 500 `TransportMismatchError`, not a silent raw stream.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
@@ -145,7 +145,7 @@ Like the file/template modes of `@Html`, `static` needs a filesystem: it's Node/
|
|||||||
@Html
|
@Html
|
||||||
ticks() { /* ... */ }
|
ticks() { /* ... */ }
|
||||||
// throws at createApp(): "@Html on GET /ticks is not allowed —
|
// throws at createApp(): "@Html on GET /ticks is not allowed —
|
||||||
// @Html only supports buffered GET/POST routes (not SSE/WS/PUT/PATCH/DELETE)"
|
// @Html only supports buffered GET/POST routes (not SSE/WS/HEAD/PUT/PATCH/DELETE/OPTIONS)"
|
||||||
```
|
```
|
||||||
|
|
||||||
`@Html` and `@Transformer` also can't be combined on the same handler — pick one:
|
`@Html` and `@Transformer` also can't be combined on the same handler — pick one:
|
||||||
|
|||||||
@@ -94,17 +94,17 @@ Mesh proxies **buffered** endpoints. `@Sse`, `@Stream` and `@Ws` routes are not
|
|||||||
|
|
||||||
## One teapot per route
|
## One teapot per route
|
||||||
|
|
||||||
A route must be exported by exactly **one** teapot. If two export the same `method + pattern`, the boot **fails**, naming the route and both teapots:
|
A route must be exported by exactly **one** teapot. If two export the same method and effective match shape — including patterns that differ only by parameter name, such as `/:id` and `/:name` — boot **fails**, naming both patterns and both teapots:
|
||||||
|
|
||||||
```
|
```
|
||||||
mesh: route 'GET /api/svc/ping' is exported by more than one teapot
|
mesh: ambiguous remote route 'GET /api/shape/:name' from ws://b/__mesh__/control
|
||||||
(ws://a/__mesh__/control and ws://b/__mesh__/control) — load balancing across
|
conflicts with 'GET /api/shape/:id' from ws://a/__mesh__/control — load balancing
|
||||||
teapots is not implemented yet, so green-tea will not choose one for you.
|
across teapots is not implemented yet, so green-tea will not choose one for you.
|
||||||
```
|
```
|
||||||
|
|
||||||
This is a hard error rather than a silent pick because there is no load balancing to fall back on: choosing one would be an arbitrary answer you could come to depend on. Scope tokens (`@Provider`/`@Step`) are unique for the same reason — and balancing them would be meaningless anyway, since an app-scope export is resolved once and cached.
|
This is a hard error rather than a silent pick because there is no load balancing to fall back on: choosing one would be an arbitrary answer you could come to depend on. Scope tokens (`@Provider`/`@Step`) are unique for the same reason — and balancing them would be meaningless anyway, since an app-scope export is resolved once and cached.
|
||||||
|
|
||||||
**Local routes win.** If you declare a route locally *and* import it from a teapot, yours takes precedence — that is how you override a teapot — and green-tea warns so a shadowed export doesn't look like a broken one:
|
**Local routes win.** If you declare a route locally *and* import the same effective method/shape from a teapot, yours takes precedence — that is how you override a teapot — and green-tea warns so a shadowed export doesn't look like a broken one:
|
||||||
|
|
||||||
```
|
```
|
||||||
[green-tea] mesh: route 'GET /api/svc/ping' is exported by teapot ws://a/… but also
|
[green-tea] mesh: route 'GET /api/svc/ping' is exported by teapot ws://a/… but also
|
||||||
|
|||||||
@@ -15,14 +15,16 @@ const spec = app.openapi({ title: 'My API', version: '1.0.0' });
|
|||||||
|
|
||||||
It reads the routes and handler signatures and produces, for each route:
|
It reads the routes and handler signatures and produces, for each route:
|
||||||
|
|
||||||
- the **path**, templated — `/users/:id` → `/users/{id}`, catch-all `:path*` → `{path}`;
|
- the **path**, templated — `/users/:id` → `/users/{id}`, constrained `:id(\d+)` → `{id}`, catch-all `:path*` → `{path}`;
|
||||||
- the **method**;
|
- the **explicitly declared method**, including `@Head` and `@Options`;
|
||||||
- **parameters** — path params from the pattern, plus query/header params from the handler's `@query` / `@headers` / `@header` decorators;
|
- **parameters** — path params from the pattern, plus query/header params from the handler's `@query` / `@headers` / `@header` decorators;
|
||||||
- a **request body** entry for routes that read `@body()`;
|
- a **request body** entry for routes that read `@body()`;
|
||||||
- the systematic **responses** — `200`, a `422` when any argument is schema-validated, and `500`.
|
- the systematic **responses** — `200`, a `422` when any argument is schema-validated, and `500`.
|
||||||
|
|
||||||
WebSocket routes are omitted (they aren't request/response).
|
WebSocket routes are omitted (they aren't request/response).
|
||||||
|
|
||||||
|
A constrained path parameter remains a string parameter and carries its route expression as `schema.pattern`. Only declared operations appear: implicit HEAD and automatic OPTIONS fallbacks are runtime conveniences and are not invented in the OpenAPI document.
|
||||||
|
|
||||||
## Serve it — `devOpenapi`
|
## Serve it — `devOpenapi`
|
||||||
|
|
||||||
Opt in to a `GET /__openapi__` endpoint that returns the document as JSON — point Swagger UI, Redoc, or a codegen client at it:
|
Opt in to a `GET /__openapi__` endpoint that returns the document as JSON — point Swagger UI, Redoc, or a codegen client at it:
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
title: Routing
|
title: Routing
|
||||||
description: "Route patterns, the catch-all, specificity precedence, and 405 handling."
|
description: "Route constraints, specificity, HEAD and OPTIONS semantics, and path validation."
|
||||||
---
|
---
|
||||||
|
|
||||||
Routes are declared with method decorators on a `@Route`-prefixed controller. Patterns are matched **by segment**.
|
Routes are declared with method decorators on a `@Route`-prefixed controller. Patterns are matched **by segment**.
|
||||||
@@ -9,7 +9,7 @@ Routes are declared with method decorators on a `@Route`-prefixed controller. Pa
|
|||||||
|
|
||||||
| Decorator | Method / transport |
|
| Decorator | Method / transport |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `@Get` `@Post` `@Put` `@Patch` `@Delete` | buffered HTTP response |
|
| `@Get` `@Head` `@Post` `@Put` `@Patch` `@Delete` `@Options` | buffered HTTP response |
|
||||||
| `@Sse` | server-sent events (`text/event-stream`) |
|
| `@Sse` | server-sent events (`text/event-stream`) |
|
||||||
| `@Ws` | WebSocket duplex |
|
| `@Ws` | WebSocket duplex |
|
||||||
| `@Stream` | negotiated — SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` |
|
| `@Stream` | negotiated — SSE / ndjson / WS, picked from the client's `Accept` / `Upgrade` |
|
||||||
@@ -28,37 +28,47 @@ The path a route matches is `joinPath(module.mountpoint, route.path)` — a cont
|
|||||||
|
|
||||||
- **Static** — `users` matches exactly.
|
- **Static** — `users` matches exactly.
|
||||||
- **`:param`** — matches exactly one segment; the decoded value lands in `params.name` (`@param('id')`).
|
- **`:param`** — matches exactly one segment; the decoded value lands in `params.name` (`@param('id')`).
|
||||||
|
- **`:param(constraint)`** — matches one complete decoded segment when it satisfies a safe regex subset, for example `:id(\d+)`.
|
||||||
- **`:name*` catch-all** — a trailing segment that captures the **rest of the path, slashes included**, into `params.name`.
|
- **`:name*` catch-all** — a trailing segment that captures the **rest of the path, slashes included**, into `params.name`.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
|
@Get('/users/:id(\\d+)') // /users/42 matches; /users/alice does not
|
||||||
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
|
@Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png"
|
||||||
```
|
```
|
||||||
|
|
||||||
A catch-all also matches zero remaining segments (`/files` → `params.path = ""`).
|
A catch-all also matches zero remaining segments (`/files` → `params.path = ""`).
|
||||||
|
|
||||||
|
Constraints are anchored to the whole segment automatically. They allow character classes, alphanumeric/literal atoms, the escaped character classes `\d`, `\D`, `\s`, `\S`, `\w`, `\W`, and simple quantifiers (`+`, `*`, `?`, `{n}`, `{n,m}`). Groups, alternation, lookarounds, backreferences, anchors, and other arbitrary regex features are rejected at boot. Expressions are limited to 128 characters, counted quantifiers are capped, and unsafe adjacent unbounded quantifiers are rejected. This deliberately small subset avoids accepting route regexes with obvious ReDoS shapes.
|
||||||
|
|
||||||
|
Patterns must start with `/`, parameter names must be unique and use identifier syntax, and a catch-all must be the final segment. Repeated slashes in a declared pattern fail at boot.
|
||||||
|
|
||||||
## Precedence
|
## Precedence
|
||||||
|
|
||||||
When more than one route matches the same path, the **most specific wins** — `static ▸ :param ▸ catch-all` — compared segment by segment, **independent of registration order**. Genuine ties (two equally-specific patterns) fall back to registration order.
|
When more than one route matches the same path, the **most specific wins** — `static ▸ constrained :param ▸ plain :param ▸ catch-all` — compared segment by segment, independent of registration order.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
@Get('/a/b') // wins for /a/b
|
@Get('/a/b') // wins for /a/b
|
||||||
|
@Get('/a/:id(\\d+)') // wins for /a/42 over the plain parameter
|
||||||
@Get('/a/:id') // wins for /a/x
|
@Get('/a/:id') // wins for /a/x
|
||||||
@Get('/a/:rest*') // wins for /a/x/y
|
@Get('/a/:rest*') // wins for /a/x/y
|
||||||
```
|
```
|
||||||
|
|
||||||
## 404 vs 405
|
Two routes under the same method cannot have the same effective shape: `/users/:id` and `/users/:name` are ambiguous and make boot fail with both declarations named. The same rule applies after mesh routes join. Different methods may reuse a shape.
|
||||||
|
|
||||||
|
## HEAD and OPTIONS
|
||||||
|
|
||||||
|
An explicit `@Head` or `@Options` route always wins. Without an explicit HEAD route, HEAD falls back to a matching **buffered** GET handler, preserves its status and headers, and suppresses the body. Streaming GET routes do not become implicit HEAD routes.
|
||||||
|
|
||||||
|
Without an explicit OPTIONS route, OPTIONS on an existing path returns `204` with a canonical `Allow` header. GET implies HEAD, and any existing path implies OPTIONS, so a GET/POST path reports `GET, HEAD, POST, OPTIONS`. A CORS preflight (OPTIONS with `Access-Control-Request-Method`) is handled before explicit or automatic OPTIONS when CORS is configured.
|
||||||
|
|
||||||
|
## Path policy and 404 vs 405
|
||||||
|
|
||||||
|
`/path` and `/path/` are equivalent. Repeated slashes such as `/path//item` are rejected rather than collapsed, and malformed percent encoding is rejected; both return `400 Bad Request` with the configured security/CORS headers. Query strings do not participate in route matching.
|
||||||
|
|
||||||
A path that no route matches returns `404`. A path that **does** exist but under a different method returns **`405 Method Not Allowed`** with an `Allow` header listing the methods that do match — not a `404`.
|
A path that no route matches returns `404`. A path that **does** exist but under a different method returns **`405 Method Not Allowed`** with an `Allow` header listing the methods that do match — not a `404`.
|
||||||
|
|
||||||
:::note
|
## Matcher scale
|
||||||
A bare `OPTIONS` request (without an `Access-Control-Request-Method` header — i.e. not a CORS preflight) to an existing path therefore returns `405` with `Allow`. CORS preflights are handled separately; see [Transport security](/docs/guides/security/).
|
|
||||||
:::
|
|
||||||
|
|
||||||
## Not yet
|
Route matching remains a **linear scan** — fine for typical route tables. A radix-tree matcher for very large route tables remains on the roadmap.
|
||||||
|
|
||||||
The matcher is intentionally small for beta. **Not built** (on the roadmap):
|
|
||||||
|
|
||||||
- Regex / typed param constraints such as `:id(\d+)`.
|
|
||||||
- Route matching is a **linear scan** — fine for typical route tables, but a radix-tree matcher for very large ones isn't implemented.
|
|
||||||
|
|
||||||
See [Streaming & real-time](/docs/guides/streaming/) for `@Sse` / `@Ws` / `@Stream`, and [Argument decorators](/docs/guides/arguments/) for everything a handler can read from a request.
|
See [Streaming & real-time](/docs/guides/streaming/) for `@Sse` / `@Ws` / `@Stream`, and [Argument decorators](/docs/guides/arguments/) for everything a handler can read from a request.
|
||||||
@@ -44,7 +44,9 @@ const app = createApp({
|
|||||||
```
|
```
|
||||||
|
|
||||||
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
|
`origins` accepts `string | string[] | '*' | (origin) => boolean`. A preflight `OPTIONS`
|
||||||
request (with `Access-Control-Request-Method`) is auto-answered with 204.
|
request (with `Access-Control-Request-Method`) is auto-answered with 204 before explicit or
|
||||||
|
automatic OPTIONS routing. A bare OPTIONS request is instead handled by an explicit `@Options`
|
||||||
|
route or the router's automatic `204` + `Allow` response.
|
||||||
|
|
||||||
- With `credentials: true`, the server **never** sends `Access-Control-Allow-Origin: *` — it
|
- With `credentials: true`, the server **never** sends `Access-Control-Allow-Origin: *` — it
|
||||||
echoes the concrete allowed origin (or blocks the request).
|
echoes the concrete allowed origin (or blocks the request).
|
||||||
|
|||||||
@@ -109,7 +109,7 @@ A route streams **because** it's declared `@Sse`, `@Stream`, or `@Ws` — never
|
|||||||
|
|
||||||
| Declare | Handler must return | Otherwise |
|
| Declare | Handler must return | Otherwise |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `@Get` / `@Post` / `@Put` / `@Patch` / `@Delete` (buffered) | a value | returning an `AsyncIterable` fails with a 500 `TransportMismatchError` |
|
| `@Get` / `@Head` / `@Post` / `@Put` / `@Patch` / `@Delete` / `@Options` (buffered) | a value | returning an `AsyncIterable` fails with a 500 `TransportMismatchError` |
|
||||||
| `@Sse` / `@Ws` (streaming) | an `AsyncIterable` | returning a plain value fails with a 500 `TransportMismatchError` |
|
| `@Sse` / `@Ws` (streaming) | an `AsyncIterable` | returning a plain value fails with a 500 `TransportMismatchError` |
|
||||||
| `@Stream` (negotiate) | either | the client picks via `Accept` / `Upgrade` — no mismatch |
|
| `@Stream` (negotiate) | either | the client picks via `Accept` / `Upgrade` — no mismatch |
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ const app = createApp(options);
|
|||||||
| `static` | `boolean \| string` | — | serve a directory as a `GET`/`HEAD` fallback (after declared routes, before `404`); `true` → `./public`, a string → that dir; path-traversal-safe; needs a filesystem — Node/Deno/Bun only ([HTML & views](/docs/guides/html/)) |
|
| `static` | `boolean \| string` | — | serve a directory as a `GET`/`HEAD` fallback (after declared routes, before `404`); `true` → `./public`, a string → that dir; path-traversal-safe; needs a filesystem — Node/Deno/Bun only ([HTML & views](/docs/guides/html/)) |
|
||||||
| `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/docs/guides/mesh/)) |
|
| `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/docs/guides/mesh/)) |
|
||||||
| `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) |
|
| `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) |
|
||||||
|
| `warnGraphDepth` | `number \| false` | `20` | warn when one route resolves to more than this many steps; `false` disables the design warning |
|
||||||
|
|
||||||
### `RequestLimits`
|
### `RequestLimits`
|
||||||
|
|
||||||
@@ -63,14 +64,17 @@ const app = createApp(options);
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `listen(port)` | `Promise<http.Server>` | boots providers, then serves |
|
| `listen(port)` | `Promise<http.Server>` | boots providers, then serves |
|
||||||
| `close()` | `Promise<void>` | drains in-flight, closes streams + mesh links |
|
| `close()` | `Promise<void>` | drains in-flight, closes streams + mesh links |
|
||||||
|
| `ready()` | `Promise<void>` | resolves the graph and mesh links without booting providers |
|
||||||
|
| `fetch(request)` | `Promise<Response>` | Web-Standards HTTP/SSE handler for Node, Deno, Bun, and edge |
|
||||||
|
| `upgrade(request, socket)` | `Promise<void>` | neutral WebSocket upgrade used by non-Node adapters |
|
||||||
| `inspect(route)` | `InspectLine[]` | the provider/step/handler chain for a route |
|
| `inspect(route)` | `InspectLine[]` | the provider/step/handler chain for a route |
|
||||||
| `explain(route)` | `Explain` | the chain annotated with each node's needs/provides |
|
| `explain(route)` | `Explain` | the chain annotated with each node's needs/provides |
|
||||||
| `graph()` | `GraphView` | the full node + route graph |
|
| `graph()` | `GraphView` | the full node + route graph |
|
||||||
| `toMermaid()` / `toDOT()` | `string` | render the graph |
|
| `toMermaid()` / `toDOT()` | `string` | render the graph |
|
||||||
| `openapi(info?)` | `OpenApiDoc` | structural OpenAPI 3.1 document ([details](/docs/guides/openapi/)) |
|
| `openapi(info?)` | `OpenApiDoc` | structural OpenAPI 3.1 document ([details](/docs/guides/openapi/)) |
|
||||||
| `degraded()` | `string[]` | optional providers running degraded (empty until `listen()`) |
|
| `degraded()` | `string[]` | optional providers running degraded (empty until providers boot through `fetch`, `upgrade`, or `listen`) |
|
||||||
| `bus` | `Bus` | lifecycle + request event bus |
|
| `bus` | `Bus` | lifecycle + request event bus |
|
||||||
|
|
||||||
:::note
|
:::note
|
||||||
On mesh apps, `graph` / `explain` / `inspect` / `degraded` are only available **after** `listen()` — the graph is finalized once remote scopes connect.
|
On mesh apps, `graph` / `explain` / `inspect` / `degraded` are only available after `ready()` or the first serving call — the graph is finalized once remote scopes connect.
|
||||||
:::
|
:::
|
||||||
@@ -64,7 +64,7 @@ Method decorators on a controller. All accept `(path, opts?)` where `opts = { ex
|
|||||||
|
|
||||||
| Decorator | Method | Transport |
|
| Decorator | Method | Transport |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `@Get` `@Post` `@Put` `@Patch` `@Delete` | as named | buffered response |
|
| `@Get` `@Head` `@Post` `@Put` `@Patch` `@Delete` `@Options` | as named | buffered response |
|
||||||
| `@Sse` | GET | `text/event-stream` |
|
| `@Sse` | GET | `text/event-stream` |
|
||||||
| `@Ws` | GET | WebSocket duplex |
|
| `@Ws` | GET | WebSocket duplex |
|
||||||
| `@Stream` | GET | negotiated (SSE / ndjson / WS) |
|
| `@Stream` | GET | negotiated (SSE / ndjson / WS) |
|
||||||
@@ -77,6 +77,8 @@ Method decorators on a controller. All accept `(path, opts?)` where `opts = { ex
|
|||||||
|
|
||||||
See [Routing](/docs/guides/routing/) for pattern matching and [Streaming](/docs/guides/streaming/) for the transports.
|
See [Routing](/docs/guides/routing/) for pattern matching and [Streaming](/docs/guides/streaming/) for the transports.
|
||||||
|
|
||||||
|
`@Head` and `@Options` declare explicit handlers. When they are absent, the router can provide an implicit buffered-GET HEAD response or an automatic `204` OPTIONS response; those fallbacks are runtime behavior, not decorator metadata.
|
||||||
|
|
||||||
## Arguments
|
## Arguments
|
||||||
|
|
||||||
A handler's signature declares exactly what it wants, in any order.
|
A handler's signature declares exactly what it wants, in any order.
|
||||||
|
|||||||
Reference in new issue
Block a user