UNPKG

37.9 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" | "unstable_validateParams";
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 * A map of route param names to regular expressions used to validate params
493 * after a route-pattern match.
494 */
495 unstable_validateParams?: Record<string, RegExp>;
496 /**
497 * The route handle.
498 */
499 handle?: any;
500 /**
501 * A function that returns a promise that resolves to the route object.
502 * Used for code-splitting routes.
503 * See [`lazy`](../../start/data/route-object#lazy).
504 */
505 lazy?: LazyRouteDefinition<BaseRouteObject>;
506 /**
507 * The React Component to render when this route matches.
508 * Mutually exclusive with `element`.
509 */
510 Component?: React$1.ComponentType | null;
511 /**
512 * The React element to render when this Route matches.
513 * Mutually exclusive with `Component`.
514 */
515 element?: React$1.ReactNode | null;
516 /**
517 * The React Component to render at this route if an error occurs.
518 * Mutually exclusive with `errorElement`.
519 */
520 ErrorBoundary?: React$1.ComponentType | null;
521 /**
522 * The React element to render at this route if an error occurs.
523 * Mutually exclusive with `ErrorBoundary`.
524 */
525 errorElement?: React$1.ReactNode | null;
526 /**
527 * The React Component to render while this router is loading data.
528 * Mutually exclusive with `hydrateFallbackElement`.
529 */
530 HydrateFallback?: React$1.ComponentType | null;
531 /**
532 * The React element to render while this router is loading data.
533 * Mutually exclusive with `HydrateFallback`.
534 */
535 hydrateFallbackElement?: React$1.ReactNode | null;
536};
537/**
538 * Index routes must not have children
539 */
540type IndexRouteObject = BaseRouteObject & {
541 /**
542 * Child Route objects - not valid on index routes.
543 */
544 children?: undefined;
545 /**
546 * Whether this is an index route.
547 */
548 index: true;
549};
550/**
551 * Non-index routes may have children, but cannot have `index` set to `true`.
552 */
553type NonIndexRouteObject = BaseRouteObject & {
554 /**
555 * Child Route objects.
556 */
557 children?: RouteObject[];
558 /**
559 * Whether this is an index route - must be `false` or undefined on non-index routes.
560 */
561 index?: false;
562};
563/**
564 * A route object represents a logical route, with (optionally) its child
565 * routes organized in a tree-like structure.
566 */
567type RouteObject = IndexRouteObject | NonIndexRouteObject;
568type DataIndexRouteObject = IndexRouteObject & {
569 id: string;
570};
571type DataNonIndexRouteObject = NonIndexRouteObject & {
572 children?: DataRouteObject[];
573 id: string;
574};
575/**
576 * A data route object, which is just a RouteObject with a required unique ID
577 */
578type DataRouteObject = DataIndexRouteObject | DataNonIndexRouteObject;
579type RouteManifest<R = DataRouteObject> = Record<string, R | undefined>;
580type 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";
581type Regex_AZ = Uppercase<Regex_az>;
582type Regex_09 = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
583type Regex_w = Regex_az | Regex_AZ | Regex_09 | "_";
584/** Emulates Regex `+` operator */
585type RegexMatchPlus<char extends string, T extends string> = _RegexMatchPlus<char, T> extends infer result extends string ? result extends '' ? never : result : never;
586type _RegexMatchPlus<char extends string, T extends string> = T extends `${infer head extends char}${infer rest}` ? `${head}${_RegexMatchPlus<char, rest>}` : '';
587type ParamNameChar = Regex_w | "-";
588type Simplify<T> = { [K in keyof T]: T[K] } & {};
589type GeneratePathParams<path extends string> = Simplify<ParseParams<path> & { [key in string]: string | null | undefined }>;
590type ParseParams<path extends string> = path extends '*' ? {
591 '*': string;
592} : path extends `${infer rest}/*` ? {
593 '*': string;
594} & ParseParams<rest> : _ParseParams<path>;
595type _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 } : {};
596type PathParam<path extends string> = (keyof ParseParams<path>) & string;
597type ParamParseKey<Segment extends string> = [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;
598/**
599 * The parameters that were parsed from the URL path.
600 */
601type Params<Key extends string = string> = { readonly [key in Key]: string | undefined };
602/**
603 * A RouteMatch contains info about how a route matched a URL.
604 */
605interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> {
606 /**
607 * The names and values of dynamic parameters in the URL.
608 */
609 params: Params<ParamKey>;
610 /**
611 * The portion of the URL pathname that was matched.
612 */
613 pathname: string;
614 /**
615 * The portion of the URL pathname that was matched before child routes.
616 */
617 pathnameBase: string;
618 /**
619 * The route object that was used to match.
620 */
621 route: RouteObjectType;
622}
623interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}
624declare function defaultMapRouteProperties(route: DataRouteObject): Partial<DataRouteObject>;
625/**
626 * Matches the given routes to a location and returns the match data.
627 *
628 * @example
629 * import { matchRoutes } from "react-router";
630 *
631 * let routes = [{
632 * path: "/",
633 * Component: Root,
634 * children: [{
635 * path: "dashboard",
636 * Component: Dashboard,
637 * }]
638 * }];
639 *
640 * matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
641 *
642 * @public
643 * @category Utils
644 * @param routes The array of route objects to match against.
645 * @param locationArg The location to match against, either a string path or a
646 * partial {@link Location} object
647 * @param basename Optional base path to strip from the location before matching.
648 * Defaults to `/`.
649 * @returns An array of matched routes, or `null` if no matches were found.
650 */
651declare function matchRoutes<RouteObjectType extends RouteObject = RouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): RouteMatch<string, RouteObjectType>[] | null;
652interface UIMatch<Data = unknown, Handle = unknown> {
653 id: string;
654 pathname: string;
655 /**
656 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
657 */
658 params: RouteMatch["params"];
659 /**
660 * The return value from the matched route's loader or clientLoader. This might
661 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
662 * an error and we're currently displaying an `ErrorBoundary`.
663 */
664 loaderData: Data | undefined;
665 /**
666 * The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
667 * exported from the matched route module
668 */
669 handle: Handle;
670}
671interface RouteMeta<RouteObjectType extends RouteObject = RouteObject> {
672 relativePath: string;
673 caseSensitive: boolean;
674 childrenIndex: number;
675 route: RouteObjectType;
676 matcher?: RegExp;
677 compiledParams?: CompiledPathParam[];
678}
679/**
680 * @private
681 * PRIVATE - DO NOT USE
682 *
683 * A "branch" of routes that match a given route pattern.
684 * This is an internal interface not intended for direct external usage.
685 */
686interface RouteBranch<RouteObjectType extends RouteObject = RouteObject> {
687 path: string;
688 score: number;
689 routesMeta: RouteMeta<RouteObjectType>[];
690}
691/**
692 * Returns a path with params interpolated.
693 *
694 * Param values are percent-encoded for use in a path segment: characters that
695 * would change the URL structure (`/`, `?`, `#`, `%`, whitespace, non-ASCII)
696 * are escaped, while characters that RFC 3986 allows literally in a path
697 * segment (`$ & + , ; = : @`) are kept as-is. Note this differs from query-string
698 * encoding (`encodeURIComponent`/`URLSearchParams`), where those characters are
699 * delimiters and must be escaped. Splat (`*`) values are encoded per segment,
700 * preserving `/` separators.
701 *
702 * See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3)
703 *
704 * @example
705 * import { generatePath } from "react-router";
706 *
707 * generatePath("/users/:id", { id: "123" }); // "/users/123"
708 * generatePath("/files/:name", { name: "a b" }); // "/files/a%20b"
709 * generatePath("/releases/:v", { v: "1.0.0+1" }); // "/releases/1.0.0+1"
710 *
711 * @public
712 * @category Utils
713 * @param originalPath The original path to generate.
714 * @param params The parameters to interpolate into the path.
715 * @returns The generated path with parameters interpolated.
716 */
717declare function generatePath<Path extends string>(originalPath: Path, params?: GeneratePathParams<Path>): string;
718/**
719 * Used to match on some portion of a URL pathname.
720 */
721interface PathPattern<Path extends string = string> {
722 /**
723 * A string to match against a URL pathname. May contain `:id`-style segments
724 * to indicate placeholders for dynamic parameters. It May also end with `/*`
725 * to indicate matching the rest of the URL pathname.
726 */
727 path: Path;
728 /**
729 * Should be `true` if the static portions of the `path` should be matched in
730 * the same case.
731 */
732 caseSensitive?: boolean;
733 /**
734 * Should be `true` if this pattern should match the entire URL pathname.
735 */
736 end?: boolean;
737}
738/**
739 * Contains info about how a {@link PathPattern} matched on a URL pathname.
740 */
741interface PathMatch<ParamKey extends string = string> {
742 /**
743 * The names and values of dynamic parameters in the URL.
744 */
745 params: Params<ParamKey>;
746 /**
747 * The portion of the URL pathname that was matched.
748 */
749 pathname: string;
750 /**
751 * The portion of the URL pathname that was matched before child routes.
752 */
753 pathnameBase: string;
754 /**
755 * The pattern that was used to match.
756 */
757 pattern: PathPattern;
758}
759/**
760 * Performs pattern matching on a URL pathname and returns information about
761 * the match.
762 *
763 * @public
764 * @category Utils
765 * @param pattern The pattern to match against the URL pathname. This can be a
766 * string or a {@link PathPattern} object. If a string is provided, it will be
767 * treated as a pattern with `caseSensitive` set to `false` and `end` set to
768 * `true`.
769 * @param pathname The URL pathname to match against the pattern.
770 * @returns A path match object if the pattern matches the pathname,
771 * or `null` if it does not match.
772 */
773declare function matchPath<Path extends string>(pattern: PathPattern<Path> | Path, pathname: string): PathMatch<ParamParseKey<Path>> | null;
774type CompiledPathParam = {
775 paramName: string;
776 isOptional?: boolean;
777};
778/**
779 * Returns a resolved {@link Path} object relative to the given pathname.
780 *
781 * @public
782 * @category Utils
783 * @param to The path to resolve, either a string or a partial {@link Path}
784 * object.
785 * @param fromPathname The pathname to resolve the path from. Defaults to `/`.
786 * @returns A {@link Path} object with the resolved pathname, search, and hash.
787 */
788declare function resolvePath(to: To, fromPathname?: string): Path;
789declare class DataWithResponseInit<D> {
790 type: string;
791 data: D;
792 init: ResponseInit | null;
793 constructor(data: D, init?: ResponseInit);
794}
795/**
796 * Create "responses" that contain `headers`/`status` without forcing
797 * serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
798 *
799 * @example
800 * import { data } from "react-router";
801 *
802 * export async function action({ request }: Route.ActionArgs) {
803 * let formData = await request.formData();
804 * let item = await createItem(formData);
805 * return data(item, {
806 * headers: { "X-Custom-Header": "value" }
807 * status: 201,
808 * });
809 * }
810 *
811 * @public
812 * @category Utils
813 * @mode framework
814 * @mode data
815 * @param data The data to be included in the response.
816 * @param init The status code or a `ResponseInit` object to be included in the
817 * response.
818 * @returns A {@link DataWithResponseInit} instance containing the data and
819 * response init.
820 */
821declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
822interface TrackedPromise extends Promise<any> {
823 _tracked?: boolean;
824 _data?: any;
825 _error?: any;
826}
827type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
828/**
829 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
830 * Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
831 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
832 *
833 * This utility accepts absolute URLs and can navigate to external domains, so
834 * the application should validate any user-supplied inputs to redirects.
835 *
836 * @example
837 * import { redirect } from "react-router";
838 *
839 * export async function loader({ request }: Route.LoaderArgs) {
840 * if (!isLoggedIn(request))
841 * throw redirect("/login");
842 * }
843 *
844 * // ...
845 * }
846 *
847 * @public
848 * @category Utils
849 * @mode framework
850 * @mode data
851 * @param url The URL to redirect to.
852 * @param init The status code or a `ResponseInit` object to be included in the
853 * response.
854 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
855 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
856 * header.
857 */
858declare const redirect: RedirectFunction;
859/**
860 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
861 * that will force a document reload to the new location. Sets the status code
862 * and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
863 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
864 *
865 * This utility accepts absolute URLs and can navigate to external domains, so
866 * the application should validate any user-supplied inputs to redirects.
867 *
868 * ```tsx filename=routes/logout.tsx
869 * import { redirectDocument } from "react-router";
870 *
871 * import { destroySession } from "../sessions.server";
872 *
873 * export async function action({ request }: Route.ActionArgs) {
874 * let session = await getSession(request.headers.get("Cookie"));
875 * return redirectDocument("/", {
876 * headers: { "Set-Cookie": await destroySession(session) }
877 * });
878 * }
879 * ```
880 *
881 * @public
882 * @category Utils
883 * @mode framework
884 * @mode data
885 * @param url The URL to redirect to.
886 * @param init The status code or a `ResponseInit` object to be included in the
887 * response.
888 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
889 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
890 * header.
891 */
892declare const redirectDocument: RedirectFunction;
893/**
894 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
895 * that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
896 * instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
897 * for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
898 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
899 *
900 * @example
901 * import { replace } from "react-router";
902 *
903 * export async function loader() {
904 * return replace("/new-location");
905 * }
906 *
907 * @public
908 * @category Utils
909 * @mode framework
910 * @mode data
911 * @param url The URL to redirect to.
912 * @param init The status code or a `ResponseInit` object to be included in the
913 * response.
914 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
915 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
916 * header.
917 */
918declare const replace: RedirectFunction;
919type ErrorResponse = {
920 status: number;
921 statusText: string;
922 data: any;
923};
924declare class ErrorResponseImpl implements ErrorResponse {
925 status: number;
926 statusText: string;
927 data: any;
928 private error?;
929 private internal;
930 constructor(status: number, statusText: string | undefined, data: any, internal?: boolean);
931}
932/**
933 * Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
934 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
935 * thrown from an [`action`](../../start/framework/route-module#action) or
936 * [`loader`](../../start/framework/route-module#loader) function.
937 *
938 * @example
939 * import { isRouteErrorResponse } from "react-router";
940 *
941 * export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
942 * if (isRouteErrorResponse(error)) {
943 * return (
944 * <>
945 * <p>Error: `${error.status}: ${error.statusText}`</p>
946 * <p>{error.data}</p>
947 * </>
948 * );
949 * }
950 *
951 * return (
952 * <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
953 * );
954 * }
955 *
956 * @public
957 * @category Utils
958 * @mode framework
959 * @mode data
960 * @param error The error to check.
961 * @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
962 */
963declare function isRouteErrorResponse(error: any): error is ErrorResponse;
964//#endregion
965export { 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