Skip to content

Commit 4b4634c

Browse files
committed
refactor(router): request stages shared by the handler and dispatch
Lift the stages around rendering out of the createRSCHandler closure into rsc/request-stages.ts, which imports no @vitejs/plugin-rsc: classify, guardRequest, partialRedirectResponse, runRequestPasses (the rewrite passes and the global middleware chain), serveResponseRoute and timeoutResponse, finalizeRequestResponse (redirect interception, onResponse drain, rewrite header, open-redirect guard, stream idle), createErrorReporter and reportBackgroundErrors. createRSCHandler runs them around its Flight executor; HandlerContext extends the stage context. dispatch drops its hand-kept copy of the same orchestration and runs the passes, the response route, the partial redirect and the finalization, keeping its previewMatch matching, its throw on an RSC route, its telemetry lifecycle and its documented boundaries. It loads the stages lazily, so the testing barrel's eager graph is unchanged; a module-graph test pins both graphs plugin-rsc-free.
1 parent d9cbaa0 commit 4b4634c

17 files changed

Lines changed: 1215 additions & 1201 deletions

‎packages/rangojs-router/docs/internal/execution-model.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1316,7 +1316,7 @@ guards run on that re-render, as on a direct visit; they never guarded the
13161316
action itself, since route middleware never wraps action execution. Only
13171317
the action and PE branches render from the outcome, so after the action the
13181318
target must be a page route: a response route, a redirect or no match on
1319-
pass 2 is an error (`coreRequestHandler`), not a fresh POST that a response
1319+
pass 2 is an error (`guardRequest` in `rsc/request-stages.ts`), not a fresh POST that a response
13201320
route's handler would serve as a second mutation. Before the action no
13211321
outcome exists, so pass 2 is classified as any request: a response route
13221322
target serves a plain POST with its body, as a direct post to it would. A JS

‎packages/rangojs-router/docs/internal/feature-file-map.md‎

Lines changed: 5 additions & 3 deletions
Large diffs are not rendered by default.

