Skip to content

Commit 6fe9451

Browse files
committed
fix(testing): #582 close three @rangojs/router/testing fidelity gaps (executionContext, scoped reverse, no consumer-object pollution)
Three lower-severity testing-primitive gaps from the #572 audit, all of the same shape (the harness diverged from production or mutated consumer state): 1. dispatch() resolved router.cache(env, executionContext) with a hardcoded undefined. A consumer whose cache config branches on executionContext (store selection, waitUntil availability) resolved a different store/enabled flag in a dispatch test than in production. Add an executionContext option to DispatchOptions and thread it to BOTH the cache resolver and createRequestContext (so ctx.waitUntil also defers to the platform), matching rsc/handler.ts. 2. renderToFlightString/renderServerTree only had routeName; ctx.reverse stayed bound to the GLOBAL route map (last-registered router), so a server component's reverse() was order-dependent across routers/test files. Add a scoped routeMap option (mirrors renderHandler/runLoader): when supplied, reverse rebinds to it with the same routeName/params scoping. 3. renderRoute's ensureSyntheticId stamped $$id / __rsc_ls_key onto the consumer's own loader/locationState objects as ENUMERABLE properties. The stamp is load-bearing (useLoader/location-state read the id off the SAME object by identity, so cloning would orphan the data), so the fix is to define the field NON-ENUMERABLE via Object.defineProperty -- matching how production stamps __rsc_ls_key (location-state-shared.ts) -- so it no longer leaks into the consumer's Object.keys/spread/JSON/toEqual. Userland coverage (through the public primitives): - dispatch.test.ts: the cache resolver receives the passed executionContext (and undefined when omitted), and ctx.waitUntil() routes to the platform executionContext.waitUntil. - flight.rsc-test.tsx: a server component's reverse() resolves against the supplied routeMap, and a second render with a different map for the same name resolves to the new pattern (order-independence). - render-route.test.tsx: an ad-hoc loader's data still resolves (the stamp is load-bearing) while Object.keys/spread/JSON of the consumer's object stay clean ($$id present but non-enumerable).
1 parent f7a9441 commit 6fe9451

6 files changed

Lines changed: 192 additions & 2 deletions

File tree

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

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -937,6 +937,85 @@ describe("dispatch", () => {
937937
});
938938
});
939939

