@rangojs/router 0.0.0-experimental.10

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