INDIE UNPKG

38.8 kBTypeScriptView Raw
1
2import { Action, Location, Path, To } from "./history.js";
3import * as React$1 from "react";
4
5//#region lib/router/utils.d.ts
6type MaybePromise<T> = T | Promise<T>;
7/**
8 * Map of routeId -> data returned from a loader/action/error
9 */
10interface RouteData {
11 [routeId: string]: any;
12}
13type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete";
14type UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;
15/**
16 * Users can specify either lowercase or uppercase form methods on `<Form>`,
17 * useSubmit(), `<fetcher.Form>`, etc.
18 */
19type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;
20/**
21 * Active navigation/fetcher form methods are exposed in uppercase on the
22 * RouterState. This is to align with the normalization done via fetch().
23 */
24type FormMethod = UpperCaseFormMethod;
25type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data" | "application/json" | "text/plain";
26type JsonObject = { [Key in string]: JsonValue } & { [Key in string]?: JsonValue | undefined };
27type JsonArray = JsonValue[] | readonly JsonValue[];
28type JsonPrimitive = string | number | boolean | null;
29type JsonValue = JsonPrimitive | JsonObject | JsonArray;
30/**
31 * @private
32 * Internal interface to pass around for action submissions, not intended for
33 * external consumption
34 */
35type Submission = {
36 formMethod: FormMethod;
37 formAction: string;
38 formEncType: FormEncType;
39 formData: FormData;
40 json: undefined;
41 text: undefined;
42} | {
43 formMethod: FormMethod;
44 formAction: string;
45 formEncType: FormEncType;
46 formData: undefined;
47 json: JsonValue;
48 text: undefined;
49} | {
50 formMethod: FormMethod;
51 formAction: string;
52 formEncType: FormEncType;
53 formData: undefined;
54 json: undefined;
55 text: string;
56};
57/**
58 * A context instance used as the key for the `get`/`set` methods of a
59 * {@link RouterContextProvider}. Accepts an optional default
60 * value to be returned if no value has been set.
61 */
62interface RouterContext<T = unknown> {
63 defaultValue?: T;
64}
65/**
66 * Creates a type-safe {@link RouterContext} object that can be used to
67 * store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
68 * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
69 * Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
70 * but specifically designed for React Router's request/response lifecycle.
71 *
72 * If a `defaultValue` is provided, it will be returned from `context.get()`
73 * when no value has been set for the context. Otherwise, reading this context
74 * when no value has been set will throw an error.
75 *
76 * ```tsx filename=app/context.ts
77 * import { createContext } from "react-router";
78 *
79 * // Create a context for user data
80 * export const userContext =
81 * createContext<User | null>(null);
82 * ```
83 *
84 * ```tsx filename=app/middleware/auth.ts
85 * import { getUserFromSession } from "~/auth.server";
86 * import { userContext } from "~/context";
87 *
88 * export const authMiddleware = async ({
89 * context,
90 * request,
91 * }) => {
92 * const user = await getUserFromSession(request);
93 * context.set(userContext, user);
94 * };
95 * ```
96 *
97 * ```tsx filename=app/routes/profile.tsx
98 * import { userContext } from "~/context";
99 *
100 * export async function loader({
101 * context,
102 * }: Route.LoaderArgs) {
103 * const user = context.get(userContext);
104 *
105 * if (!user) {
106 * throw new Response("Unauthorized", { status: 401 });
107 * }
108 *
109 * return { user };
110 * }
111 * ```
112 *
113 * @public
114 * @category Utils
115 * @mode framework
116 * @mode data
117 * @param defaultValue An optional default value for the context. This value
118 * will be returned if no value has been set for this context.
119 * @returns A {@link RouterContext} object that can be used with
120 * `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
121 * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
122 */
123declare function createContext<T>(defaultValue?: T): RouterContext<T>;
124/**
125 * Provides methods for writing/reading values in application context in a
126 * type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
127 *
128 * @example
129 * import {
130 * createContext,
131 * RouterContextProvider
132 * } from "react-router";
133 *
134 * const userContext = createContext<User | null>(null);
135 * const contextProvider = new RouterContextProvider();
136 * contextProvider.set(userContext, getUser());
137 * // ^ Type-safe
138 * const user = contextProvider.get(userContext);
139 * // ^ User
140 *
141 * @public
142 * @category Utils
143 * @mode framework
144 * @mode data
145 */
146declare class RouterContextProvider {
147 #private;
148 /**
149 * Create a new `RouterContextProvider` instance
150 * @param init An optional initial context map to populate the provider with
151 */
152 constructor(init?: Map<RouterContext, unknown>);
153 /**
154 * Access a value from the context. If no value has been set for the context,
155 * it will return the context's `defaultValue` if provided, or throw an error
156 * if no `defaultValue` was set.
157 * @param context The context to get the value for
158 * @returns The value for the context, or the context's `defaultValue` if no
159 * value was set
160 */
161 get<T>(context: RouterContext<T>): T;
162 /**
163 * Set a value for the context. If the context already has a value set, this
164 * will overwrite it.
165 *
166 * @param context The context to set the value for
167 * @param value The value to set for the context
168 * @returns {void}
169 */
170 set<C extends RouterContext>(context: C, value: C extends RouterContext<infer T> ? T : never): void;
171}
172type DefaultContext = Readonly<RouterContextProvider>;
173/**
174 * @private
175 * Arguments passed to route loader/action functions. Same for now but we keep
176 * this as a private implementation detail in case they diverge in the future.
177 */
178interface DataFunctionArgs<Context> {
179 /** A {@link https://developer.mozilla.org/en-US/docs/Web/API/Request Fetch Request instance} which you can use to read headers (like cookies, and {@link https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams URLSearchParams} from the request. */
180 request: Request;
181 /**
182 * A URL instance representing the application location being navigated to or
183 * fetched.
184 *
185 * In Framework mode, this is a normalized URL with React-Router-specific
186 * implementation details removed (`.data` suffixes, `index`/`_routes` search
187 * params). For the raw incoming URL, use `request.url`.
188 */
189 url: URL;
190 /**
191 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
192 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
193 */
194 pattern: string;
195 /**
196 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
197 * @example
198 * // app/routes.ts
199 * route("teams/:teamId", "./team.tsx"),
200 *
201 * // app/team.tsx
202 * export function loader({
203 * params,
204 * }: Route.LoaderArgs) {
205 * params.teamId;
206 * // ^ string
207 * }
208 */
209 params: Params;
210 /**
211 * This is the context passed in to your server adapter's getLoadContext() function.
212 * It's a way to bridge the gap between the adapter's request/response API with your React Router app.
213 * It is only applicable if you are using a custom server adapter.
214 */
215 context: Context;
216}
217/**
218 * Route middleware `next` function to call downstream handlers and then complete
219 * middlewares from the bottom-up
220 */
221interface MiddlewareNextFunction<Result = unknown> {
222 (): Promise<Result>;
223}
224/**
225 * Route middleware function signature. Receives the same "data" arguments as a
226 * `loader`/`action` (`request`, `params`, `context`) as the first parameter and
227 * a `next` function as the second parameter which will call downstream handlers
228 * and then complete middlewares from the bottom-up
229 */
230type MiddlewareFunction<Result = unknown> = (args: DataFunctionArgs<Readonly<RouterContextProvider>>, next: MiddlewareNextFunction<Result>) => MaybePromise<Result | void>;
231/**
232 * Arguments passed to loader functions
233 */
234interface LoaderFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {}
235/**
236 * Arguments passed to action functions
237 */
238interface ActionFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {}
239/**
240 * Loaders and actions can return anything
241 */
242type DataFunctionValue = unknown;
243type DataFunctionReturnValue = MaybePromise<DataFunctionValue>;
244/**
245 * Route loader function signature
246 */
247type LoaderFunction<Context = DefaultContext> = {
248 (args: LoaderFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
249} & {
250 hydrate?: boolean;
251};
252/**
253 * Route action function signature
254 */
255interface ActionFunction<Context = DefaultContext> {
256 (args: ActionFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
257}
258/**
259 * Arguments passed to shouldRevalidate function
260 */
261interface ShouldRevalidateFunctionArgs {
262 /** This is the url the navigation started from. You can compare it with `nextUrl` to decide if you need to revalidate this route's data. */
263 currentUrl: URL;
264 /** These are the {@link https://reactrouter.com/start/framework/routing#dynamic-segments dynamic route params} from the URL that can be compared to the `nextParams` to decide if you need to reload or not. Perhaps you're using only a partial piece of the param for data loading, you don't need to revalidate if a superfluous part of the param changed. */
265 currentParams: DataRouteMatch["params"];
266 /** In the case of navigation, this the URL the user is requesting. Some revalidations are not navigation, so it will simply be the same as currentUrl. */
267 nextUrl: URL;
268 /** In the case of navigation, these are the {@link https://reactrouter.com/start/framework/routing#dynamic-segments dynamic route params} from the next location the user is requesting. Some revalidations are not navigation, so it will simply be the same as currentParams. */
269 nextParams: DataRouteMatch["params"];
270 /** The method (probably `"GET"` or `"POST"`) used in the form submission that triggered the revalidation. */
271 formMethod?: Submission["formMethod"];
272 /** The form action (`<Form action="/somewhere">`) that triggered the revalidation. */
273 formAction?: Submission["formAction"];
274 /** The form encType (`<Form encType="application/x-www-form-urlencoded">) used in the form submission that triggered the revalidation*/
275 formEncType?: Submission["formEncType"];
276 /** The form submission data when the form's encType is `text/plain` */
277 text?: Submission["text"];
278 /** The form submission data when the form's encType is `application/x-www-form-urlencoded` or `multipart/form-data` */
279 formData?: Submission["formData"];
280 /** The form submission data when the form's encType is `application/json` */
281 json?: Submission["json"];
282 /** The status code of the action response */
283 actionStatus?: number;
284 /**
285 * When a submission causes the revalidation this will be the result of the action—either action data or an error if the action failed. It's common to include some information in the action result to instruct shouldRevalidate to revalidate or not.
286 *
287 * @example
288 * export async function action() {
289 * await saveSomeStuff();
290 * return { ok: true };
291 * }
292 *
293 * export function shouldRevalidate({
294 * actionResult,
295 * }) {
296 * if (actionResult?.ok) {
297 * return false;
298 * }
299 * return true;
300 * }
301 */
302 actionResult?: any;
303 /**
304 * By default, React Router doesn't call every loader all the time. There are reliable optimizations it can make by default. For example, only loaders with changing params are called. Consider navigating from the following URL to the one below it:
305 *
306 * /projects/123/tasks/abc
307 * /projects/123/tasks/def
308 * React Router will only call the loader for tasks/def because the param for projects/123 didn't change.
309 *
310 * It's safest to always return defaultShouldRevalidate after you've done your specific optimizations that return false, otherwise your UI might get out of sync with your data on the server.
311 */
312 defaultShouldRevalidate: boolean;
313}
314/**
315 * Route shouldRevalidate function signature. This runs after any submission
316 * (navigation or fetcher), so we flatten the navigation/fetcher submission
317 * onto the arguments. It shouldn't matter whether it came from a navigation
318 * or a fetcher, what really matters is the URLs and the formData since loaders
319 * have to re-run based on the data models that were potentially mutated.
320 */
321interface ShouldRevalidateFunction {
322 (args: ShouldRevalidateFunctionArgs): boolean;
323}
324interface DataStrategyMatch extends RouteMatch<string, DataRouteObject> {
325 /**
326 * @private
327 */
328 _lazyPromises?: {
329 middleware: Promise<void> | undefined;
330 handler: Promise<void> | undefined;
331 route: Promise<void> | undefined;
332 };
333 /**
334 * @deprecated Deprecated in favor of `shouldCallHandler`
335 *
336 * A boolean value indicating whether this route handler should be called in
337 * this pass.
338 *
339 * The `matches` array always includes _all_ matched routes even when only
340 * _some_ route handlers need to be called so that things like middleware can
341 * be implemented.
342 *
343 * `shouldLoad` is usually only interesting if you are skipping the route
344 * handler entirely and implementing custom handler logic - since it lets you
345 * determine if that custom logic should run for this route or not.
346 *
347 * For example:
348 * - If you are on `/parent/child/a` and you navigate to `/parent/child/b` -
349 * you'll get an array of three matches (`[parent, child, b]`), but only `b`
350 * will have `shouldLoad=true` because the data for `parent` and `child` is
351 * already loaded
352 * - If you are on `/parent/child/a` and you submit to `a`'s [`action`](https://reactrouter.com/docs/start/data/route-object#action),
353 * then only `a` will have `shouldLoad=true` for the action execution of
354 * `dataStrategy`
355 * - After the [`action`](https://reactrouter.com/docs/start/data/route-object#action),
356 * `dataStrategy` will be called again for the [`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
357 * revalidation, and all matches will have `shouldLoad=true` (assuming no
358 * custom `shouldRevalidate` implementations)
359 */
360 shouldLoad: boolean;
361 /**
362 * Arguments passed to the `shouldRevalidate` function for this `loader` execution.
363 * Will be `null` if this is not a revalidating loader {@link DataStrategyMatch}.
364 */
365 shouldRevalidateArgs: ShouldRevalidateFunctionArgs | null;
366 /**
367 * Determine if this route's handler should be called during this `dataStrategy`
368 * execution. Calling it with no arguments will leverage the default revalidation
369 * behavior. You can pass your own `defaultShouldRevalidate` value if you wish
370 * to change the default revalidation behavior with your `dataStrategy`.
371 *
372 * @param defaultShouldRevalidate `defaultShouldRevalidate` override value (optional)
373 */
374 shouldCallHandler(defaultShouldRevalidate?: boolean): boolean;
375 /**
376 * An async function that will resolve any `route.lazy` implementations and
377 * execute the route's handler (if necessary), returning a {@link DataStrategyResult}
378 *
379 * - Calling `match.resolve` does not mean you're calling the
380 * [`action`](https://reactrouter.com/docs/start/data/route-object#action)/[`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
381 * (the "handler") - `resolve` will only call the `handler` internally if
382 * needed _and_ if you don't pass your own `handlerOverride` function parameter
383 * - It is safe to call `match.resolve` for all matches, even if they have
384 * `shouldLoad=false`, and it will no-op if no loading is required
385 * - You should generally always call `match.resolve()` for `shouldLoad:true`
386 * routes to ensure that any `route.lazy` implementations are processed
387 * - See the examples below for how to implement custom handler execution via
388 * `match.resolve`
389 */
390 resolve: (handlerOverride?: (handler: (ctx?: unknown) => DataFunctionReturnValue) => DataFunctionReturnValue) => Promise<DataStrategyResult>;
391}
392/**
393 * The operation that initiated a data strategy execution. Static handler
394 * executions use `"static"`.
395 */
396type DataStrategyInitiator = "initialization" | "navigation" | "fetcher" | "revalidation" | "static";
397interface DataStrategyFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
398 /**
399 * Matches for this route extended with Data strategy APIs
400 */
401 matches: DataStrategyMatch[];
402 runClientMiddleware: (cb: DataStrategyFunction<Context>) => Promise<Record<string, DataStrategyResult>>;
403 /**
404 * The operation that initiated this data strategy execution
405 *
406 * This field is experimental and subject to breaking changes.
407 */
408 unstable_initiator: DataStrategyInitiator;
409 /**
410 * The history action (`"PUSH"`, `"REPLACE"`, or `"POP"`) for a navigation-
411 * initiated execution, including fetchers reloaded by that navigation.
412 * `null` for initialization, fetcher, revalidation, and static executions.
413 *
414 * This field is experimental and subject to breaking changes.
415 */
416 unstable_navigationType: Action | null;
417 /**
418 * The key of the fetcher targeted by this data strategy execution, otherwise
419 * `null`. Fetchers reloaded during a navigation or revalidation retain that
420 * `unstable_initiator` while providing their key here.
421 */
422 fetcherKey: string | null;
423}
424/**
425 * Result from a loader or action called via dataStrategy
426 */
427interface DataStrategyResult {
428 type: "data" | "error";
429 result: unknown;
430}
431interface DataStrategyFunction<Context = DefaultContext> {
432 (args: DataStrategyFunctionArgs<Context>): Promise<Record<string, DataStrategyResult>>;
433}
434type PatchRoutesOnNavigationFunctionArgs = {
435 signal: AbortSignal;
436 path: string;
437 matches: RouteMatch[];
438 fetcherKey: string | undefined;
439 patch: (routeId: string | null, children: RouteObject[]) => void;
440};
441type PatchRoutesOnNavigationFunction = (opts: PatchRoutesOnNavigationFunctionArgs) => MaybePromise<void>;
442/**
443 * Function provided to set route-specific properties from route objects
444 */
445interface MapRoutePropertiesFunction {
446 (route: DataRouteObject): Partial<DataRouteObject>;
447}
448/**
449 * Keys we cannot change from within a lazy object. We spread all other keys
450 * onto the route. Either they're meaningful to the router, or they'll get
451 * ignored.
452 */
453type UnsupportedLazyRouteObjectKey = "lazy" | "caseSensitive" | "path" | "id" | "index" | "children" | "unstable_validateParams";
454/**
455 * Keys we cannot change from within a lazy() function. We spread all other keys
456 * onto the route. Either they're meaningful to the router, or they'll get
457 * ignored.
458 */
459type UnsupportedLazyRouteFunctionKey = UnsupportedLazyRouteObjectKey | "middleware";
460/**
461 * lazy object to load route properties, which can add non-matching
462 * related properties to a route
463 */
464type LazyRouteObject<R extends RouteObject> = { [K in keyof R as K extends UnsupportedLazyRouteObjectKey ? never : K]?: () => Promise<R[K] | null | undefined> };
465/**
466 * lazy() function to load a route definition, which can add non-matching
467 * related properties to a route
468 */
469interface LazyRouteFunction<R extends RouteObject> {
470 (): Promise<Omit<R, UnsupportedLazyRouteFunctionKey> & Partial<Record<UnsupportedLazyRouteFunctionKey, never>>>;
471}
472type LazyRouteDefinition<R extends RouteObject> = LazyRouteObject<R> | LazyRouteFunction<R>;
473/**
474 * Base RouteObject with common props shared by all types of routes
475 * @internal
476 */
477type BaseRouteObject = {
478 /**
479 * Whether the path should be case-sensitive. Defaults to `false`.
480 */
481 caseSensitive?: boolean;
482 /**
483 * The path pattern to match. If unspecified or empty, then this becomes a
484 * layout route.
485 */
486 path?: string;
487 /**
488 * The unique identifier for this route (for use with {@link DataRouter}s)
489 */
490 id?: string;
491 /**
492 * The route middleware.
493 * See [`middleware`](../../start/data/route-object#middleware).
494 */
495 middleware?: MiddlewareFunction[];
496 /**
497 * The route loader.
498 * See [`loader`](../../start/data/route-object#loader).
499 */
500 loader?: LoaderFunction | boolean;
501 /**
502 * The route action.
503 * See [`action`](../../start/data/route-object#action).
504 */
505 action?: ActionFunction | boolean;
506 /**
507 * The route shouldRevalidate function.
508 * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
509 */
510 shouldRevalidate?: ShouldRevalidateFunction;
511 /**
512 * A map of route param names to regular expressions used to validate params
513 * after a route-pattern match.
514 */
515 unstable_validateParams?: Record<string, RegExp>;
516 /**
517 * The route handle.
518 */
519 handle?: any;
520 /**
521 * A function that returns a promise that resolves to the route object.
522 * Used for code-splitting routes.
523 * See [`lazy`](../../start/data/route-object#lazy).
524 */
525 lazy?: LazyRouteDefinition<BaseRouteObject>;
526 /**
527 * The React Component to render when this route matches.
528 * Mutually exclusive with `element`.
529 */
530 Component?: React$1.ComponentType | null;
531 /**
532 * The React element to render when this Route matches.
533 * Mutually exclusive with `Component`.
534 */
535 element?: React$1.ReactNode | null;
536 /**
537 * The React Component to render at this route if an error occurs.
538 * Mutually exclusive with `errorElement`.
539 */
540 ErrorBoundary?: React$1.ComponentType | null;
541 /**
542 * The React element to render at this route if an error occurs.
543 * Mutually exclusive with `ErrorBoundary`.
544 */
545 errorElement?: React$1.ReactNode | null;
546 /**
547 * The React Component to render while this router is loading data.
548 * Mutually exclusive with `hydrateFallbackElement`.
549 */
550 HydrateFallback?: React$1.ComponentType | null;
551 /**
552 * The React element to render while this router is loading data.
553 * Mutually exclusive with `HydrateFallback`.
554 */
555 hydrateFallbackElement?: React$1.ReactNode | null;
556};
557/**
558 * Index routes must not have children
559 */
560type IndexRouteObject = BaseRouteObject & {
561 /**
562 * Child Route objects - not valid on index routes.
563 */
564 children?: undefined;
565 /**
566 * Whether this is an index route.
567 */
568 index: true;
569};
570/**
571 * Non-index routes may have children, but cannot have `index` set to `true`.
572 */
573type NonIndexRouteObject = BaseRouteObject & {
574 /**
575 * Child Route objects.
576 */
577 children?: RouteObject[];
578 /**
579 * Whether this is an index route - must be `false` or undefined on non-index routes.
580 */
581 index?: false;
582};
583/**
584 * A route object represents a logical route, with (optionally) its child
585 * routes organized in a tree-like structure.
586 */
587type RouteObject = IndexRouteObject | NonIndexRouteObject;
588type DataIndexRouteObject = IndexRouteObject & {
589 id: string;
590};
591type DataNonIndexRouteObject = NonIndexRouteObject & {
592 children?: DataRouteObject[];
593 id: string;
594};
595/**
596 * A data route object, which is just a RouteObject with a required unique ID
597 */
598type DataRouteObject = DataIndexRouteObject | DataNonIndexRouteObject;
599type RouteManifest<R = DataRouteObject> = Record<string, R | undefined>;
600type Regex_az = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z";
601type Regex_AZ = Uppercase<Regex_az>;
602type Regex_09 = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
603type Regex_w = Regex_az | Regex_AZ | Regex_09 | "_";
604/** Emulates Regex `+` operator */
605type RegexMatchPlus<char extends string, T extends string> = _RegexMatchPlus<char, T> extends infer result extends string ? result extends '' ? never : result : never;
606type _RegexMatchPlus<char extends string, T extends string> = T extends `${infer head extends char}${infer rest}` ? `${head}${_RegexMatchPlus<char, rest>}` : '';
607type ParamNameChar = Regex_w | "-";
608type Simplify<T> = { [K in keyof T]: T[K] } & {};
609type GeneratePathParams<path extends string> = Simplify<ParseParams<path> & { [key in string]: string | null | undefined }>;
610type ParseParams<path extends string> = path extends '*' ? {
611 '*': string;
612} : path extends `${infer rest}/*` ? {
613 '*': string;
614} & ParseParams<rest> : _ParseParams<path>;
615type _ParseParams<path extends string> = path extends `${infer left}/${infer right}` ? _ParseParams<left> & _ParseParams<right> : path extends `:${infer param}?${string}` ? { [key in RegexMatchPlus<ParamNameChar, param>]?: string | null | undefined } : path extends `:${infer param}` ? { [key in RegexMatchPlus<ParamNameChar, param>]: string } : {};
616type PathParam<path extends string> = (keyof ParseParams<path>) & string;
617type ParamParseKey<Segment extends string> = [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;
618/**
619 * The parameters that were parsed from the URL path.
620 */
621type Params<Key extends string = string> = { readonly [key in Key]: string | undefined };
622/**
623 * A RouteMatch contains info about how a route matched a URL.
624 */
625interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> {
626 /**
627 * The names and values of dynamic parameters in the URL.
628 */
629 params: Params<ParamKey>;
630 /**
631 * The portion of the URL pathname that was matched.
632 */
633 pathname: string;
634 /**
635 * The portion of the URL pathname that was matched before child routes.
636 */
637 pathnameBase: string;
638 /**
639 * The route object that was used to match.
640 */
641 route: RouteObjectType;
642}
643interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}
644declare function defaultMapRouteProperties(route: DataRouteObject): Partial<DataRouteObject>;
645/**
646 * Matches the given routes to a location and returns the match data.
647 *
648 * @example
649 * import { matchRoutes } from "react-router";
650 *
651 * let routes = [{
652 * path: "/",
653 * Component: Root,
654 * children: [{
655 * path: "dashboard",
656 * Component: Dashboard,
657 * }]
658 * }];
659 *
660 * matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
661 *
662 * @public
663 * @category Utils
664 * @param routes The array of route objects to match against.
665 * @param locationArg The location to match against, either a string path or a
666 * partial {@link Location} object
667 * @param basename Optional base path to strip from the location before matching.
668 * Defaults to `/`.
669 * @returns An array of matched routes, or `null` if no matches were found.
670 */
671declare function matchRoutes<RouteObjectType extends RouteObject = RouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): RouteMatch<string, RouteObjectType>[] | null;
672interface UIMatch<Data = unknown, Handle = unknown> {
673 id: string;
674 pathname: string;
675 /**
676 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
677 */
678 params: RouteMatch["params"];
679 /**
680 * The return value from the matched route's loader or clientLoader. This might
681 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
682 * an error and we're currently displaying an `ErrorBoundary`.
683 */
684 loaderData: Data | undefined;
685 /**
686 * The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
687 * exported from the matched route module
688 */
689 handle: Handle;
690}
691interface RouteMeta<RouteObjectType extends RouteObject = RouteObject> {
692 relativePath: string;
693 caseSensitive: boolean;
694 childrenIndex: number;
695 route: RouteObjectType;
696 matcher?: RegExp;
697 compiledParams?: CompiledPathParam[];
698}
699/**
700 * @private
701 * PRIVATE - DO NOT USE
702 *
703 * A "branch" of routes that match a given route pattern.
704 * This is an internal interface not intended for direct external usage.
705 */
706interface RouteBranch<RouteObjectType extends RouteObject = RouteObject> {
707 path: string;
708 score: number;
709 routesMeta: RouteMeta<RouteObjectType>[];
710}
711/**
712 * Returns a path with params interpolated.
713 *
714 * Param values are percent-encoded for use in a path segment: characters that
715 * would change the URL structure (`/`, `?`, `#`, `%`, whitespace, non-ASCII)
716 * are escaped, while characters that RFC 3986 allows literally in a path
717 * segment (`$ & + , ; = : @`) are kept as-is. Note this differs from query-string
718 * encoding (`encodeURIComponent`/`URLSearchParams`), where those characters are
719 * delimiters and must be escaped. Splat (`*`) values are encoded per segment,
720 * preserving `/` separators.
721 *
722 * See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3)
723 *
724 * @example
725 * import { generatePath } from "react-router";
726 *
727 * generatePath("/users/:id", { id: "123" }); // "/users/123"
728 * generatePath("/files/:name", { name: "a b" }); // "/files/a%20b"
729 * generatePath("/releases/:v", { v: "1.0.0+1" }); // "/releases/1.0.0+1"
730 *
731 * @public
732 * @category Utils
733 * @param originalPath The original path to generate.
734 * @param params The parameters to interpolate into the path.
735 * @returns The generated path with parameters interpolated.
736 */
737declare function generatePath<Path extends string>(originalPath: Path, params?: GeneratePathParams<Path>): string;
738/**
739 * Used to match on some portion of a URL pathname.
740 */
741interface PathPattern<Path extends string = string> {
742 /**
743 * A string to match against a URL pathname. May contain `:id`-style segments
744 * to indicate placeholders for dynamic parameters. It May also end with `/*`
745 * to indicate matching the rest of the URL pathname.
746 */
747 path: Path;
748 /**
749 * Should be `true` if the static portions of the `path` should be matched in
750 * the same case.
751 */
752 caseSensitive?: boolean;
753 /**
754 * Should be `true` if this pattern should match the entire URL pathname.
755 */
756 end?: boolean;
757}
758/**
759 * Contains info about how a {@link PathPattern} matched on a URL pathname.
760 */
761interface PathMatch<ParamKey extends string = string> {
762 /**
763 * The names and values of dynamic parameters in the URL.
764 */
765 params: Params<ParamKey>;
766 /**
767 * The portion of the URL pathname that was matched.
768 */
769 pathname: string;
770 /**
771 * The portion of the URL pathname that was matched before child routes.
772 */
773 pathnameBase: string;
774 /**
775 * The pattern that was used to match.
776 */
777 pattern: PathPattern;
778}
779/**
780 * Performs pattern matching on a URL pathname and returns information about
781 * the match.
782 *
783 * @public
784 * @category Utils
785 * @param pattern The pattern to match against the URL pathname. This can be a
786 * string or a {@link PathPattern} object. If a string is provided, it will be
787 * treated as a pattern with `caseSensitive` set to `false` and `end` set to
788 * `true`.
789 * @param pathname The URL pathname to match against the pattern.
790 * @returns A path match object if the pattern matches the pathname,
791 * or `null` if it does not match.
792 */
793declare function matchPath<Path extends string>(pattern: PathPattern<Path> | Path, pathname: string): PathMatch<ParamParseKey<Path>> | null;
794type CompiledPathParam = {
795 paramName: string;
796 isOptional?: boolean;
797};
798/**
799 * Returns a resolved {@link Path} object relative to the given pathname.
800 *
801 * @public
802 * @category Utils
803 * @param to The path to resolve, either a string or a partial {@link Path}
804 * object.
805 * @param fromPathname The pathname to resolve the path from. Defaults to `/`.
806 * @returns A {@link Path} object with the resolved pathname, search, and hash.
807 */
808declare function resolvePath(to: To, fromPathname?: string): Path;
809declare class DataWithResponseInit<D> {
810 type: string;
811 data: D;
812 init: ResponseInit | null;
813 constructor(data: D, init?: ResponseInit);
814}
815/**
816 * Create "responses" that contain `headers`/`status` without forcing
817 * serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
818 *
819 * @example
820 * import { data } from "react-router";
821 *
822 * export async function action({ request }: Route.ActionArgs) {
823 * let formData = await request.formData();
824 * let item = await createItem(formData);
825 * return data(item, {
826 * headers: { "X-Custom-Header": "value" }
827 * status: 201,
828 * });
829 * }
830 *
831 * @public
832 * @category Utils
833 * @mode framework
834 * @mode data
835 * @param data The data to be included in the response.
836 * @param init The status code or a `ResponseInit` object to be included in the
837 * response.
838 * @returns A {@link DataWithResponseInit} instance containing the data and
839 * response init.
840 */
841declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
842interface TrackedPromise extends Promise<any> {
843 _tracked?: boolean;
844 _data?: any;
845 _error?: any;
846}
847type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
848/**
849 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
850 * Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
851 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
852 *
853 * This utility accepts absolute URLs and can navigate to external domains, so
854 * the application should validate any user-supplied inputs to redirects.
855 *
856 * @example
857 * import { redirect } from "react-router";
858 *
859 * export async function loader({ request }: Route.LoaderArgs) {
860 * if (!isLoggedIn(request))
861 * throw redirect("/login");
862 * }
863 *
864 * // ...
865 * }
866 *
867 * @public
868 * @category Utils
869 * @mode framework
870 * @mode data
871 * @param url The URL to redirect to.
872 * @param init The status code or a `ResponseInit` object to be included in the
873 * response.
874 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
875 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
876 * header.
877 */
878declare const redirect: RedirectFunction;
879/**
880 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
881 * that will force a document reload to the new location. Sets the status code
882 * and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
883 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
884 *
885 * This utility accepts absolute URLs and can navigate to external domains, so
886 * the application should validate any user-supplied inputs to redirects.
887 *
888 * ```tsx filename=routes/logout.tsx
889 * import { redirectDocument } from "react-router";
890 *
891 * import { destroySession } from "../sessions.server";
892 *
893 * export async function action({ request }: Route.ActionArgs) {
894 * let session = await getSession(request.headers.get("Cookie"));
895 * return redirectDocument("/", {
896 * headers: { "Set-Cookie": await destroySession(session) }
897 * });
898 * }
899 * ```
900 *
901 * @public
902 * @category Utils
903 * @mode framework
904 * @mode data
905 * @param url The URL to redirect to.
906 * @param init The status code or a `ResponseInit` object to be included in the
907 * response.
908 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
909 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
910 * header.
911 */
912declare const redirectDocument: RedirectFunction;
913/**
914 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
915 * that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
916 * instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
917 * for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
918 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
919 *
920 * @example
921 * import { replace } from "react-router";
922 *
923 * export async function loader() {
924 * return replace("/new-location");
925 * }
926 *
927 * @public
928 * @category Utils
929 * @mode framework
930 * @mode data
931 * @param url The URL to redirect to.
932 * @param init The status code or a `ResponseInit` object to be included in the
933 * response.
934 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
935 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
936 * header.
937 */
938declare const replace: RedirectFunction;
939type ErrorResponse = {
940 status: number;
941 statusText: string;
942 data: any;
943};
944declare class ErrorResponseImpl implements ErrorResponse {
945 status: number;
946 statusText: string;
947 data: any;
948 private error?;
949 private internal;
950 constructor(status: number, statusText: string | undefined, data: any, internal?: boolean);
951}
952/**
953 * Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
954 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
955 * thrown from an [`action`](../../start/framework/route-module#action) or
956 * [`loader`](../../start/framework/route-module#loader) function.
957 *
958 * @example
959 * import { isRouteErrorResponse } from "react-router";
960 *
961 * export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
962 * if (isRouteErrorResponse(error)) {
963 * return (
964 * <>
965 * <p>Error: `${error.status}: ${error.statusText}`</p>
966 * <p>{error.data}</p>
967 * </>
968 * );
969 * }
970 *
971 * return (
972 * <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
973 * );
974 * }
975 *
976 * @public
977 * @category Utils
978 * @mode framework
979 * @mode data
980 * @param error The error to check.
981 * @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
982 */
983declare function isRouteErrorResponse(error: any): error is ErrorResponse;
984//#endregion
985export { ActionFunction, ActionFunctionArgs, BaseRouteObject, DataRouteMatch, DataRouteObject, DataStrategyFunction, DataStrategyFunctionArgs, DataStrategyInitiator, DataStrategyMatch, DataStrategyResult, DataWithResponseInit, ErrorResponse, ErrorResponseImpl, FormEncType, FormMethod, HTMLFormMethod, IndexRouteObject, LazyRouteFunction, LoaderFunction, LoaderFunctionArgs, MapRoutePropertiesFunction, MaybePromise, MiddlewareFunction, MiddlewareNextFunction, NonIndexRouteObject, ParamParseKey, Params, PatchRoutesOnNavigationFunction, PatchRoutesOnNavigationFunctionArgs, PathMatch, PathParam, PathPattern, RedirectFunction, RouteBranch, RouteData, RouteManifest, RouteMatch, RouteObject, RouterContext, RouterContextProvider, ShouldRevalidateFunction, ShouldRevalidateFunctionArgs, Submission, TrackedPromise, UIMatch, createContext, data, defaultMapRouteProperties, generatePath, isRouteErrorResponse, matchPath, matchRoutes, redirect, redirectDocument, replace, resolvePath };
\No newline at end of file