UNPKG

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