‎packages/rangojs-router/docs/internal/feature-map.md‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -679,7 +679,8 @@ Route-local schema definitions (`search` option), typed route param types (`Rout
679679
- `redirect()` with optional state and location state integration. Same-origin by
680680
default: every browser-followed redirect (no-JS PE, full-page GET, middleware
681681
short-circuit, response-route 3xx) is validated by the server open-redirect
682-
guard at the single `handler.ts` chokepoint and cross-origin targets are
682+
guard at the single finalization chokepoint (`rsc/request-stages.ts`
683+
`finalizeRequestResponse`, run by `handler.ts` and `dispatch`) and cross-origin targets are
683684
neutralized to the basename root; soft SPA/Flight redirects (`X-RSC-Redirect` /
684685
Flight `metadata.redirect`) are resolved with the same rules at construction
685686
(`resolveSoftRedirectUrl`). `redirect(url, { external: true })` opts a single
@@ -695,8 +696,9 @@ Route-local schema definitions (`search` option), typed route param types (`Rout
695696
another route at the same URL: a path (basename-prefixed, kept under the
696697
basename) or a global route name with params and search. The `Rewrite`
697698
unwinds to one catch around the global middleware chain
698-
(`rsc/rewrite-passes.ts` `runRewritePasses`, shared by `rsc/handler.ts` and
699-
`dispatch`), which moves the same request context to the target
699+
(`rsc/rewrite-passes.ts` `runRewritePasses`, which `rsc/request-stages.ts`
700+
`runRequestPasses` runs for `rsc/handler.ts` and `dispatch`), which moves
701+
the same request context to the target
700702
(`applyRewrite`, `rebaseRequestContext`) and runs the request again: global
701703
middleware on the target path, the target's route middleware and render.
702704
`ctx.rewrittenFrom` (the visitor URL from the trail in
@@ -725,7 +727,8 @@ Route-local schema definitions (`search` option), typed route param types (`Rout
725727
site error: a rewrite after `next()`, a disallowed mutation's rewrite in
726728
global middleware (before the action), a mutation whose body middleware
727729
read before the action, an action whose rewrite reaches a response route
728-
or a redirect (`coreRequestHandler`: after it ran, or a JS action before);
730+
or a redirect (`guardRequest` in `rsc/request-stages.ts`: after it ran, or
731+
a JS action before);
729732
a loader fetch
730733
answers with the `loaderError` `load()` rejects with; a handler's, loader's or server action's throw is its own error
731734
(middleware only, by design: no loader rewrites).
@@ -1073,7 +1076,7 @@ The visitor's theme reads (the handler and middleware `ctx.theme`, `getRequestCo
10731076
- Default 504 response with `X-Rango-Timeout-Phase` header
10741077
- `onError` receives timeout errors with `metadata: { timeout: true, phase, durationMs, render? }`; `render` is the foreground Flight/HTML/response cursor when a render-start timeout interrupts the stage driver
10751078
- `onTimeout`, `request.timeout`, and `onError` each receive their OWN shallow copy of the `render` snapshot (`RenderTimeoutContext`: mode, phase, running/paused state, completed/total, partial phase duration) — value-equal, independent by reference, so a consumer mutating one surface's copy cannot corrupt the others
1076-
- `dispatch()` mirrors response-route `renderStartMs`/`onTimeout`/timeout telemetry through the public testing entry; its timeout context deliberately has no `render` snapshot because dispatch does not run Flight/HTML
1079+
- `dispatch()` runs the handler's response-route stage (`serveResponseRoute` and `timeoutResponse` in `rsc/request-stages.ts`), so `renderStartMs`/`onTimeout`/timeout telemetry match production through the public testing entry; its timeout context has no `render` snapshot because dispatch does not run Flight/HTML
10771080
- Timeout phases: `"action"` (server action execution), `"render-start"` (RSC render / response routes), `"stream-idle"` (post-handoff body idle-flow watchdog; onTimeout does not apply — the trip errors the stream and reports via onError with `metadata: { timeout: true, phase: "stream-idle", durationMs }` + the request.timeout event)
10781081

10791082
### Telemetry and Observability

‎packages/rangojs-router/docs/internal/security-checklist.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,9 @@ present but no `Host` header can establish the expected origin, the guard now
8383
a browser always sends `Host` alongside `Origin`, so a missing `Host` here is
8484
anomalous.
8585

86-
Implementation: `src/rsc/origin-guard.ts`, integrated in `src/rsc/handler.ts`
87-
in `coreRequestHandler()` after request classification and the
86+
Implementation: `src/rsc/origin-guard.ts`, integrated in `src/rsc/request-stages.ts`
87+
`guardRequest()` (called by `coreRequestHandler()` in `src/rsc/handler.ts`)
88+
after request classification and the
8889
redirect/version-mismatch/app-switch terminal short-circuits, gated to
8990
action/loader/PE-form modes via `ORIGIN_CHECK_PHASE_BY_MODE` (`origin-guard.ts`).
9091

‎packages/rangojs-router/skills/testing/response-routes.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ describe("api routes via dispatch", () => {
9696
- A router using `Prerender()`/`createLoader()`/`Static()` now constructs in a bare test (each assigns a runtime fallback `$$id`). Importing the whole router _file_ may still need the plugin (its page modules pull app deps / `virtual:` modules) — build from a focused include (your API routes) for whole-router dispatch.
9797
- A `throw rewrite(target)` from global or route middleware re-dispatches as the router does: global middleware matched on the target's path, the target's route middleware and handler, the same request context, `x-rango-rewrite` on the response, 508 on a loop. The visitor's URL is matched before middleware runs, so it must be a response route (or a redirect or 404) too; a rewrite target that is a component route throws the same error as a direct request.
9898
- A `_rsc_partial` request to a response route runs global middleware first (an auth gate can still 401/redirect), then returns `X-RSC-Reload` — route-level middleware is skipped, exactly like production.
99-
- `dispatch` does NOT execute server actions (`?_rsc_action`), but it DOES run the global middleware chain on an action request — middleware can still 401/redirect it, and any 3xx redirect on a partial OR action request becomes a `204` + `X-RSC-Redirect` (fetch-safe interception), the raw `Location` dropped. Location state carried on such a redirect is dropped too (production embeds it in a Flight payload); cover that at e2e.
99+
- `dispatch` does NOT execute server actions (`?_rsc_action`), but it DOES run the global middleware chain on an action request — middleware can still 401/redirect it, and a global middleware's 3xx redirect on a partial OR action request becomes a `204` + `X-RSC-Redirect` (fetch-safe interception), the raw `Location` dropped, as does a trailing-slash redirect on a partial request. Location state carried on such a redirect is dropped too (production embeds it in a Flight payload); cover that at e2e.
100100
- `createRouter({ onError })` is NOT invoked for a thrown non-Response HANDLER error here (the typed error Response still matches production), and `cache.decision` / `loader.*` telemetry never fires (no RSC render runs). Cover both at e2e.
101101

102102
## See also

‎packages/rangojs-router/src/cache/cache-scope.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,9 @@ import {
3333
// pulls @vitejs/plugin-rsc (a virtual: module the plain node/vitest runner cannot
3434
// resolve). It is imported LAZILY at the two call sites below (deserializeSegments
3535
// in lookupRoute, serializeSegments in cacheRoute) so that requiring cache-scope —
36-
// e.g. dispatch's lazy `import("../cache/cache-scope.js")` for the response-route
37-
// cache path — does not crash a consumer test that never mocks plugin-rsc. Behavior
36+
// e.g. through the request stages dispatch loads for a response route
37+
// (rsc/request-stages.ts) — does not crash a consumer test that never mocks
38+
// plugin-rsc. Behavior
3839
// is unchanged: both methods are async and already awaited the codec.
3940
import {
4041
captureHandles,

‎packages/rangojs-router/src/cache/handle-snapshot.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import type { HandleOwners, SegmentHandleData } from "./types.js";
1414
// in plain node/vitest). It is imported LAZILY inside the two async encode/decode
1515
// helpers below so that modules which import handle-snapshot only for the
1616
// plugin-rsc-free captureHandles/restoreHandles (e.g. cache-scope, on dispatch's
17-
// lazy response-route cache path) do not pull plugin-rsc at module load. Behavior
17+
// response-route path) do not pull plugin-rsc at module load. Behavior
1818
// is unchanged: both helpers are async and already awaited the codec.
1919

2020
const HANDLE_ENCODE_TIMEOUT_MS = 5000;

‎packages/rangojs-router/src/router/instrument.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -428,8 +428,8 @@ function observeInSegmentScope<C, R>(
428428
* loop (request.start/end/error, cache.decision, ...).
429429
* - segment-resolution/helpers.ts emits via a caller-provided report.telemetry
430430
* sink rather than the ALS router context.
431-
* - rsc/handler.ts handleTimeoutResponse (request.timeout), the origin guard
432-
* (request.origin-rejected), and handleStore.onError (late-handle
431+
* - rsc/request-stages.ts timeoutResponse (request.timeout) and guardRequest
432+
* (request.origin-rejected), and rsc/handler.ts handleStore.onError (late-handle
433433
* handler.error) emit via router.telemetry directly — they run outside the
434434
* RouterContext ALS (only match()/matchPartial() enter it), so a
435435
* getRouterContext() read there throws and the event would vanish.

‎packages/rangojs-router/src/rsc/handler-context.ts‎

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,17 @@
77
*/
88

99
import type { RangoInternal } from "../router/router-interfaces.js";
10-
import type { ErrorPhase } from "../types.js";
11-
import type { InvokeOnErrorContext } from "../router/error-handling.js";
1210
import type { RSCDependencies, LoadSSRModule } from "./types.js";
1311
import type { SSRStreamMode } from "../router/router-options.js";
12+
import type { RequestStageContext } from "./request-stages.js";
1413

15-
export interface HandlerContext<TEnv = unknown> {
14+
/**
15+
* Extends what the request stages (rsc/request-stages.ts) call back into, so
16+
* the handler hands this one bundle to them as well.
17+
*/
18+
export interface HandlerContext<
19+
TEnv = unknown,
20+
> extends RequestStageContext<TEnv> {
1621
router: RangoInternal<TEnv, any>;
1722
/**
1823
* The router's DOCUMENT version (router-versions.ts): payload metadata, the
@@ -28,17 +33,6 @@ export interface HandlerContext<TEnv = unknown> {
2833
decodeAction: RSCDependencies["decodeAction"];
2934
decodeFormState: RSCDependencies["decodeFormState"];
3035
loadSSRModule: LoadSSRModule;
31-
callOnError: (
32-
error: unknown,
33-
phase: ErrorPhase,
34-
context: InvokeOnErrorContext<TEnv>,
35-
) => void;
36-
getRequiredRouteMap: () => Record<string, string>;
37-
createRedirectFlightResponse: (
38-
redirectUrl: string,
39-
locationState?: Record<string, unknown>,
40-
external?: boolean,
41-
) => Response;
4236

4337
/**
4438
* Resolve the SSR stream mode for a given request.

0 commit comments

Comments
 (0)