@rangojs/router 0.0.0-experimental.8 → 0.0.0-experimental.80

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 (312) hide show
  1. package/AGENTS.md +9 -0
  2. package/README.md +942 -4
  3. package/dist/bin/rango.js +1689 -0
  4. package/dist/vite/index.js +4960 -935
  5. package/package.json +70 -60
  6. package/skills/breadcrumbs/SKILL.md +250 -0
  7. package/skills/cache-guide/SKILL.md +294 -0
  8. package/skills/caching/SKILL.md +93 -23
  9. package/skills/composability/SKILL.md +172 -0
  10. package/skills/debug-manifest/SKILL.md +12 -8
  11. package/skills/document-cache/SKILL.md +18 -16
  12. package/skills/fonts/SKILL.md +167 -0
  13. package/skills/handler-use/SKILL.md +362 -0
  14. package/skills/hooks/SKILL.md +334 -72
  15. package/skills/host-router/SKILL.md +218 -0
  16. package/skills/intercept/SKILL.md +151 -8
  17. package/skills/layout/SKILL.md +122 -3
  18. package/skills/links/SKILL.md +92 -31
  19. package/skills/loader/SKILL.md +404 -44
  20. package/skills/middleware/SKILL.md +205 -37
  21. package/skills/migrate-nextjs/SKILL.md +560 -0
  22. package/skills/migrate-react-router/SKILL.md +764 -0
  23. package/skills/mime-routes/SKILL.md +128 -0
  24. package/skills/parallel/SKILL.md +263 -1
  25. package/skills/prerender/SKILL.md +685 -0
  26. package/skills/rango/SKILL.md +87 -16
  27. package/skills/response-routes/SKILL.md +411 -0
  28. package/skills/route/SKILL.md +281 -14
  29. package/skills/router-setup/SKILL.md +210 -32
  30. package/skills/tailwind/SKILL.md +129 -0
  31. package/skills/theme/SKILL.md +9 -8
  32. package/skills/typesafety/SKILL.md +328 -89
  33. package/skills/use-cache/SKILL.md +324 -0
  34. package/src/__internal.ts +102 -4
  35. package/src/bin/rango.ts +321 -0
  36. package/src/browser/action-coordinator.ts +97 -0
  37. package/src/browser/action-response-classifier.ts +99 -0
  38. package/src/browser/app-version.ts +14 -0
  39. package/src/browser/event-controller.ts +92 -64
  40. package/src/browser/history-state.ts +80 -0
  41. package/src/browser/intercept-utils.ts +52 -0
  42. package/src/browser/link-interceptor.ts +24 -4
  43. package/src/browser/logging.ts +55 -0
  44. package/src/browser/merge-segment-loaders.ts +20 -12
  45. package/src/browser/navigation-bridge.ts +317 -560
  46. package/src/browser/navigation-client.ts +206 -68
  47. package/src/browser/navigation-store.ts +73 -55
  48. package/src/browser/navigation-transaction.ts +297 -0
  49. package/src/browser/network-error-handler.ts +61 -0
  50. package/src/browser/partial-update.ts +343 -316
  51. package/src/browser/prefetch/cache.ts +216 -0
  52. package/src/browser/prefetch/fetch.ts +206 -0
  53. package/src/browser/prefetch/observer.ts +65 -0
  54. package/src/browser/prefetch/policy.ts +48 -0
  55. package/src/browser/prefetch/queue.ts +160 -0
  56. package/src/browser/prefetch/resource-ready.ts +77 -0
  57. package/src/browser/rango-state.ts +112 -0
  58. package/src/browser/react/Link.tsx +253 -74
  59. package/src/browser/react/NavigationProvider.tsx +87 -11
  60. package/src/browser/react/context.ts +11 -0
  61. package/src/browser/react/filter-segment-order.ts +11 -0
  62. package/src/browser/react/index.ts +12 -12
  63. package/src/browser/react/location-state-shared.ts +95 -53
  64. package/src/browser/react/location-state.ts +60 -15
  65. package/src/browser/react/mount-context.ts +6 -1
  66. package/src/browser/react/nonce-context.ts +23 -0
  67. package/src/browser/react/shallow-equal.ts +27 -0
  68. package/src/browser/react/use-action.ts +29 -51
  69. package/src/browser/react/use-client-cache.ts +5 -3
  70. package/src/browser/react/use-handle.ts +30 -126
  71. package/src/browser/react/use-href.tsx +2 -2
  72. package/src/browser/react/use-link-status.ts +6 -5
  73. package/src/browser/react/use-navigation.ts +44 -65
  74. package/src/browser/react/use-params.ts +65 -0
  75. package/src/browser/react/use-pathname.ts +47 -0
  76. package/src/browser/react/use-router.ts +76 -0
  77. package/src/browser/react/use-search-params.ts +56 -0
  78. package/src/browser/react/use-segments.ts +80 -97
  79. package/src/browser/response-adapter.ts +73 -0
  80. package/src/browser/rsc-router.tsx +214 -58
  81. package/src/browser/scroll-restoration.ts +127 -52
  82. package/src/browser/segment-reconciler.ts +243 -0
  83. package/src/browser/segment-structure-assert.ts +16 -0
  84. package/src/browser/server-action-bridge.ts +510 -603
  85. package/src/browser/shallow.ts +6 -1
  86. package/src/browser/types.ts +141 -48
  87. package/src/browser/validate-redirect-origin.ts +29 -0
  88. package/src/build/generate-manifest.ts +235 -24
  89. package/src/build/generate-route-types.ts +39 -0
  90. package/src/build/index.ts +13 -0
  91. package/src/build/route-trie.ts +291 -0
  92. package/src/build/route-types/ast-helpers.ts +25 -0
  93. package/src/build/route-types/ast-route-extraction.ts +98 -0
  94. package/src/build/route-types/codegen.ts +102 -0
  95. package/src/build/route-types/include-resolution.ts +418 -0
  96. package/src/build/route-types/param-extraction.ts +48 -0
  97. package/src/build/route-types/per-module-writer.ts +128 -0
  98. package/src/build/route-types/router-processing.ts +618 -0
  99. package/src/build/route-types/scan-filter.ts +85 -0
  100. package/src/build/runtime-discovery.ts +231 -0
  101. package/src/cache/background-task.ts +34 -0
  102. package/src/cache/cache-key-utils.ts +44 -0
  103. package/src/cache/cache-policy.ts +125 -0
  104. package/src/cache/cache-runtime.ts +342 -0
  105. package/src/cache/cache-scope.ts +167 -309
  106. package/src/cache/cf/cf-cache-store.ts +571 -17
  107. package/src/cache/cf/index.ts +13 -3
  108. package/src/cache/document-cache.ts +116 -77
  109. package/src/cache/handle-capture.ts +81 -0
  110. package/src/cache/handle-snapshot.ts +41 -0
  111. package/src/cache/index.ts +1 -15
  112. package/src/cache/memory-segment-store.ts +191 -13
  113. package/src/cache/profile-registry.ts +73 -0
  114. package/src/cache/read-through-swr.ts +134 -0
  115. package/src/cache/segment-codec.ts +256 -0
  116. package/src/cache/taint.ts +153 -0
  117. package/src/cache/types.ts +72 -122
  118. package/src/client.rsc.tsx +3 -1
  119. package/src/client.tsx +135 -301
  120. package/src/component-utils.ts +4 -4
  121. package/src/components/DefaultDocument.tsx +5 -1
  122. package/src/context-var.ts +156 -0
  123. package/src/debug.ts +19 -9
  124. package/src/errors.ts +108 -2
  125. package/src/handle.ts +55 -29
  126. package/src/handles/MetaTags.tsx +73 -20
  127. package/src/handles/breadcrumbs.ts +66 -0
  128. package/src/handles/index.ts +1 -0
  129. package/src/handles/meta.ts +30 -13
  130. package/src/host/cookie-handler.ts +21 -15
  131. package/src/host/errors.ts +8 -8
  132. package/src/host/index.ts +4 -7
  133. package/src/host/pattern-matcher.ts +27 -27
  134. package/src/host/router.ts +61 -39
  135. package/src/host/testing.ts +8 -8
  136. package/src/host/types.ts +15 -7
  137. package/src/host/utils.ts +1 -1
  138. package/src/href-client.ts +119 -29
  139. package/src/index.rsc.ts +155 -19
  140. package/src/index.ts +251 -30
  141. package/src/internal-debug.ts +11 -0
  142. package/src/loader.rsc.ts +26 -157
  143. package/src/loader.ts +27 -10
  144. package/src/network-error-thrower.tsx +3 -1
  145. package/src/outlet-provider.tsx +45 -0
  146. package/src/prerender/param-hash.ts +37 -0
  147. package/src/prerender/store.ts +186 -0
  148. package/src/prerender.ts +524 -0
  149. package/src/reverse.ts +354 -0
  150. package/src/root-error-boundary.tsx +41 -29
  151. package/src/route-content-wrapper.tsx +7 -4
  152. package/src/route-definition/dsl-helpers.ts +1121 -0
  153. package/src/route-definition/helper-factories.ts +200 -0
  154. package/src/route-definition/helpers-types.ts +478 -0
  155. package/src/route-definition/index.ts +55 -0
  156. package/src/route-definition/redirect.ts +101 -0
  157. package/src/route-definition/resolve-handler-use.ts +149 -0
  158. package/src/route-definition.ts +1 -1428
  159. package/src/route-map-builder.ts +217 -123
  160. package/src/route-name.ts +53 -0
  161. package/src/route-types.ts +77 -8
  162. package/src/router/content-negotiation.ts +215 -0
  163. package/src/router/debug-manifest.ts +72 -0
  164. package/src/router/error-handling.ts +9 -9
  165. package/src/router/find-match.ts +160 -0
  166. package/src/router/handler-context.ts +438 -86
  167. package/src/router/intercept-resolution.ts +402 -0
  168. package/src/router/lazy-includes.ts +237 -0
  169. package/src/router/loader-resolution.ts +356 -128
  170. package/src/router/logging.ts +251 -0
  171. package/src/router/manifest.ts +163 -35
  172. package/src/router/match-api.ts +555 -0
  173. package/src/router/match-context.ts +5 -3
  174. package/src/router/match-handlers.ts +440 -0
  175. package/src/router/match-middleware/background-revalidation.ts +108 -93
  176. package/src/router/match-middleware/cache-lookup.ts +460 -10
  177. package/src/router/match-middleware/cache-store.ts +98 -26
  178. package/src/router/match-middleware/intercept-resolution.ts +57 -17
  179. package/src/router/match-middleware/segment-resolution.ts +80 -6
  180. package/src/router/match-pipelines.ts +10 -45
  181. package/src/router/match-result.ts +135 -35
  182. package/src/router/metrics.ts +240 -15
  183. package/src/router/middleware-cookies.ts +55 -0
  184. package/src/router/middleware-types.ts +220 -0
  185. package/src/router/middleware.ts +324 -369
  186. package/src/router/navigation-snapshot.ts +182 -0
  187. package/src/router/pattern-matching.ts +211 -43
  188. package/src/router/prerender-match.ts +502 -0
  189. package/src/router/preview-match.ts +98 -0
  190. package/src/router/request-classification.ts +310 -0
  191. package/src/router/revalidation.ts +137 -38
  192. package/src/router/route-snapshot.ts +245 -0
  193. package/src/router/router-context.ts +41 -21
  194. package/src/router/router-interfaces.ts +484 -0
  195. package/src/router/router-options.ts +618 -0
  196. package/src/router/router-registry.ts +24 -0
  197. package/src/router/segment-resolution/fresh.ts +748 -0
  198. package/src/router/segment-resolution/helpers.ts +268 -0
  199. package/src/router/segment-resolution/loader-cache.ts +199 -0
  200. package/src/router/segment-resolution/revalidation.ts +1379 -0
  201. package/src/router/segment-resolution/static-store.ts +67 -0
  202. package/src/router/segment-resolution.ts +21 -0
  203. package/src/router/segment-wrappers.ts +291 -0
  204. package/src/router/telemetry-otel.ts +299 -0
  205. package/src/router/telemetry.ts +300 -0
  206. package/src/router/timeout.ts +148 -0
  207. package/src/router/trie-matching.ts +239 -0
  208. package/src/router/types.ts +78 -3
  209. package/src/router.ts +740 -4252
  210. package/src/rsc/handler-context.ts +45 -0
  211. package/src/rsc/handler.ts +907 -797
  212. package/src/rsc/helpers.ts +140 -6
  213. package/src/rsc/index.ts +0 -20
  214. package/src/rsc/loader-fetch.ts +229 -0
  215. package/src/rsc/manifest-init.ts +90 -0
  216. package/src/rsc/nonce.ts +14 -0
  217. package/src/rsc/origin-guard.ts +141 -0
  218. package/src/rsc/progressive-enhancement.ts +391 -0
  219. package/src/rsc/response-error.ts +37 -0
  220. package/src/rsc/response-route-handler.ts +347 -0
  221. package/src/rsc/rsc-rendering.ts +246 -0
  222. package/src/rsc/runtime-warnings.ts +42 -0
  223. package/src/rsc/server-action.ts +356 -0
  224. package/src/rsc/ssr-setup.ts +128 -0
  225. package/src/rsc/types.ts +46 -11
  226. package/src/search-params.ts +230 -0
  227. package/src/segment-content-promise.ts +67 -0
  228. package/src/segment-loader-promise.ts +122 -0
  229. package/src/segment-system.tsx +134 -36
  230. package/src/server/context.ts +341 -61
  231. package/src/server/cookie-store.ts +190 -0
  232. package/src/server/fetchable-loader-store.ts +37 -0
  233. package/src/server/handle-store.ts +113 -15
  234. package/src/server/loader-registry.ts +24 -64
  235. package/src/server/request-context.ts +607 -81
  236. package/src/server.ts +35 -130
  237. package/src/ssr/index.tsx +103 -30
  238. package/src/static-handler.ts +126 -0
  239. package/src/theme/ThemeProvider.tsx +21 -15
  240. package/src/theme/ThemeScript.tsx +5 -5
  241. package/src/theme/constants.ts +5 -2
  242. package/src/theme/index.ts +4 -14
  243. package/src/theme/theme-context.ts +4 -30
  244. package/src/theme/theme-script.ts +21 -18
  245. package/src/types/boundaries.ts +158 -0
  246. package/src/types/cache-types.ts +198 -0
  247. package/src/types/error-types.ts +192 -0
  248. package/src/types/global-namespace.ts +100 -0
  249. package/src/types/handler-context.ts +791 -0
  250. package/src/types/index.ts +88 -0
  251. package/src/types/loader-types.ts +210 -0
  252. package/src/types/route-config.ts +170 -0
  253. package/src/types/route-entry.ts +120 -0
  254. package/src/types/segments.ts +150 -0
  255. package/src/types.ts +1 -1623
  256. package/src/urls/include-helper.ts +207 -0
  257. package/src/urls/index.ts +53 -0
  258. package/src/urls/path-helper-types.ts +372 -0
  259. package/src/urls/path-helper.ts +364 -0
  260. package/src/urls/pattern-types.ts +107 -0
  261. package/src/urls/response-types.ts +116 -0
  262. package/src/urls/type-extraction.ts +372 -0
  263. package/src/urls/urls-function.ts +98 -0
  264. package/src/urls.ts +1 -802
  265. package/src/use-loader.tsx +161 -81
  266. package/src/vite/discovery/bundle-postprocess.ts +181 -0
  267. package/src/vite/discovery/discover-routers.ts +348 -0
  268. package/src/vite/discovery/prerender-collection.ts +439 -0
  269. package/src/vite/discovery/route-types-writer.ts +258 -0
  270. package/src/vite/discovery/self-gen-tracking.ts +47 -0
  271. package/src/vite/discovery/state.ts +117 -0
  272. package/src/vite/discovery/virtual-module-codegen.ts +203 -0
  273. package/src/vite/index.ts +15 -1133
  274. package/src/vite/plugin-types.ts +103 -0
  275. package/src/vite/plugins/cjs-to-esm.ts +93 -0
  276. package/src/vite/plugins/client-ref-dedup.ts +115 -0
  277. package/src/vite/plugins/client-ref-hashing.ts +105 -0
  278. package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +72 -53
  279. package/src/vite/plugins/expose-id-utils.ts +299 -0
  280. package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
  281. package/src/vite/plugins/expose-ids/handler-transform.ts +209 -0
  282. package/src/vite/plugins/expose-ids/loader-transform.ts +74 -0
  283. package/src/vite/plugins/expose-ids/router-transform.ts +110 -0
  284. package/src/vite/plugins/expose-ids/types.ts +45 -0
  285. package/src/vite/plugins/expose-internal-ids.ts +786 -0
  286. package/src/vite/plugins/performance-tracks.ts +88 -0
  287. package/src/vite/plugins/refresh-cmd.ts +127 -0
  288. package/src/vite/plugins/use-cache-transform.ts +323 -0
  289. package/src/vite/plugins/version-injector.ts +83 -0
  290. package/src/vite/plugins/version-plugin.ts +266 -0
  291. package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +23 -14
  292. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  293. package/src/vite/rango.ts +462 -0
  294. package/src/vite/router-discovery.ts +918 -0
  295. package/src/vite/utils/ast-handler-extract.ts +517 -0
  296. package/src/vite/utils/banner.ts +36 -0
  297. package/src/vite/utils/bundle-analysis.ts +137 -0
  298. package/src/vite/utils/manifest-utils.ts +70 -0
  299. package/src/vite/{package-resolution.ts → utils/package-resolution.ts} +25 -29
  300. package/src/vite/utils/prerender-utils.ts +221 -0
  301. package/src/vite/utils/shared-utils.ts +170 -0
  302. package/CLAUDE.md +0 -43
  303. package/src/browser/lru-cache.ts +0 -69
  304. package/src/browser/request-controller.ts +0 -164
  305. package/src/cache/memory-store.ts +0 -253
  306. package/src/href-context.ts +0 -33
  307. package/src/href.ts +0 -255
  308. package/src/server/route-manifest-cache.ts +0 -173
  309. package/src/vite/expose-handle-id.ts +0 -209
  310. package/src/vite/expose-loader-id.ts +0 -426
  311. package/src/vite/expose-location-state-id.ts +0 -177
  312. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
