UNPKG

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