UNPKG

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