@rangojs/router 0.0.0-experimental.b9cb8739 → 0.0.0-experimental.bdaf10aa

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 (449) hide show
  1. package/AGENTS.md +8 -4
  2. package/README.md +303 -741
  3. package/dist/bin/rango.js +730 -184
  4. package/dist/testing/vitest.js +82 -0
  5. package/dist/vite/index.js +4344 -1335
  6. package/dist/vite/index.js.bak +5448 -0
  7. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  8. package/package.json +86 -15
  9. package/skills/api-client/SKILL.md +211 -0
  10. package/skills/breadcrumbs/SKILL.md +85 -6
  11. package/skills/bundle-analysis/SKILL.md +159 -0
  12. package/skills/cache-guide/SKILL.md +251 -24
  13. package/skills/caching/SKILL.md +375 -17
  14. package/skills/catalog.json +271 -0
  15. package/skills/comparison/SKILL.md +50 -0
  16. package/skills/comparison/agents/openai.yaml +4 -0
  17. package/skills/comparison/references/framework-comparison.md +837 -0
  18. package/skills/composability/SKILL.md +110 -4
  19. package/skills/css/SKILL.md +76 -0
  20. package/skills/debug-manifest/SKILL.md +5 -3
  21. package/skills/defer-hydration/SKILL.md +235 -0
  22. package/skills/document-cache/SKILL.md +87 -56
  23. package/skills/fonts/SKILL.md +1 -1
  24. package/skills/handler-use/SKILL.md +364 -0
  25. package/skills/hooks/SKILL.md +73 -691
  26. package/skills/hooks/data.md +273 -0
  27. package/skills/hooks/handle-and-actions.md +103 -0
  28. package/skills/hooks/navigation.md +110 -0
  29. package/skills/hooks/outlets.md +41 -0
  30. package/skills/hooks/state.md +228 -0
  31. package/skills/hooks/urls.md +135 -0
  32. package/skills/host-router/SKILL.md +129 -27
  33. package/skills/i18n/SKILL.md +276 -0
  34. package/skills/intercept/SKILL.md +94 -18
  35. package/skills/layout/SKILL.md +62 -19
  36. package/skills/links/SKILL.md +249 -17
  37. package/skills/loader/SKILL.md +302 -54
  38. package/skills/middleware/SKILL.md +59 -16
  39. package/skills/migrate-nextjs/SKILL.md +745 -0
  40. package/skills/migrate-react-router/SKILL.md +153 -0
  41. package/skills/migrate-react-router/cloudflare-workers.md +129 -0
  42. package/skills/migrate-react-router/component-migration.md +196 -0
  43. package/skills/migrate-react-router/data-and-actions.md +225 -0
  44. package/skills/migrate-react-router/route-mapping.md +271 -0
  45. package/skills/mime-routes/SKILL.md +29 -2
  46. package/skills/observability/SKILL.md +202 -0
  47. package/skills/parallel/SKILL.md +225 -10
  48. package/skills/ppr/SKILL.md +622 -0
  49. package/skills/prerender/SKILL.md +178 -124
  50. package/skills/rango/SKILL.md +318 -24
  51. package/skills/react-compiler/SKILL.md +168 -0
  52. package/skills/response-routes/SKILL.md +138 -49
  53. package/skills/route/SKILL.md +172 -9
  54. package/skills/router-setup/SKILL.md +131 -11
  55. package/skills/scripts/SKILL.md +179 -0
  56. package/skills/server-actions/SKILL.md +776 -0
  57. package/skills/shell-manifest/SKILL.md +185 -0
  58. package/skills/streams-and-websockets/SKILL.md +283 -0
  59. package/skills/tailwind/SKILL.md +28 -4
  60. package/skills/testing/SKILL.md +130 -0
  61. package/skills/testing/bindings.md +103 -0
  62. package/skills/testing/cache-prerender.md +127 -0
  63. package/skills/testing/client-components.md +124 -0
  64. package/skills/testing/e2e-parity.md +125 -0
  65. package/skills/testing/flight.md +91 -0
  66. package/skills/testing/handles.md +131 -0
  67. package/skills/testing/loader.md +128 -0
  68. package/skills/testing/middleware.md +99 -0
  69. package/skills/testing/render-handler.md +122 -0
  70. package/skills/testing/response-routes.md +95 -0
  71. package/skills/testing/reverse-and-types.md +85 -0
  72. package/skills/testing/server-actions.md +107 -0
  73. package/skills/testing/server-tree.md +128 -0
  74. package/skills/testing/setup.md +123 -0
  75. package/skills/theme/SKILL.md +1 -1
  76. package/skills/typesafety/SKILL.md +45 -616
  77. package/skills/typesafety/env-and-bindings.md +254 -0
  78. package/skills/typesafety/generated-files-and-cli.md +335 -0
  79. package/skills/typesafety/params-and-search.md +153 -0
  80. package/skills/typesafety/route-types.md +209 -0
  81. package/skills/use-cache/SKILL.md +74 -15
  82. package/skills/vercel/SKILL.md +128 -0
  83. package/skills/view-transitions/SKILL.md +337 -0
  84. package/src/__augment-tests__/augment.ts +81 -0
  85. package/src/__augment-tests__/augmented.check.ts +116 -0
  86. package/src/__internal.ts +1 -66
  87. package/src/browser/action-coordinator.ts +53 -36
  88. package/src/browser/action-fence.ts +47 -0
  89. package/src/browser/app-shell.ts +39 -0
  90. package/src/browser/app-version.ts +14 -0
  91. package/src/browser/connection-warmup.ts +134 -0
  92. package/src/browser/cookie-name.ts +140 -0
  93. package/src/browser/event-controller.ts +257 -158
  94. package/src/browser/history-state.ts +21 -0
  95. package/src/browser/index.ts +3 -3
  96. package/src/browser/invalidate-client-cache.ts +52 -0
  97. package/src/browser/logging.ts +28 -0
  98. package/src/browser/merge-segment-loaders.ts +6 -4
  99. package/src/browser/navigation-bridge.ts +132 -33
  100. package/src/browser/navigation-client.ts +218 -68
  101. package/src/browser/navigation-store-handle.ts +38 -0
  102. package/src/browser/navigation-store.ts +203 -80
  103. package/src/browser/navigation-transaction.ts +18 -66
  104. package/src/browser/network-error-handler.ts +34 -7
  105. package/src/browser/partial-update.ts +241 -127
  106. package/src/browser/prefetch/cache.ts +271 -44
  107. package/src/browser/prefetch/fetch.ts +367 -40
  108. package/src/browser/prefetch/queue.ts +144 -23
  109. package/src/browser/prefetch/resource-ready.ts +77 -0
  110. package/src/browser/rango-state.ts +158 -76
  111. package/src/browser/react/Link.tsx +121 -16
  112. package/src/browser/react/NavigationProvider.tsx +240 -122
  113. package/src/browser/react/ScrollRestoration.tsx +10 -6
  114. package/src/browser/react/context.ts +7 -2
  115. package/src/browser/react/filter-segment-order.ts +66 -7
  116. package/src/browser/react/index.ts +0 -48
  117. package/src/browser/react/location-state-shared.ts +178 -8
  118. package/src/browser/react/location-state.ts +39 -14
  119. package/src/browser/react/use-action.ts +6 -15
  120. package/src/browser/react/use-handle.ts +23 -69
  121. package/src/browser/react/use-href.tsx +8 -1
  122. package/src/browser/react/use-link-status.ts +33 -8
  123. package/src/browser/react/use-navigation.ts +32 -7
  124. package/src/browser/react/use-params.ts +20 -10
  125. package/src/browser/react/use-reverse.ts +106 -0
  126. package/src/browser/react/use-router.ts +46 -11
  127. package/src/browser/react/use-search-params.ts +0 -5
  128. package/src/browser/react/use-segments.ts +11 -21
  129. package/src/browser/response-adapter.ts +99 -8
  130. package/src/browser/rsc-router.tsx +272 -80
  131. package/src/browser/scroll-restoration.ts +56 -22
  132. package/src/browser/segment-reconciler.ts +44 -7
  133. package/src/browser/segment-structure-assert.ts +2 -2
  134. package/src/browser/server-action-bridge.ts +244 -71
  135. package/src/browser/types.ts +136 -12
  136. package/src/browser/validate-redirect-origin.ts +43 -16
  137. package/src/build/collect-fallback-refs.ts +107 -0
  138. package/src/build/generate-manifest.ts +207 -158
  139. package/src/build/generate-route-types.ts +6 -1
  140. package/src/build/index.ts +11 -3
  141. package/src/build/prefix-tree-utils.ts +123 -0
  142. package/src/build/route-trie.ts +198 -41
  143. package/src/build/route-types/ast-route-extraction.ts +15 -8
  144. package/src/build/route-types/codegen.ts +16 -5
  145. package/src/build/route-types/include-resolution.ts +464 -63
  146. package/src/build/route-types/param-extraction.ts +6 -3
  147. package/src/build/route-types/per-module-writer.ts +22 -6
  148. package/src/build/route-types/router-processing.ts +336 -110
  149. package/src/build/route-types/scan-filter.ts +9 -2
  150. package/src/build/route-types/source-scan.ts +216 -0
  151. package/src/build/runtime-discovery.ts +13 -21
  152. package/src/cache/cache-error.ts +104 -0
  153. package/src/cache/cache-key-utils.ts +58 -13
  154. package/src/cache/cache-policy.ts +108 -34
  155. package/src/cache/cache-runtime.ts +454 -97
  156. package/src/cache/cache-scope.ts +235 -103
  157. package/src/cache/cache-tag.ts +149 -0
  158. package/src/cache/cf/cf-base64.ts +33 -0
  159. package/src/cache/cf/cf-cache-constants.ts +127 -0
  160. package/src/cache/cf/cf-cache-store.ts +2446 -170
  161. package/src/cache/cf/cf-cache-types.ts +349 -0
  162. package/src/cache/cf/cf-kv-utils.ts +46 -0
  163. package/src/cache/cf/cf-tag-marker-memo.ts +105 -0
  164. package/src/cache/cf/index.ts +11 -17
  165. package/src/cache/document-cache.ts +144 -49
  166. package/src/cache/handle-snapshot.ts +70 -0
  167. package/src/cache/index.ts +24 -20
  168. package/src/cache/memory-segment-store.ts +243 -37
  169. package/src/cache/profile-registry.ts +46 -31
  170. package/src/cache/read-through-swr.ts +56 -12
  171. package/src/cache/segment-codec.ts +13 -21
  172. package/src/cache/shell-snapshot.ts +417 -0
  173. package/src/cache/tag-invalidation.ts +230 -0
  174. package/src/cache/taint.ts +55 -0
  175. package/src/cache/types.ts +194 -99
  176. package/src/cache/vercel/index.ts +11 -0
  177. package/src/cache/vercel/vercel-cache-store.ts +1132 -0
  178. package/src/client.rsc.tsx +41 -21
  179. package/src/client.tsx +116 -290
  180. package/src/cloudflare/index.ts +11 -0
  181. package/src/cloudflare/tracing.ts +108 -0
  182. package/src/component-utils.ts +19 -0
  183. package/src/components/DefaultDocument.tsx +8 -2
  184. package/src/context-var.ts +84 -2
  185. package/src/debug.ts +2 -2
  186. package/src/decode-loader-results.ts +52 -0
  187. package/src/defer.ts +185 -0
  188. package/src/deps/ssr.ts +0 -1
  189. package/src/encode-kv.ts +49 -0
  190. package/src/errors.ts +30 -4
  191. package/src/escape-script.ts +52 -0
  192. package/src/handle.ts +104 -34
  193. package/src/handles/MetaTags.tsx +24 -53
  194. package/src/handles/Scripts.tsx +183 -0
  195. package/src/handles/breadcrumbs.ts +35 -8
  196. package/src/handles/deferred-resolution.ts +127 -0
  197. package/src/handles/is-thenable.ts +18 -0
  198. package/src/handles/meta.ts +14 -40
  199. package/src/handles/script.ts +244 -0
  200. package/src/host/cookie-handler.ts +9 -60
  201. package/src/host/errors.ts +13 -22
  202. package/src/host/index.ts +9 -2
  203. package/src/host/pattern-matcher.ts +23 -52
  204. package/src/host/router.ts +107 -99
  205. package/src/host/testing.ts +40 -27
  206. package/src/host/types.ts +37 -4
  207. package/src/host/utils.ts +1 -1
  208. package/src/href-client.ts +137 -22
  209. package/src/index.rsc.ts +100 -13
  210. package/src/index.ts +143 -19
  211. package/src/internal-debug.ts +11 -10
  212. package/src/loader-store.ts +500 -0
  213. package/src/loader.rsc.ts +20 -13
  214. package/src/loader.ts +12 -11
  215. package/src/missing-id-error.ts +68 -0
  216. package/src/outlet-context.ts +1 -1
  217. package/src/outlet-provider.tsx +1 -5
  218. package/src/prerender/param-hash.ts +16 -16
  219. package/src/prerender/store.ts +37 -41
  220. package/src/prerender.ts +215 -86
  221. package/src/redirect-origin.ts +114 -0
  222. package/src/regex-escape.ts +8 -0
  223. package/src/render-error-thrower.tsx +20 -0
  224. package/src/response-utils.ts +62 -0
  225. package/src/reverse.ts +65 -15
  226. package/src/root-error-boundary.tsx +1 -19
  227. package/src/route-content-wrapper.tsx +19 -77
  228. package/src/route-definition/dsl-helpers.ts +485 -303
  229. package/src/route-definition/helper-factories.ts +28 -140
  230. package/src/route-definition/helpers-types.ts +153 -77
  231. package/src/route-definition/index.ts +4 -2
  232. package/src/route-definition/redirect.ts +53 -12
  233. package/src/route-definition/resolve-handler-use.ts +160 -0
  234. package/src/route-definition/use-item-types.ts +29 -0
  235. package/src/route-map-builder.ts +48 -21
  236. package/src/route-types.ts +37 -46
  237. package/src/router/basename.ts +14 -0
  238. package/src/router/content-negotiation.ts +164 -17
  239. package/src/router/error-handling.ts +45 -18
  240. package/src/router/find-match.ts +130 -29
  241. package/src/router/handler-context.ts +83 -39
  242. package/src/router/instrument.ts +355 -0
  243. package/src/router/intercept-resolution.ts +50 -24
  244. package/src/router/lazy-includes.ts +89 -63
  245. package/src/router/loader-resolution.ts +286 -56
  246. package/src/router/logging.ts +5 -8
  247. package/src/router/manifest.ts +105 -56
  248. package/src/router/match-api.ts +178 -218
  249. package/src/router/match-context.ts +0 -22
  250. package/src/router/match-handlers.ts +211 -165
  251. package/src/router/match-middleware/background-revalidation.ts +66 -22
  252. package/src/router/match-middleware/cache-lookup.ts +214 -263
  253. package/src/router/match-middleware/cache-store.ts +105 -50
  254. package/src/router/match-middleware/intercept-resolution.ts +8 -28
  255. package/src/router/match-middleware/segment-resolution.ts +52 -18
  256. package/src/router/match-pipelines.ts +1 -42
  257. package/src/router/match-result.ts +128 -44
  258. package/src/router/metrics.ts +5 -34
  259. package/src/router/middleware-types.ts +13 -142
  260. package/src/router/middleware.ts +301 -177
  261. package/src/router/navigation-snapshot.ts +133 -0
  262. package/src/router/params-util.ts +23 -0
  263. package/src/router/parse-pattern.ts +115 -0
  264. package/src/router/pattern-matching.ts +181 -150
  265. package/src/router/prefetch-cache-ttl.ts +51 -0
  266. package/src/router/prefetch-limits.ts +37 -0
  267. package/src/router/prerender-match.ts +203 -58
  268. package/src/router/preview-match.ts +35 -103
  269. package/src/router/request-classification.ts +291 -0
  270. package/src/router/revalidation.ts +123 -73
  271. package/src/router/route-snapshot.ts +256 -0
  272. package/src/router/router-context.ts +11 -29
  273. package/src/router/router-interfaces.ts +146 -35
  274. package/src/router/router-options.ts +202 -15
  275. package/src/router/router-registry.ts +2 -5
  276. package/src/router/segment-resolution/fresh.ts +301 -78
  277. package/src/router/segment-resolution/helpers.ts +115 -30
  278. package/src/router/segment-resolution/loader-cache.ts +156 -39
  279. package/src/router/segment-resolution/loader-mask.ts +60 -0
  280. package/src/router/segment-resolution/loader-snapshot.ts +259 -0
  281. package/src/router/segment-resolution/mask-nested.ts +83 -0
  282. package/src/router/segment-resolution/revalidation.ts +477 -385
  283. package/src/router/segment-resolution/static-store.ts +19 -5
  284. package/src/router/segment-resolution/streamed-handler-telemetry.ts +52 -0
  285. package/src/router/segment-resolution/view-transition-default.ts +56 -0
  286. package/src/router/segment-resolution.ts +5 -1
  287. package/src/router/segment-wrappers.ts +8 -5
  288. package/src/router/state-cookie-name.ts +33 -0
  289. package/src/router/substitute-pattern-params.ts +75 -0
  290. package/src/router/telemetry-otel.ts +160 -200
  291. package/src/router/telemetry.ts +105 -20
  292. package/src/router/timeout.ts +0 -20
  293. package/src/router/tracing.ts +215 -0
  294. package/src/router/trie-matching.ts +171 -59
  295. package/src/router/types.ts +10 -63
  296. package/src/router/url-params.ts +57 -0
  297. package/src/router.ts +210 -71
  298. package/src/rsc/full-payload.ts +70 -0
  299. package/src/rsc/handler-context.ts +3 -2
  300. package/src/rsc/handler.ts +682 -508
  301. package/src/rsc/helpers.ts +168 -46
  302. package/src/rsc/index.ts +2 -5
  303. package/src/rsc/json-route-result.ts +38 -0
  304. package/src/rsc/loader-fetch.ts +127 -31
  305. package/src/rsc/manifest-init.ts +33 -42
  306. package/src/rsc/nonce.ts +10 -1
  307. package/src/rsc/origin-guard.ts +39 -25
  308. package/src/rsc/progressive-enhancement.ts +138 -15
  309. package/src/rsc/redirect-guard.ts +100 -0
  310. package/src/rsc/response-cache-serve.ts +238 -0
  311. package/src/rsc/response-error.ts +79 -12
  312. package/src/rsc/response-route-handler.ts +99 -189
  313. package/src/rsc/rsc-rendering.ts +509 -73
  314. package/src/rsc/runtime-warnings.ts +23 -10
  315. package/src/rsc/server-action.ts +287 -113
  316. package/src/rsc/shell-capture.ts +1190 -0
  317. package/src/rsc/shell-serve.ts +181 -0
  318. package/src/rsc/ssr-setup.ts +18 -2
  319. package/src/rsc/transition-gate.ts +89 -0
  320. package/src/rsc/types.ts +62 -6
  321. package/src/runtime-env.ts +18 -0
  322. package/src/search-params.ts +35 -30
  323. package/src/segment-content-promise.ts +67 -0
  324. package/src/segment-loader-promise.ts +167 -0
  325. package/src/segment-system.tsx +449 -132
  326. package/src/serialize.ts +243 -0
  327. package/src/server/context.ts +367 -61
  328. package/src/server/cookie-parse.ts +32 -0
  329. package/src/server/cookie-store.ts +152 -5
  330. package/src/server/handle-store.ts +40 -38
  331. package/src/server/loader-registry.ts +38 -46
  332. package/src/server/request-context.ts +558 -173
  333. package/src/ssr/index.tsx +491 -174
  334. package/src/ssr/inject-rsc-eager.ts +167 -0
  335. package/src/ssr/ssr-root.tsx +228 -0
  336. package/src/static-handler.ts +27 -18
  337. package/src/testing/cache-status.ts +162 -0
  338. package/src/testing/collect-handle.ts +46 -0
  339. package/src/testing/dispatch.ts +813 -0
  340. package/src/testing/dom.entry.ts +22 -0
  341. package/src/testing/e2e/fixture.ts +188 -0
  342. package/src/testing/e2e/index.ts +128 -0
  343. package/src/testing/e2e/matchers.ts +35 -0
  344. package/src/testing/e2e/page-helpers.ts +272 -0
  345. package/src/testing/e2e/parity.ts +387 -0
  346. package/src/testing/e2e/server.ts +195 -0
  347. package/src/testing/flight-matchers.ts +97 -0
  348. package/src/testing/flight-normalize.ts +11 -0
  349. package/src/testing/flight-runtime.d.ts +57 -0
  350. package/src/testing/flight-tree.ts +682 -0
  351. package/src/testing/flight.entry.ts +52 -0
  352. package/src/testing/flight.ts +257 -0
  353. package/src/testing/generated-routes.ts +199 -0
  354. package/src/testing/index.ts +105 -0
  355. package/src/testing/internal/context.ts +371 -0
  356. package/src/testing/internal/flight-client-globals.ts +30 -0
  357. package/src/testing/internal/seed-vars.ts +54 -0
  358. package/src/testing/render-handler.ts +357 -0
  359. package/src/testing/render-route.tsx +584 -0
  360. package/src/testing/run-loader.ts +385 -0
  361. package/src/testing/run-middleware.ts +205 -0
  362. package/src/testing/run-transition-when.ts +164 -0
  363. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  364. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  365. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  366. package/src/testing/vitest-stubs/version.ts +5 -0
  367. package/src/testing/vitest.ts +305 -0
  368. package/src/theme/ThemeProvider.tsx +56 -84
  369. package/src/theme/ThemeScript.tsx +7 -9
  370. package/src/theme/constants.ts +52 -13
  371. package/src/theme/index.ts +0 -7
  372. package/src/theme/theme-context.ts +1 -5
  373. package/src/theme/theme-script.ts +22 -21
  374. package/src/theme/use-theme.ts +0 -3
  375. package/src/types/boundaries.ts +0 -35
  376. package/src/types/cache-types.ts +17 -8
  377. package/src/types/error-types.ts +30 -90
  378. package/src/types/global-namespace.ts +54 -41
  379. package/src/types/handler-context.ts +234 -82
  380. package/src/types/index.ts +3 -10
  381. package/src/types/loader-types.ts +44 -15
  382. package/src/types/request-scope.ts +112 -0
  383. package/src/types/route-config.ts +20 -52
  384. package/src/types/route-entry.ts +19 -7
  385. package/src/types/segments.ts +137 -14
  386. package/src/urls/include-helper.ts +40 -75
  387. package/src/urls/include-provider.ts +71 -0
  388. package/src/urls/index.ts +2 -11
  389. package/src/urls/path-helper-types.ts +102 -23
  390. package/src/urls/path-helper.ts +62 -111
  391. package/src/urls/pattern-types.ts +84 -19
  392. package/src/urls/response-types.ts +25 -22
  393. package/src/urls/type-extraction.ts +98 -154
  394. package/src/urls/urls-function.ts +1 -19
  395. package/src/use-loader.tsx +346 -89
  396. package/src/vercel/index.ts +11 -0
  397. package/src/vercel/tracing.ts +88 -0
  398. package/src/vite/debug.ts +185 -0
  399. package/src/vite/discovery/bundle-postprocess.ts +36 -38
  400. package/src/vite/discovery/dev-prerender-cache.ts +117 -0
  401. package/src/vite/discovery/discover-routers.ts +130 -85
  402. package/src/vite/discovery/discovery-errors.ts +255 -0
  403. package/src/vite/discovery/gate-state.ts +171 -0
  404. package/src/vite/discovery/prerender-collection.ts +214 -132
  405. package/src/vite/discovery/route-types-writer.ts +40 -84
  406. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  407. package/src/vite/discovery/state.ts +57 -6
  408. package/src/vite/discovery/virtual-module-codegen.ts +14 -34
  409. package/src/vite/index.ts +15 -0
  410. package/src/vite/inject-client-debug.ts +88 -0
  411. package/src/vite/plugin-types.ts +234 -62
  412. package/src/vite/plugins/cjs-to-esm.ts +16 -19
  413. package/src/vite/plugins/client-ref-dedup.ts +16 -11
  414. package/src/vite/plugins/client-ref-hashing.ts +28 -15
  415. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  416. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  417. package/src/vite/plugins/cloudflare-protocol-stub.ts +194 -0
  418. package/src/vite/plugins/expose-action-id.ts +49 -98
  419. package/src/vite/plugins/expose-id-utils.ts +96 -51
  420. package/src/vite/plugins/expose-ids/export-analysis.ts +101 -34
  421. package/src/vite/plugins/expose-ids/handler-transform.ts +15 -64
  422. package/src/vite/plugins/expose-ids/loader-transform.ts +14 -24
  423. package/src/vite/plugins/expose-ids/router-transform.ts +118 -29
  424. package/src/vite/plugins/expose-internal-ids.ts +553 -317
  425. package/src/vite/plugins/performance-tracks.ts +89 -0
  426. package/src/vite/plugins/refresh-cmd.ts +89 -27
  427. package/src/vite/plugins/use-cache-transform.ts +73 -83
  428. package/src/vite/plugins/vercel-output.ts +384 -0
  429. package/src/vite/plugins/version-injector.ts +40 -29
  430. package/src/vite/plugins/version-plugin.ts +46 -37
  431. package/src/vite/plugins/virtual-entries.ts +138 -27
  432. package/src/vite/rango.ts +353 -303
  433. package/src/vite/router-discovery.ts +1090 -166
  434. package/src/vite/utils/ast-handler-extract.ts +26 -35
  435. package/src/vite/utils/banner.ts +4 -4
  436. package/src/vite/utils/bundle-analysis.ts +10 -15
  437. package/src/vite/utils/client-chunks.ts +184 -0
  438. package/src/vite/utils/directive-prologue.ts +40 -0
  439. package/src/vite/utils/forward-user-plugins.ts +171 -0
  440. package/src/vite/utils/manifest-utils.ts +4 -59
  441. package/src/vite/utils/package-resolution.ts +20 -52
  442. package/src/vite/utils/prerender-utils.ts +98 -38
  443. package/src/vite/utils/shared-utils.ts +144 -44
  444. package/src/browser/action-response-classifier.ts +0 -99
  445. package/src/browser/react/use-client-cache.ts +0 -58
  446. package/src/browser/shallow.ts +0 -40
  447. package/src/handles/index.ts +0 -7
  448. package/src/network-error-thrower.tsx +0 -23
  449. package/src/router/middleware-cookies.ts +0 -55
