@rangojs/router 0.0.0-experimental.13 → 0.0.0-experimental.13221847

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 (298) hide show
  1. package/AGENTS.md +9 -0
  2. package/README.md +884 -4
  3. package/dist/bin/rango.js +1531 -212
  4. package/dist/vite/index.js +3995 -2489
  5. package/package.json +57 -52
  6. package/skills/breadcrumbs/SKILL.md +250 -0
  7. package/skills/cache-guide/SKILL.md +262 -0
  8. package/skills/caching/SKILL.md +85 -23
  9. package/skills/composability/SKILL.md +172 -0
  10. package/skills/debug-manifest/SKILL.md +12 -8
  11. package/skills/document-cache/SKILL.md +18 -16
  12. package/skills/fonts/SKILL.md +6 -4
  13. package/skills/hooks/SKILL.md +328 -70
  14. package/skills/host-router/SKILL.md +218 -0
  15. package/skills/intercept/SKILL.md +131 -8
  16. package/skills/layout/SKILL.md +100 -3
  17. package/skills/links/SKILL.md +62 -15
  18. package/skills/loader/SKILL.md +368 -42
  19. package/skills/middleware/SKILL.md +171 -34
  20. package/skills/mime-routes/SKILL.md +14 -10
  21. package/skills/parallel/SKILL.md +137 -1
  22. package/skills/prerender/SKILL.md +366 -28
  23. package/skills/rango/SKILL.md +85 -21
  24. package/skills/response-routes/SKILL.md +136 -83
  25. package/skills/route/SKILL.md +195 -21
  26. package/skills/router-setup/SKILL.md +123 -30
  27. package/skills/theme/SKILL.md +9 -8
  28. package/skills/typesafety/SKILL.md +240 -102
  29. package/skills/use-cache/SKILL.md +324 -0
  30. package/src/__internal.ts +102 -4
  31. package/src/bin/rango.ts +312 -15
  32. package/src/browser/action-coordinator.ts +97 -0
  33. package/src/browser/action-response-classifier.ts +99 -0
  34. package/src/browser/event-controller.ts +92 -64
  35. package/src/browser/history-state.ts +80 -0
  36. package/src/browser/intercept-utils.ts +52 -0
  37. package/src/browser/link-interceptor.ts +24 -4
  38. package/src/browser/logging.ts +11 -0
  39. package/src/browser/merge-segment-loaders.ts +20 -12
  40. package/src/browser/navigation-bridge.ts +266 -558
  41. package/src/browser/navigation-client.ts +132 -75
  42. package/src/browser/navigation-store.ts +33 -50
  43. package/src/browser/navigation-transaction.ts +297 -0
  44. package/src/browser/network-error-handler.ts +61 -0
  45. package/src/browser/partial-update.ts +303 -309
  46. package/src/browser/prefetch/cache.ts +206 -0
  47. package/src/browser/prefetch/fetch.ts +144 -0
  48. package/src/browser/prefetch/observer.ts +65 -0
  49. package/src/browser/prefetch/policy.ts +48 -0
  50. package/src/browser/prefetch/queue.ts +128 -0
  51. package/src/browser/rango-state.ts +112 -0
  52. package/src/browser/react/Link.tsx +190 -70
  53. package/src/browser/react/NavigationProvider.tsx +78 -11
  54. package/src/browser/react/context.ts +6 -0
  55. package/src/browser/react/filter-segment-order.ts +11 -0
  56. package/src/browser/react/index.ts +12 -12
  57. package/src/browser/react/location-state-shared.ts +95 -53
  58. package/src/browser/react/location-state.ts +60 -15
  59. package/src/browser/react/mount-context.ts +6 -1
  60. package/src/browser/react/nonce-context.ts +23 -0
  61. package/src/browser/react/shallow-equal.ts +27 -0
  62. package/src/browser/react/use-action.ts +29 -51
  63. package/src/browser/react/use-client-cache.ts +5 -3
  64. package/src/browser/react/use-handle.ts +29 -70
  65. package/src/browser/react/use-link-status.ts +6 -5
  66. package/src/browser/react/use-navigation.ts +22 -63
  67. package/src/browser/react/use-params.ts +65 -0
  68. package/src/browser/react/use-pathname.ts +47 -0
  69. package/src/browser/react/use-router.ts +63 -0
  70. package/src/browser/react/use-search-params.ts +56 -0
  71. package/src/browser/react/use-segments.ts +80 -97
  72. package/src/browser/response-adapter.ts +73 -0
  73. package/src/browser/rsc-router.tsx +188 -57
  74. package/src/browser/scroll-restoration.ts +117 -44
  75. package/src/browser/segment-reconciler.ts +221 -0
  76. package/src/browser/segment-structure-assert.ts +16 -0
  77. package/src/browser/server-action-bridge.ts +488 -606
  78. package/src/browser/shallow.ts +6 -1
  79. package/src/browser/types.ts +116 -47
  80. package/src/browser/validate-redirect-origin.ts +29 -0
  81. package/src/build/generate-manifest.ts +63 -21
  82. package/src/build/generate-route-types.ts +36 -1038
  83. package/src/build/index.ts +2 -5
  84. package/src/build/route-trie.ts +38 -12
  85. package/src/build/route-types/ast-helpers.ts +25 -0
  86. package/src/build/route-types/ast-route-extraction.ts +98 -0
  87. package/src/build/route-types/codegen.ts +102 -0
  88. package/src/build/route-types/include-resolution.ts +411 -0
  89. package/src/build/route-types/param-extraction.ts +48 -0
  90. package/src/build/route-types/per-module-writer.ts +128 -0
  91. package/src/build/route-types/router-processing.ts +479 -0
  92. package/src/build/route-types/scan-filter.ts +78 -0
  93. package/src/build/runtime-discovery.ts +231 -0
  94. package/src/cache/background-task.ts +34 -0
  95. package/src/cache/cache-key-utils.ts +44 -0
  96. package/src/cache/cache-policy.ts +125 -0
  97. package/src/cache/cache-runtime.ts +342 -0
  98. package/src/cache/cache-scope.ts +122 -303
  99. package/src/cache/cf/cf-cache-store.ts +571 -17
  100. package/src/cache/cf/index.ts +13 -3
  101. package/src/cache/document-cache.ts +116 -77
  102. package/src/cache/handle-capture.ts +81 -0
  103. package/src/cache/handle-snapshot.ts +41 -0
  104. package/src/cache/index.ts +1 -15
  105. package/src/cache/memory-segment-store.ts +191 -13
  106. package/src/cache/profile-registry.ts +73 -0
  107. package/src/cache/read-through-swr.ts +134 -0
  108. package/src/cache/segment-codec.ts +256 -0
  109. package/src/cache/taint.ts +98 -0
  110. package/src/cache/types.ts +72 -122
  111. package/src/client.rsc.tsx +3 -1
  112. package/src/client.tsx +84 -126
  113. package/src/component-utils.ts +4 -4
  114. package/src/components/DefaultDocument.tsx +5 -1
  115. package/src/context-var.ts +86 -0
  116. package/src/debug.ts +19 -9
  117. package/src/errors.ts +77 -7
  118. package/src/handle.ts +12 -7
  119. package/src/handles/MetaTags.tsx +73 -20
  120. package/src/handles/breadcrumbs.ts +66 -0
  121. package/src/handles/index.ts +1 -0
  122. package/src/handles/meta.ts +30 -13
  123. package/src/host/cookie-handler.ts +21 -15
  124. package/src/host/errors.ts +8 -8
  125. package/src/host/index.ts +4 -7
  126. package/src/host/pattern-matcher.ts +27 -27
  127. package/src/host/router.ts +61 -39
  128. package/src/host/testing.ts +8 -8
  129. package/src/host/types.ts +15 -7
  130. package/src/host/utils.ts +1 -1
  131. package/src/href-client.ts +65 -45
  132. package/src/index.rsc.ts +104 -40
  133. package/src/index.ts +122 -67
  134. package/src/internal-debug.ts +9 -3
  135. package/src/loader.rsc.ts +18 -93
  136. package/src/loader.ts +26 -9
  137. package/src/network-error-thrower.tsx +3 -1
  138. package/src/outlet-provider.tsx +45 -0
  139. package/src/prerender/param-hash.ts +4 -2
  140. package/src/prerender/store.ts +121 -17
  141. package/src/prerender.ts +325 -20
  142. package/src/reverse.ts +144 -124
  143. package/src/root-error-boundary.tsx +41 -29
  144. package/src/route-content-wrapper.tsx +7 -4
  145. package/src/route-definition/dsl-helpers.ts +959 -0
  146. package/src/route-definition/helper-factories.ts +200 -0
  147. package/src/route-definition/helpers-types.ts +430 -0
  148. package/src/route-definition/index.ts +52 -0
  149. package/src/route-definition/redirect.ts +93 -0
  150. package/src/route-definition.ts +1 -1450
  151. package/src/route-map-builder.ts +87 -133
  152. package/src/route-name.ts +53 -0
  153. package/src/route-types.ts +41 -6
  154. package/src/router/content-negotiation.ts +116 -0
  155. package/src/router/debug-manifest.ts +72 -0
  156. package/src/router/error-handling.ts +9 -9
  157. package/src/router/find-match.ts +160 -0
  158. package/src/router/handler-context.ts +324 -116
  159. package/src/router/intercept-resolution.ts +11 -4
  160. package/src/router/lazy-includes.ts +237 -0
  161. package/src/router/loader-resolution.ts +179 -133
  162. package/src/router/logging.ts +112 -6
  163. package/src/router/manifest.ts +58 -19
  164. package/src/router/match-api.ts +89 -88
  165. package/src/router/match-context.ts +4 -2
  166. package/src/router/match-handlers.ts +440 -0
  167. package/src/router/match-middleware/background-revalidation.ts +86 -89
  168. package/src/router/match-middleware/cache-lookup.ts +295 -49
  169. package/src/router/match-middleware/cache-store.ts +56 -13
  170. package/src/router/match-middleware/intercept-resolution.ts +45 -22
  171. package/src/router/match-middleware/segment-resolution.ts +20 -9
  172. package/src/router/match-pipelines.ts +10 -45
  173. package/src/router/match-result.ts +44 -21
  174. package/src/router/metrics.ts +240 -15
  175. package/src/router/middleware-cookies.ts +55 -0
  176. package/src/router/middleware-types.ts +222 -0
  177. package/src/router/middleware.ts +327 -369
  178. package/src/router/pattern-matching.ts +169 -31
  179. package/src/router/prerender-match.ts +402 -0
  180. package/src/router/preview-match.ts +170 -0
  181. package/src/router/revalidation.ts +105 -14
  182. package/src/router/router-context.ts +40 -21
  183. package/src/router/router-interfaces.ts +452 -0
  184. package/src/router/router-options.ts +592 -0
  185. package/src/router/router-registry.ts +24 -0
  186. package/src/router/segment-resolution/fresh.ts +677 -0
  187. package/src/router/segment-resolution/helpers.ts +263 -0
  188. package/src/router/segment-resolution/loader-cache.ts +199 -0
  189. package/src/router/segment-resolution/revalidation.ts +1296 -0
  190. package/src/router/segment-resolution/static-store.ts +67 -0
  191. package/src/router/segment-resolution.ts +21 -1354
  192. package/src/router/segment-wrappers.ts +291 -0
  193. package/src/router/telemetry-otel.ts +299 -0
  194. package/src/router/telemetry.ts +300 -0
  195. package/src/router/timeout.ts +148 -0
  196. package/src/router/trie-matching.ts +96 -29
  197. package/src/router/types.ts +15 -9
  198. package/src/router.ts +642 -2366
  199. package/src/rsc/handler-context.ts +45 -0
  200. package/src/rsc/handler.ts +639 -1027
  201. package/src/rsc/helpers.ts +140 -6
  202. package/src/rsc/index.ts +0 -20
  203. package/src/rsc/loader-fetch.ts +209 -0
  204. package/src/rsc/manifest-init.ts +86 -0
  205. package/src/rsc/nonce.ts +14 -0
  206. package/src/rsc/origin-guard.ts +141 -0
  207. package/src/rsc/progressive-enhancement.ts +379 -0
  208. package/src/rsc/response-error.ts +37 -0
  209. package/src/rsc/response-route-handler.ts +347 -0
  210. package/src/rsc/rsc-rendering.ts +237 -0
  211. package/src/rsc/runtime-warnings.ts +42 -0
  212. package/src/rsc/server-action.ts +348 -0
  213. package/src/rsc/ssr-setup.ts +128 -0
  214. package/src/rsc/types.ts +38 -11
  215. package/src/search-params.ts +66 -54
  216. package/src/segment-system.tsx +165 -17
  217. package/src/server/context.ts +237 -54
  218. package/src/server/cookie-store.ts +190 -0
  219. package/src/server/fetchable-loader-store.ts +11 -6
  220. package/src/server/handle-store.ts +94 -15
  221. package/src/server/loader-registry.ts +15 -56
  222. package/src/server/request-context.ts +438 -71
  223. package/src/server.ts +26 -164
  224. package/src/ssr/index.tsx +101 -31
  225. package/src/static-handler.ts +22 -4
  226. package/src/theme/ThemeProvider.tsx +21 -15
  227. package/src/theme/ThemeScript.tsx +5 -5
  228. package/src/theme/constants.ts +5 -2
  229. package/src/theme/index.ts +4 -14
  230. package/src/theme/theme-context.ts +4 -30
  231. package/src/theme/theme-script.ts +21 -18
  232. package/src/types/boundaries.ts +158 -0
  233. package/src/types/cache-types.ts +198 -0
  234. package/src/types/error-types.ts +192 -0
  235. package/src/types/global-namespace.ts +100 -0
  236. package/src/types/handler-context.ts +773 -0
  237. package/src/types/index.ts +88 -0
  238. package/src/types/loader-types.ts +183 -0
  239. package/src/types/route-config.ts +170 -0
  240. package/src/types/route-entry.ts +109 -0
  241. package/src/types/segments.ts +150 -0
  242. package/src/types.ts +1 -1795
  243. package/src/urls/include-helper.ts +197 -0
  244. package/src/urls/index.ts +53 -0
  245. package/src/urls/path-helper-types.ts +339 -0
  246. package/src/urls/path-helper.ts +329 -0
  247. package/src/urls/pattern-types.ts +95 -0
  248. package/src/urls/response-types.ts +106 -0
  249. package/src/urls/type-extraction.ts +372 -0
  250. package/src/urls/urls-function.ts +98 -0
  251. package/src/urls.ts +1 -1323
  252. package/src/use-loader.tsx +85 -77
  253. package/src/vite/discovery/bundle-postprocess.ts +184 -0
  254. package/src/vite/discovery/discover-routers.ts +344 -0
  255. package/src/vite/discovery/prerender-collection.ts +385 -0
  256. package/src/vite/discovery/route-types-writer.ts +258 -0
  257. package/src/vite/discovery/self-gen-tracking.ts +47 -0
  258. package/src/vite/discovery/state.ts +108 -0
  259. package/src/vite/discovery/virtual-module-codegen.ts +203 -0
  260. package/src/vite/index.ts +11 -2259
  261. package/src/vite/plugin-types.ts +48 -0
  262. package/src/vite/plugins/cjs-to-esm.ts +93 -0
  263. package/src/vite/plugins/client-ref-dedup.ts +115 -0
  264. package/src/vite/plugins/client-ref-hashing.ts +105 -0
  265. package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +72 -47
  266. package/src/vite/{expose-id-utils.ts → plugins/expose-id-utils.ts} +8 -43
  267. package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
  268. package/src/vite/plugins/expose-ids/handler-transform.ts +179 -0
  269. package/src/vite/plugins/expose-ids/loader-transform.ts +74 -0
  270. package/src/vite/plugins/expose-ids/router-transform.ts +110 -0
  271. package/src/vite/plugins/expose-ids/types.ts +45 -0
  272. package/src/vite/plugins/expose-internal-ids.ts +569 -0
  273. package/src/vite/plugins/refresh-cmd.ts +65 -0
  274. package/src/vite/plugins/use-cache-transform.ts +323 -0
  275. package/src/vite/plugins/version-injector.ts +83 -0
  276. package/src/vite/plugins/version-plugin.ts +266 -0
  277. package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +23 -14
  278. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  279. package/src/vite/rango.ts +445 -0
  280. package/src/vite/router-discovery.ts +777 -0
  281. package/src/vite/{ast-handler-extract.ts → utils/ast-handler-extract.ts} +181 -9
  282. package/src/vite/utils/banner.ts +36 -0
  283. package/src/vite/utils/bundle-analysis.ts +137 -0
  284. package/src/vite/utils/manifest-utils.ts +70 -0
  285. package/src/vite/{package-resolution.ts → utils/package-resolution.ts} +25 -29
  286. package/src/vite/utils/prerender-utils.ts +189 -0
  287. package/src/vite/utils/shared-utils.ts +169 -0
  288. package/CLAUDE.md +0 -43
  289. package/dist/vite/index.named-routes.gen.ts +0 -103
  290. package/src/browser/lru-cache.ts +0 -69
  291. package/src/browser/request-controller.ts +0 -164
  292. package/src/cache/memory-store.ts +0 -253
  293. package/src/href-context.ts +0 -33
  294. package/src/router.gen.ts +0 -6
  295. package/src/static-handler.gen.ts +0 -5
  296. package/src/urls.gen.ts +0 -8
  297. package/src/vite/expose-internal-ids.ts +0 -1167
  298. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