940+
// Production (rsc/handler.ts) threads the platform execution context into the
941+
// router's cache(env, executionContext) resolver AND onto the request context
942+
// (so ctx.waitUntil defers to the platform). dispatch used to hardcode
943+
// undefined, so a cache config branching on executionContext resolved a
944+
// different store/enabled flag in a test than in production. The
945+
// executionContext option closes that gap.
946+
describe("executionContext threading (production parity)", () => {
947+
it("forwards the executionContext to the router's cache(env, executionContext) resolver", async () => {
948+
const seen: unknown[] = [];
949+
const execCtx = { waitUntil: () => {} };
950+
const router = createRouter<{}>({
951+
cache: (_env, executionContext) => {
952+
seen.push(executionContext);
953+
// store is required by the type; enabled:false means dispatch never
954+
// reads it — we only assert which executionContext the resolver saw.
955+
return { store: new MemorySegmentCacheStore(), enabled: false };
956+
},
957+
}).routes(
958+
urls(({ path }) => [
959+
path.json("/api/data", () => ({ ok: true }), { name: "api.data" }),
960+
]),
961+
) as any;
962+
963+
const res = await dispatch(router, {
964+
request: "/api/data",
965+
executionContext: execCtx as any,
966+
});
967+
expect(res.status).toBe(200);
968+
// The resolver saw the exact execution context dispatch was given, not
969+
// undefined (the pre-fix behavior).
970+
expect(seen).toContain(execCtx);
971+
});
972+
973+
it("resolves the cache config with undefined when no executionContext is passed (documents the default)", async () => {
974+
const seen: unknown[] = [];
975+
const router = createRouter<{}>({
976+
cache: (_env, executionContext) => {
977+
seen.push(executionContext);
978+
// store is required by the type; enabled:false means dispatch never
979+
// reads it — we only assert which executionContext the resolver saw.
980+
return { store: new MemorySegmentCacheStore(), enabled: false };
981+
},
982+
}).routes(
983+
urls(({ path }) => [
984+
path.json("/api/data", () => ({ ok: true }), { name: "api.data" }),
985+
]),
986+
) as any;
987+
988+
await dispatch(router, { request: "/api/data" });
989+
expect(seen).toEqual([undefined]);
990+
});
991+
992+
it("routes ctx.waitUntil() to the platform executionContext.waitUntil", async () => {
993+
const waitUntil = vi.fn();
994+
const execCtx = { waitUntil };
995+
const router = createRouter<{}>({}).routes(
996+
urls(({ path }) => [
997+
path.json(
998+
"/api/defer",
999+
(ctx: { waitUntil: (fn: () => Promise<void>) => void }) => {
1000+
ctx.waitUntil(async () => {});
1001+
return { ok: true };
1002+
},
1003+
{ name: "api.defer" },
1004+
),
1005+
]),
1006+
) as any;
1007+
1008+
const res = await dispatch(router, {
1009+
request: "/api/defer",
1010+
executionContext: execCtx as any,
1011+
});
1012+
expect(res.status).toBe(200);
1013+
// Without the executionContext wiring, waitUntil would fall back to
1014+
// fire-and-forget and the platform mock would never be called.
1015+
expect(waitUntil).toHaveBeenCalledTimes(1);
1016+
});
1017+
});
1018+
9401019
// Content negotiation: when the router's previewMatch reports negotiated:true
9411020
// (set only when a route has negotiate variants and a response-route variant
9421021
// wins), dispatch appends Vary: Accept, matching handleResponseRoute's

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,14 @@ 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 via the active request context.
39+
// Without a scoped routeMap, ctx.reverse resolves against the global route map
40+
// (last-registered router) and is order-dependent across tests.
41+
async function ReverseEcho(): Promise<React.ReactElement> {
42+
const ctx = getRequestContext();
43+
return <a href={ctx.reverse("product", { slug: "widget" })}>link</a>;
44+
}
45+
3846
// A Server Component that throws during render.
3947
async function Boom(): Promise<React.ReactElement> {
4048
await Promise.resolve();
@@ -83,6 +91,25 @@ describe("renderToFlightString (Flight RSC)", () => {
8391
expect(flight).toMatchFlight("42");
8492
});
8593

94+
it("scopes ctx.reverse to the supplied routeMap (deterministic, not global)", async () => {
95+
// With a scoped routeMap, a server component's reverse() resolves against
96+
// the router under test instead of whatever router registered last.
97+
const flight = await renderToFlightString(<ReverseEcho />, {
98+
routeMap: { product: "/products/:slug" },
99+
});
100+
expect(flight).toMatchFlight("/products/widget");
101+
});
102+
103+
it("reverse routeMap is scoped per render (no cross-render leakage)", async () => {
104+
// A second render with a DIFFERENT map for the same name resolves to the
105+
// new pattern — proving the map is taken from opts each call, not a sticky
106+
// global. This is the order-independence the option exists to guarantee.
107+
const flight = await renderToFlightString(<ReverseEcho />, {
108+
routeMap: { product: "/p/:slug/detail" },
109+
});
110+
expect(flight).toMatchFlight("/p/widget/detail");
111+
});
112+
86113
it("normalizeFlight scrubs the dev reference row and file paths", () => {
87114
const dev =
88115
":N1780553241432.4255\n" +

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,37 @@ describe("renderRoute", () => {
304304
expect(getByTestId("cart").textContent).toBe("3");
305305
expect(getByTestId("page").textContent).toBe("page");
306306
});
307+
308+
it("stamps the synthetic loader id WITHOUT polluting the consumer's object surface", async () => {
309+
// An ad-hoc loader the consumer owns, with no Vite-injected $$id. The
310+
// harness must stamp an id onto THIS object (useLoader reads loader.$$id by
311+
// identity, so cloning would orphan the data) — but the stamp must not leak
312+
// into the consumer's own inspection of their object.
313+
const AdHocLoader = {
314+
__brand: "loader",
315+
} as unknown as LoaderDefinition<{ name: string }>;
316+
317+
function Profile() {
318+
const { data } = useLoader(AdHocLoader);
319+
return <span data-testid="name">{data.name}</span>;
320+
}
321+
322+
const { getByTestId } = await renderRoute(
323+
[{ path: "/profile", Component: Profile }],
324+
{ request: "/profile", loaders: [[AdHocLoader, { name: "Ada" }]] },
325+
);
326+
327+
// Non-vacuity: the stamp is load-bearing — useLoader still resolved the data.
328+
expect(getByTestId("name").textContent).toBe("Ada");
329+
330+
// The id was stamped on the object (so the lookup works)...
331+
expect("$$id" in AdHocLoader).toBe(true);
332+
// ...but NON-enumerably, so it does not surface in the consumer's own
333+
// inspection: Object.keys, spread, and JSON.stringify all stay clean.
334+
expect(Object.keys(AdHocLoader)).toEqual(["__brand"]);
335+
expect({ ...AdHocLoader }).toEqual({ __brand: "loader" });
336+
expect(JSON.stringify(AdHocLoader)).toBe('{"__brand":"loader"}');
337+
});
307338
});
308339

309340
describe("renderRoute mount (include() scope)", () => {

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

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ import {
7575
runWithRequestContext,
7676
setRequestContextParams,
7777
} from "../server/request-context.js";
78+
import type { ExecutionContext } from "../server/request-context.js";
7879
import { executeMiddleware, matchMiddleware } from "../router/middleware.js";
7980
import type {
8081
MiddlewareEntry,
@@ -156,6 +157,17 @@ export interface DispatchOptions<TEnv = any> {
156157
request: Request | string;
157158
/** Environment bindings forwarded to matching and middleware. */
158159
env?: TEnv;
160+
/**
161+
* The platform execution context (Cloudflare `ExecutionContext`, etc.) — the
162+
* same value a consumer passes as `router.fetch(req, { ctx })`. Forwarded to
163+
* the router's `cache(env, executionContext)` resolver AND onto the request
164+
* context, so a `cache` config that branches on `executionContext` resolves
165+
* the same store/enabled flag it would in production, and `ctx.waitUntil()`
166+
* defers to the platform's `waitUntil` instead of running inline. Production
167+
* threads this through (rsc/handler.ts); dispatch used to hardcode `undefined`,
168+
* silently diverging for any execution-context-dependent cache config.
169+
*/
170+
executionContext?: ExecutionContext;
159171
}
160172

161173
const DEFAULT_ORIGIN = "http://localhost/";
@@ -320,6 +332,7 @@ export async function dispatch<TEnv = any>(
320332
const req = toRequest(opts.request);
321333
const url = new URL(req.url);
322334
const env = (opts.env ?? {}) as TEnv;
335+
const executionContext = opts.executionContext;
323336

324337
// Seed the per-router manifest so reverse() resolves during handler execution.
325338
const routerId = router.id ?? router.routerId;
@@ -371,7 +384,7 @@ export async function dispatch<TEnv = any>(
371384
if (cacheOption && !url.searchParams.has("__no_cache")) {
372385
const cacheConfig =
373386
typeof cacheOption === "function"
374-
? cacheOption(env, undefined)
387+
? cacheOption(env, executionContext)
375388
: cacheOption;
376389
if (cacheConfig.enabled !== false) cacheStore = cacheConfig.store;
377390
}
@@ -383,6 +396,7 @@ export async function dispatch<TEnv = any>(
383396
variables,
384397
cacheStore,
385398
cacheProfiles: router.cacheProfiles,
399+
executionContext,
386400
});
387401
// Match production: the RSC handler stores the router's basename on the
388402
// request context (handler.ts), and redirect() prefixes root-relative URLs

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import {
4141
runWithRequestContext,
4242
setRequestContextParams,
4343
} from "../server/request-context.js";
44+
import { createReverseFunction } from "../router/handler-context.js";
4445
import { seedVariables, type VarsInit } from "./internal/seed-vars.js";
4546
import { normalizeFlight } from "./flight-normalize.js";
4647
import type { RscPayload } from "../rsc/types.js";
@@ -70,6 +71,16 @@ export interface RenderToFlightStringOptions {
7071
params?: Record<string, string>;
7172
/** Matched route name (drives `ctx.routeName` and scoped reverse). */
7273
routeName?: string;
74+
/**
75+
* Route name -> pattern map scoping `getRequestContext().reverse(...)` for the
76+
* rendered server tree. Without it, reverse resolves against the GLOBAL route
77+
* map (whatever router registered last via setRouterManifest), so a server
78+
* component that reverses is order-dependent across routers/test files. Pass
79+
* the router-under-test's map (mirrors `renderHandler`/`runLoader`) to make
80+
* reverse deterministic. Resolution is scoped by `routeName`/`params` exactly
81+
* as those primitives scope it.
82+
*/
83+
routeMap?: Record<string, string>;
7384
/**
7485
* Context variables visible to the rendered tree via `ctx.get(...)` — as a
7586
* prior middleware would have set them. Seeds the SAME way the handler-test
@@ -187,6 +198,17 @@ export async function serializeToFlightString(
187198

188199
return runWithRequestContext(ctx, () => {
189200
setRequestContextParams(opts.params ?? {}, opts.routeName);
201+
// setRequestContextParams binds ctx.reverse to the GLOBAL route map. When a
202+
// scoped routeMap is supplied, rebind reverse to it (same 3-arg scoping as
203+
// runLoader/internal context) so a server component's reverse() is
204+
// deterministic instead of order-dependent on the last-registered router.
205+
if (opts.routeMap) {
206+
ctx.reverse = createReverseFunction(
207+
opts.routeMap,
208+
opts.routeName,
209+
opts.params ?? {},
210+
) as typeof ctx.reverse;
211+
}
190212
return serializeNodeToFlight(element, clientManifest, url.pathname);
191213
});
192214
}

‎packages/rangojs-router/src/testing/render-route.tsx‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,18 @@ export type HandleDataSeed = Record<string, Record<string, unknown[]>>;
7171
const syntheticIds = new WeakMap<object, string>();
7272
let syntheticIdCounter = 0;
7373

74+
// Stamp a synthetic id onto a consumer-passed loader/locationState object so the
75+
// render can find its seeded data. The id MUST live on the SAME object the
76+
// consumer also hands to `useLoader(loader)` / a location-state hook: useLoader
77+
// reads `loader.$$id` (use-loader.tsx) and the location-state hook reads
78+
// `definition.__rsc_ls_key` (location-state.ts) BY IDENTITY, so cloning the
79+
// object would orphan the data (the hook would read the un-stamped original).
80+
// We therefore stamp in place, but define the field NON-ENUMERABLE so it does
81+
// not leak into the consumer's own inspection of their object (Object.keys,
82+
// spread, JSON.stringify, toEqual) — matching how production stamps
83+
// `__rsc_ls_key` via Object.defineProperty (location-state-shared.ts). A real
84+
// (Vite-injected) id short-circuits: we never overwrite an existing field. The
85+
// WeakMap keeps the id stable if the same object is reused across renders.
7486
function ensureSyntheticId(
7587
handle: object,
7688
field: "$$id" | "__rsc_ls_key",
@@ -82,7 +94,12 @@ function ensureSyntheticId(
8294
id = `__rango_test_id_${syntheticIdCounter++}`;
8395
syntheticIds.set(handle, id);
8496
}
85-
(handle as Record<string, string>)[field] = id;
97+
Object.defineProperty(handle, field, {
98+
value: id,
99+
enumerable: false,
100+
configurable: true,
101+
writable: true,
102+
});
86103
return id;
87104
}
88105

0 commit comments

Comments
 (0)