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