@rangojs/router 0.0.0-experimental.79 → 0.0.0-experimental.7d061845
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +120 -25
- package/dist/bin/rango.js +147 -57
- package/dist/testing/vitest.js +82 -0
- package/dist/vite/index.js +2138 -841
- package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
- package/package.json +68 -21
- package/skills/breadcrumbs/SKILL.md +3 -1
- package/skills/bundle-analysis/SKILL.md +159 -0
- package/skills/cache-guide/SKILL.md +220 -30
- package/skills/caching/SKILL.md +116 -8
- package/skills/composability/SKILL.md +27 -2
- package/skills/document-cache/SKILL.md +78 -55
- package/skills/handler-use/SKILL.md +3 -1
- package/skills/hooks/SKILL.md +229 -20
- package/skills/host-router/SKILL.md +45 -20
- package/skills/i18n/SKILL.md +276 -0
- package/skills/intercept/SKILL.md +26 -4
- package/skills/layout/SKILL.md +6 -7
- package/skills/links/SKILL.md +247 -17
- package/skills/loader/SKILL.md +219 -9
- package/skills/middleware/SKILL.md +15 -9
- package/skills/migrate-nextjs/SKILL.md +4 -2
- package/skills/migrate-react-router/SKILL.md +5 -0
- package/skills/mime-routes/SKILL.md +27 -0
- package/skills/observability/SKILL.md +137 -0
- package/skills/parallel/SKILL.md +12 -6
- package/skills/prerender/SKILL.md +14 -33
- package/skills/rango/SKILL.md +242 -24
- package/skills/react-compiler/SKILL.md +168 -0
- package/skills/response-routes/SKILL.md +66 -9
- package/skills/route/SKILL.md +33 -4
- package/skills/router-setup/SKILL.md +3 -3
- package/skills/server-actions/SKILL.md +751 -0
- package/skills/streams-and-websockets/SKILL.md +283 -0
- package/skills/testing/SKILL.md +816 -0
- package/skills/typesafety/SKILL.md +319 -27
- package/skills/use-cache/SKILL.md +34 -5
- package/skills/view-transitions/SKILL.md +294 -0
- package/src/__augment-tests__/augment.ts +81 -0
- package/src/__augment-tests__/augmented.check.ts +117 -0
- package/src/browser/action-coordinator.ts +53 -36
- package/src/browser/app-shell.ts +52 -0
- package/src/browser/event-controller.ts +86 -70
- package/src/browser/history-state.ts +21 -0
- package/src/browser/index.ts +3 -3
- package/src/browser/navigation-bridge.ts +65 -9
- package/src/browser/navigation-client.ts +45 -25
- package/src/browser/navigation-store.ts +32 -9
- package/src/browser/navigation-transaction.ts +10 -28
- package/src/browser/partial-update.ts +52 -26
- package/src/browser/prefetch/cache.ts +124 -26
- package/src/browser/prefetch/fetch.ts +114 -38
- package/src/browser/prefetch/queue.ts +36 -5
- package/src/browser/rango-state.ts +53 -13
- package/src/browser/react/Link.tsx +18 -13
- package/src/browser/react/NavigationProvider.tsx +72 -31
- package/src/browser/react/filter-segment-order.ts +51 -7
- package/src/browser/react/index.ts +3 -0
- package/src/browser/react/location-state-shared.ts +175 -4
- package/src/browser/react/location-state.ts +39 -13
- package/src/browser/react/use-handle.ts +17 -9
- package/src/browser/react/use-navigation.ts +22 -2
- package/src/browser/react/use-params.ts +20 -8
- package/src/browser/react/use-reverse.ts +106 -0
- package/src/browser/react/use-router.ts +22 -2
- package/src/browser/react/use-segments.ts +11 -8
- package/src/browser/response-adapter.ts +25 -0
- package/src/browser/rsc-router.tsx +64 -22
- package/src/browser/scroll-restoration.ts +22 -14
- package/src/browser/segment-structure-assert.ts +2 -2
- package/src/browser/server-action-bridge.ts +23 -30
- package/src/browser/types.ts +21 -0
- package/src/build/collect-fallback-refs.ts +107 -0
- package/src/build/generate-manifest.ts +60 -35
- package/src/build/generate-route-types.ts +2 -0
- package/src/build/index.ts +2 -0
- package/src/build/route-trie.ts +2 -1
- package/src/build/route-types/codegen.ts +4 -4
- package/src/build/route-types/include-resolution.ts +1 -1
- package/src/build/route-types/per-module-writer.ts +7 -4
- package/src/build/route-types/router-processing.ts +55 -14
- package/src/build/route-types/scan-filter.ts +1 -1
- package/src/build/route-types/source-scan.ts +118 -0
- package/src/build/runtime-discovery.ts +9 -20
- package/src/cache/cache-scope.ts +28 -42
- package/src/cache/cf/cf-cache-store.ts +54 -13
- package/src/client.rsc.tsx +3 -0
- package/src/client.tsx +10 -8
- package/src/context-var.ts +5 -5
- package/src/decode-loader-results.ts +36 -0
- package/src/errors.ts +30 -1
- package/src/handle.ts +26 -13
- package/src/host/index.ts +2 -2
- package/src/host/router.ts +129 -57
- package/src/host/types.ts +31 -2
- package/src/host/utils.ts +1 -1
- package/src/href-client.ts +140 -20
- package/src/index.rsc.ts +9 -4
- package/src/index.ts +16 -6
- package/src/loader-store.ts +500 -0
- package/src/loader.rsc.ts +21 -6
- package/src/loader.ts +3 -10
- package/src/missing-id-error.ts +68 -0
- package/src/outlet-context.ts +1 -1
- package/src/prerender.ts +4 -4
- package/src/response-utils.ts +37 -0
- package/src/reverse.ts +65 -39
- package/src/route-content-wrapper.tsx +6 -28
- package/src/route-definition/dsl-helpers.ts +253 -265
- package/src/route-definition/helper-factories.ts +29 -139
- package/src/route-definition/helpers-types.ts +43 -15
- package/src/route-definition/resolve-handler-use.ts +6 -0
- package/src/route-definition/use-item-types.ts +32 -0
- package/src/route-types.ts +19 -41
- package/src/router/basename.ts +14 -0
- package/src/router/content-negotiation.ts +15 -2
- package/src/router/error-handling.ts +1 -1
- package/src/router/handler-context.ts +21 -41
- package/src/router/intercept-resolution.ts +4 -18
- package/src/router/lazy-includes.ts +3 -3
- package/src/router/loader-resolution.ts +19 -2
- package/src/router/match-api.ts +4 -3
- package/src/router/match-handlers.ts +63 -20
- package/src/router/match-middleware/cache-lookup.ts +44 -91
- package/src/router/match-middleware/cache-store.ts +3 -2
- package/src/router/match-result.ts +53 -32
- package/src/router/metrics.ts +1 -1
- package/src/router/middleware-types.ts +15 -26
- package/src/router/middleware.ts +99 -84
- package/src/router/pattern-matching.ts +101 -17
- package/src/router/prerender-match.ts +1 -1
- package/src/router/preview-match.ts +3 -1
- package/src/router/request-classification.ts +4 -28
- package/src/router/revalidation.ts +58 -2
- package/src/router/router-interfaces.ts +45 -28
- package/src/router/router-options.ts +40 -1
- package/src/router/router-registry.ts +2 -5
- package/src/router/segment-resolution/fresh.ts +27 -6
- package/src/router/segment-resolution/revalidation.ts +147 -106
- package/src/router/segment-resolution/view-transition-default.ts +36 -0
- package/src/router/substitute-pattern-params.ts +56 -0
- package/src/router/telemetry.ts +99 -0
- package/src/router/trie-matching.ts +18 -13
- package/src/router/types.ts +8 -0
- package/src/router/url-params.ts +49 -0
- package/src/router.ts +38 -23
- package/src/rsc/handler-context.ts +2 -2
- package/src/rsc/handler.ts +28 -69
- package/src/rsc/helpers.ts +91 -43
- package/src/rsc/index.ts +1 -1
- package/src/rsc/origin-guard.ts +28 -10
- package/src/rsc/progressive-enhancement.ts +4 -0
- package/src/rsc/response-route-handler.ts +46 -53
- package/src/rsc/rsc-rendering.ts +35 -51
- package/src/rsc/runtime-warnings.ts +9 -10
- package/src/rsc/server-action.ts +17 -37
- package/src/rsc/ssr-setup.ts +16 -0
- package/src/rsc/types.ts +8 -2
- package/src/search-params.ts +4 -4
- package/src/segment-system.tsx +122 -56
- package/src/serialize.ts +243 -0
- package/src/server/context.ts +118 -51
- package/src/server/cookie-store.ts +28 -4
- package/src/server/request-context.ts +20 -42
- package/src/ssr/index.tsx +5 -1
- package/src/static-handler.ts +1 -1
- package/src/testing/cache-status.ts +166 -0
- package/src/testing/collect-handle.ts +63 -0
- package/src/testing/dispatch.ts +440 -0
- package/src/testing/dom.entry.ts +22 -0
- package/src/testing/e2e/fixture.ts +154 -0
- package/src/testing/e2e/index.ts +149 -0
- package/src/testing/e2e/matchers.ts +51 -0
- package/src/testing/e2e/page-helpers.ts +272 -0
- package/src/testing/e2e/parity.ts +306 -0
- package/src/testing/e2e/server.ts +183 -0
- package/src/testing/flight-matchers.ts +104 -0
- package/src/testing/flight-runtime.d.ts +57 -0
- package/src/testing/flight-tree.ts +332 -0
- package/src/testing/flight.entry.ts +46 -0
- package/src/testing/flight.ts +224 -0
- package/src/testing/generated-routes.ts +223 -0
- package/src/testing/index.ts +106 -0
- package/src/testing/internal/context.ts +304 -0
- package/src/testing/internal/flight-client-globals.ts +30 -0
- package/src/testing/internal/seed-vars.ts +42 -0
- package/src/testing/render-handler.ts +267 -0
- package/src/testing/render-route.tsx +565 -0
- package/src/testing/run-loader.ts +341 -0
- package/src/testing/run-middleware.ts +188 -0
- package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
- package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
- package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
- package/src/testing/vitest-stubs/version.ts +5 -0
- package/src/testing/vitest.ts +270 -0
- package/src/types/global-namespace.ts +39 -26
- package/src/types/handler-context.ts +68 -50
- package/src/types/index.ts +1 -0
- package/src/types/loader-types.ts +5 -6
- package/src/types/request-scope.ts +126 -0
- package/src/types/segments.ts +35 -1
- package/src/urls/include-helper.ts +10 -53
- package/src/urls/index.ts +0 -3
- package/src/urls/path-helper-types.ts +11 -3
- package/src/urls/path-helper.ts +17 -52
- package/src/urls/pattern-types.ts +36 -19
- package/src/urls/response-types.ts +22 -29
- package/src/urls/type-extraction.ts +26 -116
- package/src/urls/urls-function.ts +1 -5
- package/src/use-loader.tsx +413 -42
- package/src/vite/debug.ts +185 -0
- package/src/vite/discovery/bundle-postprocess.ts +6 -6
- package/src/vite/discovery/discover-routers.ts +101 -51
- package/src/vite/discovery/discovery-errors.ts +194 -0
- package/src/vite/discovery/gate-state.ts +171 -0
- package/src/vite/discovery/prerender-collection.ts +67 -26
- package/src/vite/discovery/route-types-writer.ts +40 -84
- package/src/vite/discovery/self-gen-tracking.ts +27 -1
- package/src/vite/discovery/state.ts +33 -0
- package/src/vite/discovery/virtual-module-codegen.ts +13 -23
- package/src/vite/index.ts +2 -0
- package/src/vite/plugin-types.ts +67 -0
- package/src/vite/plugins/cjs-to-esm.ts +8 -7
- package/src/vite/plugins/client-ref-dedup.ts +16 -0
- package/src/vite/plugins/client-ref-hashing.ts +28 -5
- package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
- package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
- package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
- package/src/vite/plugins/expose-action-id.ts +54 -30
- package/src/vite/plugins/expose-id-utils.ts +12 -8
- package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
- package/src/vite/plugins/expose-ids/handler-transform.ts +8 -61
- package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
- package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
- package/src/vite/plugins/expose-internal-ids.ts +496 -486
- package/src/vite/plugins/performance-tracks.ts +29 -25
- package/src/vite/plugins/use-cache-transform.ts +65 -50
- package/src/vite/plugins/version-injector.ts +39 -23
- package/src/vite/plugins/version-plugin.ts +59 -2
- package/src/vite/plugins/virtual-entries.ts +2 -2
- package/src/vite/rango.ts +116 -29
- package/src/vite/router-discovery.ts +750 -100
- package/src/vite/utils/ast-handler-extract.ts +15 -15
- package/src/vite/utils/banner.ts +1 -1
- package/src/vite/utils/bundle-analysis.ts +4 -2
- package/src/vite/utils/client-chunks.ts +190 -0
- package/src/vite/utils/forward-user-plugins.ts +193 -0
- package/src/vite/utils/manifest-utils.ts +21 -5
- package/src/vite/utils/package-resolution.ts +41 -1
- package/src/vite/utils/prerender-utils.ts +5 -4
- package/src/vite/utils/shared-utils.ts +107 -26
- package/src/browser/action-response-classifier.ts +0 -99
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Variable seeding shared by the node/DOM testing tier (internal/context.ts)
|
|
3
|
+
* AND the react-server Flight tier (flight.ts). Depends only on the
|
|
4
|
+
* dependency-free `context-var` module, so it is safe to import under the
|
|
5
|
+
* `react-server` condition (unlike internal/context.ts, which pulls
|
|
6
|
+
* client/browser modules).
|
|
7
|
+
*/
|
|
8
|
+
import { contextSet, type ContextVar } from "../../context-var.js";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Initializer for seeded context variables (as a prior middleware would have
|
|
12
|
+
* set, or a server component would read during render). Either a plain object
|
|
13
|
+
* keyed by var name (the common, best-inferring form: `{ user: u }`) or a list
|
|
14
|
+
* of `[key, value]` tuples where the key may be a `createVar()` handle or a
|
|
15
|
+
* string (`[[userVar, u], ["flag", true]]`).
|
|
16
|
+
*/
|
|
17
|
+
export type VarsInit =
|
|
18
|
+
| Record<string, unknown>
|
|
19
|
+
| ReadonlyArray<readonly [ContextVar<unknown> | string, unknown]>;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Preload variables as if set by upstream middleware (or visible to a rendered
|
|
23
|
+
* server tree). Accepts entries keyed by either a ContextVar (from createVar) or
|
|
24
|
+
* a string, matching ctx.set().
|
|
25
|
+
*/
|
|
26
|
+
export function seedVariables(
|
|
27
|
+
variables: Record<string, unknown>,
|
|
28
|
+
vars?: VarsInit,
|
|
29
|
+
): Record<string, unknown> {
|
|
30
|
+
if (!vars) return variables;
|
|
31
|
+
// Array/iterable form -> use the tuples as-is; plain object -> its entries.
|
|
32
|
+
const entries: Iterable<readonly [ContextVar<unknown> | string, unknown]> =
|
|
33
|
+
Symbol.iterator in (vars as object)
|
|
34
|
+
? (vars as ReadonlyArray<
|
|
35
|
+
readonly [ContextVar<unknown> | string, unknown]
|
|
36
|
+
>)
|
|
37
|
+
: Object.entries(vars as Record<string, unknown>);
|
|
38
|
+
for (const [key, value] of entries) {
|
|
39
|
+
contextSet(variables, key as ContextVar<unknown>, value);
|
|
40
|
+
}
|
|
41
|
+
return variables;
|
|
42
|
+
}
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/// <reference path="./flight-runtime.d.ts" />
|
|
2
|
+
/**
|
|
3
|
+
* renderHandler — run a REAL route handler and assert what it renders.
|
|
4
|
+
*
|
|
5
|
+
* A Rango route handler is a pure function `(ctx) => RSC` (what you pass to
|
|
6
|
+
* `path("/p/:slug", ProductPage)`), NOT a component. To test one faithfully you
|
|
7
|
+
* must give it the HandlerContext the router builds at runtime, so `ctx.params`,
|
|
8
|
+
* `ctx.use(Loader)`, `ctx.use(Meta)` / `ctx.use(Breadcrumbs)` (handles),
|
|
9
|
+
* `ctx.reverse`, `ctx.get`/`ctx.header`/`cookies()` all work. renderHandler does
|
|
10
|
+
* exactly that, then serializes the handler's returned RSC and deserializes it
|
|
11
|
+
* to an inspectable tree (same serialize/deserialize core as renderServerTree).
|
|
12
|
+
*
|
|
13
|
+
* Loaders are SEEDED (no real loader execution) the same way `runLoader` seeds
|
|
14
|
+
* them — pass `loaders: [[ProductLoader, data]]`. Handle pushes
|
|
15
|
+
* (`ctx.use(Meta)({...})`) are captured on `result.handles`. The handler's
|
|
16
|
+
* cookie/header/flash effects and a thrown/returned redirect are surfaced too
|
|
17
|
+
* (like `runInRequestContext`). If the handler returns/throws a `Response`
|
|
18
|
+
* (a response route / `throw redirect()`), there is no RSC `tree`.
|
|
19
|
+
*
|
|
20
|
+
* Must run under the `react-server` export condition (the rsc Vitest project).
|
|
21
|
+
* Wire `rangoUseClientTransform()` so `"use client"` islands in the handler's RSC
|
|
22
|
+
* auto-register (or pass `clientComponents`).
|
|
23
|
+
*/
|
|
24
|
+
import type { ReactNode } from "react";
|
|
25
|
+
import {
|
|
26
|
+
createRequestContext,
|
|
27
|
+
runWithRequestContext,
|
|
28
|
+
setRequestContextParams,
|
|
29
|
+
type RequestContext,
|
|
30
|
+
} from "../server/request-context.js";
|
|
31
|
+
import { createHandlerContext } from "../router/handler-context.js";
|
|
32
|
+
import { resolveLocationStateEntries } from "../browser/react/location-state-shared.js";
|
|
33
|
+
import { isHandle, type Handle } from "../handle.js";
|
|
34
|
+
import type { HandlerContext } from "../types/handler-context.js";
|
|
35
|
+
import type { LoaderDefinition } from "../types.js";
|
|
36
|
+
import { seedVariables, type VarsInit } from "./internal/seed-vars.js";
|
|
37
|
+
import { serializeNodeToFlight } from "./flight.js";
|
|
38
|
+
import {
|
|
39
|
+
deserializeFlight,
|
|
40
|
+
makeClientManifest,
|
|
41
|
+
registerClientComponents,
|
|
42
|
+
} from "./flight-tree.js";
|
|
43
|
+
|
|
44
|
+
const DEFAULT_URL = "http://localhost/";
|
|
45
|
+
|
|
46
|
+
/** A route handler under test: the `(ctx) => RSC | Response` function you pass to `path(...)`. */
|
|
47
|
+
export type TestableHandler<TEnv = any> = (
|
|
48
|
+
ctx: HandlerContext<any, TEnv>,
|
|
49
|
+
) => ReactNode | Promise<ReactNode> | Response | Promise<Response>;
|
|
50
|
+
|
|
51
|
+
/** Options for {@link renderHandler}. */
|
|
52
|
+
export interface RenderHandlerOptions<TEnv = any> {
|
|
53
|
+
/** Route params surfaced as `ctx.params`. */
|
|
54
|
+
params?: Record<string, string>;
|
|
55
|
+
/** Environment bindings surfaced as `ctx.env`. */
|
|
56
|
+
env?: TEnv;
|
|
57
|
+
/** Backing Request (string or Request); defaults to a localhost GET. */
|
|
58
|
+
request?: Request | string;
|
|
59
|
+
/** Request headers (e.g. Cookie) the handler reads via `cookies()`. */
|
|
60
|
+
headers?: HeadersInit;
|
|
61
|
+
/** Variables a prior middleware set, read via `ctx.get(...)`. Object or tuples. */
|
|
62
|
+
vars?: VarsInit;
|
|
63
|
+
/** Matched route name (drives `ctx.routeName` and scoped reverse). */
|
|
64
|
+
routeName?: string;
|
|
65
|
+
/** Route name -> pattern map enabling `ctx.reverse()`. */
|
|
66
|
+
routeMap?: Record<string, string>;
|
|
67
|
+
/**
|
|
68
|
+
* Seed the data `ctx.use(SomeLoader)` returns — NO real loader runs (same model
|
|
69
|
+
* as `runLoader`'s `loaders`). Matched by loader reference, so a real
|
|
70
|
+
* `createLoader()` handle resolves regardless of its build-injected `$$id`.
|
|
71
|
+
*/
|
|
72
|
+
loaders?: ReadonlyArray<readonly [LoaderDefinition<any, any>, unknown]>;
|
|
73
|
+
/**
|
|
74
|
+
* `"use client"` components in the handler's RSC, so they serialize as real
|
|
75
|
+
* boundaries when `rangoUseClientTransform()` is not wired. Keyed by name; see
|
|
76
|
+
* renderServerTree's `clientComponents`.
|
|
77
|
+
*/
|
|
78
|
+
clientComponents?: Record<string, unknown>;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Result of {@link renderHandler}. */
|
|
82
|
+
export interface RenderHandlerResult {
|
|
83
|
+
/**
|
|
84
|
+
* The deserialized RSC the handler returned, as an inspectable React element
|
|
85
|
+
* tree — `undefined` when the handler returned or threw a `Response`. Use
|
|
86
|
+
* `findClientBoundaries` (from testing/flight) to locate client islands.
|
|
87
|
+
*/
|
|
88
|
+
tree: unknown;
|
|
89
|
+
/** The raw Flight wire string; `undefined` when the handler produced a `Response`. */
|
|
90
|
+
flight: string | undefined;
|
|
91
|
+
/** The value the handler THREW (a `redirect()`/`notFound()` Response), captured not re-thrown. */
|
|
92
|
+
thrown: unknown;
|
|
93
|
+
/** The merged Response (status + headers + Set-Cookie); a thrown/returned redirect merged with accumulated effects. */
|
|
94
|
+
response: Response;
|
|
95
|
+
/** Effective cookie view after the handler ran, as `{ name: value }`. */
|
|
96
|
+
cookies: Record<string, string>;
|
|
97
|
+
/** Response headers as `{ name: value }` (excludes set-cookie; includes a redirect Location). */
|
|
98
|
+
headers: Record<string, string>;
|
|
99
|
+
/** Location state the handler set (`ctx.setLocationState`/`redirect({ state })`), as `{ key: value }`. */
|
|
100
|
+
locationState: Record<string, unknown>;
|
|
101
|
+
/** What the handler pushed via `ctx.use(Handle)(...)` (e.g. Meta, Breadcrumbs), keyed by handle. */
|
|
102
|
+
handles: Map<Handle<any, any>, unknown[]>;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* A renderHandler MISCONFIGURATION (e.g. an unseeded loader) — distinct from a
|
|
107
|
+
* value the handler intentionally threw (a redirect). Setup errors REJECT;
|
|
108
|
+
* handler throws are captured on `result.thrown`.
|
|
109
|
+
*/
|
|
110
|
+
class RenderHandlerSetupError extends Error {}
|
|
111
|
+
|
|
112
|
+
function headersToObject(headers: Headers): Record<string, string> {
|
|
113
|
+
const out: Record<string, string> = {};
|
|
114
|
+
headers.forEach((value, name) => {
|
|
115
|
+
if (name.toLowerCase() !== "set-cookie") out[name] = value;
|
|
116
|
+
});
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function toRequest(
|
|
121
|
+
request: Request | string | undefined,
|
|
122
|
+
headers?: HeadersInit,
|
|
123
|
+
): Request {
|
|
124
|
+
if (request instanceof Request) return request;
|
|
125
|
+
if (typeof request === "string") {
|
|
126
|
+
return new Request(new URL(request, DEFAULT_URL), { headers });
|
|
127
|
+
}
|
|
128
|
+
return new Request(DEFAULT_URL, { headers });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function buildResponse(reqCtx: RequestContext<any>, thrown: unknown): Response {
|
|
132
|
+
const stub = reqCtx.res;
|
|
133
|
+
if (thrown instanceof Response) {
|
|
134
|
+
const merged = new Headers(thrown.headers);
|
|
135
|
+
for (const cookie of stub.headers.getSetCookie()) {
|
|
136
|
+
merged.append("set-cookie", cookie);
|
|
137
|
+
}
|
|
138
|
+
stub.headers.forEach((value, name) => {
|
|
139
|
+
if (name.toLowerCase() === "set-cookie") return;
|
|
140
|
+
if (!merged.has(name)) merged.set(name, value);
|
|
141
|
+
});
|
|
142
|
+
return new Response(null, { status: thrown.status, headers: merged });
|
|
143
|
+
}
|
|
144
|
+
return new Response(null, { status: stub.status, headers: stub.headers });
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Run a route handler with a seeded HandlerContext and return its rendered RSC
|
|
149
|
+
* (deserialized tree) plus the effects it produced. See the module header.
|
|
150
|
+
*
|
|
151
|
+
* @example
|
|
152
|
+
* ```ts
|
|
153
|
+
* // ProductPage is the real handler: (ctx) => <main>{ctx.params.slug}...</main>
|
|
154
|
+
* const { tree, handles } = await renderHandler(ProductPage, {
|
|
155
|
+
* params: { slug: "wine" },
|
|
156
|
+
* loaders: [[ProductLoader, { name: "Wine", price: 9 }]],
|
|
157
|
+
* vars: [[Tenant, tenant]],
|
|
158
|
+
* routeMap: { product: "/p/:slug" },
|
|
159
|
+
* });
|
|
160
|
+
* ```
|
|
161
|
+
*/
|
|
162
|
+
export async function renderHandler<TEnv = any>(
|
|
163
|
+
handler: TestableHandler<TEnv>,
|
|
164
|
+
opts: RenderHandlerOptions<TEnv> = {},
|
|
165
|
+
): Promise<RenderHandlerResult> {
|
|
166
|
+
if (opts.clientComponents) registerClientComponents(opts.clientComponents);
|
|
167
|
+
const request = toRequest(opts.request, opts.headers);
|
|
168
|
+
const url = new URL(request.url);
|
|
169
|
+
const reqCtx = createRequestContext<TEnv>({
|
|
170
|
+
env: (opts.env ?? {}) as TEnv,
|
|
171
|
+
request,
|
|
172
|
+
url,
|
|
173
|
+
variables: seedVariables({}, opts.vars),
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
const loaderSeeds = new Map<unknown, unknown>(opts.loaders ?? []);
|
|
177
|
+
const handlePushes = new Map<Handle<any, any>, unknown[]>();
|
|
178
|
+
|
|
179
|
+
let out: ReactNode | Response | undefined;
|
|
180
|
+
let flight: string | undefined;
|
|
181
|
+
let thrown: unknown;
|
|
182
|
+
let didThrow = false;
|
|
183
|
+
|
|
184
|
+
await runWithRequestContext(reqCtx as RequestContext<TEnv>, async () => {
|
|
185
|
+
setRequestContextParams(opts.params ?? {}, opts.routeName);
|
|
186
|
+
const hctx = createHandlerContext<TEnv>(
|
|
187
|
+
opts.params ?? {},
|
|
188
|
+
reqCtx.request,
|
|
189
|
+
reqCtx.searchParams,
|
|
190
|
+
reqCtx.pathname,
|
|
191
|
+
reqCtx.url,
|
|
192
|
+
reqCtx.env,
|
|
193
|
+
opts.routeMap ?? {},
|
|
194
|
+
opts.routeName,
|
|
195
|
+
);
|
|
196
|
+
// Seed ctx.use: a handle returns a push fn that RECORDS (so ctx.use(Meta)
|
|
197
|
+
// doesn't crash and pushes are assertable); a loader returns its seeded data
|
|
198
|
+
// (no real loader run).
|
|
199
|
+
(hctx as { use: unknown }).use = (item: unknown) => {
|
|
200
|
+
if (isHandle(item)) {
|
|
201
|
+
const handle = item as Handle<any, any>;
|
|
202
|
+
return (value: unknown) => {
|
|
203
|
+
const pushed = handlePushes.get(handle) ?? [];
|
|
204
|
+
pushed.push(value);
|
|
205
|
+
handlePushes.set(handle, pushed);
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
if (loaderSeeds.has(item)) return loaderSeeds.get(item);
|
|
209
|
+
throw new RenderHandlerSetupError(
|
|
210
|
+
`renderHandler: ctx.use(loader) was not seeded. Pass ` +
|
|
211
|
+
`{ loaders: [[YourLoader, data]] } for each loader the handler reads.`,
|
|
212
|
+
);
|
|
213
|
+
};
|
|
214
|
+
(hctx as { _currentSegmentId?: string })._currentSegmentId = "test.segment";
|
|
215
|
+
|
|
216
|
+
try {
|
|
217
|
+
out = await handler(hctx as HandlerContext<any, TEnv>);
|
|
218
|
+
// Serialize the RSC in THIS context, so nested async server components see
|
|
219
|
+
// getRequestContext()/cookies()/vars while they render.
|
|
220
|
+
if (out !== undefined && !(out instanceof Response)) {
|
|
221
|
+
flight = await serializeNodeToFlight(
|
|
222
|
+
out as ReactNode,
|
|
223
|
+
makeClientManifest(),
|
|
224
|
+
url.pathname,
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
} catch (error) {
|
|
228
|
+
// A harness misconfiguration (unseeded loader) is the consumer's mistake —
|
|
229
|
+
// surface it as a rejection, not as a captured handler throw.
|
|
230
|
+
if (error instanceof RenderHandlerSetupError) throw error;
|
|
231
|
+
// Otherwise captured, NOT re-thrown: a handler's success path is often
|
|
232
|
+
// `throw redirect(...)`; its cookies/flash must stay observable.
|
|
233
|
+
didThrow = true;
|
|
234
|
+
thrown = error;
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
const cookies = { ...reqCtx.cookies() };
|
|
239
|
+
const responseSource = didThrow
|
|
240
|
+
? thrown
|
|
241
|
+
: out instanceof Response
|
|
242
|
+
? out
|
|
243
|
+
: undefined;
|
|
244
|
+
const response = buildResponse(reqCtx as RequestContext<any>, responseSource);
|
|
245
|
+
const headers = headersToObject(response.headers);
|
|
246
|
+
const locationState = resolveLocationStateEntries(
|
|
247
|
+
(
|
|
248
|
+
reqCtx as {
|
|
249
|
+
_locationState?: Parameters<typeof resolveLocationStateEntries>[0];
|
|
250
|
+
}
|
|
251
|
+
)._locationState ?? [],
|
|
252
|
+
);
|
|
253
|
+
// Deserialize outside the context (the client deserializer needs no ctx).
|
|
254
|
+
const tree =
|
|
255
|
+
flight !== undefined ? await deserializeFlight(flight) : undefined;
|
|
256
|
+
|
|
257
|
+
return {
|
|
258
|
+
tree,
|
|
259
|
+
flight,
|
|
260
|
+
thrown,
|
|
261
|
+
response,
|
|
262
|
+
cookies,
|
|
263
|
+
headers,
|
|
264
|
+
locationState,
|
|
265
|
+
handles: handlePushes,
|
|
266
|
+
};
|
|
267
|
+
}
|