@rangojs/router 0.0.0-experimental.7 → 0.0.0-experimental.70

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.
Files changed (307) hide show
  1. package/AGENTS.md +9 -0
  2. package/README.md +942 -4
  3. package/dist/bin/rango.js +1689 -0
  4. package/dist/vite/index.js +4951 -930
  5. package/package.json +70 -60
  6. package/skills/breadcrumbs/SKILL.md +250 -0
  7. package/skills/cache-guide/SKILL.md +294 -0
  8. package/skills/caching/SKILL.md +93 -23
  9. package/skills/composability/SKILL.md +172 -0
  10. package/skills/debug-manifest/SKILL.md +12 -8
  11. package/skills/document-cache/SKILL.md +18 -16
  12. package/skills/fonts/SKILL.md +167 -0
  13. package/skills/hooks/SKILL.md +334 -72
  14. package/skills/host-router/SKILL.md +218 -0
  15. package/skills/intercept/SKILL.md +131 -8
  16. package/skills/layout/SKILL.md +100 -3
  17. package/skills/links/SKILL.md +92 -31
  18. package/skills/loader/SKILL.md +404 -44
  19. package/skills/middleware/SKILL.md +173 -34
  20. package/skills/mime-routes/SKILL.md +128 -0
  21. package/skills/parallel/SKILL.md +204 -1
  22. package/skills/prerender/SKILL.md +685 -0
  23. package/skills/rango/SKILL.md +85 -16
  24. package/skills/response-routes/SKILL.md +411 -0
  25. package/skills/route/SKILL.md +257 -14
  26. package/skills/router-setup/SKILL.md +210 -32
  27. package/skills/tailwind/SKILL.md +129 -0
  28. package/skills/theme/SKILL.md +9 -8
  29. package/skills/typesafety/SKILL.md +328 -89
  30. package/skills/use-cache/SKILL.md +324 -0
  31. package/src/__internal.ts +102 -4
  32. package/src/bin/rango.ts +321 -0
  33. package/src/browser/action-coordinator.ts +97 -0
  34. package/src/browser/action-response-classifier.ts +99 -0
  35. package/src/browser/app-version.ts +14 -0
  36. package/src/browser/event-controller.ts +92 -64
  37. package/src/browser/history-state.ts +80 -0
  38. package/src/browser/intercept-utils.ts +52 -0
  39. package/src/browser/link-interceptor.ts +24 -4
  40. package/src/browser/logging.ts +55 -0
  41. package/src/browser/merge-segment-loaders.ts +20 -12
  42. package/src/browser/navigation-bridge.ts +296 -558
  43. package/src/browser/navigation-client.ts +179 -69
  44. package/src/browser/navigation-store.ts +73 -55
  45. package/src/browser/navigation-transaction.ts +297 -0
  46. package/src/browser/network-error-handler.ts +61 -0
  47. package/src/browser/partial-update.ts +328 -313
  48. package/src/browser/prefetch/cache.ts +206 -0
  49. package/src/browser/prefetch/fetch.ts +150 -0
  50. package/src/browser/prefetch/observer.ts +65 -0
  51. package/src/browser/prefetch/policy.ts +48 -0
  52. package/src/browser/prefetch/queue.ts +160 -0
  53. package/src/browser/prefetch/resource-ready.ts +77 -0
  54. package/src/browser/rango-state.ts +112 -0
  55. package/src/browser/react/Link.tsx +230 -74
  56. package/src/browser/react/NavigationProvider.tsx +87 -11
  57. package/src/browser/react/context.ts +11 -0
  58. package/src/browser/react/filter-segment-order.ts +11 -0
  59. package/src/browser/react/index.ts +12 -12
  60. package/src/browser/react/location-state-shared.ts +95 -53
  61. package/src/browser/react/location-state.ts +60 -15
  62. package/src/browser/react/mount-context.ts +6 -1
  63. package/src/browser/react/nonce-context.ts +23 -0
  64. package/src/browser/react/shallow-equal.ts +27 -0
  65. package/src/browser/react/use-action.ts +29 -51
  66. package/src/browser/react/use-client-cache.ts +5 -3
  67. package/src/browser/react/use-handle.ts +30 -126
  68. package/src/browser/react/use-href.tsx +2 -2
  69. package/src/browser/react/use-link-status.ts +6 -5
  70. package/src/browser/react/use-navigation.ts +22 -63
  71. package/src/browser/react/use-params.ts +65 -0
  72. package/src/browser/react/use-pathname.ts +47 -0
  73. package/src/browser/react/use-router.ts +76 -0
  74. package/src/browser/react/use-search-params.ts +56 -0
  75. package/src/browser/react/use-segments.ts +80 -97
  76. package/src/browser/response-adapter.ts +73 -0
  77. package/src/browser/rsc-router.tsx +214 -58
  78. package/src/browser/scroll-restoration.ts +127 -52
  79. package/src/browser/segment-reconciler.ts +221 -0
  80. package/src/browser/segment-structure-assert.ts +16 -0
  81. package/src/browser/server-action-bridge.ts +510 -603
  82. package/src/browser/shallow.ts +6 -1
  83. package/src/browser/types.ts +141 -48
  84. package/src/browser/validate-redirect-origin.ts +29 -0
  85. package/src/build/generate-manifest.ts +235 -24
  86. package/src/build/generate-route-types.ts +39 -0
  87. package/src/build/index.ts +13 -0
  88. package/src/build/route-trie.ts +265 -0
  89. package/src/build/route-types/ast-helpers.ts +25 -0
  90. package/src/build/route-types/ast-route-extraction.ts +98 -0
  91. package/src/build/route-types/codegen.ts +102 -0
  92. package/src/build/route-types/include-resolution.ts +418 -0
  93. package/src/build/route-types/param-extraction.ts +48 -0
  94. package/src/build/route-types/per-module-writer.ts +128 -0
  95. package/src/build/route-types/router-processing.ts +618 -0
  96. package/src/build/route-types/scan-filter.ts +85 -0
  97. package/src/build/runtime-discovery.ts +231 -0
  98. package/src/cache/background-task.ts +34 -0
  99. package/src/cache/cache-key-utils.ts +44 -0
  100. package/src/cache/cache-policy.ts +125 -0
  101. package/src/cache/cache-runtime.ts +342 -0
  102. package/src/cache/cache-scope.ts +167 -309
  103. package/src/cache/cf/cf-cache-store.ts +571 -17
  104. package/src/cache/cf/index.ts +13 -3
  105. package/src/cache/document-cache.ts +116 -77
  106. package/src/cache/handle-capture.ts +81 -0
  107. package/src/cache/handle-snapshot.ts +41 -0
  108. package/src/cache/index.ts +1 -15
  109. package/src/cache/memory-segment-store.ts +191 -13
  110. package/src/cache/profile-registry.ts +73 -0
  111. package/src/cache/read-through-swr.ts +134 -0
  112. package/src/cache/segment-codec.ts +256 -0
  113. package/src/cache/taint.ts +153 -0
  114. package/src/cache/types.ts +72 -122
  115. package/src/client.rsc.tsx +3 -1
  116. package/src/client.tsx +105 -179
  117. package/src/component-utils.ts +4 -4
  118. package/src/components/DefaultDocument.tsx +5 -1
  119. package/src/context-var.ts +156 -0
  120. package/src/debug.ts +19 -9
  121. package/src/errors.ts +108 -2
  122. package/src/handle.ts +55 -29
  123. package/src/handles/MetaTags.tsx +73 -20
  124. package/src/handles/breadcrumbs.ts +66 -0
  125. package/src/handles/index.ts +1 -0
  126. package/src/handles/meta.ts +30 -13
  127. package/src/host/cookie-handler.ts +21 -15
  128. package/src/host/errors.ts +8 -8
  129. package/src/host/index.ts +4 -7
  130. package/src/host/pattern-matcher.ts +27 -27
  131. package/src/host/router.ts +61 -39
  132. package/src/host/testing.ts +8 -8
  133. package/src/host/types.ts +15 -7
  134. package/src/host/utils.ts +1 -1
  135. package/src/href-client.ts +119 -29
  136. package/src/index.rsc.ts +155 -19
  137. package/src/index.ts +223 -30
  138. package/src/internal-debug.ts +11 -0
  139. package/src/loader.rsc.ts +26 -157
  140. package/src/loader.ts +27 -10
  141. package/src/network-error-thrower.tsx +3 -1
  142. package/src/outlet-provider.tsx +45 -0
  143. package/src/prerender/param-hash.ts +37 -0
  144. package/src/prerender/store.ts +186 -0
  145. package/src/prerender.ts +524 -0
  146. package/src/reverse.ts +351 -0
  147. package/src/root-error-boundary.tsx +41 -29
  148. package/src/route-content-wrapper.tsx +7 -4
  149. package/src/route-definition/dsl-helpers.ts +982 -0
  150. package/src/route-definition/helper-factories.ts +200 -0
  151. package/src/route-definition/helpers-types.ts +434 -0
  152. package/src/route-definition/index.ts +55 -0
  153. package/src/route-definition/redirect.ts +101 -0
  154. package/src/route-definition/resolve-handler-use.ts +149 -0
  155. package/src/route-definition.ts +1 -1428
  156. package/src/route-map-builder.ts +217 -123
  157. package/src/route-name.ts +53 -0
  158. package/src/route-types.ts +70 -8
  159. package/src/router/content-negotiation.ts +215 -0
  160. package/src/router/debug-manifest.ts +72 -0
  161. package/src/router/error-handling.ts +9 -9
  162. package/src/router/find-match.ts +160 -0
  163. package/src/router/handler-context.ts +435 -86
  164. package/src/router/intercept-resolution.ts +402 -0
  165. package/src/router/lazy-includes.ts +237 -0
  166. package/src/router/loader-resolution.ts +356 -128
  167. package/src/router/logging.ts +251 -0
  168. package/src/router/manifest.ts +154 -35
  169. package/src/router/match-api.ts +555 -0
  170. package/src/router/match-context.ts +5 -3
  171. package/src/router/match-handlers.ts +440 -0
  172. package/src/router/match-middleware/background-revalidation.ts +108 -93
  173. package/src/router/match-middleware/cache-lookup.ts +459 -10
  174. package/src/router/match-middleware/cache-store.ts +98 -26
  175. package/src/router/match-middleware/intercept-resolution.ts +57 -17
  176. package/src/router/match-middleware/segment-resolution.ts +80 -6
  177. package/src/router/match-pipelines.ts +10 -45
  178. package/src/router/match-result.ts +55 -33
  179. package/src/router/metrics.ts +240 -15
  180. package/src/router/middleware-cookies.ts +55 -0
  181. package/src/router/middleware-types.ts +220 -0
  182. package/src/router/middleware.ts +324 -369
  183. package/src/router/navigation-snapshot.ts +182 -0
  184. package/src/router/pattern-matching.ts +211 -43
  185. package/src/router/prerender-match.ts +502 -0
  186. package/src/router/preview-match.ts +98 -0
  187. package/src/router/request-classification.ts +310 -0
  188. package/src/router/revalidation.ts +137 -38
  189. package/src/router/route-snapshot.ts +245 -0
  190. package/src/router/router-context.ts +41 -21
  191. package/src/router/router-interfaces.ts +484 -0
  192. package/src/router/router-options.ts +618 -0
  193. package/src/router/router-registry.ts +24 -0
  194. package/src/router/segment-resolution/fresh.ts +743 -0
  195. package/src/router/segment-resolution/helpers.ts +268 -0
  196. package/src/router/segment-resolution/loader-cache.ts +199 -0
  197. package/src/router/segment-resolution/revalidation.ts +1373 -0
  198. package/src/router/segment-resolution/static-store.ts +67 -0
  199. package/src/router/segment-resolution.ts +21 -0
  200. package/src/router/segment-wrappers.ts +291 -0
  201. package/src/router/telemetry-otel.ts +299 -0
  202. package/src/router/telemetry.ts +300 -0
  203. package/src/router/timeout.ts +148 -0
  204. package/src/router/trie-matching.ts +239 -0
  205. package/src/router/types.ts +78 -3
  206. package/src/router.ts +740 -4252
  207. package/src/rsc/handler-context.ts +45 -0
  208. package/src/rsc/handler.ts +907 -797
  209. package/src/rsc/helpers.ts +140 -6
  210. package/src/rsc/index.ts +0 -20
  211. package/src/rsc/loader-fetch.ts +229 -0
  212. package/src/rsc/manifest-init.ts +90 -0
  213. package/src/rsc/nonce.ts +14 -0
  214. package/src/rsc/origin-guard.ts +141 -0
  215. package/src/rsc/progressive-enhancement.ts +391 -0
  216. package/src/rsc/response-error.ts +37 -0
  217. package/src/rsc/response-route-handler.ts +347 -0
  218. package/src/rsc/rsc-rendering.ts +246 -0
  219. package/src/rsc/runtime-warnings.ts +42 -0
  220. package/src/rsc/server-action.ts +356 -0
  221. package/src/rsc/ssr-setup.ts +128 -0
  222. package/src/rsc/types.ts +46 -11
  223. package/src/search-params.ts +230 -0
  224. package/src/segment-system.tsx +165 -17
  225. package/src/server/context.ts +315 -58
  226. package/src/server/cookie-store.ts +190 -0
  227. package/src/server/fetchable-loader-store.ts +37 -0
  228. package/src/server/handle-store.ts +113 -15
  229. package/src/server/loader-registry.ts +24 -64
  230. package/src/server/request-context.ts +607 -81
  231. package/src/server.ts +35 -130
  232. package/src/ssr/index.tsx +103 -30
  233. package/src/static-handler.ts +126 -0
  234. package/src/theme/ThemeProvider.tsx +21 -15
  235. package/src/theme/ThemeScript.tsx +5 -5
  236. package/src/theme/constants.ts +5 -2
  237. package/src/theme/index.ts +4 -14
  238. package/src/theme/theme-context.ts +4 -30
  239. package/src/theme/theme-script.ts +21 -18
  240. package/src/types/boundaries.ts +158 -0
  241. package/src/types/cache-types.ts +198 -0
  242. package/src/types/error-types.ts +192 -0
  243. package/src/types/global-namespace.ts +100 -0
  244. package/src/types/handler-context.ts +791 -0
  245. package/src/types/index.ts +88 -0
  246. package/src/types/loader-types.ts +210 -0
  247. package/src/types/route-config.ts +170 -0
  248. package/src/types/route-entry.ts +109 -0
  249. package/src/types/segments.ts +150 -0
  250. package/src/types.ts +1 -1623
  251. package/src/urls/include-helper.ts +197 -0
  252. package/src/urls/index.ts +53 -0
  253. package/src/urls/path-helper-types.ts +346 -0
  254. package/src/urls/path-helper.ts +364 -0
  255. package/src/urls/pattern-types.ts +107 -0
  256. package/src/urls/response-types.ts +116 -0
  257. package/src/urls/type-extraction.ts +372 -0
  258. package/src/urls/urls-function.ts +98 -0
  259. package/src/urls.ts +1 -802
  260. package/src/use-loader.tsx +161 -81
  261. package/src/vite/discovery/bundle-postprocess.ts +181 -0
  262. package/src/vite/discovery/discover-routers.ts +348 -0
  263. package/src/vite/discovery/prerender-collection.ts +439 -0
  264. package/src/vite/discovery/route-types-writer.ts +258 -0
  265. package/src/vite/discovery/self-gen-tracking.ts +47 -0
  266. package/src/vite/discovery/state.ts +117 -0
  267. package/src/vite/discovery/virtual-module-codegen.ts +203 -0
  268. package/src/vite/index.ts +15 -1129
  269. package/src/vite/plugin-types.ts +103 -0
  270. package/src/vite/plugins/cjs-to-esm.ts +93 -0
  271. package/src/vite/plugins/client-ref-dedup.ts +115 -0
  272. package/src/vite/plugins/client-ref-hashing.ts +105 -0
  273. package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +72 -53
  274. package/src/vite/plugins/expose-id-utils.ts +299 -0
  275. package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
  276. package/src/vite/plugins/expose-ids/handler-transform.ts +209 -0
  277. package/src/vite/plugins/expose-ids/loader-transform.ts +74 -0
  278. package/src/vite/plugins/expose-ids/router-transform.ts +110 -0
  279. package/src/vite/plugins/expose-ids/types.ts +45 -0
  280. package/src/vite/plugins/expose-internal-ids.ts +786 -0
  281. package/src/vite/plugins/performance-tracks.ts +88 -0
  282. package/src/vite/plugins/refresh-cmd.ts +127 -0
  283. package/src/vite/plugins/use-cache-transform.ts +323 -0
  284. package/src/vite/plugins/version-injector.ts +83 -0
  285. package/src/vite/plugins/version-plugin.ts +266 -0
  286. package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +23 -14
  287. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  288. package/src/vite/rango.ts +462 -0
  289. package/src/vite/router-discovery.ts +918 -0
  290. package/src/vite/utils/ast-handler-extract.ts +517 -0
  291. package/src/vite/utils/banner.ts +36 -0
  292. package/src/vite/utils/bundle-analysis.ts +137 -0
  293. package/src/vite/utils/manifest-utils.ts +70 -0
  294. package/src/vite/{package-resolution.ts → utils/package-resolution.ts} +25 -29
  295. package/src/vite/utils/prerender-utils.ts +207 -0
  296. package/src/vite/utils/shared-utils.ts +170 -0
  297. package/CLAUDE.md +0 -43
  298. package/src/browser/lru-cache.ts +0 -69
  299. package/src/browser/request-controller.ts +0 -164
  300. package/src/cache/memory-store.ts +0 -253
  301. package/src/href-context.ts +0 -33
  302. package/src/href.ts +0 -255
  303. package/src/server/route-manifest-cache.ts +0 -173
  304. package/src/vite/expose-handle-id.ts +0 -209
  305. package/src/vite/expose-loader-id.ts +0 -426
  306. package/src/vite/expose-location-state-id.ts +0 -177
  307. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
