@rangojs/router 0.0.0-experimental.14 → 0.0.0-experimental.140
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 +17 -0
- package/README.md +432 -7
- package/dist/bin/rango.js +2073 -213
- package/dist/testing/vitest.js +82 -0
- package/dist/vite/index.js +7258 -2714
- package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
- package/package.json +140 -67
- package/skills/api-client/SKILL.md +211 -0
- package/skills/breadcrumbs/SKILL.md +329 -0
- package/skills/bundle-analysis/SKILL.md +159 -0
- package/skills/cache-guide/SKILL.md +487 -0
- package/skills/caching/SKILL.md +357 -25
- package/skills/comparison/SKILL.md +50 -0
- package/skills/comparison/agents/openai.yaml +4 -0
- package/skills/comparison/references/framework-comparison.md +837 -0
- package/skills/composability/SKILL.md +246 -0
- package/skills/css/SKILL.md +76 -0
- package/skills/debug-manifest/SKILL.md +16 -10
- package/skills/document-cache/SKILL.md +87 -62
- package/skills/fonts/SKILL.md +6 -4
- package/skills/handler-use/SKILL.md +364 -0
- package/skills/hooks/SKILL.md +557 -79
- package/skills/host-router/SKILL.md +320 -0
- package/skills/i18n/SKILL.md +276 -0
- package/skills/intercept/SKILL.md +207 -15
- package/skills/layout/SKILL.md +146 -6
- package/skills/links/SKILL.md +304 -25
- package/skills/loader/SKILL.md +616 -54
- package/skills/middleware/SKILL.md +217 -37
- package/skills/migrate-nextjs/SKILL.md +611 -0
- package/skills/migrate-react-router/SKILL.md +927 -0
- package/skills/mime-routes/SKILL.md +42 -11
- package/skills/observability/SKILL.md +194 -0
- package/skills/parallel/SKILL.md +284 -3
- package/skills/ppr/SKILL.md +426 -0
- package/skills/prerender/SKILL.md +437 -52
- package/skills/rango/SKILL.md +369 -22
- package/skills/react-compiler/SKILL.md +168 -0
- package/skills/response-routes/SKILL.md +263 -121
- package/skills/route/SKILL.md +350 -21
- package/skills/router-setup/SKILL.md +246 -33
- package/skills/scripts/SKILL.md +179 -0
- package/skills/server-actions/SKILL.md +775 -0
- package/skills/shell-manifest/SKILL.md +185 -0
- package/skills/streams-and-websockets/SKILL.md +283 -0
- package/skills/tailwind/SKILL.md +27 -3
- package/skills/testing/SKILL.md +126 -222
- package/skills/testing/bindings.md +103 -0
- package/skills/testing/cache-prerender.md +127 -0
- package/skills/testing/client-components.md +124 -0
- package/skills/testing/e2e-parity.md +125 -0
- package/skills/testing/flight.md +91 -0
- package/skills/testing/handles.md +131 -0
- package/skills/testing/loader.md +128 -0
- package/skills/testing/middleware.md +99 -0
- package/skills/testing/render-handler.md +122 -0
- package/skills/testing/response-routes.md +95 -0
- package/skills/testing/reverse-and-types.md +85 -0
- package/skills/testing/server-actions.md +107 -0
- package/skills/testing/server-tree.md +128 -0
- package/skills/testing/setup.md +123 -0
- package/skills/theme/SKILL.md +9 -8
- package/skills/typesafety/SKILL.md +532 -103
- package/skills/use-cache/SKILL.md +367 -0
- package/skills/vercel/SKILL.md +128 -0
- package/skills/view-transitions/SKILL.md +337 -0
- package/src/__augment-tests__/augment.ts +81 -0
- package/src/__augment-tests__/augmented.check.ts +116 -0
- package/src/__internal.ts +77 -44
- package/src/bin/rango.ts +312 -15
- package/src/browser/action-coordinator.ts +114 -0
- package/src/browser/action-fence.ts +47 -0
- package/src/browser/app-shell.ts +39 -0
- package/src/browser/app-version.ts +14 -0
- package/src/browser/connection-warmup.ts +134 -0
- package/src/browser/cookie-name.ts +140 -0
- package/src/browser/event-controller.ts +293 -202
- package/src/browser/history-state.ts +101 -0
- package/src/browser/index.ts +3 -3
- package/src/browser/intercept-utils.ts +52 -0
- package/src/browser/invalidate-client-cache.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 +385 -576
- package/src/browser/navigation-client.ts +245 -75
- package/src/browser/navigation-store-handle.ts +38 -0
- package/src/browser/navigation-store.ts +184 -118
- package/src/browser/navigation-transaction.ts +247 -0
- package/src/browser/network-error-handler.ts +88 -0
- package/src/browser/partial-update.ts +412 -364
- package/src/browser/prefetch/cache.ts +359 -0
- package/src/browser/prefetch/fetch.ts +452 -0
- package/src/browser/prefetch/observer.ts +65 -0
- package/src/browser/prefetch/policy.ts +48 -0
- package/src/browser/prefetch/queue.ts +209 -0
- package/src/browser/prefetch/resource-ready.ts +77 -0
- package/src/browser/rango-state.ts +194 -0
- package/src/browser/react/Link.tsx +275 -68
- package/src/browser/react/NavigationProvider.tsx +265 -109
- package/src/browser/react/ScrollRestoration.tsx +10 -6
- package/src/browser/react/context.ts +11 -0
- package/src/browser/react/filter-segment-order.ts +70 -0
- package/src/browser/react/index.ts +0 -48
- package/src/browser/react/location-state-shared.ts +272 -60
- package/src/browser/react/location-state.ts +90 -20
- 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 +35 -66
- package/src/browser/react/use-handle.ts +39 -126
- package/src/browser/react/use-href.tsx +8 -1
- package/src/browser/react/use-link-status.ts +39 -13
- package/src/browser/react/use-navigation.ts +53 -69
- package/src/browser/react/use-params.ts +75 -0
- package/src/browser/react/use-pathname.ts +47 -0
- package/src/browser/react/use-reverse.ts +106 -0
- package/src/browser/react/use-router.ts +98 -0
- package/src/browser/react/use-search-params.ts +51 -0
- package/src/browser/react/use-segments.ts +72 -99
- package/src/browser/response-adapter.ts +164 -0
- package/src/browser/rsc-router.tsx +300 -72
- package/src/browser/scroll-restoration.ts +138 -50
- package/src/browser/segment-reconciler.ts +243 -0
- package/src/browser/segment-structure-assert.ts +17 -1
- package/src/browser/server-action-bridge.ts +668 -613
- package/src/browser/types.ts +223 -51
- package/src/browser/validate-redirect-origin.ts +56 -0
- package/src/build/collect-fallback-refs.ts +107 -0
- package/src/build/generate-manifest.ts +252 -161
- package/src/build/generate-route-types.ts +41 -1038
- package/src/build/index.ts +12 -7
- package/src/build/prefix-tree-utils.ts +123 -0
- package/src/build/route-trie.ts +225 -42
- package/src/build/route-types/ast-helpers.ts +25 -0
- package/src/build/route-types/ast-route-extraction.ts +105 -0
- package/src/build/route-types/codegen.ts +113 -0
- package/src/build/route-types/include-resolution.ts +812 -0
- package/src/build/route-types/param-extraction.ts +51 -0
- package/src/build/route-types/per-module-writer.ts +144 -0
- package/src/build/route-types/router-processing.ts +695 -0
- package/src/build/route-types/scan-filter.ts +85 -0
- package/src/build/route-types/source-scan.ts +216 -0
- package/src/build/runtime-discovery.ts +223 -0
- package/src/cache/background-task.ts +34 -0
- package/src/cache/cache-error.ts +104 -0
- package/src/cache/cache-key-utils.ts +60 -0
- package/src/cache/cache-policy.ts +199 -0
- package/src/cache/cache-runtime.ts +525 -0
- package/src/cache/cache-scope.ts +298 -332
- package/src/cache/cache-tag.ts +103 -0
- package/src/cache/cf/cf-base64.ts +33 -0
- package/src/cache/cf/cf-cache-constants.ts +127 -0
- package/src/cache/cf/cf-cache-store.ts +2500 -158
- package/src/cache/cf/cf-cache-types.ts +349 -0
- package/src/cache/cf/cf-kv-utils.ts +46 -0
- package/src/cache/cf/cf-tag-marker-memo.ts +105 -0
- package/src/cache/cf/index.ts +17 -17
- package/src/cache/document-cache.ts +199 -92
- package/src/cache/handle-capture.ts +81 -0
- package/src/cache/handle-snapshot.ts +111 -0
- package/src/cache/index.ts +29 -35
- package/src/cache/memory-segment-store.ts +363 -30
- package/src/cache/profile-registry.ts +88 -0
- package/src/cache/read-through-swr.ts +178 -0
- package/src/cache/segment-codec.ts +248 -0
- package/src/cache/shell-cache.ts +386 -0
- package/src/cache/tag-invalidation.ts +230 -0
- package/src/cache/taint.ts +153 -0
- package/src/cache/types.ts +156 -211
- package/src/cache/vercel/index.ts +11 -0
- package/src/cache/vercel/vercel-cache-store.ts +1102 -0
- package/src/client.rsc.tsx +43 -21
- package/src/client.tsx +131 -347
- package/src/cloudflare/index.ts +11 -0
- package/src/cloudflare/tracing.ts +109 -0
- package/src/component-utils.ts +23 -4
- package/src/components/DefaultDocument.tsx +13 -3
- package/src/context-var.ts +168 -0
- package/src/debug.ts +19 -9
- package/src/decode-loader-results.ts +52 -0
- package/src/defer.ts +185 -0
- package/src/deps/ssr.ts +0 -1
- package/src/encode-kv.ts +49 -0
- package/src/errors.ts +106 -10
- package/src/escape-script.ts +52 -0
- package/src/handle.ts +110 -35
- package/src/handles/MetaTags.tsx +83 -59
- package/src/handles/Scripts.tsx +183 -0
- package/src/handles/breadcrumbs.ts +93 -0
- package/src/handles/deferred-resolution.ts +127 -0
- package/src/handles/is-thenable.ts +18 -0
- package/src/handles/meta.ts +44 -53
- package/src/handles/script.ts +244 -0
- package/src/host/cookie-handler.ts +20 -65
- package/src/host/errors.ts +21 -30
- package/src/host/index.ts +13 -9
- package/src/host/pattern-matcher.ts +50 -79
- package/src/host/router.ts +151 -121
- package/src/host/testing.ts +45 -32
- package/src/host/types.ts +52 -11
- package/src/host/utils.ts +2 -2
- package/src/href-client.ts +192 -57
- package/src/index.rsc.ts +177 -35
- package/src/index.ts +255 -71
- package/src/internal-debug.ts +9 -2
- package/src/loader-store.ts +500 -0
- package/src/loader.rsc.ts +31 -99
- package/src/loader.ts +30 -12
- package/src/missing-id-error.ts +68 -0
- package/src/outlet-context.ts +1 -1
- package/src/outlet-provider.tsx +41 -0
- package/src/prerender/param-hash.ts +16 -14
- package/src/prerender/store.ts +121 -21
- package/src/prerender.ts +460 -26
- package/src/redirect-origin.ts +100 -0
- package/src/regex-escape.ts +8 -0
- package/src/render-error-thrower.tsx +20 -0
- package/src/response-utils.ts +62 -0
- package/src/reverse.ts +198 -128
- package/src/root-error-boundary.tsx +42 -48
- package/src/route-content-wrapper.tsx +22 -77
- package/src/route-definition/dsl-helpers.ts +1116 -0
- package/src/route-definition/helper-factories.ts +88 -0
- package/src/route-definition/helpers-types.ts +505 -0
- package/src/route-definition/index.ts +54 -0
- package/src/route-definition/redirect.ts +134 -0
- package/src/route-definition/resolve-handler-use.ts +160 -0
- package/src/route-definition/use-item-types.ts +29 -0
- package/src/route-definition.ts +1 -1481
- package/src/route-map-builder.ts +82 -144
- package/src/route-name.ts +53 -0
- package/src/route-types.ts +71 -45
- package/src/router/basename.ts +14 -0
- package/src/router/content-negotiation.ts +263 -0
- package/src/router/debug-manifest.ts +72 -0
- package/src/router/error-handling.ts +54 -27
- package/src/router/find-match.ts +245 -0
- package/src/router/handler-context.ts +377 -125
- package/src/router/instrument.ts +350 -0
- package/src/router/intercept-resolution.ts +59 -28
- package/src/router/lazy-includes.ts +254 -0
- package/src/router/loader-resolution.ts +421 -157
- package/src/router/logging.ts +106 -6
- package/src/router/manifest.ts +131 -57
- package/src/router/match-api.ts +167 -246
- package/src/router/match-context.ts +4 -24
- package/src/router/match-handlers.ts +440 -0
- package/src/router/match-middleware/background-revalidation.ts +117 -93
- package/src/router/match-middleware/cache-lookup.ts +297 -150
- package/src/router/match-middleware/cache-store.ts +123 -51
- package/src/router/match-middleware/intercept-resolution.ts +44 -43
- package/src/router/match-middleware/segment-resolution.ts +64 -22
- package/src/router/match-pipelines.ts +11 -87
- package/src/router/match-result.ts +121 -50
- package/src/router/metrics.ts +219 -28
- package/src/router/middleware-types.ts +93 -0
- package/src/router/middleware.ts +505 -441
- package/src/router/navigation-snapshot.ts +133 -0
- package/src/router/params-util.ts +23 -0
- package/src/router/parse-pattern.ts +115 -0
- package/src/router/pattern-matching.ts +311 -142
- package/src/router/prefetch-cache-ttl.ts +51 -0
- package/src/router/prefetch-limits.ts +37 -0
- package/src/router/prerender-match.ts +547 -0
- package/src/router/preview-match.ts +102 -0
- package/src/router/request-classification.ts +278 -0
- package/src/router/revalidation.ts +203 -62
- package/src/router/route-snapshot.ts +246 -0
- package/src/router/router-context.ts +45 -48
- package/src/router/router-interfaces.ts +554 -0
- package/src/router/router-options.ts +779 -0
- package/src/router/router-registry.ts +21 -0
- package/src/router/segment-resolution/fresh.ts +772 -0
- package/src/router/segment-resolution/helpers.ts +348 -0
- package/src/router/segment-resolution/loader-cache.ts +250 -0
- package/src/router/segment-resolution/loader-mask.ts +44 -0
- package/src/router/segment-resolution/revalidation.ts +1331 -0
- package/src/router/segment-resolution/static-store.ts +81 -0
- package/src/router/segment-resolution/streamed-handler-telemetry.ts +52 -0
- package/src/router/segment-resolution/view-transition-default.ts +56 -0
- package/src/router/segment-resolution.ts +25 -1354
- package/src/router/segment-wrappers.ts +292 -0
- package/src/router/state-cookie-name.ts +33 -0
- package/src/router/substitute-pattern-params.ts +75 -0
- package/src/router/telemetry-otel.ts +261 -0
- package/src/router/telemetry.ts +377 -0
- package/src/router/timeout.ts +128 -0
- package/src/router/tracing.ts +206 -0
- package/src/router/trie-matching.ts +240 -61
- package/src/router/types.ts +23 -70
- package/src/router/url-params.ts +57 -0
- package/src/router.ts +781 -2378
- package/src/rsc/full-payload.ts +70 -0
- package/src/rsc/handler-context.ts +46 -0
- package/src/rsc/handler.ts +905 -1142
- package/src/rsc/helpers.ts +275 -19
- package/src/rsc/index.ts +2 -25
- package/src/rsc/json-route-result.ts +38 -0
- package/src/rsc/loader-fetch.ts +305 -0
- package/src/rsc/manifest-init.ts +77 -0
- package/src/rsc/nonce.ts +14 -0
- package/src/rsc/origin-guard.ts +155 -0
- package/src/rsc/progressive-enhancement.ts +502 -0
- package/src/rsc/redirect-guard.ts +99 -0
- package/src/rsc/response-cache-serve.ts +238 -0
- package/src/rsc/response-error.ts +104 -0
- package/src/rsc/response-route-handler.ts +257 -0
- package/src/rsc/rsc-rendering.ts +337 -0
- package/src/rsc/runtime-warnings.ts +55 -0
- package/src/rsc/server-action.ts +522 -0
- package/src/rsc/shell-capture.ts +439 -0
- package/src/rsc/ssr-setup.ts +144 -0
- package/src/rsc/transition-gate.ts +89 -0
- package/src/rsc/types.ts +95 -12
- package/src/runtime-env.ts +18 -0
- package/src/search-params.ts +99 -82
- package/src/segment-content-promise.ts +67 -0
- package/src/segment-loader-promise.ts +149 -0
- package/src/segment-system.tsx +349 -134
- package/src/serialize.ts +243 -0
- package/src/server/context.ts +452 -85
- package/src/server/cookie-parse.ts +32 -0
- package/src/server/cookie-store.ts +310 -0
- package/src/server/fetchable-loader-store.ts +11 -6
- package/src/server/handle-store.ts +123 -42
- package/src/server/live.ts +130 -0
- package/src/server/loader-registry.ts +51 -100
- package/src/server/request-context.ts +842 -157
- package/src/server.ts +15 -8
- package/src/ssr/index.tsx +412 -136
- package/src/ssr/ssr-root.tsx +228 -0
- package/src/static-handler.ts +45 -18
- package/src/testing/cache-status.ts +162 -0
- package/src/testing/collect-handle.ts +46 -0
- package/src/testing/dispatch.ts +701 -0
- package/src/testing/dom.entry.ts +22 -0
- package/src/testing/e2e/fixture.ts +188 -0
- package/src/testing/e2e/index.ts +128 -0
- package/src/testing/e2e/matchers.ts +35 -0
- package/src/testing/e2e/page-helpers.ts +272 -0
- package/src/testing/e2e/parity.ts +387 -0
- package/src/testing/e2e/server.ts +195 -0
- package/src/testing/flight-matchers.ts +97 -0
- package/src/testing/flight-normalize.ts +11 -0
- package/src/testing/flight-runtime.d.ts +57 -0
- package/src/testing/flight-tree.ts +682 -0
- package/src/testing/flight.entry.ts +52 -0
- package/src/testing/flight.ts +257 -0
- package/src/testing/generated-routes.ts +199 -0
- package/src/testing/index.ts +105 -0
- package/src/testing/internal/context.ts +371 -0
- package/src/testing/internal/flight-client-globals.ts +30 -0
- package/src/testing/internal/seed-vars.ts +54 -0
- package/src/testing/render-handler.ts +357 -0
- package/src/testing/render-route.tsx +584 -0
- package/src/testing/run-loader.ts +385 -0
- package/src/testing/run-middleware.ts +205 -0
- package/src/testing/run-transition-when.ts +164 -0
- package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
- package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
- package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
- package/src/testing/vitest-stubs/version.ts +5 -0
- package/src/testing/vitest.ts +305 -0
- package/src/theme/ThemeProvider.tsx +40 -72
- package/src/theme/ThemeScript.tsx +12 -14
- package/src/theme/constants.ts +57 -15
- package/src/theme/index.ts +3 -20
- package/src/theme/theme-context.ts +5 -35
- package/src/theme/theme-script.ts +43 -39
- package/src/theme/use-theme.ts +0 -3
- package/src/types/boundaries.ts +123 -0
- package/src/types/cache-types.ts +207 -0
- package/src/types/error-types.ts +132 -0
- package/src/types/global-namespace.ts +113 -0
- package/src/types/handler-context.ts +839 -0
- package/src/types/index.ts +81 -0
- package/src/types/loader-types.ts +212 -0
- package/src/types/request-scope.ts +112 -0
- package/src/types/route-config.ts +138 -0
- package/src/types/route-entry.ts +114 -0
- package/src/types/segments.ts +271 -0
- package/src/types.ts +1 -1795
- package/src/urls/include-helper.ts +162 -0
- package/src/urls/include-provider.ts +71 -0
- package/src/urls/index.ts +43 -0
- package/src/urls/path-helper-types.ts +413 -0
- package/src/urls/path-helper.ts +275 -0
- package/src/urls/pattern-types.ts +124 -0
- package/src/urls/response-types.ts +109 -0
- package/src/urls/type-extraction.ts +316 -0
- package/src/urls/urls-function.ts +80 -0
- package/src/urls.ts +1 -1341
- package/src/use-loader.tsx +406 -141
- package/src/vercel/index.ts +11 -0
- package/src/vercel/tracing.ts +88 -0
- package/src/vite/debug.ts +185 -0
- package/src/vite/discovery/bundle-postprocess.ts +182 -0
- package/src/vite/discovery/discover-routers.ts +389 -0
- package/src/vite/discovery/discovery-errors.ts +255 -0
- package/src/vite/discovery/gate-state.ts +171 -0
- package/src/vite/discovery/prerender-collection.ts +467 -0
- package/src/vite/discovery/route-types-writer.ts +214 -0
- package/src/vite/discovery/self-gen-tracking.ts +73 -0
- package/src/vite/discovery/state.ts +161 -0
- package/src/vite/discovery/virtual-module-codegen.ts +183 -0
- package/src/vite/index.ts +23 -2255
- package/src/vite/inject-client-debug.ts +36 -0
- package/src/vite/plugin-types.ts +303 -0
- package/src/vite/plugins/cjs-to-esm.ts +90 -0
- package/src/vite/plugins/client-ref-dedup.ts +120 -0
- package/src/vite/plugins/client-ref-hashing.ts +118 -0
- package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
- package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
- package/src/vite/plugins/cloudflare-protocol-stub.ts +194 -0
- package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +88 -110
- package/src/vite/{expose-id-utils.ts → plugins/expose-id-utils.ts} +89 -79
- package/src/vite/plugins/expose-ids/export-analysis.ts +363 -0
- package/src/vite/plugins/expose-ids/handler-transform.ts +130 -0
- package/src/vite/plugins/expose-ids/loader-transform.ts +64 -0
- package/src/vite/plugins/expose-ids/router-transform.ts +199 -0
- package/src/vite/plugins/expose-ids/types.ts +45 -0
- package/src/vite/plugins/expose-internal-ids.ts +805 -0
- package/src/vite/plugins/performance-tracks.ts +89 -0
- package/src/vite/plugins/refresh-cmd.ts +127 -0
- package/src/vite/plugins/use-cache-transform.ts +313 -0
- package/src/vite/plugins/vercel-output.ts +384 -0
- package/src/vite/plugins/version-injector.ts +94 -0
- package/src/vite/plugins/version-plugin.ts +263 -0
- package/src/vite/plugins/virtual-entries.ts +234 -0
- package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
- package/src/vite/rango.ts +560 -0
- package/src/vite/router-discovery.ts +1638 -0
- package/src/vite/{ast-handler-extract.ts → utils/ast-handler-extract.ts} +200 -37
- package/src/vite/utils/banner.ts +36 -0
- package/src/vite/utils/bundle-analysis.ts +132 -0
- package/src/vite/utils/client-chunks.ts +184 -0
- package/src/vite/utils/directive-prologue.ts +40 -0
- package/src/vite/utils/forward-user-plugins.ts +171 -0
- package/src/vite/utils/manifest-utils.ts +15 -0
- package/src/vite/utils/package-resolution.ts +89 -0
- package/src/vite/utils/prerender-utils.ts +249 -0
- package/src/vite/utils/shared-utils.ts +269 -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/react/use-client-cache.ts +0 -56
- package/src/browser/request-controller.ts +0 -164
- package/src/browser/shallow.ts +0 -35
- package/src/cache/memory-store.ts +0 -253
- package/src/handles/index.ts +0 -6
- package/src/href-context.ts +0 -33
- package/src/network-error-thrower.tsx +0 -21
- 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/package-resolution.ts +0 -125
- package/src/vite/virtual-entries.ts +0 -114
- /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,96 @@
|
|
|
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 { isRouteNotFoundError } from "../errors.js";
|
|
12
|
+
import { matchMiddleware, executeMiddleware } from "../router/middleware.js";
|
|
20
13
|
import {
|
|
21
14
|
runWithRequestContext,
|
|
22
15
|
setRequestContextParams,
|
|
23
|
-
|
|
16
|
+
getRequestContext,
|
|
17
|
+
_getRequestContext,
|
|
24
18
|
createRequestContext,
|
|
25
|
-
type ExecutionContext,
|
|
26
19
|
} from "../server/request-context.js";
|
|
27
20
|
import * as rscDeps from "@vitejs/plugin-rsc/rsc";
|
|
28
|
-
|
|
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 { guardOutgoingRedirect } from "./redirect-guard.js";
|
|
34
|
+
import { resolvedHandleStream } from "../handles/deferred-resolution.js";
|
|
35
|
+
import {
|
|
36
|
+
isWebSocketUpgradeResponse,
|
|
37
|
+
appendVaryAccept,
|
|
38
|
+
} from "../response-utils.js";
|
|
39
|
+
import {
|
|
40
|
+
handleResponseRoute,
|
|
41
|
+
type ResponseRouteMatch,
|
|
42
|
+
} from "./response-route-handler.js";
|
|
43
|
+
import { generateNonce, nonce as nonceToken } from "./nonce.js";
|
|
36
44
|
import { VERSION } from "@rangojs/router:version";
|
|
37
45
|
import type { ErrorPhase } from "../types.js";
|
|
46
|
+
import type { RouterRequestInput } from "../router/router-interfaces.js";
|
|
38
47
|
import { invokeOnError } from "../router/error-handling.js";
|
|
39
48
|
import {
|
|
40
|
-
|
|
49
|
+
createReverseFunction,
|
|
50
|
+
stripInternalParams,
|
|
51
|
+
} from "../router/handler-context.js";
|
|
52
|
+
import { contextSet } from "../context-var.js";
|
|
53
|
+
import {
|
|
41
54
|
hasCachedManifest,
|
|
42
|
-
setCachedManifest,
|
|
43
55
|
getRouteTrie,
|
|
44
|
-
setRouteTrie,
|
|
45
56
|
getPrecomputedEntries,
|
|
46
57
|
waitForManifestReady,
|
|
47
58
|
getRouterManifest,
|
|
48
59
|
getRouterTrie,
|
|
49
|
-
setRouterManifest,
|
|
50
|
-
setRouterTrie,
|
|
51
60
|
} 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
|
-
|
|
61
|
+
import type { HandlerContext } from "./handler-context.js";
|
|
62
|
+
import type { CacheErrorCategory } from "../cache/cache-error.js";
|
|
63
|
+
import type { SegmentCacheStore } from "../cache/types.js";
|
|
64
|
+
import { buildRouterTrieFromUrlpatterns } from "./manifest-init.js";
|
|
65
|
+
import { handleProgressiveEnhancement } from "./progressive-enhancement.js";
|
|
66
|
+
import {
|
|
67
|
+
executeServerAction,
|
|
68
|
+
revalidateAfterAction,
|
|
69
|
+
type ActionContinuation,
|
|
70
|
+
} from "./server-action.js";
|
|
71
|
+
import { handleLoaderFetch } from "./loader-fetch.js";
|
|
72
|
+
import {
|
|
73
|
+
checkRequestOrigin,
|
|
74
|
+
ORIGIN_CHECK_PHASE_BY_MODE,
|
|
75
|
+
} from "./origin-guard.js";
|
|
76
|
+
import { handleRscRendering } from "./rsc-rendering.js";
|
|
77
|
+
import {
|
|
78
|
+
withTimeout,
|
|
79
|
+
RouterTimeoutError,
|
|
80
|
+
createDefaultTimeoutResponse,
|
|
81
|
+
type TimeoutPhase,
|
|
82
|
+
} from "../router/timeout.js";
|
|
83
|
+
import {
|
|
84
|
+
createMetricsStore,
|
|
85
|
+
appendMetric,
|
|
86
|
+
buildMetricsTiming,
|
|
87
|
+
} from "../router/metrics.js";
|
|
88
|
+
import { observePhase, observeEvent, PHASES } from "../router/instrument.js";
|
|
89
|
+
import {
|
|
90
|
+
startSSRSetup,
|
|
91
|
+
getSSRSetup,
|
|
92
|
+
mayNeedSSR,
|
|
93
|
+
isRscRequest,
|
|
94
|
+
SSR_SETUP_VAR,
|
|
95
|
+
} from "./ssr-setup.js";
|
|
96
|
+
import {
|
|
97
|
+
classifyRequest,
|
|
98
|
+
type RequestPlan,
|
|
99
|
+
type ExecutableRequestPlan,
|
|
100
|
+
} from "../router/request-classification.js";
|
|
77
101
|
|
|
78
102
|
/**
|
|
79
103
|
* Create an RSC request handler.
|
|
@@ -108,12 +132,35 @@ function createResponseErrorPayload(error: unknown, isDev: boolean): ResponseErr
|
|
|
108
132
|
* });
|
|
109
133
|
* ```
|
|
110
134
|
*/
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Response that tells the client to do a full document navigation. Shared by
|
|
138
|
+
* the terminal reload plans (version-mismatch and app-switch): an empty 200
|
|
139
|
+
* carrying X-RSC-Reload, which the client turns into window.location.href.
|
|
140
|
+
*/
|
|
141
|
+
function createReloadResponse(reloadUrl: string) {
|
|
142
|
+
return createResponseWithMergedHeaders(null, {
|
|
143
|
+
status: 200,
|
|
144
|
+
headers: {
|
|
145
|
+
"X-RSC-Reload": reloadUrl,
|
|
146
|
+
"content-type": "text/x-component;charset=utf-8",
|
|
147
|
+
},
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
111
151
|
export function createRSCHandler<
|
|
112
152
|
TEnv = unknown,
|
|
113
153
|
TRoutes extends Record<string, string> = Record<string, string>,
|
|
114
154
|
>(options: CreateRSCHandlerOptions<TEnv, TRoutes>) {
|
|
115
155
|
const { router, version = VERSION, nonce: nonceProvider } = options;
|
|
116
156
|
|
|
157
|
+
// Handler-owned registry of explicit per-scope stores from cache({ store }).
|
|
158
|
+
// Lives in the closure so it is scoped per handler (multi-router deployments
|
|
159
|
+
// get separate registries) and accumulates every explicit store this handler
|
|
160
|
+
// resolves across requests. updateTag()/revalidateTag() iterate it to reach
|
|
161
|
+
// stores not covered by the app-level ctx._cacheStore.
|
|
162
|
+
const explicitTaggedStores = new Set<SegmentCacheStore>();
|
|
163
|
+
|
|
117
164
|
// Use provided deps or default to @vitejs/plugin-rsc/rsc exports
|
|
118
165
|
const deps = options.deps ?? rscDeps;
|
|
119
166
|
const {
|
|
@@ -125,33 +172,185 @@ export function createRSCHandler<
|
|
|
125
172
|
decodeFormState,
|
|
126
173
|
} = deps;
|
|
127
174
|
|
|
128
|
-
// Use provided loadSSRModule or default to vite RSC module loader
|
|
129
|
-
|
|
175
|
+
// Use provided loadSSRModule or default to vite RSC module loader.
|
|
176
|
+
// In production the SSR module is stable across requests, so memoize
|
|
177
|
+
// the dynamic import to avoid repeated module resolution overhead.
|
|
178
|
+
// In dev mode Vite may hot-reload the module, so skip memoization.
|
|
179
|
+
const rawLoadSSRModule: LoadSSRModule =
|
|
130
180
|
options.loadSSRModule ??
|
|
131
181
|
(() => import.meta.viteRsc.loadModule("ssr", "index"));
|
|
182
|
+
let _ssrModulePromise: Promise<SSRModule> | undefined;
|
|
183
|
+
const loadSSRModule: LoadSSRModule =
|
|
184
|
+
process.env.NODE_ENV === "production"
|
|
185
|
+
? () =>
|
|
186
|
+
(_ssrModulePromise ??= rawLoadSSRModule().catch((err) => {
|
|
187
|
+
_ssrModulePromise = undefined;
|
|
188
|
+
throw err;
|
|
189
|
+
}))
|
|
190
|
+
: rawLoadSSRModule;
|
|
132
191
|
|
|
133
192
|
/**
|
|
134
|
-
*
|
|
135
|
-
*
|
|
193
|
+
* Per-request error reporter that deduplicates via the ALS request context.
|
|
194
|
+
*
|
|
195
|
+
* Uses the same _reportedErrors WeakSet as the router layer so errors
|
|
196
|
+
* that propagate across layers are only reported once per request.
|
|
136
197
|
*/
|
|
137
198
|
function callOnError(
|
|
138
199
|
error: unknown,
|
|
139
200
|
phase: ErrorPhase,
|
|
140
201
|
context: Parameters<typeof invokeOnError<TEnv>>[3],
|
|
141
202
|
): void {
|
|
203
|
+
// Guard: abort signal handlers fire asynchronously outside the ALS
|
|
204
|
+
// request scope, so the context may be gone. Skip dedup in that
|
|
205
|
+
// case — the error is from a cancelled stream, not a real failure.
|
|
206
|
+
const reqCtx = _getRequestContext();
|
|
207
|
+
if (error != null && typeof error === "object" && reqCtx) {
|
|
208
|
+
if (reqCtx._reportedErrors.has(error)) return;
|
|
209
|
+
reqCtx._reportedErrors.add(error);
|
|
210
|
+
}
|
|
142
211
|
invokeOnError(router.onError, error, phase, context, "RSC");
|
|
143
212
|
}
|
|
144
213
|
|
|
145
|
-
|
|
214
|
+
function getRequiredRouteMap(): Record<string, string> {
|
|
215
|
+
const routeMap = getRouterManifest(router.id);
|
|
216
|
+
if (!routeMap) {
|
|
217
|
+
throw new Error(
|
|
218
|
+
`Route manifest for router "${router.id}" is not available.`,
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
return routeMap;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Handle a timeout by reporting the error, emitting telemetry,
|
|
226
|
+
* and returning either the custom onTimeout response or a default 504.
|
|
227
|
+
*/
|
|
228
|
+
async function handleTimeoutResponse(
|
|
146
229
|
request: Request,
|
|
147
|
-
env: TEnv
|
|
148
|
-
|
|
230
|
+
env: TEnv,
|
|
231
|
+
url: URL,
|
|
232
|
+
phase: TimeoutPhase,
|
|
233
|
+
durationMs: number,
|
|
234
|
+
routeKey?: string,
|
|
235
|
+
actionId?: string,
|
|
236
|
+
): Promise<Response> {
|
|
237
|
+
const timeoutError = new RouterTimeoutError(phase, durationMs);
|
|
238
|
+
|
|
239
|
+
callOnError(timeoutError, phase === "action" ? "action" : "handler", {
|
|
240
|
+
request,
|
|
241
|
+
url,
|
|
242
|
+
env,
|
|
243
|
+
routeKey,
|
|
244
|
+
actionId,
|
|
245
|
+
handledByBoundary: false,
|
|
246
|
+
metadata: { timeout: true, phase, durationMs },
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
observeEvent({
|
|
250
|
+
type: "request.timeout",
|
|
251
|
+
timestamp: performance.now(),
|
|
252
|
+
phase,
|
|
253
|
+
pathname: url.pathname,
|
|
254
|
+
routeKey,
|
|
255
|
+
actionId,
|
|
256
|
+
durationMs,
|
|
257
|
+
customHandler: !!router.onTimeout,
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
if (router.onTimeout) {
|
|
261
|
+
try {
|
|
262
|
+
return await router.onTimeout({
|
|
263
|
+
phase,
|
|
264
|
+
request,
|
|
265
|
+
url,
|
|
266
|
+
env,
|
|
267
|
+
routeKey,
|
|
268
|
+
actionId,
|
|
269
|
+
durationMs,
|
|
270
|
+
});
|
|
271
|
+
} catch (e) {
|
|
272
|
+
if (process.env.NODE_ENV !== "production") {
|
|
273
|
+
console.error("[RSC] onTimeout callback error:", e);
|
|
274
|
+
}
|
|
275
|
+
return createDefaultTimeoutResponse(phase);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
return createDefaultTimeoutResponse(phase);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Build a 200 Flight response that carries a redirect URL and optional state.
|
|
284
|
+
* Used when a partial/action request results in a redirect -- fetch
|
|
285
|
+
* auto-follows 3xx so we send the redirect as payload metadata instead.
|
|
286
|
+
*/
|
|
287
|
+
function createRedirectFlightResponse(
|
|
288
|
+
redirectUrl: string,
|
|
289
|
+
locationState?: Record<string, unknown>,
|
|
290
|
+
external?: boolean,
|
|
291
|
+
): Response {
|
|
292
|
+
const redirectPayload: RscPayload = {
|
|
293
|
+
metadata: {
|
|
294
|
+
pathname: redirectUrl,
|
|
295
|
+
segments: [],
|
|
296
|
+
redirect: { url: redirectUrl, ...(external && { external: true }) },
|
|
297
|
+
...(locationState && { locationState }),
|
|
298
|
+
},
|
|
299
|
+
};
|
|
300
|
+
const rscStream = renderToReadableStream<RscPayload>(redirectPayload, {
|
|
301
|
+
onError: (error: unknown) => {
|
|
302
|
+
const reqCtx = _getRequestContext<TEnv>();
|
|
303
|
+
if (!reqCtx) return;
|
|
304
|
+
callOnError(error, "rendering", {
|
|
305
|
+
request: reqCtx.request,
|
|
306
|
+
url: reqCtx.url,
|
|
307
|
+
env: reqCtx.env,
|
|
308
|
+
});
|
|
309
|
+
},
|
|
310
|
+
});
|
|
311
|
+
return createResponseWithMergedHeaders(rscStream, {
|
|
312
|
+
status: 200,
|
|
313
|
+
headers: { "content-type": "text/x-component;charset=utf-8" },
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// Bundle shared dependencies for extracted handler functions.
|
|
318
|
+
// callOnError reads from ALS so it's inherently per-request scoped.
|
|
319
|
+
const handlerCtx: HandlerContext<TEnv> = {
|
|
320
|
+
router,
|
|
321
|
+
version,
|
|
322
|
+
renderToReadableStream,
|
|
323
|
+
decodeReply,
|
|
324
|
+
createTemporaryReferenceSet,
|
|
325
|
+
loadServerAction,
|
|
326
|
+
decodeAction,
|
|
327
|
+
decodeFormState,
|
|
328
|
+
loadSSRModule,
|
|
329
|
+
callOnError,
|
|
330
|
+
getRequiredRouteMap,
|
|
331
|
+
createRedirectFlightResponse,
|
|
332
|
+
resolveStreamMode: async (request, env, url) => {
|
|
333
|
+
const resolver = router.ssr?.resolveStreaming;
|
|
334
|
+
if (!resolver) return "stream";
|
|
335
|
+
return resolver({ request, env, url });
|
|
149
336
|
},
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
return async function handler(
|
|
340
|
+
request: Request,
|
|
341
|
+
input: RouterRequestInput<TEnv> = {},
|
|
150
342
|
): Promise<Response> {
|
|
151
343
|
const handlerStart = performance.now();
|
|
344
|
+
// Create the metrics store at handler start so handler:total has startTime=0
|
|
345
|
+
// and all metrics are relative to the request entry point.
|
|
346
|
+
const earlyMetricsStore = router.debugPerformance
|
|
347
|
+
? createMetricsStore(true, handlerStart)
|
|
348
|
+
: undefined;
|
|
349
|
+
|
|
350
|
+
const { env = {} as TEnv, vars: initialVars, ctx: executionCtx } = input;
|
|
152
351
|
|
|
153
352
|
// Connection warmup: return 204 immediately before any processing
|
|
154
|
-
if (router
|
|
353
|
+
if (router?.warmupEnabled && request.method === "HEAD") {
|
|
155
354
|
const warmupUrl = new URL(request.url);
|
|
156
355
|
if (warmupUrl.searchParams.has("_rsc_warmup")) {
|
|
157
356
|
return new Response(null, { status: 204 });
|
|
@@ -175,24 +374,27 @@ export function createRSCHandler<
|
|
|
175
374
|
const mwMatchDur = performance.now() - mwMatchStart;
|
|
176
375
|
|
|
177
376
|
// Shared variables between middleware and route handlers
|
|
178
|
-
// Initialize from
|
|
179
|
-
const variables: Record<string, any> =
|
|
180
|
-
|
|
181
|
-
|
|
377
|
+
// Initialize from input.vars if provided (allows pre-seeding from worker entry)
|
|
378
|
+
const variables: Record<string, any> = initialVars
|
|
379
|
+
? { ...initialVars }
|
|
380
|
+
: {};
|
|
182
381
|
|
|
183
|
-
// Store nonce
|
|
382
|
+
// Store nonce via ContextVar token and string key for backward compat
|
|
184
383
|
if (nonce) {
|
|
384
|
+
contextSet(variables, nonceToken, nonce);
|
|
185
385
|
variables.nonce = nonce;
|
|
186
386
|
}
|
|
187
387
|
|
|
188
388
|
// Resolve cache store configuration
|
|
189
389
|
// Priority: options.cache (handler override) > router.cache (router default)
|
|
190
390
|
// Store is enabled only if: config provided, enabled, and no ?__no_cache query param
|
|
191
|
-
let cacheStore
|
|
391
|
+
let cacheStore: SegmentCacheStore | undefined;
|
|
192
392
|
const cacheOption = options.cache ?? router.cache;
|
|
193
393
|
if (cacheOption && !url.searchParams.has("__no_cache")) {
|
|
194
394
|
const cacheConfig =
|
|
195
|
-
typeof cacheOption === "function"
|
|
395
|
+
typeof cacheOption === "function"
|
|
396
|
+
? cacheOption(env, executionCtx)
|
|
397
|
+
: cacheOption;
|
|
196
398
|
|
|
197
399
|
if (cacheConfig.enabled !== false) {
|
|
198
400
|
cacheStore = cacheConfig.store;
|
|
@@ -223,56 +425,7 @@ export function createRSCHandler<
|
|
|
223
425
|
// Cloudflare dev: generate manifest inline for this router.
|
|
224
426
|
// Each router generates its own manifest independently so
|
|
225
427
|
// 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 });
|
|
428
|
+
await buildRouterTrieFromUrlpatterns(router);
|
|
276
429
|
}
|
|
277
430
|
if (!getRouterManifest(router.id) && !hasCachedManifest()) {
|
|
278
431
|
throw new Error(
|
|
@@ -280,10 +433,17 @@ export function createRSCHandler<
|
|
|
280
433
|
);
|
|
281
434
|
}
|
|
282
435
|
}
|
|
283
|
-
const manifestCacheDur = performance.now() - manifestCacheStart;
|
|
284
436
|
|
|
285
|
-
//
|
|
286
|
-
// This
|
|
437
|
+
// Rebuild the trie when the manifest exists but the per-router trie is
|
|
438
|
+
// missing. This happens in dev mode after HMR: the virtual module sets
|
|
439
|
+
// the manifest (from fresh gen files) but the trie is intentionally not
|
|
440
|
+
// injected to avoid stale discovery-time data. Without the trie, route
|
|
441
|
+
// matching falls back to regex iteration which does not handle wildcard
|
|
442
|
+
// priority correctly (catch-all patterns match before specific routes).
|
|
443
|
+
if (!getRouterTrie(router.id) && router.urlpatterns) {
|
|
444
|
+
await buildRouterTrieFromUrlpatterns(router);
|
|
445
|
+
}
|
|
446
|
+
const manifestCacheDur = performance.now() - manifestCacheStart;
|
|
287
447
|
|
|
288
448
|
// Create unified request context with all methods
|
|
289
449
|
// Includes: stub response, handle store, loader memoization, use(), cookies, headers, cache store
|
|
@@ -295,9 +455,30 @@ export function createRSCHandler<
|
|
|
295
455
|
url,
|
|
296
456
|
variables,
|
|
297
457
|
cacheStore,
|
|
298
|
-
|
|
458
|
+
explicitTaggedStores,
|
|
459
|
+
cacheProfiles: router.cacheProfiles,
|
|
460
|
+
executionContext: executionCtx,
|
|
299
461
|
themeConfig: router.themeConfig,
|
|
462
|
+
stateCookieName: router.resolvedStateCookieName,
|
|
463
|
+
version,
|
|
300
464
|
});
|
|
465
|
+
if (earlyMetricsStore) {
|
|
466
|
+
requestContext._debugPerformance = true;
|
|
467
|
+
requestContext._metricsStore = earlyMetricsStore;
|
|
468
|
+
}
|
|
469
|
+
// Wire background error reporting so "use cache" and other subsystems
|
|
470
|
+
// can surface non-fatal errors through the router's onError callback.
|
|
471
|
+
requestContext._reportBackgroundError = (
|
|
472
|
+
error: unknown,
|
|
473
|
+
category: CacheErrorCategory,
|
|
474
|
+
) => {
|
|
475
|
+
callOnError(error, "cache", {
|
|
476
|
+
request,
|
|
477
|
+
url,
|
|
478
|
+
metadata: { category },
|
|
479
|
+
});
|
|
480
|
+
};
|
|
481
|
+
|
|
301
482
|
const ctxCreateDur = performance.now() - ctxCreateStart;
|
|
302
483
|
|
|
303
484
|
// Accumulate handler-level timing for Server-Timing header
|
|
@@ -319,296 +500,132 @@ export function createRSCHandler<
|
|
|
319
500
|
// - Server components during rendering
|
|
320
501
|
// - Error boundaries
|
|
321
502
|
// - Streaming
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
url: URL,
|
|
348
|
-
variables: Record<string, any>,
|
|
349
|
-
nonce: string | undefined,
|
|
350
|
-
): Promise<Response> {
|
|
351
|
-
// First, check for route-level middleware
|
|
352
|
-
const previewStart = performance.now();
|
|
353
|
-
const preview = await router.previewMatch(request, env);
|
|
354
|
-
const previewDur = performance.now() - previewStart;
|
|
355
|
-
const handlerTiming: string[] = variables.__handlerTiming || [];
|
|
356
|
-
handlerTiming.push(`handler-preview-match;dur=${previewDur.toFixed(2)}`);
|
|
357
|
-
// Response route short-circuit: skip entire RSC pipeline
|
|
358
|
-
if (preview?.responseType && preview.handler) {
|
|
359
|
-
const isPartial = url.searchParams.has("_rsc_partial");
|
|
360
|
-
|
|
361
|
-
// Partial requests (client-side navigation) to response routes
|
|
362
|
-
// get X-RSC-Reload to trigger hard navigation in the browser
|
|
363
|
-
if (isPartial) {
|
|
364
|
-
const cleanUrl = new URL(url);
|
|
365
|
-
cleanUrl.searchParams.delete("_rsc_partial");
|
|
366
|
-
cleanUrl.searchParams.delete("_rsc_segments");
|
|
367
|
-
cleanUrl.searchParams.delete("_rsc_v");
|
|
368
|
-
cleanUrl.searchParams.delete("_rsc_stale");
|
|
369
|
-
cleanUrl.searchParams.delete("_rsc_action");
|
|
370
|
-
cleanUrl.searchParams.delete("_rsc_prev");
|
|
371
|
-
|
|
372
|
-
return createResponseWithMergedHeaders(null, {
|
|
373
|
-
status: 200,
|
|
374
|
-
headers: {
|
|
375
|
-
"X-RSC-Reload": cleanUrl.toString(),
|
|
376
|
-
"content-type": "text/x-component;charset=utf-8",
|
|
377
|
-
},
|
|
378
|
-
});
|
|
379
|
-
}
|
|
503
|
+
// Store basename on request context (scoped per-request via existing ALS)
|
|
504
|
+
requestContext._basename = router.basename;
|
|
505
|
+
|
|
506
|
+
// Resolved span tracing for this request (read at each traced phase).
|
|
507
|
+
requestContext._tracing = router.tracing;
|
|
508
|
+
|
|
509
|
+
// The "rango.request" span is opened inside the request context so the
|
|
510
|
+
// Cloudflare runner can read executionContext.tracing, and so every nested
|
|
511
|
+
// phase span (and the platform's automatic KV/D1/fetch spans) nests under
|
|
512
|
+
// it. Construction-bound: the span ends when the Response is built, never
|
|
513
|
+
// wrapping the streamed body. metric:false — handler:total is metered
|
|
514
|
+
// directly below (a grand total incl. the pre-context bootstrap timings).
|
|
515
|
+
// When tracing is off this is a direct pass-through.
|
|
516
|
+
return runWithRequestContext(requestContext, () =>
|
|
517
|
+
observePhase(PHASES.request, async (span) => {
|
|
518
|
+
span.setAttribute("http.method", request.method);
|
|
519
|
+
// The matched route template is not known until match() runs later, so
|
|
520
|
+
// emit the concrete path as url.path (low-level), NOT http.route — the
|
|
521
|
+
// latter is reserved for the low-cardinality template (OTel convention).
|
|
522
|
+
span.setAttribute("url.path", url.pathname);
|
|
523
|
+
|
|
524
|
+
// Core handler logic (wrapped by middleware)
|
|
525
|
+
const coreHandler = async (): Promise<Response> => {
|
|
526
|
+
return coreRequestHandler(request, env, url, variables, nonce);
|
|
527
|
+
};
|
|
380
528
|
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
if (name.startsWith("/")) {
|
|
393
|
-
if (!hrefParams) return name;
|
|
394
|
-
return name.replace(/:([^/]+)/g, (_, key) => {
|
|
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
|
-
};
|
|
529
|
+
// Execute middleware chain if any, otherwise call core handler directly
|
|
530
|
+
let response: Response;
|
|
531
|
+
if (matchedMiddleware.length > 0) {
|
|
532
|
+
const mwResponse = await executeMiddleware(
|
|
533
|
+
matchedMiddleware,
|
|
534
|
+
request,
|
|
535
|
+
env,
|
|
536
|
+
variables,
|
|
537
|
+
coreHandler,
|
|
538
|
+
createReverseFunction(getRequiredRouteMap()),
|
|
539
|
+
);
|
|
406
540
|
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
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" } },
|
|
541
|
+
if (
|
|
542
|
+
url.searchParams.has("_rsc_partial") ||
|
|
543
|
+
url.searchParams.has("_rsc_action")
|
|
544
|
+
) {
|
|
545
|
+
const intercepted = interceptRedirectForPartial(
|
|
546
|
+
mwResponse,
|
|
547
|
+
createRedirectFlightResponse,
|
|
435
548
|
);
|
|
549
|
+
response = intercepted ?? finalizeResponse(mwResponse);
|
|
550
|
+
} else {
|
|
551
|
+
response = finalizeResponse(mwResponse);
|
|
436
552
|
}
|
|
553
|
+
} else {
|
|
554
|
+
response = await coreHandler();
|
|
437
555
|
}
|
|
438
556
|
|
|
439
|
-
//
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
{ status: 200, headers: { "content-type": "application/xml;charset=utf-8" } },
|
|
472
|
-
);
|
|
473
|
-
case "md":
|
|
474
|
-
return createResponseWithMergedHeaders(
|
|
475
|
-
String(result),
|
|
476
|
-
{ status: 200, headers: { "content-type": "text/markdown;charset=utf-8" } },
|
|
477
|
-
);
|
|
478
|
-
default:
|
|
479
|
-
// image, stream, any -- must return Response
|
|
480
|
-
throw new Error(
|
|
481
|
-
`Response route handler for "${preview.responseType}" must return a Response object, got ${typeof result}`
|
|
482
|
-
);
|
|
483
|
-
}
|
|
484
|
-
} catch (error) {
|
|
485
|
-
callOnError(error, "handler", errorCtx);
|
|
486
|
-
const isDev = process.env.NODE_ENV !== "production";
|
|
487
|
-
const status = error instanceof RouterError ? error.status : 500;
|
|
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" },
|
|
496
|
-
});
|
|
557
|
+
// Finalize metrics after all middleware (including post-next work)
|
|
558
|
+
// has completed so :post spans are captured in the timeline.
|
|
559
|
+
// Handler timing parts are always emitted (even without debug metrics)
|
|
560
|
+
// so non-debug requests still get bootstrap Server-Timing entries.
|
|
561
|
+
const handlerTimingArr: string[] = variables.__handlerTiming || [];
|
|
562
|
+
// Preserve any existing Server-Timing set by response routes or middleware
|
|
563
|
+
const existingTiming = response.headers.get("Server-Timing");
|
|
564
|
+
const timingParts = existingTiming
|
|
565
|
+
? [existingTiming, ...handlerTimingArr]
|
|
566
|
+
: [...handlerTimingArr];
|
|
567
|
+
|
|
568
|
+
const metricsStore = requestContext._metricsStore;
|
|
569
|
+
if (metricsStore) {
|
|
570
|
+
// When the store was created at handler start (earlyMetricsStore),
|
|
571
|
+
// handler:total covers the full request. When ctx.debugPerformance()
|
|
572
|
+
// created the store mid-request, use its requestStart to avoid a
|
|
573
|
+
// negative startTime offset.
|
|
574
|
+
const totalStart = earlyMetricsStore
|
|
575
|
+
? handlerStart
|
|
576
|
+
: metricsStore.requestStart;
|
|
577
|
+
appendMetric(
|
|
578
|
+
metricsStore,
|
|
579
|
+
"handler:total",
|
|
580
|
+
totalStart,
|
|
581
|
+
performance.now() - totalStart,
|
|
582
|
+
);
|
|
583
|
+
const metricsTiming = buildMetricsTiming(
|
|
584
|
+
request.method,
|
|
585
|
+
url.pathname,
|
|
586
|
+
metricsStore,
|
|
587
|
+
);
|
|
588
|
+
if (metricsTiming) timingParts.push(metricsTiming);
|
|
497
589
|
}
|
|
498
|
-
};
|
|
499
590
|
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
if (preview.negotiated) {
|
|
504
|
-
response.headers.append("Vary", "Accept");
|
|
591
|
+
const fullTiming = timingParts.join(", ");
|
|
592
|
+
if (fullTiming && !isWebSocketUpgradeResponse(response)) {
|
|
593
|
+
response.headers.set("Server-Timing", fullTiming);
|
|
505
594
|
}
|
|
506
|
-
return response;
|
|
507
|
-
};
|
|
508
|
-
|
|
509
|
-
if (preview.routeMiddleware && preview.routeMiddleware.length > 0) {
|
|
510
|
-
const middlewareEntries = preview.routeMiddleware.map((mw) => ({
|
|
511
|
-
entry: {
|
|
512
|
-
pattern: null,
|
|
513
|
-
regex: null,
|
|
514
|
-
paramNames: [],
|
|
515
|
-
handler: mw.handler,
|
|
516
|
-
mountPrefix: null,
|
|
517
|
-
},
|
|
518
|
-
params: mw.params,
|
|
519
|
-
}));
|
|
520
|
-
return executeMiddleware(middlewareEntries, request, env, variables, callHandlerWithVary);
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
return callHandlerWithVary();
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
// Wrap RSC handler to append Vary: Accept on content-negotiated routes
|
|
527
|
-
const rscHandler = async () => {
|
|
528
|
-
const response = await coreRequestHandlerInner(request, env, url, variables, nonce);
|
|
529
|
-
if (preview?.negotiated) {
|
|
530
|
-
response.headers.append("Vary", "Accept");
|
|
531
|
-
}
|
|
532
|
-
return response;
|
|
533
|
-
};
|
|
534
|
-
|
|
535
|
-
if (preview?.routeMiddleware && preview.routeMiddleware.length > 0) {
|
|
536
|
-
// Convert route middleware to app middleware format for execution
|
|
537
|
-
const middlewareEntries = preview.routeMiddleware.map((mw) => ({
|
|
538
|
-
entry: {
|
|
539
|
-
pattern: null,
|
|
540
|
-
regex: null,
|
|
541
|
-
paramNames: [],
|
|
542
|
-
handler: mw.handler,
|
|
543
|
-
mountPrefix: null,
|
|
544
|
-
},
|
|
545
|
-
params: mw.params,
|
|
546
|
-
}));
|
|
547
|
-
|
|
548
|
-
// Execute route middleware wrapping the actual request handling
|
|
549
|
-
return executeMiddleware(middlewareEntries, request, env, variables, rscHandler);
|
|
550
|
-
}
|
|
551
595
|
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
596
|
+
// Single open-redirect chokepoint: every response (PE, full-page,
|
|
597
|
+
// middleware short-circuit, response-route) funnels through here, so
|
|
598
|
+
// guarding browser-followed (3xx) redirects once covers them all and any
|
|
599
|
+
// future redirect exit. Soft SPA/Flight redirects are 200/204 and pass
|
|
600
|
+
// through untouched (validated client-side instead).
|
|
601
|
+
return guardOutgoingRedirect(response, url.origin, router.basename);
|
|
602
|
+
}),
|
|
603
|
+
);
|
|
604
|
+
};
|
|
555
605
|
|
|
556
|
-
//
|
|
557
|
-
|
|
606
|
+
// Core request handling logic (separated for middleware wrapping).
|
|
607
|
+
// Uses the classify → execute model: classifyRequest produces a RequestPlan,
|
|
608
|
+
// then execution dispatches on the plan mode.
|
|
609
|
+
async function coreRequestHandler(
|
|
558
610
|
request: Request,
|
|
559
611
|
env: TEnv,
|
|
560
612
|
url: URL,
|
|
561
613
|
variables: Record<string, any>,
|
|
562
614
|
nonce: string | undefined,
|
|
563
615
|
): Promise<Response> {
|
|
564
|
-
const
|
|
565
|
-
const isAction =
|
|
566
|
-
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
|
-
|
|
570
|
-
// Version mismatch detection - client may have stale code after HMR/deployment
|
|
571
|
-
// If versions don't match, tell the client to reload
|
|
572
|
-
const clientVersion = url.searchParams.get("_rsc_v");
|
|
573
|
-
if (version && clientVersion && clientVersion !== version) {
|
|
574
|
-
console.log(
|
|
575
|
-
`[RSC] Version mismatch: client=${clientVersion}, server=${version}. Forcing reload.`,
|
|
576
|
-
);
|
|
616
|
+
const handlerTiming: string[] = variables.__handlerTiming || [];
|
|
577
617
|
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
cleanUrl.searchParams.delete("_rsc_partial");
|
|
581
|
-
cleanUrl.searchParams.delete("_rsc_segments");
|
|
582
|
-
cleanUrl.searchParams.delete("_rsc_v");
|
|
583
|
-
cleanUrl.searchParams.delete("_rsc_stale");
|
|
584
|
-
cleanUrl.searchParams.delete("_rsc_action");
|
|
585
|
-
cleanUrl.searchParams.delete("_rsc_prev");
|
|
586
|
-
|
|
587
|
-
// For actions, reload current page (referer)
|
|
588
|
-
// For navigation, load the target URL
|
|
589
|
-
const reloadUrl = isAction
|
|
590
|
-
? request.headers.get("referer") || cleanUrl.toString()
|
|
591
|
-
: cleanUrl.toString();
|
|
592
|
-
|
|
593
|
-
// Return special response that tells client to reload
|
|
594
|
-
return createResponseWithMergedHeaders(null, {
|
|
595
|
-
status: 200,
|
|
596
|
-
headers: {
|
|
597
|
-
"X-RSC-Reload": reloadUrl,
|
|
598
|
-
"content-type": "text/x-component;charset=utf-8",
|
|
599
|
-
},
|
|
600
|
-
});
|
|
601
|
-
}
|
|
602
|
-
// Debug manifest endpoint: ?__debug_manifest on any route.
|
|
603
|
-
// Always available in dev, requires allowDebugManifest option in production.
|
|
618
|
+
// Debug manifest endpoint: handled before classification since it
|
|
619
|
+
// doesn't need a route match and needs trie access from the closure.
|
|
604
620
|
const isDev = process.env.NODE_ENV !== "production";
|
|
605
621
|
if (
|
|
606
622
|
url.searchParams.has("__debug_manifest") &&
|
|
607
623
|
(isDev || router.allowDebugManifest)
|
|
608
624
|
) {
|
|
609
625
|
const trie = getRouterTrie(router.id) ?? getRouteTrie();
|
|
610
|
-
const routeManifest =
|
|
611
|
-
const { extractAncestryFromTrie } =
|
|
626
|
+
const routeManifest = getRequiredRouteMap();
|
|
627
|
+
const { extractAncestryFromTrie } =
|
|
628
|
+
await import("../build/route-trie.js");
|
|
612
629
|
return new Response(
|
|
613
630
|
JSON.stringify(
|
|
614
631
|
{
|
|
@@ -627,851 +644,597 @@ export function createRSCHandler<
|
|
|
627
644
|
);
|
|
628
645
|
}
|
|
629
646
|
|
|
630
|
-
//
|
|
631
|
-
|
|
632
|
-
|
|
647
|
+
// ---- 1. Classify ----
|
|
648
|
+
// classifyRequest may throw RouteNotFoundError for unknown routes.
|
|
649
|
+
// In that case, fall through to a full-render plan so the pipeline
|
|
650
|
+
// can render the 404 page via the existing error handling path.
|
|
651
|
+
const classifyStart = performance.now();
|
|
652
|
+
let plan: RequestPlan<TEnv>;
|
|
633
653
|
try {
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
654
|
+
plan = await classifyRequest<TEnv>(request, url, {
|
|
655
|
+
findMatch: router.findMatch,
|
|
656
|
+
routerVersion: version,
|
|
657
|
+
routerId: router.id,
|
|
658
|
+
});
|
|
659
|
+
} catch (error) {
|
|
660
|
+
if (isRouteNotFoundError(error)) {
|
|
661
|
+
// Let the render path handle 404 — match()/matchPartial() will
|
|
662
|
+
// re-throw RouteNotFoundError and the catch block in
|
|
663
|
+
// executeRenderWithMiddleware renders the not-found page.
|
|
664
|
+
plan = {
|
|
665
|
+
mode: "full-render",
|
|
666
|
+
route: {
|
|
667
|
+
matched: null as any,
|
|
668
|
+
manifestEntry: null as any,
|
|
669
|
+
entries: [],
|
|
670
|
+
routeKey: "",
|
|
671
|
+
localRouteName: "",
|
|
672
|
+
params: {},
|
|
673
|
+
routeMiddleware: [],
|
|
674
|
+
cacheScope: null,
|
|
675
|
+
isPassthrough: false,
|
|
676
|
+
},
|
|
677
|
+
negotiated: false,
|
|
678
|
+
};
|
|
679
|
+
} else {
|
|
680
|
+
throw error;
|
|
647
681
|
}
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
682
|
+
}
|
|
683
|
+
const classifyDur = performance.now() - classifyStart;
|
|
684
|
+
handlerTiming.push(`handler-classify;dur=${classifyDur.toFixed(2)}`);
|
|
685
|
+
|
|
686
|
+
// ---- 2. Terminal plans (no execution needed) ----
|
|
687
|
+
if (plan.mode === "redirect") {
|
|
688
|
+
// Redirects are handled by the pipeline (match/matchPartial),
|
|
689
|
+
// but for partial requests we short-circuit with a Flight redirect.
|
|
690
|
+
if (url.searchParams.has("_rsc_partial")) {
|
|
691
|
+
return createRedirectFlightResponse(plan.redirectUrl);
|
|
654
692
|
}
|
|
693
|
+
// Full requests: let the pipeline handle the redirect via match()
|
|
694
|
+
// which returns { redirect: url }. Fall through to full-render.
|
|
695
|
+
}
|
|
655
696
|
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
}
|
|
697
|
+
if (plan.mode === "version-mismatch") {
|
|
698
|
+
console.log(
|
|
699
|
+
`[RSC] Version mismatch: client=${url.searchParams.get("_rsc_v")}, server=${version}. Forcing reload.`,
|
|
700
|
+
);
|
|
701
|
+
return createReloadResponse(plan.reloadUrl);
|
|
702
|
+
}
|
|
663
703
|
|
|
664
|
-
|
|
665
|
-
//
|
|
666
|
-
//
|
|
667
|
-
//
|
|
668
|
-
return
|
|
704
|
+
if (plan.mode === "app-switch") {
|
|
705
|
+
// Cross-app SPA navigation crossed a host-router app boundary. Force a
|
|
706
|
+
// real document navigation so the target app's document is re-established
|
|
707
|
+
// (stylesheets, theme, warmup, prefetch-TTL). See request-classification.
|
|
708
|
+
return createReloadResponse(plan.reloadUrl);
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// ---- 3. Origin guard (gate for action/loader/PE modes) ----
|
|
712
|
+
const originPhase = ORIGIN_CHECK_PHASE_BY_MODE[plan.mode];
|
|
713
|
+
if (originPhase) {
|
|
714
|
+
const originResult = await checkRequestOrigin(
|
|
669
715
|
request,
|
|
670
|
-
env,
|
|
671
716
|
url,
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
717
|
+
router.originCheck,
|
|
718
|
+
env,
|
|
719
|
+
router.id,
|
|
720
|
+
originPhase,
|
|
675
721
|
);
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
// Signal the browser to hard-navigate so it renders the raw response.
|
|
682
|
-
// Only for 200 — redirects (3xx) work already because the browser follows
|
|
683
|
-
// them automatically to a URL that serves Flight data.
|
|
684
|
-
if (isPartial && error.status === 200) {
|
|
685
|
-
console.warn(
|
|
686
|
-
`[RSC] Route handler at ${url.pathname} returned a Response during client-side navigation. ` +
|
|
687
|
-
`Falling back to hard navigation. Use data-external on the <Link> to avoid the extra round-trip.`,
|
|
688
|
-
);
|
|
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
|
-
return createResponseWithMergedHeaders(null, {
|
|
697
|
-
status: 200,
|
|
698
|
-
headers: {
|
|
699
|
-
"X-RSC-Reload": cleanUrl.toString(),
|
|
700
|
-
"content-type": "text/x-component;charset=utf-8",
|
|
701
|
-
},
|
|
702
|
-
});
|
|
703
|
-
}
|
|
704
|
-
return error;
|
|
705
|
-
}
|
|
722
|
+
if (originResult) {
|
|
723
|
+
const originError = new Error(
|
|
724
|
+
`Origin check rejected: ${request.headers.get("origin") ?? "none"} vs ${request.headers.get("host") ?? "none"}`,
|
|
725
|
+
);
|
|
726
|
+
originError.name = "OriginCheckError";
|
|
706
727
|
|
|
707
|
-
|
|
708
|
-
// Check both instanceof and error.name for cross-bundle compatibility
|
|
709
|
-
const isRouteNotFound =
|
|
710
|
-
error instanceof RouteNotFoundError ||
|
|
711
|
-
(error instanceof Error && error.name === "RouteNotFoundError");
|
|
712
|
-
if (isRouteNotFound) {
|
|
713
|
-
callOnError(error, "routing", {
|
|
728
|
+
callOnError(originError, "origin", {
|
|
714
729
|
request,
|
|
715
730
|
url,
|
|
716
731
|
env,
|
|
717
|
-
handledByBoundary:
|
|
718
|
-
});
|
|
719
|
-
|
|
720
|
-
// Get notFound component from router options or use default
|
|
721
|
-
const notFoundOption = router.notFound;
|
|
722
|
-
const notFoundComponent =
|
|
723
|
-
typeof notFoundOption === "function"
|
|
724
|
-
? notFoundOption({ pathname: url.pathname })
|
|
725
|
-
: (notFoundOption ?? createElement("h1", null, "Not Found"));
|
|
726
|
-
|
|
727
|
-
// Create a simple segment for the 404 page
|
|
728
|
-
const notFoundSegment = {
|
|
729
|
-
id: "notFound",
|
|
730
|
-
namespace: "notFound",
|
|
731
|
-
type: "route" as const,
|
|
732
|
-
index: 0,
|
|
733
|
-
component: notFoundComponent,
|
|
734
|
-
params: {},
|
|
735
|
-
};
|
|
736
|
-
|
|
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
|
-
const payload: RscPayload = {
|
|
744
|
-
root,
|
|
732
|
+
handledByBoundary: false,
|
|
745
733
|
metadata: {
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
diff: [],
|
|
750
|
-
isPartial: false,
|
|
751
|
-
handles: handleStore.stream(),
|
|
752
|
-
version,
|
|
753
|
-
themeConfig: router.themeConfig,
|
|
754
|
-
warmupEnabled: router.warmupEnabled,
|
|
755
|
-
initialTheme: requireRequestContext().theme,
|
|
756
|
-
// No routeName for not-found routes
|
|
734
|
+
phase: originPhase,
|
|
735
|
+
origin: request.headers.get("origin"),
|
|
736
|
+
host: request.headers.get("host"),
|
|
757
737
|
},
|
|
758
|
-
};
|
|
759
|
-
|
|
760
|
-
const rscStream = renderToReadableStream(payload);
|
|
761
|
-
|
|
762
|
-
// Determine if this is an RSC request or HTML request
|
|
763
|
-
const isRscRequest =
|
|
764
|
-
(!request.headers.get("accept")?.includes("text/html") &&
|
|
765
|
-
!url.searchParams.has("__html")) ||
|
|
766
|
-
url.searchParams.has("__rsc");
|
|
767
|
-
|
|
768
|
-
if (isRscRequest) {
|
|
769
|
-
return createResponseWithMergedHeaders(rscStream, {
|
|
770
|
-
status: 404,
|
|
771
|
-
headers: { "content-type": "text/x-component;charset=utf-8" },
|
|
772
|
-
});
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
// Delegate to SSR for HTML response
|
|
776
|
-
const ssrModule = await loadSSRModule();
|
|
777
|
-
const htmlStream = await ssrModule.renderHTML(rscStream, { nonce });
|
|
738
|
+
});
|
|
778
739
|
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
740
|
+
observeEvent({
|
|
741
|
+
type: "request.origin-rejected",
|
|
742
|
+
timestamp: performance.now(),
|
|
743
|
+
method: request.method,
|
|
744
|
+
pathname: url.pathname,
|
|
745
|
+
phase: originPhase,
|
|
746
|
+
origin: request.headers.get("origin"),
|
|
747
|
+
host: request.headers.get("host"),
|
|
782
748
|
});
|
|
783
|
-
}
|
|
784
749
|
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
request,
|
|
788
|
-
url,
|
|
789
|
-
env,
|
|
790
|
-
handledByBoundary: false,
|
|
791
|
-
});
|
|
792
|
-
console.error(`[RSC] Error:`, error);
|
|
793
|
-
throw error;
|
|
750
|
+
return originResult;
|
|
751
|
+
}
|
|
794
752
|
}
|
|
753
|
+
|
|
754
|
+
// ---- 4. Execute ----
|
|
755
|
+
return executeRequest(
|
|
756
|
+
plan as ExecutableRequestPlan<TEnv>,
|
|
757
|
+
request,
|
|
758
|
+
env,
|
|
759
|
+
url,
|
|
760
|
+
variables,
|
|
761
|
+
nonce,
|
|
762
|
+
);
|
|
795
763
|
}
|
|
796
764
|
|
|
797
|
-
//
|
|
798
|
-
//
|
|
799
|
-
//
|
|
800
|
-
//
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
async function handleProgressiveEnhancement(
|
|
765
|
+
// Execute a classified request plan. Dispatches to the appropriate handler
|
|
766
|
+
// based on plan.mode. Lives in the createRSCHandler closure for access to
|
|
767
|
+
// handlerCtx, router, callOnError, etc.
|
|
768
|
+
// Only receives executable plans (version-mismatch is handled above).
|
|
769
|
+
async function executeRequest(
|
|
770
|
+
plan: ExecutableRequestPlan<TEnv>,
|
|
804
771
|
request: Request,
|
|
805
772
|
env: TEnv,
|
|
806
773
|
url: URL,
|
|
807
|
-
|
|
808
|
-
handleStore: ReturnType<typeof requireRequestContext>["_handleStore"],
|
|
774
|
+
variables: Record<string, any>,
|
|
809
775
|
nonce: string | undefined,
|
|
810
|
-
): Promise<Response
|
|
811
|
-
|
|
812
|
-
const
|
|
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;
|
|
776
|
+
): Promise<Response> {
|
|
777
|
+
// Common setup
|
|
778
|
+
const handleStore = getRequestContext()._handleStore;
|
|
827
779
|
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
780
|
+
// Wire up error reporting for late streaming-handle failures
|
|
781
|
+
handleStore.onError = (error: Error) => {
|
|
782
|
+
const reqCtx = getRequestContext();
|
|
783
|
+
callOnError(error, "handler", {
|
|
784
|
+
request,
|
|
785
|
+
url,
|
|
786
|
+
routeKey: reqCtx._routeName,
|
|
787
|
+
params: reqCtx.params as Record<string, string>,
|
|
788
|
+
handledByBoundary: true,
|
|
789
|
+
});
|
|
790
|
+
observeEvent({
|
|
791
|
+
type: "handler.error",
|
|
792
|
+
timestamp: performance.now(),
|
|
793
|
+
error,
|
|
794
|
+
handledByBoundary: true,
|
|
795
|
+
pathname: url.pathname,
|
|
796
|
+
routeKey: reqCtx._routeName,
|
|
797
|
+
params: reqCtx.params as Record<string, string>,
|
|
798
|
+
});
|
|
799
|
+
};
|
|
836
800
|
|
|
837
|
-
|
|
838
|
-
|
|
801
|
+
// Set route params early so all execution paths can access ctx.params.
|
|
802
|
+
// Also store the classified snapshot so match/matchPartial can reuse it
|
|
803
|
+
// instead of calling resolveRoute again.
|
|
804
|
+
if (plan.mode !== "redirect") {
|
|
805
|
+
setRequestContextParams(plan.route.params, plan.route.routeKey);
|
|
806
|
+
getRequestContext()._classifiedRoute = plan.route;
|
|
839
807
|
}
|
|
840
808
|
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
809
|
+
const routeReverse = createReverseFunction(getRequiredRouteMap());
|
|
810
|
+
|
|
811
|
+
// ---- Response route: skip entire RSC pipeline ----
|
|
812
|
+
if (plan.mode === "response") {
|
|
813
|
+
// Build ResponseRouteMatch from plan fields. handleResponseRoute
|
|
814
|
+
// expects a flat object with params at the top level.
|
|
815
|
+
const responseMatch: ResponseRouteMatch = {
|
|
816
|
+
responseType: plan.responseType,
|
|
817
|
+
handler: plan.handler,
|
|
818
|
+
params: plan.route.params,
|
|
819
|
+
negotiated: plan.negotiated,
|
|
820
|
+
manifestEntry: plan.manifestEntry,
|
|
821
|
+
routeMiddleware: plan.routeMiddleware,
|
|
822
|
+
};
|
|
823
|
+
const responseOutcome = await withTimeout(
|
|
824
|
+
handleResponseRoute(
|
|
825
|
+
handlerCtx,
|
|
826
|
+
responseMatch,
|
|
851
827
|
request,
|
|
852
|
-
url,
|
|
853
828
|
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
829
|
url,
|
|
830
|
+
variables,
|
|
831
|
+
),
|
|
832
|
+
router.timeouts.renderStartMs,
|
|
833
|
+
"render-start",
|
|
834
|
+
);
|
|
835
|
+
if (responseOutcome.timedOut) {
|
|
836
|
+
return handleTimeoutResponse(
|
|
837
|
+
request,
|
|
875
838
|
env,
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
839
|
+
url,
|
|
840
|
+
"render-start",
|
|
841
|
+
responseOutcome.durationMs,
|
|
842
|
+
plan.route.routeKey,
|
|
843
|
+
);
|
|
844
|
+
}
|
|
845
|
+
const response = responseOutcome.result;
|
|
846
|
+
if (plan.negotiated && !isWebSocketUpgradeResponse(response)) {
|
|
847
|
+
// handleResponseRoute (callHandlerWithVary) already appends Vary: Accept
|
|
848
|
+
// for negotiated responses; dedup so we don't emit Vary: Accept, Accept.
|
|
849
|
+
appendVaryAccept(response);
|
|
880
850
|
}
|
|
851
|
+
return response;
|
|
881
852
|
}
|
|
882
853
|
|
|
883
|
-
//
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
854
|
+
// SSR setup: kick off in parallel for modes that need HTML rendering.
|
|
855
|
+
// Placed after response-route short-circuit so response/mime routes
|
|
856
|
+
// never pay for SSR work.
|
|
857
|
+
//
|
|
858
|
+
// Only kick off when the request will actually render HTML, so the
|
|
859
|
+
// eager loadSSRModule() + user resolveStreaming() are not started (and
|
|
860
|
+
// never consumed) for a request that returns an RSC stream — that wasted
|
|
861
|
+
// work also leaves an orphaned Promise.all that can reject (D7). PE form
|
|
862
|
+
// submissions always render HTML (handleProgressiveEnhancement renders via
|
|
863
|
+
// getSSRSetup regardless of Accept). For full/partial-render and action,
|
|
864
|
+
// the render-time HTML decision is exactly !isRscRequest — mayNeedSSR is
|
|
865
|
+
// the coarse transport pre-filter, isRscRequest is the precise Accept call
|
|
866
|
+
// (it, unlike mayNeedSSR, treats a MISSING Accept as RSC). Both must pass.
|
|
867
|
+
const willRenderHtml =
|
|
868
|
+
plan.mode === "pe-render" ||
|
|
869
|
+
(mayNeedSSR(request, url) &&
|
|
870
|
+
!isRscRequest(request, url, plan.mode === "partial-render"));
|
|
871
|
+
if (plan.mode !== "loader" && willRenderHtml) {
|
|
872
|
+
variables[SSR_SETUP_VAR] = startSSRSetup(
|
|
873
|
+
handlerCtx,
|
|
888
874
|
request,
|
|
889
|
-
url,
|
|
890
875
|
env,
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
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
|
-
});
|
|
876
|
+
url,
|
|
877
|
+
router.debugPerformance
|
|
878
|
+
? () => getRequestContext()._metricsStore
|
|
879
|
+
: undefined,
|
|
880
|
+
);
|
|
909
881
|
}
|
|
910
882
|
|
|
911
|
-
|
|
912
|
-
|
|
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", {
|
|
883
|
+
// ---- Loader fetch ----
|
|
884
|
+
if (plan.mode === "loader") {
|
|
885
|
+
return handleLoaderFetch(
|
|
886
|
+
handlerCtx,
|
|
976
887
|
request,
|
|
977
|
-
url,
|
|
978
888
|
env,
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
cause: error,
|
|
984
|
-
});
|
|
889
|
+
url,
|
|
890
|
+
variables,
|
|
891
|
+
plan.route.params,
|
|
892
|
+
);
|
|
985
893
|
}
|
|
986
894
|
|
|
987
|
-
//
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
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", {
|
|
895
|
+
// ---- Progressive enhancement ----
|
|
896
|
+
if (plan.mode === "pe-render") {
|
|
897
|
+
const peResult = await handleProgressiveEnhancement(
|
|
898
|
+
handlerCtx,
|
|
1005
899
|
request,
|
|
1006
|
-
url,
|
|
1007
900
|
env,
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
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
|
-
}
|
|
901
|
+
url,
|
|
902
|
+
false, // isAction = false for PE
|
|
903
|
+
handleStore,
|
|
904
|
+
nonce,
|
|
905
|
+
{
|
|
906
|
+
routeMiddleware: plan.route.routeMiddleware,
|
|
907
|
+
variables,
|
|
908
|
+
routeReverse,
|
|
909
|
+
},
|
|
910
|
+
);
|
|
911
|
+
if (peResult) return peResult;
|
|
912
|
+
// PE handler returned null (not a PE form) — fall through to render
|
|
1039
913
|
}
|
|
1040
914
|
|
|
1041
|
-
//
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
915
|
+
// ---- Action: execute action, then revalidate wrapped in route middleware ----
|
|
916
|
+
if (plan.mode === "action") {
|
|
917
|
+
let actionContinuation: ActionContinuation | undefined;
|
|
918
|
+
try {
|
|
919
|
+
// Instrument the action execution as its own phase (action:<actionId> +
|
|
920
|
+
// rango.action), so a POST shows the mutation time AND which action ran,
|
|
921
|
+
// not just the downstream revalidation render. The action's own
|
|
922
|
+
// loaders/fetches nest under rango.action.
|
|
923
|
+
const actionOutcome = await withTimeout(
|
|
924
|
+
observePhase(PHASES.action(plan.actionId), () =>
|
|
925
|
+
executeServerAction(
|
|
926
|
+
handlerCtx,
|
|
927
|
+
request,
|
|
928
|
+
env,
|
|
929
|
+
url,
|
|
930
|
+
plan.actionId,
|
|
931
|
+
handleStore,
|
|
932
|
+
),
|
|
933
|
+
),
|
|
934
|
+
router.timeouts.actionMs,
|
|
935
|
+
"action",
|
|
936
|
+
);
|
|
937
|
+
if (actionOutcome.timedOut) {
|
|
938
|
+
return handleTimeoutResponse(
|
|
939
|
+
request,
|
|
940
|
+
env,
|
|
941
|
+
url,
|
|
942
|
+
"action",
|
|
943
|
+
actionOutcome.durationMs,
|
|
944
|
+
plan.route.routeKey,
|
|
945
|
+
plan.actionId,
|
|
946
|
+
);
|
|
947
|
+
}
|
|
948
|
+
const result = actionOutcome.result;
|
|
949
|
+
// Response means redirect or error boundary — done.
|
|
950
|
+
if (result instanceof Response) return result;
|
|
951
|
+
actionContinuation = result;
|
|
952
|
+
} catch (error) {
|
|
953
|
+
callOnError(error, "action", {
|
|
954
|
+
request,
|
|
955
|
+
url,
|
|
956
|
+
env,
|
|
957
|
+
actionId: plan.actionId,
|
|
958
|
+
handledByBoundary: false,
|
|
1064
959
|
});
|
|
960
|
+
console.error(`[RSC] Action error:`, error);
|
|
961
|
+
throw error;
|
|
1065
962
|
}
|
|
1066
963
|
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
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;
|
|
964
|
+
// Revalidation render wrapped in route middleware.
|
|
965
|
+
// Actions from client-side navigation include _rsc_partial — preserve
|
|
966
|
+
// the partial flag so the revalidation returns a Flight stream, not HTML.
|
|
967
|
+
// App-switch is already excluded by classifyRequest (would be full-render).
|
|
968
|
+
const isPartialAction = url.searchParams.has("_rsc_partial");
|
|
969
|
+
return executeRenderWithMiddleware(
|
|
970
|
+
plan.route.routeMiddleware,
|
|
971
|
+
plan.negotiated,
|
|
972
|
+
plan.route.routeKey,
|
|
973
|
+
routeReverse,
|
|
974
|
+
request,
|
|
975
|
+
env,
|
|
976
|
+
url,
|
|
977
|
+
variables,
|
|
978
|
+
nonce,
|
|
979
|
+
handleStore,
|
|
980
|
+
isPartialAction,
|
|
981
|
+
actionContinuation,
|
|
982
|
+
);
|
|
1141
983
|
}
|
|
1142
984
|
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
985
|
+
// Full render, partial render, fallen-through PE, and full-page redirect all
|
|
986
|
+
// render through the same middleware-wrapped path. Only full/partial-render
|
|
987
|
+
// carry negotiation + the partial flag; pe/redirect render plainly.
|
|
988
|
+
const isPartial = plan.mode === "partial-render";
|
|
989
|
+
const negotiated =
|
|
990
|
+
plan.mode === "full-render" || plan.mode === "partial-render"
|
|
991
|
+
? plan.negotiated
|
|
992
|
+
: false;
|
|
993
|
+
return executeRenderWithMiddleware(
|
|
994
|
+
plan.route.routeMiddleware,
|
|
995
|
+
negotiated,
|
|
996
|
+
plan.route.routeKey,
|
|
997
|
+
routeReverse,
|
|
998
|
+
request,
|
|
999
|
+
env,
|
|
1000
|
+
url,
|
|
1001
|
+
variables,
|
|
1002
|
+
nonce,
|
|
1003
|
+
handleStore,
|
|
1004
|
+
isPartial,
|
|
1005
|
+
);
|
|
1147
1006
|
}
|
|
1148
1007
|
|
|
1149
|
-
//
|
|
1150
|
-
//
|
|
1151
|
-
//
|
|
1152
|
-
|
|
1153
|
-
|
|
1008
|
+
// Shared render execution: wraps handleRscRendering (or revalidateAfterAction)
|
|
1009
|
+
// in route middleware and timeout handling. Consolidates the pattern used by
|
|
1010
|
+
// action-revalidate, full-render, and partial-render modes.
|
|
1011
|
+
async function executeRenderWithMiddleware(
|
|
1012
|
+
routeMiddleware: import("../router/middleware-types.js").CollectedMiddleware[],
|
|
1013
|
+
negotiated: boolean,
|
|
1014
|
+
routeKey: string,
|
|
1015
|
+
routeReverse: ReturnType<typeof createReverseFunction>,
|
|
1154
1016
|
request: Request,
|
|
1155
1017
|
env: TEnv,
|
|
1156
1018
|
url: URL,
|
|
1157
1019
|
variables: Record<string, any>,
|
|
1020
|
+
nonce: string | undefined,
|
|
1021
|
+
handleStore: ReturnType<typeof getRequestContext>["_handleStore"],
|
|
1022
|
+
isPartial: boolean,
|
|
1023
|
+
actionContinuation?: ActionContinuation,
|
|
1158
1024
|
): Promise<Response> {
|
|
1159
|
-
const
|
|
1025
|
+
const renderHandler = async (): Promise<Response> => {
|
|
1026
|
+
try {
|
|
1027
|
+
let response: Response;
|
|
1028
|
+
if (actionContinuation) {
|
|
1029
|
+
response = await revalidateAfterAction(
|
|
1030
|
+
handlerCtx,
|
|
1031
|
+
request,
|
|
1032
|
+
env,
|
|
1033
|
+
url,
|
|
1034
|
+
handleStore,
|
|
1035
|
+
actionContinuation,
|
|
1036
|
+
);
|
|
1037
|
+
} else {
|
|
1038
|
+
response = await handleRscRendering(
|
|
1039
|
+
handlerCtx,
|
|
1040
|
+
request,
|
|
1041
|
+
env,
|
|
1042
|
+
url,
|
|
1043
|
+
isPartial,
|
|
1044
|
+
handleStore,
|
|
1045
|
+
nonce,
|
|
1046
|
+
);
|
|
1047
|
+
}
|
|
1048
|
+
if (negotiated && !isWebSocketUpgradeResponse(response)) {
|
|
1049
|
+
// handleRscRendering bakes `accept` into the RSC response's Vary list;
|
|
1050
|
+
// dedup so the negotiated append does not list accept twice.
|
|
1051
|
+
appendVaryAccept(response);
|
|
1052
|
+
}
|
|
1053
|
+
return response;
|
|
1054
|
+
} catch (error) {
|
|
1055
|
+
// Check if middleware/handler returned Response
|
|
1056
|
+
if (error instanceof Response) {
|
|
1057
|
+
// An action revalidation render is delivered to the client over the
|
|
1058
|
+
// same Flight-parsing path as a partial navigation, so a Response
|
|
1059
|
+
// thrown during it must be converted exactly like a partial one
|
|
1060
|
+
// (raw 200 -> hard-nav hint, 3xx -> Flight redirect). Without this,
|
|
1061
|
+
// the no-middleware path returns the raw Response (the with-middleware
|
|
1062
|
+
// path is already covered by the isPartial || actionContinuation
|
|
1063
|
+
// guard below).
|
|
1064
|
+
const treatAsPartial = isPartial || actionContinuation != null;
|
|
1065
|
+
|
|
1066
|
+
// During partial (client-side navigation), a 200 Response from a handler
|
|
1067
|
+
// means the route serves raw content (JSON, text, etc.), not JSX.
|
|
1068
|
+
// Signal the browser to hard-navigate so it renders the raw response.
|
|
1069
|
+
if (treatAsPartial && error.status === 200) {
|
|
1070
|
+
console.warn(
|
|
1071
|
+
`[RSC] Route handler at ${url.pathname} returned a Response during client-side navigation. ` +
|
|
1072
|
+
`Falling back to hard navigation. Use data-external on the <Link> to avoid the extra round-trip.`,
|
|
1073
|
+
);
|
|
1074
|
+
return createResponseWithMergedHeaders(null, {
|
|
1075
|
+
status: 200,
|
|
1076
|
+
headers: {
|
|
1077
|
+
"X-RSC-Reload": stripInternalParams(url).toString(),
|
|
1078
|
+
"content-type": "text/x-component;charset=utf-8",
|
|
1079
|
+
},
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1160
1082
|
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1083
|
+
if (treatAsPartial) {
|
|
1084
|
+
const intercepted = interceptRedirectForPartial(
|
|
1085
|
+
error,
|
|
1086
|
+
createRedirectFlightResponse,
|
|
1087
|
+
);
|
|
1088
|
+
if (intercepted) return intercepted;
|
|
1089
|
+
}
|
|
1166
1090
|
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
if (!registeredLoader) {
|
|
1170
|
-
return createResponseWithMergedHeaders(
|
|
1171
|
-
`Loader "${loaderId}" not found in registry`,
|
|
1172
|
-
{ status: 404 },
|
|
1173
|
-
);
|
|
1174
|
-
}
|
|
1091
|
+
return error;
|
|
1092
|
+
}
|
|
1175
1093
|
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1094
|
+
// Render 404 page for unmatched routes
|
|
1095
|
+
if (isRouteNotFoundError(error)) {
|
|
1096
|
+
callOnError(error, "routing", {
|
|
1097
|
+
request,
|
|
1098
|
+
url,
|
|
1099
|
+
env,
|
|
1100
|
+
handledByBoundary: true,
|
|
1101
|
+
});
|
|
1180
1102
|
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1103
|
+
const notFoundOption = router.notFound;
|
|
1104
|
+
const notFoundComponent =
|
|
1105
|
+
typeof notFoundOption === "function"
|
|
1106
|
+
? notFoundOption({ pathname: url.pathname })
|
|
1107
|
+
: (notFoundOption ?? createElement("h1", null, "Not Found"));
|
|
1108
|
+
|
|
1109
|
+
const notFoundSegment = {
|
|
1110
|
+
id: "notFound",
|
|
1111
|
+
namespace: "notFound",
|
|
1112
|
+
type: "route" as const,
|
|
1113
|
+
index: 0,
|
|
1114
|
+
component: notFoundComponent,
|
|
1115
|
+
params: {},
|
|
1188
1116
|
};
|
|
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
1117
|
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1118
|
+
const payload: RscPayload = {
|
|
1119
|
+
metadata: {
|
|
1120
|
+
pathname: url.pathname,
|
|
1121
|
+
routerId: router.id,
|
|
1122
|
+
basename: router.basename,
|
|
1123
|
+
segments: [notFoundSegment],
|
|
1124
|
+
matched: [],
|
|
1125
|
+
diff: [],
|
|
1126
|
+
// Shape parity with buildFullPayload (rsc-rendering.ts): the 404
|
|
1127
|
+
// payload carries params/resolvedIds/prefetchCacheTTL the same way a
|
|
1128
|
+
// matched full render does. resolvedIds mirrors the rendered segment
|
|
1129
|
+
// list (the single notFound segment) like the error-boundary path
|
|
1130
|
+
// (match-api.ts) does for its boundary segment.
|
|
1131
|
+
resolvedIds: [notFoundSegment.id],
|
|
1132
|
+
params: {},
|
|
1133
|
+
isPartial: false,
|
|
1134
|
+
rootLayout: router.rootLayout,
|
|
1135
|
+
// Full (404) render: resolve deferred handle values server-side.
|
|
1136
|
+
handles: resolvedHandleStream(handleStore),
|
|
1137
|
+
version,
|
|
1138
|
+
prefetchCacheTTL: router.prefetchCacheTTL,
|
|
1139
|
+
prefetchCacheSize: router.prefetchCacheSize,
|
|
1140
|
+
prefetchConcurrency: router.prefetchConcurrency,
|
|
1141
|
+
stateCookieName: router.resolvedStateCookieName,
|
|
1142
|
+
themeConfig: router.themeConfig,
|
|
1143
|
+
warmupEnabled: router.warmupEnabled,
|
|
1144
|
+
strictMode: router.strictMode,
|
|
1145
|
+
initialTheme: getRequestContext().theme,
|
|
1146
|
+
},
|
|
1227
1147
|
};
|
|
1228
1148
|
|
|
1229
|
-
const
|
|
1149
|
+
const rscStream = renderToReadableStream(payload, {
|
|
1150
|
+
onError: (error: unknown) => {
|
|
1151
|
+
callOnError(error, "rendering", { request, url, env });
|
|
1152
|
+
},
|
|
1153
|
+
});
|
|
1230
1154
|
|
|
1231
|
-
|
|
1232
|
-
|
|
1155
|
+
if (isRscRequest(request, url, isPartial)) {
|
|
1156
|
+
return createResponseWithMergedHeaders(rscStream, {
|
|
1157
|
+
status: 404,
|
|
1158
|
+
headers: {
|
|
1159
|
+
"content-type": "text/x-component;charset=utf-8",
|
|
1160
|
+
// Router identity for the client's pre-decode integrity check; a
|
|
1161
|
+
// same-app 404 matches and applies in place. See response-adapter.
|
|
1162
|
+
"X-RSC-Router-Id": router.id,
|
|
1163
|
+
},
|
|
1164
|
+
});
|
|
1233
1165
|
}
|
|
1234
|
-
const loaderPayload: LoaderPayload = { loaderResult: result };
|
|
1235
|
-
const rscStream =
|
|
1236
|
-
renderToReadableStream<LoaderPayload>(loaderPayload);
|
|
1237
1166
|
|
|
1238
|
-
|
|
1239
|
-
|
|
1167
|
+
const [ssrModule, streamMode] = await getSSRSetup(
|
|
1168
|
+
handlerCtx,
|
|
1169
|
+
request,
|
|
1170
|
+
env,
|
|
1171
|
+
url,
|
|
1172
|
+
getRequestContext()._metricsStore,
|
|
1173
|
+
);
|
|
1174
|
+
const htmlStream = await ssrModule.renderHTML(rscStream, {
|
|
1175
|
+
nonce,
|
|
1176
|
+
streamMode,
|
|
1240
1177
|
});
|
|
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
1178
|
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
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 },
|
|
1179
|
+
return createResponseWithMergedHeaders(htmlStream, {
|
|
1180
|
+
status: 404,
|
|
1181
|
+
headers: { "content-type": "text/html;charset=utf-8" },
|
|
1305
1182
|
});
|
|
1306
1183
|
}
|
|
1307
1184
|
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
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 },
|
|
1185
|
+
// Report unhandled errors
|
|
1186
|
+
callOnError(error, "routing", {
|
|
1187
|
+
request,
|
|
1188
|
+
url,
|
|
1189
|
+
env,
|
|
1190
|
+
handledByBoundary: false,
|
|
1358
1191
|
});
|
|
1192
|
+
console.error(`[RSC] Error:`, error);
|
|
1193
|
+
throw error;
|
|
1359
1194
|
}
|
|
1195
|
+
};
|
|
1360
1196
|
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
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" } },
|
|
1197
|
+
// Wrap the render path in a renderStartMs timeout
|
|
1198
|
+
const executeRender = async (): Promise<Response> => {
|
|
1199
|
+
if (routeMiddleware.length > 0) {
|
|
1200
|
+
const mwResponse = await executeMiddleware(
|
|
1201
|
+
buildRouteMiddlewareEntries<TEnv>(routeMiddleware),
|
|
1202
|
+
request,
|
|
1203
|
+
env,
|
|
1204
|
+
variables,
|
|
1205
|
+
renderHandler,
|
|
1206
|
+
routeReverse,
|
|
1387
1207
|
);
|
|
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
1208
|
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
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)}`);
|
|
1209
|
+
if (isPartial || actionContinuation) {
|
|
1210
|
+
const intercepted = interceptRedirectForPartial(
|
|
1211
|
+
mwResponse,
|
|
1212
|
+
createRedirectFlightResponse,
|
|
1213
|
+
);
|
|
1214
|
+
if (intercepted) return intercepted;
|
|
1215
|
+
}
|
|
1433
1216
|
|
|
1434
|
-
|
|
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;
|
|
1217
|
+
return finalizeResponse(mwResponse);
|
|
1442
1218
|
}
|
|
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
1219
|
|
|
1465
|
-
|
|
1466
|
-
const htmlHeaders: Record<string, string> = {
|
|
1467
|
-
"content-type": "text/html;charset=utf-8",
|
|
1220
|
+
return renderHandler();
|
|
1468
1221
|
};
|
|
1469
|
-
if (fullTiming) {
|
|
1470
|
-
htmlHeaders["Server-Timing"] = fullTiming;
|
|
1471
|
-
}
|
|
1472
1222
|
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1223
|
+
const renderOutcome = await withTimeout(
|
|
1224
|
+
executeRender(),
|
|
1225
|
+
router.timeouts.renderStartMs,
|
|
1226
|
+
"render-start",
|
|
1227
|
+
);
|
|
1228
|
+
if (renderOutcome.timedOut) {
|
|
1229
|
+
return handleTimeoutResponse(
|
|
1230
|
+
request,
|
|
1231
|
+
env,
|
|
1232
|
+
url,
|
|
1233
|
+
"render-start",
|
|
1234
|
+
renderOutcome.durationMs,
|
|
1235
|
+
routeKey,
|
|
1236
|
+
);
|
|
1237
|
+
}
|
|
1238
|
+
return renderOutcome.result;
|
|
1476
1239
|
}
|
|
1477
1240
|
}
|