UNPKG

124 kBTypeScriptView Raw
1import * as React from 'react';
2import { ComponentType, ReactElement } from 'react';
3
4/**
5 * An augmentable interface users can modify in their app-code to opt into
6 * future-flag-specific types
7 */
8interface Future {
9}
10type MiddlewareEnabled = Future extends {
11 v8_middleware: infer T extends boolean;
12} ? T : false;
13
14/**
15 * Actions represent the type of change to a location value.
16 */
17declare enum Action {
18 /**
19 * A POP indicates a change to an arbitrary index in the history stack, such
20 * as a back or forward navigation. It does not describe the direction of the
21 * navigation, only that the current index changed.
22 *
23 * Note: This is the default action for newly created history objects.
24 */
25 Pop = "POP",
26 /**
27 * A PUSH indicates a new entry being added to the history stack, such as when
28 * a link is clicked and a new page loads. When this happens, all subsequent
29 * entries in the stack are lost.
30 */
31 Push = "PUSH",
32 /**
33 * A REPLACE indicates the entry at the current index in the history stack
34 * being replaced by a new one.
35 */
36 Replace = "REPLACE"
37}
38/**
39 * The pathname, search, and hash values of a URL.
40 */
41interface Path {
42 /**
43 * A URL pathname, beginning with a /.
44 */
45 pathname: string;
46 /**
47 * A URL search string, beginning with a ?.
48 */
49 search: string;
50 /**
51 * A URL fragment identifier, beginning with a #.
52 */
53 hash: string;
54}
55/**
56 * An entry in a history stack. A location contains information about the
57 * URL path, as well as possibly some arbitrary state and a key.
58 */
59interface Location<State = any> extends Path {
60 /**
61 * A value of arbitrary data associated with this location.
62 */
63 state: State;
64 /**
65 * A unique string associated with this location. May be used to safely store
66 * and retrieve data in some other storage API, like `localStorage`.
67 *
68 * Note: This value is always "default" on the initial location.
69 */
70 key: string;
71}
72/**
73 * A change to the current location.
74 */
75interface Update {
76 /**
77 * The action that triggered the change.
78 */
79 action: Action;
80 /**
81 * The new location.
82 */
83 location: Location;
84 /**
85 * The delta between this location and the former location in the history stack
86 */
87 delta: number | null;
88}
89/**
90 * A function that receives notifications about location changes.
91 */
92interface Listener {
93 (update: Update): void;
94}
95/**
96 * Describes a location that is the destination of some navigation used in
97 * {@link Link}, {@link useNavigate}, etc.
98 */
99type To = string | Partial<Path>;
100/**
101 * A history is an interface to the navigation stack. The history serves as the
102 * source of truth for the current location, as well as provides a set of
103 * methods that may be used to change it.
104 *
105 * It is similar to the DOM's `window.history` object, but with a smaller, more
106 * focused API.
107 */
108interface History {
109 /**
110 * The last action that modified the current location. This will always be
111 * Action.Pop when a history instance is first created. This value is mutable.
112 */
113 readonly action: Action;
114 /**
115 * The current location. This value is mutable.
116 */
117 readonly location: Location;
118 /**
119 * Returns a valid href for the given `to` value that may be used as
120 * the value of an <a href> attribute.
121 *
122 * @param to - The destination URL
123 */
124 createHref(to: To): string;
125 /**
126 * Returns a URL for the given `to` value
127 *
128 * @param to - The destination URL
129 */
130 createURL(to: To): URL;
131 /**
132 * Encode a location the same way window.history would do (no-op for memory
133 * history) so we ensure our PUSH/REPLACE navigations for data routers
134 * behave the same as POP
135 *
136 * @param to Unencoded path
137 */
138 encodeLocation(to: To): Path;
139 /**
140 * Pushes a new location onto the history stack, increasing its length by one.
141 * If there were any entries in the stack after the current one, they are
142 * lost.
143 *
144 * @param to - The new URL
145 * @param state - Data to associate with the new location
146 */
147 push(to: To, state?: any): void;
148 /**
149 * Replaces the current location in the history stack with a new one. The
150 * location that was replaced will no longer be available.
151 *
152 * @param to - The new URL
153 * @param state - Data to associate with the new location
154 */
155 replace(to: To, state?: any): void;
156 /**
157 * Navigates `n` entries backward/forward in the history stack relative to the
158 * current index. For example, a "back" navigation would use go(-1).
159 *
160 * @param delta - The delta in the stack index
161 */
162 go(delta: number): void;
163 /**
164 * Sets up a listener that will be called whenever the current location
165 * changes.
166 *
167 * @param listener - A function that will be called when the location changes
168 * @returns unlisten - A function that may be used to stop listening
169 */
170 listen(listener: Listener): () => void;
171}
172/**
173 * A user-supplied object that describes a location. Used when providing
174 * entries to `createMemoryHistory` via its `initialEntries` option.
175 */
176type InitialEntry = string | Partial<Location>;
177/**
178 * A browser history stores the current location in regular URLs in a web
179 * browser environment. This is the standard for most web apps and provides the
180 * cleanest URLs the browser's address bar.
181 *
182 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
183 */
184interface BrowserHistory extends UrlHistory {
185}
186type BrowserHistoryOptions = UrlHistoryOptions;
187/**
188 * Browser history stores the location in regular URLs. This is the standard for
189 * most web apps, but it requires some configuration on the server to ensure you
190 * serve the same app at multiple URLs.
191 *
192 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
193 */
194declare function createBrowserHistory(options?: BrowserHistoryOptions): BrowserHistory;
195/**
196 * @private
197 */
198declare function invariant(value: boolean, message?: string): asserts value;
199declare function invariant<T>(value: T | null | undefined, message?: string): asserts value is T;
200/**
201 * Creates a string URL path from the given pathname, search, and hash components.
202 *
203 * @category Utils
204 */
205declare function createPath({ pathname, search, hash, }: Partial<Path>): string;
206/**
207 * Parses a string URL path into its separate pathname, search, and hash components.
208 *
209 * @category Utils
210 */
211declare function parsePath(path: string): Partial<Path>;
212interface UrlHistory extends History {
213}
214type UrlHistoryOptions = {
215 window?: Window;
216 v5Compat?: boolean;
217};
218
219type MaybePromise<T> = T | Promise<T>;
220/**
221 * Map of routeId -> data returned from a loader/action/error
222 */
223interface RouteData {
224 [routeId: string]: any;
225}
226type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete";
227type UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;
228/**
229 * Users can specify either lowercase or uppercase form methods on `<Form>`,
230 * useSubmit(), `<fetcher.Form>`, etc.
231 */
232type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;
233/**
234 * Active navigation/fetcher form methods are exposed in uppercase on the
235 * RouterState. This is to align with the normalization done via fetch().
236 */
237type FormMethod = UpperCaseFormMethod;
238type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data" | "application/json" | "text/plain";
239type JsonObject = {
240 [Key in string]: JsonValue;
241} & {
242 [Key in string]?: JsonValue | undefined;
243};
244type JsonArray = JsonValue[] | readonly JsonValue[];
245type JsonPrimitive = string | number | boolean | null;
246type JsonValue = JsonPrimitive | JsonObject | JsonArray;
247/**
248 * @private
249 * Internal interface to pass around for action submissions, not intended for
250 * external consumption
251 */
252type Submission = {
253 formMethod: FormMethod;
254 formAction: string;
255 formEncType: FormEncType;
256 formData: FormData;
257 json: undefined;
258 text: undefined;
259} | {
260 formMethod: FormMethod;
261 formAction: string;
262 formEncType: FormEncType;
263 formData: undefined;
264 json: JsonValue;
265 text: undefined;
266} | {
267 formMethod: FormMethod;
268 formAction: string;
269 formEncType: FormEncType;
270 formData: undefined;
271 json: undefined;
272 text: string;
273};
274/**
275 * A context instance used as the key for the `get`/`set` methods of a
276 * {@link RouterContextProvider}. Accepts an optional default
277 * value to be returned if no value has been set.
278 */
279interface RouterContext<T = unknown> {
280 defaultValue?: T;
281}
282/**
283 * Creates a type-safe {@link RouterContext} object that can be used to
284 * store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
285 * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
286 * Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
287 * but specifically designed for React Router's request/response lifecycle.
288 *
289 * If a `defaultValue` is provided, it will be returned from `context.get()`
290 * when no value has been set for the context. Otherwise, reading this context
291 * when no value has been set will throw an error.
292 *
293 * ```tsx filename=app/context.ts
294 * import { createContext } from "react-router";
295 *
296 * // Create a context for user data
297 * export const userContext =
298 * createContext<User | null>(null);
299 * ```
300 *
301 * ```tsx filename=app/middleware/auth.ts
302 * import { getUserFromSession } from "~/auth.server";
303 * import { userContext } from "~/context";
304 *
305 * export const authMiddleware = async ({
306 * context,
307 * request,
308 * }) => {
309 * const user = await getUserFromSession(request);
310 * context.set(userContext, user);
311 * };
312 * ```
313 *
314 * ```tsx filename=app/routes/profile.tsx
315 * import { userContext } from "~/context";
316 *
317 * export async function loader({
318 * context,
319 * }: Route.LoaderArgs) {
320 * const user = context.get(userContext);
321 *
322 * if (!user) {
323 * throw new Response("Unauthorized", { status: 401 });
324 * }
325 *
326 * return { user };
327 * }
328 * ```
329 *
330 * @public
331 * @category Utils
332 * @mode framework
333 * @mode data
334 * @param defaultValue An optional default value for the context. This value
335 * will be returned if no value has been set for this context.
336 * @returns A {@link RouterContext} object that can be used with
337 * `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
338 * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
339 */
340declare function createContext<T>(defaultValue?: T): RouterContext<T>;
341/**
342 * Provides methods for writing/reading values in application context in a
343 * type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
344 *
345 * @example
346 * import {
347 * createContext,
348 * RouterContextProvider
349 * } from "react-router";
350 *
351 * const userContext = createContext<User | null>(null);
352 * const contextProvider = new RouterContextProvider();
353 * contextProvider.set(userContext, getUser());
354 * // ^ Type-safe
355 * const user = contextProvider.get(userContext);
356 * // ^ User
357 *
358 * @public
359 * @category Utils
360 * @mode framework
361 * @mode data
362 */
363declare class RouterContextProvider {
364 #private;
365 /**
366 * Create a new `RouterContextProvider` instance
367 * @param init An optional initial context map to populate the provider with
368 */
369 constructor(init?: Map<RouterContext, unknown>);
370 /**
371 * Access a value from the context. If no value has been set for the context,
372 * it will return the context's `defaultValue` if provided, or throw an error
373 * if no `defaultValue` was set.
374 * @param context The context to get the value for
375 * @returns The value for the context, or the context's `defaultValue` if no
376 * value was set
377 */
378 get<T>(context: RouterContext<T>): T;
379 /**
380 * Set a value for the context. If the context already has a value set, this
381 * will overwrite it.
382 *
383 * @param context The context to set the value for
384 * @param value The value to set for the context
385 * @returns {void}
386 */
387 set<C extends RouterContext>(context: C, value: C extends RouterContext<infer T> ? T : never): void;
388}
389type DefaultContext = MiddlewareEnabled extends true ? Readonly<RouterContextProvider> : any;
390/**
391 * @private
392 * Arguments passed to route loader/action functions. Same for now but we keep
393 * this as a private implementation detail in case they diverge in the future.
394 */
395interface DataFunctionArgs<Context> {
396 /** 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. */
397 request: Request;
398 /**
399 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
400 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
401 */
402 unstable_pattern: string;
403 /**
404 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
405 * @example
406 * // app/routes.ts
407 * route("teams/:teamId", "./team.tsx"),
408 *
409 * // app/team.tsx
410 * export function loader({
411 * params,
412 * }: Route.LoaderArgs) {
413 * params.teamId;
414 * // ^ string
415 * }
416 */
417 params: Params;
418 /**
419 * This is the context passed in to your server adapter's getLoadContext() function.
420 * It's a way to bridge the gap between the adapter's request/response API with your React Router app.
421 * It is only applicable if you are using a custom server adapter.
422 */
423 context: Context;
424}
425/**
426 * Route middleware `next` function to call downstream handlers and then complete
427 * middlewares from the bottom-up
428 */
429interface MiddlewareNextFunction<Result = unknown> {
430 (): Promise<Result>;
431}
432/**
433 * Route middleware function signature. Receives the same "data" arguments as a
434 * `loader`/`action` (`request`, `params`, `context`) as the first parameter and
435 * a `next` function as the second parameter which will call downstream handlers
436 * and then complete middlewares from the bottom-up
437 */
438type MiddlewareFunction<Result = unknown> = (args: DataFunctionArgs<Readonly<RouterContextProvider>>, next: MiddlewareNextFunction<Result>) => MaybePromise<Result | void>;
439/**
440 * Arguments passed to loader functions
441 */
442interface LoaderFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
443}
444/**
445 * Arguments passed to action functions
446 */
447interface ActionFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
448}
449/**
450 * Loaders and actions can return anything
451 */
452type DataFunctionValue = unknown;
453type DataFunctionReturnValue = MaybePromise<DataFunctionValue>;
454/**
455 * Route loader function signature
456 */
457type LoaderFunction<Context = DefaultContext> = {
458 (args: LoaderFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
459} & {
460 hydrate?: boolean;
461};
462/**
463 * Route action function signature
464 */
465interface ActionFunction<Context = DefaultContext> {
466 (args: ActionFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
467}
468/**
469 * Arguments passed to shouldRevalidate function
470 */
471interface ShouldRevalidateFunctionArgs {
472 /** 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. */
473 currentUrl: URL;
474 /** 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. */
475 currentParams: AgnosticDataRouteMatch["params"];
476 /** 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. */
477 nextUrl: URL;
478 /** 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. */
479 nextParams: AgnosticDataRouteMatch["params"];
480 /** The method (probably `"GET"` or `"POST"`) used in the form submission that triggered the revalidation. */
481 formMethod?: Submission["formMethod"];
482 /** The form action (`<Form action="/somewhere">`) that triggered the revalidation. */
483 formAction?: Submission["formAction"];
484 /** The form encType (`<Form encType="application/x-www-form-urlencoded">) used in the form submission that triggered the revalidation*/
485 formEncType?: Submission["formEncType"];
486 /** The form submission data when the form's encType is `text/plain` */
487 text?: Submission["text"];
488 /** The form submission data when the form's encType is `application/x-www-form-urlencoded` or `multipart/form-data` */
489 formData?: Submission["formData"];
490 /** The form submission data when the form's encType is `application/json` */
491 json?: Submission["json"];
492 /** The status code of the action response */
493 actionStatus?: number;
494 /**
495 * 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.
496 *
497 * @example
498 * export async function action() {
499 * await saveSomeStuff();
500 * return { ok: true };
501 * }
502 *
503 * export function shouldRevalidate({
504 * actionResult,
505 * }) {
506 * if (actionResult?.ok) {
507 * return false;
508 * }
509 * return true;
510 * }
511 */
512 actionResult?: any;
513 /**
514 * 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:
515 *
516 * /projects/123/tasks/abc
517 * /projects/123/tasks/def
518 * React Router will only call the loader for tasks/def because the param for projects/123 didn't change.
519 *
520 * 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.
521 */
522 defaultShouldRevalidate: boolean;
523}
524/**
525 * Route shouldRevalidate function signature. This runs after any submission
526 * (navigation or fetcher), so we flatten the navigation/fetcher submission
527 * onto the arguments. It shouldn't matter whether it came from a navigation
528 * or a fetcher, what really matters is the URLs and the formData since loaders
529 * have to re-run based on the data models that were potentially mutated.
530 */
531interface ShouldRevalidateFunction {
532 (args: ShouldRevalidateFunctionArgs): boolean;
533}
534interface DataStrategyMatch extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {
535 /**
536 * @private
537 */
538 _lazyPromises?: {
539 middleware: Promise<void> | undefined;
540 handler: Promise<void> | undefined;
541 route: Promise<void> | undefined;
542 };
543 /**
544 * @deprecated Deprecated in favor of `shouldCallHandler`
545 *
546 * A boolean value indicating whether this route handler should be called in
547 * this pass.
548 *
549 * The `matches` array always includes _all_ matched routes even when only
550 * _some_ route handlers need to be called so that things like middleware can
551 * be implemented.
552 *
553 * `shouldLoad` is usually only interesting if you are skipping the route
554 * handler entirely and implementing custom handler logic - since it lets you
555 * determine if that custom logic should run for this route or not.
556 *
557 * For example:
558 * - If you are on `/parent/child/a` and you navigate to `/parent/child/b` -
559 * you'll get an array of three matches (`[parent, child, b]`), but only `b`
560 * will have `shouldLoad=true` because the data for `parent` and `child` is
561 * already loaded
562 * - If you are on `/parent/child/a` and you submit to `a`'s [`action`](https://reactrouter.com/docs/start/data/route-object#action),
563 * then only `a` will have `shouldLoad=true` for the action execution of
564 * `dataStrategy`
565 * - After the [`action`](https://reactrouter.com/docs/start/data/route-object#action),
566 * `dataStrategy` will be called again for the [`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
567 * revalidation, and all matches will have `shouldLoad=true` (assuming no
568 * custom `shouldRevalidate` implementations)
569 */
570 shouldLoad: boolean;
571 /**
572 * Arguments passed to the `shouldRevalidate` function for this `loader` execution.
573 * Will be `null` if this is not a revalidating loader {@link DataStrategyMatch}.
574 */
575 shouldRevalidateArgs: ShouldRevalidateFunctionArgs | null;
576 /**
577 * Determine if this route's handler should be called during this `dataStrategy`
578 * execution. Calling it with no arguments will leverage the default revalidation
579 * behavior. You can pass your own `defaultShouldRevalidate` value if you wish
580 * to change the default revalidation behavior with your `dataStrategy`.
581 *
582 * @param defaultShouldRevalidate `defaultShouldRevalidate` override value (optional)
583 */
584 shouldCallHandler(defaultShouldRevalidate?: boolean): boolean;
585 /**
586 * An async function that will resolve any `route.lazy` implementations and
587 * execute the route's handler (if necessary), returning a {@link DataStrategyResult}
588 *
589 * - Calling `match.resolve` does not mean you're calling the
590 * [`action`](https://reactrouter.com/docs/start/data/route-object#action)/[`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
591 * (the "handler") - `resolve` will only call the `handler` internally if
592 * needed _and_ if you don't pass your own `handlerOverride` function parameter
593 * - It is safe to call `match.resolve` for all matches, even if they have
594 * `shouldLoad=false`, and it will no-op if no loading is required
595 * - You should generally always call `match.resolve()` for `shouldLoad:true`
596 * routes to ensure that any `route.lazy` implementations are processed
597 * - See the examples below for how to implement custom handler execution via
598 * `match.resolve`
599 */
600 resolve: (handlerOverride?: (handler: (ctx?: unknown) => DataFunctionReturnValue) => DataFunctionReturnValue) => Promise<DataStrategyResult>;
601}
602interface DataStrategyFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
603 /**
604 * Matches for this route extended with Data strategy APIs
605 */
606 matches: DataStrategyMatch[];
607 runClientMiddleware: (cb: DataStrategyFunction<Context>) => Promise<Record<string, DataStrategyResult>>;
608 /**
609 * The key of the fetcher we are calling `dataStrategy` for, otherwise `null`
610 * for navigational executions
611 */
612 fetcherKey: string | null;
613}
614/**
615 * Result from a loader or action called via dataStrategy
616 */
617interface DataStrategyResult {
618 type: "data" | "error";
619 result: unknown;
620}
621interface DataStrategyFunction<Context = DefaultContext> {
622 (args: DataStrategyFunctionArgs<Context>): Promise<Record<string, DataStrategyResult>>;
623}
624type AgnosticPatchRoutesOnNavigationFunctionArgs<O extends AgnosticRouteObject = AgnosticRouteObject, M extends AgnosticRouteMatch = AgnosticRouteMatch> = {
625 signal: AbortSignal;
626 path: string;
627 matches: M[];
628 fetcherKey: string | undefined;
629 patch: (routeId: string | null, children: O[]) => void;
630};
631type AgnosticPatchRoutesOnNavigationFunction<O extends AgnosticRouteObject = AgnosticRouteObject, M extends AgnosticRouteMatch = AgnosticRouteMatch> = (opts: AgnosticPatchRoutesOnNavigationFunctionArgs<O, M>) => MaybePromise<void>;
632/**
633 * Function provided by the framework-aware layers to set any framework-specific
634 * properties from framework-agnostic properties
635 */
636interface MapRoutePropertiesFunction {
637 (route: AgnosticDataRouteObject): {
638 hasErrorBoundary: boolean;
639 } & Record<string, any>;
640}
641/**
642 * Keys we cannot change from within a lazy object. We spread all other keys
643 * onto the route. Either they're meaningful to the router, or they'll get
644 * ignored.
645 */
646type UnsupportedLazyRouteObjectKey = "lazy" | "caseSensitive" | "path" | "id" | "index" | "children";
647/**
648 * Keys we cannot change from within a lazy() function. We spread all other keys
649 * onto the route. Either they're meaningful to the router, or they'll get
650 * ignored.
651 */
652type UnsupportedLazyRouteFunctionKey = UnsupportedLazyRouteObjectKey | "middleware";
653/**
654 * lazy object to load route properties, which can add non-matching
655 * related properties to a route
656 */
657type LazyRouteObject<R extends AgnosticRouteObject> = {
658 [K in keyof R as K extends UnsupportedLazyRouteObjectKey ? never : K]?: () => Promise<R[K] | null | undefined>;
659};
660/**
661 * lazy() function to load a route definition, which can add non-matching
662 * related properties to a route
663 */
664interface LazyRouteFunction<R extends AgnosticRouteObject> {
665 (): Promise<Omit<R, UnsupportedLazyRouteFunctionKey> & Partial<Record<UnsupportedLazyRouteFunctionKey, never>>>;
666}
667type LazyRouteDefinition<R extends AgnosticRouteObject> = LazyRouteObject<R> | LazyRouteFunction<R>;
668/**
669 * Base RouteObject with common props shared by all types of routes
670 */
671type AgnosticBaseRouteObject = {
672 caseSensitive?: boolean;
673 path?: string;
674 id?: string;
675 middleware?: MiddlewareFunction[];
676 loader?: LoaderFunction | boolean;
677 action?: ActionFunction | boolean;
678 hasErrorBoundary?: boolean;
679 shouldRevalidate?: ShouldRevalidateFunction;
680 handle?: any;
681 lazy?: LazyRouteDefinition<AgnosticBaseRouteObject>;
682};
683/**
684 * Index routes must not have children
685 */
686type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {
687 children?: undefined;
688 index: true;
689};
690/**
691 * Non-index routes may have children, but cannot have index
692 */
693type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {
694 children?: AgnosticRouteObject[];
695 index?: false;
696};
697/**
698 * A route object represents a logical route, with (optionally) its child
699 * routes organized in a tree-like structure.
700 */
701type AgnosticRouteObject = AgnosticIndexRouteObject | AgnosticNonIndexRouteObject;
702type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {
703 id: string;
704};
705type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {
706 children?: AgnosticDataRouteObject[];
707 id: string;
708};
709/**
710 * A data route object, which is just a RouteObject with a required unique ID
711 */
712type AgnosticDataRouteObject = AgnosticDataIndexRouteObject | AgnosticDataNonIndexRouteObject;
713type RouteManifest<R = AgnosticDataRouteObject> = Record<string, R | undefined>;
714type 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";
715type Regez_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";
716type Regex_09 = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
717type Regex_w = Regex_az | Regez_AZ | Regex_09 | "_";
718type ParamChar = Regex_w | "-";
719type RegexMatchPlus<CharPattern extends string, T extends string> = T extends `${infer First}${infer Rest}` ? First extends CharPattern ? RegexMatchPlus<CharPattern, Rest> extends never ? First : `${First}${RegexMatchPlus<CharPattern, Rest>}` : never : never;
720type _PathParam<Path extends string> = Path extends `${infer L}/${infer R}` ? _PathParam<L> | _PathParam<R> : Path extends `:${infer Param}` ? Param extends `${infer Optional}?${string}` ? RegexMatchPlus<ParamChar, Optional> : RegexMatchPlus<ParamChar, Param> : never;
721type PathParam<Path extends string> = Path extends "*" | "/*" ? "*" : Path extends `${infer Rest}/*` ? "*" | _PathParam<Rest> : _PathParam<Path>;
722type ParamParseKey<Segment extends string> = [
723 PathParam<Segment>
724] extends [never] ? string : PathParam<Segment>;
725/**
726 * The parameters that were parsed from the URL path.
727 */
728type Params<Key extends string = string> = {
729 readonly [key in Key]: string | undefined;
730};
731/**
732 * A RouteMatch contains info about how a route matched a URL.
733 */
734interface AgnosticRouteMatch<ParamKey extends string = string, RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject> {
735 /**
736 * The names and values of dynamic parameters in the URL.
737 */
738 params: Params<ParamKey>;
739 /**
740 * The portion of the URL pathname that was matched.
741 */
742 pathname: string;
743 /**
744 * The portion of the URL pathname that was matched before child routes.
745 */
746 pathnameBase: string;
747 /**
748 * The route object that was used to match.
749 */
750 route: RouteObjectType;
751}
752interface AgnosticDataRouteMatch extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {
753}
754/**
755 * Matches the given routes to a location and returns the match data.
756 *
757 * @example
758 * import { matchRoutes } from "react-router";
759 *
760 * let routes = [{
761 * path: "/",
762 * Component: Root,
763 * children: [{
764 * path: "dashboard",
765 * Component: Dashboard,
766 * }]
767 * }];
768 *
769 * matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
770 *
771 * @public
772 * @category Utils
773 * @param routes The array of route objects to match against.
774 * @param locationArg The location to match against, either a string path or a
775 * partial {@link Location} object
776 * @param basename Optional base path to strip from the location before matching.
777 * Defaults to `/`.
778 * @returns An array of matched routes, or `null` if no matches were found.
779 */
780declare function matchRoutes<RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): AgnosticRouteMatch<string, RouteObjectType>[] | null;
781interface UIMatch<Data = unknown, Handle = unknown> {
782 id: string;
783 pathname: string;
784 /**
785 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
786 */
787 params: AgnosticRouteMatch["params"];
788 /**
789 * The return value from the matched route's loader or clientLoader. This might
790 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
791 * an error and we're currently displaying an `ErrorBoundary`.
792 *
793 * @deprecated Use `UIMatch.loaderData` instead
794 */
795 data: Data | undefined;
796 /**
797 * The return value from the matched route's loader or clientLoader. This might
798 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
799 * an error and we're currently displaying an `ErrorBoundary`.
800 */
801 loaderData: Data | undefined;
802 /**
803 * The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
804 * exported from the matched route module
805 */
806 handle: Handle;
807}
808/**
809 * Returns a path with params interpolated.
810 *
811 * @example
812 * import { generatePath } from "react-router";
813 *
814 * generatePath("/users/:id", { id: "123" }); // "/users/123"
815 *
816 * @public
817 * @category Utils
818 * @param originalPath The original path to generate.
819 * @param params The parameters to interpolate into the path.
820 * @returns The generated path with parameters interpolated.
821 */
822declare function generatePath<Path extends string>(originalPath: Path, params?: {
823 [key in PathParam<Path>]: string | null;
824}): string;
825/**
826 * Used to match on some portion of a URL pathname.
827 */
828interface PathPattern<Path extends string = string> {
829 /**
830 * A string to match against a URL pathname. May contain `:id`-style segments
831 * to indicate placeholders for dynamic parameters. It May also end with `/*`
832 * to indicate matching the rest of the URL pathname.
833 */
834 path: Path;
835 /**
836 * Should be `true` if the static portions of the `path` should be matched in
837 * the same case.
838 */
839 caseSensitive?: boolean;
840 /**
841 * Should be `true` if this pattern should match the entire URL pathname.
842 */
843 end?: boolean;
844}
845/**
846 * Contains info about how a {@link PathPattern} matched on a URL pathname.
847 */
848interface PathMatch<ParamKey extends string = string> {
849 /**
850 * The names and values of dynamic parameters in the URL.
851 */
852 params: Params<ParamKey>;
853 /**
854 * The portion of the URL pathname that was matched.
855 */
856 pathname: string;
857 /**
858 * The portion of the URL pathname that was matched before child routes.
859 */
860 pathnameBase: string;
861 /**
862 * The pattern that was used to match.
863 */
864 pattern: PathPattern;
865}
866/**
867 * Performs pattern matching on a URL pathname and returns information about
868 * the match.
869 *
870 * @public
871 * @category Utils
872 * @param pattern The pattern to match against the URL pathname. This can be a
873 * string or a {@link PathPattern} object. If a string is provided, it will be
874 * treated as a pattern with `caseSensitive` set to `false` and `end` set to
875 * `true`.
876 * @param pathname The URL pathname to match against the pattern.
877 * @returns A path match object if the pattern matches the pathname,
878 * or `null` if it does not match.
879 */
880declare function matchPath<ParamKey extends ParamParseKey<Path>, Path extends string>(pattern: PathPattern<Path> | Path, pathname: string): PathMatch<ParamKey> | null;
881/**
882 * Returns a resolved {@link Path} object relative to the given pathname.
883 *
884 * @public
885 * @category Utils
886 * @param to The path to resolve, either a string or a partial {@link Path}
887 * object.
888 * @param fromPathname The pathname to resolve the path from. Defaults to `/`.
889 * @returns A {@link Path} object with the resolved pathname, search, and hash.
890 */
891declare function resolvePath(to: To, fromPathname?: string): Path;
892declare class DataWithResponseInit<D> {
893 type: string;
894 data: D;
895 init: ResponseInit | null;
896 constructor(data: D, init?: ResponseInit);
897}
898/**
899 * Create "responses" that contain `headers`/`status` without forcing
900 * serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
901 *
902 * @example
903 * import { data } from "react-router";
904 *
905 * export async function action({ request }: Route.ActionArgs) {
906 * let formData = await request.formData();
907 * let item = await createItem(formData);
908 * return data(item, {
909 * headers: { "X-Custom-Header": "value" }
910 * status: 201,
911 * });
912 * }
913 *
914 * @public
915 * @category Utils
916 * @mode framework
917 * @mode data
918 * @param data The data to be included in the response.
919 * @param init The status code or a `ResponseInit` object to be included in the
920 * response.
921 * @returns A {@link DataWithResponseInit} instance containing the data and
922 * response init.
923 */
924declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
925interface TrackedPromise extends Promise<any> {
926 _tracked?: boolean;
927 _data?: any;
928 _error?: any;
929}
930type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
931/**
932 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
933 * Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
934 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
935 *
936 * @example
937 * import { redirect } from "react-router";
938 *
939 * export async function loader({ request }: Route.LoaderArgs) {
940 * if (!isLoggedIn(request))
941 * throw redirect("/login");
942 * }
943 *
944 * // ...
945 * }
946 *
947 * @public
948 * @category Utils
949 * @mode framework
950 * @mode data
951 * @param url The URL to redirect to.
952 * @param init The status code or a `ResponseInit` object to be included in the
953 * response.
954 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
955 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
956 * header.
957 */
958declare const redirect: RedirectFunction;
959/**
960 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
961 * that will force a document reload to the new location. Sets the status code
962 * and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
963 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
964 *
965 * ```tsx filename=routes/logout.tsx
966 * import { redirectDocument } from "react-router";
967 *
968 * import { destroySession } from "../sessions.server";
969 *
970 * export async function action({ request }: Route.ActionArgs) {
971 * let session = await getSession(request.headers.get("Cookie"));
972 * return redirectDocument("/", {
973 * headers: { "Set-Cookie": await destroySession(session) }
974 * });
975 * }
976 * ```
977 *
978 * @public
979 * @category Utils
980 * @mode framework
981 * @mode data
982 * @param url The URL to redirect to.
983 * @param init The status code or a `ResponseInit` object to be included in the
984 * response.
985 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
986 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
987 * header.
988 */
989declare const redirectDocument: RedirectFunction;
990/**
991 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
992 * that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
993 * instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
994 * for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
995 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
996 *
997 * @example
998 * import { replace } from "react-router";
999 *
1000 * export async function loader() {
1001 * return replace("/new-location");
1002 * }
1003 *
1004 * @public
1005 * @category Utils
1006 * @mode framework
1007 * @mode data
1008 * @param url The URL to redirect to.
1009 * @param init The status code or a `ResponseInit` object to be included in the
1010 * response.
1011 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1012 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1013 * header.
1014 */
1015declare const replace: RedirectFunction;
1016type ErrorResponse = {
1017 status: number;
1018 statusText: string;
1019 data: any;
1020};
1021declare class ErrorResponseImpl implements ErrorResponse {
1022 status: number;
1023 statusText: string;
1024 data: any;
1025 private error?;
1026 private internal;
1027 constructor(status: number, statusText: string | undefined, data: any, internal?: boolean);
1028}
1029/**
1030 * Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
1031 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1032 * thrown from an [`action`](../../start/framework/route-module#action) or
1033 * [`loader`](../../start/framework/route-module#loader) function.
1034 *
1035 * @example
1036 * import { isRouteErrorResponse } from "react-router";
1037 *
1038 * export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
1039 * if (isRouteErrorResponse(error)) {
1040 * return (
1041 * <>
1042 * <p>Error: `${error.status}: ${error.statusText}`</p>
1043 * <p>{error.data}</p>
1044 * </>
1045 * );
1046 * }
1047 *
1048 * return (
1049 * <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
1050 * );
1051 * }
1052 *
1053 * @public
1054 * @category Utils
1055 * @mode framework
1056 * @mode data
1057 * @param error The error to check.
1058 * @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
1059 */
1060declare function isRouteErrorResponse(error: any): error is ErrorResponse;
1061
1062/**
1063 * An object of unknown type for route loaders and actions provided by the
1064 * server's `getLoadContext()` function. This is defined as an empty interface
1065 * specifically so apps can leverage declaration merging to augment this type
1066 * globally: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
1067 */
1068interface AppLoadContext {
1069 [key: string]: unknown;
1070}
1071
1072/**
1073 * A Router instance manages all navigation and data loading/mutations
1074 */
1075interface Router$1 {
1076 /**
1077 * @private
1078 * PRIVATE - DO NOT USE
1079 *
1080 * Return the basename for the router
1081 */
1082 get basename(): RouterInit["basename"];
1083 /**
1084 * @private
1085 * PRIVATE - DO NOT USE
1086 *
1087 * Return the future config for the router
1088 */
1089 get future(): FutureConfig;
1090 /**
1091 * @private
1092 * PRIVATE - DO NOT USE
1093 *
1094 * Return the current state of the router
1095 */
1096 get state(): RouterState;
1097 /**
1098 * @private
1099 * PRIVATE - DO NOT USE
1100 *
1101 * Return the routes for this router instance
1102 */
1103 get routes(): AgnosticDataRouteObject[];
1104 /**
1105 * @private
1106 * PRIVATE - DO NOT USE
1107 *
1108 * Return the window associated with the router
1109 */
1110 get window(): RouterInit["window"];
1111 /**
1112 * @private
1113 * PRIVATE - DO NOT USE
1114 *
1115 * Initialize the router, including adding history listeners and kicking off
1116 * initial data fetches. Returns a function to cleanup listeners and abort
1117 * any in-progress loads
1118 */
1119 initialize(): Router$1;
1120 /**
1121 * @private
1122 * PRIVATE - DO NOT USE
1123 *
1124 * Subscribe to router.state updates
1125 *
1126 * @param fn function to call with the new state
1127 */
1128 subscribe(fn: RouterSubscriber): () => void;
1129 /**
1130 * @private
1131 * PRIVATE - DO NOT USE
1132 *
1133 * Enable scroll restoration behavior in the router
1134 *
1135 * @param savedScrollPositions Object that will manage positions, in case
1136 * it's being restored from sessionStorage
1137 * @param getScrollPosition Function to get the active Y scroll position
1138 * @param getKey Function to get the key to use for restoration
1139 */
1140 enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
1141 /**
1142 * @private
1143 * PRIVATE - DO NOT USE
1144 *
1145 * Navigate forward/backward in the history stack
1146 * @param to Delta to move in the history stack
1147 */
1148 navigate(to: number): Promise<void>;
1149 /**
1150 * Navigate to the given path
1151 * @param to Path to navigate to
1152 * @param opts Navigation options (method, submission, etc.)
1153 */
1154 navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;
1155 /**
1156 * @private
1157 * PRIVATE - DO NOT USE
1158 *
1159 * Trigger a fetcher load/submission
1160 *
1161 * @param key Fetcher key
1162 * @param routeId Route that owns the fetcher
1163 * @param href href to fetch
1164 * @param opts Fetcher options, (method, submission, etc.)
1165 */
1166 fetch(key: string, routeId: string, href: string | null, opts?: RouterFetchOptions): Promise<void>;
1167 /**
1168 * @private
1169 * PRIVATE - DO NOT USE
1170 *
1171 * Trigger a revalidation of all current route loaders and fetcher loads
1172 */
1173 revalidate(): Promise<void>;
1174 /**
1175 * @private
1176 * PRIVATE - DO NOT USE
1177 *
1178 * Utility function to create an href for the given location
1179 * @param location
1180 */
1181 createHref(location: Location | URL): string;
1182 /**
1183 * @private
1184 * PRIVATE - DO NOT USE
1185 *
1186 * Utility function to URL encode a destination path according to the internal
1187 * history implementation
1188 * @param to
1189 */
1190 encodeLocation(to: To): Path;
1191 /**
1192 * @private
1193 * PRIVATE - DO NOT USE
1194 *
1195 * Get/create a fetcher for the given key
1196 * @param key
1197 */
1198 getFetcher<TData = any>(key: string): Fetcher<TData>;
1199 /**
1200 * @internal
1201 * PRIVATE - DO NOT USE
1202 *
1203 * Reset the fetcher for a given key
1204 * @param key
1205 */
1206 resetFetcher(key: string, opts?: {
1207 reason?: unknown;
1208 }): void;
1209 /**
1210 * @private
1211 * PRIVATE - DO NOT USE
1212 *
1213 * Delete the fetcher for a given key
1214 * @param key
1215 */
1216 deleteFetcher(key: string): void;
1217 /**
1218 * @private
1219 * PRIVATE - DO NOT USE
1220 *
1221 * Cleanup listeners and abort any in-progress loads
1222 */
1223 dispose(): void;
1224 /**
1225 * @private
1226 * PRIVATE - DO NOT USE
1227 *
1228 * Get a navigation blocker
1229 * @param key The identifier for the blocker
1230 * @param fn The blocker function implementation
1231 */
1232 getBlocker(key: string, fn: BlockerFunction): Blocker;
1233 /**
1234 * @private
1235 * PRIVATE - DO NOT USE
1236 *
1237 * Delete a navigation blocker
1238 * @param key The identifier for the blocker
1239 */
1240 deleteBlocker(key: string): void;
1241 /**
1242 * @private
1243 * PRIVATE DO NOT USE
1244 *
1245 * Patch additional children routes into an existing parent route
1246 * @param routeId The parent route id or a callback function accepting `patch`
1247 * to perform batch patching
1248 * @param children The additional children routes
1249 * @param unstable_allowElementMutations Allow mutation or route elements on
1250 * existing routes. Intended for RSC-usage
1251 * only.
1252 */
1253 patchRoutes(routeId: string | null, children: AgnosticRouteObject[], unstable_allowElementMutations?: boolean): void;
1254 /**
1255 * @private
1256 * PRIVATE - DO NOT USE
1257 *
1258 * HMR needs to pass in-flight route updates to React Router
1259 * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)
1260 */
1261 _internalSetRoutes(routes: AgnosticRouteObject[]): void;
1262 /**
1263 * @private
1264 * PRIVATE - DO NOT USE
1265 *
1266 * Cause subscribers to re-render. This is used to force a re-render.
1267 */
1268 _internalSetStateDoNotUseOrYouWillBreakYourApp(state: Partial<RouterState>): void;
1269 /**
1270 * @private
1271 * PRIVATE - DO NOT USE
1272 *
1273 * Internal fetch AbortControllers accessed by unit tests
1274 */
1275 _internalFetchControllers: Map<string, AbortController>;
1276}
1277/**
1278 * State maintained internally by the router. During a navigation, all states
1279 * reflect the "old" location unless otherwise noted.
1280 */
1281interface RouterState {
1282 /**
1283 * The action of the most recent navigation
1284 */
1285 historyAction: Action;
1286 /**
1287 * The current location reflected by the router
1288 */
1289 location: Location;
1290 /**
1291 * The current set of route matches
1292 */
1293 matches: AgnosticDataRouteMatch[];
1294 /**
1295 * Tracks whether we've completed our initial data load
1296 */
1297 initialized: boolean;
1298 /**
1299 * Current scroll position we should start at for a new view
1300 * - number -> scroll position to restore to
1301 * - false -> do not restore scroll at all (used during submissions/revalidations)
1302 * - null -> don't have a saved position, scroll to hash or top of page
1303 */
1304 restoreScrollPosition: number | false | null;
1305 /**
1306 * Indicate whether this navigation should skip resetting the scroll position
1307 * if we are unable to restore the scroll position
1308 */
1309 preventScrollReset: boolean;
1310 /**
1311 * Tracks the state of the current navigation
1312 */
1313 navigation: Navigation;
1314 /**
1315 * Tracks any in-progress revalidations
1316 */
1317 revalidation: RevalidationState;
1318 /**
1319 * Data from the loaders for the current matches
1320 */
1321 loaderData: RouteData;
1322 /**
1323 * Data from the action for the current matches
1324 */
1325 actionData: RouteData | null;
1326 /**
1327 * Errors caught from loaders for the current matches
1328 */
1329 errors: RouteData | null;
1330 /**
1331 * Map of current fetchers
1332 */
1333 fetchers: Map<string, Fetcher>;
1334 /**
1335 * Map of current blockers
1336 */
1337 blockers: Map<string, Blocker>;
1338}
1339/**
1340 * Data that can be passed into hydrate a Router from SSR
1341 */
1342type HydrationState = Partial<Pick<RouterState, "loaderData" | "actionData" | "errors">>;
1343/**
1344 * Future flags to toggle new feature behavior
1345 */
1346interface FutureConfig {
1347}
1348/**
1349 * Initialization options for createRouter
1350 */
1351interface RouterInit {
1352 routes: AgnosticRouteObject[];
1353 history: History;
1354 basename?: string;
1355 getContext?: () => MaybePromise<RouterContextProvider>;
1356 unstable_instrumentations?: unstable_ClientInstrumentation[];
1357 mapRouteProperties?: MapRoutePropertiesFunction;
1358 future?: Partial<FutureConfig>;
1359 hydrationRouteProperties?: string[];
1360 hydrationData?: HydrationState;
1361 window?: Window;
1362 dataStrategy?: DataStrategyFunction;
1363 patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;
1364}
1365/**
1366 * State returned from a server-side query() call
1367 */
1368interface StaticHandlerContext {
1369 basename: Router$1["basename"];
1370 location: RouterState["location"];
1371 matches: RouterState["matches"];
1372 loaderData: RouterState["loaderData"];
1373 actionData: RouterState["actionData"];
1374 errors: RouterState["errors"];
1375 statusCode: number;
1376 loaderHeaders: Record<string, Headers>;
1377 actionHeaders: Record<string, Headers>;
1378 _deepestRenderedBoundaryId?: string | null;
1379}
1380/**
1381 * A StaticHandler instance manages a singular SSR navigation/fetch event
1382 */
1383interface StaticHandler {
1384 dataRoutes: AgnosticDataRouteObject[];
1385 query(request: Request, opts?: {
1386 requestContext?: unknown;
1387 filterMatchesToLoad?: (match: AgnosticDataRouteMatch) => boolean;
1388 skipLoaderErrorBubbling?: boolean;
1389 skipRevalidation?: boolean;
1390 dataStrategy?: DataStrategyFunction<unknown>;
1391 generateMiddlewareResponse?: (query: (r: Request, args?: {
1392 filterMatchesToLoad?: (match: AgnosticDataRouteMatch) => boolean;
1393 }) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
1394 }): Promise<StaticHandlerContext | Response>;
1395 queryRoute(request: Request, opts?: {
1396 routeId?: string;
1397 requestContext?: unknown;
1398 dataStrategy?: DataStrategyFunction<unknown>;
1399 generateMiddlewareResponse?: (queryRoute: (r: Request) => Promise<Response>) => MaybePromise<Response>;
1400 }): Promise<any>;
1401}
1402type ViewTransitionOpts = {
1403 currentLocation: Location;
1404 nextLocation: Location;
1405};
1406/**
1407 * Subscriber function signature for changes to router state
1408 */
1409interface RouterSubscriber {
1410 (state: RouterState, opts: {
1411 deletedFetchers: string[];
1412 newErrors: RouteData | null;
1413 viewTransitionOpts?: ViewTransitionOpts;
1414 flushSync: boolean;
1415 }): void;
1416}
1417/**
1418 * Function signature for determining the key to be used in scroll restoration
1419 * for a given location
1420 */
1421interface GetScrollRestorationKeyFunction {
1422 (location: Location, matches: UIMatch[]): string | null;
1423}
1424/**
1425 * Function signature for determining the current scroll position
1426 */
1427interface GetScrollPositionFunction {
1428 (): number;
1429}
1430/**
1431 * - "route": relative to the route hierarchy so `..` means remove all segments
1432 * of the current route even if it has many. For example, a `route("posts/:id")`
1433 * would have both `:id` and `posts` removed from the url.
1434 * - "path": relative to the pathname so `..` means remove one segment of the
1435 * pathname. For example, a `route("posts/:id")` would have only `:id` removed
1436 * from the url.
1437 */
1438type RelativeRoutingType = "route" | "path";
1439type BaseNavigateOrFetchOptions = {
1440 preventScrollReset?: boolean;
1441 relative?: RelativeRoutingType;
1442 flushSync?: boolean;
1443};
1444type BaseNavigateOptions = BaseNavigateOrFetchOptions & {
1445 replace?: boolean;
1446 state?: any;
1447 fromRouteId?: string;
1448 viewTransition?: boolean;
1449};
1450type BaseSubmissionOptions = {
1451 formMethod?: HTMLFormMethod;
1452 formEncType?: FormEncType;
1453} & ({
1454 formData: FormData;
1455 body?: undefined;
1456} | {
1457 formData?: undefined;
1458 body: any;
1459});
1460/**
1461 * Options for a navigate() call for a normal (non-submission) navigation
1462 */
1463type LinkNavigateOptions = BaseNavigateOptions;
1464/**
1465 * Options for a navigate() call for a submission navigation
1466 */
1467type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;
1468/**
1469 * Options to pass to navigate() for a navigation
1470 */
1471type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
1472/**
1473 * Options for a fetch() load
1474 */
1475type LoadFetchOptions = BaseNavigateOrFetchOptions;
1476/**
1477 * Options for a fetch() submission
1478 */
1479type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;
1480/**
1481 * Options to pass to fetch()
1482 */
1483type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;
1484/**
1485 * Potential states for state.navigation
1486 */
1487type NavigationStates = {
1488 Idle: {
1489 state: "idle";
1490 location: undefined;
1491 formMethod: undefined;
1492 formAction: undefined;
1493 formEncType: undefined;
1494 formData: undefined;
1495 json: undefined;
1496 text: undefined;
1497 };
1498 Loading: {
1499 state: "loading";
1500 location: Location;
1501 formMethod: Submission["formMethod"] | undefined;
1502 formAction: Submission["formAction"] | undefined;
1503 formEncType: Submission["formEncType"] | undefined;
1504 formData: Submission["formData"] | undefined;
1505 json: Submission["json"] | undefined;
1506 text: Submission["text"] | undefined;
1507 };
1508 Submitting: {
1509 state: "submitting";
1510 location: Location;
1511 formMethod: Submission["formMethod"];
1512 formAction: Submission["formAction"];
1513 formEncType: Submission["formEncType"];
1514 formData: Submission["formData"];
1515 json: Submission["json"];
1516 text: Submission["text"];
1517 };
1518};
1519type Navigation = NavigationStates[keyof NavigationStates];
1520type RevalidationState = "idle" | "loading";
1521/**
1522 * Potential states for fetchers
1523 */
1524type FetcherStates<TData = any> = {
1525 /**
1526 * The fetcher is not calling a loader or action
1527 *
1528 * ```tsx
1529 * fetcher.state === "idle"
1530 * ```
1531 */
1532 Idle: {
1533 state: "idle";
1534 formMethod: undefined;
1535 formAction: undefined;
1536 formEncType: undefined;
1537 text: undefined;
1538 formData: undefined;
1539 json: undefined;
1540 /**
1541 * If the fetcher has never been called, this will be undefined.
1542 */
1543 data: TData | undefined;
1544 };
1545 /**
1546 * The fetcher is loading data from a {@link LoaderFunction | loader} from a
1547 * call to {@link FetcherWithComponents.load | `fetcher.load`}.
1548 *
1549 * ```tsx
1550 * // somewhere
1551 * <button onClick={() => fetcher.load("/some/route") }>Load</button>
1552 *
1553 * // the state will update
1554 * fetcher.state === "loading"
1555 * ```
1556 */
1557 Loading: {
1558 state: "loading";
1559 formMethod: Submission["formMethod"] | undefined;
1560 formAction: Submission["formAction"] | undefined;
1561 formEncType: Submission["formEncType"] | undefined;
1562 text: Submission["text"] | undefined;
1563 formData: Submission["formData"] | undefined;
1564 json: Submission["json"] | undefined;
1565 data: TData | undefined;
1566 };
1567 /**
1568 The fetcher is submitting to a {@link LoaderFunction} (GET) or {@link ActionFunction} (POST) from a {@link FetcherWithComponents.Form | `fetcher.Form`} or {@link FetcherWithComponents.submit | `fetcher.submit`}.
1569
1570 ```tsx
1571 // somewhere
1572 <input
1573 onChange={e => {
1574 fetcher.submit(event.currentTarget.form, { method: "post" });
1575 }}
1576 />
1577
1578 // the state will update
1579 fetcher.state === "submitting"
1580
1581 // and formData will be available
1582 fetcher.formData
1583 ```
1584 */
1585 Submitting: {
1586 state: "submitting";
1587 formMethod: Submission["formMethod"];
1588 formAction: Submission["formAction"];
1589 formEncType: Submission["formEncType"];
1590 text: Submission["text"];
1591 formData: Submission["formData"];
1592 json: Submission["json"];
1593 data: TData | undefined;
1594 };
1595};
1596type Fetcher<TData = any> = FetcherStates<TData>[keyof FetcherStates<TData>];
1597interface BlockerBlocked {
1598 state: "blocked";
1599 reset: () => void;
1600 proceed: () => void;
1601 location: Location;
1602}
1603interface BlockerUnblocked {
1604 state: "unblocked";
1605 reset: undefined;
1606 proceed: undefined;
1607 location: undefined;
1608}
1609interface BlockerProceeding {
1610 state: "proceeding";
1611 reset: undefined;
1612 proceed: undefined;
1613 location: Location;
1614}
1615type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
1616type BlockerFunction = (args: {
1617 currentLocation: Location;
1618 nextLocation: Location;
1619 historyAction: Action;
1620}) => boolean;
1621declare const IDLE_NAVIGATION: NavigationStates["Idle"];
1622declare const IDLE_FETCHER: FetcherStates["Idle"];
1623declare const IDLE_BLOCKER: BlockerUnblocked;
1624/**
1625 * Create a router and listen to history POP navigations
1626 */
1627declare function createRouter(init: RouterInit): Router$1;
1628interface CreateStaticHandlerOptions {
1629 basename?: string;
1630 mapRouteProperties?: MapRoutePropertiesFunction;
1631 unstable_instrumentations?: Pick<unstable_ServerInstrumentation, "route">[];
1632 future?: {};
1633}
1634
1635declare function mapRouteProperties(route: RouteObject): Partial<RouteObject> & {
1636 hasErrorBoundary: boolean;
1637};
1638declare const hydrationRouteProperties: (keyof RouteObject)[];
1639/**
1640 * @category Data Routers
1641 */
1642interface MemoryRouterOpts {
1643 /**
1644 * Basename path for the application.
1645 */
1646 basename?: string;
1647 /**
1648 * A function that returns an {@link RouterContextProvider} instance
1649 * which is provided as the `context` argument to client [`action`](../../start/data/route-object#action)s,
1650 * [`loader`](../../start/data/route-object#loader)s and [middleware](../../how-to/middleware).
1651 * This function is called to generate a fresh `context` instance on each
1652 * navigation or fetcher call.
1653 */
1654 getContext?: RouterInit["getContext"];
1655 /**
1656 * Future flags to enable for the router.
1657 */
1658 future?: Partial<FutureConfig>;
1659 /**
1660 * Hydration data to initialize the router with if you have already performed
1661 * data loading on the server.
1662 */
1663 hydrationData?: HydrationState;
1664 /**
1665 * Initial entries in the in-memory history stack
1666 */
1667 initialEntries?: InitialEntry[];
1668 /**
1669 * Index of `initialEntries` the application should initialize to
1670 */
1671 initialIndex?: number;
1672 /**
1673 * Array of instrumentation objects allowing you to instrument the router and
1674 * individual routes prior to router initialization (and on any subsequently
1675 * added routes via `route.lazy` or `patchRoutesOnNavigation`). This is
1676 * mostly useful for observability such as wrapping navigations, fetches,
1677 * as well as route loaders/actions/middlewares with logging and/or performance
1678 * tracing. See the [docs](../../how-to/instrumentation) for more information.
1679 *
1680 * ```tsx
1681 * let router = createBrowserRouter(routes, {
1682 * unstable_instrumentations: [logging]
1683 * });
1684 *
1685 *
1686 * let logging = {
1687 * router({ instrument }) {
1688 * instrument({
1689 * navigate: (impl, info) => logExecution(`navigate ${info.to}`, impl),
1690 * fetch: (impl, info) => logExecution(`fetch ${info.to}`, impl)
1691 * });
1692 * },
1693 * route({ instrument, id }) {
1694 * instrument({
1695 * middleware: (impl, info) => logExecution(
1696 * `middleware ${info.request.url} (route ${id})`,
1697 * impl
1698 * ),
1699 * loader: (impl, info) => logExecution(
1700 * `loader ${info.request.url} (route ${id})`,
1701 * impl
1702 * ),
1703 * action: (impl, info) => logExecution(
1704 * `action ${info.request.url} (route ${id})`,
1705 * impl
1706 * ),
1707 * })
1708 * }
1709 * };
1710 *
1711 * async function logExecution(label: string, impl: () => Promise<void>) {
1712 * let start = performance.now();
1713 * console.log(`start ${label}`);
1714 * await impl();
1715 * let duration = Math.round(performance.now() - start);
1716 * console.log(`end ${label} (${duration}ms)`);
1717 * }
1718 * ```
1719 */
1720 unstable_instrumentations?: unstable_ClientInstrumentation[];
1721 /**
1722 * Override the default data strategy of running loaders in parallel -
1723 * see the [docs](../../how-to/data-strategy) for more information.
1724 *
1725 * ```tsx
1726 * let router = createBrowserRouter(routes, {
1727 * async dataStrategy({
1728 * matches,
1729 * request,
1730 * runClientMiddleware,
1731 * }) {
1732 * const matchesToLoad = matches.filter((m) =>
1733 * m.shouldCallHandler(),
1734 * );
1735 *
1736 * const results: Record<string, DataStrategyResult> = {};
1737 * await runClientMiddleware(() =>
1738 * Promise.all(
1739 * matchesToLoad.map(async (match) => {
1740 * results[match.route.id] = await match.resolve();
1741 * }),
1742 * ),
1743 * );
1744 * return results;
1745 * },
1746 * });
1747 * ```
1748 */
1749 dataStrategy?: DataStrategyFunction;
1750 /**
1751 * Lazily define portions of the route tree on navigations.
1752 */
1753 patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
1754}
1755/**
1756 * Create a new {@link DataRouter} that manages the application path using an
1757 * in-memory [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1758 * stack. Useful for non-browser environments without a DOM API.
1759 *
1760 * @public
1761 * @category Data Routers
1762 * @mode data
1763 * @param routes Application routes
1764 * @param opts Options
1765 * @param {MemoryRouterOpts.basename} opts.basename n/a
1766 * @param {MemoryRouterOpts.dataStrategy} opts.dataStrategy n/a
1767 * @param {MemoryRouterOpts.future} opts.future n/a
1768 * @param {MemoryRouterOpts.getContext} opts.getContext n/a
1769 * @param {MemoryRouterOpts.hydrationData} opts.hydrationData n/a
1770 * @param {MemoryRouterOpts.initialEntries} opts.initialEntries n/a
1771 * @param {MemoryRouterOpts.initialIndex} opts.initialIndex n/a
1772 * @param {MemoryRouterOpts.unstable_instrumentations} opts.unstable_instrumentations n/a
1773 * @param {MemoryRouterOpts.patchRoutesOnNavigation} opts.patchRoutesOnNavigation n/a
1774 * @returns An initialized {@link DataRouter} to pass to {@link RouterProvider | `<RouterProvider>`}
1775 */
1776declare function createMemoryRouter(routes: RouteObject[], opts?: MemoryRouterOpts): Router$1;
1777/**
1778 * Function signature for client side error handling for loader/actions errors
1779 * and rendering errors via `componentDidCatch`
1780 */
1781interface unstable_ClientOnErrorFunction {
1782 (error: unknown, info: {
1783 location: Location;
1784 params: Params;
1785 unstable_pattern: string;
1786 errorInfo?: React.ErrorInfo;
1787 }): void;
1788}
1789/**
1790 * @category Types
1791 */
1792interface RouterProviderProps {
1793 /**
1794 * The {@link DataRouter} instance to use for navigation and data fetching.
1795 */
1796 router: Router$1;
1797 /**
1798 * The [`ReactDOM.flushSync`](https://react.dev/reference/react-dom/flushSync)
1799 * implementation to use for flushing updates.
1800 *
1801 * You usually don't have to worry about this:
1802 * - The `RouterProvider` exported from `react-router/dom` handles this internally for you
1803 * - If you are rendering in a non-DOM environment, you can import
1804 * `RouterProvider` from `react-router` and ignore this prop
1805 */
1806 flushSync?: (fn: () => unknown) => undefined;
1807 /**
1808 * An error handler function that will be called for any loader/action/render
1809 * errors that are encountered in your application. This is useful for
1810 * logging or reporting errors instead of the `ErrorBoundary` because it's not
1811 * subject to re-rendering and will only run one time per error.
1812 *
1813 * The `errorInfo` parameter is passed along from
1814 * [`componentDidCatch`](https://react.dev/reference/react/Component#componentdidcatch)
1815 * and is only present for render errors.
1816 *
1817 * ```tsx
1818 * <RouterProvider unstable_onError=(error, errorInfo) => {
1819 * console.error(error, errorInfo);
1820 * reportToErrorService(error, errorInfo);
1821 * }} />
1822 * ```
1823 */
1824 unstable_onError?: unstable_ClientOnErrorFunction;
1825 /**
1826 * Control whether router state updates are internally wrapped in
1827 * [`React.startTransition`](https://react.dev/reference/react/startTransition).
1828 *
1829 * - When left `undefined`, all state updates are wrapped in
1830 * `React.startTransition`
1831 * - This can lead to buggy behaviors if you are wrapping your own
1832 * navigations/fetchers in `startTransition`.
1833 * - When set to `true`, {@link Link} and {@link Form} navigations will be wrapped
1834 * in `React.startTransition` and router state changes will be wrapped in
1835 * `React.startTransition` and also sent through
1836 * [`useOptimistic`](https://react.dev/reference/react/useOptimistic) to
1837 * surface mid-navigation router state changes to the UI.
1838 * - When set to `false`, the router will not leverage `React.startTransition` or
1839 * `React.useOptimistic` on any navigations or state changes.
1840 *
1841 * For more information, please see the [docs](https://reactrouter.com/explanation/react-transitions).
1842 */
1843 unstable_useTransitions?: boolean;
1844}
1845/**
1846 * Render the UI for the given {@link DataRouter}. This component should
1847 * typically be at the top of an app's element tree.
1848 *
1849 * ```tsx
1850 * import { createBrowserRouter } from "react-router";
1851 * import { RouterProvider } from "react-router/dom";
1852 * import { createRoot } from "react-dom/client";
1853 *
1854 * const router = createBrowserRouter(routes);
1855 * createRoot(document.getElementById("root")).render(
1856 * <RouterProvider router={router} />
1857 * );
1858 * ```
1859 *
1860 * <docs-info>Please note that this component is exported both from
1861 * `react-router` and `react-router/dom` with the only difference being that the
1862 * latter automatically wires up `react-dom`'s [`flushSync`](https://react.dev/reference/react-dom/flushSync)
1863 * implementation. You _almost always_ want to use the version from
1864 * `react-router/dom` unless you're running in a non-DOM environment.</docs-info>
1865 *
1866 *
1867 * @public
1868 * @category Data Routers
1869 * @mode data
1870 * @param props Props
1871 * @param {RouterProviderProps.flushSync} props.flushSync n/a
1872 * @param {RouterProviderProps.unstable_onError} props.unstable_onError n/a
1873 * @param {RouterProviderProps.router} props.router n/a
1874 * @param {RouterProviderProps.unstable_useTransitions} props.unstable_useTransitions n/a
1875 * @returns React element for the rendered router
1876 */
1877declare function RouterProvider({ router, flushSync: reactDomFlushSyncImpl, unstable_onError, unstable_useTransitions, }: RouterProviderProps): React.ReactElement;
1878/**
1879 * @category Types
1880 */
1881interface MemoryRouterProps {
1882 /**
1883 * Application basename
1884 */
1885 basename?: string;
1886 /**
1887 * Nested {@link Route} elements describing the route tree
1888 */
1889 children?: React.ReactNode;
1890 /**
1891 * Initial entries in the in-memory history stack
1892 */
1893 initialEntries?: InitialEntry[];
1894 /**
1895 * Index of `initialEntries` the application should initialize to
1896 */
1897 initialIndex?: number;
1898 /**
1899 * Control whether router state updates are internally wrapped in
1900 * [`React.startTransition`](https://react.dev/reference/react/startTransition).
1901 *
1902 * - When left `undefined`, all router state updates are wrapped in
1903 * `React.startTransition`
1904 * - When set to `true`, {@link Link} and {@link Form} navigations will be wrapped
1905 * in `React.startTransition` and all router state updates are wrapped in
1906 * `React.startTransition`
1907 * - When set to `false`, the router will not leverage `React.startTransition`
1908 * on any navigations or state changes.
1909 *
1910 * For more information, please see the [docs](https://reactrouter.com/explanation/react-transitions).
1911 */
1912 unstable_useTransitions?: boolean;
1913}
1914/**
1915 * A declarative {@link Router | `<Router>`} that stores all entries in memory.
1916 *
1917 * @public
1918 * @category Declarative Routers
1919 * @mode declarative
1920 * @param props Props
1921 * @param {MemoryRouterProps.basename} props.basename n/a
1922 * @param {MemoryRouterProps.children} props.children n/a
1923 * @param {MemoryRouterProps.initialEntries} props.initialEntries n/a
1924 * @param {MemoryRouterProps.initialIndex} props.initialIndex n/a
1925 * @param {MemoryRouterProps.unstable_useTransitions} props.unstable_useTransitions n/a
1926 * @returns A declarative in-memory {@link Router | `<Router>`} for client-side
1927 * routing.
1928 */
1929declare function MemoryRouter({ basename, children, initialEntries, initialIndex, unstable_useTransitions, }: MemoryRouterProps): React.ReactElement;
1930/**
1931 * @category Types
1932 */
1933interface NavigateProps {
1934 /**
1935 * The path to navigate to. This can be a string or a {@link Path} object
1936 */
1937 to: To;
1938 /**
1939 * Whether to replace the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1940 * stack
1941 */
1942 replace?: boolean;
1943 /**
1944 * State to pass to the new {@link Location} to store in [`history.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state).
1945 */
1946 state?: any;
1947 /**
1948 * How to interpret relative routing in the `to` prop.
1949 * See {@link RelativeRoutingType}.
1950 */
1951 relative?: RelativeRoutingType;
1952}
1953/**
1954 * A component-based version of {@link useNavigate} to use in a
1955 * [`React.Component` class](https://react.dev/reference/react/Component) where
1956 * hooks cannot be used.
1957 *
1958 * It's recommended to avoid using this component in favor of {@link useNavigate}.
1959 *
1960 * @example
1961 * <Navigate to="/tasks" />
1962 *
1963 * @public
1964 * @category Components
1965 * @param props Props
1966 * @param {NavigateProps.relative} props.relative n/a
1967 * @param {NavigateProps.replace} props.replace n/a
1968 * @param {NavigateProps.state} props.state n/a
1969 * @param {NavigateProps.to} props.to n/a
1970 * @returns {void}
1971 *
1972 */
1973declare function Navigate({ to, replace, state, relative, }: NavigateProps): null;
1974/**
1975 * @category Types
1976 */
1977interface OutletProps {
1978 /**
1979 * Provides a context value to the element tree below the outlet. Use when
1980 * the parent route needs to provide values to child routes.
1981 *
1982 * ```tsx
1983 * <Outlet context={myContextValue} />
1984 * ```
1985 *
1986 * Access the context with {@link useOutletContext}.
1987 */
1988 context?: unknown;
1989}
1990/**
1991 * Renders the matching child route of a parent route or nothing if no child
1992 * route matches.
1993 *
1994 * @example
1995 * import { Outlet } from "react-router";
1996 *
1997 * export default function SomeParent() {
1998 * return (
1999 * <div>
2000 * <h1>Parent Content</h1>
2001 * <Outlet />
2002 * </div>
2003 * );
2004 * }
2005 *
2006 * @public
2007 * @category Components
2008 * @param props Props
2009 * @param {OutletProps.context} props.context n/a
2010 * @returns React element for the rendered outlet or `null` if no child route matches.
2011 */
2012declare function Outlet(props: OutletProps): React.ReactElement | null;
2013/**
2014 * @category Types
2015 */
2016interface PathRouteProps {
2017 /**
2018 * Whether the path should be case-sensitive. Defaults to `false`.
2019 */
2020 caseSensitive?: NonIndexRouteObject["caseSensitive"];
2021 /**
2022 * The path pattern to match. If unspecified or empty, then this becomes a
2023 * layout route.
2024 */
2025 path?: NonIndexRouteObject["path"];
2026 /**
2027 * The unique identifier for this route (for use with {@link DataRouter}s)
2028 */
2029 id?: NonIndexRouteObject["id"];
2030 /**
2031 * A function that returns a promise that resolves to the route object.
2032 * Used for code-splitting routes.
2033 * See [`lazy`](../../start/data/route-object#lazy).
2034 */
2035 lazy?: LazyRouteFunction<NonIndexRouteObject>;
2036 /**
2037 * The route middleware.
2038 * See [`middleware`](../../start/data/route-object#middleware).
2039 */
2040 middleware?: NonIndexRouteObject["middleware"];
2041 /**
2042 * The route loader.
2043 * See [`loader`](../../start/data/route-object#loader).
2044 */
2045 loader?: NonIndexRouteObject["loader"];
2046 /**
2047 * The route action.
2048 * See [`action`](../../start/data/route-object#action).
2049 */
2050 action?: NonIndexRouteObject["action"];
2051 hasErrorBoundary?: NonIndexRouteObject["hasErrorBoundary"];
2052 /**
2053 * The route shouldRevalidate function.
2054 * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
2055 */
2056 shouldRevalidate?: NonIndexRouteObject["shouldRevalidate"];
2057 /**
2058 * The route handle.
2059 */
2060 handle?: NonIndexRouteObject["handle"];
2061 /**
2062 * Whether this is an index route.
2063 */
2064 index?: false;
2065 /**
2066 * Child Route components
2067 */
2068 children?: React.ReactNode;
2069 /**
2070 * The React element to render when this Route matches.
2071 * Mutually exclusive with `Component`.
2072 */
2073 element?: React.ReactNode | null;
2074 /**
2075 * The React element to render while this router is loading data.
2076 * Mutually exclusive with `HydrateFallback`.
2077 */
2078 hydrateFallbackElement?: React.ReactNode | null;
2079 /**
2080 * The React element to render at this route if an error occurs.
2081 * Mutually exclusive with `ErrorBoundary`.
2082 */
2083 errorElement?: React.ReactNode | null;
2084 /**
2085 * The React Component to render when this route matches.
2086 * Mutually exclusive with `element`.
2087 */
2088 Component?: React.ComponentType | null;
2089 /**
2090 * The React Component to render while this router is loading data.
2091 * Mutually exclusive with `hydrateFallbackElement`.
2092 */
2093 HydrateFallback?: React.ComponentType | null;
2094 /**
2095 * The React Component to render at this route if an error occurs.
2096 * Mutually exclusive with `errorElement`.
2097 */
2098 ErrorBoundary?: React.ComponentType | null;
2099}
2100/**
2101 * @category Types
2102 */
2103interface LayoutRouteProps extends PathRouteProps {
2104}
2105/**
2106 * @category Types
2107 */
2108interface IndexRouteProps {
2109 /**
2110 * Whether the path should be case-sensitive. Defaults to `false`.
2111 */
2112 caseSensitive?: IndexRouteObject["caseSensitive"];
2113 /**
2114 * The path pattern to match. If unspecified or empty, then this becomes a
2115 * layout route.
2116 */
2117 path?: IndexRouteObject["path"];
2118 /**
2119 * The unique identifier for this route (for use with {@link DataRouter}s)
2120 */
2121 id?: IndexRouteObject["id"];
2122 /**
2123 * A function that returns a promise that resolves to the route object.
2124 * Used for code-splitting routes.
2125 * See [`lazy`](../../start/data/route-object#lazy).
2126 */
2127 lazy?: LazyRouteFunction<IndexRouteObject>;
2128 /**
2129 * The route middleware.
2130 * See [`middleware`](../../start/data/route-object#middleware).
2131 */
2132 middleware?: IndexRouteObject["middleware"];
2133 /**
2134 * The route loader.
2135 * See [`loader`](../../start/data/route-object#loader).
2136 */
2137 loader?: IndexRouteObject["loader"];
2138 /**
2139 * The route action.
2140 * See [`action`](../../start/data/route-object#action).
2141 */
2142 action?: IndexRouteObject["action"];
2143 hasErrorBoundary?: IndexRouteObject["hasErrorBoundary"];
2144 /**
2145 * The route shouldRevalidate function.
2146 * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
2147 */
2148 shouldRevalidate?: IndexRouteObject["shouldRevalidate"];
2149 /**
2150 * The route handle.
2151 */
2152 handle?: IndexRouteObject["handle"];
2153 /**
2154 * Whether this is an index route.
2155 */
2156 index: true;
2157 /**
2158 * Child Route components
2159 */
2160 children?: undefined;
2161 /**
2162 * The React element to render when this Route matches.
2163 * Mutually exclusive with `Component`.
2164 */
2165 element?: React.ReactNode | null;
2166 /**
2167 * The React element to render while this router is loading data.
2168 * Mutually exclusive with `HydrateFallback`.
2169 */
2170 hydrateFallbackElement?: React.ReactNode | null;
2171 /**
2172 * The React element to render at this route if an error occurs.
2173 * Mutually exclusive with `ErrorBoundary`.
2174 */
2175 errorElement?: React.ReactNode | null;
2176 /**
2177 * The React Component to render when this route matches.
2178 * Mutually exclusive with `element`.
2179 */
2180 Component?: React.ComponentType | null;
2181 /**
2182 * The React Component to render while this router is loading data.
2183 * Mutually exclusive with `hydrateFallbackElement`.
2184 */
2185 HydrateFallback?: React.ComponentType | null;
2186 /**
2187 * The React Component to render at this route if an error occurs.
2188 * Mutually exclusive with `errorElement`.
2189 */
2190 ErrorBoundary?: React.ComponentType | null;
2191}
2192type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;
2193/**
2194 * Configures an element to render when a pattern matches the current location.
2195 * It must be rendered within a {@link Routes} element. Note that these routes
2196 * do not participate in data loading, actions, code splitting, or any other
2197 * route module features.
2198 *
2199 * @example
2200 * // Usually used in a declarative router
2201 * function App() {
2202 * return (
2203 * <BrowserRouter>
2204 * <Routes>
2205 * <Route index element={<StepOne />} />
2206 * <Route path="step-2" element={<StepTwo />} />
2207 * <Route path="step-3" element={<StepThree />} />
2208 * </Routes>
2209 * </BrowserRouter>
2210 * );
2211 * }
2212 *
2213 * // But can be used with a data router as well if you prefer the JSX notation
2214 * const routes = createRoutesFromElements(
2215 * <>
2216 * <Route index loader={step1Loader} Component={StepOne} />
2217 * <Route path="step-2" loader={step2Loader} Component={StepTwo} />
2218 * <Route path="step-3" loader={step3Loader} Component={StepThree} />
2219 * </>
2220 * );
2221 *
2222 * const router = createBrowserRouter(routes);
2223 *
2224 * function App() {
2225 * return <RouterProvider router={router} />;
2226 * }
2227 *
2228 * @public
2229 * @category Components
2230 * @param props Props
2231 * @param {PathRouteProps.action} props.action n/a
2232 * @param {PathRouteProps.caseSensitive} props.caseSensitive n/a
2233 * @param {PathRouteProps.Component} props.Component n/a
2234 * @param {PathRouteProps.children} props.children n/a
2235 * @param {PathRouteProps.element} props.element n/a
2236 * @param {PathRouteProps.ErrorBoundary} props.ErrorBoundary n/a
2237 * @param {PathRouteProps.errorElement} props.errorElement n/a
2238 * @param {PathRouteProps.handle} props.handle n/a
2239 * @param {PathRouteProps.HydrateFallback} props.HydrateFallback n/a
2240 * @param {PathRouteProps.hydrateFallbackElement} props.hydrateFallbackElement n/a
2241 * @param {PathRouteProps.id} props.id n/a
2242 * @param {PathRouteProps.index} props.index n/a
2243 * @param {PathRouteProps.lazy} props.lazy n/a
2244 * @param {PathRouteProps.loader} props.loader n/a
2245 * @param {PathRouteProps.path} props.path n/a
2246 * @param {PathRouteProps.shouldRevalidate} props.shouldRevalidate n/a
2247 * @returns {void}
2248 */
2249declare function Route(props: RouteProps): React.ReactElement | null;
2250/**
2251 * @category Types
2252 */
2253interface RouterProps {
2254 /**
2255 * The base path for the application. This is prepended to all locations
2256 */
2257 basename?: string;
2258 /**
2259 * Nested {@link Route} elements describing the route tree
2260 */
2261 children?: React.ReactNode;
2262 /**
2263 * The location to match against. Defaults to the current location.
2264 * This can be a string or a {@link Location} object.
2265 */
2266 location: Partial<Location> | string;
2267 /**
2268 * The type of navigation that triggered this `location` change.
2269 * Defaults to {@link NavigationType.Pop}.
2270 */
2271 navigationType?: Action;
2272 /**
2273 * The navigator to use for navigation. This is usually a history object
2274 * or a custom navigator that implements the {@link Navigator} interface.
2275 */
2276 navigator: Navigator;
2277 /**
2278 * Whether this router is static or not (used for SSR). If `true`, the router
2279 * will not be reactive to location changes.
2280 */
2281 static?: boolean;
2282 /**
2283 * Whether this router should wrap navigations in `React.startTransition()`
2284 */
2285 unstable_useTransitions: boolean;
2286}
2287/**
2288 * Provides location context for the rest of the app.
2289 *
2290 * Note: You usually won't render a `<Router>` directly. Instead, you'll render a
2291 * router that is more specific to your environment such as a {@link BrowserRouter}
2292 * in web browsers or a {@link ServerRouter} for server rendering.
2293 *
2294 * @public
2295 * @category Declarative Routers
2296 * @mode declarative
2297 * @param props Props
2298 * @param {RouterProps.basename} props.basename n/a
2299 * @param {RouterProps.children} props.children n/a
2300 * @param {RouterProps.location} props.location n/a
2301 * @param {RouterProps.navigationType} props.navigationType n/a
2302 * @param {RouterProps.navigator} props.navigator n/a
2303 * @param {RouterProps.static} props.static n/a
2304 * @param {RouterProps.unstable_useTransitions} props.unstable_useTransitions n/a
2305 * @returns React element for the rendered router or `null` if the location does
2306 * not match the {@link props.basename}
2307 */
2308declare function Router({ basename: basenameProp, children, location: locationProp, navigationType, navigator, static: staticProp, unstable_useTransitions, }: RouterProps): React.ReactElement | null;
2309/**
2310 * @category Types
2311 */
2312interface RoutesProps {
2313 /**
2314 * Nested {@link Route} elements
2315 */
2316 children?: React.ReactNode;
2317 /**
2318 * The {@link Location} to match against. Defaults to the current location.
2319 */
2320 location?: Partial<Location> | string;
2321}
2322/**
2323 * Renders a branch of {@link Route | `<Route>`s} that best matches the current
2324 * location. Note that these routes do not participate in [data loading](../../start/framework/route-module#loader),
2325 * [`action`](../../start/framework/route-module#action), code splitting, or
2326 * any other [route module](../../start/framework/route-module) features.
2327 *
2328 * @example
2329 * import { Route, Routes } from "react-router";
2330 *
2331 * <Routes>
2332 * <Route index element={<StepOne />} />
2333 * <Route path="step-2" element={<StepTwo />} />
2334 * <Route path="step-3" element={<StepThree />} />
2335 * </Routes>
2336 *
2337 * @public
2338 * @category Components
2339 * @param props Props
2340 * @param {RoutesProps.children} props.children n/a
2341 * @param {RoutesProps.location} props.location n/a
2342 * @returns React element for the rendered routes or `null` if no route matches
2343 */
2344declare function Routes({ children, location, }: RoutesProps): React.ReactElement | null;
2345interface AwaitResolveRenderFunction<Resolve = any> {
2346 (data: Awaited<Resolve>): React.ReactNode;
2347}
2348/**
2349 * @category Types
2350 */
2351interface AwaitProps<Resolve> {
2352 /**
2353 * When using a function, the resolved value is provided as the parameter.
2354 *
2355 * ```tsx [2]
2356 * <Await resolve={reviewsPromise}>
2357 * {(resolvedReviews) => <Reviews items={resolvedReviews} />}
2358 * </Await>
2359 * ```
2360 *
2361 * When using React elements, {@link useAsyncValue} will provide the
2362 * resolved value:
2363 *
2364 * ```tsx [2]
2365 * <Await resolve={reviewsPromise}>
2366 * <Reviews />
2367 * </Await>
2368 *
2369 * function Reviews() {
2370 * const resolvedReviews = useAsyncValue();
2371 * return <div>...</div>;
2372 * }
2373 * ```
2374 */
2375 children: React.ReactNode | AwaitResolveRenderFunction<Resolve>;
2376 /**
2377 * The error element renders instead of the `children` when the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
2378 * rejects.
2379 *
2380 * ```tsx
2381 * <Await
2382 * errorElement={<div>Oops</div>}
2383 * resolve={reviewsPromise}
2384 * >
2385 * <Reviews />
2386 * </Await>
2387 * ```
2388 *
2389 * To provide a more contextual error, you can use the {@link useAsyncError} in a
2390 * child component
2391 *
2392 * ```tsx
2393 * <Await
2394 * errorElement={<ReviewsError />}
2395 * resolve={reviewsPromise}
2396 * >
2397 * <Reviews />
2398 * </Await>
2399 *
2400 * function ReviewsError() {
2401 * const error = useAsyncError();
2402 * return <div>Error loading reviews: {error.message}</div>;
2403 * }
2404 * ```
2405 *
2406 * If you do not provide an `errorElement`, the rejected value will bubble up
2407 * to the nearest route-level [`ErrorBoundary`](../../start/framework/route-module#errorboundary)
2408 * and be accessible via the {@link useRouteError} hook.
2409 */
2410 errorElement?: React.ReactNode;
2411 /**
2412 * Takes a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
2413 * returned from a [`loader`](../../start/framework/route-module#loader) to be
2414 * resolved and rendered.
2415 *
2416 * ```tsx
2417 * import { Await, useLoaderData } from "react-router";
2418 *
2419 * export async function loader() {
2420 * let reviews = getReviews(); // not awaited
2421 * let book = await getBook();
2422 * return {
2423 * book,
2424 * reviews, // this is a promise
2425 * };
2426 * }
2427 *
2428 * export default function Book() {
2429 * const {
2430 * book,
2431 * reviews, // this is the same promise
2432 * } = useLoaderData();
2433 *
2434 * return (
2435 * <div>
2436 * <h1>{book.title}</h1>
2437 * <p>{book.description}</p>
2438 * <React.Suspense fallback={<ReviewsSkeleton />}>
2439 * <Await
2440 * // and is the promise we pass to Await
2441 * resolve={reviews}
2442 * >
2443 * <Reviews />
2444 * </Await>
2445 * </React.Suspense>
2446 * </div>
2447 * );
2448 * }
2449 * ```
2450 */
2451 resolve: Resolve;
2452}
2453/**
2454 * Used to render promise values with automatic error handling.
2455 *
2456 * **Note:** `<Await>` expects to be rendered inside a [`<React.Suspense>`](https://react.dev/reference/react/Suspense)
2457 *
2458 * @example
2459 * import { Await, useLoaderData } from "react-router";
2460 *
2461 * export async function loader() {
2462 * // not awaited
2463 * const reviews = getReviews();
2464 * // awaited (blocks the transition)
2465 * const book = await fetch("/api/book").then((res) => res.json());
2466 * return { book, reviews };
2467 * }
2468 *
2469 * function Book() {
2470 * const { book, reviews } = useLoaderData();
2471 * return (
2472 * <div>
2473 * <h1>{book.title}</h1>
2474 * <p>{book.description}</p>
2475 * <React.Suspense fallback={<ReviewsSkeleton />}>
2476 * <Await
2477 * resolve={reviews}
2478 * errorElement={
2479 * <div>Could not load reviews 😬</div>
2480 * }
2481 * children={(resolvedReviews) => (
2482 * <Reviews items={resolvedReviews} />
2483 * )}
2484 * />
2485 * </React.Suspense>
2486 * </div>
2487 * );
2488 * }
2489 *
2490 * @public
2491 * @category Components
2492 * @mode framework
2493 * @mode data
2494 * @param props Props
2495 * @param {AwaitProps.children} props.children n/a
2496 * @param {AwaitProps.errorElement} props.errorElement n/a
2497 * @param {AwaitProps.resolve} props.resolve n/a
2498 * @returns React element for the rendered awaited value
2499 */
2500declare function Await<Resolve>({ children, errorElement, resolve, }: AwaitProps<Resolve>): React.JSX.Element;
2501/**
2502 * Creates a route config from a React "children" object, which is usually
2503 * either a `<Route>` element or an array of them. Used internally by
2504 * `<Routes>` to create a route config from its children.
2505 *
2506 * @category Utils
2507 * @mode data
2508 * @param children The React children to convert into a route config
2509 * @param parentPath The path of the parent route, used to generate unique IDs.
2510 * @returns An array of {@link RouteObject}s that can be used with a {@link DataRouter}
2511 */
2512declare function createRoutesFromChildren(children: React.ReactNode, parentPath?: number[]): RouteObject[];
2513/**
2514 * Create route objects from JSX elements instead of arrays of objects.
2515 *
2516 * @example
2517 * const routes = createRoutesFromElements(
2518 * <>
2519 * <Route index loader={step1Loader} Component={StepOne} />
2520 * <Route path="step-2" loader={step2Loader} Component={StepTwo} />
2521 * <Route path="step-3" loader={step3Loader} Component={StepThree} />
2522 * </>
2523 * );
2524 *
2525 * const router = createBrowserRouter(routes);
2526 *
2527 * function App() {
2528 * return <RouterProvider router={router} />;
2529 * }
2530 *
2531 * @name createRoutesFromElements
2532 * @public
2533 * @category Utils
2534 * @mode data
2535 * @param children The React children to convert into a route config
2536 * @param parentPath The path of the parent route, used to generate unique IDs.
2537 * This is used for internal recursion and is not intended to be used by the
2538 * application developer.
2539 * @returns An array of {@link RouteObject}s that can be used with a {@link DataRouter}
2540 */
2541declare const createRoutesFromElements: typeof createRoutesFromChildren;
2542/**
2543 * Renders the result of {@link matchRoutes} into a React element.
2544 *
2545 * @public
2546 * @category Utils
2547 * @param matches The array of {@link RouteMatch | route matches} to render
2548 * @returns A React element that renders the matched routes or `null` if no matches
2549 */
2550declare function renderMatches(matches: RouteMatch[] | null): React.ReactElement | null;
2551declare function useRouteComponentProps(): {
2552 params: Readonly<Params<string>>;
2553 loaderData: any;
2554 actionData: any;
2555 matches: UIMatch<unknown, unknown>[];
2556};
2557type RouteComponentProps = ReturnType<typeof useRouteComponentProps>;
2558type RouteComponentType = React.ComponentType<RouteComponentProps>;
2559declare function WithComponentProps({ children, }: {
2560 children: React.ReactElement;
2561}): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
2562declare function withComponentProps(Component: RouteComponentType): () => React.ReactElement<{
2563 params: Readonly<Params<string>>;
2564 loaderData: any;
2565 actionData: any;
2566 matches: UIMatch<unknown, unknown>[];
2567}, string | React.JSXElementConstructor<any>>;
2568declare function useHydrateFallbackProps(): {
2569 params: Readonly<Params<string>>;
2570 loaderData: any;
2571 actionData: any;
2572};
2573type HydrateFallbackProps = ReturnType<typeof useHydrateFallbackProps>;
2574type HydrateFallbackType = React.ComponentType<HydrateFallbackProps>;
2575declare function WithHydrateFallbackProps({ children, }: {
2576 children: React.ReactElement;
2577}): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
2578declare function withHydrateFallbackProps(HydrateFallback: HydrateFallbackType): () => React.ReactElement<{
2579 params: Readonly<Params<string>>;
2580 loaderData: any;
2581 actionData: any;
2582}, string | React.JSXElementConstructor<any>>;
2583declare function useErrorBoundaryProps(): {
2584 params: Readonly<Params<string>>;
2585 loaderData: any;
2586 actionData: any;
2587 error: unknown;
2588};
2589type ErrorBoundaryProps = ReturnType<typeof useErrorBoundaryProps>;
2590type ErrorBoundaryType = React.ComponentType<ErrorBoundaryProps>;
2591declare function WithErrorBoundaryProps({ children, }: {
2592 children: React.ReactElement;
2593}): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
2594declare function withErrorBoundaryProps(ErrorBoundary: ErrorBoundaryType): () => React.ReactElement<{
2595 params: Readonly<Params<string>>;
2596 loaderData: any;
2597 actionData: any;
2598 error: unknown;
2599}, string | React.JSXElementConstructor<any>>;
2600
2601interface IndexRouteObject {
2602 caseSensitive?: AgnosticIndexRouteObject["caseSensitive"];
2603 path?: AgnosticIndexRouteObject["path"];
2604 id?: AgnosticIndexRouteObject["id"];
2605 middleware?: AgnosticIndexRouteObject["middleware"];
2606 loader?: AgnosticIndexRouteObject["loader"];
2607 action?: AgnosticIndexRouteObject["action"];
2608 hasErrorBoundary?: AgnosticIndexRouteObject["hasErrorBoundary"];
2609 shouldRevalidate?: AgnosticIndexRouteObject["shouldRevalidate"];
2610 handle?: AgnosticIndexRouteObject["handle"];
2611 index: true;
2612 children?: undefined;
2613 element?: React.ReactNode | null;
2614 hydrateFallbackElement?: React.ReactNode | null;
2615 errorElement?: React.ReactNode | null;
2616 Component?: React.ComponentType | null;
2617 HydrateFallback?: React.ComponentType | null;
2618 ErrorBoundary?: React.ComponentType | null;
2619 lazy?: LazyRouteDefinition<RouteObject>;
2620}
2621interface NonIndexRouteObject {
2622 caseSensitive?: AgnosticNonIndexRouteObject["caseSensitive"];
2623 path?: AgnosticNonIndexRouteObject["path"];
2624 id?: AgnosticNonIndexRouteObject["id"];
2625 middleware?: AgnosticNonIndexRouteObject["middleware"];
2626 loader?: AgnosticNonIndexRouteObject["loader"];
2627 action?: AgnosticNonIndexRouteObject["action"];
2628 hasErrorBoundary?: AgnosticNonIndexRouteObject["hasErrorBoundary"];
2629 shouldRevalidate?: AgnosticNonIndexRouteObject["shouldRevalidate"];
2630 handle?: AgnosticNonIndexRouteObject["handle"];
2631 index?: false;
2632 children?: RouteObject[];
2633 element?: React.ReactNode | null;
2634 hydrateFallbackElement?: React.ReactNode | null;
2635 errorElement?: React.ReactNode | null;
2636 Component?: React.ComponentType | null;
2637 HydrateFallback?: React.ComponentType | null;
2638 ErrorBoundary?: React.ComponentType | null;
2639 lazy?: LazyRouteDefinition<RouteObject>;
2640}
2641type RouteObject = IndexRouteObject | NonIndexRouteObject;
2642type DataRouteObject = RouteObject & {
2643 children?: DataRouteObject[];
2644 id: string;
2645};
2646interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {
2647}
2648interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {
2649}
2650type PatchRoutesOnNavigationFunctionArgs = AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;
2651type PatchRoutesOnNavigationFunction = AgnosticPatchRoutesOnNavigationFunction<RouteObject, RouteMatch>;
2652interface DataRouterContextObject extends Omit<NavigationContextObject, "future" | "unstable_useTransitions"> {
2653 router: Router$1;
2654 staticContext?: StaticHandlerContext;
2655 unstable_onError?: unstable_ClientOnErrorFunction;
2656}
2657declare const DataRouterContext: React.Context<DataRouterContextObject | null>;
2658declare const DataRouterStateContext: React.Context<RouterState | null>;
2659type ViewTransitionContextObject = {
2660 isTransitioning: false;
2661} | {
2662 isTransitioning: true;
2663 flushSync: boolean;
2664 currentLocation: Location;
2665 nextLocation: Location;
2666};
2667declare const ViewTransitionContext: React.Context<ViewTransitionContextObject>;
2668type FetchersContextObject = Map<string, any>;
2669declare const FetchersContext: React.Context<FetchersContextObject>;
2670declare const AwaitContext: React.Context<TrackedPromise | null>;
2671declare const AwaitContextProvider: (props: React.ComponentProps<typeof AwaitContext.Provider>) => React.FunctionComponentElement<React.ProviderProps<TrackedPromise | null>>;
2672interface NavigateOptions {
2673 /** Replace the current entry in the history stack instead of pushing a new one */
2674 replace?: boolean;
2675 /** Adds persistent client side routing state to the next location */
2676 state?: any;
2677 /** If you are using {@link https://api.reactrouter.com/v7/functions/react_router.ScrollRestoration.html <ScrollRestoration>}, prevent the scroll position from being reset to the top of the window when navigating */
2678 preventScrollReset?: boolean;
2679 /** Defines the relative path behavior for the link. "route" will use the route hierarchy so ".." will remove all URL segments of the current route pattern while "path" will use the URL path so ".." will remove one URL segment. */
2680 relative?: RelativeRoutingType;
2681 /** Wraps the initial state update for this navigation in a {@link https://react.dev/reference/react-dom/flushSync ReactDOM.flushSync} call instead of the default {@link https://react.dev/reference/react/startTransition React.startTransition} */
2682 flushSync?: boolean;
2683 /** Enables a {@link https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API View Transition} for this navigation by wrapping the final state update in `document.startViewTransition()`. If you need to apply specific styles for this view transition, you will also need to leverage the {@link https://api.reactrouter.com/v7/functions/react_router.useViewTransitionState.html useViewTransitionState()} hook. */
2684 viewTransition?: boolean;
2685}
2686/**
2687 * A Navigator is a "location changer"; it's how you get to different locations.
2688 *
2689 * Every history instance conforms to the Navigator interface, but the
2690 * distinction is useful primarily when it comes to the low-level `<Router>` API
2691 * where both the location and a navigator must be provided separately in order
2692 * to avoid "tearing" that may occur in a suspense-enabled app if the action
2693 * and/or location were to be read directly from the history instance.
2694 */
2695interface Navigator {
2696 createHref: History["createHref"];
2697 encodeLocation?: History["encodeLocation"];
2698 go: History["go"];
2699 push(to: To, state?: any, opts?: NavigateOptions): void;
2700 replace(to: To, state?: any, opts?: NavigateOptions): void;
2701}
2702interface NavigationContextObject {
2703 basename: string;
2704 navigator: Navigator;
2705 static: boolean;
2706 unstable_useTransitions: boolean;
2707 future: {};
2708}
2709declare const NavigationContext: React.Context<NavigationContextObject>;
2710interface LocationContextObject {
2711 location: Location;
2712 navigationType: Action;
2713}
2714declare const LocationContext: React.Context<LocationContextObject>;
2715interface RouteContextObject {
2716 outlet: React.ReactElement | null;
2717 matches: RouteMatch[];
2718 isDataRoute: boolean;
2719}
2720declare const RouteContext: React.Context<RouteContextObject>;
2721
2722type Primitive = null | undefined | string | number | boolean | symbol | bigint;
2723type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
2724interface HtmlLinkProps {
2725 /**
2726 * Address of the hyperlink
2727 */
2728 href?: string;
2729 /**
2730 * How the element handles crossorigin requests
2731 */
2732 crossOrigin?: "anonymous" | "use-credentials";
2733 /**
2734 * Relationship between the document containing the hyperlink and the destination resource
2735 */
2736 rel: LiteralUnion<"alternate" | "dns-prefetch" | "icon" | "manifest" | "modulepreload" | "next" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "search" | "stylesheet", string>;
2737 /**
2738 * Applicable media: "screen", "print", "(max-width: 764px)"
2739 */
2740 media?: string;
2741 /**
2742 * Integrity metadata used in Subresource Integrity checks
2743 */
2744 integrity?: string;
2745 /**
2746 * Language of the linked resource
2747 */
2748 hrefLang?: string;
2749 /**
2750 * Hint for the type of the referenced resource
2751 */
2752 type?: string;
2753 /**
2754 * Referrer policy for fetches initiated by the element
2755 */
2756 referrerPolicy?: "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
2757 /**
2758 * Sizes of the icons (for rel="icon")
2759 */
2760 sizes?: string;
2761 /**
2762 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
2763 */
2764 as?: LiteralUnion<"audio" | "audioworklet" | "document" | "embed" | "fetch" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt", string>;
2765 /**
2766 * Color to use when customizing a site's icon (for rel="mask-icon")
2767 */
2768 color?: string;
2769 /**
2770 * Whether the link is disabled
2771 */
2772 disabled?: boolean;
2773 /**
2774 * The title attribute has special semantics on this element: Title of the link; CSS style sheet set name.
2775 */
2776 title?: string;
2777 /**
2778 * Images to use in different situations, e.g., high-resolution displays,
2779 * small monitors, etc. (for rel="preload")
2780 */
2781 imageSrcSet?: string;
2782 /**
2783 * Image sizes for different page layouts (for rel="preload")
2784 */
2785 imageSizes?: string;
2786}
2787interface HtmlLinkPreloadImage extends HtmlLinkProps {
2788 /**
2789 * Relationship between the document containing the hyperlink and the destination resource
2790 */
2791 rel: "preload";
2792 /**
2793 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
2794 */
2795 as: "image";
2796 /**
2797 * Address of the hyperlink
2798 */
2799 href?: string;
2800 /**
2801 * Images to use in different situations, e.g., high-resolution displays,
2802 * small monitors, etc. (for rel="preload")
2803 */
2804 imageSrcSet: string;
2805 /**
2806 * Image sizes for different page layouts (for rel="preload")
2807 */
2808 imageSizes?: string;
2809}
2810/**
2811 * Represents a `<link>` element.
2812 *
2813 * WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
2814 */
2815type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "imageSizes">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "href"> & {
2816 imageSizes?: never;
2817});
2818interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
2819 /**
2820 * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
2821 * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
2822 * element
2823 */
2824 nonce?: string | undefined;
2825 /**
2826 * The absolute path of the page to prefetch, e.g. `/absolute/path`.
2827 */
2828 page: string;
2829}
2830type LinkDescriptor = HtmlLinkDescriptor | PageLinkDescriptor;
2831
2832type Serializable = undefined | null | boolean | string | symbol | number | Array<Serializable> | {
2833 [key: PropertyKey]: Serializable;
2834} | bigint | Date | URL | RegExp | Error | Map<Serializable, Serializable> | Set<Serializable> | Promise<Serializable>;
2835
2836type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
2837type IsAny<T> = 0 extends 1 & T ? true : false;
2838type Func = (...args: any[]) => unknown;
2839type Pretty<T> = {
2840 [K in keyof T]: T[K];
2841} & {};
2842type Normalize<T> = _Normalize<UnionKeys<T>, T>;
2843type _Normalize<Key extends keyof any, T> = T extends infer U ? Pretty<{
2844 [K in Key as K extends keyof U ? undefined extends U[K] ? never : K : never]: K extends keyof U ? U[K] : never;
2845} & {
2846 [K in Key as K extends keyof U ? undefined extends U[K] ? K : never : never]?: K extends keyof U ? U[K] : never;
2847} & {
2848 [K in Key as K extends keyof U ? never : K]?: undefined;
2849}> : never;
2850type UnionKeys<T> = T extends any ? keyof T : never;
2851
2852type RouteModule$1 = {
2853 meta?: Func;
2854 links?: Func;
2855 headers?: Func;
2856 loader?: Func;
2857 clientLoader?: Func;
2858 action?: Func;
2859 clientAction?: Func;
2860 HydrateFallback?: Func;
2861 default?: Func;
2862 ErrorBoundary?: Func;
2863 [key: string]: unknown;
2864};
2865
2866/**
2867 * A brand that can be applied to a type to indicate that it will serialize
2868 * to a specific type when transported to the client from a loader.
2869 * Only use this if you have additional serialization/deserialization logic
2870 * in your application.
2871 */
2872type unstable_SerializesTo<T> = {
2873 unstable__ReactRouter_SerializesTo: [T];
2874};
2875
2876type Serialize<T> = T extends unstable_SerializesTo<infer To> ? To : T extends Serializable ? T : T extends (...args: any[]) => unknown ? undefined : T extends Promise<infer U> ? Promise<Serialize<U>> : T extends Map<infer K, infer V> ? Map<Serialize<K>, Serialize<V>> : T extends ReadonlyMap<infer K, infer V> ? ReadonlyMap<Serialize<K>, Serialize<V>> : T extends Set<infer U> ? Set<Serialize<U>> : T extends ReadonlySet<infer U> ? ReadonlySet<Serialize<U>> : T extends [] ? [] : T extends readonly [infer F, ...infer R] ? [Serialize<F>, ...Serialize<R>] : T extends Array<infer U> ? Array<Serialize<U>> : T extends readonly unknown[] ? readonly Serialize<T[number]>[] : T extends Record<any, any> ? {
2877 [K in keyof T]: Serialize<T[K]>;
2878} : undefined;
2879type VoidToUndefined<T> = Equal<T, void> extends true ? undefined : T;
2880type DataFrom<T> = IsAny<T> extends true ? undefined : T extends Func ? VoidToUndefined<Awaited<ReturnType<T>>> : undefined;
2881type ClientData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? U : T;
2882type ServerData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? Serialize<U> : Serialize<T>;
2883type ServerDataFrom<T> = ServerData<DataFrom<T>>;
2884type ClientDataFrom<T> = ClientData<DataFrom<T>>;
2885type ClientDataFunctionArgs<Params> = {
2886 /**
2887 * A {@link https://developer.mozilla.org/en-US/docs/Web/API/Request Fetch Request instance} which you can use to read the URL, the method, the "content-type" header, and the request body from the request.
2888 *
2889 * @note Because client data functions are called before a network request is made, the Request object does not include the headers which the browser automatically adds. React Router infers the "content-type" header from the enc-type of the form that performed the submission.
2890 **/
2891 request: Request;
2892 /**
2893 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
2894 * @example
2895 * // app/routes.ts
2896 * route("teams/:teamId", "./team.tsx"),
2897 *
2898 * // app/team.tsx
2899 * export function clientLoader({
2900 * params,
2901 * }: Route.ClientLoaderArgs) {
2902 * params.teamId;
2903 * // ^ string
2904 * }
2905 **/
2906 params: Params;
2907 /**
2908 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
2909 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
2910 */
2911 unstable_pattern: string;
2912 /**
2913 * When `future.v8_middleware` is not enabled, this is undefined.
2914 *
2915 * When `future.v8_middleware` is enabled, this is an instance of
2916 * `RouterContextProvider` and can be used to access context values
2917 * from your route middlewares. You may pass in initial context values in your
2918 * `<HydratedRouter getContext>` prop
2919 */
2920 context: Readonly<RouterContextProvider>;
2921};
2922type ServerDataFunctionArgs<Params> = {
2923 /** A {@link https://developer.mozilla.org/en-US/docs/Web/API/Request Fetch Request instance} which you can use to read the url, method, headers (such as cookies), and request body from the request. */
2924 request: Request;
2925 /**
2926 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
2927 * @example
2928 * // app/routes.ts
2929 * route("teams/:teamId", "./team.tsx"),
2930 *
2931 * // app/team.tsx
2932 * export function loader({
2933 * params,
2934 * }: Route.LoaderArgs) {
2935 * params.teamId;
2936 * // ^ string
2937 * }
2938 **/
2939 params: Params;
2940 /**
2941 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
2942 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
2943 */
2944 unstable_pattern: string;
2945 /**
2946 * Without `future.v8_middleware` enabled, this is the context passed in
2947 * to your server adapter's `getLoadContext` function. It's a way to bridge the
2948 * gap between the adapter's request/response API with your React Router app.
2949 * It is only applicable if you are using a custom server adapter.
2950 *
2951 * With `future.v8_middleware` enabled, this is an instance of
2952 * `RouterContextProvider` and can be used for type-safe access to
2953 * context value set in your route middlewares. If you are using a custom
2954 * server adapter, you may provide an initial set of context values from your
2955 * `getLoadContext` function.
2956 */
2957 context: MiddlewareEnabled extends true ? Readonly<RouterContextProvider> : AppLoadContext;
2958};
2959type SerializeFrom<T> = T extends (...args: infer Args) => unknown ? Args extends [
2960 ClientLoaderFunctionArgs | ClientActionFunctionArgs | ClientDataFunctionArgs<unknown>
2961] ? ClientDataFrom<T> : ServerDataFrom<T> : T;
2962type IsDefined<T> = Equal<T, undefined> extends true ? false : true;
2963type IsHydrate<ClientLoader> = ClientLoader extends {
2964 hydrate: true;
2965} ? true : ClientLoader extends {
2966 hydrate: false;
2967} ? false : false;
2968type GetLoaderData<T extends RouteModule$1> = _DataLoaderData<ServerDataFrom<T["loader"]>, ClientDataFrom<T["clientLoader"]>, IsHydrate<T["clientLoader"]>, T extends {
2969 HydrateFallback: Func;
2970} ? true : false>;
2971type _DataLoaderData<ServerLoaderData, ClientLoaderData, ClientLoaderHydrate extends boolean, HasHydrateFallback> = [
2972 HasHydrateFallback,
2973 ClientLoaderHydrate
2974] extends [true, true] ? IsDefined<ClientLoaderData> extends true ? ClientLoaderData : undefined : [
2975 IsDefined<ClientLoaderData>,
2976 IsDefined<ServerLoaderData>
2977] extends [true, true] ? ServerLoaderData | ClientLoaderData : IsDefined<ClientLoaderData> extends true ? ClientLoaderData : IsDefined<ServerLoaderData> extends true ? ServerLoaderData : undefined;
2978type GetActionData<T extends RouteModule$1> = _DataActionData<ServerDataFrom<T["action"]>, ClientDataFrom<T["clientAction"]>>;
2979type _DataActionData<ServerActionData, ClientActionData> = Awaited<[
2980 IsDefined<ServerActionData>,
2981 IsDefined<ClientActionData>
2982] extends [true, true] ? ServerActionData | ClientActionData : IsDefined<ClientActionData> extends true ? ClientActionData : IsDefined<ServerActionData> extends true ? ServerActionData : undefined>;
2983
2984interface RouteModules {
2985 [routeId: string]: RouteModule | undefined;
2986}
2987/**
2988 * The shape of a route module shipped to the client
2989 */
2990interface RouteModule {
2991 clientAction?: ClientActionFunction;
2992 clientLoader?: ClientLoaderFunction;
2993 clientMiddleware?: MiddlewareFunction<Record<string, DataStrategyResult>>[];
2994 ErrorBoundary?: ErrorBoundaryComponent;
2995 HydrateFallback?: HydrateFallbackComponent;
2996 Layout?: LayoutComponent;
2997 default: RouteComponent;
2998 handle?: RouteHandle;
2999 links?: LinksFunction;
3000 meta?: MetaFunction;
3001 shouldRevalidate?: ShouldRevalidateFunction;
3002}
3003/**
3004 * The shape of a route module on the server
3005 */
3006interface ServerRouteModule extends RouteModule {
3007 action?: ActionFunction;
3008 headers?: HeadersFunction | {
3009 [name: string]: string;
3010 };
3011 loader?: LoaderFunction;
3012 middleware?: MiddlewareFunction<Response>[];
3013}
3014/**
3015 * A function that handles data mutations for a route on the client
3016 */
3017type ClientActionFunction = (args: ClientActionFunctionArgs) => ReturnType<ActionFunction>;
3018/**
3019 * Arguments passed to a route `clientAction` function
3020 */
3021type ClientActionFunctionArgs = ActionFunctionArgs & {
3022 serverAction: <T = unknown>() => Promise<SerializeFrom<T>>;
3023};
3024/**
3025 * A function that loads data for a route on the client
3026 */
3027type ClientLoaderFunction = ((args: ClientLoaderFunctionArgs) => ReturnType<LoaderFunction>) & {
3028 hydrate?: boolean;
3029};
3030/**
3031 * Arguments passed to a route `clientLoader` function
3032 */
3033type ClientLoaderFunctionArgs = LoaderFunctionArgs & {
3034 serverLoader: <T = unknown>() => Promise<SerializeFrom<T>>;
3035};
3036/**
3037 * ErrorBoundary to display for this route
3038 */
3039type ErrorBoundaryComponent = ComponentType;
3040type HeadersArgs = {
3041 loaderHeaders: Headers;
3042 parentHeaders: Headers;
3043 actionHeaders: Headers;
3044 errorHeaders: Headers | undefined;
3045};
3046/**
3047 * A function that returns HTTP headers to be used for a route. These headers
3048 * will be merged with (and take precedence over) headers from parent routes.
3049 */
3050interface HeadersFunction {
3051 (args: HeadersArgs): Headers | HeadersInit;
3052}
3053/**
3054 * `<Route HydrateFallback>` component to render on initial loads
3055 * when client loaders are present
3056 */
3057type HydrateFallbackComponent = ComponentType;
3058/**
3059 * Optional, root-only `<Route Layout>` component to wrap the root content in.
3060 * Useful for defining the <html>/<head>/<body> document shell shared by the
3061 * Component, HydrateFallback, and ErrorBoundary
3062 */
3063type LayoutComponent = ComponentType<{
3064 children: ReactElement<unknown, ErrorBoundaryComponent | HydrateFallbackComponent | RouteComponent>;
3065}>;
3066/**
3067 * A function that defines `<link>` tags to be inserted into the `<head>` of
3068 * the document on route transitions.
3069 *
3070 * @see https://reactrouter.com/start/framework/route-module#meta
3071 */
3072interface LinksFunction {
3073 (): LinkDescriptor[];
3074}
3075interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
3076 id: RouteId;
3077 pathname: DataRouteMatch["pathname"];
3078 /** @deprecated Use `MetaMatch.loaderData` instead */
3079 data: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
3080 loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
3081 handle?: RouteHandle;
3082 params: DataRouteMatch["params"];
3083 meta: MetaDescriptor[];
3084 error?: unknown;
3085}
3086type MetaMatches<MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> = Array<{
3087 [K in keyof MatchLoaders]: MetaMatch<Exclude<K, number | symbol>, MatchLoaders[K]>;
3088}[keyof MatchLoaders]>;
3089interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
3090 /** @deprecated Use `MetaArgs.loaderData` instead */
3091 data: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
3092 loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
3093 params: Params;
3094 location: Location;
3095 matches: MetaMatches<MatchLoaders>;
3096 error?: unknown;
3097}
3098/**
3099 * A function that returns an array of data objects to use for rendering
3100 * metadata HTML tags in a route. These tags are not rendered on descendant
3101 * routes in the route hierarchy. In other words, they will only be rendered on
3102 * the route in which they are exported.
3103 *
3104 * @param Loader - The type of the current route's loader function
3105 * @param MatchLoaders - Mapping from a parent route's filepath to its loader
3106 * function type
3107 *
3108 * Note that parent route filepaths are relative to the `app/` directory.
3109 *
3110 * For example, if this meta function is for `/sales/customers/$customerId`:
3111 *
3112 * ```ts
3113 * // app/root.tsx
3114 * const loader = () => ({ hello: "world" })
3115 * export type Loader = typeof loader
3116 *
3117 * // app/routes/sales.tsx
3118 * const loader = () => ({ salesCount: 1074 })
3119 * export type Loader = typeof loader
3120 *
3121 * // app/routes/sales/customers.tsx
3122 * const loader = () => ({ customerCount: 74 })
3123 * export type Loader = typeof loader
3124 *
3125 * // app/routes/sales/customers/$customersId.tsx
3126 * import type { Loader as RootLoader } from "../../../root"
3127 * import type { Loader as SalesLoader } from "../../sales"
3128 * import type { Loader as CustomersLoader } from "../../sales/customers"
3129 *
3130 * const loader = () => ({ name: "Customer name" })
3131 *
3132 * const meta: MetaFunction<typeof loader, {
3133 * "root": RootLoader,
3134 * "routes/sales": SalesLoader,
3135 * "routes/sales/customers": CustomersLoader,
3136 * }> = ({ data, matches }) => {
3137 * const { name } = data
3138 * // ^? string
3139 * const { customerCount } = matches.find((match) => match.id === "routes/sales/customers").data
3140 * // ^? number
3141 * const { salesCount } = matches.find((match) => match.id === "routes/sales").data
3142 * // ^? number
3143 * const { hello } = matches.find((match) => match.id === "root").data
3144 * // ^? "world"
3145 * }
3146 * ```
3147 */
3148interface MetaFunction<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
3149 (args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;
3150}
3151type MetaDescriptor = {
3152 charSet: "utf-8";
3153} | {
3154 title: string;
3155} | {
3156 name: string;
3157 content: string;
3158} | {
3159 property: string;
3160 content: string;
3161} | {
3162 httpEquiv: string;
3163 content: string;
3164} | {
3165 "script:ld+json": LdJsonObject;
3166} | {
3167 tagName: "meta" | "link";
3168 [name: string]: string;
3169} | {
3170 [name: string]: unknown;
3171};
3172type LdJsonObject = {
3173 [Key in string]: LdJsonValue;
3174} & {
3175 [Key in string]?: LdJsonValue | undefined;
3176};
3177type LdJsonArray = LdJsonValue[] | readonly LdJsonValue[];
3178type LdJsonPrimitive = string | number | boolean | null;
3179type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
3180/**
3181 * A React component that is rendered for a route.
3182 */
3183type RouteComponent = ComponentType<{}>;
3184/**
3185 * An arbitrary object that is associated with a route.
3186 *
3187 * @see https://reactrouter.com/how-to/using-handle
3188 */
3189type RouteHandle = unknown;
3190
3191type unstable_ServerInstrumentation = {
3192 handler?: unstable_InstrumentRequestHandlerFunction;
3193 route?: unstable_InstrumentRouteFunction;
3194};
3195type unstable_ClientInstrumentation = {
3196 router?: unstable_InstrumentRouterFunction;
3197 route?: unstable_InstrumentRouteFunction;
3198};
3199type unstable_InstrumentRequestHandlerFunction = (handler: InstrumentableRequestHandler) => void;
3200type unstable_InstrumentRouterFunction = (router: InstrumentableRouter) => void;
3201type unstable_InstrumentRouteFunction = (route: InstrumentableRoute) => void;
3202type unstable_InstrumentationHandlerResult = {
3203 status: "success";
3204 error: undefined;
3205} | {
3206 status: "error";
3207 error: Error;
3208};
3209type InstrumentFunction<T> = (handler: () => Promise<unstable_InstrumentationHandlerResult>, info: T) => Promise<void>;
3210type ReadonlyRequest = {
3211 method: string;
3212 url: string;
3213 headers: Pick<Headers, "get">;
3214};
3215type ReadonlyContext = MiddlewareEnabled extends true ? Pick<RouterContextProvider, "get"> : Readonly<AppLoadContext>;
3216type InstrumentableRoute = {
3217 id: string;
3218 index: boolean | undefined;
3219 path: string | undefined;
3220 instrument(instrumentations: RouteInstrumentations): void;
3221};
3222type RouteInstrumentations = {
3223 lazy?: InstrumentFunction<RouteLazyInstrumentationInfo>;
3224 "lazy.loader"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
3225 "lazy.action"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
3226 "lazy.middleware"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
3227 middleware?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
3228 loader?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
3229 action?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
3230};
3231type RouteLazyInstrumentationInfo = undefined;
3232type RouteHandlerInstrumentationInfo = Readonly<{
3233 request: ReadonlyRequest;
3234 params: LoaderFunctionArgs["params"];
3235 unstable_pattern: string;
3236 context: ReadonlyContext;
3237}>;
3238type InstrumentableRouter = {
3239 instrument(instrumentations: RouterInstrumentations): void;
3240};
3241type RouterInstrumentations = {
3242 navigate?: InstrumentFunction<RouterNavigationInstrumentationInfo>;
3243 fetch?: InstrumentFunction<RouterFetchInstrumentationInfo>;
3244};
3245type RouterNavigationInstrumentationInfo = Readonly<{
3246 to: string | number;
3247 currentUrl: string;
3248 formMethod?: HTMLFormMethod;
3249 formEncType?: FormEncType;
3250 formData?: FormData;
3251 body?: any;
3252}>;
3253type RouterFetchInstrumentationInfo = Readonly<{
3254 href: string;
3255 currentUrl: string;
3256 fetcherKey: string;
3257 formMethod?: HTMLFormMethod;
3258 formEncType?: FormEncType;
3259 formData?: FormData;
3260 body?: any;
3261}>;
3262type InstrumentableRequestHandler = {
3263 instrument(instrumentations: RequestHandlerInstrumentations): void;
3264};
3265type RequestHandlerInstrumentations = {
3266 request?: InstrumentFunction<RequestHandlerInstrumentationInfo>;
3267};
3268type RequestHandlerInstrumentationInfo = Readonly<{
3269 request: ReadonlyRequest;
3270 context: ReadonlyContext | undefined;
3271}>;
3272
3273export { type RouterState as $, type ActionFunction as A, type BlockerFunction as B, type ClientActionFunction as C, type DataStrategyResult as D, type PathMatch as E, type Func as F, type GetLoaderData as G, type HeadersFunction as H, type Navigation as I, Action as J, type RouteObject as K, type Location as L, type MetaFunction as M, type Normalize as N, type InitialEntry as O, type Params as P, type HydrationState as Q, type RouteModule$1 as R, type ShouldRevalidateFunction as S, type To as T, type UIMatch as U, type IndexRouteObject as V, type RouteComponentType as W, type HydrateFallbackType as X, type ErrorBoundaryType as Y, type NonIndexRouteObject as Z, type Equal as _, type ClientLoaderFunction as a, type RouterProviderProps as a$, type PatchRoutesOnNavigationFunction as a0, type DataRouteObject as a1, type StaticHandler as a2, type GetScrollPositionFunction as a3, type GetScrollRestorationKeyFunction as a4, type StaticHandlerContext as a5, type Fetcher as a6, type NavigationStates as a7, type RouterSubscriber as a8, type RouterNavigateOptions as a9, IDLE_FETCHER as aA, IDLE_BLOCKER as aB, data as aC, generatePath as aD, isRouteErrorResponse as aE, matchPath as aF, matchRoutes as aG, redirect as aH, redirectDocument as aI, replace as aJ, resolvePath as aK, type DataRouteMatch as aL, type Navigator as aM, type PatchRoutesOnNavigationFunctionArgs as aN, type RouteMatch as aO, AwaitContextProvider as aP, type AwaitProps as aQ, type IndexRouteProps as aR, type unstable_ClientOnErrorFunction as aS, type LayoutRouteProps as aT, type MemoryRouterOpts as aU, type MemoryRouterProps as aV, type NavigateProps as aW, type OutletProps as aX, type PathRouteProps as aY, type RouteProps as aZ, type RouterProps as a_, type RouterFetchOptions as aa, type RevalidationState as ab, type ActionFunctionArgs as ac, type DataStrategyFunctionArgs as ad, type DataStrategyMatch as ae, DataWithResponseInit as af, type ErrorResponse as ag, type FormEncType as ah, type FormMethod as ai, type HTMLFormMethod as aj, type LazyRouteFunction as ak, type LoaderFunctionArgs as al, type MiddlewareFunction as am, type PathParam as an, type RedirectFunction as ao, type RouterContext as ap, type ShouldRevalidateFunctionArgs as aq, createContext as ar, createPath as as, parsePath as at, type unstable_ServerInstrumentation as au, type unstable_InstrumentRequestHandlerFunction as av, type unstable_InstrumentRouterFunction as aw, type unstable_InstrumentRouteFunction as ax, type unstable_InstrumentationHandlerResult as ay, IDLE_NAVIGATION as az, type LinksFunction as b, type RoutesProps as b0, Await as b1, MemoryRouter as b2, Navigate as b3, Outlet as b4, Route as b5, Router as b6, RouterProvider as b7, Routes as b8, createMemoryRouter as b9, WithHydrateFallbackProps as bA, withHydrateFallbackProps as bB, WithErrorBoundaryProps as bC, withErrorBoundaryProps as bD, type RouteManifest as bE, type ServerRouteModule as bF, type History as bG, type FutureConfig as bH, type CreateStaticHandlerOptions as bI, createRoutesFromChildren as ba, createRoutesFromElements as bb, renderMatches as bc, type ClientActionFunctionArgs as bd, type ClientLoaderFunctionArgs as be, type HeadersArgs as bf, type MetaArgs as bg, type PageLinkDescriptor as bh, type HtmlLinkDescriptor as bi, type Future as bj, type unstable_SerializesTo as bk, createBrowserHistory as bl, invariant as bm, createRouter as bn, ErrorResponseImpl as bo, DataRouterContext as bp, DataRouterStateContext as bq, FetchersContext as br, LocationContext as bs, NavigationContext as bt, RouteContext as bu, ViewTransitionContext as bv, hydrationRouteProperties as bw, mapRouteProperties as bx, WithComponentProps as by, withComponentProps as bz, RouterContextProvider as c, type LoaderFunction as d, type RouterInit as e, type LinkDescriptor as f, type Pretty as g, type MetaDescriptor as h, type ServerDataFunctionArgs as i, type MiddlewareNextFunction as j, type ClientDataFunctionArgs as k, type ServerDataFrom as l, type GetActionData as m, type Router$1 as n, type RouteModules as o, type DataStrategyFunction as p, type MiddlewareEnabled as q, type AppLoadContext as r, type NavigateOptions as s, type Blocker as t, type unstable_ClientInstrumentation as u, type SerializeFrom as v, type RelativeRoutingType as w, type ParamParseKey as x, type Path as y, type PathPattern as z };