@rangojs/router 0.0.0-experimental.77 → 0.0.0-experimental.77ed8945

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 (239) hide show
  1. package/README.md +120 -25
  2. package/dist/bin/rango.js +147 -57
  3. package/dist/vite/index.js +2103 -861
  4. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  5. package/package.json +13 -8
  6. package/skills/api-client/SKILL.md +211 -0
  7. package/skills/breadcrumbs/SKILL.md +3 -1
  8. package/skills/bundle-analysis/SKILL.md +159 -0
  9. package/skills/cache-guide/SKILL.md +220 -30
  10. package/skills/caching/SKILL.md +116 -8
  11. package/skills/composability/SKILL.md +27 -2
  12. package/skills/css/SKILL.md +76 -0
  13. package/skills/document-cache/SKILL.md +78 -55
  14. package/skills/handler-use/SKILL.md +3 -1
  15. package/skills/hooks/SKILL.md +229 -20
  16. package/skills/host-router/SKILL.md +66 -20
  17. package/skills/i18n/SKILL.md +276 -0
  18. package/skills/intercept/SKILL.md +26 -4
  19. package/skills/layout/SKILL.md +6 -7
  20. package/skills/links/SKILL.md +247 -17
  21. package/skills/loader/SKILL.md +219 -9
  22. package/skills/middleware/SKILL.md +47 -12
  23. package/skills/migrate-nextjs/SKILL.md +562 -0
  24. package/skills/migrate-react-router/SKILL.md +769 -0
  25. package/skills/mime-routes/SKILL.md +27 -0
  26. package/skills/observability/SKILL.md +137 -0
  27. package/skills/parallel/SKILL.md +12 -6
  28. package/skills/prerender/SKILL.md +14 -33
  29. package/skills/rango/SKILL.md +238 -22
  30. package/skills/react-compiler/SKILL.md +168 -0
  31. package/skills/response-routes/SKILL.md +122 -47
  32. package/skills/route/SKILL.md +33 -4
  33. package/skills/router-setup/SKILL.md +3 -3
  34. package/skills/server-actions/SKILL.md +751 -0
  35. package/skills/streams-and-websockets/SKILL.md +283 -0
  36. package/skills/tailwind/SKILL.md +27 -3
  37. package/skills/typesafety/SKILL.md +319 -27
  38. package/skills/use-cache/SKILL.md +34 -5
  39. package/skills/view-transitions/SKILL.md +294 -0
  40. package/src/__augment-tests__/augment.ts +81 -0
  41. package/src/__augment-tests__/augmented.check.ts +116 -0
  42. package/src/browser/action-coordinator.ts +53 -36
  43. package/src/browser/app-shell.ts +39 -0
  44. package/src/browser/event-controller.ts +86 -70
  45. package/src/browser/history-state.ts +21 -0
  46. package/src/browser/index.ts +3 -3
  47. package/src/browser/navigation-bridge.ts +29 -9
  48. package/src/browser/navigation-client.ts +99 -77
  49. package/src/browser/navigation-store.ts +7 -8
  50. package/src/browser/navigation-transaction.ts +10 -28
  51. package/src/browser/partial-update.ts +60 -40
  52. package/src/browser/prefetch/cache.ts +196 -49
  53. package/src/browser/prefetch/fetch.ts +203 -59
  54. package/src/browser/prefetch/queue.ts +36 -5
  55. package/src/browser/rango-state.ts +37 -13
  56. package/src/browser/react/Link.tsx +18 -13
  57. package/src/browser/react/NavigationProvider.tsx +75 -31
  58. package/src/browser/react/filter-segment-order.ts +51 -7
  59. package/src/browser/react/index.ts +3 -0
  60. package/src/browser/react/location-state-shared.ts +175 -4
  61. package/src/browser/react/location-state.ts +39 -13
  62. package/src/browser/react/use-handle.ts +17 -9
  63. package/src/browser/react/use-navigation.ts +22 -2
  64. package/src/browser/react/use-params.ts +20 -8
  65. package/src/browser/react/use-reverse.ts +106 -0
  66. package/src/browser/react/use-router.ts +23 -2
  67. package/src/browser/react/use-segments.ts +11 -8
  68. package/src/browser/response-adapter.ts +52 -1
  69. package/src/browser/rsc-router.tsx +71 -22
  70. package/src/browser/scroll-restoration.ts +22 -14
  71. package/src/browser/segment-reconciler.ts +10 -14
  72. package/src/browser/segment-structure-assert.ts +2 -2
  73. package/src/browser/server-action-bridge.ts +44 -30
  74. package/src/browser/types.ts +12 -2
  75. package/src/build/collect-fallback-refs.ts +107 -0
  76. package/src/build/generate-manifest.ts +60 -35
  77. package/src/build/generate-route-types.ts +2 -0
  78. package/src/build/index.ts +8 -1
  79. package/src/build/prefix-tree-utils.ts +123 -0
  80. package/src/build/route-trie.ts +45 -1
  81. package/src/build/route-types/codegen.ts +4 -4
  82. package/src/build/route-types/include-resolution.ts +1 -1
  83. package/src/build/route-types/per-module-writer.ts +7 -4
  84. package/src/build/route-types/router-processing.ts +55 -14
  85. package/src/build/route-types/scan-filter.ts +1 -1
  86. package/src/build/route-types/source-scan.ts +118 -0
  87. package/src/build/runtime-discovery.ts +9 -20
  88. package/src/cache/cache-runtime.ts +17 -5
  89. package/src/cache/cache-scope.ts +51 -49
  90. package/src/cache/cf/cf-cache-store.ts +502 -32
  91. package/src/cache/cf/index.ts +3 -0
  92. package/src/cache/handle-snapshot.ts +103 -0
  93. package/src/cache/index.ts +3 -0
  94. package/src/cache/memory-segment-store.ts +3 -2
  95. package/src/cache/types.ts +10 -6
  96. package/src/client.rsc.tsx +3 -0
  97. package/src/client.tsx +96 -205
  98. package/src/context-var.ts +5 -5
  99. package/src/decode-loader-results.ts +36 -0
  100. package/src/errors.ts +30 -4
  101. package/src/handle.ts +4 -6
  102. package/src/host/index.ts +2 -2
  103. package/src/host/router.ts +129 -57
  104. package/src/host/types.ts +31 -2
  105. package/src/host/utils.ts +1 -1
  106. package/src/href-client.ts +140 -21
  107. package/src/index.rsc.ts +10 -6
  108. package/src/index.ts +17 -8
  109. package/src/loader-store.ts +500 -0
  110. package/src/loader.rsc.ts +2 -5
  111. package/src/loader.ts +3 -10
  112. package/src/missing-id-error.ts +68 -0
  113. package/src/outlet-context.ts +1 -1
  114. package/src/prerender/store.ts +9 -7
  115. package/src/prerender.ts +4 -4
  116. package/src/response-utils.ts +37 -0
  117. package/src/reverse.ts +65 -39
  118. package/src/route-content-wrapper.tsx +6 -28
  119. package/src/route-definition/dsl-helpers.ts +253 -265
  120. package/src/route-definition/helper-factories.ts +29 -139
  121. package/src/route-definition/helpers-types.ts +43 -15
  122. package/src/route-definition/resolve-handler-use.ts +6 -0
  123. package/src/route-definition/use-item-types.ts +32 -0
  124. package/src/route-types.ts +26 -41
  125. package/src/router/content-negotiation.ts +15 -2
  126. package/src/router/error-handling.ts +1 -1
  127. package/src/router/find-match.ts +54 -6
  128. package/src/router/handler-context.ts +21 -41
  129. package/src/router/intercept-resolution.ts +4 -18
  130. package/src/router/lazy-includes.ts +41 -22
  131. package/src/router/loader-resolution.ts +82 -36
  132. package/src/router/manifest.ts +41 -19
  133. package/src/router/match-api.ts +4 -3
  134. package/src/router/match-handlers.ts +1 -0
  135. package/src/router/match-middleware/cache-lookup.ts +57 -95
  136. package/src/router/match-middleware/cache-store.ts +3 -2
  137. package/src/router/match-result.ts +53 -32
  138. package/src/router/metrics.ts +1 -1
  139. package/src/router/middleware-types.ts +15 -26
  140. package/src/router/middleware.ts +99 -84
  141. package/src/router/pattern-matching.ts +116 -19
  142. package/src/router/prerender-match.ts +40 -15
  143. package/src/router/preview-match.ts +3 -1
  144. package/src/router/request-classification.ts +40 -37
  145. package/src/router/revalidation.ts +58 -2
  146. package/src/router/router-interfaces.ts +51 -35
  147. package/src/router/router-options.ts +25 -1
  148. package/src/router/router-registry.ts +2 -5
  149. package/src/router/segment-resolution/fresh.ts +27 -6
  150. package/src/router/segment-resolution/revalidation.ts +147 -106
  151. package/src/router/segment-resolution/static-store.ts +19 -5
  152. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  153. package/src/router/substitute-pattern-params.ts +56 -0
  154. package/src/router/trie-matching.ts +40 -16
  155. package/src/router/types.ts +8 -0
  156. package/src/router/url-params.ts +49 -0
  157. package/src/router.ts +37 -25
  158. package/src/rsc/handler-context.ts +2 -2
  159. package/src/rsc/handler.ts +58 -77
  160. package/src/rsc/helpers.ts +72 -43
  161. package/src/rsc/index.ts +1 -1
  162. package/src/rsc/manifest-init.ts +28 -41
  163. package/src/rsc/origin-guard.ts +30 -10
  164. package/src/rsc/progressive-enhancement.ts +4 -0
  165. package/src/rsc/response-error.ts +79 -12
  166. package/src/rsc/response-route-handler.ts +76 -61
  167. package/src/rsc/rsc-rendering.ts +45 -51
  168. package/src/rsc/runtime-warnings.ts +9 -10
  169. package/src/rsc/server-action.ts +33 -39
  170. package/src/rsc/ssr-setup.ts +16 -0
  171. package/src/rsc/types.ts +8 -2
  172. package/src/search-params.ts +4 -4
  173. package/src/segment-content-promise.ts +67 -0
  174. package/src/segment-loader-promise.ts +122 -0
  175. package/src/segment-system.tsx +132 -116
  176. package/src/serialize.ts +243 -0
  177. package/src/server/context.ts +175 -53
  178. package/src/server/cookie-store.ts +28 -4
  179. package/src/server/request-context.ts +57 -51
  180. package/src/ssr/index.tsx +5 -1
  181. package/src/static-handler.ts +1 -1
  182. package/src/types/global-namespace.ts +39 -26
  183. package/src/types/handler-context.ts +68 -50
  184. package/src/types/index.ts +1 -0
  185. package/src/types/loader-types.ts +11 -9
  186. package/src/types/request-scope.ts +126 -0
  187. package/src/types/route-entry.ts +11 -0
  188. package/src/types/segments.ts +35 -2
  189. package/src/urls/include-helper.ts +34 -67
  190. package/src/urls/index.ts +1 -5
  191. package/src/urls/path-helper-types.ts +17 -3
  192. package/src/urls/path-helper.ts +17 -52
  193. package/src/urls/pattern-types.ts +36 -19
  194. package/src/urls/response-types.ts +22 -29
  195. package/src/urls/type-extraction.ts +58 -139
  196. package/src/urls/urls-function.ts +1 -5
  197. package/src/use-loader.tsx +413 -42
  198. package/src/vite/debug.ts +185 -0
  199. package/src/vite/discovery/bundle-postprocess.ts +6 -6
  200. package/src/vite/discovery/discover-routers.ts +106 -75
  201. package/src/vite/discovery/discovery-errors.ts +194 -0
  202. package/src/vite/discovery/gate-state.ts +171 -0
  203. package/src/vite/discovery/prerender-collection.ts +72 -31
  204. package/src/vite/discovery/route-types-writer.ts +40 -84
  205. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  206. package/src/vite/discovery/state.ts +33 -0
  207. package/src/vite/discovery/virtual-module-codegen.ts +13 -23
  208. package/src/vite/index.ts +2 -0
  209. package/src/vite/plugin-types.ts +67 -0
  210. package/src/vite/plugins/cjs-to-esm.ts +8 -7
  211. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  212. package/src/vite/plugins/client-ref-hashing.ts +28 -5
  213. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  214. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  215. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  216. package/src/vite/plugins/expose-action-id.ts +54 -30
  217. package/src/vite/plugins/expose-id-utils.ts +12 -8
  218. package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
  219. package/src/vite/plugins/expose-ids/handler-transform.ts +8 -61
  220. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  221. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  222. package/src/vite/plugins/expose-internal-ids.ts +496 -486
  223. package/src/vite/plugins/performance-tracks.ts +29 -25
  224. package/src/vite/plugins/use-cache-transform.ts +65 -50
  225. package/src/vite/plugins/version-injector.ts +39 -23
  226. package/src/vite/plugins/version-plugin.ts +59 -2
  227. package/src/vite/plugins/virtual-entries.ts +2 -2
  228. package/src/vite/rango.ts +116 -29
  229. package/src/vite/router-discovery.ts +753 -104
  230. package/src/vite/utils/ast-handler-extract.ts +15 -15
  231. package/src/vite/utils/banner.ts +1 -1
  232. package/src/vite/utils/bundle-analysis.ts +4 -2
  233. package/src/vite/utils/client-chunks.ts +190 -0
  234. package/src/vite/utils/forward-user-plugins.ts +193 -0
  235. package/src/vite/utils/manifest-utils.ts +8 -59
  236. package/src/vite/utils/package-resolution.ts +41 -1
  237. package/src/vite/utils/prerender-utils.ts +5 -4
  238. package/src/vite/utils/shared-utils.ts +107 -26
  239. package/src/browser/action-response-classifier.ts +0 -99