package/src/types.ts CHANGED
@@ -1,1795 +1 @@
1
- import type { ReactNode } from "react";
2
- import type { AllUseItems } from "./route-types.js";
3
- import type { Handle } from "./handle.js";
4
- import type { MiddlewareFn } from "./router/middleware.js";
5
- import type { Theme } from "./theme/types.js";
6
- import type { ScopedReverseFunction } from "./reverse.js";
7
- import type { SearchSchema, ResolveSearchSchema } from "./search-params.js";
8
-
9
- // Re-export MiddlewareFn for internal/advanced use
10
- export type { MiddlewareFn } from "./router/middleware.js";
11
-
12
- /**
13
- * Props for the Document component that wraps the entire application.
14
- */
15
- export type DocumentProps = {
16
- children: ReactNode;
17
- };
18
-
19
- /**
20
- * Global namespace for module augmentation
21
- *
22
- * Users can augment this to provide type-safe context globally:
23
- *
24
- * @example
25
- * ```typescript
26
- * // In router.tsx or env.d.ts
27
- * declare global {
28
- * namespace RSCRouter {
29
- * interface Env extends RouterEnv<AppBindings, AppVariables> {}
30
- * }
31
- * }
32
- *
33
- * // Now all handlers have type-safe context without imports!
34
- * export default map<typeof shopRoutes>({
35
- * [middleware('*', 'auth')]: [
36
- * (ctx, next) => {
37
- * ctx.set('user', ...) // Type-safe!
38
- * }
39
- * ]
40
- * })
41
- * ```
42
- */
43
- declare global {
44
- namespace RSCRouter {
45
- // eslint-disable-next-line @typescript-eslint/no-empty-interface
46
- interface Env {
47
- // Empty by default - users augment with their RouterEnv
48
- }
49
-
50
- // eslint-disable-next-line @typescript-eslint/no-empty-interface
51
- interface RegisteredRoutes {
52
- // Empty by default - users augment with their merged route maps for type-safe href()
53
- // Values are string (pattern) for RSC routes, or { path: string; response: T } for response routes
54
- }
55
-
56
- // eslint-disable-next-line @typescript-eslint/no-empty-interface
57
- interface GeneratedRouteMap {
58
- // Empty by default - populated by generated named-routes.gen.ts
59
- // Maps route names to URL pattern strings for Handler<"routeName"> support
60
- }
61
- }
62
- }
63
-
64
- /**
65
- * Get registered routes or fallback to generic Record<string, string>
66
- * When RSCRouter.RegisteredRoutes is augmented, provides autocomplete for route names
67
- * When not augmented, allows any string (no autocomplete)
68
- */
69
- export type GetRegisteredRoutes = keyof RSCRouter.RegisteredRoutes extends never
70
- ? Record<string, string>
71
- : RSCRouter.RegisteredRoutes;
72
-
73
- /**
74
- * Default route map for Handler type.
75
- * Uses GeneratedRouteMap (from gen file) instead of RegisteredRoutes to avoid
76
- * circular dependencies: router.tsx -> urls.tsx -> handler.tsx -> RegisteredRoutes -> router.tsx.
77
- * GeneratedRouteMap is declared in a standalone gen file with no imports.
78
- */
79
- type DefaultHandlerRouteMap = keyof RSCRouter.GeneratedRouteMap extends never
80
- ? {}
81
- : RSCRouter.GeneratedRouteMap;
82
-
83
- /**
84
- * Default environment type - uses global augmentation if available, any otherwise
85
- */
86
- export type DefaultEnv = keyof RSCRouter.Env extends never
87
- ? any
88
- : RSCRouter.Env;
89
-
90
- /**
91
- * Router environment (Hono-inspired type-safe context)
92
- *
93
- * @template TBindings - Platform bindings (DB, KV, secrets, etc.)
94
- * @template TVariables - Middleware-injected variables (user, permissions, etc.)
95
- *
96
- * @example
97
- * ```typescript
98
- * interface AppBindings {
99
- * DB: D1Database;
100
- * KV: KVNamespace;
101
- * STRIPE_KEY: string;
102
- * }
103
- *
104
- * interface AppVariables {
105
- * user?: { id: string; name: string };
106
- * permissions?: string[];
107
- * }
108
- *
109
- * type AppEnv = RouterEnv<AppBindings, AppVariables>;
110
- * const router = createRouter<AppEnv>();
111
- * ```
112
- */
113
- export interface RouterEnv<TBindings = {}, TVariables = {}> {
114
- Bindings: TBindings;
115
- Variables: TVariables;
116
- }
117
-
118
- /**
119
- * Parse constraint values into a union type
120
- * "a|b|c" → "a" | "b" | "c"
121
- */
122
- type ParseConstraint<T extends string> =
123
- T extends `${infer First}|${infer Rest}` ? First | ParseConstraint<Rest> : T;
124
-
125
- /**
126
- * Extract param info from a param segment
127
- *
128
- * Handles:
129
- * - :param → { name: "param", optional: false, type: string }
130
- * - :param? → { name: "param", optional: true, type: string }
131
- * - :param(a|b) → { name: "param", optional: false, type: "a" | "b" }
132
- * - :param(a|b)? → { name: "param", optional: true, type: "a" | "b" }
133
- */
134
- type ExtractParamInfo<T extends string> =
135
- // Optional + constrained: :param(a|b)?
136
- T extends `${infer Name}(${infer Constraint})?`
137
- ? { name: Name; optional: true; type: ParseConstraint<Constraint> }
138
- : // Constrained only: :param(a|b)
139
- T extends `${infer Name}(${infer Constraint})`
140
- ? { name: Name; optional: false; type: ParseConstraint<Constraint> }
141
- : // Optional only: :param?
142
- T extends `${infer Name}?`
143
- ? { name: Name; optional: true; type: string }
144
- : // Required: :param
145
- { name: T; optional: false; type: string };
146
-
147
- /**
148
- * Build param object from info
149
- */
150
- type ParamFromInfo<Info> = Info extends {
151
- name: infer N extends string;
152
- optional: true;
153
- type: infer V;
154
- }
155
- ? { [K in N]?: V }
156
- : Info extends {
157
- name: infer N extends string;
158
- optional: false;
159
- type: infer V;
160
- }
161
- ? { [K in N]: V }
162
- : never;
163
-
164
- /**
165
- * Merge two param objects preserving optionality
166
- * Uses Pick to preserve the modifiers from source types
167
- */
168
- type MergeParams<A, B> = Pick<A, keyof A> & Pick<B, keyof B> extends infer O
169
- ? { [K in keyof O]: O[K] }
170
- : never;
171
-
172
- /**
173
- * Extract route params from a pattern with depth limit to prevent infinite recursion
174
- *
175
- * Supports:
176
- * - Required params: /:slug → { slug: string }
177
- * - Optional params: /:locale? → { locale?: string }
178
- * - Constrained params: /:locale(en|gb) → { locale: "en" | "gb" }
179
- * - Optional + constrained: /:locale(en|gb)? → { locale?: "en" | "gb" }
180
- *
181
- * @example
182
- * ExtractParams<"/products/:id"> // { id: string }
183
- * ExtractParams<"/:locale?/blog/:slug"> // { locale?: string; slug: string }
184
- * ExtractParams<"/:locale(en|gb)/blog"> // { locale: "en" | "gb" }
185
- * ExtractParams<"/:locale(en|gb)?/blog/:slug"> // { locale?: "en" | "gb"; slug: string }
186
- */
187
- export type ExtractParams<
188
- T extends string,
189
- Depth extends readonly unknown[] = [],
190
- > = Depth["length"] extends 10
191
- ? { [key: string]: string | undefined } // Fallback to generic params if too deep
192
- : // Match param with remaining path: :param.../rest
193
- T extends `${infer _Start}:${infer Param}/${infer Rest}`
194
- ? MergeParams<
195
- ParamFromInfo<ExtractParamInfo<Param>>,
196
- ExtractParams<`/${Rest}`, readonly [...Depth, unknown]>
197
- >
198
- : // Match param at end: :param...
199
- T extends `${infer _Start}:${infer Param}`
200
- ? ParamFromInfo<ExtractParamInfo<Param>>
201
- : {};
202
-
203
- /**
204
- * Route definition - maps route names to patterns
205
- */
206
- /**
207
- * Trailing slash handling mode
208
- * - "never": Redirect URLs with trailing slash to without
209
- * - "always": Redirect URLs without trailing slash to with
210
- * - "ignore": Match both with and without trailing slash
211
- */
212
- export type TrailingSlashMode = "never" | "always" | "ignore";
213
-
214
- /**
215
- * Route configuration object (alternative to string path)
216
- */
217
- export type RouteConfig = {
218
- path: string;
219
- trailingSlash?: TrailingSlashMode;
220
- };
221
-
222
- /**
223
- * Route definition options (global defaults)
224
- */
225
- export type RouteDefinitionOptions = {
226
- trailingSlash?: TrailingSlashMode;
227
- };
228
-
229
- export type RouteDefinition = {
230
- [key: string]: string | RouteConfig | RouteDefinition;
231
- };
232
-
233
- /**
234
- * Recursively flatten nested routes with depth limit to prevent infinite recursion
235
- * Transforms: { products: { detail: "/product/:slug" } } => { "products.detail": "/product/:slug" }
236
- * Also handles RouteConfig objects: { api: { path: "/api" } } => { "api": "/api" }
237
- */
238
- type FlattenRoutes<
239
- T extends RouteDefinition,
240
- Prefix extends string = "",
241
- Depth extends readonly unknown[] = [],
242
- > = Depth["length"] extends 5
243
- ? never
244
- : {
245
- [K in keyof T]: T[K] extends string
246
- ? Record<`${Prefix}${K & string}`, T[K]>
247
- : T[K] extends RouteConfig
248
- ? Record<`${Prefix}${K & string}`, T[K]["path"]>
249
- : T[K] extends RouteDefinition
250
- ? FlattenRoutes<
251
- T[K],
252
- `${Prefix}${K & string}.`,
253
- readonly [...Depth, unknown]
254
- >
255
- : never;
256
- }[keyof T];
257
-
258
- /**
259
- * Union to intersection helper
260
- */
261
- type UnionToIntersection<U> = (
262
- U extends unknown ? (k: U) => void : never
263
- ) extends (k: infer I) => void
264
- ? I
265
- : never;
266
-
267
- /**
268
- * Resolved route map - flattened route definitions with full paths
269
- */
270
- export type ResolvedRouteMap<T extends RouteDefinition> = UnionToIntersection<
271
- FlattenRoutes<T>
272
- >;
273
-
274
- /**
275
- * Handler function that receives context and returns React content or a Response
276
- *
277
- * @template T - Params object OR path pattern string
278
- * @template TEnv - Environment type
279
- *
280
- * @example
281
- * ```typescript
282
- * // With explicit params object
283
- * const handler: Handler<{ id: string }> = (ctx) => {
284
- * ctx.params.id // string
285
- * }
286
- *
287
- * // With path pattern - params extracted automatically
288
- * const handler: Handler<"/product/:id"> = (ctx) => {
289
- * ctx.params.id // string
290
- * }
291
- * ```
292
- */
293
-
294
- /**
295
- * Create a scoped view of a route map by stripping a name prefix.
296
- * Useful for handlers in modules mounted via include() — use the local
297
- * route name instead of the fully qualified global name.
298
- *
299
- * @example
300
- * ```typescript
301
- * // Given GeneratedRouteMap: { "blog.index": "/blog"; "blog.post": "/blog/:postId"; ... }
302
- * type BlogRoutes = ScopedRouteMap<"blog">;
303
- * // Resolves to: { "index": "/blog"; "post": "/blog/:postId" }
304
- *
305
- * const handler: Handler<"post", BlogRoutes> = (ctx) => {
306
- * ctx.params.postId // string
307
- * };
308
- * ```
309
- */
310
- export type ScopedRouteMap<
311
- TPrefix extends string,
312
- TMap = RSCRouter.GeneratedRouteMap,
313
- > = {
314
- [K in keyof TMap as K extends `${TPrefix}.${infer Rest}`
315
- ? Rest
316
- : never]: TMap[K];
317
- };
318
-
319
- /**
320
- * Extract the search schema from a route map entry.
321
- * - string value (old format): no search schema -> {}
322
- * - { path, search } value: extract search
323
- * - { path, response } value (no search): -> {}
324
- */
325
- type ExtractSearchFromRouteMap<TRouteMap, T> =
326
- T extends keyof TRouteMap
327
- ? TRouteMap[T] extends { readonly search: infer S extends SearchSchema }
328
- ? S
329
- : {}
330
- : {};
331
-
332
- export type Handler<
333
- T extends keyof TRouteMap | (string & {}) | Record<string, any> = {},
334
- TRouteMap extends {} = DefaultHandlerRouteMap,
335
- TEnv = DefaultEnv,
336
- > = (
337
- ctx: HandlerContext<
338
- T extends keyof TRouteMap
339
- ? TRouteMap[T] extends string
340
- ? ExtractParams<TRouteMap[T]>
341
- : TRouteMap[T] extends { readonly path: infer P extends string }
342
- ? ExtractParams<P>
343
- : T extends string
344
- ? ExtractParams<T>
345
- : T
346
- : T extends string
347
- ? ExtractParams<T>
348
- : T,
349
- TEnv,
350
- ExtractSearchFromRouteMap<TRouteMap, T>,
351
- TRouteMap extends DefaultHandlerRouteMap ? never : TRouteMap
352
- >,
353
- ) => ReactNode | Promise<ReactNode> | Response | Promise<Response>;
354
-
355
- /**
356
- * Context passed to handlers (Hono-inspired type-safe context)
357
- *
358
- * Provides type-safe access to:
359
- * - Route params (from URL pattern)
360
- * - Request data (request, searchParams, pathname, url)
361
- * - Platform bindings (env.DB, env.KV, env.SECRETS)
362
- * - Middleware variables (var.user, var.permissions)
363
- * - Getter/setter for variables (get('user'), set('user', ...))
364
- *
365
- * **Note:** System parameters (query params starting with `_rsc`) are automatically
366
- * filtered from `url`, `searchParams`, and `request.url` for cleaner access.
367
- *
368
- * @example
369
- * ```typescript
370
- * const handler = (ctx: HandlerContext<{ slug: string }, AppEnv>) => {
371
- * ctx.params.slug // Route param (string)
372
- * ctx.env.DB // Binding (D1Database)
373
- * ctx.var.user // Variable (User | undefined)
374
- * ctx.get('user') // Alternative getter
375
- * ctx.set('user', {...}) // Setter
376
- * ctx.url // Clean URL (no _rsc* params)
377
- * ctx.searchParams // Clean params (no _rsc* params)
378
- * }
379
- * ```
380
- */
381
- export type HandlerContext<TParams = {}, TEnv = DefaultEnv, TSearch extends SearchSchema = {}, TRouteMap = never> = {
382
- /**
383
- * Route parameters extracted from the URL pattern.
384
- * Type-safe when using Handler<"/path/:param"> or Handler<{ param: string }>.
385
- */
386
- params: TParams;
387
- /** @internal Phantom property for params type invariance. Prevents mounting handlers on wrong routes. */
388
- readonly _paramCheck?: (params: TParams) => TParams;
389
- /**
390
- * The incoming Request object.
391
- * System params (`_rsc*`) are filtered from the URL for cleaner access.
392
- */
393
- request: Request;
394
- /**
395
- * Query parameters from the URL (system params like `_rsc*` are filtered).
396
- *
397
- * When a route defines a `search` schema, this is a typed object with
398
- * parsed values. Otherwise it is the standard URLSearchParams.
399
- */
400
- searchParams: {} extends TSearch ? URLSearchParams : ResolveSearchSchema<TSearch>;
401
- /**
402
- * The pathname portion of the request URL.
403
- */
404
- pathname: string;
405
- /**
406
- * The full URL object (with system params filtered).
407
- */
408
- url: URL;
409
- /**
410
- * Platform bindings (DB, KV, secrets, etc.) from RouterEnv.
411
- * Access resources like `ctx.env.DB`, `ctx.env.KV`.
412
- */
413
- env: TEnv extends RouterEnv<infer B, any> ? B : {};
414
- /**
415
- * Middleware-injected variables from RouterEnv.
416
- * Access values like `ctx.var.user`, `ctx.var.permissions`.
417
- */
418
- var: TEnv extends RouterEnv<any, infer V> ? V : {};
419
- /**
420
- * Type-safe getter for middleware variables.
421
- * Alternative to `ctx.var.key` with better autocomplete.
422
- *
423
- * @example
424
- * ```typescript
425
- * const user = ctx.get("user"); // Type-safe!
426
- * ```
427
- */
428
- get: TEnv extends RouterEnv<any, infer V>
429
- ? <K extends keyof V>(key: K) => V[K]
430
- : (key: string) => any;
431
- /**
432
- * Type-safe setter for middleware variables.
433
- * Use in middleware to pass data to handlers.
434
- *
435
- * @example
436
- * ```typescript
437
- * ctx.set("user", { id: "123", name: "John" }); // Type-safe!
438
- * ```
439
- */
440
- set: TEnv extends RouterEnv<any, infer V>
441
- ? <K extends keyof V>(key: K, value: V[K]) => void
442
- : (key: string, value: any) => void;
443
- /**
444
- * Stub response for setting headers/cookies.
445
- * Headers set here are merged into the final response.
446
- *
447
- * @example
448
- * ```typescript
449
- * route("product", (ctx) => {
450
- * ctx.res.headers.set("Cache-Control", "s-maxage=60");
451
- * return <ProductPage />;
452
- * });
453
- * ```
454
- */
455
- res: Response;
456
- /**
457
- * Shorthand for ctx.res.headers - response headers.
458
- * Headers set here are merged into the final response.
459
- *
460
- * @example
461
- * ```typescript
462
- * route("product", (ctx) => {
463
- * ctx.headers.set("Cache-Control", "s-maxage=60");
464
- * return <ProductPage />;
465
- * });
466
- * ```
467
- */
468
- headers: Headers;
469
- /**
470
- * Access loader data or push handle data.
471
- *
472
- * For loaders: Returns a promise that resolves to the loader data.
473
- * Loaders are executed in parallel and memoized per request.
474
- *
475
- * For handles: Returns a push function to add data for this segment.
476
- * Handle data accumulates across all matched route segments.
477
- * Push accepts: direct value, Promise, or async callback (executed immediately).
478
- *
479
- * @example
480
- * ```typescript
481
- * // Loader usage
482
- * route("cart", async (ctx) => {
483
- * const cart = await ctx.use(CartLoader);
484
- * return <CartPage cart={cart} />;
485
- * });
486
- *
487
- * // Handle usage - direct value
488
- * route("shop", (ctx) => {
489
- * const push = ctx.use(Breadcrumbs);
490
- * push({ label: "Shop", href: "/shop" });
491
- * return <ShopPage />;
492
- * });
493
- *
494
- * // Handle usage - Promise
495
- * route("product", (ctx) => {
496
- * const push = ctx.use(Breadcrumbs);
497
- * push(fetchProductBreadcrumb(ctx.params.id));
498
- * return <ProductPage />;
499
- * });
500
- *
501
- * // Handle usage - async callback (executed immediately)
502
- * route("product", (ctx) => {
503
- * const push = ctx.use(Breadcrumbs);
504
- * push(async () => {
505
- * const product = await db.getProduct(ctx.params.id);
506
- * return { label: product.name, href: `/product/${product.id}` };
507
- * });
508
- * return <ProductPage />;
509
- * });
510
- * ```
511
- */
512
- use: {
513
- <T, TLoaderParams = any>(
514
- loader: LoaderDefinition<T, TLoaderParams>,
515
- ): Promise<T>;
516
- <TData, TAccumulated = TData[]>(
517
- handle: Handle<TData, TAccumulated>,
518
- ): (data: TData | Promise<TData> | (() => Promise<TData>)) => void;
519
- };
520
- /**
521
- * Current theme (from cookie or default).
522
- * Only available when theme is enabled in router config.
523
- *
524
- * @example
525
- * ```typescript
526
- * route("settings", (ctx) => {
527
- * const currentTheme = ctx.theme; // "light" | "dark" | "system" | undefined
528
- * return <SettingsPage theme={currentTheme} />;
529
- * });
530
- * ```
531
- */
532
- theme?: Theme;
533
- /**
534
- * Set the theme (only available when theme is enabled in router config).
535
- * Sets a cookie with the new theme value.
536
- *
537
- * @example
538
- * ```typescript
539
- * route("settings", async (ctx) => {
540
- * if (ctx.request.method === "POST") {
541
- * const formData = await ctx.request.formData();
542
- * const newTheme = formData.get("theme") as Theme;
543
- * ctx.setTheme?.(newTheme);
544
- * }
545
- * return <SettingsPage />;
546
- * });
547
- * ```
548
- */
549
- setTheme?: (theme: Theme) => void;
550
- /**
551
- * Generate URLs from route names (Django-style URL reversal).
552
- *
553
- * **Recommended: Use route names for type safety.**
554
- * Route names validate both the route exists and params are correct.
555
- * Path-based URLs (`/...`) are an escape hatch with no validation.
556
- *
557
- * @example
558
- * ```typescript
559
- * // RECOMMENDED: Use route names for type safety
560
- * ctx.reverse("shop.cart") // ✓ Validates route exists
561
- * ctx.reverse("blog.post", { slug: "hello" }) // ✓ Validates route + params
562
- *
563
- * // ESCAPE HATCH: Path-based URLs (no validation)
564
- * ctx.reverse("/about") // ⚠ No type checking
565
- * ```
566
- */
567
- reverse: [TRouteMap] extends [never] ? ScopedReverseFunction<GetRegisteredRoutes> : ScopedReverseFunction<TRouteMap & GetRegisteredRoutes>;
568
- };
569
-
570
- /**
571
- * Internal handler context with additional props for router internals.
572
- * Use `HandlerContext` for user-facing code.
573
- * @internal
574
- */
575
- export type InternalHandlerContext<
576
- TParams = {},
577
- TEnv = DefaultEnv,
578
- TSearch extends SearchSchema = {},
579
- > = HandlerContext<TParams, TEnv, TSearch> & {
580
- /** Raw request with all system parameters intact. */
581
- _originalRequest: Request;
582
- /** Current segment ID for handle data attribution. */
583
- _currentSegmentId?: string;
584
- };
585
-
586
- /**
587
- * Generic params type - flexible object with string keys
588
- * Users can narrow this by explicitly typing their params:
589
- *
590
- * @example
591
- * ```typescript
592
- * [revalidate('post')]: (({ currentParams, nextParams }: RevalidateParams<{ slug: string }>) => {
593
- * currentParams.slug // typed as string
594
- * return currentParams.slug !== nextParams.slug;
595
- * })
596
- * ```
597
- */
598
- export type GenericParams = { [key: string]: string | undefined };
599
-
600
- /**
601
- * Helper type for revalidation handler params
602
- * Allows inline type annotation for stricter param typing
603
- *
604
- * @example
605
- * ```typescript
606
- * [revalidate('post')]: (params: RevalidateParams<{ slug: string }>) => {
607
- * params.currentParams.slug // typed as string
608
- * return params.defaultShouldRevalidate;
609
- * }
610
- * ```
611
- */
612
- export type RevalidateParams<TParams = GenericParams, TEnv = any> = Parameters<
613
- ShouldRevalidateFn<TParams, TEnv>
614
- >[0];
615
-
616
- /**
617
- * Should revalidate function signature (inspired by React Router)
618
- *
619
- * Determines whether a route segment should re-render during partial navigation.
620
- * Multiple revalidation functions can be defined per route - they execute in order.
621
- *
622
- * **Return Types:**
623
- * - `boolean` - Hard decision: immediately returns this value (short-circuits)
624
- * - `{ defaultShouldRevalidate: boolean }` - Soft decision: updates suggestion for next revalidator
625
- *
626
- * **Execution Flow:**
627
- * 1. Start with built-in `defaultShouldRevalidate` (true if params changed)
628
- * 2. Execute global revalidators first, then route-specific
629
- * 3. Hard decision (boolean): stop immediately and use that value
630
- * 4. Soft decision (object): update suggestion and continue to next revalidator
631
- * 5. If all return soft decisions: use the final suggestion
632
- *
633
- * @param args.currentParams - Previous route params (generic by default, can be narrowed)
634
- * @param args.currentUrl - Previous URL
635
- * @param args.nextParams - Next route params (generic by default, can be narrowed)
636
- * @param args.nextUrl - Next URL
637
- * @param args.defaultShouldRevalidate - Current suggestion (updated by soft decisions)
638
- * @param args.context - App context (db, user, etc.)
639
- * @param args.actionResult - Result from action (future support)
640
- * @param args.formData - Form data from action (future support)
641
- * @param args.formMethod - HTTP method from action (future support)
642
- *
643
- * @returns Hard decision (boolean) or soft suggestion (object)
644
- *
645
- * @example
646
- * ```typescript
647
- * // Hard decision - definitive answer
648
- * [revalidate('post')]: ({ currentParams, nextParams }) => {
649
- * return currentParams.slug !== nextParams.slug; // boolean - short-circuits
650
- * }
651
- *
652
- * // Soft decision - allows downstream revalidators to override
653
- * [revalidate('*', 'global')]: ({ defaultShouldRevalidate }) => {
654
- * return { defaultShouldRevalidate: true }; // object - continues to next
655
- * }
656
- *
657
- * // Explicit typing for stricter params
658
- * [revalidate('post')]: ((params: RevalidateParams<{ slug: string }>) => {
659
- * return params.currentParams.slug !== params.nextParams.slug;
660
- * })
661
- * ```
662
- */
663
- export type ShouldRevalidateFn<TParams = GenericParams, TEnv = any> = (args: {
664
- currentParams: TParams;
665
- currentUrl: URL;
666
- nextParams: TParams;
667
- nextUrl: URL;
668
- defaultShouldRevalidate: boolean;
669
- context: HandlerContext<TParams, TEnv>;
670
- // Segment metadata (which segment is being evaluated):
671
- segmentType: "layout" | "route" | "parallel";
672
- layoutName?: string; // Layout name (e.g., "root", "shop", "auth") - only for layouts
673
- slotName?: string; // Slot name (e.g., "@sidebar", "@modal") - only for parallels
674
- // Action context (populated when revalidation triggered by server action):
675
- actionId?: string; // Action identifier (e.g., "src/actions.ts#addToCart")
676
- actionUrl?: URL; // URL where action was executed
677
- actionResult?: any; // Return value from action execution
678
- formData?: FormData; // FormData from action request
679
- method?: string; // Request method: 'GET' for navigation, 'POST' for actions
680
- routeName?: string; // Route name where action was executed (e.g., "products.detail")
681
- // Stale cache revalidation (SWR pattern):
682
- stale?: boolean; // True if this is a stale cache revalidation request
683
- }) => boolean | { defaultShouldRevalidate: boolean };
684
-
685
- /**
686
- * Middleware function signature
687
- *
688
- * Middleware can either call `next()` to continue the pipeline,
689
- * or return a Response to short-circuit and skip remaining middleware + handler.
690
- *
691
- * **Short-Circuit Patterns:**
692
- * - `return redirect('/login')` - Soft redirect (SPA navigation)
693
- * - `return Response.redirect('/login', 302)` - Hard redirect (full page reload)
694
- * - `return new Response('Unauthorized', { status: 401 })` - Error response
695
- *
696
- * @param TParams - Route params (defaults to GenericParams, can be narrowed with satisfies)
697
- * @param TEnv - Environment type
698
- *
699
- * @example
700
- * ```typescript
701
- * [middleware('checkout.*', 'auth')]: [
702
- * (ctx, next) => {
703
- * if (!ctx.get('user')) {
704
- * return redirect('/login'); // Soft redirect - short-circuit
705
- * }
706
- * next(); // Continue pipeline
707
- * }
708
- * ]
709
- * ```
710
- */
711
- // MiddlewareFn is imported from "./router/middleware.js" and re-exported
712
-
713
- /**
714
- * Extract all route keys from a route definition (includes flattened nested routes)
715
- */
716
- export type RouteKeys<T extends RouteDefinition> = keyof ResolvedRouteMap<T> &
717
- string;
718
-
719
- /**
720
- * Valid layout value - component or handler function
721
- * Note: Arrays are not supported. Use separate layout() declarations with unique names instead.
722
- */
723
- type LayoutValue<TEnv = any> = ReactNode | Handler<any, any, TEnv>;
724
-
725
- /**
726
- * Helper to extract params from a route key using the resolved (flattened) route map
727
- */
728
- export type ExtractRouteParams<
729
- T extends RouteDefinition,
730
- K extends string,
731
- > = K extends keyof ResolvedRouteMap<T>
732
- ? ResolvedRouteMap<T>[K] extends string
733
- ? ExtractParams<ResolvedRouteMap<T>[K]>
734
- : GenericParams
735
- : GenericParams;
736
-
737
- /**
738
- * Handlers object that maps route names to handler functions with type-safe string patterns
739
- */
740
- export type HandlersForRouteMap<T extends RouteDefinition, TEnv = any> = {
741
- // Route handlers - type-safe params extracted from route patterns
742
- [K in RouteKeys<T>]?: Handler<ExtractRouteParams<T, K & string>, any, TEnv>;
743
- } & {
744
- // Layout patterns: $layout.{routeName}.{layoutName}
745
- [K in `$layout.${RouteKeys<T> | "*"}.${string}`]?: LayoutValue<TEnv>;
746
- } & {
747
- // Parallel route patterns: $parallel.{routeName}.{parallelName}
748
- [K in `$parallel.${RouteKeys<T>}.${string}`]?: Record<
749
- `@${string}`,
750
- Handler<
751
- K extends `$parallel.${infer RouteKey}.${string}`
752
- ? RouteKey extends RouteKeys<T>
753
- ? ExtractRouteParams<T, RouteKey & string>
754
- : GenericParams
755
- : GenericParams,
756
- any,
757
- TEnv
758
- >
759
- >;
760
- } & {
761
- // Global parallel routes (with '*') use GenericParams
762
- [K in `$parallel.${"*"}.${string}`]?: Record<
763
- `@${string}`,
764
- Handler<GenericParams, any, TEnv>
765
- >;
766
- } & {
767
- // Middleware patterns: $middleware.{routeName}.{middlewareName}
768
- [K in `$middleware.${RouteKeys<T> | "*"}.${string}`]?: MiddlewareFn<
769
- TEnv,
770
- GenericParams
771
- >[];
772
- } & {
773
- // Route revalidate patterns: $revalidate.route.{routeName}.{revalidateName}
774
- [K in `$revalidate.route.${RouteKeys<T> | "*"}.${string}`]?: ShouldRevalidateFn<
775
- GenericParams,
776
- TEnv
777
- >;
778
- } & {
779
- // Layout revalidate patterns: $revalidate.layout.{routeName}.{layoutName}.{revalidateName}
780
- [K in `$revalidate.layout.${RouteKeys<T> | "*"}.${string}.${string}`]?: ShouldRevalidateFn<
781
- GenericParams,
782
- TEnv
783
- >;
784
- } & {
785
- // Parallel revalidate patterns: $revalidate.parallel.{routeName}.{parallelName}.{slotName}.{revalidateName}
786
- [K in `$revalidate.parallel.${RouteKeys<T> | "*"}.${string}.${string}.${string}`]?: ShouldRevalidateFn<
787
- GenericParams,
788
- TEnv
789
- >;
790
- };
791
-
792
- /**
793
- * Error information passed to error boundary fallback components
794
- */
795
- export interface ErrorInfo {
796
- /** Error message (always available) */
797
- message: string;
798
- /** Error name/type (e.g., "RouteNotFoundError", "MiddlewareError") */
799
- name: string;
800
- /** Optional error code for programmatic handling */
801
- code?: string;
802
- /** Stack trace (only in development) */
803
- stack?: string;
804
- /** Original error cause if available */
805
- cause?: unknown;
806
- /** Segment ID where the error occurred */
807
- segmentId: string;
808
- /** Segment type where the error occurred */
809
- segmentType:
810
- | "layout"
811
- | "route"
812
- | "parallel"
813
- | "loader"
814
- | "middleware"
815
- | "cache";
816
- }
817
-
818
- /**
819
- * Props passed to server-side error boundary fallback components
820
- *
821
- * Server error boundaries don't have a reset function since the error
822
- * occurred during server rendering. Users can navigate away or refresh.
823
- *
824
- * @example
825
- * ```typescript
826
- * function ProductErrorFallback({ error }: ErrorBoundaryFallbackProps) {
827
- * return (
828
- * <div>
829
- * <h2>Something went wrong loading the product</h2>
830
- * <p>{error.message}</p>
831
- * <a href="/">Go home</a>
832
- * </div>
833
- * );
834
- * }
835
- * ```
836
- */
837
- export interface ErrorBoundaryFallbackProps {
838
- /** Error information */
839
- error: ErrorInfo;
840
- }
841
-
842
- /**
843
- * Error boundary handler - receives error info and returns fallback UI
844
- */
845
- export type ErrorBoundaryHandler = (
846
- props: ErrorBoundaryFallbackProps,
847
- ) => ReactNode;
848
-
849
- /**
850
- * Props passed to client-side error boundary fallback components
851
- *
852
- * Client error boundaries have a reset function that clears the error state
853
- * and re-renders the children.
854
- *
855
- * @example
856
- * ```typescript
857
- * function ClientErrorFallback({ error, reset }: ClientErrorBoundaryFallbackProps) {
858
- * return (
859
- * <div>
860
- * <h2>Something went wrong</h2>
861
- * <p>{error.message}</p>
862
- * <button onClick={reset}>Try again</button>
863
- * </div>
864
- * );
865
- * }
866
- * ```
867
- */
868
- export interface ClientErrorBoundaryFallbackProps {
869
- /** Error information */
870
- error: ErrorInfo;
871
- /** Function to reset error state and retry rendering */
872
- reset: () => void;
873
- }
874
-
875
- /**
876
- * Wrapped loader data result for deferred resolution with error handling.
877
- * When loaders are deferred to client-side resolution, errors need to be
878
- * wrapped so the client can handle them appropriately.
879
- */
880
- export type LoaderDataResult<T = unknown> =
881
- | { __loaderResult: true; ok: true; data: T }
882
- | {
883
- __loaderResult: true;
884
- ok: false;
885
- error: ErrorInfo;
886
- fallback: ReactNode | null;
887
- };
888
-
889
- /**
890
- * Type guard to check if a value is a wrapped loader result
891
- */
892
- export function isLoaderDataResult(value: unknown): value is LoaderDataResult {
893
- return (
894
- typeof value === "object" &&
895
- value !== null &&
896
- "__loaderResult" in value &&
897
- (value as any).__loaderResult === true
898
- );
899
- }
900
-
901
- /**
902
- * Not found information passed to notFound boundary fallback components
903
- */
904
- export interface NotFoundInfo {
905
- /** Not found message */
906
- message: string;
907
- /** Segment ID where notFound was thrown */
908
- segmentId: string;
909
- /** Segment type where notFound was thrown */
910
- segmentType:
911
- | "layout"
912
- | "route"
913
- | "parallel"
914
- | "loader"
915
- | "middleware"
916
- | "cache";
917
- /** The pathname that triggered the not found */
918
- pathname?: string;
919
- }
920
-
921
- /**
922
- * Props passed to notFound boundary fallback components
923
- *
924
- * @example
925
- * ```typescript
926
- * function ProductNotFound({ notFound }: NotFoundBoundaryFallbackProps) {
927
- * return (
928
- * <div>
929
- * <h2>Product Not Found</h2>
930
- * <p>{notFound.message}</p>
931
- * <a href="/products">Browse all products</a>
932
- * </div>
933
- * );
934
- * }
935
- * ```
936
- */
937
- export interface NotFoundBoundaryFallbackProps {
938
- /** Not found information */
939
- notFound: NotFoundInfo;
940
- }
941
-
942
- /**
943
- * NotFound boundary handler - receives not found info and returns fallback UI
944
- */
945
- export type NotFoundBoundaryHandler = (
946
- props: NotFoundBoundaryFallbackProps,
947
- ) => ReactNode;
948
-
949
- /**
950
- * Resolved segment with component
951
- *
952
- * Segment types:
953
- * - layout: Wraps child content via <Outlet />
954
- * - route: The leaf content for a URL
955
- * - parallel: Named slots rendered via <ParallelOutlet name="@slot" />
956
- * - loader: Data segment (no visual rendering, carries loaderData)
957
- * - error: Error fallback segment (replaces failed segment with error UI)
958
- * - notFound: Not found fallback segment (replaces segment when data not found)
959
- *
960
- * @internal This type is an implementation detail and may change without notice.
961
- */
962
- export interface ResolvedSegment {
963
- id: string;
964
- namespace: string; // Optional namespace for segment (used for parallel groups)
965
- type: "layout" | "route" | "parallel" | "loader" | "error" | "notFound";
966
- index: number;
967
- component: ReactNode; // Component, handler promise, or resolved element
968
- loading?: ReactNode; // Loading component for this segment (shown during navigation)
969
- layout?: ReactNode; // Layout element to wrap content (used by intercept segments)
970
- params?: Record<string, string>;
971
- slot?: string; // For parallel segments: '@sidebar', '@modal', etc.
972
- belongsToRoute?: boolean; // True if segment belongs to the matched route (route itself + its children)
973
- layoutName?: string; // For layouts: the layout name identifier
974
- parallelName?: string; // For parallels: the parallel group name (used to match with revalidations)
975
- // Loader-specific fields
976
- loaderId?: string; // For loaders: the loader $$id identifier
977
- loaderData?: any; // For loaders: the resolved data from loader execution
978
- // Intercept loader fields (for streaming loader data in parallel segments)
979
- loaderDataPromise?: Promise<any[]> | any[]; // Loader data promise or resolved array
980
- loaderIds?: string[]; // IDs ($$id) of loaders for this segment
981
- // Error-specific fields
982
- error?: ErrorInfo; // For error segments: the error information
983
- // NotFound-specific fields
984
- notFoundInfo?: NotFoundInfo; // For notFound segments: the not found information
985
- // Mount path from include() scope, used for MountContext.Provider wrapping
986
- mountPath?: string;
987
- }
988
-
989
- /**
990
- * Segment metadata (without component)
991
- *
992
- * @internal This type is an implementation detail and may change without notice.
993
- */
994
- export interface SegmentMetadata {
995
- id: string;
996
- type: "layout" | "route" | "parallel" | "loader" | "error" | "notFound";
997
- index: number;
998
- params?: Record<string, string>;
999
- slot?: string;
1000
- loaderId?: string;
1001
- error?: ErrorInfo;
1002
- notFoundInfo?: NotFoundInfo;
1003
- }
1004
-
1005
- // Note: route symbols are now defined in route-definition.ts
1006
- // as properties on the route() function
1007
-
1008
- /**
1009
- * State of a named slot (e.g., @modal, @sidebar)
1010
- * Used for intercepting routes where slots render alternative content
1011
- *
1012
- * @internal This type is an implementation detail and may change without notice.
1013
- */
1014
- export interface SlotState {
1015
- /**
1016
- * Whether the slot is currently active (has content to render)
1017
- */
1018
- active: boolean;
1019
- /**
1020
- * Segments for this slot when active
1021
- */
1022
- segments?: ResolvedSegment[];
1023
- }
1024
-
1025
- /**
1026
- * Props passed to the root layout component
1027
- */
1028
- export interface RootLayoutProps {
1029
- children: ReactNode;
1030
- }
1031
-
1032
- /**
1033
- * Router match result
1034
- *
1035
- * @internal This type is an implementation detail and may change without notice.
1036
- */
1037
- export interface MatchResult {
1038
- segments: ResolvedSegment[];
1039
- matched: string[];
1040
- diff: string[];
1041
- /**
1042
- * Merged route params from all matched segments
1043
- * Available for use by the handler after route matching
1044
- */
1045
- params: Record<string, string>;
1046
- /**
1047
- * The matched route name (includes name prefix from include()).
1048
- * Used by ctx.reverse() for local name resolution.
1049
- */
1050
- routeName?: string;
1051
- /**
1052
- * Server-Timing header value (only present when debugPerformance is enabled)
1053
- * Can be added to response headers for DevTools integration
1054
- */
1055
- serverTiming?: string;
1056
- /**
1057
- * State of named slots for this route match
1058
- * Key is slot name (e.g., "@modal"), value is slot state
1059
- * Slots are used for intercepting routes during soft navigation
1060
- */
1061
- slots?: Record<string, SlotState>;
1062
- /**
1063
- * Redirect URL for trailing slash normalization.
1064
- * When set, the RSC handler should return a 308 redirect to this URL
1065
- * instead of rendering the page.
1066
- */
1067
- redirect?: string;
1068
- /**
1069
- * Route-level middleware collected from the matched entry tree.
1070
- * These run with the same onion-style execution as app-level middleware,
1071
- * wrapping the entire RSC response creation.
1072
- */
1073
- routeMiddleware?: Array<{
1074
- handler: import("./router/middleware.js").MiddlewareFn;
1075
- params: Record<string, string>;
1076
- }>;
1077
- }
1078
-
1079
- /**
1080
- * Context captured for lazy include evaluation
1081
- */
1082
- export interface LazyIncludeContext {
1083
- urlPrefix: string;
1084
- namePrefix: string | undefined;
1085
- parent: unknown; // EntryData - avoid circular import
1086
- }
1087
-
1088
- /**
1089
- * Internal route entry stored in router
1090
- */
1091
- export interface RouteEntry<TEnv = any> {
1092
- prefix: string;
1093
- /**
1094
- * Pre-computed static prefix for fast short-circuit matching.
1095
- * Extracted from prefix at registration time (everything before first param).
1096
- *
1097
- * Examples:
1098
- * - "/api" → staticPrefix = "/api"
1099
- * - "/site/:locale" → staticPrefix = "/site"
1100
- * - "/:locale" → staticPrefix = "" (empty, can't optimize)
1101
- *
1102
- * At runtime: if staticPrefix && !pathname.startsWith(staticPrefix), skip entry.
1103
- */
1104
- staticPrefix: string;
1105
- /**
1106
- * Route patterns map. For lazy entries, this starts as empty and is
1107
- * populated on first request.
1108
- */
1109
- routes: ResolvedRouteMap<any>;
1110
- /**
1111
- * Trailing slash config per route key
1112
- * If not specified for a route, defaults to pattern-based detection
1113
- */
1114
- trailingSlash?: Record<string, TrailingSlashMode>;
1115
- handler: () =>
1116
- | Array<AllUseItems>
1117
- | Promise<{ default: () => Array<AllUseItems> }>
1118
- | Promise<() => Array<AllUseItems>>;
1119
- mountIndex: number;
1120
-
1121
- /**
1122
- * Route keys in this entry that have pre-render handlers.
1123
- * Used by the non-trie match path to set the `pr` flag.
1124
- */
1125
- prerenderRouteKeys?: Set<string>;
1126
-
1127
- // === Lazy evaluation fields ===
1128
-
1129
- /**
1130
- * Whether this entry is lazily evaluated.
1131
- * When true, routes are populated on first matching request.
1132
- */
1133
- lazy?: boolean;
1134
-
1135
- /**
1136
- * For lazy entries: the UrlPatterns to evaluate
1137
- */
1138
- lazyPatterns?: unknown;
1139
-
1140
- /**
1141
- * For lazy entries: captured context at definition time
1142
- */
1143
- lazyContext?: LazyIncludeContext;
1144
-
1145
- /**
1146
- * For lazy entries: whether patterns have been evaluated
1147
- */
1148
- lazyEvaluated?: boolean;
1149
- }
1150
-
1151
- /**
1152
- * Revalidation function with typed params
1153
- *
1154
- * @template T - Params object
1155
- * @template TEnv - Environment type
1156
- *
1157
- * @example
1158
- * ```typescript
1159
- * const revalidate: Revalidate<{ slug: string }> = ({ currentParams, nextParams }) => {
1160
- * return currentParams.slug !== nextParams.slug;
1161
- * }
1162
- * ```
1163
- */
1164
- export type Revalidate<
1165
- T = GenericParams,
1166
- TEnv = DefaultEnv,
1167
- > = ShouldRevalidateFn<T, TEnv>;
1168
-
1169
- /**
1170
- * Middleware function with typed params and environment
1171
- *
1172
- * @template TParams - Params object (defaults to generic)
1173
- * @template TEnv - Environment type (defaults to global RSCRouter.Env)
1174
- *
1175
- * Note: Middleware cannot directly use route names for params typing because
1176
- * middleware is defined during router setup, before RegisteredRoutes is populated.
1177
- * Use ExtractParams<"/path/:id"> for typed params from a path pattern.
1178
- *
1179
- * @example
1180
- * ```typescript
1181
- * // Basic middleware (uses global RSCRouter.Env via module augmentation)
1182
- * const middleware: Middleware = async (ctx, next) => {
1183
- * ctx.set("user", { id: "123" }); // Type-safe!
1184
- * await next();
1185
- * }
1186
- *
1187
- * // With explicit params (most common)
1188
- * const middleware: Middleware<{ id: string }> = async (ctx, next) => {
1189
- * console.log(ctx.params.id);
1190
- * await next();
1191
- * }
1192
- *
1193
- * // With params from path pattern
1194
- * const middleware: Middleware<ExtractParams<"/products/:id">> = async (ctx, next) => {
1195
- * console.log(ctx.params.id);
1196
- * await next();
1197
- * }
1198
- *
1199
- * // With both params and explicit env
1200
- * const middleware: Middleware<{ id: string }, AppEnv> = async (ctx, next) => {
1201
- * ctx.set("user", { id: ctx.params.id });
1202
- * await next();
1203
- * }
1204
- * ```
1205
- */
1206
- export type Middleware<
1207
- TParams = GenericParams,
1208
- TEnv = DefaultEnv,
1209
- > = MiddlewareFn<TEnv, TParams>;
1210
-
1211
- // ============================================================================
1212
- // Cache Types
1213
- // ============================================================================
1214
-
1215
- /**
1216
- * Context passed to cache condition/key/tags functions.
1217
- *
1218
- * This is a subset of RequestContext that's guaranteed to be available
1219
- * during cache key generation (before middleware runs).
1220
- *
1221
- * Note: While the full RequestContext is passed, middleware-set variables
1222
- * (ctx.var, ctx.get()) may not be populated yet since cache lookup
1223
- * happens before middleware execution.
1224
- */
1225
- export type { RequestContext as CacheContext } from "./server/request-context.js";
1226
-
1227
- /**
1228
- * Cache configuration options for cache() DSL
1229
- *
1230
- * Controls how segments, layouts, and loaders are cached.
1231
- * Cache configuration inherits down the route tree unless overridden.
1232
- *
1233
- * @example
1234
- * ```typescript
1235
- * // Basic caching with TTL
1236
- * cache({ ttl: 60 }, () => [
1237
- * layout(<BlogLayout />),
1238
- * route("post/:slug"),
1239
- * ])
1240
- *
1241
- * // With stale-while-revalidate
1242
- * cache({ ttl: 60, swr: 300 }, () => [
1243
- * route("product/:id"),
1244
- * ])
1245
- *
1246
- * // Conditional caching
1247
- * cache({
1248
- * ttl: 300,
1249
- * condition: (ctx) => !ctx.request.headers.get('x-preview'),
1250
- * }, () => [...])
1251
- *
1252
- * // Custom cache key
1253
- * cache({
1254
- * ttl: 300,
1255
- * key: (ctx) => `product-${ctx.params.id}-${ctx.searchParams.get('variant')}`,
1256
- * }, () => [...])
1257
- *
1258
- * // With tags for invalidation
1259
- * cache({
1260
- * ttl: 300,
1261
- * tags: (ctx) => [`product:${ctx.params.id}`, 'products'],
1262
- * }, () => [...])
1263
- * ```
1264
- */
1265
- export interface CacheOptions<TEnv = unknown> {
1266
- /**
1267
- * Time-to-live in seconds.
1268
- * After this period, cached content is considered stale.
1269
- */
1270
- ttl: number;
1271
-
1272
- /**
1273
- * Stale-while-revalidate window in seconds (after TTL).
1274
- * During this window, stale content is served immediately while
1275
- * fresh content is fetched in the background via waitUntil.
1276
- *
1277
- * @example
1278
- * // TTL: 60s, SWR: 300s
1279
- * // 0-60s: FRESH (serve from cache)
1280
- * // 60-360s: STALE (serve from cache, revalidate in background)
1281
- * // 360s+: EXPIRED (cache miss, fetch fresh)
1282
- */
1283
- swr?: number;
1284
-
1285
- /**
1286
- * Override the cache store for this boundary.
1287
- * When specified, this boundary and its children use this store
1288
- * instead of the app-level store from handler config.
1289
- *
1290
- * Useful for:
1291
- * - Different backends per route section (memory vs KV vs Redis)
1292
- * - Loader-specific caching strategies
1293
- * - Hot data in fast cache, cold data in larger/slower cache
1294
- *
1295
- * @example
1296
- * ```typescript
1297
- * const kvStore = new CloudflareKVStore(env.CACHE_KV);
1298
- * const memoryStore = new MemorySegmentCacheStore({ defaults: { ttl: 10 } });
1299
- *
1300
- * // Fast memory cache for hot data
1301
- * cache({ store: memoryStore }, () => [
1302
- * route("dashboard"),
1303
- * ])
1304
- *
1305
- * // KV for larger, less frequently accessed data
1306
- * cache({ store: kvStore, ttl: 3600 }, () => [
1307
- * route("archive/:year"),
1308
- * ])
1309
- * ```
1310
- */
1311
- store?: import("./cache/types.js").SegmentCacheStore;
1312
-
1313
- /**
1314
- * Conditional cache read function.
1315
- * Return false to skip cache for this request (always fetch fresh).
1316
- *
1317
- * Has access to full RequestContext including env, request, params, cookies, etc.
1318
- * Note: Middleware-set variables (ctx.var) may not be populated yet.
1319
- *
1320
- * @example
1321
- * ```typescript
1322
- * condition: (ctx) => {
1323
- * // Skip cache for preview mode
1324
- * if (ctx.request.headers.get('x-preview')) return false;
1325
- * // Skip cache for authenticated users
1326
- * if (ctx.request.headers.has('authorization')) return false;
1327
- * return true;
1328
- * }
1329
- * ```
1330
- */
1331
- condition?: (
1332
- ctx: import("./server/request-context.js").RequestContext<TEnv>,
1333
- ) => boolean;
1334
-
1335
- /**
1336
- * Custom cache key function - FULL OVERRIDE.
1337
- * Bypasses default key generation AND store's keyGenerator.
1338
- *
1339
- * Has access to full RequestContext including env, request, params, cookies, etc.
1340
- * Note: Middleware-set variables (ctx.var) may not be populated yet.
1341
- *
1342
- * @example
1343
- * ```typescript
1344
- * // Include query params in cache key
1345
- * key: (ctx) => `product-${ctx.params.id}-${ctx.searchParams.get('variant')}`
1346
- *
1347
- * // Include env bindings
1348
- * key: (ctx) => `${ctx.env.REGION}:product:${ctx.params.id}`
1349
- *
1350
- * // Include cookies
1351
- * key: (ctx) => `${ctx.cookie('locale')}:${ctx.pathname}`
1352
- * ```
1353
- */
1354
- key?: (
1355
- ctx: import("./server/request-context.js").RequestContext<TEnv>,
1356
- ) => string | Promise<string>;
1357
-
1358
- /**
1359
- * Tags for cache invalidation.
1360
- * Can be a static array or a function that returns tags.
1361
- *
1362
- * @example
1363
- * ```typescript
1364
- * // Static tags
1365
- * tags: ['products', 'catalog']
1366
- *
1367
- * // Dynamic tags
1368
- * tags: (ctx) => [`product:${ctx.params.id}`, 'products']
1369
- * ```
1370
- */
1371
- tags?:
1372
- | string[]
1373
- | ((
1374
- ctx: import("./server/request-context.js").RequestContext<TEnv>,
1375
- ) => string[]);
1376
- }
1377
-
1378
- /**
1379
- * Partial cache options for cache() DSL.
1380
- *
1381
- * When `ttl` is not specified, it will use the default from cache config.
1382
- * This allows cache() calls to inherit app-level defaults:
1383
- *
1384
- * @example
1385
- * ```typescript
1386
- * // App-level default (in handler config)
1387
- * cache: { store: myStore, defaults: { ttl: 60 } }
1388
- *
1389
- * // Route-level (inherits ttl from defaults)
1390
- * cache(() => [
1391
- * route("products"),
1392
- * ])
1393
- *
1394
- * // Override with explicit ttl
1395
- * cache({ ttl: 300 }, () => [...])
1396
- * ```
1397
- */
1398
- export type PartialCacheOptions<TEnv = unknown> = Partial<CacheOptions<TEnv>>;
1399
-
1400
- /**
1401
- * Cache entry configuration stored in EntryData.
1402
- * Represents the resolved cache config for a segment.
1403
- */
1404
- export interface EntryCacheConfig {
1405
- /** Cache options (false means caching disabled for this entry) - ttl is optional, uses defaults */
1406
- options: PartialCacheOptions | false;
1407
- }
1408
-
1409
- // ============================================================================
1410
- // Loader Types
1411
- // ============================================================================
1412
-
1413
- /**
1414
- * Context passed to loader functions during execution
1415
- *
1416
- * Loaders run after middleware but before handlers, so they have access
1417
- * to middleware-set variables via get().
1418
- *
1419
- * @template TParams - Route params type (e.g., { slug: string })
1420
- * @template TEnv - Environment type for bindings/variables
1421
- *
1422
- * @example
1423
- * ```typescript
1424
- * const CartLoader = createLoader(async (ctx) => {
1425
- * "use server";
1426
- * const user = ctx.get("user"); // From auth middleware
1427
- * return await db.cart.get(user.id);
1428
- * });
1429
- *
1430
- * // With typed params:
1431
- * const ProductLoader = createLoader<Product, { slug: string }>(async (ctx) => {
1432
- * "use server";
1433
- * const { slug } = ctx.params; // slug is typed as string
1434
- * return await db.products.findBySlug(slug);
1435
- * });
1436
- * ```
1437
- */
1438
- export type LoaderContext<
1439
- TParams = Record<string, string | undefined>,
1440
- TEnv = DefaultEnv,
1441
- TBody = unknown,
1442
- TSearch extends SearchSchema = {},
1443
- > = {
1444
- params: TParams;
1445
- request: Request;
1446
- searchParams: {} extends TSearch ? URLSearchParams : ResolveSearchSchema<TSearch>;
1447
- pathname: string;
1448
- url: URL;
1449
- env: TEnv extends RouterEnv<infer B, any> ? B : {};
1450
- var: TEnv extends RouterEnv<any, infer V> ? V : {};
1451
- get: TEnv extends RouterEnv<any, infer V>
1452
- ? <K extends keyof V>(key: K) => V[K]
1453
- : (key: string) => any;
1454
- /**
1455
- * Access another loader's data (returns promise since loaders run in parallel)
1456
- */
1457
- use: <T, TLoaderParams = any>(
1458
- loader: LoaderDefinition<T, TLoaderParams>,
1459
- ) => Promise<T>;
1460
- /**
1461
- * HTTP method (GET, POST, PUT, PATCH, DELETE)
1462
- * Available when loader is called via load({ method: "POST", ... })
1463
- */
1464
- method: string;
1465
- /**
1466
- * Request body for POST/PUT/PATCH/DELETE requests
1467
- * Available when loader is called via load({ method: "POST", body: {...} })
1468
- */
1469
- body: TBody | undefined;
1470
- /**
1471
- * Form data when loader is invoked via action (fetchable loaders)
1472
- * Available when loader is called via form submission
1473
- */
1474
- formData?: FormData;
1475
- };
1476
-
1477
- /**
1478
- * Loader function signature
1479
- *
1480
- * @template T - The return type of the loader
1481
- * @template TParams - Route params type (defaults to generic Record)
1482
- * @template TEnv - Environment type for bindings/variables
1483
- *
1484
- * @example
1485
- * ```typescript
1486
- * const myLoader: LoaderFn<{ items: Item[] }> = async (ctx) => {
1487
- * "use server";
1488
- * return { items: await db.items.list() };
1489
- * };
1490
- *
1491
- * // With typed params:
1492
- * const productLoader: LoaderFn<Product, { slug: string }> = async (ctx) => {
1493
- * "use server";
1494
- * const { slug } = ctx.params; // typed as string
1495
- * return await db.products.findBySlug(slug);
1496
- * };
1497
- * ```
1498
- */
1499
- export type LoaderFn<
1500
- T,
1501
- TParams = Record<string, string | undefined>,
1502
- TEnv = DefaultEnv,
1503
- > = (ctx: LoaderContext<TParams, TEnv>) => Promise<T> | T;
1504
-
1505
- /**
1506
- * Loader definition object
1507
- *
1508
- * Created via createLoader(). Contains the loader name and function.
1509
- * On client builds, the fn is stripped by the bundler (via "use server" directive).
1510
- *
1511
- * @template T - The return type of the loader
1512
- * @template TParams - Route params type (for type-safe params access)
1513
- *
1514
- * @example
1515
- * ```typescript
1516
- * // Definition (same file works on server and client)
1517
- * export const CartLoader = createLoader(async (ctx) => {
1518
- * "use server";
1519
- * return await db.cart.get(ctx.get("user").id);
1520
- * });
1521
- *
1522
- * // With typed params:
1523
- * export const ProductLoader = createLoader<Product, { slug: string }>(async (ctx) => {
1524
- * "use server";
1525
- * const { slug } = ctx.params; // slug is typed as string
1526
- * return await db.products.findBySlug(slug);
1527
- * });
1528
- *
1529
- * // Server usage
1530
- * const cart = ctx.use(CartLoader);
1531
- *
1532
- * // Client usage (fn is stripped, only name remains)
1533
- * const cart = useLoader(CartLoader);
1534
- * ```
1535
- */
1536
- /**
1537
- * Options for fetchable loaders
1538
- *
1539
- * Middleware uses the same MiddlewareFn signature as route/app middleware,
1540
- * enabling reuse of the same middleware functions everywhere.
1541
- */
1542
- export type FetchableLoaderOptions = {
1543
- fetchable?: true;
1544
- middleware?: MiddlewareFn[];
1545
- };
1546
-
1547
- /**
1548
- * Options for load() calls - type-safe union based on method
1549
- */
1550
- export type LoadOptions =
1551
- | {
1552
- method?: "GET";
1553
- params?: Record<string, string>;
1554
- }
1555
- | {
1556
- method: "POST" | "PUT" | "PATCH" | "DELETE";
1557
- params?: Record<string, string>;
1558
- body?: FormData | Record<string, any>;
1559
- };
1560
-
1561
- /**
1562
- * Context passed to loader action on server
1563
- */
1564
- export type LoaderActionContext = {
1565
- method: string;
1566
- params: Record<string, string>;
1567
- body?: FormData | Record<string, any>;
1568
- formData?: FormData;
1569
- };
1570
-
1571
- /**
1572
- * @deprecated Use MiddlewareFn instead for fetchable loader middleware.
1573
- * This type is kept for backwards compatibility but will be removed in a future version.
1574
- *
1575
- * Fetchable loaders now use the same middleware signature as routes,
1576
- * enabling middleware reuse across routes and loaders.
1577
- */
1578
- export type LoaderMiddlewareFn = (
1579
- ctx: LoaderActionContext,
1580
- next: () => Promise<void>,
1581
- ) => Response | Promise<Response> | void | Promise<void>;
1582
-
1583
- /**
1584
- * Loader action function type - server action for form-based fetching
1585
- * This is a server action that can be passed to useActionState or form action prop.
1586
- *
1587
- * The signature (prevState, formData) is required for useActionState compatibility.
1588
- * When used with useActionState, React passes the previous state as the first argument.
1589
- */
1590
- export type LoaderAction<T> = (
1591
- prevState: T | null,
1592
- formData: FormData,
1593
- ) => Promise<T>;
1594
-
1595
- export type LoaderDefinition<
1596
- T = any,
1597
- TParams = Record<string, string | undefined>,
1598
- > = {
1599
- __brand: "loader";
1600
- $$id: string; // Injected by Vite plugin (exposeInternalIds) - unique identifier
1601
- fn?: LoaderFn<T, TParams, any>; // Optional - server-side only, stored in registry for RSC
1602
- action?: LoaderAction<T>; // Optional - for fetchable loaders
1603
- };
1604
-
1605
- // ============================================================================
1606
- // Error Handling Types
1607
- // ============================================================================
1608
-
1609
- /**
1610
- * Phase where the error occurred during request handling.
1611
- *
1612
- * Coverage notes:
1613
- * - "routing": Invoked when route matching fails (router.ts, rsc/handler.ts)
1614
- * - "manifest": Reserved for manifest loading errors (not currently invoked)
1615
- * - "middleware": Reserved for middleware execution errors (errors propagate to handler phase)
1616
- * - "loader": Invoked when loader execution fails (router.ts via wrapLoaderWithErrorHandling, rsc/handler.ts)
1617
- * - "handler": Invoked when route/layout handler execution fails (router.ts)
1618
- * - "rendering": Invoked during SSR rendering errors (ssr/index.tsx, separate callback)
1619
- * - "action": Invoked when server action execution fails (rsc/handler.ts, router.ts)
1620
- * - "revalidation": Invoked when revalidation fails (router.ts, conditional with action)
1621
- * - "unknown": Fallback for unclassified errors (not currently invoked)
1622
- */
1623
- export type ErrorPhase =
1624
- | "routing" // During route matching
1625
- | "manifest" // During manifest loading (reserved, not currently invoked)
1626
- | "middleware" // During middleware execution (errors propagate to handler phase)
1627
- | "loader" // During loader execution
1628
- | "handler" // During route/layout handler execution
1629
- | "rendering" // During RSC/SSR rendering (SSR handler uses separate callback)
1630
- | "action" // During server action execution
1631
- | "revalidation" // During revalidation evaluation
1632
- | "unknown"; // Fallback for unclassified errors
1633
-
1634
- /**
1635
- * Comprehensive context passed to onError callback
1636
- *
1637
- * Provides all available information about where and when an error occurred
1638
- * during request handling. The callback can use this for logging, monitoring,
1639
- * error tracking services, or custom error responses.
1640
- *
1641
- * @example
1642
- * ```typescript
1643
- * const router = createRouter<AppEnv>({
1644
- * onError: (context) => {
1645
- * // Log to error tracking service
1646
- * errorTracker.capture({
1647
- * error: context.error,
1648
- * phase: context.phase,
1649
- * url: context.request.url,
1650
- * route: context.routeKey,
1651
- * userId: context.env?.user?.id,
1652
- * });
1653
- *
1654
- * // Log to console with context
1655
- * console.error(`[${context.phase}] Error in ${context.routeKey}:`, {
1656
- * message: context.error.message,
1657
- * segment: context.segmentId,
1658
- * duration: context.duration,
1659
- * });
1660
- * },
1661
- * });
1662
- * ```
1663
- */
1664
- export interface OnErrorContext<TEnv = any> {
1665
- /**
1666
- * The error that occurred
1667
- */
1668
- error: Error;
1669
-
1670
- /**
1671
- * Phase where the error occurred
1672
- */
1673
- phase: ErrorPhase;
1674
-
1675
- /**
1676
- * The original request
1677
- */
1678
- request: Request;
1679
-
1680
- /**
1681
- * Parsed URL from the request
1682
- */
1683
- url: URL;
1684
-
1685
- /**
1686
- * Request pathname
1687
- */
1688
- pathname: string;
1689
-
1690
- /**
1691
- * HTTP method
1692
- */
1693
- method: string;
1694
-
1695
- /**
1696
- * Matched route key (if available)
1697
- * e.g., "shop.products.detail"
1698
- */
1699
- routeKey?: string;
1700
-
1701
- /**
1702
- * Route params (if available)
1703
- * e.g., { slug: "headphones" }
1704
- */
1705
- params?: Record<string, string>;
1706
-
1707
- /**
1708
- * Segment ID where error occurred (if available)
1709
- * e.g., "M1L0" for a layout, "M1R0" for a route
1710
- */
1711
- segmentId?: string;
1712
-
1713
- /**
1714
- * Segment type where error occurred (if available)
1715
- */
1716
- segmentType?: "layout" | "route" | "parallel" | "loader" | "middleware";
1717
-
1718
- /**
1719
- * Loader name (if error occurred in a loader)
1720
- */
1721
- loaderName?: string;
1722
-
1723
- /**
1724
- * Middleware name/id (if error occurred in middleware)
1725
- */
1726
- middlewareId?: string;
1727
-
1728
- /**
1729
- * Action ID (if error occurred during server action)
1730
- * e.g., "src/actions.ts#addToCart"
1731
- */
1732
- actionId?: string;
1733
-
1734
- /**
1735
- * Environment/bindings (platform context)
1736
- */
1737
- env?: TEnv;
1738
-
1739
- /**
1740
- * Duration from request start to error (milliseconds)
1741
- */
1742
- duration?: number;
1743
-
1744
- /**
1745
- * Whether this is a partial/navigation request
1746
- */
1747
- isPartial?: boolean;
1748
-
1749
- /**
1750
- * Whether an error boundary caught the error
1751
- * If true, the error was handled and a fallback UI was rendered
1752
- */
1753
- handledByBoundary?: boolean;
1754
-
1755
- /**
1756
- * Stack trace (if available)
1757
- */
1758
- stack?: string;
1759
-
1760
- /**
1761
- * Additional metadata specific to the error phase
1762
- */
1763
- metadata?: Record<string, unknown>;
1764
- }
1765
-
1766
- /**
1767
- * Callback function for error handling
1768
- *
1769
- * Called whenever an error occurs during request handling.
1770
- * The callback is for notification/logging purposes - it cannot
1771
- * modify the error handling flow (use errorBoundary for that).
1772
- *
1773
- * @param context - Comprehensive error context
1774
- *
1775
- * @example
1776
- * ```typescript
1777
- * const onError: OnErrorCallback = (context) => {
1778
- * // Send to error tracking service
1779
- * Sentry.captureException(context.error, {
1780
- * tags: {
1781
- * phase: context.phase,
1782
- * route: context.routeKey,
1783
- * },
1784
- * extra: {
1785
- * url: context.url.toString(),
1786
- * params: context.params,
1787
- * duration: context.duration,
1788
- * },
1789
- * });
1790
- * };
1791
- * ```
1792
- */
1793
- export type OnErrorCallback<TEnv = any> = (
1794
- context: OnErrorContext<TEnv>,
1795
- ) => void | Promise<void>;
1
+ export * from "./types/index.js";