@rangojs/router 0.0.0-experimental.10

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