@rangojs/router 0.0.0-experimental.3 → 0.0.0-experimental.30

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 (297) hide show
  1. package/AGENTS.md +5 -0
  2. package/README.md +883 -4
  3. package/dist/bin/rango.js +1601 -0
  4. package/dist/vite/index.js +4655 -747
  5. package/package.json +78 -50
  6. package/skills/cache-guide/SKILL.md +262 -0
  7. package/skills/caching/SKILL.md +54 -25
  8. package/skills/composability/SKILL.md +172 -0
  9. package/skills/debug-manifest/SKILL.md +12 -8
  10. package/skills/document-cache/SKILL.md +23 -21
  11. package/skills/fonts/SKILL.md +167 -0
  12. package/skills/hooks/SKILL.md +390 -63
  13. package/skills/host-router/SKILL.md +218 -0
  14. package/skills/intercept/SKILL.md +133 -10
  15. package/skills/layout/SKILL.md +102 -5
  16. package/skills/links/SKILL.md +239 -0
  17. package/skills/loader/SKILL.md +366 -29
  18. package/skills/middleware/SKILL.md +173 -36
  19. package/skills/mime-routes/SKILL.md +128 -0
  20. package/skills/parallel/SKILL.md +80 -3
  21. package/skills/prerender/SKILL.md +643 -0
  22. package/skills/rango/SKILL.md +86 -16
  23. package/skills/response-routes/SKILL.md +411 -0
  24. package/skills/route/SKILL.md +227 -14
  25. package/skills/router-setup/SKILL.md +225 -32
  26. package/skills/tailwind/SKILL.md +129 -0
  27. package/skills/theme/SKILL.md +12 -11
  28. package/skills/typesafety/SKILL.md +401 -75
  29. package/skills/use-cache/SKILL.md +324 -0
  30. package/src/__internal.ts +10 -4
  31. package/src/bin/rango.ts +321 -0
  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 +87 -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 +20 -4
  38. package/src/browser/logging.ts +55 -0
  39. package/src/browser/merge-segment-loaders.ts +20 -12
  40. package/src/browser/navigation-bridge.ts +201 -553
  41. package/src/browser/navigation-client.ts +124 -71
  42. package/src/browser/navigation-store.ts +33 -50
  43. package/src/browser/navigation-transaction.ts +295 -0
  44. package/src/browser/network-error-handler.ts +61 -0
  45. package/src/browser/partial-update.ts +267 -317
  46. package/src/browser/prefetch/cache.ts +146 -0
  47. package/src/browser/prefetch/fetch.ts +135 -0
  48. package/src/browser/prefetch/observer.ts +65 -0
  49. package/src/browser/prefetch/policy.ts +42 -0
  50. package/src/browser/prefetch/queue.ts +88 -0
  51. package/src/browser/rango-state.ts +112 -0
  52. package/src/browser/react/Link.tsx +173 -73
  53. package/src/browser/react/NavigationProvider.tsx +138 -27
  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 +37 -0
  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 +49 -65
  65. package/src/browser/react/use-href.tsx +20 -188
  66. package/src/browser/react/use-link-status.ts +6 -5
  67. package/src/browser/react/use-mount.ts +31 -0
  68. package/src/browser/react/use-navigation.ts +27 -78
  69. package/src/browser/react/use-params.ts +65 -0
  70. package/src/browser/react/use-pathname.ts +47 -0
  71. package/src/browser/react/use-router.ts +63 -0
  72. package/src/browser/react/use-search-params.ts +56 -0
  73. package/src/browser/react/use-segments.ts +80 -97
  74. package/src/browser/response-adapter.ts +73 -0
  75. package/src/browser/rsc-router.tsx +111 -26
  76. package/src/browser/scroll-restoration.ts +92 -16
  77. package/src/browser/segment-reconciler.ts +216 -0
  78. package/src/browser/segment-structure-assert.ts +83 -0
  79. package/src/browser/server-action-bridge.ts +504 -584
  80. package/src/browser/shallow.ts +6 -1
  81. package/src/browser/types.ts +92 -57
  82. package/src/browser/validate-redirect-origin.ts +29 -0
  83. package/src/build/generate-manifest.ts +438 -0
  84. package/src/build/generate-route-types.ts +36 -0
  85. package/src/build/index.ts +35 -0
  86. package/src/build/route-trie.ts +265 -0
  87. package/src/build/route-types/ast-helpers.ts +25 -0
  88. package/src/build/route-types/ast-route-extraction.ts +98 -0
  89. package/src/build/route-types/codegen.ts +102 -0
  90. package/src/build/route-types/include-resolution.ts +411 -0
  91. package/src/build/route-types/param-extraction.ts +48 -0
  92. package/src/build/route-types/per-module-writer.ts +128 -0
  93. package/src/build/route-types/router-processing.ts +469 -0
  94. package/src/build/route-types/scan-filter.ts +78 -0
  95. package/src/build/runtime-discovery.ts +231 -0
  96. package/src/cache/background-task.ts +34 -0
  97. package/src/cache/cache-key-utils.ts +44 -0
  98. package/src/cache/cache-policy.ts +125 -0
  99. package/src/cache/cache-runtime.ts +338 -0
  100. package/src/cache/cache-scope.ts +120 -303
  101. package/src/cache/cf/cf-cache-store.ts +119 -7
  102. package/src/cache/cf/index.ts +8 -2
  103. package/src/cache/document-cache.ts +101 -72
  104. package/src/cache/handle-capture.ts +81 -0
  105. package/src/cache/handle-snapshot.ts +41 -0
  106. package/src/cache/index.ts +0 -15
  107. package/src/cache/memory-segment-store.ts +191 -13
  108. package/src/cache/profile-registry.ts +73 -0
  109. package/src/cache/read-through-swr.ts +134 -0
  110. package/src/cache/segment-codec.ts +256 -0
  111. package/src/cache/taint.ts +98 -0
  112. package/src/cache/types.ts +72 -122
  113. package/src/client.rsc.tsx +10 -15
  114. package/src/client.tsx +114 -135
  115. package/src/component-utils.ts +4 -4
  116. package/src/components/DefaultDocument.tsx +5 -1
  117. package/src/context-var.ts +86 -0
  118. package/src/debug.ts +17 -7
  119. package/src/errors.ts +108 -2
  120. package/src/handle.ts +34 -19
  121. package/src/handles/MetaTags.tsx +73 -20
  122. package/src/handles/meta.ts +30 -13
  123. package/src/host/cookie-handler.ts +165 -0
  124. package/src/host/errors.ts +97 -0
  125. package/src/host/index.ts +53 -0
  126. package/src/host/pattern-matcher.ts +214 -0
  127. package/src/host/router.ts +352 -0
  128. package/src/host/testing.ts +79 -0
  129. package/src/host/types.ts +146 -0
  130. package/src/host/utils.ts +25 -0
  131. package/src/href-client.ts +135 -49
  132. package/src/index.rsc.ts +182 -17
  133. package/src/index.ts +238 -24
  134. package/src/internal-debug.ts +11 -0
  135. package/src/loader.rsc.ts +27 -142
  136. package/src/loader.ts +27 -10
  137. package/src/network-error-thrower.tsx +3 -1
  138. package/src/outlet-provider.tsx +45 -0
  139. package/src/prerender/param-hash.ts +37 -0
  140. package/src/prerender/store.ts +185 -0
  141. package/src/prerender.ts +463 -0
  142. package/src/reverse.ts +330 -0
  143. package/src/root-error-boundary.tsx +41 -29
  144. package/src/route-content-wrapper.tsx +9 -11
  145. package/src/route-definition/dsl-helpers.ts +934 -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 -1388
  151. package/src/route-map-builder.ts +241 -112
  152. package/src/route-name.ts +53 -0
  153. package/src/route-types.ts +70 -9
  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 +158 -0
  158. package/src/router/handler-context.ts +371 -81
  159. package/src/router/intercept-resolution.ts +395 -0
  160. package/src/router/lazy-includes.ts +234 -0
  161. package/src/router/loader-resolution.ts +215 -122
  162. package/src/router/logging.ts +248 -0
  163. package/src/router/manifest.ts +155 -32
  164. package/src/router/match-api.ts +620 -0
  165. package/src/router/match-context.ts +5 -3
  166. package/src/router/match-handlers.ts +440 -0
  167. package/src/router/match-middleware/background-revalidation.ts +80 -93
  168. package/src/router/match-middleware/cache-lookup.ts +382 -9
  169. package/src/router/match-middleware/cache-store.ts +51 -22
  170. package/src/router/match-middleware/intercept-resolution.ts +55 -17
  171. package/src/router/match-middleware/segment-resolution.ts +24 -6
  172. package/src/router/match-pipelines.ts +10 -45
  173. package/src/router/match-result.ts +34 -29
  174. package/src/router/metrics.ts +235 -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 +324 -367
  178. package/src/router/pattern-matching.ts +321 -30
  179. package/src/router/prerender-match.ts +400 -0
  180. package/src/router/preview-match.ts +170 -0
  181. package/src/router/revalidation.ts +137 -38
  182. package/src/router/router-context.ts +36 -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 +570 -0
  187. package/src/router/segment-resolution/helpers.ts +263 -0
  188. package/src/router/segment-resolution/loader-cache.ts +198 -0
  189. package/src/router/segment-resolution/revalidation.ts +1241 -0
  190. package/src/router/segment-resolution/static-store.ts +67 -0
  191. package/src/router/segment-resolution.ts +21 -0
  192. package/src/router/segment-wrappers.ts +289 -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 +239 -0
  197. package/src/router/types.ts +77 -3
  198. package/src/router.ts +688 -3656
  199. package/src/rsc/handler-context.ts +45 -0
  200. package/src/rsc/handler.ts +786 -760
  201. package/src/rsc/helpers.ts +140 -6
  202. package/src/rsc/index.ts +5 -25
  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 +235 -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 +40 -14
  215. package/src/search-params.ts +230 -0
  216. package/src/segment-system.tsx +57 -61
  217. package/src/server/context.ts +202 -51
  218. package/src/server/cookie-store.ts +190 -0
  219. package/src/server/fetchable-loader-store.ts +37 -0
  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 +422 -70
  223. package/src/server.ts +36 -120
  224. package/src/ssr/index.tsx +157 -26
  225. package/src/static-handler.ts +114 -0
  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 +687 -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 +102 -0
  241. package/src/types/segments.ts +148 -0
  242. package/src/types.ts +1 -1577
  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 -726
  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 +110 -0
  259. package/src/vite/discovery/virtual-module-codegen.ts +203 -0
  260. package/src/vite/index.ts +11 -782
  261. package/src/vite/plugin-types.ts +131 -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 -51
  266. package/src/vite/plugins/expose-id-utils.ts +287 -0
  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 +254 -0
  277. package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +29 -15
  278. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  279. package/src/vite/rango.ts +510 -0
  280. package/src/vite/router-discovery.ts +785 -0
  281. package/src/vite/utils/ast-handler-extract.ts +517 -0
  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 -3
  289. package/src/browser/lru-cache.ts +0 -69
  290. package/src/browser/request-controller.ts +0 -164
  291. package/src/cache/memory-store.ts +0 -253
  292. package/src/href-context.ts +0 -33
  293. package/src/href.ts +0 -255
  294. package/src/vite/expose-handle-id.ts +0 -209
  295. package/src/vite/expose-loader-id.ts +0 -357
  296. package/src/vite/expose-location-state-id.ts +0 -177
  297. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
