@rangojs/router 0.0.0-experimental.2

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