UNPKG

37 kBTypeScriptView Raw
1
2import { 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}
392interface DataStrategyFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
393 /**
394 * Matches for this route extended with Data strategy APIs
395 */
396 matches: DataStrategyMatch[];
397 runClientMiddleware: (cb: DataStrategyFunction<Context>) => Promise<Record<string, DataStrategyResult>>;
398 /**
399 * The key of the fetcher we are calling `dataStrategy` for, otherwise `null`
400 * for navigational executions
401 */
402 fetcherKey: string | null;
403}
404/**
405 * Result from a loader or action called via dataStrategy
406 */
407interface DataStrategyResult {
408 type: "data" | "error";
409 result: unknown;
410}
411interface DataStrategyFunction<Context = DefaultContext> {
412 (args: DataStrategyFunctionArgs<Context>): Promise<Record<string, DataStrategyResult>>;
413}
414type PatchRoutesOnNavigationFunctionArgs = {
415 signal: AbortSignal;
416 path: string;
417 matches: RouteMatch[];
418 fetcherKey: string | undefined;
419 patch: (routeId: string | null, children: RouteObject[]) => void;
420};
421type PatchRoutesOnNavigationFunction = (opts: PatchRoutesOnNavigationFunctionArgs) => MaybePromise<void>;
422/**
423 * Function provided to set route-specific properties from route objects
424 */
425interface MapRoutePropertiesFunction {
426 (route: DataRouteObject): Partial<DataRouteObject>;
427}
428/**
429 * Keys we cannot change from within a lazy object. We spread all other keys
430 * onto the route. Either they're meaningful to the router, or they'll get
431 * ignored.
432 */
433type UnsupportedLazyRouteObjectKey = "lazy" | "caseSensitive" | "path" | "id" | "index" | "children";
434/**
435 * Keys we cannot change from within a lazy() function. We spread all other keys
436 * onto the route. Either they're meaningful to the router, or they'll get
437 * ignored.
438 */
439type UnsupportedLazyRouteFunctionKey = UnsupportedLazyRouteObjectKey | "middleware";
440/**
441 * lazy object to load route properties, which can add non-matching
442 * related properties to a route
443 */
444type LazyRouteObject<R extends RouteObject> = { [K in keyof R as K extends UnsupportedLazyRouteObjectKey ? never : K]?: () => Promise<R[K] | null | undefined> };
445/**
446 * lazy() function to load a route definition, which can add non-matching
447 * related properties to a route
448 */
449interface LazyRouteFunction<R extends RouteObject> {
450 (): Promise<Omit<R, UnsupportedLazyRouteFunctionKey> & Partial<Record<UnsupportedLazyRouteFunctionKey, never>>>;
451}
452type LazyRouteDefinition<R extends RouteObject> = LazyRouteObject<R> | LazyRouteFunction<R>;
453/**
454 * Base RouteObject with common props shared by all types of routes
455 * @internal
456 */
457type BaseRouteObject = {
458 /**
459 * Whether the path should be case-sensitive. Defaults to `false`.
460 */
461 caseSensitive?: boolean;
462 /**
463 * The path pattern to match. If unspecified or empty, then this becomes a
464 * layout route.
465 */
466 path?: string;
467 /**
468 * The unique identifier for this route (for use with {@link DataRouter}s)
469 */
470 id?: string;
471 /**
472 * The route middleware.
473 * See [`middleware`](../../start/data/route-object#middleware).
474 */
475 middleware?: MiddlewareFunction[];
476 /**
477 * The route loader.
478 * See [`loader`](../../start/data/route-object#loader).
479 */
480 loader?: LoaderFunction | boolean;
481 /**
482 * The route action.
483 * See [`action`](../../start/data/route-object#action).
484 */
485 action?: ActionFunction | boolean;
486 /**
487 * The route shouldRevalidate function.
488 * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
489 */
490 shouldRevalidate?: ShouldRevalidateFunction;
491 /**
492 * The route handle.
493 */
494 handle?: any;
495 /**
496 * A function that returns a promise that resolves to the route object.
497 * Used for code-splitting routes.
498 * See [`lazy`](../../start/data/route-object#lazy).
499 */
500 lazy?: LazyRouteDefinition<BaseRouteObject>;
501 /**
502 * The React Component to render when this route matches.
503 * Mutually exclusive with `element`.
504 */
505 Component?: React$1.ComponentType | null;
506 /**
507 * The React element to render when this Route matches.
508 * Mutually exclusive with `Component`.
509 */
510 element?: React$1.ReactNode | null;
511 /**
512 * The React Component to render at this route if an error occurs.
513 * Mutually exclusive with `errorElement`.
514 */
515 ErrorBoundary?: React$1.ComponentType | null;
516 /**
517 * The React element to render at this route if an error occurs.
518 * Mutually exclusive with `ErrorBoundary`.
519 */
520 errorElement?: React$1.ReactNode | null;
521 /**
522 * The React Component to render while this router is loading data.
523 * Mutually exclusive with `hydrateFallbackElement`.
524 */
525 HydrateFallback?: React$1.ComponentType | null;
526 /**
527 * The React element to render while this router is loading data.
528 * Mutually exclusive with `HydrateFallback`.
529 */
530 hydrateFallbackElement?: React$1.ReactNode | null;
531};
532/**
533 * Index routes must not have children
534 */
535type IndexRouteObject = BaseRouteObject & {
536 /**
537 * Child Route objects - not valid on index routes.
538 */
539 children?: undefined;
540 /**
541 * Whether this is an index route.
542 */
543 index: true;
544};
545/**
546 * Non-index routes may have children, but cannot have `index` set to `true`.
547 */
548type NonIndexRouteObject = BaseRouteObject & {
549 /**
550 * Child Route objects.
551 */
552 children?: RouteObject[];
553 /**
554 * Whether this is an index route - must be `false` or undefined on non-index routes.
555 */
556 index?: false;
557};
558/**
559 * A route object represents a logical route, with (optionally) its child
560 * routes organized in a tree-like structure.
561 */
562type RouteObject = IndexRouteObject | NonIndexRouteObject;
563type DataIndexRouteObject = IndexRouteObject & {
564 id: string;
565};
566type DataNonIndexRouteObject = NonIndexRouteObject & {
567 children?: DataRouteObject[];
568 id: string;
569};
570/**
571 * A data route object, which is just a RouteObject with a required unique ID
572 */
573type DataRouteObject = DataIndexRouteObject | DataNonIndexRouteObject;
574type RouteManifest<R = DataRouteObject> = Record<string, R | undefined>;
575type 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";
576type Regex_AZ = Uppercase<Regex_az>;
577type Regex_09 = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
578type Regex_w = Regex_az | Regex_AZ | Regex_09 | "_";
579/** Emulates Regex `+` operator */
580type RegexMatchPlus<char extends string, T extends string> = _RegexMatchPlus<char, T> extends infer result extends string ? result extends '' ? never : result : never;
581type _RegexMatchPlus<char extends string, T extends string> = T extends `${infer head extends char}${infer rest}` ? `${head}${_RegexMatchPlus<char, rest>}` : '';
582type ParamNameChar = Regex_w | "-";
583type Simplify<T> = { [K in keyof T]: T[K] } & {};
584type GeneratePathParams<path extends string> = Simplify<ParseParams<path> & { [key in string]: string | null | undefined }>;
585type ParseParams<path extends string> = path extends '*' ? {
586 '*': string;
587} : path extends `${infer rest}/*` ? {
588 '*': string;
589} & ParseParams<rest> : _ParseParams<path>;
590type _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 } : {};
591type PathParam<path extends string> = (keyof ParseParams<path>) & string;
592type ParamParseKey<Segment extends string> = [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;
593/**
594 * The parameters that were parsed from the URL path.
595 */
596type Params<Key extends string = string> = { readonly [key in Key]: string | undefined };
597/**
598 * A RouteMatch contains info about how a route matched a URL.
599 */
600interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> {
601 /**
602 * The names and values of dynamic parameters in the URL.
603 */
604 params: Params<ParamKey>;
605 /**
606 * The portion of the URL pathname that was matched.
607 */
608 pathname: string;
609 /**
610 * The portion of the URL pathname that was matched before child routes.
611 */
612 pathnameBase: string;
613 /**
614 * The route object that was used to match.
615 */
616 route: RouteObjectType;
617}
618interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}
619declare function defaultMapRouteProperties(route: DataRouteObject): Partial<DataRouteObject>;
620/**
621 * Matches the given routes to a location and returns the match data.
622 *
623 * @example
624 * import { matchRoutes } from "react-router";
625 *
626 * let routes = [{
627 * path: "/",
628 * Component: Root,
629 * children: [{
630 * path: "dashboard",
631 * Component: Dashboard,
632 * }]
633 * }];
634 *
635 * matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
636 *
637 * @public
638 * @category Utils
639 * @param routes The array of route objects to match against.
640 * @param locationArg The location to match against, either a string path or a
641 * partial {@link Location} object
642 * @param basename Optional base path to strip from the location before matching.
643 * Defaults to `/`.
644 * @returns An array of matched routes, or `null` if no matches were found.
645 */
646declare function matchRoutes<RouteObjectType extends RouteObject = RouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): RouteMatch<string, RouteObjectType>[] | null;
647interface UIMatch<Data = unknown, Handle = unknown> {
648 id: string;
649 pathname: string;
650 /**
651 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
652 */
653 params: RouteMatch["params"];
654 /**
655 * The return value from the matched route's loader or clientLoader. This might
656 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
657 * an error and we're currently displaying an `ErrorBoundary`.
658 */
659 loaderData: Data | undefined;
660 /**
661 * The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
662 * exported from the matched route module
663 */
664 handle: Handle;
665}
666interface RouteMeta<RouteObjectType extends RouteObject = RouteObject> {
667 relativePath: string;
668 caseSensitive: boolean;
669 childrenIndex: number;
670 route: RouteObjectType;
671 matcher?: RegExp;
672 compiledParams?: CompiledPathParam[];
673}
674/**
675 * @private
676 * PRIVATE - DO NOT USE
677 *
678 * A "branch" of routes that match a given route pattern.
679 * This is an internal interface not intended for direct external usage.
680 */
681interface RouteBranch<RouteObjectType extends RouteObject = RouteObject> {
682 path: string;
683 score: number;
684 routesMeta: RouteMeta<RouteObjectType>[];
685}
686/**
687 * Returns a path with params interpolated.
688 *
689 * @example
690 * import { generatePath } from "react-router";
691 *
692 * generatePath("/users/:id", { id: "123" }); // "/users/123"
693 *
694 * @public
695 * @category Utils
696 * @param originalPath The original path to generate.
697 * @param params The parameters to interpolate into the path.
698 * @returns The generated path with parameters interpolated.
699 */
700declare function generatePath<Path extends string>(originalPath: Path, params?: GeneratePathParams<Path>): string;
701/**
702 * Used to match on some portion of a URL pathname.
703 */
704interface PathPattern<Path extends string = string> {
705 /**
706 * A string to match against a URL pathname. May contain `:id`-style segments
707 * to indicate placeholders for dynamic parameters. It May also end with `/*`
708 * to indicate matching the rest of the URL pathname.
709 */
710 path: Path;
711 /**
712 * Should be `true` if the static portions of the `path` should be matched in
713 * the same case.
714 */
715 caseSensitive?: boolean;
716 /**
717 * Should be `true` if this pattern should match the entire URL pathname.
718 */
719 end?: boolean;
720}
721/**
722 * Contains info about how a {@link PathPattern} matched on a URL pathname.
723 */
724interface PathMatch<ParamKey extends string = string> {
725 /**
726 * The names and values of dynamic parameters in the URL.
727 */
728 params: Params<ParamKey>;
729 /**
730 * The portion of the URL pathname that was matched.
731 */
732 pathname: string;
733 /**
734 * The portion of the URL pathname that was matched before child routes.
735 */
736 pathnameBase: string;
737 /**
738 * The pattern that was used to match.
739 */
740 pattern: PathPattern;
741}
742/**
743 * Performs pattern matching on a URL pathname and returns information about
744 * the match.
745 *
746 * @public
747 * @category Utils
748 * @param pattern The pattern to match against the URL pathname. This can be a
749 * string or a {@link PathPattern} object. If a string is provided, it will be
750 * treated as a pattern with `caseSensitive` set to `false` and `end` set to
751 * `true`.
752 * @param pathname The URL pathname to match against the pattern.
753 * @returns A path match object if the pattern matches the pathname,
754 * or `null` if it does not match.
755 */
756declare function matchPath<Path extends string>(pattern: PathPattern<Path> | Path, pathname: string): PathMatch<ParamParseKey<Path>> | null;
757type CompiledPathParam = {
758 paramName: string;
759 isOptional?: boolean;
760};
761/**
762 * Returns a resolved {@link Path} object relative to the given pathname.
763 *
764 * @public
765 * @category Utils
766 * @param to The path to resolve, either a string or a partial {@link Path}
767 * object.
768 * @param fromPathname The pathname to resolve the path from. Defaults to `/`.
769 * @returns A {@link Path} object with the resolved pathname, search, and hash.
770 */
771declare function resolvePath(to: To, fromPathname?: string): Path;
772declare class DataWithResponseInit<D> {
773 type: string;
774 data: D;
775 init: ResponseInit | null;
776 constructor(data: D, init?: ResponseInit);
777}
778/**
779 * Create "responses" that contain `headers`/`status` without forcing
780 * serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
781 *
782 * @example
783 * import { data } from "react-router";
784 *
785 * export async function action({ request }: Route.ActionArgs) {
786 * let formData = await request.formData();
787 * let item = await createItem(formData);
788 * return data(item, {
789 * headers: { "X-Custom-Header": "value" }
790 * status: 201,
791 * });
792 * }
793 *
794 * @public
795 * @category Utils
796 * @mode framework
797 * @mode data
798 * @param data The data to be included in the response.
799 * @param init The status code or a `ResponseInit` object to be included in the
800 * response.
801 * @returns A {@link DataWithResponseInit} instance containing the data and
802 * response init.
803 */
804declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
805interface TrackedPromise extends Promise<any> {
806 _tracked?: boolean;
807 _data?: any;
808 _error?: any;
809}
810type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
811/**
812 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
813 * Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
814 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
815 *
816 * This utility accepts absolute URLs and can navigate to external domains, so
817 * the application should validate any user-supplied inputs to redirects.
818 *
819 * @example
820 * import { redirect } from "react-router";
821 *
822 * export async function loader({ request }: Route.LoaderArgs) {
823 * if (!isLoggedIn(request))
824 * throw redirect("/login");
825 * }
826 *
827 * // ...
828 * }
829 *
830 * @public
831 * @category Utils
832 * @mode framework
833 * @mode data
834 * @param url The URL to redirect to.
835 * @param init The status code or a `ResponseInit` object to be included in the
836 * response.
837 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
838 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
839 * header.
840 */
841declare const redirect: RedirectFunction;
842/**
843 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
844 * that will force a document reload to the new location. Sets the status code
845 * and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
846 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
847 *
848 * This utility accepts absolute URLs and can navigate to external domains, so
849 * the application should validate any user-supplied inputs to redirects.
850 *
851 * ```tsx filename=routes/logout.tsx
852 * import { redirectDocument } from "react-router";
853 *
854 * import { destroySession } from "../sessions.server";
855 *
856 * export async function action({ request }: Route.ActionArgs) {
857 * let session = await getSession(request.headers.get("Cookie"));
858 * return redirectDocument("/", {
859 * headers: { "Set-Cookie": await destroySession(session) }
860 * });
861 * }
862 * ```
863 *
864 * @public
865 * @category Utils
866 * @mode framework
867 * @mode data
868 * @param url The URL to redirect to.
869 * @param init The status code or a `ResponseInit` object to be included in the
870 * response.
871 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
872 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
873 * header.
874 */
875declare const redirectDocument: RedirectFunction;
876/**
877 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
878 * that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
879 * instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
880 * for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
881 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
882 *
883 * @example
884 * import { replace } from "react-router";
885 *
886 * export async function loader() {
887 * return replace("/new-location");
888 * }
889 *
890 * @public
891 * @category Utils
892 * @mode framework
893 * @mode data
894 * @param url The URL to redirect to.
895 * @param init The status code or a `ResponseInit` object to be included in the
896 * response.
897 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
898 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
899 * header.
900 */
901declare const replace: RedirectFunction;
902type ErrorResponse = {
903 status: number;
904 statusText: string;
905 data: any;
906};
907declare class ErrorResponseImpl implements ErrorResponse {
908 status: number;
909 statusText: string;
910 data: any;
911 private error?;
912 private internal;
913 constructor(status: number, statusText: string | undefined, data: any, internal?: boolean);
914}
915/**
916 * Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
917 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
918 * thrown from an [`action`](../../start/framework/route-module#action) or
919 * [`loader`](../../start/framework/route-module#loader) function.
920 *
921 * @example
922 * import { isRouteErrorResponse } from "react-router";
923 *
924 * export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
925 * if (isRouteErrorResponse(error)) {
926 * return (
927 * <>
928 * <p>Error: `${error.status}: ${error.statusText}`</p>
929 * <p>{error.data}</p>
930 * </>
931 * );
932 * }
933 *
934 * return (
935 * <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
936 * );
937 * }
938 *
939 * @public
940 * @category Utils
941 * @mode framework
942 * @mode data
943 * @param error The error to check.
944 * @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
945 */
946declare function isRouteErrorResponse(error: any): error is ErrorResponse;
947//#endregion
948export { ActionFunction, ActionFunctionArgs, BaseRouteObject, DataRouteMatch, DataRouteObject, DataStrategyFunction, DataStrategyFunctionArgs, 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