UNPKG

68 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 * The masked location displayed in the URL bar, which differs from the URL the
73 * router is operating on
74 */
75 unstable_mask: Path | undefined;
76}
77/**
78 * A change to the current location.
79 */
80interface Update {
81 /**
82 * The action that triggered the change.
83 */
84 action: Action;
85 /**
86 * The new location.
87 */
88 location: Location;
89 /**
90 * The delta between this location and the former location in the history stack
91 */
92 delta: number | null;
93}
94/**
95 * A function that receives notifications about location changes.
96 */
97interface Listener {
98 (update: Update): void;
99}
100/**
101 * Describes a location that is the destination of some navigation used in
102 * {@link Link}, {@link useNavigate}, etc.
103 */
104type To = string | Partial<Path>;
105/**
106 * A history is an interface to the navigation stack. The history serves as the
107 * source of truth for the current location, as well as provides a set of
108 * methods that may be used to change it.
109 *
110 * It is similar to the DOM's `window.history` object, but with a smaller, more
111 * focused API.
112 */
113interface History {
114 /**
115 * The last action that modified the current location. This will always be
116 * Action.Pop when a history instance is first created. This value is mutable.
117 */
118 readonly action: Action;
119 /**
120 * The current location. This value is mutable.
121 */
122 readonly location: Location;
123 /**
124 * Returns a valid href for the given `to` value that may be used as
125 * the value of an <a href> attribute.
126 *
127 * @param to - The destination URL
128 */
129 createHref(to: To): string;
130 /**
131 * Returns a URL for the given `to` value
132 *
133 * @param to - The destination URL
134 */
135 createURL(to: To): URL;
136 /**
137 * Encode a location the same way window.history would do (no-op for memory
138 * history) so we ensure our PUSH/REPLACE navigations for data routers
139 * behave the same as POP
140 *
141 * @param to Unencoded path
142 */
143 encodeLocation(to: To): Path;
144 /**
145 * Pushes a new location onto the history stack, increasing its length by one.
146 * If there were any entries in the stack after the current one, they are
147 * lost.
148 *
149 * @param to - The new URL
150 * @param state - Data to associate with the new location
151 */
152 push(to: To, state?: any): void;
153 /**
154 * Replaces the current location in the history stack with a new one. The
155 * location that was replaced will no longer be available.
156 *
157 * @param to - The new URL
158 * @param state - Data to associate with the new location
159 */
160 replace(to: To, state?: any): void;
161 /**
162 * Navigates `n` entries backward/forward in the history stack relative to the
163 * current index. For example, a "back" navigation would use go(-1).
164 *
165 * @param delta - The delta in the stack index
166 */
167 go(delta: number): void;
168 /**
169 * Sets up a listener that will be called whenever the current location
170 * changes.
171 *
172 * @param listener - A function that will be called when the location changes
173 * @returns unlisten - A function that may be used to stop listening
174 */
175 listen(listener: Listener): () => void;
176}
177/**
178 * A user-supplied object that describes a location. Used when providing
179 * entries to `createMemoryHistory` via its `initialEntries` option.
180 */
181type InitialEntry = string | Partial<Location>;
182type MemoryHistoryOptions = {
183 initialEntries?: InitialEntry[];
184 initialIndex?: number;
185 v5Compat?: boolean;
186};
187/**
188 * A memory history stores locations in memory. This is useful in stateful
189 * environments where there is no web browser, such as node tests or React
190 * Native.
191 */
192interface MemoryHistory extends History {
193 /**
194 * The current index in the history stack.
195 */
196 readonly index: number;
197}
198/**
199 * Memory history stores the current location in memory. It is designed for use
200 * in stateful non-browser environments like tests and React Native.
201 */
202declare function createMemoryHistory(options?: MemoryHistoryOptions): MemoryHistory;
203/**
204 * A browser history stores the current location in regular URLs in a web
205 * browser environment. This is the standard for most web apps and provides the
206 * cleanest URLs the browser's address bar.
207 *
208 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
209 */
210interface BrowserHistory extends UrlHistory {
211}
212type BrowserHistoryOptions = UrlHistoryOptions;
213/**
214 * Browser history stores the location in regular URLs. This is the standard for
215 * most web apps, but it requires some configuration on the server to ensure you
216 * serve the same app at multiple URLs.
217 *
218 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
219 */
220declare function createBrowserHistory(options?: BrowserHistoryOptions): BrowserHistory;
221/**
222 * A hash history stores the current location in the fragment identifier portion
223 * of the URL in a web browser environment.
224 *
225 * This is ideal for apps that do not control the server for some reason
226 * (because the fragment identifier is never sent to the server), including some
227 * shared hosting environments that do not provide fine-grained controls over
228 * which pages are served at which URLs.
229 *
230 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory
231 */
232interface HashHistory extends UrlHistory {
233}
234type HashHistoryOptions = UrlHistoryOptions;
235/**
236 * Hash history stores the location in window.location.hash. This makes it ideal
237 * for situations where you don't want to send the location to the server for
238 * some reason, either because you do cannot configure it or the URL space is
239 * reserved for something else.
240 *
241 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
242 */
243declare function createHashHistory(options?: HashHistoryOptions): HashHistory;
244/**
245 * @private
246 */
247declare function invariant(value: boolean, message?: string): asserts value;
248declare function invariant<T>(value: T | null | undefined, message?: string): asserts value is T;
249/**
250 * Creates a string URL path from the given pathname, search, and hash components.
251 *
252 * @category Utils
253 */
254declare function createPath({ pathname, search, hash, }: Partial<Path>): string;
255/**
256 * Parses a string URL path into its separate pathname, search, and hash components.
257 *
258 * @category Utils
259 */
260declare function parsePath(path: string): Partial<Path>;
261interface UrlHistory extends History {
262}
263type UrlHistoryOptions = {
264 window?: Window;
265 v5Compat?: boolean;
266};
267
268type MaybePromise<T> = T | Promise<T>;
269/**
270 * Map of routeId -> data returned from a loader/action/error
271 */
272interface RouteData {
273 [routeId: string]: any;
274}
275type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete";
276type UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;
277/**
278 * Users can specify either lowercase or uppercase form methods on `<Form>`,
279 * useSubmit(), `<fetcher.Form>`, etc.
280 */
281type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;
282/**
283 * Active navigation/fetcher form methods are exposed in uppercase on the
284 * RouterState. This is to align with the normalization done via fetch().
285 */
286type FormMethod = UpperCaseFormMethod;
287type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data" | "application/json" | "text/plain";
288type JsonObject = {
289 [Key in string]: JsonValue;
290} & {
291 [Key in string]?: JsonValue | undefined;
292};
293type JsonArray = JsonValue[] | readonly JsonValue[];
294type JsonPrimitive = string | number | boolean | null;
295type JsonValue = JsonPrimitive | JsonObject | JsonArray;
296/**
297 * @private
298 * Internal interface to pass around for action submissions, not intended for
299 * external consumption
300 */
301type Submission = {
302 formMethod: FormMethod;
303 formAction: string;
304 formEncType: FormEncType;
305 formData: FormData;
306 json: undefined;
307 text: undefined;
308} | {
309 formMethod: FormMethod;
310 formAction: string;
311 formEncType: FormEncType;
312 formData: undefined;
313 json: JsonValue;
314 text: undefined;
315} | {
316 formMethod: FormMethod;
317 formAction: string;
318 formEncType: FormEncType;
319 formData: undefined;
320 json: undefined;
321 text: string;
322};
323/**
324 * A context instance used as the key for the `get`/`set` methods of a
325 * {@link RouterContextProvider}. Accepts an optional default
326 * value to be returned if no value has been set.
327 */
328interface RouterContext<T = unknown> {
329 defaultValue?: T;
330}
331/**
332 * Creates a type-safe {@link RouterContext} object that can be used to
333 * store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
334 * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
335 * Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
336 * but specifically designed for React Router's request/response lifecycle.
337 *
338 * If a `defaultValue` is provided, it will be returned from `context.get()`
339 * when no value has been set for the context. Otherwise, reading this context
340 * when no value has been set will throw an error.
341 *
342 * ```tsx filename=app/context.ts
343 * import { createContext } from "react-router";
344 *
345 * // Create a context for user data
346 * export const userContext =
347 * createContext<User | null>(null);
348 * ```
349 *
350 * ```tsx filename=app/middleware/auth.ts
351 * import { getUserFromSession } from "~/auth.server";
352 * import { userContext } from "~/context";
353 *
354 * export const authMiddleware = async ({
355 * context,
356 * request,
357 * }) => {
358 * const user = await getUserFromSession(request);
359 * context.set(userContext, user);
360 * };
361 * ```
362 *
363 * ```tsx filename=app/routes/profile.tsx
364 * import { userContext } from "~/context";
365 *
366 * export async function loader({
367 * context,
368 * }: Route.LoaderArgs) {
369 * const user = context.get(userContext);
370 *
371 * if (!user) {
372 * throw new Response("Unauthorized", { status: 401 });
373 * }
374 *
375 * return { user };
376 * }
377 * ```
378 *
379 * @public
380 * @category Utils
381 * @mode framework
382 * @mode data
383 * @param defaultValue An optional default value for the context. This value
384 * will be returned if no value has been set for this context.
385 * @returns A {@link RouterContext} object that can be used with
386 * `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
387 * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
388 */
389declare function createContext<T>(defaultValue?: T): RouterContext<T>;
390/**
391 * Provides methods for writing/reading values in application context in a
392 * type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
393 *
394 * @example
395 * import {
396 * createContext,
397 * RouterContextProvider
398 * } from "react-router";
399 *
400 * const userContext = createContext<User | null>(null);
401 * const contextProvider = new RouterContextProvider();
402 * contextProvider.set(userContext, getUser());
403 * // ^ Type-safe
404 * const user = contextProvider.get(userContext);
405 * // ^ User
406 *
407 * @public
408 * @category Utils
409 * @mode framework
410 * @mode data
411 */
412declare class RouterContextProvider {
413 #private;
414 /**
415 * Create a new `RouterContextProvider` instance
416 * @param init An optional initial context map to populate the provider with
417 */
418 constructor(init?: Map<RouterContext, unknown>);
419 /**
420 * Access a value from the context. If no value has been set for the context,
421 * it will return the context's `defaultValue` if provided, or throw an error
422 * if no `defaultValue` was set.
423 * @param context The context to get the value for
424 * @returns The value for the context, or the context's `defaultValue` if no
425 * value was set
426 */
427 get<T>(context: RouterContext<T>): T;
428 /**
429 * Set a value for the context. If the context already has a value set, this
430 * will overwrite it.
431 *
432 * @param context The context to set the value for
433 * @param value The value to set for the context
434 * @returns {void}
435 */
436 set<C extends RouterContext>(context: C, value: C extends RouterContext<infer T> ? T : never): void;
437}
438type DefaultContext = MiddlewareEnabled extends true ? Readonly<RouterContextProvider> : any;
439/**
440 * @private
441 * Arguments passed to route loader/action functions. Same for now but we keep
442 * this as a private implementation detail in case they diverge in the future.
443 */
444interface DataFunctionArgs<Context> {
445 /** 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. */
446 request: Request;
447 /**
448 * A URL instance representing the application location being navigated to or fetched.
449 * Without `future.unstable_passThroughRequests` enabled, this matches `request.url`.
450 * With `future.unstable_passThroughRequests` enabled, this is a normalized
451 * URL with React-Router-specific implementation details removed (`.data`
452 * suffixes, `index`/`_routes` search params).
453 * The URL includes the origin from the request for convenience.
454 */
455 unstable_url: URL;
456 /**
457 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
458 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
459 */
460 unstable_pattern: string;
461 /**
462 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
463 * @example
464 * // app/routes.ts
465 * route("teams/:teamId", "./team.tsx"),
466 *
467 * // app/team.tsx
468 * export function loader({
469 * params,
470 * }: Route.LoaderArgs) {
471 * params.teamId;
472 * // ^ string
473 * }
474 */
475 params: Params;
476 /**
477 * This is the context passed in to your server adapter's getLoadContext() function.
478 * It's a way to bridge the gap between the adapter's request/response API with your React Router app.
479 * It is only applicable if you are using a custom server adapter.
480 */
481 context: Context;
482}
483/**
484 * Route middleware `next` function to call downstream handlers and then complete
485 * middlewares from the bottom-up
486 */
487interface MiddlewareNextFunction<Result = unknown> {
488 (): Promise<Result>;
489}
490/**
491 * Route middleware function signature. Receives the same "data" arguments as a
492 * `loader`/`action` (`request`, `params`, `context`) as the first parameter and
493 * a `next` function as the second parameter which will call downstream handlers
494 * and then complete middlewares from the bottom-up
495 */
496type MiddlewareFunction<Result = unknown> = (args: DataFunctionArgs<Readonly<RouterContextProvider>>, next: MiddlewareNextFunction<Result>) => MaybePromise<Result | void>;
497/**
498 * Arguments passed to loader functions
499 */
500interface LoaderFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
501}
502/**
503 * Arguments passed to action functions
504 */
505interface ActionFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
506}
507/**
508 * Loaders and actions can return anything
509 */
510type DataFunctionValue = unknown;
511type DataFunctionReturnValue = MaybePromise<DataFunctionValue>;
512/**
513 * Route loader function signature
514 */
515type LoaderFunction<Context = DefaultContext> = {
516 (args: LoaderFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
517} & {
518 hydrate?: boolean;
519};
520/**
521 * Route action function signature
522 */
523interface ActionFunction<Context = DefaultContext> {
524 (args: ActionFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
525}
526/**
527 * Arguments passed to shouldRevalidate function
528 */
529interface ShouldRevalidateFunctionArgs {
530 /** 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. */
531 currentUrl: URL;
532 /** 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. */
533 currentParams: DataRouteMatch["params"];
534 /** 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. */
535 nextUrl: URL;
536 /** 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. */
537 nextParams: DataRouteMatch["params"];
538 /** The method (probably `"GET"` or `"POST"`) used in the form submission that triggered the revalidation. */
539 formMethod?: Submission["formMethod"];
540 /** The form action (`<Form action="/somewhere">`) that triggered the revalidation. */
541 formAction?: Submission["formAction"];
542 /** The form encType (`<Form encType="application/x-www-form-urlencoded">) used in the form submission that triggered the revalidation*/
543 formEncType?: Submission["formEncType"];
544 /** The form submission data when the form's encType is `text/plain` */
545 text?: Submission["text"];
546 /** The form submission data when the form's encType is `application/x-www-form-urlencoded` or `multipart/form-data` */
547 formData?: Submission["formData"];
548 /** The form submission data when the form's encType is `application/json` */
549 json?: Submission["json"];
550 /** The status code of the action response */
551 actionStatus?: number;
552 /**
553 * 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.
554 *
555 * @example
556 * export async function action() {
557 * await saveSomeStuff();
558 * return { ok: true };
559 * }
560 *
561 * export function shouldRevalidate({
562 * actionResult,
563 * }) {
564 * if (actionResult?.ok) {
565 * return false;
566 * }
567 * return true;
568 * }
569 */
570 actionResult?: any;
571 /**
572 * 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:
573 *
574 * /projects/123/tasks/abc
575 * /projects/123/tasks/def
576 * React Router will only call the loader for tasks/def because the param for projects/123 didn't change.
577 *
578 * 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.
579 */
580 defaultShouldRevalidate: boolean;
581}
582/**
583 * Route shouldRevalidate function signature. This runs after any submission
584 * (navigation or fetcher), so we flatten the navigation/fetcher submission
585 * onto the arguments. It shouldn't matter whether it came from a navigation
586 * or a fetcher, what really matters is the URLs and the formData since loaders
587 * have to re-run based on the data models that were potentially mutated.
588 */
589interface ShouldRevalidateFunction {
590 (args: ShouldRevalidateFunctionArgs): boolean;
591}
592interface DataStrategyMatch extends RouteMatch<string, DataRouteObject> {
593 /**
594 * @private
595 */
596 _lazyPromises?: {
597 middleware: Promise<void> | undefined;
598 handler: Promise<void> | undefined;
599 route: Promise<void> | undefined;
600 };
601 /**
602 * @deprecated Deprecated in favor of `shouldCallHandler`
603 *
604 * A boolean value indicating whether this route handler should be called in
605 * this pass.
606 *
607 * The `matches` array always includes _all_ matched routes even when only
608 * _some_ route handlers need to be called so that things like middleware can
609 * be implemented.
610 *
611 * `shouldLoad` is usually only interesting if you are skipping the route
612 * handler entirely and implementing custom handler logic - since it lets you
613 * determine if that custom logic should run for this route or not.
614 *
615 * For example:
616 * - If you are on `/parent/child/a` and you navigate to `/parent/child/b` -
617 * you'll get an array of three matches (`[parent, child, b]`), but only `b`
618 * will have `shouldLoad=true` because the data for `parent` and `child` is
619 * already loaded
620 * - If you are on `/parent/child/a` and you submit to `a`'s [`action`](https://reactrouter.com/docs/start/data/route-object#action),
621 * then only `a` will have `shouldLoad=true` for the action execution of
622 * `dataStrategy`
623 * - After the [`action`](https://reactrouter.com/docs/start/data/route-object#action),
624 * `dataStrategy` will be called again for the [`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
625 * revalidation, and all matches will have `shouldLoad=true` (assuming no
626 * custom `shouldRevalidate` implementations)
627 */
628 shouldLoad: boolean;
629 /**
630 * Arguments passed to the `shouldRevalidate` function for this `loader` execution.
631 * Will be `null` if this is not a revalidating loader {@link DataStrategyMatch}.
632 */
633 shouldRevalidateArgs: ShouldRevalidateFunctionArgs | null;
634 /**
635 * Determine if this route's handler should be called during this `dataStrategy`
636 * execution. Calling it with no arguments will leverage the default revalidation
637 * behavior. You can pass your own `defaultShouldRevalidate` value if you wish
638 * to change the default revalidation behavior with your `dataStrategy`.
639 *
640 * @param defaultShouldRevalidate `defaultShouldRevalidate` override value (optional)
641 */
642 shouldCallHandler(defaultShouldRevalidate?: boolean): boolean;
643 /**
644 * An async function that will resolve any `route.lazy` implementations and
645 * execute the route's handler (if necessary), returning a {@link DataStrategyResult}
646 *
647 * - Calling `match.resolve` does not mean you're calling the
648 * [`action`](https://reactrouter.com/docs/start/data/route-object#action)/[`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
649 * (the "handler") - `resolve` will only call the `handler` internally if
650 * needed _and_ if you don't pass your own `handlerOverride` function parameter
651 * - It is safe to call `match.resolve` for all matches, even if they have
652 * `shouldLoad=false`, and it will no-op if no loading is required
653 * - You should generally always call `match.resolve()` for `shouldLoad:true`
654 * routes to ensure that any `route.lazy` implementations are processed
655 * - See the examples below for how to implement custom handler execution via
656 * `match.resolve`
657 */
658 resolve: (handlerOverride?: (handler: (ctx?: unknown) => DataFunctionReturnValue) => DataFunctionReturnValue) => Promise<DataStrategyResult>;
659}
660interface DataStrategyFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
661 /**
662 * Matches for this route extended with Data strategy APIs
663 */
664 matches: DataStrategyMatch[];
665 runClientMiddleware: (cb: DataStrategyFunction<Context>) => Promise<Record<string, DataStrategyResult>>;
666 /**
667 * The key of the fetcher we are calling `dataStrategy` for, otherwise `null`
668 * for navigational executions
669 */
670 fetcherKey: string | null;
671}
672/**
673 * Result from a loader or action called via dataStrategy
674 */
675interface DataStrategyResult {
676 type: "data" | "error";
677 result: unknown;
678}
679interface DataStrategyFunction<Context = DefaultContext> {
680 (args: DataStrategyFunctionArgs<Context>): Promise<Record<string, DataStrategyResult>>;
681}
682type PatchRoutesOnNavigationFunctionArgs = {
683 signal: AbortSignal;
684 path: string;
685 matches: RouteMatch[];
686 fetcherKey: string | undefined;
687 patch: (routeId: string | null, children: RouteObject[]) => void;
688};
689type PatchRoutesOnNavigationFunction = (opts: PatchRoutesOnNavigationFunctionArgs) => MaybePromise<void>;
690/**
691 * Function provided to set route-specific properties from route objects
692 */
693interface MapRoutePropertiesFunction {
694 (route: DataRouteObject): {
695 hasErrorBoundary: boolean;
696 } & Record<string, any>;
697}
698/**
699 * Keys we cannot change from within a lazy object. We spread all other keys
700 * onto the route. Either they're meaningful to the router, or they'll get
701 * ignored.
702 */
703type UnsupportedLazyRouteObjectKey = "lazy" | "caseSensitive" | "path" | "id" | "index" | "children";
704/**
705 * Keys we cannot change from within a lazy() function. We spread all other keys
706 * onto the route. Either they're meaningful to the router, or they'll get
707 * ignored.
708 */
709type UnsupportedLazyRouteFunctionKey = UnsupportedLazyRouteObjectKey | "middleware";
710/**
711 * lazy object to load route properties, which can add non-matching
712 * related properties to a route
713 */
714type LazyRouteObject<R extends RouteObject> = {
715 [K in keyof R as K extends UnsupportedLazyRouteObjectKey ? never : K]?: () => Promise<R[K] | null | undefined>;
716};
717/**
718 * lazy() function to load a route definition, which can add non-matching
719 * related properties to a route
720 */
721interface LazyRouteFunction<R extends RouteObject> {
722 (): Promise<Omit<R, UnsupportedLazyRouteFunctionKey> & Partial<Record<UnsupportedLazyRouteFunctionKey, never>>>;
723}
724type LazyRouteDefinition<R extends RouteObject> = LazyRouteObject<R> | LazyRouteFunction<R>;
725/**
726 * Base RouteObject with common props shared by all types of routes
727 * @internal
728 */
729type BaseRouteObject = {
730 /**
731 * Whether the path should be case-sensitive. Defaults to `false`.
732 */
733 caseSensitive?: boolean;
734 /**
735 * The path pattern to match. If unspecified or empty, then this becomes a
736 * layout route.
737 */
738 path?: string;
739 /**
740 * The unique identifier for this route (for use with {@link DataRouter}s)
741 */
742 id?: string;
743 /**
744 * The route middleware.
745 * See [`middleware`](../../start/data/route-object#middleware).
746 */
747 middleware?: MiddlewareFunction[];
748 /**
749 * The route loader.
750 * See [`loader`](../../start/data/route-object#loader).
751 */
752 loader?: LoaderFunction | boolean;
753 /**
754 * The route action.
755 * See [`action`](../../start/data/route-object#action).
756 */
757 action?: ActionFunction | boolean;
758 hasErrorBoundary?: boolean;
759 /**
760 * The route shouldRevalidate function.
761 * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
762 */
763 shouldRevalidate?: ShouldRevalidateFunction;
764 /**
765 * The route handle.
766 */
767 handle?: any;
768 /**
769 * A function that returns a promise that resolves to the route object.
770 * Used for code-splitting routes.
771 * See [`lazy`](../../start/data/route-object#lazy).
772 */
773 lazy?: LazyRouteDefinition<BaseRouteObject>;
774 /**
775 * The React Component to render when this route matches.
776 * Mutually exclusive with `element`.
777 */
778 Component?: React.ComponentType | null;
779 /**
780 * The React element to render when this Route matches.
781 * Mutually exclusive with `Component`.
782 */
783 element?: React.ReactNode | null;
784 /**
785 * The React Component to render at this route if an error occurs.
786 * Mutually exclusive with `errorElement`.
787 */
788 ErrorBoundary?: React.ComponentType | null;
789 /**
790 * The React element to render at this route if an error occurs.
791 * Mutually exclusive with `ErrorBoundary`.
792 */
793 errorElement?: React.ReactNode | null;
794 /**
795 * The React Component to render while this router is loading data.
796 * Mutually exclusive with `hydrateFallbackElement`.
797 */
798 HydrateFallback?: React.ComponentType | null;
799 /**
800 * The React element to render while this router is loading data.
801 * Mutually exclusive with `HydrateFallback`.
802 */
803 hydrateFallbackElement?: React.ReactNode | null;
804};
805/**
806 * Index routes must not have children
807 */
808type IndexRouteObject = BaseRouteObject & {
809 /**
810 * Child Route objects - not valid on index routes.
811 */
812 children?: undefined;
813 /**
814 * Whether this is an index route.
815 */
816 index: true;
817};
818/**
819 * Non-index routes may have children, but cannot have `index` set to `true`.
820 */
821type NonIndexRouteObject = BaseRouteObject & {
822 /**
823 * Child Route objects.
824 */
825 children?: RouteObject[];
826 /**
827 * Whether this is an index route - must be `false` or undefined on non-index routes.
828 */
829 index?: false;
830};
831/**
832 * A route object represents a logical route, with (optionally) its child
833 * routes organized in a tree-like structure.
834 */
835type RouteObject = IndexRouteObject | NonIndexRouteObject;
836type DataIndexRouteObject = IndexRouteObject & {
837 id: string;
838};
839type DataNonIndexRouteObject = NonIndexRouteObject & {
840 children?: DataRouteObject[];
841 id: string;
842};
843/**
844 * A data route object, which is just a RouteObject with a required unique ID
845 */
846type DataRouteObject = DataIndexRouteObject | DataNonIndexRouteObject;
847type RouteManifest<R = DataRouteObject> = Record<string, R | undefined>;
848type 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";
849type 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";
850type Regex_09 = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
851type Regex_w = Regex_az | Regez_AZ | Regex_09 | "_";
852type ParamChar = Regex_w | "-";
853type 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;
854type _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;
855type PathParam<Path extends string> = Path extends "*" | "/*" ? "*" : Path extends `${infer Rest}/*` ? "*" | _PathParam<Rest> : _PathParam<Path>;
856type ParamParseKey<Segment extends string> = [
857 PathParam<Segment>
858] extends [never] ? string : PathParam<Segment>;
859/**
860 * The parameters that were parsed from the URL path.
861 */
862type Params<Key extends string = string> = {
863 readonly [key in Key]: string | undefined;
864};
865/**
866 * A RouteMatch contains info about how a route matched a URL.
867 */
868interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> {
869 /**
870 * The names and values of dynamic parameters in the URL.
871 */
872 params: Params<ParamKey>;
873 /**
874 * The portion of the URL pathname that was matched.
875 */
876 pathname: string;
877 /**
878 * The portion of the URL pathname that was matched before child routes.
879 */
880 pathnameBase: string;
881 /**
882 * The route object that was used to match.
883 */
884 route: RouteObjectType;
885}
886interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {
887}
888/**
889 * Matches the given routes to a location and returns the match data.
890 *
891 * @example
892 * import { matchRoutes } from "react-router";
893 *
894 * let routes = [{
895 * path: "/",
896 * Component: Root,
897 * children: [{
898 * path: "dashboard",
899 * Component: Dashboard,
900 * }]
901 * }];
902 *
903 * matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
904 *
905 * @public
906 * @category Utils
907 * @param routes The array of route objects to match against.
908 * @param locationArg The location to match against, either a string path or a
909 * partial {@link Location} object
910 * @param basename Optional base path to strip from the location before matching.
911 * Defaults to `/`.
912 * @returns An array of matched routes, or `null` if no matches were found.
913 */
914declare function matchRoutes<RouteObjectType extends RouteObject = RouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): RouteMatch<string, RouteObjectType>[] | null;
915interface UIMatch<Data = unknown, Handle = unknown> {
916 id: string;
917 pathname: string;
918 /**
919 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
920 */
921 params: RouteMatch["params"];
922 /**
923 * The return value from the matched route's loader or clientLoader. This might
924 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
925 * an error and we're currently displaying an `ErrorBoundary`.
926 *
927 * @deprecated Use `UIMatch.loaderData` instead
928 */
929 data: Data | undefined;
930 /**
931 * The return value from the matched route's loader or clientLoader. This might
932 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
933 * an error and we're currently displaying an `ErrorBoundary`.
934 */
935 loaderData: Data | undefined;
936 /**
937 * The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
938 * exported from the matched route module
939 */
940 handle: Handle;
941}
942/**
943 * Returns a path with params interpolated.
944 *
945 * @example
946 * import { generatePath } from "react-router";
947 *
948 * generatePath("/users/:id", { id: "123" }); // "/users/123"
949 *
950 * @public
951 * @category Utils
952 * @param originalPath The original path to generate.
953 * @param params The parameters to interpolate into the path.
954 * @returns The generated path with parameters interpolated.
955 */
956declare function generatePath<Path extends string>(originalPath: Path, params?: {
957 [key in PathParam<Path>]: string | null;
958}): string;
959/**
960 * Used to match on some portion of a URL pathname.
961 */
962interface PathPattern<Path extends string = string> {
963 /**
964 * A string to match against a URL pathname. May contain `:id`-style segments
965 * to indicate placeholders for dynamic parameters. It May also end with `/*`
966 * to indicate matching the rest of the URL pathname.
967 */
968 path: Path;
969 /**
970 * Should be `true` if the static portions of the `path` should be matched in
971 * the same case.
972 */
973 caseSensitive?: boolean;
974 /**
975 * Should be `true` if this pattern should match the entire URL pathname.
976 */
977 end?: boolean;
978}
979/**
980 * Contains info about how a {@link PathPattern} matched on a URL pathname.
981 */
982interface PathMatch<ParamKey extends string = string> {
983 /**
984 * The names and values of dynamic parameters in the URL.
985 */
986 params: Params<ParamKey>;
987 /**
988 * The portion of the URL pathname that was matched.
989 */
990 pathname: string;
991 /**
992 * The portion of the URL pathname that was matched before child routes.
993 */
994 pathnameBase: string;
995 /**
996 * The pattern that was used to match.
997 */
998 pattern: PathPattern;
999}
1000/**
1001 * Performs pattern matching on a URL pathname and returns information about
1002 * the match.
1003 *
1004 * @public
1005 * @category Utils
1006 * @param pattern The pattern to match against the URL pathname. This can be a
1007 * string or a {@link PathPattern} object. If a string is provided, it will be
1008 * treated as a pattern with `caseSensitive` set to `false` and `end` set to
1009 * `true`.
1010 * @param pathname The URL pathname to match against the pattern.
1011 * @returns A path match object if the pattern matches the pathname,
1012 * or `null` if it does not match.
1013 */
1014declare function matchPath<ParamKey extends ParamParseKey<Path>, Path extends string>(pattern: PathPattern<Path> | Path, pathname: string): PathMatch<ParamKey> | null;
1015/**
1016 * Returns a resolved {@link Path} object relative to the given pathname.
1017 *
1018 * @public
1019 * @category Utils
1020 * @param to The path to resolve, either a string or a partial {@link Path}
1021 * object.
1022 * @param fromPathname The pathname to resolve the path from. Defaults to `/`.
1023 * @returns A {@link Path} object with the resolved pathname, search, and hash.
1024 */
1025declare function resolvePath(to: To, fromPathname?: string): Path;
1026declare class DataWithResponseInit<D> {
1027 type: string;
1028 data: D;
1029 init: ResponseInit | null;
1030 constructor(data: D, init?: ResponseInit);
1031}
1032/**
1033 * Create "responses" that contain `headers`/`status` without forcing
1034 * serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1035 *
1036 * @example
1037 * import { data } from "react-router";
1038 *
1039 * export async function action({ request }: Route.ActionArgs) {
1040 * let formData = await request.formData();
1041 * let item = await createItem(formData);
1042 * return data(item, {
1043 * headers: { "X-Custom-Header": "value" }
1044 * status: 201,
1045 * });
1046 * }
1047 *
1048 * @public
1049 * @category Utils
1050 * @mode framework
1051 * @mode data
1052 * @param data The data to be included in the response.
1053 * @param init The status code or a `ResponseInit` object to be included in the
1054 * response.
1055 * @returns A {@link DataWithResponseInit} instance containing the data and
1056 * response init.
1057 */
1058declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
1059interface TrackedPromise extends Promise<any> {
1060 _tracked?: boolean;
1061 _data?: any;
1062 _error?: any;
1063}
1064type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
1065/**
1066 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
1067 * Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1068 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
1069 *
1070 * This utility accepts absolute URLs and can navigate to external domains, so
1071 * the application should validate any user-supplied inputs to redirects.
1072 *
1073 * @example
1074 * import { redirect } from "react-router";
1075 *
1076 * export async function loader({ request }: Route.LoaderArgs) {
1077 * if (!isLoggedIn(request))
1078 * throw redirect("/login");
1079 * }
1080 *
1081 * // ...
1082 * }
1083 *
1084 * @public
1085 * @category Utils
1086 * @mode framework
1087 * @mode data
1088 * @param url The URL to redirect to.
1089 * @param init The status code or a `ResponseInit` object to be included in the
1090 * response.
1091 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1092 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1093 * header.
1094 */
1095declare const redirect: RedirectFunction;
1096/**
1097 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1098 * that will force a document reload to the new location. Sets the status code
1099 * and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1100 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
1101 *
1102 * This utility accepts absolute URLs and can navigate to external domains, so
1103 * the application should validate any user-supplied inputs to redirects.
1104 *
1105 * ```tsx filename=routes/logout.tsx
1106 * import { redirectDocument } from "react-router";
1107 *
1108 * import { destroySession } from "../sessions.server";
1109 *
1110 * export async function action({ request }: Route.ActionArgs) {
1111 * let session = await getSession(request.headers.get("Cookie"));
1112 * return redirectDocument("/", {
1113 * headers: { "Set-Cookie": await destroySession(session) }
1114 * });
1115 * }
1116 * ```
1117 *
1118 * @public
1119 * @category Utils
1120 * @mode framework
1121 * @mode data
1122 * @param url The URL to redirect to.
1123 * @param init The status code or a `ResponseInit` object to be included in the
1124 * response.
1125 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1126 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1127 * header.
1128 */
1129declare const redirectDocument: RedirectFunction;
1130/**
1131 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1132 * that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
1133 * instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
1134 * for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1135 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
1136 *
1137 * @example
1138 * import { replace } from "react-router";
1139 *
1140 * export async function loader() {
1141 * return replace("/new-location");
1142 * }
1143 *
1144 * @public
1145 * @category Utils
1146 * @mode framework
1147 * @mode data
1148 * @param url The URL to redirect to.
1149 * @param init The status code or a `ResponseInit` object to be included in the
1150 * response.
1151 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1152 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1153 * header.
1154 */
1155declare const replace: RedirectFunction;
1156type ErrorResponse = {
1157 status: number;
1158 statusText: string;
1159 data: any;
1160};
1161declare class ErrorResponseImpl implements ErrorResponse {
1162 status: number;
1163 statusText: string;
1164 data: any;
1165 private error?;
1166 private internal;
1167 constructor(status: number, statusText: string | undefined, data: any, internal?: boolean);
1168}
1169/**
1170 * Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
1171 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1172 * thrown from an [`action`](../../start/framework/route-module#action) or
1173 * [`loader`](../../start/framework/route-module#loader) function.
1174 *
1175 * @example
1176 * import { isRouteErrorResponse } from "react-router";
1177 *
1178 * export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
1179 * if (isRouteErrorResponse(error)) {
1180 * return (
1181 * <>
1182 * <p>Error: `${error.status}: ${error.statusText}`</p>
1183 * <p>{error.data}</p>
1184 * </>
1185 * );
1186 * }
1187 *
1188 * return (
1189 * <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
1190 * );
1191 * }
1192 *
1193 * @public
1194 * @category Utils
1195 * @mode framework
1196 * @mode data
1197 * @param error The error to check.
1198 * @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
1199 */
1200declare function isRouteErrorResponse(error: any): error is ErrorResponse;
1201
1202/**
1203 * An object of unknown type for route loaders and actions provided by the
1204 * server's `getLoadContext()` function. This is defined as an empty interface
1205 * specifically so apps can leverage declaration merging to augment this type
1206 * globally: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
1207 */
1208interface AppLoadContext {
1209 [key: string]: unknown;
1210}
1211
1212type Primitive = null | undefined | string | number | boolean | symbol | bigint;
1213type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
1214interface HtmlLinkProps {
1215 /**
1216 * Address of the hyperlink
1217 */
1218 href?: string;
1219 /**
1220 * How the element handles crossorigin requests
1221 */
1222 crossOrigin?: "anonymous" | "use-credentials";
1223 /**
1224 * Relationship between the document containing the hyperlink and the destination resource
1225 */
1226 rel: LiteralUnion<"alternate" | "dns-prefetch" | "icon" | "manifest" | "modulepreload" | "next" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "search" | "stylesheet", string>;
1227 /**
1228 * Applicable media: "screen", "print", "(max-width: 764px)"
1229 */
1230 media?: string;
1231 /**
1232 * Integrity metadata used in Subresource Integrity checks
1233 */
1234 integrity?: string;
1235 /**
1236 * Language of the linked resource
1237 */
1238 hrefLang?: string;
1239 /**
1240 * Hint for the type of the referenced resource
1241 */
1242 type?: string;
1243 /**
1244 * Referrer policy for fetches initiated by the element
1245 */
1246 referrerPolicy?: "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
1247 /**
1248 * Sizes of the icons (for rel="icon")
1249 */
1250 sizes?: string;
1251 /**
1252 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1253 */
1254 as?: LiteralUnion<"audio" | "audioworklet" | "document" | "embed" | "fetch" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt", string>;
1255 /**
1256 * Color to use when customizing a site's icon (for rel="mask-icon")
1257 */
1258 color?: string;
1259 /**
1260 * Whether the link is disabled
1261 */
1262 disabled?: boolean;
1263 /**
1264 * The title attribute has special semantics on this element: Title of the link; CSS style sheet set name.
1265 */
1266 title?: string;
1267 /**
1268 * Images to use in different situations, e.g., high-resolution displays,
1269 * small monitors, etc. (for rel="preload")
1270 */
1271 imageSrcSet?: string;
1272 /**
1273 * Image sizes for different page layouts (for rel="preload")
1274 */
1275 imageSizes?: string;
1276}
1277interface HtmlLinkPreloadImage extends HtmlLinkProps {
1278 /**
1279 * Relationship between the document containing the hyperlink and the destination resource
1280 */
1281 rel: "preload";
1282 /**
1283 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1284 */
1285 as: "image";
1286 /**
1287 * Address of the hyperlink
1288 */
1289 href?: string;
1290 /**
1291 * Images to use in different situations, e.g., high-resolution displays,
1292 * small monitors, etc. (for rel="preload")
1293 */
1294 imageSrcSet: string;
1295 /**
1296 * Image sizes for different page layouts (for rel="preload")
1297 */
1298 imageSizes?: string;
1299}
1300/**
1301 * Represents a `<link>` element.
1302 *
1303 * WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
1304 */
1305type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "imageSizes">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "href"> & {
1306 imageSizes?: never;
1307});
1308interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
1309 /**
1310 * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
1311 * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
1312 * element
1313 */
1314 nonce?: string | undefined;
1315 /**
1316 * The absolute path of the page to prefetch, e.g. `/absolute/path`.
1317 */
1318 page: string;
1319}
1320type LinkDescriptor = HtmlLinkDescriptor | PageLinkDescriptor;
1321
1322type Serializable = undefined | null | boolean | string | symbol | number | Array<Serializable> | {
1323 [key: PropertyKey]: Serializable;
1324} | bigint | Date | URL | RegExp | Error | Map<Serializable, Serializable> | Set<Serializable> | Promise<Serializable>;
1325
1326type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
1327type IsAny<T> = 0 extends 1 & T ? true : false;
1328type Func = (...args: any[]) => unknown;
1329type Pretty<T> = {
1330 [K in keyof T]: T[K];
1331} & {};
1332type Normalize<T> = _Normalize<UnionKeys<T>, T>;
1333type _Normalize<Key extends keyof any, T> = T extends infer U ? Pretty<{
1334 [K in Key as K extends keyof U ? undefined extends U[K] ? never : K : never]: K extends keyof U ? U[K] : never;
1335} & {
1336 [K in Key as K extends keyof U ? undefined extends U[K] ? K : never : never]?: K extends keyof U ? U[K] : never;
1337} & {
1338 [K in Key as K extends keyof U ? never : K]?: undefined;
1339}> : never;
1340type UnionKeys<T> = T extends any ? keyof T : never;
1341
1342type RouteModule$1 = {
1343 meta?: Func;
1344 links?: Func;
1345 headers?: Func;
1346 loader?: Func;
1347 clientLoader?: Func;
1348 action?: Func;
1349 clientAction?: Func;
1350 HydrateFallback?: Func;
1351 default?: Func;
1352 ErrorBoundary?: Func;
1353 [key: string]: unknown;
1354};
1355
1356/**
1357 * A brand that can be applied to a type to indicate that it will serialize
1358 * to a specific type when transported to the client from a loader.
1359 * Only use this if you have additional serialization/deserialization logic
1360 * in your application.
1361 */
1362type unstable_SerializesTo<T> = {
1363 unstable__ReactRouter_SerializesTo: [T];
1364};
1365
1366type 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> ? {
1367 [K in keyof T]: Serialize<T[K]>;
1368} : undefined;
1369type VoidToUndefined<T> = Equal<T, void> extends true ? undefined : T;
1370type DataFrom<T> = IsAny<T> extends true ? undefined : T extends Func ? VoidToUndefined<Awaited<ReturnType<T>>> : undefined;
1371type ClientData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? U : T;
1372type ServerData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? Serialize<U> : Serialize<T>;
1373type ServerDataFrom<T> = ServerData<DataFrom<T>>;
1374type ClientDataFrom<T> = ClientData<DataFrom<T>>;
1375type ClientDataFunctionArgs<Params> = {
1376 /**
1377 * 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.
1378 *
1379 * @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.
1380 **/
1381 request: Request;
1382 /**
1383 * A URL instance representing the application location being navigated to or fetched.
1384 * Without `future.unstable_passThroughRequests` enabled, this matches `request.url`.
1385 * With `future.unstable_passThroughRequests` enabled, this is a normalized
1386 * URL with React-Router-specific implementation details removed (`.data`
1387 * pathnames, `index`/`_routes` search params).
1388 * The URL includes the origin from the request for convenience.
1389 */
1390 unstable_url: URL;
1391 /**
1392 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
1393 * @example
1394 * // app/routes.ts
1395 * route("teams/:teamId", "./team.tsx"),
1396 *
1397 * // app/team.tsx
1398 * export function clientLoader({
1399 * params,
1400 * }: Route.ClientLoaderArgs) {
1401 * params.teamId;
1402 * // ^ string
1403 * }
1404 **/
1405 params: Params;
1406 /**
1407 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
1408 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
1409 */
1410 unstable_pattern: string;
1411 /**
1412 * When `future.v8_middleware` is not enabled, this is undefined.
1413 *
1414 * When `future.v8_middleware` is enabled, this is an instance of
1415 * `RouterContextProvider` and can be used to access context values
1416 * from your route middlewares. You may pass in initial context values in your
1417 * `<HydratedRouter getContext>` prop
1418 */
1419 context: Readonly<RouterContextProvider>;
1420};
1421type ServerDataFunctionArgs<Params> = {
1422 /** 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. */
1423 request: Request;
1424 /**
1425 * A URL instance representing the application location being navigated to or fetched.
1426 * Without `future.unstable_passThroughRequests` enabled, this matches `request.url`.
1427 * With `future.unstable_passThroughRequests` enabled, this is a normalized
1428 * URL with React-Router-specific implementation details removed (`.data`
1429 * pathnames, `index`/`_routes` search params).
1430 * The URL includes the origin from the request for convenience.
1431 */
1432 unstable_url: URL;
1433 /**
1434 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
1435 * @example
1436 * // app/routes.ts
1437 * route("teams/:teamId", "./team.tsx"),
1438 *
1439 * // app/team.tsx
1440 * export function loader({
1441 * params,
1442 * }: Route.LoaderArgs) {
1443 * params.teamId;
1444 * // ^ string
1445 * }
1446 **/
1447 params: Params;
1448 /**
1449 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
1450 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
1451 */
1452 unstable_pattern: string;
1453 /**
1454 * Without `future.v8_middleware` enabled, this is the context passed in
1455 * to your server adapter's `getLoadContext` function. It's a way to bridge the
1456 * gap between the adapter's request/response API with your React Router app.
1457 * It is only applicable if you are using a custom server adapter.
1458 *
1459 * With `future.v8_middleware` enabled, this is an instance of
1460 * `RouterContextProvider` and can be used for type-safe access to
1461 * context value set in your route middlewares. If you are using a custom
1462 * server adapter, you may provide an initial set of context values from your
1463 * `getLoadContext` function.
1464 */
1465 context: MiddlewareEnabled extends true ? Readonly<RouterContextProvider> : AppLoadContext;
1466};
1467type SerializeFrom<T> = T extends (...args: infer Args) => unknown ? Args extends [
1468 ClientLoaderFunctionArgs | ClientActionFunctionArgs | ClientDataFunctionArgs<unknown>
1469] ? ClientDataFrom<T> : ServerDataFrom<T> : T;
1470type IsDefined<T> = Equal<T, undefined> extends true ? false : true;
1471type IsHydrate<ClientLoader> = ClientLoader extends {
1472 hydrate: true;
1473} ? true : ClientLoader extends {
1474 hydrate: false;
1475} ? false : false;
1476type GetLoaderData<T extends RouteModule$1> = _DataLoaderData<ServerDataFrom<T["loader"]>, ClientDataFrom<T["clientLoader"]>, IsHydrate<T["clientLoader"]>, T extends {
1477 HydrateFallback: Func;
1478} ? true : false>;
1479type _DataLoaderData<ServerLoaderData, ClientLoaderData, ClientLoaderHydrate extends boolean, HasHydrateFallback> = [
1480 HasHydrateFallback,
1481 ClientLoaderHydrate
1482] extends [true, true] ? IsDefined<ClientLoaderData> extends true ? ClientLoaderData : undefined : [
1483 IsDefined<ClientLoaderData>,
1484 IsDefined<ServerLoaderData>
1485] extends [true, true] ? ServerLoaderData | ClientLoaderData : IsDefined<ClientLoaderData> extends true ? ClientLoaderData : IsDefined<ServerLoaderData> extends true ? ServerLoaderData : undefined;
1486type GetActionData<T extends RouteModule$1> = _DataActionData<ServerDataFrom<T["action"]>, ClientDataFrom<T["clientAction"]>>;
1487type _DataActionData<ServerActionData, ClientActionData> = Awaited<[
1488 IsDefined<ServerActionData>,
1489 IsDefined<ClientActionData>
1490] extends [true, true] ? ServerActionData | ClientActionData : IsDefined<ClientActionData> extends true ? ClientActionData : IsDefined<ServerActionData> extends true ? ServerActionData : undefined>;
1491
1492interface RouteModules {
1493 [routeId: string]: RouteModule | undefined;
1494}
1495/**
1496 * The shape of a route module shipped to the client
1497 */
1498interface RouteModule {
1499 clientAction?: ClientActionFunction;
1500 clientLoader?: ClientLoaderFunction;
1501 clientMiddleware?: MiddlewareFunction<Record<string, DataStrategyResult>>[];
1502 ErrorBoundary?: ErrorBoundaryComponent;
1503 HydrateFallback?: HydrateFallbackComponent;
1504 Layout?: LayoutComponent;
1505 default: RouteComponent;
1506 handle?: RouteHandle;
1507 links?: LinksFunction;
1508 meta?: MetaFunction;
1509 shouldRevalidate?: ShouldRevalidateFunction;
1510}
1511/**
1512 * The shape of a route module on the server
1513 */
1514interface ServerRouteModule extends RouteModule {
1515 action?: ActionFunction;
1516 headers?: HeadersFunction | {
1517 [name: string]: string;
1518 };
1519 loader?: LoaderFunction;
1520 middleware?: MiddlewareFunction<Response>[];
1521}
1522/**
1523 * A function that handles data mutations for a route on the client
1524 */
1525type ClientActionFunction = (args: ClientActionFunctionArgs) => ReturnType<ActionFunction>;
1526/**
1527 * Arguments passed to a route `clientAction` function
1528 */
1529type ClientActionFunctionArgs = ActionFunctionArgs & {
1530 serverAction: <T = unknown>() => Promise<SerializeFrom<T>>;
1531};
1532/**
1533 * A function that loads data for a route on the client
1534 */
1535type ClientLoaderFunction = ((args: ClientLoaderFunctionArgs) => ReturnType<LoaderFunction>) & {
1536 hydrate?: boolean;
1537};
1538/**
1539 * Arguments passed to a route `clientLoader` function
1540 */
1541type ClientLoaderFunctionArgs = LoaderFunctionArgs & {
1542 serverLoader: <T = unknown>() => Promise<SerializeFrom<T>>;
1543};
1544/**
1545 * ErrorBoundary to display for this route
1546 */
1547type ErrorBoundaryComponent = ComponentType;
1548type HeadersArgs = {
1549 loaderHeaders: Headers;
1550 parentHeaders: Headers;
1551 actionHeaders: Headers;
1552 errorHeaders: Headers | undefined;
1553};
1554/**
1555 * A function that returns HTTP headers to be used for a route. These headers
1556 * will be merged with (and take precedence over) headers from parent routes.
1557 */
1558interface HeadersFunction {
1559 (args: HeadersArgs): Headers | HeadersInit;
1560}
1561/**
1562 * `<Route HydrateFallback>` component to render on initial loads
1563 * when client loaders are present
1564 */
1565type HydrateFallbackComponent = ComponentType;
1566/**
1567 * Optional, root-only `<Route Layout>` component to wrap the root content in.
1568 * Useful for defining the <html>/<head>/<body> document shell shared by the
1569 * Component, HydrateFallback, and ErrorBoundary
1570 */
1571type LayoutComponent = ComponentType<{
1572 children: ReactElement<unknown, ErrorBoundaryComponent | HydrateFallbackComponent | RouteComponent>;
1573}>;
1574/**
1575 * A function that defines `<link>` tags to be inserted into the `<head>` of
1576 * the document on route transitions.
1577 *
1578 * @see https://reactrouter.com/start/framework/route-module#meta
1579 */
1580interface LinksFunction {
1581 (): LinkDescriptor[];
1582}
1583interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
1584 id: RouteId;
1585 pathname: DataRouteMatch["pathname"];
1586 /** @deprecated Use `MetaMatch.loaderData` instead */
1587 data: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
1588 loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
1589 handle?: RouteHandle;
1590 params: DataRouteMatch["params"];
1591 meta: MetaDescriptor[];
1592 error?: unknown;
1593}
1594type MetaMatches<MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> = Array<{
1595 [K in keyof MatchLoaders]: MetaMatch<Exclude<K, number | symbol>, MatchLoaders[K]>;
1596}[keyof MatchLoaders]>;
1597interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
1598 /** @deprecated Use `MetaArgs.loaderData` instead */
1599 data: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
1600 loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
1601 params: Params;
1602 location: Location;
1603 matches: MetaMatches<MatchLoaders>;
1604 error?: unknown;
1605}
1606/**
1607 * A function that returns an array of data objects to use for rendering
1608 * metadata HTML tags in a route. These tags are not rendered on descendant
1609 * routes in the route hierarchy. In other words, they will only be rendered on
1610 * the route in which they are exported.
1611 *
1612 * @param Loader - The type of the current route's loader function
1613 * @param MatchLoaders - Mapping from a parent route's filepath to its loader
1614 * function type
1615 *
1616 * Note that parent route filepaths are relative to the `app/` directory.
1617 *
1618 * For example, if this meta function is for `/sales/customers/$customerId`:
1619 *
1620 * ```ts
1621 * // app/root.tsx
1622 * const loader = () => ({ hello: "world" })
1623 * export type Loader = typeof loader
1624 *
1625 * // app/routes/sales.tsx
1626 * const loader = () => ({ salesCount: 1074 })
1627 * export type Loader = typeof loader
1628 *
1629 * // app/routes/sales/customers.tsx
1630 * const loader = () => ({ customerCount: 74 })
1631 * export type Loader = typeof loader
1632 *
1633 * // app/routes/sales/customers/$customersId.tsx
1634 * import type { Loader as RootLoader } from "../../../root"
1635 * import type { Loader as SalesLoader } from "../../sales"
1636 * import type { Loader as CustomersLoader } from "../../sales/customers"
1637 *
1638 * const loader = () => ({ name: "Customer name" })
1639 *
1640 * const meta: MetaFunction<typeof loader, {
1641 * "root": RootLoader,
1642 * "routes/sales": SalesLoader,
1643 * "routes/sales/customers": CustomersLoader,
1644 * }> = ({ data, matches }) => {
1645 * const { name } = data
1646 * // ^? string
1647 * const { customerCount } = matches.find((match) => match.id === "routes/sales/customers").data
1648 * // ^? number
1649 * const { salesCount } = matches.find((match) => match.id === "routes/sales").data
1650 * // ^? number
1651 * const { hello } = matches.find((match) => match.id === "root").data
1652 * // ^? "world"
1653 * }
1654 * ```
1655 */
1656interface MetaFunction<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
1657 (args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;
1658}
1659type MetaDescriptor = {
1660 charSet: "utf-8";
1661} | {
1662 title: string;
1663} | {
1664 name: string;
1665 content: string;
1666} | {
1667 property: string;
1668 content: string;
1669} | {
1670 httpEquiv: string;
1671 content: string;
1672} | {
1673 "script:ld+json": LdJsonObject;
1674} | {
1675 tagName: "meta" | "link";
1676 [name: string]: string;
1677} | {
1678 [name: string]: unknown;
1679};
1680type LdJsonObject = {
1681 [Key in string]: LdJsonValue;
1682} & {
1683 [Key in string]?: LdJsonValue | undefined;
1684};
1685type LdJsonArray = LdJsonValue[] | readonly LdJsonValue[];
1686type LdJsonPrimitive = string | number | boolean | null;
1687type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
1688/**
1689 * A React component that is rendered for a route.
1690 */
1691type RouteComponent = ComponentType<{}>;
1692/**
1693 * An arbitrary object that is associated with a route.
1694 *
1695 * @see https://reactrouter.com/how-to/using-handle
1696 */
1697type RouteHandle = unknown;
1698
1699export { type BaseRouteObject as $, type ActionFunction as A, type DataStrategyResult as B, type ClientActionFunction as C, type DataRouteMatch as D, type ServerDataFrom as E, type FormEncType as F, type GetLoaderData as G, type HeadersFunction as H, type GetActionData as I, type RouteModules as J, type SerializeFrom as K, type Location as L, type MetaFunction as M, type Normalize as N, type ParamParseKey as O, type Params as P, type PathPattern as Q, type RouteModule$1 as R, type ShouldRevalidateFunction as S, type To as T, type UIMatch as U, type PathMatch as V, type InitialEntry as W, type IndexRouteObject as X, type NonIndexRouteObject as Y, type Equal as Z, type ActionFunctionArgs as _, type ClientLoaderFunction as a, type DataStrategyFunctionArgs as a0, type DataStrategyMatch as a1, DataWithResponseInit as a2, type ErrorResponse as a3, type FormMethod as a4, type LazyRouteFunction as a5, type MiddlewareFunction as a6, type PatchRoutesOnNavigationFunctionArgs as a7, type PathParam as a8, type RedirectFunction as a9, invariant as aA, ErrorResponseImpl as aB, type RouteManifest as aC, type ServerRouteModule as aD, type TrackedPromise as aE, type RouteMatch as aa, type RouterContext as ab, type ShouldRevalidateFunctionArgs as ac, createContext as ad, createPath as ae, parsePath as af, data as ag, generatePath as ah, isRouteErrorResponse as ai, matchPath as aj, matchRoutes as ak, redirect as al, redirectDocument as am, replace as an, resolvePath as ao, type ClientActionFunctionArgs as ap, type ClientLoaderFunctionArgs as aq, type HeadersArgs as ar, type MetaArgs as as, type PageLinkDescriptor as at, type HtmlLinkDescriptor as au, type Future as av, type unstable_SerializesTo as aw, createMemoryHistory as ax, createBrowserHistory as ay, createHashHistory as az, type LinksFunction as b, RouterContextProvider as c, type LoaderFunction as d, type RouteObject as e, type History as f, type MaybePromise as g, type MapRoutePropertiesFunction as h, Action as i, type Submission as j, type RouteData as k, type DataStrategyFunction as l, type PatchRoutesOnNavigationFunction as m, type DataRouteObject as n, type HTMLFormMethod as o, type Path as p, type LoaderFunctionArgs as q, type MiddlewareEnabled as r, type AppLoadContext as s, type LinkDescriptor as t, type Func as u, type Pretty as v, type MetaDescriptor as w, type ServerDataFunctionArgs as x, type MiddlewareNextFunction as y, type ClientDataFunctionArgs as z };
1700
\No newline at end of file