@@ -10,14 +10,25 @@ import type { Plugin } from "vite";
10
10
  import { createServer as createViteServer } from "vite";
11
11
  import { resolve } from "node:path";
12
12
  import { readFileSync } from "node:fs";
13
+ import { createRequire, register } from "node:module";
14
+ import { pathToFileURL } from "node:url";
13
15
  import {
14
16
  formatNestedRouterConflictError,
15
17
  findNestedRouterConflict,
16
18
  findRouterFiles,
17
19
  createScanFilter,
18
20
  } from "../build/generate-route-types.js";
21
+ import { firstCodeMatchIndex } from "../build/route-types/source-scan.js";
22
+ import {
23
+ injectClientDebugFlag,
24
+ internalDebugNoCacheMiddleware,
25
+ } from "./inject-client-debug.js";
19
26
  import { createVersionPlugin } from "./plugins/version-plugin.js";
20
27
  import { createVirtualStubPlugin } from "./plugins/virtual-stub-plugin.js";
28
+ import {
29
+ BUILD_ENV_GLOBAL_KEY,
30
+ createCloudflareProtocolStubPlugin,
31
+ } from "./plugins/cloudflare-protocol-stub.js";
21
32
  import {
22
33
  exposeInternalIds,
23
34
  exposeRouterId,
@@ -30,8 +41,17 @@ import {
30
41
  type DiscoveryState,
31
42
  type PluginOptions,
32
43
  } from "./discovery/state.js";
33
- import { consumeSelfGenWrite } from "./discovery/self-gen-tracking.js";
44
+ import {
45
+ consumeSelfGenWrite,
46
+ peekSelfGenWrite,
47
+ } from "./discovery/self-gen-tracking.js";
34
48
  import { discoverRouters } from "./discovery/discover-routers.js";
49
+ import { describeDiscoveryFailure } from "./discovery/discovery-errors.js";
50
+ import {
51
+ createDevPrerenderCache,
52
+ devPrerenderCacheKey,
53
+ payloadBodiesFromResult,
54
+ } from "./discovery/dev-prerender-cache.js";
35
55
  import {
36
56
  writeCombinedRouteTypesWithTracking,
37
57
  writeRouteTypesFiles,
@@ -42,10 +62,65 @@ import {
42
62
  generatePerRouterModule,
43
63
  } from "./discovery/virtual-module-codegen.js";
44
64
  import { postprocessBundle } from "./discovery/bundle-postprocess.js";
65
+ import { createDiscoveryGate } from "./discovery/gate-state.js";
45
66
  import { resetStagedBuildAssets } from "./utils/prerender-utils.js";
67
+ import { resolveRscEntryFromConfig } from "./utils/shared-utils.js";
68
+ import {
69
+ pickForwardedRunnerConfig,
70
+ selectForwardableResolvePlugins,
71
+ } from "./utils/forward-user-plugins.js";
72
+ import { createRangoDebugger, timed, timedSync, NS } from "./debug.js";
73
+
74
+ const debugDiscovery = createRangoDebugger(NS.discovery);
75
+ const debugRoutes = createRangoDebugger(NS.routes);
76
+ const debugBuild = createRangoDebugger(NS.build);
77
+ const debugDev = createRangoDebugger(NS.dev);
46
78
 
47
79
  export { VIRTUAL_ROUTES_MANIFEST_ID };
48
80
 
81
+ // ============================================================================
82
+ // Node ESM Loader Hook Registration
83
+ // ============================================================================
84
+
85
+ /**
86
+ * Registers a Node ESM loader hook that resolves `cloudflare:*` specifiers
87
+ * to a data: URL stub. Defense-in-depth alongside the Vite transform in
88
+ * `cloudflare-protocol-stub.ts`:
89
+ *
90
+ * - The Vite transform catches `cloudflare:*` imports in modules that flow
91
+ * through Vite's plugin pipeline. That's the vast majority of cases.
92
+ * - The Node loader catches imports in modules that Vite/Rollup externalize
93
+ * (e.g. the `partyserver` package, which has a top-level
94
+ * `import { DurableObject, env } from "cloudflare:workers"` and ships
95
+ * shapes plugin-rsc marks as external). Externalized modules are loaded
96
+ * via Node's native ESM loader, which rejects URL schemes.
97
+ *
98
+ * Registration is process-global and one-shot. The hook only intercepts
99
+ * `cloudflare:*` specifiers; everything else passes through via
100
+ * `nextResolve()`. It runs in a separate worker thread (Node ESM loader
101
+ * architecture), so it can't read the `globalThis[BUILD_ENV_GLOBAL_KEY]`
102
+ * bridge that the Vite transform uses — the stubs served here always
103
+ * return `env = {}`. That's fine because externalized libraries don't
104
+ * typically access `env` at module top level; user source (where real
105
+ * `env` matters at build time) flows through the Vite transform.
106
+ */
107
+ let loaderHookRegistered = false;
108
+ function ensureCloudflareProtocolLoaderRegistered(): void {
109
+ if (loaderHookRegistered) return;
110
+ loaderHookRegistered = true;
111
+ try {
112
+ register(
113
+ new URL("./plugins/cloudflare-protocol-loader-hook.mjs", import.meta.url),
114
+ );
115
+ } catch (err: any) {
116
+ // register() requires Node 18.19+ / 20.6+. Older Node still has the
117
+ // Vite transform as primary defense.
118
+ console.warn(
119
+ `[rango] Could not register Node ESM loader hook for cloudflare:* imports (${err?.message ?? err}). Falling back to Vite transform only.`,
120
+ );
121
+ }
122
+ }
123
+
49
124
  // ============================================================================
50
125
  // Temp Server Factory
51
126
  // ============================================================================
@@ -65,15 +140,32 @@ async function createTempRscServer(
65
140
  state: DiscoveryState,
66
141
  options: { forceBuild?: boolean; cacheDir?: string } = {},
67
142
  ) {
143
+ // Install the Node ESM loader hook before any module evaluation so
144
+ // `cloudflare:*` specifiers in externalized/loader-delegated modules
145
+ // (e.g. packages plugin-rsc marks as external) resolve to stubs
146
+ // instead of crashing Node's native loader.
147
+ ensureCloudflareProtocolLoaderRegistered();
68
148
  const { default: rsc } = await import("@vitejs/plugin-rsc");
149
+ // Mirror the user's resolution config + plugins so discovery (and the
150
+ // prerender/static rendering that shares this runner) resolves modules the
151
+ // same way the real environment does. Falls back to the legacy alias-only
152
+ // behavior if configResolved hasn't populated the parity slice yet.
153
+ const runnerConfig = state.userRunnerConfig;
154
+ const resolveConfig = runnerConfig?.resolve ?? {
155
+ alias: state.userResolveAlias,
156
+ };
157
+ const oxcConfig = runnerConfig?.oxc ?? {
158
+ jsx: { runtime: "automatic", importSource: "react" },
159
+ };
69
160
  return createViteServer({
70
161
  root: state.projectRoot,
71
162
  configFile: false,
72
163
  server: { middlewareMode: true },
73
164
  appType: "custom",
74
165
  logLevel: "silent",
75
- resolve: { alias: state.userResolveAlias },
76
- esbuild: { jsx: "automatic", jsxImportSource: "react" },
166
+ resolve: resolveConfig,
167
+ ...(runnerConfig?.define ? { define: runnerConfig.define } : {}),
168
+ oxc: oxcConfig as any,
77
169
  ...(options.cacheDir && { cacheDir: options.cacheDir }),
78
170
  plugins: [
79
171
  rsc({
@@ -87,14 +179,124 @@ async function createTempRscServer(
87
179
  ...(options.forceBuild ? [hashClientRefs(state.projectRoot)] : []),
88
180
  createVersionPlugin(),
89
181
  createVirtualStubPlugin(),
182
+ createCloudflareProtocolStubPlugin(),
90
183
  // Dev prerender must use dev-mode IDs (path-based) to match the workerd
91
184
  // runtime. forceBuild produces hashed IDs for production bundle consistency.
92
185
  exposeInternalIds(options.forceBuild ? { forceBuild: true } : undefined),
93
186
  exposeRouterId(),
187
+ // Forwarded user resolution plugins (e.g. vite-tsconfig-paths). Stripped
188
+ // to resolveId/load and placed last so framework resolution runs first;
189
+ // Vite re-sorts by `enforce`, so `enforce: "pre"` resolvers still lead.
190
+ ...state.userResolvePlugins,
94
191
  ],
95
192
  });
96
193
  }
97
194
 
195
+ // ============================================================================
196
+ // Build-Time Env Resolution
197
+ // ============================================================================
198
+
199
+ import type {
200
+ BuildEnvOption,
201
+ BuildEnvFactoryContext,
202
+ BuildEnvResult,
203
+ } from "./plugin-types.js";
204
+
205
+ /**
206
+ * Resolve the buildEnv option into a concrete { env, dispose? } result.
207
+ * Handles all four input shapes: false, "auto", factory, plain object.
208
+ */
209
+ async function resolveBuildEnv(
210
+ option: BuildEnvOption | undefined,
211
+ factoryCtx: BuildEnvFactoryContext,
212
+ ): Promise<BuildEnvResult | null> {
213
+ if (!option) return null;
214
+
215
+ if (option === "auto") {
216
+ if (factoryCtx.preset !== "cloudflare") {
217
+ throw new Error(
218
+ '[rango] buildEnv: "auto" is only supported with preset: "cloudflare". ' +
219
+ "Use a factory function or plain object for other presets.",
220
+ );
221
+ }
222
+ try {
223
+ // Resolve wrangler from the user's project root (not the router package)
224
+ const userRequire = createRequire(
225
+ resolve(factoryCtx.root, "package.json"),
226
+ );
227
+ const wranglerPath = userRequire.resolve("wrangler");
228
+ const { getPlatformProxy } = (await import(
229
+ pathToFileURL(wranglerPath).href
230
+ )) as {
231
+ getPlatformProxy: (opts?: any) => Promise<any>;
232
+ };
233
+ const proxy = await getPlatformProxy();
234
+ return {
235
+ env: proxy.env as Record<string, unknown>,
236
+ dispose: proxy.dispose,
237
+ };
238
+ } catch (err: any) {
239
+ throw new Error(
240
+ '[rango] buildEnv: "auto" requires wrangler to be installed.\n' +
241
+ `Install it with: pnpm add -D wrangler\n${err.message}`,
242
+ );
243
+ }
244
+ }
245
+
246
+ if (typeof option === "function") {
247
+ return await option(factoryCtx);
248
+ }
249
+
250
+ // Plain object
251
+ return { env: option };
252
+ }
253
+
254
+ /**
255
+ * Acquire build-time env bindings and store on discovery state.
256
+ * Returns true if env was acquired, false if buildEnv is disabled.
257
+ */
258
+ async function acquireBuildEnv(
259
+ s: DiscoveryState,
260
+ command: "serve" | "build",
261
+ mode: string,
262
+ ): Promise<boolean> {
263
+ const option = s.opts?.buildEnv;
264
+ if (!option) return false;
265
+
266
+ const result = await resolveBuildEnv(option, {
267
+ root: s.projectRoot,
268
+ mode,
269
+ command,
270
+ preset: s.opts?.preset ?? "node",
271
+ });
272
+ if (!result) return false;
273
+
274
+ s.resolvedBuildEnv = result.env;
275
+ s.buildEnvDispose = result.dispose ?? null;
276
+ // Bridge the resolved env into `cloudflare:workers`'s stubbed `env`
277
+ // export so user code that does `import { env } from "cloudflare:workers"`
278
+ // sees the real bindings proxy during discovery + prerender instead of
279
+ // an empty object. The stub reads this global at module-evaluation time.
280
+ (globalThis as Record<string, unknown>)[BUILD_ENV_GLOBAL_KEY] = result.env;
281
+ return true;
282
+ }
283
+
284
+ /**
285
+ * Release build-time env resources and clear state.
286
+ */
287
+ async function releaseBuildEnv(s: DiscoveryState): Promise<void> {
288
+ if (s.buildEnvDispose) {
289
+ try {
290
+ await s.buildEnvDispose();
291
+ } catch (err: any) {
292
+ console.warn(`[rango] buildEnv dispose failed: ${err.message}`);
293
+ }
294
+ s.buildEnvDispose = null;
295
+ }
296
+ s.resolvedBuildEnv = undefined;
297
+ delete (globalThis as Record<string, unknown>)[BUILD_ENV_GLOBAL_KEY];
298
+ }
299
+
98
300
  /**
99
301
  * Plugin that discovers router instances at dev/build time via the RSC environment.
100
302
  *
@@ -112,68 +314,56 @@ export function createRouterDiscoveryPlugin(
112
314
  opts?: PluginOptions,
113
315
  ): Plugin {
114
316
  const s = createDiscoveryState(entryPath, opts);
317
+ let viteCommand: "serve" | "build" = "build";
318
+ let viteMode = "production";
115
319
 
116
320
  return {
117
321
  name: "@rangojs/router:discovery",
118
322
 
119
- config() {
120
- const config: any = {
121
- define: {
122
- __RANGO_DEBUG__: JSON.stringify(!!process.env.INTERNAL_RANGO_DEBUG),
123
- },
124
- };
125
- if (opts?.enableBuildPrerender) {
126
- config.environments = {
127
- rsc: {
128
- build: {
129
- rollupOptions: {
130
- output: {
131
- manualChunks(id: string) {
132
- if (s.resolvedPrerenderModules?.has(id)) {
133
- return "__prerender-handlers";
134
- }
135
- if (s.resolvedStaticModules?.has(id)) {
136
- return "__static-handlers";
137
- }
138
- },
139
- },
140
- },
141
- },
142
- },
143
- };
144
- }
145
- return config;
323
+ // Make INTERNAL_RANGO_DEBUG reach the CLIENT debug logs by just setting the
324
+ // env var. See injectClientDebugFlag: bakes the resolved flag into the
325
+ // internal-debug module so FE debug no longer depends on Vite delivering the
326
+ // `__RANGO_DEBUG__` define to the client (which it does only as an injected
327
+ // global whose presence varies across consumer setups). Runs in dev and build.
328
+ transform(_code, id) {
329
+ return injectClientDebugFlag(id);
146
330
  },
147
331
 
148
332
  configResolved(config) {
149
333
  s.projectRoot = config.root;
334
+ // Compile the optional discovery scan filter (glob include/exclude) now
335
+ // that the project root is known. findRouterFiles() below — and the
336
+ // build/HMR rediscovery paths — honor s.scanFilter.
337
+ s.scanFilter = opts?.discovery
338
+ ? createScanFilter(s.projectRoot, opts.discovery)
339
+ : undefined;
150
340
  s.isBuildMode = config.command === "build";
341
+ viteCommand = config.command as "serve" | "build";
342
+ viteMode = config.mode;
151
343
  // Capture user's resolve aliases for the temp server
152
344
  s.userResolveAlias = config.resolve.alias;
345
+ // Capture the data-only resolution config (resolve.*, define, oxc) and
346
+ // the user's resolution plugins (resolveId/load) so the discovery temp
347
+ // server resolves modules the same way the real environment does.
348
+ // Without this, both flavors of user resolution are absent during
349
+ // discovery/prerender/static rendering even though they apply at request
350
+ // time: third-party resolvers (e.g. vite-tsconfig-paths, forwarded as
351
+ // plugins) and Vite 8's native resolve.tsconfigPaths (forwarded in the
352
+ // data slice). See utils/forward-user-plugins.ts.
353
+ s.userRunnerConfig = pickForwardedRunnerConfig(config);
354
+ s.userResolvePlugins = selectForwardableResolvePlugins(
355
+ config.plugins as any,
356
+ );
153
357
  // Node preset: pick up auto-discovered router path from the config() hook.
154
358
  // The auto-discover plugin runs in config() using Vite's resolved root,
155
359
  // populating the mutable ref before configResolved fires.
156
360
  if (!s.resolvedEntryPath && opts?.routerPathRef?.path) {
157
361
  s.resolvedEntryPath = opts.routerPathRef.path;
158
362
  }
159
- // Cloudflare preset: read entry from resolved environment config.
160
- // The @cloudflare/vite-plugin reads wrangler config (toml/json/jsonc)
161
- // and sets optimizeDeps.entries on the RSC environment.
363
+ // Cloudflare preset: entry comes from the resolved RSC env config.
162
364
  if (!s.resolvedEntryPath) {
163
- const rscEnvConfig = (config.environments as any)?.["rsc"];
164
- const entries = rscEnvConfig?.optimizeDeps?.entries;
165
- if (typeof entries === "string") {
166
- s.resolvedEntryPath = entries;
167
- } else if (Array.isArray(entries) && entries.length > 0) {
168
- s.resolvedEntryPath = entries[0];
169
- }
170
- }
171
- // Compile include/exclude patterns into a scan filter
172
- if (opts?.include || opts?.exclude) {
173
- s.scanFilter = createScanFilter(s.projectRoot, {
174
- include: opts.include,
175
- exclude: opts.exclude,
176
- });
365
+ const entry = resolveRscEntryFromConfig(config);
366
+ if (entry) s.resolvedEntryPath = entry;
177
367
  }
178
368
  // Generate combined named-routes.gen.ts from static source parsing.
179
369
  // Runs before the dev server starts so the gen file exists immediately for IDE.
@@ -205,6 +395,11 @@ export function createRouterDiscoveryPlugin(
205
395
  if ((globalThis as any).__rscRouterDiscoveryActive) return;
206
396
  s.devServer = server;
207
397
 
398
+ // Serve the internal-debug module no-cache: consumers resolve it into
399
+ // node_modules, where dev's immutable `?v=` caching pinned browsers to a
400
+ // stale baked INTERNAL_RANGO_DEBUG. See internalDebugNoCacheMiddleware.
401
+ server.middlewares.use(internalDebugNoCacheMiddleware());
402
+
208
403
  // Discovery promise that the handler can await if requests arrive
209
404
  // before discovery completes
210
405
  let resolveDiscovery: () => void;
@@ -212,6 +407,17 @@ export function createRouterDiscoveryPlugin(
212
407
  resolveDiscovery = resolve;
213
408
  });
214
409
 
410
+ // Manifest-readiness gate + rediscovery scheduler.
411
+ // The virtual:rsc-router/routes-manifest module's `load()` hook
412
+ // awaits `s.discoveryDone`; the gate is reset on each discovery
413
+ // cycle so workerd's HMR reloads block until the new gen file is
414
+ // written. State machine + transitions are extracted into
415
+ // ./discovery/gate-state.ts and unit-tested there — see the
416
+ // module's JSDoc for the four-flag contract.
417
+ const gate = createDiscoveryGate(s, debugDiscovery);
418
+ const beginDiscoveryGate = gate.beginGate;
419
+ const resolveDiscoveryGate = gate.resolveGate;
420
+
215
421
  // Compute dev server origin from resolved URLs (preferred) or config port (fallback).
216
422
  // Called after discovery (or in the load hook) when the server may be listening.
217
423
  const getDevServerOrigin = () =>
@@ -225,18 +431,113 @@ export function createRouterDiscoveryPlugin(
225
431
  let prerenderTempServer: any = null;
226
432
  let prerenderNodeRegistry: Map<string, any> | null = null;
227
433
 
228
- // Clean up the temporary server when the dev server shuts down
434
+ // Clean up the temporary server and build env when the dev server shuts down
229
435
  server.httpServer?.on("close", () => {
230
436
  if (prerenderTempServer) {
231
437
  prerenderTempServer.close().catch(() => {});
232
438
  prerenderTempServer = null;
233
439
  }
440
+ releaseBuildEnv(s).catch(() => {});
234
441
  });
235
442
 
443
+ // Mirror the build-path contract (the buildStart hook below, which sets
444
+ // __rscRouterDiscoveryActive before running user modules):
445
+ // set __rscRouterDiscoveryActive before running user modules so any
446
+ // module-level router.reverse() calls return a placeholder instead
447
+ // of throwing. The temp Vite server's module runner has its own
448
+ // module context; the flag must be on globalThis to cross that
449
+ // boundary. Cleared in finally so the dev request handlers run with
450
+ // strict reverse() semantics afterwards.
451
+ async function importEntryAndRegistry(tempRscEnv: any): Promise<void> {
452
+ const flagAlreadySet = !!(globalThis as any).__rscRouterDiscoveryActive;
453
+ if (!flagAlreadySet) {
454
+ (globalThis as any).__rscRouterDiscoveryActive = true;
455
+ }
456
+ try {
457
+ debugDiscovery?.(
458
+ "importEntryAndRegistry: importing entry (flag=%s)",
459
+ (globalThis as any).__rscRouterDiscoveryActive ?? false,
460
+ );
461
+ await tempRscEnv.runner.import(s.resolvedEntryPath!);
462
+ debugDiscovery?.(
463
+ "importEntryAndRegistry: entry import OK, fetching RouterRegistry",
464
+ );
465
+ const serverMod = await tempRscEnv.runner.import(
466
+ "@rangojs/router/server",
467
+ );
468
+ prerenderNodeRegistry = serverMod.RouterRegistry;
469
+ debugDiscovery?.(
470
+ "importEntryAndRegistry: registry size=%d",
471
+ prerenderNodeRegistry?.size ?? 0,
472
+ );
473
+ } finally {
474
+ if (!flagAlreadySet) {
475
+ delete (globalThis as any).__rscRouterDiscoveryActive;
476
+ debugDiscovery?.(
477
+ "importEntryAndRegistry: cleared __rscRouterDiscoveryActive",
478
+ );
479
+ }
480
+ }
481
+ }
482
+
236
483
  async function getOrCreateTempServer(): Promise<any | null> {
237
- if (prerenderNodeRegistry) {
238
- return (prerenderTempServer.environments as any)?.rsc ?? null;
484
+ // Reuse path: if a temp server is already alive, prefer reusing
485
+ // it over orphaning the existing instance and spinning up a new
486
+ // one. This handles two cases:
487
+ //
488
+ // 1. Steady-state cache hit (cold-start completed, registry
489
+ // cached) — return the env immediately.
490
+ // 2. Recovery from a failed refresh: refreshTempRscEnv() may
491
+ // have invalidated and nulled the registry, then thrown
492
+ // during importEntryAndRegistry. Without reuse, the next
493
+ // call would `createTempRscServer` and overwrite the
494
+ // handle, leaking the previous server. Try to re-import on
495
+ // the existing runner first; only if THAT fails do we
496
+ // close the orphan and create new.
497
+ if (prerenderTempServer) {
498
+ const existingEnv = (prerenderTempServer.environments as any)?.rsc;
499
+ if (existingEnv?.runner) {
500
+ if (prerenderNodeRegistry) {
501
+ debugDiscovery?.(
502
+ "getOrCreateTempServer: cached temp runner reused",
503
+ );
504
+ return existingEnv;
505
+ }
506
+ // Server alive but registry missing — likely after a prior
507
+ // refresh's invalidate + import threw. Try to re-import.
508
+ debugDiscovery?.(
509
+ "getOrCreateTempServer: server alive but registry missing — re-importing",
510
+ );
511
+ try {
512
+ await importEntryAndRegistry(existingEnv);
513
+ return existingEnv;
514
+ } catch (err: any) {
515
+ debugDiscovery?.(
516
+ "getOrCreateTempServer: reuse import failed (%s) — closing orphan and creating fresh",
517
+ err?.message ?? String(err),
518
+ );
519
+ await prerenderTempServer.close().catch(() => {});
520
+ prerenderTempServer = null;
521
+ prerenderNodeRegistry = null;
522
+ // Fall through to create-new path below.
523
+ }
524
+ } else {
525
+ // Server reference exists but its rsc env is unhealthy
526
+ // (no runner). Close and recreate.
527
+ debugDiscovery?.(
528
+ "getOrCreateTempServer: existing server has no rsc.runner — closing and recreating",
529
+ );
530
+ await prerenderTempServer.close().catch(() => {});
531
+ prerenderTempServer = null;
532
+ prerenderNodeRegistry = null;
533
+ }
239
534
  }
535
+
536
+ // Create path: no existing temp server (or just nullified above).
537
+ debugDiscovery?.(
538
+ "getOrCreateTempServer: creating new temp server, entry=%s",
539
+ s.resolvedEntryPath ?? "(unset)",
540
+ );
240
541
  try {
241
542
  prerenderTempServer = await createTempRscServer(s, {
242
543
  cacheDir: "node_modules/.vite_prerender",
@@ -244,59 +545,249 @@ export function createRouterDiscoveryPlugin(
244
545
 
245
546
  const tempRscEnv = (prerenderTempServer.environments as any)?.rsc;
246
547
  if (tempRscEnv?.runner) {
247
- await tempRscEnv.runner.import(s.resolvedEntryPath!);
248
- const serverMod = await tempRscEnv.runner.import(
249
- "@rangojs/router/server",
250
- );
251
- prerenderNodeRegistry = serverMod.RouterRegistry;
548
+ await importEntryAndRegistry(tempRscEnv);
252
549
  return tempRscEnv;
253
550
  }
551
+ debugDiscovery?.(
552
+ "getOrCreateTempServer: tempRscEnv.runner unavailable",
553
+ );
254
554
  } catch (err: any) {
255
- console.warn(
256
- `[rsc-router] Failed to create temp runner: ${err.message}`,
555
+ debugDiscovery?.(
556
+ "getOrCreateTempServer: FAILED message=%s",
557
+ err.message,
257
558
  );
559
+ console.warn(`[rango] Failed to create temp runner: ${err.message}`);
258
560
  }
561
+ // Reached only on failure (runner unavailable, or create/import threw
562
+ // AFTER the server was created). Close the just-created server so a
563
+ // failed discovery does not leak it until the next call or dev shutdown,
564
+ // and null the refs so the reuse path above starts clean. Mirrors the
565
+ // close pattern used when an existing server is discarded (above).
566
+ await prerenderTempServer?.close().catch(() => {});
567
+ prerenderTempServer = null;
568
+ prerenderNodeRegistry = null;
259
569
  return null;
260
570
  }
261
571
 
572
+ // Clear the package-level singleton registries that survive a Vite
573
+ // moduleGraph.invalidateAll(). createRouter() / createHostRouter()
574
+ // call .set(id, ...) on these Maps; for "router removed" or
575
+ // "router id changed" edits, the OLD entry would persist after
576
+ // re-import without an explicit .clear(), leaving ghost routes
577
+ // in discoverRouters' output.
578
+ //
579
+ // We import the same module the runner imports, so the .clear()
580
+ // here mutates the same Map the freshly re-imported entry will
581
+ // populate.
582
+ async function clearTempRegistries(tempRscEnv: any): Promise<void> {
583
+ try {
584
+ const serverMod = await tempRscEnv.runner.import(
585
+ "@rangojs/router/server",
586
+ );
587
+ if (typeof serverMod?.RouterRegistry?.clear === "function") {
588
+ serverMod.RouterRegistry.clear();
589
+ }
590
+ if (typeof serverMod?.HostRouterRegistry?.clear === "function") {
591
+ serverMod.HostRouterRegistry.clear();
592
+ }
593
+ debugDiscovery?.(
594
+ "clearTempRegistries: cleared RouterRegistry + HostRouterRegistry",
595
+ );
596
+ } catch (err: any) {
597
+ // Non-fatal: if the import fails here, importEntryAndRegistry
598
+ // below will fail loudly with the same root cause and the
599
+ // caller will surface it.
600
+ debugDiscovery?.(
601
+ "clearTempRegistries: import @rangojs/router/server failed (%s)",
602
+ err?.message ?? String(err),
603
+ );
604
+ }
605
+ }
606
+
607
+ // HMR refresh: keep the temp Vite server alive across HMR cycles and
608
+ // invalidate its module graph instead of close+recreate. Closing the
609
+ // temp server during workerd's first post-cold-start module-fetch
610
+ // window disrupted the main dev server's transport — the user-visible
611
+ // symptom was a `transport was disconnected, cannot call "fetchModule"`
612
+ // error on the first urls.tsx edit (workerd's cache was cold, so its
613
+ // eval was still in flight when our close() ran). Module-graph
614
+ // invalidation is the architecturally cleaner refresh: same Vite
615
+ // instance, same transport, fresh source.
616
+ //
617
+ // Falls back to close+recreate when neither the env-level nor
618
+ // server-level moduleGraph exposes invalidateAll() (defensive — Vite
619
+ // versions / preset configurations may differ in which graph carries
620
+ // the module-runner cache).
621
+ async function refreshTempRscEnv(): Promise<any | null> {
622
+ let tempRscEnv = await getOrCreateTempServer();
623
+ if (!tempRscEnv) return null;
624
+
625
+ // Module-runner cache is on the per-environment graph in Vite 6+;
626
+ // older / non-environments setups carry it on the server graph.
627
+ // Try env first, server second.
628
+ const envGraph = (tempRscEnv as any).moduleGraph;
629
+ const serverGraph = (prerenderTempServer as any)?.moduleGraph;
630
+ const target = envGraph?.invalidateAll
631
+ ? envGraph
632
+ : serverGraph?.invalidateAll
633
+ ? serverGraph
634
+ : null;
635
+
636
+ if (!target) {
637
+ // No invalidate method available — fall back to close+recreate.
638
+ // This preserves the previous behavior in case a Vite version
639
+ // doesn't expose invalidateAll on either graph.
640
+ debugDiscovery?.(
641
+ "refreshTempRscEnv: invalidateAll unavailable on env+server graphs, falling back to close+recreate",
642
+ );
643
+ if (prerenderTempServer) {
644
+ await prerenderTempServer.close().catch(() => {});
645
+ prerenderTempServer = null;
646
+ prerenderNodeRegistry = null;
647
+ }
648
+ return await getOrCreateTempServer();
649
+ }
650
+
651
+ debugDiscovery?.(
652
+ "refreshTempRscEnv: invalidating module graph (%s)",
653
+ envGraph?.invalidateAll ? "env" : "server",
654
+ );
655
+ target.invalidateAll();
656
+ // Drop the cached registry so importEntryAndRegistry re-reads it
657
+ // through the now-invalidated module runner.
658
+ prerenderNodeRegistry = null;
659
+ // Clear singleton Maps that Vite's moduleGraph invalidation can't
660
+ // reach (RouterRegistry / HostRouterRegistry). Without this, an
661
+ // edit that REMOVES a createRouter() call or CHANGES a router id
662
+ // would leave the old entry in the registry, and discoverRouters
663
+ // would still emit its routes alongside whatever the new source
664
+ // declares.
665
+ await clearTempRegistries(tempRscEnv);
666
+ await importEntryAndRegistry(tempRscEnv);
667
+ return tempRscEnv;
668
+ }
669
+
670
+ // Surface a discovery failure on either dev path (Node RSC runner or the
671
+ // Cloudflare temp Node server). `hashBefore`/`hashAfter` are the discovering
672
+ // environment's dep-optimizer browserHash snapshots: a change across the
673
+ // attempt means a reload-causing re-optimization landed mid-flight, so an
674
+ // empty registry was the transient race (downgraded to a warning) rather
675
+ // than a genuine misconfig (loud, actionable error). Shared so both catch
676
+ // sites frame the same failure identically.
677
+ const emitDiscoveryFailure = (
678
+ err: unknown,
679
+ hashBefore: string | undefined,
680
+ hashAfter: string | undefined,
681
+ ): void => {
682
+ const reoptimizeObserved =
683
+ hashBefore !== undefined &&
684
+ hashAfter !== undefined &&
685
+ hashBefore !== hashAfter;
686
+ const report = describeDiscoveryFailure(err, { reoptimizeObserved });
687
+ if (report.level === "warn") {
688
+ console.warn(report.message);
689
+ } else {
690
+ console.error(report.message);
691
+ }
692
+ };
693
+
262
694
  const discover = async () => {
695
+ const discoverStart = performance.now();
263
696
  const rscEnv = (server.environments as any)?.rsc;
264
697
  if (!rscEnv?.runner) {
265
698
  // Cloudflare dev: no module runner available (workerd-based RSC env).
266
699
  // Set devServerOrigin so the virtual module can inject __PRERENDER_DEV_URL
267
700
  // for on-demand prerender via the /__rsc_prerender endpoint.
701
+ debugDiscovery?.(
702
+ "dev: cloudflare path start, __rscRouterDiscoveryActive=%s",
703
+ (globalThis as any).__rscRouterDiscoveryActive ?? false,
704
+ );
268
705
  s.devServerOrigin = getDevServerOrigin();
269
706
 
270
707
  // Create a temp Node.js server to run runtime discovery and generate
271
708
  // named route types (static parser can't resolve factory calls).
709
+ // The temp server is a separate Vite instance with its own dep
710
+ // optimizer; snapshot ITS browserHash (hoisted so the catch can tell a
711
+ // transient re-optimization apart from a genuine empty registry, the
712
+ // same way the Node path below does).
713
+ let tempRscEnv: any;
714
+ let optimizerHashBefore: string | undefined;
272
715
  try {
273
- const tempRscEnv = await getOrCreateTempServer();
716
+ // Acquire build-time env bindings for dev prerender
717
+ await timed(debugDiscovery, "acquireBuildEnv", () =>
718
+ acquireBuildEnv(s, viteCommand, viteMode),
719
+ );
720
+
721
+ tempRscEnv = await timed(
722
+ debugDiscovery,
723
+ "getOrCreateTempServer",
724
+ () => getOrCreateTempServer(),
725
+ );
274
726
  if (tempRscEnv) {
275
- await discoverRouters(s, tempRscEnv);
276
- writeRouteTypesFiles(s);
727
+ optimizerHashBefore =
728
+ tempRscEnv.depsOptimizer?.metadata?.browserHash;
729
+ await timed(debugDiscovery, "discoverRouters (cloudflare)", () =>
730
+ discoverRouters(s, tempRscEnv),
731
+ );
732
+ timedSync(debugDiscovery, "writeRouteTypesFiles", () =>
733
+ writeRouteTypesFiles(s),
734
+ );
277
735
  }
278
736
  } catch (err: any) {
279
- console.warn(
280
- `[rsc-router] Cloudflare dev discovery failed: ${err.message}\n${err.stack}`,
737
+ emitDiscoveryFailure(
738
+ err,
739
+ optimizerHashBefore,
740
+ tempRscEnv?.depsOptimizer?.metadata?.browserHash,
281
741
  );
282
742
  }
283
743
 
744
+ debugDiscovery?.(
745
+ "dev discovery done (%sms)",
746
+ (performance.now() - discoverStart).toFixed(1),
747
+ );
284
748
  resolveDiscovery!();
285
749
  return;
286
750
  }
287
751
 
752
+ // Snapshot the dep-optimizer hash before discovery so the catch can tell
753
+ // a transient re-optimization race apart from a genuine empty registry.
754
+ // A reload-causing re-optimization regenerates browserHash; if it changed
755
+ // across the attempt, an empty read was almost certainly the race below.
756
+ const optimizerHashBefore: string | undefined =
757
+ rscEnv.depsOptimizer?.metadata?.browserHash;
758
+
288
759
  try {
289
- // Set the readiness gate BEFORE discovery so early requests
290
- // block until manifest is populated
291
- const serverMod = await rscEnv.runner.import(
292
- "@rangojs/router/server",
760
+ // Acquire build-time env bindings for dev prerender (Node.js path)
761
+ debugDiscovery?.("dev: node path start");
762
+ await timed(debugDiscovery, "acquireBuildEnv", () =>
763
+ acquireBuildEnv(s, viteCommand, viteMode),
764
+ );
765
+
766
+ // Discover routers FIRST, then arm the manifest-readiness gate on the
767
+ // server module discovery actually read the registry from.
768
+ //
769
+ // We deliberately do NOT pre-import "@rangojs/router/server" before the
770
+ // entry to arm the gate early. During a Vite dependency re-optimization
771
+ // (dev boot after a lockfile change, or `vite dev --force`), a module
772
+ // imported here before the entry resolves to the pre-optimize copy of
773
+ // the runner's module graph, while discoverRouters' entry import — which
774
+ // awaits the in-flight re-optimization — resolves to the post-optimize
775
+ // copy. createRouter() then populates RouterRegistry on the fresh copy,
776
+ // but a stale pre-imported "@rangojs/router/server" reads the other
777
+ // copy's empty Map and discovery throws a spurious "No routers found"
778
+ // even though the app is configured correctly. discoverRouters imports
779
+ // the entry first and reads the registry off the same instance, keeping
780
+ // read and write on one copy. The virtual manifest module's own gate
781
+ // (s.discoveryDone, armed by beginDiscoveryGate) already blocks early
782
+ // requests during discovery on the Node path, so arming
783
+ // manifestReadyPromise after discovery is sufficient here.
784
+ const serverMod = await timed(debugDiscovery, "discoverRouters", () =>
785
+ discoverRouters(s, rscEnv),
293
786
  );
294
787
  if (serverMod?.setManifestReadyPromise) {
295
788
  serverMod.setManifestReadyPromise(discoveryPromise);
296
789
  }
297
790
 
298
- await discoverRouters(s, rscEnv);
299
-
300
791
  // Store server origin for dev prerender endpoint (virtual module injection)
301
792
  s.devServerOrigin = getDevServerOrigin();
302
793
 
@@ -305,24 +796,38 @@ export function createRouterDiscoveryPlugin(
305
796
  // routes (e.g. Array.from loops) that the static parser cannot see.
306
797
  // writeRouteTypesFiles() only writes when content changes, so this
307
798
  // won't cause unnecessary HMR triggers.
308
- writeRouteTypesFiles(s);
799
+ timedSync(debugDiscovery, "writeRouteTypesFiles", () =>
800
+ writeRouteTypesFiles(s),
801
+ );
309
802
 
310
803
  // Populate the route map and per-router data in the RSC env
311
- await propagateDiscoveryState(rscEnv);
804
+ await timed(debugDiscovery, "propagateDiscoveryState", () =>
805
+ propagateDiscoveryState(rscEnv),
806
+ );
312
807
  } catch (err: any) {
313
- console.warn(
314
- `[rsc-router] Router discovery failed: ${err.message}\n${err.stack}`,
808
+ emitDiscoveryFailure(
809
+ err,
810
+ optimizerHashBefore,
811
+ rscEnv.depsOptimizer?.metadata?.browserHash,
315
812
  );
316
813
  } finally {
814
+ debugDiscovery?.(
815
+ "dev discovery done (%sms)",
816
+ (performance.now() - discoverStart).toFixed(1),
817
+ );
317
818
  resolveDiscovery!();
318
819
  }
319
820
  };
320
821
 
321
822
  // Schedule after all plugins have finished configureServer.
322
- // Store the promise so the virtual module's load hook can await it.
323
- s.discoveryDone = new Promise<void>((resolve) => {
324
- setTimeout(() => discover().then(resolve, resolve), 0);
325
- });
823
+ // The gate (s.discoveryDone) is reset via beginDiscoveryGate() and
824
+ // resolved when discover() finishes, so the virtual manifest module's
825
+ // load() awaits the populated state.
826
+ beginDiscoveryGate();
827
+ setTimeout(
828
+ () => discover().then(resolveDiscoveryGate, resolveDiscoveryGate),
829
+ 0,
830
+ );
326
831
 
327
832
  // Dev-mode on-demand prerender endpoint.
328
833
  // When workerd hits a prerender route, it fetches this endpoint instead of
@@ -336,6 +841,15 @@ export function createRouterDiscoveryPlugin(
336
841
  // Registry from the main server's RSC environment (populated by discoverRouters)
337
842
  let mainRegistry: Map<string, any> | null = null;
338
843
 
844
+ // Memoized /__rsc_prerender render results, keyed by router-instance
845
+ // identity (#654). The per-request entry re-import below is what makes
846
+ // identity a valid freshness key: an HMR-invalidated chain re-runs
847
+ // createRouter() and replaces the registry instance, so cached bodies
848
+ // for the old instance become unreachable; an untouched chain returns
849
+ // the same instance and the cached body is byte-identical to a fresh
850
+ // render. See dev-prerender-cache.ts for the full invariant.
851
+ const devPrerenderCache = createDevPrerenderCache();
852
+
339
853
  // Push discovery state (manifest, trie, precomputed entries) to the
340
854
  // server module so runtime request handling uses the current routes.
341
855
  // Shared by initial discovery and HMR-triggered re-discovery.
@@ -362,24 +876,30 @@ export function createRouterDiscoveryPlugin(
362
876
  if (s.mergedRouteTrie && serverMod.setRouteTrie) {
363
877
  serverMod.setRouteTrie(s.mergedRouteTrie);
364
878
  }
365
- if (serverMod.setRouterManifest) {
366
- for (const [routerId, manifest] of s.perRouterManifestDataMap) {
367
- serverMod.setRouterManifest(routerId, manifest);
368
- }
369
- }
370
- if (serverMod.setRouterTrie) {
371
- for (const [routerId, trie] of s.perRouterTrieMap) {
372
- serverMod.setRouterTrie(routerId, trie);
373
- }
374
- }
375
- if (serverMod.setRouterPrecomputedEntries) {
376
- for (const [routerId, entries] of s.perRouterPrecomputedMap) {
377
- serverMod.setRouterPrecomputedEntries(routerId, entries);
378
- }
879
+ const perRouterSetters: Array<[Map<string, any>, string]> = [
880
+ [s.perRouterManifestDataMap, "setRouterManifest"],
881
+ [s.perRouterTrieMap, "setRouterTrie"],
882
+ [s.perRouterPrecomputedMap, "setRouterPrecomputedEntries"],
883
+ ];
884
+ for (const [map, fn] of perRouterSetters) {
885
+ const setter = serverMod[fn];
886
+ if (typeof setter !== "function") continue;
887
+ for (const [routerId, value] of map) setter(routerId, value);
379
888
  }
380
889
  };
381
890
 
382
891
  server.middlewares.use("/__rsc_prerender", async (req: any, res: any) => {
892
+ const reqStart = debugDev ? performance.now() : 0;
893
+ const logResult = (status: number, note: string) => {
894
+ debugDev?.(
895
+ "/__rsc_prerender %s -> %d %s (%sms)",
896
+ req.url,
897
+ status,
898
+ note,
899
+ (performance.now() - reqStart).toFixed(1),
900
+ );
901
+ };
902
+
383
903
  if (s.discoveryDone) await s.discoveryDone;
384
904
 
385
905
  const url = new URL(req.url || "/", "http://localhost");
@@ -387,18 +907,61 @@ export function createRouterDiscoveryPlugin(
387
907
  if (!pathname) {
388
908
  res.statusCode = 400;
389
909
  res.end("Missing pathname");
910
+ logResult(400, "missing pathname");
390
911
  return;
391
912
  }
392
913
 
393
- // Prefer the main server's registry (Node.js preset: module runner available).
394
- // Fall back to a temp server for Cloudflare where the main RSC env uses workerd.
395
- let registry = mainRegistry;
914
+ // Import the user's entry module to force re-evaluation of any
915
+ // HMR-invalidated modules in the chain (entry router urls handlers).
916
+ // This ensures createRouter() re-runs with updated handler code before
917
+ // we read RouterRegistry. Without this, edits to prerender handler files
918
+ // produce stale content because the old router instance remains registered.
919
+ const rscEnv = (server.environments as any)?.rsc;
920
+ let registry: Map<string, any> | null = null;
921
+ if (rscEnv?.runner && s.resolvedEntryPath) {
922
+ try {
923
+ await rscEnv.runner.import(s.resolvedEntryPath);
924
+ const serverMod = await rscEnv.runner.import(
925
+ "@rangojs/router/server",
926
+ );
927
+ registry = serverMod.RouterRegistry ?? null;
928
+ } catch (err: any) {
929
+ console.warn(
930
+ `[rango] Dev prerender module refresh failed: ${err.message}`,
931
+ );
932
+ res.statusCode = 500;
933
+ res.end(`Prerender handler error: ${err.message}`);
934
+ logResult(500, "module refresh failed");
935
+ return;
936
+ }
937
+ } else {
938
+ registry = mainRegistry;
939
+ }
396
940
 
397
941
  if (!registry) {
398
942
  // No main registry: the RSC env has no module runner (Cloudflare dev).
399
- // Lazily create a Node.js temp server for prerender evaluation.
400
- if (!prerenderNodeRegistry) {
401
- await getOrCreateTempServer();
943
+ // Lazily create a Node.js temp server for prerender evaluation, and
944
+ // re-import the entry through it on EVERY request — the temp server
945
+ // has its own file watcher, so a handler-only edit (a file without
946
+ // urls()/createRouter() that the main watcher's route-file sniff
947
+ // ignores) invalidates its module graph; the re-import re-evaluates
948
+ // exactly the dirty subgraph and re-registers fresh router
949
+ // instances. Before #654 the cached registry was only refreshed on
950
+ // route-file edits, so handler-only edits served stale prerender
951
+ // content on this path. Warm-cache re-imports are module-cache hits.
952
+ const tempRscEnv = await getOrCreateTempServer();
953
+ if (tempRscEnv) {
954
+ try {
955
+ await importEntryAndRegistry(tempRscEnv);
956
+ } catch (err: any) {
957
+ console.warn(
958
+ `[rango] Dev prerender module refresh failed: ${err.message}`,
959
+ );
960
+ res.statusCode = 500;
961
+ res.end(`Prerender handler error: ${err.message}`);
962
+ logResult(500, "temp module refresh failed");
963
+ return;
964
+ }
402
965
  }
403
966
  registry = prerenderNodeRegistry;
404
967
  }
@@ -406,6 +969,7 @@ export function createRouterDiscoveryPlugin(
406
969
  if (!registry || registry.size === 0) {
407
970
  res.statusCode = 503;
408
971
  res.end("Prerender runner not available");
972
+ logResult(503, "no registry");
409
973
  return;
410
974
  }
411
975
 
@@ -413,14 +977,46 @@ export function createRouterDiscoveryPlugin(
413
977
  const wantRouteName = url.searchParams.get("routeName");
414
978
  const wantPassthrough = url.searchParams.get("passthrough") === "1";
415
979
 
980
+ // One render warms BOTH variant keys (matchForPrerender computes the
981
+ // intercept segments unconditionally), so a route's main and modal
982
+ // variants cost a single render per HMR generation.
983
+ const variantDims = {
984
+ passthrough: wantPassthrough,
985
+ routeName: wantRouteName,
986
+ };
987
+ const keyMain = devPrerenderCacheKey(pathname, {
988
+ intercept: false,
989
+ ...variantDims,
990
+ });
991
+ const keyIntercept = devPrerenderCacheKey(pathname, {
992
+ intercept: true,
993
+ ...variantDims,
994
+ });
995
+ const requestedKey = wantIntercept ? keyIntercept : keyMain;
996
+
416
997
  for (const [, routerInstance] of registry) {
417
998
  if (!routerInstance.matchForPrerender) continue;
999
+ // Cache is consulted per router IN LOOP ORDER so multi-router
1000
+ // fall-through semantics are identical to the uncached path: a
1001
+ // router that never produced a payload for this key still runs
1002
+ // its matchForPrerender (cheap trie miss / intentionally-uncached
1003
+ // error retry) before the next router is considered.
1004
+ const cached = devPrerenderCache.get(routerInstance, requestedKey);
1005
+ if (cached !== undefined) {
1006
+ res.setHeader("content-type", "application/json");
1007
+ res.setHeader("x-rango-prerender-cache", "HIT");
1008
+ res.end(cached);
1009
+ logResult(200, "cache hit");
1010
+ return;
1011
+ }
418
1012
  try {
419
1013
  const result = await routerInstance.matchForPrerender(
420
1014
  pathname,
421
1015
  {},
422
1016
  undefined,
423
1017
  wantPassthrough,
1018
+ s.resolvedBuildEnv,
1019
+ true, // devMode: check getParams for passthrough routes
424
1020
  );
425
1021
  if (!result) continue;
426
1022
  if (result.passthrough) continue;
@@ -428,30 +1024,37 @@ export function createRouterDiscoveryPlugin(
428
1024
  // This prevents returning the wrong entry when multiple routers
429
1025
  // have prerenderable routes sharing the same pathname.
430
1026
  if (wantRouteName && result.routeName !== wantRouteName) continue;
1027
+ // Pre-encoded MERGED handle string in the intercept body comes
1028
+ // from the producer (handles are Flight-encoded so
1029
+ // Promise/ReactNode values survive the wire).
1030
+ const bodies = payloadBodiesFromResult(result);
1031
+ devPrerenderCache.set(routerInstance, keyMain, bodies.main);
1032
+ devPrerenderCache.set(
1033
+ routerInstance,
1034
+ keyIntercept,
1035
+ bodies.intercept,
1036
+ );
431
1037
  res.setHeader("content-type", "application/json");
432
- let payload: Record<string, unknown>;
433
- if (wantIntercept && result.interceptSegments?.length) {
434
- payload = {
435
- segments: [...result.segments, ...result.interceptSegments],
436
- handles: {
437
- ...result.handles,
438
- ...(result.interceptHandles || {}),
439
- },
440
- };
441
- } else {
442
- payload = { segments: result.segments, handles: result.handles };
443
- }
444
- res.end(JSON.stringify(payload));
1038
+ res.setHeader("x-rango-prerender-cache", "MISS");
1039
+ res.end(wantIntercept ? bodies.intercept : bodies.main);
1040
+ logResult(200, `match ${result.routeName}`);
445
1041
  return;
446
1042
  } catch (err: any) {
447
- console.warn(
448
- `[rsc-router] Dev prerender failed for ${pathname}: ${err.message}`,
449
- );
1043
+ // matchForPrerender now re-throws render failures instead of baking
1044
+ // an error page (issue #587). In dev there is no frozen artifact, so
1045
+ // we fall through (404 -> live handler). A `throw new Skip()` is the
1046
+ // expected "skip this URL" signal, not a failure, so it stays quiet.
1047
+ if (err?.name !== "Skip") {
1048
+ console.warn(
1049
+ `[rango] Dev prerender error for ${pathname} (serving live instead): ${err.message}`,
1050
+ );
1051
+ }
450
1052
  }
451
1053
  }
452
1054
 
453
1055
  res.statusCode = 404;
454
1056
  res.end("No prerender match");
1057
+ logResult(404, "no match");
455
1058
  });
456
1059
 
457
1060
  // Watch url module and router files for changes and regenerate named-routes.gen.ts.
@@ -494,21 +1097,135 @@ export function createRouterDiscoveryPlugin(
494
1097
 
495
1098
  // Re-run runtime discovery so factory-generated routes that the
496
1099
  // static parser cannot see are refreshed after source changes.
497
- let runtimeRediscoveryInProgress = false;
1100
+ // The state-machine concerns (queued/pending/gatePending) are
1101
+ // owned by the gate created above (./discovery/gate-state.ts).
1102
+ // Here we provide just the env-specific work.
498
1103
  const refreshRuntimeDiscovery = async () => {
499
1104
  const rscEnv = (server.environments as any)?.rsc;
500
- if (!rscEnv?.runner || runtimeRediscoveryInProgress) return;
501
- runtimeRediscoveryInProgress = true;
1105
+ const hasMainRunner = !!rscEnv?.runner;
1106
+ // Cloudflare HMR has no main RSC runner (workerd is a separate
1107
+ // runtime). When we have a populated runtime manifest from cold
1108
+ // start, we can re-discover via the temp Node runner — the same
1109
+ // mechanism getOrCreateTempServer() uses at startup. Without a
1110
+ // populated manifest there's nothing useful to do, so bail
1111
+ // before involving the gate machine at all.
1112
+ if (!hasMainRunner && s.perRouterManifests.length === 0) return;
1113
+ await gate.runRefreshCycle(async () => {
1114
+ const hmrStart = performance.now();
1115
+ try {
1116
+ if (hasMainRunner) {
1117
+ await timed(debugDiscovery, "hmr discoverRouters", () =>
1118
+ discoverRouters(s, rscEnv),
1119
+ );
1120
+ timedSync(debugDiscovery, "hmr writeRouteTypesFiles", () =>
1121
+ writeRouteTypesFiles(s),
1122
+ );
1123
+ await timed(debugDiscovery, "hmr propagateDiscoveryState", () =>
1124
+ propagateDiscoveryState(rscEnv),
1125
+ );
1126
+ } else {
1127
+ // Cloudflare HMR: invalidate the temp server's RSC module
1128
+ // graph (or close+recreate as a fallback) so the runner
1129
+ // re-reads the freshly edited source. Keeping the same
1130
+ // Vite instance alive avoids disrupting workerd's transport
1131
+ // during the first post-cold-start module-fetch window.
1132
+ const tempRscEnv = await timed(
1133
+ debugDiscovery,
1134
+ "hmr refreshTempRscEnv (cloudflare)",
1135
+ () => refreshTempRscEnv(),
1136
+ );
1137
+ if (!tempRscEnv) {
1138
+ throw new Error(
1139
+ "temp runner unavailable for cloudflare HMR rediscovery",
1140
+ );
1141
+ }
1142
+ await timed(
1143
+ debugDiscovery,
1144
+ "hmr discoverRouters (cloudflare)",
1145
+ () => discoverRouters(s, tempRscEnv),
1146
+ );
1147
+ timedSync(debugDiscovery, "hmr writeRouteTypesFiles", () =>
1148
+ writeRouteTypesFiles(s),
1149
+ );
1150
+ }
1151
+ if (s.lastDiscoveryError) {
1152
+ debugDiscovery?.(
1153
+ "hmr: cleared lastDiscoveryError (%s) after successful rediscovery",
1154
+ s.lastDiscoveryError.message,
1155
+ );
1156
+ s.lastDiscoveryError = null;
1157
+ }
1158
+ // Cloudflare dev: on a successful cycle drop the workerd runner's
1159
+ // cached worker-entry chain so the next request re-evaluates
1160
+ // createRouter() with the new routes. Fired here in the work path
1161
+ // (not the caller's .then()) so a queued follow-up cycle that
1162
+ // succeeds after an earlier failed cycle still reloads:
1163
+ // runRefreshCycle recurses queued work without awaiting it, so the
1164
+ // original call already resolved on the failed cycle. A failed
1165
+ // cycle throws above and never reaches here, so a broken edit
1166
+ // never reloads the worker onto bad source.
1167
+ if (rscEnv && !rscEnv.runner) forceCloudflareWorkerReload(rscEnv);
1168
+ } catch (err: any) {
1169
+ s.lastDiscoveryError = {
1170
+ message: err?.message ?? String(err),
1171
+ at: Date.now(),
1172
+ };
1173
+ console.warn(
1174
+ `[rango] Runtime re-discovery failed: ${err.message}`,
1175
+ );
1176
+ debugDiscovery?.(
1177
+ "hmr: lastDiscoveryError set (%s) — manifest preserved at last-good; recovery mode active (any in-scan source change will trigger rediscovery)",
1178
+ err?.message,
1179
+ );
1180
+ } finally {
1181
+ debugDiscovery?.(
1182
+ "hmr re-discovery done (%sms)",
1183
+ (performance.now() - hmrStart).toFixed(1),
1184
+ );
1185
+ }
1186
+ });
1187
+ };
1188
+
1189
+ // Cloudflare dev only. workerd serves every request through the
1190
+ // runner-worker singleton, which re-resolves the worker entry per
1191
+ // request via runner.import("virtual:cloudflare/worker-entry"). The
1192
+ // route table lives in the user's createRouter() instance, captured
1193
+ // when that entry chain (entry -> router -> urls) was last evaluated
1194
+ // and then cached in the runner's evaluatedModules. The route-file
1195
+ // watcher refreshes discovery + types on the Node side, but the worker
1196
+ // keeps serving the cached (stale) router: route-definition modules
1197
+ // have no import.meta.hot boundary, so Vite never sends the worker an
1198
+ // HMR update for them and the entry chain is never evicted.
1199
+ //
1200
+ // Fix: after discovery completes, (1) invalidate the worker env's
1201
+ // Node-side module graph, then (2) send a full-reload to the worker.
1202
+ // Step (2) alone is insufficient: the full-reload handler clears the
1203
+ // runner's evaluatedModules and re-imports entrypoints, but each
1204
+ // re-import fetches the module back through this Node-side graph, which
1205
+ // still holds the pre-edit transform of urls.tsx — so createRouter()
1206
+ // rebuilds the stale route table and the new route 404s/hits the
1207
+ // catch-all. Invalidating the graph forces a fresh transform on
1208
+ // re-fetch (the same mechanism refreshTempRscEnv uses for discovery),
1209
+ // so the re-import re-runs createRouter() with the new routes. This is
1210
+ // the programmatic equivalent of the dev-server "r + enter" restart,
1211
+ // scoped to the worker environment instead of tearing down the server.
1212
+ const forceCloudflareWorkerReload = (rscEnv: any) => {
1213
+ if (!rscEnv?.hot) return;
502
1214
  try {
503
- await discoverRouters(s, rscEnv);
504
- writeRouteTypesFiles(s);
505
- await propagateDiscoveryState(rscEnv);
1215
+ const graph = rscEnv.moduleGraph;
1216
+ if (graph?.invalidateAll) {
1217
+ graph.invalidateAll();
1218
+ debugDiscovery?.("hmr: invalidated workerd rsc module graph");
1219
+ }
1220
+ rscEnv.hot.send({ type: "full-reload" });
1221
+ debugDiscovery?.(
1222
+ "hmr: forced workerd rsc env reload (full-reload)",
1223
+ );
506
1224
  } catch (err: any) {
507
- console.warn(
508
- `[rsc-router] Runtime re-discovery failed: ${err.message}`,
1225
+ debugDiscovery?.(
1226
+ "hmr: workerd reload failed: %s",
1227
+ err?.message ?? err,
509
1228
  );
510
- } finally {
511
- runtimeRediscoveryInProgress = false;
512
1229
  }
513
1230
  };
514
1231
 
@@ -516,23 +1233,50 @@ export function createRouterDiscoveryPlugin(
516
1233
  clearTimeout(routeChangeTimer);
517
1234
  routeChangeTimer = setTimeout(() => {
518
1235
  routeChangeTimer = undefined;
1236
+ const regenStart = debugDiscovery ? performance.now() : 0;
1237
+ const rscEnv = (server.environments as any)?.rsc;
1238
+ const skipStaticWrite =
1239
+ !rscEnv?.runner && s.perRouterManifests.length > 0;
519
1240
  try {
520
- writeCombinedRouteTypesWithTracking(s);
521
- if (s.perRouterManifests.length > 0) {
522
- supplementGenFilesWithRuntimeRoutes(s);
1241
+ // In cloudflare dev with a populated runtime manifest, the
1242
+ // static parser produces a strictly smaller (and actively
1243
+ // wrong) gen file — supplementGenFilesWithRuntimeRoutes can
1244
+ // only restore factory-only prefixes, and apps with mixed
1245
+ // static+factory routes under shared prefixes (cf-stress)
1246
+ // collapse to the 19-route static view. Skip the static
1247
+ // write entirely; runtime rediscovery below will overwrite
1248
+ // the gen file with the authoritative manifest.
1249
+ if (skipStaticWrite) {
1250
+ debugDiscovery?.(
1251
+ "watcher: skipping static write (cloudflare HMR — runtime rediscovery owns gen file)",
1252
+ );
1253
+ } else {
1254
+ writeCombinedRouteTypesWithTracking(s);
1255
+ if (s.perRouterManifests.length > 0) {
1256
+ supplementGenFilesWithRuntimeRoutes(s);
1257
+ }
523
1258
  }
524
1259
  } catch (err: any) {
525
- console.error(
526
- `[rsc-router] Route regeneration error: ${err.message}`,
527
- );
1260
+ console.error(`[rango] Route regeneration error: ${err.message}`);
528
1261
  }
1262
+ debugDiscovery?.(
1263
+ "watcher: regenerated gen files (%sms)",
1264
+ (performance.now() - regenStart).toFixed(1),
1265
+ );
529
1266
  // Async: re-run runtime discovery to refresh factory-generated
530
- // routes that the static parser cannot resolve.
1267
+ // routes that the static parser cannot resolve. Resolves the
1268
+ // discovery gate when complete.
531
1269
  if (s.perRouterManifests.length > 0) {
1270
+ // The cloudflare workerd reload fires inside refreshRuntimeDiscovery
1271
+ // on the successful cycle (see forceCloudflareWorkerReload call
1272
+ // there) so queued follow-up cycles also trigger it.
532
1273
  refreshRuntimeDiscovery().catch((err: any) => {
533
1274
  console.warn(
534
- `[rsc-router] Runtime re-discovery error: ${err.message}`,
1275
+ `[rango] Runtime re-discovery error: ${err.message}`,
535
1276
  );
1277
+ // Even on error, unblock the gate so workerd's reload doesn't
1278
+ // hang indefinitely against the previous manifest.
1279
+ resolveDiscoveryGate();
536
1280
  });
537
1281
  }
538
1282
  }, 100);
@@ -545,21 +1289,74 @@ export function createRouterDiscoveryPlugin(
545
1289
  !filePath.endsWith(".tsx") &&
546
1290
  !filePath.endsWith(".js") &&
547
1291
  !filePath.endsWith(".jsx")
548
- )
1292
+ ) {
1293
+ if (s.lastDiscoveryError) {
1294
+ debugDiscovery?.(
1295
+ "watcher: skip non-source %s [LASTERR %s]",
1296
+ filePath,
1297
+ s.lastDiscoveryError.message,
1298
+ );
1299
+ }
549
1300
  return;
1301
+ }
550
1302
  // Apply scan filter as early-exit before reading file
551
- if (s.scanFilter && !s.scanFilter(filePath)) return;
1303
+ if (s.scanFilter && !s.scanFilter(filePath)) {
1304
+ if (s.lastDiscoveryError) {
1305
+ debugDiscovery?.(
1306
+ "watcher: skip scan-filter %s [LASTERR %s]",
1307
+ filePath,
1308
+ s.lastDiscoveryError.message,
1309
+ );
1310
+ }
1311
+ return;
1312
+ }
1313
+ // Recovery mode: when the previous HMR re-discovery failed, the
1314
+ // import graph is incomplete and the manifest is stuck at the
1315
+ // last-good state. The fix may land in a non-route file (e.g. a
1316
+ // helper imported by the router, a missing module being created,
1317
+ // or a "use client" component) that the narrow content sniff
1318
+ // would otherwise filter out. While in recovery, treat any
1319
+ // in-scan source change as a candidate for rediscovery; the
1320
+ // tighter filter resumes once discovery succeeds again.
1321
+ const inRecoveryMode = !!s.lastDiscoveryError;
552
1322
  try {
553
1323
  const source = readFileSync(filePath, "utf-8");
554
1324
  const trimmed = source.trimStart();
555
- if (
1325
+ const isUseClient =
556
1326
  trimmed.startsWith('"use client"') ||
557
- trimmed.startsWith("'use client'")
558
- )
559
- return;
560
- const hasUrls = source.includes("urls(");
561
- const hasCreateRouter = /\bcreateRouter\s*[<(]/.test(source);
562
- if (!hasUrls && !hasCreateRouter) return;
1327
+ trimmed.startsWith("'use client'");
1328
+ if (!inRecoveryMode && isUseClient) return;
1329
+ // Cheap raw pre-check first; only when a candidate token is present
1330
+ // do we confirm it occurs in real code (not a comment/string) via a
1331
+ // single allocation-free code-region scan. Most saved files contain
1332
+ // neither token and skip the scan entirely. This avoids a comment or
1333
+ // string mention spuriously marking a file relevant and triggering an
1334
+ // unnecessary re-discovery on save.
1335
+ let hasUrls = source.includes("urls(");
1336
+ let hasCreateRouter = /\bcreateRouter\s*[<(]/.test(source);
1337
+ if (hasUrls) hasUrls = firstCodeMatchIndex(source, /urls\(/g) >= 0;
1338
+ if (hasCreateRouter) {
1339
+ hasCreateRouter =
1340
+ firstCodeMatchIndex(source, /\bcreateRouter\s*[<(]/g) >= 0;
1341
+ }
1342
+ if (!inRecoveryMode && !hasUrls && !hasCreateRouter) return;
1343
+ if (inRecoveryMode) {
1344
+ debugDiscovery?.(
1345
+ "watcher: recovery rediscovery for %s (urls=%s, router=%s, useClient=%s) [LASTERR %s]",
1346
+ filePath,
1347
+ hasUrls,
1348
+ hasCreateRouter,
1349
+ isUseClient,
1350
+ s.lastDiscoveryError!.message,
1351
+ );
1352
+ } else {
1353
+ debugDiscovery?.(
1354
+ "watcher: %s matches (urls=%s, router=%s)",
1355
+ filePath,
1356
+ hasUrls,
1357
+ hasCreateRouter,
1358
+ );
1359
+ }
563
1360
  // Invalidate cache when a router file changes (new router added/removed)
564
1361
  if (hasCreateRouter) {
565
1362
  const nestedRouterConflict = findNestedRouterConflict([
@@ -574,8 +1371,27 @@ export function createRouterDiscoveryPlugin(
574
1371
  }
575
1372
  s.cachedRouterFiles = undefined;
576
1373
  }
1374
+ // Note the event in the gate machine IMMEDIATELY (before the
1375
+ // 100ms debounce and any downstream HMR fanout). This sets
1376
+ // both `pendingEvents` (so refresh's finally holds the gate
1377
+ // through the tail window even if no rediscovery is queued)
1378
+ // and resets `discoveryDone` to a fresh pending promise (so
1379
+ // workerd reloads triggered by the same source change can't
1380
+ // observe a stale resolved gate from cold-start). Resolved
1381
+ // by the trailing refreshRuntimeDiscovery() cycle.
1382
+ if (s.perRouterManifests.length > 0) {
1383
+ gate.noteRouteEvent();
1384
+ }
577
1385
  scheduleRouteRegeneration();
578
- } catch {
1386
+ } catch (readErr: any) {
1387
+ if (s.lastDiscoveryError) {
1388
+ debugDiscovery?.(
1389
+ "watcher: read error %s: %s [LASTERR %s]",
1390
+ filePath,
1391
+ readErr?.message,
1392
+ s.lastDiscoveryError.message,
1393
+ );
1394
+ }
579
1395
  // Ignore read errors for deleted/moved files
580
1396
  }
581
1397
  };
@@ -604,11 +1420,24 @@ export function createRouterDiscoveryPlugin(
604
1420
  async buildStart() {
605
1421
  if (!s.isBuildMode) return;
606
1422
  // Only run once across environment builds
607
- if (s.mergedRouteManifest !== null) return;
1423
+ if (s.mergedRouteManifest !== null) {
1424
+ debugDiscovery?.(
1425
+ "build: skip (already discovered, env=%s)",
1426
+ this.environment?.name ?? "?",
1427
+ );
1428
+ return;
1429
+ }
1430
+ const buildStartTime = performance.now();
1431
+ debugDiscovery?.("build: start (env=%s)", this.environment?.name ?? "?");
608
1432
  resetStagedBuildAssets(s.projectRoot);
609
1433
  s.prerenderManifestEntries = null;
610
1434
  s.staticManifestEntries = null;
611
1435
 
1436
+ // Acquire build-time env bindings if configured
1437
+ await timed(debugDiscovery, "build acquireBuildEnv", () =>
1438
+ acquireBuildEnv(s, viteCommand, viteMode),
1439
+ );
1440
+
612
1441
  let tempServer: any = null;
613
1442
  // Signal to user-space code (e.g. reverse.ts) that build-time discovery
614
1443
  // is active. Uses globalThis because the temp server's module runner
@@ -616,12 +1445,16 @@ export function createRouterDiscoveryPlugin(
616
1445
  // between the vite plugin and user code loaded via runner.import().
617
1446
  (globalThis as any).__rscRouterDiscoveryActive = true;
618
1447
  try {
619
- tempServer = await createTempRscServer(s, { forceBuild: true });
1448
+ tempServer = await timed(
1449
+ debugDiscovery,
1450
+ "build createTempRscServer",
1451
+ () => createTempRscServer(s, { forceBuild: true }),
1452
+ );
620
1453
 
621
1454
  const rscEnv = (tempServer.environments as any)?.rsc;
622
1455
  if (!rscEnv?.runner) {
623
1456
  console.warn(
624
- "[rsc-router] RSC environment runner not available during build, skipping manifest generation",
1457
+ "[rango] RSC environment runner not available during build, skipping manifest generation",
625
1458
  );
626
1459
  return;
627
1460
  }
@@ -636,11 +1469,15 @@ export function createRouterDiscoveryPlugin(
636
1469
  s.resolvedStaticModules = tempIdsPlugin.api.staticHandlerModules;
637
1470
  }
638
1471
 
639
- await discoverRouters(s, rscEnv);
1472
+ await timed(debugDiscovery, "build discoverRouters", () =>
1473
+ discoverRouters(s, rscEnv),
1474
+ );
640
1475
  // Update named-routes.gen.ts from runtime discovery.
641
1476
  // The runtime manifest includes dynamically generated routes
642
1477
  // that the static parser cannot extract from source code.
643
- writeRouteTypesFiles(s);
1478
+ timedSync(debugDiscovery, "build writeRouteTypesFiles", () =>
1479
+ writeRouteTypesFiles(s),
1480
+ );
644
1481
  } catch (err: any) {
645
1482
  // Extract the user source file from the stack trace (skip internal frames)
646
1483
  const sourceFile = err.stack
@@ -660,13 +1497,50 @@ export function createRouterDiscoveryPlugin(
660
1497
  .filter(Boolean)
661
1498
  .join("\n");
662
1499
  throw new Error(
663
- `[rsc-router] Build-time router discovery failed:\n${details}`,
1500
+ `[rango] Build-time router discovery failed:\n${details}`,
1501
+ { cause: err },
664
1502
  );
665
1503
  } finally {
666
1504
  delete (globalThis as any).__rscRouterDiscoveryActive;
667
1505
  if (tempServer) {
668
- await tempServer.close();
1506
+ await timed(debugDiscovery, "build tempServer.close", () =>
1507
+ tempServer.close(),
1508
+ );
669
1509
  }
1510
+ await releaseBuildEnv(s);
1511
+ debugDiscovery?.(
1512
+ "build discovery done (%sms)",
1513
+ (performance.now() - buildStartTime).toFixed(1),
1514
+ );
1515
+ }
1516
+ },
1517
+
1518
+ // Suppress vite's HMR cascade for our own gen-file writes.
1519
+ //
1520
+ // After every cf HMR cycle, refreshTempRscEnv → writeRouteTypesFiles
1521
+ // writes the configured gen files (default `router.named-routes.gen.ts`,
1522
+ // but the source filenames and gen suffix are user-configurable). The
1523
+ // chokidar watcher then fires twice independently: our
1524
+ // `handleRouteFileChange` (already short-circuited by
1525
+ // `consumeSelfGenWrite` inside `maybeHandleGeneratedRouteFileMutation`),
1526
+ // AND vite's own HMR pipeline (which invalidates the gen file's
1527
+ // importers and triggers a second workerd full reload — visible to the
1528
+ // user as a duplicate "[Rango] HMR: version changed" on the client).
1529
+ //
1530
+ // `peekSelfGenWrite` is the authoritative filter: its map only contains
1531
+ // paths that `markSelfGenWrite` has registered, so it natively works
1532
+ // for any configured gen-file name. It is non-consuming so the chokidar
1533
+ // handler that fires later can still consume the same entry. Returning
1534
+ // [] tells vite "no modules invalidated by this change" — safe because
1535
+ // `s.perRouterManifests` is already up-to-date (the write that just
1536
+ // happened is the consequence of our just-completed rediscovery).
1537
+ handleHotUpdate(ctx) {
1538
+ if (peekSelfGenWrite(s, ctx.file)) {
1539
+ debugDiscovery?.(
1540
+ "handleHotUpdate: suppressing self-write HMR cascade for %s",
1541
+ ctx.file,
1542
+ );
1543
+ return [];
670
1544
  }
671
1545
  },
672
1546
 
@@ -690,19 +1564,38 @@ export function createRouterDiscoveryPlugin(
690
1564
  // This is critical for Cloudflare dev where the worker runs in a separate
691
1565
  // Miniflare process and can only receive manifest data via the virtual module.
692
1566
  if (s.discoveryDone) {
693
- await s.discoveryDone;
1567
+ await timed(
1568
+ debugRoutes,
1569
+ "await discoveryDone (manifest)",
1570
+ () => s.discoveryDone,
1571
+ );
694
1572
  }
695
- return generateRoutesManifestModule(s);
1573
+ const code = await timed(
1574
+ debugRoutes,
1575
+ "generateRoutesManifestModule",
1576
+ () => generateRoutesManifestModule(s),
1577
+ );
1578
+ debugRoutes?.("manifest module emitted (%d bytes)", code?.length ?? 0);
1579
+ return code;
696
1580
  }
697
1581
  // Per-router virtual modules: pure data exports (no side effects).
698
1582
  // ensureRouterManifest() imports the module and stores the data.
699
1583
  const perRouterPrefix = "\0" + VIRTUAL_ROUTES_MANIFEST_ID + "/";
700
1584
  if (id.startsWith(perRouterPrefix)) {
701
1585
  if (s.discoveryDone) {
702
- await s.discoveryDone;
1586
+ await timed(
1587
+ debugRoutes,
1588
+ "await discoveryDone (per-router)",
1589
+ () => s.discoveryDone,
1590
+ );
703
1591
  }
704
1592
  const routerId = id.slice(perRouterPrefix.length);
705
- return generatePerRouterModule(s, routerId);
1593
+ const code = await timed(
1594
+ debugRoutes,
1595
+ `generatePerRouterModule ${routerId}`,
1596
+ () => generatePerRouterModule(s, routerId),
1597
+ );
1598
+ return code;
706
1599
  }
707
1600
  // virtual:rsc-router/prerender-paths load handler removed
708
1601
  return null;
@@ -712,6 +1605,7 @@ export function createRouterDiscoveryPlugin(
712
1605
  // Used by closeBundle for handler code eviction and prerender data injection.
713
1606
  generateBundle(_options: any, bundle: any) {
714
1607
  if (this.environment?.name !== "rsc") return;
1608
+ const genStart = debugBuild ? performance.now() : 0;
715
1609
 
716
1610
  // Record RSC entry chunk filename for closeBundle injection
717
1611
  for (const [fileName, chunk] of Object.entries(bundle) as [
@@ -724,8 +1618,19 @@ export function createRouterDiscoveryPlugin(
724
1618
  }
725
1619
  }
726
1620
 
727
- if (!s.resolvedPrerenderModules?.size && !s.resolvedStaticModules?.size)
1621
+ if (!s.resolvedPrerenderModules?.size && !s.resolvedStaticModules?.size) {
1622
+ debugBuild?.(
1623
+ "generateBundle (rsc): no handlers to scan (%sms)",
1624
+ (performance.now() - genStart).toFixed(1),
1625
+ );
728
1626
  return;
1627
+ }
1628
+
1629
+ // Clear maps at the start of each RSC generateBundle pass.
1630
+ // Vite 6 multi-environment builds run RSC twice (analysis + production);
1631
+ // clearing prevents stale/duplicate records from the analysis pass.
1632
+ s.handlerChunkInfoMap.clear();
1633
+ s.staticHandlerChunkInfoMap.clear();
729
1634
 
730
1635
  for (const [fileName, chunk] of Object.entries(bundle) as [
731
1636
  string,
@@ -733,27 +1638,28 @@ export function createRouterDiscoveryPlugin(
733
1638
  ][]) {
734
1639
  if (chunk.type !== "chunk") continue;
735
1640
 
736
- // Prerender handlers chunk
737
- if (
738
- fileName.includes("__prerender-handlers") &&
739
- s.resolvedPrerenderModules?.size
740
- ) {
1641
+ // Scan all chunks for handler exports (handlers may land in any chunk)
1642
+ if (s.resolvedPrerenderModules?.size) {
741
1643
  const handlers = extractHandlerExportsFromChunk(
742
1644
  chunk.code,
743
1645
  s.resolvedPrerenderModules,
744
1646
  "Prerender",
745
- true,
1647
+ false,
746
1648
  );
747
1649
  if (handlers.length > 0) {
748
- s.handlerChunkInfo = { fileName, exports: handlers };
1650
+ const existing = s.handlerChunkInfoMap.get(fileName);
1651
+ if (existing) {
1652
+ existing.exports.push(...handlers);
1653
+ } else {
1654
+ s.handlerChunkInfoMap.set(fileName, {
1655
+ fileName,
1656
+ exports: handlers,
1657
+ });
1658
+ }
749
1659
  }
750
1660
  }
751
1661
 
752
- // Static handlers chunk
753
- if (
754
- fileName.includes("__static-handlers") &&
755
- s.resolvedStaticModules?.size
756
- ) {
1662
+ if (s.resolvedStaticModules?.size) {
757
1663
  const handlers = extractHandlerExportsFromChunk(
758
1664
  chunk.code,
759
1665
  s.resolvedStaticModules,
@@ -761,10 +1667,26 @@ export function createRouterDiscoveryPlugin(
761
1667
  false,
762
1668
  );
763
1669
  if (handlers.length > 0) {
764
- s.staticHandlerChunkInfo = { fileName, exports: handlers };
1670
+ const existing = s.staticHandlerChunkInfoMap.get(fileName);
1671
+ if (existing) {
1672
+ existing.exports.push(...handlers);
1673
+ } else {
1674
+ s.staticHandlerChunkInfoMap.set(fileName, {
1675
+ fileName,
1676
+ exports: handlers,
1677
+ });
1678
+ }
765
1679
  }
766
1680
  }
767
1681
  }
1682
+
1683
+ debugBuild?.(
1684
+ "generateBundle (rsc): scanned %d chunks, %d prerender chunk(s), %d static chunk(s) (%sms)",
1685
+ Object.keys(bundle).length,
1686
+ s.handlerChunkInfoMap.size,
1687
+ s.staticHandlerChunkInfoMap.size,
1688
+ (performance.now() - genStart).toFixed(1),
1689
+ );
768
1690
  },
769
1691
 
770
1692
  // Build-time pre-rendering: evict handler code and inject collected prerender data.
@@ -778,7 +1700,9 @@ export function createRouterDiscoveryPlugin(
778
1700
  // Only run for the RSC environment — other environments (client, ssr) have
779
1701
  // no prerender/static data to process and would just do redundant file I/O.
780
1702
  if (this.environment && this.environment.name !== "rsc") return;
781
- postprocessBundle(s);
1703
+ timedSync(debugBuild, "closeBundle postprocessBundle", () =>
1704
+ postprocessBundle(s),
1705
+ );
782
1706
  },
783
1707
  },
784
1708
  };