@rangojs/router 0.0.0-experimental.13 → 0.0.0-experimental.13221847

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 (298) hide show
  1. package/AGENTS.md +9 -0
  2. package/README.md +884 -4
  3. package/dist/bin/rango.js +1531 -212
  4. package/dist/vite/index.js +3995 -2489
  5. package/package.json +57 -52
  6. package/skills/breadcrumbs/SKILL.md +250 -0
  7. package/skills/cache-guide/SKILL.md +262 -0
  8. package/skills/caching/SKILL.md +85 -23
  9. package/skills/composability/SKILL.md +172 -0
  10. package/skills/debug-manifest/SKILL.md +12 -8
  11. package/skills/document-cache/SKILL.md +18 -16
  12. package/skills/fonts/SKILL.md +6 -4
  13. package/skills/hooks/SKILL.md +328 -70
  14. package/skills/host-router/SKILL.md +218 -0
  15. package/skills/intercept/SKILL.md +131 -8
  16. package/skills/layout/SKILL.md +100 -3
  17. package/skills/links/SKILL.md +62 -15
  18. package/skills/loader/SKILL.md +368 -42
  19. package/skills/middleware/SKILL.md +171 -34
  20. package/skills/mime-routes/SKILL.md +14 -10
  21. package/skills/parallel/SKILL.md +137 -1
  22. package/skills/prerender/SKILL.md +366 -28
  23. package/skills/rango/SKILL.md +85 -21
  24. package/skills/response-routes/SKILL.md +136 -83
  25. package/skills/route/SKILL.md +195 -21
  26. package/skills/router-setup/SKILL.md +123 -30
  27. package/skills/theme/SKILL.md +9 -8
  28. package/skills/typesafety/SKILL.md +240 -102
  29. package/skills/use-cache/SKILL.md +324 -0
  30. package/src/__internal.ts +102 -4
  31. package/src/bin/rango.ts +312 -15
  32. package/src/browser/action-coordinator.ts +97 -0
  33. package/src/browser/action-response-classifier.ts +99 -0
  34. package/src/browser/event-controller.ts +92 -64
  35. package/src/browser/history-state.ts +80 -0
  36. package/src/browser/intercept-utils.ts +52 -0
  37. package/src/browser/link-interceptor.ts +24 -4
  38. package/src/browser/logging.ts +11 -0
  39. package/src/browser/merge-segment-loaders.ts +20 -12
  40. package/src/browser/navigation-bridge.ts +266 -558
  41. package/src/browser/navigation-client.ts +132 -75
  42. package/src/browser/navigation-store.ts +33 -50
  43. package/src/browser/navigation-transaction.ts +297 -0
  44. package/src/browser/network-error-handler.ts +61 -0
  45. package/src/browser/partial-update.ts +303 -309
  46. package/src/browser/prefetch/cache.ts +206 -0
  47. package/src/browser/prefetch/fetch.ts +144 -0
  48. package/src/browser/prefetch/observer.ts +65 -0
  49. package/src/browser/prefetch/policy.ts +48 -0
  50. package/src/browser/prefetch/queue.ts +128 -0
  51. package/src/browser/rango-state.ts +112 -0
  52. package/src/browser/react/Link.tsx +190 -70
  53. package/src/browser/react/NavigationProvider.tsx +78 -11
  54. package/src/browser/react/context.ts +6 -0
  55. package/src/browser/react/filter-segment-order.ts +11 -0
  56. package/src/browser/react/index.ts +12 -12
  57. package/src/browser/react/location-state-shared.ts +95 -53
  58. package/src/browser/react/location-state.ts +60 -15
  59. package/src/browser/react/mount-context.ts +6 -1
  60. package/src/browser/react/nonce-context.ts +23 -0
  61. package/src/browser/react/shallow-equal.ts +27 -0
  62. package/src/browser/react/use-action.ts +29 -51
  63. package/src/browser/react/use-client-cache.ts +5 -3
  64. package/src/browser/react/use-handle.ts +29 -70
  65. package/src/browser/react/use-link-status.ts +6 -5
  66. package/src/browser/react/use-navigation.ts +22 -63
  67. package/src/browser/react/use-params.ts +65 -0
  68. package/src/browser/react/use-pathname.ts +47 -0
  69. package/src/browser/react/use-router.ts +63 -0
  70. package/src/browser/react/use-search-params.ts +56 -0
  71. package/src/browser/react/use-segments.ts +80 -97
  72. package/src/browser/response-adapter.ts +73 -0
  73. package/src/browser/rsc-router.tsx +188 -57
  74. package/src/browser/scroll-restoration.ts +117 -44
  75. package/src/browser/segment-reconciler.ts +221 -0
  76. package/src/browser/segment-structure-assert.ts +16 -0
  77. package/src/browser/server-action-bridge.ts +488 -606
  78. package/src/browser/shallow.ts +6 -1
  79. package/src/browser/types.ts +116 -47
  80. package/src/browser/validate-redirect-origin.ts +29 -0
  81. package/src/build/generate-manifest.ts +63 -21
  82. package/src/build/generate-route-types.ts +36 -1038
  83. package/src/build/index.ts +2 -5
  84. package/src/build/route-trie.ts +38 -12
  85. package/src/build/route-types/ast-helpers.ts +25 -0
  86. package/src/build/route-types/ast-route-extraction.ts +98 -0
  87. package/src/build/route-types/codegen.ts +102 -0
  88. package/src/build/route-types/include-resolution.ts +411 -0
  89. package/src/build/route-types/param-extraction.ts +48 -0
  90. package/src/build/route-types/per-module-writer.ts +128 -0
  91. package/src/build/route-types/router-processing.ts +479 -0
  92. package/src/build/route-types/scan-filter.ts +78 -0
  93. package/src/build/runtime-discovery.ts +231 -0
  94. package/src/cache/background-task.ts +34 -0
  95. package/src/cache/cache-key-utils.ts +44 -0
  96. package/src/cache/cache-policy.ts +125 -0
  97. package/src/cache/cache-runtime.ts +342 -0
  98. package/src/cache/cache-scope.ts +122 -303
  99. package/src/cache/cf/cf-cache-store.ts +571 -17
  100. package/src/cache/cf/index.ts +13 -3
  101. package/src/cache/document-cache.ts +116 -77
  102. package/src/cache/handle-capture.ts +81 -0
  103. package/src/cache/handle-snapshot.ts +41 -0
  104. package/src/cache/index.ts +1 -15
  105. package/src/cache/memory-segment-store.ts +191 -13
  106. package/src/cache/profile-registry.ts +73 -0
  107. package/src/cache/read-through-swr.ts +134 -0
  108. package/src/cache/segment-codec.ts +256 -0
  109. package/src/cache/taint.ts +98 -0
  110. package/src/cache/types.ts +72 -122
  111. package/src/client.rsc.tsx +3 -1
  112. package/src/client.tsx +84 -126
  113. package/src/component-utils.ts +4 -4
  114. package/src/components/DefaultDocument.tsx +5 -1
  115. package/src/context-var.ts +86 -0
  116. package/src/debug.ts +19 -9
  117. package/src/errors.ts +77 -7
  118. package/src/handle.ts +12 -7
  119. package/src/handles/MetaTags.tsx +73 -20
  120. package/src/handles/breadcrumbs.ts +66 -0
  121. package/src/handles/index.ts +1 -0
  122. package/src/handles/meta.ts +30 -13
  123. package/src/host/cookie-handler.ts +21 -15
  124. package/src/host/errors.ts +8 -8
  125. package/src/host/index.ts +4 -7
  126. package/src/host/pattern-matcher.ts +27 -27
  127. package/src/host/router.ts +61 -39
  128. package/src/host/testing.ts +8 -8
  129. package/src/host/types.ts +15 -7
  130. package/src/host/utils.ts +1 -1
  131. package/src/href-client.ts +65 -45
  132. package/src/index.rsc.ts +104 -40
  133. package/src/index.ts +122 -67
  134. package/src/internal-debug.ts +9 -3
  135. package/src/loader.rsc.ts +18 -93
  136. package/src/loader.ts +26 -9
  137. package/src/network-error-thrower.tsx +3 -1
  138. package/src/outlet-provider.tsx +45 -0
  139. package/src/prerender/param-hash.ts +4 -2
  140. package/src/prerender/store.ts +121 -17
  141. package/src/prerender.ts +325 -20
  142. package/src/reverse.ts +144 -124
  143. package/src/root-error-boundary.tsx +41 -29
  144. package/src/route-content-wrapper.tsx +7 -4
  145. package/src/route-definition/dsl-helpers.ts +959 -0
  146. package/src/route-definition/helper-factories.ts +200 -0
  147. package/src/route-definition/helpers-types.ts +430 -0
  148. package/src/route-definition/index.ts +52 -0
  149. package/src/route-definition/redirect.ts +93 -0
  150. package/src/route-definition.ts +1 -1450
  151. package/src/route-map-builder.ts +87 -133
  152. package/src/route-name.ts +53 -0
  153. package/src/route-types.ts +41 -6
  154. package/src/router/content-negotiation.ts +116 -0
  155. package/src/router/debug-manifest.ts +72 -0
  156. package/src/router/error-handling.ts +9 -9
  157. package/src/router/find-match.ts +160 -0
  158. package/src/router/handler-context.ts +324 -116
  159. package/src/router/intercept-resolution.ts +11 -4
  160. package/src/router/lazy-includes.ts +237 -0
  161. package/src/router/loader-resolution.ts +179 -133
  162. package/src/router/logging.ts +112 -6
  163. package/src/router/manifest.ts +58 -19
  164. package/src/router/match-api.ts +89 -88
  165. package/src/router/match-context.ts +4 -2
  166. package/src/router/match-handlers.ts +440 -0
  167. package/src/router/match-middleware/background-revalidation.ts +86 -89
  168. package/src/router/match-middleware/cache-lookup.ts +295 -49
  169. package/src/router/match-middleware/cache-store.ts +56 -13
  170. package/src/router/match-middleware/intercept-resolution.ts +45 -22
  171. package/src/router/match-middleware/segment-resolution.ts +20 -9
  172. package/src/router/match-pipelines.ts +10 -45
  173. package/src/router/match-result.ts +44 -21
  174. package/src/router/metrics.ts +240 -15
  175. package/src/router/middleware-cookies.ts +55 -0
  176. package/src/router/middleware-types.ts +222 -0
  177. package/src/router/middleware.ts +327 -369
  178. package/src/router/pattern-matching.ts +169 -31
  179. package/src/router/prerender-match.ts +402 -0
  180. package/src/router/preview-match.ts +170 -0
  181. package/src/router/revalidation.ts +105 -14
  182. package/src/router/router-context.ts +40 -21
  183. package/src/router/router-interfaces.ts +452 -0
  184. package/src/router/router-options.ts +592 -0
  185. package/src/router/router-registry.ts +24 -0
  186. package/src/router/segment-resolution/fresh.ts +677 -0
  187. package/src/router/segment-resolution/helpers.ts +263 -0
  188. package/src/router/segment-resolution/loader-cache.ts +199 -0
  189. package/src/router/segment-resolution/revalidation.ts +1296 -0
  190. package/src/router/segment-resolution/static-store.ts +67 -0
  191. package/src/router/segment-resolution.ts +21 -1354
  192. package/src/router/segment-wrappers.ts +291 -0
  193. package/src/router/telemetry-otel.ts +299 -0
  194. package/src/router/telemetry.ts +300 -0
  195. package/src/router/timeout.ts +148 -0
  196. package/src/router/trie-matching.ts +96 -29
  197. package/src/router/types.ts +15 -9
  198. package/src/router.ts +642 -2366
  199. package/src/rsc/handler-context.ts +45 -0
  200. package/src/rsc/handler.ts +639 -1027
  201. package/src/rsc/helpers.ts +140 -6
  202. package/src/rsc/index.ts +0 -20
  203. package/src/rsc/loader-fetch.ts +209 -0
  204. package/src/rsc/manifest-init.ts +86 -0
  205. package/src/rsc/nonce.ts +14 -0
  206. package/src/rsc/origin-guard.ts +141 -0
  207. package/src/rsc/progressive-enhancement.ts +379 -0
  208. package/src/rsc/response-error.ts +37 -0
  209. package/src/rsc/response-route-handler.ts +347 -0
  210. package/src/rsc/rsc-rendering.ts +237 -0
  211. package/src/rsc/runtime-warnings.ts +42 -0
  212. package/src/rsc/server-action.ts +348 -0
  213. package/src/rsc/ssr-setup.ts +128 -0
  214. package/src/rsc/types.ts +38 -11
  215. package/src/search-params.ts +66 -54
  216. package/src/segment-system.tsx +165 -17
  217. package/src/server/context.ts +237 -54
  218. package/src/server/cookie-store.ts +190 -0
  219. package/src/server/fetchable-loader-store.ts +11 -6
  220. package/src/server/handle-store.ts +94 -15
  221. package/src/server/loader-registry.ts +15 -56
  222. package/src/server/request-context.ts +438 -71
  223. package/src/server.ts +26 -164
  224. package/src/ssr/index.tsx +101 -31
  225. package/src/static-handler.ts +22 -4
  226. package/src/theme/ThemeProvider.tsx +21 -15
  227. package/src/theme/ThemeScript.tsx +5 -5
  228. package/src/theme/constants.ts +5 -2
  229. package/src/theme/index.ts +4 -14
  230. package/src/theme/theme-context.ts +4 -30
  231. package/src/theme/theme-script.ts +21 -18
  232. package/src/types/boundaries.ts +158 -0
  233. package/src/types/cache-types.ts +198 -0
  234. package/src/types/error-types.ts +192 -0
  235. package/src/types/global-namespace.ts +100 -0
  236. package/src/types/handler-context.ts +773 -0
  237. package/src/types/index.ts +88 -0
  238. package/src/types/loader-types.ts +183 -0
  239. package/src/types/route-config.ts +170 -0
  240. package/src/types/route-entry.ts +109 -0
  241. package/src/types/segments.ts +150 -0
  242. package/src/types.ts +1 -1795
  243. package/src/urls/include-helper.ts +197 -0
  244. package/src/urls/index.ts +53 -0
  245. package/src/urls/path-helper-types.ts +339 -0
  246. package/src/urls/path-helper.ts +329 -0
  247. package/src/urls/pattern-types.ts +95 -0
  248. package/src/urls/response-types.ts +106 -0
  249. package/src/urls/type-extraction.ts +372 -0
  250. package/src/urls/urls-function.ts +98 -0
  251. package/src/urls.ts +1 -1323
  252. package/src/use-loader.tsx +85 -77
  253. package/src/vite/discovery/bundle-postprocess.ts +184 -0
  254. package/src/vite/discovery/discover-routers.ts +344 -0
  255. package/src/vite/discovery/prerender-collection.ts +385 -0
  256. package/src/vite/discovery/route-types-writer.ts +258 -0
  257. package/src/vite/discovery/self-gen-tracking.ts +47 -0
  258. package/src/vite/discovery/state.ts +108 -0
  259. package/src/vite/discovery/virtual-module-codegen.ts +203 -0
  260. package/src/vite/index.ts +11 -2259
  261. package/src/vite/plugin-types.ts +48 -0
  262. package/src/vite/plugins/cjs-to-esm.ts +93 -0
  263. package/src/vite/plugins/client-ref-dedup.ts +115 -0
  264. package/src/vite/plugins/client-ref-hashing.ts +105 -0
  265. package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +72 -47
  266. package/src/vite/{expose-id-utils.ts → plugins/expose-id-utils.ts} +8 -43
  267. package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
  268. package/src/vite/plugins/expose-ids/handler-transform.ts +179 -0
  269. package/src/vite/plugins/expose-ids/loader-transform.ts +74 -0
  270. package/src/vite/plugins/expose-ids/router-transform.ts +110 -0
  271. package/src/vite/plugins/expose-ids/types.ts +45 -0
  272. package/src/vite/plugins/expose-internal-ids.ts +569 -0
  273. package/src/vite/plugins/refresh-cmd.ts +65 -0
  274. package/src/vite/plugins/use-cache-transform.ts +323 -0
  275. package/src/vite/plugins/version-injector.ts +83 -0
  276. package/src/vite/plugins/version-plugin.ts +266 -0
  277. package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +23 -14
  278. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  279. package/src/vite/rango.ts +445 -0
  280. package/src/vite/router-discovery.ts +777 -0
  281. package/src/vite/{ast-handler-extract.ts → utils/ast-handler-extract.ts} +181 -9
  282. package/src/vite/utils/banner.ts +36 -0
  283. package/src/vite/utils/bundle-analysis.ts +137 -0
  284. package/src/vite/utils/manifest-utils.ts +70 -0
  285. package/src/vite/{package-resolution.ts → utils/package-resolution.ts} +25 -29
  286. package/src/vite/utils/prerender-utils.ts +189 -0
  287. package/src/vite/utils/shared-utils.ts +169 -0
  288. package/CLAUDE.md +0 -43
  289. package/dist/vite/index.named-routes.gen.ts +0 -103
  290. package/src/browser/lru-cache.ts +0 -69
  291. package/src/browser/request-controller.ts +0 -164
  292. package/src/cache/memory-store.ts +0 -253
  293. package/src/href-context.ts +0 -33
  294. package/src/router.gen.ts +0 -6
  295. package/src/static-handler.gen.ts +0 -5
  296. package/src/urls.gen.ts +0 -8
  297. package/src/vite/expose-internal-ids.ts +0 -1167
  298. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
