UNPKG

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