package/src/vite/index.ts CHANGED
@@ -1,1138 +1,20 @@
1
- import type { Plugin, PluginOption } from "vite";
2
- import { createServer as createViteServer } from "vite";
3
- import * as Vite from "vite";
4
- import { resolve, join } from "node:path";
5
- import { createHash } from "node:crypto";
6
- import { mkdirSync, writeFileSync, readFileSync, existsSync } from "node:fs";
7
- import { exposeActionId } from "./expose-action-id.ts";
8
- import { exposeLoaderId } from "./expose-loader-id.ts";
9
- import { exposeHandleId } from "./expose-handle-id.ts";
10
- import { exposeLocationStateId } from "./expose-location-state-id.ts";
11
- import {
12
- VIRTUAL_ENTRY_BROWSER,
13
- VIRTUAL_ENTRY_SSR,
14
- getVirtualEntryRSC,
15
- getVirtualVersionContent,
16
- VIRTUAL_IDS,
17
- } from "./virtual-entries.ts";
18
- import {
19
- getExcludeDeps,
20
- getPackageAliases,
21
- getPublishedPackageName,
22
- isWorkspaceDevelopment,
23
- } from "./package-resolution.ts";
24
-
25
- // Re-export plugins
26
- export { exposeActionId } from "./expose-action-id.ts";
27
- export { exposeLoaderId } from "./expose-loader-id.ts";
28
- export { exposeHandleId } from "./expose-handle-id.ts";
29
- export { exposeLocationStateId } from "./expose-location-state-id.ts";
30
-
31
- // Virtual module type declarations in ./version.d.ts
32
-
33
- /**
34
- * esbuild plugin to provide rsc-router:version virtual module during optimization.
35
- * This is needed because esbuild runs during Vite's dependency optimization phase,
36
- * before Vite's plugin system can handle virtual modules.
37
- */
38
- const versionEsbuildPlugin = {
39
- name: "@rangojs/router-version",
40
- setup(build: any) {
41
- build.onResolve({ filter: /^rsc-router:version$/ }, (args: any) => ({
42
- path: args.path,
43
- namespace: "@rangojs/router-virtual",
44
- }));
45
- build.onLoad({ filter: /.*/, namespace: "@rangojs/router-virtual" }, () => ({
46
- contents: `export const VERSION = "dev";`,
47
- loader: "js",
48
- }));
49
- },
50
- };
51
-
52
- /**
53
- * Shared esbuild options for dependency optimization.
54
- * Includes the version stub plugin for all environments.
55
- */
56
- const sharedEsbuildOptions = {
57
- plugins: [versionEsbuildPlugin],
58
- };
59
-
60
- /**
61
- * RSC plugin entry points configuration.
62
- * All entries use virtual modules by default. Specify a path to use a custom entry file.
63
- */
64
- export interface RscEntries {
65
- /**
66
- * Path to a custom browser/client entry file.
67
- * If not specified, a default virtual entry is used.
68
- */
69
- client?: string;
70
-
71
- /**
72
- * Path to a custom SSR entry file.
73
- * If not specified, a default virtual entry is used.
74
- */
75
- ssr?: string;
76
-
77
- /**
78
- * Path to a custom RSC entry file.
79
- * If not specified, a default virtual entry is used that imports the router from the `entry` option.
80
- */
81
- rsc?: string;
82
- }
83
-
84
- /**
85
- * Options for @vitejs/plugin-rsc integration
86
- */
87
- export interface RscPluginOptions {
88
- /**
89
- * Entry points for client, ssr, and rsc environments.
90
- * All entries use virtual modules by default.
91
- * Specify paths only when you need custom entry files.
92
- */
93
- entries?: RscEntries;
94
- }
95
-
96
- /**
97
- * Base options shared by all presets
98
- */
99
- interface RscRouterBaseOptions {
100
- /**
101
- * Expose $$id property on server action functions.
102
- * Required for action-based revalidation to work.
103
- * @default true
104
- */
105
- exposeActionId?: boolean;
106
- }
107
-
108
- /**
109
- * Options for Node.js deployment (default)
110
- */
111
- export interface RscRouterNodeOptions extends RscRouterBaseOptions {
112
- /**
113
- * Deployment preset. Defaults to 'node' when not specified.
114
- */
115
- preset?: "node";
116
-
117
- /**
118
- * Path to your router configuration file that exports the route tree.
119
- * This file must export a `router` object created with `createRouter()`.
120
- *
121
- * @example
122
- * ```ts
123
- * rscRouter({ router: './src/router.tsx' })
124
- * ```
125
- */
126
- router: string;
127
-
128
- /**
129
- * RSC plugin configuration. By default, rsc-router includes @vitejs/plugin-rsc
130
- * with sensible defaults.
131
- *
132
- * Entry files (browser, ssr, rsc) are optional - if they don't exist,
133
- * virtual defaults are used.
134
- *
135
- * - Omit or pass `true`/`{}` to use defaults (recommended)
136
- * - Pass `{ entries: {...} }` to customize entry paths
137
- * - Pass `false` to disable (for manual @vitejs/plugin-rsc configuration)
138
- *
139
- * @default true
140
- */
141
- rsc?: boolean | RscPluginOptions;
142
- }
143
-
144
- /**
145
- * Options for Cloudflare Workers deployment
146
- */
147
- export interface RscRouterCloudflareOptions extends RscRouterBaseOptions {
148
- /**
149
- * Deployment preset for Cloudflare Workers.
150
- * When using cloudflare preset:
151
- * - @vitejs/plugin-rsc is NOT added (cloudflare plugin adds it)
152
- * - Your worker entry (e.g., worker.rsc.tsx) imports the router directly
153
- * - Browser and SSR use virtual entries
154
- * - Build-time manifest generation is auto-detected from wrangler.json main entry
155
- */
156
- preset: "cloudflare";
157
- }
158
-
159
- /**
160
- * Options for rscRouter plugin
161
- */
162
- export type RscRouterOptions = RscRouterNodeOptions | RscRouterCloudflareOptions;
163
-
164
- /**
165
- * Create a virtual modules plugin for default entry files.
166
- * Provides virtual module content when entries use VIRTUAL_IDS (no custom entry configured).
167
- */
168
- function createVirtualEntriesPlugin(
169
- entries: { client: string; ssr: string; rsc?: string },
170
- routerPath?: string
171
- ): Plugin {
172
-
173
- // Build virtual modules map based on which entries use virtual IDs
174
- const virtualModules: Record<string, string> = {};
175
-
176
- if (entries.client === VIRTUAL_IDS.browser) {
177
- virtualModules[VIRTUAL_IDS.browser] = VIRTUAL_ENTRY_BROWSER;
178
- }
179
- if (entries.ssr === VIRTUAL_IDS.ssr) {
180
- virtualModules[VIRTUAL_IDS.ssr] = VIRTUAL_ENTRY_SSR;
181
- }
182
- if (entries.rsc === VIRTUAL_IDS.rsc && routerPath) {
183
- // Convert relative path to absolute for virtual module imports
184
- const absoluteRouterPath = routerPath.startsWith(".")
185
- ? "/" + routerPath.slice(2) // ./src/router.tsx -> /src/router.tsx
186
- : routerPath;
187
- virtualModules[VIRTUAL_IDS.rsc] = getVirtualEntryRSC(absoluteRouterPath);
188
- }
189
-
190
- return {
191
- name: "@rangojs/router:virtual-entries",
192
- enforce: "pre",
193
-
194
- resolveId(id) {
195
- if (id in virtualModules) {
196
- return "\0" + id;
197
- }
198
- // Handle if the id already has the null prefix (RSC plugin wrapper imports)
199
- if (id.startsWith("\0") && id.slice(1) in virtualModules) {
200
- return id;
201
- }
202
- return null;
203
- },
204
-
205
- load(id) {
206
- if (id.startsWith("\0virtual:rsc-router/")) {
207
- const virtualId = id.slice(1);
208
- if (virtualId in virtualModules) {
209
- return virtualModules[virtualId];
210
- }
211
- }
212
- return null;
213
- },
214
- };
215
- }
216
-
217
- /**
218
- * Manual chunks configuration for client build.
219
- * Splits React and router packages into separate chunks for better caching.
220
- */
221
- function getManualChunks(id: string): string | undefined {
222
- const normalized = Vite.normalizePath(id);
223
-
224
- if (
225
- normalized.includes("node_modules/react/") ||
226
- normalized.includes("node_modules/react-dom/") ||
227
- normalized.includes("node_modules/react-server-dom-webpack/") ||
228
- normalized.includes("node_modules/@vitejs/plugin-rsc/")
229
- ) {
230
- return "react";
231
- }
232
- // Use dynamic package name from package.json
233
- // Check both npm install path and workspace symlink resolved path
234
- const packageName = getPublishedPackageName();
235
- if (
236
- normalized.includes(`node_modules/${packageName}/`) ||
237
- normalized.includes("packages/rsc-router/") ||
238
- normalized.includes("packages/rangojs-router/")
239
- ) {
240
- return "router";
241
- }
242
- return undefined;
243
- }
244
-
245
- /**
246
- * Plugin providing rsc-router:version virtual module.
247
- * Exports VERSION that changes when RSC modules change (dev) or at build time (production).
248
- *
249
- * The version is used for:
250
- * 1. Cache invalidation - CFCacheStore uses VERSION to invalidate stale cache
251
- * 2. Version mismatch detection - client sends version, server reloads on mismatch
252
- *
253
- * In dev mode, the version updates when:
254
- * - Server starts (initial version)
255
- * - RSC modules change via HMR (triggers version module invalidation)
256
- *
257
- * Client-only HMR changes don't update the version since they don't affect
258
- * server-rendered content or cached RSC payloads.
259
- * @internal
260
- */
261
- function createVersionPlugin(): Plugin {
262
- // Generate version at plugin creation time (build/server start)
263
- const buildVersion = Date.now().toString(16);
264
- let currentVersion = buildVersion;
265
- let isDev = false;
266
- let server: any = null;
267
-
268
- return {
269
- name: "@rangojs/router:version",
270
- enforce: "pre",
271
-
272
- configResolved(config) {
273
- isDev = config.command === "serve";
274
- },
275
-
276
- configureServer(devServer) {
277
- server = devServer;
278
- },
279
-
280
- resolveId(id) {
281
- if (id === VIRTUAL_IDS.version) {
282
- return "\0" + id;
283
- }
284
- return null;
285
- },
286
-
287
- load(id) {
288
- if (id === "\0" + VIRTUAL_IDS.version) {
289
- return getVirtualVersionContent(currentVersion);
290
- }
291
- return null;
292
- },
293
-
294
- // Track RSC module changes and update version
295
- hotUpdate(ctx) {
296
- if (!isDev) return;
297
-
298
- // Check if this is an RSC environment update (not client/ssr)
299
- // RSC modules affect server-rendered content and cached payloads
300
- // In Vite 6, environment is accessed via `this.environment`
301
- const isRscModule = this.environment?.name === "rsc";
302
-
303
- if (isRscModule && ctx.modules.length > 0) {
304
- // Update version when RSC modules change
305
- currentVersion = Date.now().toString(16);
306
- console.log(
307
- `[rsc-router] RSC module changed, version updated: ${currentVersion}`
308
- );
309
-
310
- // Invalidate the version module so it gets reloaded with new version
311
- if (server) {
312
- const rscEnv = server.environments?.rsc;
313
- if (rscEnv?.moduleGraph) {
314
- const versionMod = rscEnv.moduleGraph.getModuleById(
315
- "\0" + VIRTUAL_IDS.version
316
- );
317
- if (versionMod) {
318
- rscEnv.moduleGraph.invalidateModule(versionMod);
319
- }
320
- }
321
- }
322
- }
323
- },
324
- };
325
- }
326
-
327
- /**
328
- * Plugin that discovers router instances at dev/build time via the RSC environment.
329
- *
330
- * Uses `server.environments.rsc.runner.import()` to load the user's router file
331
- * with full TS/TSX compilation. This triggers `createRouter()` which populates
332
- * the `RouterRegistry`. The plugin then generates manifests for each router.
333
- *
334
- * In dev mode, this runs in `configureServer` (post-middleware setup).
335
- * In build mode, this will run in `buildStart` (future).
336
- *
337
- * @internal
338
- */
339
- function createRouterDiscoveryPlugin(entryPath: string): Plugin {
340
- let projectRoot = "";
341
- let isBuildMode = false;
342
- let userResolveAlias: any = undefined;
343
-
344
- // Merged route manifest from all discovered routers.
345
- // Populated during discovery (dev: configureServer, build: buildStart).
346
- // Read by the virtual module's load hook to emit setCachedManifest() call.
347
- let mergedRouteManifest: Record<string, string> | null = null;
348
-
349
- // Shared discovery logic: import entry via RSC runner, generate manifests,
350
- // write static files, and populate mergedRouteManifest.
351
- async function discoverRouters(rscEnv: any) {
352
- // Import the entry file via RSC environment.
353
- // For node preset: this is the router file (createRouter() registers in RouterRegistry).
354
- // For cloudflare preset: this is the worker entry (which imports the router).
355
- await rscEnv.runner.import(entryPath);
356
-
357
- // Import the router package to access the registry
358
- const serverMod = await rscEnv.runner.import("@rangojs/router/server");
359
- let registry: Map<string, any> = serverMod.RouterRegistry;
360
-
361
- if (!registry || registry.size === 0) {
362
- // No RSC routers found directly. Check for host routers with lazy handlers
363
- // that need to be resolved to trigger sub-app createRouter() calls.
364
- try {
365
- const hostMod = await rscEnv.runner.import("@rangojs/router/host");
366
- const hostRegistry: Map<string, any> | undefined = hostMod.HostRouterRegistry;
367
-
368
- if (hostRegistry && hostRegistry.size > 0) {
369
- console.log(
370
- `[rsc-router] Found ${hostRegistry.size} host router(s), resolving lazy handlers...`
371
- );
372
-
373
- for (const [, entry] of hostRegistry) {
374
- for (const route of entry.routes) {
375
- if (typeof route.handler === 'function') {
376
- try {
377
- await route.handler();
378
- } catch {
379
- // Lazy handler may fail in temp server context, that's OK
380
- }
381
- }
382
- }
383
- if (entry.fallback && typeof entry.fallback.handler === 'function') {
384
- try {
385
- await entry.fallback.handler();
386
- } catch {
387
- // Fallback handler may fail in temp server context
388
- }
389
- }
390
- }
391
-
392
- // Re-read RouterRegistry - sub-app createRouter() calls should have populated it
393
- const freshServerMod = await rscEnv.runner.import("@rangojs/router/server");
394
- const freshRegistry: Map<string, any> = freshServerMod.RouterRegistry;
395
-
396
- if (freshRegistry && freshRegistry.size > 0) {
397
- // Update references so the manifest generation below uses the fresh data
398
- Object.assign(serverMod, freshServerMod);
399
- registry = freshRegistry;
400
- }
401
- }
402
- } catch {
403
- // @rangojs/router/host not available or import failed, skip
404
- }
405
-
406
- // If still no routers after host router resolution, fail
407
- if (!registry || registry.size === 0) {
408
- throw new Error(
409
- `[rsc-router] No routers found in registry after importing ${entryPath}`
410
- );
411
- }
412
- }
413
-
414
- // Import build utilities for manifest generation
415
- const buildMod = await rscEnv.runner.import("@rangojs/router/build");
416
- const generateManifest = buildMod.generateManifest;
417
-
418
- mergedRouteManifest = {};
419
-
420
- for (const [id, router] of registry) {
421
- if (!router.urlpatterns || !generateManifest) {
422
- continue;
423
- }
424
-
425
- const manifest = generateManifest(router.urlpatterns);
426
- const routeCount = Object.keys(manifest.routeManifest).length;
427
- const staticRoutes = Object.values(manifest.routeManifest).filter(
428
- (p: any) => !p.includes(":") && !p.includes("*")
429
- ).length;
430
- const dynamicRoutes = routeCount - staticRoutes;
431
-
432
- // Merge into the combined manifest
433
- Object.assign(mergedRouteManifest, manifest.routeManifest);
434
-
435
- // Write static files for this router
436
- const hash = hashRouterId(id);
437
- const outDir = join(projectRoot, "dist", "static", `__${hash}`);
438
- mkdirSync(outDir, { recursive: true });
439
-
440
- writeFileSync(
441
- join(outDir, "routes.json"),
442
- JSON.stringify(manifest.routeManifest, null, 2) + "\n"
443
- );
444
-
445
- writeFileSync(
446
- join(outDir, "prefixes.json"),
447
- JSON.stringify(manifest.prefixTree, null, 2) + "\n"
448
- );
449
-
450
- console.log(
451
- `[rsc-router] Router "${id}" -> ${routeCount} routes ` +
452
- `(${staticRoutes} static, ${dynamicRoutes} dynamic) ` +
453
- `-> dist/static/__${hash}/`
454
- );
455
- }
456
-
457
- return serverMod;
458
- }
459
-
460
- return {
461
- name: "@rangojs/router:discovery",
462
-
463
- configResolved(config) {
464
- projectRoot = config.root;
465
- isBuildMode = config.command === "build";
466
- // Capture user's resolve aliases for the temp server
467
- userResolveAlias = config.resolve.alias;
468
- },
469
-
470
- // Dev mode: discover routers and populate manifest in memory.
471
- // Skipped in build mode (buildStart handles it).
472
- configureServer(server) {
473
- if (isBuildMode) return;
474
- // Skip if this is a temp server created by buildStart
475
- if ((globalThis as any).__rscRouterDiscoveryActive) return;
476
- const discover = async () => {
477
- const rscEnv = (server.environments as any)?.rsc;
478
- if (!rscEnv?.runner) {
479
- return;
480
- }
481
-
482
- try {
483
- const serverMod = await discoverRouters(rscEnv);
484
-
485
- // In dev mode, also populate the route map in the RSC env
486
- // so href() works immediately without first-request penalty
487
- if (mergedRouteManifest && serverMod?.setCachedManifest) {
488
- serverMod.setCachedManifest(mergedRouteManifest);
489
- }
490
- } catch (err: any) {
491
- console.warn(
492
- `[rsc-router] Router discovery failed: ${err.message}`
493
- );
494
- }
495
- };
496
-
497
- // Schedule after all plugins have finished configureServer
498
- setTimeout(discover, 0);
499
- },
500
-
501
- // Build mode: create a temporary Vite dev server to access the RSC
502
- // environment's module runner, then discover routers and generate manifests.
503
- // The manifest data is stored for the virtual module's load hook.
504
- async buildStart() {
505
- if (!isBuildMode) return;
506
- // Only run once across environment builds
507
- if (mergedRouteManifest !== null) return;
508
-
509
- let tempServer: any = null;
510
- try {
511
- // Prevent the temp server's plugin instances from running discovery
512
- (globalThis as any).__rscRouterDiscoveryActive = true;
513
-
514
- // Create a minimal Vite server with just the RSC plugin.
515
- // We bypass the user's config file because:
516
- // - Custom environments (e.g., CloudflareDevEnvironment) may not expose
517
- // a module runner compatible with runner.import()
518
- // - The temp server only needs RSC conditions to import the router
519
- const { default: rsc } = await import("@vitejs/plugin-rsc");
520
- tempServer = await createViteServer({
521
- root: projectRoot,
522
- configFile: false,
523
- server: { middlewareMode: true },
524
- appType: "custom",
525
- logLevel: "silent",
526
- // Use the resolved aliases from the real config (includes user's path aliases
527
- // like @/ -> src/ AND package aliases from rsc-router)
528
- resolve: { alias: userResolveAlias },
529
- // Enable automatic JSX runtime so .tsx files don't need `import React`.
530
- // Without this, esbuild defaults to classic mode (React.createElement)
531
- // which fails when lazy host-router handlers load sub-app modules with JSX.
532
- esbuild: { jsx: "automatic", jsxImportSource: "react" },
533
- plugins: [
534
- rsc({ entries: { client: "virtual:entry-client", ssr: "virtual:entry-ssr", rsc: entryPath } }),
535
- createVersionPlugin(),
536
- // Stub virtual modules that the RSC entry may import
537
- // (e.g., virtual:rsc-router/routes-manifest, virtual:rsc-router/loader-manifest)
538
- createVirtualStubPlugin(),
539
- ],
540
- });
541
-
542
- const rscEnv = (tempServer.environments as any)?.rsc;
543
- if (!rscEnv?.runner) {
544
- console.warn(
545
- "[rsc-router] RSC environment runner not available during build, skipping manifest generation"
546
- );
547
- return;
548
- }
549
-
550
- await discoverRouters(rscEnv);
551
- } catch (err: any) {
552
- // Clean up before re-throwing so the temp server doesn't leak
553
- delete (globalThis as any).__rscRouterDiscoveryActive;
554
- if (tempServer) {
555
- await tempServer.close();
556
- }
557
- throw new Error(
558
- `[rsc-router] Build-time router discovery failed: ${err.message}`
559
- );
560
- } finally {
561
- delete (globalThis as any).__rscRouterDiscoveryActive;
562
- if (tempServer) {
563
- await tempServer.close();
564
- }
565
- }
566
- },
567
-
568
- // Virtual module: provides the pre-generated route manifest as a JS module
569
- // that calls setCachedManifest() at import time.
570
- resolveId(id) {
571
- if (id === VIRTUAL_ROUTES_MANIFEST_ID) {
572
- return "\0" + VIRTUAL_ROUTES_MANIFEST_ID;
573
- }
574
- return null;
575
- },
576
-
577
- load(id) {
578
- if (id === "\0" + VIRTUAL_ROUTES_MANIFEST_ID) {
579
- const hasManifest = mergedRouteManifest && Object.keys(mergedRouteManifest).length > 0;
580
- if (hasManifest) {
581
- return [
582
- `import { setCachedManifest } from "@rangojs/router/server";`,
583
- `setCachedManifest(${JSON.stringify(mergedRouteManifest)});`,
584
- ].join("\n");
585
- }
586
- // No manifest available yet (dev mode: discovery hasn't completed)
587
- return `// Route manifest will be populated at runtime`;
588
- }
589
- return null;
590
- },
591
- };
592
- }
593
-
594
- const VIRTUAL_ROUTES_MANIFEST_ID = "virtual:rsc-router/routes-manifest";
595
-
596
- /**
597
- * Resolve the entry path for build-time router discovery.
598
- * - Node preset: uses the required `router` option.
599
- * - Cloudflare preset: reads the `main` field from wrangler.json.
600
- */
601
- function resolveDiscoveryEntryPath(options: RscRouterOptions): string | undefined {
602
- if (options.preset === "cloudflare") {
603
- // Auto-detect from wrangler.json
604
- const wranglerPaths = ["wrangler.json", "wrangler.jsonc"];
605
- for (const filename of wranglerPaths) {
606
- if (existsSync(filename)) {
607
- try {
608
- const raw = readFileSync(filename, "utf-8");
609
- // Strip JSON comments for .jsonc
610
- const cleaned = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
611
- const config = JSON.parse(cleaned);
612
- if (config.main) {
613
- return config.main;
614
- }
615
- } catch {
616
- // Ignore parse errors
617
- }
618
- }
619
- }
620
- return undefined;
621
- }
622
- // Node preset: router is required
623
- return (options as RscRouterNodeOptions).router;
624
- }
625
-
626
1
  /**
627
- * Stub plugin for virtual modules in the temp discovery server.
628
- * The RSC entry may import virtual modules (routes-manifest, loader-manifest)
629
- * that aren't available in the temp server. The RSC plugin also requires
630
- * client/ssr entries which don't need real content for discovery.
631
- */
632
- function createVirtualStubPlugin(): Plugin {
633
- const STUB_PREFIXES = [
634
- "virtual:rsc-router/",
635
- "virtual:entry-",
636
- "virtual:vite-rsc/",
637
- ];
638
- return {
639
- name: "@rangojs/router:virtual-stubs",
640
- resolveId(id) {
641
- if (STUB_PREFIXES.some((p) => id.startsWith(p))) {
642
- return "\0stub:" + id;
643
- }
644
- return null;
645
- },
646
- load(id) {
647
- if (id.startsWith("\0stub:")) {
648
- return "export default {}";
649
- }
650
- return null;
651
- },
652
- };
653
- }
654
-
655
- /**
656
- * Generate a deterministic 12-char hex hash from a router id.
657
- * Used to create collision-free directory names for per-router static output.
658
- */
659
- function hashRouterId(id: string): string {
660
- return createHash("sha256").update(id).digest("hex").slice(0, 12);
661
- }
662
-
663
- /**
664
- * Plugin that auto-injects VERSION into custom entry.rsc files.
665
- * If a custom entry.rsc file uses createRSCHandler but doesn't pass version,
666
- * this transform adds the import and property automatically.
667
- * @internal
668
- */
669
- function createVersionInjectorPlugin(rscEntryPath: string): Plugin {
670
- let projectRoot = "";
671
- let resolvedEntryPath = "";
672
-
673
- return {
674
- name: "@rangojs/router:version-injector",
675
- enforce: "pre",
676
-
677
- configResolved(config) {
678
- projectRoot = config.root;
679
- resolvedEntryPath = resolve(projectRoot, rscEntryPath);
680
- },
681
-
682
- transform(code, id) {
683
- // Only transform the RSC entry file
684
- const normalizedId = Vite.normalizePath(id);
685
- const normalizedEntry = Vite.normalizePath(resolvedEntryPath);
686
-
687
- if (normalizedId !== normalizedEntry) {
688
- return null;
689
- }
690
-
691
- // Check if file uses createRSCHandler
692
- if (!code.includes("createRSCHandler")) {
693
- return null;
694
- }
695
-
696
- // Check if VERSION is already imported
697
- if (code.includes("@rangojs/router:version")) {
698
- return null;
699
- }
700
-
701
- // Check if version property is already being passed
702
- // Look for version: in the createRSCHandler call
703
- const handlerCallMatch = code.match(/createRSCHandler\s*\(\s*\{/);
704
- if (!handlerCallMatch) {
705
- return null;
706
- }
707
-
708
- // Add VERSION import after the last import statement
709
- const lastImportIndex = code.lastIndexOf("import ");
710
- if (lastImportIndex === -1) {
711
- return null;
712
- }
713
-
714
- // Find the end of the last import statement
715
- const afterLastImport = code.indexOf("\n", lastImportIndex);
716
- if (afterLastImport === -1) {
717
- return null;
718
- }
719
-
720
- // Find next line that's not an import continuation
721
- let insertIndex = afterLastImport + 1;
722
- while (
723
- insertIndex < code.length &&
724
- (code.slice(insertIndex).match(/^\s*(from|import)\s/) ||
725
- code[insertIndex] === "\n")
726
- ) {
727
- const nextNewline = code.indexOf("\n", insertIndex);
728
- if (nextNewline === -1) break;
729
- insertIndex = nextNewline + 1;
730
- }
731
-
732
- // Insert VERSION import
733
- const versionImport = `import { VERSION } from "@rangojs/router:version";\n`;
734
- let newCode = code.slice(0, insertIndex) + versionImport + code.slice(insertIndex);
735
-
736
- // Add version: VERSION to createRSCHandler call
737
- // Find createRSCHandler({ and add version: VERSION right after the opening brace
738
- newCode = newCode.replace(
739
- /createRSCHandler\s*\(\s*\{/,
740
- "createRSCHandler({\n version: VERSION,"
741
- );
742
-
743
- return {
744
- code: newCode,
745
- map: null,
746
- };
747
- },
748
- };
749
- }
750
-
751
- /**
752
- * Vite plugin for rsc-router.
753
- *
754
- * Includes @vitejs/plugin-rsc and all necessary transforms for the router
755
- * to function correctly with React Server Components.
2
+ * Public API for @rangojs/router/vite
756
3
  *
757
- * @example Node.js (default)
758
- * ```ts
759
- * export default defineConfig({
760
- * plugins: [react(), rscRouter({ router: './src/router.tsx' })],
761
- * });
762
- * ```
763
- *
764
- * @example Cloudflare Workers
765
- * ```ts
766
- * export default defineConfig({
767
- * plugins: [
768
- * react(),
769
- * rscRouter({ preset: 'cloudflare' }),
770
- * cloudflare({ viteEnvironment: { name: 'rsc' } }),
771
- * ],
772
- * });
773
- * ```
4
+ * Exports: rango() plugin factory, poke() dev utility plugin,
5
+ * and related option types. All other utilities are internal implementation
6
+ * details consumed via direct imports within the package.
774
7
  */
775
- export async function rscRouter(
776
- options: RscRouterOptions
777
- ): Promise<PluginOption[]> {
778
- const preset = options.preset ?? "node";
779
- const enableExposeActionId = options.exposeActionId ?? true;
780
-
781
- const plugins: PluginOption[] = [];
782
-
783
- // Get package resolution info (workspace vs npm install)
784
- const rscRouterAliases = getPackageAliases();
785
- const excludeDeps = getExcludeDeps();
786
-
787
- // Track RSC entry path for version injection
788
- let rscEntryPath: string | null = null;
789
-
790
- if (preset === "cloudflare") {
791
- // Cloudflare preset: configure entries for cloudflare worker setup
792
- // Router is not needed here - worker.rsc.tsx imports it directly
793
-
794
- // Dynamically import @vitejs/plugin-rsc
795
- const { default: rsc } = await import("@vitejs/plugin-rsc");
796
-
797
- // Only client and ssr entries - rsc entry is handled by cloudflare plugin
798
- // Always use virtual modules for cloudflare preset
799
- const finalEntries: { client: string; ssr: string } = {
800
- client: VIRTUAL_IDS.browser,
801
- ssr: VIRTUAL_IDS.ssr,
802
- };
803
-
804
- plugins.push({
805
- name: "@rangojs/router:cloudflare-integration",
806
- enforce: "pre",
807
- config() {
808
- // Configure environments for cloudflare deployment
809
- return {
810
- // Exclude rsc-router modules from optimization to prevent module duplication
811
- // This ensures the same Context instance is used by both browser entry and RSC proxy modules
812
- optimizeDeps: {
813
- exclude: excludeDeps,
814
- esbuildOptions: sharedEsbuildOptions,
815
- },
816
- resolve: {
817
- alias: rscRouterAliases,
818
- },
819
- environments: {
820
- client: {
821
- build: {
822
- rollupOptions: {
823
- output: {
824
- manualChunks: getManualChunks,
825
- },
826
- },
827
- },
828
- // Pre-bundle rsc-html-stream to prevent discovery during first request
829
- // Exclude rsc-router modules to ensure same Context instance
830
- optimizeDeps: {
831
- include: ["rsc-html-stream/client"],
832
- exclude: excludeDeps,
833
- esbuildOptions: sharedEsbuildOptions,
834
- },
835
- },
836
- ssr: {
837
- // Build SSR inside RSC directory so wrangler can deploy self-contained dist/rsc
838
- build: {
839
- outDir: "./dist/rsc/ssr",
840
- },
841
- resolve: {
842
- // Ensure single React instance in SSR child environment
843
- dedupe: ["react", "react-dom"],
844
- },
845
- // Pre-bundle SSR entry and React for proper module linking with childEnvironments
846
- // Exclude rsc-router modules to ensure same Context instance
847
- optimizeDeps: {
848
- entries: [finalEntries.ssr],
849
- include: [
850
- "react",
851
- "react-dom/server.edge",
852
- "react/jsx-runtime",
853
- "rsc-html-stream/server",
854
- ],
855
- exclude: excludeDeps,
856
- esbuildOptions: sharedEsbuildOptions,
857
- },
858
- },
859
- rsc: {
860
- // RSC environment needs exclude list and esbuild options
861
- // Exclude rsc-router modules to prevent createContext in RSC environment
862
- optimizeDeps: {
863
- exclude: excludeDeps,
864
- esbuildOptions: sharedEsbuildOptions,
865
- },
866
- },
867
- },
868
- };
869
- },
870
- });
871
-
872
- plugins.push(createVirtualEntriesPlugin(finalEntries));
873
-
874
- // Add RSC plugin with cloudflare-specific options
875
- // Note: loadModuleDevProxy should NOT be used with childEnvironments
876
- // since SSR runs in workerd alongside RSC
877
- plugins.push(
878
- rsc({
879
- get entries() {
880
- return finalEntries;
881
- },
882
- serverHandler: false,
883
- }) as PluginOption
884
- );
885
- } else {
886
- // Node preset: full RSC plugin integration
887
- const nodeOptions = options as RscRouterNodeOptions;
888
- const routerPath = nodeOptions.router;
889
- const rscOption = nodeOptions.rsc ?? true;
890
-
891
- // Add RSC plugin by default (can be disabled with rsc: false)
892
- if (rscOption !== false) {
893
- // Dynamically import @vitejs/plugin-rsc
894
- const { default: rsc } = await import("@vitejs/plugin-rsc");
895
-
896
- // Resolve entry paths: use explicit config or virtual modules
897
- const userEntries =
898
- typeof rscOption === "boolean" ? {} : rscOption.entries || {};
899
- const finalEntries = {
900
- client: userEntries.client ?? VIRTUAL_IDS.browser,
901
- ssr: userEntries.ssr ?? VIRTUAL_IDS.ssr,
902
- rsc: userEntries.rsc ?? VIRTUAL_IDS.rsc,
903
- };
904
-
905
- // Track RSC entry for version injection (only if custom entry provided)
906
- rscEntryPath = userEntries.rsc ?? null;
907
-
908
- // Create wrapper plugin that checks for duplicates
909
- let hasWarnedDuplicate = false;
910
-
911
- plugins.push({
912
- name: "@rangojs/router:rsc-integration",
913
- enforce: "pre",
914
-
915
- config() {
916
- // Configure environments for RSC
917
- // When using virtual entries, we need to explicitly configure optimizeDeps
918
- // so Vite pre-bundles React before processing the virtual modules.
919
- // Without this, the dep optimizer may run multiple times with different hashes,
920
- // causing React instance mismatches.
921
- const useVirtualClient = finalEntries.client === VIRTUAL_IDS.browser;
922
- const useVirtualSSR = finalEntries.ssr === VIRTUAL_IDS.ssr;
923
- const useVirtualRSC = finalEntries.rsc === VIRTUAL_IDS.rsc;
924
-
925
- return {
926
- // Exclude rsc-router modules from optimization to prevent module duplication
927
- // This ensures the same Context instance is used by both browser entry and RSC proxy modules
928
- optimizeDeps: {
929
- exclude: excludeDeps,
930
- esbuildOptions: sharedEsbuildOptions,
931
- },
932
- resolve: {
933
- alias: rscRouterAliases,
934
- },
935
- environments: {
936
- client: {
937
- build: {
938
- rollupOptions: {
939
- output: {
940
- manualChunks: getManualChunks,
941
- },
942
- },
943
- },
944
- // Always exclude rsc-router modules, conditionally add virtual entry
945
- optimizeDeps: {
946
- exclude: excludeDeps,
947
- esbuildOptions: sharedEsbuildOptions,
948
- ...(useVirtualClient && {
949
- // Tell Vite to scan the virtual entry for dependencies
950
- entries: [VIRTUAL_IDS.browser],
951
- }),
952
- },
953
- },
954
- ...(useVirtualSSR && {
955
- ssr: {
956
- optimizeDeps: {
957
- entries: [VIRTUAL_IDS.ssr],
958
- // Pre-bundle React for SSR to ensure single instance
959
- include: ["react", "react-dom/server.edge", "react/jsx-runtime"],
960
- exclude: excludeDeps,
961
- esbuildOptions: sharedEsbuildOptions,
962
- },
963
- },
964
- }),
965
- ...(useVirtualRSC && {
966
- rsc: {
967
- optimizeDeps: {
968
- entries: [VIRTUAL_IDS.rsc],
969
- // Pre-bundle React for RSC to ensure single instance
970
- include: ["react", "react/jsx-runtime"],
971
- esbuildOptions: sharedEsbuildOptions,
972
- },
973
- },
974
- }),
975
- },
976
- };
977
- },
978
-
979
- configResolved(config) {
980
- // Count how many RSC base plugins there are (rsc:minimal is the main one)
981
- const rscMinimalCount = config.plugins.filter(
982
- (p) => p.name === "rsc:minimal"
983
- ).length;
984
-
985
- if (rscMinimalCount > 1 && !hasWarnedDuplicate) {
986
- hasWarnedDuplicate = true;
987
- console.warn(
988
- "[rsc-router] Duplicate @vitejs/plugin-rsc detected. " +
989
- "Remove rsc() from your config or use rscRouter({ rsc: false }) for manual configuration."
990
- );
991
- }
992
- },
993
- });
994
-
995
- // Add virtual entries plugin
996
- plugins.push(createVirtualEntriesPlugin(finalEntries, routerPath));
997
-
998
- // Add the RSC plugin directly
999
- // Cast to PluginOption to handle type differences between bundled vite types
1000
- plugins.push(
1001
- rsc({
1002
- entries: finalEntries,
1003
- }) as PluginOption
1004
- );
1005
- }
1006
- }
1007
-
1008
- if (enableExposeActionId) {
1009
- plugins.push(exposeActionId());
1010
- }
1011
-
1012
- // Always add exposeLoaderId for GET-based loader fetching with useFetchLoader
1013
- plugins.push(exposeLoaderId());
1014
-
1015
- // Always add exposeHandleId for auto-generated handle IDs
1016
- plugins.push(exposeHandleId());
1017
-
1018
- // Always add exposeLocationStateId for auto-generated location state keys
1019
- plugins.push(exposeLocationStateId());
1020
-
1021
- // Add version virtual module plugin for cache invalidation
1022
- plugins.push(createVersionPlugin());
1023
-
1024
- // Add version injector for custom entry.rsc files
1025
- if (rscEntryPath) {
1026
- plugins.push(createVersionInjectorPlugin(rscEntryPath));
1027
- }
1028
-
1029
- // Transform CJS vendor files to ESM for browser compatibility
1030
- // optimizeDeps.include doesn't work because the file is loaded after initial optimization
1031
- plugins.push(createCjsToEsmPlugin());
1032
-
1033
- // Add router discovery plugin for build-time manifest generation.
1034
- // Node preset: uses the required router path.
1035
- // Cloudflare preset: auto-detects RSC entry from wrangler.json main field.
1036
- const discoveryEntryPath = resolveDiscoveryEntryPath(options);
1037
- if (discoveryEntryPath) {
1038
- plugins.push(createRouterDiscoveryPlugin(discoveryEntryPath));
1039
- }
1040
-
1041
- return plugins;
1042
- }
1043
-
1044
- /** Alias for backwards compatibility */
1045
- export const rango = rscRouter;
1046
-
1047
- /**
1048
- * Transform CJS vendor files from @vitejs/plugin-rsc to ESM for browser compatibility.
1049
- * The react-server-dom vendor files are shipped as CJS which doesn't work in browsers.
1050
- */
1051
- function createCjsToEsmPlugin(): Plugin {
1052
- return {
1053
- name: "@rangojs/router:cjs-to-esm",
1054
- enforce: "pre",
1055
- transform(code, id) {
1056
- const cleanId = id.split("?")[0];
1057
-
1058
- // Transform the client.browser.js entry point to re-export from CJS
1059
- if (
1060
- cleanId.includes("vendor/react-server-dom/client.browser.js") ||
1061
- cleanId.includes("vendor\\react-server-dom\\client.browser.js")
1062
- ) {
1063
- const isProd = process.env.NODE_ENV === "production";
1064
- const cjsFile = isProd
1065
- ? "./cjs/react-server-dom-webpack-client.browser.production.js"
1066
- : "./cjs/react-server-dom-webpack-client.browser.development.js";
1067
-
1068
- return {
1069
- code: `export * from "${cjsFile}";`,
1070
- map: null,
1071
- };
1072
- }
1073
-
1074
- // Transform the actual CJS files to ESM
1075
- if (
1076
- (cleanId.includes("vendor/react-server-dom/cjs/") ||
1077
- cleanId.includes("vendor\\react-server-dom\\cjs\\")) &&
1078
- cleanId.includes("client.browser")
1079
- ) {
1080
- let transformed = code;
1081
-
1082
- // Extract the license comment to preserve it
1083
- const licenseMatch = transformed.match(/^\/\*\*[\s\S]*?\*\//);
1084
- const license = licenseMatch ? licenseMatch[0] : "";
1085
- if (license) {
1086
- transformed = transformed.slice(license.length);
1087
- }
1088
-
1089
- // Remove "use strict" (both dev and prod have this)
1090
- transformed = transformed.replace(/^\s*["']use strict["'];\s*/, "");
1091
-
1092
- // Remove the conditional IIFE wrapper (development only)
1093
- transformed = transformed.replace(
1094
- /^\s*["']production["']\s*!==\s*process\.env\.NODE_ENV\s*&&\s*\(function\s*\(\)\s*\{/,
1095
- ""
1096
- );
1097
-
1098
- // Remove the closing of the conditional IIFE at the end (development only)
1099
- transformed = transformed.replace(/\}\)\(\);?\s*$/, "");
1100
-
1101
- // Replace require('react') and require('react-dom') with imports (development)
1102
- transformed = transformed.replace(
1103
- /var\s+React\s*=\s*require\s*\(\s*["']react["']\s*\)\s*,[\s\n]+ReactDOM\s*=\s*require\s*\(\s*["']react-dom["']\s*\)\s*,/g,
1104
- 'import React from "react";\nimport ReactDOM from "react-dom";\nvar '
1105
- );
1106
-
1107
- // Replace require('react-dom') only (production - doesn't import React)
1108
- transformed = transformed.replace(
1109
- /var\s+ReactDOM\s*=\s*require\s*\(\s*["']react-dom["']\s*\)\s*,/g,
1110
- 'import ReactDOM from "react-dom";\nvar '
1111
- );
1112
-
1113
- // Transform exports.xyz = function() to export function xyz()
1114
- transformed = transformed.replace(
1115
- /exports\.(\w+)\s*=\s*function\s*\(/g,
1116
- "export function $1("
1117
- );
1118
-
1119
- // Transform exports.xyz = value to export const xyz = value
1120
- transformed = transformed.replace(
1121
- /exports\.(\w+)\s*=/g,
1122
- "export const $1 ="
1123
- );
1124
-
1125
- // Reconstruct with license at the top
1126
- transformed = license + "\n" + transformed;
1127
-
1128
- return {
1129
- code: transformed,
1130
- map: null,
1131
- };
1132
- }
1133
8
 
1134
- return null;
1135
- },
1136
- };
1137
- }
9
+ export { rango } from "./rango.js";
10
+ export { poke } from "./plugins/refresh-cmd.js";
1138
11
 
12
+ export type {
13
+ RangoNodeOptions,
14
+ RangoCloudflareOptions,
15
+ RangoOptions,
16
+ BuildEnvOption,
17
+ BuildEnvFactory,
18
+ BuildEnvFactoryContext,
19
+ BuildEnvResult,
20
+ } from "./plugin-types.js";