@@ -1,1388 +1 @@
1
- import type { ReactNode } from "react";
2
- import type {
3
- PartialCacheOptions,
4
- DefaultEnv,
5
- ErrorBoundaryHandler,
6
- ExtractRouteParams,
7
- Handler,
8
- HandlersForRouteMap,
9
- LoaderDefinition,
10
- LoaderFn,
11
- MiddlewareFn,
12
- NotFoundBoundaryHandler,
13
- ResolvedRouteMap,
14
- RouteConfig,
15
- RouteDefinition,
16
- RouteDefinitionOptions,
17
- ShouldRevalidateFn,
18
- TrailingSlashMode,
19
- } from "./types.js";
20
- import {
21
- getContext,
22
- getNamePrefix,
23
- type EntryData,
24
- type InterceptEntry,
25
- type InterceptWhenFn,
26
- type InterceptSelectorContext,
27
- } from "./server/context";
28
- import { invariant } from "./errors";
29
- import RootLayout from "./server/root-layout";
30
- import type {
31
- AllUseItems,
32
- LayoutItem,
33
- RouteItem,
34
- ParallelItem,
35
- InterceptItem,
36
- MiddlewareItem,
37
- RevalidateItem,
38
- LoaderItem,
39
- LoadingItem,
40
- ErrorBoundaryItem,
41
- NotFoundBoundaryItem,
42
- LayoutUseItem,
43
- RouteUseItem,
44
- ParallelUseItem,
45
- InterceptUseItem,
46
- LoaderUseItem,
47
- WhenItem,
48
- CacheItem,
49
- } from "./route-types.js";
50
- // const __DEV__ = import.meta.MODE === "development";
51
-
52
- /**
53
- * Result of route() function with paths and trailing slash config
54
- */
55
- export interface RouteDefinitionResult<T extends RouteDefinition> {
56
- routes: ResolvedRouteMap<T>;
57
- trailingSlash: Record<string, TrailingSlashMode>;
58
- }
59
-
60
- /**
61
- * Check if a value is a RouteConfig object
62
- */
63
- function isRouteConfig(value: unknown): value is RouteConfig {
64
- return (
65
- typeof value === "object" &&
66
- value !== null &&
67
- "path" in value &&
68
- typeof (value as RouteConfig).path === "string"
69
- );
70
- }
71
-
72
- /**
73
- * Define routes with optional trailing slash configuration
74
- *
75
- * @example
76
- * ```typescript
77
- * // Simple string paths
78
- * const routes = route({
79
- * blog: "/blog",
80
- * post: "/blog/:id",
81
- * });
82
- *
83
- * // With trailing slash config
84
- * const routes = route({
85
- * blog: "/blog",
86
- * api: { path: "/api", trailingSlash: "ignore" },
87
- * }, { trailingSlash: "never" }); // global default
88
- * ```
89
- */
90
- export function route<const T extends RouteDefinition>(
91
- input: T,
92
- options?: RouteDefinitionOptions
93
- ): ResolvedRouteMap<T> & {
94
- __trailingSlash?: Record<string, TrailingSlashMode>;
95
- } {
96
- const trailingSlash: Record<string, TrailingSlashMode> = {};
97
- const routes = flattenRoutes(
98
- input as RouteDefinition,
99
- "",
100
- trailingSlash,
101
- options?.trailingSlash
102
- );
103
-
104
- // Attach trailing slash config as a non-enumerable property
105
- // This keeps backwards compatibility while passing the config through
106
- const result = routes as ResolvedRouteMap<T> & {
107
- __trailingSlash?: Record<string, TrailingSlashMode>;
108
- };
109
- if (Object.keys(trailingSlash).length > 0) {
110
- Object.defineProperty(result, "__trailingSlash", {
111
- value: trailingSlash,
112
- enumerable: false,
113
- writable: false,
114
- });
115
- }
116
-
117
- return result;
118
- }
119
-
120
- /**
121
- * Flatten nested route definitions
122
- */
123
- function flattenRoutes(
124
- routes: RouteDefinition,
125
- prefix: string,
126
- trailingSlashConfig: Record<string, TrailingSlashMode>,
127
- defaultTrailingSlash?: TrailingSlashMode
128
- ): Record<string, string> {
129
- const flattened: Record<string, string> = {};
130
-
131
- for (const [key, value] of Object.entries(routes)) {
132
- const fullKey = prefix + key;
133
-
134
- if (typeof value === "string") {
135
- // Direct route pattern - include prefix
136
- flattened[fullKey] = value;
137
- // Apply default trailing slash if set
138
- if (defaultTrailingSlash) {
139
- trailingSlashConfig[fullKey] = defaultTrailingSlash;
140
- }
141
- } else if (isRouteConfig(value)) {
142
- // Route config object with path and optional trailingSlash
143
- flattened[fullKey] = value.path;
144
- // Use route-specific config or fall back to default
145
- const mode = value.trailingSlash ?? defaultTrailingSlash;
146
- if (mode) {
147
- trailingSlashConfig[fullKey] = mode;
148
- }
149
- } else {
150
- // Nested routes - flatten recursively
151
- const nested = flattenRoutes(
152
- value,
153
- `${fullKey}.`,
154
- trailingSlashConfig,
155
- defaultTrailingSlash
156
- );
157
- Object.assign(flattened, nested);
158
- }
159
- }
160
-
161
- return flattened;
162
- }
163
-
164
- // Type definitions moved to route-types.ts to avoid bundling in client code
165
- // Re-export for backward compatibility within this module
166
- export type {
167
- AllUseItems,
168
- LayoutItem,
169
- RouteItem,
170
- ParallelItem,
171
- InterceptItem,
172
- MiddlewareItem,
173
- RevalidateItem,
174
- LoaderItem,
175
- ErrorBoundaryItem,
176
- NotFoundBoundaryItem,
177
- LayoutUseItem,
178
- RouteUseItem,
179
- ParallelUseItem,
180
- InterceptUseItem,
181
- WhenItem,
182
- CacheItem,
183
- } from "./route-types.js";
184
-
185
- // Re-export intercept selector types for use in handlers
186
- export type {
187
- InterceptSelectorContext,
188
- InterceptSegmentsState,
189
- InterceptWhenFn,
190
- } from "./server/context";
191
-
192
- /**
193
- * Route helpers provided by map()
194
- * These are the only typed helpers users interact with
195
- */
196
- export type RouteHelpers<T extends RouteDefinition, TEnv> = {
197
- /**
198
- * Define a route handler for a specific route pattern
199
- * ```typescript
200
- * route("products.detail", async (ctx) => {
201
- * const product = await getProduct(ctx.params.slug);
202
- * return <ProductPage product={product} />;
203
- * })
204
- *
205
- * // With nested use() for middleware, loaders, etc.
206
- * route("products.detail", ProductHandler, () => [
207
- * loader(ProductLoader),
208
- * loading(<ProductSkeleton />),
209
- * ])
210
- * ```
211
- * @param name - Route name matching a key from route definitions
212
- * @param handler - Async function that returns JSX for the route
213
- * @param use - Optional callback returning middleware, loaders, loading, etc.
214
- */
215
- route: <K extends keyof ResolvedRouteMap<T> & string>(
216
- name: K,
217
- handler: Handler<ExtractRouteParams<T, K & string>, TEnv>,
218
- use?: () => RouteUseItem[]
219
- ) => RouteItem;
220
- /**
221
- * Define a layout that wraps child routes
222
- * ```typescript
223
- * layout(<AppShell />, () => [
224
- * route("home", HomePage),
225
- * route("about", AboutPage),
226
- * ])
227
- *
228
- * // With dynamic layout handler
229
- * layout(async (ctx) => {
230
- * const user = ctx.get("user");
231
- * return <DashboardShell user={user} />;
232
- * }, () => [
233
- * middleware(authMiddleware),
234
- * route("dashboard", DashboardPage),
235
- * ])
236
- * ```
237
- * @param component - Static JSX or async handler for the layout
238
- * @param use - Callback returning child routes, middleware, loaders, etc.
239
- */
240
- layout: (
241
- component: ReactNode | Handler<any, TEnv>,
242
- use?: () => LayoutUseItem[]
243
- ) => LayoutItem;
244
- /**
245
- * Define parallel routes that render simultaneously in named slots
246
- * ```typescript
247
- * parallel({
248
- * "@sidebar": <Sidebar />,
249
- * "@main": async (ctx) => <MainContent data={ctx.use(DataLoader)} />,
250
- * })
251
- *
252
- * // With loaders and loading states
253
- * parallel({
254
- * "@analytics": AnalyticsPanel,
255
- * "@metrics": MetricsPanel,
256
- * }, () => [
257
- * loader(DashboardLoader),
258
- * loading(<DashboardSkeleton />),
259
- * ])
260
- * ```
261
- * @param slots - Object with slot names (prefixed with @) mapped to handlers
262
- * @param use - Optional callback for loaders, loading, revalidate, etc.
263
- */
264
- parallel: <
265
- TSlots extends Record<`@${string}`, Handler<any, TEnv> | ReactNode>,
266
- >(
267
- slots: TSlots,
268
- use?: () => ParallelUseItem[]
269
- ) => ParallelItem;
270
- /**
271
- * Define an intercepting route for soft navigation
272
- *
273
- * When soft-navigating to the target route from within the current layout,
274
- * the intercept handler renders in the named slot instead of the route's
275
- * default handler. Direct navigation uses the route's handler.
276
- *
277
- * ```typescript
278
- * // In a layout - intercept "card" route as modal
279
- * layout(<KanbanLayout />, () => [
280
- * intercept("@modal", "card", () => <CardModal />),
281
- * ])
282
- *
283
- * // With loaders and revalidation
284
- * intercept("@modal", "card", () => <CardModal />, () => [
285
- * loader(CardModalLoader),
286
- * revalidate(() => false),
287
- * ])
288
- * ```
289
- * @param slotName - Named slot (prefixed with @) where intercept renders
290
- * @param routeName - Route name to intercept
291
- * @param handler - Component or handler for intercepted render
292
- * @param use - Optional callback for loaders, middleware, revalidate, etc.
293
- */
294
- intercept: <K extends keyof ResolvedRouteMap<T> & string>(
295
- slotName: `@${string}`,
296
- routeName: K,
297
- handler: ReactNode | Handler<ExtractRouteParams<T, K>, TEnv>,
298
- use?: () => InterceptUseItem[]
299
- ) => InterceptItem;
300
- /**
301
- * Attach middleware to the current route/layout
302
- * ```typescript
303
- * middleware(async (ctx, next) => {
304
- * const session = await getSession(ctx.request);
305
- * if (!session) return redirect("/login");
306
- * ctx.set("user", session.user);
307
- * next();
308
- * })
309
- *
310
- * // Chain multiple middleware
311
- * middleware(authMiddleware, loggingMiddleware, rateLimitMiddleware)
312
- * ```
313
- * @param fns - One or more middleware functions to execute in order
314
- */
315
- middleware: (...fns: MiddlewareFn<TEnv>[]) => MiddlewareItem;
316
- /**
317
- * Control when a segment should revalidate during navigation
318
- * ```typescript
319
- * // Revalidate when params change
320
- * revalidate(({ currentParams, nextParams }) =>
321
- * currentParams.slug !== nextParams.slug
322
- * )
323
- *
324
- * // Revalidate after specific actions (actionId format: "path/to/file.ts#exportName")
325
- * revalidate(({ actionId }) =>
326
- * actionId?.includes("Cart") ?? false
327
- * )
328
- *
329
- * // Soft decision (suggest but allow override)
330
- * revalidate(({ defaultShouldRevalidate }) =>
331
- * ({ defaultShouldRevalidate: true })
332
- * )
333
- * ```
334
- * @param fn - Function that returns boolean (hard) or { defaultShouldRevalidate } (soft)
335
- */
336
- revalidate: (fn: ShouldRevalidateFn<any, TEnv>) => RevalidateItem;
337
- /**
338
- * Attach a data loader to the current route/layout
339
- * ```typescript
340
- * loader(ProductLoader)
341
- *
342
- * // With loader-specific revalidation (match by file or export name)
343
- * loader(CartLoader, () => [
344
- * revalidate(({ actionId }) => actionId?.includes("Cart") ?? false),
345
- * ])
346
- *
347
- * // Access loader data in handlers via ctx.use()
348
- * route("products.detail", async (ctx) => {
349
- * const product = await ctx.use(ProductLoader);
350
- * return <ProductPage product={product} />;
351
- * })
352
- * ```
353
- * @param loaderDef - Loader created with createLoader()
354
- * @param use - Optional callback for loader-specific revalidation rules
355
- */
356
- loader: <TData>(
357
- loaderDef: LoaderDefinition<TData>,
358
- use?: () => LoaderUseItem[]
359
- ) => LoaderItem;
360
- /**
361
- * Attach a loading component to the current route/layout
362
- * ```typescript
363
- * // Show loading on all requests (including SSR)
364
- * loading(<Skeleton />)
365
- *
366
- * // Skip loading on SSR, only show on client navigation
367
- * loading(<Skeleton />, { ssr: false })
368
- * ```
369
- * @param component - The loading UI to show during navigation
370
- * @param options - Configuration options
371
- * @param options.ssr - If false, skip showing loading on document requests (SSR)
372
- */
373
- loading: (component: ReactNode, options?: { ssr?: boolean }) => LoadingItem;
374
- /**
375
- * Attach an error boundary to catch errors in this segment and children
376
- * ```typescript
377
- * errorBoundary(<ErrorFallback />)
378
- *
379
- * // With dynamic error handler
380
- * errorBoundary(({ error, reset }) => (
381
- * <div>
382
- * <h2>Something went wrong</h2>
383
- * <p>{error.message}</p>
384
- * <button onClick={reset}>Try again</button>
385
- * </div>
386
- * ))
387
- * ```
388
- * @param fallback - Static JSX or handler receiving error info and reset function
389
- */
390
- errorBoundary: (
391
- fallback: ReactNode | ErrorBoundaryHandler
392
- ) => ErrorBoundaryItem;
393
- /**
394
- * Attach a not-found boundary to handle notFound() calls in this segment
395
- * ```typescript
396
- * notFoundBoundary(<ProductNotFound />)
397
- *
398
- * // With dynamic handler
399
- * notFoundBoundary(({ notFound }) => (
400
- * <div>
401
- * <h2>{notFound.message}</h2>
402
- * <a href="/products">Browse all products</a>
403
- * </div>
404
- * ))
405
- * ```
406
- * @param fallback - Static JSX or handler receiving not-found info
407
- */
408
- notFoundBoundary: (
409
- fallback: ReactNode | NotFoundBoundaryHandler
410
- ) => NotFoundBoundaryItem;
411
- /**
412
- * Define a condition for when an intercept should activate
413
- *
414
- * Only valid inside intercept() use() callback. When multiple when() calls
415
- * are present, ALL must return true for the intercept to activate.
416
- * If no when() is defined, the intercept always activates on soft navigation.
417
- *
418
- * Context properties:
419
- * - `from` - Source URL (where user is navigating from)
420
- * - `to` - Destination URL (where user is navigating to)
421
- * - `params` - Matched route params
422
- * - `segments` - Client's current segments with `path` and `ids`
423
- *
424
- * ```typescript
425
- * // Only intercept when coming from the board page
426
- * intercept("@modal", "card", <CardModal />, () => [
427
- * when(({ from }) => from.pathname.startsWith("/board")),
428
- * loader(CardDetailLoader),
429
- * ])
430
- *
431
- * // Use segments to check current route context
432
- * intercept("@modal", "card", <CardModal />, () => [
433
- * when(({ segments }) => segments.path[0] === "kanban"),
434
- * ])
435
- *
436
- * // Multiple conditions (AND logic)
437
- * intercept("@modal", "card", <CardModal />, () => [
438
- * when(({ from }) => from.pathname.startsWith("/board")),
439
- * when(({ segments }) => segments.ids.includes("kanban-layout")),
440
- * ])
441
- * ```
442
- * @param fn - Selector function receiving navigation context, returns boolean
443
- */
444
- when: (fn: InterceptWhenFn) => WhenItem;
445
- /**
446
- * Define cache configuration for segments
447
- *
448
- * Creates a cache boundary that applies to all children unless overridden.
449
- * Cache config inherits down the route tree like middleware wrapping.
450
- *
451
- * When ttl is not specified, uses store defaults (explicit store first,
452
- * then app-level store). When store is not specified, uses app-level store.
453
- *
454
- * Note: Loaders are NOT cached by default. Use cache() inside loader()
455
- * to explicitly opt-in to loader caching.
456
- *
457
- * ```typescript
458
- * // Using app-level defaults (ttl inherited from store.defaults)
459
- * cache(() => [
460
- * layout(<BlogLayout />), // cached with default TTL
461
- * route("post/:slug"), // cached with default TTL
462
- * ])
463
- *
464
- * // Cache all segments with explicit 60s TTL
465
- * cache({ ttl: 60 }, () => [
466
- * layout(<BlogLayout />), // cached
467
- * route("post/:slug"), // cached
468
- * ])
469
- *
470
- * // With stale-while-revalidate
471
- * cache({ ttl: 60, swr: 300 }, () => [
472
- * route("product/:id"),
473
- * ])
474
- *
475
- * // Override for specific section
476
- * cache({ ttl: 60 }, () => [
477
- * layout(<RootLayout />),
478
- * cache({ ttl: 300 }, () => [
479
- * route("static-page"), // longer TTL
480
- * ]),
481
- * cache(false, () => [
482
- * route("admin"), // not cached
483
- * ]),
484
- * ])
485
- *
486
- * // Use different store for specific routes
487
- * cache({ store: kvStore, ttl: 3600 }, () => [
488
- * route("archive/:year"), // uses KV store
489
- * ])
490
- *
491
- * // Opt-in loader caching
492
- * route("product/:id", ProductHandler, () => [
493
- * loader(ProductLoader), // NOT cached (default)
494
- * loader(StaticMetadata, () => [
495
- * cache({ ttl: 3600 }), // cached for 1 hour
496
- * ]),
497
- * ])
498
- * ```
499
- * @param optionsOrChildren - Cache options, false to disable, or children callback
500
- * @param children - Optional callback returning child segments (when first arg is options)
501
- */
502
- cache: {
503
- (): CacheItem;
504
- (children: () => AllUseItems[]): CacheItem;
505
- (
506
- options: PartialCacheOptions | false,
507
- use?: () => AllUseItems[]
508
- ): CacheItem;
509
- };
510
- };
511
-
512
- /**
513
- * Check if an item contains routes (directly or inside nested structures like cache).
514
- * Used to determine if a layout or cache should be treated as an orphan.
515
- */
516
- const hasRoutesInItem = (item: AllUseItems): boolean => {
517
- if (item.type === "route") return true;
518
- if (item.type === "cache" && item.uses) {
519
- return item.uses.some((child) => hasRoutesInItem(child));
520
- }
521
- if (item.type === "layout" && item.uses) {
522
- return item.uses.some((child) => hasRoutesInItem(child));
523
- }
524
- return false;
525
- };
526
-
527
- const revalidate: RouteHelpers<any, any>["revalidate"] = (fn) => {
528
- const ctx = getContext().getStore();
529
- if (!ctx) throw new Error("revalidate() must be called inside map()");
530
-
531
- // Attach to last entry in stack
532
- const parent = ctx.parent;
533
- if (!parent || !("revalidate" in parent)) {
534
- invariant(false, "No parent entry available for revalidate()");
535
- }
536
- const name = `$${getContext().getNextIndex("revalidate")}`;
537
- parent.revalidate.push(fn);
538
- return { name, type: "revalidate" } as RevalidateItem;
539
- };
540
-
541
- /**
542
- * Error boundary helper - attaches an error fallback to the current entry
543
- *
544
- * When an error occurs during rendering of this segment or its children,
545
- * the fallback will be rendered instead. The fallback can be:
546
- * - A static ReactNode (e.g., <ErrorPage />)
547
- * - A handler function that receives error info and reset function
548
- *
549
- * Error boundaries catch errors from:
550
- * - Middleware execution
551
- * - Loader execution
552
- * - Handler/component rendering
553
- *
554
- * @example
555
- * ```typescript
556
- * layout(<ShopLayout />, () => [
557
- * errorBoundary(<ShopErrorFallback />),
558
- * route("products.detail", ProductDetail),
559
- * ])
560
- *
561
- * // Or with handler for dynamic error UI:
562
- * route("products.detail", ProductDetail, () => [
563
- * errorBoundary(({ error, reset }) => (
564
- * <div>
565
- * <h2>Product failed to load</h2>
566
- * <p>{error.message}</p>
567
- * <button onClick={reset}>Retry</button>
568
- * </div>
569
- * )),
570
- * ])
571
- * ```
572
- */
573
- const errorBoundary: RouteHelpers<any, any>["errorBoundary"] = (fallback) => {
574
- const ctx = getContext().getStore();
575
- if (!ctx) throw new Error("errorBoundary() must be called inside map()");
576
-
577
- // Attach to parent entry in stack
578
- const parent = ctx.parent;
579
- if (!parent || !("errorBoundary" in parent)) {
580
- invariant(false, "No parent entry available for errorBoundary()");
581
- }
582
- const name = `$${getContext().getNextIndex("errorBoundary")}`;
583
- parent.errorBoundary.push(fallback);
584
- return { name, type: "errorBoundary" } as ErrorBoundaryItem;
585
- };
586
-
587
- /**
588
- * NotFound boundary helper - attaches a not-found fallback to the current entry
589
- *
590
- * When a DataNotFoundError is thrown (via notFound()) during rendering of this
591
- * segment or its children, the fallback will be rendered instead. The fallback can be:
592
- * - A static ReactNode (e.g., <ProductNotFound />)
593
- * - A handler function that receives not found info
594
- *
595
- * NotFound boundaries catch DataNotFoundError from:
596
- * - Loader execution
597
- * - Handler/component rendering
598
- *
599
- * @example
600
- * ```typescript
601
- * layout(<ShopLayout />, () => [
602
- * notFoundBoundary(<ProductNotFound />),
603
- * route("products.detail", ProductDetail),
604
- * ])
605
- *
606
- * // Or with handler for dynamic not found UI:
607
- * route("products.detail", ProductDetail, () => [
608
- * notFoundBoundary(({ notFound }) => (
609
- * <div>
610
- * <h2>Product not found</h2>
611
- * <p>{notFound.message}</p>
612
- * <a href="/products">Browse all products</a>
613
- * </div>
614
- * )),
615
- * ])
616
- * ```
617
- */
618
- const notFoundBoundary: RouteHelpers<any, any>["notFoundBoundary"] = (
619
- fallback
620
- ) => {
621
- const ctx = getContext().getStore();
622
- if (!ctx) throw new Error("notFoundBoundary() must be called inside map()");
623
-
624
- // Attach to parent entry in stack
625
- const parent = ctx.parent;
626
- if (!parent || !("notFoundBoundary" in parent)) {
627
- invariant(false, "No parent entry available for notFoundBoundary()");
628
- }
629
- const name = `$${getContext().getNextIndex("notFoundBoundary")}`;
630
- parent.notFoundBoundary.push(fallback);
631
- return { name, type: "notFoundBoundary" } as NotFoundBoundaryItem;
632
- };
633
-
634
- /**
635
- * When helper - defines a condition for intercept activation
636
- *
637
- * Only valid inside intercept() use() callback. The when() function
638
- * is captured by the intercept and stored in its `when` array.
639
- * During soft navigation, all when() conditions must return true
640
- * for the intercept to activate.
641
- */
642
- const when: RouteHelpers<any, any>["when"] = (fn) => {
643
- const ctx = getContext().getStore();
644
- if (!ctx) throw new Error("when() must be called inside intercept()");
645
-
646
- // The when() function needs to be captured by the intercept's tempParent
647
- // which should have a `when` array. If not present, we're not inside intercept()
648
- const parent = ctx.parent as any;
649
- if (!parent || !("when" in parent)) {
650
- invariant(
651
- false,
652
- "when() can only be used inside intercept() use() callback"
653
- );
654
- }
655
-
656
- const name = `$${getContext().getNextIndex("when")}`;
657
- parent.when.push(fn);
658
- return { name, type: "when" } as WhenItem;
659
- };
660
-
661
- /**
662
- * Cache helper - defines caching configuration for segments
663
- *
664
- * Creates a cache boundary that applies to all children unless overridden.
665
- * When used without children, attaches cache config to the parent entry
666
- * (e.g., for loader-specific caching).
667
- *
668
- * Supports three call signatures:
669
- * - cache() - no args, uses app-level defaults (for loader caching)
670
- * - cache(() => [...]) - wraps children with app-level defaults
671
- * - cache({ ttl: 60 }, () => [...]) - with explicit options
672
- */
673
- const cache: RouteHelpers<any, any>["cache"] = (
674
- optionsOrChildren?: PartialCacheOptions | false | (() => AllUseItems[]),
675
- maybeChildren?: () => AllUseItems[]
676
- ) => {
677
- const store = getContext();
678
- const ctx = store.getStore();
679
- if (!ctx) throw new Error("cache() must be called inside map()");
680
-
681
- // Handle overloaded signature: cache(), cache(children), or cache(options, children)
682
- let options: PartialCacheOptions | false;
683
- let children: (() => AllUseItems[]) | undefined;
684
-
685
- if (optionsOrChildren === undefined) {
686
- // cache() - no args, use defaults
687
- options = {};
688
- children = undefined;
689
- } else if (typeof optionsOrChildren === "function") {
690
- // cache(() => [...]) - use empty options (will use defaults)
691
- options = {};
692
- children = optionsOrChildren;
693
- } else {
694
- // cache(options, children) - explicit options
695
- options = optionsOrChildren;
696
- children = maybeChildren;
697
- }
698
-
699
- const name = `$${store.getNextIndex("cache")}`;
700
- const cacheConfig = { options };
701
-
702
- // If no children, attach cache config to current parent (for loader caching)
703
- if (!children) {
704
- // Check if we're inside a loader() use() callback
705
- const parent = ctx.parent as any;
706
- if (parent && "cache" in parent) {
707
- // Direct assignment to loader entry's cache field
708
- parent.cache = cacheConfig;
709
- } else if (parent) {
710
- // Attach to parent entry (layout/route/parallel)
711
- parent.cache = cacheConfig;
712
- }
713
- return { name, type: "cache" } as CacheItem;
714
- }
715
-
716
- // With children: create a cache entry (like layout with caching semantics)
717
- const namespace = `${ctx.namespace}.${store.getNextIndex("cache")}`;
718
-
719
- const entry = {
720
- id: namespace,
721
- shortCode: store.getShortCode("cache"),
722
- type: "cache",
723
- parent: ctx.parent,
724
- cache: cacheConfig,
725
- // Cache entries render like layouts (with Outlet as default handler)
726
- handler: RootLayout, // RootLayout just renders <Outlet />
727
- middleware: [],
728
- revalidate: [],
729
- errorBoundary: [],
730
- notFoundBoundary: [],
731
- layout: [],
732
- parallel: [],
733
- intercept: [],
734
- loader: [],
735
- } as EntryData;
736
-
737
- // Run children with cache entry as parent
738
- const result = store.run(namespace, entry, children);
739
-
740
- invariant(
741
- Array.isArray(result) && result.every((item) => isValidUseItem(item)),
742
- `cache() children callback must return an array of use items [${namespace}]`
743
- );
744
-
745
- // Check if this cache has routes (including nested caches/layouts)
746
- const hasRoutes =
747
- result &&
748
- Array.isArray(result) &&
749
- result.some((item) => hasRoutesInItem(item));
750
-
751
- if (!hasRoutes) {
752
- const parent = ctx.parent;
753
- if (parent && "layout" in parent) {
754
- // Attach to parent's layout array (cache entries are structural like layouts)
755
- entry.parent = null;
756
- parent.layout.push(entry);
757
- }
758
- }
759
-
760
- return { name: namespace, type: "cache", uses: result } as CacheItem;
761
- };
762
-
763
- const middleware: RouteHelpers<any, any>["middleware"] = (...fn) => {
764
- const ctx = getContext().getStore();
765
- if (!ctx) throw new Error("middleware() must be called inside map()");
766
-
767
- // Attach to last entry in stack
768
- const parent = ctx.parent;
769
- if (!parent || !("middleware" in parent)) {
770
- invariant(false, "No parent entry available for middleware()");
771
- }
772
- const name = `$${getContext().getNextIndex("middleware")}`;
773
- parent.middleware.push(...fn);
774
- return { name, type: "middleware" } as MiddlewareItem;
775
- };
776
-
777
- const parallel: RouteHelpers<any, any>["parallel"] = (slots, use) => {
778
- const store = getContext();
779
- const ctx = store.getStore();
780
- if (!ctx) throw new Error("parallel() must be called inside map()");
781
-
782
- if (!ctx.parent || !ctx.parent?.parallel) {
783
- invariant(false, "No parent entry available for parallel()");
784
- }
785
-
786
- const namespace = `${ctx.namespace}.$${store.getNextIndex("parallel")}`;
787
-
788
- // Create full EntryData for parallel with its own loaders/revalidate/loading
789
- const entry = {
790
- id: namespace,
791
- shortCode: store.getShortCode("parallel"),
792
- type: "parallel",
793
- parent: null, // Parallels don't participate in parent chain traversal
794
- handler: slots,
795
- loading: undefined, // Allow loading() to attach loading state
796
- middleware: [],
797
- revalidate: [],
798
- errorBoundary: [],
799
- notFoundBoundary: [],
800
- layout: [],
801
- parallel: [],
802
- intercept: [],
803
- loader: [],
804
- } satisfies EntryData;
805
-
806
- // Run use callback if provided to collect loaders, revalidate, loading
807
- if (use && typeof use === "function") {
808
- const result = store.run(namespace, entry, use);
809
- invariant(
810
- Array.isArray(result) && result.every((item) => isValidUseItem(item)),
811
- `parallel() use() callback must return an array of use items [${namespace}]`
812
- );
813
- }
814
-
815
- ctx.parent.parallel.push(entry);
816
- return { name: namespace, type: "parallel" } as ParallelItem;
817
- };
818
-
819
- /**
820
- * Intercept helper - defines an intercepting route for soft navigation
821
- */
822
- const intercept: RouteHelpers<any, any>["intercept"] = (
823
- slotName,
824
- routeName,
825
- handler,
826
- use
827
- ) => {
828
- const store = getContext();
829
- const ctx = store.getStore();
830
- if (!ctx) throw new Error("intercept() must be called inside map()");
831
-
832
- if (!ctx.parent || !ctx.parent?.intercept) {
833
- invariant(false, "No parent entry available for intercept()");
834
- }
835
-
836
- const namespace = `${ctx.namespace}.$${store.getNextIndex("intercept")}.${slotName}`;
837
-
838
- // Apply name prefix to routeName (from include())
839
- // This ensures intercepts match prefixed route keys
840
- const namePrefix = getNamePrefix();
841
- const prefixedRouteName = namePrefix ? `${namePrefix}.${routeName}` : routeName;
842
-
843
- // Create intercept entry with its own loaders/revalidate/middleware/when
844
- const entry: InterceptEntry = {
845
- slotName: slotName as `@${string}`,
846
- routeName: prefixedRouteName,
847
- handler,
848
- middleware: [],
849
- revalidate: [],
850
- errorBoundary: [],
851
- notFoundBoundary: [],
852
- loader: [],
853
- when: [], // Selector conditions for conditional interception
854
- };
855
-
856
- // Run use callback if provided to collect loaders, revalidate, middleware, etc.
857
- if (use && typeof use === "function") {
858
- // Create a temporary parent context for the use() callback
859
- // so that middleware, loader, revalidate attach to the intercept entry
860
- const originalParent = ctx.parent;
861
-
862
- // Capture layouts in a temporary array
863
- const capturedLayouts: EntryData[] = [];
864
-
865
- const tempParent = {
866
- ...originalParent,
867
- middleware: entry.middleware,
868
- revalidate: entry.revalidate,
869
- errorBoundary: entry.errorBoundary,
870
- notFoundBoundary: entry.notFoundBoundary,
871
- loader: entry.loader,
872
- layout: capturedLayouts, // Capture layout() calls
873
- when: entry.when, // Capture when() conditions
874
- // Use getter/setter to capture loading on the entry
875
- get loading() {
876
- return entry.loading;
877
- },
878
- set loading(value: ReactNode | false | undefined) {
879
- entry.loading = value;
880
- },
881
- };
882
- ctx.parent = tempParent as EntryData;
883
-
884
- const result = use();
885
-
886
- // Restore original parent
887
- ctx.parent = originalParent;
888
-
889
- // Extract layout from captured layouts (use first one if multiple)
890
- // Layout inside intercept should always be ReactNode or Handler, not Record slots
891
- if (capturedLayouts.length > 0 && capturedLayouts[0].type === "layout") {
892
- entry.layout = capturedLayouts[0].handler as
893
- | ReactNode
894
- | Handler<any, any>;
895
- }
896
-
897
- invariant(
898
- Array.isArray(result) && result.every((item) => isValidUseItem(item)),
899
- `intercept() use() callback must return an array of use items [${namespace}]`
900
- );
901
- }
902
-
903
- ctx.parent.intercept.push(entry);
904
- return { name: namespace, type: "intercept" } as InterceptItem;
905
- };
906
-
907
- /**
908
- * Loader helper - attaches a loader to the current entry
909
- */
910
- const loaderFn: RouteHelpers<any, any>["loader"] = (loaderDef, use) => {
911
- const store = getContext();
912
- const ctx = store.getStore();
913
- if (!ctx) throw new Error("loader() must be called inside map()");
914
-
915
- // Attach to last entry in stack
916
- if (!ctx.parent || !ctx.parent?.loader) {
917
- invariant(false, "No parent entry available for loader()");
918
- }
919
-
920
- const name = `${ctx.namespace}.$${store.getNextIndex("loader")}`;
921
-
922
- // Create loader entry with empty revalidate array
923
- const loaderEntry = {
924
- loader: loaderDef,
925
- revalidate: [] as ShouldRevalidateFn<any, any>[],
926
- };
927
-
928
- // If use() callback provided, run it to collect revalidation rules
929
- if (use && typeof use === "function") {
930
- // Temporarily set context for revalidate() calls to target this loader
931
- const originalParent = ctx.parent;
932
- // Create a temporary "parent" that has the revalidate array we want to populate
933
- const tempParent = {
934
- ...originalParent,
935
- revalidate: loaderEntry.revalidate,
936
- };
937
- ctx.parent = tempParent as EntryData;
938
-
939
- const result = use();
940
-
941
- // Restore original parent
942
- ctx.parent = originalParent;
943
-
944
- invariant(
945
- Array.isArray(result) && result.every((item) => isValidUseItem(item)),
946
- `loader() use() callback must return an array of use items [${name}]`
947
- );
948
- }
949
-
950
- ctx.parent.loader.push(loaderEntry);
951
- return { name, type: "loader" } as LoaderItem;
952
- };
953
-
954
- /**
955
- * Loading helper - attaches a loading component to the current entry
956
- * Loading components are static (no context) and shown during navigation
957
- */
958
- const loadingFn: RouteHelpers<any, any>["loading"] = (component, options) => {
959
- const store = getContext();
960
- const ctx = store.getStore();
961
- if (!ctx) throw new Error("loading() must be called inside map()");
962
-
963
- const parent = ctx.parent;
964
- if (!parent || !("loading" in parent)) {
965
- invariant(false, "No parent entry available for loading()");
966
- }
967
-
968
- // If ssr: false and we're in SSR, set loading to false
969
- if (options?.ssr === false && ctx.isSSR) {
970
- parent.loading = false;
971
- } else {
972
- parent.loading = component;
973
- }
974
-
975
- const name = `$${store.getNextIndex("loading")}`;
976
- return { name, type: "loading" } as LoadingItem;
977
- };
978
-
979
- const routeFn: RouteHelpers<any, any>["route"] = (name, handler, use) => {
980
- const store = getContext();
981
- const ctx = store.getStore();
982
- if (!ctx) throw new Error("route() must be called inside map()");
983
-
984
- const namespace = `${ctx.namespace}.${store.getNextIndex("route")}.${name}`;
985
-
986
- const entry = {
987
- id: namespace,
988
- shortCode: store.getShortCode("route"),
989
- type: "route",
990
- parent: ctx.parent,
991
- handler,
992
- loading: undefined, // Allow loading() to attach loading state
993
- middleware: [],
994
- revalidate: [],
995
- errorBoundary: [],
996
- notFoundBoundary: [],
997
- layout: [],
998
- parallel: [],
999
- intercept: [],
1000
- loader: [],
1001
- } satisfies EntryData;
1002
-
1003
- /* We will throw if user is registring same route name twice */
1004
- invariant(
1005
- ctx.manifest.get(name) === undefined,
1006
- `Duplicate route name: ${name} at ${namespace}`
1007
- );
1008
- /* Register route entry */
1009
- ctx.manifest.set(name, entry);
1010
- /* Run use and attach handlers */
1011
- if (use && typeof use === "function") {
1012
- const result = store.run(namespace, entry, use);
1013
- invariant(
1014
- Array.isArray(result) && result.every((item) => isValidUseItem(item)),
1015
- `route() use() callback must return an array of use items [${namespace}]`
1016
- );
1017
- return { name: namespace, type: "route", uses: result } as RouteItem;
1018
- }
1019
-
1020
- /* typesafe item */
1021
- return { name: namespace, type: "route" } as RouteItem;
1022
- };
1023
-
1024
- const layout: RouteHelpers<any, any>["layout"] = (handler, use) => {
1025
- const store = getContext();
1026
- const ctx = store.getStore();
1027
- if (!ctx) throw new Error("layout() must be called inside map()");
1028
- const isRoot = !ctx.parent || ctx.parent === null;
1029
- const namespace = `${ctx.namespace}.${
1030
- isRoot ? "$root" : store.getNextIndex("layout")
1031
- }`;
1032
-
1033
- const entry = {
1034
- id: namespace,
1035
- shortCode: store.getShortCode("layout"),
1036
- type: "layout",
1037
- parent: ctx.parent,
1038
- handler,
1039
- loading: undefined, // Allow loading() to attach loading state
1040
- middleware: [],
1041
- revalidate: [],
1042
- errorBoundary: [],
1043
- notFoundBoundary: [],
1044
- parallel: [],
1045
- intercept: [],
1046
- layout: [],
1047
- loader: [],
1048
- } satisfies EntryData;
1049
-
1050
- // Run use callback if provided
1051
- let result: AllUseItems[] | undefined;
1052
- if (use && typeof use === "function") {
1053
- result = store.run(namespace, entry, use);
1054
-
1055
- invariant(
1056
- Array.isArray(result) && result.every((item) => isValidUseItem(item)),
1057
- `layout() use() callback must return an array of use items [${namespace}]`
1058
- );
1059
- }
1060
-
1061
- // Check if this is an orphan layout (no routes in children, including nested caches)
1062
- const hasRoutes =
1063
- result &&
1064
- Array.isArray(result) &&
1065
- result.some((item) => hasRoutesInItem(item));
1066
-
1067
- if (!hasRoutes) {
1068
- const parent = ctx.parent;
1069
-
1070
- // Allow orphan layouts at root level if they're part of map() builder result
1071
- if (!parent || parent === null) {
1072
- if (!isRoot) {
1073
- invariant(
1074
- false,
1075
- `Orphan layout cannot be used at non-root level without parent [${namespace}]`
1076
- );
1077
- }
1078
- // Root-level orphan is allowed (e.g., sibling layouts in map() builder)
1079
- } else {
1080
- // Has parent - register as orphan layout
1081
- invariant(
1082
- parent.type === "route" ||
1083
- parent.type === "layout" ||
1084
- parent.type === "cache",
1085
- `Orphan layouts can only be defined inside route or layout > check [${namespace}]`
1086
- );
1087
-
1088
- // Clear parent pointer for orphan layouts to prevent duplicate processing
1089
- entry.parent = null;
1090
- parent.layout.push(entry);
1091
- }
1092
- }
1093
-
1094
- if (result) {
1095
- return { name: namespace, type: "layout", uses: result } as LayoutItem;
1096
- }
1097
- return {
1098
- name: namespace,
1099
- type: "layout",
1100
- } as LayoutItem;
1101
- };
1102
-
1103
- const isValidUseItem = (item: any): item is AllUseItems | undefined | null => {
1104
- return (
1105
- typeof item === "undefined" ||
1106
- item === null ||
1107
- (item &&
1108
- typeof item === "object" &&
1109
- "type" in item &&
1110
- [
1111
- "layout",
1112
- "route",
1113
- "middleware",
1114
- "revalidate",
1115
- "parallel",
1116
- "intercept",
1117
- "loader",
1118
- "loading",
1119
- "errorBoundary",
1120
- "notFoundBoundary",
1121
- "when",
1122
- "cache",
1123
- "include", // For urls() include() helper
1124
- ].includes(item.type))
1125
- );
1126
- };
1127
-
1128
- const isOrphanLayout = (item: AllUseItems): boolean => {
1129
- return (
1130
- item.type === "layout" &&
1131
- !item.uses?.some((child) => hasRoutesInItem(child))
1132
- );
1133
- };
1134
-
1135
- /*
1136
- * Create revalidate helper
1137
- */
1138
- const createRevalidateHelper = <TEnv>(): RouteHelpers<
1139
- any,
1140
- TEnv
1141
- >["revalidate"] => {
1142
- return revalidate as RouteHelpers<any, TEnv>["revalidate"];
1143
- };
1144
-
1145
- /**
1146
- * Create errorBoundary helper
1147
- */
1148
- const createErrorBoundaryHelper = <TEnv>(): RouteHelpers<
1149
- any,
1150
- TEnv
1151
- >["errorBoundary"] => {
1152
- return errorBoundary as RouteHelpers<any, TEnv>["errorBoundary"];
1153
- };
1154
-
1155
- /**
1156
- * Create notFoundBoundary helper
1157
- */
1158
- const createNotFoundBoundaryHelper = <TEnv>(): RouteHelpers<
1159
- any,
1160
- TEnv
1161
- >["notFoundBoundary"] => {
1162
- return notFoundBoundary as RouteHelpers<any, TEnv>["notFoundBoundary"];
1163
- };
1164
-
1165
- /**
1166
- * Create middleware helper
1167
- */
1168
- const createMiddlewareHelper = <TEnv>(): RouteHelpers<
1169
- any,
1170
- TEnv
1171
- >["middleware"] => {
1172
- return middleware as RouteHelpers<any, TEnv>["middleware"];
1173
- };
1174
-
1175
- /**
1176
- * Create parallel helper
1177
- */
1178
- const createParallelHelper = <TEnv>(): RouteHelpers<any, TEnv>["parallel"] => {
1179
- return parallel as RouteHelpers<any, TEnv>["parallel"];
1180
- };
1181
-
1182
- /**
1183
- * Create intercept helper
1184
- */
1185
- const createInterceptHelper = <
1186
- const T extends RouteDefinition,
1187
- TEnv,
1188
- >(): RouteHelpers<T, TEnv>["intercept"] => {
1189
- return intercept as RouteHelpers<T, TEnv>["intercept"];
1190
- };
1191
-
1192
- /**
1193
- * Create loader helper
1194
- */
1195
- const createLoaderHelper = <TEnv>(): RouteHelpers<any, TEnv>["loader"] => {
1196
- return loaderFn as RouteHelpers<any, TEnv>["loader"];
1197
- };
1198
-
1199
- /**
1200
- * Create loading helper
1201
- */
1202
- const createLoadingHelper = (): RouteHelpers<any, any>["loading"] => {
1203
- return loadingFn;
1204
- };
1205
-
1206
- /**
1207
- * Create route helper
1208
- */
1209
- const createRouteHelper = <
1210
- const T extends RouteDefinition,
1211
- TEnv,
1212
- >(): RouteHelpers<T, TEnv>["route"] => {
1213
- return routeFn as RouteHelpers<T, TEnv>["route"];
1214
- };
1215
-
1216
- /**
1217
- * Create layout helper
1218
- */
1219
- const createLayoutHelper = <TEnv>(): RouteHelpers<any, TEnv>["layout"] => {
1220
- return layout as RouteHelpers<any, TEnv>["layout"];
1221
- };
1222
-
1223
- /**
1224
- * Create when helper for intercept conditions
1225
- */
1226
- const createWhenHelper = (): RouteHelpers<any, any>["when"] => {
1227
- return when;
1228
- };
1229
-
1230
- /**
1231
- * Create cache helper for cache configuration
1232
- */
1233
- const createCacheHelper = (): RouteHelpers<any, any>["cache"] => {
1234
- return cache;
1235
- };
1236
-
1237
- /**
1238
- * Branded type for route handlers that carries the route type info.
1239
- * This enables type-safe verification that imported handlers match route definitions.
1240
- */
1241
- export interface RouteHandlers<T extends RouteDefinition> {
1242
- (): Array<AllUseItems>;
1243
- /** Brand to carry route type info for type checking */
1244
- readonly __routes: T;
1245
- }
1246
-
1247
- /**
1248
- * Type-safe handler definition helper
1249
- *
1250
- */
1251
- export function map<const T extends RouteDefinition, TEnv = DefaultEnv>(
1252
- builder: (helpers: RouteHelpers<T, TEnv>) => Array<AllUseItems>
1253
- ): RouteHandlers<T> {
1254
- const handler = () => {
1255
- // Check if it's a builder function (array-based API)
1256
- invariant(
1257
- typeof builder === "function",
1258
- "map() expects a builder function as its argument"
1259
- );
1260
- // Create helpers
1261
- const helpers: RouteHelpers<T, TEnv> = {
1262
- route: createRouteHelper<T, TEnv>(),
1263
- layout: createLayoutHelper<TEnv>(),
1264
- parallel: createParallelHelper<TEnv>(),
1265
- intercept: createInterceptHelper<T, TEnv>(),
1266
- middleware: createMiddlewareHelper<TEnv>(),
1267
- revalidate: createRevalidateHelper<TEnv>(),
1268
- loader: createLoaderHelper<TEnv>(),
1269
- loading: createLoadingHelper(),
1270
- errorBoundary: createErrorBoundaryHelper<TEnv>(),
1271
- notFoundBoundary: createNotFoundBoundaryHelper<TEnv>(),
1272
- when: createWhenHelper(),
1273
- cache: createCacheHelper(),
1274
- };
1275
-
1276
- return [layout(RootLayout, () => builder(helpers))].flat(3);
1277
- };
1278
- // Cast to RouteHandlers to carry the route type brand
1279
- return handler as RouteHandlers<T>;
1280
- }
1281
-
1282
- /**
1283
- * Create RouteHelpers for inline route definitions
1284
- * Used internally by router.map() for inline handler syntax
1285
- */
1286
- export function createRouteHelpers<
1287
- T extends RouteDefinition,
1288
- TEnv,
1289
- >(): RouteHelpers<T, TEnv> {
1290
- return {
1291
- route: createRouteHelper<T, TEnv>(),
1292
- layout: createLayoutHelper<TEnv>(),
1293
- parallel: createParallelHelper<TEnv>(),
1294
- intercept: createInterceptHelper<T, TEnv>(),
1295
- middleware: createMiddlewareHelper<TEnv>(),
1296
- revalidate: createRevalidateHelper<TEnv>(),
1297
- loader: createLoaderHelper<TEnv>(),
1298
- loading: createLoadingHelper(),
1299
- errorBoundary: createErrorBoundaryHelper<TEnv>(),
1300
- notFoundBoundary: createNotFoundBoundaryHelper<TEnv>(),
1301
- when: createWhenHelper(),
1302
- cache: createCacheHelper(),
1303
- };
1304
- }
1305
-
1306
- /**
1307
- * Create a loader definition
1308
- *
1309
- * Loaders are RSC-compatible data fetchers that:
1310
- * - Run after middleware, before handlers
1311
- * - Are scoped to where attached (layout/route subtree)
1312
- * - Revalidate independently from UI segments
1313
- * - Are memoized per request (multiple ctx.use() calls return same value)
1314
- *
1315
- * Use the `"use server"` directive inside the loader function to ensure
1316
- * the function is stripped from client bundles.
1317
- *
1318
- * Return type is automatically inferred from the callback.
1319
- *
1320
- * @param fn - Async function that fetches data (should contain "use server" directive)
1321
- * @param fetchable - Optional flag to make the loader fetchable via useFetchLoader
1322
- *
1323
- * @example
1324
- * ```typescript
1325
- * // loaders/cart.ts - return type inferred from callback
1326
- * export const CartLoader = createLoader(async (ctx) => {
1327
- * "use server";
1328
- * const user = ctx.get("user");
1329
- * return await db.cart.get(user.id); // Return type inferred!
1330
- * });
1331
- *
1332
- * // loaders/product.ts - return type inferred
1333
- * export const ProductLoader = createLoader(async (ctx) => {
1334
- * "use server";
1335
- * const { slug } = ctx.params;
1336
- * return await db.products.findBySlug(slug); // Return type inferred!
1337
- * });
1338
- *
1339
- * // Usage in handlers
1340
- * layout(<ShopLayout />, () => [
1341
- * loader(CartLoader),
1342
- * loader(CartLoader, () => [
1343
- * revalidate(({ actionId }) => actionId?.includes("Cart") ?? false),
1344
- * ]),
1345
- * ])
1346
- *
1347
- * // Server-side access
1348
- * route("cart", (ctx) => {
1349
- * const cart = ctx.use(CartLoader);
1350
- * return <CartPage cart={cart} />;
1351
- * });
1352
- *
1353
- * // Client-side access
1354
- * const cart = useLoader(CartLoader);
1355
- * ```
1356
- */
1357
- // Re-export createLoader from loader.rsc.ts for RSC/server context
1358
- export { createLoader } from "./loader.rsc.js";
1359
-
1360
- /**
1361
- * Create a soft redirect Response for middleware short-circuit
1362
- *
1363
- * Returns a Response that signals a client-side navigation to the target URL.
1364
- * Unlike Response.redirect() which causes a full page reload, this redirect
1365
- * is handled by the router for SPA-style navigation.
1366
- *
1367
- * @param url - The URL to redirect to
1368
- * @param status - HTTP status code (default: 302)
1369
- *
1370
- * @example
1371
- * ```typescript
1372
- * middleware((ctx, next) => {
1373
- * if (!ctx.get('user')) {
1374
- * return redirect('/login');
1375
- * }
1376
- * next();
1377
- * })
1378
- * ```
1379
- */
1380
- export function redirect(url: string, status: number = 302): Response {
1381
- return new Response(null, {
1382
- status,
1383
- headers: {
1384
- Location: url,
1385
- "X-RSC-Redirect": "soft",
1386
- },
1387
- });
1388
- }
1
+ export * from "./route-definition/index.js";