UNPKG

68.5 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 mask?: Path;
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
449 * fetched. By default, this matches `request.url`.
450 *
451 * In Framework mode with `future.v8_passThroughRequests` enabled, this is a
452 * normalized URL with React-Router-specific implementation details removed
453 * (`.data` suffixes, `index`/`_routes` search params).
454 */
455 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 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 Regex_AZ = Uppercase<Regex_az>;
850type Regex_09 = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
851type Regex_w = Regex_az | Regex_AZ | Regex_09 | "_";
852/** Emulates Regex `+` operator */
853type RegexMatchPlus<char extends string, T extends string> = _RegexMatchPlus<char, T> extends infer result extends string ? result extends '' ? never : result : never;
854type _RegexMatchPlus<char extends string, T extends string> = T extends `${infer head extends char}${infer rest}` ? `${head}${_RegexMatchPlus<char, rest>}` : '';
855type ParamNameChar = Regex_w | "-";
856type Simplify<T> = {
857 [K in keyof T]: T[K];
858} & {};
859type GeneratePathParams<path extends string> = Simplify<ParseParams<path> & {
860 [key in string]: string | null | undefined;
861}>;
862type ParseParams<path extends string> = path extends '*' ? {
863 '*': string;
864} : path extends `${infer rest}/*` ? {
865 '*': string;
866} & ParseParams<rest> : _ParseParams<path>;
867type _ParseParams<path extends string> = path extends `${infer left}/${infer right}` ? _ParseParams<left> & _ParseParams<right> : path extends `:${infer param}?${string}` ? {
868 [key in RegexMatchPlus<ParamNameChar, param>]?: string | null | undefined;
869} : path extends `:${infer param}` ? {
870 [key in RegexMatchPlus<ParamNameChar, param>]: string;
871} : {};
872type PathParam<path extends string> = (keyof ParseParams<path>) & string;
873type ParamParseKey<Segment extends string> = [
874 PathParam<Segment>
875] extends [never] ? string : PathParam<Segment>;
876/**
877 * The parameters that were parsed from the URL path.
878 */
879type Params<Key extends string = string> = {
880 readonly [key in Key]: string | undefined;
881};
882/**
883 * A RouteMatch contains info about how a route matched a URL.
884 */
885interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> {
886 /**
887 * The names and values of dynamic parameters in the URL.
888 */
889 params: Params<ParamKey>;
890 /**
891 * The portion of the URL pathname that was matched.
892 */
893 pathname: string;
894 /**
895 * The portion of the URL pathname that was matched before child routes.
896 */
897 pathnameBase: string;
898 /**
899 * The route object that was used to match.
900 */
901 route: RouteObjectType;
902}
903interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {
904}
905/**
906 * Matches the given routes to a location and returns the match data.
907 *
908 * @example
909 * import { matchRoutes } from "react-router";
910 *
911 * let routes = [{
912 * path: "/",
913 * Component: Root,
914 * children: [{
915 * path: "dashboard",
916 * Component: Dashboard,
917 * }]
918 * }];
919 *
920 * matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
921 *
922 * @public
923 * @category Utils
924 * @param routes The array of route objects to match against.
925 * @param locationArg The location to match against, either a string path or a
926 * partial {@link Location} object
927 * @param basename Optional base path to strip from the location before matching.
928 * Defaults to `/`.
929 * @returns An array of matched routes, or `null` if no matches were found.
930 */
931declare function matchRoutes<RouteObjectType extends RouteObject = RouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): RouteMatch<string, RouteObjectType>[] | null;
932interface UIMatch<Data = unknown, Handle = unknown> {
933 id: string;
934 pathname: string;
935 /**
936 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
937 */
938 params: RouteMatch["params"];
939 /**
940 * The return value from the matched route's loader or clientLoader. This might
941 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
942 * an error and we're currently displaying an `ErrorBoundary`.
943 *
944 * @deprecated Use `UIMatch.loaderData` instead
945 */
946 data: Data | undefined;
947 /**
948 * The return value from the matched route's loader or clientLoader. This might
949 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
950 * an error and we're currently displaying an `ErrorBoundary`.
951 */
952 loaderData: Data | undefined;
953 /**
954 * The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
955 * exported from the matched route module
956 */
957 handle: Handle;
958}
959interface RouteMeta<RouteObjectType extends RouteObject = RouteObject> {
960 relativePath: string;
961 caseSensitive: boolean;
962 childrenIndex: number;
963 route: RouteObjectType;
964}
965/**
966 * @private
967 * PRIVATE - DO NOT USE
968 *
969 * A "branch" of routes that match a given route pattern.
970 * This is an internal interface not intended for direct external usage.
971 */
972interface RouteBranch<RouteObjectType extends RouteObject = RouteObject> {
973 path: string;
974 score: number;
975 routesMeta: RouteMeta<RouteObjectType>[];
976}
977/**
978 * Returns a path with params interpolated.
979 *
980 * @example
981 * import { generatePath } from "react-router";
982 *
983 * generatePath("/users/:id", { id: "123" }); // "/users/123"
984 *
985 * @public
986 * @category Utils
987 * @param originalPath The original path to generate.
988 * @param params The parameters to interpolate into the path.
989 * @returns The generated path with parameters interpolated.
990 */
991declare function generatePath<Path extends string>(originalPath: Path, params?: GeneratePathParams<Path>): string;
992/**
993 * Used to match on some portion of a URL pathname.
994 */
995interface PathPattern<Path extends string = string> {
996 /**
997 * A string to match against a URL pathname. May contain `:id`-style segments
998 * to indicate placeholders for dynamic parameters. It May also end with `/*`
999 * to indicate matching the rest of the URL pathname.
1000 */
1001 path: Path;
1002 /**
1003 * Should be `true` if the static portions of the `path` should be matched in
1004 * the same case.
1005 */
1006 caseSensitive?: boolean;
1007 /**
1008 * Should be `true` if this pattern should match the entire URL pathname.
1009 */
1010 end?: boolean;
1011}
1012/**
1013 * Contains info about how a {@link PathPattern} matched on a URL pathname.
1014 */
1015interface PathMatch<ParamKey extends string = string> {
1016 /**
1017 * The names and values of dynamic parameters in the URL.
1018 */
1019 params: Params<ParamKey>;
1020 /**
1021 * The portion of the URL pathname that was matched.
1022 */
1023 pathname: string;
1024 /**
1025 * The portion of the URL pathname that was matched before child routes.
1026 */
1027 pathnameBase: string;
1028 /**
1029 * The pattern that was used to match.
1030 */
1031 pattern: PathPattern;
1032}
1033/**
1034 * Performs pattern matching on a URL pathname and returns information about
1035 * the match.
1036 *
1037 * @public
1038 * @category Utils
1039 * @param pattern The pattern to match against the URL pathname. This can be a
1040 * string or a {@link PathPattern} object. If a string is provided, it will be
1041 * treated as a pattern with `caseSensitive` set to `false` and `end` set to
1042 * `true`.
1043 * @param pathname The URL pathname to match against the pattern.
1044 * @returns A path match object if the pattern matches the pathname,
1045 * or `null` if it does not match.
1046 */
1047declare function matchPath<Path extends string>(pattern: PathPattern<Path> | Path, pathname: string): PathMatch<ParamParseKey<Path>> | null;
1048/**
1049 * Returns a resolved {@link Path} object relative to the given pathname.
1050 *
1051 * @public
1052 * @category Utils
1053 * @param to The path to resolve, either a string or a partial {@link Path}
1054 * object.
1055 * @param fromPathname The pathname to resolve the path from. Defaults to `/`.
1056 * @returns A {@link Path} object with the resolved pathname, search, and hash.
1057 */
1058declare function resolvePath(to: To, fromPathname?: string): Path;
1059declare class DataWithResponseInit<D> {
1060 type: string;
1061 data: D;
1062 init: ResponseInit | null;
1063 constructor(data: D, init?: ResponseInit);
1064}
1065/**
1066 * Create "responses" that contain `headers`/`status` without forcing
1067 * serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1068 *
1069 * @example
1070 * import { data } from "react-router";
1071 *
1072 * export async function action({ request }: Route.ActionArgs) {
1073 * let formData = await request.formData();
1074 * let item = await createItem(formData);
1075 * return data(item, {
1076 * headers: { "X-Custom-Header": "value" }
1077 * status: 201,
1078 * });
1079 * }
1080 *
1081 * @public
1082 * @category Utils
1083 * @mode framework
1084 * @mode data
1085 * @param data The data to be included in the response.
1086 * @param init The status code or a `ResponseInit` object to be included in the
1087 * response.
1088 * @returns A {@link DataWithResponseInit} instance containing the data and
1089 * response init.
1090 */
1091declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
1092interface TrackedPromise extends Promise<any> {
1093 _tracked?: boolean;
1094 _data?: any;
1095 _error?: any;
1096}
1097type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
1098/**
1099 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
1100 * Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1101 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
1102 *
1103 * This utility accepts absolute URLs and can navigate to external domains, so
1104 * the application should validate any user-supplied inputs to redirects.
1105 *
1106 * @example
1107 * import { redirect } from "react-router";
1108 *
1109 * export async function loader({ request }: Route.LoaderArgs) {
1110 * if (!isLoggedIn(request))
1111 * throw redirect("/login");
1112 * }
1113 *
1114 * // ...
1115 * }
1116 *
1117 * @public
1118 * @category Utils
1119 * @mode framework
1120 * @mode data
1121 * @param url The URL to redirect to.
1122 * @param init The status code or a `ResponseInit` object to be included in the
1123 * response.
1124 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1125 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1126 * header.
1127 */
1128declare const redirect: RedirectFunction;
1129/**
1130 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1131 * that will force a document reload to the new location. Sets the status code
1132 * and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1133 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
1134 *
1135 * This utility accepts absolute URLs and can navigate to external domains, so
1136 * the application should validate any user-supplied inputs to redirects.
1137 *
1138 * ```tsx filename=routes/logout.tsx
1139 * import { redirectDocument } from "react-router";
1140 *
1141 * import { destroySession } from "../sessions.server";
1142 *
1143 * export async function action({ request }: Route.ActionArgs) {
1144 * let session = await getSession(request.headers.get("Cookie"));
1145 * return redirectDocument("/", {
1146 * headers: { "Set-Cookie": await destroySession(session) }
1147 * });
1148 * }
1149 * ```
1150 *
1151 * @public
1152 * @category Utils
1153 * @mode framework
1154 * @mode data
1155 * @param url The URL to redirect to.
1156 * @param init The status code or a `ResponseInit` object to be included in the
1157 * response.
1158 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1159 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1160 * header.
1161 */
1162declare const redirectDocument: RedirectFunction;
1163/**
1164 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1165 * that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
1166 * instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
1167 * for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1168 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
1169 *
1170 * @example
1171 * import { replace } from "react-router";
1172 *
1173 * export async function loader() {
1174 * return replace("/new-location");
1175 * }
1176 *
1177 * @public
1178 * @category Utils
1179 * @mode framework
1180 * @mode data
1181 * @param url The URL to redirect to.
1182 * @param init The status code or a `ResponseInit` object to be included in the
1183 * response.
1184 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1185 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
1186 * header.
1187 */
1188declare const replace: RedirectFunction;
1189type ErrorResponse = {
1190 status: number;
1191 statusText: string;
1192 data: any;
1193};
1194declare class ErrorResponseImpl implements ErrorResponse {
1195 status: number;
1196 statusText: string;
1197 data: any;
1198 private error?;
1199 private internal;
1200 constructor(status: number, statusText: string | undefined, data: any, internal?: boolean);
1201}
1202/**
1203 * Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
1204 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
1205 * thrown from an [`action`](../../start/framework/route-module#action) or
1206 * [`loader`](../../start/framework/route-module#loader) function.
1207 *
1208 * @example
1209 * import { isRouteErrorResponse } from "react-router";
1210 *
1211 * export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
1212 * if (isRouteErrorResponse(error)) {
1213 * return (
1214 * <>
1215 * <p>Error: `${error.status}: ${error.statusText}`</p>
1216 * <p>{error.data}</p>
1217 * </>
1218 * );
1219 * }
1220 *
1221 * return (
1222 * <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
1223 * );
1224 * }
1225 *
1226 * @public
1227 * @category Utils
1228 * @mode framework
1229 * @mode data
1230 * @param error The error to check.
1231 * @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
1232 */
1233declare function isRouteErrorResponse(error: any): error is ErrorResponse;
1234
1235type Primitive = null | undefined | string | number | boolean | symbol | bigint;
1236type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
1237interface HtmlLinkProps {
1238 /**
1239 * Address of the hyperlink
1240 */
1241 href?: string;
1242 /**
1243 * How the element handles crossorigin requests
1244 */
1245 crossOrigin?: "anonymous" | "use-credentials";
1246 /**
1247 * Relationship between the document containing the hyperlink and the destination resource
1248 */
1249 rel: LiteralUnion<"alternate" | "dns-prefetch" | "icon" | "manifest" | "modulepreload" | "next" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "search" | "stylesheet", string>;
1250 /**
1251 * Applicable media: "screen", "print", "(max-width: 764px)"
1252 */
1253 media?: string;
1254 /**
1255 * Integrity metadata used in Subresource Integrity checks
1256 */
1257 integrity?: string;
1258 /**
1259 * Language of the linked resource
1260 */
1261 hrefLang?: string;
1262 /**
1263 * Hint for the type of the referenced resource
1264 */
1265 type?: string;
1266 /**
1267 * Referrer policy for fetches initiated by the element
1268 */
1269 referrerPolicy?: "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
1270 /**
1271 * Sizes of the icons (for rel="icon")
1272 */
1273 sizes?: string;
1274 /**
1275 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1276 */
1277 as?: LiteralUnion<"audio" | "audioworklet" | "document" | "embed" | "fetch" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt", string>;
1278 /**
1279 * Color to use when customizing a site's icon (for rel="mask-icon")
1280 */
1281 color?: string;
1282 /**
1283 * Whether the link is disabled
1284 */
1285 disabled?: boolean;
1286 /**
1287 * The title attribute has special semantics on this element: Title of the link; CSS style sheet set name.
1288 */
1289 title?: 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}
1300interface HtmlLinkPreloadImage extends HtmlLinkProps {
1301 /**
1302 * Relationship between the document containing the hyperlink and the destination resource
1303 */
1304 rel: "preload";
1305 /**
1306 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1307 */
1308 as: "image";
1309 /**
1310 * Address of the hyperlink
1311 */
1312 href?: string;
1313 /**
1314 * Images to use in different situations, e.g., high-resolution displays,
1315 * small monitors, etc. (for rel="preload")
1316 */
1317 imageSrcSet: string;
1318 /**
1319 * Image sizes for different page layouts (for rel="preload")
1320 */
1321 imageSizes?: string;
1322}
1323/**
1324 * Represents a `<link>` element.
1325 *
1326 * WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
1327 */
1328type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "imageSizes">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "href"> & {
1329 imageSizes?: never;
1330});
1331interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
1332 /**
1333 * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
1334 * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
1335 * element
1336 */
1337 nonce?: string | undefined;
1338 /**
1339 * The absolute path of the page to prefetch, e.g. `/absolute/path`.
1340 */
1341 page: string;
1342}
1343type LinkDescriptor = HtmlLinkDescriptor | PageLinkDescriptor;
1344
1345type Serializable = undefined | null | boolean | string | symbol | number | Array<Serializable> | {
1346 [key: PropertyKey]: Serializable;
1347} | bigint | Date | URL | RegExp | Error | Map<Serializable, Serializable> | Set<Serializable> | Promise<Serializable>;
1348
1349type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
1350type IsAny<T> = 0 extends 1 & T ? true : false;
1351type Func = (...args: any[]) => unknown;
1352type Pretty<T> = {
1353 [K in keyof T]: T[K];
1354} & {};
1355type Normalize<T> = _Normalize<UnionKeys<T>, T>;
1356type _Normalize<Key extends keyof any, T> = T extends infer U ? Pretty<{
1357 [K in Key as K extends keyof U ? undefined extends U[K] ? never : K : never]: K extends keyof U ? U[K] : never;
1358} & {
1359 [K in Key as K extends keyof U ? undefined extends U[K] ? K : never : never]?: K extends keyof U ? U[K] : never;
1360} & {
1361 [K in Key as K extends keyof U ? never : K]?: undefined;
1362}> : never;
1363type UnionKeys<T> = T extends any ? keyof T : never;
1364
1365type RouteModule$1 = {
1366 meta?: Func;
1367 links?: Func;
1368 headers?: Func;
1369 loader?: Func;
1370 clientLoader?: Func;
1371 action?: Func;
1372 clientAction?: Func;
1373 HydrateFallback?: Func;
1374 default?: Func;
1375 ErrorBoundary?: Func;
1376 [key: string]: unknown;
1377};
1378
1379/**
1380 * A brand that can be applied to a type to indicate that it will serialize
1381 * to a specific type when transported to the client from a loader.
1382 * Only use this if you have additional serialization/deserialization logic
1383 * in your application.
1384 */
1385type unstable_SerializesTo<T> = {
1386 unstable__ReactRouter_SerializesTo: [T];
1387};
1388
1389type 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> ? {
1390 [K in keyof T]: Serialize<T[K]>;
1391} : undefined;
1392type VoidToUndefined<T> = Equal<T, void> extends true ? undefined : T;
1393type DataFrom<T> = IsAny<T> extends true ? undefined : T extends Func ? VoidToUndefined<Awaited<ReturnType<T>>> : undefined;
1394type ClientData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? U : T;
1395type ServerData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? Serialize<U> : Serialize<T>;
1396type ServerDataFrom<T> = ServerData<DataFrom<T>>;
1397type ClientDataFrom<T> = ClientData<DataFrom<T>>;
1398type ClientDataFunctionArgs<Params> = {
1399 /**
1400 * 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.
1401 *
1402 * @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.
1403 **/
1404 request: Request;
1405 /**
1406 * A URL instance representing the application location being navigated to or
1407 * fetched. By default, this matches `request.url`.
1408 *
1409 * In Framework mode with `future.v8_passThroughRequests` enabled, this is a
1410 * normalized URL with React-Router-specific implementation details removed
1411 * (`.data` suffixes, `index`/`_routes` search params).
1412 */
1413 url: URL;
1414 /**
1415 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
1416 * @example
1417 * // app/routes.ts
1418 * route("teams/:teamId", "./team.tsx"),
1419 *
1420 * // app/team.tsx
1421 * export function clientLoader({
1422 * params,
1423 * }: Route.ClientLoaderArgs) {
1424 * params.teamId;
1425 * // ^ string
1426 * }
1427 **/
1428 params: Params;
1429 /**
1430 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
1431 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
1432 */
1433 pattern: string;
1434 /**
1435 * When `future.v8_middleware` is not enabled, this is undefined.
1436 *
1437 * When `future.v8_middleware` is enabled, this is an instance of
1438 * `RouterContextProvider` and can be used to access context values
1439 * from your route middlewares. You may pass in initial context values in your
1440 * `<HydratedRouter getContext>` prop
1441 */
1442 context: Readonly<RouterContextProvider>;
1443};
1444type ServerDataFunctionArgs<Params> = {
1445 /** 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. */
1446 request: Request;
1447 /**
1448 * A URL instance representing the application location being navigated to or
1449 * fetched. By default, this matches `request.url`.
1450 *
1451 * In Framework mode with `future.v8_passThroughRequests` enabled, this is a
1452 * normalized URL with React-Router-specific implementation details removed
1453 * (`.data` suffixes, `index`/`_routes` search params).
1454 */
1455 url: URL;
1456 /**
1457 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
1458 * @example
1459 * // app/routes.ts
1460 * route("teams/:teamId", "./team.tsx"),
1461 *
1462 * // app/team.tsx
1463 * export function loader({
1464 * params,
1465 * }: Route.LoaderArgs) {
1466 * params.teamId;
1467 * // ^ string
1468 * }
1469 **/
1470 params: Params;
1471 /**
1472 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
1473 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
1474 */
1475 pattern: string;
1476 /**
1477 * Without `future.v8_middleware` enabled, this is the context passed in
1478 * to your server adapter's `getLoadContext` function. It's a way to bridge the
1479 * gap between the adapter's request/response API with your React Router app.
1480 * It is only applicable if you are using a custom server adapter.
1481 *
1482 * With `future.v8_middleware` enabled, this is an instance of
1483 * `RouterContextProvider` and can be used for type-safe access to
1484 * context value set in your route middlewares. If you are using a custom
1485 * server adapter, you may provide an initial set of context values from your
1486 * `getLoadContext` function.
1487 */
1488 context: MiddlewareEnabled extends true ? Readonly<RouterContextProvider> : AppLoadContext;
1489};
1490type SerializeFrom<T> = T extends (...args: infer Args) => unknown ? Args extends [
1491 ClientLoaderFunctionArgs | ClientActionFunctionArgs | ClientDataFunctionArgs<unknown>
1492] ? ClientDataFrom<T> : ServerDataFrom<T> : T;
1493type IsDefined<T> = Equal<T, undefined> extends true ? false : true;
1494type IsHydrate<ClientLoader> = ClientLoader extends {
1495 hydrate: true;
1496} ? true : ClientLoader extends {
1497 hydrate: false;
1498} ? false : false;
1499type GetLoaderData<T extends RouteModule$1> = _DataLoaderData<ServerDataFrom<T["loader"]>, ClientDataFrom<T["clientLoader"]>, IsHydrate<T["clientLoader"]>, T extends {
1500 HydrateFallback: Func;
1501} ? true : false>;
1502type _DataLoaderData<ServerLoaderData, ClientLoaderData, ClientLoaderHydrate extends boolean, HasHydrateFallback> = [
1503 HasHydrateFallback,
1504 ClientLoaderHydrate
1505] extends [true, true] ? IsDefined<ClientLoaderData> extends true ? ClientLoaderData : undefined : [
1506 IsDefined<ClientLoaderData>,
1507 IsDefined<ServerLoaderData>
1508] extends [true, true] ? ServerLoaderData | ClientLoaderData : IsDefined<ClientLoaderData> extends true ? ClientLoaderData : IsDefined<ServerLoaderData> extends true ? ServerLoaderData : undefined;
1509type GetActionData<T extends RouteModule$1> = _DataActionData<ServerDataFrom<T["action"]>, ClientDataFrom<T["clientAction"]>>;
1510type _DataActionData<ServerActionData, ClientActionData> = Awaited<[
1511 IsDefined<ServerActionData>,
1512 IsDefined<ClientActionData>
1513] extends [true, true] ? ServerActionData | ClientActionData : IsDefined<ClientActionData> extends true ? ClientActionData : IsDefined<ServerActionData> extends true ? ServerActionData : undefined>;
1514
1515interface RouteModules {
1516 [routeId: string]: RouteModule | undefined;
1517}
1518/**
1519 * The shape of a route module shipped to the client
1520 */
1521interface RouteModule {
1522 clientAction?: ClientActionFunction;
1523 clientLoader?: ClientLoaderFunction;
1524 clientMiddleware?: MiddlewareFunction<Record<string, DataStrategyResult>>[];
1525 ErrorBoundary?: ErrorBoundaryComponent;
1526 HydrateFallback?: HydrateFallbackComponent;
1527 Layout?: LayoutComponent;
1528 default: RouteComponent;
1529 handle?: RouteHandle;
1530 links?: LinksFunction;
1531 meta?: MetaFunction;
1532 shouldRevalidate?: ShouldRevalidateFunction;
1533}
1534/**
1535 * The shape of a route module on the server
1536 */
1537interface ServerRouteModule extends RouteModule {
1538 action?: ActionFunction;
1539 headers?: HeadersFunction | {
1540 [name: string]: string;
1541 };
1542 loader?: LoaderFunction;
1543 middleware?: MiddlewareFunction<Response>[];
1544}
1545/**
1546 * A function that handles data mutations for a route on the client
1547 */
1548type ClientActionFunction = (args: ClientActionFunctionArgs) => ReturnType<ActionFunction>;
1549/**
1550 * Arguments passed to a route `clientAction` function
1551 */
1552type ClientActionFunctionArgs = ActionFunctionArgs & {
1553 serverAction: <T = unknown>() => Promise<SerializeFrom<T>>;
1554};
1555/**
1556 * A function that loads data for a route on the client
1557 */
1558type ClientLoaderFunction = ((args: ClientLoaderFunctionArgs) => ReturnType<LoaderFunction>) & {
1559 hydrate?: boolean;
1560};
1561/**
1562 * Arguments passed to a route `clientLoader` function
1563 */
1564type ClientLoaderFunctionArgs = LoaderFunctionArgs & {
1565 serverLoader: <T = unknown>() => Promise<SerializeFrom<T>>;
1566};
1567/**
1568 * ErrorBoundary to display for this route
1569 */
1570type ErrorBoundaryComponent = ComponentType;
1571type HeadersArgs = {
1572 loaderHeaders: Headers;
1573 parentHeaders: Headers;
1574 actionHeaders: Headers;
1575 errorHeaders: Headers | undefined;
1576};
1577/**
1578 * A function that returns HTTP headers to be used for a route. These headers
1579 * will be merged with (and take precedence over) headers from parent routes.
1580 */
1581interface HeadersFunction {
1582 (args: HeadersArgs): Headers | HeadersInit;
1583}
1584/**
1585 * `<Route HydrateFallback>` component to render on initial loads
1586 * when client loaders are present
1587 */
1588type HydrateFallbackComponent = ComponentType;
1589/**
1590 * Optional, root-only `<Route Layout>` component to wrap the root content in.
1591 * Useful for defining the <html>/<head>/<body> document shell shared by the
1592 * Component, HydrateFallback, and ErrorBoundary
1593 */
1594type LayoutComponent = ComponentType<{
1595 children: ReactElement<unknown, ErrorBoundaryComponent | HydrateFallbackComponent | RouteComponent>;
1596}>;
1597/**
1598 * A function that defines `<link>` tags to be inserted into the `<head>` of
1599 * the document on route transitions.
1600 *
1601 * @see https://reactrouter.com/start/framework/route-module#meta
1602 */
1603interface LinksFunction {
1604 (): LinkDescriptor[];
1605}
1606interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
1607 id: RouteId;
1608 pathname: DataRouteMatch["pathname"];
1609 /** @deprecated Use `MetaMatch.loaderData` instead */
1610 data: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
1611 loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
1612 handle?: RouteHandle;
1613 params: DataRouteMatch["params"];
1614 meta: MetaDescriptor[];
1615 error?: unknown;
1616}
1617type MetaMatches<MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> = Array<{
1618 [K in keyof MatchLoaders]: MetaMatch<Exclude<K, number | symbol>, MatchLoaders[K]>;
1619}[keyof MatchLoaders]>;
1620interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
1621 /** @deprecated Use `MetaArgs.loaderData` instead */
1622 data: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
1623 loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
1624 params: Params;
1625 location: Location;
1626 matches: MetaMatches<MatchLoaders>;
1627 error?: unknown;
1628}
1629/**
1630 * A function that returns an array of data objects to use for rendering
1631 * metadata HTML tags in a route. These tags are not rendered on descendant
1632 * routes in the route hierarchy. In other words, they will only be rendered on
1633 * the route in which they are exported.
1634 *
1635 * @param Loader - The type of the current route's loader function
1636 * @param MatchLoaders - Mapping from a parent route's filepath to its loader
1637 * function type
1638 *
1639 * Note that parent route filepaths are relative to the `app/` directory.
1640 *
1641 * For example, if this meta function is for `/sales/customers/$customerId`:
1642 *
1643 * ```ts
1644 * // app/root.tsx
1645 * const loader = () => ({ hello: "world" })
1646 * export type Loader = typeof loader
1647 *
1648 * // app/routes/sales.tsx
1649 * const loader = () => ({ salesCount: 1074 })
1650 * export type Loader = typeof loader
1651 *
1652 * // app/routes/sales/customers.tsx
1653 * const loader = () => ({ customerCount: 74 })
1654 * export type Loader = typeof loader
1655 *
1656 * // app/routes/sales/customers/$customersId.tsx
1657 * import type { Loader as RootLoader } from "../../../root"
1658 * import type { Loader as SalesLoader } from "../../sales"
1659 * import type { Loader as CustomersLoader } from "../../sales/customers"
1660 *
1661 * const loader = () => ({ name: "Customer name" })
1662 *
1663 * const meta: MetaFunction<typeof loader, {
1664 * "root": RootLoader,
1665 * "routes/sales": SalesLoader,
1666 * "routes/sales/customers": CustomersLoader,
1667 * }> = ({ data, matches }) => {
1668 * const { name } = data
1669 * // ^? string
1670 * const { customerCount } = matches.find((match) => match.id === "routes/sales/customers").data
1671 * // ^? number
1672 * const { salesCount } = matches.find((match) => match.id === "routes/sales").data
1673 * // ^? number
1674 * const { hello } = matches.find((match) => match.id === "root").data
1675 * // ^? "world"
1676 * }
1677 * ```
1678 */
1679interface MetaFunction<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
1680 (args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;
1681}
1682type MetaDescriptor = {
1683 charSet: "utf-8";
1684} | {
1685 title: string;
1686} | {
1687 name: string;
1688 content: string;
1689} | {
1690 property: string;
1691 content: string;
1692} | {
1693 httpEquiv: string;
1694 content: string;
1695} | {
1696 "script:ld+json": LdJsonObject;
1697} | {
1698 tagName: "meta" | "link";
1699 [name: string]: string;
1700} | {
1701 [name: string]: unknown;
1702};
1703type LdJsonObject = {
1704 [Key in string]: LdJsonValue;
1705} & {
1706 [Key in string]?: LdJsonValue | undefined;
1707};
1708type LdJsonArray = LdJsonValue[] | readonly LdJsonValue[];
1709type LdJsonPrimitive = string | number | boolean | null;
1710type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
1711/**
1712 * A React component that is rendered for a route.
1713 */
1714type RouteComponent = ComponentType<{}>;
1715/**
1716 * An arbitrary object that is associated with a route.
1717 *
1718 * @see https://reactrouter.com/how-to/using-handle
1719 */
1720type RouteHandle = unknown;
1721
1722/**
1723 * An object of unknown type for route loaders and actions provided by the
1724 * server's `getLoadContext()` function. This is defined as an empty interface
1725 * specifically so apps can leverage declaration merging to augment this type
1726 * globally: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
1727 */
1728interface AppLoadContext {
1729 [key: string]: unknown;
1730}
1731
1732export { type Equal as $, type ActionFunction as A, type MiddlewareNextFunction as B, type ClientActionFunction as C, type DataRouteMatch as D, type ClientDataFunctionArgs as E, type FormEncType as F, type GetLoaderData as G, type HeadersFunction as H, type DataStrategyResult as I, type ServerDataFrom as J, type GetActionData as K, type Location as L, type MetaFunction as M, type Normalize as N, type RouteModules as O, type Params as P, type SerializeFrom as Q, type RouteModule$1 as R, type ShouldRevalidateFunction as S, type To as T, type UIMatch as U, type PathPattern as V, type PathMatch as W, type ParamParseKey as X, type InitialEntry as Y, type IndexRouteObject as Z, type NonIndexRouteObject as _, type ClientLoaderFunction as a, type ActionFunctionArgs as a0, type BaseRouteObject as a1, type DataStrategyFunctionArgs as a2, type DataStrategyMatch as a3, DataWithResponseInit as a4, type ErrorResponse as a5, type FormMethod as a6, type LazyRouteFunction as a7, type MiddlewareFunction as a8, type PatchRoutesOnNavigationFunctionArgs as a9, createBrowserHistory as aA, createHashHistory as aB, invariant as aC, ErrorResponseImpl as aD, type ServerRouteModule as aE, type TrackedPromise as aF, type PathParam as aa, type RedirectFunction as ab, type RouteMatch as ac, type RouterContext as ad, type ShouldRevalidateFunctionArgs as ae, createContext as af, createPath as ag, parsePath as ah, data as ai, generatePath as aj, isRouteErrorResponse as ak, matchPath as al, matchRoutes as am, redirect as an, redirectDocument as ao, replace as ap, resolvePath as aq, type ClientActionFunctionArgs as ar, type ClientLoaderFunctionArgs as as, type HeadersArgs as at, type MetaArgs as au, type PageLinkDescriptor as av, type HtmlLinkDescriptor as aw, type Future as ax, type unstable_SerializesTo as ay, createMemoryHistory 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 RouteBranch as o, type RouteManifest as p, type HTMLFormMethod as q, type Path as r, type LoaderFunctionArgs as s, type MiddlewareEnabled as t, type AppLoadContext as u, type LinkDescriptor as v, type Func as w, type Pretty as x, type MetaDescriptor as y, type ServerDataFunctionArgs as z };