@@ -1,1167 +0,0 @@
1
- import type { Plugin, ResolvedConfig } from "vite";
2
- import { parseAst } from "vite";
3
- import MagicString from "magic-string";
4
- import path from "node:path";
5
- import { createHash } from "node:crypto";
6
- import {
7
- normalizePath,
8
- hashId,
9
- detectImports,
10
- findMatchingParen,
11
- countArgs,
12
- findStatementEnd,
13
- buildExportMap,
14
- } from "./expose-id-utils.ts";
15
- import {
16
- transformInlineHandlers,
17
- type VirtualHandlerEntry,
18
- } from "./ast-handler-extract.ts";
19
-
20
- // ---------------------------------------------------------------------------
21
- // Virtual module for loader manifest
22
- // ---------------------------------------------------------------------------
23
-
24
- const VIRTUAL_LOADER_MANIFEST = "virtual:rsc-router/loader-manifest";
25
- const RESOLVED_VIRTUAL_LOADER_MANIFEST = "\0" + VIRTUAL_LOADER_MANIFEST;
26
-
27
- // ---------------------------------------------------------------------------
28
- // Virtual module prefix for extracted inline handlers
29
- // ---------------------------------------------------------------------------
30
-
31
- const VIRTUAL_HANDLER_PREFIX = "virtual:handler-extract:";
32
-
33
- // ---------------------------------------------------------------------------
34
- // Handler transform config
35
- // ---------------------------------------------------------------------------
36
-
37
- interface HandlerTransformConfig {
38
- fnName: string;
39
- brand: string;
40
- }
41
-
42
- interface CreateExportBinding {
43
- localName: string;
44
- exportNames: string[];
45
- callExprStart: number;
46
- callOpenParenPos: number;
47
- callCloseParenPos: number;
48
- argCount: number;
49
- statementEnd: number;
50
- }
51
-
52
- interface StrictCreateTransformConfig {
53
- fnName: "createLoader" | "createHandle" | "createLocationState";
54
- }
55
-
56
- const PRERENDER_CONFIG: HandlerTransformConfig = {
57
- fnName: "Prerender",
58
- brand: "prerenderHandler",
59
- };
60
-
61
- const STATIC_CONFIG: HandlerTransformConfig = {
62
- fnName: "Static",
63
- brand: "staticHandler",
64
- };
65
-
66
- const STRICT_CREATE_CONFIGS: StrictCreateTransformConfig[] = [
67
- { fnName: "createLoader" },
68
- { fnName: "createHandle" },
69
- { fnName: "createLocationState" },
70
- ];
71
-
72
- function escapeRegExp(input: string): string {
73
- return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
74
- }
75
-
76
- /**
77
- * Check whether every non-type export in `code` is accounted for by the given
78
- * bindings. Returns false if any export exists that is not one of the known
79
- * create* call locals/exports, allowing callers to bail out for mixed-export
80
- * files.
81
- */
82
- function isExportOnlyFile(
83
- code: string,
84
- bindings: CreateExportBinding[],
85
- ): boolean {
86
- if (bindings.length === 0) return false;
87
-
88
- const knownLocals = new Set<string>();
89
- const knownExports = new Set<string>();
90
- for (const b of bindings) {
91
- knownLocals.add(b.localName);
92
- for (const e of b.exportNames) knownExports.add(e);
93
- }
94
-
95
- // Bail on star re-exports (unknown exports)
96
- if (/export\s*\*/.test(code)) return false;
97
-
98
- // Check `export const/let/var/function/class/default X` declarations
99
- const declExportPattern =
100
- /export\s+(const|let|var|function|class|default)\s+(\w+)/g;
101
- let match: RegExpExecArray | null;
102
- while ((match = declExportPattern.exec(code)) !== null) {
103
- if (!knownExports.has(match[2])) return false;
104
- }
105
-
106
- // Check `export { X }` and `export { X as Y }` specifiers: the local name
107
- // must reference a known create* binding.
108
- const specExportPattern = /export\s*\{([^}]+)\}/g;
109
- while ((match = specExportPattern.exec(code)) !== null) {
110
- const specifiers = match[1]
111
- .split(",")
112
- .map((s) => s.trim())
113
- .filter(Boolean);
114
- for (const spec of specifiers) {
115
- const m = spec.match(
116
- /^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/,
117
- );
118
- if (!m) continue;
119
- const local = m[1];
120
- if (!knownLocals.has(local)) return false;
121
- }
122
- }
123
-
124
- return true;
125
- }
126
-
127
- // NOTE: This regex may over-count when the fn name appears inside strings or
128
- // comments, but it's only used for the warning heuristic (totalCalls >
129
- // supportedBindings) and the inline-extraction pre-check, so over-counting
130
- // triggers a harmless extra AST parse rather than affecting correctness.
131
- function countCreateCallsForNames(code: string, fnNames: string[]): number {
132
- const pattern = new RegExp(
133
- `\\b(?:${fnNames.map(escapeRegExp).join("|")})\\s*(?:<[^>]*>\\s*)?\\(`,
134
- "g",
135
- );
136
- return (code.match(pattern) || []).length;
137
- }
138
-
139
- function getImportedFnNames(
140
- code: string,
141
- importedName: string,
142
- ): string[] {
143
- const importPattern =
144
- /import\s*\{([^}]*)\}\s*from\s*["']@rangojs\/router(?:\/[^"']*)?["']/g;
145
-
146
- const localNames = new Set<string>();
147
- let match: RegExpExecArray | null;
148
-
149
- while ((match = importPattern.exec(code)) !== null) {
150
- const specList = match[1]
151
- .split(",")
152
- .map((s) => s.trim())
153
- .filter(Boolean);
154
-
155
- for (const spec of specList) {
156
- const m = spec.match(/^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/);
157
- if (!m) continue;
158
- const imported = m[1];
159
- const local = m[2] || imported;
160
- if (imported === importedName) {
161
- localNames.add(local);
162
- }
163
- }
164
- }
165
-
166
- const names = Array.from(localNames);
167
- return names.length > 0 ? names : [importedName];
168
- }
169
-
170
- function getCalledIdentifierFromCall(callExpr: any): string | null {
171
- const callee = callExpr?.callee;
172
- if (callee?.type === "Identifier") return callee.name;
173
- if (
174
- callee?.type === "TSInstantiationExpression" &&
175
- callee.expression?.type === "Identifier"
176
- ) {
177
- return callee.expression.name;
178
- }
179
- return null;
180
- }
181
-
182
- function collectCreateExportBindingsFallback(
183
- code: string,
184
- fnNames: string[],
185
- ): CreateExportBinding[] {
186
- const alternation = fnNames.map(escapeRegExp).join("|");
187
- const exportConstPattern = new RegExp(
188
- `export\\s+const\\s+(\\w+)\\s*=\\s*(?:${alternation})\\s*(?:<[^>]*>)?\\s*\\(`,
189
- "g",
190
- );
191
- const localDeclPattern = new RegExp(
192
- `\\bconst\\s+(\\w+)\\s*=\\s*((?:${alternation})\\s*(?:<[^>]*>)?\\s*\\()`,
193
- "g",
194
- );
195
- const exportSpecPattern = /export\s*\{([^}]+)\}/g;
196
-
197
- const exportMap = new Map<string, string[]>();
198
- const pushExport = (local: string, exported: string) => {
199
- const list = exportMap.get(local);
200
- if (list) {
201
- if (!list.includes(exported)) list.push(exported);
202
- return;
203
- }
204
- exportMap.set(local, [exported]);
205
- };
206
-
207
- let match: RegExpExecArray | null;
208
- while ((match = exportConstPattern.exec(code)) !== null) {
209
- pushExport(match[1], match[1]);
210
- }
211
-
212
- while ((match = exportSpecPattern.exec(code)) !== null) {
213
- const specifiers = match[1]
214
- .split(",")
215
- .map((s) => s.trim())
216
- .filter(Boolean);
217
- for (const specifier of specifiers) {
218
- const specMatch = specifier.match(
219
- /^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/,
220
- );
221
- if (!specMatch) continue;
222
- const local = specMatch[1];
223
- const exported = specMatch[2] || local;
224
- pushExport(local, exported);
225
- }
226
- }
227
-
228
- const bindings: CreateExportBinding[] = [];
229
- while ((match = localDeclPattern.exec(code)) !== null) {
230
- const localName = match[1];
231
- const exportNames = exportMap.get(localName) ?? [];
232
- if (exportNames.length === 0) continue;
233
-
234
- const openParenPos = match.index + match[0].length - 1;
235
- const closeParenPos = findMatchingParen(code, openParenPos + 1) - 1;
236
- if (closeParenPos <= openParenPos) continue;
237
-
238
- bindings.push({
239
- localName,
240
- exportNames,
241
- callExprStart: match.index + match[0].length - match[2].length,
242
- callOpenParenPos: openParenPos,
243
- callCloseParenPos: closeParenPos,
244
- argCount: countArgs(code, openParenPos + 1, closeParenPos),
245
- statementEnd: findStatementEnd(code, closeParenPos + 1),
246
- });
247
- }
248
-
249
- return bindings;
250
- }
251
-
252
- function collectCreateExportBindings(
253
- code: string,
254
- fnNames: string[],
255
- program?: any,
256
- ): CreateExportBinding[] {
257
- if (!program) {
258
- try {
259
- program = parseAst(code, { jsx: true });
260
- } catch {
261
- return collectCreateExportBindingsFallback(code, fnNames);
262
- }
263
- }
264
-
265
- const exportMap = buildExportMap(program);
266
- const fnNameSet = new Set(fnNames);
267
- const bindings: CreateExportBinding[] = [];
268
-
269
- const collectFromVarDecl = (varDecl: any, statementEnd: number) => {
270
- if (varDecl?.type !== "VariableDeclaration" || varDecl.kind !== "const") {
271
- return;
272
- }
273
-
274
- for (const decl of varDecl.declarations ?? []) {
275
- const calledIdentifier = getCalledIdentifierFromCall(decl?.init);
276
- if (
277
- decl?.id?.type !== "Identifier" ||
278
- decl?.init?.type !== "CallExpression" ||
279
- !calledIdentifier ||
280
- !fnNameSet.has(calledIdentifier)
281
- ) {
282
- continue;
283
- }
284
-
285
- const localName = decl.id.name;
286
- const exportNames = exportMap.get(localName) ?? [];
287
- if (exportNames.length === 0) continue;
288
-
289
- const callStart = decl.init.start as number;
290
- const callEnd = decl.init.end as number;
291
- const calleeEnd = decl.init.callee.end as number;
292
-
293
- let openParenPos = -1;
294
- for (let i = calleeEnd; i < callEnd; i++) {
295
- if (code[i] === "(") {
296
- openParenPos = i;
297
- break;
298
- }
299
- }
300
- if (openParenPos === -1) continue;
301
-
302
- const closeParenPos = findMatchingParen(code, openParenPos + 1) - 1;
303
- if (closeParenPos <= openParenPos) continue;
304
-
305
- bindings.push({
306
- localName,
307
- exportNames,
308
- callExprStart: decl.init.start as number,
309
- callOpenParenPos: openParenPos,
310
- callCloseParenPos: closeParenPos,
311
- argCount: decl.init.arguments?.length ?? 0,
312
- statementEnd,
313
- });
314
- }
315
- };
316
-
317
- for (const node of program.body ?? []) {
318
- if (node?.type === "VariableDeclaration") {
319
- collectFromVarDecl(node, node.end as number);
320
- continue;
321
- }
322
-
323
- if (
324
- node?.type === "ExportNamedDeclaration" &&
325
- node.declaration?.type === "VariableDeclaration"
326
- ) {
327
- collectFromVarDecl(node.declaration, node.end as number);
328
- }
329
- }
330
-
331
- return bindings;
332
- }
333
-
334
- function buildUnsupportedShapeWarning(filePath: string, fnName: string): string {
335
- return [
336
- `[rsc-router] Unsupported ${fnName} shape in "${filePath}".`,
337
- `Supported shapes are:`,
338
- ` - export const X = ${fnName}(...)`,
339
- ` - const X = ${fnName}(...); export { X }`,
340
- ` - const X = ${fnName}(...); export { X as Y }`,
341
- `Potentially unsupported forms include:`,
342
- ` - export let/var X = ${fnName}(...)`,
343
- ` - inline ${fnName}(...) calls`,
344
- ].join("\n");
345
- }
346
-
347
- // ---------------------------------------------------------------------------
348
- // Plugin API type (consumed by router-discovery in index.ts)
349
- // ---------------------------------------------------------------------------
350
-
351
- export interface ExposeInternalIdsApi {
352
- /** Tracks absolute module IDs that contain prerender handler exports.
353
- * key: absolute module ID (filesystem path)
354
- * value: array of export names (e.g., ["ArticlesIndex", "ArticleDetail"]) */
355
- prerenderHandlerModules: Map<string, string[]>;
356
- /** Tracks absolute module IDs that contain static handler exports.
357
- * key: absolute module ID (filesystem path)
358
- * value: array of export names (e.g., ["DocsNav", "DocShell"]) */
359
- staticHandlerModules: Map<string, string[]>;
360
- }
361
-
362
- // ---------------------------------------------------------------------------
363
- // Loader helpers
364
- // ---------------------------------------------------------------------------
365
-
366
- function hasCreateLoaderImport(code: string): boolean {
367
- return /import\s*\{[^}]*\bcreateLoader\b[^}]*\}\s*from\s*["']@rangojs\/router(?:\/server)?["']/.test(
368
- code,
369
- );
370
- }
371
-
372
- /**
373
- * Generate lightweight client stubs for loader files.
374
- *
375
- * When a loader file is imported from a client component (e.g., for useLoader()),
376
- * the client only needs { __brand: "loader", $$id: "..." } objects.
377
- * This function replaces the entire file contents with just those stub exports,
378
- * preventing server-only data (constants, DB queries, etc.) from leaking into
379
- * the client bundle.
380
- *
381
- * Only applies when ALL named exports are createLoader() calls (plus type exports
382
- * which are erased at compile time). Files with mixed exports are left untouched.
383
- */
384
- function generateClientLoaderStubs(
385
- bindings: CreateExportBinding[],
386
- code: string,
387
- filePath: string,
388
- isBuild: boolean,
389
- ): { code: string; map?: undefined } | null {
390
- if (!isExportOnlyFile(code, bindings)) return null;
391
-
392
- const exportNames = bindings.flatMap((b) => b.exportNames);
393
- const stubs = exportNames.map((name) => {
394
- const loaderId = isBuild
395
- ? hashId(filePath, name)
396
- : `${filePath}#${name}`;
397
- return `export const ${name} = { __brand: "loader", $$id: "${loaderId}" };`;
398
- });
399
-
400
- return { code: stubs.join("\n") + "\n" };
401
- }
402
-
403
- function transformLoaders(
404
- bindings: CreateExportBinding[],
405
- s: MagicString,
406
- filePath: string,
407
- isBuild: boolean,
408
- ): boolean {
409
- let hasChanges = false;
410
- for (const binding of bindings) {
411
- const exportName = binding.exportNames[0];
412
-
413
- const loaderId = isBuild
414
- ? hashId(filePath, exportName)
415
- : `${filePath}#${exportName}`;
416
-
417
- // Inject $$id as hidden third parameter.
418
- // createLoader(fn) -> createLoader(fn, undefined, "id")
419
- // createLoader(fn, true) -> createLoader(fn, true, "id")
420
- const paramInjection =
421
- binding.argCount === 1
422
- ? `, undefined, "${loaderId}"`
423
- : `, "${loaderId}"`;
424
- s.appendLeft(binding.callCloseParenPos, paramInjection);
425
-
426
- const propInjection = `\n${binding.localName}.$$id = "${loaderId}";`;
427
- s.appendRight(binding.statementEnd, propInjection);
428
- hasChanges = true;
429
- }
430
-
431
- return hasChanges;
432
- }
433
-
434
- // ---------------------------------------------------------------------------
435
- // Handle helpers
436
- // ---------------------------------------------------------------------------
437
-
438
- function analyzeCreateHandleArgs(
439
- code: string,
440
- startPos: number,
441
- endPos: number,
442
- ): { hasArgs: boolean } {
443
- const content = code.slice(startPos, endPos).trim();
444
- return { hasArgs: content.length > 0 };
445
- }
446
-
447
- function transformHandles(
448
- bindings: CreateExportBinding[],
449
- s: MagicString,
450
- code: string,
451
- filePath: string,
452
- isBuild: boolean,
453
- ): boolean {
454
- let hasChanges = false;
455
- for (const binding of bindings) {
456
- const exportName = binding.exportNames[0];
457
- const args = analyzeCreateHandleArgs(
458
- code,
459
- binding.callOpenParenPos + 1,
460
- binding.callCloseParenPos,
461
- );
462
-
463
- const handleId = isBuild
464
- ? hashId(filePath, exportName)
465
- : `${filePath}#${exportName}`;
466
-
467
- let paramInjection: string;
468
- if (!args.hasArgs) {
469
- paramInjection = `undefined, "${handleId}"`;
470
- } else {
471
- paramInjection = `, "${handleId}"`;
472
- }
473
- s.appendLeft(binding.callCloseParenPos, paramInjection);
474
-
475
- const propInjection = `\n${binding.localName}.$$id = "${handleId}";`;
476
- s.appendRight(binding.statementEnd, propInjection);
477
- hasChanges = true;
478
- }
479
-
480
- return hasChanges;
481
- }
482
-
483
- // ---------------------------------------------------------------------------
484
- // LocationState helpers
485
- // ---------------------------------------------------------------------------
486
-
487
- function transformLocationState(
488
- bindings: CreateExportBinding[],
489
- s: MagicString,
490
- filePath: string,
491
- isBuild: boolean,
492
- ): boolean {
493
- let hasChanges = false;
494
- for (const binding of bindings) {
495
- if (binding.argCount > 0) continue; // Already has a key, skip
496
- const exportName = binding.exportNames[0];
497
-
498
- const stateKey = isBuild
499
- ? hashId(filePath, exportName)
500
- : `${filePath}#${exportName}`;
501
-
502
- s.appendLeft(binding.callCloseParenPos, `"${stateKey}"`);
503
-
504
- const propInjection =
505
- `\n${binding.localName}.__rsc_ls_key = "__rsc_ls_${stateKey}";`;
506
- s.appendRight(binding.statementEnd, propInjection);
507
- hasChanges = true;
508
- }
509
-
510
- return hasChanges;
511
- }
512
-
513
- // ---------------------------------------------------------------------------
514
- // Parameterized handler helpers (prerender + static)
515
- // ---------------------------------------------------------------------------
516
-
517
- /**
518
- * Replace the entire file with lightweight stubs when ALL non-type exports are
519
- * handler calls of the given type. Returns null for files with mixed exports.
520
- */
521
- function generateWholeFileStubs(
522
- cfg: HandlerTransformConfig,
523
- bindings: CreateExportBinding[],
524
- code: string,
525
- filePath: string,
526
- isBuild: boolean,
527
- ): { code: string; map: null } | null {
528
- if (!isExportOnlyFile(code, bindings)) return null;
529
-
530
- const exportNames = bindings.flatMap((b) => b.exportNames);
531
- const stubs = exportNames.map((name) => {
532
- const handlerId = isBuild
533
- ? hashId(filePath, name)
534
- : `${filePath}#${name}`;
535
- return `export const ${name} = { __brand: "${cfg.brand}", $$id: "${handlerId}" };`;
536
- });
537
-
538
- return { code: stubs.join("\n") + "\n", map: null };
539
- }
540
-
541
- /**
542
- * Replace handler call expressions with lightweight stub objects in non-RSC
543
- * environments. Other exports, imports, and module-level code remain untouched.
544
- */
545
- function generateExprStubs(
546
- cfg: HandlerTransformConfig,
547
- bindings: CreateExportBinding[],
548
- code: string,
549
- filePath: string,
550
- sourceId: string,
551
- isBuild: boolean,
552
- ): { code: string; map: ReturnType<MagicString["generateMap"]> } | null {
553
- if (bindings.length === 0) return null;
554
-
555
- const s = new MagicString(code);
556
- let hasChanges = false;
557
-
558
- for (const binding of bindings) {
559
- const exportName = binding.exportNames[0];
560
- const handlerId = isBuild
561
- ? hashId(filePath, exportName)
562
- : `${filePath}#${exportName}`;
563
-
564
- s.overwrite(
565
- binding.callExprStart,
566
- binding.callCloseParenPos + 1,
567
- `{ __brand: "${cfg.brand}", $$id: "${handlerId}" }`,
568
- );
569
- hasChanges = true;
570
- }
571
-
572
- if (!hasChanges) return null;
573
-
574
- return {
575
- code: s.toString(),
576
- map: s.generateMap({
577
- source: sourceId,
578
- includeContent: true,
579
- hires: "boundary",
580
- }),
581
- };
582
- }
583
-
584
- /**
585
- * Inject $$id into export const handler calls in RSC environments.
586
- */
587
- function transformHandlerIds(
588
- cfg: HandlerTransformConfig,
589
- bindings: CreateExportBinding[],
590
- s: MagicString,
591
- filePath: string,
592
- isBuild: boolean,
593
- ): boolean {
594
- let hasChanges = false;
595
- for (const binding of bindings) {
596
- const exportName = binding.exportNames[0];
597
-
598
- const handlerId = isBuild
599
- ? hashId(filePath, exportName)
600
- : `${filePath}#${exportName}`;
601
-
602
- // Injection strategy matches the runtime overload signatures:
603
- // 0 args -> inject undefined, "id"
604
- // 1 arg (handler) -> inject , undefined, "id"
605
- // 2+ args -> inject , "id"
606
- let paramInjection: string;
607
- if (binding.argCount === 0) {
608
- paramInjection = `undefined, "${handlerId}"`;
609
- } else if (binding.argCount === 1) {
610
- paramInjection = `, undefined, "${handlerId}"`;
611
- } else {
612
- paramInjection = `, "${handlerId}"`;
613
- }
614
- s.appendLeft(binding.callCloseParenPos, paramInjection);
615
-
616
- const propInjection = `\n${binding.localName}.$$id = "${handlerId}";`;
617
- s.appendRight(binding.statementEnd, propInjection);
618
- hasChanges = true;
619
- }
620
-
621
- return hasChanges;
622
- }
623
-
624
- // ---------------------------------------------------------------------------
625
- // Router helpers
626
- // ---------------------------------------------------------------------------
627
-
628
- function transformRouter(
629
- code: string,
630
- filePath: string,
631
- routerFnNames: string[],
632
- ): { code: string; map: ReturnType<MagicString["generateMap"]> } | null {
633
- const pat = new RegExp(
634
- `\\b(?:${routerFnNames.map(escapeRegExp).join("|")})\\s*(?:<[^>]*>)?\\s*\\(`,
635
- "g",
636
- );
637
- let match: RegExpExecArray | null;
638
- const s = new MagicString(code);
639
- let changed = false;
640
-
641
- // Compute the import path for the generated route names file.
642
- // filePath is relative to project root (e.g., "src/router.tsx")
643
- const basename = path.basename(filePath).replace(/\.(tsx?|jsx?)$/, "");
644
- const routeNamesImport = `./${basename}.named-routes.gen.js`;
645
- const routeNamesVar = `__rsc_rn`;
646
-
647
- while ((match = pat.exec(code)) !== null) {
648
- const callStart = match.index;
649
- const parenPos = match.index + match[0].length - 1;
650
-
651
- const afterParen = code.slice(parenPos + 1).trimStart();
652
-
653
- // Skip if $$id is already present
654
- if (afterParen.includes("$$id")) continue;
655
-
656
- // Compute line number for this call
657
- const lineNumber = code.slice(0, callStart).split("\n").length;
658
- const hash = createHash("sha256")
659
- .update(`${filePath}:${lineNumber}`)
660
- .digest("hex")
661
- .slice(0, 8);
662
-
663
- changed = true;
664
- const injected = ` $$id: "${hash}", $$routeNames: ${routeNamesVar},`;
665
-
666
- if (afterParen.startsWith("{")) {
667
- const bracePos = code.indexOf("{", parenPos + 1);
668
- s.appendRight(bracePos + 1, injected);
669
- } else if (afterParen.startsWith(")")) {
670
- s.appendRight(parenPos + 1, `{${injected} }`);
671
- }
672
- }
673
-
674
- if (!changed) return null;
675
-
676
- // Prepend the static import as the first line. MagicString tracks the
677
- // offset so all downstream source maps remain correct.
678
- s.prepend(`import { NamedRoutes as ${routeNamesVar} } from "${routeNamesImport}";\n`);
679
-
680
- return {
681
- code: s.toString(),
682
- map: s.generateMap({ hires: true }),
683
- };
684
- }
685
-
686
- // ---------------------------------------------------------------------------
687
- // Router ID plugin (separate: must run at normal priority, NOT "post")
688
- // ---------------------------------------------------------------------------
689
-
690
- /**
691
- * Inject stable $$id into createRouter() calls at compile time.
692
- * This must be a separate plugin without enforce:"post" because running
693
- * at "post" priority changes Vite's dep optimization timing and can cause
694
- * ERR_OUTDATED_OPTIMIZED_DEP / React dual-instance issues.
695
- */
696
- export function exposeRouterId(): Plugin {
697
- let projectRoot = "";
698
- return {
699
- name: "@rangojs/router:expose-router-id",
700
- configResolved(config) {
701
- projectRoot = config.root;
702
- },
703
- transform(code, id) {
704
- if (!code.includes("createRouter")) return null;
705
- if (
706
- !/import\s*\{[^}]*\bcreateRouter\b[^}]*\}\s*from\s*["']@rangojs\/router(?:\/server)?["']/.test(
707
- code,
708
- )
709
- ) {
710
- return null;
711
- }
712
- if (id.includes("node_modules")) return null;
713
-
714
- const filePath = normalizePath(path.relative(projectRoot, id));
715
- const routerFnNames = getImportedFnNames(code, "createRouter");
716
- return transformRouter(code, filePath, routerFnNames);
717
- },
718
- };
719
- }
720
-
721
- // ---------------------------------------------------------------------------
722
- // Consolidated plugin
723
- // ---------------------------------------------------------------------------
724
-
725
- export function exposeInternalIds(options?: {
726
- forceBuild?: boolean;
727
- }): Plugin {
728
- let config: ResolvedConfig;
729
- let isBuild = false;
730
- let projectRoot = "";
731
-
732
- // Loader registry: hashedId -> { filePath, exportName }
733
- const loaderRegistry = new Map<
734
- string,
735
- { filePath: string; exportName: string }
736
- >();
737
-
738
- // Prerender handler module tracking (consumed via plugin API)
739
- const prerenderHandlerModules: Map<string, string[]> = new Map();
740
-
741
- // Static handler module tracking (consumed via plugin API)
742
- const staticHandlerModules: Map<string, string[]> = new Map();
743
-
744
- // Virtual module registry for inline handler extraction (both types)
745
- const virtualHandlers = new Map<string, VirtualHandlerEntry>();
746
- // De-duplicate unsupported shape warnings across repeated transforms.
747
- const unsupportedShapeWarnings = new Set<string>();
748
-
749
- return {
750
- name: "@rangojs/router:expose-internal-ids",
751
- enforce: "post",
752
-
753
- api: {
754
- prerenderHandlerModules,
755
- staticHandlerModules,
756
- } satisfies ExposeInternalIdsApi,
757
-
758
- configResolved(resolved) {
759
- config = resolved;
760
- isBuild = options?.forceBuild || config.command === "build";
761
- projectRoot = config.root;
762
- },
763
-
764
- // --------------- Virtual module support ---------------
765
-
766
- resolveId(id, importer) {
767
- if (id === VIRTUAL_LOADER_MANIFEST) {
768
- return RESOLVED_VIRTUAL_LOADER_MANIFEST;
769
- }
770
- if (id.startsWith(VIRTUAL_HANDLER_PREFIX)) {
771
- return "\0" + id;
772
- }
773
- // Resolve imports FROM virtual modules against the original file
774
- if (importer?.startsWith("\0" + VIRTUAL_HANDLER_PREFIX)) {
775
- const entry = virtualHandlers.get(importer);
776
- if (entry) {
777
- return this.resolve(id, entry.originalModuleId, { skipSelf: true });
778
- }
779
- }
780
- },
781
-
782
- load(id) {
783
- // Virtual handler modules (both prerender and static)
784
- if (id.startsWith("\0" + VIRTUAL_HANDLER_PREFIX)) {
785
- const entry = virtualHandlers.get(id);
786
- if (!entry) return null;
787
- return [
788
- ...entry.imports,
789
- `export const ${entry.exportName} = ${entry.handlerCode};`,
790
- ].join("\n") + "\n";
791
- }
792
-
793
- if (id !== RESOLVED_VIRTUAL_LOADER_MANIFEST) return;
794
-
795
- if (!isBuild) {
796
- return `import { setLoaderImports } from "@rangojs/router/server";
797
-
798
- // Dev mode: empty map, loaders are resolved dynamically via path parsing
799
- setLoaderImports({});
800
- `;
801
- }
802
-
803
- // Build mode: generate lazy import map
804
- const lazyImports: string[] = [];
805
-
806
- for (const [hashedId, { filePath, exportName }] of loaderRegistry) {
807
- lazyImports.push(
808
- ` "${hashedId}": () => import("/${filePath}").then(m => m.${exportName})`,
809
- );
810
- }
811
-
812
- if (lazyImports.length === 0) {
813
- return `import { setLoaderImports } from "@rangojs/router/server";
814
-
815
- // No fetchable loaders discovered during build
816
- setLoaderImports({});
817
- `;
818
- }
819
-
820
- return `import { setLoaderImports } from "@rangojs/router/server";
821
-
822
- // Lazy import map - loaders are loaded on-demand when first requested
823
- setLoaderImports({
824
- ${lazyImports.join(",\n")}
825
- });
826
- `;
827
- },
828
-
829
- // --------------- Loader pre-scan (build mode) ---------------
830
-
831
- async buildStart() {
832
- if (!isBuild) return;
833
-
834
- const fs = await import("node:fs/promises");
835
-
836
- async function scanDir(dir: string): Promise<string[]> {
837
- const results: string[] = [];
838
- try {
839
- const entries = await fs.readdir(dir, { withFileTypes: true });
840
- for (const entry of entries) {
841
- const fullPath = path.join(dir, entry.name);
842
- if (entry.isDirectory()) {
843
- if (entry.name !== "node_modules") {
844
- results.push(...(await scanDir(fullPath)));
845
- }
846
- } else if (/\.(ts|tsx|js|jsx)$/.test(entry.name)) {
847
- results.push(fullPath);
848
- }
849
- }
850
- } catch {
851
- // Directory doesn't exist or not readable
852
- }
853
- return results;
854
- }
855
-
856
- try {
857
- const srcDir = path.join(projectRoot, "src");
858
- const files = await scanDir(srcDir);
859
-
860
- for (const filePath of files) {
861
- const content = await fs.readFile(filePath, "utf-8");
862
-
863
- if (!content.includes("createLoader")) continue;
864
- if (!hasCreateLoaderImport(content)) continue;
865
-
866
- const fnNames = getImportedFnNames(content, "createLoader");
867
- const relativePath = normalizePath(
868
- path.relative(projectRoot, filePath),
869
- );
870
- const bindings = collectCreateExportBindings(content, fnNames);
871
-
872
- for (const binding of bindings) {
873
- const exportName = binding.exportNames[0];
874
- const hashedId = hashId(relativePath, exportName);
875
- loaderRegistry.set(hashedId, {
876
- filePath: relativePath,
877
- exportName,
878
- });
879
- }
880
- }
881
- } catch (error) {
882
- console.warn("[exposeInternalIds] Loader pre-scan failed:", error);
883
- }
884
- },
885
-
886
- // --------------- Unified transform ---------------
887
-
888
- transform(code, id) {
889
- if (id.includes("/node_modules/")) return;
890
-
891
- const filePath = normalizePath(path.relative(projectRoot, id));
892
- const isRscEnv = this.environment?.name === "rsc";
893
-
894
- // Warn if named-routes.gen is imported in a client component.
895
- // NamedRoutes is server-only data and would bloat the client bundle.
896
- if (id.includes(".named-routes.gen.") && !isRscEnv && this.environment?.name === "client") {
897
- this.warn(
898
- `\n` +
899
- `!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n` +
900
- `!! !!\n` +
901
- `!! WARNING: NamedRoutes imported in a CLIENT component! !!\n` +
902
- `!! !!\n` +
903
- `!! File: ${filePath.padEnd(53)}!!\n` +
904
- `!! !!\n` +
905
- `!! NamedRoutes contains your entire route structure — every !!\n` +
906
- `!! route name and URL pattern in your application. Shipping !!\n` +
907
- `!! this to the browser exposes your full routing topology to !!\n` +
908
- `!! the client, which is a security concern (internal/admin !!\n` +
909
- `!! routes, API endpoints, hidden paths become visible). !!\n` +
910
- `!! !!\n` +
911
- `!! It also bloats the client bundle — this map contains all !!\n` +
912
- `!! named routes in your application. !!\n` +
913
- `!! !!\n` +
914
- `!! Fix: remove the import or move it to a server component. !!\n` +
915
- `!! !!\n` +
916
- `!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n`
917
- );
918
- }
919
-
920
- // Fast exit: if the file doesn't import from @rangojs/router at all,
921
- // skip all create* analysis and transforms.
922
- if (!code.includes("@rangojs/router")) return;
923
-
924
- // Detect all relevant imports in one pass
925
- const has = detectImports(code);
926
-
927
- // Quick bail-out: also check for raw create* identifiers.
928
- // This is safe even with aliases (e.g., `import { createLoader as cl }`)
929
- // because the import statement itself always contains the canonical name
930
- // "createLoader", so code.includes("createLoader") will still match.
931
- const hasLoaderCode = has.loader && code.includes("createLoader");
932
- const hasHandleCode = has.handle && code.includes("createHandle");
933
- const hasLocationStateCode =
934
- has.locationState && code.includes("createLocationState");
935
- const hasPrerenderHandlerCode =
936
- has.prerenderHandler && code.includes("Prerender");
937
- const hasStaticHandlerCode =
938
- has.staticHandler && code.includes("Static");
939
- if (
940
- !hasLoaderCode &&
941
- !hasHandleCode &&
942
- !hasLocationStateCode &&
943
- !hasPrerenderHandlerCode &&
944
- !hasStaticHandlerCode
945
- ) {
946
- return;
947
- }
948
-
949
- // Per-invocation caches to avoid redundant AST parsing.
950
- // getImportedFnNames is cached by canonical name (imports never change).
951
- // collectCreateExportBindings is cached by fnNames key; the cache is
952
- // cleared when `code` changes (e.g., after inline handler extraction).
953
- const _fnNamesCache = new Map<string, string[]>();
954
- const _bindingsCache = new Map<string, CreateExportBinding[]>();
955
- let _cachedAst: any;
956
- let _astParseFailed = false;
957
- let _astCodeRef = code;
958
-
959
- const getFnNames = (canonicalName: string): string[] => {
960
- let result = _fnNamesCache.get(canonicalName);
961
- if (!result) {
962
- result = getImportedFnNames(code, canonicalName);
963
- _fnNamesCache.set(canonicalName, result);
964
- }
965
- return result;
966
- };
967
-
968
- // Lazy AST parse: parsed once and shared across all
969
- // collectCreateExportBindings calls for the same code string.
970
- const lazyAst = (): any | undefined => {
971
- if (code !== _astCodeRef) {
972
- _cachedAst = undefined;
973
- _astParseFailed = false;
974
- _astCodeRef = code;
975
- }
976
- if (_cachedAst !== undefined || _astParseFailed) return _cachedAst;
977
- try {
978
- _cachedAst = parseAst(code, { jsx: true });
979
- } catch {
980
- _astParseFailed = true;
981
- }
982
- return _cachedAst;
983
- };
984
-
985
- const getBindings = (currentCode: string, fnNames: string[]): CreateExportBinding[] => {
986
- const key = fnNames.join("\0");
987
- let result = _bindingsCache.get(key);
988
- if (!result) {
989
- result = collectCreateExportBindings(currentCode, fnNames, lazyAst());
990
- _bindingsCache.set(key, result);
991
- }
992
- return result;
993
- };
994
-
995
- // Warn on create* declaration shapes that are currently unsupported by
996
- // non-AST transforms (loader/handle/locationState only).
997
- for (const cfg of STRICT_CREATE_CONFIGS) {
998
- const hasCode =
999
- cfg.fnName === "createLoader"
1000
- ? hasLoaderCode
1001
- : cfg.fnName === "createHandle"
1002
- ? hasHandleCode
1003
- : hasLocationStateCode;
1004
- if (!hasCode) continue;
1005
-
1006
- const fnNames = getFnNames(cfg.fnName);
1007
- const totalCalls = countCreateCallsForNames(code, fnNames);
1008
- const supportedBindings = getBindings(code, fnNames).length;
1009
- if (totalCalls <= supportedBindings) continue;
1010
-
1011
- const warnKey = `${id}::${cfg.fnName}`;
1012
- if (unsupportedShapeWarnings.has(warnKey)) continue;
1013
- unsupportedShapeWarnings.add(warnKey);
1014
- this.warn(buildUnsupportedShapeWarning(filePath, cfg.fnName));
1015
- }
1016
-
1017
- // --- Loader: track for manifest (RSC env only) ---
1018
- if (hasLoaderCode && isRscEnv) {
1019
- const fnNames = getFnNames("createLoader");
1020
- const bindings = getBindings(code, fnNames);
1021
- for (const binding of bindings) {
1022
- const exportName = binding.exportNames[0];
1023
- const hashedId = hashId(filePath, exportName);
1024
- loaderRegistry.set(hashedId, {
1025
- filePath,
1026
- exportName,
1027
- });
1028
- }
1029
- }
1030
-
1031
- // --- Loader: client stubs for non-RSC environments ---
1032
- if (hasLoaderCode && !isRscEnv) {
1033
- const fnNames = getFnNames("createLoader");
1034
- const bindings = getBindings(code, fnNames);
1035
- const stubResult = generateClientLoaderStubs(bindings, code, filePath, isBuild);
1036
- if (stubResult) return stubResult;
1037
- }
1038
-
1039
- // --- PrerenderHandler: non-RSC stub replacement ---
1040
- if (hasPrerenderHandlerCode && !isRscEnv) {
1041
- const fnNames = getFnNames(PRERENDER_CONFIG.fnName);
1042
- const bindings = getBindings(code, fnNames);
1043
- const wholeFile = generateWholeFileStubs(
1044
- PRERENDER_CONFIG, bindings, code, filePath, isBuild,
1045
- );
1046
- if (wholeFile) return wholeFile;
1047
-
1048
- const exprStubs = generateExprStubs(
1049
- PRERENDER_CONFIG, bindings, code, filePath, id, isBuild,
1050
- );
1051
- if (exprStubs) return exprStubs;
1052
- }
1053
-
1054
- // --- PrerenderHandler: RSC build module tracking ---
1055
- if (hasPrerenderHandlerCode && isRscEnv && isBuild) {
1056
- const fnNames = getFnNames(PRERENDER_CONFIG.fnName);
1057
- const exportNames = getBindings(code, fnNames)
1058
- .map((b) => b.exportNames[0]);
1059
- if (exportNames.length > 0) {
1060
- prerenderHandlerModules.set(id, exportNames);
1061
- }
1062
- }
1063
-
1064
- // --- Inline handler extraction to virtual modules ---
1065
- // Runs before stubs/tracking so inline calls become imports, then
1066
- // the existing regex fast path handles both the original file's
1067
- // export const patterns and the virtual modules independently.
1068
- //
1069
- // Cheap pre-check: count total fnName( occurrences vs export const
1070
- // patterns. If they match, every call is a named export and the
1071
- // regex fast path handles them -- skip the AST parse entirely.
1072
- //
1073
- // Each iteration creates a fresh MagicString so that AST positions
1074
- // from findHandlerCalls always match the string they were parsed from.
1075
- let changed = false;
1076
-
1077
- const handlerConfigs = [
1078
- hasStaticHandlerCode && STATIC_CONFIG,
1079
- hasPrerenderHandlerCode && PRERENDER_CONFIG,
1080
- ].filter((c): c is HandlerTransformConfig => !!c).map((cfg) => {
1081
- const fnNames = getFnNames(cfg.fnName);
1082
- return { cfg, fnNames };
1083
- });
1084
-
1085
- for (const { cfg, fnNames } of handlerConfigs) {
1086
- const totalCalls = countCreateCallsForNames(code, fnNames);
1087
- const supportedBindings = getBindings(code, fnNames).length;
1088
-
1089
- if (totalCalls > supportedBindings) {
1090
- const iterS = new MagicString(code);
1091
- const result = transformInlineHandlers(
1092
- cfg.fnName, VIRTUAL_HANDLER_PREFIX,
1093
- iterS, code, filePath,
1094
- virtualHandlers, id, parseAst,
1095
- );
1096
- if (result) {
1097
- changed = true;
1098
- code = iterS.toString();
1099
- _bindingsCache.clear();
1100
- }
1101
- }
1102
- }
1103
-
1104
- // --- StaticHandler: non-RSC stub replacement ---
1105
- if (hasStaticHandlerCode && !isRscEnv) {
1106
- const fnNames = getFnNames(STATIC_CONFIG.fnName);
1107
- const bindings = getBindings(code, fnNames);
1108
- const wholeFile = generateWholeFileStubs(
1109
- STATIC_CONFIG, bindings, code, filePath, isBuild,
1110
- );
1111
- if (wholeFile) return wholeFile;
1112
-
1113
- const exprStubs = generateExprStubs(
1114
- STATIC_CONFIG, bindings, code, filePath, id, isBuild,
1115
- );
1116
- if (exprStubs) return exprStubs;
1117
- }
1118
-
1119
- // --- StaticHandler: RSC build module tracking ---
1120
- if (hasStaticHandlerCode && isRscEnv && isBuild) {
1121
- const fnNames = getFnNames(STATIC_CONFIG.fnName);
1122
- const exportNames = getBindings(code, fnNames)
1123
- .map((b) => b.exportNames[0]);
1124
- if (exportNames.length > 0) {
1125
- staticHandlerModules.set(id, exportNames);
1126
- }
1127
- }
1128
-
1129
- // --- Unified MagicString transforms ---
1130
- // Single pipeline for all downstream transforms (loaders, handles,
1131
- // locationState, handler IDs). Uses the post-extraction code so
1132
- // positions are always consistent.
1133
- const s = new MagicString(code);
1134
-
1135
- if (hasLoaderCode) {
1136
- const fnNames = getFnNames("createLoader");
1137
- changed = transformLoaders(getBindings(code, fnNames), s, filePath, isBuild) || changed;
1138
- }
1139
- if (hasHandleCode) {
1140
- const fnNames = getFnNames("createHandle");
1141
- changed = transformHandles(getBindings(code, fnNames), s, code, filePath, isBuild) || changed;
1142
- }
1143
- if (hasLocationStateCode) {
1144
- const fnNames = getFnNames("createLocationState");
1145
- changed =
1146
- transformLocationState(getBindings(code, fnNames), s, filePath, isBuild) || changed;
1147
- }
1148
- if (hasPrerenderHandlerCode && isRscEnv) {
1149
- const fnNames = getFnNames(PRERENDER_CONFIG.fnName);
1150
- changed =
1151
- transformHandlerIds(PRERENDER_CONFIG, getBindings(code, fnNames), s, filePath, isBuild) || changed;
1152
- }
1153
- if (hasStaticHandlerCode && isRscEnv) {
1154
- const fnNames = getFnNames(STATIC_CONFIG.fnName);
1155
- changed =
1156
- transformHandlerIds(STATIC_CONFIG, getBindings(code, fnNames), s, filePath, isBuild) || changed;
1157
- }
1158
-
1159
- if (!changed) return;
1160
-
1161
- return {
1162
- code: s.toString(),
1163
- map: s.generateMap({ source: id, includeContent: true }),
1164
- };
1165
- },
1166
- };
1167
- }