UNPKG

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