@rangojs/router 0.0.0-experimental.5 → 0.0.0-experimental.50

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