@rangojs/router 0.0.0-experimental.13 → 0.0.0-experimental.13221847
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/AGENTS.md +9 -0
- package/README.md +884 -4
- package/dist/bin/rango.js +1531 -212
- package/dist/vite/index.js +3995 -2489
- package/package.json +57 -52
- package/skills/breadcrumbs/SKILL.md +250 -0
- package/skills/cache-guide/SKILL.md +262 -0
- package/skills/caching/SKILL.md +85 -23
- package/skills/composability/SKILL.md +172 -0
- package/skills/debug-manifest/SKILL.md +12 -8
- package/skills/document-cache/SKILL.md +18 -16
- package/skills/fonts/SKILL.md +6 -4
- package/skills/hooks/SKILL.md +328 -70
- package/skills/host-router/SKILL.md +218 -0
- package/skills/intercept/SKILL.md +131 -8
- package/skills/layout/SKILL.md +100 -3
- package/skills/links/SKILL.md +62 -15
- package/skills/loader/SKILL.md +368 -42
- package/skills/middleware/SKILL.md +171 -34
- package/skills/mime-routes/SKILL.md +14 -10
- package/skills/parallel/SKILL.md +137 -1
- package/skills/prerender/SKILL.md +366 -28
- package/skills/rango/SKILL.md +85 -21
- package/skills/response-routes/SKILL.md +136 -83
- package/skills/route/SKILL.md +195 -21
- package/skills/router-setup/SKILL.md +123 -30
- package/skills/theme/SKILL.md +9 -8
- package/skills/typesafety/SKILL.md +240 -102
- package/skills/use-cache/SKILL.md +324 -0
- package/src/__internal.ts +102 -4
- package/src/bin/rango.ts +312 -15
- package/src/browser/action-coordinator.ts +97 -0
- package/src/browser/action-response-classifier.ts +99 -0
- package/src/browser/event-controller.ts +92 -64
- package/src/browser/history-state.ts +80 -0
- package/src/browser/intercept-utils.ts +52 -0
- package/src/browser/link-interceptor.ts +24 -4
- package/src/browser/logging.ts +11 -0
- package/src/browser/merge-segment-loaders.ts +20 -12
- package/src/browser/navigation-bridge.ts +266 -558
- package/src/browser/navigation-client.ts +132 -75
- package/src/browser/navigation-store.ts +33 -50
- package/src/browser/navigation-transaction.ts +297 -0
- package/src/browser/network-error-handler.ts +61 -0
- package/src/browser/partial-update.ts +303 -309
- package/src/browser/prefetch/cache.ts +206 -0
- package/src/browser/prefetch/fetch.ts +144 -0
- package/src/browser/prefetch/observer.ts +65 -0
- package/src/browser/prefetch/policy.ts +48 -0
- package/src/browser/prefetch/queue.ts +128 -0
- package/src/browser/rango-state.ts +112 -0
- package/src/browser/react/Link.tsx +190 -70
- package/src/browser/react/NavigationProvider.tsx +78 -11
- package/src/browser/react/context.ts +6 -0
- package/src/browser/react/filter-segment-order.ts +11 -0
- package/src/browser/react/index.ts +12 -12
- package/src/browser/react/location-state-shared.ts +95 -53
- package/src/browser/react/location-state.ts +60 -15
- package/src/browser/react/mount-context.ts +6 -1
- package/src/browser/react/nonce-context.ts +23 -0
- package/src/browser/react/shallow-equal.ts +27 -0
- package/src/browser/react/use-action.ts +29 -51
- package/src/browser/react/use-client-cache.ts +5 -3
- package/src/browser/react/use-handle.ts +29 -70
- package/src/browser/react/use-link-status.ts +6 -5
- package/src/browser/react/use-navigation.ts +22 -63
- package/src/browser/react/use-params.ts +65 -0
- package/src/browser/react/use-pathname.ts +47 -0
- package/src/browser/react/use-router.ts +63 -0
- package/src/browser/react/use-search-params.ts +56 -0
- package/src/browser/react/use-segments.ts +80 -97
- package/src/browser/response-adapter.ts +73 -0
- package/src/browser/rsc-router.tsx +188 -57
- package/src/browser/scroll-restoration.ts +117 -44
- package/src/browser/segment-reconciler.ts +221 -0
- package/src/browser/segment-structure-assert.ts +16 -0
- package/src/browser/server-action-bridge.ts +488 -606
- package/src/browser/shallow.ts +6 -1
- package/src/browser/types.ts +116 -47
- package/src/browser/validate-redirect-origin.ts +29 -0
- package/src/build/generate-manifest.ts +63 -21
- package/src/build/generate-route-types.ts +36 -1038
- package/src/build/index.ts +2 -5
- package/src/build/route-trie.ts +38 -12
- package/src/build/route-types/ast-helpers.ts +25 -0
- package/src/build/route-types/ast-route-extraction.ts +98 -0
- package/src/build/route-types/codegen.ts +102 -0
- package/src/build/route-types/include-resolution.ts +411 -0
- package/src/build/route-types/param-extraction.ts +48 -0
- package/src/build/route-types/per-module-writer.ts +128 -0
- package/src/build/route-types/router-processing.ts +479 -0
- package/src/build/route-types/scan-filter.ts +78 -0
- package/src/build/runtime-discovery.ts +231 -0
- package/src/cache/background-task.ts +34 -0
- package/src/cache/cache-key-utils.ts +44 -0
- package/src/cache/cache-policy.ts +125 -0
- package/src/cache/cache-runtime.ts +342 -0
- package/src/cache/cache-scope.ts +122 -303
- package/src/cache/cf/cf-cache-store.ts +571 -17
- package/src/cache/cf/index.ts +13 -3
- package/src/cache/document-cache.ts +116 -77
- package/src/cache/handle-capture.ts +81 -0
- package/src/cache/handle-snapshot.ts +41 -0
- package/src/cache/index.ts +1 -15
- package/src/cache/memory-segment-store.ts +191 -13
- package/src/cache/profile-registry.ts +73 -0
- package/src/cache/read-through-swr.ts +134 -0
- package/src/cache/segment-codec.ts +256 -0
- package/src/cache/taint.ts +98 -0
- package/src/cache/types.ts +72 -122
- package/src/client.rsc.tsx +3 -1
- package/src/client.tsx +84 -126
- package/src/component-utils.ts +4 -4
- package/src/components/DefaultDocument.tsx +5 -1
- package/src/context-var.ts +86 -0
- package/src/debug.ts +19 -9
- package/src/errors.ts +77 -7
- package/src/handle.ts +12 -7
- package/src/handles/MetaTags.tsx +73 -20
- package/src/handles/breadcrumbs.ts +66 -0
- package/src/handles/index.ts +1 -0
- package/src/handles/meta.ts +30 -13
- package/src/host/cookie-handler.ts +21 -15
- package/src/host/errors.ts +8 -8
- package/src/host/index.ts +4 -7
- package/src/host/pattern-matcher.ts +27 -27
- package/src/host/router.ts +61 -39
- package/src/host/testing.ts +8 -8
- package/src/host/types.ts +15 -7
- package/src/host/utils.ts +1 -1
- package/src/href-client.ts +65 -45
- package/src/index.rsc.ts +104 -40
- package/src/index.ts +122 -67
- package/src/internal-debug.ts +9 -3
- package/src/loader.rsc.ts +18 -93
- package/src/loader.ts +26 -9
- package/src/network-error-thrower.tsx +3 -1
- package/src/outlet-provider.tsx +45 -0
- package/src/prerender/param-hash.ts +4 -2
- package/src/prerender/store.ts +121 -17
- package/src/prerender.ts +325 -20
- package/src/reverse.ts +144 -124
- package/src/root-error-boundary.tsx +41 -29
- package/src/route-content-wrapper.tsx +7 -4
- package/src/route-definition/dsl-helpers.ts +959 -0
- package/src/route-definition/helper-factories.ts +200 -0
- package/src/route-definition/helpers-types.ts +430 -0
- package/src/route-definition/index.ts +52 -0
- package/src/route-definition/redirect.ts +93 -0
- package/src/route-definition.ts +1 -1450
- package/src/route-map-builder.ts +87 -133
- package/src/route-name.ts +53 -0
- package/src/route-types.ts +41 -6
- package/src/router/content-negotiation.ts +116 -0
- package/src/router/debug-manifest.ts +72 -0
- package/src/router/error-handling.ts +9 -9
- package/src/router/find-match.ts +160 -0
- package/src/router/handler-context.ts +324 -116
- package/src/router/intercept-resolution.ts +11 -4
- package/src/router/lazy-includes.ts +237 -0
- package/src/router/loader-resolution.ts +179 -133
- package/src/router/logging.ts +112 -6
- package/src/router/manifest.ts +58 -19
- package/src/router/match-api.ts +89 -88
- package/src/router/match-context.ts +4 -2
- package/src/router/match-handlers.ts +440 -0
- package/src/router/match-middleware/background-revalidation.ts +86 -89
- package/src/router/match-middleware/cache-lookup.ts +295 -49
- package/src/router/match-middleware/cache-store.ts +56 -13
- package/src/router/match-middleware/intercept-resolution.ts +45 -22
- package/src/router/match-middleware/segment-resolution.ts +20 -9
- package/src/router/match-pipelines.ts +10 -45
- package/src/router/match-result.ts +44 -21
- package/src/router/metrics.ts +240 -15
- package/src/router/middleware-cookies.ts +55 -0
- package/src/router/middleware-types.ts +222 -0
- package/src/router/middleware.ts +327 -369
- package/src/router/pattern-matching.ts +169 -31
- package/src/router/prerender-match.ts +402 -0
- package/src/router/preview-match.ts +170 -0
- package/src/router/revalidation.ts +105 -14
- package/src/router/router-context.ts +40 -21
- package/src/router/router-interfaces.ts +452 -0
- package/src/router/router-options.ts +592 -0
- package/src/router/router-registry.ts +24 -0
- package/src/router/segment-resolution/fresh.ts +677 -0
- package/src/router/segment-resolution/helpers.ts +263 -0
- package/src/router/segment-resolution/loader-cache.ts +199 -0
- package/src/router/segment-resolution/revalidation.ts +1296 -0
- package/src/router/segment-resolution/static-store.ts +67 -0
- package/src/router/segment-resolution.ts +21 -1354
- package/src/router/segment-wrappers.ts +291 -0
- package/src/router/telemetry-otel.ts +299 -0
- package/src/router/telemetry.ts +300 -0
- package/src/router/timeout.ts +148 -0
- package/src/router/trie-matching.ts +96 -29
- package/src/router/types.ts +15 -9
- package/src/router.ts +642 -2366
- package/src/rsc/handler-context.ts +45 -0
- package/src/rsc/handler.ts +639 -1027
- package/src/rsc/helpers.ts +140 -6
- package/src/rsc/index.ts +0 -20
- package/src/rsc/loader-fetch.ts +209 -0
- package/src/rsc/manifest-init.ts +86 -0
- package/src/rsc/nonce.ts +14 -0
- package/src/rsc/origin-guard.ts +141 -0
- package/src/rsc/progressive-enhancement.ts +379 -0
- package/src/rsc/response-error.ts +37 -0
- package/src/rsc/response-route-handler.ts +347 -0
- package/src/rsc/rsc-rendering.ts +237 -0
- package/src/rsc/runtime-warnings.ts +42 -0
- package/src/rsc/server-action.ts +348 -0
- package/src/rsc/ssr-setup.ts +128 -0
- package/src/rsc/types.ts +38 -11
- package/src/search-params.ts +66 -54
- package/src/segment-system.tsx +165 -17
- package/src/server/context.ts +237 -54
- package/src/server/cookie-store.ts +190 -0
- package/src/server/fetchable-loader-store.ts +11 -6
- package/src/server/handle-store.ts +94 -15
- package/src/server/loader-registry.ts +15 -56
- package/src/server/request-context.ts +438 -71
- package/src/server.ts +26 -164
- package/src/ssr/index.tsx +101 -31
- package/src/static-handler.ts +22 -4
- package/src/theme/ThemeProvider.tsx +21 -15
- package/src/theme/ThemeScript.tsx +5 -5
- package/src/theme/constants.ts +5 -2
- package/src/theme/index.ts +4 -14
- package/src/theme/theme-context.ts +4 -30
- package/src/theme/theme-script.ts +21 -18
- package/src/types/boundaries.ts +158 -0
- package/src/types/cache-types.ts +198 -0
- package/src/types/error-types.ts +192 -0
- package/src/types/global-namespace.ts +100 -0
- package/src/types/handler-context.ts +773 -0
- package/src/types/index.ts +88 -0
- package/src/types/loader-types.ts +183 -0
- package/src/types/route-config.ts +170 -0
- package/src/types/route-entry.ts +109 -0
- package/src/types/segments.ts +150 -0
- package/src/types.ts +1 -1795
- package/src/urls/include-helper.ts +197 -0
- package/src/urls/index.ts +53 -0
- package/src/urls/path-helper-types.ts +339 -0
- package/src/urls/path-helper.ts +329 -0
- package/src/urls/pattern-types.ts +95 -0
- package/src/urls/response-types.ts +106 -0
- package/src/urls/type-extraction.ts +372 -0
- package/src/urls/urls-function.ts +98 -0
- package/src/urls.ts +1 -1323
- package/src/use-loader.tsx +85 -77
- package/src/vite/discovery/bundle-postprocess.ts +184 -0
- package/src/vite/discovery/discover-routers.ts +344 -0
- package/src/vite/discovery/prerender-collection.ts +385 -0
- package/src/vite/discovery/route-types-writer.ts +258 -0
- package/src/vite/discovery/self-gen-tracking.ts +47 -0
- package/src/vite/discovery/state.ts +108 -0
- package/src/vite/discovery/virtual-module-codegen.ts +203 -0
- package/src/vite/index.ts +11 -2259
- package/src/vite/plugin-types.ts +48 -0
- package/src/vite/plugins/cjs-to-esm.ts +93 -0
- package/src/vite/plugins/client-ref-dedup.ts +115 -0
- package/src/vite/plugins/client-ref-hashing.ts +105 -0
- package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +72 -47
- package/src/vite/{expose-id-utils.ts → plugins/expose-id-utils.ts} +8 -43
- package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
- package/src/vite/plugins/expose-ids/handler-transform.ts +179 -0
- package/src/vite/plugins/expose-ids/loader-transform.ts +74 -0
- package/src/vite/plugins/expose-ids/router-transform.ts +110 -0
- package/src/vite/plugins/expose-ids/types.ts +45 -0
- package/src/vite/plugins/expose-internal-ids.ts +569 -0
- package/src/vite/plugins/refresh-cmd.ts +65 -0
- package/src/vite/plugins/use-cache-transform.ts +323 -0
- package/src/vite/plugins/version-injector.ts +83 -0
- package/src/vite/plugins/version-plugin.ts +266 -0
- package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +23 -14
- package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
- package/src/vite/rango.ts +445 -0
- package/src/vite/router-discovery.ts +777 -0
- package/src/vite/{ast-handler-extract.ts → utils/ast-handler-extract.ts} +181 -9
- package/src/vite/utils/banner.ts +36 -0
- package/src/vite/utils/bundle-analysis.ts +137 -0
- package/src/vite/utils/manifest-utils.ts +70 -0
- package/src/vite/{package-resolution.ts → utils/package-resolution.ts} +25 -29
- package/src/vite/utils/prerender-utils.ts +189 -0
- package/src/vite/utils/shared-utils.ts +169 -0
- package/CLAUDE.md +0 -43
- package/dist/vite/index.named-routes.gen.ts +0 -103
- package/src/browser/lru-cache.ts +0 -69
- package/src/browser/request-controller.ts +0 -164
- package/src/cache/memory-store.ts +0 -253
- package/src/href-context.ts +0 -33
- package/src/router.gen.ts +0 -6
- package/src/static-handler.gen.ts +0 -5
- package/src/urls.gen.ts +0 -8
- package/src/vite/expose-internal-ids.ts +0 -1167
- /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
package/src/rsc/handler.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="@vitejs/plugin-rsc/types" />
|
|
2
|
-
/// <reference path="../vite/version.d.ts" />
|
|
2
|
+
/// <reference path="../vite/plugins/version.d.ts" />
|
|
3
3
|
/**
|
|
4
4
|
* RSC Request Handler
|
|
5
5
|
*
|
|
@@ -8,72 +8,80 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import { createElement } from "react";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import type { ResponseError } from "../urls.js";
|
|
14
|
-
import { getLoaderLazy } from "../server/loader-registry.js";
|
|
15
|
-
import {
|
|
16
|
-
matchMiddleware,
|
|
17
|
-
executeMiddleware,
|
|
18
|
-
executeLoaderMiddleware,
|
|
19
|
-
} from "../router/middleware.js";
|
|
11
|
+
import { RouteNotFoundError } from "../errors.js";
|
|
12
|
+
import { matchMiddleware, executeMiddleware } from "../router/middleware.js";
|
|
20
13
|
import {
|
|
21
14
|
runWithRequestContext,
|
|
22
15
|
setRequestContextParams,
|
|
23
16
|
requireRequestContext,
|
|
24
17
|
createRequestContext,
|
|
25
|
-
type ExecutionContext,
|
|
26
18
|
} from "../server/request-context.js";
|
|
27
19
|
import * as rscDeps from "@vitejs/plugin-rsc/rsc";
|
|
28
20
|
|
|
29
21
|
import type {
|
|
30
22
|
RscPayload,
|
|
31
|
-
ReactFormState,
|
|
32
23
|
CreateRSCHandlerOptions,
|
|
24
|
+
LoadSSRModule,
|
|
25
|
+
SSRModule,
|
|
33
26
|
} from "./types.js";
|
|
34
|
-
import {
|
|
35
|
-
|
|
27
|
+
import {
|
|
28
|
+
createResponseWithMergedHeaders,
|
|
29
|
+
finalizeResponse,
|
|
30
|
+
interceptRedirectForPartial,
|
|
31
|
+
buildRouteMiddlewareEntries,
|
|
32
|
+
} from "./helpers.js";
|
|
33
|
+
import {
|
|
34
|
+
handleResponseRoute,
|
|
35
|
+
type ResponseRouteMatch,
|
|
36
|
+
} from "./response-route-handler.js";
|
|
37
|
+
import { generateNonce, nonce as nonceToken } from "./nonce.js";
|
|
36
38
|
import { VERSION } from "@rangojs/router:version";
|
|
37
39
|
import type { ErrorPhase } from "../types.js";
|
|
40
|
+
import type { RouterRequestInput } from "../router/router-interfaces.js";
|
|
38
41
|
import { invokeOnError } from "../router/error-handling.js";
|
|
39
42
|
import {
|
|
40
|
-
|
|
43
|
+
createReverseFunction,
|
|
44
|
+
stripInternalParams,
|
|
45
|
+
} from "../router/handler-context.js";
|
|
46
|
+
import { getRouterContext } from "../router/router-context.js";
|
|
47
|
+
import { resolveSink, safeEmit } from "../router/telemetry.js";
|
|
48
|
+
import { contextSet } from "../context-var.js";
|
|
49
|
+
import {
|
|
41
50
|
hasCachedManifest,
|
|
42
|
-
setCachedManifest,
|
|
43
51
|
getRouteTrie,
|
|
44
|
-
setRouteTrie,
|
|
45
52
|
getPrecomputedEntries,
|
|
46
53
|
waitForManifestReady,
|
|
47
54
|
getRouterManifest,
|
|
48
55
|
getRouterTrie,
|
|
49
|
-
setRouterManifest,
|
|
50
|
-
setRouterTrie,
|
|
51
56
|
} from "../route-map-builder.js";
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
57
|
+
import type { HandlerContext } from "./handler-context.js";
|
|
58
|
+
import { buildRouterTrieFromUrlpatterns } from "./manifest-init.js";
|
|
59
|
+
import { handleProgressiveEnhancement } from "./progressive-enhancement.js";
|
|
60
|
+
import {
|
|
61
|
+
executeServerAction,
|
|
62
|
+
revalidateAfterAction,
|
|
63
|
+
type ActionContinuation,
|
|
64
|
+
} from "./server-action.js";
|
|
65
|
+
import { handleLoaderFetch } from "./loader-fetch.js";
|
|
66
|
+
import { checkRequestOrigin, type OriginCheckPhase } from "./origin-guard.js";
|
|
67
|
+
import { handleRscRendering } from "./rsc-rendering.js";
|
|
68
|
+
import {
|
|
69
|
+
withTimeout,
|
|
70
|
+
RouterTimeoutError,
|
|
71
|
+
createDefaultTimeoutResponse,
|
|
72
|
+
type TimeoutPhase,
|
|
73
|
+
} from "../router/timeout.js";
|
|
74
|
+
import {
|
|
75
|
+
createMetricsStore,
|
|
76
|
+
appendMetric,
|
|
77
|
+
buildMetricsTiming,
|
|
78
|
+
} from "../router/metrics.js";
|
|
79
|
+
import {
|
|
80
|
+
startSSRSetup,
|
|
81
|
+
getSSRSetup,
|
|
82
|
+
mayNeedSSR,
|
|
83
|
+
SSR_SETUP_VAR,
|
|
84
|
+
} from "./ssr-setup.js";
|
|
77
85
|
|
|
78
86
|
/**
|
|
79
87
|
* Create an RSC request handler.
|
|
@@ -125,33 +133,179 @@ export function createRSCHandler<
|
|
|
125
133
|
decodeFormState,
|
|
126
134
|
} = deps;
|
|
127
135
|
|
|
128
|
-
// Use provided loadSSRModule or default to vite RSC module loader
|
|
129
|
-
|
|
136
|
+
// Use provided loadSSRModule or default to vite RSC module loader.
|
|
137
|
+
// In production the SSR module is stable across requests, so memoize
|
|
138
|
+
// the dynamic import to avoid repeated module resolution overhead.
|
|
139
|
+
// In dev mode Vite may hot-reload the module, so skip memoization.
|
|
140
|
+
const rawLoadSSRModule: LoadSSRModule =
|
|
130
141
|
options.loadSSRModule ??
|
|
131
142
|
(() => import.meta.viteRsc.loadModule("ssr", "index"));
|
|
143
|
+
let _ssrModulePromise: Promise<SSRModule> | undefined;
|
|
144
|
+
const loadSSRModule: LoadSSRModule =
|
|
145
|
+
process.env.NODE_ENV === "production"
|
|
146
|
+
? () =>
|
|
147
|
+
(_ssrModulePromise ??= rawLoadSSRModule().catch((err) => {
|
|
148
|
+
_ssrModulePromise = undefined;
|
|
149
|
+
throw err;
|
|
150
|
+
}))
|
|
151
|
+
: rawLoadSSRModule;
|
|
132
152
|
|
|
133
153
|
/**
|
|
134
|
-
*
|
|
135
|
-
*
|
|
154
|
+
* Per-request error reporter that deduplicates via the ALS request context.
|
|
155
|
+
*
|
|
156
|
+
* Uses the same _reportedErrors WeakSet as the router layer so errors
|
|
157
|
+
* that propagate across layers are only reported once per request.
|
|
136
158
|
*/
|
|
137
159
|
function callOnError(
|
|
138
160
|
error: unknown,
|
|
139
161
|
phase: ErrorPhase,
|
|
140
162
|
context: Parameters<typeof invokeOnError<TEnv>>[3],
|
|
141
163
|
): void {
|
|
164
|
+
if (error != null && typeof error === "object") {
|
|
165
|
+
const reportedErrors = requireRequestContext()._reportedErrors;
|
|
166
|
+
if (reportedErrors.has(error)) return;
|
|
167
|
+
reportedErrors.add(error);
|
|
168
|
+
}
|
|
142
169
|
invokeOnError(router.onError, error, phase, context, "RSC");
|
|
143
170
|
}
|
|
144
171
|
|
|
145
|
-
|
|
172
|
+
function getRequiredRouteMap(): Record<string, string> {
|
|
173
|
+
const routeMap = getRouterManifest(router.id);
|
|
174
|
+
if (!routeMap) {
|
|
175
|
+
throw new Error(
|
|
176
|
+
`Route manifest for router "${router.id}" is not available.`,
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
return routeMap;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Handle a timeout by reporting the error, emitting telemetry,
|
|
184
|
+
* and returning either the custom onTimeout response or a default 504.
|
|
185
|
+
*/
|
|
186
|
+
async function handleTimeoutResponse(
|
|
146
187
|
request: Request,
|
|
147
|
-
env: TEnv
|
|
148
|
-
|
|
188
|
+
env: TEnv,
|
|
189
|
+
url: URL,
|
|
190
|
+
phase: TimeoutPhase,
|
|
191
|
+
durationMs: number,
|
|
192
|
+
routeKey?: string,
|
|
193
|
+
actionId?: string,
|
|
194
|
+
): Promise<Response> {
|
|
195
|
+
const timeoutError = new RouterTimeoutError(phase, durationMs);
|
|
196
|
+
|
|
197
|
+
callOnError(timeoutError, phase === "action" ? "action" : "handler", {
|
|
198
|
+
request,
|
|
199
|
+
url,
|
|
200
|
+
env,
|
|
201
|
+
routeKey,
|
|
202
|
+
actionId,
|
|
203
|
+
handledByBoundary: false,
|
|
204
|
+
metadata: { timeout: true, phase, durationMs },
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
try {
|
|
208
|
+
const routerCtx = getRouterContext();
|
|
209
|
+
if (routerCtx?.telemetry) {
|
|
210
|
+
safeEmit(resolveSink(routerCtx.telemetry), {
|
|
211
|
+
type: "request.timeout" as const,
|
|
212
|
+
timestamp: performance.now(),
|
|
213
|
+
requestId: routerCtx.requestId,
|
|
214
|
+
phase,
|
|
215
|
+
pathname: url.pathname,
|
|
216
|
+
routeKey,
|
|
217
|
+
actionId,
|
|
218
|
+
durationMs,
|
|
219
|
+
customHandler: !!router.onTimeout,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
} catch {
|
|
223
|
+
// Router context may not be available
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
if (router.onTimeout) {
|
|
227
|
+
try {
|
|
228
|
+
return await router.onTimeout({
|
|
229
|
+
phase,
|
|
230
|
+
request,
|
|
231
|
+
url,
|
|
232
|
+
env,
|
|
233
|
+
routeKey,
|
|
234
|
+
actionId,
|
|
235
|
+
durationMs,
|
|
236
|
+
});
|
|
237
|
+
} catch (e) {
|
|
238
|
+
if (process.env.NODE_ENV !== "production") {
|
|
239
|
+
console.error("[RSC] onTimeout callback error:", e);
|
|
240
|
+
}
|
|
241
|
+
return createDefaultTimeoutResponse(phase);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return createDefaultTimeoutResponse(phase);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Build a 200 Flight response that carries a redirect URL and optional state.
|
|
250
|
+
* Used when a partial/action request results in a redirect -- fetch
|
|
251
|
+
* auto-follows 3xx so we send the redirect as payload metadata instead.
|
|
252
|
+
*/
|
|
253
|
+
function createRedirectFlightResponse(
|
|
254
|
+
redirectUrl: string,
|
|
255
|
+
locationState?: Record<string, unknown>,
|
|
256
|
+
): Response {
|
|
257
|
+
const redirectPayload: RscPayload = {
|
|
258
|
+
metadata: {
|
|
259
|
+
pathname: redirectUrl,
|
|
260
|
+
segments: [],
|
|
261
|
+
redirect: { url: redirectUrl },
|
|
262
|
+
...(locationState && { locationState }),
|
|
263
|
+
},
|
|
264
|
+
};
|
|
265
|
+
const rscStream = renderToReadableStream<RscPayload>(redirectPayload);
|
|
266
|
+
return createResponseWithMergedHeaders(rscStream, {
|
|
267
|
+
status: 200,
|
|
268
|
+
headers: { "content-type": "text/x-component;charset=utf-8" },
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Bundle shared dependencies for extracted handler functions.
|
|
273
|
+
// callOnError reads from ALS so it's inherently per-request scoped.
|
|
274
|
+
const handlerCtx: HandlerContext<TEnv> = {
|
|
275
|
+
router,
|
|
276
|
+
version,
|
|
277
|
+
renderToReadableStream,
|
|
278
|
+
decodeReply,
|
|
279
|
+
createTemporaryReferenceSet,
|
|
280
|
+
loadServerAction,
|
|
281
|
+
decodeAction,
|
|
282
|
+
decodeFormState,
|
|
283
|
+
loadSSRModule,
|
|
284
|
+
callOnError,
|
|
285
|
+
getRequiredRouteMap,
|
|
286
|
+
createRedirectFlightResponse,
|
|
287
|
+
resolveStreamMode: async (request, env, url) => {
|
|
288
|
+
const resolver = router.ssr?.resolveStreaming;
|
|
289
|
+
if (!resolver) return "stream";
|
|
290
|
+
return resolver({ request, env, url });
|
|
149
291
|
},
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
return async function handler(
|
|
295
|
+
request: Request,
|
|
296
|
+
input: RouterRequestInput<TEnv> = {},
|
|
150
297
|
): Promise<Response> {
|
|
151
298
|
const handlerStart = performance.now();
|
|
299
|
+
// Create the metrics store at handler start so handler:total has startTime=0
|
|
300
|
+
// and all metrics are relative to the request entry point.
|
|
301
|
+
const earlyMetricsStore = router.debugPerformance
|
|
302
|
+
? createMetricsStore(true, handlerStart)
|
|
303
|
+
: undefined;
|
|
304
|
+
|
|
305
|
+
const { env = {} as TEnv, vars: initialVars, ctx: executionCtx } = input;
|
|
152
306
|
|
|
153
307
|
// Connection warmup: return 204 immediately before any processing
|
|
154
|
-
if (router
|
|
308
|
+
if (router?.warmupEnabled && request.method === "HEAD") {
|
|
155
309
|
const warmupUrl = new URL(request.url);
|
|
156
310
|
if (warmupUrl.searchParams.has("_rsc_warmup")) {
|
|
157
311
|
return new Response(null, { status: 204 });
|
|
@@ -175,13 +329,14 @@ export function createRSCHandler<
|
|
|
175
329
|
const mwMatchDur = performance.now() - mwMatchStart;
|
|
176
330
|
|
|
177
331
|
// Shared variables between middleware and route handlers
|
|
178
|
-
// Initialize from
|
|
179
|
-
const variables: Record<string, any> =
|
|
180
|
-
|
|
181
|
-
|
|
332
|
+
// Initialize from input.vars if provided (allows pre-seeding from worker entry)
|
|
333
|
+
const variables: Record<string, any> = initialVars
|
|
334
|
+
? { ...initialVars }
|
|
335
|
+
: {};
|
|
182
336
|
|
|
183
|
-
// Store nonce
|
|
337
|
+
// Store nonce via ContextVar token and string key for backward compat
|
|
184
338
|
if (nonce) {
|
|
339
|
+
contextSet(variables, nonceToken, nonce);
|
|
185
340
|
variables.nonce = nonce;
|
|
186
341
|
}
|
|
187
342
|
|
|
@@ -192,7 +347,9 @@ export function createRSCHandler<
|
|
|
192
347
|
const cacheOption = options.cache ?? router.cache;
|
|
193
348
|
if (cacheOption && !url.searchParams.has("__no_cache")) {
|
|
194
349
|
const cacheConfig =
|
|
195
|
-
typeof cacheOption === "function"
|
|
350
|
+
typeof cacheOption === "function"
|
|
351
|
+
? cacheOption(env, executionCtx)
|
|
352
|
+
: cacheOption;
|
|
196
353
|
|
|
197
354
|
if (cacheConfig.enabled !== false) {
|
|
198
355
|
cacheStore = cacheConfig.store;
|
|
@@ -223,56 +380,7 @@ export function createRSCHandler<
|
|
|
223
380
|
// Cloudflare dev: generate manifest inline for this router.
|
|
224
381
|
// Each router generates its own manifest independently so
|
|
225
382
|
// multi-router setups (host routing) work correctly.
|
|
226
|
-
|
|
227
|
-
await import("../build/generate-manifest.js");
|
|
228
|
-
const generated = generateManifest(router.urlpatterns);
|
|
229
|
-
if (
|
|
230
|
-
generated._routeAncestry &&
|
|
231
|
-
Object.keys(generated._routeAncestry).length > 0
|
|
232
|
-
) {
|
|
233
|
-
const { buildRouteTrie } = await import("../build/route-trie.js");
|
|
234
|
-
// Map each route to its include() staticPrefix so the trie
|
|
235
|
-
// returns the correct sp for lazy entry lookup in findMatch.
|
|
236
|
-
const routeToStaticPrefix: Record<string, string> = {};
|
|
237
|
-
for (const name of Object.keys(generated.routeManifest)) {
|
|
238
|
-
routeToStaticPrefix[name] = "";
|
|
239
|
-
}
|
|
240
|
-
// Override with prefix from include() entries so the trie
|
|
241
|
-
// returns the correct sp for lazy entry lookup in findMatch.
|
|
242
|
-
// Walk recursively to include routes in nested includes.
|
|
243
|
-
if (generated.prefixTree) {
|
|
244
|
-
const visitPrefixNode = (node: any): void => {
|
|
245
|
-
const sp = node.staticPrefix || "";
|
|
246
|
-
for (const route of (node.routes || [])) {
|
|
247
|
-
routeToStaticPrefix[route] = sp;
|
|
248
|
-
}
|
|
249
|
-
for (const child of Object.values(node.children || {})) {
|
|
250
|
-
visitPrefixNode(child);
|
|
251
|
-
}
|
|
252
|
-
};
|
|
253
|
-
for (const node of Object.values(generated.prefixTree)) {
|
|
254
|
-
visitPrefixNode(node);
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
const trie = buildRouteTrie(
|
|
258
|
-
generated.routeManifest,
|
|
259
|
-
generated._routeAncestry,
|
|
260
|
-
routeToStaticPrefix,
|
|
261
|
-
generated.routeTrailingSlash,
|
|
262
|
-
generated.prerenderRoutes ? new Set(generated.prerenderRoutes) : undefined,
|
|
263
|
-
generated.passthroughRoutes ? new Set(generated.passthroughRoutes) : undefined,
|
|
264
|
-
generated.responseTypeRoutes,
|
|
265
|
-
);
|
|
266
|
-
setRouterTrie(router.id, trie);
|
|
267
|
-
// Set global trie only if not already set by another router
|
|
268
|
-
if (!getRouteTrie()) {
|
|
269
|
-
setRouteTrie(trie);
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
setRouterManifest(router.id, generated.routeManifest);
|
|
273
|
-
// Merge into global manifest (needed for reverse/href across routers)
|
|
274
|
-
const existing = hasCachedManifest() ? getGlobalRouteMap() : {};
|
|
275
|
-
setCachedManifest({ ...existing, ...generated.routeManifest });
|
|
383
|
+
await buildRouterTrieFromUrlpatterns(router);
|
|
276
384
|
}
|
|
277
385
|
if (!getRouterManifest(router.id) && !hasCachedManifest()) {
|
|
278
386
|
throw new Error(
|
|
@@ -280,10 +388,17 @@ export function createRSCHandler<
|
|
|
280
388
|
);
|
|
281
389
|
}
|
|
282
390
|
}
|
|
283
|
-
const manifestCacheDur = performance.now() - manifestCacheStart;
|
|
284
391
|
|
|
285
|
-
//
|
|
286
|
-
// This
|
|
392
|
+
// Rebuild the trie when the manifest exists but the per-router trie is
|
|
393
|
+
// missing. This happens in dev mode after HMR: the virtual module sets
|
|
394
|
+
// the manifest (from fresh gen files) but the trie is intentionally not
|
|
395
|
+
// injected to avoid stale discovery-time data. Without the trie, route
|
|
396
|
+
// matching falls back to regex iteration which does not handle wildcard
|
|
397
|
+
// priority correctly (catch-all patterns match before specific routes).
|
|
398
|
+
if (!getRouterTrie(router.id) && router.urlpatterns) {
|
|
399
|
+
await buildRouterTrieFromUrlpatterns(router);
|
|
400
|
+
}
|
|
401
|
+
const manifestCacheDur = performance.now() - manifestCacheStart;
|
|
287
402
|
|
|
288
403
|
// Create unified request context with all methods
|
|
289
404
|
// Includes: stub response, handle store, loader memoization, use(), cookies, headers, cache store
|
|
@@ -295,9 +410,27 @@ export function createRSCHandler<
|
|
|
295
410
|
url,
|
|
296
411
|
variables,
|
|
297
412
|
cacheStore,
|
|
298
|
-
|
|
413
|
+
cacheProfiles: router.cacheProfiles,
|
|
414
|
+
executionContext: executionCtx,
|
|
299
415
|
themeConfig: router.themeConfig,
|
|
300
416
|
});
|
|
417
|
+
if (earlyMetricsStore) {
|
|
418
|
+
requestContext._debugPerformance = true;
|
|
419
|
+
requestContext._metricsStore = earlyMetricsStore;
|
|
420
|
+
}
|
|
421
|
+
// Wire background error reporting so "use cache" and other subsystems
|
|
422
|
+
// can surface non-fatal errors through the router's onError callback.
|
|
423
|
+
requestContext._reportBackgroundError = (
|
|
424
|
+
error: unknown,
|
|
425
|
+
category: string,
|
|
426
|
+
) => {
|
|
427
|
+
callOnError(error, "cache", {
|
|
428
|
+
request,
|
|
429
|
+
url,
|
|
430
|
+
metadata: { category },
|
|
431
|
+
});
|
|
432
|
+
};
|
|
433
|
+
|
|
301
434
|
const ctxCreateDur = performance.now() - ctxCreateStart;
|
|
302
435
|
|
|
303
436
|
// Accumulate handler-level timing for Server-Timing header
|
|
@@ -326,17 +459,71 @@ export function createRSCHandler<
|
|
|
326
459
|
};
|
|
327
460
|
|
|
328
461
|
// Execute middleware chain if any, otherwise call core handler directly
|
|
462
|
+
let response: Response;
|
|
329
463
|
if (matchedMiddleware.length > 0) {
|
|
330
|
-
|
|
464
|
+
const mwResponse = await executeMiddleware(
|
|
331
465
|
matchedMiddleware,
|
|
332
466
|
request,
|
|
333
467
|
env,
|
|
334
468
|
variables,
|
|
335
469
|
coreHandler,
|
|
470
|
+
createReverseFunction(getRequiredRouteMap()),
|
|
471
|
+
);
|
|
472
|
+
|
|
473
|
+
if (
|
|
474
|
+
url.searchParams.has("_rsc_partial") ||
|
|
475
|
+
url.searchParams.has("_rsc_action")
|
|
476
|
+
) {
|
|
477
|
+
const intercepted = interceptRedirectForPartial(
|
|
478
|
+
mwResponse,
|
|
479
|
+
createRedirectFlightResponse,
|
|
480
|
+
);
|
|
481
|
+
response = intercepted ?? finalizeResponse(mwResponse);
|
|
482
|
+
} else {
|
|
483
|
+
response = finalizeResponse(mwResponse);
|
|
484
|
+
}
|
|
485
|
+
} else {
|
|
486
|
+
response = await coreHandler();
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// Finalize metrics after all middleware (including post-next work)
|
|
490
|
+
// has completed so :post spans are captured in the timeline.
|
|
491
|
+
// Handler timing parts are always emitted (even without debug metrics)
|
|
492
|
+
// so non-debug requests still get bootstrap Server-Timing entries.
|
|
493
|
+
const handlerTimingArr: string[] = variables.__handlerTiming || [];
|
|
494
|
+
// Preserve any existing Server-Timing set by response routes or middleware
|
|
495
|
+
const existingTiming = response.headers.get("Server-Timing");
|
|
496
|
+
const timingParts = existingTiming
|
|
497
|
+
? [existingTiming, ...handlerTimingArr]
|
|
498
|
+
: [...handlerTimingArr];
|
|
499
|
+
|
|
500
|
+
const metricsStore = requestContext._metricsStore;
|
|
501
|
+
if (metricsStore) {
|
|
502
|
+
// When the store was created at handler start (earlyMetricsStore),
|
|
503
|
+
// handler:total covers the full request. When ctx.debugPerformance()
|
|
504
|
+
// created the store mid-request, use its requestStart to avoid a
|
|
505
|
+
// negative startTime offset.
|
|
506
|
+
const totalStart = earlyMetricsStore
|
|
507
|
+
? handlerStart
|
|
508
|
+
: metricsStore.requestStart;
|
|
509
|
+
appendMetric(
|
|
510
|
+
metricsStore,
|
|
511
|
+
"handler:total",
|
|
512
|
+
totalStart,
|
|
513
|
+
performance.now() - totalStart,
|
|
336
514
|
);
|
|
515
|
+
const metricsTiming = buildMetricsTiming(
|
|
516
|
+
request.method,
|
|
517
|
+
url.pathname,
|
|
518
|
+
metricsStore,
|
|
519
|
+
);
|
|
520
|
+
if (metricsTiming) timingParts.push(metricsTiming);
|
|
337
521
|
}
|
|
338
522
|
|
|
339
|
-
|
|
523
|
+
const fullTiming = timingParts.join(", ");
|
|
524
|
+
if (fullTiming) response.headers.set("Server-Timing", fullTiming);
|
|
525
|
+
|
|
526
|
+
return response;
|
|
340
527
|
});
|
|
341
528
|
};
|
|
342
529
|
|
|
@@ -348,224 +535,314 @@ export function createRSCHandler<
|
|
|
348
535
|
variables: Record<string, any>,
|
|
349
536
|
nonce: string | undefined,
|
|
350
537
|
): Promise<Response> {
|
|
351
|
-
// First, check for route-level middleware
|
|
352
538
|
const previewStart = performance.now();
|
|
353
|
-
const preview = await router.previewMatch(request, env);
|
|
539
|
+
const preview = await router.previewMatch(request, { env });
|
|
354
540
|
const previewDur = performance.now() - previewStart;
|
|
355
541
|
const handlerTiming: string[] = variables.__handlerTiming || [];
|
|
356
542
|
handlerTiming.push(`handler-preview-match;dur=${previewDur.toFixed(2)}`);
|
|
357
543
|
// Response route short-circuit: skip entire RSC pipeline
|
|
358
544
|
if (preview?.responseType && preview.handler) {
|
|
359
|
-
const
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
return
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
545
|
+
const responseOutcome = await withTimeout(
|
|
546
|
+
handleResponseRoute(
|
|
547
|
+
handlerCtx,
|
|
548
|
+
preview as ResponseRouteMatch,
|
|
549
|
+
request,
|
|
550
|
+
env,
|
|
551
|
+
url,
|
|
552
|
+
variables,
|
|
553
|
+
),
|
|
554
|
+
router.timeouts.renderStartMs,
|
|
555
|
+
"render-start",
|
|
556
|
+
);
|
|
557
|
+
if (responseOutcome.timedOut) {
|
|
558
|
+
return handleTimeoutResponse(
|
|
559
|
+
request,
|
|
560
|
+
env,
|
|
561
|
+
url,
|
|
562
|
+
"render-start",
|
|
563
|
+
responseOutcome.durationMs,
|
|
564
|
+
preview?.routeKey,
|
|
565
|
+
);
|
|
379
566
|
}
|
|
567
|
+
return responseOutcome.result;
|
|
568
|
+
}
|
|
380
569
|
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
570
|
+
// Kick off SSR module loading + stream mode resolution in parallel with
|
|
571
|
+
// segment resolution. Placed after the response-route short-circuit so
|
|
572
|
+
// response/mime routes never pay for SSR work.
|
|
573
|
+
if (mayNeedSSR(request, url)) {
|
|
574
|
+
variables[SSR_SETUP_VAR] = startSSRSetup(
|
|
575
|
+
handlerCtx,
|
|
385
576
|
request,
|
|
386
|
-
|
|
387
|
-
env: bindings,
|
|
388
|
-
searchParams: url.searchParams,
|
|
577
|
+
env,
|
|
389
578
|
url,
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
const value = hrefParams[key];
|
|
396
|
-
if (value === undefined) throw new Error(`Missing param "${key}" for path "${name}"`);
|
|
397
|
-
return encodeURIComponent(value);
|
|
398
|
-
});
|
|
399
|
-
}
|
|
400
|
-
return name;
|
|
401
|
-
},
|
|
402
|
-
get: (key: string) => variables[key],
|
|
403
|
-
header: (name: string, value: string) => reqCtx.header(name, value),
|
|
404
|
-
setCookie: (name: string, value: string, options?: any) => reqCtx.setCookie(name, value, options),
|
|
405
|
-
};
|
|
579
|
+
router.debugPerformance
|
|
580
|
+
? () => requireRequestContext()._metricsStore
|
|
581
|
+
: undefined,
|
|
582
|
+
);
|
|
583
|
+
}
|
|
406
584
|
|
|
407
|
-
|
|
408
|
-
const callHandler = async () => {
|
|
409
|
-
// JSON response routes: wrap in { data } / { error } envelope
|
|
410
|
-
if (preview.responseType === "json") {
|
|
411
|
-
const errorCtx = { request, url, env };
|
|
412
|
-
try {
|
|
413
|
-
const result = await (preview.handler as Function)(responseHandlerCtx);
|
|
414
|
-
if (result instanceof Response) {
|
|
415
|
-
const mergedHeaders: Record<string, string> = {};
|
|
416
|
-
result.headers.forEach((value, key) => {
|
|
417
|
-
mergedHeaders[key] = value;
|
|
418
|
-
});
|
|
419
|
-
return createResponseWithMergedHeaders(result.body, {
|
|
420
|
-
status: result.status,
|
|
421
|
-
headers: mergedHeaders,
|
|
422
|
-
});
|
|
423
|
-
}
|
|
424
|
-
return createResponseWithMergedHeaders(
|
|
425
|
-
JSON.stringify({ data: result }),
|
|
426
|
-
{ status: 200, headers: { "content-type": "application/json;charset=utf-8" } },
|
|
427
|
-
);
|
|
428
|
-
} catch (error) {
|
|
429
|
-
callOnError(error, "handler", errorCtx);
|
|
430
|
-
const isDev = process.env.NODE_ENV !== "production";
|
|
431
|
-
const status = error instanceof RouterError ? error.status : 500;
|
|
432
|
-
return createResponseWithMergedHeaders(
|
|
433
|
-
JSON.stringify({ error: createResponseErrorPayload(error, isDev) }),
|
|
434
|
-
{ status, headers: { "content-type": "application/json;charset=utf-8" } },
|
|
435
|
-
);
|
|
436
|
-
}
|
|
437
|
-
}
|
|
585
|
+
const routeReverse = createReverseFunction(getRequiredRouteMap());
|
|
438
586
|
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
587
|
+
const isAction =
|
|
588
|
+
request.headers.has("rsc-action") || url.searchParams.has("_rsc_action");
|
|
589
|
+
const isLoaderFetch = url.searchParams.has("_rsc_loader");
|
|
590
|
+
const actionId =
|
|
591
|
+
request.headers.get("rsc-action") || url.searchParams.get("_rsc_action");
|
|
443
592
|
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
593
|
+
// Origin guard: reject cross-origin actions, loader fetches, and
|
|
594
|
+
// PE form submissions before any execution. Regular page navigations
|
|
595
|
+
// (GET without _rsc_loader/_rsc_action) are not affected.
|
|
596
|
+
const originPhase: OriginCheckPhase | null = isAction
|
|
597
|
+
? "action"
|
|
598
|
+
: isLoaderFetch
|
|
599
|
+
? "loader"
|
|
600
|
+
: request.method === "POST"
|
|
601
|
+
? "pe-form"
|
|
602
|
+
: null;
|
|
603
|
+
if (originPhase) {
|
|
604
|
+
const originResult = await checkRequestOrigin(
|
|
605
|
+
request,
|
|
606
|
+
url,
|
|
607
|
+
router.originCheck,
|
|
608
|
+
env,
|
|
609
|
+
router.id,
|
|
610
|
+
originPhase,
|
|
611
|
+
);
|
|
612
|
+
if (originResult) {
|
|
613
|
+
const originError = new Error(
|
|
614
|
+
`Origin check rejected: ${request.headers.get("origin") ?? "none"} vs ${request.headers.get("host") ?? "none"}`,
|
|
615
|
+
);
|
|
616
|
+
originError.name = "OriginCheckError";
|
|
617
|
+
|
|
618
|
+
callOnError(originError, "origin", {
|
|
619
|
+
request,
|
|
620
|
+
url,
|
|
621
|
+
env,
|
|
622
|
+
handledByBoundary: false,
|
|
623
|
+
metadata: {
|
|
624
|
+
phase: originPhase,
|
|
625
|
+
origin: request.headers.get("origin"),
|
|
626
|
+
host: request.headers.get("host"),
|
|
627
|
+
},
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
try {
|
|
631
|
+
const routerCtx = getRouterContext();
|
|
632
|
+
if (routerCtx?.telemetry) {
|
|
633
|
+
safeEmit(resolveSink(routerCtx.telemetry), {
|
|
634
|
+
type: "request.origin-rejected" as const,
|
|
635
|
+
timestamp: performance.now(),
|
|
636
|
+
requestId: routerCtx.requestId,
|
|
637
|
+
method: request.method,
|
|
638
|
+
pathname: url.pathname,
|
|
639
|
+
phase: originPhase,
|
|
640
|
+
origin: request.headers.get("origin"),
|
|
641
|
+
host: request.headers.get("host"),
|
|
453
642
|
});
|
|
454
643
|
}
|
|
644
|
+
} catch {
|
|
645
|
+
// Router context may not be available
|
|
646
|
+
}
|
|
455
647
|
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
const message = error instanceof RouterError
|
|
489
|
-
? error.message
|
|
490
|
-
: isDev && error instanceof Error
|
|
491
|
-
? error.message
|
|
492
|
-
: "Internal Server Error";
|
|
493
|
-
return createResponseWithMergedHeaders(message, {
|
|
494
|
-
status,
|
|
495
|
-
headers: { "content-type": "text/plain;charset=utf-8" },
|
|
648
|
+
return originResult;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// Get handle store from request context
|
|
653
|
+
const handleStore = requireRequestContext()._handleStore;
|
|
654
|
+
|
|
655
|
+
// Wire up error reporting for late streaming-handle failures
|
|
656
|
+
// (LateHandlePushError: handle pushed after stream completion).
|
|
657
|
+
// Without this, these errors are only caught by React's error boundary
|
|
658
|
+
// and never reach the router's onError callback or telemetry.
|
|
659
|
+
handleStore.onError = (error: Error) => {
|
|
660
|
+
const reqCtx = requireRequestContext();
|
|
661
|
+
callOnError(error, "handler", {
|
|
662
|
+
request,
|
|
663
|
+
url,
|
|
664
|
+
routeKey: reqCtx._routeName,
|
|
665
|
+
params: reqCtx.params as Record<string, string>,
|
|
666
|
+
handledByBoundary: true,
|
|
667
|
+
});
|
|
668
|
+
try {
|
|
669
|
+
const routerCtx = getRouterContext();
|
|
670
|
+
if (routerCtx?.telemetry) {
|
|
671
|
+
safeEmit(resolveSink(routerCtx.telemetry), {
|
|
672
|
+
type: "handler.error" as const,
|
|
673
|
+
timestamp: performance.now(),
|
|
674
|
+
requestId: routerCtx.requestId,
|
|
675
|
+
error,
|
|
676
|
+
handledByBoundary: true,
|
|
677
|
+
pathname: url.pathname,
|
|
678
|
+
routeKey: reqCtx._routeName,
|
|
679
|
+
params: reqCtx.params as Record<string, string>,
|
|
496
680
|
});
|
|
497
681
|
}
|
|
498
|
-
}
|
|
682
|
+
} catch {
|
|
683
|
+
// Router context may not be available (e.g. prerender path)
|
|
684
|
+
}
|
|
685
|
+
};
|
|
499
686
|
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
response.headers.append("Vary", "Accept");
|
|
505
|
-
}
|
|
506
|
-
return response;
|
|
507
|
-
};
|
|
687
|
+
// Set route params early so all execution paths can access ctx.params.
|
|
688
|
+
if (preview?.params) {
|
|
689
|
+
setRequestContextParams(preview.params, preview.routeKey);
|
|
690
|
+
}
|
|
508
691
|
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
692
|
+
// Progressive enhancement runs before the normal action/render paths.
|
|
693
|
+
// Route middleware wraps the PE re-render so handlers see the same
|
|
694
|
+
// context variables regardless of JS/no-JS transport.
|
|
695
|
+
const progressiveResult = await handleProgressiveEnhancement(
|
|
696
|
+
handlerCtx,
|
|
697
|
+
request,
|
|
698
|
+
env,
|
|
699
|
+
url,
|
|
700
|
+
isAction,
|
|
701
|
+
handleStore,
|
|
702
|
+
nonce,
|
|
703
|
+
{
|
|
704
|
+
routeMiddleware: preview?.routeMiddleware,
|
|
705
|
+
variables,
|
|
706
|
+
routeReverse,
|
|
707
|
+
},
|
|
708
|
+
);
|
|
709
|
+
if (progressiveResult) {
|
|
710
|
+
return progressiveResult;
|
|
711
|
+
}
|
|
522
712
|
|
|
523
|
-
|
|
713
|
+
// --- Action execution: runs BEFORE route middleware ---
|
|
714
|
+
// Route middleware wraps rendering only. For actions, the action runs
|
|
715
|
+
// first in the global middleware context, then route middleware wraps
|
|
716
|
+
// the revalidation pass (identical to a normal render).
|
|
717
|
+
let actionContinuation: ActionContinuation | undefined;
|
|
718
|
+
if (isAction && actionId) {
|
|
719
|
+
try {
|
|
720
|
+
const actionOutcome = await withTimeout(
|
|
721
|
+
executeServerAction(
|
|
722
|
+
handlerCtx,
|
|
723
|
+
request,
|
|
724
|
+
env,
|
|
725
|
+
url,
|
|
726
|
+
actionId,
|
|
727
|
+
handleStore,
|
|
728
|
+
),
|
|
729
|
+
router.timeouts.actionMs,
|
|
730
|
+
"action",
|
|
731
|
+
);
|
|
732
|
+
if (actionOutcome.timedOut) {
|
|
733
|
+
return handleTimeoutResponse(
|
|
734
|
+
request,
|
|
735
|
+
env,
|
|
736
|
+
url,
|
|
737
|
+
"action",
|
|
738
|
+
actionOutcome.durationMs,
|
|
739
|
+
preview?.routeKey,
|
|
740
|
+
actionId,
|
|
741
|
+
);
|
|
742
|
+
}
|
|
743
|
+
const result = actionOutcome.result;
|
|
744
|
+
// Response means redirect or error boundary — done.
|
|
745
|
+
if (result instanceof Response) return result;
|
|
746
|
+
actionContinuation = result;
|
|
747
|
+
} catch (error) {
|
|
748
|
+
callOnError(error, "action", {
|
|
749
|
+
request,
|
|
750
|
+
url,
|
|
751
|
+
env,
|
|
752
|
+
actionId,
|
|
753
|
+
handledByBoundary: false,
|
|
754
|
+
});
|
|
755
|
+
console.error(`[RSC] Action error:`, error);
|
|
756
|
+
throw error;
|
|
757
|
+
}
|
|
524
758
|
}
|
|
525
759
|
|
|
526
|
-
//
|
|
527
|
-
|
|
528
|
-
|
|
760
|
+
// --- Rendering (action revalidation or navigation) ---
|
|
761
|
+
// Route middleware wraps this — same code path for both cases.
|
|
762
|
+
const renderHandler = async () => {
|
|
763
|
+
const response = await coreRequestHandlerInner(
|
|
764
|
+
request,
|
|
765
|
+
env,
|
|
766
|
+
url,
|
|
767
|
+
variables,
|
|
768
|
+
nonce,
|
|
769
|
+
preview?.params,
|
|
770
|
+
preview?.routeKey,
|
|
771
|
+
handleStore,
|
|
772
|
+
actionContinuation,
|
|
773
|
+
);
|
|
529
774
|
if (preview?.negotiated) {
|
|
530
775
|
response.headers.append("Vary", "Accept");
|
|
531
776
|
}
|
|
532
777
|
return response;
|
|
533
778
|
};
|
|
534
779
|
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
780
|
+
// Wrap the render path (with or without route middleware) in a
|
|
781
|
+
// renderStartMs timeout so slow renders are caught before output.
|
|
782
|
+
const executeRender = async (): Promise<Response> => {
|
|
783
|
+
if (preview?.routeMiddleware && preview.routeMiddleware.length > 0) {
|
|
784
|
+
const mwResponse = await executeMiddleware(
|
|
785
|
+
buildRouteMiddlewareEntries<TEnv>(preview.routeMiddleware),
|
|
786
|
+
request,
|
|
787
|
+
env,
|
|
788
|
+
variables,
|
|
789
|
+
renderHandler,
|
|
790
|
+
routeReverse,
|
|
791
|
+
);
|
|
547
792
|
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
793
|
+
if (
|
|
794
|
+
url.searchParams.has("_rsc_partial") ||
|
|
795
|
+
url.searchParams.has("_rsc_action")
|
|
796
|
+
) {
|
|
797
|
+
const intercepted = interceptRedirectForPartial(
|
|
798
|
+
mwResponse,
|
|
799
|
+
createRedirectFlightResponse,
|
|
800
|
+
);
|
|
801
|
+
if (intercepted) return intercepted;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
return finalizeResponse(mwResponse);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
// No route middleware, proceed directly
|
|
808
|
+
return renderHandler();
|
|
809
|
+
};
|
|
551
810
|
|
|
552
|
-
|
|
553
|
-
|
|
811
|
+
const renderOutcome = await withTimeout(
|
|
812
|
+
executeRender(),
|
|
813
|
+
router.timeouts.renderStartMs,
|
|
814
|
+
"render-start",
|
|
815
|
+
);
|
|
816
|
+
if (renderOutcome.timedOut) {
|
|
817
|
+
return handleTimeoutResponse(
|
|
818
|
+
request,
|
|
819
|
+
env,
|
|
820
|
+
url,
|
|
821
|
+
"render-start",
|
|
822
|
+
renderOutcome.durationMs,
|
|
823
|
+
preview?.routeKey,
|
|
824
|
+
);
|
|
825
|
+
}
|
|
826
|
+
return renderOutcome.result;
|
|
554
827
|
}
|
|
555
828
|
|
|
556
|
-
// Inner request handler
|
|
829
|
+
// Inner request handler: rendering logic wrapped by route middleware.
|
|
830
|
+
// Handles action revalidation (when actionContinuation is present),
|
|
831
|
+
// loader fetches, and regular RSC rendering.
|
|
557
832
|
async function coreRequestHandlerInner(
|
|
558
833
|
request: Request,
|
|
559
834
|
env: TEnv,
|
|
560
835
|
url: URL,
|
|
561
836
|
variables: Record<string, any>,
|
|
562
837
|
nonce: string | undefined,
|
|
838
|
+
routeParams?: Record<string, string>,
|
|
839
|
+
routeKey?: string,
|
|
840
|
+
handleStore?: ReturnType<typeof requireRequestContext>["_handleStore"],
|
|
841
|
+
actionContinuation?: ActionContinuation,
|
|
563
842
|
): Promise<Response> {
|
|
564
843
|
const isPartial = url.searchParams.has("_rsc_partial");
|
|
565
844
|
const isAction =
|
|
566
845
|
request.headers.has("rsc-action") || url.searchParams.has("_rsc_action");
|
|
567
|
-
const actionId =
|
|
568
|
-
request.headers.get("rsc-action") || url.searchParams.get("_rsc_action");
|
|
569
846
|
|
|
570
847
|
// Version mismatch detection - client may have stale code after HMR/deployment
|
|
571
848
|
// If versions don't match, tell the client to reload
|
|
@@ -575,20 +852,23 @@ export function createRSCHandler<
|
|
|
575
852
|
`[RSC] Version mismatch: client=${clientVersion}, server=${version}. Forcing reload.`,
|
|
576
853
|
);
|
|
577
854
|
|
|
578
|
-
//
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
855
|
+
// For actions, reload current page (referer) if same origin.
|
|
856
|
+
// For navigation, load the target URL.
|
|
857
|
+
// Validate referer origin to prevent open redirect via crafted header.
|
|
858
|
+
let reloadUrl = stripInternalParams(url).toString();
|
|
859
|
+
if (isAction) {
|
|
860
|
+
const referer = request.headers.get("referer");
|
|
861
|
+
if (referer) {
|
|
862
|
+
try {
|
|
863
|
+
const refererUrl = new URL(referer);
|
|
864
|
+
if (refererUrl.origin === url.origin) {
|
|
865
|
+
reloadUrl = referer;
|
|
866
|
+
}
|
|
867
|
+
} catch {
|
|
868
|
+
// Malformed referer, fall back to cleanUrl
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
}
|
|
592
872
|
|
|
593
873
|
// Return special response that tells client to reload
|
|
594
874
|
return createResponseWithMergedHeaders(null, {
|
|
@@ -607,8 +887,9 @@ export function createRSCHandler<
|
|
|
607
887
|
(isDev || router.allowDebugManifest)
|
|
608
888
|
) {
|
|
609
889
|
const trie = getRouterTrie(router.id) ?? getRouteTrie();
|
|
610
|
-
const routeManifest =
|
|
611
|
-
const { extractAncestryFromTrie } =
|
|
890
|
+
const routeManifest = getRequiredRouteMap();
|
|
891
|
+
const { extractAncestryFromTrie } =
|
|
892
|
+
await import("../build/route-trie.js");
|
|
612
893
|
return new Response(
|
|
613
894
|
JSON.stringify(
|
|
614
895
|
{
|
|
@@ -627,30 +908,27 @@ export function createRSCHandler<
|
|
|
627
908
|
);
|
|
628
909
|
}
|
|
629
910
|
|
|
630
|
-
|
|
631
|
-
const handleStore = requireRequestContext()._handleStore;
|
|
911
|
+
const store = handleStore ?? requireRequestContext()._handleStore;
|
|
632
912
|
|
|
633
913
|
try {
|
|
634
|
-
//
|
|
635
|
-
//
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
request,
|
|
639
|
-
env,
|
|
640
|
-
url,
|
|
641
|
-
isAction,
|
|
642
|
-
handleStore,
|
|
643
|
-
nonce,
|
|
644
|
-
);
|
|
645
|
-
if (progressiveResult) {
|
|
646
|
-
return progressiveResult;
|
|
914
|
+
// Route params were already set in coreRequestHandler, but set again
|
|
915
|
+
// for callers that enter coreRequestHandlerInner directly.
|
|
916
|
+
if (routeParams) {
|
|
917
|
+
setRequestContextParams(routeParams, routeKey);
|
|
647
918
|
}
|
|
648
919
|
|
|
649
920
|
// ============================================================================
|
|
650
|
-
//
|
|
921
|
+
// ACTION REVALIDATION (action already executed, revalidate segments)
|
|
651
922
|
// ============================================================================
|
|
652
|
-
if (
|
|
653
|
-
return
|
|
923
|
+
if (actionContinuation) {
|
|
924
|
+
return await revalidateAfterAction(
|
|
925
|
+
handlerCtx,
|
|
926
|
+
request,
|
|
927
|
+
env,
|
|
928
|
+
url,
|
|
929
|
+
store,
|
|
930
|
+
actionContinuation,
|
|
931
|
+
);
|
|
654
932
|
}
|
|
655
933
|
|
|
656
934
|
// ============================================================================
|
|
@@ -658,7 +936,14 @@ export function createRSCHandler<
|
|
|
658
936
|
// ============================================================================
|
|
659
937
|
const isLoaderRequest = url.searchParams.has("_rsc_loader");
|
|
660
938
|
if (isLoaderRequest) {
|
|
661
|
-
return handleLoaderFetch(
|
|
939
|
+
return handleLoaderFetch(
|
|
940
|
+
handlerCtx,
|
|
941
|
+
request,
|
|
942
|
+
env,
|
|
943
|
+
url,
|
|
944
|
+
variables,
|
|
945
|
+
routeParams,
|
|
946
|
+
);
|
|
662
947
|
}
|
|
663
948
|
|
|
664
949
|
// ============================================================================
|
|
@@ -666,11 +951,12 @@ export function createRSCHandler<
|
|
|
666
951
|
// ============================================================================
|
|
667
952
|
// Note: Must use "return await" for try/catch to catch async rejections
|
|
668
953
|
return await handleRscRendering(
|
|
954
|
+
handlerCtx,
|
|
669
955
|
request,
|
|
670
956
|
env,
|
|
671
957
|
url,
|
|
672
958
|
isPartial,
|
|
673
|
-
|
|
959
|
+
store,
|
|
674
960
|
nonce,
|
|
675
961
|
);
|
|
676
962
|
} catch (error) {
|
|
@@ -684,23 +970,25 @@ export function createRSCHandler<
|
|
|
684
970
|
if (isPartial && error.status === 200) {
|
|
685
971
|
console.warn(
|
|
686
972
|
`[RSC] Route handler at ${url.pathname} returned a Response during client-side navigation. ` +
|
|
687
|
-
|
|
973
|
+
`Falling back to hard navigation. Use data-external on the <Link> to avoid the extra round-trip.`,
|
|
688
974
|
);
|
|
689
|
-
const cleanUrl = new URL(url);
|
|
690
|
-
cleanUrl.searchParams.delete("_rsc_partial");
|
|
691
|
-
cleanUrl.searchParams.delete("_rsc_segments");
|
|
692
|
-
cleanUrl.searchParams.delete("_rsc_v");
|
|
693
|
-
cleanUrl.searchParams.delete("_rsc_stale");
|
|
694
|
-
cleanUrl.searchParams.delete("_rsc_action");
|
|
695
|
-
cleanUrl.searchParams.delete("_rsc_prev");
|
|
696
975
|
return createResponseWithMergedHeaders(null, {
|
|
697
976
|
status: 200,
|
|
698
977
|
headers: {
|
|
699
|
-
"X-RSC-Reload":
|
|
978
|
+
"X-RSC-Reload": stripInternalParams(url).toString(),
|
|
700
979
|
"content-type": "text/x-component;charset=utf-8",
|
|
701
980
|
},
|
|
702
981
|
});
|
|
703
982
|
}
|
|
983
|
+
|
|
984
|
+
if (isPartial) {
|
|
985
|
+
const intercepted = interceptRedirectForPartial(
|
|
986
|
+
error,
|
|
987
|
+
createRedirectFlightResponse,
|
|
988
|
+
);
|
|
989
|
+
if (intercepted) return intercepted;
|
|
990
|
+
}
|
|
991
|
+
|
|
704
992
|
return error;
|
|
705
993
|
}
|
|
706
994
|
|
|
@@ -734,21 +1022,15 @@ export function createRSCHandler<
|
|
|
734
1022
|
params: {},
|
|
735
1023
|
};
|
|
736
1024
|
|
|
737
|
-
// Render with rootLayout to maintain app shell
|
|
738
|
-
const root = await renderSegments([notFoundSegment], {
|
|
739
|
-
rootLayout: router.rootLayout,
|
|
740
|
-
// No routeName for not-found routes
|
|
741
|
-
});
|
|
742
|
-
|
|
743
1025
|
const payload: RscPayload = {
|
|
744
|
-
root,
|
|
745
1026
|
metadata: {
|
|
746
1027
|
pathname: url.pathname,
|
|
747
1028
|
segments: [notFoundSegment],
|
|
748
1029
|
matched: [],
|
|
749
1030
|
diff: [],
|
|
750
1031
|
isPartial: false,
|
|
751
|
-
|
|
1032
|
+
rootLayout: router.rootLayout,
|
|
1033
|
+
handles: store.stream(),
|
|
752
1034
|
version,
|
|
753
1035
|
themeConfig: router.themeConfig,
|
|
754
1036
|
warmupEnabled: router.warmupEnabled,
|
|
@@ -759,8 +1041,10 @@ export function createRSCHandler<
|
|
|
759
1041
|
|
|
760
1042
|
const rscStream = renderToReadableStream(payload);
|
|
761
1043
|
|
|
762
|
-
// Determine if this is an RSC request or HTML request
|
|
1044
|
+
// Determine if this is an RSC request or HTML request.
|
|
1045
|
+
// Partial requests are always RSC (see main isRscRequest comment).
|
|
763
1046
|
const isRscRequest =
|
|
1047
|
+
isPartial ||
|
|
764
1048
|
(!request.headers.get("accept")?.includes("text/html") &&
|
|
765
1049
|
!url.searchParams.has("__html")) ||
|
|
766
1050
|
url.searchParams.has("__rsc");
|
|
@@ -772,9 +1056,18 @@ export function createRSCHandler<
|
|
|
772
1056
|
});
|
|
773
1057
|
}
|
|
774
1058
|
|
|
775
|
-
// Delegate to SSR for HTML response
|
|
776
|
-
const ssrModule = await
|
|
777
|
-
|
|
1059
|
+
// Delegate to SSR for HTML response (reuse early setup if available)
|
|
1060
|
+
const [ssrModule, streamMode] = await getSSRSetup(
|
|
1061
|
+
handlerCtx,
|
|
1062
|
+
request,
|
|
1063
|
+
env,
|
|
1064
|
+
url,
|
|
1065
|
+
requireRequestContext()._metricsStore,
|
|
1066
|
+
);
|
|
1067
|
+
const htmlStream = await ssrModule.renderHTML(rscStream, {
|
|
1068
|
+
nonce,
|
|
1069
|
+
streamMode,
|
|
1070
|
+
});
|
|
778
1071
|
|
|
779
1072
|
return createResponseWithMergedHeaders(htmlStream, {
|
|
780
1073
|
status: 404,
|
|
@@ -793,685 +1086,4 @@ export function createRSCHandler<
|
|
|
793
1086
|
throw error;
|
|
794
1087
|
}
|
|
795
1088
|
}
|
|
796
|
-
|
|
797
|
-
// ============================================================================
|
|
798
|
-
// PROGRESSIVE ENHANCEMENT HANDLER
|
|
799
|
-
// When JavaScript is disabled, React renders forms with hidden fields
|
|
800
|
-
// ($ACTION_REF_*, $ACTION_KEY) containing the action reference.
|
|
801
|
-
// We detect these and return HTML instead of RSC stream.
|
|
802
|
-
// ============================================================================
|
|
803
|
-
async function handleProgressiveEnhancement(
|
|
804
|
-
request: Request,
|
|
805
|
-
env: TEnv,
|
|
806
|
-
url: URL,
|
|
807
|
-
isAction: boolean,
|
|
808
|
-
handleStore: ReturnType<typeof requireRequestContext>["_handleStore"],
|
|
809
|
-
nonce: string | undefined,
|
|
810
|
-
): Promise<Response | null> {
|
|
811
|
-
const contentType = request.headers.get("content-type") || "";
|
|
812
|
-
const isFormSubmission =
|
|
813
|
-
contentType.includes("multipart/form-data") ||
|
|
814
|
-
contentType.includes("application/x-www-form-urlencoded");
|
|
815
|
-
|
|
816
|
-
if (request.method !== "POST" || isAction || !isFormSubmission) {
|
|
817
|
-
return null;
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
// Clone the request to read FormData without consuming it
|
|
821
|
-
const formData = await request.clone().formData();
|
|
822
|
-
|
|
823
|
-
// Look for React's progressive enhancement hidden fields
|
|
824
|
-
let isDirectAction = false;
|
|
825
|
-
let isUseActionState = false;
|
|
826
|
-
let directActionId: string | null = null;
|
|
827
|
-
|
|
828
|
-
formData.forEach((_value, key) => {
|
|
829
|
-
if (key.startsWith("$ACTION_ID_")) {
|
|
830
|
-
isDirectAction = true;
|
|
831
|
-
directActionId = key.slice("$ACTION_ID_".length);
|
|
832
|
-
} else if (key.startsWith("$ACTION_REF_")) {
|
|
833
|
-
isUseActionState = true;
|
|
834
|
-
}
|
|
835
|
-
});
|
|
836
|
-
|
|
837
|
-
if (!isDirectAction && !isUseActionState) {
|
|
838
|
-
return null;
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
// Execute action and return HTML
|
|
842
|
-
let actionResult: unknown = undefined;
|
|
843
|
-
let reactFormState: ReactFormState | null = null;
|
|
844
|
-
|
|
845
|
-
if (isUseActionState) {
|
|
846
|
-
try {
|
|
847
|
-
const boundAction = await decodeAction(formData);
|
|
848
|
-
actionResult = await boundAction();
|
|
849
|
-
} catch (error) {
|
|
850
|
-
callOnError(error, "action", {
|
|
851
|
-
request,
|
|
852
|
-
url,
|
|
853
|
-
env,
|
|
854
|
-
handledByBoundary: false,
|
|
855
|
-
});
|
|
856
|
-
console.error("[RSC] Progressive enhancement action error:", error);
|
|
857
|
-
}
|
|
858
|
-
} else if (isDirectAction && directActionId) {
|
|
859
|
-
const temporaryReferences = createTemporaryReferenceSet();
|
|
860
|
-
|
|
861
|
-
let args: unknown[] = [];
|
|
862
|
-
try {
|
|
863
|
-
args = await decodeReply(formData, { temporaryReferences });
|
|
864
|
-
} catch {
|
|
865
|
-
args = [formData];
|
|
866
|
-
}
|
|
867
|
-
|
|
868
|
-
try {
|
|
869
|
-
const loadedAction = await loadServerAction(directActionId);
|
|
870
|
-
actionResult = await loadedAction.apply(null, args);
|
|
871
|
-
} catch (error) {
|
|
872
|
-
callOnError(error, "action", {
|
|
873
|
-
request,
|
|
874
|
-
url,
|
|
875
|
-
env,
|
|
876
|
-
actionId: directActionId,
|
|
877
|
-
handledByBoundary: false,
|
|
878
|
-
});
|
|
879
|
-
console.error("[RSC] Progressive enhancement action error:", error);
|
|
880
|
-
}
|
|
881
|
-
}
|
|
882
|
-
|
|
883
|
-
// Decode form state for useActionState progressive enhancement
|
|
884
|
-
try {
|
|
885
|
-
reactFormState = await decodeFormState(actionResult, formData);
|
|
886
|
-
} catch (error) {
|
|
887
|
-
callOnError(error, "action", {
|
|
888
|
-
request,
|
|
889
|
-
url,
|
|
890
|
-
env,
|
|
891
|
-
handledByBoundary: false,
|
|
892
|
-
});
|
|
893
|
-
console.error("[RSC] Failed to decode form state:", error);
|
|
894
|
-
}
|
|
895
|
-
|
|
896
|
-
// Re-render the page and return HTML
|
|
897
|
-
const renderRequest = new Request(url.toString(), {
|
|
898
|
-
method: "GET",
|
|
899
|
-
headers: new Headers({ accept: "text/html" }),
|
|
900
|
-
});
|
|
901
|
-
|
|
902
|
-
const match = await router.match(renderRequest, env);
|
|
903
|
-
|
|
904
|
-
if (match.redirect) {
|
|
905
|
-
return new Response(null, {
|
|
906
|
-
status: 308,
|
|
907
|
-
headers: { Location: match.redirect },
|
|
908
|
-
});
|
|
909
|
-
}
|
|
910
|
-
|
|
911
|
-
const root = renderSegments(match.segments, {
|
|
912
|
-
rootLayout: router.rootLayout,
|
|
913
|
-
});
|
|
914
|
-
|
|
915
|
-
const payload: RscPayload = {
|
|
916
|
-
root,
|
|
917
|
-
metadata: {
|
|
918
|
-
pathname: url.pathname,
|
|
919
|
-
segments: match.segments,
|
|
920
|
-
matched: match.matched,
|
|
921
|
-
diff: match.diff,
|
|
922
|
-
isPartial: false,
|
|
923
|
-
rootLayout: router.rootLayout,
|
|
924
|
-
handles: handleStore.stream(),
|
|
925
|
-
version,
|
|
926
|
-
themeConfig: router.themeConfig,
|
|
927
|
-
warmupEnabled: router.warmupEnabled,
|
|
928
|
-
initialTheme: requireRequestContext().theme,
|
|
929
|
-
},
|
|
930
|
-
formState: actionResult,
|
|
931
|
-
};
|
|
932
|
-
|
|
933
|
-
const rscStream = renderToReadableStream<RscPayload>(payload);
|
|
934
|
-
const ssrModule = await loadSSRModule();
|
|
935
|
-
const htmlStream = await ssrModule.renderHTML(rscStream, {
|
|
936
|
-
formState: reactFormState,
|
|
937
|
-
nonce,
|
|
938
|
-
});
|
|
939
|
-
|
|
940
|
-
return new Response(htmlStream, {
|
|
941
|
-
headers: { "content-type": "text/html;charset=utf-8" },
|
|
942
|
-
});
|
|
943
|
-
}
|
|
944
|
-
|
|
945
|
-
// ============================================================================
|
|
946
|
-
// SERVER ACTION HANDLER
|
|
947
|
-
// ============================================================================
|
|
948
|
-
async function handleServerAction(
|
|
949
|
-
request: Request,
|
|
950
|
-
env: TEnv,
|
|
951
|
-
url: URL,
|
|
952
|
-
actionId: string,
|
|
953
|
-
handleStore: ReturnType<typeof requireRequestContext>["_handleStore"],
|
|
954
|
-
): Promise<Response> {
|
|
955
|
-
const temporaryReferences = createTemporaryReferenceSet();
|
|
956
|
-
|
|
957
|
-
// Decode action arguments from request body
|
|
958
|
-
const contentType = request.headers.get("content-type") || "";
|
|
959
|
-
let args: unknown[] = [];
|
|
960
|
-
let actionFormData: FormData | undefined;
|
|
961
|
-
|
|
962
|
-
try {
|
|
963
|
-
const body = contentType.includes("multipart/form-data")
|
|
964
|
-
? await request.formData()
|
|
965
|
-
: await request.text();
|
|
966
|
-
|
|
967
|
-
if (body instanceof FormData) {
|
|
968
|
-
actionFormData = body;
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
if (hasBodyContent(body)) {
|
|
972
|
-
args = await decodeReply(body, { temporaryReferences });
|
|
973
|
-
}
|
|
974
|
-
} catch (error) {
|
|
975
|
-
callOnError(error, "action", {
|
|
976
|
-
request,
|
|
977
|
-
url,
|
|
978
|
-
env,
|
|
979
|
-
actionId,
|
|
980
|
-
handledByBoundary: false,
|
|
981
|
-
});
|
|
982
|
-
throw new Error(`Failed to decode action arguments: ${error}`, {
|
|
983
|
-
cause: error,
|
|
984
|
-
});
|
|
985
|
-
}
|
|
986
|
-
|
|
987
|
-
// Execute the server action
|
|
988
|
-
let returnValue: { ok: boolean; data: unknown };
|
|
989
|
-
let actionStatus = 200;
|
|
990
|
-
let loadedAction: Function | undefined;
|
|
991
|
-
|
|
992
|
-
try {
|
|
993
|
-
loadedAction = await loadServerAction(actionId);
|
|
994
|
-
const data = await loadedAction!.apply(null, args);
|
|
995
|
-
returnValue = { ok: true, data };
|
|
996
|
-
} catch (error) {
|
|
997
|
-
returnValue = { ok: false, data: error };
|
|
998
|
-
actionStatus = 500;
|
|
999
|
-
|
|
1000
|
-
// Try to render error boundary
|
|
1001
|
-
const errorResult = await router.matchError(request, env, error, "route");
|
|
1002
|
-
|
|
1003
|
-
// Report the action error (handledByBoundary indicates if error boundary will render)
|
|
1004
|
-
callOnError(error, "action", {
|
|
1005
|
-
request,
|
|
1006
|
-
url,
|
|
1007
|
-
env,
|
|
1008
|
-
actionId,
|
|
1009
|
-
handledByBoundary: !!errorResult,
|
|
1010
|
-
});
|
|
1011
|
-
|
|
1012
|
-
if (errorResult) {
|
|
1013
|
-
setRequestContextParams(errorResult.params);
|
|
1014
|
-
|
|
1015
|
-
const payload: RscPayload = {
|
|
1016
|
-
root: null,
|
|
1017
|
-
metadata: {
|
|
1018
|
-
pathname: url.pathname,
|
|
1019
|
-
segments: errorResult.segments,
|
|
1020
|
-
isPartial: true,
|
|
1021
|
-
matched: errorResult.matched,
|
|
1022
|
-
diff: errorResult.diff,
|
|
1023
|
-
isError: true,
|
|
1024
|
-
handles: handleStore.stream(),
|
|
1025
|
-
version,
|
|
1026
|
-
},
|
|
1027
|
-
returnValue,
|
|
1028
|
-
};
|
|
1029
|
-
|
|
1030
|
-
const rscStream = renderToReadableStream<RscPayload>(payload, {
|
|
1031
|
-
temporaryReferences,
|
|
1032
|
-
});
|
|
1033
|
-
|
|
1034
|
-
return createResponseWithMergedHeaders(rscStream, {
|
|
1035
|
-
status: actionStatus,
|
|
1036
|
-
headers: { "content-type": "text/x-component;charset=utf-8" },
|
|
1037
|
-
});
|
|
1038
|
-
}
|
|
1039
|
-
}
|
|
1040
|
-
|
|
1041
|
-
// Revalidate after action
|
|
1042
|
-
const resolvedActionId =
|
|
1043
|
-
(loadedAction as { $id?: string; $$id?: string } | undefined)?.$id ??
|
|
1044
|
-
(loadedAction as { $$id?: string } | undefined)?.$$id ??
|
|
1045
|
-
actionId;
|
|
1046
|
-
const actionContext = {
|
|
1047
|
-
actionId: resolvedActionId,
|
|
1048
|
-
actionUrl: new URL(request.url),
|
|
1049
|
-
actionResult: returnValue.data,
|
|
1050
|
-
formData: actionFormData,
|
|
1051
|
-
};
|
|
1052
|
-
|
|
1053
|
-
const matchResult = await router.matchPartial(request, env, actionContext);
|
|
1054
|
-
|
|
1055
|
-
if (!matchResult) {
|
|
1056
|
-
// Fall back to full render
|
|
1057
|
-
const fullMatch = await router.match(request, env);
|
|
1058
|
-
setRequestContextParams(fullMatch.params);
|
|
1059
|
-
|
|
1060
|
-
if (fullMatch.redirect) {
|
|
1061
|
-
return createResponseWithMergedHeaders(null, {
|
|
1062
|
-
status: 308,
|
|
1063
|
-
headers: { Location: fullMatch.redirect },
|
|
1064
|
-
});
|
|
1065
|
-
}
|
|
1066
|
-
|
|
1067
|
-
const renderStart = performance.now();
|
|
1068
|
-
const root = renderSegments(fullMatch.segments, {
|
|
1069
|
-
rootLayout: router.rootLayout,
|
|
1070
|
-
isAction: true,
|
|
1071
|
-
});
|
|
1072
|
-
const renderDuration = performance.now() - renderStart;
|
|
1073
|
-
const serverTiming = fullMatch.serverTiming
|
|
1074
|
-
? `${fullMatch.serverTiming}, rendering;dur=${renderDuration.toFixed(2)}`
|
|
1075
|
-
: `rendering;dur=${renderDuration.toFixed(2)}`;
|
|
1076
|
-
|
|
1077
|
-
const payload: RscPayload = {
|
|
1078
|
-
root,
|
|
1079
|
-
metadata: {
|
|
1080
|
-
pathname: url.pathname,
|
|
1081
|
-
segments: fullMatch.segments,
|
|
1082
|
-
matched: fullMatch.matched,
|
|
1083
|
-
diff: fullMatch.diff,
|
|
1084
|
-
handles: handleStore.stream(),
|
|
1085
|
-
version,
|
|
1086
|
-
},
|
|
1087
|
-
returnValue,
|
|
1088
|
-
};
|
|
1089
|
-
|
|
1090
|
-
const rscStream = renderToReadableStream<RscPayload>(payload, {
|
|
1091
|
-
temporaryReferences,
|
|
1092
|
-
});
|
|
1093
|
-
|
|
1094
|
-
const headers: Record<string, string> = {
|
|
1095
|
-
"content-type": "text/x-component;charset=utf-8",
|
|
1096
|
-
};
|
|
1097
|
-
if (serverTiming) {
|
|
1098
|
-
headers["Server-Timing"] = serverTiming;
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
return createResponseWithMergedHeaders(rscStream, {
|
|
1102
|
-
status: actionStatus,
|
|
1103
|
-
headers,
|
|
1104
|
-
});
|
|
1105
|
-
}
|
|
1106
|
-
|
|
1107
|
-
// Return updated segments
|
|
1108
|
-
setRequestContextParams(matchResult.params);
|
|
1109
|
-
|
|
1110
|
-
const renderStart = performance.now();
|
|
1111
|
-
|
|
1112
|
-
const renderDuration = performance.now() - renderStart;
|
|
1113
|
-
const serverTiming = matchResult.serverTiming
|
|
1114
|
-
? `${matchResult.serverTiming}, rendering;dur=${renderDuration.toFixed(2)}`
|
|
1115
|
-
: `rendering;dur=${renderDuration.toFixed(2)}`;
|
|
1116
|
-
|
|
1117
|
-
const payload: RscPayload = {
|
|
1118
|
-
root: null,
|
|
1119
|
-
metadata: {
|
|
1120
|
-
pathname: url.pathname,
|
|
1121
|
-
segments: matchResult.segments,
|
|
1122
|
-
isPartial: true,
|
|
1123
|
-
matched: matchResult.matched,
|
|
1124
|
-
diff: matchResult.diff,
|
|
1125
|
-
slots: matchResult.slots,
|
|
1126
|
-
handles: handleStore.stream(),
|
|
1127
|
-
version,
|
|
1128
|
-
},
|
|
1129
|
-
returnValue,
|
|
1130
|
-
};
|
|
1131
|
-
|
|
1132
|
-
const rscStream = renderToReadableStream<RscPayload>(payload, {
|
|
1133
|
-
temporaryReferences,
|
|
1134
|
-
});
|
|
1135
|
-
|
|
1136
|
-
const actionHeaders: Record<string, string> = {
|
|
1137
|
-
"content-type": "text/x-component;charset=utf-8",
|
|
1138
|
-
};
|
|
1139
|
-
if (serverTiming) {
|
|
1140
|
-
actionHeaders["Server-Timing"] = serverTiming;
|
|
1141
|
-
}
|
|
1142
|
-
|
|
1143
|
-
return createResponseWithMergedHeaders(rscStream, {
|
|
1144
|
-
status: actionStatus,
|
|
1145
|
-
headers: actionHeaders,
|
|
1146
|
-
});
|
|
1147
|
-
}
|
|
1148
|
-
|
|
1149
|
-
// ============================================================================
|
|
1150
|
-
// LOADER FETCH HANDLER
|
|
1151
|
-
// Supports GET (params in query string) and POST/PUT/PATCH/DELETE (JSON body)
|
|
1152
|
-
// ============================================================================
|
|
1153
|
-
async function handleLoaderFetch(
|
|
1154
|
-
request: Request,
|
|
1155
|
-
env: TEnv,
|
|
1156
|
-
url: URL,
|
|
1157
|
-
variables: Record<string, any>,
|
|
1158
|
-
): Promise<Response> {
|
|
1159
|
-
const loaderId = url.searchParams.get("_rsc_loader");
|
|
1160
|
-
|
|
1161
|
-
if (!loaderId) {
|
|
1162
|
-
return createResponseWithMergedHeaders("Missing _rsc_loader parameter", {
|
|
1163
|
-
status: 400,
|
|
1164
|
-
});
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
// Look up loader lazily
|
|
1168
|
-
const registeredLoader = await getLoaderLazy(loaderId);
|
|
1169
|
-
if (!registeredLoader) {
|
|
1170
|
-
return createResponseWithMergedHeaders(
|
|
1171
|
-
`Loader "${loaderId}" not found in registry`,
|
|
1172
|
-
{ status: 404 },
|
|
1173
|
-
);
|
|
1174
|
-
}
|
|
1175
|
-
|
|
1176
|
-
// Parse params and body based on request method
|
|
1177
|
-
let loaderParams: Record<string, string> = {};
|
|
1178
|
-
let loaderBody: unknown = undefined;
|
|
1179
|
-
const isBodyMethod = request.method !== "GET" && request.method !== "HEAD";
|
|
1180
|
-
|
|
1181
|
-
if (isBodyMethod) {
|
|
1182
|
-
try {
|
|
1183
|
-
const contentType = request.headers.get("content-type") || "";
|
|
1184
|
-
if (contentType.includes("application/json")) {
|
|
1185
|
-
const jsonBody = (await request.json()) as {
|
|
1186
|
-
params?: Record<string, string>;
|
|
1187
|
-
body?: unknown;
|
|
1188
|
-
};
|
|
1189
|
-
loaderParams = jsonBody.params ?? {};
|
|
1190
|
-
loaderBody = jsonBody.body;
|
|
1191
|
-
}
|
|
1192
|
-
} catch {
|
|
1193
|
-
return createResponseWithMergedHeaders("Invalid JSON body", {
|
|
1194
|
-
status: 400,
|
|
1195
|
-
});
|
|
1196
|
-
}
|
|
1197
|
-
} else {
|
|
1198
|
-
const loaderParamsJson = url.searchParams.get("_rsc_loader_params");
|
|
1199
|
-
if (loaderParamsJson) {
|
|
1200
|
-
try {
|
|
1201
|
-
loaderParams = JSON.parse(loaderParamsJson);
|
|
1202
|
-
} catch {
|
|
1203
|
-
return createResponseWithMergedHeaders(
|
|
1204
|
-
"Invalid _rsc_loader_params JSON",
|
|
1205
|
-
{ status: 400 },
|
|
1206
|
-
);
|
|
1207
|
-
}
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1210
|
-
|
|
1211
|
-
// Execute the loader with middleware
|
|
1212
|
-
try {
|
|
1213
|
-
const { fn, middleware } = registeredLoader;
|
|
1214
|
-
|
|
1215
|
-
return await executeLoaderMiddleware(
|
|
1216
|
-
middleware,
|
|
1217
|
-
request,
|
|
1218
|
-
env,
|
|
1219
|
-
loaderParams,
|
|
1220
|
-
variables,
|
|
1221
|
-
async () => {
|
|
1222
|
-
const ctx = requireRequestContext();
|
|
1223
|
-
const loaderCtx: any = {
|
|
1224
|
-
...ctx,
|
|
1225
|
-
params: loaderParams,
|
|
1226
|
-
body: loaderBody,
|
|
1227
|
-
};
|
|
1228
|
-
|
|
1229
|
-
const result = await fn(loaderCtx);
|
|
1230
|
-
|
|
1231
|
-
interface LoaderPayload {
|
|
1232
|
-
loaderResult: unknown;
|
|
1233
|
-
}
|
|
1234
|
-
const loaderPayload: LoaderPayload = { loaderResult: result };
|
|
1235
|
-
const rscStream =
|
|
1236
|
-
renderToReadableStream<LoaderPayload>(loaderPayload);
|
|
1237
|
-
|
|
1238
|
-
return createResponseWithMergedHeaders(rscStream, {
|
|
1239
|
-
headers: { "content-type": "text/x-component;charset=utf-8" },
|
|
1240
|
-
});
|
|
1241
|
-
},
|
|
1242
|
-
);
|
|
1243
|
-
} catch (error) {
|
|
1244
|
-
const err = error instanceof Error ? error : new Error(String(error));
|
|
1245
|
-
const isDev = process.env.NODE_ENV !== "production";
|
|
1246
|
-
|
|
1247
|
-
console.error("[RSC] Loader error:", error);
|
|
1248
|
-
|
|
1249
|
-
callOnError(error, "loader", {
|
|
1250
|
-
request,
|
|
1251
|
-
url,
|
|
1252
|
-
env,
|
|
1253
|
-
loaderName: loaderId,
|
|
1254
|
-
handledByBoundary: false,
|
|
1255
|
-
});
|
|
1256
|
-
|
|
1257
|
-
const errorPayload = {
|
|
1258
|
-
loaderResult: null,
|
|
1259
|
-
loaderError: {
|
|
1260
|
-
message: isDev ? err.message : "An error occurred",
|
|
1261
|
-
name: err.name,
|
|
1262
|
-
},
|
|
1263
|
-
};
|
|
1264
|
-
const rscStream = renderToReadableStream(errorPayload);
|
|
1265
|
-
|
|
1266
|
-
return createResponseWithMergedHeaders(rscStream, {
|
|
1267
|
-
status: 500,
|
|
1268
|
-
headers: { "content-type": "text/x-component;charset=utf-8" },
|
|
1269
|
-
});
|
|
1270
|
-
}
|
|
1271
|
-
}
|
|
1272
|
-
|
|
1273
|
-
// ============================================================================
|
|
1274
|
-
// RSC RENDERING HANDLER (Navigation)
|
|
1275
|
-
// ============================================================================
|
|
1276
|
-
async function handleRscRendering(
|
|
1277
|
-
request: Request,
|
|
1278
|
-
env: TEnv,
|
|
1279
|
-
url: URL,
|
|
1280
|
-
isPartial: boolean,
|
|
1281
|
-
handleStore: ReturnType<typeof requireRequestContext>["_handleStore"],
|
|
1282
|
-
nonce: string | undefined,
|
|
1283
|
-
): Promise<Response> {
|
|
1284
|
-
// Retrieve handler-level timing from variables
|
|
1285
|
-
const reqCtx = requireRequestContext();
|
|
1286
|
-
const handlerTimingArr: string[] = reqCtx.var.__handlerTiming || [];
|
|
1287
|
-
const handlerStart: number = reqCtx.var.__handlerStart || 0;
|
|
1288
|
-
|
|
1289
|
-
let payload: RscPayload;
|
|
1290
|
-
let serverTiming: string | undefined;
|
|
1291
|
-
|
|
1292
|
-
if (isPartial) {
|
|
1293
|
-
// Partial render (navigation)
|
|
1294
|
-
const result = await router.matchPartial(request, env);
|
|
1295
|
-
|
|
1296
|
-
if (!result) {
|
|
1297
|
-
// Fall back to full render
|
|
1298
|
-
const match = await router.match(request, env);
|
|
1299
|
-
setRequestContextParams(match.params);
|
|
1300
|
-
|
|
1301
|
-
if (match.redirect) {
|
|
1302
|
-
return createResponseWithMergedHeaders(null, {
|
|
1303
|
-
status: 308,
|
|
1304
|
-
headers: { Location: match.redirect },
|
|
1305
|
-
});
|
|
1306
|
-
}
|
|
1307
|
-
|
|
1308
|
-
const renderStart = performance.now();
|
|
1309
|
-
const root = renderSegments(match.segments, {
|
|
1310
|
-
rootLayout: router.rootLayout,
|
|
1311
|
-
});
|
|
1312
|
-
const renderDuration = performance.now() - renderStart;
|
|
1313
|
-
serverTiming = match.serverTiming
|
|
1314
|
-
? `${match.serverTiming}, rendering;dur=${renderDuration.toFixed(2)}`
|
|
1315
|
-
: `rendering;dur=${renderDuration.toFixed(2)}`;
|
|
1316
|
-
|
|
1317
|
-
payload = {
|
|
1318
|
-
root,
|
|
1319
|
-
metadata: {
|
|
1320
|
-
pathname: url.pathname,
|
|
1321
|
-
segments: match.segments,
|
|
1322
|
-
matched: match.matched,
|
|
1323
|
-
diff: match.diff,
|
|
1324
|
-
isPartial: false,
|
|
1325
|
-
handles: handleStore.stream(),
|
|
1326
|
-
version,
|
|
1327
|
-
themeConfig: router.themeConfig,
|
|
1328
|
-
initialTheme: reqCtx.theme,
|
|
1329
|
-
},
|
|
1330
|
-
};
|
|
1331
|
-
} else {
|
|
1332
|
-
setRequestContextParams(result.params);
|
|
1333
|
-
serverTiming = result.serverTiming;
|
|
1334
|
-
|
|
1335
|
-
payload = {
|
|
1336
|
-
root: null,
|
|
1337
|
-
metadata: {
|
|
1338
|
-
pathname: url.pathname,
|
|
1339
|
-
segments: result.segments,
|
|
1340
|
-
matched: result.matched,
|
|
1341
|
-
diff: result.diff,
|
|
1342
|
-
isPartial: true,
|
|
1343
|
-
slots: result.slots,
|
|
1344
|
-
handles: handleStore.stream(),
|
|
1345
|
-
version,
|
|
1346
|
-
},
|
|
1347
|
-
};
|
|
1348
|
-
}
|
|
1349
|
-
} else {
|
|
1350
|
-
// Full render (initial page load)
|
|
1351
|
-
const match = await router.match(request, env);
|
|
1352
|
-
setRequestContextParams(match.params);
|
|
1353
|
-
|
|
1354
|
-
if (match.redirect) {
|
|
1355
|
-
return createResponseWithMergedHeaders(null, {
|
|
1356
|
-
status: 308,
|
|
1357
|
-
headers: { Location: match.redirect },
|
|
1358
|
-
});
|
|
1359
|
-
}
|
|
1360
|
-
|
|
1361
|
-
// Caching is now handled in router.match() via cache provider in request context
|
|
1362
|
-
// match.segments already contains cached or fresh segments as appropriate
|
|
1363
|
-
|
|
1364
|
-
if (url.searchParams.has("__prerender_collect")) {
|
|
1365
|
-
// Build-time prerender collection: serialize segments and handle data
|
|
1366
|
-
// to JSON for storage as build artifacts. At runtime the worker
|
|
1367
|
-
// deserializes these and feeds them through the normal segment pipeline.
|
|
1368
|
-
const nonLoaderSegments = match.segments.filter((s) => s.type !== "loader");
|
|
1369
|
-
await handleStore.settled;
|
|
1370
|
-
const { serializeSegments } = await import("../cache/cache-scope.js");
|
|
1371
|
-
const serializedSegments = await serializeSegments(nonLoaderSegments);
|
|
1372
|
-
const handles: Record<string, Record<string, unknown[]>> = {};
|
|
1373
|
-
for (const seg of nonLoaderSegments) {
|
|
1374
|
-
const segHandles = handleStore.getDataForSegment(seg.id);
|
|
1375
|
-
if (Object.keys(segHandles).length > 0) {
|
|
1376
|
-
handles[seg.id] = segHandles;
|
|
1377
|
-
}
|
|
1378
|
-
}
|
|
1379
|
-
return new Response(
|
|
1380
|
-
JSON.stringify({
|
|
1381
|
-
segments: serializedSegments,
|
|
1382
|
-
handles,
|
|
1383
|
-
routeName: match.routeName,
|
|
1384
|
-
params: match.params,
|
|
1385
|
-
}),
|
|
1386
|
-
{ headers: { "Content-Type": "application/json" } },
|
|
1387
|
-
);
|
|
1388
|
-
} else {
|
|
1389
|
-
const renderStart = performance.now();
|
|
1390
|
-
const root = renderSegments(match.segments, {
|
|
1391
|
-
rootLayout: router.rootLayout,
|
|
1392
|
-
});
|
|
1393
|
-
const renderDuration = performance.now() - renderStart;
|
|
1394
|
-
serverTiming = match.serverTiming
|
|
1395
|
-
? `${match.serverTiming}, rendering;dur=${renderDuration.toFixed(2)}`
|
|
1396
|
-
: `rendering;dur=${renderDuration.toFixed(2)}`;
|
|
1397
|
-
|
|
1398
|
-
payload = {
|
|
1399
|
-
root,
|
|
1400
|
-
metadata: {
|
|
1401
|
-
pathname: url.pathname,
|
|
1402
|
-
segments: match.segments,
|
|
1403
|
-
matched: match.matched,
|
|
1404
|
-
diff: match.diff,
|
|
1405
|
-
isPartial: false,
|
|
1406
|
-
rootLayout: router.rootLayout,
|
|
1407
|
-
handles: handleStore.stream(),
|
|
1408
|
-
version,
|
|
1409
|
-
themeConfig: router.themeConfig,
|
|
1410
|
-
initialTheme: reqCtx.theme,
|
|
1411
|
-
},
|
|
1412
|
-
};
|
|
1413
|
-
}
|
|
1414
|
-
}
|
|
1415
|
-
|
|
1416
|
-
// Serialize to RSC stream
|
|
1417
|
-
const rscSerializeStart = performance.now();
|
|
1418
|
-
const rscStream = renderToReadableStream<RscPayload>(payload);
|
|
1419
|
-
const rscSerializeDur = performance.now() - rscSerializeStart;
|
|
1420
|
-
|
|
1421
|
-
// Determine if this is an RSC request or HTML request
|
|
1422
|
-
const isRscRequest =
|
|
1423
|
-
(!request.headers.get("accept")?.includes("text/html") &&
|
|
1424
|
-
!url.searchParams.has("__html")) ||
|
|
1425
|
-
url.searchParams.has("__rsc");
|
|
1426
|
-
|
|
1427
|
-
// Build complete Server-Timing: handler phases + match/manifest + rendering + RSC serialize
|
|
1428
|
-
const timingParts: string[] = [...handlerTimingArr];
|
|
1429
|
-
if (serverTiming) {
|
|
1430
|
-
timingParts.push(serverTiming);
|
|
1431
|
-
}
|
|
1432
|
-
timingParts.push(`rsc-serialize;dur=${rscSerializeDur.toFixed(2)}`);
|
|
1433
|
-
|
|
1434
|
-
if (isRscRequest) {
|
|
1435
|
-
const fullTiming = timingParts.join(", ");
|
|
1436
|
-
const rscHeaders: Record<string, string> = {
|
|
1437
|
-
"content-type": "text/x-component;charset=utf-8",
|
|
1438
|
-
vary: "accept",
|
|
1439
|
-
};
|
|
1440
|
-
if (fullTiming) {
|
|
1441
|
-
rscHeaders["Server-Timing"] = fullTiming;
|
|
1442
|
-
}
|
|
1443
|
-
return createResponseWithMergedHeaders(rscStream, {
|
|
1444
|
-
headers: rscHeaders,
|
|
1445
|
-
});
|
|
1446
|
-
}
|
|
1447
|
-
|
|
1448
|
-
// Delegate to SSR for HTML response
|
|
1449
|
-
const ssrModuleStart = performance.now();
|
|
1450
|
-
const ssrModule = await loadSSRModule();
|
|
1451
|
-
const ssrModuleDur = performance.now() - ssrModuleStart;
|
|
1452
|
-
timingParts.push(`ssr-module-load;dur=${ssrModuleDur.toFixed(2)}`);
|
|
1453
|
-
|
|
1454
|
-
const ssrRenderStart = performance.now();
|
|
1455
|
-
const htmlStream = await ssrModule.renderHTML(rscStream, { nonce });
|
|
1456
|
-
const ssrRenderDur = performance.now() - ssrRenderStart;
|
|
1457
|
-
timingParts.push(`ssr-render-html;dur=${ssrRenderDur.toFixed(2)}`);
|
|
1458
|
-
|
|
1459
|
-
// Add total handler duration
|
|
1460
|
-
if (handlerStart) {
|
|
1461
|
-
const totalHandler = performance.now() - handlerStart;
|
|
1462
|
-
timingParts.push(`handler-total;dur=${totalHandler.toFixed(2)}`);
|
|
1463
|
-
}
|
|
1464
|
-
|
|
1465
|
-
const fullTiming = timingParts.join(", ");
|
|
1466
|
-
const htmlHeaders: Record<string, string> = {
|
|
1467
|
-
"content-type": "text/html;charset=utf-8",
|
|
1468
|
-
};
|
|
1469
|
-
if (fullTiming) {
|
|
1470
|
-
htmlHeaders["Server-Timing"] = fullTiming;
|
|
1471
|
-
}
|
|
1472
|
-
|
|
1473
|
-
return createResponseWithMergedHeaders(htmlStream, {
|
|
1474
|
-
headers: htmlHeaders,
|
|
1475
|
-
});
|
|
1476
|
-
}
|
|
1477
1089
|
}
|