UNPKG

100 kB TypeScript View Raw
1
2import * as React from "react";
3import { CookieParseOptions, CookieParseOptions as CookieParseOptions$1, CookieSerializeOptions, CookieSerializeOptions as CookieSerializeOptions$1 } from "cookie-es";
4import { BrowserRouter, Form, HashRouter, Link, Links, MemoryRouter, Meta, NavLink, Navigate, Outlet, Route, Router, RouterProvider, Routes, ScrollRestoration, StaticRouter, StaticRouterProvider, unstable_HistoryRouter } from "react-router/internal/react-server-client";
5import { ReactFormState } from "react-dom/client";
6
7//#region lib/router/history.d.ts
8/**
9 * Actions represent the type of change to a location value.
10 */
11declare enum Action {
12 /**
13 * A POP indicates a change to an arbitrary index in the history stack, such
14 * as a back or forward navigation. It does not describe the direction of the
15 * navigation, only that the current index changed.
16 *
17 * Note: This is the default action for newly created history objects.
18 */
19 Pop = "POP",
20 /**
21 * A PUSH indicates a new entry being added to the history stack, such as when
22 * a link is clicked and a new page loads. When this happens, all subsequent
23 * entries in the stack are lost.
24 */
25 Push = "PUSH",
26 /**
27 * A REPLACE indicates the entry at the current index in the history stack
28 * being replaced by a new one.
29 */
30 Replace = "REPLACE"
31}
32/**
33 * The pathname, search, and hash values of a URL.
34 */
35interface Path {
36 /**
37 * A URL pathname, beginning with a /.
38 */
39 pathname: string;
40 /**
41 * A URL search string, beginning with a ?.
42 */
43 search: string;
44 /**
45 * A URL fragment identifier, beginning with a #.
46 */
47 hash: string;
48}
49/**
50 * An entry in a history stack. A location contains information about the
51 * URL path, as well as possibly some arbitrary state and a key.
52 */
53interface Location<State = any> extends Path {
54 /**
55 * A value of arbitrary data associated with this location.
56 */
57 state: State;
58 /**
59 * A unique string associated with this location. May be used to safely store
60 * and retrieve data in some other storage API, like `localStorage`.
61 *
62 * Note: This value is always "default" on the initial location.
63 */
64 key: string;
65 /**
66 * The masked location displayed in the URL bar, which differs from the URL the
67 * router is operating on
68 */
69 mask?: Path;
70}
71/**
72 * A change to the current location.
73 */
74interface Update {
75 /**
76 * The action that triggered the change.
77 */
78 action: Action;
79 /**
80 * The new location.
81 */
82 location: Location;
83 /**
84 * The delta between this location and the former location in the history stack
85 */
86 delta: number | null;
87}
88/**
89 * A function that receives notifications about location changes.
90 */
91interface Listener {
92 (update: Update): void;
93}
94/**
95 * Describes a location that is the destination of some navigation used in
96 * {@link Link}, {@link useNavigate}, etc.
97 */
98type To = string | Partial<Path>;
99/**
100 * A history is an interface to the navigation stack. The history serves as the
101 * source of truth for the current location, as well as provides a set of
102 * methods that may be used to change it.
103 *
104 * It is similar to the DOM's `window.history` object, but with a smaller, more
105 * focused API.
106 */
107interface History {
108 /**
109 * The last action that modified the current location. This will always be
110 * Action.Pop when a history instance is first created. This value is mutable.
111 */
112 readonly action: Action;
113 /**
114 * The current location. This value is mutable.
115 */
116 readonly location: Location;
117 /**
118 * Returns a valid href for the given `to` value that may be used as
119 * the value of an <a href> attribute.
120 *
121 * @param to - The destination URL
122 */
123 createHref(to: To): string;
124 /**
125 * Returns a URL for the given `to` value
126 *
127 * @param to - The destination URL
128 */
129 createURL(to: To): URL;
130 /**
131 * Encode a location the same way window.history would do (no-op for memory
132 * history) so we ensure our PUSH/REPLACE navigations for data routers
133 * behave the same as POP
134 *
135 * @param to Unencoded path
136 */
137 encodeLocation(to: To): Path;
138 /**
139 * Pushes a new location onto the history stack, increasing its length by one.
140 * If there were any entries in the stack after the current one, they are
141 * lost.
142 *
143 * @param to - The new URL
144 * @param state - Data to associate with the new location
145 */
146 push(to: To, state?: any): void;
147 /**
148 * Replaces the current location in the history stack with a new one. The
149 * location that was replaced will no longer be available.
150 *
151 * @param to - The new URL
152 * @param state - Data to associate with the new location
153 */
154 replace(to: To, state?: any): void;
155 /**
156 * Navigates `n` entries backward/forward in the history stack relative to the
157 * current index. For example, a "back" navigation would use go(-1).
158 *
159 * @param delta - The delta in the stack index
160 */
161 go(delta: number): void;
162 /**
163 * Sets up a listener that will be called whenever the current location
164 * changes.
165 *
166 * @param listener - A function that will be called when the location changes
167 * @returns unlisten - A function that may be used to stop listening
168 */
169 listen(listener: Listener): () => void;
170}
171//#endregion
172//#region lib/router/utils.d.ts
173type MaybePromise<T> = T | Promise<T>;
174/**
175 * Map of routeId -> data returned from a loader/action/error
176 */
177interface RouteData {
178 [routeId: string]: any;
179}
180type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete";
181type UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;
182/**
183 * Users can specify either lowercase or uppercase form methods on `<Form>`,
184 * useSubmit(), `<fetcher.Form>`, etc.
185 */
186type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;
187/**
188 * Active navigation/fetcher form methods are exposed in uppercase on the
189 * RouterState. This is to align with the normalization done via fetch().
190 */
191type FormMethod = UpperCaseFormMethod;
192type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data" | "application/json" | "text/plain";
193type JsonObject = { [Key in string]: JsonValue } & { [Key in string]?: JsonValue | undefined };
194type JsonArray = JsonValue[] | readonly JsonValue[];
195type JsonPrimitive = string | number | boolean | null;
196type JsonValue = JsonPrimitive | JsonObject | JsonArray;
197/**
198 * @private
199 * Internal interface to pass around for action submissions, not intended for
200 * external consumption
201 */
202type Submission = {
203 formMethod: FormMethod;
204 formAction: string;
205 formEncType: FormEncType;
206 formData: FormData;
207 json: undefined;
208 text: undefined;
209} | {
210 formMethod: FormMethod;
211 formAction: string;
212 formEncType: FormEncType;
213 formData: undefined;
214 json: JsonValue;
215 text: undefined;
216} | {
217 formMethod: FormMethod;
218 formAction: string;
219 formEncType: FormEncType;
220 formData: undefined;
221 json: undefined;
222 text: string;
223};
224/**
225 * A context instance used as the key for the `get`/`set` methods of a
226 * {@link RouterContextProvider}. Accepts an optional default
227 * value to be returned if no value has been set.
228 */
229interface RouterContext<T = unknown> {
230 defaultValue?: T;
231}
232/**
233 * Creates a type-safe {@link RouterContext} object that can be used to
234 * store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
235 * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
236 * Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
237 * but specifically designed for React Router's request/response lifecycle.
238 *
239 * If a `defaultValue` is provided, it will be returned from `context.get()`
240 * when no value has been set for the context. Otherwise, reading this context
241 * when no value has been set will throw an error.
242 *
243 * ```tsx filename=app/context.ts
244 * import { createContext } from "react-router";
245 *
246 * // Create a context for user data
247 * export const userContext =
248 * createContext<User | null>(null);
249 * ```
250 *
251 * ```tsx filename=app/middleware/auth.ts
252 * import { getUserFromSession } from "~/auth.server";
253 * import { userContext } from "~/context";
254 *
255 * export const authMiddleware = async ({
256 * context,
257 * request,
258 * }) => {
259 * const user = await getUserFromSession(request);
260 * context.set(userContext, user);
261 * };
262 * ```
263 *
264 * ```tsx filename=app/routes/profile.tsx
265 * import { userContext } from "~/context";
266 *
267 * export async function loader({
268 * context,
269 * }: Route.LoaderArgs) {
270 * const user = context.get(userContext);
271 *
272 * if (!user) {
273 * throw new Response("Unauthorized", { status: 401 });
274 * }
275 *
276 * return { user };
277 * }
278 * ```
279 *
280 * @public
281 * @category Utils
282 * @mode framework
283 * @mode data
284 * @param defaultValue An optional default value for the context. This value
285 * will be returned if no value has been set for this context.
286 * @returns A {@link RouterContext} object that can be used with
287 * `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
288 * [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
289 */
290declare function createContext<T>(defaultValue?: T): RouterContext<T>;
291/**
292 * Provides methods for writing/reading values in application context in a
293 * type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
294 *
295 * @example
296 * import {
297 * createContext,
298 * RouterContextProvider
299 * } from "react-router";
300 *
301 * const userContext = createContext<User | null>(null);
302 * const contextProvider = new RouterContextProvider();
303 * contextProvider.set(userContext, getUser());
304 * // ^ Type-safe
305 * const user = contextProvider.get(userContext);
306 * // ^ User
307 *
308 * @public
309 * @category Utils
310 * @mode framework
311 * @mode data
312 */
313declare class RouterContextProvider {
314 #private;
315 /**
316 * Create a new `RouterContextProvider` instance
317 * @param init An optional initial context map to populate the provider with
318 */
319 constructor(init?: Map<RouterContext, unknown>);
320 /**
321 * Access a value from the context. If no value has been set for the context,
322 * it will return the context's `defaultValue` if provided, or throw an error
323 * if no `defaultValue` was set.
324 * @param context The context to get the value for
325 * @returns The value for the context, or the context's `defaultValue` if no
326 * value was set
327 */
328 get<T>(context: RouterContext<T>): T;
329 /**
330 * Set a value for the context. If the context already has a value set, this
331 * will overwrite it.
332 *
333 * @param context The context to set the value for
334 * @param value The value to set for the context
335 * @returns {void}
336 */
337 set<C extends RouterContext>(context: C, value: C extends RouterContext<infer T> ? T : never): void;
338}
339type DefaultContext = Readonly<RouterContextProvider>;
340/**
341 * @private
342 * Arguments passed to route loader/action functions. Same for now but we keep
343 * this as a private implementation detail in case they diverge in the future.
344 */
345interface DataFunctionArgs<Context> {
346 /** 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. */
347 request: Request;
348 /**
349 * A URL instance representing the application location being navigated to or
350 * fetched.
351 *
352 * In Framework mode, this is a normalized URL with React-Router-specific
353 * implementation details removed (`.data` suffixes, `index`/`_routes` search
354 * params). For the raw incoming URL, use `request.url`.
355 */
356 url: URL;
357 /**
358 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
359 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
360 */
361 pattern: string;
362 /**
363 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
364 * @example
365 * // app/routes.ts
366 * route("teams/:teamId", "./team.tsx"),
367 *
368 * // app/team.tsx
369 * export function loader({
370 * params,
371 * }: Route.LoaderArgs) {
372 * params.teamId;
373 * // ^ string
374 * }
375 */
376 params: Params;
377 /**
378 * This is the context passed in to your server adapter's getLoadContext() function.
379 * It's a way to bridge the gap between the adapter's request/response API with your React Router app.
380 * It is only applicable if you are using a custom server adapter.
381 */
382 context: Context;
383}
384/**
385 * Route middleware `next` function to call downstream handlers and then complete
386 * middlewares from the bottom-up
387 */
388interface MiddlewareNextFunction<Result = unknown> {
389 (): Promise<Result>;
390}
391/**
392 * Route middleware function signature. Receives the same "data" arguments as a
393 * `loader`/`action` (`request`, `params`, `context`) as the first parameter and
394 * a `next` function as the second parameter which will call downstream handlers
395 * and then complete middlewares from the bottom-up
396 */
397type MiddlewareFunction<Result = unknown> = (args: DataFunctionArgs<Readonly<RouterContextProvider>>, next: MiddlewareNextFunction<Result>) => MaybePromise<Result | void>;
398/**
399 * Arguments passed to loader functions
400 */
401interface LoaderFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {}
402/**
403 * Arguments passed to action functions
404 */
405interface ActionFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {}
406/**
407 * Loaders and actions can return anything
408 */
409type DataFunctionValue = unknown;
410type DataFunctionReturnValue = MaybePromise<DataFunctionValue>;
411/**
412 * Route loader function signature
413 */
414type LoaderFunction<Context = DefaultContext> = {
415 (args: LoaderFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
416} & {
417 hydrate?: boolean;
418};
419/**
420 * Route action function signature
421 */
422interface ActionFunction<Context = DefaultContext> {
423 (args: ActionFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
424}
425/**
426 * Arguments passed to shouldRevalidate function
427 */
428interface ShouldRevalidateFunctionArgs {
429 /** 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. */
430 currentUrl: URL;
431 /** 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. */
432 currentParams: DataRouteMatch["params"];
433 /** 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. */
434 nextUrl: URL;
435 /** 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. */
436 nextParams: DataRouteMatch["params"];
437 /** The method (probably `"GET"` or `"POST"`) used in the form submission that triggered the revalidation. */
438 formMethod?: Submission["formMethod"];
439 /** The form action (`<Form action="/somewhere">`) that triggered the revalidation. */
440 formAction?: Submission["formAction"];
441 /** The form encType (`<Form encType="application/x-www-form-urlencoded">) used in the form submission that triggered the revalidation*/
442 formEncType?: Submission["formEncType"];
443 /** The form submission data when the form's encType is `text/plain` */
444 text?: Submission["text"];
445 /** The form submission data when the form's encType is `application/x-www-form-urlencoded` or `multipart/form-data` */
446 formData?: Submission["formData"];
447 /** The form submission data when the form's encType is `application/json` */
448 json?: Submission["json"];
449 /** The status code of the action response */
450 actionStatus?: number;
451 /**
452 * 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.
453 *
454 * @example
455 * export async function action() {
456 * await saveSomeStuff();
457 * return { ok: true };
458 * }
459 *
460 * export function shouldRevalidate({
461 * actionResult,
462 * }) {
463 * if (actionResult?.ok) {
464 * return false;
465 * }
466 * return true;
467 * }
468 */
469 actionResult?: any;
470 /**
471 * 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:
472 *
473 * /projects/123/tasks/abc
474 * /projects/123/tasks/def
475 * React Router will only call the loader for tasks/def because the param for projects/123 didn't change.
476 *
477 * 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.
478 */
479 defaultShouldRevalidate: boolean;
480}
481/**
482 * Route shouldRevalidate function signature. This runs after any submission
483 * (navigation or fetcher), so we flatten the navigation/fetcher submission
484 * onto the arguments. It shouldn't matter whether it came from a navigation
485 * or a fetcher, what really matters is the URLs and the formData since loaders
486 * have to re-run based on the data models that were potentially mutated.
487 */
488interface ShouldRevalidateFunction {
489 (args: ShouldRevalidateFunctionArgs): boolean;
490}
491interface DataStrategyMatch extends RouteMatch<string, DataRouteObject> {
492 /**
493 * @private
494 */
495 _lazyPromises?: {
496 middleware: Promise<void> | undefined;
497 handler: Promise<void> | undefined;
498 route: Promise<void> | undefined;
499 };
500 /**
501 * @deprecated Deprecated in favor of `shouldCallHandler`
502 *
503 * A boolean value indicating whether this route handler should be called in
504 * this pass.
505 *
506 * The `matches` array always includes _all_ matched routes even when only
507 * _some_ route handlers need to be called so that things like middleware can
508 * be implemented.
509 *
510 * `shouldLoad` is usually only interesting if you are skipping the route
511 * handler entirely and implementing custom handler logic - since it lets you
512 * determine if that custom logic should run for this route or not.
513 *
514 * For example:
515 * - If you are on `/parent/child/a` and you navigate to `/parent/child/b` -
516 * you'll get an array of three matches (`[parent, child, b]`), but only `b`
517 * will have `shouldLoad=true` because the data for `parent` and `child` is
518 * already loaded
519 * - If you are on `/parent/child/a` and you submit to `a`'s [`action`](https://reactrouter.com/docs/start/data/route-object#action),
520 * then only `a` will have `shouldLoad=true` for the action execution of
521 * `dataStrategy`
522 * - After the [`action`](https://reactrouter.com/docs/start/data/route-object#action),
523 * `dataStrategy` will be called again for the [`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
524 * revalidation, and all matches will have `shouldLoad=true` (assuming no
525 * custom `shouldRevalidate` implementations)
526 */
527 shouldLoad: boolean;
528 /**
529 * Arguments passed to the `shouldRevalidate` function for this `loader` execution.
530 * Will be `null` if this is not a revalidating loader {@link DataStrategyMatch}.
531 */
532 shouldRevalidateArgs: ShouldRevalidateFunctionArgs | null;
533 /**
534 * Determine if this route's handler should be called during this `dataStrategy`
535 * execution. Calling it with no arguments will leverage the default revalidation
536 * behavior. You can pass your own `defaultShouldRevalidate` value if you wish
537 * to change the default revalidation behavior with your `dataStrategy`.
538 *
539 * @param defaultShouldRevalidate `defaultShouldRevalidate` override value (optional)
540 */
541 shouldCallHandler(defaultShouldRevalidate?: boolean): boolean;
542 /**
543 * An async function that will resolve any `route.lazy` implementations and
544 * execute the route's handler (if necessary), returning a {@link DataStrategyResult}
545 *
546 * - Calling `match.resolve` does not mean you're calling the
547 * [`action`](https://reactrouter.com/docs/start/data/route-object#action)/[`loader`](https://reactrouter.com/docs/start/data/route-object#loader)
548 * (the "handler") - `resolve` will only call the `handler` internally if
549 * needed _and_ if you don't pass your own `handlerOverride` function parameter
550 * - It is safe to call `match.resolve` for all matches, even if they have
551 * `shouldLoad=false`, and it will no-op if no loading is required
552 * - You should generally always call `match.resolve()` for `shouldLoad:true`
553 * routes to ensure that any `route.lazy` implementations are processed
554 * - See the examples below for how to implement custom handler execution via
555 * `match.resolve`
556 */
557 resolve: (handlerOverride?: (handler: (ctx?: unknown) => DataFunctionReturnValue) => DataFunctionReturnValue) => Promise<DataStrategyResult>;
558}
559interface DataStrategyFunctionArgs<Context = DefaultContext> extends DataFunctionArgs<Context> {
560 /**
561 * Matches for this route extended with Data strategy APIs
562 */
563 matches: DataStrategyMatch[];
564 runClientMiddleware: (cb: DataStrategyFunction<Context>) => Promise<Record<string, DataStrategyResult>>;
565 /**
566 * The key of the fetcher we are calling `dataStrategy` for, otherwise `null`
567 * for navigational executions
568 */
569 fetcherKey: string | null;
570}
571/**
572 * Result from a loader or action called via dataStrategy
573 */
574interface DataStrategyResult {
575 type: "data" | "error";
576 result: unknown;
577}
578interface DataStrategyFunction<Context = DefaultContext> {
579 (args: DataStrategyFunctionArgs<Context>): Promise<Record<string, DataStrategyResult>>;
580}
581type PatchRoutesOnNavigationFunctionArgs = {
582 signal: AbortSignal;
583 path: string;
584 matches: RouteMatch[];
585 fetcherKey: string | undefined;
586 patch: (routeId: string | null, children: RouteObject[]) => void;
587};
588type PatchRoutesOnNavigationFunction = (opts: PatchRoutesOnNavigationFunctionArgs) => MaybePromise<void>;
589/**
590 * Function provided to set route-specific properties from route objects
591 */
592interface MapRoutePropertiesFunction {
593 (route: DataRouteObject): Partial<DataRouteObject>;
594}
595/**
596 * Keys we cannot change from within a lazy object. We spread all other keys
597 * onto the route. Either they're meaningful to the router, or they'll get
598 * ignored.
599 */
600type UnsupportedLazyRouteObjectKey = "lazy" | "caseSensitive" | "path" | "id" | "index" | "children";
601/**
602 * Keys we cannot change from within a lazy() function. We spread all other keys
603 * onto the route. Either they're meaningful to the router, or they'll get
604 * ignored.
605 */
606type UnsupportedLazyRouteFunctionKey = UnsupportedLazyRouteObjectKey | "middleware";
607/**
608 * lazy object to load route properties, which can add non-matching
609 * related properties to a route
610 */
611type LazyRouteObject<R extends RouteObject> = { [K in keyof R as K extends UnsupportedLazyRouteObjectKey ? never : K]?: () => Promise<R[K] | null | undefined> };
612/**
613 * lazy() function to load a route definition, which can add non-matching
614 * related properties to a route
615 */
616interface LazyRouteFunction<R extends RouteObject> {
617 (): Promise<Omit<R, UnsupportedLazyRouteFunctionKey> & Partial<Record<UnsupportedLazyRouteFunctionKey, never>>>;
618}
619type LazyRouteDefinition<R extends RouteObject> = LazyRouteObject<R> | LazyRouteFunction<R>;
620/**
621 * Base RouteObject with common props shared by all types of routes
622 * @internal
623 */
624type BaseRouteObject = {
625 /**
626 * Whether the path should be case-sensitive. Defaults to `false`.
627 */
628 caseSensitive?: boolean;
629 /**
630 * The path pattern to match. If unspecified or empty, then this becomes a
631 * layout route.
632 */
633 path?: string;
634 /**
635 * The unique identifier for this route (for use with {@link DataRouter}s)
636 */
637 id?: string;
638 /**
639 * The route middleware.
640 * See [`middleware`](../../start/data/route-object#middleware).
641 */
642 middleware?: MiddlewareFunction[];
643 /**
644 * The route loader.
645 * See [`loader`](../../start/data/route-object#loader).
646 */
647 loader?: LoaderFunction | boolean;
648 /**
649 * The route action.
650 * See [`action`](../../start/data/route-object#action).
651 */
652 action?: ActionFunction | boolean;
653 /**
654 * The route shouldRevalidate function.
655 * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
656 */
657 shouldRevalidate?: ShouldRevalidateFunction;
658 /**
659 * The route handle.
660 */
661 handle?: any;
662 /**
663 * A function that returns a promise that resolves to the route object.
664 * Used for code-splitting routes.
665 * See [`lazy`](../../start/data/route-object#lazy).
666 */
667 lazy?: LazyRouteDefinition<BaseRouteObject>;
668 /**
669 * The React Component to render when this route matches.
670 * Mutually exclusive with `element`.
671 */
672 Component?: React.ComponentType | null;
673 /**
674 * The React element to render when this Route matches.
675 * Mutually exclusive with `Component`.
676 */
677 element?: React.ReactNode | null;
678 /**
679 * The React Component to render at this route if an error occurs.
680 * Mutually exclusive with `errorElement`.
681 */
682 ErrorBoundary?: React.ComponentType | null;
683 /**
684 * The React element to render at this route if an error occurs.
685 * Mutually exclusive with `ErrorBoundary`.
686 */
687 errorElement?: React.ReactNode | null;
688 /**
689 * The React Component to render while this router is loading data.
690 * Mutually exclusive with `hydrateFallbackElement`.
691 */
692 HydrateFallback?: React.ComponentType | null;
693 /**
694 * The React element to render while this router is loading data.
695 * Mutually exclusive with `HydrateFallback`.
696 */
697 hydrateFallbackElement?: React.ReactNode | null;
698};
699/**
700 * Index routes must not have children
701 */
702type IndexRouteObject = BaseRouteObject & {
703 /**
704 * Child Route objects - not valid on index routes.
705 */
706 children?: undefined;
707 /**
708 * Whether this is an index route.
709 */
710 index: true;
711};
712/**
713 * Non-index routes may have children, but cannot have `index` set to `true`.
714 */
715type NonIndexRouteObject = BaseRouteObject & {
716 /**
717 * Child Route objects.
718 */
719 children?: RouteObject[];
720 /**
721 * Whether this is an index route - must be `false` or undefined on non-index routes.
722 */
723 index?: false;
724};
725/**
726 * A route object represents a logical route, with (optionally) its child
727 * routes organized in a tree-like structure.
728 */
729type RouteObject = IndexRouteObject | NonIndexRouteObject;
730type DataIndexRouteObject = IndexRouteObject & {
731 id: string;
732};
733type DataNonIndexRouteObject = NonIndexRouteObject & {
734 children?: DataRouteObject[];
735 id: string;
736};
737/**
738 * A data route object, which is just a RouteObject with a required unique ID
739 */
740type DataRouteObject = DataIndexRouteObject | DataNonIndexRouteObject;
741type RouteManifest<R = DataRouteObject> = Record<string, R | undefined>;
742/**
743 * The parameters that were parsed from the URL path.
744 */
745type Params<Key extends string = string> = { readonly [key in Key]: string | undefined };
746/**
747 * A RouteMatch contains info about how a route matched a URL.
748 */
749interface RouteMatch<ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> {
750 /**
751 * The names and values of dynamic parameters in the URL.
752 */
753 params: Params<ParamKey>;
754 /**
755 * The portion of the URL pathname that was matched.
756 */
757 pathname: string;
758 /**
759 * The portion of the URL pathname that was matched before child routes.
760 */
761 pathnameBase: string;
762 /**
763 * The route object that was used to match.
764 */
765 route: RouteObjectType;
766}
767interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}
768/**
769 * Matches the given routes to a location and returns the match data.
770 *
771 * @example
772 * import { matchRoutes } from "react-router";
773 *
774 * let routes = [{
775 * path: "/",
776 * Component: Root,
777 * children: [{
778 * path: "dashboard",
779 * Component: Dashboard,
780 * }]
781 * }];
782 *
783 * matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
784 *
785 * @public
786 * @category Utils
787 * @param routes The array of route objects to match against.
788 * @param locationArg The location to match against, either a string path or a
789 * partial {@link Location} object
790 * @param basename Optional base path to strip from the location before matching.
791 * Defaults to `/`.
792 * @returns An array of matched routes, or `null` if no matches were found.
793 */
794declare function matchRoutes<RouteObjectType extends RouteObject = RouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): RouteMatch<string, RouteObjectType>[] | null;
795interface UIMatch<Data = unknown, Handle = unknown> {
796 id: string;
797 pathname: string;
798 /**
799 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the matched route.
800 */
801 params: RouteMatch["params"];
802 /**
803 * The return value from the matched route's loader or clientLoader. This might
804 * be `undefined` if this route's `loader` (or a deeper route's `loader`) threw
805 * an error and we're currently displaying an `ErrorBoundary`.
806 */
807 loaderData: Data | undefined;
808 /**
809 * The {@link https://reactrouter.com/start/framework/route-module#handle handle object}
810 * exported from the matched route module
811 */
812 handle: Handle;
813}
814interface RouteMeta<RouteObjectType extends RouteObject = RouteObject> {
815 relativePath: string;
816 caseSensitive: boolean;
817 childrenIndex: number;
818 route: RouteObjectType;
819 matcher?: RegExp;
820 compiledParams?: CompiledPathParam[];
821}
822/**
823 * @private
824 * PRIVATE - DO NOT USE
825 *
826 * A "branch" of routes that match a given route pattern.
827 * This is an internal interface not intended for direct external usage.
828 */
829interface RouteBranch<RouteObjectType extends RouteObject = RouteObject> {
830 path: string;
831 score: number;
832 routesMeta: RouteMeta<RouteObjectType>[];
833}
834type CompiledPathParam = {
835 paramName: string;
836 isOptional?: boolean;
837};
838declare class DataWithResponseInit<D> {
839 type: string;
840 data: D;
841 init: ResponseInit | null;
842 constructor(data: D, init?: ResponseInit);
843}
844/**
845 * Create "responses" that contain `headers`/`status` without forcing
846 * serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
847 *
848 * @example
849 * import { data } from "react-router";
850 *
851 * export async function action({ request }: Route.ActionArgs) {
852 * let formData = await request.formData();
853 * let item = await createItem(formData);
854 * return data(item, {
855 * headers: { "X-Custom-Header": "value" }
856 * status: 201,
857 * });
858 * }
859 *
860 * @public
861 * @category Utils
862 * @mode framework
863 * @mode data
864 * @param data The data to be included in the response.
865 * @param init The status code or a `ResponseInit` object to be included in the
866 * response.
867 * @returns A {@link DataWithResponseInit} instance containing the data and
868 * response init.
869 */
870declare function data<D>(data: D, init?: number | ResponseInit): DataWithResponseInit<D>;
871type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
872/**
873 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
874 * Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
875 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
876 *
877 * This utility accepts absolute URLs and can navigate to external domains, so
878 * the application should validate any user-supplied inputs to redirects.
879 *
880 * @example
881 * import { redirect } from "react-router";
882 *
883 * export async function loader({ request }: Route.LoaderArgs) {
884 * if (!isLoggedIn(request))
885 * throw redirect("/login");
886 * }
887 *
888 * // ...
889 * }
890 *
891 * @public
892 * @category Utils
893 * @mode framework
894 * @mode data
895 * @param url The URL to redirect to.
896 * @param init The status code or a `ResponseInit` object to be included in the
897 * response.
898 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
899 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
900 * header.
901 */
902declare const redirect$1: RedirectFunction;
903/**
904 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
905 * that will force a document reload to the new location. Sets the status code
906 * and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
907 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
908 *
909 * This utility accepts absolute URLs and can navigate to external domains, so
910 * the application should validate any user-supplied inputs to redirects.
911 *
912 * ```tsx filename=routes/logout.tsx
913 * import { redirectDocument } from "react-router";
914 *
915 * import { destroySession } from "../sessions.server";
916 *
917 * export async function action({ request }: Route.ActionArgs) {
918 * let session = await getSession(request.headers.get("Cookie"));
919 * return redirectDocument("/", {
920 * headers: { "Set-Cookie": await destroySession(session) }
921 * });
922 * }
923 * ```
924 *
925 * @public
926 * @category Utils
927 * @mode framework
928 * @mode data
929 * @param url The URL to redirect to.
930 * @param init The status code or a `ResponseInit` object to be included in the
931 * response.
932 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
933 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
934 * header.
935 */
936declare const redirectDocument$1: RedirectFunction;
937/**
938 * A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
939 * that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
940 * instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
941 * for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
942 * header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
943 *
944 * @example
945 * import { replace } from "react-router";
946 *
947 * export async function loader() {
948 * return replace("/new-location");
949 * }
950 *
951 * @public
952 * @category Utils
953 * @mode framework
954 * @mode data
955 * @param url The URL to redirect to.
956 * @param init The status code or a `ResponseInit` object to be included in the
957 * response.
958 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
959 * object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
960 * header.
961 */
962declare const replace$2: RedirectFunction;
963type ErrorResponse = {
964 status: number;
965 statusText: string;
966 data: any;
967};
968/**
969 * Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
970 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
971 * thrown from an [`action`](../../start/framework/route-module#action) or
972 * [`loader`](../../start/framework/route-module#loader) function.
973 *
974 * @example
975 * import { isRouteErrorResponse } from "react-router";
976 *
977 * export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
978 * if (isRouteErrorResponse(error)) {
979 * return (
980 * <>
981 * <p>Error: `${error.status}: ${error.statusText}`</p>
982 * <p>{error.data}</p>
983 * </>
984 * );
985 * }
986 *
987 * return (
988 * <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
989 * );
990 * }
991 *
992 * @public
993 * @category Utils
994 * @mode framework
995 * @mode data
996 * @param error The error to check.
997 * @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
998 */
999declare function isRouteErrorResponse(error: any): error is ErrorResponse;
1000//#endregion
1001//#region lib/router/instrumentation.d.ts
1002type ServerInstrumentation = {
1003 handler?: InstrumentRequestHandlerFunction;
1004 route?: InstrumentRouteFunction;
1005};
1006type ClientInstrumentation = {
1007 router?: InstrumentRouterFunction;
1008 route?: InstrumentRouteFunction;
1009};
1010type InstrumentRequestHandlerFunction = (handler: InstrumentableRequestHandler) => void;
1011type InstrumentRouterFunction = (router: InstrumentableRouter) => void;
1012type InstrumentRouteFunction = (route: InstrumentableRoute) => void;
1013/**
1014 * Route metadata available after React Router has matched an instrumented
1015 * request, navigation, or fetcher call.
1016 */
1017type InstrumentationResultMeta = {
1018 url: LoaderFunctionArgs["url"];
1019 pattern: string;
1020 params: LoaderFunctionArgs["params"];
1021};
1022/**
1023 * Result returned by route-level instrumented handler calls, such as
1024 * instrumented loaders, actions, middleware, and lazy route functions.
1025 */
1026type InstrumentationHandlerResult = {
1027 status: "success";
1028 error: undefined;
1029} | {
1030 status: "error";
1031 error: Error;
1032};
1033/**
1034 * Result returned by client-side router instrumented navigation and fetcher
1035 * calls.
1036 */
1037type InstrumentationClientRouterResult = InstrumentationHandlerResult & {
1038 meta: InstrumentationResultMeta | undefined;
1039};
1040/**
1041 * Result returned by server request handler instrumentation.
1042 */
1043type InstrumentationServerHandlerResult = InstrumentationHandlerResult & {
1044 statusCode: number;
1045 meta: InstrumentationResultMeta | undefined;
1046};
1047type InstrumentFunction<T, TInnerResult = InstrumentationHandlerResult> = (handler: () => Promise<TInnerResult>, info: T) => Promise<void>;
1048type ReadonlyRequest = {
1049 method: string;
1050 url: string;
1051 headers: Pick<Headers, "get">;
1052};
1053type ReadonlyContext = Pick<RouterContextProvider, "get">;
1054type InstrumentableRoute = {
1055 id: string;
1056 index: boolean | undefined;
1057 path: string | undefined;
1058 instrument(instrumentations: RouteInstrumentations): void;
1059};
1060type RouteInstrumentations = {
1061 lazy?: InstrumentFunction<RouteLazyInstrumentationInfo>;
1062 "lazy.loader"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
1063 "lazy.action"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
1064 "lazy.middleware"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
1065 middleware?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
1066 loader?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
1067 action?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
1068};
1069type RouteLazyInstrumentationInfo = undefined;
1070type RouteHandlerInstrumentationInfo = Readonly<Omit<LoaderFunctionArgs, "request" | "context"> & {
1071 request: ReadonlyRequest;
1072 context: ReadonlyContext;
1073}>;
1074type InstrumentableRouter = {
1075 instrument(instrumentations: RouterInstrumentations): void;
1076};
1077type RouterInstrumentations = {
1078 navigate?: InstrumentFunction<RouterNavigationInstrumentationInfo, InstrumentationClientRouterResult>;
1079 fetch?: InstrumentFunction<RouterFetchInstrumentationInfo, InstrumentationClientRouterResult>;
1080};
1081type RouterNavigationInstrumentationInfo = Readonly<{
1082 to: string | number;
1083 currentUrl: string;
1084 formMethod?: HTMLFormMethod;
1085 formEncType?: FormEncType;
1086 formData?: FormData;
1087 body?: any;
1088}>;
1089type RouterFetchInstrumentationInfo = Readonly<{
1090 href: string;
1091 currentUrl: string;
1092 fetcherKey: string;
1093 formMethod?: HTMLFormMethod;
1094 formEncType?: FormEncType;
1095 formData?: FormData;
1096 body?: any;
1097}>;
1098type InstrumentableRequestHandler = {
1099 instrument(instrumentations: RequestHandlerInstrumentations): void;
1100};
1101type RequestHandlerInstrumentations = {
1102 request?: InstrumentFunction<RequestHandlerInstrumentationInfo, InstrumentationServerHandlerResult>;
1103};
1104type RequestHandlerInstrumentationInfo = Readonly<{
1105 request: ReadonlyRequest;
1106 context: ReadonlyContext | undefined;
1107}>;
1108//#endregion
1109//#region lib/router/router.d.ts
1110/**
1111 * A Router instance manages all navigation and data loading/mutations
1112 */
1113interface Router$1 {
1114 /**
1115 * @private
1116 * PRIVATE - DO NOT USE
1117 *
1118 * Return the basename for the router
1119 */
1120 get basename(): RouterInit["basename"];
1121 /**
1122 * @private
1123 * PRIVATE - DO NOT USE
1124 *
1125 * Return the future config for the router
1126 */
1127 get future(): FutureConfig;
1128 /**
1129 * @private
1130 * PRIVATE - DO NOT USE
1131 *
1132 * Return the current state of the router
1133 */
1134 get state(): RouterState;
1135 /**
1136 * @private
1137 * PRIVATE - DO NOT USE
1138 *
1139 * Return the routes for this router instance
1140 */
1141 get routes(): DataRouteObject[];
1142 /**
1143 * @private
1144 * PRIVATE - DO NOT USE
1145 *
1146 * Return the route branches for this router instance
1147 */
1148 get branches(): RouteBranch<DataRouteObject>[] | undefined;
1149 /**
1150 * @private
1151 * PRIVATE - DO NOT USE
1152 *
1153 * Return the manifest for this router instance
1154 */
1155 get manifest(): RouteManifest;
1156 /**
1157 * @private
1158 * PRIVATE - DO NOT USE
1159 *
1160 * Return the window associated with the router
1161 */
1162 get window(): RouterInit["window"];
1163 /**
1164 * @private
1165 * PRIVATE - DO NOT USE
1166 *
1167 * Initialize the router, including adding history listeners and kicking off
1168 * initial data fetches. Returns a function to cleanup listeners and abort
1169 * any in-progress loads
1170 */
1171 initialize(): Router$1;
1172 /**
1173 * @private
1174 * PRIVATE - DO NOT USE
1175 *
1176 * Subscribe to router.state updates
1177 *
1178 * @param fn function to call with the new state
1179 */
1180 subscribe(fn: RouterSubscriber): () => void;
1181 /**
1182 * @private
1183 * PRIVATE - DO NOT USE
1184 *
1185 * Enable scroll restoration behavior in the router
1186 *
1187 * @param savedScrollPositions Object that will manage positions, in case
1188 * it's being restored from sessionStorage
1189 * @param getScrollPosition Function to get the active Y scroll position
1190 * @param getKey Function to get the key to use for restoration
1191 */
1192 enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
1193 /**
1194 * @private
1195 * PRIVATE - DO NOT USE
1196 *
1197 * Navigate forward/backward in the history stack
1198 * @param to Delta to move in the history stack
1199 */
1200 navigate(to: number): Promise<void>;
1201 /**
1202 * Navigate to the given path
1203 * @param to Path to navigate to
1204 * @param opts Navigation options (method, submission, etc.)
1205 */
1206 navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;
1207 /**
1208 * @private
1209 * PRIVATE - DO NOT USE
1210 *
1211 * Trigger a fetcher load/submission
1212 *
1213 * @param key Fetcher key
1214 * @param routeId Route that owns the fetcher
1215 * @param href href to fetch
1216 * @param opts Fetcher options, (method, submission, etc.)
1217 */
1218 fetch(key: string, routeId: string, href: string | null, opts?: RouterFetchOptions): Promise<void>;
1219 /**
1220 * @private
1221 * PRIVATE - DO NOT USE
1222 *
1223 * Trigger a revalidation of all current route loaders and fetcher loads
1224 */
1225 revalidate(): Promise<void>;
1226 /**
1227 * @private
1228 * PRIVATE - DO NOT USE
1229 *
1230 * Utility function to create an href for the given location
1231 * @param location
1232 */
1233 createHref(location: Location | URL): string;
1234 /**
1235 * @private
1236 * PRIVATE - DO NOT USE
1237 *
1238 * Utility function to create a URL for the given location
1239 * @param location
1240 */
1241 createURL?(to: To): URL;
1242 /**
1243 * @private
1244 * PRIVATE - DO NOT USE
1245 *
1246 * Utility function to URL encode a destination path according to the internal
1247 * history implementation
1248 * @param to
1249 */
1250 encodeLocation(to: To): Path;
1251 /**
1252 * @private
1253 * PRIVATE - DO NOT USE
1254 *
1255 * Get/create a fetcher for the given key
1256 * @param key
1257 */
1258 getFetcher<TData = any>(key: string): Fetcher<TData>;
1259 /**
1260 * @internal
1261 * PRIVATE - DO NOT USE
1262 *
1263 * Reset the fetcher for a given key
1264 * @param key
1265 */
1266 resetFetcher(key: string, opts?: {
1267 reason?: unknown;
1268 }): void;
1269 /**
1270 * @private
1271 * PRIVATE - DO NOT USE
1272 *
1273 * Delete the fetcher for a given key
1274 * @param key
1275 */
1276 deleteFetcher(key: string): void;
1277 /**
1278 * @private
1279 * PRIVATE - DO NOT USE
1280 *
1281 * Cleanup listeners and abort any in-progress loads
1282 */
1283 dispose(): void;
1284 /**
1285 * @private
1286 * PRIVATE - DO NOT USE
1287 *
1288 * Get a navigation blocker
1289 * @param key The identifier for the blocker
1290 * @param fn The blocker function implementation
1291 */
1292 getBlocker(key: string, fn: BlockerFunction): Blocker;
1293 /**
1294 * @private
1295 * PRIVATE - DO NOT USE
1296 *
1297 * Delete a navigation blocker
1298 * @param key The identifier for the blocker
1299 */
1300 deleteBlocker(key: string): void;
1301 /**
1302 * @private
1303 * PRIVATE DO NOT USE
1304 *
1305 * Patch additional children routes into an existing parent route
1306 * @param routeId The parent route id or a callback function accepting `patch`
1307 * to perform batch patching
1308 * @param children The additional children routes
1309 * @param unstable_allowElementMutations Allow mutation or route elements on
1310 * existing routes. Intended for RSC-usage
1311 * only.
1312 */
1313 patchRoutes(routeId: string | null, children: RouteObject[], unstable_allowElementMutations?: boolean): void;
1314 /**
1315 * @private
1316 * PRIVATE - DO NOT USE
1317 *
1318 * HMR needs to pass in-flight route updates to React Router
1319 * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)
1320 */
1321 _internalSetRoutes(routes: RouteObject[]): void;
1322 /**
1323 * @private
1324 * PRIVATE - DO NOT USE
1325 *
1326 * Cause subscribers to re-render. This is used to force a re-render.
1327 */
1328 _internalSetStateDoNotUseOrYouWillBreakYourApp(state: Partial<RouterState>): void;
1329 /**
1330 * @private
1331 * PRIVATE - DO NOT USE
1332 *
1333 * Internal fetch AbortControllers accessed by unit tests
1334 */
1335 _internalFetchControllers: Map<string, AbortController>;
1336}
1337/**
1338 * State maintained internally by the router. During a navigation, all states
1339 * reflect the "old" location unless otherwise noted.
1340 */
1341interface RouterState {
1342 /**
1343 * The action of the most recent navigation
1344 */
1345 historyAction: Action;
1346 /**
1347 * The current location reflected by the router
1348 */
1349 location: Location;
1350 /**
1351 * The current set of route matches
1352 */
1353 matches: DataRouteMatch[];
1354 /**
1355 * Tracks whether we've completed our initial data load
1356 */
1357 initialized: boolean;
1358 /**
1359 * Tracks whether we should be rendering a HydrateFallback during hydration
1360 */
1361 renderFallback: boolean;
1362 /**
1363 * Current scroll position we should start at for a new view
1364 * - number -> scroll position to restore to
1365 * - false -> do not restore scroll at all (used during submissions/revalidations)
1366 * - null -> don't have a saved position, scroll to hash or top of page
1367 */
1368 restoreScrollPosition: number | false | null;
1369 /**
1370 * Indicate whether this navigation should skip resetting the scroll position
1371 * if we are unable to restore the scroll position
1372 */
1373 preventScrollReset: boolean;
1374 /**
1375 * Tracks the state of the current navigation
1376 */
1377 navigation: Navigation;
1378 /**
1379 * Tracks any in-progress revalidations
1380 */
1381 revalidation: RevalidationState;
1382 /**
1383 * Data from the loaders for the current matches
1384 */
1385 loaderData: RouteData;
1386 /**
1387 * Data from the action for the current matches
1388 */
1389 actionData: RouteData | null;
1390 /**
1391 * Errors caught from loaders for the current matches
1392 */
1393 errors: RouteData | null;
1394 /**
1395 * Map of current fetchers
1396 */
1397 fetchers: Map<string, Fetcher>;
1398 /**
1399 * Map of current blockers
1400 */
1401 blockers: Map<string, Blocker>;
1402}
1403/**
1404 * Data that can be passed into hydrate a Router from SSR
1405 */
1406type HydrationState = Partial<Pick<RouterState, "loaderData" | "actionData" | "errors">>;
1407/**
1408 * Future flags to toggle new feature behavior
1409 */
1410interface FutureConfig {}
1411/**
1412 * Initialization options for createRouter
1413 */
1414interface RouterInit {
1415 routes: RouteObject[];
1416 history: History;
1417 basename?: string;
1418 getContext?: () => MaybePromise<RouterContextProvider>;
1419 instrumentations?: ClientInstrumentation[];
1420 mapRouteProperties?: MapRoutePropertiesFunction;
1421 future?: Partial<FutureConfig>;
1422 hydrationRouteProperties?: string[];
1423 hydrationData?: HydrationState;
1424 window?: Window;
1425 dataStrategy?: DataStrategyFunction;
1426 patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
1427}
1428/**
1429 * State returned from a server-side query() call
1430 */
1431interface StaticHandlerContext {
1432 basename: Router$1["basename"];
1433 location: RouterState["location"];
1434 matches: RouterState["matches"];
1435 loaderData: RouterState["loaderData"];
1436 actionData: RouterState["actionData"];
1437 errors: RouterState["errors"];
1438 statusCode: number;
1439 loaderHeaders: Record<string, Headers>;
1440 actionHeaders: Record<string, Headers>;
1441 _deepestRenderedBoundaryId?: string | null;
1442}
1443/**
1444 * A StaticHandler instance manages a singular SSR navigation/fetch event
1445 */
1446interface StaticHandler {
1447 /**
1448 * The set of data routes managed by this handler
1449 */
1450 dataRoutes: DataRouteObject[];
1451 /**
1452 * @private
1453 * PRIVATE - DO NOT USE
1454 *
1455 * The route branches derived from the data routes, used for internal route
1456 * matching in Framework Mode
1457 */
1458 _internalRouteBranches: RouteBranch<DataRouteObject>[];
1459 /**
1460 * Perform a query for a given request - executing all matched route
1461 * loaders/actions. Used for document requests.
1462 *
1463 * @param request The request to query
1464 * @param opts Optional query options
1465 * @param opts.dataStrategy Alternate dataStrategy implementation
1466 * @param opts.filterMatchesToLoad Predicate function to filter which matches should be loaded
1467 * @param opts.generateMiddlewareResponse To enable middleware, provide a function
1468 * to generate a response to bubble back up the middleware chain
1469 * @param opts.requestContext Context object to pass to loaders/actions
1470 * @param opts.skipLoaderErrorBubbling Skip loader error bubbling
1471 * @param opts.skipRevalidation Skip revalidation after action submission
1472 * @param opts.normalizePath Normalize the request path
1473 */
1474 query(request: Request, opts?: {
1475 requestContext?: unknown;
1476 filterMatchesToLoad?: (match: DataRouteMatch) => boolean;
1477 skipLoaderErrorBubbling?: boolean;
1478 skipRevalidation?: boolean;
1479 dataStrategy?: DataStrategyFunction<unknown>;
1480 generateMiddlewareResponse?: (query: (r: Request, args?: {
1481 filterMatchesToLoad?: (match: DataRouteMatch) => boolean;
1482 }) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
1483 normalizePath?: (request: Request) => Path;
1484 }): Promise<StaticHandlerContext | Response>;
1485 /**
1486 * Perform a query for a specific route. Used for resource requests.
1487 *
1488 * @param request The request to query
1489 * @param opts Optional queryRoute options
1490 * @param opts.dataStrategy Alternate dataStrategy implementation
1491 * @param opts.generateMiddlewareResponse To enable middleware, provide a function
1492 * to generate a response to bubble back up the middleware chain
1493 * @param opts.requestContext Context object to pass to loaders/actions
1494 * @param opts.routeId The ID of the route to query
1495 * @param opts.normalizePath Normalize the request path
1496 */
1497 queryRoute(request: Request, opts?: {
1498 routeId?: string;
1499 requestContext?: unknown;
1500 dataStrategy?: DataStrategyFunction<unknown>;
1501 generateMiddlewareResponse?: (queryRoute: (r: Request) => Promise<Response>) => MaybePromise<Response>;
1502 normalizePath?: (request: Request) => Path;
1503 }): Promise<any>;
1504}
1505type ViewTransitionOpts = {
1506 currentLocation: Location;
1507 nextLocation: Location;
1508};
1509/**
1510 * Subscriber function signature for changes to router state
1511 */
1512interface RouterSubscriber {
1513 (state: RouterState, opts: {
1514 deletedFetchers: string[];
1515 newErrors: RouteData | null;
1516 viewTransitionOpts?: ViewTransitionOpts;
1517 flushSync: boolean;
1518 }): void;
1519}
1520/**
1521 * Function signature for determining the key to be used in scroll restoration
1522 * for a given location
1523 */
1524interface GetScrollRestorationKeyFunction {
1525 (location: Location, matches: UIMatch[]): string | null;
1526}
1527/**
1528 * Function signature for determining the current scroll position
1529 */
1530interface GetScrollPositionFunction {
1531 (): number;
1532}
1533/**
1534 * - "route": relative to the route hierarchy so `..` means remove all segments
1535 * of the current route even if it has many. For example, a `route("posts/:id")`
1536 * would have both `:id` and `posts` removed from the url.
1537 * - "path": relative to the pathname so `..` means remove one segment of the
1538 * pathname. For example, a `route("posts/:id")` would have only `:id` removed
1539 * from the url.
1540 */
1541type RelativeRoutingType = "route" | "path";
1542type BaseNavigateOrFetchOptions = {
1543 preventScrollReset?: boolean;
1544 relative?: RelativeRoutingType;
1545 flushSync?: boolean;
1546 defaultShouldRevalidate?: boolean;
1547};
1548type BaseNavigateOptions = BaseNavigateOrFetchOptions & {
1549 replace?: boolean;
1550 state?: any;
1551 fromRouteId?: string;
1552 viewTransition?: boolean;
1553 mask?: To;
1554};
1555type BaseSubmissionOptions = {
1556 formMethod?: HTMLFormMethod;
1557 formEncType?: FormEncType;
1558} & ({
1559 formData: FormData;
1560 body?: undefined;
1561} | {
1562 formData?: undefined;
1563 body: any;
1564});
1565/**
1566 * Options for a navigate() call for a normal (non-submission) navigation
1567 */
1568type LinkNavigateOptions = BaseNavigateOptions;
1569/**
1570 * Options for a navigate() call for a submission navigation
1571 */
1572type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;
1573/**
1574 * Options to pass to navigate() for a navigation
1575 */
1576type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
1577/**
1578 * Options for a fetch() load
1579 */
1580type LoadFetchOptions = BaseNavigateOrFetchOptions;
1581/**
1582 * Options for a fetch() submission
1583 */
1584type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;
1585/**
1586 * Options to pass to fetch()
1587 */
1588type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;
1589/**
1590 * Potential states for state.navigation
1591 */
1592type NavigationStates = {
1593 Idle: {
1594 state: "idle";
1595 location: undefined;
1596 matches: undefined;
1597 historyAction: undefined;
1598 formMethod: undefined;
1599 formAction: undefined;
1600 formEncType: undefined;
1601 formData: undefined;
1602 json: undefined;
1603 text: undefined;
1604 };
1605 Loading: {
1606 state: "loading";
1607 location: Location;
1608 matches: DataRouteMatch[];
1609 historyAction: Action;
1610 formMethod: Submission["formMethod"] | undefined;
1611 formAction: Submission["formAction"] | undefined;
1612 formEncType: Submission["formEncType"] | undefined;
1613 formData: Submission["formData"] | undefined;
1614 json: Submission["json"] | undefined;
1615 text: Submission["text"] | undefined;
1616 };
1617 Submitting: {
1618 state: "submitting";
1619 location: Location;
1620 matches: DataRouteMatch[];
1621 historyAction: Action;
1622 formMethod: Submission["formMethod"];
1623 formAction: Submission["formAction"];
1624 formEncType: Submission["formEncType"];
1625 formData: Submission["formData"];
1626 json: Submission["json"];
1627 text: Submission["text"];
1628 };
1629};
1630type Navigation = NavigationStates[keyof NavigationStates];
1631type RevalidationState = "idle" | "loading";
1632/**
1633 * Potential states for fetchers
1634 */
1635type FetcherStates<TData = any> = {
1636 /**
1637 * The fetcher is not calling a loader or action
1638 *
1639 * ```tsx
1640 * fetcher.state === "idle"
1641 * ```
1642 */
1643 Idle: {
1644 state: "idle";
1645 formMethod: undefined;
1646 formAction: undefined;
1647 formEncType: undefined;
1648 text: undefined;
1649 formData: undefined;
1650 json: undefined;
1651 /**
1652 * If the fetcher has never been called, this will be undefined.
1653 */
1654 data: TData | undefined;
1655 };
1656 /**
1657 * The fetcher is loading data from a {@link LoaderFunction | loader} from a
1658 * call to {@link FetcherWithComponents.load | `fetcher.load`}.
1659 *
1660 * ```tsx
1661 * // somewhere
1662 * <button onClick={() => fetcher.load("/some/route") }>Load</button>
1663 *
1664 * // the state will update
1665 * fetcher.state === "loading"
1666 * ```
1667 */
1668 Loading: {
1669 state: "loading";
1670 formMethod: Submission["formMethod"] | undefined;
1671 formAction: Submission["formAction"] | undefined;
1672 formEncType: Submission["formEncType"] | undefined;
1673 text: Submission["text"] | undefined;
1674 formData: Submission["formData"] | undefined;
1675 json: Submission["json"] | undefined;
1676 data: TData | undefined;
1677 };
1678 /**
1679 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`}.
1680 ```tsx
1681 // somewhere
1682 <input
1683 onChange={e => {
1684 fetcher.submit(event.currentTarget.form, { method: "post" });
1685 }}
1686 />
1687 // the state will update
1688 fetcher.state === "submitting"
1689 // and formData will be available
1690 fetcher.formData
1691 ```
1692 */
1693 Submitting: {
1694 state: "submitting";
1695 formMethod: Submission["formMethod"];
1696 formAction: Submission["formAction"];
1697 formEncType: Submission["formEncType"];
1698 text: Submission["text"];
1699 formData: Submission["formData"];
1700 json: Submission["json"];
1701 data: TData | undefined;
1702 };
1703};
1704type Fetcher<TData = any> = FetcherStates<TData>[keyof FetcherStates<TData>];
1705interface BlockerBlocked {
1706 state: "blocked";
1707 reset: () => void;
1708 proceed: () => void;
1709 location: Location;
1710}
1711interface BlockerUnblocked {
1712 state: "unblocked";
1713 reset: undefined;
1714 proceed: undefined;
1715 location: undefined;
1716}
1717interface BlockerProceeding {
1718 state: "proceeding";
1719 reset: undefined;
1720 proceed: undefined;
1721 location: Location;
1722}
1723type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
1724type BlockerFunction = (args: {
1725 currentLocation: Location;
1726 nextLocation: Location;
1727 historyAction: Action;
1728}) => boolean;
1729interface CreateStaticHandlerOptions {
1730 basename?: string;
1731 mapRouteProperties?: MapRoutePropertiesFunction;
1732 instrumentations?: Pick<ServerInstrumentation, "route">[];
1733 future?: Partial<FutureConfig>;
1734}
1735/**
1736 * Create a static handler to perform server-side data loading
1737 *
1738 * @example
1739 * export async function handleRequest(request: Request) {
1740 * let { query, dataRoutes } = createStaticHandler(routes);
1741 * let context = await query(request);
1742 *
1743 * if (context instanceof Response) {
1744 * return context;
1745 * }
1746 *
1747 * let router = createStaticRouter(dataRoutes, context);
1748 * return new Response(
1749 * ReactDOMServer.renderToString(<StaticRouterProvider ... />),
1750 * { headers: { "Content-Type": "text/html" } }
1751 * );
1752 * }
1753 *
1754 * @public
1755 * @category Data Routers
1756 * @mode data
1757 * @param routes The {@link RouteObject | route objects} to create a static
1758 * handler for
1759 * @param opts Options
1760 * @param opts.basename The base URL for the static handler (default: `/`)
1761 * @param opts.future Future flags for the static handler
1762 * @returns A static handler that can be used to query data for the provided
1763 * routes
1764 */
1765declare function createStaticHandler(routes: RouteObject[], opts?: CreateStaticHandlerOptions): StaticHandler;
1766//#endregion
1767//#region lib/router/links.d.ts
1768type Primitive = null | undefined | string | number | boolean | symbol | bigint;
1769type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
1770interface HtmlLinkProps {
1771 /**
1772 * Address of the hyperlink
1773 */
1774 href?: string;
1775 /**
1776 * How the element handles crossorigin requests
1777 */
1778 crossOrigin?: "anonymous" | "use-credentials";
1779 /**
1780 * Relationship between the document containing the hyperlink and the destination resource
1781 */
1782 rel: LiteralUnion<"alternate" | "dns-prefetch" | "icon" | "manifest" | "modulepreload" | "next" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "search" | "stylesheet", string>;
1783 /**
1784 * Applicable media: "screen", "print", "(max-width: 764px)"
1785 */
1786 media?: string;
1787 /**
1788 * Integrity metadata used in Subresource Integrity checks
1789 */
1790 integrity?: string;
1791 /**
1792 * Language of the linked resource
1793 */
1794 hrefLang?: string;
1795 /**
1796 * Hint for the type of the referenced resource
1797 */
1798 type?: string;
1799 /**
1800 * Referrer policy for fetches initiated by the element
1801 */
1802 referrerPolicy?: "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
1803 /**
1804 * Sizes of the icons (for rel="icon")
1805 */
1806 sizes?: string;
1807 /**
1808 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1809 */
1810 as?: LiteralUnion<"audio" | "audioworklet" | "document" | "embed" | "fetch" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt", string>;
1811 /**
1812 * Color to use when customizing a site's icon (for rel="mask-icon")
1813 */
1814 color?: string;
1815 /**
1816 * Whether the link is disabled
1817 */
1818 disabled?: boolean;
1819 /**
1820 * The title attribute has special semantics on this element: Title of the link; CSS style sheet set name.
1821 */
1822 title?: string;
1823 /**
1824 * Images to use in different situations, e.g., high-resolution displays,
1825 * small monitors, etc. (for rel="preload")
1826 */
1827 imageSrcSet?: string;
1828 /**
1829 * Image sizes for different page layouts (for rel="preload")
1830 */
1831 imageSizes?: string;
1832}
1833interface HtmlLinkPreloadImage extends HtmlLinkProps {
1834 /**
1835 * Relationship between the document containing the hyperlink and the destination resource
1836 */
1837 rel: "preload";
1838 /**
1839 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
1840 */
1841 as: "image";
1842 /**
1843 * Address of the hyperlink
1844 */
1845 href?: string;
1846 /**
1847 * Images to use in different situations, e.g., high-resolution displays,
1848 * small monitors, etc. (for rel="preload")
1849 */
1850 imageSrcSet: string;
1851 /**
1852 * Image sizes for different page layouts (for rel="preload")
1853 */
1854 imageSizes?: string;
1855}
1856/**
1857 * Represents a `<link>` element.
1858 *
1859 * WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
1860 */
1861type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "imageSizes">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "href"> & {
1862 imageSizes?: never;
1863});
1864interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
1865 /**
1866 * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
1867 * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
1868 * element. If not provided in Framework Mode, it will default to any
1869 * {@link ServerRouter | `<ServerRouter nonce>`} prop.
1870 */
1871 nonce?: string | undefined;
1872 /**
1873 * The absolute path of the page to prefetch, e.g. `/absolute/path`.
1874 */
1875 page: string;
1876}
1877type LinkDescriptor = HtmlLinkDescriptor | PageLinkDescriptor;
1878//#endregion
1879//#region lib/server-runtime/single-fetch.d.ts
1880type Serializable = undefined | null | boolean | string | symbol | number | Array<Serializable> | {
1881 [key: PropertyKey]: Serializable;
1882} | bigint | Date | URL | RegExp | Error | Map<Serializable, Serializable> | Set<Serializable> | Promise<Serializable>;
1883//#endregion
1884//#region lib/types/utils.d.ts
1885type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
1886type IsAny<T> = 0 extends 1 & T ? true : false;
1887type Func = (...args: any[]) => unknown;
1888//#endregion
1889//#region lib/types/serializes-to.d.ts
1890/**
1891 * A brand that can be applied to a type to indicate that it will serialize
1892 * to a specific type when transported to the client from a loader.
1893 * Only use this if you have additional serialization/deserialization logic
1894 * in your application.
1895 */
1896type unstable_SerializesTo<T> = {
1897 unstable__ReactRouter_SerializesTo: [T];
1898};
1899//#endregion
1900//#region lib/types/route-data.d.ts
1901type Serialize<T> = T extends unstable_SerializesTo<infer To> ? To : T extends Serializable ? T : T extends ((...args: any[]) => unknown) ? undefined : T extends Promise<infer U> ? Promise<Serialize<U>> : T extends Map<infer K, infer V> ? Map<Serialize<K>, Serialize<V>> : T extends ReadonlyMap<infer K, infer V> ? ReadonlyMap<Serialize<K>, Serialize<V>> : T extends Set<infer U> ? Set<Serialize<U>> : T extends ReadonlySet<infer U> ? ReadonlySet<Serialize<U>> : T extends [] ? [] : T extends readonly [infer F, ...infer R] ? [Serialize<F>, ...Serialize<R>] : T extends Array<infer U> ? Array<Serialize<U>> : T extends readonly unknown[] ? readonly Serialize<T[number]>[] : T extends Record<any, any> ? { [K in keyof T]: Serialize<T[K]> } : undefined;
1902type VoidToUndefined<T> = Equal<T, void> extends true ? undefined : T;
1903type DataFrom<T> = IsAny<T> extends true ? undefined : T extends Func ? VoidToUndefined<Awaited<ReturnType<T>>> : undefined;
1904type ClientData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? U : T;
1905type ServerData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? Serialize<U> : Serialize<T>;
1906type ServerDataFrom<T> = ServerData<DataFrom<T>>;
1907type ClientDataFrom<T> = ClientData<DataFrom<T>>;
1908type ClientDataFunctionArgs<Params> = {
1909 /**
1910 * A {@link https://developer.mozilla.org/en-US/docs/Web/API/Request Fetch Request instance} which you can use to read the URL, the method, the "content-type" header, and the request body from the request.
1911 *
1912 * @note Because client data functions are called before a network request is made, the Request object does not include the headers which the browser automatically adds. React Router infers the "content-type" header from the enc-type of the form that performed the submission.
1913 **/
1914 request: Request;
1915 /**
1916 * A URL instance representing the application location being navigated to or
1917 * fetched.
1918 *
1919 * In Framework mode, this is a normalized URL with React-Router-specific
1920 * implementation details removed (`.data` suffixes, `index`/`_routes` search
1921 * params). For the raw incoming URL, use `request.url`.
1922 */
1923 url: URL;
1924 /**
1925 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
1926 * @example
1927 * // app/routes.ts
1928 * route("teams/:teamId", "./team.tsx"),
1929 *
1930 * // app/team.tsx
1931 * export function clientLoader({
1932 * params,
1933 * }: Route.ClientLoaderArgs) {
1934 * params.teamId;
1935 * // ^ string
1936 * }
1937 **/
1938 params: Params;
1939 /**
1940 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
1941 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
1942 */
1943 pattern: string;
1944 /**
1945 * An instance of `RouterContextProvider` that can be used to access context
1946 * values from your route middlewares. You may pass in initial context values
1947 * in your `<HydratedRouter getContext>` prop.
1948 */
1949 context: Readonly<RouterContextProvider>;
1950};
1951type SerializeFrom<T> = T extends ((...args: infer Args) => unknown) ? Args extends [ClientLoaderFunctionArgs | ClientActionFunctionArgs | ClientDataFunctionArgs<unknown>] ? ClientDataFrom<T> : ServerDataFrom<T> : T;
1952//#endregion
1953//#region lib/dom/ssr/routeModules.d.ts
1954/**
1955 * A function that handles data mutations for a route on the client
1956 */
1957type ClientActionFunction = (args: ClientActionFunctionArgs) => ReturnType<ActionFunction>;
1958/**
1959 * Arguments passed to a route `clientAction` function
1960 */
1961type ClientActionFunctionArgs = ActionFunctionArgs & {
1962 serverAction: <T = unknown>() => Promise<SerializeFrom<T>>;
1963};
1964/**
1965 * A function that loads data for a route on the client
1966 */
1967type ClientLoaderFunction = ((args: ClientLoaderFunctionArgs) => ReturnType<LoaderFunction>) & {
1968 hydrate?: boolean;
1969};
1970/**
1971 * Arguments passed to a route `clientLoader` function
1972 */
1973type ClientLoaderFunctionArgs = LoaderFunctionArgs & {
1974 serverLoader: <T = unknown>() => Promise<SerializeFrom<T>>;
1975};
1976type HeadersArgs = {
1977 loaderHeaders: Headers;
1978 parentHeaders: Headers;
1979 actionHeaders: Headers;
1980 errorHeaders: Headers | undefined;
1981};
1982/**
1983 * A function that returns HTTP headers to be used for a route. These headers
1984 * will be merged with (and take precedence over) headers from parent routes.
1985 */
1986interface HeadersFunction {
1987 (args: HeadersArgs): Headers | HeadersInit;
1988}
1989/**
1990 * A function that defines `<link>` tags to be inserted into the `<head>` of
1991 * the document on route transitions.
1992 *
1993 * @see https://reactrouter.com/start/framework/route-module#meta
1994 */
1995interface LinksFunction {
1996 (): LinkDescriptor[];
1997}
1998interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
1999 id: RouteId;
2000 pathname: DataRouteMatch["pathname"];
2001 loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
2002 handle?: RouteHandle;
2003 params: DataRouteMatch["params"];
2004 meta: MetaDescriptor[];
2005 error?: unknown;
2006}
2007type MetaMatches<MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> = Array<{ [K in keyof MatchLoaders]: MetaMatch<Exclude<K, number | symbol>, MatchLoaders[K]> }[keyof MatchLoaders]>;
2008interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
2009 loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
2010 params: Params;
2011 location: Location;
2012 matches: MetaMatches<MatchLoaders>;
2013 error?: unknown;
2014}
2015/**
2016 * A function that returns an array of data objects to use for rendering
2017 * metadata HTML tags in a route. These tags are not rendered on descendant
2018 * routes in the route hierarchy. In other words, they will only be rendered on
2019 * the route in which they are exported.
2020 *
2021 * @param Loader - The type of the current route's loader function
2022 * @param MatchLoaders - Mapping from a parent route's filepath to its loader
2023 * function type
2024 *
2025 * Note that parent route filepaths are relative to the `app/` directory.
2026 *
2027 * For example, if this meta function is for `/sales/customers/$customerId`:
2028 *
2029 * ```ts
2030 * // app/root.tsx
2031 * const loader = () => ({ hello: "world" })
2032 * export type Loader = typeof loader
2033 *
2034 * // app/routes/sales.tsx
2035 * const loader = () => ({ salesCount: 1074 })
2036 * export type Loader = typeof loader
2037 *
2038 * // app/routes/sales/customers.tsx
2039 * const loader = () => ({ customerCount: 74 })
2040 * export type Loader = typeof loader
2041 *
2042 * // app/routes/sales/customers/$customersId.tsx
2043 * import type { Loader as RootLoader } from "../../../root"
2044 * import type { Loader as SalesLoader } from "../../sales"
2045 * import type { Loader as CustomersLoader } from "../../sales/customers"
2046 *
2047 * const loader = () => ({ name: "Customer name" })
2048 *
2049 * const meta: MetaFunction<typeof loader, {
2050 * "root": RootLoader,
2051 * "routes/sales": SalesLoader,
2052 * "routes/sales/customers": CustomersLoader,
2053 * }> = ({ loaderData, matches }) => {
2054 * const { name } = loaderData
2055 * // ^? string
2056 * const { customerCount } = matches.find((match) => match.id === "routes/sales/customers").loaderData
2057 * // ^? number
2058 * const { salesCount } = matches.find((match) => match.id === "routes/sales").loaderData
2059 * // ^? number
2060 * const { hello } = matches.find((match) => match.id === "root").loaderData
2061 * // ^? "world"
2062 * }
2063 * ```
2064 */
2065interface MetaFunction<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
2066 (args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;
2067}
2068type MetaDescriptor = {
2069 charSet: "utf-8";
2070} | {
2071 title: string;
2072} | {
2073 name: string;
2074 content: string;
2075} | {
2076 property: string;
2077 content: string;
2078} | {
2079 httpEquiv: string;
2080 content: string;
2081} | {
2082 "script:ld+json": LdJsonObject | LdJsonObject[];
2083} | {
2084 tagName: "meta" | "link";
2085 [name: string]: string;
2086} | {
2087 [name: string]: unknown;
2088};
2089type LdJsonObject = { [Key in string]: LdJsonValue } & { [Key in string]?: LdJsonValue | undefined };
2090type LdJsonArray = LdJsonValue[] | readonly LdJsonValue[];
2091type LdJsonPrimitive = string | number | boolean | null;
2092type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
2093/**
2094 * A React component that is rendered for a route.
2095 */
2096/**
2097 * An arbitrary object that is associated with a route.
2098 *
2099 * @see https://reactrouter.com/how-to/using-handle
2100 */
2101type RouteHandle = unknown;
2102//#endregion
2103//#region lib/components.d.ts
2104interface AwaitResolveRenderFunction<Resolve = any> {
2105 (data: Awaited<Resolve>): React.ReactNode;
2106}
2107/**
2108 * @category Types
2109 */
2110interface AwaitProps<Resolve> {
2111 /**
2112 * When using a function, the resolved value is provided as the parameter.
2113 *
2114 * ```tsx [2]
2115 * <Await resolve={reviewsPromise}>
2116 * {(resolvedReviews) => <Reviews items={resolvedReviews} />}
2117 * </Await>
2118 * ```
2119 *
2120 * When using React elements, {@link useAsyncValue} will provide the
2121 * resolved value:
2122 *
2123 * ```tsx [2]
2124 * <Await resolve={reviewsPromise}>
2125 * <Reviews />
2126 * </Await>
2127 *
2128 * function Reviews() {
2129 * const resolvedReviews = useAsyncValue();
2130 * return <div>...</div>;
2131 * }
2132 * ```
2133 */
2134 children: React.ReactNode | AwaitResolveRenderFunction<Resolve>;
2135 /**
2136 * The error element renders instead of the `children` when the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
2137 * rejects.
2138 *
2139 * ```tsx
2140 * <Await
2141 * errorElement={<div>Oops</div>}
2142 * resolve={reviewsPromise}
2143 * >
2144 * <Reviews />
2145 * </Await>
2146 * ```
2147 *
2148 * To provide a more contextual error, you can use the {@link useAsyncError} in a
2149 * child component
2150 *
2151 * ```tsx
2152 * <Await
2153 * errorElement={<ReviewsError />}
2154 * resolve={reviewsPromise}
2155 * >
2156 * <Reviews />
2157 * </Await>
2158 *
2159 * function ReviewsError() {
2160 * const error = useAsyncError();
2161 * return <div>Error loading reviews: {error.message}</div>;
2162 * }
2163 * ```
2164 *
2165 * If you do not provide an `errorElement`, the rejected value will bubble up
2166 * to the nearest route-level [`ErrorBoundary`](../../start/framework/route-module#errorboundary)
2167 * and be accessible via the {@link useRouteError} hook.
2168 */
2169 errorElement?: React.ReactNode;
2170 /**
2171 * Takes a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
2172 * returned from a [`loader`](../../start/framework/route-module#loader) to be
2173 * resolved and rendered.
2174 *
2175 * ```tsx
2176 * import { Await, useLoaderData } from "react-router";
2177 *
2178 * export async function loader() {
2179 * let reviews = getReviews(); // not awaited
2180 * let book = await getBook();
2181 * return {
2182 * book,
2183 * reviews, // this is a promise
2184 * };
2185 * }
2186 *
2187 * export default function Book() {
2188 * const {
2189 * book,
2190 * reviews, // this is the same promise
2191 * } = useLoaderData();
2192 *
2193 * return (
2194 * <div>
2195 * <h1>{book.title}</h1>
2196 * <p>{book.description}</p>
2197 * <React.Suspense fallback={<ReviewsSkeleton />}>
2198 * <Await
2199 * // and is the promise we pass to Await
2200 * resolve={reviews}
2201 * >
2202 * <Reviews />
2203 * </Await>
2204 * </React.Suspense>
2205 * </div>
2206 * );
2207 * }
2208 * ```
2209 */
2210 resolve: Resolve;
2211}
2212/**
2213 * Used to render promise values with automatic error handling.
2214 *
2215 * **Note:** `<Await>` expects to be rendered inside a [`<React.Suspense>`](https://react.dev/reference/react/Suspense)
2216 *
2217 * @example
2218 * import { Await, useLoaderData } from "react-router";
2219 *
2220 * export async function loader() {
2221 * // not awaited
2222 * const reviews = getReviews();
2223 * // awaited (blocks the transition)
2224 * const book = await fetch("/api/book").then((res) => res.json());
2225 * return { book, reviews };
2226 * }
2227 *
2228 * function Book() {
2229 * const { book, reviews } = useLoaderData();
2230 * return (
2231 * <div>
2232 * <h1>{book.title}</h1>
2233 * <p>{book.description}</p>
2234 * <React.Suspense fallback={<ReviewsSkeleton />}>
2235 * <Await
2236 * resolve={reviews}
2237 * errorElement={
2238 * <div>Could not load reviews 😬</div>
2239 * }
2240 * children={(resolvedReviews) => (
2241 * <Reviews items={resolvedReviews} />
2242 * )}
2243 * />
2244 * </React.Suspense>
2245 * </div>
2246 * );
2247 * }
2248 *
2249 * @public
2250 * @category Components
2251 * @mode framework
2252 * @mode data
2253 * @param props Props
2254 * @param {AwaitProps.children} props.children n/a
2255 * @param {AwaitProps.errorElement} props.errorElement n/a
2256 * @param {AwaitProps.resolve} props.resolve n/a
2257 * @returns React element for the rendered awaited value
2258 */
2259declare function Await$1<Resolve>({
2260 children,
2261 errorElement,
2262 resolve
2263}: AwaitProps<Resolve>): React.JSX.Element;
2264//#endregion
2265//#region lib/rsc/server.rsc.d.ts
2266declare function getRequest(): Request;
2267declare const redirect: typeof redirect$1;
2268declare const redirectDocument: typeof redirectDocument$1;
2269declare const replace$1: typeof replace$2;
2270declare const Await: typeof Await$1;
2271type RSCRouteConfigEntryBase = {
2272 action?: ActionFunction;
2273 clientAction?: ClientActionFunction;
2274 clientLoader?: ClientLoaderFunction;
2275 ErrorBoundary?: React.ComponentType<any>;
2276 handle?: any;
2277 headers?: HeadersFunction;
2278 HydrateFallback?: React.ComponentType<any>;
2279 Layout?: React.ComponentType<any>;
2280 links?: LinksFunction;
2281 loader?: LoaderFunction;
2282 meta?: MetaFunction;
2283 shouldRevalidate?: ShouldRevalidateFunction;
2284};
2285type RSCRouteConfigEntry = RSCRouteConfigEntryBase & {
2286 id: string;
2287 path?: string;
2288 Component?: React.ComponentType<any>;
2289 lazy?: () => Promise<RSCRouteConfigEntryBase & ({
2290 default?: React.ComponentType<any>;
2291 Component?: never;
2292 } | {
2293 default?: never;
2294 Component?: React.ComponentType<any>;
2295 })>;
2296} & ({
2297 index: true;
2298} | {
2299 children?: RSCRouteConfigEntry[];
2300});
2301type RSCRouteConfig = Array<RSCRouteConfigEntry>;
2302type RSCRouteManifest = {
2303 clientAction?: ClientActionFunction;
2304 clientLoader?: ClientLoaderFunction;
2305 element?: React.ReactElement | false;
2306 errorElement?: React.ReactElement;
2307 handle?: any;
2308 hasAction: boolean;
2309 hasComponent: boolean;
2310 hasLoader: boolean;
2311 hydrateFallbackElement?: React.ReactElement;
2312 id: string;
2313 index?: boolean;
2314 links?: LinksFunction;
2315 meta?: MetaFunction;
2316 parentId?: string;
2317 path?: string;
2318 shouldRevalidate?: ShouldRevalidateFunction;
2319};
2320type RSCRouteMatch = RSCRouteManifest & {
2321 params: Params;
2322 pathname: string;
2323 pathnameBase: string;
2324};
2325type RSCRenderPayload = {
2326 type: "render";
2327 actionData: Record<string, any> | null;
2328 basename: string | undefined;
2329 clientVersion?: string;
2330 errors: Record<string, any> | null;
2331 loaderData: Record<string, any>;
2332 location: Location;
2333 routeDiscovery: RouteDiscovery;
2334 matches: RSCRouteMatch[];
2335 patches?: Promise<RSCRouteManifest[]>;
2336 formState?: ReactFormState;
2337};
2338type RSCManifestPayload = {
2339 type: "manifest";
2340 patches: Promise<RSCRouteManifest[]>;
2341};
2342type RSCActionPayload = {
2343 type: "action";
2344 actionResult: Promise<unknown>;
2345 rerender?: Promise<RSCRenderPayload | RSCRedirectPayload>;
2346};
2347type RSCRedirectPayload = {
2348 type: "redirect";
2349 status: number;
2350 location: string;
2351 replace: boolean;
2352 reload: boolean;
2353 actionResult?: Promise<unknown>;
2354};
2355type RSCPayload = RSCRenderPayload | RSCManifestPayload | RSCActionPayload | RSCRedirectPayload;
2356type RSCMatch = {
2357 statusCode: number;
2358 headers: Headers;
2359 payload: RSCPayload;
2360};
2361type DecodeActionFunction = (formData: FormData) => Promise<() => Promise<unknown>>;
2362type DecodeFormStateFunction = (result: unknown, formData: FormData) => Promise<ReactFormState | undefined>;
2363type DecodeReplyFunction = (reply: FormData | string, options: {
2364 temporaryReferences: unknown;
2365}) => Promise<unknown[]>;
2366type LoadServerActionFunction = (id: string) => Promise<Function>;
2367type RouteDiscovery = {
2368 mode: "lazy";
2369 manifestPath?: string | undefined;
2370} | {
2371 mode: "initial";
2372};
2373/**
2374 * Matches the given routes to a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
2375 * and returns an [RSC](https://react.dev/reference/rsc/server-components)
2376 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2377 * encoding an {@link unstable_RSCPayload} for consumption by an [RSC](https://react.dev/reference/rsc/server-components)
2378 * enabled client router.
2379 *
2380 * @example
2381 * import {
2382 * createTemporaryReferenceSet,
2383 * decodeAction,
2384 * decodeReply,
2385 * loadServerAction,
2386 * renderToReadableStream,
2387 * } from "@vitejs/plugin-rsc/rsc";
2388 * import { unstable_matchRSCServerRequest as matchRSCServerRequest } from "react-router";
2389 *
2390 * matchRSCServerRequest({
2391 * createTemporaryReferenceSet,
2392 * decodeAction,
2393 * decodeFormState,
2394 * decodeReply,
2395 * loadServerAction,
2396 * request,
2397 * routes: routes(),
2398 * generateResponse(match) {
2399 * return new Response(
2400 * renderToReadableStream(match.payload),
2401 * {
2402 * status: match.statusCode,
2403 * headers: match.headers,
2404 * }
2405 * );
2406 * },
2407 * });
2408 *
2409 * @name unstable_matchRSCServerRequest
2410 * @public
2411 * @category RSC
2412 * @mode data
2413 * @param opts Options
2414 * @param opts.allowedActionOrigins Origin patterns that are allowed to execute actions.
2415 * @param opts.basename The basename to use when matching the request.
2416 * @param opts.createTemporaryReferenceSet A function that returns a temporary
2417 * reference set for the request, used to track temporary references in the [RSC](https://react.dev/reference/rsc/server-components)
2418 * stream.
2419 * @param opts.decodeAction Your `react-server-dom-xyz/server`'s `decodeAction`
2420 * function, responsible for loading a server action.
2421 * @param opts.decodeFormState A function responsible for decoding form state for
2422 * progressively enhanceable forms with React's [`useActionState`](https://react.dev/reference/react/useActionState)
2423 * using your `react-server-dom-xyz/server`'s `decodeFormState`.
2424 * @param opts.decodeReply Your `react-server-dom-xyz/server`'s `decodeReply`
2425 * function, used to decode the server function's arguments and bind them to the
2426 * implementation for invocation by the router.
2427 * @param opts.generateResponse A function responsible for using your
2428 * `renderToReadableStream` to generate a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2429 * encoding the {@link unstable_RSCPayload}.
2430 * @param opts.loadServerAction Your `react-server-dom-xyz/server`'s
2431 * `loadServerAction` function, used to load a server action by ID.
2432 * @param opts.clientVersion A version derived from the client build output used
2433 * to detect stale clients during lazy route discovery.
2434 * @param opts.onError An optional error handler that will be called with any
2435 * errors that occur during the request processing.
2436 * @param opts.request The [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
2437 * to match against.
2438 * @param opts.requestContext An instance of {@link RouterContextProvider}
2439 * that should be created per request, to be passed to [`action`](../../start/data/route-object#action)s,
2440 * [`loader`](../../start/data/route-object#loader)s and [middleware](../../how-to/middleware).
2441 * @param opts.routeDiscovery The route discovery configuration, used to determine how the router should discover new routes during navigations.
2442 * @param opts.routes Your {@link unstable_RSCRouteConfigEntry | route definitions}.
2443 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2444 * that contains the [RSC](https://react.dev/reference/rsc/server-components)
2445 * data for hydration.
2446 */
2447declare function matchRSCServerRequest({
2448 allowedActionOrigins,
2449 createTemporaryReferenceSet,
2450 basename,
2451 decodeReply,
2452 requestContext,
2453 routeDiscovery,
2454 loadServerAction,
2455 decodeAction,
2456 decodeFormState,
2457 clientVersion,
2458 onError,
2459 request,
2460 routes,
2461 generateResponse
2462}: {
2463 allowedActionOrigins?: string[];
2464 createTemporaryReferenceSet: () => unknown;
2465 basename?: string;
2466 decodeReply?: DecodeReplyFunction;
2467 decodeAction?: DecodeActionFunction;
2468 decodeFormState?: DecodeFormStateFunction;
2469 requestContext?: RouterContextProvider;
2470 loadServerAction?: LoadServerActionFunction;
2471 clientVersion?: string;
2472 onError?: (error: unknown) => void;
2473 request: Request;
2474 routes: RSCRouteConfigEntry[];
2475 routeDiscovery?: RouteDiscovery;
2476 generateResponse: (match: RSCMatch, {
2477 onError,
2478 temporaryReferences
2479 }: {
2480 onError(error: unknown): string | undefined;
2481 temporaryReferences: unknown;
2482 }) => Response;
2483}): Promise<Response>;
2484//#endregion
2485//#region lib/types/register.d.ts
2486/**
2487 * Apps can use this interface to "register" app-wide types for React Router via interface declaration merging and module augmentation.
2488 * React Router should handle this for you via type generation.
2489 *
2490 * For more on declaration merging and module augmentation, see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation .
2491 */
2492interface Register {}
2493type AnyParams = Record<string, string | undefined>;
2494type AnyPages = Record<string, {
2495 params: AnyParams;
2496}>;
2497type Pages = Register extends {
2498 pages: infer Registered extends AnyPages;
2499} ? Registered : AnyPages;
2500//#endregion
2501//#region lib/href.d.ts
2502type Args = { [K in keyof Pages]: ToArgs<Pages[K]["params"]> };
2503type ToArgs<Params extends Record<string, string | undefined>> = Equal<Params, {}> extends true ? [] : Partial<Params> extends Params ? [Params] | [] : [Params];
2504/**
2505 * Returns a resolved URL path for the specified route.
2506 *
2507 * Param values are percent-encoded for use in a path segment: characters that
2508 * would change the URL structure (`/`, `?`, `#`, `%`, whitespace, non-ASCII)
2509 * are escaped, while characters that RFC 3986 allows literally in a path
2510 * segment (`$ & + , ; = : @`) are kept as-is. Note this differs from query-string
2511 * encoding (`encodeURIComponent`/`URLSearchParams`), where those characters are
2512 * delimiters and must be escaped. Splat (`*`) values are encoded per segment,
2513 * preserving `/` separators.
2514 *
2515 * See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3)
2516 *
2517 * @example
2518 * const h = href("/:lang?/about", { lang: "en" })
2519 * // -> `/en/about`
2520 *
2521 * <Link to={href("/products/:id", { id: "abc123" })} />
2522 *
2523 * @public
2524 * @category Utils
2525 * @mode framework
2526 * @param path The route path to resolve
2527 * @param args The route params to use when resolving the path
2528 * @returns The resolved URL path
2529 */
2530declare function href<Path extends keyof Args>(path: Path, ...args: Args[Path]): string;
2531//#endregion
2532//#region lib/server-runtime/cookies.d.ts
2533interface CookieSignatureOptions {
2534 /**
2535 * An array of secrets that may be used to sign/unsign the value of a cookie.
2536 *
2537 * The array makes it easy to rotate secrets. New secrets should be added to
2538 * the beginning of the array. `cookie.serialize()` will always use the first
2539 * value in the array, but `cookie.parse()` may use any of them so that
2540 * cookies that were signed with older secrets still work.
2541 */
2542 secrets?: string[];
2543}
2544type CookieOptions = CookieParseOptions & CookieSerializeOptions & CookieSignatureOptions;
2545/**
2546 * A HTTP cookie.
2547 *
2548 * A Cookie is a logical container for metadata about a HTTP cookie; its name
2549 * and options. But it doesn't contain a value. Instead, it has `parse()` and
2550 * `serialize()` methods that allow a single instance to be reused for
2551 * parsing/encoding multiple different values.
2552 *
2553 * @see https://remix.run/utils/cookies#cookie-api
2554 */
2555interface Cookie {
2556 /**
2557 * The name of the cookie, used in the `Cookie` and `Set-Cookie` headers.
2558 */
2559 readonly name: string;
2560 /**
2561 * True if this cookie uses one or more secrets for verification.
2562 */
2563 readonly isSigned: boolean;
2564 /**
2565 * The Date this cookie expires.
2566 *
2567 * Note: This is calculated at access time using `maxAge` when no `expires`
2568 * option is provided to `createCookie()`.
2569 */
2570 readonly expires?: Date;
2571 /**
2572 * Parses a raw `Cookie` header and returns the value of this cookie or
2573 * `null` if it's not present.
2574 */
2575 parse(cookieHeader: string | null, options?: CookieParseOptions): Promise<any>;
2576 /**
2577 * Serializes the given value to a string and returns the `Set-Cookie`
2578 * header.
2579 */
2580 serialize(value: any, options?: CookieSerializeOptions): Promise<string>;
2581}
2582/**
2583 * Creates a logical container for managing a browser cookie from the server.
2584 *
2585 * @public
2586 * @category Utils
2587 * @mode framework
2588 * @mode data
2589 * @param name The name of the cookie.
2590 * @param cookieOptions Options for parsing and serializing the cookie.
2591 * @returns A {@link Cookie} object for parsing and serializing the cookie.
2592 */
2593declare const createCookie: (name: string, cookieOptions?: CookieOptions) => Cookie;
2594/**
2595 * A function that determines whether a value is a React Router {@link Cookie}
2596 * object.
2597 *
2598 * @public
2599 * @category Utils
2600 * @mode framework
2601 * @mode data
2602 * @param object The value to check.
2603 * @returns `true` if the value is a React Router {@link Cookie} object;
2604 * otherwise, `false`.
2605 */
2606type IsCookieFunction = (object: any) => object is Cookie;
2607/**
2608 * Returns `true` if a value is a React Router {@link Cookie} object.
2609 *
2610 * @public
2611 * @category Utils
2612 * @mode framework
2613 * @mode data
2614 * @param object The value to check.
2615 * @returns `true` if the value is a React Router {@link Cookie} object;
2616 * otherwise, `false`.
2617 */
2618declare const isCookie: IsCookieFunction;
2619//#endregion
2620//#region lib/server-runtime/sessions.d.ts
2621/**
2622 * An object of name/value pairs to be used in the session.
2623 */
2624interface SessionData {
2625 [name: string]: any;
2626}
2627/**
2628 * Session persists data across HTTP requests.
2629 *
2630 * @see https://reactrouter.com/explanation/sessions-and-cookies#sessions
2631 */
2632interface Session<Data = SessionData, FlashData = Data> {
2633 /**
2634 * A unique identifier for this session.
2635 *
2636 * Note: This will be the empty string for newly created sessions and
2637 * sessions that are not backed by a database (i.e. cookie-based sessions).
2638 */
2639 readonly id: string;
2640 /**
2641 * The raw data contained in this session.
2642 *
2643 * This is useful mostly for SessionStorage internally to access the raw
2644 * session data to persist.
2645 */
2646 readonly data: FlashSessionData<Data, FlashData>;
2647 /**
2648 * Returns `true` if the session has a value for the given `name`, `false`
2649 * otherwise.
2650 */
2651 has(name: (keyof Data | keyof FlashData) & string): boolean;
2652 /**
2653 * Returns the value for the given `name` in this session.
2654 */
2655 get<Key extends (keyof Data | keyof FlashData) & string>(name: Key): (Key extends keyof Data ? Data[Key] : undefined) | (Key extends keyof FlashData ? FlashData[Key] : undefined) | undefined;
2656 /**
2657 * Sets a value in the session for the given `name`.
2658 */
2659 set<Key extends keyof Data & string>(name: Key, value: Data[Key]): void;
2660 /**
2661 * Sets a value in the session that is only valid until the next `get()`.
2662 * This can be useful for temporary values, like error messages.
2663 */
2664 flash<Key extends keyof FlashData & string>(name: Key, value: FlashData[Key]): void;
2665 /**
2666 * Removes a value from the session.
2667 */
2668 unset(name: keyof Data & string): void;
2669}
2670type FlashSessionData<Data, FlashData> = Partial<Data & { [Key in keyof FlashData as FlashDataKey<Key & string>]: FlashData[Key] }>;
2671type FlashDataKey<Key extends string> = `__flash_${Key}__`;
2672type CreateSessionFunction = <Data = SessionData, FlashData = Data>(initialData?: Data, id?: string) => Session<Data, FlashData>;
2673/**
2674 * Creates a new Session object.
2675 *
2676 * Note: This function is typically not invoked directly by application code.
2677 * Instead, use a `SessionStorage` object's `getSession` method.
2678 *
2679 * @category Utils
2680 * @param initialData The initial data for the session.
2681 * @param id The identifier for the session. Defaults to an empty string for a
2682 * new session.
2683 * @returns A new {@link Session} object.
2684 */
2685declare const createSession: CreateSessionFunction;
2686/**
2687 * A function that determines whether a value is a React Router {@link Session}
2688 * object.
2689 *
2690 * @public
2691 * @category Utils
2692 * @mode framework
2693 * @mode data
2694 * @param object The value to check.
2695 * @returns `true` if the value is a React Router {@link Session} object;
2696 * otherwise, `false`.
2697 */
2698type IsSessionFunction = (object: any) => object is Session;
2699/**
2700 * Returns `true` if a value is a React Router {@link Session} object.
2701 *
2702 * @public
2703 * @category Utils
2704 * @mode framework
2705 * @mode data
2706 * @param object The value to check.
2707 * @returns `true` if the value is a React Router {@link Session} object;
2708 * otherwise, `false`.
2709 */
2710declare const isSession: IsSessionFunction;
2711/**
2712 * SessionStorage stores session data between HTTP requests and knows how to
2713 * parse and create cookies.
2714 *
2715 * A SessionStorage creates Session objects using a `Cookie` header as input.
2716 * Then, later it generates the `Set-Cookie` header to be used in the response.
2717 */
2718interface SessionStorage<Data = SessionData, FlashData = Data> {
2719 /**
2720 * Parses a Cookie header from a HTTP request and returns the associated
2721 * Session. If there is no session associated with the cookie, this will
2722 * return a new Session with no data.
2723 */
2724 getSession: (cookieHeader?: string | null, options?: CookieParseOptions$1) => Promise<Session<Data, FlashData>>;
2725 /**
2726 * Stores all data in the Session and returns the Set-Cookie header to be
2727 * used in the HTTP response.
2728 */
2729 commitSession: (session: Session<Data, FlashData>, options?: CookieSerializeOptions$1) => Promise<string>;
2730 /**
2731 * Deletes all data associated with the Session and returns the Set-Cookie
2732 * header to be used in the HTTP response.
2733 */
2734 destroySession: (session: Session<Data, FlashData>, options?: CookieSerializeOptions$1) => Promise<string>;
2735}
2736/**
2737 * SessionIdStorageStrategy is designed to allow anyone to easily build their
2738 * own SessionStorage using `createSessionStorage(strategy)`.
2739 *
2740 * This strategy describes a common scenario where the session id is stored in
2741 * a cookie but the actual session data is stored elsewhere, usually in a
2742 * database or on disk. A set of create, read, update, and delete operations
2743 * are provided for managing the session data.
2744 */
2745interface SessionIdStorageStrategy<Data = SessionData, FlashData = Data> {
2746 /**
2747 * The Cookie used to store the session id, or options used to automatically
2748 * create one.
2749 */
2750 cookie?: Cookie | (CookieOptions & {
2751 name?: string;
2752 });
2753 /**
2754 * Creates a new record with the given data and returns the session id.
2755 */
2756 createData: (data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<string>;
2757 /**
2758 * Returns data for a given session id, or `null` if there isn't any.
2759 */
2760 readData: (id: string) => Promise<FlashSessionData<Data, FlashData> | null>;
2761 /**
2762 * Updates data for the given session id.
2763 */
2764 updateData: (id: string, data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<void>;
2765 /**
2766 * Deletes data for a given session id from the data store.
2767 */
2768 deleteData: (id: string) => Promise<void>;
2769}
2770/**
2771 * Creates a SessionStorage object using a SessionIdStorageStrategy.
2772 *
2773 * Note: This is a low-level API that should only be used if none of the
2774 * existing session storage options meet your requirements.
2775 *
2776 * @category Utils
2777 * @param strategy The strategy used to store session identifiers and data.
2778 * @returns A {@link SessionStorage} object that persists session data using the
2779 * provided strategy.
2780 */
2781declare function createSessionStorage<Data = SessionData, FlashData = Data>({
2782 cookie: cookieArg,
2783 createData,
2784 readData,
2785 updateData,
2786 deleteData
2787}: SessionIdStorageStrategy<Data, FlashData>): SessionStorage<Data, FlashData>;
2788//#endregion
2789//#region lib/server-runtime/sessions/cookieStorage.d.ts
2790interface CookieSessionStorageOptions {
2791 /**
2792 * The Cookie used to store the session data on the client, or options used
2793 * to automatically create one.
2794 */
2795 cookie?: SessionIdStorageStrategy["cookie"];
2796}
2797/**
2798 * Creates and returns a SessionStorage object that stores all session data
2799 * directly in the session cookie itself.
2800 *
2801 * This has the advantage that no database or other backend services are
2802 * needed, and can help to simplify some load-balanced scenarios. However, it
2803 * also has the limitation that serialized session data may not exceed the
2804 * browser's maximum cookie size. Trade-offs!
2805 *
2806 * @public
2807 * @category Utils
2808 * @mode framework
2809 * @mode data
2810 * @param options Options for creating the cookie-backed session storage.
2811 * @returns A {@link SessionStorage} object that stores all session data in its
2812 * cookie.
2813 */
2814declare function createCookieSessionStorage<Data = SessionData, FlashData = Data>({
2815 cookie: cookieArg
2816}?: CookieSessionStorageOptions): SessionStorage<Data, FlashData>;
2817//#endregion
2818//#region lib/server-runtime/sessions/memoryStorage.d.ts
2819interface MemorySessionStorageOptions {
2820 /**
2821 * The Cookie used to store the session id on the client, or options used
2822 * to automatically create one.
2823 */
2824 cookie?: SessionIdStorageStrategy["cookie"];
2825}
2826/**
2827 * Creates and returns a simple in-memory SessionStorage object.
2828 *
2829 * Intended for local development and testing. It does not scale beyond a single
2830 * process, and all session data is lost when the server process stops/restarts.
2831 *
2832 * @public
2833 * @category Utils
2834 * @mode framework
2835 * @mode data
2836 * @param options Options for creating the in-memory session storage.
2837 * @returns A {@link SessionStorage} object that stores session data in memory.
2838 */
2839declare function createMemorySessionStorage<Data = SessionData, FlashData = Data>({
2840 cookie
2841}?: MemorySessionStorageOptions): SessionStorage<Data, FlashData>;
2842//#endregion
2843export { Await, BrowserRouter, type Cookie, type CookieOptions, type CookieParseOptions, type CookieSerializeOptions, type CookieSignatureOptions, type FlashSessionData, Form, HashRouter, type IsCookieFunction, type IsSessionFunction, Link, Links, MemoryRouter, Meta, type MiddlewareFunction, type MiddlewareNextFunction, NavLink, Navigate, Outlet, Route, Router, type RouterContext, RouterContextProvider, RouterProvider, Routes, ScrollRestoration, type Session, type SessionData, type SessionIdStorageStrategy, type SessionStorage, StaticRouter, StaticRouterProvider, createContext, createCookie, createCookieSessionStorage, createMemorySessionStorage, createSession, createSessionStorage, createStaticHandler, data, href, isCookie, isRouteErrorResponse, isSession, matchRoutes, redirect, redirectDocument, replace$1 as replace, type DecodeActionFunction as unstable_DecodeActionFunction, type DecodeFormStateFunction as unstable_DecodeFormStateFunction, type DecodeReplyFunction as unstable_DecodeReplyFunction, unstable_HistoryRouter, type LoadServerActionFunction as unstable_LoadServerActionFunction, type RSCManifestPayload as unstable_RSCManifestPayload, type RSCMatch as unstable_RSCMatch, type RSCPayload as unstable_RSCPayload, type RSCRenderPayload as unstable_RSCRenderPayload, type RSCRouteConfig as unstable_RSCRouteConfig, type RSCRouteConfigEntry as unstable_RSCRouteConfigEntry, type RSCRouteManifest as unstable_RSCRouteManifest, type RSCRouteMatch as unstable_RSCRouteMatch, getRequest as unstable_getRequest, matchRSCServerRequest as unstable_matchRSCServerRequest };
\No newline at end of file