@@ -10,6 +10,8 @@ import {
10
10
  parsePattern,
11
11
  type ParsedSegment,
12
12
  } from "../router/pattern-matching.js";
13
+ import { buildRouteToStaticPrefix } from "./prefix-tree-utils.js";
14
+ import type { FullManifest } from "./generate-manifest.js";
13
15
 
14
16
  // -- Trie data structures (compact keys for JSON serialization) --
15
17
 
@@ -20,7 +22,8 @@ export interface TrieLeaf {
20
22
  sp: string;
21
23
  /** Ancestry shortCodes from root to route [M0L0, M0L0L0, M0L0L0R499] */
22
24
  a: string[];
23
- /** Optional param names (absent params get empty string value) */
25
+ /** Optional param names declared on the route. Absent params are
26
+ * omitted from the matched params record (read as `undefined`). */
24
27
  op?: string[];
25
28
  /** Constraint validation: paramName -> allowed values */
26
29
  cv?: Record<string, string[]>;
@@ -97,6 +100,47 @@ export function buildRouteTrie(
97
100
  return root;
98
101
  }
99
102
 
103
+ /**
104
+ * Build a per-router trie from a generated manifest. This is the single
105
+ * construction path shared by build/discovery (discover-routers.ts, serialized
106
+ * into the production chunk) and the dev/HMR runtime rebuild
107
+ * (rsc/manifest-init.ts). Keeping one code path is what guarantees the dev
108
+ * runtime trie and the production serialized trie are byte-for-byte identical
109
+ * (modulo `leaf.a` ancestry, which embeds the mount index and is debug-only).
110
+ *
111
+ * Returns null when the manifest has no route ancestry (no routes), matching
112
+ * the prior guard at both call sites.
113
+ */
114
+ export function buildPerRouterTrie(manifest: FullManifest): TrieNode | null {
115
+ const ancestry = manifest._routeAncestry;
116
+ if (!ancestry || Object.keys(ancestry).length === 0) {
117
+ return null;
118
+ }
119
+
120
+ // Seed every route to the root static prefix (""), then override with each
121
+ // route's include() scope prefix from the prefix tree so the trie returns the
122
+ // correct `sp` for lazy-entry lookup in find-match.
123
+ const routeToStaticPrefix: Record<string, string> = {};
124
+ for (const name of Object.keys(manifest.routeManifest)) {
125
+ routeToStaticPrefix[name] = "";
126
+ }
127
+ if (manifest.prefixTree) {
128
+ buildRouteToStaticPrefix(manifest.prefixTree, routeToStaticPrefix);
129
+ }
130
+
131
+ return buildRouteTrie(
132
+ manifest.routeManifest,
133
+ ancestry,
134
+ routeToStaticPrefix,
135
+ manifest.routeTrailingSlash,
136
+ manifest.prerenderRoutes ? new Set(manifest.prerenderRoutes) : undefined,
137
+ manifest.passthroughRoutes
138
+ ? new Set(manifest.passthroughRoutes)
139
+ : undefined,
140
+ manifest.responseTypeRoutes,
141
+ );
142
+ }
143
+
100
144
  /**
101
145
  * Insert a route into the trie. Optional params expand into two branches at
102
146
  * registration time (skip-first, then present), so each terminal lives at the
@@ -23,7 +23,7 @@ export function generatePerModuleTypesSource(
23
23
  const valid = routes.filter(({ name }) => {
24
24
  if (!name || /["'\\`\n\r]/.test(name)) {
25
25
  console.warn(
26
- `[rsc-router] Skipping route with invalid name: ${JSON.stringify(name)}`,
26
+ `[rango] Skipping route with invalid name: ${JSON.stringify(name)}`,
27
27
  );
28
28
  return false;
29
29
  }
@@ -42,7 +42,7 @@ export function generatePerModuleTypesSource(
42
42
  for (const { name, pattern, params, search } of valid) {
43
43
  if (deduped.has(name)) {
44
44
  console.warn(
45
- `[rsc-router] Duplicate route name "${name}" — keeping first definition`,
45
+ `[rango] Duplicate route name "${name}" — keeping first definition`,
46
46
  );
47
47
  continue;
48
48
  }
@@ -59,7 +59,7 @@ export function generatePerModuleTypesSource(
59
59
  }
60
60
 
61
61
  /**
62
- * Generates a .ts file that augments RSCRouter.GeneratedRouteMap
62
+ * Generates a .ts file that augments Rango.GeneratedRouteMap
63
63
  * with route name -> pattern mappings. This enables Handler<"routeName">
64
64
  * without circular references since the file has no imports from the app.
65
65
  */
@@ -94,7 +94,7 @@ ${objectBody}
94
94
  } as const;
