Skip to content

Commit c8e2d5d

Browse files
authored
fix(testing): dispatch json nested-Promise guard + scoped routeMap for flight/handler primitives (#582) (#583)
Two `@rangojs/router/testing` parity gaps from #582 (split from #572). 1. dispatch() json route lacked production's nested-Promise guard. Production (response-route-handler) serializes a json() result with a replacer that throws RESPONSE_NOT_SERIALIZABLE on a nested unresolved Promise (the forgotten-await footgun: `() => ({ data: fetchSomething() })`); dispatch did a bare JSON.stringify and shipped `{"data":{}}` green while production 500s. Extracted the replacer into a shared lightweight module (rsc/json-route-result.ts, depends only on errors.js) used by BOTH, so a dispatch json test fails exactly where production fails. dispatch's catch already maps the thrown RouterError to the same problem+json 500. The helper lives in its OWN module, not response-route-handler.ts: importing the latter into dispatch dragged its heavy runtime graph, which transitively reaches a Vite virtual module and breaks a plain (non-Vite) vitest import (caught: run-in-request-context.test.ts went red). 2. The testing primitives leaked ctx.reverse to the GLOBAL route map (order-dependent on whatever router registered last). Added a scoped `routeMap` option to renderToFlightString/renderServerTree (mirroring renderHandler), threaded through setRequestContextParams(params, routeName, routeMap?) -- backward compatible (production callers omit it and keep getGlobalRouteMap()). renderHandler now also passes routeMap to setRequestContextParams, so a nested server component reading getRequestContext().reverse scopes to the same map as the handler's ctx.reverse -- all three primitives now scope reverse uniformly. Tests (red-before-green): a dispatch json route returning a nested Promise -> a problem+json 500 (not a green {}); ctx.reverse() scoped to a provided routeMap under renderToFlightString, renderServerTree, AND a nested server component in renderHandler (vs "Unknown route" against the empty global map). Docs: flight skill routeMap option, feature-file-map new module. Out of #582 this PR: item 8 (renderRoute synthetic-id stamping) is already addressed by #581 via a stable WeakMap + a documented input-mutation contract; item 9 (dispatch executionContext=undefined) is correct for an in-process harness with no platform execution context. Cross-seam + self-review items remain in #582. Full gate green: typecheck, test:unit:all (incl. RSC suites), lint, format.
1 parent 0e9f3a1 commit c8e2d5d

12 files changed

Lines changed: 167 additions & 32 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎packages/rangojs-router/skills/testing/flight.md‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,15 @@
1010

1111
### Options — `RenderToFlightStringOptions`
1212

13-
| Field | Type | Meaning |
14-
| ----------- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
15-
| `request` | `Request \| string` | The request the render runs under: a `Request`, or a URL string (absolute or path). Defaults to `http://localhost/`. A component reading `getRequestContext()` sees this request's url/cookies. When a `Request` is passed, its headers are used and `headers` is ignored. |
16-
| `headers` | `HeadersInit` | Request headers (e.g. Cookie) visible to the server tree, used only when `request` is a string. |
17-
| `env` | `unknown` | Env / bindings exposed as `ctx.env`. Defaults to `{}`. |
18-
| `params` | `Record<string, string>` | Route params exposed via `ctx.params` and loader contexts. |
19-
| `routeName` | `string` | Matched route name (drives `ctx.routeName` and scoped reverse). |
20-
| `vars` | `VarsInit` | Variables a prior middleware would have set, visible via `ctx.get(...)`. Object form (`{ user }`) or `[key, value]` tuples (`[[userVar, u]]`). |
13+
| Field | Type | Meaning |
14+
| ----------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
15+
| `request` | `Request \| string` | The request the render runs under: a `Request`, or a URL string (absolute or path). Defaults to `http://localhost/`. A component reading `getRequestContext()` sees this request's url/cookies. When a `Request` is passed, its headers are used and `headers` is ignored. |
16+
| `headers` | `HeadersInit` | Request headers (e.g. Cookie) visible to the server tree, used only when `request` is a string. |
17+
| `env` | `unknown` | Env / bindings exposed as `ctx.env`. Defaults to `{}`. |
18+
| `params` | `Record<string, string>` | Route params exposed via `ctx.params` and loader contexts. |
19+
| `routeName` | `string` | Matched route name (drives `ctx.routeName` and scoped reverse). |
20+
| `routeMap` | `Record<string, string>` | Route name -> pattern map scoping `ctx.reverse()` (like `renderHandler`). Without it, a component that reverses resolves against the GLOBAL route map and is order-dependent on whatever router registered last. Pass the router-under-test's map for deterministic reverse. |
21+
| `vars` | `VarsInit` | Variables a prior middleware would have set, visible via `ctx.get(...)`. Object form (`{ user }`) or `[key, value]` tuples (`[[userVar, u]]`). |
2122

2223
### Context — `RequestContext` (what your component receives)
2324

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Shared serialization for `json()` response-route results.
3+
*
4+
* Kept in its own lightweight module (depends only on `errors.js`) so the
5+
* `dispatch()` testing primitive can import it WITHOUT dragging in
6+
* `response-route-handler.ts`'s heavy runtime graph, which transitively reaches
7+
* a Vite virtual module and breaks a plain (non-Vite) vitest import.
8+
*/
9+
10+
import { RouterError } from "../errors.js";
11+
12+
/**
13+
* Serialize a `json()` response-route result, rejecting a nested unresolved
14+
* Promise (the forgotten-await footgun: `() => ({ data: fetchSomething() })`).
15+
* `JSON.stringify` would silently emit `{}` for a Promise, shipping empty data;
16+
* the RSC pipeline awaits nested promises but this path does not. Throwing
17+
* `RESPONSE_NOT_SERIALIZABLE` makes the failure loud.
18+
*
19+
* Shared by the production response-route handler and the `dispatch()` testing
20+
* primitive so a `dispatch` json test of a forgotten await fails exactly where
21+
* production 500s, instead of going green.
22+
*/
23+
export function stringifyJsonRouteResult(result: unknown): string {
24+
return JSON.stringify(result, (_key, value) => {
25+
if (
26+
value != null &&
27+
typeof (value as { then?: unknown }).then === "function"
28+
) {
29+
throw new RouterError(
30+
"RESPONSE_NOT_SERIALIZABLE",
31+
"A json() response route returned a Promise (likely a forgotten " +
32+
"await). Await async values before returning so they serialize, " +
33+
"instead of emitting an empty {}.",
34+
);
35+
}
36+
return value;
37+
});
38+
}

‎packages/rangojs-router/src/rsc/response-route-handler.ts‎

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
mergeStubHeadersAndFinalize,
3131
} from "./helpers.js";
3232
import { isWebSocketUpgradeResponse } from "../response-utils.js";
33+
import { stringifyJsonRouteResult } from "./json-route-result.js";
3334
import {
3435
EXTERNAL_REDIRECT_MARKER,
3536
isExternalRedirect,
@@ -151,23 +152,9 @@ export async function handleResponseRoute<TEnv>(
151152
if (preview.responseType === "json") {
152153
// Runtime guard: the json() return type rejects nested Promises at
153154
// compile time, but an `as`-cast or untyped (JS) handler can still slip
154-
// one through. JSON.stringify would silently emit {} for it (the
155-
// forgotten-await footgun — the RSC pipeline awaits nested promises, this
156-
// path does not). Throw a clear error instead of shipping empty data.
157-
const body = JSON.stringify(result, (_key, value) => {
158-
if (
159-
value != null &&
160-
typeof (value as { then?: unknown }).then === "function"
161-
) {
162-
throw new RouterError(
163-
"RESPONSE_NOT_SERIALIZABLE",
164-
"A json() response route returned a Promise (likely a forgotten " +
165-
"await). Await async values before returning so they serialize, " +
166-
"instead of emitting an empty {}.",
167-
);
168-
}
169-
return value;
170-
});
155+
// one through. stringifyJsonRouteResult throws a clear error instead of
156+
// shipping empty data (shared with dispatch() so the two cannot drift).
157+
const body = stringifyJsonRouteResult(result);
171158
return createResponseWithMergedHeaders(body, {
172159
status: 200,
173160
headers: { "content-type": "application/json;charset=utf-8" },

‎packages/rangojs-router/src/server/request-context.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,7 @@ export function _getRequestContext<TEnv = DefaultEnv>():
477477
export function setRequestContextParams(
478478
params: Record<string, string>,
479479
routeName?: string,
480+
routeMap?: Record<string, string>,
480481
): void {
481482
const ctx = requestContextStorage.getStore();
482483
if (ctx) {
@@ -489,9 +490,13 @@ export function setRequestContextParams(
489490
: undefined
490491
) as DefaultRouteName | undefined;
491492
}
492-
// Update reverse with scoped resolution now that route is known
493+
// Update reverse with scoped resolution now that route is known. Production
494+
// omits routeMap and uses the global map (routes are registered globally);
495+
// the testing primitives (renderToFlightString/renderServerTree) pass a
496+
// scoped routeMap so `ctx.reverse` is not order-dependent on whatever router
497+
// registered last.
493498
ctx.reverse = createReverseFunction(
494-
getGlobalRouteMap(),
499+
routeMap ?? getGlobalRouteMap(),
495500
routeName,
496501
params,
497502
routeName ? isRouteRootScoped(routeName) : undefined,

‎packages/rangojs-router/src/testing/__tests__/dispatch.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -745,6 +745,36 @@ describe("dispatch", () => {
745745
expect(body.type).toBeUndefined();
746746
});
747747

748+
// Parity regression (#572 / #582): a json route that returns a nested
749+
// unresolved Promise (forgotten await) must reject EXACTLY like production.
750+
// Pre-fix, dispatch did a bare JSON.stringify and shipped `{"data":{}}` green
751+
// while production throws RESPONSE_NOT_SERIALIZABLE and 500s. The shared
752+
// stringifyJsonRouteResult guard makes dispatch fail where production fails.
753+
it("rejects a json route returning a nested Promise (forgotten await) as a problem+json 500, like production", async () => {
754+
const router = createRouter<{}>({}).routes(
755+
urls(({ path }) => [
756+
path.json(
757+
"/api/forgot-await",
758+
// The cast mimics an `as`-cast or untyped (JS) handler slipping a
759+
// Promise past the compile-time nested-Promise rejection.
760+
(() => ({ data: Promise.resolve("late") })) as any,
761+
{ name: "api.forgotAwait" },
762+
),
763+
]),
764+
) as any;
765+
766+
const res = await dispatch(router, { request: "/api/forgot-await" });
767+
expect(res.status).toBe(500);
768+
expect(res.headers.get("content-type")).toBe(
769+
"application/problem+json;charset=utf-8",
770+
);
771+
const body = await res.json();
772+
expect(body.code).toBe("RESPONSE_NOT_SERIALIZABLE");
773+
expect(body.status).toBe(500);
774+
// The silent forgotten-await body must NEVER ship.
775+
expect(body).not.toHaveProperty("data");
776+
});
777+
748778
it("sanitizes a thrown generic Error on a json route to a problem+json 500 in production", async () => {
749779
const prev = process.env.NODE_ENV;
750780
process.env.NODE_ENV = "production";

‎packages/rangojs-router/src/testing/__tests__/flight-tree.rsc-test.tsx‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,20 @@ describe("renderServerTree", () => {
5959
expect(json).toContain("root");
6060
});
6161

62+
// #572 / #582 item: renderServerTree inherits the scoped `routeMap` option
63+
// (shared serializeToFlightString path), so ctx.reverse() resolves against the
64+
// provided map, not the order-dependent global route map.
65+
test("scopes ctx.reverse() to the provided routeMap option", async () => {
66+
async function ReverseEcho() {
67+
const ctx = getRequestContext();
68+
return <a href={ctx.reverse("product", { id: "7" })}>go</a>;
69+
}
70+
const { tree } = await renderServerTree(<ReverseEcho />, {
71+
routeMap: { product: "/scoped/products/:id" },
72+
});
73+
expect(JSON.stringify(tree)).toContain("/scoped/products/7");
74+
});
75+
6276
test("client island auto-discovered as an I-row (not inlined)", async () => {
6377
// No clientComponents: the transform registers Counter from its import.
6478
function Page() {

‎packages/rangojs-router/src/testing/__tests__/flight.rsc-test.tsx‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,13 @@ async function ParamEcho(): Promise<React.ReactElement> {
3535
return <span>id={ctx.params.id}</span>;
3636
}
3737

38+
// A Server Component that reverses a route name, proving ctx.reverse resolves
39+
// against the SCOPED routeMap option rather than the global route map.
40+
async function ReverseEcho(): Promise<React.ReactElement> {
41+
const ctx = getRequestContext();
42+
return <span>url={ctx.reverse("product", { id: "5" })}</span>;
43+
}
44+
3845
// A Server Component that throws during render.
3946
async function Boom(): Promise<React.ReactElement> {
4047
await Promise.resolve();
@@ -83,6 +90,18 @@ describe("renderToFlightString (Flight RSC)", () => {
8390
expect(flight).toMatchFlight("42");
8491
});
8592

93+
// #572 / #582 item: ctx.reverse() must resolve against the SCOPED routeMap
94+
// option, not the global route map (which is order-dependent on whatever
95+
// router registered last). With no router registered in this bare RSC test,
96+
// the global map has no "product", so only the scoped option can resolve it.
97+
it("scopes ctx.reverse() to the provided routeMap option", async () => {
98+
const flight = await renderToFlightString(<ReverseEcho />, {
99+
routeMap: { product: "/scoped/products/:id" },
100+
});
101+
expect(flight).toMatchFlight("url=");
102+
expect(flight).toMatchFlight("/scoped/products/5");
103+
});
104+
86105
it("normalizeFlight scrubs the dev reference row and file paths", () => {
87106
const dev =
88107
":N1780553241432.4255\n" +

‎packages/rangojs-router/src/testing/__tests__/render-handler.rsc-test.tsx‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,28 @@ describe("renderHandler", () => {
4949
expect(json).toContain("9");
5050
});
5151

52+
// #582 parity: renderHandler scopes the request-context reverse to the
53+
// routeMap option (not only the handler context), so a NESTED server component
54+
// reading getRequestContext().reverse() resolves against the same map as the
55+
// handler's ctx.reverse -- consistent with renderToFlightString/renderServerTree.
56+
test("a nested server component's getRequestContext().reverse scopes to the routeMap option", async () => {
57+
async function NestedReverse() {
58+
const ctx = getRequestContext();
59+
return <a href={ctx.reverse("product", { id: "9" })}>go</a>;
60+
}
61+
function Page() {
62+
return (
63+
<main>
64+
<NestedReverse />
65+
</main>
66+
);
67+
}
68+
const { tree } = await renderHandler(Page, {
69+
routeMap: { product: "/scoped/products/:id" },
70+
});
71+
expect(JSON.stringify(tree)).toContain("/scoped/products/9");
72+
});
73+
5274
test("captures handle pushes (ctx.use(Meta)) without crashing", async () => {
5375
function Page(ctx: HandlerContext) {
5476
const meta = ctx.use(Meta);

‎packages/rangojs-router/src/testing/dispatch.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ import {
9696
mergeStubHeadersAndFinalize,
9797
} from "../rsc/helpers.js";
9898
import { guardOutgoingRedirect } from "../rsc/redirect-guard.js";
99+
import { stringifyJsonRouteResult } from "../rsc/json-route-result.js";
99100
import {
100101
EXTERNAL_REDIRECT_MARKER,
101102
isExternalRedirect,
@@ -164,7 +165,8 @@ function toRequest(request: Request | string): Request {
164165
/**
165166
* Serialize a NON-Response response-route handler result, mirroring the
166167
* router's handleResponseRoute() contract:
167-
* - "json" serializes the value verbatim (bare) with application/json,
168+
* - "json" serializes the value (bare) with application/json, rejecting a nested
169+
* unresolved Promise via the shared stringifyJsonRouteResult guard,
168170
* - text/html/xml/md stringify with the mapped MIME type.
169171
*
170172
* A handler-returned Response is NOT routed here — callHandler re-wraps it via
@@ -177,7 +179,12 @@ function serializeResponseRouteResult(
177179
responseType: string,
178180
): Response {
179181
if (responseType === "json") {
180-
return new Response(JSON.stringify(result), {
182+
// Serialize through the SAME guard production uses: a nested unresolved
183+
// Promise (forgotten await) throws RESPONSE_NOT_SERIALIZABLE here, caught by
184+
// callHandler's catch and mapped to the identical typed 500 production
185+
// returns -- so a dispatch json test fails exactly where production would,
186+
// instead of silently emitting {} and passing.
187+
return new Response(stringifyJsonRouteResult(result), {
181188
status: 200,
182189
headers: { "content-type": "application/json;charset=utf-8" },
183190
});

0 commit comments

Comments
 (0)