@rangojs/router 0.5.2 → 0.7.0

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 (178) hide show
  1. package/dist/bin/rango.js +343 -125
  2. package/dist/types/browser/react/use-router.d.ts +10 -3
  3. package/dist/types/browser/react/use-search-params.d.ts +57 -10
  4. package/dist/types/browser/types.d.ts +22 -0
  5. package/dist/types/build/merge-full-manifests.d.ts +3 -0
  6. package/dist/types/build/route-trie.d.ts +4 -73
  7. package/dist/types/build/route-types/per-module-writer.d.ts +6 -4
  8. package/dist/types/build/route-types/router-processing.d.ts +2 -3
  9. package/dist/types/cache/cache-exec-scope.d.ts +31 -0
  10. package/dist/types/cache/taint.d.ts +12 -6
  11. package/dist/types/client-urls/client-root.d.ts +38 -0
  12. package/dist/types/client-urls/client-urls.d.ts +5 -0
  13. package/dist/types/client-urls/navigation.d.ts +38 -0
  14. package/dist/types/client-urls/revalidation-protocol.d.ts +25 -0
  15. package/dist/types/client-urls/server-projection.d.ts +71 -0
  16. package/dist/types/client-urls/types.d.ts +147 -0
  17. package/dist/types/client.d.ts +12 -4
  18. package/dist/types/client.rsc.d.ts +4 -1
  19. package/dist/types/decode-loader-results.d.ts +37 -0
  20. package/dist/types/errors.d.ts +1 -0
  21. package/dist/types/index.d.ts +1 -1
  22. package/dist/types/loader-redirect.d.ts +27 -0
  23. package/dist/types/outlet-context.d.ts +12 -0
  24. package/dist/types/outlet-provider.d.ts +3 -1
  25. package/dist/types/redirect-origin.d.ts +4 -0
  26. package/dist/types/route-content-wrapper.d.ts +42 -1
  27. package/dist/types/route-definition/helpers-types.d.ts +13 -2
  28. package/dist/types/router/error-handling.d.ts +35 -1
  29. package/dist/types/router/intercept-resolution.d.ts +12 -0
  30. package/dist/types/router/loader-resolution.d.ts +24 -2
  31. package/dist/types/router/revalidation.d.ts +7 -0
  32. package/dist/types/router/route-trie-builder.d.ts +77 -0
  33. package/dist/types/router/router-interfaces.d.ts +20 -0
  34. package/dist/types/router/segment-resolution/helpers.d.ts +1 -1
  35. package/dist/types/router/segment-resolution/loader-mask.d.ts +9 -9
  36. package/dist/types/router/trie-matching.d.ts +1 -1
  37. package/dist/types/rsc/manifest-init.d.ts +5 -5
  38. package/dist/types/rsc/shell-capture.d.ts +9 -0
  39. package/dist/types/rsc/shell-serve.d.ts +11 -0
  40. package/dist/types/rsc/types.d.ts +30 -0
  41. package/dist/types/segment-system.d.ts +2 -0
  42. package/dist/types/server/context.d.ts +10 -0
  43. package/dist/types/server/handle-store.d.ts +34 -3
  44. package/dist/types/server/request-context.d.ts +11 -1
  45. package/dist/types/server.d.ts +1 -0
  46. package/dist/types/ssr/index.d.ts +22 -0
  47. package/dist/types/ssr/ssr-root.d.ts +10 -0
  48. package/dist/types/testing/dom.entry.d.ts +1 -1
  49. package/dist/types/testing/render-route.d.ts +16 -6
  50. package/dist/types/testing/run-loader.d.ts +9 -0
  51. package/dist/types/types/boundaries.d.ts +22 -0
  52. package/dist/types/types/index.d.ts +1 -1
  53. package/dist/types/types/loader-types.d.ts +57 -5
  54. package/dist/types/types/segments.d.ts +7 -0
  55. package/dist/types/urls/path-helper-types.d.ts +13 -4
  56. package/dist/types/vite/discovery/client-urls-projection.d.ts +53 -0
  57. package/dist/types/vite/discovery/discover-routers.d.ts +1 -1
  58. package/dist/types/vite/discovery/state.d.ts +8 -1
  59. package/dist/types/vite/plugins/client-ref-dedup.d.ts +0 -11
  60. package/dist/vite/index.js +6159 -2959
  61. package/package.json +6 -5
  62. package/skills/breadcrumbs/SKILL.md +39 -9
  63. package/skills/catalog.json +7 -1
  64. package/skills/client-urls/SKILL.md +338 -0
  65. package/skills/comparison/references/framework-comparison.md +23 -9
  66. package/skills/hooks/SKILL.md +2 -2
  67. package/skills/hooks/data.md +11 -2
  68. package/skills/hooks/handle-and-actions.md +7 -0
  69. package/skills/hooks/outlets.md +26 -5
  70. package/skills/hooks/urls.md +40 -3
  71. package/skills/loader/SKILL.md +132 -20
  72. package/skills/migrate-nextjs/SKILL.md +70 -10
  73. package/skills/migrate-react-router/SKILL.md +49 -13
  74. package/skills/migrate-react-router/component-migration.md +18 -13
  75. package/skills/migrate-react-router/data-and-actions.md +14 -3
  76. package/skills/migrate-react-router/route-mapping.md +15 -2
  77. package/skills/parallel/SKILL.md +32 -1
  78. package/skills/ppr/SKILL.md +16 -6
  79. package/skills/prerender/SKILL.md +8 -4
  80. package/skills/rango/SKILL.md +21 -17
  81. package/skills/react-compiler/SKILL.md +3 -3
  82. package/skills/route/SKILL.md +5 -2
  83. package/skills/router-setup/SKILL.md +16 -2
  84. package/skills/scripts/SKILL.md +16 -6
  85. package/skills/shell-manifest/SKILL.md +16 -7
  86. package/skills/testing/SKILL.md +2 -2
  87. package/skills/testing/client-components.md +6 -0
  88. package/skills/testing/handles.md +30 -8
  89. package/skills/testing/loader.md +51 -49
  90. package/skills/testing/middleware.md +1 -1
  91. package/skills/theme/SKILL.md +8 -5
  92. package/src/bin/rango.ts +7 -3
  93. package/src/browser/navigation-bridge.ts +6 -0
  94. package/src/browser/navigation-client.ts +5 -0
  95. package/src/browser/partial-update.ts +65 -13
  96. package/src/browser/react/use-router.ts +40 -11
  97. package/src/browser/react/use-search-params.ts +140 -17
  98. package/src/browser/rsc-router.tsx +59 -0
  99. package/src/browser/server-action-bridge.ts +26 -0
  100. package/src/browser/types.ts +22 -0
  101. package/src/build/merge-full-manifests.ts +161 -0
  102. package/src/build/route-trie.ts +9 -332
  103. package/src/build/route-types/include-resolution.ts +66 -11
  104. package/src/build/route-types/per-module-writer.ts +11 -6
  105. package/src/build/route-types/router-processing.ts +184 -153
  106. package/src/build/runtime-discovery.ts +23 -12
  107. package/src/cache/cache-exec-scope.ts +47 -0
  108. package/src/cache/cache-runtime.ts +24 -25
  109. package/src/cache/taint.ts +28 -9
  110. package/src/client-urls/client-root.tsx +168 -0
  111. package/src/client-urls/client-urls.ts +776 -0
  112. package/src/client-urls/navigation.ts +237 -0
  113. package/src/client-urls/revalidation-protocol.ts +56 -0
  114. package/src/client-urls/server-projection.ts +670 -0
  115. package/src/client-urls/types.ts +201 -0
  116. package/src/client.rsc.tsx +12 -0
  117. package/src/client.tsx +49 -6
  118. package/src/decode-loader-results.ts +113 -0
  119. package/src/errors.ts +14 -0
  120. package/src/handles/deferred-resolution.ts +14 -7
  121. package/src/index.ts +1 -0
  122. package/src/loader-redirect.tsx +64 -0
  123. package/src/outlet-context.ts +12 -0
  124. package/src/outlet-provider.tsx +15 -1
  125. package/src/redirect-origin.ts +29 -0
  126. package/src/route-content-wrapper.tsx +96 -3
  127. package/src/route-definition/dsl-helpers.ts +28 -3
  128. package/src/route-definition/helpers-types.ts +13 -0
  129. package/src/route-definition/redirect.ts +17 -18
  130. package/src/router/error-handling.ts +65 -11
  131. package/src/router/intercept-resolution.ts +29 -0
  132. package/src/router/loader-resolution.ts +261 -28
  133. package/src/router/match-result.ts +7 -0
  134. package/src/router/revalidation.ts +24 -11
  135. package/src/router/route-trie-builder.ts +334 -0
  136. package/src/router/router-interfaces.ts +38 -0
  137. package/src/router/segment-resolution/fresh.ts +55 -2
  138. package/src/router/segment-resolution/helpers.ts +9 -11
  139. package/src/router/segment-resolution/loader-cache.ts +34 -23
  140. package/src/router/segment-resolution/loader-mask.ts +9 -9
  141. package/src/router/segment-resolution/revalidation.ts +23 -2
  142. package/src/router/trie-matching.ts +3 -3
  143. package/src/router.ts +46 -1
  144. package/src/rsc/full-payload.ts +6 -0
  145. package/src/rsc/handler.ts +10 -7
  146. package/src/rsc/loader-fetch.ts +2 -2
  147. package/src/rsc/manifest-init.ts +28 -9
  148. package/src/rsc/rsc-rendering.ts +15 -1
  149. package/src/rsc/shell-capture.ts +12 -0
  150. package/src/rsc/shell-serve.ts +15 -2
  151. package/src/rsc/ssr-setup.ts +10 -1
  152. package/src/rsc/types.ts +31 -2
  153. package/src/segment-system.tsx +83 -26
  154. package/src/server/context.ts +10 -0
  155. package/src/server/cookie-store.ts +19 -19
  156. package/src/server/handle-store.ts +185 -48
  157. package/src/server/request-context.ts +30 -6
  158. package/src/server.ts +7 -0
  159. package/src/ssr/index.tsx +37 -2
  160. package/src/ssr/ssr-root.tsx +29 -2
  161. package/src/testing/dom.entry.ts +1 -1
  162. package/src/testing/render-route.tsx +22 -8
  163. package/src/testing/run-loader.ts +51 -13
  164. package/src/types/boundaries.ts +19 -0
  165. package/src/types/index.ts +1 -0
  166. package/src/types/loader-types.ts +60 -5
  167. package/src/types/segments.ts +7 -0
  168. package/src/urls/include-helper.ts +22 -4
  169. package/src/urls/path-helper-types.ts +17 -1
  170. package/src/use-loader.tsx +67 -6
  171. package/src/vite/discovery/client-urls-projection.ts +322 -0
  172. package/src/vite/discovery/discover-routers.ts +43 -17
  173. package/src/vite/discovery/state.ts +11 -1
  174. package/src/vite/discovery/virtual-module-codegen.ts +20 -0
  175. package/src/vite/plugins/client-ref-dedup.ts +281 -19
  176. package/src/vite/plugins/expose-action-id.ts +45 -23
  177. package/src/vite/plugins/virtual-entries.ts +12 -3
  178. package/src/vite/router-discovery.ts +163 -12