95
95
 
96
96
  declare global {
97
- namespace RSCRouter {
97
+ namespace Rango {
98
98
  interface GeneratedRouteMap extends Readonly<typeof NamedRoutes> {}
99
99
  }
100
100
  }
@@ -376,7 +376,7 @@ export function buildCombinedRouteMapWithSearch(
376
376
  const realPath = resolve(filePath);
377
377
  const key = variableName ? `${realPath}:${variableName}` : realPath;
378
378
  if (visited.has(key)) {
379
- console.warn(`[rsc-router] Circular include detected, skipping: ${key}`);
379
+ console.warn(`[rango] Circular include detected, skipping: ${key}`);
380
380
  return { routes: {}, searchSchemas: {} };
381
381
  }
382
382
  visited.add(key);
@@ -97,7 +97,10 @@ export function writePerModuleRouteTypesForFile(filePath: string): void {
97
97
  routes = extractRoutesFromSource(source);
98
98
  }
99
99
 
100
- const genPath = filePath.replace(/\.(tsx?)$/, ".gen.ts");
100
+ // Match .ts/.tsx/.js/.jsx (same as router-processing.ts / router-transform.ts).
101
+ // Without the jsx? branch a .jsx/.js source produced genPath === filePath,
102
+ // overwriting the source file instead of writing a sibling .gen.ts.
103
+ const genPath = filePath.replace(/\.(tsx?|jsx?)$/, ".gen.ts");
101
104
 
102
105
  // When a urls() variable was found but static resolution yields zero
103
106
  // routes, write an empty placeholder so generated imports stay
@@ -106,7 +109,7 @@ export function writePerModuleRouteTypesForFile(filePath: string): void {
106
109
  if (varNames.length > 0 && !existsSync(genPath)) {
107
110
  writeFileSync(genPath, generatePerModuleTypesSource([]));
108
111
  console.log(
109
- `[rsc-router] Generated route types (placeholder) -> ${genPath}`,
112
+ `[rango] Generated route types (placeholder) -> ${genPath}`,
110
113
  );
111
114
  }
112
115
  return;
@@ -118,11 +121,11 @@ export function writePerModuleRouteTypesForFile(filePath: string): void {
118
121
  : null;
119
122
  if (existing !== genSource) {
120
123
  writeFileSync(genPath, genSource);
121
- console.log(`[rsc-router] Generated route types -> ${genPath}`);
124
+ console.log(`[rango] Generated route types -> ${genPath}`);
122
125
  }
123
126
  } catch (err) {
124
127
  console.warn(
125
- `[rsc-router] Failed to generate route types for ${filePath}: ${(err as Error).message}`,
128
+ `[rango] Failed to generate route types for ${filePath}: ${(err as Error).message}`,
126
129
  );
127
130
  }
128
131
  }
@@ -15,6 +15,7 @@ import {
15
15
  import ts from "typescript";
16
16
  import { generateRouteTypesSource } from "./codegen.js";
17
17
  import type { ScanFilter } from "./scan-filter.js";
18
+ import { firstCodeMatchIndex } from "./source-scan.js";
18
19
  import {
19
20
  resolveImportedVariable,
20
21
  resolveImportPath,
@@ -38,6 +39,8 @@ function countPublicRouteEntries(source: string): number {
38
39
  }
39
40
 
40
41
  const ROUTER_CALL_PATTERN = /\bcreateRouter\s*[<(]/;
42
+ // Global variant for the code-region scan (firstCodeMatchIndex sets lastIndex).
43
+ const ROUTER_CALL_PATTERN_G = /\bcreateRouter\s*[<(]/g;
41
44
 
42
45
  function isRoutableSourceFile(name: string): boolean {
43
46
  return (
@@ -61,7 +64,7 @@ function findRouterFilesRecursive(
61
64
  entries = readdirSync(dir, { withFileTypes: true });
62
65
  } catch (err) {
63
66
  console.warn(
64
- `[rsc-router] Failed to scan directory ${dir}: ${(err as Error).message}`,
67
+ `[rango] Failed to scan directory ${dir}: ${(err as Error).message}`,
65
68
  );
66
69
  return;
67
70
  }
@@ -90,7 +93,17 @@ function findRouterFilesRecursive(
90
93
 
91
94
  try {
92
95
  const source = readFileSync(fullPath, "utf-8");
93
- if (ROUTER_CALL_PATTERN.test(source)) {
96
+ // Fast path: most files contain no `createRouter(` at all, so the cheap
97
+ // raw regex short-circuits before the code-region scan. Only a file that
98
+ // mentions the token (real call OR a comment/string mention) is rescanned
99
+ // over code regions — allocation-free, never building a stripped copy —
100
+ // so a mention inside a comment or string is not mistaken for a real
101
+ // router file (which previously triggered a spurious "Multiple routers
102
+ // found" error).
103
+ if (
104
+ ROUTER_CALL_PATTERN.test(source) &&
105
+ firstCodeMatchIndex(source, ROUTER_CALL_PATTERN_G) >= 0
106
+ ) {
94
107
  routerFilesInDir.push(fullPath);
95
108
  }
96
109
  } catch {
@@ -142,7 +155,7 @@ export function findNestedRouterConflict(
142
155
 
143
156
  export function formatNestedRouterConflictError(
144
157
  conflict: { ancestor: string; nested: string },
145
- prefix = "[rsc-router]",
158
+ prefix = "[rango]",
146
159
  ): string {
147
160
  return (
148
161
  `${prefix} Nested router roots are not supported.\n` +
@@ -339,6 +352,36 @@ function applyBasenameToRoutes(
339
352
  return { routes: prefixed, searchSchemas: result.searchSchemas };
340
353
  }
341
354
 
355
+ // Filesystem path of the generated route-types file for a router source file.
356
+ // Native separators — matches the self-gen-tracking Map key the watcher compares.
357
+ export function genFileTsPath(sourceFile: string): string {
358
+ const base = pathBasename(sourceFile).replace(/\.(tsx?|jsx?)$/, "");
359
+ return join(dirname(sourceFile), `${base}.named-routes.gen.ts`);
360
+ }
361
+
362
+ // Search schemas for the gen file: prefer the runtime manifest's; when it omits
363
+ // them (some module-runner flows) fall back to static parsing filtered to the
364
+ // public route-name set. Returns the runtime value unchanged otherwise.
365
+ export function resolveSearchSchemas(
366
+ publicRouteNames: string[],
367
+ runtimeSchemas: Record<string, Record<string, string>> | undefined,
368
+ sourceFile: string,
369
+ ): Record<string, Record<string, string>> | undefined {
370
+ if (runtimeSchemas && Object.keys(runtimeSchemas).length > 0) {
371
+ return runtimeSchemas;
372
+ }
373
+ const staticParsed = buildCombinedRouteMapForRouterFile(sourceFile);
374
+ if (Object.keys(staticParsed.searchSchemas).length === 0) {
375
+ return runtimeSchemas;
376
+ }
377
+ const filtered: Record<string, Record<string, string>> = {};
378
+ for (const name of publicRouteNames) {
379
+ const schema = staticParsed.searchSchemas[name];
380
+ if (schema) filtered[name] = schema;
381
+ }
382
+ return Object.keys(filtered).length > 0 ? filtered : runtimeSchemas;
383
+ }
384
+
342
385
  /**
343
386
  * Resolve routes and search schemas from a router source file by following the
344
387
  * variable passed to `.routes(...)` or `urls: ...` in createRouter options,
@@ -528,7 +571,10 @@ export function findRouterFiles(root: string, filter?: ScanFilter): string[] {
528
571
  export function writeCombinedRouteTypes(
529
572
  root: string,
530
573
  knownRouterFiles?: string[],
531
- opts?: { preserveIfLarger?: boolean },
574
+ opts?: {
575
+ preserveIfLarger?: boolean;
576
+ onWrite?: (outPath: string, content: string) => void;
577
+ },
532
578
  ): void {
533
579
  // Delete old combined named-routes.gen.ts if it exists (stale from older versions)
534
580
  try {
@@ -536,7 +582,7 @@ export function writeCombinedRouteTypes(
536
582
  if (existsSync(oldCombinedPath)) {
537
583
  unlinkSync(oldCombinedPath);
538
584
  console.log(
539
- `[rsc-router] Removed stale combined route types: ${oldCombinedPath}`,
585
+ `[rango] Removed stale combined route types: ${oldCombinedPath}`,
540
586
  );
541
587
  }
542
588
  } catch {}
@@ -566,14 +612,7 @@ export function writeCombinedRouteTypes(
566
612
  if (!extractUrlsFromRouter(routerSource)) continue;
567
613
  }
568
614
 
569
- const routerBasename = pathBasename(routerFilePath).replace(
570
- /\.(tsx?|jsx?)$/,
571
- "",
572
- );
573
- const outPath = join(
574
- dirname(routerFilePath),
575
- `${routerBasename}.named-routes.gen.ts`,
576
- );
615
+ const outPath = genFileTsPath(routerFilePath);
577
616
  const existing = existsSync(outPath)
578
617
  ? readFileSync(outPath, "utf-8")
579
618
  : null;
@@ -584,6 +623,7 @@ export function writeCombinedRouteTypes(
584
623
  if (Object.keys(result.routes).length === 0) {
585
624
  if (!existing) {
586
625
  const emptySource = generateRouteTypesSource({});
626
+ opts?.onWrite?.(outPath, emptySource);
587
627
  writeFileSync(outPath, emptySource);
588
628
  }
589
629
  continue;
@@ -609,9 +649,10 @@ export function writeCombinedRouteTypes(
609
649
  continue;
610
650
  }
611
651
  }
652
+ opts?.onWrite?.(outPath, source);
612
653
  writeFileSync(outPath, source);
613
654
  console.log(
614
- `[rsc-router] Generated route types (${Object.keys(result.routes).length} routes) -> ${outPath}`,
655
+ `[rango] Generated route types (${Object.keys(result.routes).length} routes) -> ${outPath}`,
615
656
  );
616
657
  }
617
658
  }
@@ -54,7 +54,7 @@ export function findTsFiles(dir: string, filter?: ScanFilter): string[] {
54
54
  entries = readdirSync(dir, { withFileTypes: true });
55
55
  } catch (err) {
56
56
  console.warn(
57
- `[rsc-router] Failed to scan directory ${dir}: ${(err as Error).message}`,
57
+ `[rango] Failed to scan directory ${dir}: ${(err as Error).message}`,
58
58
  );
59
59
  return results;
60
60
  }
@@ -0,0 +1,118 @@
1
+ // Allocation-light, linear-time source scanning for the build-time scanners.
2
+ //
3
+ // The router-file scanner, the HMR relevance check, and the unsupported-shape
4
+ // warning all need to know whether a token like `createRouter(` / `createLoader(`
5
+ // appears in REAL code versus inside a comment or string literal. Rather than
6
+ // build a full comment/string-stripped copy of the source (which on a large
7
+ // file allocates an O(n) string plus, naively, a per-char array), these helpers
8
+ // run the regex over the whole source ONCE (the engine sweeps left-to-right,
9
+ // O(n)) and classify each match's offset with a forward, O(1)-memory cursor that
10
+ // advances monotonically across the source.
11
+ //
12
+ // Time: O(n) — one native regex sweep plus one forward classification pass.
13
+ // Memory: O(1) for the boolean check; O(#matches) for the index list. No
14
+ // stripped copy and no per-char array are ever materialized.
15
+ //
16
+ // Pragmatic scanner, not a full tokenizer: regex literals are not special-cased
17
+ // (a target token inside one is implausible) and template interpolations are
18
+ // treated as opaque string content. One intentional consequence: a token whose
19
+ // match would only complete by treating an interleaved comment as whitespace
20
+ // (e.g. `createRouter /* x */ (`) is not detected — real calls never interleave
21
+ // a comment between the callee and its arguments.
22
+
23
+ // JS line terminators end a `//` comment: LF, CR, LS (U+2028), PS (U+2029).
24
+ function isLineTerminator(ch: string): boolean {
25
+ const c = ch.charCodeAt(0);
26
+ // LF, CR, LS (U+2028), PS (U+2029)
27
+ return c === 10 || c === 13 || c === 0x2028 || c === 0x2029;
28
+ }
29
+
30
+ /**
31
+ * Build a classifier that answers "is offset `q` in code (not a comment or
32
+ * string)?" for STRICTLY INCREASING `q`. The internal cursor only moves forward,
33
+ * so a full left-to-right sequence of queries costs O(n) total with O(1) memory.
34
+ */
35
+ function makeCodeClassifier(code: string): (q: number) => boolean {
36
+ const n = code.length;
37
+ let i = 0; // forward cursor: everything before `i` is already classified
38
+ let skipStart = -1; // last detected comment/string region (cache)
39
+ let skipEnd = -1;
40
+
41
+ return (q: number): boolean => {
42
+ if (q >= skipStart && q < skipEnd) return false; // q in the cached region
43
+ while (i < n && i <= q) {
44
+ const c = code[i];
45
+ const d = i + 1 < n ? code[i + 1] : "";
46
+ let end = -1;
47
+ if (c === "/" && d === "/") {
48
+ let j = i + 2;
49
+ while (j < n && !isLineTerminator(code[j])) j++;
50
+ end = j;
51
+ } else if (c === "/" && d === "*") {
52
+ let j = i + 2;
53
+ while (j < n && !(code[j] === "*" && code[j + 1] === "/")) j++;
54
+ end = Math.min(n, j + 2);
55
+ } else if (c === '"' || c === "'" || c === "`") {
56
+ let j = i + 1;
57
+ while (j < n) {
58
+ if (code[j] === "\\") {
59
+ j += 2;
60
+ continue;
61
+ }
62
+ if (code[j] === c) {
63
+ j++;
64
+ break;
65
+ }
66
+ j++;
67
+ }
68
+ end = j;
69
+ }
70
+ if (end >= 0) {
71
+ // Comment/string region [i, end). `q >= i` here (loop condition).
72
+ if (q < end) {
73
+ skipStart = i;
74
+ skipEnd = end;
75
+ return false;
76
+ }
77
+ i = end;
78
+ } else {
79
+ i++;
80
+ }
81
+ }
82
+ return true; // reached q in code mode
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Index of the first match of `pattern` that occurs in code (not in a comment
88
+ * or string), or -1. `pattern` MUST be a global (`/g`) regex. Single native
89
+ * regex sweep with early-exit; O(1) extra memory.
90
+ */
91
+ export function firstCodeMatchIndex(code: string, pattern: RegExp): number {
92
+ const inCode = makeCodeClassifier(code);
93
+ pattern.lastIndex = 0;
94
+ let m: RegExpExecArray | null;
95
+ while ((m = pattern.exec(code)) !== null) {
96
+ if (inCode(m.index)) return m.index;
97
+ if (pattern.lastIndex <= m.index) pattern.lastIndex = m.index + 1;
98
+ }
99
+ return -1;
100
+ }
101
+
102
+ /**
103
+ * Byte offsets of every match of `pattern` that occurs in code (not in a
104
+ * comment or string). `pattern` MUST be a global (`/g`) regex. Each offset is
105
+ * the match start — the same byte offset a raw `pattern.exec` reports. O(n)
106
+ * time, O(#matches) memory.
107
+ */
108
+ export function codeMatchIndices(code: string, pattern: RegExp): number[] {
109
+ const inCode = makeCodeClassifier(code);
110
+ const indices: number[] = [];
111
+ pattern.lastIndex = 0;
112
+ let m: RegExpExecArray | null;
113
+ while ((m = pattern.exec(code)) !== null) {
114
+ if (inCode(m.index)) indices.push(m.index);
115
+ if (pattern.lastIndex <= m.index) pattern.lastIndex = m.index + 1;
116
+ }
117
+ return indices;
118
+ }
@@ -1,8 +1,9 @@
1
- import { dirname, join, basename, resolve } from "node:path";
1
+ import { resolve } from "node:path";
2
2
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import {
4
4
  generateRouteTypesSource,
5
- buildCombinedRouteMapForRouterFile,
5
+ genFileTsPath,
6
+ resolveSearchSchemas,
6
7
  } from "./generate-route-types.ts";
7
8
  import { isAutoGeneratedRouteName } from "../route-name.js";
8
9
 
@@ -175,25 +176,13 @@ export async function discoverAndWriteRouteTypes(
175
176
  );
176
177
  }
177
178
 
178
- // Search schema fallback: runtime manifest may omit search schema metadata
179
- // in some module-runner flows. Fall back to static source parsing.
180
- if (!routeSearchSchemas || Object.keys(routeSearchSchemas).length === 0) {
181
- const staticParsed = buildCombinedRouteMapForRouterFile(sourceFile);
182
- if (Object.keys(staticParsed.searchSchemas).length > 0) {
183
- const filtered: Record<string, Record<string, string>> = {};
184
- for (const name of Object.keys(routeManifest)) {
185
- const schema = staticParsed.searchSchemas[name];
186
- if (schema) filtered[name] = schema;
187
- }
188
- if (Object.keys(filtered).length > 0) {
189
- routeSearchSchemas = filtered;
190
- }
191
- }
192
- }
179
+ routeSearchSchemas = resolveSearchSchemas(
180
+ Object.keys(routeManifest),
181
+ routeSearchSchemas,
182
+ sourceFile,
183
+ );
193
184
 
194
- const routerDir = dirname(sourceFile);
195
- const routerBasename = basename(sourceFile).replace(/\.(tsx?|jsx?)$/, "");
196
- const outPath = join(routerDir, `${routerBasename}.named-routes.gen.ts`);
185
+ const outPath = genFileTsPath(sourceFile);
197
186
 
198
187
  const source = generateRouteTypesSource(
199
188
  routeManifest,
@@ -32,7 +32,11 @@ import {
32
32
  export { isCachedFunction };
33
33
  import { serializeResult, deserializeResult } from "./segment-codec.js";
34
34
  import { createHandleStore } from "../server/handle-store.js";
35
- import { restoreHandles } from "./handle-snapshot.js";
35
+ import {
36
+ restoreHandles,
37
+ encodeHandles,
38
+ decodeHandles,
39
+ } from "./handle-snapshot.js";
36
40
  import { startHandleCapture, type HandleCapture } from "./handle-capture.js";
37
41
  import { sortedSearchString } from "./cache-key-utils.js";
38
42
  import { runBackground } from "./background-task.js";
@@ -170,7 +174,8 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
170
174
  if (cached.handles && hasTaintedArgs) {
171
175
  const handleStore = requestCtx?._handleStore;
172
176
  if (handleStore) {
173
- restoreHandles(cached.handles, handleStore);
177
+ const r = await decodeHandles(cached.handles);
178
+ if (r) restoreHandles(r, handleStore);
174
179
  }
175
180
  }
176
181
  return result;
@@ -186,7 +191,8 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
186
191
  if (cached.handles && hasTaintedArgs) {
187
192
  const handleStore = requestCtx?._handleStore;
188
193
  if (handleStore) {
189
- restoreHandles(cached.handles, handleStore);
194
+ const r = await decodeHandles(cached.handles);
195
+ if (r) restoreHandles(r, handleStore);
190
196
  }
191
197
  }
192
198
  // Background revalidation — must capture handles if tainted args present.
@@ -242,8 +248,11 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
242
248
  bgStopCapture?.();
243
249
  const serialized = await serializeResult(freshResult);
244
250
  if (serialized !== null) {
251
+ const encodedHandles = bgCapture?.data
252
+ ? await encodeHandles(bgCapture.data)
253
+ : undefined;
245
254
  await store.setItem!(cacheKey, serialized, {
246
- handles: bgCapture?.data,
255
+ handles: encodedHandles,
247
256
  ttl: profile.ttl,
248
257
  swr: profile.swr,
249
258
  tags: profile.tags,
@@ -317,8 +326,11 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
317
326
  try {
318
327
  const serialized = await serializeResult(result);
319
328
  if (serialized !== null) {
329
+ const encodedHandles = capture?.data
330
+ ? await encodeHandles(capture.data)
331
+ : undefined;
320
332
  await store.setItem!(cacheKey, serialized, {
321
- handles: capture?.data,
333
+ handles: encodedHandles,
322
334
  ttl: profile.ttl,
323
335
  swr: profile.swr,
324
336
  tags: profile.tags,
@@ -17,7 +17,12 @@ import {
17
17
  _getRequestContext,
18
18
  } from "../server/request-context.js";
19
19
  import { serializeSegments, deserializeSegments } from "./segment-codec.js";
20
- import { captureHandles, restoreHandles } from "./handle-snapshot.js";
20
+ import {
21
+ captureHandles,
22
+ restoreHandles,
23
+ encodeHandles,
24
+ decodeHandles,
25
+ } from "./handle-snapshot.js";
21
26
  import { sortedSearchString, sortedRouteParams } from "./cache-key-utils.js";
22
27
  import {
23
28
  DEFAULT_ROUTE_TTL,
@@ -187,6 +192,32 @@ export class CacheScope {
187
192
  return resolveCacheKey(keyFn, this.getStore(), defaultKey, "CacheScope");
188
193
  }
189
194
 
195
+ /**
196
+ * Evaluate the cache `condition` predicate. Returns false (skip the cache
197
+ * operation) when the predicate returns false or throws; returns true when
198
+ * there is no condition or no request context to evaluate it against.
199
+ */
200
+ private conditionAllows(op: "read" | "write"): boolean {
201
+ if (this.config === false || !this.config.condition) return true;
202
+ const requestCtx = getRequestContext();
203
+ if (!requestCtx) return true;
204
+ try {
205
+ if (!this.config.condition(requestCtx)) {
206
+ debugCacheLog(
207
+ `[CacheScope] condition returned false, skipping cache ${op}`,
208
+ );
209
+ return false;
210
+ }
211
+ return true;
212
+ } catch (error) {
213
+ console.error(
214
+ `[CacheScope] condition function threw, skipping cache ${op}:`,
215
+ error,
216
+ );
217
+ return false;
218
+ }
219
+ }
220
+
190
221
  /**
191
222
  * Lookup cached segments for a route (single cache entry per request).
192
223
  * Returns { segments, shouldRevalidate } or null if cache miss.
@@ -204,27 +235,7 @@ export class CacheScope {
204
235
  shouldRevalidate: boolean;
205
236
  } | null> {
206
237
  if (!this.enabled) return null;
207
-
208
- // Evaluate condition — skip cache read when condition returns false
209
- if (this.config !== false && this.config.condition) {
210
- const requestCtx = getRequestContext();
211
- if (requestCtx) {
212
- try {
213
- if (!this.config.condition(requestCtx)) {
214
- debugCacheLog(
215
- `[CacheScope] condition returned false, skipping cache read`,
216
- );
217
- return null;
218
- }
219
- } catch (error) {
220
- console.error(
221
- `[CacheScope] condition function threw, skipping cache read:`,
222
- error,
223
- );
224
- return null;
225
- }
226
- }
227
- }
238
+ if (!this.conditionAllows("read")) return null;
228
239
 
229
240
  const store = this.getStore();
230
241
  if (!store) return null;
@@ -245,10 +256,16 @@ export class CacheScope {
245
256
  // Deserialize segments
246
257
  const segments = await deserializeSegments(cached.segments);
247
258
 
248
- // Replay handle data
259
+ // Replay handle data. An empty string means the route pushed no handles —
260
+ // skip the decode entirely (the common case). Otherwise decode the
261
+ // Flight-encoded blob; a decode failure skips handle restore but keeps the
262
+ // valid cached segments.
249
263
  const handleStore = _getRequestContext()?._handleStore;
250
- if (handleStore) {
251
- restoreHandles(cached.handles, handleStore);
264
+ if (handleStore && cached.handles) {
265
+ const handlesRecord = await decodeHandles(cached.handles);
266
+ if (handlesRecord) {
267
+ restoreHandles(handlesRecord, handleStore);
268
+ }
252
269
  }
253
270
 
254
271
  if (INTERNAL_RANGO_DEBUG) {
@@ -284,27 +301,7 @@ export class CacheScope {
284
301
  isIntercept?: boolean,
285
302
  ): Promise<void> {
286
303
  if (!this.enabled || segments.length === 0) return;
287
-
288
- // Evaluate condition — skip cache write when condition returns false
289
- if (this.config !== false && this.config.condition) {
290
- const conditionCtx = getRequestContext();
291
- if (conditionCtx) {
292
- try {
293
- if (!this.config.condition(conditionCtx)) {
294
- debugCacheLog(
295
- `[CacheScope] condition returned false, skipping cache write`,
296
- );
297
- return;
298
- }
299
- } catch (error) {
300
- console.error(
301
- `[CacheScope] condition function threw, skipping cache write:`,
302
- error,
303
- );
304
- return;
305
- }
306
- }
307
- }
304
+ if (!this.conditionAllows("write")) return;
308
305
 
309
306
  const store = this.getStore();
310
307
  if (!store) return;
@@ -381,12 +378,17 @@ export class CacheScope {
381
378
  );
382
379
  }
383
380
 
384
- // Serialize non-loader segments only
385
- const serializedSegments = await serializeSegments(nonLoaderSegments);
381
+ // Serialize segments and Flight-encode handles in parallel. Handles go
382
+ // through the codec (not raw into the entry) so Promise/ReactNode handle
383
+ // values survive a JSON-serializing store — see encodeHandles.
384
+ const [serializedSegments, encodedHandles] = await Promise.all([
385
+ serializeSegments(nonLoaderSegments),
386
+ encodeHandles(handles),
387
+ ]);
386
388
 
387
389
  const data: CachedEntryData = {
388
390
  segments: serializedSegments,
389
- handles,
391
+ handles: encodedHandles,
390
392
  expiresAt: Date.now() + ttl * 1000,
391
393
  };
392
394