@@ -0,0 +1,1373 @@
1
+ /**
2
+ * Revalidation Path Segment Resolution
3
+ *
4
+ * Functions for resolving segments during partial (revalidation) requests.
5
+ * Mirrors the fresh path but adds revalidation awareness: only re-resolves
6
+ * segments whose revalidate() predicate returns true.
7
+ */
8
+
9
+ import type { ReactNode } from "react";
10
+ import { invariant } from "../../errors";
11
+ import { revalidate } from "../loader-resolution.js";
12
+ import { evaluateRevalidation } from "../revalidation.js";
13
+ import {
14
+ getParallelEntries,
15
+ getParallelSlotEntries,
16
+ type EntryData,
17
+ } from "../../server/context";
18
+ import type {
19
+ HandlerContext,
20
+ InternalHandlerContext,
21
+ ResolvedSegment,
22
+ ShouldRevalidateFn,
23
+ } from "../../types";
24
+ import type {
25
+ SegmentResolutionDeps,
26
+ SegmentRevalidationResult,
27
+ ActionContext,
28
+ } from "../types.js";
29
+ import {
30
+ debugLog,
31
+ pushRevalidationTraceEntry,
32
+ isTraceActive,
33
+ } from "../logging.js";
34
+ import { resolveLoaderData } from "./loader-cache.js";
35
+ import {
36
+ handleHandlerResult,
37
+ tryStaticHandler,
38
+ tryStaticSlot,
39
+ resolveLayoutComponent,
40
+ resolveWithErrorBoundary,
41
+ } from "./helpers.js";
42
+ import { getRouterContext } from "../router-context.js";
43
+ import { resolveSink, safeEmit } from "../telemetry.js";
44
+ import {
45
+ track,
46
+ RSCRouterContext,
47
+ runInsideLoaderScope,
48
+ } from "../../server/context.js";
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // Telemetry helpers
52
+ // ---------------------------------------------------------------------------
53
+
54
+ /**
55
+ * Attach a fire-and-forget rejection observer to a streamed handler promise.
56
+ * Silently no-ops when called outside RouterContext (e.g. in unit tests).
57
+ */
58
+ function observeStreamedHandler(
59
+ promise: Promise<ReactNode>,
60
+ segmentId: string,
61
+ segmentType: string,
62
+ pathname?: string,
63
+ routeKey?: string,
64
+ params?: Record<string, string>,
65
+ ): void {
66
+ let routerCtx;
67
+ try {
68
+ routerCtx = getRouterContext();
69
+ } catch {
70
+ return;
71
+ }
72
+ if (!routerCtx?.telemetry) return;
73
+ const sink = resolveSink(routerCtx.telemetry);
74
+ const reqId = routerCtx.requestId;
75
+ promise.catch((err: unknown) => {
76
+ const errorObj = err instanceof Error ? err : new Error(String(err));
77
+ safeEmit(sink, {
78
+ type: "handler.error",
79
+ timestamp: performance.now(),
80
+ requestId: reqId,
81
+ segmentId,
82
+ segmentType,
83
+ error: errorObj,
84
+ handledByBoundary: true,
85
+ pathname,
86
+ routeKey,
87
+ params,
88
+ });
89
+ });
90
+ }
91
+
92
+ // ---------------------------------------------------------------------------
93
+ // Revalidation telemetry helper
94
+ // ---------------------------------------------------------------------------
95
+
96
+ /**
97
+ * Emit revalidation.decision telemetry for a segment if a sink is configured.
98
+ * Called after evaluateRevalidation returns to capture the decision.
99
+ * Silently no-ops when called outside RouterContext (e.g. in unit tests).
100
+ */
101
+ function emitRevalidationDecision(
102
+ segmentId: string,
103
+ pathname: string,
104
+ routeKey: string,
105
+ shouldRevalidate: boolean,
106
+ ): void {
107
+ let routerCtx;
108
+ try {
109
+ routerCtx = getRouterContext();
110
+ } catch {
111
+ return;
112
+ }
113
+ if (routerCtx?.telemetry) {
114
+ safeEmit(resolveSink(routerCtx.telemetry), {
115
+ type: "revalidation.decision",
116
+ timestamp: performance.now(),
117
+ requestId: routerCtx.requestId,
118
+ segmentId,
119
+ pathname,
120
+ routeKey,
121
+ shouldRevalidate,
122
+ });
123
+ }
124
+ }
125
+
126
+ // ---------------------------------------------------------------------------
127
+ // Revalidation path (partial match)
128
+ // ---------------------------------------------------------------------------
129
+
130
+ /**
131
+ * Resolve loaders with revalidation awareness (for partial rendering).
132
+ * Returns both segments to render AND all matched segment IDs.
133
+ */
134
+ export async function resolveLoadersWithRevalidation<TEnv>(
135
+ entry: EntryData,
136
+ ctx: HandlerContext<any, TEnv>,
137
+ belongsToRoute: boolean,
138
+ clientSegmentIds: Set<string>,
139
+ prevParams: Record<string, string>,
140
+ request: Request,
141
+ prevUrl: URL,
142
+ nextUrl: URL,
143
+ routeKey: string,
144
+ deps: SegmentResolutionDeps<TEnv>,
145
+ actionContext?: ActionContext,
146
+ shortCodeOverride?: string,
147
+ stale?: boolean,
148
+ ): Promise<{ segments: ResolvedSegment[]; matchedIds: string[] }> {
149
+ const loaderEntries = entry.loader ?? [];
150
+ if (loaderEntries.length === 0) return { segments: [], matchedIds: [] };
151
+
152
+ const shortCode = shortCodeOverride ?? entry.shortCode;
153
+
154
+ const loaderMeta = loaderEntries.map((loaderEntry, i) => ({
155
+ loaderEntry,
156
+ loader: loaderEntry.loader,
157
+ loaderRevalidateFns: loaderEntry.revalidate,
158
+ segmentId: `${shortCode}D${i}.${loaderEntry.loader.$$id}`,
159
+ index: i,
160
+ }));
161
+
162
+ const matchedIds = loaderMeta.map((m) => m.segmentId);
163
+
164
+ const revalidationChecks = await Promise.all(
165
+ loaderMeta.map(
166
+ async ({
167
+ loaderEntry,
168
+ loader,
169
+ loaderRevalidateFns,
170
+ segmentId,
171
+ index,
172
+ }) => {
173
+ const shouldRun = await revalidate(
174
+ async () => {
175
+ if (!clientSegmentIds.has(segmentId)) {
176
+ if (isTraceActive()) {
177
+ pushRevalidationTraceEntry({
178
+ segmentId,
179
+ segmentType: "loader",
180
+ belongsToRoute,
181
+ source: "loader",
182
+ defaultShouldRevalidate: true,
183
+ finalShouldRevalidate: true,
184
+ reason: "new-segment",
185
+ });
186
+ }
187
+ return true;
188
+ }
189
+
190
+ const dummySegment: ResolvedSegment = {
191
+ id: segmentId,
192
+ namespace: entry.id,
193
+ type: "loader",
194
+ index,
195
+ component: null,
196
+ params: ctx.params,
197
+ loaderId: loader.$$id,
198
+ belongsToRoute,
199
+ };
200
+
201
+ return await evaluateRevalidation({
202
+ segment: dummySegment,
203
+ prevParams,
204
+ getPrevSegment: null,
205
+ request,
206
+ prevUrl,
207
+ nextUrl,
208
+ revalidations: loaderRevalidateFns.map((fn, j) => ({
209
+ name: `loader-revalidate${j}`,
210
+ fn,
211
+ })),
212
+ routeKey,
213
+ context: ctx,
214
+ actionContext,
215
+ stale,
216
+ traceSource: "loader",
217
+ });
218
+ },
219
+ async () => true,
220
+ () => false,
221
+ );
222
+ emitRevalidationDecision(segmentId, ctx.pathname, routeKey, shouldRun);
223
+ return { shouldRun, loaderEntry, loader, segmentId, index };
224
+ },
225
+ ),
226
+ );
227
+
228
+ const loadersToRun = revalidationChecks.filter((c) => c.shouldRun);
229
+ const segments: ResolvedSegment[] = loadersToRun.map(
230
+ ({ loaderEntry, loader, segmentId, index }) => ({
231
+ id: segmentId,
232
+ namespace: entry.id,
233
+ type: "loader" as const,
234
+ index,
235
+ component: null,
236
+ params: ctx.params,
237
+ loaderId: loader.$$id,
238
+ loaderData: deps.wrapLoaderPromise(
239
+ runInsideLoaderScope(() =>
240
+ resolveLoaderData(loaderEntry, ctx, ctx.pathname),
241
+ ),
242
+ entry,
243
+ segmentId,
244
+ ctx.pathname,
245
+ ),
246
+ belongsToRoute,
247
+ }),
248
+ );
249
+
250
+ return { segments, matchedIds };
251
+ }
252
+
253
+ /**
254
+ * Resolve only loader segments for all entries with revalidation logic.
255
+ */
256
+ export async function resolveLoadersOnlyWithRevalidation<TEnv>(
257
+ entries: EntryData[],
258
+ context: HandlerContext<any, TEnv>,
259
+ clientSegmentIds: Set<string>,
260
+ prevParams: Record<string, string>,
261
+ request: Request,
262
+ prevUrl: URL,
263
+ nextUrl: URL,
264
+ routeKey: string,
265
+ deps: SegmentResolutionDeps<TEnv>,
266
+ actionContext?: ActionContext,
267
+ stale?: boolean,
268
+ ): Promise<{ segments: ResolvedSegment[]; matchedIds: string[] }> {
269
+ const allLoaderSegments: ResolvedSegment[] = [];
270
+ const allMatchedIds: string[] = [];
271
+ const seenIds = new Set<string>();
272
+
273
+ async function collectEntryLoaders(
274
+ entry: EntryData,
275
+ belongsToRoute: boolean,
276
+ shortCodeOverride?: string,
277
+ ): Promise<void> {
278
+ // Skip if all loaders from this entry have already been resolved
279
+ // via a parent (e.g., cache boundary wrapping a layout with shared loaders).
280
+ const loaderEntries = entry.loader ?? [];
281
+ const sc = shortCodeOverride ?? entry.shortCode;
282
+ const allAlreadySeen =
283
+ loaderEntries.length > 0 &&
284
+ loaderEntries.every((le, i) =>
285
+ seenIds.has(`${sc}D${i}.${le.loader.$$id}`),
286
+ );
287
+ if (!allAlreadySeen) {
288
+ const { segments, matchedIds } = await resolveLoadersWithRevalidation(
289
+ entry,
290
+ context,
291
+ belongsToRoute,
292
+ clientSegmentIds,
293
+ prevParams,
294
+ request,
295
+ prevUrl,
296
+ nextUrl,
297
+ routeKey,
298
+ deps,
299
+ actionContext,
300
+ shortCodeOverride,
301
+ stale,
302
+ );
303
+ for (const seg of segments) {
304
+ if (!seenIds.has(seg.id)) {
305
+ seenIds.add(seg.id);
306
+ allLoaderSegments.push(seg);
307
+ }
308
+ }
309
+ allMatchedIds.push(...matchedIds);
310
+ }
311
+
312
+ const seenParallelEntryIds = new Set<string>();
313
+ for (const parallelEntry of getParallelEntries(entry.parallel)) {
314
+ if (seenParallelEntryIds.has(parallelEntry.id)) continue;
315
+ seenParallelEntryIds.add(parallelEntry.id);
316
+ await collectEntryLoaders(parallelEntry, belongsToRoute, entry.shortCode);
317
+ }
318
+
319
+ const childBelongsToRoute = belongsToRoute || entry.type === "route";
320
+ for (const layoutEntry of entry.layout) {
321
+ await collectEntryLoaders(layoutEntry, childBelongsToRoute);
322
+ // Inherit route loaders for orphan layouts with parallels.
323
+ // Resolve directly — do NOT re-enter collectEntryLoaders with the
324
+ // route entry, as that would re-iterate route.layout and loop.
325
+ if (
326
+ entry.type === "route" &&
327
+ entry.loader &&
328
+ entry.loader.length > 0 &&
329
+ Object.keys(layoutEntry.parallel).length > 0
330
+ ) {
331
+ const inherited = await resolveLoadersWithRevalidation(
332
+ entry,
333
+ context,
334
+ childBelongsToRoute,
335
+ clientSegmentIds,
336
+ prevParams,
337
+ request,
338
+ prevUrl,
339
+ nextUrl,
340
+ routeKey,
341
+ deps,
342
+ actionContext,
343
+ layoutEntry.shortCode,
344
+ stale,
345
+ );
346
+ for (const seg of inherited.segments) {
347
+ if (!seenIds.has(seg.id)) {
348
+ seenIds.add(seg.id);
349
+ allLoaderSegments.push(seg);
350
+ }
351
+ }
352
+ allMatchedIds.push(...inherited.matchedIds);
353
+ }
354
+ }
355
+ }
356
+
357
+ for (const entry of entries) {
358
+ await collectEntryLoaders(entry, entry.type === "route");
359
+ }
360
+
361
+ return { segments: allLoaderSegments, matchedIds: allMatchedIds };
362
+ }
363
+
364
+ /**
365
+ * Build a map of segment shortCode -> entry with revalidate functions.
366
+ */
367
+ export function buildEntryRevalidateMap(
368
+ entries: EntryData[],
369
+ ): Map<
370
+ string,
371
+ { entry: EntryData; revalidate: ShouldRevalidateFn<any, any>[] }
372
+ > {
373
+ const map = new Map<
374
+ string,
375
+ { entry: EntryData; revalidate: ShouldRevalidateFn<any, any>[] }
376
+ >();
377
+
378
+ function processEntry(entry: EntryData, parentShortCode?: string) {
379
+ map.set(entry.shortCode, { entry, revalidate: entry.revalidate });
380
+
381
+ if (entry.type !== "parallel") {
382
+ for (const { slot, entry: parallelEntry } of getParallelSlotEntries(
383
+ entry.parallel,
384
+ )) {
385
+ const parallelParentShortCode = parentShortCode ?? entry.shortCode;
386
+ const parallelId = `${parallelParentShortCode}.${slot}`;
387
+ map.set(parallelId, {
388
+ entry: parallelEntry,
389
+ revalidate: parallelEntry.revalidate,
390
+ });
391
+ }
392
+ }
393
+
394
+ for (const layoutEntry of entry.layout) {
395
+ processEntry(layoutEntry, entry.shortCode);
396
+ }
397
+ }
398
+
399
+ for (const entry of entries) {
400
+ processEntry(entry);
401
+ }
402
+
403
+ return map;
404
+ }
405
+
406
+ /**
407
+ * Resolve parallel segments with revalidation.
408
+ */
409
+ export async function resolveParallelSegmentsWithRevalidation<TEnv>(
410
+ entry: EntryData,
411
+ params: Record<string, string>,
412
+ context: HandlerContext<any, TEnv>,
413
+ belongsToRoute: boolean,
414
+ clientSegmentIds: Set<string>,
415
+ prevParams: Record<string, string>,
416
+ request: Request,
417
+ prevUrl: URL,
418
+ nextUrl: URL,
419
+ routeKey: string,
420
+ deps: SegmentResolutionDeps<TEnv>,
421
+ actionContext?: ActionContext,
422
+ stale?: boolean,
423
+ ): Promise<SegmentRevalidationResult> {
424
+ const segments: ResolvedSegment[] = [];
425
+ const matchedIds: string[] = [];
426
+
427
+ const resolvedParallelEntries = new Set<string>();
428
+ for (const { slot, entry: parallelEntry } of getParallelSlotEntries(
429
+ entry.parallel,
430
+ )) {
431
+ invariant(
432
+ parallelEntry.type === "parallel",
433
+ `Expected parallel entry, got: ${parallelEntry.type}`,
434
+ );
435
+
436
+ const slots = parallelEntry.handler as Record<
437
+ `@${string}`,
438
+ | ((ctx: HandlerContext<any, TEnv>) => ReactNode | Promise<ReactNode>)
439
+ | ReactNode
440
+ >;
441
+ // In production, static handler bodies are evicted and the slot value
442
+ // may be undefined. The static store holds the pre-rendered component.
443
+ // We defer the handler check until after tryStaticSlot.
444
+ const handler = slots[slot];
445
+
446
+ const parallelId = `${entry.shortCode}.${slot}`;
447
+
448
+ const isFullRefetch = clientSegmentIds.size === 0;
449
+ const isNewParent = !clientSegmentIds.has(entry.shortCode);
450
+ if (
451
+ isFullRefetch ||
452
+ clientSegmentIds.has(parallelId) ||
453
+ belongsToRoute ||
454
+ isNewParent
455
+ ) {
456
+ matchedIds.push(parallelId);
457
+ }
458
+
459
+ const shouldResolve = await (async () => {
460
+ if (isFullRefetch) {
461
+ if (isTraceActive()) {
462
+ pushRevalidationTraceEntry({
463
+ segmentId: parallelId,
464
+ segmentType: "parallel",
465
+ belongsToRoute,
466
+ source: "parallel",
467
+ defaultShouldRevalidate: true,
468
+ finalShouldRevalidate: true,
469
+ reason: "full-refetch",
470
+ });
471
+ }
472
+ return true;
473
+ }
474
+ if (!clientSegmentIds.has(parallelId)) {
475
+ const result = belongsToRoute || isNewParent;
476
+ if (isTraceActive()) {
477
+ pushRevalidationTraceEntry({
478
+ segmentId: parallelId,
479
+ segmentType: "parallel",
480
+ belongsToRoute,
481
+ source: "parallel",
482
+ defaultShouldRevalidate: result,
483
+ finalShouldRevalidate: result,
484
+ reason: result ? "new-segment" : "skip-parent-chain",
485
+ });
486
+ }
487
+ return result;
488
+ }
489
+
490
+ const dummySegment: ResolvedSegment = {
491
+ id: parallelId,
492
+ namespace: parallelEntry.id,
493
+ type: "parallel",
494
+ index: 0,
495
+ component: null as any,
496
+ params,
497
+ slot,
498
+ belongsToRoute,
499
+ parallelName: `${parallelEntry.id}.${slot}`,
500
+ ...(parallelEntry.mountPath
501
+ ? { mountPath: parallelEntry.mountPath }
502
+ : {}),
503
+ };
504
+
505
+ return await evaluateRevalidation({
506
+ segment: dummySegment,
507
+ prevParams,
508
+ getPrevSegment: null,
509
+ request,
510
+ prevUrl,
511
+ nextUrl,
512
+ revalidations: parallelEntry.revalidate.map((fn, i) => ({
513
+ name: `revalidate${i}`,
514
+ fn,
515
+ })),
516
+ routeKey,
517
+ context,
518
+ actionContext,
519
+ stale,
520
+ traceSource: "parallel",
521
+ });
522
+ })();
523
+ emitRevalidationDecision(
524
+ parallelId,
525
+ context.pathname,
526
+ routeKey,
527
+ shouldResolve,
528
+ );
529
+
530
+ let component: ReactNode | undefined;
531
+ if (shouldResolve) {
532
+ component = await tryStaticSlot(parallelEntry, slot, parallelId);
533
+ }
534
+ if (component === undefined) {
535
+ const hasLoadingFallback =
536
+ parallelEntry.loading !== undefined && parallelEntry.loading !== false;
537
+ if (!shouldResolve) {
538
+ component = null;
539
+ } else if (handler === undefined) {
540
+ // Handler evicted (production static slot) but static lookup missed.
541
+ // Nothing to render — use null so the client keeps its cached version.
542
+ component = null;
543
+ } else if (hasLoadingFallback) {
544
+ const result =
545
+ typeof handler === "function" ? handler(context) : handler;
546
+ if (result instanceof Promise) {
547
+ const tracked = deps.trackHandler(result, {
548
+ segmentId: parallelId,
549
+ segmentType: "parallel",
550
+ });
551
+ observeStreamedHandler(
552
+ tracked,
553
+ parallelId,
554
+ "parallel",
555
+ context.pathname,
556
+ routeKey,
557
+ params,
558
+ );
559
+ component = tracked as ReactNode;
560
+ } else {
561
+ component = result as ReactNode;
562
+ }
563
+ } else {
564
+ component =
565
+ typeof handler === "function" ? await handler(context) : handler;
566
+ }
567
+ }
568
+
569
+ segments.push({
570
+ id: parallelId,
571
+ namespace: parallelEntry.id,
572
+ type: "parallel",
573
+ index: 0,
574
+ component,
575
+ loading: parallelEntry.loading === false ? null : parallelEntry.loading,
576
+ transition: parallelEntry.transition,
577
+ params,
578
+ slot,
579
+ belongsToRoute,
580
+ parallelName: `${parallelEntry.id}.${slot}`,
581
+ ...(parallelEntry.mountPath
582
+ ? { mountPath: parallelEntry.mountPath }
583
+ : {}),
584
+ });
585
+
586
+ if (resolvedParallelEntries.has(parallelEntry.id)) {
587
+ continue;
588
+ }
589
+
590
+ const loaderResult = await resolveLoadersWithRevalidation(
591
+ parallelEntry,
592
+ context,
593
+ belongsToRoute,
594
+ clientSegmentIds,
595
+ prevParams,
596
+ request,
597
+ prevUrl,
598
+ nextUrl,
599
+ routeKey,
600
+ deps,
601
+ actionContext,
602
+ entry.shortCode,
603
+ stale,
604
+ );
605
+ segments.push(...loaderResult.segments);
606
+ matchedIds.push(...loaderResult.matchedIds);
607
+ resolvedParallelEntries.add(parallelEntry.id);
608
+ }
609
+
610
+ return { segments, matchedIds };
611
+ }
612
+
613
+ /**
614
+ * Resolve entry handler (layout, cache, or route) with revalidation.
615
+ */
616
+ export async function resolveEntryHandlerWithRevalidation<TEnv>(
617
+ entry: Exclude<EntryData, { type: "parallel" }>,
618
+ params: Record<string, string>,
619
+ context: HandlerContext<any, TEnv>,
620
+ belongsToRoute: boolean,
621
+ clientSegmentIds: Set<string>,
622
+ prevParams: Record<string, string>,
623
+ request: Request,
624
+ prevUrl: URL,
625
+ nextUrl: URL,
626
+ routeKey: string,
627
+ deps: SegmentResolutionDeps<TEnv>,
628
+ actionContext?: ActionContext,
629
+ stale?: boolean,
630
+ ): Promise<{ segment: ResolvedSegment; matchedId: string }> {
631
+ const matchedId = entry.shortCode;
632
+
633
+ const component = await revalidate(
634
+ async () => {
635
+ const hasSegment = clientSegmentIds.has(entry.shortCode);
636
+ debugLog("segment.revalidate", "entry presence check", {
637
+ segmentId: entry.shortCode,
638
+ entryType: entry.type,
639
+ clientHasSegment: hasSegment,
640
+ belongsToRoute,
641
+ });
642
+ if (!hasSegment) {
643
+ if (isTraceActive()) {
644
+ const segType =
645
+ entry.type === "cache"
646
+ ? "layout"
647
+ : (entry.type as "layout" | "route");
648
+ pushRevalidationTraceEntry({
649
+ segmentId: entry.shortCode,
650
+ segmentType: segType,
651
+ belongsToRoute,
652
+ source: "segment-resolution",
653
+ defaultShouldRevalidate: true,
654
+ finalShouldRevalidate: true,
655
+ reason: "new-segment",
656
+ });
657
+ }
658
+ return true;
659
+ }
660
+
661
+ const dummySegment: ResolvedSegment = {
662
+ id: entry.shortCode,
663
+ namespace: entry.id,
664
+ type:
665
+ entry.type === "cache"
666
+ ? "layout"
667
+ : (entry.type as "layout" | "route"),
668
+ index: 0,
669
+ component: null as any,
670
+ params,
671
+ belongsToRoute,
672
+ ...(entry.type === "layout" || entry.type === "cache"
673
+ ? { layoutName: entry.id }
674
+ : {}),
675
+ ...(entry.mountPath ? { mountPath: entry.mountPath } : {}),
676
+ };
677
+
678
+ const shouldRevalidate = await evaluateRevalidation({
679
+ segment: dummySegment,
680
+ prevParams,
681
+ getPrevSegment: null,
682
+ request,
683
+ prevUrl,
684
+ nextUrl,
685
+ revalidations: entry.revalidate.map((fn, i) => ({
686
+ name: `revalidate${i}`,
687
+ fn,
688
+ })),
689
+ routeKey,
690
+ context,
691
+ actionContext,
692
+ stale,
693
+ traceSource:
694
+ entry.type === "route" ? "route-handler" : "layout-handler",
695
+ });
696
+ emitRevalidationDecision(
697
+ entry.shortCode,
698
+ context.pathname,
699
+ routeKey,
700
+ shouldRevalidate,
701
+ );
702
+ debugLog("segment.revalidate", "entry revalidation decision", {
703
+ segmentId: entry.shortCode,
704
+ shouldRevalidate,
705
+ });
706
+ return shouldRevalidate;
707
+ },
708
+ async () => {
709
+ const doneHandler = track(`handler:${entry.id}`, 2);
710
+ (context as InternalHandlerContext<any, TEnv>)._currentSegmentId =
711
+ entry.shortCode;
712
+ if (entry.type === "layout" || entry.type === "cache") {
713
+ const layoutComponent = await resolveLayoutComponent(entry, context);
714
+ doneHandler();
715
+ return layoutComponent;
716
+ }
717
+ const staticComponent = await tryStaticHandler(entry, entry.shortCode);
718
+ if (staticComponent !== undefined) {
719
+ doneHandler();
720
+ return staticComponent;
721
+ }
722
+ const routeEntry = entry as Extract<EntryData, { type: "route" }>;
723
+ // For Passthrough routes at runtime, use the live handler instead of
724
+ // the build handler. At build time (context.build === true), always
725
+ // use the build handler from routeEntry.handler.
726
+ const handler =
727
+ !context.build && routeEntry.liveHandler
728
+ ? routeEntry.liveHandler
729
+ : routeEntry.handler;
730
+ if (!routeEntry.loading) {
731
+ const result = handleHandlerResult(await handler(context));
732
+ doneHandler();
733
+ return result;
734
+ }
735
+ if (!actionContext) {
736
+ const result = handleHandlerResult(handler(context));
737
+ if (result instanceof Promise) {
738
+ result.finally(doneHandler).catch(() => {});
739
+ const tracked = deps.trackHandler(result, {
740
+ segmentId: entry.shortCode,
741
+ segmentType: entry.type,
742
+ });
743
+ observeStreamedHandler(
744
+ tracked,
745
+ entry.shortCode,
746
+ entry.type,
747
+ context.pathname,
748
+ routeKey,
749
+ params,
750
+ );
751
+ return { content: tracked };
752
+ }
753
+ doneHandler();
754
+ return { content: result };
755
+ }
756
+ debugLog("segment.action", "resolving action route with awaited value", {
757
+ entryId: entry.id,
758
+ });
759
+ const actionResult = handleHandlerResult(await handler(context));
760
+ doneHandler();
761
+ return {
762
+ content: Promise.resolve(actionResult),
763
+ };
764
+ },
765
+ () => null,
766
+ );
767
+
768
+ // Normalize void handlers (undefined) to null so the reconciler's
769
+ // component === null checks work consistently for both void and explicit null.
770
+ const resolvedComponent =
771
+ component && typeof component === "object" && "content" in component
772
+ ? ((component as { content: ReactNode }).content ?? null)
773
+ : (component ?? null);
774
+
775
+ const segment: ResolvedSegment = {
776
+ id: entry.shortCode,
777
+ namespace: entry.id,
778
+ type:
779
+ entry.type === "cache" ? "layout" : (entry.type as "layout" | "route"),
780
+ index: 0,
781
+ component: resolvedComponent,
782
+ loading: entry.loading === false ? null : entry.loading,
783
+ transition: entry.transition,
784
+ params,
785
+ belongsToRoute,
786
+ ...(entry.type === "layout" || entry.type === "cache"
787
+ ? { layoutName: entry.id }
788
+ : {}),
789
+ ...(entry.mountPath ? { mountPath: entry.mountPath } : {}),
790
+ };
791
+
792
+ return { segment, matchedId };
793
+ }
794
+
795
+ /**
796
+ * Resolve segments with revalidation awareness (for partial rendering).
797
+ */
798
+ export async function resolveSegmentWithRevalidation<TEnv>(
799
+ entry: Exclude<EntryData, { type: "parallel" }>,
800
+ routeKey: string,
801
+ params: Record<string, string>,
802
+ context: HandlerContext<any, TEnv>,
803
+ clientSegmentIds: Set<string>,
804
+ prevParams: Record<string, string>,
805
+ request: Request,
806
+ prevUrl: URL,
807
+ nextUrl: URL,
808
+ loaderPromises: Map<string, Promise<any>>,
809
+ deps: SegmentResolutionDeps<TEnv>,
810
+ actionContext?: ActionContext,
811
+ stale?: boolean,
812
+ ): Promise<SegmentRevalidationResult> {
813
+ const segments: ResolvedSegment[] = [];
814
+ const matchedIds: string[] = [];
815
+
816
+ const belongsToRoute = entry.type === "route";
817
+
818
+ const loaderResult = await resolveLoadersWithRevalidation(
819
+ entry,
820
+ context,
821
+ belongsToRoute,
822
+ clientSegmentIds,
823
+ prevParams,
824
+ request,
825
+ prevUrl,
826
+ nextUrl,
827
+ routeKey,
828
+ deps,
829
+ actionContext,
830
+ undefined,
831
+ stale,
832
+ );
833
+ segments.push(...loaderResult.segments);
834
+ matchedIds.push(...loaderResult.matchedIds);
835
+
836
+ // For route entries, execute the handler BEFORE orphan layouts and parallels
837
+ // so ctx.set() data is available to them via ctx.get(). The handler's
838
+ // segment is pushed after children to preserve tree composition order.
839
+ let routeHandlerResult:
840
+ | { segment: ResolvedSegment; matchedId: string }
841
+ | undefined;
842
+ if (entry.type === "route") {
843
+ routeHandlerResult = await resolveEntryHandlerWithRevalidation(
844
+ entry,
845
+ params,
846
+ context,
847
+ belongsToRoute,
848
+ clientSegmentIds,
849
+ prevParams,
850
+ request,
851
+ prevUrl,
852
+ nextUrl,
853
+ routeKey,
854
+ deps,
855
+ actionContext,
856
+ stale,
857
+ );
858
+
859
+ for (const orphan of entry.layout) {
860
+ const orphanResult = await resolveOrphanLayoutWithRevalidation(
861
+ orphan,
862
+ params,
863
+ context,
864
+ clientSegmentIds,
865
+ prevParams,
866
+ request,
867
+ prevUrl,
868
+ nextUrl,
869
+ routeKey,
870
+ loaderPromises,
871
+ true,
872
+ deps,
873
+ actionContext,
874
+ stale,
875
+ entry,
876
+ );
877
+ segments.push(...orphanResult.segments);
878
+ matchedIds.push(...orphanResult.matchedIds);
879
+ }
880
+ }
881
+
882
+ if (routeHandlerResult) {
883
+ // Route entry: handler already executed above; resolve parallels
884
+ // (handler data visible) then push handler segment last for tree order.
885
+ const parallelResult = await resolveParallelSegmentsWithRevalidation(
886
+ entry,
887
+ params,
888
+ context,
889
+ belongsToRoute,
890
+ clientSegmentIds,
891
+ prevParams,
892
+ request,
893
+ prevUrl,
894
+ nextUrl,
895
+ routeKey,
896
+ deps,
897
+ actionContext,
898
+ stale,
899
+ );
900
+ segments.push(...parallelResult.segments);
901
+ matchedIds.push(...parallelResult.matchedIds);
902
+
903
+ segments.push(routeHandlerResult.segment);
904
+ matchedIds.push(routeHandlerResult.matchedId);
905
+ } else {
906
+ // Layout/cache entry: handler-first — resolve handler before parallels
907
+ // so ctx.set() values are visible to parallel children.
908
+ const handlerResult = await resolveEntryHandlerWithRevalidation(
909
+ entry,
910
+ params,
911
+ context,
912
+ belongsToRoute,
913
+ clientSegmentIds,
914
+ prevParams,
915
+ request,
916
+ prevUrl,
917
+ nextUrl,
918
+ routeKey,
919
+ deps,
920
+ actionContext,
921
+ stale,
922
+ );
923
+ segments.push(handlerResult.segment);
924
+ matchedIds.push(handlerResult.matchedId);
925
+
926
+ const parallelResult = await resolveParallelSegmentsWithRevalidation(
927
+ entry,
928
+ params,
929
+ context,
930
+ belongsToRoute,
931
+ clientSegmentIds,
932
+ prevParams,
933
+ request,
934
+ prevUrl,
935
+ nextUrl,
936
+ routeKey,
937
+ deps,
938
+ actionContext,
939
+ stale,
940
+ );
941
+ segments.push(...parallelResult.segments);
942
+ matchedIds.push(...parallelResult.matchedIds);
943
+
944
+ for (const orphan of entry.layout) {
945
+ const orphanResult = await resolveOrphanLayoutWithRevalidation(
946
+ orphan,
947
+ params,
948
+ context,
949
+ clientSegmentIds,
950
+ prevParams,
951
+ request,
952
+ prevUrl,
953
+ nextUrl,
954
+ routeKey,
955
+ loaderPromises,
956
+ false,
957
+ deps,
958
+ actionContext,
959
+ stale,
960
+ );
961
+ segments.push(...orphanResult.segments);
962
+ matchedIds.push(...orphanResult.matchedIds);
963
+ }
964
+ }
965
+
966
+ return { segments, matchedIds };
967
+ }
968
+
969
+ /**
970
+ * Resolve orphan layout with revalidation.
971
+ */
972
+ export async function resolveOrphanLayoutWithRevalidation<TEnv>(
973
+ orphan: EntryData,
974
+ params: Record<string, string>,
975
+ context: HandlerContext<any, TEnv>,
976
+ clientSegmentIds: Set<string>,
977
+ prevParams: Record<string, string>,
978
+ request: Request,
979
+ prevUrl: URL,
980
+ nextUrl: URL,
981
+ routeKey: string,
982
+ loaderPromises: Map<string, Promise<any>>,
983
+ belongsToRoute: boolean,
984
+ deps: SegmentResolutionDeps<TEnv>,
985
+ actionContext?: ActionContext,
986
+ stale?: boolean,
987
+ /** Parent route entry — its loaders are inherited so parallel slots can access them. */
988
+ parentRouteEntry?: EntryData,
989
+ ): Promise<SegmentRevalidationResult> {
990
+ invariant(
991
+ orphan.type === "layout" || orphan.type === "cache",
992
+ `Expected orphan to be a layout or cache, got: ${orphan.type}`,
993
+ );
994
+
995
+ const segments: ResolvedSegment[] = [];
996
+ const matchedIds: string[] = [];
997
+
998
+ const loaderResult = await resolveLoadersWithRevalidation(
999
+ orphan,
1000
+ context,
1001
+ belongsToRoute,
1002
+ clientSegmentIds,
1003
+ prevParams,
1004
+ request,
1005
+ prevUrl,
1006
+ nextUrl,
1007
+ routeKey,
1008
+ deps,
1009
+ actionContext,
1010
+ undefined,
1011
+ stale,
1012
+ );
1013
+ segments.push(...loaderResult.segments);
1014
+ matchedIds.push(...loaderResult.matchedIds);
1015
+
1016
+ // Inherit parent route's loaders so parallel slots inside this layout
1017
+ // can access them via useLoader(). See resolveOrphanLayout in fresh.ts.
1018
+ if (
1019
+ parentRouteEntry &&
1020
+ parentRouteEntry.loader &&
1021
+ parentRouteEntry.loader.length > 0 &&
1022
+ Object.keys(orphan.parallel).length > 0
1023
+ ) {
1024
+ const inheritedResult = await resolveLoadersWithRevalidation(
1025
+ parentRouteEntry,
1026
+ context,
1027
+ belongsToRoute,
1028
+ clientSegmentIds,
1029
+ prevParams,
1030
+ request,
1031
+ prevUrl,
1032
+ nextUrl,
1033
+ routeKey,
1034
+ deps,
1035
+ actionContext,
1036
+ orphan.shortCode,
1037
+ stale,
1038
+ );
1039
+ segments.push(...inheritedResult.segments);
1040
+ matchedIds.push(...inheritedResult.matchedIds);
1041
+ }
1042
+
1043
+ // Handler-first: resolve orphan layout handler before its parallels
1044
+ // so ctx.set() values are visible to parallel children.
1045
+ matchedIds.push(orphan.shortCode);
1046
+
1047
+ const component = await revalidate(
1048
+ async () => {
1049
+ if (!clientSegmentIds.has(orphan.shortCode)) {
1050
+ if (isTraceActive()) {
1051
+ pushRevalidationTraceEntry({
1052
+ segmentId: orphan.shortCode,
1053
+ segmentType: "layout",
1054
+ belongsToRoute,
1055
+ source: "orphan-layout",
1056
+ defaultShouldRevalidate: true,
1057
+ finalShouldRevalidate: true,
1058
+ reason: "new-segment",
1059
+ });
1060
+ }
1061
+ return true;
1062
+ }
1063
+
1064
+ const dummySegment: ResolvedSegment = {
1065
+ id: orphan.shortCode,
1066
+ namespace: orphan.id,
1067
+ type: "layout",
1068
+ index: 0,
1069
+ component: null as any,
1070
+ params,
1071
+ belongsToRoute,
1072
+ layoutName: orphan.id,
1073
+ ...(orphan.mountPath ? { mountPath: orphan.mountPath } : {}),
1074
+ };
1075
+
1076
+ const shouldRevalidate = await evaluateRevalidation({
1077
+ segment: dummySegment,
1078
+ prevParams,
1079
+ getPrevSegment: null,
1080
+ request,
1081
+ prevUrl,
1082
+ nextUrl,
1083
+ revalidations: orphan.revalidate.map((fn, i) => ({
1084
+ name: `revalidate${i}`,
1085
+ fn,
1086
+ })),
1087
+ routeKey,
1088
+ context,
1089
+ actionContext,
1090
+ stale,
1091
+ traceSource: "orphan-layout",
1092
+ });
1093
+ emitRevalidationDecision(
1094
+ orphan.shortCode,
1095
+ context.pathname,
1096
+ routeKey,
1097
+ shouldRevalidate,
1098
+ );
1099
+ return shouldRevalidate;
1100
+ },
1101
+ async () => resolveLayoutComponent(orphan, context),
1102
+ () => null,
1103
+ );
1104
+
1105
+ segments.push({
1106
+ id: orphan.shortCode,
1107
+ namespace: orphan.id,
1108
+ type: "layout",
1109
+ index: 0,
1110
+ component,
1111
+ params,
1112
+ belongsToRoute,
1113
+ layoutName: orphan.id,
1114
+ loading: orphan.loading === false ? null : orphan.loading,
1115
+ transition: orphan.transition,
1116
+ ...(orphan.mountPath ? { mountPath: orphan.mountPath } : {}),
1117
+ });
1118
+
1119
+ const resolvedParallelEntries = new Set<string>();
1120
+ for (const { slot, entry: parallelEntry } of getParallelSlotEntries(
1121
+ orphan.parallel,
1122
+ )) {
1123
+ invariant(
1124
+ parallelEntry.type === "parallel",
1125
+ `Expected parallel entry, got: ${parallelEntry.type}`,
1126
+ );
1127
+
1128
+ if (!resolvedParallelEntries.has(parallelEntry.id)) {
1129
+ const loaderResult = await resolveLoadersWithRevalidation(
1130
+ parallelEntry,
1131
+ context,
1132
+ belongsToRoute,
1133
+ clientSegmentIds,
1134
+ prevParams,
1135
+ request,
1136
+ prevUrl,
1137
+ nextUrl,
1138
+ routeKey,
1139
+ deps,
1140
+ actionContext,
1141
+ undefined,
1142
+ stale,
1143
+ );
1144
+ segments.push(...loaderResult.segments);
1145
+ matchedIds.push(...loaderResult.matchedIds);
1146
+ resolvedParallelEntries.add(parallelEntry.id);
1147
+ }
1148
+
1149
+ const slots = parallelEntry.handler as Record<
1150
+ `@${string}`,
1151
+ | ((ctx: HandlerContext<any, TEnv>) => ReactNode | Promise<ReactNode>)
1152
+ | ReactNode
1153
+ >;
1154
+ // Handler may be undefined in production after static handler eviction.
1155
+ const handler = slots[slot];
1156
+
1157
+ // Use orphan.shortCode (the parent layout) to match the SSR path
1158
+ // (resolveParallelEntry receives parentShortCode = orphan.shortCode).
1159
+ // Using parallelEntry.shortCode would generate IDs the client doesn't know about.
1160
+ const parallelId = `${orphan.shortCode}.${slot}`;
1161
+ matchedIds.push(parallelId);
1162
+
1163
+ const shouldResolve = await (async () => {
1164
+ if (!clientSegmentIds.has(parallelId)) {
1165
+ if (isTraceActive()) {
1166
+ pushRevalidationTraceEntry({
1167
+ segmentId: parallelId,
1168
+ segmentType: "parallel",
1169
+ belongsToRoute,
1170
+ source: "parallel",
1171
+ defaultShouldRevalidate: true,
1172
+ finalShouldRevalidate: true,
1173
+ reason: "new-segment",
1174
+ });
1175
+ }
1176
+ return true;
1177
+ }
1178
+
1179
+ const dummySegment: ResolvedSegment = {
1180
+ id: parallelId,
1181
+ namespace: parallelEntry.id,
1182
+ type: "parallel",
1183
+ index: 0,
1184
+ component: null as any,
1185
+ params,
1186
+ slot,
1187
+ belongsToRoute,
1188
+ parallelName: `${parallelEntry.id}.${slot}`,
1189
+ ...(parallelEntry.mountPath
1190
+ ? { mountPath: parallelEntry.mountPath }
1191
+ : {}),
1192
+ };
1193
+
1194
+ return await evaluateRevalidation({
1195
+ segment: dummySegment,
1196
+ prevParams,
1197
+ getPrevSegment: null,
1198
+ request,
1199
+ prevUrl,
1200
+ nextUrl,
1201
+ revalidations: parallelEntry.revalidate.map((fn, i) => ({
1202
+ name: `revalidate${i}`,
1203
+ fn,
1204
+ })),
1205
+ routeKey,
1206
+ context,
1207
+ actionContext,
1208
+ stale,
1209
+ traceSource: "parallel",
1210
+ });
1211
+ })();
1212
+ emitRevalidationDecision(
1213
+ parallelId,
1214
+ context.pathname,
1215
+ routeKey,
1216
+ shouldResolve,
1217
+ );
1218
+
1219
+ let component: ReactNode | undefined;
1220
+ if (shouldResolve) {
1221
+ component = await tryStaticSlot(parallelEntry, slot, parallelId);
1222
+ }
1223
+ if (component === undefined) {
1224
+ const hasLoadingFallback =
1225
+ parallelEntry.loading !== undefined && parallelEntry.loading !== false;
1226
+ if (!shouldResolve) {
1227
+ component = null;
1228
+ } else if (handler === undefined) {
1229
+ // Handler evicted (production static slot) but static lookup missed.
1230
+ component = null;
1231
+ } else if (hasLoadingFallback) {
1232
+ const result =
1233
+ typeof handler === "function" ? handler(context) : handler;
1234
+ if (result instanceof Promise) {
1235
+ const tracked = deps.trackHandler(result, {
1236
+ segmentId: parallelId,
1237
+ segmentType: "parallel",
1238
+ });
1239
+ observeStreamedHandler(
1240
+ tracked,
1241
+ parallelId,
1242
+ "parallel",
1243
+ context.pathname,
1244
+ routeKey,
1245
+ params,
1246
+ );
1247
+ component = tracked as ReactNode;
1248
+ } else {
1249
+ component = result as ReactNode;
1250
+ }
1251
+ } else {
1252
+ component =
1253
+ typeof handler === "function" ? await handler(context) : handler;
1254
+ }
1255
+ }
1256
+
1257
+ segments.push({
1258
+ id: parallelId,
1259
+ namespace: parallelEntry.id,
1260
+ type: "parallel",
1261
+ index: 0,
1262
+ component,
1263
+ loading: parallelEntry.loading === false ? null : parallelEntry.loading,
1264
+ transition: parallelEntry.transition,
1265
+ params,
1266
+ slot,
1267
+ belongsToRoute,
1268
+ parallelName: `${parallelEntry.id}.${slot}`,
1269
+ ...(parallelEntry.mountPath
1270
+ ? { mountPath: parallelEntry.mountPath }
1271
+ : {}),
1272
+ });
1273
+ }
1274
+
1275
+ return { segments, matchedIds };
1276
+ }
1277
+
1278
+ /**
1279
+ * Resolve all segments for a route with revalidation logic (for matchPartial).
1280
+ */
1281
+ export async function resolveAllSegmentsWithRevalidation<TEnv>(
1282
+ entries: EntryData[],
1283
+ routeKey: string,
1284
+ params: Record<string, string>,
1285
+ context: HandlerContext<any, TEnv>,
1286
+ clientSegmentSet: Set<string>,
1287
+ prevParams: Record<string, string>,
1288
+ request: Request,
1289
+ prevUrl: URL,
1290
+ nextUrl: URL,
1291
+ loaderPromises: Map<string, Promise<any>>,
1292
+ actionContext: ActionContext | undefined,
1293
+ interceptResult: { intercept: any; entry: EntryData } | null,
1294
+ localRouteName: string,
1295
+ pathname: string,
1296
+ deps: SegmentResolutionDeps<TEnv>,
1297
+ stale?: boolean,
1298
+ ): Promise<{ segments: ResolvedSegment[]; matchedIds: string[] }> {
1299
+ const allSegments: ResolvedSegment[] = [];
1300
+ const matchedIds: string[] = [];
1301
+ const seenSegIds = new Set<string>();
1302
+ const seenMatchIds = new Set<string>();
1303
+
1304
+ const telemetry = getRouterContext()?.telemetry;
1305
+
1306
+ for (const entry of entries) {
1307
+ if (entry.type === "route" && interceptResult) {
1308
+ debugLog(
1309
+ "matchPartial.intercept",
1310
+ "skipping route handler during intercept",
1311
+ {
1312
+ localRouteName,
1313
+ segmentId: entry.shortCode,
1314
+ },
1315
+ );
1316
+ if (!seenMatchIds.has(entry.shortCode)) {
1317
+ seenMatchIds.add(entry.shortCode);
1318
+ matchedIds.push(entry.shortCode);
1319
+ }
1320
+ continue;
1321
+ }
1322
+
1323
+ const nonParallelEntry = entry as Exclude<EntryData, { type: "parallel" }>;
1324
+ if (entry.type === "cache") {
1325
+ const store = RSCRouterContext.getStore();
1326
+ if (store) store.insideCacheScope = true;
1327
+ }
1328
+ const doneEntry = track(`segment:${entry.id}`, 1);
1329
+ const resolved = await resolveWithErrorBoundary(
1330
+ nonParallelEntry,
1331
+ params,
1332
+ () =>
1333
+ resolveSegmentWithRevalidation(
1334
+ nonParallelEntry,
1335
+ routeKey,
1336
+ params,
1337
+ context,
1338
+ clientSegmentSet,
1339
+ prevParams,
1340
+ request,
1341
+ prevUrl,
1342
+ nextUrl,
1343
+ loaderPromises,
1344
+ deps,
1345
+ actionContext,
1346
+ stale,
1347
+ ),
1348
+ (seg) => ({ segments: [seg], matchedIds: [seg.id] }),
1349
+ deps,
1350
+ { request, url: context.url, routeKey, isPartial: true, telemetry },
1351
+ pathname,
1352
+ );
1353
+ doneEntry();
1354
+
1355
+ // Deduplicate segments and matchedIds by ID, matching resolveAllSegments.
1356
+ // include() scopes can produce entries that resolve the same shared
1357
+ // layout/loader segment. Duplicates cause React tree depth changes.
1358
+ for (const seg of resolved.segments) {
1359
+ if (!seenSegIds.has(seg.id)) {
1360
+ seenSegIds.add(seg.id);
1361
+ allSegments.push(seg);
1362
+ }
1363
+ }
1364
+ for (const id of resolved.matchedIds) {
1365
+ if (!seenMatchIds.has(id)) {
1366
+ seenMatchIds.add(id);
1367
+ matchedIds.push(id);
1368
+ }
1369
+ }
1370
+ }
1371
+
1372
+ return { segments: allSegments, matchedIds };
1373
+ }