UNPKG

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