@@ -5,6 +5,7 @@ import type {
5
5
  Handler,
6
6
  HandlerContext,
7
7
  LoaderDefinition,
8
+ LoaderOptions,
8
9
  MiddlewareFn,
9
10
  NotFoundBoundaryHandler,
10
11
  PartialCacheOptions,
@@ -57,6 +58,7 @@ import type {
57
58
  IncludeOptions,
58
59
  } from "./pattern-types.js";
59
60
  import type { ExtractRoutes, ExtractResponses } from "./type-extraction.js";
61
+ import type { ClientUrlPatterns } from "../client-urls/types.js";
60
62
 
61
63
  /**
62
64
  * Base path function signature for defining routes with URL patterns.
@@ -175,6 +177,11 @@ export type IncludeArg<
175
177
  TResponses extends Record<string, unknown>,
176
178
  > =
177
179
  | UrlPatterns<TEnv, TRoutes, TResponses>
180
+ // clientUrls() definitions mount through include() like any urls() module;
181
+ // on the server the runtime value is the module's client reference, but the
182
+ // TypeScript type of that default export IS ClientUrlPatterns, so route
183
+ // names flow into NamedRoutes through the same TRoutes inference.
184
+ | ClientUrlPatterns<TRoutes>
178
185
  | (() =>
179
186
  | IncludeResolved<TEnv, TRoutes, TResponses>
180
187
  | Promise<IncludeResolved<TEnv, TRoutes, TResponses>>);
@@ -338,10 +345,19 @@ export type PathHelpers<TEnv> = {
338
345
  revalidate: (fn: ShouldRevalidateFn<any, TEnv>) => RevalidateItem;
339
346
 
340
347
  /**
341
- * Attach a data loader to the current route/layout
348
+ * Attach a data loader to the current route/layout.
349
+ *
350
+ * Pass `{ stream: "navigation" }` to await this loader before first flush
351
+ * on DOCUMENT requests (see {@link LoaderOptions}) — the opt-in for loaders
352
+ * whose data, handle pushes, or thrown notFound()/redirect() must be in the
353
+ * SSR'd HTML. Per-loader: a dynamic sibling keeps streaming. Under a
354
+ * `ppr` route the flag BAKES: the loader executes at shell capture and
355
+ * its settled return freezes into the shell (nested promises stay live
356
+ * holes) — the pre-flush promise applied to the prelude.
342
357
  */
343
358
  loader: <TData>(
344
359
  loaderDef: LoaderDefinition<TData>,
360
+ optionsOrUse?: LoaderOptions | (() => LoaderUseItem[]),
345
361
  use?: () => LoaderUseItem[],
346
362
  ) => LoaderItem;
347
363
 
@@ -3,6 +3,7 @@
3
3
  import {
4
4
  isValidElement,
5
5
  startTransition,
6
+ use,
6
7
  useCallback,
7
8
  useContext,
8
9
  useEffect,
@@ -13,6 +14,7 @@ import {
13
14
  } from "react";
14
15
  import { OutletContext, type OutletContextValue } from "./outlet-context.js";
15
16
  import { loaderStore, type LoaderEntry } from "./loader-store.js";
17
+ import { decodeLoaderEntry } from "./decode-loader-results.js";
16
18
  import type { LoaderDefinition, LoadOptions } from "./types.js";
17
19
 
18
20
  function isShareableGet(options: LoadOptions | undefined): boolean {
@@ -34,19 +36,47 @@ let privateGroupBucketSeq = 0;
34
36
 
35
37
  const NOT_FOUND = Symbol("not-found");
36
38
 
39
+ /**
40
+ * SPIKE (streaming useLoader): lookup results distinguish a synchronously
41
+ * available value from a still-streaming per-loader promise. A pending stream
42
+ * is `use()`d at the read site (implicit suspension); the promise identity is
43
+ * stable per commit (it comes from the provider's memoized context value /
44
+ * element props), which use() requires across replays.
45
+ */
46
+ type LoaderLookup =
47
+ | typeof NOT_FOUND
48
+ | { value: unknown }
49
+ | { stream: Promise<unknown> };
50
+
51
+ function lookupLoaderStreams(
52
+ loaderStreams: Record<string, unknown> | undefined,
53
+ loaderId: string,
54
+ ): LoaderLookup {
55
+ if (!loaderStreams || !(loaderId in loaderStreams)) return NOT_FOUND;
56
+ const entry = loaderStreams[loaderId];
57
+ // Within the loaderStreams channel a Promise always means "still streaming";
58
+ // settled entries are undecoded result values, never promises.
59
+ return entry instanceof Promise
60
+ ? { stream: entry }
61
+ : { value: decodeLoaderEntry(entry) };
62
+ }
63
+
37
64
  function extractContentLoaderData(
38
65
  node: ReactNode,
39
66
  loaderId: string,
40
- ): unknown | typeof NOT_FOUND {
67
+ ): LoaderLookup {
41
68
  if (!isValidElement(node)) return NOT_FOUND;
42
69
  const props = node.props as Record<string, any> | undefined;
43
70
  if (!props) return NOT_FOUND;
44
71
 
45
72
  // Direct OutletProvider with loaderData
46
73
  if (props.loaderData && loaderId in props.loaderData) {
47
- return props.loaderData[loaderId];
74
+ return { value: props.loaderData[loaderId] };
48
75
  }
49
76
 
77
+ const streamed = lookupLoaderStreams(props.loaderStreams, loaderId);
78
+ if (streamed !== NOT_FOUND) return streamed;
79
+
50
80
  if (
51
81
  props.loaderIds &&
52
82
  Array.isArray(props.loaderIds) &&
@@ -57,9 +87,9 @@ function extractContentLoaderData(
57
87
  if (idx !== -1) {
58
88
  const data = (props.loaderDataPromise as any[])[idx];
59
89
  if (data && typeof data === "object" && "ok" in data) {
60
- return data.ok ? data.data : NOT_FOUND;
90
+ return data.ok ? { value: data.data } : NOT_FOUND;
61
91
  }
62
- return data;
92
+ return { value: data };
63
93
  }
64
94
  }
65
95
 
@@ -102,9 +132,10 @@ function useLoaderInternal<T>(
102
132
  ): UseFetchLoaderResult<T> {
103
133
  const context = useContext(OutletContext);
104
134
 
105
- const { contextData, hasContextData } = useMemo((): {
135
+ const walk = useMemo((): {
106
136
  contextData: T | undefined;
107
137
  hasContextData: boolean;
138
+ pendingStream?: Promise<unknown>;
108
139
  } => {
109
140
  let current: OutletContextValue | null | undefined = context;
110
141
  while (current) {
@@ -114,18 +145,48 @@ function useLoaderInternal<T>(
114
145
  hasContextData: true,
115
146
  };
116
147
  }
148
+ const streamed = lookupLoaderStreams(current.loaderStreams, loader.$$id);
149
+ if (streamed !== NOT_FOUND) {
150
+ if ("stream" in streamed) {
151
+ return {
152
+ contextData: undefined,
153
+ hasContextData: true,
154
+ pendingStream: streamed.stream,
155
+ };
156
+ }
157
+ return { contextData: streamed.value as T, hasContextData: true };
158
+ }
117
159
  const contentData = extractContentLoaderData(
118
160
  current.content,
119
161
  loader.$$id,
120
162
  );
121
163
  if (contentData !== NOT_FOUND) {
122
- return { contextData: contentData as T, hasContextData: true };
164
+ if ("stream" in contentData) {
165
+ return {
166
+ contextData: undefined,
167
+ hasContextData: true,
168
+ pendingStream: contentData.stream,
169
+ };
170
+ }
171
+ return { contextData: contentData.value as T, hasContextData: true };
123
172
  }
124
173
  current = current.parent;
125
174
  }
126
175
  return { contextData: undefined, hasContextData: false };
127
176
  }, [context, loader.$$id]);
128
177
 
178
+ // SPIKE (streaming useLoader): a pending per-loader stream suspends HERE —
179
+ // the implicit-suspense read. use() is exempt from hook-order rules, so the
180
+ // conditional call is legal; on replay after resolution it returns
181
+ // synchronously and the decoded value takes the contextData slot. Hooks
182
+ // below never run in a suspended render, so their order is stable across
183
+ // every COMPLETED render.
184
+ const { hasContextData } = walk;
185
+ let contextData = walk.contextData;
186
+ if (walk.pendingStream) {
187
+ contextData = decodeLoaderEntry(use(walk.pendingStream)) as T;
188
+ }
189
+
129
190
  const loaderId = loader.$$id;
130
191
  const key = options?.key;
131
192
  const refreshGroupOption = options?.refreshGroup;
@@ -0,0 +1,322 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { isAbsolute, relative, resolve } from "node:path";
3
+ import { normalizePath, parseAst } from "vite";
4
+ import {
5
+ serializeClientUrlPatterns,
6
+ type ClientUrlProjection,
7
+ } from "../../client-urls/server-projection.js";
8
+ import type { ClientUrlPatterns } from "../../client-urls/types.js";
9
+ import {
10
+ computeProductionHash,
11
+ hashRefKey,
12
+ } from "../plugins/client-ref-hashing.js";
13
+ import { hasUseClientDirective } from "../utils/directive-prologue.js";
14
+ import { createRangoDebugger, NS } from "../debug.js";
15
+ import { findTsFiles } from "../../build/route-types/scan-filter.js";
16
+ import type { DiscoveryState } from "./state.js";
17
+
18
+ const debug = createRangoDebugger(NS.discovery);
19
+
20
+ interface ClientUrlSsrEnvironment {
21
+ readonly runner?: {
22
+ import(id: string): Promise<Record<string, unknown>>;
23
+ };
24
+ }
25
+
26
+ interface ClientUrlProjectionServerModule {
27
+ clearClientUrlProjections(): void;
28
+ setClientUrlProjection(
29
+ referenceId: string,
30
+ projection: ClientUrlProjection,
31
+ ): void;
32
+ }
33
+
34
+ function hasDefaultExport(code: string): boolean {
35
+ let program: { body?: any[] };
36
+ try {
37
+ program = parseAst(code, { lang: "tsx" }) as { body?: any[] };
38
+ } catch {
39
+ return false;
40
+ }
41
+
42
+ for (const node of program.body ?? []) {
43
+ if (node?.type === "ExportDefaultDeclaration") return true;
44
+ if (node?.type !== "ExportNamedDeclaration") continue;
45
+ for (const specifier of node.specifiers ?? []) {
46
+ const exportedName =
47
+ specifier?.exported?.name ?? specifier?.exported?.value;
48
+ if (exportedName === "default") return true;
49
+ }
50
+ }
51
+ return false;
52
+ }
53
+
54
+ function normalizeSource(state: DiscoveryState, id: string): string {
55
+ const cleanId = id.split("?", 1)[0];
56
+ const absoluteId = isAbsolute(cleanId)
57
+ ? cleanId
58
+ : resolve(state.projectRoot, cleanId);
59
+ return normalizePath(absoluteId);
60
+ }
61
+
62
+ function referenceId(referenceKey: string): string {
63
+ return `${referenceKey}#default`;
64
+ }
65
+
66
+ function withoutReferenceQuery(reference: string): string {
67
+ const exportIndex = reference.lastIndexOf("#");
68
+ const moduleId =
69
+ exportIndex === -1 ? reference : reference.slice(0, exportIndex);
70
+ const exportName = exportIndex === -1 ? "" : reference.slice(exportIndex);
71
+ const queryIndex = moduleId.indexOf("?");
72
+ return `${queryIndex === -1 ? moduleId : moduleId.slice(0, queryIndex)}${exportName}`;
73
+ }
74
+
75
+ export function recordClientUrlsModule(
76
+ state: DiscoveryState,
77
+ code: string,
78
+ id: string,
79
+ ): void {
80
+ if (
81
+ !code.includes("clientUrls(") ||
82
+ !hasUseClientDirective(code) ||
83
+ !hasDefaultExport(code)
84
+ ) {
85
+ return;
86
+ }
87
+
88
+ const source = normalizeSource(state, id);
89
+ const projectRoot = normalizePath(resolve(state.projectRoot));
90
+ const relativeId = normalizePath(relative(projectRoot, source));
91
+ const outsideProject =
92
+ relativeId === ".." ||
93
+ relativeId.startsWith("../") ||
94
+ isAbsolute(relativeId);
95
+ const devReferenceKey = outsideProject ? `/@fs${source}` : `/${relativeId}`;
96
+
97
+ const sourceByReferenceId = (state.clientUrlSourceByReferenceId ??=
98
+ new Map());
99
+ sourceByReferenceId.set(referenceId(devReferenceKey), source);
100
+
101
+ const productionReferenceKeys = new Set([
102
+ hashRefKey(relativeId),
103
+ computeProductionHash(projectRoot, devReferenceKey),
104
+ ]);
105
+ for (const productionReferenceKey of productionReferenceKeys) {
106
+ sourceByReferenceId.set(referenceId(productionReferenceKey), source);
107
+ }
108
+ }
109
+
110
+ export function resolveClientUrlsSource(
111
+ state: DiscoveryState,
112
+ referenceId: string,
113
+ ): string | undefined {
114
+ return state.clientUrlSourceByReferenceId?.get(
115
+ withoutReferenceQuery(referenceId),
116
+ );
117
+ }
118
+
119
+ /**
120
+ * Deterministic filesystem discovery of clientUrls modules. Transform-based
121
+ * recording only sees modules that some environment actually loads — a
122
+ * clientUrls module not yet reachable from any transformed graph at discovery
123
+ * time (cold ordering, a mount added before its first import is served) would
124
+ * never be recorded and its include would fail with empty projections. Walking
125
+ * the project source (the same walk static route-type generation performs)
126
+ * makes recording independent of module-graph timing. The transform hooks
127
+ * still record too — they refresh dev HMR edits between scans.
128
+ */
129
+ export function scanForClientUrlModules(state: DiscoveryState): void {
130
+ if (!state.projectRoot) return;
131
+ for (const filePath of findTsFiles(state.projectRoot, state.scanFilter)) {
132
+ let code: string;
133
+ try {
134
+ code = readFileSync(filePath, "utf-8");
135
+ } catch {
136
+ continue;
137
+ }
138
+ recordClientUrlsModule(state, code, filePath);
139
+ }
140
+ }
141
+
142
+ function projectionError(
143
+ referenceId: string,
144
+ source: string | undefined,
145
+ message: string,
146
+ cause?: unknown,
147
+ ): Error {
148
+ const sourceDescription = source ? ` from source "${source}"` : "";
149
+ const errorMessage = `Cannot discover client URL projection for reference "${referenceId}"${sourceDescription}: ${message}`;
150
+ return cause === undefined
151
+ ? new Error(errorMessage)
152
+ : new Error(errorMessage, { cause });
153
+ }
154
+
155
+ /**
156
+ * Lenient pre-entry projection refresh. Re-serializes every RECORDED clientUrls
157
+ * module before the discovery pass imports the entry, so routers re-created by
158
+ * that import materialize against the CURRENT module contents.
159
+ *
160
+ * Scar: node-preset HMR served stale client-urls routes after a route-shape
161
+ * edit — the clientUrls module is an HMR-accepted client boundary in the rsc
162
+ * graph, and the strict registry-driven pass below only runs AFTER the entry
163
+ * import, so `.routes(reference)` materialized the previous pass's projection.
164
+ *
165
+ * Errors are deliberately swallowed per source (a module mid-edit keeps its
166
+ * last-known projection); the strict discoverClientUrlProjections() pass still
167
+ * surfaces real failures afterwards. No-ops on cold start (nothing recorded
168
+ * yet) and when the SSR runner is unavailable.
169
+ */
170
+ export async function refreshRecordedClientUrlProjections(
171
+ state: DiscoveryState,
172
+ ssrEnv: ClientUrlSsrEnvironment | undefined,
173
+ serverMod: ClientUrlProjectionServerModule,
174
+ ): Promise<void> {
175
+ const sourceByReferenceId = state.clientUrlSourceByReferenceId;
176
+ if (
177
+ !sourceByReferenceId?.size ||
178
+ typeof ssrEnv?.runner?.import !== "function"
179
+ ) {
180
+ return;
181
+ }
182
+
183
+ const referenceIdsBySource = new Map<string, string[]>();
184
+ for (const [refId, source] of sourceByReferenceId) {
185
+ const ids = referenceIdsBySource.get(source);
186
+ if (ids) {
187
+ ids.push(refId);
188
+ } else {
189
+ referenceIdsBySource.set(source, [refId]);
190
+ }
191
+ }
192
+
193
+ for (const [source, referenceIds] of referenceIdsBySource) {
194
+ let definition: unknown;
195
+ try {
196
+ definition = (await ssrEnv.runner.import(source)).default;
197
+ } catch {
198
+ continue;
199
+ }
200
+ if (
201
+ (typeof definition !== "object" && typeof definition !== "function") ||
202
+ definition === null ||
203
+ (definition as { __brand?: unknown }).__brand !== "client-urls"
204
+ ) {
205
+ continue;
206
+ }
207
+ const projection = serializeClientUrlPatterns(
208
+ definition as ClientUrlPatterns,
209
+ );
210
+ debug?.(
211
+ "pre-entry refresh %s -> [%s]",
212
+ source,
213
+ projection.routes.map((route) => route.pattern).join(", "),
214
+ );
215
+ for (const referenceId of referenceIds) {
216
+ serverMod.setClientUrlProjection(referenceId, projection);
217
+ // The eager routes-manifest virtual module REPLAYS this state map
218
+ // (clearClientUrlProjections + set) whenever it re-evaluates — and the
219
+ // watcher's gen-file write invalidates it right before the entry import,
220
+ // so a stale map here would clobber the registry install above before
221
+ // the router materializes its mount. Keep both in sync.
222
+ state.clientUrlProjectionMap?.set(referenceId, projection);
223
+ }
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Strict projection discovery over every RECORDED clientUrls module. Recorded
229
+ * modules — not router references — are the source of truth: include() mounts
230
+ * materialize lazily from the projection registry, so there is no router-level
231
+ * reference list to consult. Serializes every source before atomically
232
+ * installing the new projections (a failure preserves last-known state).
233
+ *
234
+ * A recorded source whose file no longer exists is dropped silently
235
+ * (recordClientUrlsModule never un-records, so deletions must self-heal here).
236
+ * A present-but-broken module is a hard error: it is part of the app graph.
237
+ */
238
+ export async function discoverClientUrlProjections(
239
+ state: DiscoveryState,
240
+ ssrEnv: ClientUrlSsrEnvironment | undefined,
241
+ serverMod: ClientUrlProjectionServerModule,
242
+ ): Promise<void> {
243
+ scanForClientUrlModules(state);
244
+ const sourceByReferenceId = state.clientUrlSourceByReferenceId;
245
+ if (!sourceByReferenceId?.size) {
246
+ serverMod.clearClientUrlProjections();
247
+ state.clientUrlProjectionMap = new Map();
248
+ return;
249
+ }
250
+
251
+ const referenceIdsBySource = new Map<string, string[]>();
252
+ for (const [referenceId, source] of sourceByReferenceId) {
253
+ const ids = referenceIdsBySource.get(source);
254
+ if (ids) {
255
+ ids.push(referenceId);
256
+ } else {
257
+ referenceIdsBySource.set(source, [referenceId]);
258
+ }
259
+ }
260
+
261
+ if (typeof ssrEnv?.runner?.import !== "function") {
262
+ const [source, ids] = referenceIdsBySource.entries().next().value as [
263
+ string,
264
+ string[],
265
+ ];
266
+ throw projectionError(
267
+ ids[0],
268
+ source,
269
+ "the SSR module runner is unavailable",
270
+ );
271
+ }
272
+
273
+ const nextProjections = new Map<string, ClientUrlProjection>();
274
+ const removedSources: string[] = [];
275
+ for (const [source, referenceIds] of referenceIdsBySource) {
276
+ let module: Record<string, unknown>;
277
+ try {
278
+ module = await ssrEnv.runner.import(source);
279
+ } catch (cause) {
280
+ if (!existsSync(source)) {
281
+ removedSources.push(source);
282
+ continue;
283
+ }
284
+ throw projectionError(
285
+ referenceIds[0],
286
+ source,
287
+ "failed to import the source module",
288
+ cause,
289
+ );
290
+ }
291
+ const definition = module.default;
292
+ if (
293
+ (typeof definition !== "object" && typeof definition !== "function") ||
294
+ definition === null ||
295
+ (definition as { __brand?: unknown }).__brand !== "client-urls"
296
+ ) {
297
+ throw projectionError(
298
+ referenceIds[0],
299
+ source,
300
+ 'the module default export must be created by clientUrls() and have __brand === "client-urls"',
301
+ );
302
+ }
303
+ const projection = serializeClientUrlPatterns(
304
+ definition as ClientUrlPatterns,
305
+ );
306
+ for (const referenceId of referenceIds) {
307
+ nextProjections.set(referenceId, projection);
308
+ }
309
+ }
310
+
311
+ for (const source of removedSources) {
312
+ for (const [referenceId, recorded] of sourceByReferenceId) {
313
+ if (recorded === source) sourceByReferenceId.delete(referenceId);
314
+ }
315
+ }
316
+
317
+ serverMod.clearClientUrlProjections();
318
+ for (const [id, projection] of nextProjections) {
319
+ serverMod.setClientUrlProjection(id, projection);
320
+ }
321
+ state.clientUrlProjectionMap = nextProjections;
322
+ }
@@ -21,6 +21,7 @@ import {
21
21
  // RangoContext from the runner realm) — see the runner.import below.
22
22
  import { buildPerRouterTrie } from "../../build/route-trie.js";
23
23
  import { collectFallbackClientRefs } from "../../build/collect-fallback-refs.js";
24
+ import { mergeFullManifests } from "../../build/merge-full-manifests.js";
24
25
  import { flattenLeafEntries } from "../utils/manifest-utils.js";
25
26
  import type { DiscoveryState, PrecomputedEntry } from "./state.js";
26
27
  import {
@@ -34,6 +35,10 @@ import {
34
35
  } from "./discovery-errors.js";
35
36
  import { createRangoDebugger, timed, NS } from "../debug.js";
36
37
  import { computeProductionHash } from "../plugins/client-ref-hashing.js";
38
+ import {
39
+ discoverClientUrlProjections,
40
+ refreshRecordedClientUrlProjections,
41
+ } from "./client-urls-projection.js";
37
42
 
38
43
  const debug = createRangoDebugger(NS.discovery);
39
44
 
@@ -48,9 +53,25 @@ const debug = createRangoDebugger(NS.discovery);
48
53
  export async function discoverRouters(
49
54
  state: DiscoveryState,
50
55
  rscEnv: any,
56
+ ssrEnv?: any,
51
57
  ): Promise<any> {
52
58
  if (!state.resolvedEntryPath) return;
53
59
 
60
+ // Import the router package FIRST (leaf module, no side effects on user
61
+ // code) so recorded clientUrls projections can be refreshed BEFORE the entry
62
+ // import: routers re-created by that import call `.routes(reference)` at
63
+ // module scope and materialize whatever projection is installed at that
64
+ // moment. On HMR re-discovery that must be the CURRENT module contents, not
65
+ // the previous pass's snapshot (see refreshRecordedClientUrlProjections).
66
+ const serverMod = await timed(
67
+ debug,
68
+ "inner: import @rangojs/router/server",
69
+ () => rscEnv.runner.import("@rangojs/router/server"),
70
+ );
71
+ await timed(debug, "inner: refresh recorded client URL projections", () =>
72
+ refreshRecordedClientUrlProjections(state, ssrEnv, serverMod),
73
+ );
74
+
54
75
  // Import the entry file via RSC environment.
55
76
  // For node preset: this is the router file (createRouter() registers in RouterRegistry).
56
77
  // For cloudflare preset: this is the worker entry (which imports the router).
@@ -58,12 +79,6 @@ export async function discoverRouters(
58
79
  rscEnv.runner.import(state.resolvedEntryPath),
59
80
  );
60
81
 
61
- // Import the router package to access the registry
62
- const serverMod = await timed(
63
- debug,
64
- "inner: import @rangojs/router/server",
65
- () => rscEnv.runner.import("@rangojs/router/server"),
66
- );
67
82
  let registry: Map<string, any> = serverMod.RouterRegistry;
68
83
 
69
84
  if (!registry || registry.size === 0) {
@@ -114,6 +129,10 @@ export async function discoverRouters(
114
129
  }
115
130
  }
116
131
 
132
+ await timed(debug, "inner: discover client URL projections", () =>
133
+ discoverClientUrlProjections(state, ssrEnv, serverMod),
134
+ );
135
+
117
136
  // generateManifestFull must run in the RSC runner realm: it invokes the
118
137
  // user's urlpatterns.handler() via RangoContext, consuming router instances
119
138
  // from the runner. The trie/fallback-ref builders are pure transforms over
@@ -176,20 +195,27 @@ export async function discoverRouters(
176
195
 
177
196
  const manifestGenStart = debug ? performance.now() : 0;
178
197
  for (const [id, router] of registry) {
179
- if (!router.urlpatterns || !generateManifestFull) {
198
+ if (!generateManifestFull) {
180
199
  continue;
181
200
  }
182
201
 
183
- const manifest = await generateManifestFull(
184
- router.urlpatterns,
185
- routerMountIndex,
186
- {
187
- routerId: id,
188
- ...(router.__basename ? { urlPrefix: router.__basename } : {}),
189
- ...(collectClientFallbackRef ? { collectClientFallbackRef } : {}),
190
- },
191
- );
192
- routerMountIndex++;
202
+ const mounts =
203
+ router.__urlpatternMounts ??
204
+ (router.urlpatterns ? [{ patterns: router.urlpatterns }] : []);
205
+ if (mounts.length === 0) continue;
206
+
207
+ const mountManifests = [];
208
+ for (const mount of mounts) {
209
+ mountManifests.push(
210
+ await generateManifestFull(mount.patterns, routerMountIndex, {
211
+ routerId: id,
212
+ ...(router.__basename ? { urlPrefix: router.__basename } : {}),
213
+ ...(collectClientFallbackRef ? { collectClientFallbackRef } : {}),
214
+ }),
215
+ );
216
+ routerMountIndex++;
217
+ }
218
+ const manifest = mergeFullManifests(mountManifests);
193
219
  allManifests.push({ id, manifest });
194
220
 
195
221
  // Router-level "use client" boundary defaults -> app-fallback (the
@@ -7,6 +7,7 @@
7
7
  */
8
8
 
9
9
  import type { ScanFilter } from "../../build/generate-route-types.js";
10
+ import type { ClientUrlProjection } from "../../client-urls/server-projection.js";
10
11
 
11
12
  export const VIRTUAL_ROUTES_MANIFEST_ID = "virtual:rsc-router/routes-manifest";
12
13
 
@@ -79,6 +80,11 @@ export interface ShellPrerenderCandidate {
79
80
  | { ttl?: number; swr?: number; tags?: string[]; captureTimeout?: number };
80
81
  }
81
82
 
83
+ export interface ClientUrlDiscoveryState {
84
+ clientUrlSourceByReferenceId: Map<string, string>;
85
+ clientUrlProjectionMap: Map<string, ClientUrlProjection>;
86
+ }
87
+
82
88
  export interface DiscoveryState {
83
89
  resolvedEntryPath: string | undefined;
84
90
  projectRoot: string;
@@ -109,6 +115,8 @@ export interface DiscoveryState {
109
115
  perRouterTrieMap: Map<string, any>;
110
116
  perRouterPrecomputedMap: Map<string, PrecomputedEntry[]>;
111
117
  perRouterManifestDataMap: Map<string, Record<string, string>>;
118
+ clientUrlSourceByReferenceId?: Map<string, string>;
119
+ clientUrlProjectionMap?: Map<string, ClientUrlProjection>;
112
120
 
113
121
  prerenderManifestEntries: Record<string, string> | null;
114
122
  staticManifestEntries: Record<string, string> | null;
@@ -164,7 +172,7 @@ export interface DiscoveryState {
164
172
  export function createDiscoveryState(
165
173
  entryPath: string | undefined,
166
174
  opts: PluginOptions | undefined,
167
- ): DiscoveryState {
175
+ ): DiscoveryState & ClientUrlDiscoveryState {
168
176
  return {
169
177
  resolvedEntryPath: entryPath,
170
178
  projectRoot: "",
@@ -182,6 +190,8 @@ export function createDiscoveryState(
182
190
  perRouterTrieMap: new Map(),
183
191
  perRouterPrecomputedMap: new Map(),
184
192
  perRouterManifestDataMap: new Map(),
193
+ clientUrlSourceByReferenceId: new Map(),
194
+ clientUrlProjectionMap: new Map(),
185
195
 
186
196
  prerenderManifestEntries: null,
187
197
  staticManifestEntries: null,